/**
* Gallery/browser verification bridge for the SDF body-tracking example.
*
* This module is bundled by the gallery adapter and is intentionally excluded
* from the authored source shown to learners.
*/
import * as THREE from 'three/webgpu';
import { mergeVertices } from 'three/addons/utils/BufferGeometryUtils.js';
const vectors = [
new THREE.Vector3(),
new THREE.Vector3(),
new THREE.Vector3(),
new THREE.Vector3(),
];
function inspection( controller ) {
if ( typeof controller?.inspect !== 'function' ) {
throw new Error( 'SDF body tracking: the gallery bridge requires an inspectable controller.' );
}
return controller.inspect();
}
function setJoint( pose, index, x, y, z ) {
pose[ index * 3 ] = x;
pose[ index * 3 + 1 ] = y;
pose[ index * 3 + 2 ] = z;
}
function getJoint( pose, index, target ) {
return target.set( pose[ index * 3 ], pose[ index * 3 + 1 ], pose[ index * 3 + 2 ] );
}
function midpoint( pose, a, b, target ) {
getJoint( pose, a, target );
getJoint( pose, b, vectors[ 3 ] );
return target.add( vectors[ 3 ] ).multiplyScalar( 0.5 );
}
function poseDirection( pose, a, b, target ) {
getJoint( pose, a, target );
getJoint( pose, b, vectors[ 3 ] );
return target.subVectors( vectors[ 3 ], target ).normalize();
}
function knownPose( controller, kind ) {
const { retargeter, constants: { LM } } = inspection( controller );
const pose = Float32Array.from( retargeter.restPose );
if ( kind === 'right-arm-raise' ) {
getJoint( pose, LM.RIGHT_SHOULDER, vectors[ 0 ] );
setJoint( pose, LM.RIGHT_ELBOW, vectors[ 0 ].x, vectors[ 0 ].y + 0.32, vectors[ 0 ].z );
setJoint( pose, LM.RIGHT_WRIST, vectors[ 0 ].x, vectors[ 0 ].y + 0.62, vectors[ 0 ].z );
setJoint( pose, LM.RIGHT_INDEX, vectors[ 0 ].x, vectors[ 0 ].y + 0.72, vectors[ 0 ].z );
} else if ( kind === 'right-leg-sweep' ) {
getJoint( pose, LM.RIGHT_HIP, vectors[ 0 ] );
setJoint( pose, LM.RIGHT_KNEE, vectors[ 0 ].x + 0.05, vectors[ 0 ].y - 0.22, vectors[ 0 ].z + 0.38 );
setJoint( pose, LM.RIGHT_ANKLE, vectors[ 0 ].x + 0.08, vectors[ 0 ].y - 0.3, vectors[ 0 ].z + 0.78 );
setJoint( pose, LM.RIGHT_HEEL, vectors[ 0 ].x + 0.08, vectors[ 0 ].y - 0.32, vectors[ 0 ].z + 0.76 );
setJoint( pose, LM.RIGHT_FOOT, vectors[ 0 ].x + 0.08, vectors[ 0 ].y - 0.31, vectors[ 0 ].z + 0.94 );
} else if ( kind === 'head-depth-inverted' ) {
const center = midpoint( pose, LM.LEFT_EAR, LM.RIGHT_EAR, vectors[ 0 ] );
getJoint( pose, LM.NOSE, vectors[ 1 ] );
vectors[ 1 ].sub( center ).negate().add( center );
setJoint( pose, LM.NOSE, vectors[ 1 ].x, vectors[ 1 ].y, vectors[ 1 ].z );
}
return pose;
}
function knownVisibility( controller, kind ) {
const { retargeter, constants: { LM } } = inspection( controller );
const visibility = Float32Array.from( retargeter.restVis );
if ( kind !== 'upper-body-only' ) return visibility;
visibility.fill( 0.05 );
for ( const joint of [
LM.NOSE,
LM.LEFT_EAR, LM.RIGHT_EAR,
LM.LEFT_SHOULDER, LM.RIGHT_SHOULDER,
LM.LEFT_ELBOW, LM.RIGHT_ELBOW,
LM.LEFT_WRIST, LM.RIGHT_WRIST,
LM.LEFT_INDEX, LM.RIGHT_INDEX,
] ) visibility[ joint ] = 1;
return visibility;
}
function createSyntheticPacket( controller, stagePose, visibility = null, leftHand = null, rightHand = null ) {
const { params, constants: { packetLayout } } = inspection( controller );
const {
PKT_SIZE, PKT_HAS_POSE, PKT_HAS_LEFT, PKT_HAS_RIGHT,
PKT_POSE_NORM, PKT_POSE_WORLD, PKT_LEFT_HAND, PKT_RIGHT_HAND,
} = packetLayout;
const packet = new Float32Array( PKT_SIZE );
packet[ PKT_HAS_POSE ] = 1;
packet[ PKT_HAS_LEFT ] = leftHand ? 1 : 0;
packet[ PKT_HAS_RIGHT ] = rightHand ? 1 : 0;
const mirror = params.mirror ? - 1 : 1;
for ( let index = 0; index < 33; index ++ ) {
const x = stagePose[ index * 3 ];
const y = stagePose[ index * 3 + 1 ];
const z = stagePose[ index * 3 + 2 ];
const confidence = visibility?.[ index ] ?? 1;
const normalizedX = THREE.MathUtils.clamp( 0.5 - x * 0.7, 0.02, 0.98 );
const normalizedY = THREE.MathUtils.clamp( 0.55 - ( y - 0.9 ) * 0.45, 0.02, 0.98 );
packet.set( [ normalizedX, normalizedY, 0, confidence ], PKT_POSE_NORM + index * 4 );
packet.set( [ x / mirror, - y, - z, confidence ], PKT_POSE_WORLD + index * 4 );
}
const encodeHand = ( hand, offset ) => {
if ( ! hand ) return;
for ( let index = 0; index < 21; index ++ ) {
packet[ offset + index * 3 ] = hand[ index * 3 ] / mirror;
packet[ offset + index * 3 + 1 ] = - hand[ index * 3 + 1 ];
packet[ offset + index * 3 + 2 ] = - hand[ index * 3 + 2 ];
}
};
encodeHand( leftHand, PKT_LEFT_HAND );
encodeHand( rightHand, PKT_RIGHT_HAND );
return packet;
}
function createKnownPacket( controller, kind ) {
return createSyntheticPacket(
controller,
knownPose( controller, kind ),
knownVisibility( controller, kind )
);
}
function ingestKnownPose( controller, kind ) {
const packet = createKnownPacket( controller, kind );
controller.configure( { mode: 'Your Body' } );
controller.ingestTrackingPacket( packet, 4 / 3 );
return Array.from( packet );
}
function runRetargetKnownAnswers( controller ) {
const context = inspection( controller );
const { retargeter, mixer, params, classes: { BodyRig }, constants: { LM } } = context;
if ( ! retargeter || ! mixer ) throw new Error( 'Michelle is not ready.' );
const savedMode = params.mode;
const boneState = [ ...retargeter.bones.values() ].map( ( bone ) => ( {
bone,
position: bone.position.clone(),
quaternion: bone.quaternion.clone(),
} ) );
const twistState = retargeter.entries.map( ( entry ) => entry.filteredTwist );
const runPose = ( pose, visibility = retargeter.restVis ) => {
const testRig = new BodyRig();
params.mode = 'Your Body';
const packet = createSyntheticPacket( controller, pose, visibility );
for ( let index = 0; index < 60; index ++ ) {
testRig.ingest( packet, 4 / 3, 1 / 30 );
testRig.update( 1 / 30 );
}
retargeter.apply( testRig, 1 / 60, 1 );
return testRig;
};
let maxRestDegrees = 0;
const boneErrors = {};
const tPoseRig = runPose( knownPose( controller, 'tpose' ) );
for ( const entry of retargeter.entries ) {
const dotValue = Math.min( 1, Math.abs( entry.bone.quaternion.dot( entry.restLocalQuaternion ) ) );
const degrees = THREE.MathUtils.radToDeg( 2 * Math.acos( dotValue ) );
const restTargetDirection = retargeter.stageVectorToActor( entry.aim( tPoseRig.displayPose, new THREE.Vector3() ) );
const directionDegrees = THREE.MathUtils.radToDeg( entry.restDirection.angleTo( restTargetDirection ) );
const actualRestDirection = entry.child.getWorldPosition( new THREE.Vector3() )
.sub( entry.bone.getWorldPosition( new THREE.Vector3() ) ).normalize();
boneErrors[ entry.name ] = {
localDegrees: degrees,
inputDirectionDegrees: directionDegrees,
worldDirectionDegrees: THREE.MathUtils.radToDeg( entry.restDirection.angleTo( actualRestDirection ) ),
};
maxRestDegrees = Math.max( maxRestDegrees, degrees );
}
const raisedRig = runPose( knownPose( controller, 'right-arm-raise' ) );
const arm = retargeter.bones.get( 'RightArm' );
const forearm = retargeter.bones.get( 'RightForeArm' );
const actualDirection = forearm.getWorldPosition( vectors[ 0 ] ).sub( arm.getWorldPosition( vectors[ 1 ] ) ).normalize();
const targetDirection = retargeter.stageVectorToActor(
poseDirection( raisedRig.displayPose, LM.RIGHT_SHOULDER, LM.RIGHT_ELBOW, vectors[ 2 ] )
);
const rightArmDegrees = THREE.MathUtils.radToDeg( actualDirection.angleTo( targetDirection ) );
runPose( knownPose( controller, 'head-depth-inverted' ) );
const headEntry = retargeter.entries.find( ( entry ) => entry.name === 'Head' );
const headWorldQuaternion = headEntry.bone.getWorldQuaternion( new THREE.Quaternion() );
const headRestDelta = headWorldQuaternion.multiply( headEntry.restWorldQuaternion.clone().invert() );
const headFacing = headEntry.restHint.clone().applyQuaternion( headRestDelta ).normalize();
const headFacingDot = headFacing.dot( headEntry.restHint );
const upperBodyRig = runPose(
knownPose( controller, 'upper-body-only' ),
knownVisibility( controller, 'upper-body-only' )
);
const upperBodyPelvisY = upperBodyRig.getPelvis( new THREE.Vector3() ).y;
const upperBodyWristY = Math.max(
upperBodyRig.displayPose[ LM.LEFT_WRIST * 3 + 1 ],
upperBodyRig.displayPose[ LM.RIGHT_WRIST * 3 + 1 ]
);
const upperBodyFraming = {
weight: upperBodyRig.upperBodyOnlyWeight,
pelvisY: upperBodyPelvisY,
highestWristY: upperBodyWristY,
pass: upperBodyRig.upperBodyOnlyWeight >= 0.9
&& upperBodyPelvisY >= 0.43
&& upperBodyPelvisY <= 0.58
&& upperBodyWristY >= 0.5
&& upperBodyWristY <= 1.15,
};
const mirrorInvariant = tPoseRig.displayPose[ LM.LEFT_SHOULDER * 3 ] < tPoseRig.displayPose[ LM.RIGHT_SHOULDER * 3 ];
const groundedY = Math.min(
tPoseRig.displayPose[ LM.LEFT_HEEL * 3 + 1 ],
tPoseRig.displayPose[ LM.RIGHT_HEEL * 3 + 1 ],
tPoseRig.displayPose[ LM.LEFT_ANKLE * 3 + 1 ],
tPoseRig.displayPose[ LM.RIGHT_ANKLE * 3 + 1 ]
);
for ( const state of boneState ) {
state.bone.position.copy( state.position );
state.bone.quaternion.copy( state.quaternion );
}
retargeter.entries.forEach( ( entry, index ) => {
entry.filteredTwist = twistState[ index ];
} );
retargeter.root.updateMatrixWorld( true );
params.mode = savedMode;
return {
tPoseMaxDegrees: maxRestDegrees,
boneErrors,
rightArmDegrees,
headFacingDot,
upperBodyFraming,
mirrorInvariant,
groundedY,
pass: maxRestDegrees <= 3
&& rightArmDegrees <= 5
&& headFacingDot >= 0.8
&& upperBodyFraming.pass
&& mirrorInvariant
&& Math.abs( groundedY - 0.042 ) <= 0.06,
};
}
async function readField( renderer, sdfBuilder ) {
return new Float32Array( await renderer.getArrayBufferAsync( sdfBuilder.resolvedField.value ) );
}
async function readSolverDiagnostics( controller ) {
const { renderer, solverDiagnostics } = inspection( controller );
if ( ! solverDiagnostics ) return null;
const values = new Uint32Array( await renderer.getArrayBufferAsync( solverDiagnostics.value ) );
const view = new DataView( new ArrayBuffer( 4 ) );
view.setUint32( 0, values[ 2 ], true );
const maxSpeedSquared = view.getFloat32( 0, true );
return {
interiorCount: values[ 0 ],
fastBallCount: values[ 1 ],
maxSpeed: Math.sqrt( Math.max( 0, maxSpeedSquared ) ),
};
}
async function sampleSDF( controller, points ) {
const { renderer, sdfBuilder } = inspection( controller );
if ( ! sdfBuilder ) return [];
const field = await readField( renderer, sdfBuilder );
return points.map( ( pointValue ) => {
const point = vectors[ 0 ].fromArray( pointValue );
const uvw = point.applyMatrix4( sdfBuilder.worldToSdfMatrix );
const x = THREE.MathUtils.clamp( Math.floor( uvw.x * sdfBuilder.resolution ), 0, sdfBuilder.resolution - 1 );
const y = THREE.MathUtils.clamp( Math.floor( uvw.y * sdfBuilder.resolution ), 0, sdfBuilder.resolution - 1 );
const z = THREE.MathUtils.clamp( Math.floor( uvw.z * sdfBuilder.resolution ), 0, sdfBuilder.resolution - 1 );
const pointer = ( x + y * sdfBuilder.resolution + z * sdfBuilder.resolution ** 2 ) * 4;
return Array.from( field.subarray( pointer, pointer + 4 ) );
} );
}
async function readSDFStats( controller ) {
const { renderer, sdfBuilder, constants: { SDF_FAR } } = inspection( controller );
if ( ! sdfBuilder ) return null;
const [ field, propagatedBuffer, velocityBuffer ] = await Promise.all( [
readField( renderer, sdfBuilder ),
renderer.getArrayBufferAsync( sdfBuilder.finalField.value ),
renderer.getArrayBufferAsync( sdfBuilder.velocityBuffer.value ),
] );
const propagated = new Float32Array( propagatedBuffer );
const velocities = new Float32Array( velocityBuffer );
const indices = sdfBuilder.geometry.index.array;
let negativeVoxelCount = 0;
let seededVoxelCount = 0;
let maxSurfaceSpeed = 0;
let maxReferencedVertexSpeed = 0;
const referencedTriangles = new Set();
let minimumDistance = Infinity;
for ( let pointer = 0; pointer < field.length; pointer += 4 ) {
const speed = Math.hypot( field[ pointer ], field[ pointer + 1 ], field[ pointer + 2 ] );
const signedDistance = field[ pointer + 3 ];
if ( signedDistance < 0 ) negativeVoxelCount ++;
if ( Math.abs( signedDistance ) < sdfBuilder.band * 1.05 ) seededVoxelCount ++;
maxSurfaceSpeed = Math.max( maxSurfaceSpeed, speed );
minimumDistance = Math.min( minimumDistance, signedDistance );
const voxel = pointer / 4;
if ( propagated[ voxel * 2 ] < SDF_FAR * 0.99 ) {
const triangle = Math.round( propagated[ voxel * 2 + 1 ] );
if ( triangle >= 0 && triangle < sdfBuilder.triangleCount ) {
referencedTriangles.add( triangle );
for ( let corner = 0; corner < 3; corner ++ ) {
const vertexPointer = indices[ triangle * 3 + corner ] * 4;
maxReferencedVertexSpeed = Math.max( maxReferencedVertexSpeed, Math.hypot(
velocities[ vertexPointer ],
velocities[ vertexPointer + 1 ],
velocities[ vertexPointer + 2 ]
) );
}
}
}
}
return {
negativeVoxelCount,
seededVoxelCount,
maxSurfaceSpeed,
maxReferencedVertexSpeed,
referencedTriangleCount: referencedTriangles.size,
minimumDistance,
};
}
async function readSkinStats( controller ) {
const { renderer, sdfBuilder } = inspection( controller );
if ( ! sdfBuilder ) return null;
const [ positions, velocities ] = await Promise.all( [
renderer.getArrayBufferAsync( sdfBuilder.positionBuffer.value ),
renderer.getArrayBufferAsync( sdfBuilder.velocityBuffer.value ),
] );
const positionValues = new Float32Array( positions );
const velocityValues = new Float32Array( velocities );
const minimum = [ Infinity, Infinity, Infinity ];
const maximum = [ - Infinity, - Infinity, - Infinity ];
let checksum = 0;
let maxSpeed = 0;
for ( let pointer = 0; pointer < positionValues.length; pointer += 4 ) {
for ( let axis = 0; axis < 3; axis ++ ) {
const value = positionValues[ pointer + axis ];
minimum[ axis ] = Math.min( minimum[ axis ], value );
maximum[ axis ] = Math.max( maximum[ axis ], value );
checksum += value * ( axis + 1 );
}
maxSpeed = Math.max( maxSpeed, Math.hypot(
velocityValues[ pointer ],
velocityValues[ pointer + 1 ],
velocityValues[ pointer + 2 ]
) );
}
return { minimum, maximum, checksum, maxSpeed };
}
async function readBallMirror( controller ) {
const { renderer, ballMirror } = inspection( controller );
if ( ! ballMirror ) return [];
return Array.from( new Float32Array( await renderer.getArrayBufferAsync( ballMirror.value ) ) );
}
async function probeInteriorBalls( controller ) {
const { renderer, sdfBuilder, ballMirror, solver, constants: { BALL_RADIUS } } = inspection( controller );
if ( ! sdfBuilder || ! ballMirror || ! solver ) return null;
const [ field, mirrorBuffer ] = await Promise.all( [
readField( renderer, sdfBuilder ),
renderer.getArrayBufferAsync( ballMirror.value ),
] );
const balls = new Float32Array( mirrorBuffer );
let count = 0;
let minimumDistance = Infinity;
for ( let index = 0; index < solver.particleCount; index ++ ) {
const pointer = index * 4;
const uvw = vectors[ 0 ].set( balls[ pointer ], balls[ pointer + 1 ], balls[ pointer + 2 ] )
.applyMatrix4( sdfBuilder.worldToSdfMatrix );
if ( uvw.x < 0 || uvw.x > 1 || uvw.y < 0 || uvw.y > 1 || uvw.z < 0 || uvw.z > 1 ) continue;
const x = THREE.MathUtils.clamp( Math.floor( uvw.x * sdfBuilder.resolution ), 0, sdfBuilder.resolution - 1 );
const y = THREE.MathUtils.clamp( Math.floor( uvw.y * sdfBuilder.resolution ), 0, sdfBuilder.resolution - 1 );
const z = THREE.MathUtils.clamp( Math.floor( uvw.z * sdfBuilder.resolution ), 0, sdfBuilder.resolution - 1 );
const signedDistance = field[ ( x + y * sdfBuilder.resolution + z * sdfBuilder.resolution ** 2 ) * 4 + 3 ];
minimumDistance = Math.min( minimumDistance, signedDistance );
if ( signedDistance < - BALL_RADIUS * 0.2 ) count ++;
}
return { count, minimumDistance };
}
async function runSDFSignProbes( controller ) {
const { retargeter, sdfBuilder } = inspection( controller );
if ( ! retargeter || ! sdfBuilder ) return null;
const bonePoint = ( name ) => retargeter.bones.get( name ).getWorldPosition( new THREE.Vector3() );
const inside = [
[ 'hips', bonePoint( 'Hips' ) ],
[ 'lower-spine', bonePoint( 'Spine1' ) ],
[ 'upper-spine', bonePoint( 'Spine2' ) ],
[ 'neck', bonePoint( 'Neck' ) ],
[ 'left-thigh', bonePoint( 'LeftUpLeg' ).lerp( bonePoint( 'LeftLeg' ), 0.35 ) ],
[ 'right-thigh', bonePoint( 'RightUpLeg' ).lerp( bonePoint( 'RightLeg' ), 0.35 ) ],
];
const outside = [
[ 'hips-front', bonePoint( 'Hips' ).add( new THREE.Vector3( 0, 0, 0.5 ) ) ],
[ 'spine-right', bonePoint( 'Spine2' ).add( new THREE.Vector3( 0.48, 0, 0 ) ) ],
[ 'head-above', bonePoint( 'Head' ).add( new THREE.Vector3( 0, 0.36, 0 ) ) ],
[ 'left-arm-front', bonePoint( 'LeftArm' ).add( new THREE.Vector3( 0, 0, 0.28 ) ) ],
[ 'left-leg-side', bonePoint( 'LeftLeg' ).add( new THREE.Vector3( - 0.36, 0, 0 ) ) ],
[ 'right-leg-side', bonePoint( 'RightLeg' ).add( new THREE.Vector3( 0.36, 0, 0 ) ) ],
];
const definitions = [
...inside.map( ( [ label, point ] ) => ( { label, expected: 'inside', point: point.toArray() } ) ),
...outside.map( ( [ label, point ] ) => ( { label, expected: 'outside', point: point.toArray() } ) ),
];
const samples = await sampleSDF( controller, definitions.map( ( probe ) => probe.point ) );
const probes = definitions.map( ( probe, index ) => ( {
...probe,
sample: samples[ index ],
pass: probe.expected === 'inside' ? samples[ index ][ 3 ] < 0 : samples[ index ][ 3 ] > 0,
} ) );
return { probes, pass: probes.every( ( probe ) => probe.pass ) };
}
async function runIcosphereSDFFixture( controller ) {
const {
renderer,
classes: { SkinnedMeshSDF },
constants: { SDF_DOMAIN_SIZE },
} = inspection( controller );
const resolution = 32;
const radius = 0.45;
const center = new THREE.Vector3( 0, SDF_DOMAIN_SIZE.y * 0.5, 0 );
const geometry = mergeVertices( new THREE.IcosahedronGeometry( radius, 3 ) );
const vertexCount = geometry.getAttribute( 'position' ).count;
const triangleCount = geometry.index.count / 3;
const skinIndices = new Uint16Array( vertexCount * 4 );
const skinWeights = new Float32Array( vertexCount * 4 );
for ( let index = 0; index < vertexCount; index ++ ) skinWeights[ index * 4 ] = 1;
geometry.setAttribute( 'skinIndex', new THREE.Uint16BufferAttribute( skinIndices, 4 ) );
geometry.setAttribute( 'skinWeight', new THREE.Float32BufferAttribute( skinWeights, 4 ) );
const bone = new THREE.Bone();
const skeleton = new THREE.Skeleton( [ bone ] );
const material = new THREE.MeshBasicMaterial();
const mesh = new THREE.SkinnedMesh( geometry, material );
mesh.add( bone );
mesh.position.copy( center );
mesh.updateMatrixWorld( true );
mesh.bind( skeleton );
skeleton.update();
const fixture = new SkinnedMeshSDF( mesh, { resolution, domain: SDF_DOMAIN_SIZE } );
fixture.update( 1 / 60, center );
fixture.dispatch( renderer );
await renderer.backend.device.queue.onSubmittedWorkDone();
const field = await readField( renderer, fixture );
const errors = [];
let signMismatches = 0;
let samples = 0;
const voxelStep = fixture.voxelStep;
const shell = 1;
for ( let z = shell; z < resolution - shell; z ++ ) {
for ( let y = shell; y < resolution - shell; y ++ ) {
for ( let x = shell; x < resolution - shell; x ++ ) {
const worldX = ( ( x + 0.5 ) / resolution - 0.5 ) * SDF_DOMAIN_SIZE.x;
const worldY = ( y + 0.5 ) / resolution * SDF_DOMAIN_SIZE.y;
const worldZ = ( ( z + 0.5 ) / resolution - 0.5 ) * SDF_DOMAIN_SIZE.z;
const analytic = Math.hypot( worldX, worldY - center.y, worldZ ) - radius;
if ( Math.abs( analytic ) > fixture.band * 0.8 ) continue;
const pointer = x + y * resolution + z * resolution * resolution;
const sampled = field[ pointer * 4 + 3 ];
const error = Math.abs( sampled - analytic );
errors.push( error );
samples ++;
if ( Math.abs( analytic ) > voxelStep * 0.15 && Math.sign( sampled ) !== Math.sign( analytic ) ) signMismatches ++;
}
}
}
const maxError = errors.length > 0 ? Math.max( ...errors ) : Infinity;
const rmsError = errors.length > 0
? Math.sqrt( errors.reduce( ( total, value ) => total + value * value, 0 ) / errors.length )
: Infinity;
fixture.dispose();
geometry.dispose();
material.dispose();
skeleton.dispose();
return {
resolution,
vertices: vertexCount,
triangles: triangleCount,
samples,
signMismatches,
voxelStep,
maxError,
maxErrorVoxels: maxError / voxelStep,
rmsError,
rmsErrorVoxels: rmsError / voxelStep,
pass: samples > 100 && signMismatches === 0 && maxError <= voxelStep * 0.5,
};
}
function getComputeWGSL( controller, passName ) {
const { renderer, sdfBuilder, solver } = inspection( controller );
const passNode = sdfBuilder?.passes.find( ( pass ) => pass.name === passName )
?? solver?.lastSubmittedBatch?.find( ( pass ) => pass.name === passName )
?? solver?.passes?.find( ( pass ) => pass.name === passName );
if ( ! passNode ) return null;
const builder = renderer.backend.createNodeBuilder( passNode, renderer );
builder.build();
return builder.computeShader;
}
async function waitForGPU( controller ) {
const { renderer } = inspection( controller );
await renderer.backend.device.queue.onSubmittedWorkDone();
}
async function prepareCapture( controller ) {
controller.pause();
controller.render();
await waitForGPU( controller );
}
async function stabilize( controller, targetFrame = 30 ) {
const desiredFrame = Math.max( 0, Math.floor( Number( targetFrame ) ) );
while ( controller.getDiagnostics().frame < desiredFrame && ! controller.getDiagnostics().paused ) {
await new Promise( ( resolve ) => requestAnimationFrame( resolve ) );
}
const remaining = desiredFrame - controller.getDiagnostics().frame;
if ( remaining > 0 ) await controller.step( remaining );
await prepareCapture( controller );
}
export function createSDFBodyTrackingBridge( controller ) {
const { packetLayout } = inspection( controller ).constants;
return {
packetLayout,
getState: controller.getDiagnostics,
getPerformance: controller.getPerformance,
getJoints: controller.getTrackingPose,
getBoneRest: controller.getBoneRest,
getBoneWorld: controller.getBonePose,
ingestPacket: controller.ingestTrackingPacket,
ingestKnownPose: ( kind ) => ingestKnownPose( controller, kind ),
createKnownPacket: ( kind ) => Array.from( createKnownPacket( controller, kind ) ),
runKnownAnswers: () => runRetargetKnownAnswers( controller ),
readDiagnostics: () => readSolverDiagnostics( controller ),
sampleSDF: ( points ) => sampleSDF( controller, points ),
readSDFStats: () => readSDFStats( controller ),
readSkinStats: () => readSkinStats( controller ),
readBallMirror: () => readBallMirror( controller ),
probeInteriorBalls: () => probeInteriorBalls( controller ),
runSDFSignProbes: () => runSDFSignProbes( controller ),
runIcosphereSDFFixture: () => runIcosphereSDFFixture( controller ),
getComputeWGSL: ( passName ) => getComputeWGSL( controller, passName ),
waitForGPU: () => waitForGPU( controller ),
prepareCapture: () => prepareCapture( controller ),
stabilize: ( frame ) => stabilize( controller, frame ),
setState: ( state = {} ) => controller.configure( {
...state,
startTracking: state.startCamera === true || state.startTracking === true,
} ),
};
}