picking-gpu.html 7.3 KB

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