indexed-textures-random-colors.html 13 KB

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