threejs-indexed-textures-picking.html 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. 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. {
  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 normalMatrix = new THREE.Matrix3();
  146. const positiveZ = new THREE.Vector3(0, 0, 1);
  147. const settings = {
  148. minArea: 20,
  149. visibleAngleDeg: 75,
  150. };
  151. const gui = new dat.GUI({width: 300});
  152. gui.add(settings, 'minArea', 0, 50).onChange(requestRenderIfNotRequested);
  153. gui.add(settings, 'visibleAngleDeg', 0, 180).onChange(requestRenderIfNotRequested);
  154. function updateLabels() {
  155. // exit if we have not loaded the data yet
  156. if (!countryInfos) {
  157. return;
  158. }
  159. const large = settings.minArea * settings.minArea;
  160. const visibleDot = Math.cos(THREE.Math.degToRad(settings.visibleAngleDeg));
  161. // get a matrix that represents a relative orientation of the camera
  162. normalMatrix.getNormalMatrix(camera.matrixWorldInverse);
  163. for (const countryInfo of countryInfos) {
  164. const {position, elem, area, selected} = countryInfo;
  165. const largeEnough = area >= large;
  166. const show = selected || (numCountriesSelected === 0 && largeEnough);
  167. if (!show) {
  168. elem.style.display = 'none';
  169. continue;
  170. }
  171. // orient the position based on the camera's orientation
  172. tempV.copy(position);
  173. tempV.applyMatrix3(normalMatrix);
  174. // get the dot product with positiveZ
  175. // -1 = facing directly away and +1 = facing directly toward us
  176. const dot = tempV.dot(positiveZ);
  177. // if the orientation is not facing us hide it.
  178. if (dot < visibleDot) {
  179. elem.style.display = 'none';
  180. continue;
  181. }
  182. // restore the element to its default display style
  183. elem.style.display = '';
  184. // get the normalized screen coordinate of that position
  185. // x and y will be in the -1 to +1 range with x = -1 being
  186. // on the left and y = -1 being on the bottom
  187. tempV.copy(position);
  188. tempV.project(camera);
  189. // convert the normalized position to CSS coordinates
  190. const x = (tempV.x * .5 + .5) * canvas.clientWidth;
  191. const y = (tempV.y * -.5 + .5) * canvas.clientHeight;
  192. // move the elem to that position
  193. countryInfo.elem.style.transform = `translate(-50%, -50%) translate(${x}px,${y}px)`;
  194. }
  195. }
  196. class GPUPickHelper {
  197. constructor() {
  198. // create a 1x1 pixel render target
  199. this.pickingTexture = new THREE.WebGLRenderTarget(1, 1);
  200. this.pixelBuffer = new Uint8Array(4);
  201. }
  202. pick(cssPosition, scene, camera) {
  203. const {pickingTexture, pixelBuffer} = this;
  204. // set the view offset to represent just a single pixel under the mouse
  205. const pixelRatio = renderer.getPixelRatio();
  206. camera.setViewOffset(
  207. renderer.context.drawingBufferWidth, // full width
  208. renderer.context.drawingBufferHeight, // full top
  209. cssPosition.x * pixelRatio | 0, // rect x
  210. cssPosition.y * pixelRatio | 0, // rect y
  211. 1, // rect width
  212. 1, // rect height
  213. );
  214. // render the scene
  215. renderer.setRenderTarget(pickingTexture);
  216. renderer.render(scene, camera);
  217. renderer.setRenderTarget(null);
  218. // clear the view offset so rendering returns to normal
  219. camera.clearViewOffset();
  220. //read the pixel
  221. renderer.readRenderTargetPixels(
  222. pickingTexture,
  223. 0, // x
  224. 0, // y
  225. 1, // width
  226. 1, // height
  227. pixelBuffer);
  228. const id =
  229. (pixelBuffer[0] << 0) |
  230. (pixelBuffer[1] << 8) |
  231. (pixelBuffer[2] << 16);
  232. return id;
  233. }
  234. }
  235. const pickHelper = new GPUPickHelper();
  236. function pickCountry(event) {
  237. // exit if we have not loaded the data yet
  238. if (!countryInfos) {
  239. return;
  240. }
  241. const position = {x: event.clientX, y: event.clientY};
  242. const id = pickHelper.pick(position, pickingScene, camera);
  243. if (id > 0) {
  244. // we clicked a country. Toggle its 'selected' property
  245. const countryInfo = countryInfos[id - 1];
  246. const selected = !countryInfo.selected;
  247. // if we're selecting this country and modifiers are not
  248. // pressed unselect everything else.
  249. if (selected && !event.shiftKey && !event.ctrlKey && !event.metaKey) {
  250. unselectAllCountries();
  251. }
  252. numCountriesSelected += selected ? 1 : -1;
  253. countryInfo.selected = selected;
  254. } else if (numCountriesSelected) {
  255. unselectAllCountries();
  256. }
  257. requestRenderIfNotRequested();
  258. }
  259. function unselectAllCountries() {
  260. numCountriesSelected = 0;
  261. countryInfos.forEach((countryInfo) => {
  262. countryInfo.selected = false;
  263. });
  264. }
  265. canvas.addEventListener('mouseup', pickCountry);
  266. let lastTouch;
  267. canvas.addEventListener('touchstart', (event) => {
  268. // prevent the window from scrolling
  269. event.preventDefault();
  270. lastTouch = event.touches[0];
  271. }, {passive: false});
  272. canvas.addEventListener('touchsmove', (event) => {
  273. lastTouch = event.touches[0];
  274. });
  275. canvas.addEventListener('touchend', () => {
  276. pickCountry(lastTouch);
  277. });
  278. function resizeRendererToDisplaySize(renderer) {
  279. const canvas = renderer.domElement;
  280. const width = canvas.clientWidth;
  281. const height = canvas.clientHeight;
  282. const needResize = canvas.width !== width || canvas.height !== height;
  283. if (needResize) {
  284. renderer.setSize(width, height, false);
  285. }
  286. return needResize;
  287. }
  288. let renderRequested = false;
  289. function render() {
  290. renderRequested = undefined;
  291. if (resizeRendererToDisplaySize(renderer)) {
  292. const canvas = renderer.domElement;
  293. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  294. camera.updateProjectionMatrix();
  295. }
  296. controls.update();
  297. updateLabels();
  298. renderer.render(scene, camera);
  299. }
  300. render();
  301. function requestRenderIfNotRequested() {
  302. if (!renderRequested) {
  303. renderRequested = true;
  304. requestAnimationFrame(render);
  305. }
  306. }
  307. controls.addEventListener('change', requestRenderIfNotRequested);
  308. window.addEventListener('resize', requestRenderIfNotRequested);
  309. }
  310. main();
  311. </script>
  312. </html>