indexed-textures.html 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. Title: Three.js Indexed Textures for Picking and Color
  2. Description: Using Indexed Textures for Picking and Color
  3. TOC: Using Indexed Textures for Picking and Color
  4. This article is a continuation of [an article about aligning html elements to 3d](threejs-align-html-elements-to-3d.html).
  5. If you haven't read that yet you should start there before continuing here.
  6. Sometimes using three.js requires coming up with creative solutions.
  7. I'm not sure this is a great solution but I thought I'd share it and
  8. you can see if it suggests any solutions for your needs.
  9. In the [previous article](threejs-align-html-elements-to-3d.html) we
  10. displayed country names around a 3d globe. How would we go about letting
  11. the user select a country and show their selection?
  12. The first idea that comes to mind is to generate geometry for each country.
  13. We could [use a picking solution](threejs-picking.html) like we covered before.
  14. We'd build 3D geometry for each country. If the user clicks on the mesh for
  15. that country we'd know what country was clicked.
  16. So, just to check that solution I tried generating 3D meshes of all the countries
  17. using the same data I used to generate the outlines
  18. [in the previous article](threejs-align-html-elements-to-3d.html).
  19. The result was a 15.5meg binary GLTF (.glb) file. Making the user download 15.5meg
  20. sounds like too much to me.
  21. There are lots of ways to compress the data. The first would probably be
  22. to apply some algorithm to lower the resolution of the outlines. I didn't spend
  23. any time pursuing that solution. For borders of the USA that's probably a huge
  24. win. For a borders of Canada probably much less.
  25. Another solution would be to use just actual data compression. For example gzipping
  26. the file brought it down to 11meg. That's 30% less but arguably not enough.
  27. We could store all the data as 16bit ranged values instead of 32bit float values.
  28. Or we could use something like [draco compression](https://google.github.io/draco/)
  29. and maybe that would be enough. I didn't check and I would encourage you to check
  30. yourself and tell me how it goes as I'd love to know. 😅
  31. In my case I thought about [the GPU picking solution](threejs-picking.html)
  32. we covered at the end of [the article on picking](threejs-picking.html). In
  33. that solution we drew every mesh with a unique color that represented that
  34. mesh's id. We then drew all the meshes and looked at the color that was clicked
  35. on.
  36. Taking inspiration from that we could pre-generate a map of countries where
  37. each country's color is its index number in our array of countries. We could
  38. then use a similar GPU picking technique. We'd draw the globe off screen using
  39. this index texture. Looking at the color of the pixel the user clicks would
  40. tell us the country id.
  41. So, I [wrote some code](https://github.com/gfxfundamentals/threejsfundamentals/blob/master/threejs/lessons/tools/geo-picking/)
  42. to generate such a texture. Here it is.
  43. <div class="threejs_center"><img src="../resources/data/world/country-index-texture.png" style="width: 700px;"></div>
  44. Note: The data used to generate this texture comes from [this website](http://thematicmapping.org/downloads/world_borders.php)
  45. and is therefore licensed as [CC-BY-SA](http://creativecommons.org/licenses/by-sa/3.0/).
  46. It's only 217k, much better than the 14meg for the country meshes. In fact we could probably
  47. even lower the resolution but 217k seems good enough for now.
  48. So let's try using it for picking countries.
  49. Grabbing code from the [gpu picking example](threejs-picking.html) we need
  50. a scene for picking.
  51. ```js
  52. const pickingScene = new THREE.Scene();
  53. pickingScene.background = new THREE.Color(0);
  54. ```
  55. and we need to add the globe with the our index texture to the
  56. picking scene.
  57. ```js
  58. {
  59. const loader = new THREE.TextureLoader();
  60. const geometry = new THREE.SphereGeometry(1, 64, 32);
  61. + const indexTexture = loader.load('resources/data/world/country-index-texture.png', render);
  62. + indexTexture.minFilter = THREE.NearestFilter;
  63. + indexTexture.magFilter = THREE.NearestFilter;
  64. +
  65. + const pickingMaterial = new THREE.MeshBasicMaterial({map: indexTexture});
  66. + pickingScene.add(new THREE.Mesh(geometry, pickingMaterial));
  67. const texture = loader.load('resources/data/world/country-outlines-4k.png', render);
  68. const material = new THREE.MeshBasicMaterial({map: texture});
  69. scene.add(new THREE.Mesh(geometry, material));
  70. }
  71. ```
  72. Then let's copy over the `GPUPickingHelper` class we used
  73. before with a few minor changes.
  74. ```js
  75. class GPUPickHelper {
  76. constructor() {
  77. // create a 1x1 pixel render target
  78. this.pickingTexture = new THREE.WebGLRenderTarget(1, 1);
  79. this.pixelBuffer = new Uint8Array(4);
  80. - this.pickedObject = null;
  81. - this.pickedObjectSavedColor = 0;
  82. }
  83. pick(cssPosition, scene, camera) {
  84. const {pickingTexture, pixelBuffer} = this;
  85. // set the view offset to represent just a single pixel under the mouse
  86. const pixelRatio = renderer.getPixelRatio();
  87. camera.setViewOffset(
  88. renderer.getContext().drawingBufferWidth, // full width
  89. renderer.getContext().drawingBufferHeight, // full top
  90. cssPosition.x * pixelRatio | 0, // rect x
  91. cssPosition.y * pixelRatio | 0, // rect y
  92. 1, // rect width
  93. 1, // rect height
  94. );
  95. // render the scene
  96. renderer.setRenderTarget(pickingTexture);
  97. renderer.render(scene, camera);
  98. renderer.setRenderTarget(null);
  99. // clear the view offset so rendering returns to normal
  100. camera.clearViewOffset();
  101. //read the pixel
  102. renderer.readRenderTargetPixels(
  103. pickingTexture,
  104. 0, // x
  105. 0, // y
  106. 1, // width
  107. 1, // height
  108. pixelBuffer);
  109. + const id =
  110. + (pixelBuffer[0] << 16) |
  111. + (pixelBuffer[1] << 8) |
  112. + (pixelBuffer[2] << 0);
  113. +
  114. + return id;
  115. - const id =
  116. - (pixelBuffer[0] << 16) |
  117. - (pixelBuffer[1] << 8) |
  118. - (pixelBuffer[2] );
  119. - const intersectedObject = idToObject[id];
  120. - if (intersectedObject) {
  121. - // pick the first object. It's the closest one
  122. - this.pickedObject = intersectedObject;
  123. - // save its color
  124. - this.pickedObjectSavedColor = this.pickedObject.material.emissive.getHex();
  125. - // set its emissive color to flashing red/yellow
  126. - this.pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFFFF00 : 0xFF0000);
  127. - }
  128. }
  129. }
  130. ```
  131. Now we can use that to pick countries.
  132. ```js
  133. const pickHelper = new GPUPickHelper();
  134. function getCanvasRelativePosition(event) {
  135. const rect = canvas.getBoundingClientRect();
  136. return {
  137. x: (event.clientX - rect.left) * canvas.width / rect.width,
  138. y: (event.clientY - rect.top ) * canvas.height / rect.height,
  139. };
  140. }
  141. function pickCountry(event) {
  142. // exit if we have not loaded the data yet
  143. if (!countryInfos) {
  144. return;
  145. }
  146. const position = getCanvasRelativePosition(event);
  147. const id = pickHelper.pick(position, pickingScene, camera);
  148. if (id > 0) {
  149. // we clicked a country. Toggle its 'selected' property
  150. const countryInfo = countryInfos[id - 1];
  151. const selected = !countryInfo.selected;
  152. // if we're selecting this country and modifiers are not
  153. // pressed unselect everything else.
  154. if (selected && !event.shiftKey && !event.ctrlKey && !event.metaKey) {
  155. unselectAllCountries();
  156. }
  157. numCountriesSelected += selected ? 1 : -1;
  158. countryInfo.selected = selected;
  159. } else if (numCountriesSelected) {
  160. // the ocean or sky was clicked
  161. unselectAllCountries();
  162. }
  163. requestRenderIfNotRequested();
  164. }
  165. function unselectAllCountries() {
  166. numCountriesSelected = 0;
  167. countryInfos.forEach((countryInfo) => {
  168. countryInfo.selected = false;
  169. });
  170. }
  171. canvas.addEventListener('pointerup', pickCountry);
  172. ```
  173. The code above sets/unsets the `selected` property on
  174. the array of countries. If `shift` or `ctrl` or `cmd`
  175. is pressed then you can select more than one country.
  176. All that's left is showing the selected countries. For now
  177. let's just update the labels.
  178. ```js
  179. function updateLabels() {
  180. // exit if we have not loaded the data yet
  181. if (!countryInfos) {
  182. return;
  183. }
  184. const large = settings.minArea * settings.minArea;
  185. // get a matrix that represents a relative orientation of the camera
  186. normalMatrix.getNormalMatrix(camera.matrixWorldInverse);
  187. // get the camera's position
  188. camera.getWorldPosition(cameraPosition);
  189. for (const countryInfo of countryInfos) {
  190. - const {position, elem, area} = countryInfo;
  191. - // large enough?
  192. - if (area < large) {
  193. + const {position, elem, area, selected} = countryInfo;
  194. + const largeEnough = area >= large;
  195. + const show = selected || (numCountriesSelected === 0 && largeEnough);
  196. + if (!show) {
  197. elem.style.display = 'none';
  198. continue;
  199. }
  200. ...
  201. ```
  202. and with that we should be able to pick countries
  203. {{{example url="../threejs-indexed-textures-picking.html" }}}
  204. The code stills shows countries based on their area but if you
  205. click one just that one will have a label.
  206. So that seems like a reasonable solution for picking countries
  207. but what about highlighting the selected countries?
  208. For that we can take inspiration from *paletted graphics*.
  209. [Paletted graphics](https://en.wikipedia.org/wiki/Palette_%28computing%29)
  210. or [Indexed Color](https://en.wikipedia.org/wiki/Indexed_color) is
  211. what older systems like the Atari 800, Amiga, NES,
  212. Super Nintendo, and even older IBM PCs used. Instead of storing bitmaps
  213. as RGB colors 8bits per color, 24 bytes per pixel or more, they stored
  214. bitmaps as 8bit values or less. The value for each pixel was an index
  215. into a palette. So for example a value
  216. of 3 in the image means "display color 3". What color color#3 is is
  217. defined somewhere else called a "palette".
  218. In JavaScript you can think of it like this
  219. ```js
  220. const face7x7PixelImageData = [
  221. 0, 1, 1, 1, 1, 1, 0,
  222. 1, 0, 0, 0, 0, 0, 1,
  223. 1, 0, 2, 0, 2, 0, 1,
  224. 1, 0, 0, 0, 0, 0, 1,
  225. 1, 0, 3, 3, 3, 0, 1,
  226. 1, 0, 0, 0, 0, 0, 1,
  227. 0, 1, 1, 1, 1, 1, 1,
  228. ];
  229. const palette = [
  230. [255, 255, 255], // white
  231. [ 0, 0, 0], // black
  232. [ 0, 255, 255], // cyan
  233. [255, 0, 0], // red
  234. ];
  235. ```
  236. Where each pixel in the image data is an index into palette. If you interpreted
  237. the image data through the palette above you'd get this image
  238. <div class="threejs_center"><img src="resources/images/7x7-indexed-face.png"></div>
  239. In our case we already have a texture above that has a different id
  240. per country. So, we could use that same texture through a palette
  241. texture to give each country its own color. By changing the palette
  242. texture we can color each individual country. For example by setting
  243. the entire palette texture to black and then for one country's entry
  244. in the palette a different color, we can highlight just that country.
  245. To do paletted index graphics requires some custom shader code.
  246. Let's modify the default shaders in three.js.
  247. That way we can use lighting and other features if we want.
  248. Like we covered in [the article on animating lots of objects](threejs-optimize-lots-of-objects-animated.html)
  249. we can modify the default shaders by adding a function to a material's
  250. `onBeforeCompile` property.
  251. The default fragment shader looks something like this before compiling.
  252. ```glsl
  253. #include <common>
  254. #include <color_pars_fragment>
  255. #include <uv_pars_fragment>
  256. #include <uv2_pars_fragment>
  257. #include <map_pars_fragment>
  258. #include <alphamap_pars_fragment>
  259. #include <aomap_pars_fragment>
  260. #include <lightmap_pars_fragment>
  261. #include <envmap_pars_fragment>
  262. #include <fog_pars_fragment>
  263. #include <specularmap_pars_fragment>
  264. #include <logdepthbuf_pars_fragment>
  265. #include <clipping_planes_pars_fragment>
  266. void main() {
  267. #include <clipping_planes_fragment>
  268. vec4 diffuseColor = vec4( diffuse, opacity );
  269. #include <logdepthbuf_fragment>
  270. #include <map_fragment>
  271. #include <color_fragment>
  272. #include <alphamap_fragment>
  273. #include <alphatest_fragment>
  274. #include <specularmap_fragment>
  275. ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
  276. #ifdef USE_LIGHTMAP
  277. reflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;
  278. #else
  279. reflectedLight.indirectDiffuse += vec3( 1.0 );
  280. #endif
  281. #include <aomap_fragment>
  282. reflectedLight.indirectDiffuse *= diffuseColor.rgb;
  283. vec3 outgoingLight = reflectedLight.indirectDiffuse;
  284. #include <envmap_fragment>
  285. gl_FragColor = vec4( outgoingLight, diffuseColor.a );
  286. #include <premultiplied_alpha_fragment>
  287. #include <tonemapping_fragment>
  288. #include <encodings_fragment>
  289. #include <fog_fragment>
  290. }
  291. ```
  292. [Digging through all those snippets](https://github.com/mrdoob/three.js/tree/dev/src/renderers/shaders/ShaderChunk)
  293. we find that three.js uses a variable called `diffuseColor` to manage the
  294. base material color. It sets this in the `<color_fragment>` [snippet](https://github.com/mrdoob/three.js/blob/dev/src/renderers/shaders/ShaderChunk/color_fragment.glsl.js)
  295. so we should be able to modify it after that point.
  296. `diffuseColor` at that point in the shader should already be the color from
  297. our outline texture so we can look up the color from a palette texture
  298. and mix them for the final result.
  299. Like we [did before](threejs-optimize-lots-of-objects-animated.html) we'll make an array
  300. of search and replacement strings and apply them to the shader in
  301. `Material.onBeforeCompile`.
  302. ```js
  303. {
  304. const loader = new THREE.TextureLoader();
  305. const geometry = new THREE.SphereGeometry(1, 64, 32);
  306. const indexTexture = loader.load('resources/data/world/country-index-texture.png', render);
  307. indexTexture.minFilter = THREE.NearestFilter;
  308. indexTexture.magFilter = THREE.NearestFilter;
  309. const pickingMaterial = new THREE.MeshBasicMaterial({map: indexTexture});
  310. pickingScene.add(new THREE.Mesh(geometry, pickingMaterial));
  311. + const fragmentShaderReplacements = [
  312. + {
  313. + from: '#include <common>',
  314. + to: `
  315. + #include <common>
  316. + uniform sampler2D indexTexture;
  317. + uniform sampler2D paletteTexture;
  318. + uniform float paletteTextureWidth;
  319. + `,
  320. + },
  321. + {
  322. + from: '#include <color_fragment>',
  323. + to: `
  324. + #include <color_fragment>
  325. + {
  326. + vec4 indexColor = texture2D(indexTexture, vUv);
  327. + float index = indexColor.r * 255.0 + indexColor.g * 255.0 * 256.0;
  328. + vec2 paletteUV = vec2((index + 0.5) / paletteTextureWidth, 0.5);
  329. + vec4 paletteColor = texture2D(paletteTexture, paletteUV);
  330. + // diffuseColor.rgb += paletteColor.rgb; // white outlines
  331. + diffuseColor.rgb = paletteColor.rgb - diffuseColor.rgb; // black outlines
  332. + }
  333. + `,
  334. + },
  335. + ];
  336. const texture = loader.load('resources/data/world/country-outlines-4k.png', render);
  337. const material = new THREE.MeshBasicMaterial({map: texture});
  338. + material.onBeforeCompile = function(shader) {
  339. + fragmentShaderReplacements.forEach((rep) => {
  340. + shader.fragmentShader = shader.fragmentShader.replace(rep.from, rep.to);
  341. + });
  342. + };
  343. scene.add(new THREE.Mesh(geometry, material));
  344. }
  345. ```
  346. Above can see above we add 3 uniforms, `indexTexture`, `paletteTexture`,
  347. and `paletteTextureWidth`. We get a color from the `indexTexture`
  348. and convert it to an index. `vUv` is the texture coordinates provided by
  349. three.js. We then use that index to get a color out of the palette texture.
  350. We then mix the result with the current `diffuseColor`. The `diffuseColor`
  351. at this point is our black and white outline texture so if we add the 2 colors
  352. we'll get white outlines. If we subtract the current diffuse color we'll get
  353. black outlines.
  354. Before we can render we need to setup the palette texture
  355. and these 3 uniforms.
  356. For the palette texture it just needs to be wide enough to
  357. hold one color per country + one for the ocean (id = 0).
  358. There are 240 something countries. We could wait until the
  359. list of countries loads to get an exact number or look it up.
  360. There's not much harm in just picking some larger number so
  361. let's choose 512.
  362. Here's the code to create the palette texture
  363. ```js
  364. const maxNumCountries = 512;
  365. const paletteTextureWidth = maxNumCountries;
  366. const paletteTextureHeight = 1;
  367. const palette = new Uint8Array(paletteTextureWidth * 3);
  368. const paletteTexture = new THREE.DataTexture(
  369. palette, paletteTextureWidth, paletteTextureHeight, THREE.RGBFormat);
  370. paletteTexture.minFilter = THREE.NearestFilter;
  371. paletteTexture.magFilter = THREE.NearestFilter;
  372. ```
  373. A `DataTexture` let's us give a texture raw data. In this case
  374. we're giving it 512 RGB colors, 3 bytes each where each byte is
  375. red, green, and blue respectively using values that go from 0 to 255.
  376. Let's fill it with random colors just to see it work
  377. ```js
  378. for (let i = 1; i < palette.length; ++i) {
  379. palette[i] = Math.random() * 256;
  380. }
  381. // set the ocean color (index #0)
  382. palette.set([100, 200, 255], 0);
  383. paletteTexture.needsUpdate = true;
  384. ```
  385. Anytime we want three.js to update the palette texture with
  386. the contents of the `palette` array we need to set `paletteTexture.needsUpdate`
  387. to `true`.
  388. And then we still need to set the uniforms on the material.
  389. ```js
  390. const geometry = new THREE.SphereGeometry(1, 64, 32);
  391. const material = new THREE.MeshBasicMaterial({map: texture});
  392. material.onBeforeCompile = function(shader) {
  393. fragmentShaderReplacements.forEach((rep) => {
  394. shader.fragmentShader = shader.fragmentShader.replace(rep.from, rep.to);
  395. });
  396. + shader.uniforms.paletteTexture = {value: paletteTexture};
  397. + shader.uniforms.indexTexture = {value: indexTexture};
  398. + shader.uniforms.paletteTextureWidth = {value: paletteTextureWidth};
  399. };
  400. scene.add(new THREE.Mesh(geometry, material));
  401. ```
  402. and with that we get randomly colored countries.
  403. {{{example url="../threejs-indexed-textures-random-colors.html" }}}
  404. Now that we can see the index and palette textures are working
  405. let's manipulate the palette for highlighting.
  406. First let's make function that will let us pass in a three.js
  407. style color and give us values we can put in the palette texture.
  408. ```js
  409. const tempColor = new THREE.Color();
  410. function get255BasedColor(color) {
  411. tempColor.set(color);
  412. return tempColor.toArray().map(v => v * 255);
  413. }
  414. ```
  415. Calling it like this `color = get255BasedColor('red')` will
  416. return an array like `[255, 0, 0]`.
  417. Next let's use it to make a few colors and fill out the
  418. palette.
  419. ```js
  420. const selectedColor = get255BasedColor('red');
  421. const unselectedColor = get255BasedColor('#444');
  422. const oceanColor = get255BasedColor('rgb(100,200,255)');
  423. resetPalette();
  424. function setPaletteColor(index, color) {
  425. palette.set(color, index * 3);
  426. }
  427. function resetPalette() {
  428. // make all colors the unselected color
  429. for (let i = 1; i < maxNumCountries; ++i) {
  430. setPaletteColor(i, unselectedColor);
  431. }
  432. // set the ocean color (index #0)
  433. setPaletteColor(0, oceanColor);
  434. paletteTexture.needsUpdate = true;
  435. }
  436. ```
  437. Now let's use those functions to update the palette when a country
  438. is selected
  439. ```js
  440. function getCanvasRelativePosition(event) {
  441. const rect = canvas.getBoundingClientRect();
  442. return {
  443. x: (event.clientX - rect.left) * canvas.width / rect.width,
  444. y: (event.clientY - rect.top ) * canvas.height / rect.height,
  445. };
  446. }
  447. function pickCountry(event) {
  448. // exit if we have not loaded the data yet
  449. if (!countryInfos) {
  450. return;
  451. }
  452. const position = getCanvasRelativePosition(event);
  453. const id = pickHelper.pick(position, pickingScene, camera);
  454. if (id > 0) {
  455. const countryInfo = countryInfos[id - 1];
  456. const selected = !countryInfo.selected;
  457. if (selected && !event.shiftKey && !event.ctrlKey && !event.metaKey) {
  458. unselectAllCountries();
  459. }
  460. numCountriesSelected += selected ? 1 : -1;
  461. countryInfo.selected = selected;
  462. + setPaletteColor(id, selected ? selectedColor : unselectedColor);
  463. + paletteTexture.needsUpdate = true;
  464. } else if (numCountriesSelected) {
  465. unselectAllCountries();
  466. }
  467. requestRenderIfNotRequested();
  468. }
  469. function unselectAllCountries() {
  470. numCountriesSelected = 0;
  471. countryInfos.forEach((countryInfo) => {
  472. countryInfo.selected = false;
  473. });
  474. + resetPalette();
  475. }
  476. ```
  477. and we that we should be able to highlight 1 or more countries.
  478. {{{example url="../threejs-indexed-textures-picking-and-highlighting.html" }}}
  479. That seems to work!
  480. One minor thing is we can't spin the globe without changing
  481. the selection state. If we select a country and then want to
  482. rotate the globe the selection will change.
  483. Let's try to fix that. Off the top of my head we can check 2 things.
  484. How much time passed between clicking and letting go.
  485. Another is did the user actually move the mouse. If the
  486. time is short or if they didn't move the mouse then it
  487. was probably a click. Otherwise they were probably trying
  488. to drag the globe.
  489. ```js
  490. +const maxClickTimeMs = 200;
  491. +const maxMoveDeltaSq = 5 * 5;
  492. +const startPosition = {};
  493. +let startTimeMs;
  494. +
  495. +function recordStartTimeAndPosition(event) {
  496. + startTimeMs = performance.now();
  497. + const pos = getCanvasRelativePosition(event);
  498. + startPosition.x = pos.x;
  499. + startPosition.y = pos.y;
  500. +}
  501. function getCanvasRelativePosition(event) {
  502. const rect = canvas.getBoundingClientRect();
  503. return {
  504. x: (event.clientX - rect.left) * canvas.width / rect.width,
  505. y: (event.clientY - rect.top ) * canvas.height / rect.height,
  506. };
  507. }
  508. function pickCountry(event) {
  509. // exit if we have not loaded the data yet
  510. if (!countryInfos) {
  511. return;
  512. }
  513. + // if it's been a moment since the user started
  514. + // then assume it was a drag action, not a select action
  515. + const clickTimeMs = performance.now() - startTimeMs;
  516. + if (clickTimeMs > maxClickTimeMs) {
  517. + return;
  518. + }
  519. +
  520. + // if they moved assume it was a drag action
  521. + const position = getCanvasRelativePosition(event);
  522. + const moveDeltaSq = (startPosition.x - position.x) ** 2 +
  523. + (startPosition.y - position.y) ** 2;
  524. + if (moveDeltaSq > maxMoveDeltaSq) {
  525. + return;
  526. + }
  527. - const position = {x: event.clientX, y: event.clientY};
  528. const id = pickHelper.pick(position, pickingScene, camera);
  529. if (id > 0) {
  530. const countryInfo = countryInfos[id - 1];
  531. const selected = !countryInfo.selected;
  532. if (selected && !event.shiftKey && !event.ctrlKey && !event.metaKey) {
  533. unselectAllCountries();
  534. }
  535. numCountriesSelected += selected ? 1 : -1;
  536. countryInfo.selected = selected;
  537. setPaletteColor(id, selected ? selectedColor : unselectedColor);
  538. paletteTexture.needsUpdate = true;
  539. } else if (numCountriesSelected) {
  540. unselectAllCountries();
  541. }
  542. requestRenderIfNotRequested();
  543. }
  544. function unselectAllCountries() {
  545. numCountriesSelected = 0;
  546. countryInfos.forEach((countryInfo) => {
  547. countryInfo.selected = false;
  548. });
  549. resetPalette();
  550. }
  551. +canvas.addEventListener('pointerdown', recordStartTimeAndPosition);
  552. canvas.addEventListener('pointerup', pickCountry);
  553. ```
  554. and with those changes it *seems* like it works to me.
  555. {{{example url="../threejs-indexed-textures-picking-debounced.html" }}}
  556. I'm not a UX expert so I'd love to hear if there is a better
  557. solution.
  558. I hope that gave you some idea of how indexed graphics can be useful
  559. and how you can modify the shaders three.js makes to add simple features.
  560. How to use GLSL, the language the shaders are written in, is too much for
  561. this article. There are a few links to some info in
  562. [the article on post processing](threejs-post-processing.html).
粤ICP备19079148号