threejs-picking-gpu.html 7.3 KB

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