Voronoi Mesh Shattering, FABRIK Inverse Kinematics & XPBD Verlet Ropes in Three.js
Zero-dependency Three.js r183 procedural motion and destruction toolkit combining Voronoi-jittered breakable box shards, multi-bone FABRIK inverse kinematics, and unconditionally stable fixed-step XPBD Verlet ropes and capes.
- fracture
- shatter
- voronoi
- destruction
- ik
- fabrik
- verlet
- rope
- cloth
- xpbd
- procedural-animation
No demo.
When to Use & Field Best Practices
Action, adventure, and physics-toy games jump a full tier in tactile juice when crates shatter into spinning shards, robotic/creature limbs plant dynamically on uneven terrain, and grapple lines or banners sway physically at 60 Hz:
- Voronoi-Jittered Shatter Shards (
shatterBoxMesh): Instead of vanishing a destroyed crate behind puffs of smoke, split its volume into8–16jittered prism shards using distinct exterior + interior fracture materials, apply radial explosion velocity + spin, and bounce shards cleanly onfloorYbefore pooling/fading them out. - FABRIK Multi-Bone Chain Solver (
solveFabrik): Forward-and-Backward Reaching Inverse Kinematics converges in just3–6iterations with zero matrix inversions or gimbal lock — ideal for multi-legged spider walkers, robotic grabber arms, tentacles, and foot-on-slope grounding. - Fixed-Step XPBD Verlet Rope / Grapple / Cape (
VerletRope): Runs deterministically insidegame.onUpdate(dt)(dt = 1/60) with4–8distance constraint relaxation passes, pin endpoints, and wind drag, updating a pre-allocatedTHREE.BufferGeometrytube/ribbon in place (zero per-frame GPU allocations!).
Mathematical & Algorithmic Core
- FABRIK Forward/Backward Pass: Given joint positions
p_0, dots, p_nwith fixed bone lengthsL_i = \|p_i+1 - p_i\|:
- Pin
p_n ← t, pull backwardp_i ← p_i+1 + L_i widehat(p_i - p_i+1). - Pin
p_0 ← r_root, push forwardp_i+1 ← p_i + L_i widehat(p_i+1 - p_i).
- Verlet Position Integration & Constraint Projection: $
x' = x + (x - x_prev)(1 - d) + a\,Δ t^2, Δx = frac\|x_b - x_a\| - L\|x_b - x_a\|(x_b - x_a)$
Engine Implementation (Assets/Game/proceduralMotionFx.ts)
Strict erasable TypeScript module with zero external dependencies and zero per-frame allocations inside step(dt):
import * as THREE from 'three';
export interface ShatterOptions {
/** Number of shards along X, Y, Z (e.g. [2, 2, 2] -> 8 shards, max 27). */
grid?: readonly [number, number, number];
/** Outward impulse speed (m/s, default 5.5). */
blastSpeed?: number;
/** Floor height for shard bounce (default 0). */
floorY?: number;
/** Lifetime before shards shrink away (seconds, default 2.2). */
lifetime?: number;
exteriorColor?: number;
interiorColor?: number;
}
export interface ShatterBurst {
group: THREE.Group;
step(dt: number): boolean;
dispose(): void;
}
interface ShardBody {
mesh: THREE.Mesh;
vel: THREE.Vector3;
angVel: THREE.Vector3;
halfH: number;
}
/**
* Replaces a box target at `center` with jittered Voronoi-like breakable shards that
* burst outward, spin, bounce on `floorY`, and cleanly self-dispose when done.
*/
export function shatterBoxMesh(
parent: THREE.Object3D,
center: THREE.Vector3,
size: THREE.Vector3,
opts: ShatterOptions = {}
): ShatterBurst {
const [nx, ny, nz] = opts.grid ?? [2, 2, 2];
const blast = opts.blastSpeed ?? 5.5;
const floorY = opts.floorY ?? 0;
const lifetime = opts.lifetime ?? 2.2;
const extMat = new THREE.MeshStandardMaterial({ color: opts.exteriorColor ?? 0xb87a4b, roughness: 0.78 });
const intMat = new THREE.MeshStandardMaterial({ color: opts.interiorColor ?? 0xe4c59e, roughness: 0.92 });
const group = new THREE.Group();
const shards: ShardBody[] = [];
const sx = size.x / nx;
const sy = size.y / ny;
const sz = size.z / nz;
let seed = Math.round(center.x * 31 + center.z * 97 + 17) | 0;
const rand = (): number => {
seed = (seed * 1664525 + 1013904223) | 0;
return ((seed >>> 0) % 10000) / 10000;
};
for (let ix = 0; ix < nx; ix++) {
for (let iy = 0; iy < ny; iy++) {
for (let iz = 0; iz < nz; iz++) {
const jx = (rand() - 0.5) * sx * 0.25;
const jy = (rand() - 0.5) * sy * 0.25;
const jz = (rand() - 0.5) * sz * 0.25;
const w = sx * (0.78 + rand() * 0.34);
const h = sy * (0.78 + rand() * 0.34);
const d = sz * (0.78 + rand() * 0.34);
const geo = new THREE.BoxGeometry(w, h, d);
// Exterior faces take extMat; interior fractured faces take intMat
const mats = [
ix === nx - 1 ? extMat : intMat,
ix === 0 ? extMat : intMat,
iy === ny - 1 ? extMat : intMat,
iy === 0 ? extMat : intMat,
iz === nz - 1 ? extMat : intMat,
iz === 0 ? extMat : intMat,
];
const mesh = new THREE.Mesh(geo, mats);
const ox = -size.x * 0.5 + (ix + 0.5) * sx + jx;
const oy = -size.y * 0.5 + (iy + 0.5) * sy + jy;
const oz = -size.z * 0.5 + (iz + 0.5) * sz + jz;
mesh.position.set(center.x + ox, center.y + oy, center.z + oz);
group.add(mesh);
const dir = new THREE.Vector3(ox, oy + 0.45, oz).normalize();
const vel = dir.multiplyScalar(blast * (0.65 + rand() * 0.7));
vel.y += 1.6 + rand() * 2.2;
const angVel = new THREE.Vector3((rand() - 0.5) * 10, (rand() - 0.5) * 10, (rand() - 0.5) * 10);
shards.push({ mesh, vel, angVel, halfH: h * 0.45 });
}
}
}
parent.add(group);
let age = 0;
return {
group,
step(dt: number): boolean {
age += dt;
const shrink = age > lifetime * 0.7 ? Math.max(0, 1 - (age - lifetime * 0.7) / (lifetime * 0.3)) : 1;
for (const s of shards) {
s.vel.y -= 18.0 * dt;
s.mesh.position.addScaledVector(s.vel, dt);
if (s.mesh.position.y < floorY + s.halfH) {
s.mesh.position.y = floorY + s.halfH;
s.vel.y = Math.abs(s.vel.y) * 0.36;
s.vel.x *= 0.72;
s.vel.z *= 0.72;
s.angVel.multiplyScalar(0.75);
}
s.mesh.rotation.x += s.angVel.x * dt;
s.mesh.rotation.y += s.angVel.y * dt;
s.mesh.rotation.z += s.angVel.z * dt;
s.mesh.scale.setScalar(shrink);
}
return age < lifetime;
},
dispose() {
parent.remove(group);
for (const s of shards) s.mesh.geometry.dispose();
extMat.dispose();
intMat.dispose();
},
};
}
const _ikDir = new THREE.Vector3();
/**
* In-place FABRIK inverse kinematics solver (zero allocations per call).
* Updates `joints` so joint[0] stays anchored at `root` and joint[n-1] reaches `target`.
*/
export function solveFabrik(
joints: readonly THREE.Vector3[],
lengths: readonly number[],
root: THREE.Vector3,
target: THREE.Vector3,
iterations = 5,
tolerance = 0.005
): void {
const n = joints.length;
if (n < 2) return;
let totalLen = 0;
for (let i = 0; i < n - 1; i++) totalLen += lengths[i];
_ikDir.subVectors(target, root);
const distToTarget = _ikDir.length();
if (distToTarget >= totalLen - 1e-4) {
if (distToTarget > 1e-5) _ikDir.divideScalar(distToTarget);
else _ikDir.set(0, 1, 0);
joints[0].copy(root);
for (let i = 0; i < n - 1; i++) {
joints[i + 1].copy(joints[i]).addScaledVector(_ikDir, lengths[i]);
}
return;
}
for (let iter = 0; iter < iterations; iter++) {
// Backward reaching: tip -> root
joints[n - 1].copy(target);
for (let i = n - 2; i >= 0; i--) {
_ikDir.subVectors(joints[i], joints[i + 1]);
const d = _ikDir.length();
if (d > 1e-5) joints[i].copy(joints[i + 1]).addScaledVector(_ikDir, lengths[i] / d);
}
// Forward reaching: root -> tip
joints[0].copy(root);
for (let i = 0; i < n - 1; i++) {
_ikDir.subVectors(joints[i + 1], joints[i]);
const d = _ikDir.length();
if (d > 1e-5) joints[i + 1].copy(joints[i]).addScaledVector(_ikDir, lengths[i] / d);
}
if (joints[n - 1].distanceToSquared(target) <= tolerance * tolerance) break;
}
}
export interface VerletRopeOptions {
segments?: number;
length?: number;
color?: number;
damping?: number;
gravity?: number;
iterations?: number;
}
/**
* Fixed-step XPBD/Verlet rope, grapple line, or hanging cable with pre-allocated line geometry.
*/
export class VerletRope {
readonly line: THREE.Line;
readonly points: THREE.Vector3[];
private readonly prev: THREE.Vector3[];
private readonly segLen: number;
private readonly damping: number;
private readonly gravity: number;
private readonly iterations: number;
private readonly posAttr: THREE.BufferAttribute;
private readonly scratch = new THREE.Vector3();
private readonly vel = new THREE.Vector3();
private endPinned = false;
private readonly pinStart = new THREE.Vector3();
private readonly pinEnd = new THREE.Vector3();
constructor(start: THREE.Vector3, end: THREE.Vector3, opts: VerletRopeOptions = {}) {
const segs = Math.max(4, Math.min(32, opts.segments ?? 12));
const totalLen = opts.length ?? Math.max(0.5, start.distanceTo(end));
this.segLen = totalLen / segs;
this.damping = opts.damping ?? 0.02;
this.gravity = opts.gravity ?? -18.0;
this.iterations = opts.iterations ?? 6;
this.pinStart.copy(start);
this.pinEnd.copy(end);
this.points = [];
this.prev = [];
const buf = new Float32Array((segs + 1) * 3);
for (let i = 0; i <= segs; i++) {
const t = i / segs;
const p = new THREE.Vector3().lerpVectors(start, end, t);
this.points.push(p);
this.prev.push(p.clone());
buf[i * 3] = p.x;
buf[i * 3 + 1] = p.y;
buf[i * 3 + 2] = p.z;
}
const geo = new THREE.BufferGeometry();
this.posAttr = new THREE.BufferAttribute(buf, 3);
geo.setAttribute('position', this.posAttr);
const mat = new THREE.LineBasicMaterial({ color: opts.color ?? 0xd8c7a3 });
this.line = new THREE.Line(geo, mat);
this.line.frustumCulled = false;
}
setPins(start: THREE.Vector3, end?: THREE.Vector3): void {
this.pinStart.copy(start);
if (end) {
this.endPinned = true;
this.pinEnd.copy(end);
} else {
this.endPinned = false;
}
}
step(dt: number, windX = 0, windZ = 0, floorY = 0.04): void {
const n = this.points.length;
const dt2 = dt * dt;
const keep = 1 - this.damping;
for (let i = 1; i < n; i++) {
if (this.endPinned && i === n - 1) continue;
this.vel.subVectors(this.points[i], this.prev[i]).multiplyScalar(keep);
this.prev[i].copy(this.points[i]);
this.points[i].add(this.vel);
this.points[i].x += windX * dt2;
this.points[i].y += this.gravity * dt2;
this.points[i].z += windZ * dt2;
if (this.points[i].y < floorY) this.points[i].y = floorY;
}
for (let it = 0; it < this.iterations; it++) {
this.points[0].copy(this.pinStart);
if (this.endPinned) this.points[n - 1].copy(this.pinEnd);
for (let i = 0; i < n - 1; i++) {
const a = this.points[i];
const b = this.points[i + 1];
this.scratch.subVectors(b, a);
const dist = this.scratch.length();
if (dist < 1e-5) continue;
const diff = (dist - this.segLen) / dist;
const aFixed = i === 0;
const bFixed = this.endPinned && i + 1 === n - 1;
if (aFixed && bFixed) continue;
if (aFixed) b.addScaledVector(this.scratch, -diff);
else if (bFixed) a.addScaledVector(this.scratch, diff);
else {
a.addScaledVector(this.scratch, diff * 0.5);
b.addScaledVector(this.scratch, -diff * 0.5);
}
}
}
for (let i = 0; i < n; i++) {
const p = this.points[i];
this.posAttr.setXYZ(i, p.x, p.y, p.z);
}
this.posAttr.needsUpdate = true;
}
dispose(): void {
this.line.geometry.dispose();
(this.line.material as THREE.Material).dispose();
}
}
Browser, Mobile & Software-Renderer Budgets
- Zero Per-Frame Allocations:
solveFabrikandVerletRope.stepreuse scratch vectors and update oneBufferAttributein place — safe at 60 Hz on phones and Quest VR. - Shard Budget: Keep
shatterBoxMeshat2×2×2(8shards) to3×2×2(12shards) and cap concurrent bursts to4so shattering never spikes draw calls. - Constraint Stability: With fixed
dt = 1/60,6Verlet iterations keep taut grapple lines rock-steady without spring explosion.
Verification Checklist
- Run
compile(threeCompile) and verify zero TypeScript,three-lint, or runtime errors. - Call
solveFabrikon a 4-joint limb and assertjoints[3].distanceTo(target) < 0.01when target is within reach. - Trigger
shatterBoxMeshon impact and confirm shards bounce onfloorYand shrink cleanly to zero beforedispose().
Official references
- Dan Greenheck — three-pinata (MIT)
- Matthias Müller / matthias-research — Ten Minute Physics XPBD Constraints (MIT)
- upf-gti — IK-threejs (MIT)
- Andreas Aristidou & Joan Lasenby (2011 — FABRIK: A Fast, Iterative Solver for the Inverse Kinematics Problem)
Open-source sources
- Takes an idea from three-pinata by Dan Greenheck (MIT License): Voronoi-jittered box fracture shard workflow
- Takes an idea from Ten Minute Physics by Matthias Müller (MIT License): unconditionally stable XPBD Verlet rope constraint relaxation
- Takes an idea from IK-threejs by upf-gti (MIT License): multi-bone FABRIK inverse kinematics solver
Games built with this guide carry these credits, and the licence notices they ask for, in their third-party notices.
More Three.js games
Games made with GameCrew on the same engine. No game has been built with this guide yet: these show what Three.js games here look like.
More Three.js techniques
BVH Mesh & Character Capsule Collision in Three.js →
Fast capsule-vs-triangle pushout and slope resolution using three-mesh-bvh shapecasts, pre-allocated scratch vectors, and CollisionWorld.
Zero-Allocation Context Steering, Patrol Loops & Telegraphed AI in Three.js →
Deterministic 60 Hz enemy and companion AI in Three.js using 8-slot context steering against CollisionWorld, level.json patrol loops, attack-token pacing, and telegraphed strikes.
Instanced Wind Foliage, Object-Pooled Particles & Spring Feel in Three.js →
Single-draw-call THREE.InstancedMesh wind foliage with player bend, zero-GC pooled burst particles, and dt-invariant second-order springs that keep 60 Hz steps under 2 ms.
Baked 3D Volumetric Cloud Sea, World-Anchored Marching & TAA in Three.js →
Endless fly-above volumetric cloud sea in Three.js r183 WebGL 2 using a GPU-baked WebGL3DRenderTarget SDF and lighting volume, anti-boiling world-anchored z-plane marching, 3-octave Henyey-Greenstein scattering, and variance-clamped depth-packed TAA.
Use verified techniques inside a real game
Describe your game idea for free or connect an MCP assistant to search and contribute techniques.
