@@ -2,32 +2,45 @@ use std::{
2
2
any:: { Any , TypeId } ,
3
3
cell:: RefCell ,
4
4
collections:: HashMap ,
5
+ ops:: { Deref , DerefMut } ,
5
6
rc:: Rc ,
6
7
} ;
7
8
8
9
/// Marker trait for ECS components
9
10
pub trait Component : ' static { }
10
11
11
- /// Trait for ECS systems that operate on the World
12
- pub trait System {
13
- /// Execute the system with the given World
14
- fn execute ( & mut self , world : & mut World ) ;
15
- }
12
+ /// Marker trait for ECS resources
13
+ pub trait Resource : ' static { }
16
14
17
15
/// A unique identifier for an entity
18
16
#[ derive( Debug , Clone , Copy , PartialEq , Eq , Hash ) ]
19
17
pub struct EntityId ( pub u32 ) ;
20
18
19
+ impl Deref for EntityId {
20
+ type Target = u32 ;
21
+
22
+ fn deref ( & self ) -> & Self :: Target {
23
+ & self . 0
24
+ }
25
+ }
26
+
27
+ impl DerefMut for EntityId {
28
+ fn deref_mut ( & mut self ) -> & mut Self :: Target {
29
+ & mut self . 0
30
+ }
31
+ }
32
+
21
33
/// The main ECS world that holds all entities and their components
22
34
pub struct World {
23
35
entities : HashMap < EntityId , Entity > ,
36
+ resources : HashMap < TypeId , Rc < RefCell < dyn Resource > > > ,
24
37
next_id : u32 ,
25
38
}
26
39
27
40
/// An entity is just a collection of components
28
41
pub struct Entity {
29
42
pub id : EntityId ,
30
- components : HashMap < TypeId , Rc < RefCell < dyn Any > > > ,
43
+ components : HashMap < TypeId , Rc < RefCell < dyn Component > > > ,
31
44
}
32
45
33
46
impl Default for World {
@@ -40,6 +53,7 @@ impl World {
40
53
pub fn new ( ) -> Self {
41
54
Self {
42
55
entities : HashMap :: new ( ) ,
56
+ resources : HashMap :: new ( ) ,
43
57
next_id : 0 ,
44
58
}
45
59
}
@@ -128,4 +142,13 @@ impl World {
128
142
pub fn get_all_entities ( & self ) -> Vec < EntityId > {
129
143
self . entities . keys ( ) . copied ( ) . collect ( )
130
144
}
145
+
146
+ pub fn get_resource ( & self , type_id : TypeId ) -> Option < Rc < RefCell < dyn Resource > > > {
147
+ self . resources . get ( & type_id) . cloned ( )
148
+ }
149
+
150
+ pub fn insert_resource < T : Resource > ( & mut self , resource : T ) {
151
+ self . resources
152
+ . insert ( resource. type_id ( ) , Rc :: new ( RefCell :: new ( resource) ) ) ;
153
+ }
131
154
}
0 commit comments