Three Blocks

Skinned fox / source

Open preview
webgpu_gaussiansplat_skinned/source.jsPlain text ↗
/** Sample a textured fox in its rest pose and animate the splats with its glTF skeleton. */
import * as THREE from 'three/webgpu';
import { mix, screenUV, smoothstep, vec2, vec3 } from 'three/tsl';
import WebGPU from 'three/addons/capabilities/WebGPU.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { addEarFold, sampleFoxSplats } from './foxSplats.js';
import { registerDevtools } from 'three-blocks/devtools';
import { SplatMesh, SplatSkin } from 'three-blocks/gaussian-splats';
import { createExampleCaption } from '../helpers/ExampleCaption.js';
import { createExampleGui } from '../helpers/exampleGui.js';
import { withAssetLoader } from '../helpers/LoadingManager.js';

const MAX_PIXEL_RATIO = 1;
const CLIP_FADE_SECONDS = 0.35;
const CAMERA_TWEEN_SECONDS = 0.8;
const CAMERA_DIRECTION = new THREE.Vector3( - 1, 0.19, 0.46 ).normalize();
// The glTF head joint sits at the neck. Aim midway between the muzzle and ears.
const HEAD_FOCUS_OFFSET = new THREE.Vector3( 16.6, 7.2, 0 );
const headPosition = new THREE.Vector3();
const headMovement = new THREE.Vector3();
const cameraOrbit = new THREE.Spherical();

let container;
let containerStyle;
let renderer;
let devtools;
let scene;
let camera;
let controls;
let resizeObserver;
let timer;
let gui = null;
let caption = null;
let splats = null;
let skin = null;
let rig = null;
let headBone = null;
let followHead = false;
let cameraTween = null;
let mixer = null;
let bodyAction = null;
let options;
let mounted = false;

const params = { clip: '', speed: 1, showRig: false, deformation: 'surface' };

export async function mount( containerElement, mountOptions = {} ) {

	container = containerElement;
	options = {
		assets: mountOptions.assets ?? {},
		quality: mountOptions.quality ?? 'quality',
		// Deterministic captures hold one pose: no playback, no idle life, no orbit.
		autoPlay: mountOptions.autoPlay ?? true,
		initialTime: mountOptions.initialTime ?? 0,
	};
	containerStyle = {
		position: container.style.position,
		overflow: container.style.overflow,
		touchAction: container.style.touchAction,
	};
	container.style.position = 'relative';
	container.style.overflow = 'hidden';
	container.style.touchAction = 'none';
	mounted = true;

	if ( WebGPU.isAvailable() === false ) {

		container.appendChild( WebGPU.getErrorMessage() );
		throw new Error( 'No WebGPU support' );

	}

	await init();
	return {
		dispose: unmount,
		getDiagnostics: () => ( {
			splatCount: splats?.count ?? 0,
			clip: params.clip,
			shapeKeys: skin?.meshes.reduce( ( count, mesh ) => count + ( mesh.morphTargetInfluences?.length ?? 0 ), 0 ) ?? 0,
		} ),
	};

}

function assetUrl() {

	const direct = options.assets?.fox;
	if ( typeof direct === 'string' && direct.length > 0 ) return direct;
	const root = options.assets?.media;
	if ( typeof root !== 'string' || root.length === 0 ) throw new Error( `Skinned splats require assets.fox or assets.media.` );
	return `${ root.replace( /\/$/u, '' ) }/splat/fox.glb`;

}

async function init() {

	const width = Math.max( 1, container.clientWidth );
	const height = Math.max( 1, container.clientHeight );
	camera = new THREE.PerspectiveCamera( 32, width / height, 0.05, 50 );
	scene = new THREE.Scene();
	// Display-referred like the splats themselves: a warm pool of light on a dark stage.
	const glow = smoothstep( 0.75, 0.0, screenUV.sub( vec2( 0.5, 0.42 ) ).length() );
	scene.backgroundNode = mix( vec3( 0.035, 0.03, 0.028 ), vec3( 0.24, 0.19, 0.15 ), glow );

	renderer = new THREE.WebGPURenderer( { antialias: false } );
	devtools = registerDevtools( { renderer, container } );
	void devtools?.setStatsPanelMode( 'expanded' );
	renderer.setPixelRatio( Math.min( window.devicePixelRatio || 1, MAX_PIXEL_RATIO ) );
	renderer.setSize( width, height );
	renderer.toneMapping = THREE.NoToneMapping;
	renderer.outputColorSpace = THREE.LinearSRGBColorSpace;
	container.appendChild( renderer.domElement );
	await renderer.init();

	controls = new OrbitControls( camera, renderer.domElement );
	controls.enableDamping = true;
	controls.dampingFactor = 0.045;
	controls.zoomToCursor = true;
	controls.autoRotate = false;
	controls.autoRotateSpeed = 0.7;
	controls.addEventListener( 'start', () => { cameraTween = null; } );

	const gltf = await withAssetLoader( container, [ 'Fox' ], manager =>
		manager.load( 'Fox', onProgress => new GLTFLoader().loadAsync( assetUrl(), onProgress ) )
	);
	if ( ! mounted ) return;
	rig = gltf.scene;
	rig.scale.setScalar( 0.015 );
	rig.updateMatrixWorld( true );
	const fox = rig.getObjectByProperty( 'isSkinnedMesh', true );
	addEarFold( fox );
	const restSplats = sampleFoxSplats( fox, 80_000 );
	splats = await SplatMesh.parse( restSplats, 'fox.splat', {
		quality: options.quality,
		attributeMode: 'expanded',
		rendererMode: 'compute-tiles',
		compositing: 'display',
		alphaMode: 'premultiplied',
		appearance: { mode: 'unlit' },
	} );
	if ( ! mounted ) { splats.dispose(); return; }
	headBone = rig.getObjectByName( 'b_Head_05' );
	scene.add( rig, splats );
	const rigMaterial = new THREE.MeshBasicMaterial( { color: 0x7dd3fc, wireframe: true, transparent: true, opacity: 0.35, depthTest: false } );
	rig.traverse( object => {

		if ( ! object.isMesh ) return;
		object.material.map?.image?.close?.();
		object.material.map?.dispose();
		object.material.dispose();
		object.material = rigMaterial;
		object.visible = params.showRig;
		object.frustumCulled = false;
		object.renderOrder = 1; // over the splats

	} );
	frameSubject( false, false );
	skin = new SplatSkin( splats, rig, { deformation: params.deformation } );

	// From here on it is the classic three.js animation stack.
	mixer = new THREE.AnimationMixer( rig );
	const bodyClips = gltf.animations;
	const walk = bodyClips.find( clip => /walk/iu.test( clip.name ) ) ?? bodyClips[ 0 ];
	if ( walk ) playClip( walk );
	if ( ! options.autoPlay ) mixer.setTime( options.initialTime );

	buildGui( bodyClips );
	caption = createCaption();
	container.appendChild( caption );

	timer = new THREE.Timer();
	timer.connect( document );
	resizeObserver = new ResizeObserver( onResize );
	resizeObserver.observe( container );
	renderer.setAnimationLoop( render );

}

function playClip( clip ) {

	const next = mixer.clipAction( clip );
	next.reset().setEffectiveWeight( 1 ).play();
	if ( bodyAction && bodyAction !== next ) bodyAction.crossFadeTo( next, CLIP_FADE_SECONDS, false );
	bodyAction = next;
	params.clip = clip.name;

}

function buildGui( bodyClips ) {

	gui = createExampleGui( 'Skinned splats' );
	if ( container.clientWidth < 560 ) gui.close();
	const view = gui.addFolder( 'Camera' );
	const views = { head: () => frameSubject( true ), body: () => frameSubject() };
	if ( headBone ) view.add( views, 'head' ).name( 'Focus head' )
		.info( 'Follow the head. Scroll or pinch to zoom; right-drag or two-finger drag to pan.' );
	view.add( views, 'body' ).name( 'Full body' );
	view.add( controls, 'autoRotate' ).name( 'Auto rotate' ).listen();
	const label = clip => clip.name.replace( /^.*_/u, '' );
	const skeleton = gui.addFolder( 'Skeleton' );
	if ( bodyClips.length ) {

		const clips = Object.fromEntries( bodyClips.map( clip => [ label( clip ), clip.name ] ) );
		skeleton.add( params, 'clip', clips ).name( 'Clip' ).onChange( name => playClip( bodyClips.find( clip => clip.name === name ) ) );

	}
	skeleton.add( params, 'speed', 0, 10, 0.01 ).name( 'Speed' );
	skeleton.add( params, 'showRig' ).name( 'Show rig' ).onChange( visible => rig.traverse( object => {

		if ( object.isMesh ) object.visible = visible;

	} ) );

	const shapeKeys = gui.addFolder( 'Shape keys' );
	// 'surface' stretches and turns each splat with its posed triangle; 'rigid' only turns it with the bones.
	shapeKeys.add( params, 'deformation', [ 'surface', 'rigid' ] ).name( 'Deformation' ).onChange( deformation => {

		skin.dispose();
		skin = new SplatSkin( splats, rig, { deformation } );

	} );
	const fox = rig.getObjectByProperty( 'isSkinnedMesh', true );
	shapeKeys.add( fox.morphTargetInfluences, 0, 0, 1, 0.01 ).name( 'Fold ears' );

}

function createCaption() {

	return createExampleCaption( {
		accent: '#e0a458',
		ariaLabel: 'About this skinned splat',
		label: 'About',
		content: `
			<span class="tb-example-caption__eyebrow">Animated Gaussian splats</span>
			<h2 class="tb-example-caption__title">Skinned splats</h2>
			<p class="tb-example-caption__note">PixelMannen’s fox is sampled into 80,000 Gaussians. Switch between the three skeletal clips or fold its ears to see the splats follow the mesh.</p>
		`,
	} );

}

function frameSubject( focusHead = false, animate = true ) {

	const bounds = splats._sourceBounds.clone().applyMatrix4( splats._coordTransform );
	const center = bounds.getCenter( new THREE.Vector3() );
	const radius = Math.max( bounds.getSize( new THREE.Vector3() ).length() * 0.5, 0.01 );
	followHead = focusHead && Boolean( headBone );
	if ( followHead ) {

		headBone.localToWorld( center.copy( HEAD_FOCUS_OFFSET ) );
		headPosition.copy( center );
		controls.autoRotate = false;

	}
	const verticalFov = THREE.MathUtils.degToRad( camera.fov );
	const horizontalFov = 2 * Math.atan( Math.tan( verticalFov * 0.5 ) * camera.aspect );
	// The bounding sphere of a long animal is mostly empty; sit closer than it suggests.
	const distance = radius / Math.sin( Math.min( verticalFov, horizontalFov ) * 0.5 ) * ( followHead ? 0.24 : 0.7 );
	camera.near = radius * 0.005;
	camera.far = radius * 40;
	camera.updateProjectionMatrix();
	controls.minDistance = radius * 0.12;
	controls.maxDistance = radius * 8;
	cameraTween = null;
	if ( animate && ! window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches ) {

		const fromOrbit = new THREE.Spherical().setFromVector3( camera.position.clone().sub( controls.target ) );
		const toOrbit = new THREE.Spherical().setFromVector3( CAMERA_DIRECTION.clone().multiplyScalar( distance ) );
		// Take the short orbit around the subject instead of cutting through it.
		const angle = toOrbit.theta - fromOrbit.theta;
		toOrbit.theta = fromOrbit.theta + Math.atan2( Math.sin( angle ), Math.cos( angle ) );
		cameraTween = { elapsed: 0, fromTarget: controls.target.clone(), target: center, fromOrbit, toOrbit };

	} else {

		camera.position.copy( center ).addScaledVector( CAMERA_DIRECTION, distance );
		controls.target.copy( center );
		controls.update( 0 );

	}

}

function render() {

	timer.update();
	const delta = Math.min( timer.getDelta(), 0.05 );
	if ( options.autoPlay ) {

		mixer.update( delta * params.speed );

	}
	if ( followHead ) {

		// Move both ends together so animation preserves the user's orbit, zoom and pan.
		headBone.localToWorld( headMovement.copy( HEAD_FOCUS_OFFSET ) );
		headMovement.sub( headPosition );
		if ( cameraTween ) cameraTween.target.add( headMovement );
		else {

			camera.position.add( headMovement );
			controls.target.add( headMovement );

		}
		headPosition.add( headMovement );

	}
	if ( cameraTween ) {

		// Clear orbit/pan momentum while the tween owns the camera.
		controls.enableDamping = false;
		controls.update( 0 );
		controls.enableDamping = true;
		const tween = cameraTween;
		tween.elapsed += delta;
		const alpha = THREE.MathUtils.smootherstep( tween.elapsed, 0, CAMERA_TWEEN_SECONDS );
		controls.target.lerpVectors( tween.fromTarget, tween.target, alpha );
		cameraOrbit.set(
			THREE.MathUtils.lerp( tween.fromOrbit.radius, tween.toOrbit.radius, alpha ),
			THREE.MathUtils.lerp( tween.fromOrbit.phi, tween.toOrbit.phi, alpha ),
			THREE.MathUtils.lerp( tween.fromOrbit.theta, tween.toOrbit.theta, alpha )
		);
		camera.position.setFromSpherical( cameraOrbit ).add( controls.target );
		camera.lookAt( controls.target );
		if ( tween.elapsed >= CAMERA_TWEEN_SECONDS ) cameraTween = null;

	} else controls.update( delta );
	renderer.render( scene, camera );

}

function onResize() {

	if ( ! container || ! renderer || ! camera ) return;
	const width = Math.max( 1, container.clientWidth );
	const height = Math.max( 1, container.clientHeight );
	renderer.setPixelRatio( Math.min( window.devicePixelRatio || 1, MAX_PIXEL_RATIO ) );
	renderer.setSize( width, height );
	camera.aspect = width / height;
	camera.updateProjectionMatrix();

}

export function unmount() {

	mounted = false;
	renderer?.setAnimationLoop( null );
	resizeObserver?.disconnect();
	resizeObserver = null;
	gui?.destroy();
	gui = null;
	caption?.remove();
	caption = null;
	mixer?.stopAllAction();
	mixer = null;
	bodyAction = null;
	skin?.dispose();
	skin = null;
	controls?.dispose();
	controls = null;
	if ( splats ) {

		scene?.remove( splats );
		splats.dispose();
		splats = null;

	}
	rig?.traverse( object => {

		if ( object.isMesh ) { object.geometry.dispose(); object.material.dispose(); }

	} );
	rig = null;
	headBone = null;
	followHead = false;
	cameraTween = null;
	if ( renderer ) {

		devtools?.dispose();
		devtools = null;
		renderer.dispose();
		renderer.domElement.remove();
		renderer = null;

	}
	if ( container && containerStyle ) Object.assign( container.style, containerStyle );
	containerStyle = null;
	scene = null;
	camera = null;
	timer?.dispose();
	timer = null;
	container = null;
	options = null;

}