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