rapier2d/data/
modified_objects.rs

1use std::marker::PhantomData;
2use std::ops::Deref;
3
4/// Contains handles of modified objects.
5///
6/// This is a wrapper over a `Vec` to ensure we don’t forget to set the object’s
7/// MODIFIED flag when adding it to this set.
8/// It is possible to bypass the wrapper with `.as_mut_internal`. But this should only
9/// be done for internal engine usage (like the physics pipeline).
10#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
11#[derive(Clone, Debug)]
12pub struct ModifiedObjects<Handle, Object>(Vec<Handle>, PhantomData<Object>);
13
14impl<Handle, Object> Default for ModifiedObjects<Handle, Object> {
15    fn default() -> Self {
16        Self(Vec::new(), PhantomData)
17    }
18}
19
20/// Objects that internally track a flag indicating whether they've been modified
21pub trait HasModifiedFlag {
22    /// Whether the object has been modified
23    fn has_modified_flag(&self) -> bool;
24    /// Mark object as modified
25    fn set_modified_flag(&mut self);
26}
27
28impl<Handle, Object> Deref for ModifiedObjects<Handle, Object> {
29    type Target = Vec<Handle>;
30    fn deref(&self) -> &Self::Target {
31        &self.0
32    }
33}
34
35impl<Handle, Object: HasModifiedFlag> ModifiedObjects<Handle, Object> {
36    /// Preallocate memory for `capacity` handles
37    pub fn with_capacity(capacity: usize) -> Self {
38        Self(Vec::with_capacity(capacity), PhantomData)
39    }
40
41    /// Remove every handle from this set.
42    ///
43    /// Note that the corresponding object MODIFIED flags won’t be reset automatically by this function.
44    pub fn clear(&mut self) {
45        self.0.clear()
46    }
47
48    /// Pushes a object handle to this set after checking that it doesn’t have the MODIFIED
49    /// flag set.
50    ///
51    /// This will also set the object’s MODIFIED flag.
52    pub fn push_once(&mut self, handle: Handle, object: &mut Object) {
53        if !object.has_modified_flag() {
54            self.push_unchecked(handle, object);
55        }
56    }
57
58    /// Pushes an object handle to this set without checking if the object already has the MODIFIED
59    /// flags.
60    ///
61    /// Only use in situation where you are certain (due to other contextual information) that
62    /// the object isn’t already in the set.
63    ///
64    /// This will also set the object’s MODIFIED flag.
65    pub fn push_unchecked(&mut self, handle: Handle, object: &mut Object) {
66        object.set_modified_flag();
67        self.0.push(handle);
68    }
69}