Skip to main content

rapier_cloth_core/implicit/
settings.rs

1use crate::{ClothError, Real};
2
3/// Action when the Newton iteration budget is exhausted. Other failures always
4/// reject the step. Task qualification is limited to the documented towel fixture.
5#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
6pub enum ImplicitCapPolicy {
7    /// Reject an unconverged step and preserve the accepted state.
8    #[default]
9    Strict,
10    /// Return the last accepted iterate only after final CCD, contact, finite-state,
11    /// hard-target and less-than-3% edge-extension checks. Requires the default
12    /// iteration cap, tolerance and convergence window. This does not certify
13    /// stationary accuracy.
14    ApproximateWithFinalValidation,
15}
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum ImplicitTermination {
19    /// The configured Newton-displacement criterion was met.
20    Converged,
21    /// The iteration cap was reached; final physical validation passed.
22    ApproximateIterationCap,
23}
24
25/// Diagnostics for an accepted implicit step, after all final checks succeed.
26/// Residual forces are the negative free-particle objective gradient, in newtons.
27/// Neither the residual nor `converged` bounds trajectory or shape error.
28#[derive(Debug, Clone, Copy, PartialEq)]
29pub struct ImplicitOutcome {
30    pub termination: ImplicitTermination,
31    /// False for `ApproximateIterationCap`, even when the physical checks pass.
32    pub converged: bool,
33    /// Final backward-Euler objective, in joules.
34    pub energy: Real,
35    /// RMS residual force magnitude over free particles (zero if all fixed).
36    pub force_rms: Real,
37    /// Maximum free-particle residual force magnitude.
38    pub force_max: Real,
39}
40
41/// CPU execution budget for one implicit cloth solve. Numerical accumulation
42/// order is the same in both modes. Host applications own scheduling across
43/// cloths; no global pool or thread-affinity policy is installed.
44#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
45pub enum ImplicitExecution {
46    /// Run on the calling thread, without creating workers.
47    #[default]
48    Serial,
49    /// Use the calling thread and up to three scoped workers for material and
50    /// parent-contact evaluation. Small inputs and other phases stay serial.
51    /// Requires a target that supports spawning native threads.
52    Parallel4,
53}
54
55/// Thin-shell material in metres and pascals. Areal mass and velocity
56/// damping remain in `ClothMaterial`. Collision thickness is configured
57/// separately through `ClothContactSettings`.
58///
59/// The membrane is isotropic Neo-Hookean in `youngs_modulus` and
60/// `poisson_ratio`. Woven cloth is stiffer along its threads than on the bias:
61/// `warp_stiffness` and `weft_stiffness` add a stretch energy
62/// `k / 2 (|F a| - 1)^2` per unit volume along each triangle's material axis
63/// and across it, for triangles whose mesh carries material axes
64/// (`ClothMesh::set_material_axes`); triangles without an axis, and the
65/// defaults of zero, keep the isotropic behavior.
66#[derive(Debug, Clone, Copy, PartialEq)]
67pub struct ShellMaterial {
68    pub youngs_modulus: Real,
69    pub poisson_ratio: Real,
70    pub thickness: Real,
71    /// Extra stiffness along the material axis (warp), in pascals.
72    pub warp_stiffness: Real,
73    /// Extra stiffness across the material axis (weft), in pascals.
74    pub weft_stiffness: Real,
75    /// Spring stiffness of the mesh's stitches (`ClothMesh::stitches`), in
76    /// newtons per metre.
77    pub stitch_stiffness: Real,
78}
79
80impl Default for ShellMaterial {
81    fn default() -> Self {
82        Self {
83            youngs_modulus: 821000.0,
84            poisson_ratio: 0.243,
85            thickness: 0.000318,
86            warp_stiffness: 0.0,
87            weft_stiffness: 0.0,
88            stitch_stiffness: 500.0,
89        }
90    }
91}
92
93/// Initial iterate of the Newton solve. Both converge to the same objective;
94/// the seed changes the iteration count and roundoff-level differences only.
95#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
96pub enum ImplicitSeed {
97    /// Start free vertices at their previous positions.
98    Previous,
99    /// Start free vertices at `previous + velocity * h`, shortened by the
100    /// continuous checks and only if every contact keeps positive clearance;
101    /// otherwise fall back to the previous positions. This typically saves
102    /// 10–20% of the Newton iterations.
103    #[default]
104    Velocity,
105}
106
107/// Bounded global backward-Euler solve with a Neo-Hookean membrane, dihedral
108/// bending, a positive-gap contact barrier and lagged smooth Coulomb friction.
109/// The initial supported runtime uses f64 and hard particle grasps. Contact
110/// activation margin sets the barrier width and must be positive. Existing
111/// collision-work limits apply to the entire physical step.
112#[derive(Debug, Clone, Copy, PartialEq)]
113pub struct ImplicitSettings {
114    pub material: ShellMaterial,
115    /// Explicit per-cloth CPU budget, also preserved by checkpoints.
116    pub execution: ImplicitExecution,
117    /// Explicit opt-in to approximate returns; checkpoints preserve this policy.
118    pub cap_policy: ImplicitCapPolicy,
119    pub max_iterations: usize,
120    pub max_line_search_iterations: usize,
121    /// RMS Newton displacement divided by h, in m/s. The solve converges once
122    /// `convergence_window` consecutive Newton directions are within it, or when
123    /// the first direction of the step already is (a state at rest stays put).
124    pub velocity_tolerance: Real,
125    /// Consecutive iterations that must meet `velocity_tolerance`, 1 to 8. The
126    /// default 3 follows the author solver. Smaller windows stop sooner but can
127    /// accept the low point of an oscillating iteration far from convergence.
128    pub convergence_window: usize,
129    /// Per-contact barrier stiffness, in N/m; this is a numerical contact
130    /// parameter and is not a continuum material modulus.
131    pub barrier_stiffness: Real,
132    /// Smooth Coulomb transition velocity, in m/s. Nonzero values allow creep
133    /// under static tangential load; this is not exact static friction.
134    pub friction_velocity: Real,
135    /// Initial Newton iterate; checkpoints preserve it.
136    pub seed: ImplicitSeed,
137}
138
139impl Default for ImplicitSettings {
140    fn default() -> Self {
141        Self {
142            material: ShellMaterial::default(),
143            execution: ImplicitExecution::Serial,
144            cap_policy: ImplicitCapPolicy::Strict,
145            max_iterations: 128,
146            max_line_search_iterations: 24,
147            velocity_tolerance: 0.001,
148            convergence_window: 3,
149            barrier_stiffness: 30.0,
150            friction_velocity: 0.001,
151            seed: ImplicitSeed::Velocity,
152        }
153    }
154}
155
156impl ImplicitSettings {
157    pub fn validate(&self) -> Result<(), ClothError> {
158        // Keep approximate returns within the qualified stopping profile.
159        let profile = Self::default();
160        if self.cap_policy == ImplicitCapPolicy::ApproximateWithFinalValidation
161            && (self.max_iterations != profile.max_iterations
162                || self.velocity_tolerance != profile.velocity_tolerance
163                || self.convergence_window != profile.convergence_window)
164        {
165            return Err(ClothError::InvalidParameter(
166                "approximate cap policy requires baseline profile",
167            ));
168        }
169        if cfg!(feature = "f32") {
170            return Err(ClothError::InvalidParameter(
171                "the experimental implicit solver requires f64",
172            ));
173        }
174        for value in [
175            self.material.youngs_modulus,
176            self.material.thickness,
177            self.velocity_tolerance,
178            self.barrier_stiffness,
179            self.friction_velocity,
180        ] {
181            if !value.is_finite() || value <= 0.0 {
182                return Err(ClothError::InvalidParameter("implicit solver parameter"));
183            }
184        }
185        if [
186            self.material.warp_stiffness,
187            self.material.weft_stiffness,
188            self.material.stitch_stiffness,
189        ]
190        .iter()
191        .any(|v| !v.is_finite() || *v < 0.0)
192        {
193            return Err(ClothError::InvalidParameter(
194                "directional stiffness must be finite and non-negative",
195            ));
196        }
197        if !self.material.poisson_ratio.is_finite()
198            || self.material.poisson_ratio <= -1.0
199            || self.material.poisson_ratio >= 0.5
200            || !(3..=1024).contains(&self.max_iterations)
201            || !(1..=128).contains(&self.max_line_search_iterations)
202            || !(1..=8).contains(&self.convergence_window)
203        {
204            return Err(ClothError::InvalidParameter("implicit solver parameter"));
205        }
206        Ok(())
207    }
208}