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
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
use std::collections::HashMap;
use std::fmt;
use std::hash::Hasher;

use crcbl_reflect::Reflect;

use crate::access::Access;
use crate::component_hash::ComponentHash;
use crate::entity::Entity;

/// Stub struct for debug-draw context.
///
/// Empty for now; this is the hook point for future visualization tooling.
/// Systems with a debug-draw callback receive a `&DebugCtx` each tick so they
/// can push lines, labels, or shapes to a shared draw list without depending
/// on any renderer crate.
#[derive(Debug)]
pub struct DebugCtx;

/// Callback type for per-system debug drawing.
///
/// Set via [`System::set_debug_draw`]; called once per tick with a
/// [`&DebugCtx`](DebugCtx). `Send` because the [`System`] holding it is a
/// [`SystemTrait`], which a schedule may tick on another thread.
pub type DebugDrawFn = Box<dyn FnMut(&DebugCtx) + Send>;

// ---------------------------------------------------------------------------
// Object-safe trait
// ---------------------------------------------------------------------------

/// Object-safe trait every system in the [`Schedule`](crate::Schedule) must
/// implement.
///
/// The concrete [`System<T>`] implements this automatically; custom systems
/// (e.g. systems that tick multiple arrays at once) implement it directly.
///
/// **`Send`**, because a [`Schedule`](crate::Schedule) given a pool ticks the
/// systems of one stage on the pool's threads
/// ([`Schedule::set_pool`](crate::Schedule::set_pool)). A system holding an
/// `Rc` or a `RefCell` handle shares it with something on another thread, and
/// the bound is what makes that a compile error rather than a race.
pub trait SystemTrait: Send {
    /// Human-readable name for the inspector / debug overlay.
    fn name(&self) -> &str;

    /// Called once per tick by the schedule.
    ///
    /// `dt` is the schedule's fixed timestep in seconds — the real tick
    /// period, not an assumed one. A system that integrates over time must
    /// use it, or its simulated speed becomes a function of the tick rate.
    /// See [`World::set_tick_dt`](crate::World::set_tick_dt).
    fn tick(&mut self, dt: f64);

    /// The [`Shared`](crate::Shared) resources this system's
    /// [`tick`](Self::tick) reads and writes — everything it touches beyond
    /// its own arrays.
    ///
    /// **Required, with no default**, so that no system inherits "touches
    /// nothing" by forgetting to answer: a schedule that took a missing answer
    /// for independence would order nothing and say so confidently. A system
    /// whose tick works on its own arrays alone answers [`Access::none`].
    ///
    /// Asked once, when the system is registered
    /// ([`Schedule::add_system`](crate::Schedule::add_system)): the schedule
    /// refuses a name not registered with it, derives the system's conflicts
    /// with those registered before it, and in debug builds panics if the
    /// tick touches a resource the answer left out.
    fn access(&self) -> Access;

    /// Number of entities currently registered with this system.
    fn entity_count(&self) -> usize;

    /// Remove every entity listed in `dead` from this system.
    ///
    /// Called once per tick, after `tick`, with the set of entities that were
    /// despawned during this tick.
    fn sweep(&mut self, dead: &[Entity]);

    /// Called once per tick so the system can emit debug-draw primitives.
    ///
    /// The default implementation is a no-op; override this rather than
    /// setting a callback if the system needs access to its own data.
    fn debug_draw(&mut self, ctx: &DebugCtx);

    /// Hash the system's component state into `hasher`.
    ///
    /// The default implementation is a no-op.  Override this to feed
    /// per-entity component data into a determinism hash (used by
    /// `crcbl-server`'s sim-hash harness).
    fn hash_state(&self, _hasher: &mut dyn Hasher) {}

    /// Whether this system's `SystemTrait::hash_state` contributes
    /// component data to the determinism hash.
    ///
    /// Returns `false` by default — systems that override `hash_state`
    /// must also override this to return `true`, otherwise the
    /// determinism harness will warn that they are not contributing.
    /// The concrete [`System<T>`] returns `true`.
    fn contributes_to_hash(&self) -> bool {
        false
    }

    /// Serialise this system's per-entity component data for replication.
    ///
    /// Appends `(entity_bits: u64, data_len: u32, data: [u8])` triples — all
    /// little-endian — to `out`, one per replicated entity. Returns `true`
    /// if any data was written.
    ///
    /// The default returns `false` (system not replicated); the server then
    /// emits only the entity count for this system. Custom systems that own
    /// their component arrays (e.g. `crcbl-phys`' `PhysicsSystem`) override
    /// this to publish real state.
    fn replicate(&self, _out: &mut Vec<u8>) -> bool {
        false
    }

    /// What this system holds for `entity`, for a debug overlay to show.
    ///
    /// A selected entity is described by every system that answers `Some`
    /// here, one section each, with the overlay walking the value's
    /// [`Reflect::fields`] — so a system describes itself through data, and
    /// this crate never names a UI. `None` when the system holds nothing for
    /// `entity`, and always from this default.
    ///
    /// **The default is not a check that passes by doing nothing**: nothing is
    /// verified through this method, and a system that does not override it is
    /// one the overlay lists no section for — the same complete answer
    /// [`SystemTrait::replicate`]'s `false` gives the server. The concrete
    /// [`System<T>`] answers when it was built with [`System::reflected`]; a
    /// custom system lends whichever of its rows it has a [`Reflect`] value
    /// for.
    fn debug_fields(&self, _entity: Entity) -> Option<&dyn Reflect> {
        None
    }

    /// Downcast support for callers that hold `&mut dyn SystemTrait` (e.g.
    /// through [`Schedule::iter_mut`](crate::Schedule::iter_mut)) and need the
    /// concrete system type.
    /// Implementations are the one-liner `self`.
    fn as_any_mut(&mut self) -> &mut dyn std::any::Any;
}

impl fmt::Debug for dyn SystemTrait {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("dyn SystemTrait")
            .field("name", &self.name())
            .field("entity_count", &self.entity_count())
            .finish()
    }
}

// ---------------------------------------------------------------------------
// Concrete System<T>
// ---------------------------------------------------------------------------

/// A system that owns a dense `Vec<T>` of component data plus a sparse
/// entity→index map.
///
/// # Layout
///
/// * `data: Vec<T>` — the values, stored contiguously for cache-friendly
///   iteration.
/// * `index_to_entity: Vec<Entity>` — parallel to `data`; `index_to_entity[i]`
///   is the entity that owns `data[i]`.
/// * `entity_to_index: HashMap<Entity, usize>` — inverse of the above; answers
///   "where is this entity's data?" in O(1).
///
/// Removal uses swap-remove on both vectors and updates the moved entity's
/// mapping, so removal is O(1) but does not preserve insertion order.
pub struct System<T> {
    name: String,
    data: Vec<T>,
    entity_to_index: HashMap<Entity, usize>,
    index_to_entity: Vec<Entity>,
    debug_draw_fn: Option<DebugDrawFn>,
    /// How a row is lent to [`SystemTrait::debug_fields`]: set by
    /// [`System::reflected`], `None` from [`System::new`].
    reflect: Option<ReflectRow<T>>,
}

/// A row seen as [`Reflect`]; see [`System::reflected`] for why it is a stored
/// function rather than a bound.
type ReflectRow<T> = fn(&T) -> &dyn Reflect;

/// [`ReflectRow`] for a `T` that is [`Reflect`]: the unsizing coercion, named
/// so it can be stored as a function pointer.
fn reflect_row<T: Reflect>(row: &T) -> &dyn Reflect {
    row
}

impl<T> System<T> {
    /// Creates an empty system with the given human-readable `name`.
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            data: Vec::new(),
            entity_to_index: HashMap::new(),
            index_to_entity: Vec::new(),
            debug_draw_fn: None,
            reflect: None,
        }
    }

    /// The system's name (same as [`SystemTrait::name`]).
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    // -- registration -------------------------------------------------------

    /// Registers `entity` with this system, storing `data`.
    ///
    /// If `entity` is already registered, its existing data is overwritten
    /// in-place. Otherwise a new entry is pushed.
    ///
    /// `entity` must be alive. A system owns no entity pool and so cannot
    /// check: attaching a handle that [`World::sweep`](crate::World::sweep)
    /// has already retired stores data that nothing will ever remove, and it
    /// counts towards [`SystemTrait::entity_count`] and
    /// [`SystemTrait::hash_state`] for the rest of the run.
    pub fn attach(&mut self, entity: Entity, data: T) {
        if let Some(&index) = self.entity_to_index.get(&entity) {
            self.data[index] = data;
        } else {
            let index = self.data.len();
            self.data.push(data);
            self.index_to_entity.push(entity);
            self.entity_to_index.insert(entity, index);
        }
    }

    /// Removes `entity` from this system, returning its data if it was
    /// registered.
    ///
    /// Uses swap-remove: O(1) but may reorder the remaining entries.
    pub fn detach(&mut self, entity: Entity) -> Option<T> {
        let index = self.entity_to_index.remove(&entity)?;
        let last = self.data.len() - 1;
        if index != last {
            self.data.swap(index, last);
            self.index_to_entity.swap(index, last);
            let moved_entity = self.index_to_entity[index];
            self.entity_to_index.insert(moved_entity, index);
        }
        self.index_to_entity.pop();
        Some(self.data.pop().unwrap())
    }

    // -- lookup ---------------------------------------------------------------

    /// Borrows the data for `entity`, or `None` if it isn't registered.
    #[must_use]
    pub fn get(&self, entity: Entity) -> Option<&T> {
        let &index = self.entity_to_index.get(&entity)?;
        Some(&self.data[index])
    }

    /// Mutably borrows the data for `entity`.
    #[must_use]
    pub fn get_mut(&mut self, entity: Entity) -> Option<&mut T> {
        let &index = self.entity_to_index.get(&entity)?;
        Some(&mut self.data[index])
    }

    // -- iteration -----------------------------------------------------------

    /// Iterates all component data in storage order (contiguous, cache-friendly).
    pub fn iter(&self) -> impl Iterator<Item = &T> {
        self.data.iter()
    }

    /// Mutably iterates all component data in storage order.
    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> {
        self.data.iter_mut()
    }

    /// Iterates `(entity, &data)` pairs.
    pub fn iter_entities(&self) -> impl Iterator<Item = (Entity, &T)> {
        self.index_to_entity.iter().copied().zip(self.data.iter())
    }

    // -- debug draw ----------------------------------------------------------

    /// Sets a callback invoked each tick by [`SystemTrait::debug_draw`].
    ///
    /// Pass `None` to clear a previously-set callback.
    pub fn set_debug_draw(&mut self, f: Option<DebugDrawFn>) {
        self.debug_draw_fn = f;
    }
}

impl<T: Reflect> System<T> {
    /// [`System::new`], for a component a debug overlay can read: this
    /// system's [`SystemTrait::debug_fields`] answers with the entity's row.
    ///
    /// **A constructor rather than a bound**, because the bound cannot be
    /// added: `SystemTrait` is implemented for every `System<T>` whose `T` is
    /// [`ComponentHash`], tuples and `char` among them, and neither of those is
    /// [`Reflect`]. Bounding that impl on `Reflect` would stop every such
    /// system from being registered at all, and stable Rust has no
    /// specialisation to answer differently for the `T` that is. So the choice
    /// is made where `T` is known to be `Reflect` — here — and kept as the one
    /// function pointer that coercion needs.
    #[must_use]
    pub fn reflected(name: impl Into<String>) -> Self {
        Self {
            reflect: Some(reflect_row::<T>),
            ..Self::new(name)
        }
    }
}

impl<T: ComponentHash + Send + 'static> SystemTrait for System<T> {
    fn name(&self) -> &str {
        &self.name
    }

    fn tick(&mut self, _dt: f64) {
        // Default: no-op. Users that need per-tick logic iterate the system
        // directly or implement `SystemTrait` on their own type.
    }

    /// Nothing shared: the tick does nothing, and the arrays are its own.
    fn access(&self) -> Access {
        Access::none()
    }

    fn entity_count(&self) -> usize {
        self.data.len()
    }

    fn sweep(&mut self, dead: &[Entity]) {
        for &entity in dead {
            self.detach(entity);
        }
    }

    fn debug_draw(&mut self, ctx: &DebugCtx) {
        if let Some(ref mut f) = self.debug_draw_fn {
            f(ctx);
        }
    }

    /// Hashes `(entity, component)` pairs in ascending entity order.
    ///
    /// Storage order is not canonical — `detach` swap-removes, so two systems
    /// holding the same logical state reach different `data` orders from
    /// different attach/detach histories. Sorting by entity makes the hash a
    /// function of the state alone.
    fn hash_state(&self, hasher: &mut dyn Hasher) {
        let mut order: Vec<usize> = (0..self.data.len()).collect();
        order.sort_unstable_by_key(|&i| self.index_to_entity[i].to_bits());
        for i in order {
            hasher.write(&self.index_to_entity[i].to_bits().to_le_bytes());
            self.data[i].hash_component(hasher);
        }
    }

    fn contributes_to_hash(&self) -> bool {
        true
    }

    /// The entity's row, when this system was built with
    /// [`System::reflected`].
    fn debug_fields(&self, entity: Entity) -> Option<&dyn Reflect> {
        let reflect = self.reflect?;
        self.get(entity).map(reflect)
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }
}

impl<T> fmt::Debug for System<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("System")
            .field("name", &self.name)
            .field("entity_count", &self.data.len())
            .finish()
    }
}

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

#[cfg(test)]
mod tests {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};

    use super::*;

    fn e(idx: u32) -> Entity {
        crate::test_entity(idx, 1)
    }

    #[test]
    fn a_component_attached_to_an_entity_is_what_get_answers_with() {
        let mut sys = System::<i32>::new("test");
        let ent = e(1);
        sys.attach(ent, 42);
        assert_eq!(sys.get(ent), Some(&42));
    }

    #[test]
    fn attaching_twice_to_one_entity_replaces_the_value_without_adding_a_row() {
        let mut sys = System::<i32>::new("test");
        let ent = e(1);
        sys.attach(ent, 10);
        sys.attach(ent, 99);
        assert_eq!(sys.entity_count(), 1);
        assert_eq!(sys.get(ent), Some(&99));
    }

    #[test]
    fn detach_removes_and_reorders() {
        let mut sys = System::<i32>::new("test");
        let a = e(1);
        let b = e(2);
        let c = e(3);
        sys.attach(a, 1);
        sys.attach(b, 2);
        sys.attach(c, 3);

        assert_eq!(sys.detach(b), Some(2));
        assert_eq!(sys.entity_count(), 2);
        assert_eq!(sys.get(b), None);
        // a and c must still be present
        assert!(sys.get(a).is_some());
        assert!(sys.get(c).is_some());
    }

    #[test]
    fn detach_unknown_returns_none() {
        let mut sys = System::<i32>::new("test");
        let ent = e(42);
        assert_eq!(sys.detach(ent), None);
    }

    #[test]
    fn double_detach_is_safe() {
        let mut sys = System::<i32>::new("test");
        let ent = e(1);
        sys.attach(ent, 7);
        assert_eq!(sys.detach(ent), Some(7));
        assert_eq!(sys.detach(ent), None);
        assert_eq!(sys.entity_count(), 0);
    }

    #[test]
    fn iter_yields_all_values() {
        let mut sys = System::<i32>::new("test");
        sys.attach(e(1), 10);
        sys.attach(e(2), 20);
        let mut sum = 0;
        for v in sys.iter() {
            sum += *v;
        }
        assert_eq!(sum, 30);
    }

    #[test]
    fn iter_mut_allows_mutation() {
        let mut sys = System::<i32>::new("test");
        let a = e(1);
        let b = e(2);
        sys.attach(a, 1);
        sys.attach(b, 2);
        for v in sys.iter_mut() {
            *v *= 10;
        }
        assert_eq!(sys.get(a), Some(&10));
        assert_eq!(sys.get(b), Some(&20));
    }

    #[test]
    fn iter_entities_yields_pairs() {
        let mut sys = System::<&str>::new("test");
        let a = e(10);
        let b = e(20);
        sys.attach(a, "alpha");
        sys.attach(b, "beta");

        let mut pairs: Vec<_> = sys.iter_entities().map(|(ent, d)| (ent, *d)).collect();
        pairs.sort_by_key(|(ent, _)| ent.to_bits());
        assert_eq!(pairs, vec![(a, "alpha"), (b, "beta")]);
    }

    #[test]
    fn sweep_removes_dead_entities() {
        let mut sys = System::<i32>::new("test");
        let a = e(1);
        let b = e(2);
        let c = e(3);
        sys.attach(a, 1);
        sys.attach(b, 2);
        sys.attach(c, 3);

        sys.sweep(&[b, c]);
        assert_eq!(sys.entity_count(), 1);
        assert!(sys.get(a).is_some());
        assert!(sys.get(b).is_none());
        assert!(sys.get(c).is_none());
    }

    #[test]
    fn sweep_empty_dead_list_is_noop() {
        let mut sys = System::<i32>::new("test");
        sys.attach(e(1), 42);
        sys.sweep(&[]);
        assert_eq!(sys.entity_count(), 1);
    }

    #[test]
    fn sweep_unknown_entity_is_noop() {
        let mut sys = System::<i32>::new("test");
        sys.attach(e(1), 42);
        let ghost = e(999);
        sys.sweep(&[ghost]);
        assert_eq!(sys.entity_count(), 1);
    }

    #[test]
    fn debug_draw_callback_is_called() {
        let mut sys = System::<i32>::new("test");
        let called = Arc::new(AtomicBool::new(false));
        let called2 = Arc::clone(&called);
        sys.set_debug_draw(Some(Box::new(move |_ctx| {
            called2.store(true, Ordering::SeqCst);
        })));
        sys.debug_draw(&DebugCtx);
        assert!(called.load(Ordering::SeqCst));
    }

    /// The neighbour above proves the hook is called when one is set; this is
    /// the other half, and it used to be spelled as "must not panic" — which a
    /// `debug_draw` that called a *stale* callback would also satisfy.
    #[test]
    fn debug_draw_without_a_callback_calls_nothing() {
        let mut sys = System::<i32>::new("test");
        let called = Arc::new(AtomicBool::new(false));
        let called2 = Arc::clone(&called);
        sys.set_debug_draw(Some(Box::new(move |_ctx| {
            called2.store(true, Ordering::SeqCst);
        })));
        sys.set_debug_draw(None);

        sys.debug_draw(&DebugCtx);
        assert!(
            !called.load(Ordering::SeqCst),
            "a callback that has been taken away must not still run"
        );
    }

    #[test]
    fn hash_state_ignores_attach_and_detach_history() {
        use std::collections::hash_map::DefaultHasher;

        fn hash(sys: &System<i32>) -> u64 {
            let mut h = DefaultHasher::new();
            sys.hash_state(&mut h);
            h.finish()
        }

        let (a, b, c) = (e(1), e(2), e(3));

        // Same logical state, reached two ways.  The second system's `data`
        // ends up in swap-remove order, which is not ascending entity order.
        let mut direct = System::<i32>::new("s");
        direct.attach(a, 10);
        direct.attach(b, 20);
        direct.attach(c, 30);

        let mut churned = System::<i32>::new("s");
        churned.attach(c, 30);
        churned.attach(e(4), 40);
        churned.attach(a, 10);
        churned.detach(e(4));
        churned.attach(b, 20);

        assert_eq!(hash(&direct), hash(&churned));

        // The hash still tracks the state itself.
        let mut changed = System::<i32>::new("s");
        changed.attach(a, 10);
        changed.attach(b, 20);
        changed.attach(c, 31);
        assert_ne!(hash(&direct), hash(&changed));
    }

    #[test]
    fn a_system_reports_the_name_it_was_built_with() {
        let sys = System::<i32>::new("physics");
        assert_eq!(sys.name(), "physics");
    }

    /// A component an overlay can read, with a field the reflection is
    /// checked against by name and by value.
    #[derive(crcbl_reflect::Reflect, Clone, Copy, Debug, PartialEq)]
    struct Health {
        current: i32,
        #[reflect(name = "Max")]
        max: i32,
    }

    impl ComponentHash for Health {
        fn hash_component(&self, hasher: &mut dyn Hasher) {
            self.current.hash_component(hasher);
            self.max.hash_component(hasher);
        }
    }

    #[test]
    fn a_reflected_system_lends_the_entitys_own_row_and_nothing_for_others() {
        use crcbl_reflect::{Value, get_path};

        let (held, other, absent) = (e(1), e(2), e(3));
        let mut sys = System::<Health>::reflected("health");
        sys.attach(other, Health { current: 1, max: 2 });
        sys.attach(held, Health { current: 7, max: 9 });

        let row = sys
            .debug_fields(held)
            .expect("the system holds this entity");
        assert_eq!(row.type_name(), "Health");
        assert_eq!(row.fields()[1].label, "Max");
        assert_eq!(
            get_path(row, "current"),
            Ok(Value::Int(7)),
            "the row is this entity's, not the first one stored"
        );
        assert_eq!(get_path(row, "max"), Ok(Value::Int(9)));

        assert!(
            sys.debug_fields(absent).is_none(),
            "an entity the system does not hold has no row to lend"
        );
    }

    #[test]
    fn a_system_that_lends_nothing_answers_none() {
        struct Silent;
        impl SystemTrait for Silent {
            fn name(&self) -> &str {
                "silent"
            }
            fn access(&self) -> Access {
                Access::none()
            }
            fn tick(&mut self, _dt: f64) {}
            fn entity_count(&self) -> usize {
                1
            }
            fn sweep(&mut self, _dead: &[Entity]) {}
            fn debug_draw(&mut self, _ctx: &DebugCtx) {}
            fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
                self
            }
        }
        assert!(
            Silent.debug_fields(e(1)).is_none(),
            "the default lends nothing, whatever the system holds"
        );

        // `System::new` keeps the rows to itself even for a `T` that is
        // `Reflect`: only `System::reflected` opts in.
        let mut plain = System::<Health>::new("plain");
        plain.attach(e(1), Health { current: 1, max: 1 });
        assert!(plain.debug_fields(e(1)).is_none());
    }

    #[test]
    fn a_systems_debug_output_names_it_and_reports_its_entity_count() {
        let mut sys = System::<i32>::new("render");
        sys.attach(e(7), 1);
        let s = format!("{sys:?}");
        assert!(s.contains("render"));
        assert!(s.contains("entity_count: 1"));
    }
}