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

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