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

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