Skip to main content

rapier2d/dynamics/
integration_parameters.rs

1#[cfg(all(doc, feature = "alloc"))]
2use super::RigidBodyActivation;
3use crate::math::Real;
4use simba::simd::SimdRealField;
5
6// NOTE: the 2x2 block solver (`block-solver` feature) runs in BOTH passes and solves the COMPLIANT
7//       LCP `(K + C, b)`, `C = diag((1/ms_i - 1) k_ii)` — the coupled soft step — so it shares
8//       the sequential sweep's fixed points; a rigid-LCP-then-cfm-scale variant left piles micro-jiggling.
9
10/// Friction models used for all contact constraints between two rigid-bodies.
11///
12/// This selection does not apply to multibodies that always rely on the [`FrictionModel::Coulomb`].
13#[cfg(feature = "dim3")]
14#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)]
15#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
16pub enum FrictionModel {
17    /// A simplified friction model significantly faster to solve than [`Self::Coulomb`]
18    /// but less accurate.
19    ///
20    /// Instead of solving one Coulomb friction constraint per contact in a contact manifold,
21    /// this approximation only solves one Coulomb friction constraint per group of 4 contacts
22    /// in a contact manifold, plus one "twist" constraint. The "twist" constraint is purely
23    /// rotational and aims to eliminate angular movement in the manifold’s tangent plane.
24    #[default]
25    Simplified,
26    /// The coulomb friction model.
27    ///
28    /// This results in one Coulomb friction constraint per contact point.
29    Coulomb,
30}
31
32#[derive(Copy, Clone, Debug, PartialEq)]
33#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
34// TODO: we should be able to combine this with MotorModel.
35/// Coefficients for a spring, typically used for configuring constraint softness for contacts and
36/// joints.
37pub struct SpringCoefficients<N> {
38    /// Sets the natural frequency (Hz) of the spring-like constraint.
39    ///
40    /// Higher values make the constraint stiffer and resolve constraint violations more quickly.
41    pub natural_frequency: N,
42    /// Sets the damping ratio for the spring-like constraint.
43    ///
44    /// Larger values make the joint more compliant (allowing more drift before stabilization).
45    pub damping_ratio: N,
46}
47
48impl<N: SimdRealField<Element = Real> + Copy> SpringCoefficients<N> {
49    /// Initializes spring coefficients from the spring natural frequency and damping ratio.
50    pub fn new(natural_frequency: N, damping_ratio: N) -> Self {
51        Self {
52            natural_frequency,
53            damping_ratio,
54        }
55    }
56
57    /// Default softness coefficients for contacts (30 Hz, ζ = 10).
58    /// The high ζ is load-bearing for large piles/stacks: softer contacts settle
59    /// deeper under load, and the extra penetration keeps them wedging and creeping instead of resting.
60    pub fn contact_defaults() -> Self {
61        Self {
62            natural_frequency: N::splat(30.0),
63            damping_ratio: N::splat(10.0),
64        }
65    }
66
67    /// Default softness coefficients for contacts touching a fixed body: twice the natural
68    /// frequency of [`Self::contact_defaults`], holding piled/pushed
69    /// bodies more firmly against walls and floors so they are less likely to squeeze through.
70    pub fn contact_static_defaults() -> Self {
71        Self {
72            natural_frequency: N::splat(60.0),
73            damping_ratio: N::splat(10.0),
74        }
75    }
76
77    /// Default softness coefficients for joints.
78    pub fn joint_defaults() -> Self {
79        Self {
80            natural_frequency: N::splat(1.0e6),
81            damping_ratio: N::splat(1.0),
82        }
83    }
84
85    /// The contact’s spring angular frequency for constraints regularization.
86    pub fn angular_frequency(&self) -> N {
87        self.natural_frequency * N::simd_two_pi()
88    }
89
90    /// The [`Self::erp`] coefficient, multiplied by the inverse timestep length.
91    pub fn erp_inv_dt(&self, dt: N) -> N {
92        let ang_freq = self.angular_frequency();
93        ang_freq / (dt * ang_freq + N::splat(2.0) * self.damping_ratio)
94    }
95
96    /// The effective Error Reduction Parameter applied for calculating regularization forces.
97    ///
98    /// This parameter is computed automatically from [`Self::natural_frequency`],
99    /// [`Self::damping_ratio`] and the substep length.
100    pub fn erp(&self, dt: N) -> N {
101        dt * self.erp_inv_dt(dt)
102    }
103
104    /// Compute CFM assuming a critically damped spring multiplied by the damping ratio.
105    ///
106    /// This coefficient softens the impulse applied at each solver iteration.
107    pub fn cfm_coeff(&self, dt: N) -> N {
108        let one = N::one();
109        let erp = self.erp(dt);
110        let erp_is_not_zero = erp.simd_ne(N::zero());
111
112        let damped = {
113            let inv_erp_minus_one = one / erp - one;
114
115            // let stiffness = 4.0 * damping_ratio * damping_ratio * projected_mass
116            //     / (dt * dt * inv_erp_minus_one * inv_erp_minus_one);
117            // let damping = 4.0 * damping_ratio * damping_ratio * projected_mass
118            //     / (dt * inv_erp_minus_one);
119            // let cfm = 1.0 / (dt * dt * stiffness + dt * damping);
120            // NOTE: This simplifies to cfm = cfm_coeff / projected_mass:
121            inv_erp_minus_one * inv_erp_minus_one
122                / ((one + inv_erp_minus_one)
123                    * N::splat(4.0)
124                    * self.damping_ratio
125                    * self.damping_ratio)
126        };
127        let undamped = {
128            // Undamped version if the damping ratio is zero.
129            let dt_omega = dt * self.angular_frequency();
130            one / (dt_omega * (dt_omega + N::splat(2.0) * self.damping_ratio))
131        };
132
133        let damping_is_zero = self.damping_ratio.simd_eq(N::zero());
134        let result = undamped.select(damping_is_zero, damped);
135        result.select(erp_is_not_zero, N::zero())
136    }
137
138    /// The CFM factor to be used in the constraint resolution.
139    ///
140    /// This parameter is computed automatically from [`Self::natural_frequency`],
141    /// [`Self::damping_ratio`] and the substep length.
142    pub fn cfm_factor(&self, dt: N) -> N {
143        let one = N::one();
144        let cfm_coeff = self.cfm_coeff(dt);
145
146        // We use this coefficient inside the impulse resolution.
147        // Surprisingly, several simplifications happen there.
148        // Let `m` the projected mass of the constraint.
149        // Let `m’` the projected mass that includes CFM: `m’ = 1 / (1 / m + cfm_coeff / m) = m / (1 + cfm_coeff)`
150        // We have:
151        // new_impulse = old_impulse - m’ (delta_vel - cfm * old_impulse)
152        //             = old_impulse - m / (1 + cfm_coeff) * (delta_vel - cfm_coeff / m * old_impulse)
153        //             = old_impulse * (1 - cfm_coeff / (1 + cfm_coeff)) - m / (1 + cfm_coeff) * delta_vel
154        //             = old_impulse / (1 + cfm_coeff) - m * delta_vel / (1 + cfm_coeff)
155        //             = 1 / (1 + cfm_coeff) * (old_impulse - m * delta_vel)
156        // So, setting cfm_factor = 1 / (1 + cfm_coeff).
157        // We obtain:
158        // new_impulse = cfm_factor * (old_impulse - m * delta_vel)
159        //
160        // The value returned by this function is this cfm_factor that can be used directly
161        // in the constraint solver.
162        one / (one + cfm_coeff)
163    }
164}
165
166/// Configuration parameters that control the physics simulation quality and behavior.
167///
168/// These parameters affect how the physics engine advances time, resolves collisions, and
169/// maintains stability. The defaults work well for most games, but you may want to adjust
170/// them based on your specific needs.
171///
172/// # Key parameters for beginners
173///
174/// - **`dt`**: Timestep duration (default: 1/60 second). Most games run physics at 60Hz.
175/// - **`num_solver_iterations`**: More iterations = more accurate but slower (default: 4)
176/// - **`length_unit`**: Scale factor if your world units aren't meters (e.g., 100 for pixel-based games)
177///
178/// # Example
179///
180/// ```
181/// # use rapier3d::prelude::*;
182/// // Standard 60 FPS physics with default settings
183/// let mut integration_params = IntegrationParameters::default();
184///
185/// // For a more accurate (but slower) simulation:
186/// integration_params.num_solver_iterations = 8;
187///
188/// // For pixel-based 2D games where 100 pixels = 1 meter:
189/// integration_params.length_unit = 100.0;
190/// ```
191///
192/// Most other parameters are advanced settings for fine-tuning stability and performance.
193#[derive(Copy, Clone, Debug, PartialEq)]
194#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
195pub struct IntegrationParameters {
196    /// The timestep length - how much simulated time passes per physics step (default: `1.0 / 60.0`).
197    ///
198    /// Set this to `1.0 / your_target_fps`. For example:
199    /// - 60 FPS: `1.0 / 60.0` ≈ 0.0167 seconds
200    /// - 120 FPS: `1.0 / 120.0` ≈ 0.0083 seconds
201    ///
202    /// Smaller timesteps are more accurate but require more CPU time per second of simulated time.
203    ///
204    /// With a zero (or negative) `dt`, [`PhysicsPipeline::step`](crate::pipeline::PhysicsPipeline::step)
205    /// only applies the user changes and updates the collision detection (contacts, collision
206    /// events, scene queries): no time passes, so no body moves (kinematic bodies included) and
207    /// velocities are left untouched.
208    pub dt: Real,
209    /// Minimum timestep size when using CCD with multiple substeps (default: `1.0 / 60.0 / 100.0`).
210    ///
211    /// When CCD with multiple substeps is enabled, the timestep is subdivided
212    /// into smaller pieces. This timestep subdivision won't generate timestep
213    /// lengths smaller than `min_ccd_dt`.
214    ///
215    /// Setting this to a large value will reduce the opportunity to performing
216    /// CCD substepping, resulting in potentially more time dropped by the
217    /// motion-clamping mechanism. Setting this to an very small value may lead
218    /// to numerical instabilities.
219    pub min_ccd_dt: Real,
220
221    /// Softness coefficients for contact constraints.
222    pub contact_softness: SpringCoefficients<Real>,
223
224    /// Softness coefficients for contact constraints where one side is a fixed body.
225    ///
226    /// Stiffer than [`Self::contact_softness`] by default so bodies are
227    /// held firmly against static walls/floors; set equal to [`Self::contact_softness`] to disable.
228    pub static_contact_softness: SpringCoefficients<Real>,
229
230    /// The coefficient in `[0, 1]` applied to warmstart impulses, i.e., impulses that are used as the
231    /// initial solution (instead of 0) at the next simulation step.
232    ///
233    /// This should generally be set to 1.
234    ///
235    /// (default `1.0`).
236    pub warmstart_coefficient: Real,
237
238    /// The scale factor for your world if you're not using meters (default: `1.0`).
239    ///
240    /// Rapier is tuned for human-scale objects measured in meters. If your game uses different
241    /// units, set this to how many of your units equal 1 meter in the real world.
242    ///
243    /// **Examples:**
244    /// - Your game uses meters: `length_unit = 1.0` (default)
245    /// - Your game uses centimeters: `length_unit = 100.0` (100 cm = 1 m)
246    /// - Pixel-based 2D game where typical objects are 100 pixels tall: `length_unit = 100.0`
247    /// - Your game uses feet: `length_unit = 3.28` (approximately)
248    ///
249    /// This automatically scales various internal tolerances and thresholds to work correctly
250    /// with your chosen units.
251    pub length_unit: Real,
252
253    /// Settings shared by every soft body: tangle recovery, strained-constraint re-sweep, impact
254    /// substeps, contact stiffening and FEM solver tuning (see [`SoftBodiesSettings`]).
255    ///
256    /// [`SoftBodiesSettings`]: crate::dynamics::SoftBodiesSettings
257    #[cfg(feature = "alloc")]
258    #[cfg_attr(feature = "serde-serialize", serde(default))]
259    pub soft_bodies: crate::dynamics::SoftBodiesSettings,
260
261    /// Geometric slop distance (default: `0.005`), e.g. the standoff kept
262    /// by the CCD clamp. NOT a deadzone on the position-correction bias: penetrations are corrected
263    /// all the way to zero; a deadzone would keep loaded piles wedging and creeping.
264    ///
265    /// This value is implicitly scaled by [`IntegrationParameters::length_unit`].
266    pub normalized_allowed_linear_error: Real,
267    /// Maximum speed at which contact penetration is pushed out by the biased solve
268    /// (default: `3.0`).
269    ///
270    /// Capping this recovery velocity keeps deep penetrations from being resolved explosively.
271    /// This value is implicitly scaled by [`IntegrationParameters::length_unit`].
272    pub normalized_max_corrective_velocity: Real,
273    /// The maximal distance separating two objects that will generate predictive contacts (default: `0.02`).
274    ///
275    /// This value is implicitly scaled by [`IntegrationParameters::length_unit`].
276    pub normalized_prediction_distance: Real,
277    /// Maximum linear velocity a body may have after each solver substep (default: `400.0` m/s).
278    /// Bounding per-step travel keeps CCD and speculative contacts
279    /// reliable (a body cannot be flung or crushed to an arbitrary speed); set to `Real::MAX` to disable.
280    ///
281    /// This value is implicitly scaled by [`IntegrationParameters::length_unit`].
282    pub normalized_max_linear_velocity: Real,
283    /// The number of solver iterations run by the constraints solver for calculating forces (default: `4`).
284    ///
285    /// Higher values produce more accurate and stable simulations at the cost of performance.
286    /// - `4` (default): Good balance for most games
287    /// - `8-12`: Use for demanding scenarios (stacks of objects, complex machinery)
288    /// - `1-2`: Use if performance is critical and accuracy can be sacrificed
289    pub num_solver_iterations: usize,
290    /// Number of internal Project Gauss Seidel (PGS) iterations run at each solver iteration (default: `1`).
291    pub num_internal_pgs_iterations: usize,
292    /// The number of stabilization iterations run at each solver iterations (default: `1`).
293    pub num_internal_stabilization_iterations: usize,
294    /// Maximum number of CCD substeps performed by the solver (default: `1`).
295    ///
296    /// Also the global CCD on/off switch: `0` disables **all** CCD for the world (including the
297    /// automatic CCD of fast dynamic bodies vs fixed colliders).
298    pub max_ccd_substeps: usize,
299    /// If enabled, contact manifolds of a collider pair sharing (nearly) the same normal are merged
300    /// into one "cluster" manifold before constraint generation (default: `true`, 3D only), so at
301    /// most 4 contact points are solved per contact plane — a large solver win on composite shapes
302    /// (meshes, heightfields, compounds, voxels) that emit one manifold per subshape. When clustering
303    /// applies, read solver contacts/impulses from [`crate::geometry::RigidPairContacts::solver_clusters`],
304    /// not [`crate::geometry::ContactPair::manifolds`].
305    pub contact_clustering: bool,
306    /// If enabled, a contact pair whose relative pose moved less than [`Self::contact_recycle_distance`]
307    /// since its last full narrow-phase update skips contact determination and keeps its existing points
308    /// (default: `true`) — a large speed-up for quasi-static scenes. Trade-offs:
309    /// contact features and user-facing contact data (`dist`, is-new bits) may be stale by up to that
310    /// distance, and per-step joint-based contact filtering is skipped until the pair moves.
311    /// [`crate::pipeline::ActiveHooks`] pairs are never recycled.
312    pub contact_recycling: bool,
313    /// Maximum relative-pose drift (translation plus rotation-arc) below which a contact pair may
314    /// be recycled instead of fully updated (default: `0.05`, i.e. ten times the linear slop,
315    /// multiplied by [`Self::length_unit`]). Only used when [`Self::contact_recycling`] is enabled.
316    pub normalized_contact_recycle_distance: Real,
317    /// If `false`, friction is only solved during the unbiased (relax) pass of each substep instead
318    /// of both passes (default: `false`, the "no friction when applying bias" rule).
319    /// This makes contact kernels much cheaper and is load-bearing for tall stacks: friction
320    /// reacting to bias velocities pumps their coherent lean mode until they topple. If
321    /// [`Self::num_internal_stabilization_iterations`] is zero there is no unbiased pass and this flag is ignored.
322    pub friction_in_bias_pass: bool,
323    /// If enabled, impulse-joint constraints are warm-started like contacts: impulses accumulated
324    /// by the previous step are re-applied (scaled by [`Self::warmstart_coefficient`]) at the start
325    /// of each substep instead of restarting from zero (default: `false`). This
326    /// noticeably improves convergence of stiff joint assemblies. Multibody joints are unaffected.
327    pub warmstart_joints: bool,
328    /// The type of friction constraints used in the simulation.
329    #[cfg(feature = "dim3")]
330    pub friction_model: FrictionModel,
331}
332
333impl IntegrationParameters {
334    /// The inverse of the time-stepping length, i.e. the steps per seconds (Hz).
335    ///
336    /// This is zero if `self.dt` is zero.
337    #[inline]
338    pub fn inv_dt(&self) -> Real {
339        if self.dt == 0.0 { 0.0 } else { 1.0 / self.dt }
340    }
341
342    /// Sets the time-stepping length.
343    #[inline]
344    #[deprecated = "You can just set the `IntegrationParams::dt` value directly"]
345    pub fn set_dt(&mut self, dt: Real) {
346        assert!(dt >= 0.0, "The time-stepping length cannot be negative.");
347        self.dt = dt;
348    }
349
350    /// Sets the inverse time-stepping length (i.e. the frequency).
351    ///
352    /// This automatically recompute `self.dt`.
353    #[inline]
354    pub fn set_inv_dt(&mut self, inv_dt: Real) {
355        if inv_dt == 0.0 {
356            self.dt = 0.0
357        } else {
358            self.dt = 1.0 / inv_dt
359        }
360    }
361
362    /// Amount of penetration the engine won't attempt to correct (default: `0.001` multiplied by
363    /// [`Self::length_unit`]).
364    pub fn allowed_linear_error(&self) -> Real {
365        self.normalized_allowed_linear_error * self.length_unit
366    }
367
368    /// Maximum amount of penetration the solver will attempt to resolve in one timestep.
369    ///
370    /// This is equal to [`Self::normalized_max_corrective_velocity`] multiplied by
371    /// [`Self::length_unit`].
372    pub fn max_corrective_velocity(&self) -> Real {
373        if self.normalized_max_corrective_velocity != Real::MAX {
374            self.normalized_max_corrective_velocity * self.length_unit
375        } else {
376            Real::MAX
377        }
378    }
379
380    /// The maximal distance separating two objects that will generate predictive contacts
381    /// (default: `0.02` multiplied by [`Self::length_unit`]).
382    pub fn prediction_distance(&self) -> Real {
383        self.normalized_prediction_distance * self.length_unit
384    }
385
386    /// Maximum linear velocity a body may have after each solver substep.
387    ///
388    /// This is equal to [`Self::normalized_max_linear_velocity`] multiplied by
389    /// [`Self::length_unit`], or `Real::MAX` when the linear speed cap is disabled.
390    pub fn max_linear_velocity(&self) -> Real {
391        if self.normalized_max_linear_velocity != Real::MAX {
392            self.normalized_max_linear_velocity * self.length_unit
393        } else {
394            Real::MAX
395        }
396    }
397
398    /// Maximum relative-pose drift below which a contact pair can be recycled instead of fully
399    /// updated: [`Self::normalized_contact_recycle_distance`] multiplied by [`Self::length_unit`].
400    /// Only used when [`Self::contact_recycling`] is enabled.
401    pub fn contact_recycle_distance(&self) -> Real {
402        self.normalized_contact_recycle_distance * self.length_unit
403    }
404}
405
406impl Default for IntegrationParameters {
407    fn default() -> Self {
408        Self {
409            dt: 1.0 / 60.0,
410            min_ccd_dt: 1.0 / 60.0 / 100.0,
411            contact_softness: SpringCoefficients::contact_defaults(),
412            static_contact_softness: SpringCoefficients::contact_static_defaults(),
413            warmstart_coefficient: 1.0,
414            num_internal_pgs_iterations: 1,
415            num_internal_stabilization_iterations: 1,
416            num_solver_iterations: 4,
417            normalized_allowed_linear_error: 0.005,
418            normalized_max_corrective_velocity: 3.0,
419            // Four times the linear slop. A larger speculative
420            // margin generates contacts earlier, which (together with oriented/one-sided static
421            // geometry) keeps fast/piled bodies from tunneling through thin walls.
422            normalized_prediction_distance: 0.02,
423            normalized_max_linear_velocity: 400.0,
424            max_ccd_substeps: 1,
425            contact_clustering: true,
426            contact_recycling: true,
427            normalized_contact_recycle_distance: 0.05,
428            friction_in_bias_pass: false,
429            warmstart_joints: false,
430            length_unit: 1.0,
431            #[cfg(feature = "alloc")]
432            soft_bodies: Default::default(),
433            #[cfg(feature = "dim3")]
434            friction_model: FrictionModel::default(),
435        }
436    }
437}