picking-gpu.html 7.3 KB

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