crcbl-ecs 0.20.0

Crucible entity system: system-owned arrays
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
use std::fmt;

use crcbl_core::Pool;

use crate::access::AccessError;
use crate::entity::{Entity, EntityMarker};
use crate::schedule::Schedule;
use crate::shared::Shared;
use crate::system::SystemTrait;

/// The top-level ECS container.
///
/// Owns the entity [`Pool`], the [`Schedule`], and a deferred-destruction
/// queue. The typical per-frame flow is:
///
/// ```text
/// world.tick();  // schedule.run() then sweep()
/// ```
pub struct World {
    pool: Pool<EntityMarker>,
    schedule: Schedule,
    dead: Vec<Entity>,
    tick_dt: f64,
}

impl World {
    /// The tick period assumed by [`World::tick`] until
    /// [`World::set_tick_dt`] says otherwise: 60 Hz.
    pub const DEFAULT_TICK_DT: f64 = 1.0 / 60.0;

    /// Creates an empty world ticking at [`World::DEFAULT_TICK_DT`].
    ///
    /// A host that runs at any other rate **must** call
    /// [`World::set_tick_dt`], or every system that integrates over time will
    /// simulate at the wrong speed.
    #[must_use]
    pub fn new() -> Self {
        Self {
            pool: Pool::new(),
            schedule: Schedule::new(),
            dead: Vec::new(),
            tick_dt: Self::DEFAULT_TICK_DT,
        }
    }

    /// Set the fixed timestep, in seconds, handed to every system's
    /// [`SystemTrait::tick`].
    ///
    /// This is the host's real tick period — `1.0 / tick_hz` for a
    /// fixed-rate server loop.
    pub fn set_tick_dt(&mut self, dt: f64) {
        self.tick_dt = dt;
    }

    /// The fixed timestep handed to systems each tick, in seconds.
    #[must_use]
    pub fn tick_dt(&self) -> f64 {
        self.tick_dt
    }

    /// Allocates a fresh entity and returns its handle.
    ///
    /// The entity has no data until it is attached to one or more systems.
    pub fn spawn(&mut self) -> Entity {
        self.pool.insert(EntityMarker)
    }

    /// Marks `entity` for deferred destruction.
    ///
    /// The entity is *not* removed immediately. It is queued and swept at the
    /// end of the current tick (during [`sweep`](Self::sweep) or
    /// [`tick`](Self::tick)). Stale handles (already despawned or never
    /// spawned) are silently ignored.
    pub fn despawn(&mut self, entity: Entity) {
        if self.pool.contains(entity) {
            self.dead.push(entity);
        }
    }

    /// Removes every queued entity from all systems and from the pool, then
    /// clears the queue.
    ///
    /// Called automatically at the end of [`tick`](Self::tick).
    pub fn sweep(&mut self) {
        if self.dead.is_empty() {
            return;
        }
        self.schedule.sweep(&self.dead);
        for &entity in &self.dead {
            self.pool.remove(entity);
        }
        self.dead.clear();
    }

    /// Registers a [`Shared`] resource with the schedule, so a system's
    /// [`SystemTrait::access`] may name it. See [`Schedule::share`].
    ///
    /// # Errors
    ///
    /// [`AccessError::DuplicateResource`] when one of that name already is.
    pub fn share<T>(&mut self, shared: &Shared<T>) -> Result<(), AccessError> {
        self.schedule.share(shared)
    }

    /// Adds a system to the schedule. Systems run in insertion order.
    ///
    /// # Panics
    ///
    /// When the system's [`SystemTrait::access`] names a resource not
    /// registered with [`World::share`], naming both — see
    /// [`Schedule::add_system`].
    pub fn register_system(&mut self, system: Box<dyn SystemTrait>) {
        self.schedule.add_system(system);
    }

    /// Ticks each stage of the schedule across `pool`'s threads from the next
    /// tick, or every system on the calling thread with `None`, handing back
    /// the pool the world had. See [`Schedule::set_pool`].
    ///
    /// No world has a pool until it is given one: who sizes a pool is the
    /// host's decision, made against everything else it runs.
    pub fn set_pool(&mut self, pool: Option<crcbl_jobs::Pool>) -> Option<crcbl_jobs::Pool> {
        self.schedule.set_pool(pool)
    }

    /// Runs one tick at [`World::tick_dt`]: calls every system's `tick`, then
    /// sweeps dead entities.
    pub fn tick(&mut self) {
        self.tick_with_dt(self.tick_dt);
    }

    /// Runs one tick of `dt` seconds without changing the stored
    /// [`World::tick_dt`].
    ///
    /// Use this when the host already has the tick period to hand and would
    /// otherwise have to keep it in sync with the world.
    pub fn tick_with_dt(&mut self, dt: f64) {
        self.schedule.run(dt);
        self.sweep();
    }

    /// Borrows the schedule (for inspection, stats, etc.).
    pub fn schedule(&self) -> &Schedule {
        &self.schedule
    }

    /// Mutably borrows the schedule — used to reach concrete systems via
    /// [`Schedule::iter_mut`] outside of ticking (setup, tests, tooling).
    pub fn schedule_mut(&mut self) -> &mut Schedule {
        &mut self.schedule
    }

    /// The first system of type `T`, if the schedule holds one.
    ///
    /// The typed form of walking [`Schedule::iter_mut`] and downcasting, which
    /// every game that reaches for its physics system was writing out. The type
    /// is the whole query: a caller that also compares
    /// [`SystemTrait::name`] is asking the same question twice and getting a
    /// silent `None` the day the system is renamed, where the downcast keeps
    /// answering. Systems are few and this scans them, so it belongs in setup
    /// and tooling rather than inside a tick.
    pub fn system_mut<T: SystemTrait + 'static>(&mut self) -> Option<&mut T> {
        self.schedule
            .iter_mut()
            .find_map(|system| system.as_any_mut().downcast_mut::<T>())
    }

    /// Every live entity, in slot order: what a debug overlay picks one from.
    ///
    /// Like [`entity_count`](Self::entity_count), this includes entities
    /// queued for despawn until the next [`sweep`](Self::sweep).
    pub fn entities(&self) -> impl Iterator<Item = Entity> + '_ {
        self.pool.iter().map(|(entity, _)| entity)
    }

    /// Whether `entity` is still alive (in the pool, not yet swept).
    #[must_use]
    pub fn is_alive(&self, entity: Entity) -> bool {
        self.pool.contains(entity)
    }

    /// Hash every system's component state into `hasher` for determinism
    /// checks.  Delegates to [`Schedule::hash_state`].
    pub fn hash_state(&self, hasher: &mut dyn std::hash::Hasher) {
        self.schedule.hash_state(hasher);
    }

    /// Returns the names of systems that do NOT contribute component data
    /// to the determinism hash.  See [`Schedule::non_contributing_systems`].
    pub fn non_contributing_systems(&self) -> Vec<&str> {
        self.schedule.non_contributing_systems()
    }

    /// Number of entities in the pool, **including** those already queued for
    /// deferred destruction.
    ///
    /// Between [`sweep`](Self::sweep)s this is larger than the number of
    /// entities that will survive. In a `crcbl-server` run that window does not
    /// exist between ticks — `Server::tick` sweeps after the game module and
    /// before the snapshot — so a caller reading this between ticks is reading
    /// an exact count. A caller that despawns *outside* a tick and reads before
    /// the next sweep is not, and wants [`dead_queue_len`](Self::dead_queue_len).
    #[must_use]
    pub fn entity_count(&self) -> usize {
        self.pool.len()
    }

    /// Number of entries in the deferred-destruction queue.
    ///
    /// Counts *queue entries*, not distinct entities: [`despawn`](Self::despawn)
    /// pushes one per call, so despawning the same handle twice queues it twice.
    #[must_use]
    pub fn dead_queue_len(&self) -> usize {
        self.dead.len()
    }
}

impl fmt::Debug for World {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("World")
            .field("entity_count", &self.pool.len())
            .field("schedule", &self.schedule)
            .field("dead_queue_len", &self.dead.len())
            .finish()
    }
}

impl Default for World {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::system::System;

    #[test]
    fn spawn_and_despawn_lifecycle() {
        let mut world = World::new();
        let e = world.spawn();
        assert!(world.is_alive(e));
        assert_eq!(world.entity_count(), 1);

        world.despawn(e);
        // Not removed yet — sweep hasn't run.
        assert!(world.is_alive(e));
        assert_eq!(world.dead_queue_len(), 1);

        world.sweep();
        assert!(!world.is_alive(e));
        assert_eq!(world.entity_count(), 0);
        assert_eq!(world.dead_queue_len(), 0);
    }

    #[test]
    fn despawn_stale_handle_is_noop() {
        let mut world = World::new();
        let stale = crate::test_entity(0xDEAD, 1);
        world.despawn(stale);
        assert_eq!(world.dead_queue_len(), 0);
    }

    #[test]
    fn double_despawn_queues_once() {
        let mut world = World::new();
        let e = world.spawn();
        world.despawn(e);
        world.despawn(e);
        assert_eq!(world.dead_queue_len(), 2); // queued twice but sweep handles it
        world.sweep();
        assert!(!world.is_alive(e));
    }

    #[test]
    fn tick_runs_systems_then_sweeps() {
        let mut world = World::new();
        let e = world.spawn();
        world.despawn(e);

        // Register a system that records whether it was ticked.
        struct Record {
            ticked: bool,
        }
        impl SystemTrait for Record {
            fn name(&self) -> &str {
                "rec"
            }
            fn access(&self) -> crate::Access {
                crate::Access::none()
            }
            fn tick(&mut self, _dt: f64) {
                self.ticked = true;
            }
            fn entity_count(&self) -> usize {
                0
            }
            fn sweep(&mut self, _dead: &[Entity]) {}
            fn debug_draw(&mut self, _ctx: &crate::system::DebugCtx) {}
            fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
                self
            }
        }

        let rec = Record { ticked: false };
        world.register_system(Box::new(rec));
        world.tick();
        assert!(!world.is_alive(e));
        assert!(
            world
                .system_mut::<Record>()
                .expect("the registered system is still there")
                .ticked,
            "the sweep having run says nothing about the system having ticked — \
             this reads the flag the system set"
        );
    }

    /// The type is the whole query, so a system answers to it under any name.
    ///
    /// This is the property that made the four samples' hand-written
    /// `with_physics` fragile: each compared `name() == "physics"` before
    /// downcasting, so renaming the system would have turned every physics call
    /// in every game into a silent no-op with nothing failing to say so.
    #[test]
    fn a_system_is_found_by_its_type_whatever_it_is_called() {
        struct Odd(u32);
        impl SystemTrait for Odd {
            fn name(&self) -> &str {
                "not the name anybody would guess"
            }
            fn access(&self) -> crate::Access {
                crate::Access::none()
            }
            fn tick(&mut self, _dt: f64) {}
            fn entity_count(&self) -> usize {
                0
            }
            fn sweep(&mut self, _dead: &[Entity]) {}
            fn debug_draw(&mut self, _ctx: &crate::system::DebugCtx) {}
            fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
                self
            }
        }

        let mut world = World::new();
        world.register_system(Box::new(Odd(7)));
        assert_eq!(
            world.system_mut::<Odd>().map(|odd| odd.0),
            Some(7),
            "the downcast is what answers, not the name"
        );

        world.system_mut::<Odd>().expect("registered above").0 = 9;
        assert_eq!(
            world.system_mut::<Odd>().map(|odd| odd.0),
            Some(9),
            "the borrow is the real system, not a copy of it"
        );
    }

    /// A type the schedule does not hold is `None`, not the wrong system.
    #[test]
    fn asking_for_a_system_that_is_not_there_answers_none() {
        let mut world = World::new();
        world.register_system(Box::new(System::<i32>::new("ints")));
        assert!(
            world.system_mut::<System<u8>>().is_none(),
            "a different component type is a different system"
        );
        assert!(
            world.system_mut::<System<i32>>().is_some(),
            "and the one that is there is still found"
        );
    }

    #[test]
    fn sweep_removes_from_all_systems() {
        let mut world = World::new();
        let e = world.spawn();

        let mut s1 = System::<i32>::new("s1");
        s1.attach(e, 10);
        let mut s2 = System::<i32>::new("s2");
        s2.attach(e, 20);

        world.register_system(Box::new(s1));
        world.register_system(Box::new(s2));
        world.despawn(e);
        world.sweep();

        let stats: Vec<_> = world.schedule().stats().collect();
        assert_eq!(stats, vec![("s1".into(), 0), ("s2".into(), 0)]);
    }

    #[test]
    fn respawn_after_despawn_gives_new_generation() {
        let mut world = World::new();
        let old = world.spawn();
        world.despawn(old);
        world.sweep();

        let new = world.spawn();
        assert_ne!(old.generation(), new.generation());
        // Old handle must not resolve.
        assert!(!world.is_alive(old));
        assert!(world.is_alive(new));
    }

    #[test]
    fn stale_handle_in_system_get_returns_none() {
        let mut world = World::new();
        let e = world.spawn();
        let mut sys = System::<i32>::new("test");
        sys.attach(e, 42);
        world.register_system(Box::new(sys));

        world.despawn(e);
        world.sweep();

        // Entity is gone from pool; systems in the schedule have been swept.
        let stats: Vec<_> = world.schedule().stats().collect();
        assert_eq!(stats, vec![("test".into(), 0)]);
    }

    #[test]
    fn entities_lists_the_live_ones_and_drops_the_swept() {
        let mut world = World::new();
        let (a, b, c) = (world.spawn(), world.spawn(), world.spawn());
        assert_eq!(world.entities().collect::<Vec<_>>(), vec![a, b, c]);

        world.despawn(b);
        world.sweep();
        assert_eq!(world.entities().collect::<Vec<_>>(), vec![a, c]);
    }

    #[test]
    fn the_worlds_debug_output_reports_how_many_entities_it_holds() {
        let mut world = World::new();
        world.spawn();
        world.spawn();
        let s = format!("{world:?}");
        assert!(s.contains("entity_count: 2"));
    }
}