2
0

indexed-textures-picking-debounced.html 15 KB

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