threejs-indexed-textures-picking.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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</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 src="resources/threejs/r102/three.js"></script>
  61. <script src="resources/threejs/r102/js/utils/BufferGeometryUtils.js"></script>
  62. <script src="resources/threejs/r102/js/controls/OrbitControls.js"></script>
  63. <script>
  64. 'use strict';
  65. /* global THREE */
  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. {
  88. const loader = new THREE.TextureLoader();
  89. const geometry = new THREE.SphereBufferGeometry(1, 64, 32);
  90. const indexTexture = loader.load('resources/data/world/country-index-texture.png', render);
  91. indexTexture.minFilter = THREE.NearestFilter;
  92. indexTexture.magFilter = THREE.NearestFilter;
  93. const pickingMaterial = new THREE.MeshBasicMaterial({map: indexTexture});
  94. pickingScene.add(new THREE.Mesh(geometry, pickingMaterial));
  95. const texture = loader.load('resources/data/world/country-outlines-4k.png', render);
  96. const material = new THREE.MeshBasicMaterial({map: texture});
  97. scene.add(new THREE.Mesh(geometry, material));
  98. }
  99. async function loadJSON(url) {
  100. const req = await fetch(url);
  101. return req.json();
  102. }
  103. let numCountriesSelected = 0;
  104. let countryInfos;
  105. async function loadCountryData() {
  106. countryInfos = await loadJSON('resources/data/world/country-info.json'); /* threejsfundamentals: url */
  107. const lonFudge = Math.PI * 1.5;
  108. const latFudge = Math.PI;
  109. // these helpers will make it easy to position the boxes
  110. // We can rotate the lon helper on its Y axis to the longitude
  111. const lonHelper = new THREE.Object3D();
  112. // We rotate the latHelper on its X axis to the latitude
  113. const latHelper = new THREE.Object3D();
  114. lonHelper.add(latHelper);
  115. // The position helper moves the object to the edge of the sphere
  116. const positionHelper = new THREE.Object3D();
  117. positionHelper.position.z = 1;
  118. latHelper.add(positionHelper);
  119. const labelParentElem = document.querySelector('#labels');
  120. for (const countryInfo of countryInfos) {
  121. const {lat, lon, min, max, name} = countryInfo;
  122. // adjust the helpers to point to the latitude and longitude
  123. lonHelper.rotation.y = THREE.Math.degToRad(lon) + lonFudge;
  124. latHelper.rotation.x = THREE.Math.degToRad(lat) + latFudge;
  125. // get the position of the lat/lon
  126. positionHelper.updateWorldMatrix(true, false);
  127. const position = new THREE.Vector3();
  128. positionHelper.getWorldPosition(position);
  129. countryInfo.position = position;
  130. // compute the area for each country
  131. const width = max[0] - min[0];
  132. const height = max[1] - min[1];
  133. const area = width * height;
  134. countryInfo.area = area;
  135. // add an element for each country
  136. const elem = document.createElement('div');
  137. elem.textContent = name;
  138. labelParentElem.appendChild(elem);
  139. countryInfo.elem = elem;
  140. }
  141. requestRenderIfNotRequested();
  142. }
  143. loadCountryData();
  144. const tempV = new THREE.Vector3();
  145. const cameraToPoint = new THREE.Vector3();
  146. const cameraPosition = new THREE.Vector3();
  147. const normalMatrix = new THREE.Matrix3();
  148. const settings = {
  149. minArea: 20,
  150. maxVisibleDot: -0.2,
  151. };
  152. function updateLabels() {
  153. // exit if we have not loaded the data yet
  154. if (!countryInfos) {
  155. return;
  156. }
  157. const large = settings.minArea * settings.minArea;
  158. // get a matrix that represents a relative orientation of the camera
  159. normalMatrix.getNormalMatrix(camera.matrixWorldInverse);
  160. // get the camera's position
  161. camera.getWorldPosition(cameraPosition);
  162. for (const countryInfo of countryInfos) {
  163. const {position, elem, area, selected} = countryInfo;
  164. const largeEnough = area >= large;
  165. const show = selected || (numCountriesSelected === 0 && largeEnough);
  166. if (!show) {
  167. elem.style.display = 'none';
  168. continue;
  169. }
  170. // Orient the position based on the camera's orientation.
  171. // Since the sphere is at the origin and the sphere is a unit sphere
  172. // this gives us a camera relative direction vector for the position.
  173. tempV.copy(position);
  174. tempV.applyMatrix3(normalMatrix);
  175. // compute the direction to this position from the camera
  176. cameraToPoint.copy(position);
  177. cameraToPoint.applyMatrix4(camera.matrixWorldInverse).normalize();
  178. // get the dot product of camera relative direction to this position
  179. // on the globe with the direction from the camera to that point.
  180. // 1 = facing directly towards the camera
  181. // 0 = exactly on tangent of the sphere from the camera
  182. // < 0 = facing away
  183. const dot = tempV.dot(cameraToPoint);
  184. // if the orientation is not facing us hide it.
  185. if (dot > settings.maxVisibleDot) {
  186. elem.style.display = 'none';
  187. continue;
  188. }
  189. // restore the element to its default display style
  190. elem.style.display = '';
  191. // get the normalized screen coordinate of that position
  192. // x and y will be in the -1 to +1 range with x = -1 being
  193. // on the left and y = -1 being on the bottom
  194. tempV.copy(position);
  195. tempV.project(camera);
  196. // convert the normalized position to CSS coordinates
  197. const x = (tempV.x * .5 + .5) * canvas.clientWidth;
  198. const y = (tempV.y * -.5 + .5) * canvas.clientHeight;
  199. // move the elem to that position
  200. elem.style.transform = `translate(-50%, -50%) translate(${x}px,${y}px)`;
  201. // set the zIndex for sorting
  202. elem.style.zIndex = (-tempV.z * .5 + .5) * 100000 | 0;
  203. }
  204. }
  205. class GPUPickHelper {
  206. constructor() {
  207. // create a 1x1 pixel render target
  208. this.pickingTexture = new THREE.WebGLRenderTarget(1, 1);
  209. this.pixelBuffer = new Uint8Array(4);
  210. }
  211. pick(cssPosition, scene, camera) {
  212. const {pickingTexture, pixelBuffer} = this;
  213. // set the view offset to represent just a single pixel under the mouse
  214. const pixelRatio = renderer.getPixelRatio();
  215. camera.setViewOffset(
  216. renderer.context.drawingBufferWidth, // full width
  217. renderer.context.drawingBufferHeight, // full top
  218. cssPosition.x * pixelRatio | 0, // rect x
  219. cssPosition.y * pixelRatio | 0, // rect y
  220. 1, // rect width
  221. 1, // rect height
  222. );
  223. // render the scene
  224. renderer.setRenderTarget(pickingTexture);
  225. renderer.render(scene, camera);
  226. renderer.setRenderTarget(null);
  227. // clear the view offset so rendering returns to normal
  228. camera.clearViewOffset();
  229. //read the pixel
  230. renderer.readRenderTargetPixels(
  231. pickingTexture,
  232. 0, // x
  233. 0, // y
  234. 1, // width
  235. 1, // height
  236. pixelBuffer);
  237. const id =
  238. (pixelBuffer[0] << 0) |
  239. (pixelBuffer[1] << 8) |
  240. (pixelBuffer[2] << 16);
  241. return id;
  242. }
  243. }
  244. const pickHelper = new GPUPickHelper();
  245. function pickCountry(event) {
  246. // exit if we have not loaded the data yet
  247. if (!countryInfos) {
  248. return;
  249. }
  250. const position = {x: event.clientX, y: event.clientY};
  251. const id = pickHelper.pick(position, pickingScene, camera);
  252. if (id > 0) {
  253. // we clicked a country. Toggle its 'selected' property
  254. const countryInfo = countryInfos[id - 1];
  255. const selected = !countryInfo.selected;
  256. // if we're selecting this country and modifiers are not
  257. // pressed unselect everything else.
  258. if (selected && !event.shiftKey && !event.ctrlKey && !event.metaKey) {
  259. unselectAllCountries();
  260. }
  261. numCountriesSelected += selected ? 1 : -1;
  262. countryInfo.selected = selected;
  263. } else if (numCountriesSelected) {
  264. unselectAllCountries();
  265. }
  266. requestRenderIfNotRequested();
  267. }
  268. function unselectAllCountries() {
  269. numCountriesSelected = 0;
  270. countryInfos.forEach((countryInfo) => {
  271. countryInfo.selected = false;
  272. });
  273. }
  274. canvas.addEventListener('mouseup', pickCountry);
  275. let lastTouch;
  276. canvas.addEventListener('touchstart', (event) => {
  277. // prevent the window from scrolling
  278. event.preventDefault();
  279. lastTouch = event.touches[0];
  280. }, {passive: false});
  281. canvas.addEventListener('touchsmove', (event) => {
  282. lastTouch = event.touches[0];
  283. });
  284. canvas.addEventListener('touchend', () => {
  285. pickCountry(lastTouch);
  286. });
  287. function resizeRendererToDisplaySize(renderer) {
  288. const canvas = renderer.domElement;
  289. const width = canvas.clientWidth;
  290. const height = canvas.clientHeight;
  291. const needResize = canvas.width !== width || canvas.height !== height;
  292. if (needResize) {
  293. renderer.setSize(width, height, false);
  294. }
  295. return needResize;
  296. }
  297. let renderRequested = false;
  298. function render() {
  299. renderRequested = undefined;
  300. if (resizeRendererToDisplaySize(renderer)) {
  301. const canvas = renderer.domElement;
  302. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  303. camera.updateProjectionMatrix();
  304. }
  305. controls.update();
  306. updateLabels();
  307. renderer.render(scene, camera);
  308. }
  309. render();
  310. function requestRenderIfNotRequested() {
  311. if (!renderRequested) {
  312. renderRequested = true;
  313. requestAnimationFrame(render);
  314. }
  315. }
  316. controls.addEventListener('change', requestRenderIfNotRequested);
  317. window.addEventListener('resize', requestRenderIfNotRequested);
  318. }
  319. main();
  320. </script>
  321. </html>