Three Blocks

A live signed-distance field from a skinned mesh

SkinnedMeshSDF rebuilds a distance and surface-velocity field from the posed triangles of a Three.js SkinnedMesh. A clip, a tracking system or your own code can drive the bones. In Ball pit, thousands of particles query the same field to follow the moving silhouette.

Build and update the field

Use a loaded skinned mesh with a bound skeleton. This helper belongs in the scene that already owns the renderer and animation or tracking updates.

import type { SkinnedMesh, Vector3, WebGPURenderer } from "three/webgpu";
import { SkinnedMeshSDF } from "three-blocks/sdf-raymarching";

export function trackSurface(mesh: SkinnedMesh, renderer: WebGPURenderer) {
  const field = new SkinnedMeshSDF(mesh, { resolution: 64 });
  return {
    field,
    rebuild(seconds: number, center: Vector3) {
      mesh.updateWorldMatrix(true, true);
      field.update(seconds, center);
      field.dispatch(renderer);
    },
    dispose: () => field.dispose(),
  };
}

Update the skeleton first, call rebuild with the field center in world space, and dispatch the consumer afterwards. distance, gradient and surfaceVelocity return TSL nodes for use inside a GPU graph. They do not synchronously return samples to JavaScript.

Why this exists

Body-driven interaction usually reaches for one of two compromises:

  1. Primitive proxies — spheres/capsules attached to joints. Cheap, stable, immediate, and for a great many experiences completely sufficient: the Waves of Connection installation shipped exactly this (ten spheres per visitor). But the collider is a generalization of the body: no hands, no clothing silhouette, and every consumer needs its own proxy rig.
  2. Baked SDFs through a BVH — accurate, but built for static meshes. For a deforming body you pay a CPU skin + BVH refit every frame, on the wrong thread.

SkinnedMeshSDF removes the compromise: the field is rebuilt from the actual skinned triangles each frame, so whatever the skeleton does — a samba clip, a MediaPipe stream, a Kinect rig — the field is the body, down to the mesh's real silhouette. And because the field also stores per-voxel surface velocity, consumers don't just know where the body is; they know how it is moving. A heel and a swinging hand push particles differently. That is the kick.

Which tier is correct is a product question, not a ranking. Proxies are the right answer whenever the body is an input to the experience; the field is the right answer when the body's shape is the experience. See Proxy bodies versus full-surface fields for the public version of that decision.

The provider seam: the skeleton is the interface

The block deliberately has no tracking API. It reads skeleton.boneMatrices — the standard three.js skinning contract — so the "provider abstraction" costs zero code and zero configuration:

ProviderHow it plugs in
AnimationMixerplay a clip; the skeleton is already posed
MediaPipe (the showcase)landmarks → filtered joints → retargeted bone quaternions
Kinect / depth sensorsjoint orientations → bone quaternions
WebXR hands / VRM mocapjoint transforms → bones

The showcase's tracking stack (parallel pose∥hands workers, One-Euro filters, critically-damped springs, shortest-arc retargeting) lives in example land on purpose: it is one provider among many, and its 17–31 MB of vendored models have no business inside a rendering library. Lose the camera and the AnimationMixer takes the same skeleton back — the field never knows.

Tracking, filtering, calibration, and retargeting are provider concerns. None of them are, or will become, SDF responsibilities.

The pipeline: nine named stages, fourteen passes, zero CPU

Everything below runs in one renderer.compute( bodySDF.passes ) batch. The mesh in the numbers is Michelle, the classic three.js Mixamo character: 16,340 vertices, 28,106 triangles, 65 bones, at 64³ over a 2.6 × 2.4 × 2.6 m domain (3.75–4.06 cm voxels).

getPassNames() returns the dispatch order, and it is what a GPU profiler shows:

#PassDispatchWhat it does
1sdfBody_skin16,340 threadsApplies bone matrices to every vertex (the same math as the vertex shader, in compute). Finite-difference surface velocity against the previous frame, clamped to maxSurfaceSpeed.
2sdfBody_normalsClear16,340 threadsZeroes the fixed-point pseudonormal accumulator (three i32 per vertex).
3sdfBody_normalsAccumulate28,106 threadsPer triangle: atomicAdd its unit normal into each corner, weighted by that corner's interior angle — the Bærentzen–Aanæs angle-weighted pseudonormal, at 2²⁰ fixed point. Contributions land on a welded vertex index, so glTF's UV/normal seam splits don't split the fan.
4sdfBody_normalsResolve16,340 threadsNormalizes each accumulator into a per-vertex pseudonormal for this frame's pose.
5sdfBody_clear64³Resets the atomic seed grid to the sentinel.
6sdfBody_splat28,106 threadsPer triangle: compute the skinned AABB inflated by the band (bandVoxels × the shortest voxel edge, 1.5 by default), and for each candidate voxel run an exact point-to-triangle distance (hardened iq formula — degenerate triangles from collapsed skin weights return a stable vertex instead of NaN). Pack (quantized distance ≪ 16) | triangle id into a u32 and atomicMin it — nearest triangle wins, no sorting, no prefix sums.
7sdfBody_seedResolve64³Unpacks the winning seed, recomputes the exact distance, and decides the sign — the only pass that ever does. Encodes the verdict as ±(triangle + 1); zero means unseeded.
8sdfBody_propagate_0…56 × 64³Ping-pong distance propagation: each voxel takes min(neighbour + axis step) over its 6-neighbourhood, carrying the seeding triangle and its sign along. Six passes reach six cells — about 23 cm at the default grid, on top of the band.
9sdfBody_resolve64³Exact distance to the carried triangle, signed by the transported verdict; interpolate that triangle's vertex velocities barycentrically; write rgba16float = (surface velocity.xyz, signed distance.w). Every cell resolves, the outermost layer included.

Four details carry the whole design:

  • The atomic trick. WebGPU atomics are 32-bit. Quantizing the distance to 16 bits over the band range only (not world meters) keeps millimeter precision, and the low 16 bits ride along with the triangle id — so one atomicMin resolves both "how far" and "from which triangle" race-free. (Corollary: meshes are capped at 65,535 triangles; the constructor enforces it.)
  • The sign is decided once and transported. A half-space test (dot(point − closest, normal)) is only trustworthy in the band, where the seed race guarantees the winning triangle really is the nearest surface. Deciding it again at propagation range leaks on every concavity. So seedResolve decides it in-band and encodes it in the sign bit of the carried triangle id; propagation moves the verdict outward with the distance; resolve reads it back. The referee is feature-aware, per Bærentzen–Aanæs: with the closest point in the face interior the face plane is exact, and a smooth interpolated normal can tilt past it on thin fins and folded elbows; on edges and vertices the winning face is an arbitrary member of a shared fan, so the angle-weighted pseudonormal referees instead. A grazing verdict (cosine below 0.12) reads as outside — past the rim of an open shell, "behind" is a coin flip that propagation would paint into a rod of phantom interior.
  • The hop cost is per axis. Propagation bills a step at the true edge length of the axis it walks (voxelSize.x/y/z), not one shared minimum. A uniform step underestimates hops on the longer axes, which lets a chain from a near-zero seed — a cell inside a thin sole or cuff sandwich — outrun the honest outside seeds and paint a rod along that axis.
  • The r185 dodge. Every read/write stage uses flat storage buffers; the 3D texture is write-only in resolve and sampled everywhere else. This sidesteps the r185 3D-storage-read TSL bug entirely and gets free trilinear filtering at query time.

Measured effect of the sign work (2026-08-16, Michelle, film freeze-2 pose)

BeforeAfter
False-inside cells99 (12% of shown), 91 of them propagated8, zero propagated
Sole/cuff rod leaks (per-axis hop fix)310
Unreached boundary cells (feet on a floor-seated domain)40

In this historical sample, sub-voxel thin features (Michelle's fin blades are ~1 cm against 3.75 cm voxels) cannot own a cell centre at 64³. That is resolution physics. Raise resolution if the feature is the point.

Using it in a real simulation

Use collide() in a solver's existing particle-force hook. This function returns the callback expected by MPMSolver. Supply the field from trackSurface, the transform from normalized particle position to the world, and the world-space edge length of one simulation cell. This version assumes matching cell dimensions along the three axes, as in the ball pit.

import { Matrix4 } from "three/webgpu";
import { uniform, vec4 } from "three/tsl";
import type { MPMSolverOptions } from "three-blocks/mpm";
import type { SkinnedMeshSDF } from "three-blocks/sdf-raymarching";

export function makeBodyContact(field: SkinnedMeshSDF, domainToWorld: Matrix4, cellSize: number): NonNullable<MPMSolverOptions["particleForce"]> {
  const transform = uniform(domainToWorld, "mat4");
  return ({ position, velocity }) => {
    const worldPosition = transform.mul(vec4(position, 1)).xyz;
    const next = field.collide({ position: worldPosition, velocity: velocity.mul(cellSize),
      radius: 0.041, friction: 0.3, restitution: 0.18 });
    velocity.assign(next.div(cellSize));
  };
}

Pass the result as the particleForce option when constructing the solver, seed the solver, then call its step after the field dispatch in each frame. The complete example source includes the real pit dimensions, seeding, tracked skeleton and draw.

What collide() does, in order: bail unless the position is inside the domain; one field sample; bail unless distance < radius; four guarded taps → tetrahedral gradient → contact normal, blended toward a domain-radial escape direction for deep penetrations (open meshes — sleeves, cuffs, soles — can pocket a particle where neighboring seed normals disagree); decompose the velocity relative to the surface's own motion; damp the tangential part by friction; reflect the approach part by restitution; add a push-out capped by maxPushOutSpeed. Because the response is relative to the field's per-voxel surface velocity, a standing leg and a kicking leg produce different impulses with the same five lines.

OptionDefaultMeaning
radius0particle radius; response triggers below it
friction0.2tangential fraction removed on contact
restitution0approach fraction reflected on contact
pushOutRate96 /sseparation speed per meter of penetration
maxPushOutSpeed12 m/spush-out cap
deepEscape0.7max blend toward the radial escape normal; 0 = raw gradient

Every option takes a number or a float node, so GUI-driven uniforms plug in directly. For a non-MPM particle system the recipe is the same minus the unit conversions: keep everything in world space and assign the returned velocity.

The consumer contract

One texture, one matrix, four sampling helpers plus the response:

  • bodySDF.texture — rgba16float Storage3DTexture, linear filtered, clamped: (surfaceVelocity.xyz, signedDistance.w).
  • bodySDF.uniforms.worldToSdf / .sdfToWorld — the domain mapping, updated when the field follows the subject.
  • sample / distance / gradient / surfaceVelocity — TSL helpers for materials, particles, and simulation hooks.

Out-of-domain semantics live in the samplers, not in a sacrificed shell. The texture holds real data all the way into its outermost texels, so a body touching a domain face — feet on a floor-seated domain — keeps its boundary layer and stays collidable. Every owned read path routes through a domain-guarded sample that returns far empty space outside the box, and the gradient's taps are guarded individually, so a tap crossing a face still pushes back into the domain. A consumer that binds bodySDF.texture directly owns that guard itself: box-clip the ray or clamp the coordinates, because a clamped read past a face repeats that face's data.

Everything speaks this contract already:

  • MLS-MPM (three-blocks/mpm): the showcase's ball pit particleForce is bodySDF.collide() plus two unit conversions — the full worked integration above.
  • SmokeVolume: the texture is SDFGridBoundary-compatible — dust puffs on impact are a config change, not an integration.
  • Rendering: RayMarchSDFNodeMaterial, the SDF slice/volume materials, or any custom TSL that can sample a 3D texture.
  • The skin pass is a bonus API: positionBuffer / velocityBuffer hold the skinned world-space vertices and velocities as storage — emit particles from the tracked body's surface without touching the SDF at all.

Interpreting the timing measurements

An August 2026 measurement on an Apple M5 Max used Michelle (16,340 vertices, 28,106 triangles and 65 bones), a 64³ field over 2.6 × 2.4 × 2.6 m, bandVoxels 1.5 and six propagation passes. After eight warm-up rebuilds, 61 GPU timestamp samples gave a median isolated rebuild of 0.149 ms. The measured setup used Three.js r185. These numbers describe that mesh, field and device. They measure the field separately from the particle simulation and final image.

To reproduce a comparison in your scene, hold the pose and domain fixed, warm the compute pipeline, then collect GPU samples while changing one resolution. For an accuracy check, compare the sign and distance at known inside/outside points and look specifically at thin cuffs, fingers or soles. A 96³ field has 3.375 times as many cells as a 64³ field. Tight bounds can improve the physical size represented by each voxel before you pay that higher cost.

Compare a posed mesh BVH

three-mesh-bvh is excellent — and already in this package (ComputeSDFGenerator bakes static SDFs through it). For a deforming mesh queried millions of times per frame, the trade inverts. Measured head to head in one session, one GPU, the same skinned Michelle at the same 64³, with the same timestamp queries (2026-08-21, Apple M5 Max, three-mesh-bvh@0.9.14 BVHComputeData + closestPointToPoint, 31 rounds each → the same recorded BVH comparison):

BVH refit pathSkinnedMeshSDF
One-time build30.9 ms (BVHComputeData.update())— (graph built at construction, no GPU work)
Per-frame build22.4 ms CPU refit + re-upload, main thread (median, 21.8–24.5, n = 31)0.21 ms GPU whole bake (median, 0.148–1.85, n = 31)
Filling the same 262,144 cells3.17 ms GPU sweep (median, 3.05–3.28, n = 31)included in the 0.21 ms above
Per querytree traversalone trilinear texture fetch
12M queries/frameprohibitive~free (it's a texture read)
Exactnessexact everywhereexact in the band, propagated beyond (where sub-voxel exactness stops mattering)
Surface velocitynot modeledper-voxel, barycentric

Method caveats, stated because the comparison is deliberately generous to them: their query writes only a distance (ours also carries sign, seeding triangle, and surface velocity), and their update() is timed on its own so the row can be read either way. Their sweep is one traversal per cell — the closest thing to a like-for-like "fill the grid" — not their intended usage pattern, which is sparse exact queries, and at that they are excellent. The 0.21 ms bake in this table is the same-session figure with the BVH's storage also resident and a shorter warm-up; the clean isolated figure is the 0.149 ms above. Quote whichever the sentence needs, never one number under the other's method. A traversal sanity check runs with it: 2,015 cells within one voxel of the skin, 0 misses, max distance 1.84 m — proof the traversal really ran.

The field build is amortized over every query — that is the whole argument. The BVH path survives as the offline correctness fixture: the T-pose field is cross-checked against it in tests. Same story for flood-fill signing (fillInterior): correct, but ~20× the passes; pseudonormal sign + local propagation is exact where particles live.

And the v1 lesson worth keeping: at 48 analytic capsules, raymarching the capsules directly beat any baked field for rendering. Physics flipped the verdict because queries outnumber pixels. Measure per consumer; the crossover is real on both sides.

Using it outside body tracking

Nothing in the block knows about bodies:

  • Any Mixamo/VRM character with an AnimationMixer → moving collider for particles, cloth interaction, or smoke.
  • A skinned creature/tail/tentacle → same.
  • The domain is a knob: domain sets the box, setDomainCenter follows a bone. The showcase clamps the center to the ball-pit interior and floor-seats it — policy that lives in the example, not the block.
Read as Markdown ↗