dirk_universe 0.1.0

DirkEngine's ECS system
Documentation
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
#![doc = include_str!("../README.md")]

use std::{
    any::TypeId,
    collections::{HashMap, HashSet},
};

use crate::{
    command_buffer::Command,
    components::{AnyComponent, Component, Components},
    systems::{
        ComponentSystem, ComponentSystemStorage, EntitySystem, EntitySystemStorage, TickingSystem,
        TickingSystemStorage, UniverseSystem, UniverseSystemStorage,
    },
};

pub mod components;
pub mod query;
pub mod systems;

mod command_buffer;
pub use command_buffer::CommandBuffer;

mod entity;
pub use entity::{Entity, EntityBuilder};

mod world;
use tracing::warn;
pub use world::{World, WorldBuilder, WorldId};

/// This struct is the manager for all the worlds.
pub struct Universe {
    worlds: HashMap<WorldId, World>,
    next_world_id: WorldId,

    entities: HashMap<Entity, WorldId>,
    next_entity_id: Entity,

    // this field starts with `universe`
    #[allow(clippy::struct_field_names)]
    universe_systems: UniverseSystemStorage,
    ticking_systems: TickingSystemStorage,
    entity_systems: EntitySystemStorage,
    component_systems: ComponentSystemStorage,

    components: Components,

    /// The queue of command buffers that need to be submitted
    buffers: Vec<CommandBuffer>,
}

impl Universe {
    /// Returns a [`UniverseBuilder`] to easily construct a [`Universe`].
    #[must_use]
    pub fn builder() -> UniverseBuilder {
        UniverseBuilder::new()
    }

    #[must_use]
    fn build(builder: UniverseBuilder) -> Self {
        let mut universe = Self {
            worlds: HashMap::new(),
            next_world_id: WorldId::default(),
            entities: HashMap::new(),
            next_entity_id: Entity::default(),
            universe_systems: builder.universe_systems,
            ticking_systems: builder.ticking_systems,
            entity_systems: builder.entity_systems,
            component_systems: builder.component_systems,
            components: Components::default(),
            buffers: Vec::new(),
        };

        let mut cmd = CommandBuffer::new();
        for builder in builder.worlds {
            cmd.create_world(builder);
        }
        universe.submit_buffer(cmd);
        universe
    }

    /// Ticks every the entire [`Universe`].
    ///
    /// # Panics
    ///
    /// Will panic in certain internal conditions like if a [`World`] that
    /// was just created is not found in the [`Universe`].
    /// No panic should be caused by user error.
    pub fn tick(&mut self, delta_time: f64) {
        let mut cmd = CommandBuffer::new();

        let buffers = std::mem::take(&mut self.buffers);

        let mut commands: Vec<Command> = Vec::new();
        for sub in buffers {
            commands.append(&mut sub.commands());
        }

        self.run_commands(&mut cmd, commands);

        self.universe_systems
            .iter()
            .for_each(|system| system.tick(&mut cmd, self, delta_time));

        self.ticking_systems.iter().for_each(|system| {
            system.tick(&mut cmd, self, delta_time, &mut system.query().query(self));
        });

        self.submit_buffer(cmd);
    }

    // HELPERS FOR THE TICK FUNCTION

    #[allow(clippy::too_many_lines)]
    fn run_commands(&mut self, cmd: &mut CommandBuffer, commands: Vec<Command>) {
        let mut created_worlds: HashSet<WorldId> = HashSet::new();
        let mut destroyed_worlds: HashSet<WorldId> = HashSet::new();
        let mut spawned_entities: HashSet<Entity> = HashSet::new();
        let mut despawned_entities: HashSet<Entity> = HashSet::new();
        let mut sent_entities: HashSet<(Entity, WorldId, WorldId)> = HashSet::new(); // entity, from, to
        let mut added_components: HashSet<(Entity, TypeId)> = HashSet::new();
        let mut updated_components: Vec<(Entity, TypeId, Box<dyn AnyComponent>)> = Vec::new(); // we use a vec as updated_components is not `Hash`
        let mut removed_components: HashSet<(Entity, TypeId)> = HashSet::new();

        for command in commands {
            match command {
                Command::CreateWorld(builder) => {
                    let id = self.next_world_id;
                    self.next_world_id += 1;

                    let world = World::new(id, builder.name);
                    self.worlds.insert(id, world);

                    for builder in builder.entities {
                        let entity = self.add_entity(id).expect("just created world");
                        spawned_entities.insert(entity);

                        builder.components.into_values().for_each(|component| {
                            let type_id = component.component_type_id();
                            self.components.insert_any(entity, component);
                            added_components.insert((entity, type_id));
                        });
                    }

                    created_worlds.insert(id);
                }
                Command::DestroyWorld(world) => {
                    let Some(world) = self.worlds.get(&world) else {
                        continue;
                    };

                    for &entity in &world.alive {
                        despawned_entities.insert(entity);
                        for (type_id, _) in self.components.get_all(entity) {
                            removed_components.insert((entity, type_id));
                        }
                    }
                    destroyed_worlds.insert(world.id());
                }
                Command::Spawn(world, builder) => {
                    let Some(entity) = self.add_entity(world) else {
                        warn!("cannot add entity to world {world} as it does not exist");
                        continue;
                    };
                    spawned_entities.insert(entity);

                    builder.components.into_values().for_each(|component| {
                        let type_id = component.component_type_id();
                        self.components.insert_any(entity, component);
                        added_components.insert((entity, type_id));
                    });
                }
                Command::Despawn(entity) => {
                    if !self.is_alive(entity) {
                        continue;
                    }
                    despawned_entities.insert(entity);
                    for (type_id, _) in self.components.get_all(entity) {
                        removed_components.insert((entity, type_id));
                    }
                }
                Command::Send(entity, to) => {
                    let Some(from) = self.entities.get(&entity).copied() else {
                        warn!("cannot send {entity:?} as it does not exist");
                        continue;
                    };
                    if from == to {
                        continue;
                    }
                    if !self.worlds.contains_key(&to) {
                        warn!("cannot send {entity:?} to world {to} as it does not exist");
                        continue;
                    }

                    let old = self
                        .worlds
                        .get_mut(&from)
                        .expect("entity is registered as in this world");
                    old.alive.remove(&entity);

                    let new = self.worlds.get_mut(&to).expect("just checked it exists");
                    new.alive.insert(entity);

                    self.entities.insert(entity, to);
                    sent_entities.insert((entity, from, to));
                }
                Command::SetComponent(entity, component) => {
                    if !self.is_alive(entity) {
                        continue;
                    }

                    let type_id = component.component_type_id();
                    if let Some(old) = self.components.insert_any(entity, component) {
                        updated_components.push((entity, type_id, old));
                    } else {
                        added_components.insert((entity, type_id));
                    }
                }
                Command::RemoveComponent(entity, type_id) => {
                    if self.components.get_any(entity, type_id).is_some() {
                        removed_components.insert((entity, type_id));
                    }
                }
            }
        }

        // World: created
        for world in created_worlds {
            let world = self.worlds.get(&world).expect("we just added this world");
            self.universe_systems
                .iter()
                .for_each(|system| system.world_created(cmd, self, world));
        }

        // Entity: spawned
        for entity in spawned_entities {
            self.universe_systems
                .iter()
                .for_each(|system| system.entity_spawned(cmd, self, entity));
            self.entity_systems.iter().for_each(|system| {
                if !system.query().matches(self, entity) {
                    return;
                }
                system.spawned(cmd, self, entity);
            });
        }

        // Component: added
        for (entity, type_id) in added_components {
            let component = self
                .components
                .get_any(entity, type_id)
                .expect("just added component");
            self.component_systems
                .iter(type_id)
                .for_each(|system| system.added(cmd, entity, component));
        }

        // Component: updated
        for (entity, type_id, old) in updated_components {
            let component = self
                .components
                .get_any(entity, type_id)
                .expect("just updated component");
            self.component_systems
                .iter(type_id)
                .for_each(|system| system.updated(cmd, entity, old.as_ref(), component));
        }

        // Entity: sent
        for (entity, from, to) in sent_entities {
            self.universe_systems
                .iter()
                .for_each(|system| system.entity_sent(cmd, self, entity, from, to));
            self.entity_systems.iter().for_each(|system| {
                if !system.query().matches(self, entity) {
                    return;
                }

                system.sent(cmd, self, entity, from, to);
            });
        }

        // Component: removed
        for &(entity, type_id) in &removed_components {
            let component = self
                .components
                .get_any(entity, type_id)
                .expect("haven't removed component yet");
            self.component_systems
                .iter(type_id)
                .for_each(|system| system.removed(cmd, entity, component));
        }

        // Entity: despawned
        for &entity in &despawned_entities {
            self.universe_systems
                .iter()
                .for_each(|system| system.entity_despawned(cmd, self, entity));
            self.entity_systems.iter().for_each(|system| {
                if !system.query().matches(self, entity) {
                    return;
                }

                system.despawned(cmd, self, entity);
            });
        }

        // World: destroyed
        for world in &destroyed_worlds {
            let world = self.worlds.get(world).expect("world not added yet");
            self.universe_systems
                .iter()
                .for_each(|system| system.world_destroyed(cmd, self, world));
        }

        // destroy components
        for (entity, type_id) in removed_components {
            self.components.remove_any(entity, type_id);
        }

        // destroy entities
        for entity in despawned_entities {
            if let Some(world) = self.get_world(entity)
                && let Some(world) = self.worlds.get_mut(&world)
            {
                world.alive.remove(&entity);
            }
            self.entities.remove(&entity);
        }

        // destroy worlds
        for world in destroyed_worlds {
            self.worlds.remove(&world);
        }
    }

    /// Just adds an [`Entity`] to the `world` & returns its ID.
    /// Returns `None` if the `world` does not exist.
    fn add_entity(&mut self, world: WorldId) -> Option<Entity> {
        let world = self.worlds.get_mut(&world)?;

        let entity = self.next_entity_id;
        self.next_entity_id += 1;
        self.entities.insert(entity, world.id());

        world.alive.insert(entity);
        Some(entity)
    }

    // COMMAND BUFFERS

    /// Will submit a buffer for execution.
    pub fn submit_buffer(&mut self, buffer: CommandBuffer) {
        if buffer.is_empty() {
            return;
        }
        self.buffers.push(buffer);
    }

    // UTILITIES & GETTERS

    /// Returns an optional reference to the requested [`World`].
    #[must_use]
    pub fn world(&self, world: WorldId) -> Option<&World> {
        self.worlds.get(&world)
    }

    /// Returns the [`WorldId`] of the [`Entity`]'s [`World`].
    #[must_use]
    pub fn get_world(&self, entity: Entity) -> Option<WorldId> {
        self.entities.get(&entity).copied()
    }

    /// Returns if the given [`Entity`] is in the given [`World`].
    #[must_use]
    pub fn is_in_world(&self, world: WorldId, entity: Entity) -> bool {
        self.entities.get(&entity) == Some(&world)
    }

    /// Returns the total number of alive entities.
    #[must_use]
    pub fn alive_count(&self) -> usize {
        self.entities.len()
    }

    /// Returns if the specified entity is alive
    #[must_use]
    pub fn is_alive(&self, entity: Entity) -> bool {
        self.entities.contains_key(&entity)
    }

    /// Returns a shared reference to a component, or `None` if the entity
    /// does not have one.
    #[must_use]
    pub fn component<C: Component>(&self, entity: Entity) -> Option<&C> {
        self.components.get(entity)
    }

    /// Will create a new [`World`] & return it [`WorldId`].
    ///
    /// The world creation runs immediately unlike when directly
    /// submitting a [`CommandBuffer`].
    pub fn create_world(&mut self, builder: WorldBuilder) -> Option<WorldId> {
        let next_id = self.next_world_id;
        let mut cmd = CommandBuffer::new();
        self.run_commands(&mut cmd, vec![Command::CreateWorld(builder)]);
        self.submit_buffer(cmd);
        let new_next = self.next_world_id;

        if next_id == new_next {
            None
        } else {
            Some(next_id)
        }
    }

    /// Will spawn a new [`Entity`] & return its ID.
    ///
    /// The spawning runs immediately unlike when directly submitting a [`CommandBuffer`].
    pub fn spawn_entity(&mut self, world: WorldId, builder: EntityBuilder) -> Option<Entity> {
        let next_id = self.next_entity_id;
        let mut cmd = CommandBuffer::new();
        self.run_commands(&mut cmd, vec![Command::Spawn(world, builder)]);
        self.submit_buffer(cmd);
        let new_next = self.next_entity_id;

        if next_id == new_next {
            None
        } else {
            Some(next_id)
        }
    }
}

/// Builder struct used to construct a [`Universe`].
#[derive(Default)]
pub struct UniverseBuilder {
    worlds: Vec<WorldBuilder>,
    universe_systems: UniverseSystemStorage,
    ticking_systems: TickingSystemStorage,
    entity_systems: EntitySystemStorage,
    component_systems: ComponentSystemStorage,
}

impl UniverseBuilder {
    #[must_use]
    fn new() -> Self {
        Self::default()
    }

    /// Will build a new [`Universe`] from the current builder.
    #[must_use]
    pub fn build(self) -> Universe {
        Universe::build(self)
    }

    /// Adds a [`World`] that will be created at the same time as the [`Universe`].
    #[must_use]
    pub fn with_world(mut self, builder: WorldBuilder) -> Self {
        self.worlds.push(builder);
        self
    }

    /// Adds a [`UniverseSystem`] that will be added to the [`Universe`].
    #[must_use]
    pub fn with_universe_system(mut self, system: impl UniverseSystem) -> Self {
        self.universe_systems.push(system);
        self
    }

    /// Adds a [`EntitySystem`] that will be added to the [`Universe`].
    #[must_use]
    pub fn with_entity_system(mut self, system: impl EntitySystem) -> Self {
        self.entity_systems.push(system);
        self
    }

    /// Adds a [`TickingSystem`] that will be added to the [`Universe`].
    #[must_use]
    pub fn with_ticking_system(mut self, system: impl TickingSystem) -> Self {
        self.ticking_systems.push(system);
        self
    }

    /// Adds a [`ComponentSystem`] that will be added to the [`Universe`].
    #[must_use]
    pub fn with_component_system(mut self, system: impl ComponentSystem) -> Self {
        self.component_systems.push(system);
        self
    }

    /// Will combine the `other` [`UniverseBuilder`] with this one.
    #[must_use]
    pub fn with_other(mut self, other: Self) -> Self {
        for world in other.worlds {
            self.worlds.push(world);
        }

        for system in other.universe_systems {
            self.universe_systems.push_any(system);
        }

        for system in other.entity_systems {
            self.entity_systems.push_any(system);
        }

        for system in other.ticking_systems {
            self.ticking_systems.push_any(system);
        }

        for (type_id, systems) in other.component_systems {
            for system in systems {
                self.component_systems.push_any(type_id, system);
            }
        }

        self
    }
}

#[cfg(test)]
mod tests;