summaryrefslogtreecommitdiff
path: root/engine-ecs/src/uid.rs
blob: 26fbaee91f7a73f4dd1cbdc6f57acb3e485a5f93 (plain)
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
use std::fmt::{Debug, Display, Formatter};
use std::sync::atomic::{AtomicU32, Ordering};

use seq_macro::seq;

use crate::component::Component;
use crate::util::{gen_mask_64, Array, BitMask, NumberExt};

static NEXT: AtomicU32 = AtomicU32::new(Uid::FIRST_UNIQUE_ID);

static WILDCARD_ID: u32 = 1;

const ID_BITS: BitMask<u64> = BitMask::new(gen_mask_64!(32..=63));
const RELATION_BITS: BitMask<u64> = BitMask::new(gen_mask_64!(6..=31));
const IS_PAIR_BITS: BitMask<u64> = BitMask::new(1 << 0);

/// A unique identifier.
#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Uid
{
    inner: u64,
}

impl Uid
{
    /// The id part of the first unique `Uid`. The ids `0..Uid::FIRST_UNIQUE_ID` are
    /// reserved.
    pub const FIRST_UNIQUE_ID: u32 = 5;

    /// Returns a new unique entity/component ID.
    pub fn new_unique() -> Self
    {
        let id = NEXT.fetch_add(1, Ordering::Relaxed);

        Self {
            inner: ID_BITS.field_prep(u64::from(id)) | IS_PAIR_BITS.field_prep(0),
        }
    }

    #[must_use]
    pub fn wildcard() -> Self
    {
        Self {
            inner: ID_BITS.field_prep(u64::from(WILDCARD_ID))
                | IS_PAIR_BITS.field_prep(0),
        }
    }

    /// Returns a new pair UID.
    ///
    /// # Panics
    /// Will panic if either the given relation or target is a pair UID.
    #[must_use]
    pub fn new_pair(params: &PairParams) -> Self
    {
        assert!(!params.relation.is_pair(), "Pair relation cannot be a pair");
        assert!(!params.target.is_pair(), "Pair target cannot be a pair");

        Self {
            inner: ID_BITS.field_prep(u64::from(params.target.id()))
                | RELATION_BITS.field_prep(u64::from(params.relation.id()))
                | IS_PAIR_BITS.field_prep(1),
        }
    }

    #[must_use]
    pub fn id(&self) -> u32
    {
        let Ok(id) = u32::try_from(self.inner.field_get(ID_BITS)) else {
            unreachable!("Uid id does not fit in u32");
        };

        id
    }

    #[must_use]
    pub fn is_pair(&self) -> bool
    {
        let Ok(is_pair) = u8::try_from(self.inner.field_get(IS_PAIR_BITS)) else {
            unreachable!();
        };

        is_pair == 1
    }

    /// If this `Uid` is a pair, returns the relation `Uid`.
    ///
    /// # Panics
    /// Will panic if this `Uid` is not a pair.
    #[must_use]
    pub fn relation(&self) -> Self
    {
        assert!(self.is_pair(), "Uid is not a pair");

        let Ok(relation) = u32::try_from(self.inner.field_get(RELATION_BITS)) else {
            unreachable!("Uid relation does not fit in u32");
        };

        Self {
            inner: ID_BITS.field_prep(u64::from(relation)) | IS_PAIR_BITS.field_prep(0),
        }
    }

    /// Compares the relation of this pair `Uid` with the relation of another pair `Uid`.
    ///
    /// # Panics
    /// Will panic if any of the `Uid`s are not a pair.
    #[must_use]
    pub fn has_same_relation_as(&self, other: Self) -> bool
    {
        self.relation() == other.relation()
    }

    /// If this `Uid` is a pair, returns the target `Uid`.
    ///
    /// # Panics
    /// Will panic if this `Uid` is not a pair.
    #[must_use]
    pub fn target(&self) -> Self
    {
        assert!(self.is_pair(), "Uid is not a pair");

        Self {
            inner: ID_BITS.field_prep(u64::from(self.id())) | IS_PAIR_BITS.field_prep(0),
        }
    }
}

impl Debug for Uid
{
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result
    {
        let mut debug_struct = formatter.debug_struct("Uid");

        if self.is_pair() {
            return debug_struct
                .field("relation", &self.relation())
                .field("target", &self.target())
                .finish();
        }

        debug_struct.field("id", &self.id()).finish()
    }
}

impl Display for Uid
{
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result
    {
        if self.is_pair() {
            return write!(formatter, "({}, {})", self.relation(), self.target());
        }

        if *self == Uid::wildcard() {
            return write!(formatter, "*");
        }

        write!(formatter, "{}", self.id())
    }
}

#[derive(Debug, Clone)]
pub struct PairParams
{
    pub relation: Uid,
    pub target: Uid,
}

pub trait With
{
    fn uid() -> Uid;
}

impl<ComponentT: Component> With for ComponentT
{
    fn uid() -> Uid
    {
        Self::id()
    }
}

pub trait WithUidTuple
{
    type UidsArray: Array<Uid>;

    fn uids() -> Self::UidsArray;
}

macro_rules! impl_with_uid_tuple {
    ($c: tt) => {
        seq!(I in 0..=$c {
            impl<#(WithUid~I: With,)*> WithUidTuple for (#(WithUid~I,)*)
            {
                type UidsArray = [Uid; $c + 1];

                fn uids() -> Self::UidsArray
                {
                    [#(WithUid~I::uid(),)*]
                }
            }
        });
    };
}

seq!(C in 0..=16 {
    impl_with_uid_tuple!(C);
});