intuicio_framework_ecs/
resources.rs

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
use crate::{
    archetype::ArchetypeColumnInfo,
    bundle::{Bundle, BundleColumns},
    query::{TypedQueryFetch, TypedQueryIter},
    world::{World, WorldChanges, WorldError},
    Component, ComponentRef, ComponentRefMut,
};
use intuicio_data::type_hash::TypeHash;
use std::{error::Error, sync::RwLockReadGuard};

#[derive(Default)]
pub struct Resources {
    world: World,
}

impl Resources {
    pub fn add(&mut self, bundle: impl Bundle) -> Result<(), Box<dyn Error>> {
        let entity = self.world.entities().next();
        if let Some(entity) = entity {
            WorldError::allow(
                self.world.insert(entity, bundle),
                [WorldError::EmptyColumnSet],
                (),
            )?;
        } else {
            self.world.spawn(bundle)?;
        }
        Ok(())
    }

    pub fn remove<T: BundleColumns>(&mut self) -> Result<(), Box<dyn Error>> {
        let entity = self.world.entities().next();
        if let Some(entity) = entity {
            self.world.remove::<T>(entity)?;
        }
        Ok(())
    }

    pub fn remove_raw(&mut self, columns: Vec<ArchetypeColumnInfo>) -> Result<(), Box<dyn Error>> {
        let entity = self.world.entities().next();
        if let Some(entity) = entity {
            self.world.remove_raw(entity, columns)?;
        }
        Ok(())
    }

    pub fn clear(&mut self) {
        self.world.clear();
    }

    pub fn clear_changes(&mut self) {
        self.world.clear_changes();
    }

    pub fn added(&self) -> &WorldChanges {
        self.world.added()
    }

    pub fn removed(&self) -> &WorldChanges {
        self.world.removed()
    }

    pub fn updated(&self) -> Option<RwLockReadGuard<'_, WorldChanges>> {
        self.world.updated()
    }

    pub fn did_changed<T: Component>(&self) -> bool {
        self.world.component_did_changed::<T>()
    }

    pub fn did_changed_raw(&self, type_hash: TypeHash) -> bool {
        self.world.component_did_changed_raw(type_hash)
    }

    pub fn get<const LOCKING: bool, T: Component>(
        &self,
    ) -> Result<ComponentRef<LOCKING, T>, Box<dyn Error>> {
        let entity = self.world.entities().next().unwrap_or_default();
        Ok(self.world.component(entity)?)
    }

    pub fn get_mut<const LOCKING: bool, T: Component>(
        &self,
    ) -> Result<ComponentRefMut<LOCKING, T>, Box<dyn Error>> {
        let entity = self.world.entities().next().unwrap_or_default();
        Ok(self.world.component_mut(entity)?)
    }

    pub fn query<'a, const LOCKING: bool, Fetch: TypedQueryFetch<'a, LOCKING>>(
        &'a self,
    ) -> TypedQueryIter<'a, LOCKING, Fetch> {
        self.world.query::<LOCKING, Fetch>()
    }
}