threejs-indexed-textures-picking.html 12 KB

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