indexed-textures-picking-debounced.html 15 KB

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