@web-engine-dev/cloth
Real-time cloth simulation using Position-Based Dynamics (PBD) with constraint-based deformation. Verlet integration ensures unconditional stability — even at low iteration counts, the simulation remains physically plausible.
Layer 4 · Simulation
Features
- Position-Based Dynamics (PBD): Constraint-based solver with unconditional stability
- Verlet Integration: Numerically stable, no explosive instability
- 3 Constraint Types: Distance (structural), bending (dihedral angle), pin (attachment)
- Collision Response: Sphere, capsule, convex hull, and plane colliders
- Wind Zones: Directional and turbulent wind forces
- Tearing: Strain-based constraint removal for destructible fabrics
- Material Presets: Silk, cotton, leather, rubber with per-material stiffness and damping
- Triangular & Quad Topology: Supports both mesh types
- Self-Collision Detection: Prevents cloth from passing through itself
Installation
bash
npm install @web-engine-dev/cloth
# or
pnpm add @web-engine-dev/clothQuick Start
typescript
import { ClothSimulation, ClothMaterial } from '@web-engine-dev/cloth';
// Create a cloth simulation
const cloth = new ClothSimulation({
width: 10,
height: 10,
resolution: 20, // 20x20 particle grid
material: ClothMaterial.COTTON,
iterations: 4, // Constraint solver iterations per frame
});
// Pin the top edge to a world position
cloth.pinRow(0);
// Add wind
cloth.setWind({
direction: { x: 1, y: 0, z: 0.3 },
strength: 5.0,
turbulence: 0.3,
});
// Attach to a character entity (e.g., cape)
cloth.pinParticle(0, characterShoulderLeft);
cloth.pinParticle(9, characterShoulderRight);
// Step simulation each frame
cloth.step(deltaTime);Simulation Pipeline
- External Forces — Apply gravity, wind, and turbulence
- Verlet Predict —
pos + (pos - prev) × damp - Constraint Solve — N iterations × all constraints (distance, bending, pin)
- Collision Resolve — Sphere, capsule, plane, box collision response
- Write Back — Update previous positions
Constraint Types
| Constraint | Purpose | Details |
|---|---|---|
| Distance | Maintain rest length between particles | Structural edges, shear diagonals, skip-one bending |
| Bending | Preserve dihedral angles | Asymmetric — resists compression, allows outward bending |
| Pin | Fix particles to world/entity positions | Cape attachment to character shoulders, curtain rods |
Why PBD Over Spring-Mass?
Spring-mass systems compute forces from Hooke's law, then integrate accelerations. High stiffness demands tiny timesteps or the simulation explodes. PBD sidesteps this by directly moving particles to satisfy constraints via iterative Gauss-Seidel relaxation. Even a single solver iteration produces visually plausible results — more iterations refine accuracy without ever risking instability.
Dependencies
@web-engine-dev/math— Vector types@web-engine-dev/spatial— Collision detection@web-engine-dev/physics3d— Collider interaction (optional)