indexed-textures-picking.html 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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. html, body {
  10. height: 100%;
  11. margin: 0;
  12. font-family: sans-serif;
  13. }
  14. #c {
  15. width: 100%; /* let our container decide our size */
  16. height: 100%;
  17. display: block;
  18. }
  19. #container {
  20. position: relative; /* makes this the origin of its children */
  21. width: 100%;
  22. height: 100%;
  23. overflow: hidden;
  24. }
  25. #labels {
  26. position: absolute; /* let us position ourself inside the container */
  27. z-index: 0; /* make a new stacking context so children don't sort with rest of page */
  28. left: 0; /* make our position the top left of the container */
  29. top: 0;
  30. color: white;
  31. }
  32. #labels>div {
  33. position: absolute; /* let us position them inside the container */
  34. left: 0; /* make their default position the top left of the container */
  35. top: 0;
  36. cursor: pointer; /* change the cursor to a hand when over us */
  37. font-size: small;
  38. user-select: none; /* don't let the text get selected */
  39. pointer-events: none; /* make us invisible to the pointer */
  40. text-shadow: /* create a black outline */
  41. -1px -1px 0 #000,
  42. 0 -1px 0 #000,
  43. 1px -1px 0 #000,
  44. 1px 0 0 #000,
  45. 1px 1px 0 #000,
  46. 0 1px 0 #000,
  47. -1px 1px 0 #000,
  48. -1px 0 0 #000;
  49. }
  50. #labels>div:hover {
  51. color: red;
  52. }
  53. </style>
  54. </head>
  55. <body>
  56. <div id="container">
  57. <canvas id="c"></canvas>
  58. <div id="labels"></div>
  59. </div>
  60. </body>
  61. <!-- Import maps polyfill -->
  62. <!-- Remove this when import maps will be widely supported -->
  63. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  64. <script type="importmap">
  65. {
  66. "imports": {
  67. "three": "../../build/three.module.js",
  68. "three/addons/": "../../examples/jsm/"
  69. }
  70. }
  71. </script>
  72. <script type="module">
  73. import * as THREE from 'three';
  74. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  75. function main() {
  76. const canvas = document.querySelector( '#c' );
  77. const renderer = new THREE.WebGLRenderer( { antialias: true, canvas } );
  78. renderer.useLegacyLights = false;
  79. const fov = 60;
  80. const aspect = 2; // the canvas default
  81. const near = 0.1;
  82. const far = 10;
  83. const camera = new THREE.PerspectiveCamera( fov, aspect, near, far );
  84. camera.position.z = 2.5;
  85. const controls = new OrbitControls( camera, canvas );
  86. controls.enableDamping = true;
  87. controls.enablePan = false;
  88. controls.minDistance = 1.2;
  89. controls.maxDistance = 4;
  90. controls.update();
  91. const scene = new THREE.Scene();
  92. scene.background = new THREE.Color( '#246' );
  93. const pickingScene = new THREE.Scene();
  94. pickingScene.background = new THREE.Color( 0 );
  95. {
  96. const loader = new THREE.TextureLoader();
  97. const geometry = new THREE.SphereGeometry( 1, 64, 32 );
  98. const indexTexture = loader.load( 'resources/data/world/country-index-texture.png', render );
  99. indexTexture.minFilter = THREE.NearestFilter;
  100. indexTexture.magFilter = THREE.NearestFilter;
  101. const pickingMaterial = new THREE.MeshBasicMaterial( { map: indexTexture } );
  102. pickingScene.add( new THREE.Mesh( geometry, pickingMaterial ) );
  103. const texture = loader.load( 'resources/data/world/country-outlines-4k.png', render );
  104. const material = new THREE.MeshBasicMaterial( { map: texture } );
  105. scene.add( new THREE.Mesh( geometry, material ) );
  106. }
  107. async function loadJSON( url ) {
  108. const req = await fetch( url );
  109. return req.json();
  110. }
  111. let numCountriesSelected = 0;
  112. let countryInfos;
  113. async function loadCountryData() {
  114. countryInfos = await loadJSON( 'resources/data/world/country-info.json' ); /* threejs.org: url */
  115. const lonFudge = Math.PI * 1.5;
  116. const latFudge = Math.PI;
  117. // these helpers will make it easy to position the boxes
  118. // We can rotate the lon helper on its Y axis to the longitude
  119. const lonHelper = new THREE.Object3D();
  120. // We rotate the latHelper on its X axis to the latitude
  121. const latHelper = new THREE.Object3D();
  122. lonHelper.add( latHelper );
  123. // The position helper moves the object to the edge of the sphere
  124. const positionHelper = new THREE.Object3D();
  125. positionHelper.position.z = 1;
  126. latHelper.add( positionHelper );
  127. const labelParentElem = document.querySelector( '#labels' );
  128. for ( const countryInfo of countryInfos ) {
  129. const { lat, lon, min, max, name } = countryInfo;
  130. // adjust the helpers to point to the latitude and longitude
  131. lonHelper.rotation.y = THREE.MathUtils.degToRad( lon ) + lonFudge;
  132. latHelper.rotation.x = THREE.MathUtils.degToRad( lat ) + latFudge;
  133. // get the position of the lat/lon
  134. positionHelper.updateWorldMatrix( true, false );
  135. const position = new THREE.Vector3();
  136. positionHelper.getWorldPosition( position );
  137. countryInfo.position = position;
  138. // compute the area for each country
  139. const width = max[ 0 ] - min[ 0 ];
  140. const height = max[ 1 ] - min[ 1 ];
  141. const area = width * height;
  142. countryInfo.area = area;
  143. // add an element for each country
  144. const elem = document.createElement( 'div' );
  145. elem.textContent = name;
  146. labelParentElem.appendChild( elem );
  147. countryInfo.elem = elem;
  148. }
  149. requestRenderIfNotRequested();
  150. }
  151. loadCountryData();
  152. const tempV = new THREE.Vector3();
  153. const cameraToPoint = new THREE.Vector3();
  154. const cameraPosition = new THREE.Vector3();
  155. const normalMatrix = new THREE.Matrix3();
  156. const settings = {
  157. minArea: 20,
  158. maxVisibleDot: - 0.2,
  159. };
  160. function updateLabels() {
  161. // exit if we have not loaded the data yet
  162. if ( ! countryInfos ) {
  163. return;
  164. }
  165. const large = settings.minArea * settings.minArea;
  166. // get a matrix that represents a relative orientation of the camera
  167. normalMatrix.getNormalMatrix( camera.matrixWorldInverse );
  168. // get the camera's position
  169. camera.getWorldPosition( cameraPosition );
  170. for ( const countryInfo of countryInfos ) {
  171. const { position, elem, area, selected } = countryInfo;
  172. const largeEnough = area >= large;
  173. const show = selected || ( numCountriesSelected === 0 && largeEnough );
  174. if ( ! show ) {
  175. elem.style.display = 'none';
  176. continue;
  177. }
  178. // Orient the position based on the camera's orientation.
  179. // Since the sphere is at the origin and the sphere is a unit sphere
  180. // this gives us a camera relative direction vector for the position.
  181. tempV.copy( position );
  182. tempV.applyMatrix3( normalMatrix );
  183. // compute the direction to this position from the camera
  184. cameraToPoint.copy( position );
  185. cameraToPoint.applyMatrix4( camera.matrixWorldInverse ).normalize();
  186. // get the dot product of camera relative direction to this position
  187. // on the globe with the direction from the camera to that point.
  188. // 1 = facing directly towards the camera
  189. // 0 = exactly on tangent of the sphere from the camera
  190. // < 0 = facing away
  191. const dot = tempV.dot( cameraToPoint );
  192. // if the orientation is not facing us hide it.
  193. if ( dot > settings.maxVisibleDot ) {
  194. elem.style.display = 'none';
  195. continue;
  196. }
  197. // restore the element to its default display style
  198. elem.style.display = '';
  199. // get the normalized screen coordinate of that position
  200. // x and y will be in the -1 to +1 range with x = -1 being
  201. // on the left and y = -1 being on the bottom
  202. tempV.copy( position );
  203. tempV.project( camera );
  204. // convert the normalized position to CSS coordinates
  205. const x = ( tempV.x * .5 + .5 ) * canvas.clientWidth;
  206. const y = ( tempV.y * - .5 + .5 ) * canvas.clientHeight;
  207. // move the elem to that position
  208. elem.style.transform = `translate(-50%, -50%) translate(${x}px,${y}px)`;
  209. // set the zIndex for sorting
  210. elem.style.zIndex = ( - tempV.z * .5 + .5 ) * 100000 | 0;
  211. }
  212. }
  213. class GPUPickHelper {
  214. constructor() {
  215. // create a 1x1 pixel render target
  216. this.pickingTexture = new THREE.WebGLRenderTarget( 1, 1 );
  217. this.pixelBuffer = new Uint8Array( 4 );
  218. }
  219. pick( cssPosition, scene, camera ) {
  220. const { pickingTexture, pixelBuffer } = this;
  221. // set the view offset to represent just a single pixel under the mouse
  222. const pixelRatio = renderer.getPixelRatio();
  223. camera.setViewOffset(
  224. renderer.getContext().drawingBufferWidth, // full width
  225. renderer.getContext().drawingBufferHeight, // full top
  226. cssPosition.x * pixelRatio | 0, // rect x
  227. cssPosition.y * pixelRatio | 0, // rect y
  228. 1, // rect width
  229. 1, // rect height
  230. );
  231. // render the scene
  232. renderer.setRenderTarget( pickingTexture );
  233. renderer.render( scene, camera );
  234. renderer.setRenderTarget( null );
  235. // clear the view offset so rendering returns to normal
  236. camera.clearViewOffset();
  237. //read the pixel
  238. renderer.readRenderTargetPixels(
  239. pickingTexture,
  240. 0, // x
  241. 0, // y
  242. 1, // width
  243. 1, // height
  244. pixelBuffer );
  245. const id =
  246. ( pixelBuffer[ 0 ] << 0 ) |
  247. ( pixelBuffer[ 1 ] << 8 ) |
  248. ( pixelBuffer[ 2 ] << 16 );
  249. return id;
  250. }
  251. }
  252. const pickHelper = new GPUPickHelper();
  253. function getCanvasRelativePosition( event ) {
  254. const rect = canvas.getBoundingClientRect();
  255. return {
  256. x: ( event.clientX - rect.left ) * canvas.width / rect.width,
  257. y: ( event.clientY - rect.top ) * canvas.height / rect.height,
  258. };
  259. }
  260. function pickCountry( event ) {
  261. // exit if we have not loaded the data yet
  262. if ( ! countryInfos ) {
  263. return;
  264. }
  265. const position = getCanvasRelativePosition( event );
  266. const id = pickHelper.pick( position, pickingScene, camera );
  267. if ( id > 0 ) {
  268. // we clicked a country. Toggle its 'selected' property
  269. const countryInfo = countryInfos[ id - 1 ];
  270. const selected = ! countryInfo.selected;
  271. // if we're selecting this country and modifiers are not
  272. // pressed unselect everything else.
  273. if ( selected && ! event.shiftKey && ! event.ctrlKey && ! event.metaKey ) {
  274. unselectAllCountries();
  275. }
  276. numCountriesSelected += selected ? 1 : - 1;
  277. countryInfo.selected = selected;
  278. } else if ( numCountriesSelected ) {
  279. unselectAllCountries();
  280. }
  281. requestRenderIfNotRequested();
  282. }
  283. function unselectAllCountries() {
  284. numCountriesSelected = 0;
  285. countryInfos.forEach( ( countryInfo ) => {
  286. countryInfo.selected = false;
  287. } );
  288. }
  289. canvas.addEventListener( 'pointerup', pickCountry );
  290. function resizeRendererToDisplaySize( renderer ) {
  291. const canvas = renderer.domElement;
  292. const width = canvas.clientWidth;
  293. const height = canvas.clientHeight;
  294. const needResize = canvas.width !== width || canvas.height !== height;
  295. if ( needResize ) {
  296. renderer.setSize( width, height, false );
  297. }
  298. return needResize;
  299. }
  300. let renderRequested = false;
  301. function render() {
  302. renderRequested = undefined;
  303. if ( resizeRendererToDisplaySize( renderer ) ) {
  304. const canvas = renderer.domElement;
  305. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  306. camera.updateProjectionMatrix();
  307. }
  308. controls.update();
  309. updateLabels();
  310. renderer.render( scene, camera );
  311. }
  312. render();
  313. function requestRenderIfNotRequested() {
  314. if ( ! renderRequested ) {
  315. renderRequested = true;
  316. requestAnimationFrame( render );
  317. }
  318. }
  319. controls.addEventListener( 'change', requestRenderIfNotRequested );
  320. window.addEventListener( 'resize', requestRenderIfNotRequested );
  321. }
  322. main();
  323. </script>
  324. </html>