picking-gpu.html 7.1 KB

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