summaryrefslogtreecommitdiff
path: root/ecs/src/archetype.rs
blob: 808d00663861ddddabcfe71f813f8b69aacfe23c (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
use std::hash::{DefaultHasher, Hash, Hasher};

use crate::component::{
    Id as ComponentId,
    IsOptional as ComponentIsOptional,
    Metadata as ComponentMetadata,
};

/// Archetype ID.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Id
{
    hash: u64,
}

impl Id
{
    pub fn from_components_metadata(
        components_metadata: impl IntoIterator<Item = ComponentMetadata>,
    ) -> Self
    {
        Self::new(
            components_metadata
                .into_iter()
                .filter_map(|component_metadata| {
                    if component_metadata.is_optional == ComponentIsOptional::Yes {
                        return None;
                    }

                    Some(component_metadata.id)
                }),
        )
    }

    /// Returns the ID of a archetype with the given components.
    fn new(component_ids: impl IntoIterator<Item = ComponentId>) -> Self
    {
        let mut hasher = DefaultHasher::new();

        for component_id in component_ids {
            component_id.hash(&mut hasher);
        }

        let hash = hasher.finish();

        Self { hash }
    }
}