webgpu_postprocessing_ssgi_ballpool.html 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - SSGI Ball Pool</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <meta property="og:title" content="three.js webgpu - SSGI Ball Pool">
  8. <meta property="og:type" content="website">
  9. <meta property="og:url" content="https://threejs.org/examples/webgpu_postprocessing_ssgi_ballpool.html">
  10. <meta property="og:image" content="https://threejs.org/examples/screenshots/webgpu_postprocessing_ssgi_ballpool.jpg">
  11. <link type="text/css" rel="stylesheet" href="example.css">
  12. <style>
  13. canvas {
  14. touch-action: none;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="info">
  20. <a href="https://threejs.org/" target="_blank" rel="noopener" class="logo-link"></a>
  21. <div class="title-wrapper">
  22. <a href="https://threejs.org/" target="_blank" rel="noopener">three.js</a><span>SSGI Ball Pool</span>
  23. </div>
  24. <small>Real-time indirect illumination with interactive physics ball pool.</small>
  25. </div>
  26. <script type="importmap">
  27. {
  28. "imports": {
  29. "three": "../build/three.webgpu.js",
  30. "three/webgpu": "../build/three.webgpu.js",
  31. "three/tsl": "../build/three.tsl.js",
  32. "three/addons/": "./jsm/",
  33. "monomorph": "https://cdn.jsdelivr.net/npm/monomorph@2.3.1/build/monomorph.js",
  34. "@perplexdotgg/bounce": "https://cdn.jsdelivr.net/npm/@perplexdotgg/bounce@1.8.1/build/bounce.js"
  35. }
  36. }
  37. </script>
  38. <script type="module">
  39. import * as THREE from 'three/webgpu';
  40. import { pass, mrt, output, normalView, diffuseColor, velocity, add, vec4, packNormalToRGB, unpackRGBToNormal, sample } from 'three/tsl';
  41. import { ssgi } from 'three/addons/tsl/display/SSGINode.js';
  42. import { traa } from 'three/addons/tsl/display/TRAANode.js';
  43. import { World } from '@perplexdotgg/bounce';
  44. import { Inspector } from 'three/addons/inspector/Inspector.js';
  45. const BALL_RADIUS = 0.4;
  46. const FILL_RATIO = 0.4;
  47. const PACKING = 0.6;
  48. const BOX_HEIGHT = 6;
  49. const BOX_DEPTH = 8;
  50. const WALL_THICKNESS = 0.5;
  51. const CAM_FOV = 45;
  52. const EASE_SPEED = 8;
  53. let camera, scene, renderer, renderPipeline;
  54. let raycaster, pointer;
  55. let mouseLight;
  56. let world;
  57. let ballCount = 0;
  58. let bodies = [];
  59. let ballsMesh = null;
  60. let wallMeshes = [];
  61. const boxSize = { w: 8, h: BOX_HEIGHT, d: BOX_DEPTH };
  62. const mouseRayOrigin = new THREE.Vector3();
  63. const mouseRayDir = new THREE.Vector3();
  64. let mouseMoving = false;
  65. let mouseStopTimer = 0;
  66. let pointerDown = false;
  67. const activePointers = new Set();
  68. const mouseLightTarget = new THREE.Vector3( 0, BOX_HEIGHT / 2, BOX_DEPTH / 2 );
  69. const mouseRayOriginTarget = new THREE.Vector3();
  70. const mouseRayDirTarget = new THREE.Vector3();
  71. init();
  72. async function init() {
  73. camera = new THREE.PerspectiveCamera( CAM_FOV, window.innerWidth / window.innerHeight, 0.1, 100 );
  74. scene = new THREE.Scene();
  75. renderer = new THREE.WebGPURenderer( { antialias: false } );
  76. renderer.setSize( window.innerWidth, window.innerHeight );
  77. renderer.setAnimationLoop( animate );
  78. renderer.toneMapping = THREE.ACESFilmicToneMapping;
  79. renderer.toneMappingExposure = 0.5;
  80. renderer.shadowMap.enabled = true;
  81. renderer.inspector = new Inspector();
  82. document.body.appendChild( renderer.domElement );
  83. //
  84. renderPipeline = new THREE.RenderPipeline( renderer );
  85. const scenePass = pass( scene, camera );
  86. scenePass.setMRT( mrt( {
  87. output: output,
  88. diffuseColor: diffuseColor,
  89. normal: packNormalToRGB( normalView ),
  90. velocity: velocity
  91. } ) );
  92. const scenePassColor = scenePass.getTextureNode( 'output' );
  93. const scenePassDiffuse = scenePass.getTextureNode( 'diffuseColor' );
  94. const scenePassDepth = scenePass.getTextureNode( 'depth' );
  95. const scenePassNormal = scenePass.getTextureNode( 'normal' );
  96. const scenePassVelocity = scenePass.getTextureNode( 'velocity' );
  97. // bandwidth optimization
  98. const diffuseTexture = scenePass.getTexture( 'diffuseColor' );
  99. diffuseTexture.type = THREE.UnsignedByteType;
  100. const normalTexture = scenePass.getTexture( 'normal' );
  101. normalTexture.type = THREE.UnsignedByteType;
  102. const sceneNormal = sample( ( uv ) => {
  103. return unpackRGBToNormal( scenePassNormal.sample( uv ) );
  104. } );
  105. // gi
  106. const giPass = ssgi( scenePassColor, scenePassDepth, sceneNormal, camera );
  107. giPass.sliceCount.value = 2;
  108. giPass.stepCount.value = 8;
  109. // composite
  110. const gi = giPass.rgb.toInspector( 'SSGI' );
  111. const ao = giPass.a.toInspector( 'AO' );
  112. const compositePass = vec4(
  113. add( scenePassColor.rgb.mul( ao ), scenePassDiffuse.rgb.mul( gi ) ),
  114. scenePassColor.a
  115. );
  116. // traa
  117. const traaPass = traa( compositePass, scenePassDepth, scenePassVelocity, camera );
  118. renderPipeline.outputNode = traaPass;
  119. // light
  120. mouseLight = new THREE.PointLight( 0xffffff, 80 );
  121. mouseLight.position.set( 0, BOX_HEIGHT / 2, BOX_DEPTH / 2 );
  122. mouseLight.castShadow = true;
  123. mouseLight.shadow.mapSize.set( 1024, 1024 );
  124. mouseLight.shadow.radius = 20;
  125. scene.add( mouseLight );
  126. //
  127. raycaster = new THREE.Raycaster();
  128. pointer = new THREE.Vector2();
  129. rebuildScene();
  130. //
  131. renderer.domElement.addEventListener( 'pointerdown', onPointerDown );
  132. renderer.domElement.addEventListener( 'pointermove', onPointerMove );
  133. renderer.domElement.addEventListener( 'pointerup', onPointerUp );
  134. renderer.domElement.addEventListener( 'pointercancel', onPointerUp );
  135. window.addEventListener( 'resize', onWindowResize );
  136. }
  137. function getBoxWidth() {
  138. const aspect = window.innerWidth / window.innerHeight;
  139. const vFov = THREE.MathUtils.degToRad( CAM_FOV / 2 );
  140. const dist = ( BOX_HEIGHT / 2 ) / Math.tan( vFov );
  141. return Math.tan( vFov ) * aspect * dist * 2;
  142. }
  143. function getBallCount() {
  144. const roomVolume = boxSize.w * boxSize.h * boxSize.d;
  145. const ballVolume = ( 4 / 3 ) * Math.PI * Math.pow( BALL_RADIUS, 3 );
  146. return Math.floor( roomVolume * FILL_RATIO * PACKING / ballVolume );
  147. }
  148. function rebuildScene() {
  149. for ( const mesh of wallMeshes ) {
  150. scene.remove( mesh );
  151. mesh.geometry.dispose();
  152. }
  153. wallMeshes = [];
  154. if ( ballsMesh ) {
  155. scene.remove( ballsMesh );
  156. ballsMesh.dispose();
  157. ballsMesh = null;
  158. }
  159. bodies = [];
  160. boxSize.w = getBoxWidth();
  161. ballCount = getBallCount();
  162. world = new World( {
  163. gravity: [ 0, - 9.81, 0 ],
  164. solveVelocityIterations: 6,
  165. solvePositionIterations: 2,
  166. linearDamping: 0.1,
  167. angularDamping: 0.1,
  168. restitution: 0.4,
  169. friction: 0.5
  170. } );
  171. fitCameraToBox();
  172. createBox();
  173. createBalls();
  174. }
  175. function createBox() {
  176. const hw = boxSize.w / 2;
  177. const hh = boxSize.h / 2;
  178. const hd = boxSize.d / 2;
  179. const t = WALL_THICKNESS;
  180. const whiteMaterial = new THREE.MeshPhysicalMaterial( {
  181. color: 0xeeeeee,
  182. roughness: 0.7,
  183. metalness: 0.0
  184. } );
  185. const redMaterial = new THREE.MeshPhysicalMaterial( {
  186. color: 0xff2222,
  187. roughness: 0.7,
  188. metalness: 0.0
  189. } );
  190. const greenMaterial = new THREE.MeshPhysicalMaterial( {
  191. color: 0x22ff22,
  192. roughness: 0.7,
  193. metalness: 0.0
  194. } );
  195. const walls = [
  196. { size: [ boxSize.w, t, boxSize.d ], pos: [ 0, - t / 2, 0 ], mat: whiteMaterial },
  197. { size: [ boxSize.w, t, boxSize.d ], pos: [ 0, boxSize.h + t / 2, 0 ], mat: whiteMaterial },
  198. { size: [ boxSize.w, boxSize.h, t ], pos: [ 0, hh, - hd - t / 2 ], mat: whiteMaterial },
  199. { size: [ boxSize.w, boxSize.h, t ], pos: [ 0, hh, hd + t / 2 ], noMesh: true },
  200. { size: [ t, boxSize.h, boxSize.d ], pos: [ - hw - t / 2, hh, 0 ], mat: redMaterial },
  201. { size: [ t, boxSize.h, boxSize.d ], pos: [ hw + t / 2, hh, 0 ], mat: greenMaterial }
  202. ];
  203. for ( const w of walls ) {
  204. const shape = world.createBox( { width: w.size[ 0 ], height: w.size[ 1 ], depth: w.size[ 2 ] } );
  205. world.createStaticBody( { shape, position: w.pos } );
  206. if ( ! w.noMesh ) {
  207. const geo = new THREE.BoxGeometry( w.size[ 0 ], w.size[ 1 ], w.size[ 2 ] );
  208. const mesh = new THREE.Mesh( geo, w.mat );
  209. mesh.position.set( ...w.pos );
  210. mesh.receiveShadow = true;
  211. scene.add( mesh );
  212. wallMeshes.push( mesh );
  213. }
  214. }
  215. }
  216. function createBalls() {
  217. const sphereGeo = new THREE.SphereGeometry( BALL_RADIUS, 32, 16 );
  218. const sphereShape = world.createSphere( { radius: BALL_RADIUS } );
  219. const material = new THREE.MeshPhysicalMaterial( {
  220. roughness: 0.3,
  221. metalness: 0.1
  222. } );
  223. ballsMesh = new THREE.InstancedMesh( sphereGeo, material, ballCount );
  224. ballsMesh.castShadow = true;
  225. ballsMesh.receiveShadow = true;
  226. scene.add( ballsMesh );
  227. const colors = [
  228. 0xff4444, 0x44ff44, 0x4488ff, 0xffaa00, 0xff44ff,
  229. 0x44ffff, 0xffff44, 0xff8844, 0x8844ff, 0x44ff88
  230. ];
  231. const color = new THREE.Color();
  232. const hw = boxSize.w / 2 - BALL_RADIUS - 0.1;
  233. const hd = boxSize.d / 2 - BALL_RADIUS - 0.1;
  234. for ( let i = 0; i < ballCount; i ++ ) {
  235. color.set( colors[ i % colors.length ] );
  236. ballsMesh.setColorAt( i, color );
  237. const x = ( Math.random() - 0.5 ) * 2 * hw;
  238. const y = BALL_RADIUS + Math.random() * ( boxSize.h - BALL_RADIUS * 2 );
  239. const z = ( Math.random() - 0.5 ) * 2 * hd;
  240. const body = world.createDynamicBody( {
  241. shape: sphereShape,
  242. position: [ x, y, z ],
  243. mass: 1,
  244. restitution: 0.5,
  245. friction: 0.4
  246. } );
  247. bodies.push( body );
  248. }
  249. }
  250. function onPointerDown( event ) {
  251. activePointers.add( event.pointerId );
  252. if ( event.pointerType === 'touch' ) {
  253. pointerDown = activePointers.size >= 2;
  254. } else {
  255. pointerDown = true;
  256. }
  257. }
  258. function onPointerUp( event ) {
  259. activePointers.delete( event.pointerId );
  260. if ( event.pointerType === 'touch' ) {
  261. pointerDown = activePointers.size >= 2;
  262. } else {
  263. pointerDown = false;
  264. }
  265. }
  266. function onPointerMove( event ) {
  267. pointer.x = ( event.clientX / window.innerWidth ) * 2 - 1;
  268. pointer.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
  269. raycaster.setFromCamera( pointer, camera );
  270. mouseRayOriginTarget.copy( raycaster.ray.origin );
  271. mouseRayDirTarget.copy( raycaster.ray.direction );
  272. mouseMoving = true;
  273. clearTimeout( mouseStopTimer );
  274. mouseStopTimer = setTimeout( () => mouseMoving = false, 50 );
  275. const frontPlane = new THREE.Plane( new THREE.Vector3( 0, 0, 1 ), - boxSize.d / 2 );
  276. const hit = new THREE.Vector3();
  277. if ( raycaster.ray.intersectPlane( frontPlane, hit ) ) {
  278. mouseLightTarget.copy( hit );
  279. }
  280. }
  281. function respawnBalls() {
  282. const hw = boxSize.w / 2 - BALL_RADIUS - 0.1;
  283. const hd = boxSize.d / 2 - BALL_RADIUS - 0.1;
  284. const count = 5;
  285. for ( let i = 0; i < count; i ++ ) {
  286. const body = bodies[ Math.floor( Math.random() * bodies.length ) ];
  287. body.position.set( [
  288. ( Math.random() - 0.5 ) * 2 * hw,
  289. boxSize.h - BALL_RADIUS - Math.random() * 1,
  290. ( Math.random() - 0.5 ) * 2 * hd
  291. ] );
  292. body.linearVelocity.set( [ 0, 0, 0 ] );
  293. body.angularVelocity.set( [ 0, 0, 0 ] );
  294. body.commitChanges();
  295. }
  296. }
  297. function fitCameraToBox() {
  298. const vFov = THREE.MathUtils.degToRad( CAM_FOV / 2 );
  299. const dist = ( boxSize.h / 2 ) / Math.tan( vFov );
  300. camera.aspect = window.innerWidth / window.innerHeight;
  301. camera.position.set( 0, boxSize.h / 2, dist + boxSize.d / 2 );
  302. camera.lookAt( 0, boxSize.h / 2, 0 );
  303. camera.updateProjectionMatrix();
  304. }
  305. function onWindowResize() {
  306. renderer.setSize( window.innerWidth, window.innerHeight );
  307. rebuildScene();
  308. }
  309. const timer = new THREE.Timer();
  310. const _dummy = new THREE.Object3D();
  311. function animate() {
  312. timer.update();
  313. const dt = Math.min( timer.getDelta(), 1 / 30 );
  314. const easeFactor = 1 - Math.exp( - EASE_SPEED * dt );
  315. mouseRayOrigin.lerp( mouseRayOriginTarget, easeFactor );
  316. mouseRayDir.lerp( mouseRayDirTarget, easeFactor );
  317. mouseLight.position.lerp( mouseLightTarget, easeFactor );
  318. if ( pointerDown ) {
  319. respawnBalls();
  320. }
  321. if ( mouseMoving ) {
  322. const pushRadius = 1.5;
  323. const pushStrength = 15;
  324. const _closest = new THREE.Vector3();
  325. const _ballPos = new THREE.Vector3();
  326. const _pushDir = new THREE.Vector3();
  327. for ( const body of bodies ) {
  328. const bp = body.position;
  329. _ballPos.set( bp.x, bp.y, bp.z );
  330. const ray = new THREE.Ray( mouseRayOrigin, mouseRayDir );
  331. ray.closestPointToPoint( _ballPos, _closest );
  332. const dist = _closest.distanceTo( _ballPos );
  333. if ( dist < pushRadius ) {
  334. _pushDir.subVectors( _ballPos, _closest );
  335. if ( _pushDir.lengthSq() < 0.001 ) _pushDir.set( 0, 1, 0 );
  336. _pushDir.normalize();
  337. const strength = pushStrength * ( 1 - dist / pushRadius );
  338. body.applyLinearImpulse( {
  339. x: _pushDir.x * strength,
  340. y: _pushDir.y * strength,
  341. z: _pushDir.z * strength
  342. } );
  343. }
  344. }
  345. }
  346. if ( world ) {
  347. world.advanceTime( 1 / 60, dt );
  348. }
  349. for ( let i = 0; i < bodies.length; i ++ ) {
  350. const body = bodies[ i ];
  351. const p = body.position;
  352. const q = body.orientation;
  353. _dummy.position.set( p.x, p.y, p.z );
  354. _dummy.quaternion.set( q.x, q.y, q.z, q.w );
  355. _dummy.updateMatrix();
  356. ballsMesh.setMatrixAt( i, _dummy.matrix );
  357. }
  358. ballsMesh.instanceMatrix.needsUpdate = true;
  359. renderPipeline.render();
  360. }
  361. </script>
  362. </body>
  363. </html>
粤ICP备19079148号