webgpu_postprocessing_ssgi_ballpool.html 13 KB

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