primase-core 0.2.0

primase core: the world store, core components, frames, the pass manager and gates
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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
//! What a pass leaves out on purpose, by name: the measures a drop is counted in ([`Measure`]) and the helper that
//! despawns an entity declaring what it held ([`despawn`]). A pass records a drop with [`PassLog::dropped`]; a
//! conversion reports every drop as a selection notice ([`crate::convert::ConvertReport::notices`]).
//!
//! **Conservation diagnostics** (opt in: [`crate::pass::PassManager::with_conservation`]; off by default, and then
//! nothing below runs): the manager counts the four measures before and after each pass and compares what it lost
//! with what it declared ([`Conservation::Report`] records each difference in the step's report and as a diagnostic
//! notice; [`Conservation::Enforce`] fails the pass, for tests). A difference is a coverage finding (a pass that leaves
//! something out without saying so, or says so wrongly), never a reason to change content to satisfy the count.
//!
//! - **Placements**: entities with a `core.instance`. Exact: each one despawned, or that lost its instance, is a drop.
//! - **Textures**: entities with a `core.texture`, a `core.texture_layers` or a `core.texture_file`. Exact, by entity:
//!   loading a file into pixels keeps the entity and is no drop; a texture despawned or left with none is one.
//! - **Primitives**: the primitives of a `core.mesh`. Exact through [`World::rebuild_primitives`]: a source primitive
//!   none of the rebuilt ones comes from is a drop. Meshes are told apart by identity ([`Mesh::new`] makes a new one; a
//!   clone, an in-place edit and [`World::apply_linear`] keep it), never by their primitive count, and followed by it:
//!   a mesh gone from its entity that stands on another with its identity (moved with [`World::move_components`], or a
//!   [`World::duplicate`] or clone standing in for an entity despawned) is compared there as if it had stayed, exactly.
//!   A copy made beside a mesh that stays is an addition. A mesh replaced by another identity (a new [`Mesh`] inserted
//!   or assigned, or despawned with its entity and found nowhere), before, between or after rebuilds, is counted net
//!   over all such meshes; the meshes that appeared (a loaded file, a form's new mesh) add to that balance.
//! - **Triangles**: inside kept primitives only (a dropped primitive's triangles go with it): per source primitive of a
//!   rebuild, what its pieces lost; per mesh edited in place ([`Mesh::primitives_mut`]), what each primitive lost. Net
//!   per primitive. Triangles are those of [`Topology::Triangles`] primitives, core's only triangle topology.
//!
//! What it does not see: the triangle losses of a mesh replaced by another identity (counted net by primitives only),
//! topologies other than triangle lists, anything outside the four measures (collision soups, lights, markers, source
//! namespaces) and changes that keep the counts (a moved vertex, a recoloured texture). It is a check of declarations,
//! not proof of fidelity.
//!
//! - **Collision triangles** ([`Measure::CollisionTriangles`]) are declared and reported, never measured: collision
//!   soups are outside what it counts, so a declared collision drop is reported as a notice like any other and left
//!   out of the comparison.
//!
//! Adding is never a drop and needs no declaration.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;

use crate::TextureLayers;
use crate::asset::Asset;
use crate::clip::ClipBinding;
use crate::components::{Instance, Mesh, Texture, TextureFile, Topology};
use crate::pass::PassLog;
use crate::world::{Entity, RebuildLog, Rebuilt, World};

/// What a drop is counted in.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Measure {
    Placements,
    Primitives,
    Triangles,
    Textures,
    /// Triangles of collision soups (`core.collision`): declared and reported, not measured (see the module).
    CollisionTriangles,
}

impl Measure {
    pub const ALL: [Measure; 5] = [
        Measure::Placements,
        Measure::Primitives,
        Measure::Triangles,
        Measure::Textures,
        Measure::CollisionTriangles,
    ];

    /// Whether the diagnostics count it before and after a pass (every measure but collision triangles).
    pub const fn measured(self) -> bool {
        !matches!(self, Measure::CollisionTriangles)
    }
}

impl fmt::Display for Measure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Measure::Placements => "placements",
            Measure::Primitives => "primitives",
            Measure::Triangles => "triangles",
            Measure::Textures => "textures",
            Measure::CollisionTriangles => "collision triangles",
        })
    }
}

/// What `e` holds of the measures: a placement, a texture, its mesh's primitives.
pub fn held(w: &World, e: Entity) -> Vec<(Measure, u64)> {
    let mut out = Vec::new();
    if w.has::<Instance>(e) {
        out.push((Measure::Placements, 1));
    }
    if w.has::<Texture>(e) || w.has::<TextureLayers>(e) || w.has::<TextureFile>(e) {
        out.push((Measure::Textures, 1));
    }
    if let Some(m) = w.get::<Mesh>(e) {
        out.push((Measure::Primitives, m.primitives().len() as u64));
    }
    out
}

/// Despawn `e` on purpose, declaring in `log` what it held ([`held`]) as left out for `why`. False, and nothing
/// declared, when it was not alive. Every `core.asset` that lists `e` as a member stops listing it (an asset naming an
/// entity that is gone is not an asset the world verifies), counted as "asset members dropped with the entity they
/// listed", and every `core.clip_binding` that names `e` as a mesh it drives stops naming it ([`unbind`]); a pass that
/// despawns entities an asset or a clip binding may name declares that it modifies `core.asset` or `core.clip_binding`.
pub fn despawn(w: &mut World, e: Entity, log: &mut PassLog, why: &str) -> bool {
    if !w.is_alive(e) {
        return false;
    }
    for (m, n) in held(w, e) {
        log.dropped(m, why, n);
    }
    let gone = w.despawn(e);
    unlist(w, e, log);
    unbind(w, e, log);
    gone
}

/// Every `core.clip_binding` that names `e` among the mesh occurrences its clip drives stops naming it, counted as
/// "clip binding meshes dropped with the entity they named": the clip still drives the occurrences that remain, and a
/// binding naming an entity that is gone is not one the world verifies. The binding's clip and rig are not touched.
pub fn unbind(w: &mut World, e: Entity, log: &mut PassLog) {
    let naming: Vec<Entity> = w
        .iter::<ClipBinding>()
        .filter(|(_, b)| b.meshes.contains(&e))
        .map(|(b, _)| b)
        .collect();
    for b in naming {
        if let Some(binding) = w.get_mut::<ClipBinding>(b) {
            let before = binding.meshes.len();
            binding.meshes.retain(|m| *m != e);
            log.count(
                "clip binding meshes dropped with the entity they named",
                (before - binding.meshes.len()) as u64,
            );
        }
    }
}

/// Every `core.asset` that lists `e` as a member stops listing it, counted as "asset members dropped with the entity they
/// listed". For a pass that despawns an entity whose primitives or placements are kept elsewhere, and so declares nothing
/// left out ([`despawn`] declares what the entity held); it declares that it modifies `core.asset`.
pub fn unlist(w: &mut World, e: Entity, log: &mut PassLog) {
    let listing: Vec<Entity> = w
        .iter::<Asset>()
        .filter(|(_, a)| a.members.iter().any(|(m, _)| *m == e))
        .map(|(a, _)| a)
        .collect();
    for a in listing {
        if let Some(asset) = w.get_mut::<Asset>(a) {
            let before = asset.members.len();
            asset.members.retain(|(m, _)| *m != e);
            log.count(
                "asset members dropped with the entity they listed",
                (before - asset.members.len()) as u64,
            );
        }
    }
}

/// Whether the pass manager runs the conservation diagnostics (see the module documentation).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Conservation {
    /// Not counted (the default): no scan, no cost.
    #[default]
    Off,
    /// Counted; each difference recorded in the step's report ([`crate::pass::StepReport::conservation`]).
    Report,
    /// Counted; a difference fails the pass ([`crate::pass::Error::Conservation`]).
    Enforce,
}

/// A pass whose losses in `measure` differ from what it declared.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Gap {
    pub measure: Measure,
    /// What it left out, counted.
    pub dropped: u64,
    /// What it declared ([`PassLog::declared`]).
    pub declared: u64,
}

impl fmt::Display for Gap {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} left out {} but declared {}",
            self.measure, self.dropped, self.declared
        )
    }
}

/// Triangles of each primitive of a mesh (0 for other topologies).
fn triangles(mesh: &Mesh) -> Vec<u64> {
    mesh.primitives()
        .iter()
        .map(|p| match p.topology {
            Topology::Triangles => (p.indices.as_ref().map_or(p.vertex_count(), Vec::len) / 3) as u64,
            _ => 0,
        })
        .collect()
}

/// What a mesh `before` of identity `id` lost, primitives and triangles, if what now stands in its place is it,
/// rebuilt (the last rebuild `rebuild` made `now` from it) or edited in place at most; `None` when it is not.
fn exact(
    before: &[u64],
    id: u64,
    rebuild: Option<&Option<Rebuilt>>,
    now: Option<&(u64, Vec<u64>)>,
) -> Option<(u64, u64)> {
    let (now_id, now) = now?;
    match rebuild {
        Some(Some(r)) if r.source == id && r.made == *now_id => {
            let kept: BTreeSet<usize> = r.from.iter().copied().collect();
            let mut tris = 0;
            for &j in &kept {
                let pieces: u64 = r
                    .from
                    .iter()
                    .zip(now)
                    .filter(|(i, _)| **i == j)
                    .map(|(_, t)| t)
                    .sum();
                tris += before[j].saturating_sub(pieces);
            }
            Some(((r.first - kept.len()) as u64, tris))
        }
        None if now_id == &id => Some((0, before.iter().zip(now).map(|(b, a)| b.saturating_sub(*a)).sum())),
        _ => None,
    }
}

/// The world as the diagnostics see it before a pass.
#[derive(Debug)]
pub(crate) struct Before {
    placements: BTreeSet<Entity>,
    textures: BTreeSet<Entity>,
    /// Per mesh, its identity and its primitives' triangles.
    meshes: BTreeMap<Entity, (u64, Vec<u64>)>,
}

impl Before {
    pub(crate) fn take(w: &World) -> Self {
        let mut textures: BTreeSet<Entity> = w.iter::<Texture>().map(|(e, _)| e).collect();
        textures.extend(w.iter::<TextureLayers>().map(|(e, _)| e));
        textures.extend(w.iter::<TextureFile>().map(|(e, _)| e));
        Before {
            placements: w.iter::<Instance>().map(|(e, _)| e).collect(),
            textures,
            meshes: w
                .iter::<Mesh>()
                .map(|(e, m)| (e, (m.id(), triangles(m))))
                .collect(),
        }
    }

    /// What the pass left out, per measure, given the world after it and its primitive rebuilds.
    pub(crate) fn dropped(&self, w: &World, rebuilds: &RebuildLog) -> BTreeMap<Measure, u64> {
        let placements = self.placements.iter().filter(|&&e| !w.has::<Instance>(e)).count() as u64;
        let textures = self
            .textures
            .iter()
            .filter(|&&e| !w.has::<Texture>(e) && !w.has::<TextureLayers>(e) && !w.has::<TextureFile>(e))
            .count() as u64;
        let (mut primitives, mut tris) = (0u64, 0u64);
        let after: BTreeMap<Entity, (u64, Vec<u64>)> = w
            .iter::<Mesh>()
            .map(|(e, m)| (e, (m.id(), triangles(m))))
            .collect();
        // each mesh compared where it stood; one that is no longer there (its entity gone, or its mesh replaced) is
        // left for its identity to find
        let mut gone: Vec<(u64, &Vec<u64>)> = Vec::new();
        let mut matched: BTreeSet<Entity> = BTreeSet::new();
        for (e, (id, before)) in &self.meshes {
            match exact(before, *id, rebuilds.get(e), after.get(e)) {
                Some((p, t)) => {
                    primitives += p;
                    tris += t;
                    matched.insert(*e);
                }
                None => gone.push((*id, before)),
            }
        }
        // a mesh that went from where it stood and stands elsewhere with its identity (moved with
        // World::move_components, or a duplicate or clone standing in for an entity despawned) is compared there
        // as if it had stayed; the rest are counted net, primitives only, all together
        let (mut net_before, mut net_after) = (0u64, 0u64);
        let mut unmatched: Vec<(Entity, &(u64, Vec<u64>))> = after
            .iter()
            .filter(|(e, _)| !matched.contains(*e))
            .map(|(e, a)| (*e, a))
            .collect();
        for (id, before) in gone {
            let found = unmatched.iter().position(|(e, (now_id, _))| {
                *now_id == id
                    || rebuilds
                        .get(e)
                        .is_some_and(|r| r.as_ref().is_some_and(|r| r.source == id))
            });
            match found.and_then(|i| {
                let (e, now) = unmatched[i];
                exact(before, id, rebuilds.get(&e), Some(now)).map(|c| (i, c))
            }) {
                Some((i, (p, t))) => {
                    primitives += p;
                    tris += t;
                    unmatched.remove(i);
                }
                None => net_before += before.len() as u64,
            }
        }
        // meshes that appeared (a loaded file, a form's new mesh, what a pass made) and replacements balance the net
        // count
        net_after += unmatched
            .iter()
            .map(|(_, (_, now))| now.len() as u64)
            .sum::<u64>();
        primitives += net_before.saturating_sub(net_after);
        BTreeMap::from([
            (Measure::Placements, placements),
            (Measure::Primitives, primitives),
            (Measure::Triangles, tris),
            (Measure::Textures, textures),
        ])
    }

    /// Each measure whose count differs from what `log` declared. Collision triangles are left out: collision soups are
    /// outside what the diagnostics count, so a declared collision drop can only be reported, not measured.
    pub(crate) fn gaps(&self, w: &World, rebuilds: &RebuildLog, log: &PassLog) -> Vec<Gap> {
        self.dropped(w, rebuilds)
            .into_iter()
            .filter(|(measure, _)| measure.measured())
            .map(|(measure, dropped)| Gap {
                measure,
                dropped,
                declared: log.declared(measure),
            })
            .filter(|g| g.dropped != g.declared)
            .collect()
    }
}

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

    use crate::components::{ColorSpace, Semantic, Stream, TexRole};
    use crate::pass::{Error, Pass, PassManager, PassRegistry, Pipeline, RunReport};
    use crate::texformat::TexFormat;
    use std::collections::BTreeMap as Map;

    /// A triangle list of `n` triangles.
    /// Primitive `i` of `m` given `p`'s contents, field by field (a pass editing it in place).
    fn set(m: &mut Mesh, i: usize, p: Primitive) {
        let mut q = m.primitive_mut(i).unwrap();
        let f = q.fields();
        (*f.topology, *f.streams, *f.indices, *f.material) = (p.topology, p.streams, p.indices, p.material);
    }

    fn prim(n: u32) -> Primitive {
        Primitive {
            topology: Topology::Triangles,
            streams: Map::from([(Semantic::Position, Stream::F32x3(vec![[0.; 3]; 3]))]),
            indices: Some((0..n).flat_map(|_| [0, 1, 2]).collect()),
            material: None,
        }
    }

    fn texture() -> Texture {
        Texture {
            width: 1,
            height: 1,
            format: TexFormat::Rgba8Unorm,
            levels: vec![vec![0; 4]],
            color_space: ColorSpace::Srgb,
            role: TexRole::Color,
            normal: None,
        }
    }

    /// e0: a prototype of three primitives (1, 2, 3 triangles); e1, e2: its placements; e3: a texture file.
    fn world() -> World {
        let mut w = World::new();
        let p = w.spawn();
        w.insert(p, Mesh::new(vec![prim(1), prim(2), prim(3)]));
        for _ in 0..2 {
            let e = w.spawn();
            w.insert(
                e,
                Instance {
                    prototype: p,
                    variant: 0,
                },
            );
            w.insert(e, crate::Transform::IDENTITY);
        }
        let t = w.spawn();
        w.insert(t, TextureFile { path: "a.png".into() });
        w
    }

    /// A pass that runs `f` and declares `drops`.
    struct Do {
        f: fn(&mut World),
        drops: Vec<(Measure, u64)>,
    }
    impl Pass for Do {
        fn name(&self) -> &'static str {
            "do"
        }
        fn removes(&self) -> &[&'static str] {
            &["core.instance", "core.texture_file", "core.mesh"]
        }
        fn provides(&self) -> &[&'static str] {
            &["core.texture", "core.mesh"]
        }
        fn modifies(&self) -> &[&'static str] {
            &["core.mesh"]
        }
        fn despawns_entities(&self) -> bool {
            true
        }
        fn run(&self, w: &mut World, log: &mut PassLog) -> Result<(), String> {
            (self.f)(w);
            for &(m, n) in &self.drops {
                log.dropped(m, "on purpose", n);
            }
            Ok(())
        }
    }

    fn run_with(c: Conservation, f: fn(&mut World), drops: Vec<(Measure, u64)>) -> Result<RunReport, Error> {
        let mut report = RunReport::default();
        PassManager::new(PassRegistry::new()).with_conservation(c).run(
            &mut world(),
            &Pipeline {
                passes: vec![Box::new(Do { f, drops })],
            },
            &mut report,
        )?;
        Ok(report)
    }

    fn run(f: fn(&mut World), drops: Vec<(Measure, u64)>) -> Result<RunReport, Error> {
        run_with(Conservation::Enforce, f, drops)
    }

    fn left_out(f: fn(&mut World), drops: Vec<(Measure, u64)>) -> (Measure, u64, u64) {
        match run(f, drops) {
            Err(Error::Conservation {
                measure,
                dropped,
                declared,
                ..
            }) => (measure, dropped, declared),
            other => panic!("{other:?}"),
        }
    }

    /// Off by default: an undeclared drop passes unseen; Report records it in the step and the run goes on; Enforce
    /// fails the pass.
    #[test]
    fn the_check_is_off_unless_asked_and_reports_or_fails_as_asked() {
        let despawn = |w: &mut World| {
            w.despawn(Entity::from_index(1));
        };
        let r = run_with(Conservation::Off, despawn, vec![]).unwrap();
        assert!(r.steps[0].conservation.is_empty());
        let r = run_with(Conservation::Report, despawn, vec![]).unwrap();
        assert_eq!(
            r.steps[0].conservation,
            vec![Gap {
                measure: Measure::Placements,
                dropped: 1,
                declared: 0
            }]
        );
        assert!(
            r.to_string().contains("!placements left out 1 but declared 0"),
            "{r}"
        );
        assert_eq!(left_out(despawn, vec![]), (Measure::Placements, 1, 0));
    }

    /// A declared collision drop is reported, never compared: the soups are outside what the check counts.
    #[test]
    fn collision_drops_are_reported_not_measured() {
        let nothing = |_: &mut World| {};
        let r = run(nothing, vec![(Measure::CollisionTriangles, 3)]).unwrap();
        assert!(r.steps[0].conservation.is_empty());
        assert_eq!(r.steps[0].log.declared(Measure::CollisionTriangles), 3);
    }

    #[test]
    fn placements_and_textures_are_counted_by_entity() {
        // a despawned placement must be declared; declaring it passes; declaring more than happened fails too
        let despawn = |w: &mut World| {
            w.despawn(Entity::from_index(1));
        };
        run(despawn, vec![(Measure::Placements, 1)]).unwrap();
        assert_eq!(
            left_out(despawn, vec![(Measure::Placements, 2)]),
            (Measure::Placements, 1, 2)
        );
        // spawning a placement doesn't excuse losing another
        let swap = |w: &mut World| {
            w.despawn(Entity::from_index(1));
            let e = w.spawn();
            w.insert(
                e,
                Instance {
                    prototype: Entity::from_index(0),
                    variant: 0,
                },
            );
            w.insert(e, crate::Transform::IDENTITY);
        };
        assert_eq!(left_out(swap, vec![]), (Measure::Placements, 1, 0));
        // loading a texture file keeps the texture: no drop; losing both is one
        let load = |w: &mut World| {
            let t = Entity::from_index(3);
            w.remove::<TextureFile>(t);
            w.insert(t, texture());
        };
        run(load, vec![]).unwrap();
        let lose = |w: &mut World| {
            w.remove::<TextureFile>(Entity::from_index(3));
        };
        assert_eq!(left_out(lose, vec![]), (Measure::Textures, 1, 0));
    }

    #[test]
    fn a_rebuild_is_exact_so_a_split_cannot_hide_a_drop() {
        // drop primitive 0 and split primitive 2 in two: one more primitive than before, still one dropped
        let split = |w: &mut World| {
            w.rebuild_primitives(Entity::from_index(0), |_| {
                Ok((vec![prim(2), prim(1), prim(2)], vec![1, 2, 2]))
            })
            .unwrap();
        };
        // and primitive 2's pieces hold 3 of its 3 triangles: no triangle lost
        assert_eq!(left_out(split, vec![]), (Measure::Primitives, 1, 0));
        run(split, vec![(Measure::Primitives, 1)]).unwrap();
        // two rebuilds in one pass compose: the second drops a piece of primitive 2 (1 triangle of it lost)
        let twice = |w: &mut World| {
            let e = Entity::from_index(0);
            w.rebuild_primitives(e, |_| Ok((vec![prim(2), prim(1), prim(2)], vec![1, 2, 2])))
                .unwrap();
            w.rebuild_primitives(e, |_| Ok((vec![prim(2), prim(2)], vec![0, 2])))
                .unwrap();
        };
        assert_eq!(
            left_out(twice, vec![(Measure::Primitives, 1)]),
            (Measure::Triangles, 1, 0)
        );
        run(twice, vec![(Measure::Primitives, 1), (Measure::Triangles, 1)]).unwrap();
    }

    #[test]
    fn triangles_are_counted_inside_kept_primitives() {
        // decimate primitive 2 from 3 triangles to 1 in place
        let decimate = |w: &mut World| {
            set(w.get_mut::<Mesh>(Entity::from_index(0)).unwrap(), 2, prim(1));
        };
        assert_eq!(left_out(decimate, vec![]), (Measure::Triangles, 2, 0));
        run(decimate, vec![(Measure::Triangles, 2)]).unwrap();
    }

    #[test]
    fn a_replaced_mesh_is_counted_net_whatever_its_primitive_count() {
        // replaced whole by one of the same count with fewer triangles (inserted, or assigned through get_mut): its
        // primitives are not the old ones, so nothing is compared primitive by primitive and nothing is left out
        let insert = |w: &mut World| {
            w.insert(Entity::from_index(0), Mesh::new(vec![prim(1), prim(1), prim(1)]));
        };
        run(insert, vec![]).unwrap();
        let assign = |w: &mut World| {
            *w.get_mut::<Mesh>(Entity::from_index(0)).unwrap() = Mesh::new(vec![prim(1), prim(1), prim(1)]);
        };
        run(assign, vec![]).unwrap();
        // a replacement between two rebuilds breaks their composition: what is left out is the net one primitive
        let between = |w: &mut World| {
            let e = Entity::from_index(0);
            w.rebuild_primitives(e, |_| Ok((vec![prim(2), prim(3), prim(1)], vec![1, 2, 0])))
                .unwrap();
            w.insert(e, Mesh::new(vec![prim(1), prim(1), prim(1)]));
            w.rebuild_primitives(e, |_| Ok((vec![prim(1), prim(1)], vec![1, 2])))
                .unwrap();
        };
        assert_eq!(left_out(between, vec![]), (Measure::Primitives, 1, 0));
        run(between, vec![(Measure::Primitives, 1)]).unwrap();
        // and one before the first rebuild: the rebuild starts from the replacement, not the mesh the pass was given
        let before = |w: &mut World| {
            let e = Entity::from_index(0);
            w.insert(e, Mesh::new(vec![prim(1), prim(1), prim(1)]));
            w.rebuild_primitives(e, |_| Ok((vec![prim(1), prim(1)], vec![1, 2])))
                .unwrap();
        };
        run(before, vec![(Measure::Primitives, 1)]).unwrap();
    }

    /// A mesh edited through [`World::edit_mesh`] counts as exactly as a rebuild: a split that adds a primitive cannot
    /// hide one dropped (a net count over a hand-made replacement would see none), and an edit that keeps the list is
    /// compared primitive by primitive. A failing edit puts the mesh back.
    #[test]
    fn an_edited_mesh_is_counted_exactly() {
        let split_and_drop = |w: &mut World| {
            w.edit_mesh(Entity::from_index(0), |m| {
                let p = m.primitives().to_vec();
                *m = Mesh::new(vec![p[1].clone(), prim(1), prim(2)]);
                Ok(Some(vec![1, 2, 2]))
            })
            .unwrap();
        };
        assert_eq!(left_out(split_and_drop, vec![]), (Measure::Primitives, 1, 0));
        run(split_and_drop, vec![(Measure::Primitives, 1)]).unwrap();
        let in_place = |w: &mut World| {
            w.edit_mesh(Entity::from_index(0), |m| {
                set(m, 0, prim(0));
                Ok(None)
            })
            .unwrap();
        };
        assert_eq!(left_out(in_place, vec![]), (Measure::Triangles, 1, 0));
        // an edit that rebuilds the mesh object but keeps its primitives in order (None) stays the same mesh, so a
        // later rebuild in the pass composes with it: a split there cannot hide a drop either
        let renewed_then_split = |w: &mut World| {
            let e = Entity::from_index(0);
            w.edit_mesh(e, |m| {
                *m = Mesh::new(m.primitives().to_vec());
                Ok(None)
            })
            .unwrap();
            w.edit_mesh(e, |m| {
                let p = m.primitives().to_vec();
                *m = Mesh::new(vec![p[1].clone(), prim(1), prim(2)]);
                Ok(Some(vec![1, 2, 2]))
            })
            .unwrap();
        };
        assert_eq!(left_out(renewed_then_split, vec![]), (Measure::Primitives, 1, 0));
        let mut w = world();
        let e = Entity::from_index(0);
        assert!(w.edit_mesh(e, |_| Err("no".into())).is_err());
        assert_eq!(w.get::<Mesh>(e).map(|m| m.primitives().len()), Some(3));
        assert!(w.edit_mesh(e, |_| Ok(Some(vec![5]))).is_err());
        assert_eq!(w.get::<Mesh>(e).map(|m| m.primitives().len()), Some(3));
        assert_eq!(w.edit_mesh(Entity::from_index(1), |_| Ok(None)), Ok(false));
    }

    /// The World APIs as the diagnostics see them: a clone keeps its mesh's identity (put back after an edit, it is
    /// compared primitive by primitive), a mesh moved between entities is no drop (the one it replaced is), a duplicate
    /// standing in for its original is no drop, a linear map keeps the mesh (no triangle lost), and a world clone or
    /// subset starts with no rebuild log of its own.
    #[test]
    fn clone_move_duplicate_and_linear_maps_count_as_they_should() {
        let clone_back = |w: &mut World| {
            let e = Entity::from_index(0);
            let mut m = w.get::<Mesh>(e).unwrap().clone();
            set(&mut m, 1, prim(1));
            w.insert(e, m);
        };
        assert_eq!(left_out(clone_back, vec![]), (Measure::Triangles, 1, 0));
        let moved = |w: &mut World| {
            let form = w.spawn();
            w.insert(form, Mesh::new(vec![prim(1)]));
            w.move_components(form, Entity::from_index(0)).unwrap();
        };
        assert_eq!(left_out(moved, vec![]), (Measure::Primitives, 2, 0));
        run(moved, vec![(Measure::Primitives, 2)]).unwrap();
        let duplicated = |w: &mut World| {
            let p = Entity::from_index(0);
            let copy = w.duplicate(p).unwrap();
            for e in [Entity::from_index(1), Entity::from_index(2)] {
                w.get_mut::<Instance>(e).unwrap().prototype = copy;
            }
            w.despawn(p);
        };
        run(duplicated, vec![]).unwrap();
        let mirrored = |w: &mut World| {
            let l = crate::Linear::mirror_x();
            w.apply_linear(Entity::from_index(0), &l).unwrap();
        };
        run(mirrored, vec![]).unwrap();
        let mut w = world();
        w.start_rebuild_log();
        w.rebuild_primitives(Entity::from_index(0), |_| Ok((vec![prim(1)], vec![0])))
            .unwrap();
        assert!(w.clone().take_rebuild_log().is_empty());
        assert!(w.subset(&w.entities().collect()).take_rebuild_log().is_empty());
        assert_eq!(w.take_rebuild_log().len(), 1);
    }

    /// A mesh is followed by its identity, not its entity: one moved to another entity, or a duplicate standing in for
    /// an entity despawned, is compared where it went, as if it had stayed (a rebuild there or an edit in place counted
    /// exactly); a copy made beside a mesh that stays is an addition, whatever is done to it after.
    #[test]
    fn a_mesh_is_followed_by_its_identity_across_entities() {
        fn stand_in(w: &mut World) -> Entity {
            let p = Entity::from_index(0);
            let copy = w.duplicate(p).unwrap();
            for e in [Entity::from_index(1), Entity::from_index(2)] {
                w.get_mut::<Instance>(e).unwrap().prototype = copy;
            }
            w.despawn(p);
            copy
        }
        fn moved(w: &mut World) -> Entity {
            let to = w.spawn();
            w.move_components(Entity::from_index(0), to).unwrap();
            for e in [Entity::from_index(1), Entity::from_index(2)] {
                w.get_mut::<Instance>(e).unwrap().prototype = to;
            }
            to
        }
        // the stand-in edited in place (primitive 2 from 3 triangles to 1), and rebuilt without primitive 2
        let stand_in_edited = |w: &mut World| {
            let copy = stand_in(w);
            set(w.get_mut::<Mesh>(copy).unwrap(), 2, prim(1));
        };
        assert_eq!(left_out(stand_in_edited, vec![]), (Measure::Triangles, 2, 0));
        run(stand_in_edited, vec![(Measure::Triangles, 2)]).unwrap();
        let stand_in_rebuilt = |w: &mut World| {
            let copy = stand_in(w);
            w.rebuild_primitives(copy, |_| Ok((vec![prim(1), prim(2)], vec![0, 1])))
                .unwrap();
        };
        assert_eq!(left_out(stand_in_rebuilt, vec![]), (Measure::Primitives, 1, 0));
        // moved, then edited in place or split so that a primitive is hidden by a piece
        let moved_edited = |w: &mut World| {
            let to = moved(w);
            set(w.get_mut::<Mesh>(to).unwrap(), 2, prim(1));
        };
        assert_eq!(left_out(moved_edited, vec![]), (Measure::Triangles, 2, 0));
        let moved_split = |w: &mut World| {
            let to = moved(w);
            w.rebuild_primitives(to, |_| Ok((vec![prim(2), prim(1), prim(2)], vec![1, 2, 2])))
                .unwrap();
        };
        assert_eq!(left_out(moved_split, vec![]), (Measure::Primitives, 1, 0));
        // a copy beside the mesh, which stays whole: the copy's losses are not the source's
        let copy_edited = |w: &mut World| {
            let copy = w.duplicate(Entity::from_index(0)).unwrap();
            set(w.get_mut::<Mesh>(copy).unwrap(), 2, prim(1));
        };
        run(copy_edited, vec![]).unwrap();
        let copy_rebuilt = |w: &mut World| {
            let to = w.spawn();
            w.copy_components(Entity::from_index(0), to);
            w.rebuild_primitives(to, |_| Ok((vec![prim(1)], vec![0])))
                .unwrap();
        };
        run(copy_rebuilt, vec![]).unwrap();
        let clone_elsewhere = |w: &mut World| {
            let m = w.get::<Mesh>(Entity::from_index(0)).unwrap().clone();
            let to = w.spawn();
            w.insert(to, m);
            set(w.get_mut::<Mesh>(to).unwrap(), 0, prim(0));
        };
        run(clone_elsewhere, vec![]).unwrap();
        // and the source losing a primitive is its loss, a whole copy beside it or not
        let source_rebuilt = |w: &mut World| {
            w.duplicate(Entity::from_index(0)).unwrap();
            w.rebuild_primitives(Entity::from_index(0), |_| {
                Ok((vec![prim(1), prim(2)], vec![0, 1]))
            })
            .unwrap();
        };
        assert_eq!(left_out(source_rebuilt, vec![]), (Measure::Primitives, 1, 0));
    }

    /// An entity's drop names what it held: a placement and its mesh's primitives; nothing for one gone already.
    #[test]
    fn despawn_declares_what_the_entity_held() {
        let mut w = World::new();
        let proto = w.spawn();
        let e = w.spawn();
        w.insert(
            e,
            Instance {
                prototype: proto,
                variant: 0,
            },
        );
        w.insert(e, crate::Transform::IDENTITY);
        let prim = Primitive {
            topology: Topology::Triangles,
            streams: Default::default(),
            indices: None,
            material: None,
        };
        w.insert(e, Mesh::new(vec![prim.clone(), prim]));
        let mut log = PassLog::default();
        assert!(despawn(&mut w, e, &mut log, "left out"));
        assert!(!despawn(&mut w, e, &mut log, "left out"));
        assert_eq!(log.declared(Measure::Placements), 1);
        assert_eq!(log.declared(Measure::Primitives), 2);
        assert_eq!(log.declared(Measure::Textures), 0);
        assert_eq!(
            log.drops.get(&(Measure::Primitives, "left out".to_owned())),
            Some(&2)
        );
    }

    /// An entity an asset lists as a member is dropped from the asset when it is despawned, counted: the asset stays
    /// whole (what it lists is alive), and an entity no asset lists is not counted.
    #[test]
    fn despawn_drops_the_entity_from_the_assets_that_list_it() {
        use crate::asset::Role;
        let mut w = World::new();
        let (part, rig, other) = (w.spawn(), w.spawn(), w.spawn());
        let (a, b) = (w.spawn(), w.spawn());
        w.insert(
            a,
            Asset {
                members: vec![(rig, Role::Rig), (part, Role::Part)],
            },
        );
        w.insert(
            b,
            Asset {
                members: vec![(part, Role::Part), (other, Role::Part)],
            },
        );
        let mut log = PassLog::default();
        assert!(despawn(&mut w, part, &mut log, "left out"));
        assert_eq!(w.get::<Asset>(a).unwrap().members, [(rig, Role::Rig)]);
        assert_eq!(w.get::<Asset>(b).unwrap().members, [(other, Role::Part)]);
        assert_eq!(log.counts["asset members dropped with the entity they listed"], 2);
        let mut log = PassLog::default();
        assert!(despawn(&mut w, other, &mut log, "left out"));
        assert_eq!(log.counts["asset members dropped with the entity they listed"], 1);
        // an entity no asset lists counts nothing
        let loose = w.spawn();
        let mut log = PassLog::default();
        assert!(despawn(&mut w, loose, &mut log, "left out"));
        assert!(
            !log.counts
                .contains_key("asset members dropped with the entity they listed")
        );
    }

    /// An occurrence a clip binding drives is dropped from the binding when it is despawned, counted: the binding keeps
    /// its clip and its other meshes, and an entity no binding names counts nothing.
    #[test]
    fn despawn_drops_the_entity_from_the_clip_bindings_that_name_it() {
        let mut w = World::new();
        let (clip, a, b) = (w.spawn(), w.spawn(), w.spawn());
        let (first, second) = (w.spawn(), w.spawn());
        for (e, meshes) in [(first, vec![a, b]), (second, vec![a])] {
            w.insert(
                e,
                ClipBinding {
                    clip,
                    rig: None,
                    meshes,
                },
            );
        }
        let mut log = PassLog::default();
        assert!(despawn(&mut w, a, &mut log, "left out"));
        assert_eq!(w.get::<ClipBinding>(first).unwrap().meshes, [b]);
        assert!(w.get::<ClipBinding>(second).unwrap().meshes.is_empty());
        assert_eq!(w.get::<ClipBinding>(first).unwrap().clip, clip);
        assert_eq!(
            log.counts["clip binding meshes dropped with the entity they named"],
            2
        );
        let loose = w.spawn();
        let mut log = PassLog::default();
        assert!(despawn(&mut w, loose, &mut log, "left out"));
        assert!(
            !log.counts
                .contains_key("clip binding meshes dropped with the entity they named")
        );
    }
}