unlit3d 0.1.0-dev.2

The high-level WebGPU rendering API over unlit_wgpu and unlit_ecs: ECS components, frame sources, input, UI and winit presentation.
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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
//! Frame sources: the things a frame is made of.
//!
//! A [`Renderer`](crate::renderer::Renderer) draws nothing itself. It assembles a frame
//! out of [`FrameSource`]s, each of which builds its own [`Scene`] from the
//! world and states where in the frame it belongs. The built-in mesh rendering
//! is one such source ([`MeshSource`](crate::mesh_source::MeshSource)) and a
//! UI overlay is another; a caller's own pass over the frame is a third, with
//! no more privilege than the built-in ones.
//!
//! A source is an ordinary component holding a boxed [`AnySource`], so one
//! query drives every concrete source type: build all of them, then record
//! their scenes in [`FrameSourceOrder`]. The GPU state a source needs — the device,
//! the queue and the resource graph — lives in the world too, addressed by the
//! [`RenderContext`] the sources are handed; that is what lets a source fetch
//! the graph while the driver only holds a shared borrow of the world.
//!
//! [`Scene`]: unlit_wgpu::scene::Scene

use core::any::Any;

use unlit_ecs::{Entity, World};
use unlit_wgpu::capabilities::DeviceCapabilities;
use unlit_wgpu::resources::ResourceGraph;
use unlit_wgpu::scene::{Scene, ViewportRect};
use unlit_wgpu::specialize::SurfaceKey;

/// Where a source records, relative to every other source.
///
/// Lower values record first. Deliberately has no `Default`: every source
/// states its ordering intent, and a silent default is exactly what an explicit
/// order exists to remove.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct FrameSourceOrder(pub i32);

impl FrameSourceOrder {
    /// The built-in mesh source's order.
    pub const MESH: Self = Self(0);
    /// A source that composes over the meshes, such as the UI.
    pub const UI: Self = Self(100);
}

/// The GPU state a frame is drawn with, as world addresses.
///
/// It holds [`Entity`] handles rather than borrows, so it is `Copy` and never
/// conflicts with a source's own borrow of the world. A source fetches what it
/// needs from the components those entities carry:
/// `world.get_mut::<ResourceGraph>(ctx.graph)`.
///
/// The handles are spawned once by [`spawn_context`] and stay valid for the
/// world's life; a resource entity is never despawned while frames are drawn.
///
/// The context is itself a component: [`spawn_context`] stores a copy on the
/// entity carrying the [`ResourceGraph`], so a reader that was handed one of
/// the four addresses can query its way back to the whole context instead of
/// assuming the world holds exactly one.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RenderContext {
    /// The [`wgpu::Device`] the frame is drawn with, as a resource entity.
    pub device: Entity,
    /// The [`wgpu::Queue`] the frame is submitted to, as a resource entity.
    pub queue: Entity,
    /// The [`ResourceGraph`] holding the frame's resources, as a resource
    /// entity.
    pub graph: Entity,
    /// What the device can do beyond the WebGPU baseline, as a resource
    /// entity.
    ///
    /// The device cannot report this itself — it is a property of the adapter,
    /// which is normally gone by the time frames are drawn — so it is captured
    /// once and carried here. See
    /// [`DeviceCapabilities`].
    pub capabilities: Entity,
}

impl RenderContext {
    /// Maintain the frame's [`ResourceGraph`] when the returned scope drops.
    ///
    /// Call this at the top of [`FrameSource::build_scene`] and drop the scope
    /// before reading a resource: every return in between — including the early
    /// ones a source takes when it has nothing to draw — settles the graph, so
    /// no path has to remember to. The pass is the same one
    /// [`ResourceGraph::maintain`] makes; the scope only decides when it runs.
    ///
    /// The scope borrows neither the graph nor the source: it holds the world
    /// and this context's graph address, and fetches the graph when it ends, so
    /// the code between taking the scope and dropping it is free to borrow the
    /// graph itself, as a build does.
    pub fn maintain_scope<'w>(self, world: &'w World) -> MaintainScope<'w> {
        MaintainScope { world, ctx: self }
    }
}

/// A [`RenderContext`] as plain data.
///
/// The context's four resource entities, for a reader — a debug overlay, an MCP
/// server — that reports the GPU state without borrowing the world. The handles
/// round-trip through [`Entity::to_bits`] and [`Entity::from_bits`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct RenderContextInfo {
    /// The entity carrying the [`wgpu::Device`].
    #[cfg_attr(feature = "reflect", facet(opaque, proxy = unlit_ecs::EntityProxy))]
    pub device: Entity,
    /// The entity carrying the [`wgpu::Queue`].
    #[cfg_attr(feature = "reflect", facet(opaque, proxy = unlit_ecs::EntityProxy))]
    pub queue: Entity,
    /// The entity carrying the [`ResourceGraph`].
    #[cfg_attr(feature = "reflect", facet(opaque, proxy = unlit_ecs::EntityProxy))]
    pub graph: Entity,
    /// The entity carrying the [`DeviceCapabilities`].
    #[cfg_attr(feature = "reflect", facet(opaque, proxy = unlit_ecs::EntityProxy))]
    pub capabilities: Entity,
}

impl RenderContext {
    /// The context the world holds, found from any one of its addresses.
    ///
    /// The four resource entities and the graph entity all carry the whole
    /// [`RenderContext`], so a caller that was handed a device, queue, graph
    /// or capabilities address gets the rest without assuming the world holds
    /// exactly one context. `None` when `anchor` carries no context.
    #[must_use]
    pub fn of(world: &World, anchor: Entity) -> Option<Self> {
        world.get::<RenderContext>(anchor).map(|context| *context)
    }

    /// The context's resource addresses as plain data.
    pub fn info(self) -> RenderContextInfo {
        RenderContextInfo {
            device: self.device,
            queue: self.queue,
            graph: self.graph,
            capabilities: self.capabilities,
        }
    }
}

/// Maintains the frame's resource graph when it ends.
///
/// [`RenderContext::maintain_scope`] returns one. It is a scope guard rather
/// than a call so that a frame source cannot forget the pass on a return: the
/// guard settles the graph on every way out of the scope it lives in, and a
/// build that has to read the graph before the end — assembling a frame from
/// the bind groups the pass just rebuilt — drops it explicitly at that point.
#[must_use = "the graph is maintained when the scope is dropped"]
pub struct MaintainScope<'w> {
    world: &'w World,
    ctx: RenderContext,
}

impl Drop for MaintainScope<'_> {
    fn drop(&mut self) {
        // A missing graph is a caller error, and panicking here would be a
        // second panic on the way out of one, so the scope does nothing.
        if let Some(mut graph) = self.world.get_mut::<ResourceGraph>(self.ctx.graph) {
            graph.maintain();
        }
    }
}

/// The render target the frame currently draws into.
///
/// A source specializes every pipeline on the frame's target, but
/// [`RenderContext`] is spawned once and must stay `Copy`, so the target is a
/// separate resource the frame loop writes before it renders — see
/// [`set_frame_target`]. It is deliberately not a field on [`RenderContext`]:
/// putting a per-frame value there would mean writing the context every frame,
/// and a source reading it could not tell a stale value from this frame's.
///
/// A source that runs before any target was written reads `None` from
/// [`frame_target`] and must refuse to draw rather than fall back to the
/// previous frame's target.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FrameTarget {
    /// The target's pipeline specialization key.
    pub surface: SurfaceKey,
    /// The target's width, in physical pixels.
    pub width: u32,
    /// The target's height, in physical pixels.
    pub height: u32,
}

/// The world resource holding the frame's current [`FrameTarget`].
///
/// Internal: the frame loop writes it through [`set_frame_target`] and sources
/// read it through [`frame_target`], so the `Option` never has to be handled
/// twice.
#[derive(Clone, Copy, Debug, Default)]
struct FrameTargetSlot(Option<FrameTarget>);

/// The region of the frame's target that scene-like sources draw into, or
/// `None` for the whole of it.
///
/// This is how a frame loop letterboxes content whose own aspect differs from
/// its target's: it states the rectangle once per frame, and every source that
/// draws 3D content records into it — so the content is scaled uniformly and
/// the same picture appears on any target shape. A source that composes over
/// the content rather than being part of it, a UI overlay for instance, ignores
/// this and covers the whole target.
///
/// It is a per-frame value rather than a field on [`RenderContext`] for the
/// same reason [`FrameTarget`] is: the context is spawned once and stays `Copy`,
/// while this changes with every resize.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FrameViewport(pub ViewportRect);

/// The world resource holding the frame's current [`FrameViewport`].
///
/// Internal: the frame loop writes it through [`set_frame_viewport`] and
/// sources read it through [`frame_viewport`].
#[derive(Clone, Copy, Debug, Default)]
struct FrameViewportSlot(Option<FrameViewport>);

/// What a source claimed of the frame's input.
///
/// A UI toolkit decides whether it wants the pointer or the keyboard while it
/// lays a frame out, and the answer belongs to the frame just laid out: a game
/// control reading it is asking whether the input it is about to handle has
/// already been claimed by an interface. Sources write it; nothing is
/// intercepted automatically, so a caller decides what the claim means.
///
/// The frame context spawns it, so a world that draws a frame has one.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct InputCapture {
    /// A source wants the pointer, so a click belongs to it.
    pub pointer: bool,
    /// A source wants the keyboard, so a key belongs to it.
    pub keyboard: bool,
}

impl InputCapture {
    /// Whether either kind of input was claimed.
    pub fn any(self) -> bool {
        self.pointer || self.keyboard
    }
}

/// The frame's target, or `None` before any frame loop wrote one.
///
/// A source calls this in
/// [`build_scene`](FrameSource::build_scene). `None` means the frame loop never
/// stated what the frame draws into, which is a programming error on its part —
/// a source cannot invent a target — so a source that needs it should refuse to
/// draw rather than fall back.
pub fn frame_target(world: &World) -> Option<FrameTarget> {
    world
        .query::<&FrameTargetSlot>()
        .next()
        .and_then(|(_, slot)| slot.0)
}

/// State the target the frame draws into.
///
/// The frame loop calls this before it renders — [`Renderer::set_render_target`](crate::renderer::Renderer::set_render_target)
/// does it for the built-in path. Returns whether a slot existed to write; a
/// world only gets one from [`spawn_context`].
pub fn set_frame_target(world: &World, target: FrameTarget) -> bool {
    let Some(entity) = world.query::<&FrameTargetSlot>().next().map(|(e, _)| e) else {
        return false;
    };
    world
        .with_mut::<FrameTargetSlot, _>(entity, |slot| slot.0 = Some(target))
        .is_some()
}

/// Unset the target the frame draws into.
///
/// The inverse of [`set_frame_target`]: sources then read no target and refuse
/// to draw instead of drawing into one that is gone. Returns whether a slot
/// existed to write; a world only gets one from [`spawn_context`].
///
/// Internal: this is how [`Renderer::unset_render_target`](crate::renderer::Renderer::unset_render_target)
/// stops the world claiming a target whose attachments it released, so a
/// caller states a target again by setting one rather than by unsetting one.
pub(crate) fn unset_frame_target(world: &World) -> bool {
    let Some(entity) = world.query::<&FrameTargetSlot>().next().map(|(e, _)| e) else {
        return false;
    };
    world
        .with_mut::<FrameTargetSlot, _>(entity, |slot| slot.0 = None)
        .is_some()
}

/// The region of the frame's target that 3D sources draw into.
///
/// A source calls this in [`FrameSource::build_scene`] to learn where the
/// content it is part of belongs, and passes it to
/// [`Scene::set_viewport`] so its draws land inside it.
///
/// `None` means the frame loop stated no letterbox, so the whole target is the
/// region — the ordinary case, and the one every caller that never letterboxes
/// leaves the world in.
pub fn frame_viewport(world: &World) -> Option<FrameViewport> {
    world
        .query::<&FrameViewportSlot>()
        .next()
        .and_then(|(_, slot)| slot.0)
}

/// State the region of the frame's target that 3D sources draw into.
///
/// The frame loop calls this before it renders, next to
/// [`set_frame_target`](crate::renderer::Renderer::set_render_target). A frame
/// loop that never calls it leaves the whole target as the region, which is
/// what every caller that does not letterbox wants.
///
/// A letterbox is a property of the target, not of a source, so it is stated
/// here rather than by each source: see [`FrameViewport`]. Returns whether a
/// slot existed to write; a world only gets one from [`spawn_context`].
pub fn set_frame_viewport(world: &World, viewport: Option<FrameViewport>) -> bool {
    let Some(entity) = world.query::<&FrameViewportSlot>().next().map(|(e, _)| e) else {
        return false;
    };
    world
        .with_mut::<FrameViewportSlot, _>(entity, |slot| slot.0 = viewport)
        .is_some()
}

/// A source of one frame's draws.
///
/// A source owns whatever state it draws from and the [`Scene`] it fills each
/// frame. The driver calls [`FrameSource::build_scene`] on every source, then
/// records the scenes in [`FrameSource::order`].
pub trait FrameSource: 'static {
    /// Assemble this frame's [`Scene`], fetching what it needs from `world`.
    ///
    /// `ctx` carries only entity ids, so it never conflicts with the source's
    /// own borrow of `world`. `encoder` is the frame's one encoder, and a
    /// source stages its uploads through it: the pass is opened only after
    /// every source has built, so the uploads and the draws that read them
    /// share one submission.
    ///
    /// A source that has nothing to draw clears its scene and returns: the
    /// frame still records, and still applies its load ops.
    fn build_scene(
        &mut self,
        world: &World,
        ctx: RenderContext,
        encoder: &mut wgpu::CommandEncoder,
    );

    /// The scene built by the last [`FrameSource::build_scene`].
    fn scene(&self) -> &Scene;

    /// Where this source records, relative to the others.
    ///
    /// Required, not defaulted: a source that stayed silent would be ordered
    /// by mount position alone, which is the implicit behaviour this exists to
    /// replace. Use [`FrameSourceOrder::MESH`], [`FrameSourceOrder::UI`], or a value
    /// of your own.
    ///
    /// A [`Source`] may override this per entity with [`Source::with_order`],
    /// which is how a caller reorders an existing source without rebuilding it.
    fn order(&self) -> FrameSourceOrder;
}

/// A frame source behind an erased handle, so one query sees every concrete
/// source type.
///
/// Method-free on purpose: [`Any`] supplies downcasting, the [`FrameSource`]
/// supertrait supplies the trait API, and the blanket impl means an implementor
/// writes no boilerplate at all.
pub trait AnySource: Any + FrameSource {}

impl<T: FrameSource> AnySource for T {}

/// A frame source as an ECS component.
///
/// The trait API is reachable directly (`source.order()`,
/// `source.build_scene(..)`, `source.scene()`); typed access upcasts to
/// `dyn Any` and downcasts, which is what [`Source::as_mut`] wraps.
pub struct Source {
    source: Box<dyn AnySource>,
    /// An explicit order that overrides the source's own.
    order: Option<FrameSourceOrder>,
    /// When the source was mounted.
    ///
    /// This is the tie-break between sources that declare the same
    /// [`FrameSourceOrder`]. It cannot be the entity index or the query's row order:
    /// `despawn` moves the last row into the freed one, so row order changes
    /// as sources come and go.
    mount_index: u64,
}

impl Source {
    /// Wrap `source`, taking its order from [`FrameSource::order`].
    pub fn new(source: impl FrameSource) -> Self {
        Self {
            source: Box::new(source),
            order: None,
            mount_index: 0,
        }
    }

    /// Wrap `source`, recording it at `order` regardless of what
    /// [`FrameSource::order`] says.
    pub fn with_order(mut self, order: FrameSourceOrder) -> Self {
        self.order = Some(order);
        self
    }

    /// The order this source records at, explicit or declared.
    pub fn order(&self) -> FrameSourceOrder {
        self.order.unwrap_or_else(|| self.source.order())
    }

    /// Override the order this source records at.
    ///
    /// Setting the same value again is a no-op, so a caller may apply an order
    /// every frame without disturbing the ambiguity bookkeeping.
    pub fn set_order(&mut self, order: Option<FrameSourceOrder>) {
        self.order = order;
    }

    /// When the source was mounted, which breaks ties between equal orders.
    pub fn mount_index(&self) -> u64 {
        self.mount_index
    }

    /// The source as its concrete type, or `None` for a different type.
    pub fn as_mut<T: FrameSource>(&mut self) -> Option<&mut T> {
        let erased: &mut dyn Any = &mut *self.source;
        erased.downcast_mut::<T>()
    }

    /// The source as its concrete type, or `None` for a different type.
    pub fn as_ref<T: FrameSource>(&self) -> Option<&T> {
        let erased: &dyn Any = &*self.source;
        erased.downcast_ref::<T>()
    }

    /// Assemble this source's scene for the frame.
    pub fn build_scene(
        &mut self,
        world: &World,
        ctx: RenderContext,
        encoder: &mut wgpu::CommandEncoder,
    ) {
        self.source.build_scene(world, ctx, encoder);
    }

    /// The scene this source built for the frame.
    pub fn scene(&self) -> &Scene {
        self.source.scene()
    }
}

impl core::fmt::Debug for Source {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Source")
            .field("order", &self.order())
            .field("mount_index", &self.mount_index)
            .finish_non_exhaustive()
    }
}

/// The next mount index to hand out.
///
/// Kept as a resource so it is monotonic across the world's life rather than
/// per-renderer: two renderers sharing a world must not hand out the same
/// indices, or the tie-break would not be total.
#[derive(Debug, Default)]
struct MountCounter(u64);

/// Spawn the frame's GPU state as resources and return its addresses.
///
/// The device and queue are `Clone` handles on a shared context, so the world
/// holds its own reference to each; the graph is not `Sync` and moves into the
/// world whole. Call this once per world.
pub fn spawn_context(
    world: &mut World,
    device: wgpu::Device,
    queue: wgpu::Queue,
    graph_component: ResourceGraph,
    capabilities: DeviceCapabilities,
) -> RenderContext {
    // The graph entity is reserved first because the context names it, and
    // every one of the four entities carries the whole context: a reader handed
    // any single address can query the rest back instead of assuming the world
    // holds exactly one context.
    let graph = world.reserve_entity();
    let context = RenderContext {
        device: world.reserve_entity(),
        queue: world.reserve_entity(),
        graph,
        capabilities: world.reserve_entity(),
    };
    world.spawn_at(context.device, (device, context));
    world.spawn_at(context.queue, (queue, context));
    world.spawn_at(context.capabilities, (capabilities, context));
    world.spawn_at(graph, (graph_component, context));
    world.spawn((MountCounter::default(),));
    // The frame loop writes the target here every frame; until it does, no
    // source may draw.
    world.spawn((FrameTargetSlot::default(),));
    // Where in that target the frame's 3D content belongs; the whole of it
    // until a frame loop states a letterbox.
    world.spawn((FrameViewportSlot::default(),));
    // What the frame's sources claimed of its input, written by whichever
    // source consumes input and read by the caller's own logic.
    world.spawn((InputCapture::default(),));
    context
}

/// Mounting a [`FrameSource`] on a [`World`].
///
/// The methods are the work the free functions did; the trait only gathers it
/// onto the world the sources are mounted on.
pub trait WorldSourceExt {
    /// Mount `source`, taking its order from [`FrameSource::order`].
    fn spawn_source(&mut self, source: impl FrameSource) -> Entity;

    /// Mount `source`, recording it at `order`.
    fn spawn_source_at(&mut self, order: FrameSourceOrder, source: impl FrameSource) -> Entity;
}

impl WorldSourceExt for World {
    fn spawn_source(&mut self, source: impl FrameSource) -> Entity {
        let source = Source::new(source);
        let index = next_mount_index(self);
        self.spawn((bump_mount(source, index),))
    }

    fn spawn_source_at(&mut self, order: FrameSourceOrder, source: impl FrameSource) -> Entity {
        let source = Source::new(source).with_order(order);
        let index = next_mount_index(self);
        self.spawn((bump_mount(source, index),))
    }
}

/// Take the next mount index from the world's counter.
fn next_mount_index(world: &World) -> u64 {
    let Some(counter) = world.query::<&MountCounter>().next().map(|(e, _)| e) else {
        return 0;
    };
    world
        .with_mut::<MountCounter, _>(counter, |counter| {
            let index = counter.0;
            counter.0 += 1;
            index
        })
        .unwrap_or(0)
}

fn bump_mount(mut source: Source, index: u64) -> Source {
    source.mount_index = index;
    source
}

/// One group of sources that declared the same [`FrameSourceOrder`].
pub type AmbiguousGroup = (FrameSourceOrder, Vec<Entity>);

/// The frame's sources in record order, and the ambiguous groups among them.
///
/// Resolved once per frame, so it is kept as a reusable buffer rather than
/// handed back as fresh `Vec`s: a steady scene then resolves its order without
/// allocating. [`Self::resolve`] clears and refills every buffer in place, so
/// the capacity survives from one frame to the next.
#[derive(Debug, Default)]
pub struct SourceOrder {
    /// `(order, mount_index, entity)` for every source, sorted by the first
    /// two. Scratch: the entities are copied into [`Self::order`] once the run
    /// boundaries have been found.
    keys: Vec<(FrameSourceOrder, u64, Entity)>,
    /// The sources to record, in the order they record.
    order: Vec<Entity>,
    /// The runs of equal orders among them, in order.
    ambiguous: Vec<AmbiguousGroup>,
}

impl SourceOrder {
    /// Resolve `world`'s sources, reusing whatever this already holds.
    ///
    /// Sorted by `(order, mount_index)`, so equal orders keep their mount
    /// order; every run of more than one equal order is an ambiguity.
    pub fn resolve(&mut self, world: &World) {
        self.keys.clear();
        self.keys.extend(
            world
                .query::<&Source>()
                .map(|(entity, source)| (source.order(), source.mount_index(), entity)),
        );
        self.keys
            .sort_unstable_by_key(|(order, mount_index, _)| (*order, *mount_index));

        self.order.clear();
        self.ambiguous.clear();
        let mut start = 0;
        while start < self.keys.len() {
            let order = self.keys[start].0;
            let mut end = start + 1;
            while end < self.keys.len() && self.keys[end].0 == order {
                end += 1;
            }
            if end - start > 1 {
                // A run of equal orders: an ambiguity. Its entities are in
                // mount order already, because that is what the sort used as
                // the tie-break.
                let group = self.keys[start..end]
                    .iter()
                    .map(|(_, _, entity)| *entity)
                    .collect();
                self.ambiguous.push((order, group));
            }
            start = end;
        }
        self.order
            .extend(self.keys.iter().map(|(_, _, entity)| *entity));
    }

    /// The sources to record, in the order they record.
    pub fn entities(&self) -> &[Entity] {
        &self.order
    }

    /// The groups of sources that declared the same [`FrameSourceOrder`], in order.
    ///
    /// Equal orders are not an error — two sources that really are
    /// interchangeable may share one — but they are worth reporting; see
    /// [`OrderWarnings`].
    pub fn ambiguous(&self) -> &[AmbiguousGroup] {
        &self.ambiguous
    }
}

/// Reports sources that declared the same [`FrameSourceOrder`], without repeating
/// itself.
///
/// Equal orders are not an error — two sources that really are
/// interchangeable may share one — so this warns rather than panicking. What it
/// must not do is warn on every frame: a steady scene would flood the log. It
/// therefore remembers the groups it last reported and speaks up again only
/// when they change, which is exactly when sources were added, removed or
/// reordered.
#[derive(Debug, Default)]
pub struct OrderWarnings {
    reported: Vec<AmbiguousGroup>,
}

impl OrderWarnings {
    /// Warn about `ambiguous` unless it is what was already reported.
    ///
    /// Returns whether anything was reported, which is what the tests assert
    /// on; the log line names the group's size, its order and its entities.
    pub fn check(&mut self, ambiguous: &[AmbiguousGroup]) -> bool {
        if self.reported == ambiguous {
            return false;
        }
        for (order, group) in ambiguous {
            log::warn!(
                "{} sources declared the same FrameSourceOrder({}): entities {:?}; \
                 recording them in mount order — give them distinct orders to \
                 choose explicitly",
                group.len(),
                order.0,
                group,
            );
        }
        self.reported = ambiguous.to_vec();
        !ambiguous.is_empty()
    }
}

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

    /// A noop device and queue, enough to spawn a context: the tests here
    /// exercise the ordering and mounting bookkeeping, which never touches the
    /// GPU.
    fn test_context(world: &mut World) -> RenderContext {
        let (device, queue) = wgpu::Device::noop(&wgpu::DeviceDescriptor::default());
        spawn_context(
            world,
            device,
            queue,
            ResourceGraph::new(),
            DeviceCapabilities::default(),
        )
    }

    /// A source that records how many times it was built and what it saw.
    struct RecordingSource {
        order: FrameSourceOrder,
        built: Rc<Cell<u32>>,
        scene: Scene,
    }

    impl RecordingSource {
        fn new(order: FrameSourceOrder) -> Self {
            Self {
                order,
                built: Rc::new(Cell::new(0)),
                scene: Scene::new(),
            }
        }
    }

    impl FrameSource for RecordingSource {
        fn build_scene(
            &mut self,
            _world: &World,
            _ctx: RenderContext,
            _encoder: &mut wgpu::CommandEncoder,
        ) {
            self.built.set(self.built.get() + 1);
        }

        fn scene(&self) -> &Scene {
            &self.scene
        }

        fn order(&self) -> FrameSourceOrder {
            self.order
        }
    }

    use std::cell::{Cell, RefCell};
    use std::rc::Rc;

    /// Resolve `world`'s order in one shot, as the tests want it: the entities
    /// and the ambiguous groups, both owned so an assertion can hold them while
    /// the world changes.
    fn record_order(world: &World) -> (Vec<Entity>, Vec<AmbiguousGroup>) {
        let mut resolved = SourceOrder::default();
        resolved.resolve(world);
        (resolved.entities().to_vec(), resolved.ambiguous().to_vec())
    }

    /// Sources record in the order they declare, not the order they were
    /// mounted in — the whole point of an explicit order.
    #[test]
    fn explicit_order_wins_over_mount_order() {
        let mut world = World::new();
        spawn_context(
            &mut world,
            wgpu::Device::noop(&wgpu::DeviceDescriptor::default()).0,
            wgpu::Device::noop(&wgpu::DeviceDescriptor::default()).1,
            ResourceGraph::new(),
            DeviceCapabilities::default(),
        );

        // Mounted overlay-first, so mount order is the opposite of draw order.
        let overlay = world.spawn_source(RecordingSource::new(FrameSourceOrder::UI));
        let mesh = world.spawn_source(RecordingSource::new(FrameSourceOrder::MESH));

        let (order, ambiguous) = record_order(&world);
        assert_eq!(order, vec![mesh, overlay], "the lower order records first");
        assert!(ambiguous.is_empty(), "distinct orders are not ambiguous");
    }

    /// Equal orders keep mount order, and the mount index is stable when an
    /// earlier source is despawned — which is why it cannot be the ECS row
    /// order.
    #[test]
    fn equal_orders_keep_mount_order_across_a_despawn() {
        let mut world = World::new();
        test_context(&mut world);

        let first = world.spawn_source(RecordingSource::new(FrameSourceOrder::UI));
        let second = world.spawn_source(RecordingSource::new(FrameSourceOrder::UI));
        let third = world.spawn_source(RecordingSource::new(FrameSourceOrder::UI));
        assert_eq!(record_order(&world).0, vec![first, second, third]);

        // Despawning the first leaves the other two in mount order, even
        // though the ECS moved the last row into the freed one.
        world.despawn(first);
        assert_eq!(
            record_order(&world).0,
            vec![second, third],
            "mount order survives a despawn"
        );
    }

    /// A source mounted at an explicit order ignores what its own `order`
    /// says, and `set_order` can change it later.
    #[test]
    fn an_explicit_order_overrides_the_one_the_source_declares() {
        let mut world = World::new();
        test_context(&mut world);

        let a = world.spawn_source_at(
            FrameSourceOrder::UI,
            RecordingSource::new(FrameSourceOrder::MESH),
        );
        let b = world.spawn_source(RecordingSource::new(FrameSourceOrder::MESH));

        // `a` was mounted as an overlay, so it records last despite declaring
        // `MESH` itself.
        assert_eq!(record_order(&world).0, vec![b, a]);

        let _ = world.with_mut::<Source, _>(a, |source| source.set_order(None));
        assert_eq!(
            record_order(&world).0,
            vec![a, b],
            "dropping the override falls back to the declared order"
        );
    }

    /// Typed access finds the concrete type and returns `None` for another,
    /// rather than panicking.
    #[test]
    fn typed_access_downcasts_and_rejects_the_wrong_type() {
        struct OtherSource(Scene);

        impl FrameSource for OtherSource {
            fn build_scene(
                &mut self,
                _world: &World,
                _ctx: RenderContext,
                _encoder: &mut wgpu::CommandEncoder,
            ) {
            }
            fn scene(&self) -> &Scene {
                &self.0
            }
            fn order(&self) -> FrameSourceOrder {
                FrameSourceOrder::MESH
            }
        }

        let mut world = World::new();
        test_context(&mut world);

        let recording = world.spawn_source(RecordingSource::new(FrameSourceOrder::MESH));
        let other = world.spawn_source(OtherSource(Scene::new()));

        assert!(
            world
                .with_mut::<Source, _>(recording, |s| s.as_mut::<RecordingSource>().is_some())
                .unwrap()
        );
        assert!(
            world
                .with_mut::<Source, _>(recording, |s| s.as_mut::<OtherSource>().is_none())
                .unwrap()
        );
        assert!(
            world
                .with_mut::<Source, _>(other, |s| s.as_mut::<OtherSource>().is_some())
                .unwrap()
        );
        assert!(
            world
                .with_mut::<Source, _>(other, |s| s.as_ref::<RecordingSource>().is_none())
                .unwrap()
        );
    }

    /// One query drives sources of different concrete types, which is what the
    /// erased handle is for.
    #[test]
    fn one_query_builds_every_source_type() {
        struct CountingSource(u32, Scene);

        impl FrameSource for CountingSource {
            fn build_scene(
                &mut self,
                _world: &World,
                _ctx: RenderContext,
                _encoder: &mut wgpu::CommandEncoder,
            ) {
                self.0 += 1;
            }
            fn scene(&self) -> &Scene {
                &self.1
            }
            fn order(&self) -> FrameSourceOrder {
                FrameSourceOrder::UI
            }
        }

        let mut world = World::new();
        let ctx = test_context(&mut world);
        world.spawn_source(RecordingSource::new(FrameSourceOrder::MESH));
        world.spawn_source(CountingSource(0, Scene::new()));

        let mut encoder = wgpu::Device::noop(&wgpu::DeviceDescriptor::default())
            .0
            .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
        let entities: Vec<Entity> = world.query::<&Source>().map(|(e, _)| e).collect();
        assert_eq!(entities.len(), 2, "both sources are seen by one query type");
        for entity in entities {
            world
                .with_mut::<Source, _>(entity, |source| {
                    source.build_scene(&world, ctx, &mut encoder)
                })
                .unwrap();
        }
    }

    /// Both phases run in the documented order: every source is built before
    /// any scene is recorded.
    #[test]
    fn every_source_is_built_before_any_is_recorded() {
        let mut world = World::new();
        let ctx = test_context(&mut world);

        let order = Rc::new(RefCell::new(Vec::new()));
        struct PhasedSource {
            name: &'static str,
            log: Rc<RefCell<Vec<String>>>,
            scene: Scene,
        }
        impl FrameSource for PhasedSource {
            fn build_scene(
                &mut self,
                _world: &World,
                _ctx: RenderContext,
                _encoder: &mut wgpu::CommandEncoder,
            ) {
                self.log.borrow_mut().push(format!("build {}", self.name));
            }
            fn scene(&self) -> &Scene {
                &self.scene
            }
            fn order(&self) -> FrameSourceOrder {
                FrameSourceOrder::MESH
            }
        }

        for name in ["a", "b"] {
            world.spawn_source(PhasedSource {
                name,
                log: Rc::clone(&order),
                scene: Scene::new(),
            });
        }

        let mut encoder = wgpu::Device::noop(&wgpu::DeviceDescriptor::default())
            .0
            .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
        let entities: Vec<Entity> = world.query::<&Source>().map(|(e, _)| e).collect();
        for entity in &entities {
            world
                .with_mut::<Source, _>(*entity, |source| {
                    source.build_scene(&world, ctx, &mut encoder)
                })
                .unwrap();
        }
        order.borrow_mut().push("record".to_string());

        assert_eq!(
            &*order.borrow(),
            &["build a", "build b", "record"],
            "both sources build before the record phase starts"
        );
    }

    /// A source that was never mounted at an explicit order takes the one it
    /// declares, and a fresh source reports what it declared.
    #[test]
    fn a_source_reports_its_declared_order_until_overridden() {
        let source = Source::new(RecordingSource::new(FrameSourceOrder::UI));
        assert_eq!(source.order(), FrameSourceOrder::UI);

        let mut source = Source::new(RecordingSource::new(FrameSourceOrder::MESH))
            .with_order(FrameSourceOrder::UI);
        assert_eq!(source.order(), FrameSourceOrder::UI, "the override wins");

        source.set_order(None);
        assert_eq!(source.order(), FrameSourceOrder::MESH, "and can be dropped");
    }

    /// An ambiguity is reported once, and only again when it changes: a steady
    /// frame must not flood the log.
    #[test]
    fn an_ambiguity_is_reported_once_and_again_only_when_it_changes() {
        let mut world = World::new();
        test_context(&mut world);

        let a = world.spawn_source(RecordingSource::new(FrameSourceOrder::MESH));
        let b = world.spawn_source(RecordingSource::new(FrameSourceOrder::MESH));

        let (_, ambiguous) = record_order(&world);
        assert_eq!(ambiguous.len(), 1, "the two share one order");
        assert_eq!(ambiguous[0].0, FrameSourceOrder::MESH);
        assert_eq!(ambiguous[0].1, vec![a, b], "in mount order");

        let mut warnings = OrderWarnings::default();
        assert!(warnings.check(&ambiguous), "the first frame reports it");
        assert!(!warnings.check(&ambiguous), "a steady frame stays quiet");

        // Resolving the ambiguity stops the reporting; reintroducing it warns
        // once more.
        let _ =
            world.with_mut::<Source, _>(b, |source| source.set_order(Some(FrameSourceOrder::UI)));
        let (_, resolved) = record_order(&world);
        assert!(resolved.is_empty());
        assert!(!warnings.check(&resolved));

        let _ =
            world.with_mut::<Source, _>(b, |source| source.set_order(Some(FrameSourceOrder::MESH)));
        let (_, again) = record_order(&world);
        assert!(warnings.check(&again), "the ambiguity is back");
        assert!(!warnings.check(&again), "and still reports only once");
    }

    /// Resolving the order reuses its buffers, so a steady scene stops
    /// allocating.
    ///
    /// The capacity is what proves reuse: a fresh `Vec` per frame would leave
    /// each one at its own length, while a cleared-and-refilled one keeps the
    /// largest capacity it has ever needed.
    #[test]
    fn resolving_the_order_reuses_its_buffers() {
        let mut world = World::new();
        test_context(&mut world);
        for _ in 0..4 {
            world.spawn_source(RecordingSource::new(FrameSourceOrder::MESH));
        }
        world.spawn_source(RecordingSource::new(FrameSourceOrder::UI));

        let mut resolved = SourceOrder::default();
        resolved.resolve(&world);
        let order_capacity = resolved.order.capacity();
        let ambiguous_capacity = resolved.ambiguous.capacity();
        assert_eq!(resolved.entities().len(), 5);
        assert_eq!(resolved.ambiguous().len(), 1, "four share one order");

        // A later frame with fewer sources keeps both allocations.
        let first = world.query::<&Source>().next().expect("a source").0;
        world.despawn(first);
        resolved.resolve(&world);
        assert_eq!(resolved.entities().len(), 4);
        assert_eq!(
            resolved.order.capacity(),
            order_capacity,
            "the order buffer is reused rather than reallocated"
        );
        assert_eq!(
            resolved.ambiguous.capacity(),
            ambiguous_capacity,
            "the ambiguity buffer is reused rather than reallocated"
        );
    }

    /// Distinct orders produce no ambiguity at all.
    #[test]
    fn distinct_orders_are_never_ambiguous() {
        let mut world = World::new();
        test_context(&mut world);
        world.spawn_source(RecordingSource::new(FrameSourceOrder::MESH));
        world.spawn_source(RecordingSource::new(FrameSourceOrder::UI));

        let (order, ambiguous) = record_order(&world);
        assert_eq!(order.len(), 2);
        assert!(ambiguous.is_empty());
        assert!(!OrderWarnings::default().check(&ambiguous));
    }

    /// A logger that keeps what was logged, so a test can assert on the
    /// message rather than only on the boolean the check returns.
    struct CaptureLogger;

    static CAPTURED: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());

    impl log::Log for CaptureLogger {
        fn enabled(&self, _metadata: &log::Metadata<'_>) -> bool {
            true
        }

        fn log(&self, record: &log::Record<'_>) {
            if let Ok(mut captured) = CAPTURED.lock() {
                captured.push(record.args().to_string());
            }
        }

        fn flush(&self) {}
    }

    /// Install the capture logger before anything logs, and read back what it
    /// caught. `log` allows one logger per process, so every test that wants
    /// the messages goes through here.
    fn capture_logs(f: impl FnOnce()) -> Vec<String> {
        // A test process has no logger yet, so this always succeeds; a second
        // install in the same process would be ignored, which is why the
        // captured list is cleared first.
        static LOGGER: CaptureLogger = CaptureLogger;
        let _ = log::set_logger(&LOGGER);
        log::set_max_level(log::LevelFilter::Warn);
        CAPTURED.lock().expect("the capture mutex").clear();

        f();

        let captured = CAPTURED.lock().expect("the capture mutex");
        captured.clone()
    }

    /// The warning names the group's size, its order and its entities, so a
    /// reader can tell which sources are ambiguous without guessing.
    #[test]
    fn the_ambiguity_warning_names_the_group_order_and_entities() {
        let mut world = World::new();
        test_context(&mut world);
        let a = world.spawn_source(RecordingSource::new(FrameSourceOrder::UI));
        let b = world.spawn_source(RecordingSource::new(FrameSourceOrder::UI));

        let messages = capture_logs(|| {
            let (_, ambiguous) = record_order(&world);
            let mut warnings = OrderWarnings::default();
            assert!(warnings.check(&ambiguous), "the group is reported");
        });

        assert_eq!(messages.len(), 1, "exactly one warning: {messages:?}");
        let message = &messages[0];
        assert!(
            message.contains('2'),
            "the group's size is named: {message}"
        );
        assert!(
            message.contains(&FrameSourceOrder::UI.0.to_string()),
            "the order's value is named: {message}"
        );
        assert!(
            message.contains(&format!("{a:?}")) && message.contains(&format!("{b:?}")),
            "both entities are named: {message}"
        );
    }

    /// Distinct orders log nothing at all, so a correct frame is silent.
    #[test]
    fn distinct_orders_log_nothing() {
        let mut world = World::new();
        test_context(&mut world);
        world.spawn_source(RecordingSource::new(FrameSourceOrder::MESH));
        world.spawn_source(RecordingSource::new(FrameSourceOrder::UI));

        let messages = capture_logs(|| {
            let (_, ambiguous) = record_order(&world);
            assert!(!OrderWarnings::default().check(&ambiguous));
        });
        assert!(messages.is_empty(), "nothing to warn about: {messages:?}");
    }

    /// A steady frame does not repeat the warning, and resolving the ambiguity
    /// stops it: the log reports a change, not a condition that persists.
    #[test]
    fn a_steady_frame_repeats_nothing_in_the_log() {
        let mut world = World::new();
        test_context(&mut world);
        let a = world.spawn_source(RecordingSource::new(FrameSourceOrder::MESH));
        let _b = world.spawn_source(RecordingSource::new(FrameSourceOrder::MESH));
        let mut warnings = OrderWarnings::default();

        let messages = capture_logs(|| {
            for _ in 0..5 {
                let (_, ambiguous) = record_order(&world);
                warnings.check(&ambiguous);
            }
        });
        assert_eq!(
            messages.len(),
            1,
            "five steady frames warn once: {messages:?}"
        );

        // Resolving it and reintroducing it warns once more, not twice.
        let _ =
            world.with_mut::<Source, _>(a, |source| source.set_order(Some(FrameSourceOrder::UI)));
        let messages = capture_logs(|| {
            let (_, resolved) = record_order(&world);
            assert!(!warnings.check(&resolved), "resolved: nothing to say");
        });
        assert!(messages.is_empty(), "resolving is silent: {messages:?}");
    }

    /// Re-applying the order a source already has does not disturb the
    /// ambiguity bookkeeping, so a caller may set an order every frame.
    #[test]
    fn re_applying_the_same_order_keeps_the_log_quiet() {
        let mut world = World::new();
        test_context(&mut world);
        let a = world.spawn_source(RecordingSource::new(FrameSourceOrder::MESH));
        let b = world.spawn_source(RecordingSource::new(FrameSourceOrder::MESH));
        let mut warnings = OrderWarnings::default();

        let messages = capture_logs(|| {
            for _ in 0..3 {
                // What a caller that pins its sources' order every frame does.
                let _ = world.with_mut::<Source, _>(a, |source| {
                    source.set_order(Some(FrameSourceOrder::MESH))
                });
                let _ = world.with_mut::<Source, _>(b, |source| {
                    source.set_order(Some(FrameSourceOrder::MESH))
                });
                let (_, ambiguous) = record_order(&world);
                warnings.check(&ambiguous);
            }
        });
        assert_eq!(
            messages.len(),
            1,
            "the second and third frames change nothing: {messages:?}"
        );
    }

    /// Three sources sharing an order are one group, not three pairs, and the
    /// group lists every entity.
    #[test]
    fn a_three_way_ambiguity_is_one_group_of_three() {
        let mut world = World::new();
        test_context(&mut world);

        let ids: Vec<Entity> = (0..3)
            .map(|_| world.spawn_source(RecordingSource::new(FrameSourceOrder::MESH)))
            .collect();

        let (_, ambiguous) = record_order(&world);
        assert_eq!(ambiguous.len(), 1, "one group, not pairs");
        assert_eq!(ambiguous[0].1, ids);
    }

    /// Mounting is monotonic, so a source mounted later always breaks a tie
    /// after one mounted earlier.
    #[test]
    fn mount_indices_are_monotonic() {
        let mut world = World::new();
        test_context(&mut world);

        let indices: Vec<u64> = (0..3)
            .map(|_| {
                let entity = world.spawn_source(RecordingSource::new(FrameSourceOrder::MESH));
                world
                    .with_mut::<Source, _>(entity, |s| s.mount_index())
                    .unwrap()
            })
            .collect();
        assert_eq!(indices, vec![0, 1, 2]);
    }
}

#[cfg(test)]
mod release_tests {
    use super::*;
    use unlit_wgpu::resources::{ResHandle, Resource as GraphResource};

    /// A source that registers a node, so dropping it has something to give up.
    ///
    /// It holds the id in its own state, as a real source does: the node stays
    /// alive for as long as the source component does.
    struct OwningSource {
        context: RenderContext,
        node: Option<ResHandle>,
        scene: Scene,
    }

    impl FrameSource for OwningSource {
        fn build_scene(
            &mut self,
            world: &World,
            ctx: RenderContext,
            _encoder: &mut wgpu::CommandEncoder,
        ) {
            // Register once, on the first frame: a node the source owns and
            // nothing else refers to.
            self.context = ctx;
            if self.node.is_none() {
                self.node = Some(
                    world
                        .get_mut::<ResourceGraph>(ctx.graph)
                        .expect("the context's graph exists")
                        .insert(GraphResource::Virtual, None),
                );
            }
        }

        fn scene(&self) -> &Scene {
            &self.scene
        }

        fn order(&self) -> FrameSourceOrder {
            FrameSourceOrder::UI
        }
    }

    /// A source whose build takes a maintain scope and then returns at once,
    /// the way a source with nothing to draw does.
    struct EarlyReturnSource {
        context: RenderContext,
        node: Option<ResHandle>,
        scene: Scene,
    }

    impl FrameSource for EarlyReturnSource {
        fn build_scene(
            &mut self,
            world: &World,
            ctx: RenderContext,
            _encoder: &mut wgpu::CommandEncoder,
        ) {
            // The scope is the whole of the build's graph handling: this source
            // never calls `maintain`, and the return is what settles the graph.
            let _maintain = ctx.maintain_scope(world);
            self.context = ctx;
            if self.node.is_none() {
                self.node = Some(
                    world
                        .get_mut::<ResourceGraph>(ctx.graph)
                        .expect("the context's graph exists")
                        .insert(GraphResource::Virtual, None),
                );
            } else {
                // A source with nothing left to draw: it gives its node up and
                // returns, leaving the scope's drop to collect it.
                self.node = None;
            }
        }

        fn scene(&self) -> &Scene {
            &self.scene
        }

        fn order(&self) -> FrameSourceOrder {
            FrameSourceOrder::MESH
        }
    }

    fn noop_context(world: &mut World) -> RenderContext {
        spawn_context(
            world,
            wgpu::Device::noop(&wgpu::DeviceDescriptor::default()).0,
            wgpu::Device::noop(&wgpu::DeviceDescriptor::default()).1,
            ResourceGraph::new(),
            DeviceCapabilities::default(),
        )
    }

    /// Build the source once, so it registers its node.
    ///
    /// The node's id is deliberately not handed back: an id is a strong
    /// reference, so a test holding one would keep the very node it wants to
    /// watch the graph collect.
    fn build_once(world: &mut World, entity: Entity, ctx: RenderContext) {
        let mut encoder = wgpu::Device::noop(&wgpu::DeviceDescriptor::default())
            .0
            .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
        world
            .with_mut::<Source, _>(entity, |source| {
                source.build_scene(world, ctx, &mut encoder)
            })
            .expect("the source entity exists");
    }

    /// How many nodes the context's graph holds.
    fn graph_len(world: &World, ctx: RenderContext) -> usize {
        world.get_mut::<ResourceGraph>(ctx.graph).unwrap().len()
    }

    /// Drive the graph's collection the way a frame would.
    fn maintain(world: &mut World, ctx: RenderContext) {
        world
            .get_mut::<ResourceGraph>(ctx.graph)
            .unwrap()
            .maintain();
    }

    /// Despawning a source drops the ids it holds, and the next `maintain`
    /// collects the nodes they were the last references to.
    ///
    /// `despawn` drops the component, so nothing has to tell the graph that an
    /// entity is gone — the reference counts carry that on their own.
    #[test]
    fn dropping_a_source_releases_the_nodes_it_owns() {
        let mut world = World::new();
        let ctx = noop_context(&mut world);
        let entity = world.spawn_source(OwningSource {
            context: ctx,
            node: None,
            scene: Scene::new(),
        });
        build_once(&mut world, entity, ctx);
        assert_eq!(
            graph_len(&world, ctx),
            1,
            "the source registered exactly the node it owns"
        );

        world.despawn(entity);

        // Giving up the id only moves a count: the node is still there, and
        // the graph resolves it until something maintains.
        assert_eq!(
            graph_len(&world, ctx),
            1,
            "dropping an id does not itself remove the node"
        );

        maintain(&mut world, ctx);
        assert_eq!(
            graph_len(&world, ctx),
            0,
            "maintain collected the node nothing refers to"
        );
    }

    /// A source that owns nothing still despawns, so dropping a source is safe
    /// for every source.
    #[test]
    fn removing_a_source_that_owns_nothing_still_removes_it() {
        let mut world = World::new();
        let ctx = noop_context(&mut world);
        let entity = world.spawn_source(OwningSource {
            context: ctx,
            node: None,
            scene: Scene::new(),
        });

        world.despawn(entity);
        assert!(!world.contains(entity));
        maintain(&mut world, ctx);
        assert_eq!(graph_len(&world, ctx), 0);
    }

    /// Two sources leaving in the same frame give up their ids, and the frame's
    /// single `maintain` is what drops both.
    ///
    /// Neither removal touches the graph: each is a reference count reaching
    /// zero, and one pass collects whatever the frame left unreferenced.
    #[test]
    fn one_maintain_drops_the_nodes_every_source_gave_up() {
        let mut world = World::new();
        let ctx = noop_context(&mut world);
        let mut entities = Vec::new();
        for _ in 0..2 {
            entities.push(world.spawn_source(OwningSource {
                context: ctx,
                node: None,
                scene: Scene::new(),
            }));
        }

        for &entity in &entities {
            build_once(&mut world, entity, ctx);
        }
        assert_eq!(graph_len(&world, ctx), 2, "each source registered a node");

        for &entity in &entities {
            world.despawn(entity);
        }

        // Both removals only moved counts: the nodes the two sources owned are
        // still there until the frame maintains.
        assert_eq!(
            graph_len(&world, ctx),
            2,
            "dropping an id does not itself remove the node"
        );

        // The frame's one pass drops everything the two of them gave up.
        maintain(&mut world, ctx);
        assert_eq!(
            graph_len(&world, ctx),
            0,
            "the single maintain collected every unreferenced node"
        );
    }

    /// A build that returns early still settles the graph: the scope a source
    /// takes at its top maintains on the way out, so no return has to remember
    /// the call.
    #[test]
    fn a_build_that_returns_early_still_maintains() {
        let mut world = World::new();
        let ctx = noop_context(&mut world);
        let entity = world.spawn_source(EarlyReturnSource {
            context: ctx,
            node: None,
            scene: Scene::new(),
        });

        // The first build registers the node the source owns.
        build_once(&mut world, entity, ctx);
        assert_eq!(graph_len(&world, ctx), 1, "the source registered a node");

        // The second build gives it up and returns at once. Nothing calls
        // `maintain`: the scope's drop is the pass, and it collects the node
        // the build left unreferenced.
        build_once(&mut world, entity, ctx);
        assert_eq!(
            graph_len(&world, ctx),
            0,
            "the early return maintained the graph"
        );
    }
}