threejs-indexed-textures-picking.html 12 KB

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