threejs-indexed-textures-picking-and-highlighting.html 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. <!-- Licensed under a BSD license. See license.html for license -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
  7. <title>Three.js - Indexed Textures - Picking and Highlighting</title>
  8. <style>
  9. body {
  10. margin: 0;
  11. font-family: sans-serif;
  12. }
  13. #c {
  14. width: 100%; /* let our container decide our size */
  15. height: 100%;
  16. display: block;
  17. }
  18. #container {
  19. position: relative; /* makes this the origin of its children */
  20. width: 100vw;
  21. height: 100vh;
  22. overflow: hidden;
  23. }
  24. #labels {
  25. position: absolute; /* let us position ourself inside the container */
  26. z-index: 0; /* make a new stacking context so children don't sort with rest of page */
  27. left: 0; /* make our position the top left of the container */
  28. top: 0;
  29. color: white;
  30. }
  31. #labels>div {
  32. position: absolute; /* let us position them inside the container */
  33. left: 0; /* make their default position the top left of the container */
  34. top: 0;
  35. cursor: pointer; /* change the cursor to a hand when over us */
  36. font-size: small;
  37. user-select: none; /* don't let the text get selected */
  38. pointer-events: none; /* make us invisible to the pointer */
  39. text-shadow: /* create a black outline */
  40. -1px -1px 0 #000,
  41. 0 -1px 0 #000,
  42. 1px -1px 0 #000,
  43. 1px 0 0 #000,
  44. 1px 1px 0 #000,
  45. 0 1px 0 #000,
  46. -1px 1px 0 #000,
  47. -1px 0 0 #000;
  48. }
  49. #labels>div:hover {
  50. color: red;
  51. }
  52. </style>
  53. </head>
  54. <body>
  55. <div id="container">
  56. <canvas id="c"></canvas>
  57. <div id="labels"></div>
  58. </div>
  59. </body>
  60. <script src="resources/threejs/r108/three.min.js"></script>
  61. <script src="resources/threejs/r108/js/utils/BufferGeometryUtils.js"></script>
  62. <script src="resources/threejs/r108/js/controls/OrbitControls.js"></script>
  63. <script>
  64. 'use strict';
  65. /* global THREE */
  66. function main() {
  67. const canvas = document.querySelector('#c');
  68. const renderer = new THREE.WebGLRenderer({canvas});
  69. const fov = 60;
  70. const aspect = 2; // the canvas default
  71. const near = 0.1;
  72. const far = 10;
  73. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  74. camera.position.z = 2.5;
  75. const controls = new THREE.OrbitControls(camera, canvas);
  76. controls.enableDamping = true;
  77. controls.enablePan = false;
  78. controls.minDistance = 1.2;
  79. controls.maxDistance = 4;
  80. controls.update();
  81. const scene = new THREE.Scene();
  82. scene.background = new THREE.Color('#246');
  83. const pickingScene = new THREE.Scene();
  84. pickingScene.background = new THREE.Color(0);
  85. const tempColor = new THREE.Color();
  86. function get255BasedColor(color) {
  87. tempColor.set(color);
  88. return tempColor.toArray().map(v => v * 255);
  89. }
  90. const maxNumCountries = 512;
  91. const paletteTextureWidth = maxNumCountries;
  92. const paletteTextureHeight = 1;
  93. const palette = new Uint8Array(paletteTextureWidth * 3);
  94. const paletteTexture = new THREE.DataTexture(
  95. palette, paletteTextureWidth, paletteTextureHeight, THREE.RGBFormat);
  96. paletteTexture.minFilter = THREE.NearestFilter;
  97. paletteTexture.magFilter = THREE.NearestFilter;
  98. const selectedColor = get255BasedColor('red');
  99. const unselectedColor = get255BasedColor('#444');
  100. const oceanColor = get255BasedColor('rgb(100,200,255)');
  101. resetPalette();
  102. function setPaletteColor(index, color) {
  103. palette.set(color, index * 3);
  104. }
  105. function resetPalette() {
  106. // make all colors the unselected color
  107. for (let i = 1; i < maxNumCountries; ++i) {
  108. setPaletteColor(i, unselectedColor);
  109. }
  110. // set the ocean color (index #0)
  111. setPaletteColor(0, oceanColor);
  112. paletteTexture.needsUpdate = true;
  113. }
  114. {
  115. const loader = new THREE.TextureLoader();
  116. const geometry = new THREE.SphereBufferGeometry(1, 64, 32);
  117. const indexTexture = loader.load('resources/data/world/country-index-texture.png', render);
  118. indexTexture.minFilter = THREE.NearestFilter;
  119. indexTexture.magFilter = THREE.NearestFilter;
  120. const pickingMaterial = new THREE.MeshBasicMaterial({map: indexTexture});
  121. pickingScene.add(new THREE.Mesh(geometry, pickingMaterial));
  122. const fragmentShaderReplacements = [
  123. {
  124. from: '#include <common>',
  125. to: `
  126. #include <common>
  127. uniform sampler2D indexTexture;
  128. uniform sampler2D paletteTexture;
  129. uniform float paletteTextureWidth;
  130. `,
  131. },
  132. {
  133. from: '#include <color_fragment>',
  134. to: `
  135. #include <color_fragment>
  136. {
  137. vec4 indexColor = texture2D(indexTexture, vUv);
  138. float index = indexColor.r * 255.0 + indexColor.g * 255.0 * 256.0;
  139. vec2 paletteUV = vec2((index + 0.5) / paletteTextureWidth, 0.5);
  140. vec4 paletteColor = texture2D(paletteTexture, paletteUV);
  141. // diffuseColor.rgb += paletteColor.rgb; // white outlines
  142. diffuseColor.rgb = paletteColor.rgb - diffuseColor.rgb; // black outlines
  143. }
  144. `,
  145. },
  146. ];
  147. const texture = loader.load('resources/data/world/country-outlines-4k.png', render);
  148. const material = new THREE.MeshBasicMaterial({map: texture});
  149. material.onBeforeCompile = function(shader) {
  150. fragmentShaderReplacements.forEach((rep) => {
  151. shader.fragmentShader = shader.fragmentShader.replace(rep.from, rep.to);
  152. });
  153. shader.uniforms.paletteTexture = {value: paletteTexture};
  154. shader.uniforms.indexTexture = {value: indexTexture};
  155. shader.uniforms.paletteTextureWidth = {value: paletteTextureWidth};
  156. };
  157. scene.add(new THREE.Mesh(geometry, material));
  158. }
  159. async function loadJSON(url) {
  160. const req = await fetch(url);
  161. return req.json();
  162. }
  163. let numCountriesSelected = 0;
  164. let countryInfos;
  165. async function loadCountryData() {
  166. countryInfos = await loadJSON('resources/data/world/country-info.json'); /* threejsfundamentals: url */
  167. const lonFudge = Math.PI * 1.5;
  168. const latFudge = Math.PI;
  169. // these helpers will make it easy to position the boxes
  170. // We can rotate the lon helper on its Y axis to the longitude
  171. const lonHelper = new THREE.Object3D();
  172. // We rotate the latHelper on its X axis to the latitude
  173. const latHelper = new THREE.Object3D();
  174. lonHelper.add(latHelper);
  175. // The position helper moves the object to the edge of the sphere
  176. const positionHelper = new THREE.Object3D();
  177. positionHelper.position.z = 1;
  178. latHelper.add(positionHelper);
  179. const labelParentElem = document.querySelector('#labels');
  180. for (const countryInfo of countryInfos) {
  181. const {lat, lon, min, max, name} = countryInfo;
  182. // adjust the helpers to point to the latitude and longitude
  183. lonHelper.rotation.y = THREE.Math.degToRad(lon) + lonFudge;
  184. latHelper.rotation.x = THREE.Math.degToRad(lat) + latFudge;
  185. // get the position of the lat/lon
  186. positionHelper.updateWorldMatrix(true, false);
  187. const position = new THREE.Vector3();
  188. positionHelper.getWorldPosition(position);
  189. countryInfo.position = position;
  190. // compute the area for each country
  191. const width = max[0] - min[0];
  192. const height = max[1] - min[1];
  193. const area = width * height;
  194. countryInfo.area = area;
  195. // add an element for each country
  196. const elem = document.createElement('div');
  197. elem.textContent = name;
  198. labelParentElem.appendChild(elem);
  199. countryInfo.elem = elem;
  200. }
  201. requestRenderIfNotRequested();
  202. }
  203. loadCountryData();
  204. const tempV = new THREE.Vector3();
  205. const cameraToPoint = new THREE.Vector3();
  206. const cameraPosition = new THREE.Vector3();
  207. const normalMatrix = new THREE.Matrix3();
  208. const settings = {
  209. minArea: 20,
  210. maxVisibleDot: -0.2,
  211. };
  212. function updateLabels() {
  213. // exit if we have not loaded the data yet
  214. if (!countryInfos) {
  215. return;
  216. }
  217. const large = settings.minArea * settings.minArea;
  218. // get a matrix that represents a relative orientation of the camera
  219. normalMatrix.getNormalMatrix(camera.matrixWorldInverse);
  220. // get the camera's position
  221. camera.getWorldPosition(cameraPosition);
  222. for (const countryInfo of countryInfos) {
  223. const {position, elem, area, selected} = countryInfo;
  224. const largeEnough = area >= large;
  225. const show = selected || (numCountriesSelected === 0 && largeEnough);
  226. if (!show) {
  227. elem.style.display = 'none';
  228. continue;
  229. }
  230. // Orient the position based on the camera's orientation.
  231. // Since the sphere is at the origin and the sphere is a unit sphere
  232. // this gives us a camera relative direction vector for the position.
  233. tempV.copy(position);
  234. tempV.applyMatrix3(normalMatrix);
  235. // compute the direction to this position from the camera
  236. cameraToPoint.copy(position);
  237. cameraToPoint.applyMatrix4(camera.matrixWorldInverse).normalize();
  238. // get the dot product of camera relative direction to this position
  239. // on the globe with the direction from the camera to that point.
  240. // -1 = facing directly towards the camera
  241. // 0 = exactly on tangent of the sphere from the camera
  242. // > 0 = facing away
  243. const dot = tempV.dot(cameraToPoint);
  244. // if the orientation is not facing us hide it.
  245. if (dot > settings.maxVisibleDot) {
  246. elem.style.display = 'none';
  247. continue;
  248. }
  249. // restore the element to its default display style
  250. elem.style.display = '';
  251. // get the normalized screen coordinate of that position
  252. // x and y will be in the -1 to +1 range with x = -1 being
  253. // on the left and y = -1 being on the bottom
  254. tempV.copy(position);
  255. tempV.project(camera);
  256. // convert the normalized position to CSS coordinates
  257. const x = (tempV.x * .5 + .5) * canvas.clientWidth;
  258. const y = (tempV.y * -.5 + .5) * canvas.clientHeight;
  259. // move the elem to that position
  260. elem.style.transform = `translate(-50%, -50%) translate(${x}px,${y}px)`;
  261. // set the zIndex for sorting
  262. elem.style.zIndex = (-tempV.z * .5 + .5) * 100000 | 0;
  263. }
  264. }
  265. class GPUPickHelper {
  266. constructor() {
  267. // create a 1x1 pixel render target
  268. this.pickingTexture = new THREE.WebGLRenderTarget(1, 1);
  269. this.pixelBuffer = new Uint8Array(4);
  270. }
  271. pick(cssPosition, scene, camera) {
  272. const {pickingTexture, pixelBuffer} = this;
  273. // set the view offset to represent just a single pixel under the mouse
  274. const pixelRatio = renderer.getPixelRatio();
  275. camera.setViewOffset(
  276. renderer.context.drawingBufferWidth, // full width
  277. renderer.context.drawingBufferHeight, // full top
  278. cssPosition.x * pixelRatio | 0, // rect x
  279. cssPosition.y * pixelRatio | 0, // rect y
  280. 1, // rect width
  281. 1, // rect height
  282. );
  283. // render the scene
  284. renderer.setRenderTarget(pickingTexture);
  285. renderer.render(scene, camera);
  286. renderer.setRenderTarget(null);
  287. // clear the view offset so rendering returns to normal
  288. camera.clearViewOffset();
  289. //read the pixel
  290. renderer.readRenderTargetPixels(
  291. pickingTexture,
  292. 0, // x
  293. 0, // y
  294. 1, // width
  295. 1, // height
  296. pixelBuffer);
  297. const id =
  298. (pixelBuffer[0] << 0) |
  299. (pixelBuffer[1] << 8) |
  300. (pixelBuffer[2] << 16);
  301. return id;
  302. }
  303. }
  304. const pickHelper = new GPUPickHelper();
  305. function getCanvasRelativePosition(event) {
  306. const rect = canvas.getBoundingClientRect();
  307. return {
  308. x: event.clientX - rect.left,
  309. y: event.clientY - rect.top,
  310. };
  311. }
  312. function pickCountry(event) {
  313. // exit if we have not loaded the data yet
  314. if (!countryInfos) {
  315. return;
  316. }
  317. const position = getCanvasRelativePosition(event);
  318. const id = pickHelper.pick(position, pickingScene, camera);
  319. if (id > 0) {
  320. const countryInfo = countryInfos[id - 1];
  321. const selected = !countryInfo.selected;
  322. if (selected && !event.shiftKey && !event.ctrlKey && !event.metaKey) {
  323. unselectAllCountries();
  324. }
  325. numCountriesSelected += selected ? 1 : -1;
  326. countryInfo.selected = selected;
  327. setPaletteColor(id, selected ? selectedColor : unselectedColor);
  328. paletteTexture.needsUpdate = true;
  329. } else if (numCountriesSelected) {
  330. unselectAllCountries();
  331. }
  332. requestRenderIfNotRequested();
  333. }
  334. function unselectAllCountries() {
  335. numCountriesSelected = 0;
  336. countryInfos.forEach((countryInfo) => {
  337. countryInfo.selected = false;
  338. });
  339. resetPalette();
  340. }
  341. canvas.addEventListener('mouseup', pickCountry);
  342. let lastTouch;
  343. canvas.addEventListener('touchstart', (event) => {
  344. // prevent the window from scrolling
  345. event.preventDefault();
  346. lastTouch = event.touches[0];
  347. }, {passive: false});
  348. canvas.addEventListener('touchsmove', (event) => {
  349. lastTouch = event.touches[0];
  350. });
  351. canvas.addEventListener('touchend', () => {
  352. pickCountry(lastTouch);
  353. });
  354. function resizeRendererToDisplaySize(renderer) {
  355. const canvas = renderer.domElement;
  356. const width = canvas.clientWidth;
  357. const height = canvas.clientHeight;
  358. const needResize = canvas.width !== width || canvas.height !== height;
  359. if (needResize) {
  360. renderer.setSize(width, height, false);
  361. }
  362. return needResize;
  363. }
  364. let renderRequested = false;
  365. function render() {
  366. renderRequested = undefined;
  367. if (resizeRendererToDisplaySize(renderer)) {
  368. const canvas = renderer.domElement;
  369. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  370. camera.updateProjectionMatrix();
  371. }
  372. controls.update();
  373. updateLabels();
  374. renderer.render(scene, camera);
  375. }
  376. render();
  377. function requestRenderIfNotRequested() {
  378. if (!renderRequested) {
  379. renderRequested = true;
  380. requestAnimationFrame(render);
  381. }
  382. }
  383. controls.addEventListener('change', requestRenderIfNotRequested);
  384. window.addEventListener('resize', requestRenderIfNotRequested);
  385. }
  386. main();
  387. </script>
  388. </html>