2
0

picking-gpu.html 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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 - Picking - RayCaster w/Transparency</title>
  8. <style>
  9. html, body {
  10. height: 100%;
  11. margin: 0;
  12. }
  13. #c {
  14. width: 100%;
  15. height: 100%;
  16. display: block;
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <canvas id="c"></canvas>
  22. </body>
  23. <!-- Import maps polyfill -->
  24. <!-- Remove this when import maps will be widely supported -->
  25. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  26. <script type="importmap">
  27. {
  28. "imports": {
  29. "three": "../../build/three.module.js"
  30. }
  31. }
  32. </script>
  33. <script type="module">
  34. import * as THREE from 'three';
  35. function main() {
  36. const canvas = document.querySelector('#c');
  37. const renderer = new THREE.WebGLRenderer({canvas});
  38. const fov = 60;
  39. const aspect = 2; // the canvas default
  40. const near = 0.1;
  41. const far = 200;
  42. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  43. camera.position.z = 30;
  44. const scene = new THREE.Scene();
  45. scene.background = new THREE.Color('white');
  46. const pickingScene = new THREE.Scene();
  47. pickingScene.background = new THREE.Color(0);
  48. // put the camera on a pole (parent it to an object)
  49. // so we can spin the pole to move the camera around the scene
  50. const cameraPole = new THREE.Object3D();
  51. scene.add(cameraPole);
  52. cameraPole.add(camera);
  53. {
  54. const color = 0xFFFFFF;
  55. const intensity = 1;
  56. const light = new THREE.DirectionalLight(color, intensity);
  57. light.position.set(-1, 2, 4);
  58. camera.add(light);
  59. }
  60. const boxWidth = 1;
  61. const boxHeight = 1;
  62. const boxDepth = 1;
  63. const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  64. function rand(min, max) {
  65. if (max === undefined) {
  66. max = min;
  67. min = 0;
  68. }
  69. return min + (max - min) * Math.random();
  70. }
  71. function randomColor() {
  72. return `hsl(${rand(360) | 0}, ${rand(50, 100) | 0}%, 50%)`;
  73. }
  74. const loader = new THREE.TextureLoader();
  75. const texture = loader.load('resources/images/frame.png');
  76. const idToObject = {};
  77. const numObjects = 100;
  78. for (let i = 0; i < numObjects; ++i) {
  79. const id = i + 1;
  80. const material = new THREE.MeshPhongMaterial({
  81. color: randomColor(),
  82. map: texture,
  83. transparent: true,
  84. side: THREE.DoubleSide,
  85. alphaTest: 0.5,
  86. });
  87. const cube = new THREE.Mesh(geometry, material);
  88. scene.add(cube);
  89. idToObject[id] = cube;
  90. cube.position.set(rand(-20, 20), rand(-20, 20), rand(-20, 20));
  91. cube.rotation.set(rand(Math.PI), rand(Math.PI), 0);
  92. cube.scale.set(rand(3, 6), rand(3, 6), rand(3, 6));
  93. const pickingMaterial = new THREE.MeshPhongMaterial({
  94. emissive: new THREE.Color(id),
  95. color: new THREE.Color(0, 0, 0),
  96. specular: new THREE.Color(0, 0, 0),
  97. map: texture,
  98. transparent: true,
  99. side: THREE.DoubleSide,
  100. alphaTest: 0.5,
  101. blending: THREE.NoBlending,
  102. });
  103. const pickingCube = new THREE.Mesh(geometry, pickingMaterial);
  104. pickingScene.add(pickingCube);
  105. pickingCube.position.copy(cube.position);
  106. pickingCube.rotation.copy(cube.rotation);
  107. pickingCube.scale.copy(cube.scale);
  108. }
  109. function resizeRendererToDisplaySize(renderer) {
  110. const canvas = renderer.domElement;
  111. const width = canvas.clientWidth;
  112. const height = canvas.clientHeight;
  113. const needResize = canvas.width !== width || canvas.height !== height;
  114. if (needResize) {
  115. renderer.setSize(width, height, false);
  116. }
  117. return needResize;
  118. }
  119. class GPUPickHelper {
  120. constructor() {
  121. // create a 1x1 pixel render target
  122. this.pickingTexture = new THREE.WebGLRenderTarget(1, 1);
  123. this.pixelBuffer = new Uint8Array(4);
  124. this.pickedObject = null;
  125. this.pickedObjectSavedColor = 0;
  126. }
  127. pick(cssPosition, scene, camera, time) {
  128. const {pickingTexture, pixelBuffer} = this;
  129. // restore the color if there is a picked object
  130. if (this.pickedObject) {
  131. this.pickedObject.material.emissive.setHex(this.pickedObjectSavedColor);
  132. this.pickedObject = undefined;
  133. }
  134. // set the view offset to represent just a single pixel under the mouse
  135. const pixelRatio = renderer.getPixelRatio();
  136. camera.setViewOffset(
  137. renderer.getContext().drawingBufferWidth, // full width
  138. renderer.getContext().drawingBufferHeight, // full top
  139. cssPosition.x * pixelRatio | 0, // rect x
  140. cssPosition.y * pixelRatio | 0, // rect y
  141. 1, // rect width
  142. 1, // rect height
  143. );
  144. // render the scene
  145. renderer.setRenderTarget(pickingTexture);
  146. renderer.render(scene, camera);
  147. renderer.setRenderTarget(null);
  148. // clear the view offset so rendering returns to normal
  149. camera.clearViewOffset();
  150. //read the pixel
  151. renderer.readRenderTargetPixels(
  152. pickingTexture,
  153. 0, // x
  154. 0, // y
  155. 1, // width
  156. 1, // height
  157. pixelBuffer);
  158. const id =
  159. (pixelBuffer[0] << 16) |
  160. (pixelBuffer[1] << 8) |
  161. (pixelBuffer[2] );
  162. const intersectedObject = idToObject[id];
  163. if (intersectedObject) {
  164. // pick the first object. It's the closest one
  165. this.pickedObject = intersectedObject;
  166. // save its color
  167. this.pickedObjectSavedColor = this.pickedObject.material.emissive.getHex();
  168. // set its emissive color to flashing red/yellow
  169. this.pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFFFF00 : 0xFF0000);
  170. }
  171. }
  172. }
  173. const pickPosition = {x: 0, y: 0};
  174. const pickHelper = new GPUPickHelper();
  175. clearPickPosition();
  176. function render(time) {
  177. time *= 0.001; // convert to seconds;
  178. if (resizeRendererToDisplaySize(renderer)) {
  179. const canvas = renderer.domElement;
  180. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  181. camera.updateProjectionMatrix();
  182. }
  183. cameraPole.rotation.y = time * .1;
  184. pickHelper.pick(pickPosition, pickingScene, camera, time);
  185. renderer.render(scene, camera);
  186. requestAnimationFrame(render);
  187. }
  188. requestAnimationFrame(render);
  189. function getCanvasRelativePosition(event) {
  190. const rect = canvas.getBoundingClientRect();
  191. return {
  192. x: (event.clientX - rect.left) * canvas.width / rect.width,
  193. y: (event.clientY - rect.top ) * canvas.height / rect.height,
  194. };
  195. }
  196. function setPickPosition(event) {
  197. const pos = getCanvasRelativePosition(event);
  198. pickPosition.x = pos.x;
  199. pickPosition.y = pos.y;
  200. }
  201. function clearPickPosition() {
  202. // unlike the mouse which always has a position
  203. // if the user stops touching the screen we want
  204. // to stop picking. For now we just pick a value
  205. // unlikely to pick something
  206. pickPosition.x = -100000;
  207. pickPosition.y = -100000;
  208. }
  209. window.addEventListener('mousemove', setPickPosition);
  210. window.addEventListener('mouseout', clearPickPosition);
  211. window.addEventListener('mouseleave', clearPickPosition);
  212. window.addEventListener('touchstart', (event) => {
  213. // prevent the window from scrolling
  214. event.preventDefault();
  215. setPickPosition(event.touches[0]);
  216. }, {passive: false});
  217. window.addEventListener('touchmove', (event) => {
  218. setPickPosition(event.touches[0]);
  219. });
  220. window.addEventListener('touchend', clearPickPosition);
  221. }
  222. main();
  223. </script>
  224. </html>