rocketsim 0.3.6

Simulate Rocket League games at maximum efficiency
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not};

use glam::{Affine3A, Mat3A, Quat, Vec3A};

use crate::{
    bullet::{
        collision::{
            narrowphase::persistent_manifold::CONTACT_BREAKING_THRESHOLD,
            shapes::collision_shape::CollisionShapes,
        },
        linear_math::{bullet_quat_from_basis_columns, integrate_trans, integrate_trans_no_rot},
    },
    shared::math::powf,
    sim::UserInfoType,
};

pub struct RigidBodyConstructionInfo {
    pub mass: f32,
    pub start_world_trans: Affine3A,
    pub collision_shape: CollisionShapes,
    pub local_inertia: Vec3A,
    pub linear_damping: f32,
    pub friction: f32,
    pub restitution: f32,
    pub linear_sleeping_threshold: f32,
    pub angular_sleeping_threshold: f32,
}

pub(crate) struct RigidBodyUpdateInfo {
    pub shape: CollisionShapes,
    pub mass: f32,
    pub local_inertia: Vec3A,
    pub friction: f32,
    pub restitution: f32,
    pub linear_damping: f32,
    pub invalidate_contacts: bool,
}

impl RigidBodyConstructionInfo {
    pub const fn new(mass: f32, collision_shape: CollisionShapes) -> Self {
        Self {
            mass,
            collision_shape,
            local_inertia: Vec3A::ZERO,
            linear_damping: 0.0,
            friction: 0.5,
            restitution: 0.0,
            linear_sleeping_threshold: 0.0,
            angular_sleeping_threshold: 1.0,
            start_world_trans: Affine3A::IDENTITY,
        }
    }
}

/// Controls whether a body participates in motion integration.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ActivationState {
    /// The body is active. This is the default state.
    #[default]
    Active,
    /// The body is asleep. A collision can activate it.
    Sleeping,
    /// Motion integration is disabled. Demoed cars use this state.
    DisableSimulation,
    /// The body remains active while its simulation island waits for sleep.
    WantsDeactivation,
}

pub enum CollisionFlags {
    StaticObject = 1,
    CustomMaterialCallback = (1 << 1),
    CanSleep = (1 << 2),
    NoContactResponse = (1 << 3),
    NoWorldGravity = (1 << 4),
    /// Keep the world matrix and quaternion at identity. Keep angular velocity.
    /// Transform setters ignore supplied rotations when this bit is set.
    NoAngularMotion = (1 << 5),
    /// The world matrix is identity and its translation is zero.
    /// Transform setters maintain this bit. Signed zeros compare equal.
    IdentityTransform = (1 << 6),
}

impl BitOrAssign<CollisionFlags> for u8 {
    fn bitor_assign(&mut self, rhs: CollisionFlags) {
        *self |= rhs as u8;
    }
}

impl BitAndAssign<CollisionFlags> for u8 {
    fn bitand_assign(&mut self, rhs: CollisionFlags) {
        *self &= rhs as u8;
    }
}

impl BitAnd<CollisionFlags> for u8 {
    type Output = u8;

    fn bitand(self, rhs: CollisionFlags) -> Self::Output {
        self & (rhs as u8)
    }
}

impl BitOr<CollisionFlags> for u8 {
    type Output = u8;

    fn bitor(self, rhs: CollisionFlags) -> Self::Output {
        self | (rhs as u8)
    }
}

impl BitXor<CollisionFlags> for u8 {
    type Output = u8;

    fn bitxor(self, rhs: CollisionFlags) -> Self::Output {
        self ^ (rhs as u8)
    }
}

impl BitOr for CollisionFlags {
    type Output = u8;

    fn bitor(self, rhs: Self) -> Self::Output {
        self as u8 | rhs as u8
    }
}

impl BitXorAssign<CollisionFlags> for u8 {
    fn bitxor_assign(&mut self, rhs: CollisionFlags) {
        *self ^= rhs as u8;
    }
}

impl Not for CollisionFlags {
    type Output = u8;

    fn not(self) -> Self::Output {
        !(self as u8)
    }
}

#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Impulse {
    /// (lin_impulse)
    Linear(Vec3A),
    /// (lin_impulse, rel_pos_offset)
    LinearRelPos(Vec3A, Vec3A),
    /// (ang_impulse)
    Angular(Vec3A),
}

#[derive(Clone)]
pub struct RigidBody {
    world_trans: Affine3A,
    world_quat: Quat,
    shape: CollisionShapes,
    activation: ActivationState,
    broadphase_handle: usize,

    pub interp_world_trans: Affine3A,
    pub contact_processing_threshold: f32,
    /// Cached shape breaking threshold (`angular_disc * 0.02`).
    /// Refresh this value when physical properties replace the shape.
    /// Read it via [`get_contact_breaking_threshold`](Self::get_contact_breaking_threshold).
    contact_breaking_threshold: f32,

    /// Preserve `IdentityTransform` when changing collision settings.
    /// Enable `NoAngularMotion` only with an identity matrix and quaternion.
    /// Transform setters maintain `IdentityTransform`.
    pub collision_flags: u8,
    pub companion_id: Option<usize>,
    /// The index of this object in `CollisionWorld`
    pub world_array_idx: usize,
    pub deactivation_time: f32,
    pub friction: f32,
    pub restitution: f32,
    pub user_pointer: usize,
    pub user_idx: UserInfoType,

    pub inv_inertia_tensor_world: Mat3A,
    pub lin_vel: Vec3A,
    pub ang_vel: Vec3A,
    pub mass: f32,
    pub inv_mass: f32,
    pub inv_inertia_local: Vec3A,

    pub accum_lin_vel: Vec3A,
    pub accum_ang_vel: Vec3A,

    pub linear_damping: f32,
    /// Cached `(1 - linear_damping)^time_step` for the repeated fixed tick.
    cached_linear_damping: f32,
    cached_damping_time_step: f32,
    cached_linear_damping_value: f32,
    pub linear_sleeping_threshold: f32,
    pub angular_sleeping_threshold: f32,
    pub inv_mass_splat: Vec3A,
}

impl RigidBody {
    pub fn new(info: RigidBodyConstructionInfo) -> Self {
        let (inverse_mass, mut collision_flags) = if info.mass == 0.0 {
            (0.0, CollisionFlags::StaticObject as u8)
        } else {
            (1.0 / info.mass, 0)
        };

        if info.start_world_trans.matrix3 == Mat3A::IDENTITY {
            if info.mass == 0.0 {
                collision_flags |= CollisionFlags::NoAngularMotion;
            }

            if info.start_world_trans.translation == Vec3A::ZERO {
                collision_flags |= CollisionFlags::IdentityTransform;
            }
        }

        let linear_damping = info.linear_damping.clamp(0.0, 1.0);
        let linear_sleeping_threshold = info.linear_sleeping_threshold;
        let angular_sleeping_threshold = info.angular_sleeping_threshold;

        let inv_inertia_local = Vec3A::select(
            info.local_inertia.cmpeq(Vec3A::ZERO),
            Vec3A::ZERO,
            1.0 / info.local_inertia,
        );

        let inv_inertia_tensor_world =
            Self::get_inertia_tensor(info.start_world_trans.matrix3, inv_inertia_local);

        // Cache the angular-disc threshold for manifold creation.
        let contact_breaking_threshold = info
            .collision_shape
            .get_contact_breaking_threshold(CONTACT_BREAKING_THRESHOLD);

        Self {
            world_trans: info.start_world_trans,
            world_quat: bullet_quat_from_basis_columns(
                info.start_world_trans.matrix3.x_axis,
                info.start_world_trans.matrix3.y_axis,
                info.start_world_trans.matrix3.z_axis,
            ),
            interp_world_trans: info.start_world_trans,
            contact_processing_threshold: f32::MAX,
            contact_breaking_threshold,
            broadphase_handle: 0,
            shape: info.collision_shape,
            collision_flags,
            companion_id: None,
            world_array_idx: 0,
            activation: ActivationState::Active,
            deactivation_time: 0.0,
            friction: info.friction,
            restitution: info.restitution,
            user_pointer: 0,
            user_idx: UserInfoType::default(),
            inv_inertia_tensor_world,
            lin_vel: Vec3A::ZERO,
            ang_vel: Vec3A::ZERO,
            mass: info.mass,
            inv_mass: inverse_mass,
            inv_inertia_local,
            accum_lin_vel: Vec3A::ZERO,
            accum_ang_vel: Vec3A::ZERO,
            linear_damping,
            cached_linear_damping: 1.0,
            cached_damping_time_step: 0.0,
            cached_linear_damping_value: linear_damping,
            linear_sleeping_threshold,
            angular_sleeping_threshold,
            inv_mass_splat: Vec3A::splat(inverse_mass),
        }
    }

    /// Cached breaking threshold for this body's current shape (see field docs).
    #[inline]
    pub const fn get_contact_breaking_threshold(&self) -> f32 {
        self.contact_breaking_threshold
    }

    /// Assert that an inserted static body does not change transform.
    ///
    /// A static proxy AABB is final after `CollisionWorld::add_collision_obj`
    /// assigns a broadphase handle. The `bullet` module is private, and the
    /// public `Arena` API exposes no mutable static body. Internal setup code
    /// must set `start_world_trans` before insertion.
    #[inline]
    fn assert_static_transform_unchanged(&self, world_trans: &Affine3A) {
        assert!(
            !self.is_static_obj()
                || self.broadphase_handle == 0
                || *world_trans == self.world_trans,
            "static collision object {} changed its world transform after broadphase insertion; its proxy AABB would be stale",
            self.world_array_idx
        );
    }

    /// Set the world transform.
    /// Ignore rotation when `NoAngularMotion` is set. Keep angular velocity.
    ///
    /// # Panics
    ///
    /// Panics when this is a static body with a broadphase handle and the new
    /// transform differs from the cached transform.
    pub fn set_world_trans(&mut self, mut world_trans: Affine3A) {
        let world_quat = if self.collision_flags & CollisionFlags::NoAngularMotion != 0 {
            world_trans.matrix3 = Mat3A::IDENTITY;
            Quat::IDENTITY
        } else {
            bullet_quat_from_basis_columns(
                world_trans.matrix3.x_axis,
                world_trans.matrix3.y_axis,
                world_trans.matrix3.z_axis,
            )
        };
        self.assert_static_transform_unchanged(&world_trans);

        self.world_quat = world_quat;
        self.world_trans = world_trans;
        self.update_transform_flags();
    }

    #[inline]
    fn update_transform_flags(&mut self) {
        debug_assert!(
            self.collision_flags & CollisionFlags::NoAngularMotion == 0
                || self.world_trans.matrix3 == Mat3A::IDENTITY,
            "NoAngularMotion requires an identity world matrix"
        );
        self.collision_flags &= !CollisionFlags::IdentityTransform;
        if self.world_trans.translation == Vec3A::ZERO
            && (self.collision_flags & CollisionFlags::NoAngularMotion != 0
                || self.world_trans.matrix3 == Mat3A::IDENTITY)
        {
            self.collision_flags |= CollisionFlags::IdentityTransform;
        }
    }

    pub const fn get_world_trans(&self) -> &Affine3A {
        &self.world_trans
    }

    pub const fn get_world_rot(&self) -> Quat {
        self.world_quat
    }

    /// Set the world transform and its matching cached quaternion.
    ///
    /// The caller must supply a quaternion that describes the matrix.
    /// This avoids a matrix conversion when the quaternion is already known.
    /// Ignore both rotations when `NoAngularMotion` is set.
    ///
    /// # Panics
    ///
    /// Panics when an inserted static body changes its transform.
    pub(crate) fn set_world_trans_and_rot(&mut self, mut world_trans: Affine3A, mut quat: Quat) {
        if self.collision_flags & CollisionFlags::NoAngularMotion != 0 {
            world_trans.matrix3 = Mat3A::IDENTITY;
            quat = Quat::IDENTITY;
        }
        self.assert_static_transform_unchanged(&world_trans);
        self.world_trans = world_trans;
        self.world_quat = quat;
        self.update_transform_flags();
    }

    pub const fn get_collision_shape(&self) -> &CollisionShapes {
        &self.shape
    }

    pub fn is_static_obj(&self) -> bool {
        (self.collision_flags & CollisionFlags::StaticObject) != 0
    }

    pub const fn is_active(&self) -> bool {
        !matches!(
            self.activation,
            ActivationState::Sleeping | ActivationState::DisableSimulation
        )
    }

    pub fn has_contact_response(&self) -> bool {
        self.collision_flags & CollisionFlags::NoContactResponse == 0
    }

    pub fn set_activation_state(&mut self, new_state: ActivationState) {
        if self.activation != ActivationState::DisableSimulation {
            self.activation = new_state;
        }
    }

    pub(crate) fn update_physical_properties(&mut self, properties: RigidBodyUpdateInfo) {
        self.shape = properties.shape;
        self.mass = properties.mass;
        self.inv_mass = if properties.mass == 0.0 {
            0.0
        } else {
            1.0 / properties.mass
        };
        self.inv_mass_splat = Vec3A::splat(self.inv_mass);
        self.inv_inertia_local = Vec3A::select(
            properties.local_inertia.cmpeq(Vec3A::ZERO),
            Vec3A::ZERO,
            1.0 / properties.local_inertia,
        );
        self.update_inertia_tensor();
        self.contact_breaking_threshold = self
            .shape
            .get_contact_breaking_threshold(CONTACT_BREAKING_THRESHOLD);
        self.friction = properties.friction;
        self.restitution = properties.restitution;
        self.linear_damping = properties.linear_damping.clamp(0.0, 1.0);
        self.cached_damping_time_step = 0.0;
        self.cached_linear_damping_value = self.linear_damping;
        self.clear_accum_vels();
        self.force_activate();
    }

    pub const fn force_activate(&mut self) {
        self.activation = ActivationState::Active;
        self.deactivation_time = 0.0;
    }

    pub const fn set_broadphase_handle(&mut self, handle: usize) {
        self.broadphase_handle = handle;
    }

    pub const fn get_broadphase_handle(&self) -> usize {
        self.broadphase_handle
    }

    pub fn set_lin_vel(&mut self, lin_vel: Vec3A) {
        debug_assert!(!lin_vel.is_nan());
        self.lin_vel = lin_vel;
    }

    pub fn set_ang_vel(&mut self, ang_vel: Vec3A) {
        debug_assert!(!ang_vel.is_nan());
        self.ang_vel = ang_vel;
    }

    fn get_inertia_tensor(world_mat: Mat3A, inv_inertia_local: Vec3A) -> Mat3A {
        let mut scaled_mat = world_mat.transpose();
        scaled_mat.x_axis *= inv_inertia_local;
        scaled_mat.y_axis *= inv_inertia_local;
        scaled_mat.z_axis *= inv_inertia_local;

        world_mat * scaled_mat
    }

    pub fn update_inertia_tensor(&mut self) {
        self.inv_inertia_tensor_world =
            Self::get_inertia_tensor(self.get_world_trans().matrix3, self.inv_inertia_local);
    }

    /// Add an impulse of a given type
    ///
    /// `massed`: Scale down by `self.inv_mass`
    ///
    /// `accum`: Accumulate this impulse to be applied while
    /// stepping the simulation (instead of immediately)
    #[inline(always)] // Should assure const evaluation
    pub fn add_impulse(&mut self, impulse: Impulse, massed: bool, accum: bool) {
        let mut lin_impulse = Vec3A::ZERO;
        let mut ang_impulse = Vec3A::ZERO;

        let massed_scaler = if massed { self.inv_mass } else { 1.0 };
        match impulse {
            Impulse::Linear(v) => {
                lin_impulse = v * massed_scaler;
            }
            Impulse::LinearRelPos(v, rel_pos) => {
                lin_impulse = v * massed_scaler;
                ang_impulse = self.inv_inertia_tensor_world * rel_pos.cross(v);
                if !massed {
                    ang_impulse *= self.mass; // Have to undo the effects of inv inertia tensor
                }
            }
            Impulse::Angular(av) => {
                ang_impulse = av * massed_scaler;
            }
        };

        if accum {
            self.accum_lin_vel += lin_impulse;
            self.accum_ang_vel += ang_impulse;
        } else {
            self.lin_vel += lin_impulse;
            self.ang_vel += ang_impulse;
        }
    }

    pub fn apply_damping(&mut self, time_step: f32) {
        if self.linear_damping != 0.0 {
            if self.cached_damping_time_step != time_step
                || self.cached_linear_damping_value != self.linear_damping
            {
                self.cached_linear_damping = powf((1.0 - self.linear_damping).max(0.0), time_step);
                self.cached_damping_time_step = time_step;
                self.cached_linear_damping_value = self.linear_damping;
            }

            self.lin_vel *= self.cached_linear_damping;
        }
    }

    #[inline]
    pub fn predict_integration_trans(&self, time_step: f32) -> Affine3A {
        self.predict_integration_trans_and_rot(time_step).0
    }

    /// Predict the transform and the matching orientation.
    ///
    /// `time_step` is in seconds. Keep the returned values together.
    /// Converting the matrix back to a quaternion can discard low bits of
    /// the integrated orientation.
    #[inline]
    pub(crate) fn predict_integration_trans_and_rot(&self, time_step: f32) -> (Affine3A, Quat) {
        let mut trans = self.world_trans;
        let mut quat = self.world_quat;

        if (self.collision_flags & CollisionFlags::NoAngularMotion) != 0 {
            integrate_trans_no_rot(&mut trans.translation, self.lin_vel, time_step);
        } else {
            integrate_trans(&mut trans, &mut quat, self.lin_vel, self.ang_vel, time_step);
        }

        (trans, quat)
    }

    /// Set the center-of-mass transform and its matching orientation.
    ///
    /// Use this form when the caller already has the exact integrated
    /// quaternion. It keeps the quaternion and the matrix coherent.
    pub(crate) fn set_center_of_mass_trans_and_rot(&mut self, xform: Affine3A, quat: Quat) {
        self.set_world_trans_and_rot(xform, quat);
        self.interp_world_trans = self.world_trans;

        self.update_inertia_tensor();
    }

    pub fn get_vel_in_local_point(&self, rel_pos: Vec3A) -> Vec3A {
        self.lin_vel + self.ang_vel.cross(rel_pos)
    }

    pub fn update_activation_state(&mut self, time_step: f32) {
        if self.collision_flags & CollisionFlags::CanSleep == 0 {
            self.set_activation_state(ActivationState::Active);
            return;
        }

        if self.activation == ActivationState::Sleeping {
            return;
        }

        let lin_thresh_sq = self.linear_sleeping_threshold * self.linear_sleeping_threshold;
        let ang_thresh_sq = self.angular_sleeping_threshold * self.angular_sleeping_threshold;
        let within_sleep_thresh = self.lin_vel.length_squared() < lin_thresh_sq
            && self.ang_vel.length_squared() < ang_thresh_sq;

        if within_sleep_thresh {
            self.deactivation_time += time_step;
            if self.deactivation_time > 2.0 && self.activation == ActivationState::Active {
                self.set_activation_state(ActivationState::WantsDeactivation);
            }
        } else {
            self.deactivation_time = 0.0;
            self.set_activation_state(ActivationState::Active);
        }
    }

    pub(crate) const fn activation_state(&self) -> ActivationState {
        self.activation
    }

    /// Set the activation state without the `DisableSimulation` guard.
    ///
    /// Use this to restore an exact captured state. It does not change the
    /// velocity or the deactivation timer.
    pub(crate) fn restore_activation_state(&mut self, state: ActivationState) {
        self.activation = state;
    }

    pub(crate) fn sleep(&mut self) {
        self.set_activation_state(ActivationState::Sleeping);
        self.lin_vel = Vec3A::ZERO;
        self.ang_vel = Vec3A::ZERO;
    }

    pub fn clear_accum_vels(&mut self) {
        self.accum_lin_vel = Vec3A::ZERO;
        self.accum_ang_vel = Vec3A::ZERO;
    }

    pub fn get_mass(&self) -> f32 {
        if self.inv_mass == 0.0 {
            0.0
        } else {
            1.0 / self.inv_mass
        }
    }

    pub fn compute_impulse_denominator(&self, pos: Vec3A, normal: Vec3A) -> f32 {
        let r0 = pos - self.get_world_trans().translation;
        let c0 = r0.cross(normal);
        let vec = self
            .inv_inertia_tensor_world
            .transpose_mul_vec3a(c0)
            .cross(r0);

        self.inv_mass + normal.dot(vec)
    }

    pub const fn get_up_vector(&self) -> Vec3A {
        self.get_world_trans().matrix3.z_axis
    }

    pub const fn get_forward_vector(&self) -> Vec3A {
        self.get_world_trans().matrix3.x_axis
    }

    pub fn get_forward_speed(&self) -> f32 {
        self.lin_vel.dot(self.get_forward_vector())
    }

    pub const fn get_world_pos(&self) -> Vec3A {
        self.get_world_trans().translation
    }

    /// Set the world translation.
    ///
    /// # Panics
    ///
    /// Panics when this is a static body with a broadphase handle and the new
    /// position differs from the cached position.
    pub fn set_world_pos(&mut self, pos: Vec3A) {
        let mut world_trans = self.world_trans;
        world_trans.translation = pos;
        self.assert_static_transform_unchanged(&world_trans);
        self.world_trans.translation = pos;
        self.update_transform_flags();
    }

    pub fn limit_vels(&mut self, max_lin_speed: f32, max_ang_speed: f32) {
        if self.lin_vel.length_squared() > max_lin_speed.powi(2) {
            self.lin_vel = self.lin_vel.normalize_or_zero() * max_lin_speed;
        }

        if self.ang_vel.length_squared() > max_ang_speed.powi(2) {
            self.ang_vel = self.ang_vel.normalize_or_zero() * max_ang_speed;
        }
    }
}