Skip to main content

Crate rapier_cloth

Crate rapier_cloth 

Source
Expand description

§rapier-cloth

CPU cloth simulation for Rust applications using Rapier 3D. Add deformable triangle meshes to an existing physics world, with contacts, pinned vertices and attachments to rigid bodies. The default solver uses extended position-based dynamics (XPBD); an optional implicit shell solver supports folding experiments.

rapier-cloth-core provides the engine-independent solver; rapier-cloth adds Rapier collision queries, attachments and time synchronization.

§Try the live demo

From a repository checkout, with Rust and Node.js 22.12 or newer:

npm --prefix demos/viewer ci
npm --prefix demos/viewer run live

Open http://127.0.0.1:5173/live.html to drape cloth over a sphere, adjust wind, move the obstacle and release pinned vertices. The launcher builds a local Rust CPU server and starts the browser UI. For implicit towel folding and Rapier end-effector pose commands, run npm --prefix demos/viewer run live:implicit and open /live.html?scene=implicit_towel&paused=1. Strict stopping is the default; the scene also offers an explicit validated-approximation policy applied on Reset. Use 5 mm moves, 5 degree rotations and independent releases. See robot control and the live demo guide. General folding and wall-clock real-time performance remain under development.

§Use from Rust

[dependencies]
rapier-cloth = "0.3"

A repository checkout also works as a path dependency (rapier-cloth = { path = "../rapier-cloth" }). The engine-independent solver is available on its own as rapier-cloth-core. Rust 1.90 or newer is required. The default is f32, compatible with rapier3d 0.34. For rapier3d-f64 0.34, set default-features = false, features = ["f64"]. Select exactly one precision; do not use --all-features.

use rapier_cloth::{rapier::prelude::*, prelude::*};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let id = WorldId::new();
    let mut rigid = PhysicsWorld::new();
    let h = 1.0 / 240.0;
    rigid.integration_parameters.dt = h;
    let mut cloths = RapierClothWorld::new(id);
    let cloth = Cloth::new(
        GridBuilder::new(32, 32).origin(Vec3::Y).build()?,
        ClothMaterial::default(),
    )?;
    let handle = cloths.add_cloth(cloth);

    // Run this sequence once per substep, using the same h for both worlds.
    let before = SceneSnapshot::capture(id, 0, &rigid.bodies, &rigid.colliders);
    // Set any kinematic targets here, after taking the snapshot.
    rigid.step();
    let query = rigid.broad_phase.as_query_pipeline(
        rigid.narrow_phase.query_dispatcher(),
        &rigid.bodies, &rigid.colliders, QueryFilter::default(),
    );
    cloths.step_substep(h, &RapierScene::new(query, &before, h, rigid.gravity))?;
    let surface = cloths.cloth(handle)?.surface();
    assert_eq!(surface.positions.len(), 1024);
    Ok(())
}

See integration for step ordering, rendering, materials, collision filters, attachments and recovery after a failed step.

§Capabilities and limits

The solver supports fixed triangle topology, surface density, stretch and dihedral bending constraints, pins and attachments with body-local anchors. Collisions support spheres, boxes, capsules, convex hulls, compounds of those solids (such as convex decompositions) and fixed half-spaces. Kinematic obstacle motion is bounded per substep.

Coupling is one-way. Experimental self-collision and whole-triangle rigid contact are available as opt-in settings. Cloth-to-cloth collision, reactions on dynamic rigid bodies and arbitrary collision meshes are not implemented. Experimental continuous rigid-surface checks cover bounded primitive motion and solver corrections. The optional implicit towel example tests a separate fold, release and settle trajectory at 0.04 or 0.1 s per physical step. General folding and its real-time CPU budget remain under development. Use surface queries and grasp attachments to select exposed cloth layers and command a point or patch; static friction alone is not a grasp model. Read the compatibility and limitations before integrating.

§Documentation

Licensed under the MIT License.

Re-exports§

pub use grasp::ClothSurfaceHit;
pub use grasp::ClothSurfacePoint;
pub use grasp::GraspOptions;
pub use grasp::GraspPatch;
pub use attachment::AttachmentDesc;
pub use attachment::AttachmentEvent;
pub use attachment::AttachmentEventKind;
pub use attachment::AttachmentHandle;
pub use attachment::AttachmentPoint;
pub use attachment::SurfaceAttachmentDesc;
pub use attachment::SurfaceAttachmentPoint;
pub use diagnostics::IntegrationError;
pub use diagnostics::WorldStepReport;
pub use scene::RapierScene;
pub use scene::SceneSnapshot;
pub use scene::WorldId;
pub use world::ClothCheckpoint;
pub use world::CollisionSettings;
pub use world::RapierClothWorld;
pub use rapier_cloth_core as core;
pub use rapier_f64 as rapier;

Modules§

attachment
cloth
collision
Surface contact geometry, independent of any rigid-body engine.
constraints
contact
diagnostics
error
garment
Parametric garments built as flat-folded cloth meshes.
grasp
Surface selection and idealized commanded grasps. Robot kinematics and fingertip force control remain responsibilities of the host simulator.
implicit
Experimental global implicit shell solver. Enable with the implicit feature. The f64 path supports hard particle grasps and finite-thickness surface contact. Neo-Hookean membrane, discrete shell bending, finite-thickness barrier and lagged regularized Coulomb friction share one position objective.
material
math
Precision aliases independent of Rapier and Parry.
mesh
prelude
scene
solver
surface
world

Structs§

Cloth
A cloth’s physical state; rest topology is shared when making checkpoints.
ClothContactSettings
ClothHandle
Includes arena identity as well as a generation, so handles from another ClothSet cannot accidentally resolve even when indices coincide.
ClothMaterial
Metres, kilograms, seconds. Compliances parameterize discrete constraints, not calibrated continuum fabric moduli.
ClothMesh
Validated, immutable simulation topology. No implicit vertex welding.
ClothSet
CollisionLimits
CollisionWork
Contact
A unilateral plane constraint n dot (x - point) >= particle radius. normal is a unit vector from the obstacle towards the cloth. All vectors are in the application’s world frame; friction is already combined.
ContactKey
ContactMotion
Proposed linear cloth motion. Prediction spans the source’s whole physical substep. Stabilization uses its previous obstacle pose; Iteration holds obstacles at their current pose while cloth constraints are corrected. The built-in solvers certify the accepted path segment by segment and request no Final-stage sweep of the substep’s chord; that variant is kept for compatibility and still names the final contact query. An iteration combines elastic, target and contact projections into a trial before checking it. A shortened trial is followed by a separately checked correction that only pushes features outward to full thickness. Intermediate trials are not states committed to the cloth, and callback counts are not fixed per iteration.
Garment
A built garment: the mesh plus the pattern metadata that locates panels, seams and landmarks in it.
GridBuilder
Rectangular grid in an explicitly chosen plane; defaults to X/Z.
ImplicitOutcome
Diagnostics for an accepted implicit step, after all final checks succeed. Residual forces are the negative free-particle objective gradient, in newtons. Neither the residual nor converged bounds trajectory or shape error.
ImplicitSettings
Bounded global backward-Euler solve with a Neo-Hookean membrane, dihedral bending, a positive-gap contact barrier and lagged smooth Coulomb friction. The initial supported runtime uses f64 and hard particle grasps. Contact activation margin sets the barrier width and must be positive. Existing collision-work limits apply to the entire physical step.
NoContacts
ShellMaterial
Thin-shell material in metres and pascals. Areal mass and velocity damping remain in ClothMaterial. Collision thickness is configured separately through ClothContactSettings.
Solver
Reusable staging buffers. Cloth state is committed only after all queries, projections and finite-value checks succeed.
SolverSettings
StepReport
SurfaceContact
A surface constraint with relative position sum(weights[i]*x[i])-offset. Vertex-face weights are [1, -b0, -b1, -b2]; edge-edge weights are [1-s, s, -(1-t), -t]. Unused slots have zero weights. Each used particle appears once. Normal and offset are in the application world frame.
SurfaceContactKey
SurfaceHit
SurfacePoint
A material point on a fixed-topology mesh. It is local to one cloth; the integration boundary additionally associates it with a generational handle.
SurfaceQueryLimits
SurfaceRay
A finite point approach in the current, static cloth pose. Direction is normalized by the query; max_distance is in world length units.
SurfaceTarget
Constrain a triangle’s material point without pinning its support vertices.
SurfaceView
One-to-one simulation/render vertex mapping in 0.1. Indices are stable for the cloth lifetime. The borrow prevents stepping while these slices are live.
TShirtPattern
Dimensions of a T-shirt pattern in metres.
Target
Vec3
A 3-dimensional vector.

Enums§

ClothError
Errors never silently repair or discard unsupported input.
CollisionBudgetKind
ContactStage
GarmentLayers
Which panels a pattern is cut into.
ImplicitCapPolicy
Action when the Newton iteration budget is exhausted. Other failures always reject the step. Task qualification is limited to the documented towel fixture.
ImplicitExecution
CPU execution budget for one implicit cloth solve. Numerical accumulation order is the same in both modes. Host applications own scheduling across cloths; no global pool or thread-affinity policy is installed.
ImplicitTermination
SurfaceFeature

Traits§

ContactSource
A narrow boundary for refreshing external constraints. Output is cleared by the solver before every call. Failure aborts the entire cloth substep. Every stage, including prediction, may be queried repeatedly for trial poses in the same substep. A source must retain unique keys when caching witnesses.

Type Aliases§

Real