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

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