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
use bevy::{
    ecs::component::Component,
    reflect::{FromReflect, Reflect},
};

/// Describes a collision layer
///
/// It is recommended to implement it using the derive macro.
#[allow(missing_docs)]
pub trait PhysicsLayer: Sized {
    fn to_bits(&self) -> u32;
    fn all_bits() -> u32;
}

impl<T: PhysicsLayer> PhysicsLayer for &T {
    fn to_bits(&self) -> u32 {
        T::to_bits(self)
    }

    fn all_bits() -> u32 {
        T::all_bits()
    }
}

/// Components that defines the collision layers of the collision shape.
///
/// This component contains two collections of layers: "groups" and "masks".
///
/// Two entities A and B will interact iff:
///  * There is a layer in the groups of A that is also in the masks of B
///  * There is a layer in the groups of B that is also in the masks of A
///
/// An entity without this component is considered has having all layers in its "groups" and
/// "masks", and will interact with everything.
///
/// This component must be on the same entity of a [`CollisionShape`](crate::CollisionShape)
///
/// To build an instance, start with either [`CollisionLayers::new()`], [`CollisionLayers::all_groups()`],
/// [`CollisionLayers::all_masks()`], [`CollisionLayers::all()`] or
/// [`CollisionLayers::none()`], and then add or remove layers by calling
/// `with_group`/`without_group` and `with_mask`/`without_mask`.
///
/// Theses methods take a type that implement [`PhysicsLayer`]. The best option is to create an enum
/// with a `#[derive(PhysicsLayer)]` clause.
///
/// # Example
///
/// ```
/// # use heron_core::*;
/// # use bevy::prelude::*;
/// # enum GameLayer {
/// #   World,
/// #   Player,
/// #   Enemies,
/// # }
/// # impl PhysicsLayer for GameLayer {
/// #     fn to_bits(&self) -> u32 {
/// #         todo!()
/// #     }
/// #     fn all_bits() -> u32 {
/// #         todo!()
/// #     }
/// # }
/// fn spawn(mut commands: Commands) {
///    commands.spawn_bundle(todo!("Spawn a bundle of your choice"))
///         .insert(RigidBody::Dynamic) // <-- Create a rigid body
///         .insert(CollisionShape::Sphere { radius: 10.0 }) // <-- Attach a collision shape
///         .insert(
///
///             // Define the collision layer of this *collision shape*
///             CollisionLayers::none()
///                 .with_group(GameLayer::Player) // <-- Mark it as the player
///                 .with_masks(&[GameLayer::World, GameLayer::Enemies]) // <-- Defines that the player collides with world and enemies (but not with other players)
///         );
/// }
/// ```
#[derive(Debug, Component, Copy, Clone, Eq, PartialEq, Reflect, FromReflect)]
pub struct CollisionLayers {
    groups: u32,
    masks: u32,
}

impl Default for CollisionLayers {
    fn default() -> Self {
        Self {
            groups: 0xffff_ffff,
            masks: 0xffff_ffff,
        }
    }
}

impl CollisionLayers {
    /// Create a new collision layers configuration with a single group and mask.
    ///
    /// You may add more groups and mask with `with_group` and `with_mask`.
    #[must_use]
    pub fn new<L: PhysicsLayer>(group: L, mask: L) -> Self {
        Self::from_bits(group.to_bits(), mask.to_bits())
    }

    /// Contains all groups and masks
    ///
    /// The entity, will interacts with everything (except the entities that interact with
    /// nothing).
    #[must_use]
    pub fn all<L: PhysicsLayer>() -> Self {
        Self::from_bits(L::all_bits(), L::all_bits())
    }

    /// Contains all groups and no masks
    ///
    /// The entity, will not interact with anything, unless you add masks via [`CollisionLayers::with_mask`]. You
    /// can also exclude specific groups using [`CollisionLayers::without_group`].
    #[must_use]
    pub fn all_groups<L: PhysicsLayer>() -> Self {
        Self::from_bits(L::all_bits(), 0)
    }

    /// Contains no groups and all masks
    ///
    /// The entity, will not interact with anything, unless you add group via [`CollisionLayers::with_group`]. You
    /// can also exclude specific masks using [`CollisionLayers::without_mask`].
    #[must_use]
    pub fn all_masks<L: PhysicsLayer>() -> Self {
        Self::from_bits(0, L::all_bits())
    }

    /// Contains no masks and groups
    ///
    /// The entity, will not interact with anything
    #[must_use]
    pub const fn none() -> Self {
        Self::from_bits(0, 0)
    }

    #[must_use]
    #[allow(missing_docs)]
    pub const fn from_bits(groups: u32, masks: u32) -> Self {
        Self { groups, masks }
    }

    /// Returns true if the entity would interact with an entity containing the `other` [`CollisionLayers]`
    #[must_use]
    pub fn interacts_with(self, other: Self) -> bool {
        (self.groups & other.masks) != 0 && (other.groups & self.masks) != 0
    }

    /// Returns true if the given layer is contained in the "groups"
    #[must_use]
    pub fn contains_group(self, layer: impl PhysicsLayer) -> bool {
        (self.groups & layer.to_bits()) != 0
    }

    /// Add the given layer in the "groups"
    #[must_use]
    pub fn with_group(mut self, layer: impl PhysicsLayer) -> Self {
        self.groups |= layer.to_bits();
        self
    }

    /// Add the given layers in the "groups"
    #[must_use]
    pub fn with_groups(mut self, layers: impl IntoIterator<Item = impl PhysicsLayer>) -> Self {
        for layer in layers.into_iter().map(|l| l.to_bits()) {
            self.groups |= layer;
        }

        self
    }

    /// Remove the given layer from the "groups"
    #[must_use]
    pub fn without_group(mut self, layer: impl PhysicsLayer) -> Self {
        self.groups &= !layer.to_bits();
        self
    }

    /// Returns true if the given layer is contained in the "masks"
    #[must_use]
    pub fn contains_mask(self, layer: impl PhysicsLayer) -> bool {
        (self.masks & layer.to_bits()) != 0
    }

    /// Add the given layer in the "masks"
    #[must_use]
    pub fn with_mask(mut self, layer: impl PhysicsLayer) -> Self {
        self.masks |= layer.to_bits();
        self
    }

    /// Add the given layers in the "masks"
    #[must_use]
    pub fn with_masks(mut self, layers: impl IntoIterator<Item = impl PhysicsLayer>) -> Self {
        for layer in layers.into_iter().map(|l| l.to_bits()) {
            self.masks |= layer;
        }

        self
    }

    /// Remove the given layer from the "masks"
    #[must_use]
    pub fn without_mask(mut self, layer: impl PhysicsLayer) -> Self {
        self.masks &= !layer.to_bits();
        self
    }

    #[must_use]
    #[allow(missing_docs)]
    pub fn groups_bits(self) -> u32 {
        self.groups
    }

    #[must_use]
    #[allow(missing_docs)]
    pub fn masks_bits(self) -> u32 {
        self.masks
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;

    use super::*;

    enum TestLayer {
        One,
        Two,
    }

    impl PhysicsLayer for TestLayer {
        fn to_bits(&self) -> u32 {
            match self {
                TestLayer::One => 1,
                TestLayer::Two => 2,
            }
        }

        fn all_bits() -> u32 {
            3
        }
    }

    #[test]
    fn all_interacts_with_all() {
        assert!(
            CollisionLayers::all::<TestLayer>().interacts_with(CollisionLayers::all::<TestLayer>())
        );
    }

    #[rstest]
    #[case(CollisionLayers::all::<TestLayer>())]
    #[case(CollisionLayers::none())]
    #[case(CollisionLayers::all_groups::<TestLayer>())]
    #[case(CollisionLayers::all_masks::<TestLayer>())]
    fn none_does_not_interact_with_any_anything(#[case] other: CollisionLayers) {
        assert!(!CollisionLayers::none().interacts_with(other));
        assert!(!other.interacts_with(CollisionLayers::none()));
    }

    #[test]
    fn empty_groups_and_masks_not_interact() {
        let c1 = CollisionLayers::all_groups::<TestLayer>();
        let c2 = CollisionLayers::all_masks::<TestLayer>();

        assert!(!c1.interacts_with(c2));
        assert!(!c2.interacts_with(c1));
    }

    #[test]
    fn with_layer_adds_interaction() {
        let c1 = CollisionLayers::none()
            .with_group(TestLayer::One)
            .with_mask(TestLayer::Two);

        let c2 = CollisionLayers::none()
            .with_group(TestLayer::Two)
            .with_mask(TestLayer::One);

        assert!(c1.interacts_with(c2));
        assert!(c2.interacts_with(c1));
        assert!(!c1.interacts_with(c1));
        assert!(!c2.interacts_with(c2));
    }

    #[test]
    fn without_layer_removes_interaction() {
        let c1 = CollisionLayers::all::<TestLayer>()
            .without_group(TestLayer::One)
            .without_mask(TestLayer::Two);

        let c2 = CollisionLayers::all::<TestLayer>()
            .without_group(TestLayer::Two)
            .without_mask(TestLayer::One);

        println!("{:?}, {:?}", c1, c2);
        assert!(c1.interacts_with(c2));
        assert!(c2.interacts_with(c1));
        assert!(!c1.interacts_with(c1));
        assert!(!c2.interacts_with(c2));
    }
}