/** * WebGPU Gaussian Splat → Solid * * A Gaussian splat is a cloud of fuzzy particles: it has an appearance but no * body — nothing can rest on it, bounce off it, or hide behind it. This example * gives a capture a body without meshing it: * * 1. GaussianSplatsPoints extracts the splat centers as a point cloud. * 2. PointsBVH from three-mesh-bvh accelerates nearest-point queries. * 3. ComputePointsSDFGenerator bakes a flood-filled signed-distance field on * the GPU: every voxel knows whether it is inside the capture. * 4. A GPU grain simulation pours glowing grains onto the capture; each grain * collides with the field, slides down the pot, and pools on the base. * 5. A TSL raymarch turns the field into a depth-only body, so grains behind * the capture are hidden while its visible skin stays intact. */ import * as THREE from 'three/webgpu'; import { Break, Fn, If, PI2, bool, cameraPosition, cameraProjectionMatrix, cameraViewMatrix, dot, float, hash, instanceIndex, instancedArray, max, mix, modelWorldMatrix, normalize, smoothstep, uint, uniform, uv, vec3, vec4, } from 'three/tsl'; import { registerDevtools } from 'three-blocks/devtools'; import WebGPU from 'three/addons/capabilities/WebGPU.js'; import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; import { PointsBVH, computeBoundsTree, disposeBoundsTree } from 'three-mesh-bvh'; import { SplatMesh, GaussianSplatsPoints } from 'three-blocks/gaussian-splats'; import { ComputePointsSDFGenerator, RaymarchingBox, createSDFBoundsHelper, sdfFieldNodes, } from 'three-blocks/sdf-raymarching'; import { createExampleCaption } from '../helpers/ExampleCaption.js'; import { createExampleGui } from '../helpers/exampleGui.js'; import { withAssetLoader } from '../helpers/LoadingManager.js'; import { frameCameraForAspect } from '../helpers/mobile.js'; THREE.BufferGeometry.prototype.computeBoundsTree = computeBoundsTree; THREE.BufferGeometry.prototype.disposeBoundsTree = disposeBoundsTree; // // Module state // let container, renderer, scene, camera, controls, devtools, gui, infoElement, resizeObserver; let containerPosition = ''; let exampleOptions; let splats = null; let pointCloud = null; let sdfGenerator = null; let field = null; let interior = null; let grains = null; let grainKernel = null; let boundsHelper = null; let rebuildPromise = null; const timer = new THREE.Timer(); const raycaster = new THREE.Raycaster(); const pointer = new THREE.Vector2(); const _boundsSize = new THREE.Vector3(); const _boundsCenter = new THREE.Vector3(); const _pointerEmitter = new THREE.Vector3(); const _idleEmitter = new THREE.Vector3(); const _cameraDirection = new THREE.Vector3( 0.22, 0.12, 1 ).normalize(); let pointerWeight = 0; let pointerTarget = 0; let objectRadius = 1; let objectHeight = 1; let emitterHeight = 0; const REDUCED_MOTION = window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches; const DEBUG = new URLSearchParams( window.location.search ).has( 'debug' ); const MARCH_STEPS = Object.freeze( { 1: 40, 2: 64, 3: 96 } ); const GRAIN_COUNT = Object.freeze( { 1: 4096, 2: 8192, 3: 16384 } ); const params = { motion: ! REDUCED_MOTION, rotationSpeed: 0.5, // Grains pour: true, grainColor: 0x3fe4ff, grainGlow: 1, grainSize: 3, restitution: 0.15, friction: 0.2, // Field sdfResolution: 128, surfaceDepth: 0.2, depthBias: 2.5, preroll: 7, quality: 3, showBounds: false, showPoints: false, }; // Shared by the interior raymarch and grain kernel. const u = { time: uniform( 0 ), dt: uniform( 0 ), frame: uniform( 0, 'uint' ), skinColor: uniform( new THREE.Color( params.grainColor ) ), surface: uniform( 0 ), depthBias: uniform( 0 ), worldScale: uniform( 1 ), // Grains emitter: uniform( new THREE.Vector3() ), emitRadius: uniform( 0.2 ), emitSpeed: uniform( 0.3 ), pouring: uniform( 1 ), gravity: uniform( 3 ), drag: uniform( 0.5 ), restitution: uniform( params.restitution ), friction: uniform( params.friction ), grainRadius: uniform( 0.01 ), grainScale: uniform( 0.03 ), grainGlow: uniform( params.grainGlow ), floorY: uniform( - 10 ), }; // // Entry point // export async function mount( containerElement, mountOptions = {} ) { container = containerElement; exampleOptions = { assets: mountOptions.assets ?? {}, debug: mountOptions.debug ?? DEBUG, }; params.motion = mountOptions.motion ?? ! REDUCED_MOTION; if ( Number.isFinite( mountOptions.preroll ) ) params.preroll = THREE.MathUtils.clamp( mountOptions.preroll, 0, 30 ); if ( Number.isInteger( mountOptions.quality ) ) params.quality = THREE.MathUtils.clamp( mountOptions.quality, 1, 3 ); params.sdfResolution = Number.isInteger( mountOptions.sdfResolution ) ? THREE.MathUtils.clamp( mountOptions.sdfResolution, 32, 256 ) : 128; containerPosition = container.style.position; container.style.position = 'relative'; if ( WebGPU.isAvailable() === false ) { container.appendChild( WebGPU.getErrorMessage() ); throw new Error( 'No WebGPU support' ); } await init(); return createExampleHandle(); } async function init() { createInfoElement(); const width = Math.max( 1, container.clientWidth ); const height = Math.max( 1, container.clientHeight ); camera = new THREE.PerspectiveCamera( 50, width / height, 0.01, 1000 ); scene = new THREE.Scene(); scene.background = new THREE.Color( 0x05070a ); renderer = new THREE.WebGPURenderer( { antialias: true, trackTimestamp: true } ); devtools = registerDevtools( { renderer, container } ); renderer.setPixelRatio( Math.min( window.devicePixelRatio || 1, 1.5 ) ); renderer.setSize( width, height ); container.appendChild( renderer.domElement ); await renderer.init(); controls = new OrbitControls( camera, renderer.domElement ); controls.enableDamping = true; controls.autoRotate = params.motion; controls.autoRotateSpeed = params.rotationSpeed; await loadSplats(); await rebuildField(); createGrains(); // Open on a populated scene: the same fixed steps live and under capture. stepGrains( params.preroll * 60, 1 / 60 ); await setupGui(); renderer.domElement.addEventListener( 'pointermove', onPointerMove ); renderer.domElement.addEventListener( 'pointerleave', onPointerLeave ); renderer.setAnimationLoop( animate ); resizeObserver = new ResizeObserver( onWindowResize ); resizeObserver.observe( container ); onWindowResize(); } // // Splats // function splatAssetUrl() { const asset = exampleOptions.assets.pointCloud; if ( asset ) return asset instanceof URL ? asset.href : asset; const filesRoot = exampleOptions.assets.files; if ( filesRoot ) return new URL( 'splat/raspberry-gallery.sog', new URL( filesRoot, window.location.href ) ).href; throw new Error( 'This example requires assets.pointCloud or assets.files.' ); } async function loadSplats() { splats = await withAssetLoader( container, [ 'Gaussian capture' ], manager => ( manager.load( 'Gaussian capture', onProgress => SplatMesh.load( splatAssetUrl(), { onProgress, } ) ) ) ); scene.add( splats ); // Splat centers, already in world space, as the BVH source. pointCloud = new GaussianSplatsPoints( splats, { pointSize: 2, color: 0x3fe4ff, sizeAttenuation: false } ); pointCloud.material.opacity = 0.5; pointCloud.visible = params.showPoints; pointCloud.geometry.computeBoundsTree( { type: PointsBVH } ); scene.add( pointCloud ); frameSplats(); } function frameSplats() { const geometry = pointCloud.geometry; geometry.computeBoundingBox(); geometry.boundingBox.getCenter( _boundsCenter ); geometry.boundingBox.getSize( _boundsSize ); objectRadius = Math.max( _boundsSize.length() * 0.5, 0.1 ); objectHeight = Math.max( _boundsSize.y, 0.1 ); emitterHeight = geometry.boundingBox.max.y + objectHeight * 0.06; u.floorY.value = geometry.boundingBox.min.y - objectHeight * 0.15; const halfFov = THREE.MathUtils.degToRad( camera.fov * 0.5 ); const distance = objectRadius / Math.sin( halfFov ) * 1.08; controls.target.copy( _boundsCenter ); camera.position.copy( _boundsCenter ).addScaledVector( _cameraDirection, distance ); frameCameraForAspect( camera, controls.target, true ); camera.near = Math.max( distance / 500, 0.001 ); camera.far = distance * 20; camera.updateProjectionMatrix(); controls.minDistance = objectRadius * 0.55; controls.maxDistance = objectRadius * 8; controls.update(); } // // Field // async function rebuildField() { if ( rebuildPromise ) return rebuildPromise; rebuildPromise = ( async () => { sdfGenerator ??= new ComputePointsSDFGenerator( { margin: 0.15 } ); sdfGenerator.resolution = params.sdfResolution; await sdfGenerator.generate( pointCloud.geometry, pointCloud.geometry.boundsTree, renderer ); if ( field ) field.update(); else field = sdfFieldNodes( sdfGenerator ); sdfGenerator.bounds.getSize( _boundsSize ); u.worldScale.value = Math.max( _boundsSize.x, _boundsSize.y, _boundsSize.z ); applyParams(); if ( ! interior ) { interior = new THREE.Mesh( new THREE.BoxGeometry( 1, 1, 1 ), createInteriorMaterial() ); interior.name = 'Splat body'; interior.matrixAutoUpdate = false; interior.frustumCulled = false; interior.renderOrder = 1; scene.add( interior ); } interior.matrix.copy( sdfGenerator.boundsMatrix ); interior.matrixWorldNeedsUpdate = true; if ( boundsHelper ) scene.remove( boundsHelper ); boundsHelper = createSDFBoundsHelper( sdfGenerator, 0x3fe4ff ); boundsHelper.visible = params.showBounds; scene.add( boundsHelper ); updateInfo(); } )(); rebuildPromise.finally( () => { rebuildPromise = null; } ); return rebuildPromise; } function applyParams() { u.skinColor.value.set( params.grainColor ); u.pouring.value = params.pour ? 1 : 0; u.grainGlow.value = params.grainGlow; u.restitution.value = params.restitution; u.friction.value = params.friction; u.gravity.value = objectRadius * 2.6; u.drag.value = 0.8; u.emitRadius.value = objectRadius * 0.12; u.emitSpeed.value = objectRadius * 0.15; u.grainRadius.value = objectRadius * 0.005; u.grainScale.value = objectRadius * 0.014 * params.grainSize; // The field's zero level sits one shell radius proud of the splat centers, and inside a // capture the values never get much deeper than one shell (the interior is a soup of // centers). The solid therefore starts just inside the crust, and its written depth is // pushed `depthBias` shells back along the view ray so the front skin still composites // over it while the far skin is occluded. if ( sdfGenerator ) { u.surface.value = - sdfGenerator.shellRadius * params.surfaceDepth; u.depthBias.value = sdfGenerator.shellRadius * params.depthBias; } } // // Body raymarch: sphere-trace the field and write only its entry depth, so it occludes // grains behind the capture without adding another visible effect. // function createInteriorMaterial() { const steps = MARCH_STEPS[ params.quality ]; const material = new THREE.NodeMaterial(); material.name = 'Splat body'; material.side = THREE.BackSide; material.colorWrite = false; material.transparent = true; const depth = Fn( () => { const entered = bool( false ).toVar(); const hitPosition = vec3( 0 ).toVar(); RaymarchingBox( steps, ( { positionRay, delta, stepAdvance } ) => { const worldPosition = modelWorldMatrix.mul( vec4( positionRay, 1 ) ).xyz.toVar(); const distance = field.distance( worldPosition ).sub( u.surface ).toVar(); If( distance.lessThan( 0 ), () => { entered.assign( true ); hitPosition.assign( worldPosition ); Break(); } ); // Empty space: sphere-trace toward the solid, at half steps once it is near. stepAdvance.assign( max( delta.mul( 0.5 ), distance.mul( 0.8 ).div( u.worldScale ) ) ); } ); entered.not().discard(); const viewDirection = normalize( cameraPosition.sub( hitPosition ) ); const depthPosition = hitPosition.sub( viewDirection.mul( u.depthBias ) ); const clip = cameraProjectionMatrix.mul( cameraViewMatrix ).mul( vec4( depthPosition, 1 ) ); return clip.z.div( clip.w ); } )(); material.fragmentNode = vec4( 0 ); material.depthNode = depth; return material; } // // Grains: a GPU particle pour. Each grain falls, collides with the field (push-out along // the field normal, bounce, friction), slides down slopes, and pools on flat spots. // function createGrains() { const count = GRAIN_COUNT[ params.quality ]; const positions = instancedArray( count, 'vec4' ); // xyz, remaining life const velocities = instancedArray( count, 'vec4' ); // Start every grain dead below the floor with a staggered (deterministic) life so the // pour ramps up instead of dumping every grain on the first frame. const initial = positions.value.array; for ( let i = 0; i < count; i ++ ) { initial[ i * 4 + 1 ] = - 1e3; initial[ i * 4 + 3 ] = ( ( i * 2654435761 ) >>> 0 ) / 2 ** 32 * 8; } const random = ( salt ) => hash( instanceIndex.mul( uint( 16 ) ).add( uint( salt ) ).add( u.frame.mul( uint( 100003 ) ) ) ); grainKernel = Fn( () => { const record = positions.element( instanceIndex ); const motion = velocities.element( instanceIndex ); const position = record.xyz.toVar(); const velocity = motion.xyz.toVar(); const life = record.w.sub( u.dt ).toVar(); If( life.lessThanEqual( 0 ).or( position.y.lessThan( u.floorY ) ), () => { // Dead grain: park it below the floor, and respawn it at the emitter while pouring. position.assign( vec3( 0, - 1e3, 0 ) ); velocity.assign( vec3( 0 ) ); life.assign( random( 1 ).mul( 0.25 ) ); If( u.pouring.greaterThan( 0.5 ).and( random( 2 ).lessThan( 0.16 ) ), () => { const angle = random( 3 ).mul( PI2 ); const radius = random( 4 ).sqrt().mul( u.emitRadius ); position.assign( u.emitter.add( vec3( angle.cos().mul( radius ), random( 5 ).mul( u.emitRadius ), angle.sin().mul( radius ) ) ) ); velocity.assign( vec3( random( 6 ).sub( 0.5 ), random( 7 ).mul( - 0.5 ), random( 8 ).sub( 0.5 ) ).mul( u.emitSpeed ) ); life.assign( random( 9 ).mul( 10 ).add( 10 ) ); } ); } ).Else( () => { velocity.assign( velocity.add( vec3( 0, u.gravity.mul( u.dt ).negate(), 0 ) ) ); velocity.assign( velocity.mul( float( 1 ).sub( u.drag.mul( u.dt ) ).max( 0 ) ) ); position.assign( position.add( velocity.mul( u.dt ) ) ); const distance = field.distance( position ).toVar(); If( distance.lessThan( u.grainRadius ), () => { const normal = field.normal( position ).toVar(); position.assign( position.add( normal.mul( u.grainRadius.sub( distance ) ) ) ); const approach = dot( velocity, normal ).toVar(); If( approach.lessThan( 0 ), () => { velocity.assign( velocity.sub( normal.mul( approach.mul( u.restitution.add( 1 ) ) ) ) ); } ); velocity.assign( velocity.mul( float( 1 ).sub( u.friction ) ) ); } ); } ); record.assign( vec4( position, life ) ); motion.assign( vec4( velocity, 0 ) ); } )().compute( count ); const material = new THREE.SpriteNodeMaterial( { transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, } ); const record = positions.element( instanceIndex ); const speed = velocities.element( instanceIndex ).xyz.length(); const alive = record.w.greaterThan( 0 ).and( record.y.greaterThan( u.floorY ) ); const fade = smoothstep( 0, 1.2, record.w ); const heat = smoothstep( 0.1, 1.2, speed.div( u.gravity ) ); material.positionNode = record.xyz; material.scaleNode = u.grainScale.mul( alive.select( float( 1 ), float( 0 ) ) ).mul( heat.mul( 0.4 ).add( 0.6 ) ); material.colorNode = mix( u.skinColor, vec3( 0.85, 1, 1 ), heat ).mul( u.grainGlow.mul( 1.4 ) ); material.opacityNode = smoothstep( 0.5, 0.05, uv().sub( 0.5 ).length() ).mul( fade ); grains = new THREE.InstancedMesh( new THREE.PlaneGeometry( 1, 1 ), material, count ); grains.name = 'Grains'; grains.frustumCulled = false; // Composite after the splat skin; depth-tested against the body so far-side grains hide. grains.renderOrder = 2; scene.add( grains ); } // // Interface // function updateInfo() { if ( ! infoElement || ! splats ) return; const detail = infoElement.querySelector( '[data-detail]' ); if ( detail ) detail.textContent = `${( splats.count || splats.maxSplats ).toLocaleString()} splats · ${params.sdfResolution}³ field · ${GRAIN_COUNT[ params.quality ].toLocaleString()} grains · move to pour`; } function createInfoElement() { infoElement = createExampleCaption( { accent: '#3fe4ff', ariaLabel: 'Splat body details', label: 'Scene details', content: ` A Gaussian capture with a body Splats → solid Distance field baked from the splat centers Building the distance field… `, } ); container.appendChild( infoElement ); } async function setupGui() { gui = await createExampleGui( 'Splat body' ); if ( container.clientWidth < 560 ) gui.close(); gui.add( params, 'pour' ).name( 'Pour grains' ).onChange( applyParams ); gui.add( params, 'motion' ).name( 'Animate' ); const grainFolder = gui.addFolder( 'Grains' ); grainFolder.addColor( params, 'grainColor' ).name( 'Glow color' ).onChange( applyParams ); grainFolder.add( params, 'grainGlow', 0, 3, 0.01 ).name( 'Brightness' ).onChange( applyParams ); grainFolder.add( params, 'grainSize', 0.4, 3, 0.05 ).name( 'Size' ).onChange( applyParams ); grainFolder.add( params, 'restitution', 0, 0.9, 0.01 ).name( 'Bounce' ).onChange( applyParams ); grainFolder.add( params, 'friction', 0, 0.5, 0.01 ).name( 'Friction' ).onChange( applyParams ); if ( ! exampleOptions.debug ) return; const fieldFolder = gui.addFolder( 'Engineering · field' ); fieldFolder.add( params, 'sdfResolution', [ 32, 48, 64, 96, 128 ] ).name( 'Resolution' ).onChange( rebuildField ); fieldFolder.add( params, 'surfaceDepth', 0, 1, 0.05 ).name( 'Body depth (shells)' ).onChange( applyParams ); fieldFolder.add( params, 'depthBias', 0, 6, 0.1 ).name( 'Depth bias (shells)' ).onChange( applyParams ); fieldFolder.add( params, 'showBounds' ).name( 'Show bounds' ).onChange( value => { if ( boundsHelper ) boundsHelper.visible = value; } ); fieldFolder.add( params, 'showPoints' ).name( 'Show centers' ).onChange( value => { if ( pointCloud ) pointCloud.visible = value; } ); } function createExampleHandle() { const settle = ( frameCount = 3 ) => new Promise( resolve => { let remaining = Math.max( 1, Math.floor( frameCount ) ); const advance = () => { remaining --; if ( remaining <= 0 ) resolve(); else requestAnimationFrame( advance ); }; requestAnimationFrame( advance ); } ); return { version: 2, ready: true, setViewAzimuth( degrees, elevationDegrees = 7 ) { const radius = camera.position.distanceTo( controls.target ); const azimuth = THREE.MathUtils.degToRad( degrees ); const elevation = THREE.MathUtils.degToRad( elevationDegrees ); camera.position.copy( controls.target ).add( new THREE.Vector3( Math.sin( azimuth ) * Math.cos( elevation ) * radius, Math.sin( elevation ) * radius, Math.cos( azimuth ) * Math.cos( elevation ) * radius ) ); controls.update(); }, setMotion( enabled ) { params.motion = Boolean( enabled ); }, advance( seconds ) { stepGrains( Math.round( Math.max( 0, seconds ) * 60 ), 1 / 60 ); }, whenSettled: settle, getDiagnostics() { return { splats: splats?.count ?? 0, grains: GRAIN_COUNT[ params.quality ], resolution: params.sdfResolution, shellRadius: sdfGenerator?.shellRadius ?? 0, quality: params.quality, renderTimestamp: renderer.info?.render?.timestamp ?? null, }; }, dispose: unmount, }; } // // Frame loop // function stepGrains( steps, dt ) { for ( let i = 0; i < steps; i ++ ) { u.time.value += dt; u.dt.value = dt; u.frame.value = ( u.frame.value + 1 ) % 65536; updateEmitter( dt ); renderer.compute( grainKernel ); } } function updateEmitter( delta ) { // Pour from under the pointer while it is over the scene, from a slow orbit otherwise. pointerWeight += ( pointerTarget - pointerWeight ) * Math.min( 1, delta * 6 ); const orbit = u.time.value * 0.45; _idleEmitter.set( _boundsCenter.x + Math.cos( orbit ) * objectRadius * 0.18, emitterHeight, _boundsCenter.z + Math.sin( orbit ) * objectRadius * 0.18 ); u.emitter.value.lerpVectors( _idleEmitter, _pointerEmitter, pointerWeight ); } function animate( timestamp ) { // The loop timestamp keeps capture frames on their fixed virtual clock. timer.update( timestamp ); const delta = Math.min( timer.getDelta(), 1 / 30 ); controls.autoRotate = params.motion; controls.autoRotateSpeed = params.rotationSpeed; controls.update( delta ); // Grains always simulate: a still frame with nothing pooled says nothing. stepGrains( 1, delta ); renderer.render( scene, camera ); } // // Events // function onPointerMove( event ) { const rect = renderer.domElement.getBoundingClientRect(); pointer.set( ( ( event.clientX - rect.left ) / rect.width ) * 2 - 1, - ( ( event.clientY - rect.top ) / rect.height ) * 2 + 1 ); raycaster.setFromCamera( pointer, camera ); // Pour from above the point the pointer ray passes closest to the capture. raycaster.ray.closestPointToPoint( _boundsCenter, _pointerEmitter ); _pointerEmitter.x = THREE.MathUtils.clamp( _pointerEmitter.x, _boundsCenter.x - _boundsSize.x * 0.5, _boundsCenter.x + _boundsSize.x * 0.5 ); _pointerEmitter.y = emitterHeight; _pointerEmitter.z = THREE.MathUtils.clamp( _pointerEmitter.z, _boundsCenter.z - _boundsSize.z * 0.5, _boundsCenter.z + _boundsSize.z * 0.5 ); pointerTarget = 1; } function onPointerLeave() { pointerTarget = 0; } function onWindowResize() { const width = Math.max( 1, container.clientWidth ); const height = Math.max( 1, container.clientHeight ); camera.aspect = width / height; camera.updateProjectionMatrix(); frameCameraForAspect( camera, controls.target ); renderer.setSize( width, height ); } export function unmount() { renderer?.setAnimationLoop( null ); renderer?.domElement.removeEventListener( 'pointermove', onPointerMove ); renderer?.domElement.removeEventListener( 'pointerleave', onPointerLeave ); resizeObserver?.disconnect(); resizeObserver = null; for ( const mesh of [ interior, grains ] ) { if ( ! mesh ) continue; scene.remove( mesh ); mesh.geometry.dispose(); mesh.material.dispose(); } interior = null; grains = null; grainKernel = null; if ( boundsHelper ) { scene.remove( boundsHelper ); boundsHelper.traverse?.( object => { object.geometry?.dispose?.(); object.material?.dispose?.(); } ); boundsHelper = null; } if ( pointCloud ) { scene.remove( pointCloud ); pointCloud.geometry.disposeBoundsTree?.(); pointCloud.geometry.dispose(); pointCloud.material.dispose(); pointCloud = null; } if ( splats ) { scene.remove( splats ); splats.dispose(); splats = null; } sdfGenerator?.dispose(); sdfGenerator = null; field = null; gui?.destroy(); gui = null; controls?.dispose(); controls = null; infoElement?.remove(); infoElement = null; devtools?.dispose(); devtools = null; renderer?.dispose(); renderer?.domElement?.remove(); renderer = null; scene = null; camera = null; if ( container ) container.style.position = containerPosition; containerPosition = ''; container = null; exampleOptions = null; }