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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
//! Common components and bundles for rigid bodies.

// Components
mod forces;
mod locked_axes;
mod mass_properties;
mod world_query;

pub use forces::{ExternalAngularImpulse, ExternalForce, ExternalImpulse, ExternalTorque};
pub use locked_axes::LockedAxes;
pub use mass_properties::*;
pub use world_query::*;

#[cfg(feature = "2d")]
pub(crate) use forces::FloatZero;
pub(crate) use forces::Torque;

use crate::prelude::*;
use bevy::prelude::*;
use derive_more::From;

/// A non-deformable body used for the simulation of most physics objects.
///
/// ## Rigid body types
///
/// A rigid body can be either dynamic, kinematic or static.
///
/// - **Dynamic bodies** are similar to real life objects and are affected by forces and contacts.
/// - **Kinematic bodies** can only be moved programmatically, which is useful for things like character controllers and moving platforms.
/// - **Static bodies** can not move, so they can be good for objects in the environment like the ground and walls.
///
/// ## Creation
///
/// Creating a rigid body is as simple as adding the [`RigidBody`] component:
///
/// ```
#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
/// use bevy::prelude::*;
///
/// fn setup(mut commands: Commands) {
///     // Spawn a dynamic rigid body and specify its position (optional)
///     commands.spawn((
///         RigidBody::Dynamic,
///         TransformBundle::from_transform(Transform::from_xyz(0.0, 3.0, 0.0)),
///     ));
/// }
/// ```
///
/// Avian will automatically add any missing components, like the following:
///
/// - [`Position`]
/// - [`Rotation`]
/// - [`LinearVelocity`]
/// - [`AngularVelocity`]
/// - [`ExternalForce`]
/// - [`ExternalTorque`]
/// - [`ExternalImpulse`]
/// - [`ExternalAngularImpulse`]
/// - [`Friction`]
/// - [`Restitution`]
/// - [`Mass`]
/// - [`Inertia`]
/// - [`CenterOfMass`]
///
/// You can change any of these during initialization and runtime in order to alter the behaviour of the body.
///
/// By default, rigid bodies will get a mass based on the attached colliders and their densities.
/// See [mass properties](#mass-properties).
///
/// ## Movement
///
/// A rigid body can be moved in three ways: by modifying its position directly,
/// by changing its velocity, or by applying forces or impulses.
///
/// To change the position of a rigid body, you can simply modify its `Transform`:
///
/// ```
#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
/// use bevy::prelude::*;
///
/// fn move_bodies(mut query: Query<&mut Transform, With<RigidBody>>) {
///     for mut transform in query.iter_mut() {
///         transform.translation.x += 0.1;
///     }
/// }
/// ```
///
/// However, moving a dynamic body by changing its position directly is similar
/// to teleporting the body, which can result in unexpected behavior since the body can move
/// inside walls.
///
/// You can instead change the velocity of a dynamic or kinematic body with the [`LinearVelocity`]
/// and [`AngularVelocity`] components:
///
/// ```
#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
/// use bevy::prelude::*;
///
/// fn accelerate_bodies(mut query: Query<(&mut LinearVelocity, &mut AngularVelocity)>) {
///     for (mut linear_velocity, mut angular_velocity) in query.iter_mut() {
///         linear_velocity.x += 0.05;
#[cfg_attr(feature = "2d", doc = "        angular_velocity.0 += 0.05;")]
#[cfg_attr(feature = "3d", doc = "        angular_velocity.z += 0.05;")]
///     }
/// }
/// ```
///
/// For applying forces and impulses to dynamic bodies, see the [`ExternalForce`], [`ExternalTorque`],
/// [`ExternalImpulse`] and [`ExternalAngularImpulse`] components.
///
/// Avian does not have a built-in character controller, so if you need one,
/// you will need to implement it yourself or use a third party option.
/// You can take a look at the [`basic_dynamic_character`] and [`basic_kinematic_character`]
/// examples for a simple implementation.
///
/// [`basic_dynamic_character`]: https://github.com/Jondolf/avian/blob/42fb8b21c756a7f4dd91071597dc251245ddaa8f/crates/avian3d/examples/basic_dynamic_character.rs
/// [`basic_kinematic_character`]: https://github.com/Jondolf/avian/blob/42fb8b21c756a7f4dd91071597dc251245ddaa8f/crates/avian3d/examples/basic_kinematic_character.rs
///
/// ## Mass properties
///
/// The mass properties of a rigid body consist of its [`Mass`], [`Inertia`]
/// and local [`CenterOfMass`]. They control how forces and torques impact a rigid body
/// and how it affects other bodies.
///
/// You should always give dynamic rigid bodies mass properties so that forces
/// are applied to them correctly. The easiest way to do that is to simply [add a collider](Collider):
///
/// ```
#[cfg_attr(feature = "2d", doc = "# use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "# use avian3d::prelude::*;")]
/// # use bevy::prelude::*;
/// #
/// # fn setup(mut commands: Commands) {
#[cfg_attr(
    feature = "2d",
    doc = "commands.spawn((RigidBody::Dynamic, Collider::circle(0.5)));"
)]
#[cfg_attr(
    feature = "3d",
    doc = "commands.spawn((RigidBody::Dynamic, Collider::sphere(0.5)));"
)]
/// # }
/// ```
///
/// This will automatically compute the [collider's mass properties](ColliderMassProperties)
/// and add them to the body's own mass properties.
///
/// By default, each collider has a density of `1.0`. This can be configured with
/// the [`ColliderDensity`] component:
///
/// ```
#[cfg_attr(feature = "2d", doc = "# use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "# use avian3d::prelude::*;")]
/// # use bevy::prelude::*;
/// #
/// # fn setup(mut commands: Commands) {
/// commands.spawn((
///     RigidBody::Dynamic,
#[cfg_attr(feature = "2d", doc = "    Collider::circle(0.5),")]
#[cfg_attr(feature = "3d", doc = "    Collider::sphere(0.5),")]
///     ColliderDensity(2.5),
/// ));
/// # }
/// ```
///
/// If you don't want to add a collider, you can instead add a [`MassPropertiesBundle`]
/// with the mass properties computed from a collider shape using the
/// [`MassPropertiesBundle::new_computed`](MassPropertiesBundle::new_computed) method.
///
/// ```
#[cfg_attr(feature = "2d", doc = "# use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "# use avian3d::prelude::*;")]
/// # use bevy::prelude::*;
/// #
/// # fn setup(mut commands: Commands) {
/// // This is equivalent to the earlier approach, but no collider will be added
/// commands.spawn((
///     RigidBody::Dynamic,
#[cfg_attr(
    feature = "2d",
    doc = "    MassPropertiesBundle::new_computed(&Collider::circle(0.5), 2.5),"
)]
#[cfg_attr(
    feature = "3d",
    doc = "    MassPropertiesBundle::new_computed(&Collider::sphere(0.5), 2.5),"
)]
/// ));
/// # }
/// ```
///
/// You can also specify the exact values of the mass properties by adding the components manually.
/// To avoid the collider mass properties from being added to the body's own mass properties,
/// you can simply set the collider's density to zero.
///
/// ```
#[cfg_attr(feature = "2d", doc = "# use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "# use avian3d::prelude::*;")]
/// # use bevy::prelude::*;
/// #
/// # fn setup(mut commands: Commands) {
/// // Create a rigid body with a mass of 5.0 and a collider with no mass
/// commands.spawn((
///     RigidBody::Dynamic,
#[cfg_attr(feature = "2d", doc = "    Collider::circle(0.5),")]
#[cfg_attr(feature = "3d", doc = "    Collider::sphere(0.5),")]
///     ColliderDensity(0.0),
///     Mass(5.0),
///     // ...the rest of the mass properties
/// ));
/// # }
///
/// ```
///
/// ## See more
///
/// - [Colliders](Collider)
/// - [Gravity] and [gravity scale](GravityScale)
/// - [Linear](LinearDamping) and [angular](AngularDamping) velocity damping
/// - [Lock translational and rotational axes](LockedAxes)
/// - [Dominance]
/// - [Continuous Collision Detection](dynamics::ccd)
/// - [Automatic deactivation with sleeping](Sleeping)
#[derive(Reflect, Clone, Copy, Component, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Debug, Component, Default, PartialEq)]
pub enum RigidBody {
    /// Dynamic bodies are bodies that are affected by forces, velocity and collisions.
    #[default]
    Dynamic,

    /// Static bodies are not affected by any forces, collisions or velocity, and they act as if they have an infinite mass and moment of inertia.
    /// The only way to move a static body is to manually change its position.
    ///
    /// Collisions with static bodies will affect dynamic bodies, but not other static bodies or kinematic bodies.
    ///
    /// Static bodies are typically used for things like the ground, walls and any other objects that you don't want to move.
    Static,

    /// Kinematic bodies are bodies that are not affected by any external forces or collisions.
    /// They will realistically affect colliding dynamic bodies, but not other kinematic bodies.
    ///
    /// Unlike static bodies, kinematic bodies can have velocity.
    /// The engine doesn't modify the values of a kinematic body's components,
    /// so you have full control of them.
    Kinematic,
}

impl RigidBody {
    /// Checks if the rigid body is dynamic.
    pub fn is_dynamic(&self) -> bool {
        *self == Self::Dynamic
    }

    /// Checks if the rigid body is static.
    pub fn is_static(&self) -> bool {
        *self == Self::Static
    }

    /// Checks if the rigid body is kinematic.
    pub fn is_kinematic(&self) -> bool {
        *self == Self::Kinematic
    }
}

/// Indicates that a [rigid body](RigidBody) is not simulated by the physics engine until woken up again.
/// This is done to improve performance and to help prevent small jitter that is typically present in collisions.
///
/// Bodies are marked as sleeping when their linear and angular velocity is below the [`SleepingThreshold`] for a time
/// indicated by [`DeactivationTime`]. A sleeping body is woken up when an active body interacts with it through
/// collisions or other constraints, or when gravity changes, or when the body's
/// position, rotation, velocity, or external forces are modified.
///
/// Sleeping can be disabled for specific entities with the [`SleepingDisabled`] component,
/// or for all entities by setting the [`SleepingThreshold`] to a negative value.
#[derive(Reflect, Clone, Copy, Component, Debug, Default, PartialEq, Eq, From)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Debug, Component, Default, PartialEq)]
pub struct Sleeping;

/// How long the velocity of the body has been below the [`SleepingThreshold`],
/// i.e. how long the body has been able to sleep.
///
/// See [`Sleeping`] for further information.
#[derive(Reflect, Clone, Copy, Component, Debug, Default, PartialEq, From)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Debug, Component, Default, PartialEq)]
pub struct TimeSleeping(pub Scalar);

/// Indicates that the body can not be deactivated by the physics engine. See [`Sleeping`] for information about sleeping.
#[derive(Reflect, Clone, Copy, Component, Debug, Default, PartialEq, Eq, From)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Debug, Component, Default, PartialEq)]
pub struct SleepingDisabled;

/// Translation accumulated during the physics frame.
///
/// When updating position during integration or constraint solving, the required translation
/// is added to [`AccumulatedTranslation`], instead of [`Position`]. This improves numerical stability
/// of the simulation, especially for bodies far away from world origin.
///
/// At the end of each physics frame, the actual [`Position`] is updated in [`SolverSet::ApplyTranslation`].
#[derive(Reflect, Clone, Copy, Component, Debug, Default, Deref, DerefMut, PartialEq, From)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Debug, Component, Default, PartialEq)]
pub struct AccumulatedTranslation(pub Vector);

/// The linear velocity of a [rigid body](RigidBody).
///
/// ## Example
///
/// ```
#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
/// use bevy::prelude::*;
///
/// fn accelerate_bodies(mut query: Query<&mut LinearVelocity>) {
///     for mut linear_velocity in query.iter_mut() {
///         linear_velocity.x += 0.05;
///     }
/// }
/// ```
#[derive(Reflect, Clone, Copy, Component, Debug, Default, Deref, DerefMut, PartialEq, From)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Debug, Component, Default, PartialEq)]
pub struct LinearVelocity(pub Vector);

impl LinearVelocity {
    /// Zero linear velocity.
    pub const ZERO: LinearVelocity = LinearVelocity(Vector::ZERO);
}

/// The linear velocity of a [rigid body](RigidBody) before the velocity solve is performed.
#[derive(Reflect, Clone, Copy, Component, Debug, Default, Deref, DerefMut, PartialEq, From)]
#[reflect(Component)]
pub(crate) struct PreSolveLinearVelocity(pub Vector);

/// The angular velocity of a [rigid body](RigidBody) in radians per second.
/// Positive values will result in counterclockwise rotation.
///
/// ## Example
///
/// ```
/// use avian2d::prelude::*;
/// use bevy::prelude::*;
///
/// fn increase_angular_velocities(mut query: Query<&mut AngularVelocity>) {
///     for mut angular_velocity in query.iter_mut() {
///         angular_velocity.0 += 0.05;
///     }
/// }
/// ```
#[cfg(feature = "2d")]
#[derive(Reflect, Clone, Copy, Component, Debug, Default, PartialEq, From)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Debug, Component, Default, PartialEq)]
pub struct AngularVelocity(pub Scalar);

/// The angular velocity of a [rigid body](RigidBody) as a rotation axis
/// multiplied by the angular speed in radians per second.
///
/// ## Example
///
/// ```
/// use avian3d::prelude::*;
/// use bevy::prelude::*;
///
/// fn increase_angular_velocities(mut query: Query<&mut AngularVelocity>) {
///     for mut angular_velocity in query.iter_mut() {
///         angular_velocity.z += 0.05;
///     }
/// }
/// ```
#[cfg(feature = "3d")]
#[derive(Reflect, Clone, Copy, Component, Debug, Default, Deref, DerefMut, PartialEq, From)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Debug, Component, Default, PartialEq)]
pub struct AngularVelocity(pub Vector);

impl AngularVelocity {
    /// Zero angular velocity.
    #[cfg(feature = "2d")]
    pub const ZERO: AngularVelocity = AngularVelocity(0.0);
    /// Zero angular velocity.
    #[cfg(feature = "3d")]
    pub const ZERO: AngularVelocity = AngularVelocity(Vector::ZERO);
}

/// The angular velocity of a [rigid body](RigidBody) in radians per second, before
/// the velocity solve is performed. Positive values will result in counterclockwise rotation.
#[cfg(feature = "2d")]
#[derive(Reflect, Clone, Copy, Component, Debug, Default, PartialEq, From)]
#[reflect(Component)]
pub(crate) struct PreSolveAngularVelocity(pub Scalar);

/// The angular velocity of a [rigid body](RigidBody) as a rotation axis
/// multiplied by the angular speed in radians per second, before the velocity solve is performed.
#[cfg(feature = "3d")]
#[derive(Reflect, Clone, Copy, Component, Debug, Default, Deref, DerefMut, PartialEq, From)]
#[reflect(Component)]
pub(crate) struct PreSolveAngularVelocity(pub Vector);

/// Controls how [gravity](Gravity) affects a specific [rigid body](RigidBody).
///
/// A gravity scale of `0.0` will disable gravity, while `2.0` will double the gravity.
/// Using a negative value will flip the direction of the gravity.
///
/// ## Example
///
/// ```
#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
/// use bevy::prelude::*;
///
/// // Spawn a body with 1.5 times the normal gravity
/// fn setup(mut commands: Commands) {
///     commands.spawn((
///         RigidBody::Dynamic,
///         GravityScale(1.5),
///     ));
/// }
/// ```
#[derive(Component, Reflect, Debug, Clone, Copy, PartialEq, PartialOrd, Deref, DerefMut, From)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Debug, Component, Default, PartialEq)]
pub struct GravityScale(pub Scalar);

impl Default for GravityScale {
    fn default() -> Self {
        Self(1.0)
    }
}

/// Determines how coefficients are combined for [`Restitution`] and [`Friction`].
/// The default is `Average`.
///
/// When combine rules clash with each other, the following priority order is used:
/// `Max > Multiply > Min > Average`.
#[derive(Reflect, Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Debug, Default, PartialEq)]
pub enum CoefficientCombine {
    // The discriminants allow priority ordering to work automatically via comparison methods
    /// Coefficients are combined by computing their average.
    #[default]
    Average = 1,
    /// Coefficients are combined by choosing the smaller coefficient.
    Min = 2,
    /// Coefficients are combined by computing their product.
    Multiply = 3,
    /// Coefficients are combined by choosing the larger coefficient.
    Max = 4,
}

/// A component for the [coefficient of restitution](https://en.wikipedia.org/wiki/Coefficient_of_restitution).
/// This controls how bouncy a [rigid body](RigidBody) is.
///
/// The coefficient is between 0 and 1, where 0 corresponds to a **perfectly inelastic collision**, and 1 corresponds
/// to a **perfectly elastic collision** that preserves all kinetic energy. The default coefficient is 0.3, and it currently
/// can not be configured at a global level.
///
/// When two bodies collide, their restitution coefficients are combined using the specified [`CoefficientCombine`] rule.
///
/// ## Example
///
/// Create a new [`Restitution`] component with a restitution coefficient of 0.4:
///
/// ```ignore
/// Restitution::new(0.4)
/// ```
///
/// Configure how two restitution coefficients are combined with [`CoefficientCombine`]:
///
/// ```ignore
/// Restitution::new(0.4).with_combine_rule(CoefficientCombine::Multiply)
/// ```
///
/// Combine the properties of two [`Restitution`] components:
///
/// ```
#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
///
/// let first = Restitution::new(0.8).with_combine_rule(CoefficientCombine::Average);
/// let second = Restitution::new(0.5).with_combine_rule(CoefficientCombine::Multiply);
///
/// // CoefficientCombine::Multiply has higher priority, so the coefficients are multiplied
/// assert_eq!(
///     first.combine(second),
///     Restitution::new(0.4).with_combine_rule(CoefficientCombine::Multiply)
/// );
/// ```
#[doc(alias = "Bounciness")]
#[doc(alias = "Elasticity")]
#[derive(Reflect, Clone, Copy, Component, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Debug, Component, PartialEq)]
pub struct Restitution {
    /// The [coefficient of restitution](https://en.wikipedia.org/wiki/Coefficient_of_restitution).
    ///
    /// This should be between 0 and 1, where 0 corresponds to a **perfectly inelastic collision**, and 1 corresponds
    /// to a **perfectly elastic collision** that preserves all kinetic energy. The default value is 0.3.
    pub coefficient: Scalar,
    /// The coefficient combine rule used when two bodies collide.
    pub combine_rule: CoefficientCombine,
}

impl Restitution {
    /// A restitution coefficient of 0.0 and a combine rule of [`CoefficientCombine::Average`].
    ///
    /// This is equivalent to [`Restitution::PERFECTLY_INELASTIC`].
    pub const ZERO: Self = Self {
        coefficient: 0.0,
        combine_rule: CoefficientCombine::Average,
    };

    /// A restitution coefficient of 0.0, which corresponds to a perfectly inelastic collision.
    ///
    /// Uses [`CoefficientCombine::Average`].
    pub const PERFECTLY_INELASTIC: Self = Self {
        coefficient: 0.0,
        combine_rule: CoefficientCombine::Average,
    };

    /// A restitution coefficient of 1.0, which corresponds to a perfectly elastic collision.
    ///
    /// Uses [`CoefficientCombine::Average`].
    pub const PERFECTLY_ELASTIC: Self = Self {
        coefficient: 1.0,
        combine_rule: CoefficientCombine::Average,
    };

    /// Creates a new [`Restitution`] component with the given restitution coefficient.
    pub fn new(coefficient: Scalar) -> Self {
        Self {
            coefficient: coefficient.clamp(0.0, 1.0),
            combine_rule: CoefficientCombine::Average,
        }
    }

    /// Sets the [`CoefficientCombine`] rule used.
    pub fn with_combine_rule(&self, combine_rule: CoefficientCombine) -> Self {
        Self {
            combine_rule,
            ..*self
        }
    }

    /// Combines the properties of two [`Restitution`] components.
    pub fn combine(&self, other: Self) -> Self {
        // Choose rule with higher priority
        let rule = self.combine_rule.max(other.combine_rule);

        Self {
            coefficient: match rule {
                CoefficientCombine::Average => (self.coefficient + other.coefficient) * 0.5,
                CoefficientCombine::Min => self.coefficient.min(other.coefficient),
                CoefficientCombine::Multiply => self.coefficient * other.coefficient,
                CoefficientCombine::Max => self.coefficient.max(other.coefficient),
            },
            combine_rule: rule,
        }
    }
}

impl Default for Restitution {
    fn default() -> Self {
        Self {
            coefficient: 0.3,
            combine_rule: CoefficientCombine::default(),
        }
    }
}

impl From<Scalar> for Restitution {
    fn from(coefficient: Scalar) -> Self {
        Self {
            coefficient,
            ..default()
        }
    }
}

/// Controls how strongly the material of an entity prevents relative tangential movement at contact points.
///
/// For surfaces that are at rest relative to each other, static friction is used.
/// Once the static friction is overcome, the bodies will start sliding relative to each other, and dynamic friction is applied instead.
///
/// 0.0: No friction at all, the body slides indefinitely\
/// 1.0: High friction\
///
/// ## Example
///
/// Create a new [`Friction`] component with dynamic and static friction coefficients of 0.4:
///
/// ```ignore
/// Friction::new(0.4)
/// ```
///
/// Set the other friction coefficient:
///
/// ```ignore
/// // 0.4 static and 0.6 dynamic
/// Friction::new(0.4).with_dynamic_coefficient(0.6)
/// // 0.4 dynamic and 0.6 static
/// Friction::new(0.4).with_static_coefficient(0.6)
/// ```
///
/// Configure how the friction coefficients of two [`Friction`] components are combined with [`CoefficientCombine`]:
///
/// ```ignore
/// Friction::new(0.4).with_combine_rule(CoefficientCombine::Multiply)
/// ```
///
/// Combine the properties of two [`Friction`] components:
///
/// ```
#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
///
/// let first = Friction::new(0.8).with_combine_rule(CoefficientCombine::Average);
/// let second = Friction::new(0.5).with_combine_rule(CoefficientCombine::Multiply);
///
/// // CoefficientCombine::Multiply has higher priority, so the coefficients are multiplied
/// assert_eq!(
///     first.combine(second),
///     Friction::new(0.4).with_combine_rule(CoefficientCombine::Multiply)
/// );
/// ```
#[derive(Reflect, Clone, Copy, Component, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Debug, Component, PartialEq)]
pub struct Friction {
    /// Coefficient of dynamic friction.
    pub dynamic_coefficient: Scalar,
    /// Coefficient of static friction.
    pub static_coefficient: Scalar,
    /// The coefficient combine rule used when two bodies collide.
    pub combine_rule: CoefficientCombine,
}

impl Friction {
    /// Zero dynamic and static friction and [`CoefficientCombine::Average`].
    pub const ZERO: Self = Self {
        dynamic_coefficient: 0.0,
        static_coefficient: 0.0,
        combine_rule: CoefficientCombine::Average,
    };

    /// Creates a new `Friction` component with the same dynamic and static friction coefficients.
    pub fn new(friction_coefficient: Scalar) -> Self {
        Self {
            dynamic_coefficient: friction_coefficient,
            static_coefficient: friction_coefficient,
            ..default()
        }
    }

    /// Sets the [`CoefficientCombine`] rule used.
    pub fn with_combine_rule(&self, combine_rule: CoefficientCombine) -> Self {
        Self {
            combine_rule,
            ..*self
        }
    }

    /// Sets the coefficient of dynamic friction.
    pub fn with_dynamic_coefficient(&self, coefficient: Scalar) -> Self {
        Self {
            dynamic_coefficient: coefficient,
            ..*self
        }
    }

    /// Sets the coefficient of static friction.
    pub fn with_static_coefficient(&self, coefficient: Scalar) -> Self {
        Self {
            static_coefficient: coefficient,
            ..*self
        }
    }

    /// Combines the properties of two `Friction` components.
    pub fn combine(&self, other: Self) -> Self {
        // Choose rule with higher priority
        let rule = self.combine_rule.max(other.combine_rule);
        let (dynamic1, dynamic2) = (self.dynamic_coefficient, other.dynamic_coefficient);
        let (static1, static2) = (self.static_coefficient, other.static_coefficient);

        Self {
            dynamic_coefficient: match rule {
                CoefficientCombine::Average => (dynamic1 + dynamic2) * 0.5,
                CoefficientCombine::Min => dynamic1.min(dynamic2),
                CoefficientCombine::Multiply => dynamic1 * dynamic2,
                CoefficientCombine::Max => dynamic1.max(dynamic2),
            },
            static_coefficient: match rule {
                CoefficientCombine::Average => (static1 + static2) * 0.5,
                CoefficientCombine::Min => static1.min(static2),
                CoefficientCombine::Multiply => static1 * static2,
                CoefficientCombine::Max => static1.max(static2),
            },
            combine_rule: rule,
        }
    }
}

impl Default for Friction {
    fn default() -> Self {
        Self {
            dynamic_coefficient: 0.3,
            static_coefficient: 0.3,
            combine_rule: CoefficientCombine::default(),
        }
    }
}

impl From<Scalar> for Friction {
    fn from(coefficient: Scalar) -> Self {
        Self {
            dynamic_coefficient: coefficient,
            static_coefficient: coefficient,
            ..default()
        }
    }
}

/// Automatically slows down a dynamic [rigid body](RigidBody), decreasing its
/// [linear velocity](LinearVelocity) each frame. This can be used to simulate air resistance.
///
/// The default linear damping coefficient is `0.0`, which corresponds to no damping.
///
/// ## Example
///
/// ```
#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
/// use bevy::prelude::*;
///
/// fn setup(mut commands: Commands) {
///     commands.spawn((
///         RigidBody::Dynamic,
///         LinearDamping(0.8),
///     ));
/// }
/// ```
#[derive(
    Component, Reflect, Debug, Clone, Copy, PartialEq, PartialOrd, Default, Deref, DerefMut, From,
)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Debug, Component, Default, PartialEq)]
pub struct LinearDamping(pub Scalar);

/// Automatically slows down a dynamic [rigid body](RigidBody), decreasing its
/// [angular velocity](AngularVelocity) each frame. This can be used to simulate air resistance.
///
/// The default angular damping coefficient is `0.0`, which corresponds to no damping.
///
/// ## Example
///
/// ```
#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
/// use bevy::prelude::*;
///
/// fn setup(mut commands: Commands) {
///     commands.spawn((
///         RigidBody::Dynamic,
///         AngularDamping(1.6),
///     ));
/// }
/// ```
#[derive(
    Component, Reflect, Debug, Clone, Copy, PartialEq, PartialOrd, Default, Deref, DerefMut, From,
)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Debug, Component, Default, PartialEq)]
pub struct AngularDamping(pub Scalar);

/// **Dominance** allows [dynamic rigid bodies](RigidBody::Dynamic) to dominate
/// each other during physical interactions.
/// 
/// The body with a higher dominance acts as if it had infinite mass, and will be unaffected during
/// collisions and other interactions, while the other body will be affected normally.
/// 
/// The dominance must be between `-127` and `127`, and the default value is `0`.
/// Note that static and kinematic bodies will always have a higher dominance value
/// than dynamic bodies regardless of the value of this component.
/// 
/// ## Example
/// 
/// ```
#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")]
/// use bevy::prelude::*;
///
/// // Player dominates all dynamic bodies with a dominance lower than 5
/// fn spawn_player(mut commands: Commands) {
///     commands.spawn((
///         RigidBody::Dynamic,
///         Collider::capsule(0.4, 1.0),
///         Dominance(5),
///     ));
/// }
/// ```
#[rustfmt::skip]
#[derive(Component, Reflect, Debug, Clone, Copy, Default, Deref, DerefMut, From, PartialEq, PartialOrd, Eq, Ord)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(Debug, Component, Default, PartialEq)]
pub struct Dominance(pub i8);

#[cfg(test)]
mod tests {
    use crate::prelude::*;
    use approx::assert_relative_eq;

    #[test]
    fn restitution_clamping_works() {
        assert_eq!(Restitution::new(-2.0).coefficient, 0.0);
        assert_eq!(Restitution::new(0.6).coefficient, 0.6);
        assert_eq!(Restitution::new(3.0).coefficient, 1.0);
    }

    #[test]
    fn coefficient_combine_works() {
        let r1 = Restitution::new(0.3).with_combine_rule(CoefficientCombine::Average);

        // (0.3 + 0.7) / 2.0 == 0.5
        let average_result =
            r1.combine(Restitution::new(0.7).with_combine_rule(CoefficientCombine::Average));
        let average_expected = Restitution::new(0.5).with_combine_rule(CoefficientCombine::Average);
        assert_relative_eq!(
            average_result.coefficient,
            average_expected.coefficient,
            epsilon = 0.0001
        );
        assert_eq!(average_result.combine_rule, average_expected.combine_rule);

        // 0.3.min(0.7) == 0.3
        assert_eq!(
            r1.combine(Restitution::new(0.7).with_combine_rule(CoefficientCombine::Min)),
            Restitution::new(0.3).with_combine_rule(CoefficientCombine::Min)
        );

        // 0.3 * 0.7 == 0.21
        let multiply_result =
            r1.combine(Restitution::new(0.7).with_combine_rule(CoefficientCombine::Multiply));
        let multiply_expected =
            Restitution::new(0.21).with_combine_rule(CoefficientCombine::Multiply);
        assert_relative_eq!(
            multiply_result.coefficient,
            multiply_expected.coefficient,
            epsilon = 0.0001
        );
        assert_eq!(multiply_result.combine_rule, multiply_expected.combine_rule);

        // 0.3.max(0.7) == 0.7
        assert_eq!(
            r1.combine(Restitution::new(0.7).with_combine_rule(CoefficientCombine::Max)),
            Restitution::new(0.7).with_combine_rule(CoefficientCombine::Max)
        );
    }
}