threejs-picking-gpu.html 7.0 KB

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