bevy_lights 0.5.0

Practical lights for Bevy: fires that flicker and flare as they kindle, a budgeted pool of real lights placed over thousands of virtual ones, and billboard shader flames.
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
//! Smoke: what a fire gives off above its flame.
//!
//! Add [`FlameSmoke`] to a [`FlameSite`](crate::FlameSite) and its [`Flame`] gets one more child, a camera-facing additive quad
//! (`src/smoke.wesl`) holding a faint plume: a column that leaves the flame's tip, bends downwind and widens as a turbulent plume
//! does, whose wisps are lit by the fire and thin into the dark. There is no particle state: the column is a pure function of the
//! shared clock, so the host pays one draw per fire that asks and the smoke of a fire is the same on every machine.
//!
//! The quad is the flame's child, so it takes the fire's catch and the wind's lean from the flame's own instance scale: a fire being
//! lit smokes nothing until it has caught, a fire put out stops, and a wind bends the column further than it leans the flame. It has
//! the sparks' quad's geometry, so it carries the sparks' culling box ([`ember_cull_extents`](crate::ember_cull_extents)), kept in
//! step with the flame's scale.
//!
//! The smoke is **additive**: at night smoke is visible only by the light the fire puts into it, which is what an additive layer
//! draws, and an additive layer joins no sorting against the host's other transparent surfaces. It has no dark, occluding half; a
//! host that wants daylight smoke draws its own.
//!
//! The design and its sources are in `docs/research/flame-smoke.md`.

use bevy::asset::embedded_asset;
use bevy::camera::primitives::Aabb;
use bevy::camera::visibility::NoAutoAabb;
use bevy::light::NotShadowCaster;
use bevy::math::Vec3A;
use bevy::mesh::{MeshTag, MeshVertexBufferLayoutRef};
use bevy::pbr::{Material, MaterialPipeline, MaterialPipelineKey, MeshMaterial3d};
use bevy::prelude::*;
use bevy::render::render_resource::{AsBindGroup, RenderPipelineDescriptor, SpecializedMeshPipelineError};
use bevy::shader::ShaderRef;
use bevy::time::Real;

use crate::Snuff;
use crate::flame::{Flame, FlameAssets, FlameLook, FlameSite, TintKey, TintedMaterials, scene_colour};
use crate::model::fire_colour::{SPARK_DULL_RED, SPARK_ORANGE};
use crate::model::{
    SMOKE_TAIL_SECONDS, SNUFF_SECONDS, ember_cull_extents, pack_flame_tag, retint, set_flame_brightness,
    unpack_flame_tag,
};

/// The smoke shader, embedded in the binary by [`FlamePlugin`](crate::FlamePlugin).
const SMOKE_SHADER_PATH: &str = "embedded://bevy_lights/smoke.wesl";

/// The most density a fire's smoke can ask for: [`FlameSmoke::density`] above it draws at it.
pub const MAX_SMOKE_DENSITY: f32 = 1.0;

/// How long a wick goes on making smoke after the fire began to go out, in seconds: the emission falls from full to nothing over this
/// long (`docs/research/flame-smoke-tail.md`). A design default: twice [`SNUFF_SECONDS`], the wick smouldering on after its flame.
const EMISSION_SECONDS: f32 = 2.4;

/// How bright the coals' glow lights a put-out fire's smoke, against the unit light of the flame it replaces (a design default).
const AFTERGLOW: f32 = 0.18;

/// The bit of a smoke quad's tag, the lowest of the height's sixteen, that says "this quad is a trail: read the scale's `x` as the
/// seconds since the fire went out". A steady quad's tag always has it clear ([`steady_tag`]), so the height keeps fifteen bits of its
/// sixteen, an error of `2 · max_height / 65535` in the quad's size.
const TAIL_BIT: u32 = 1 << 16;

/// A smoke quad's tag for `site` at `share` of the most density: the flame's tag with the trail bit clear.
fn steady_tag(site: &FlameSite, share: f32, max_height: f32) -> u32 {
    pack_flame_tag(site.phase, site.height, share, max_height) & !TAIL_BIT
}

/// A fire's smoke: add it to a [`FlameSite`](crate::FlameSite) to give its flame a plume, remove it to take the plume away.
///
/// A site without one is drawn exactly as it always was: no extra entity, no extra draw. The smoke is the fire's own colour
/// ([`FlameSite::color`], or the scene's [`FlameLook::color`]), the sparks' orange moved to that hue ([`retint`](crate::retint)) and
/// pulled toward grey, so a green fire smokes a green-grey. Its strength is [`FlameLook::strength`] times the
/// [`density`](Self::density); both follow a changed look.
///
/// The smoke respects the site's [`depth_fade`](crate::FlameSite::depth_fade) (a fire whose source cannot be seen smokes nothing
/// that can) and its catch (a flame that has not caught smokes nothing). Its default density is a design default
/// (`docs/research/flame-smoke.md`); [`FireKind::smoke`](crate::FireKind::smoke) gives each kind its own.
///
/// **A fire put out leaves a trail.** When the light a site's [`fire`](crate::FlameSite::fire) names gets a [`Snuff`], the flame
/// goes out over [`SNUFF_SECONDS`] as it always did, but the smoke does not shrink with it: it is carried on up the way the air carries
/// smoke, the base of the column lifts off the wick and thins as the wick smoulders out, and the trail ends, exactly dark, after
/// [`SMOKE_TAIL_SECONDS`] (`docs/research/flame-smoke-tail.md`). It is lit by the dying flame and then by the coals' glow. A site that
/// names no fire has no douse to follow and keeps no trail, a fire loaded as already out begins none, and re-lighting a fire (removing
/// its `Snuff`) ends the trail at once: the plume goes back to following the catch.
#[derive(Component, Clone, Copy, Debug, PartialEq, Reflect)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(default))]
#[reflect(Component)]
pub struct FlameSmoke {
    /// How much smoke the fire gives off, `0.0..=`[`MAX_SMOKE_DENSITY`]: the brightness of the lit column. `0.0` gives none.
    pub density: f32,
}

impl Default for FlameSmoke {
    fn default() -> Self {
        Self { density: 0.8 }
    }
}

impl FlameSmoke {
    /// What is unusable in these settings, field by field; empty when they are fine. See
    /// [`Flicker::problems`](crate::Flicker::problems).
    pub fn problems(&self) -> Vec<crate::Problem> {
        let mut out = Vec::new();
        crate::model::problem::within(&mut out, "density", self.density, 0.0, MAX_SMOKE_DENSITY);
        out
    }

    /// The density as the share of [`MAX_SMOKE_DENSITY`] the mesh tag's low byte carries.
    fn share(&self) -> f32 {
        if self.density.is_finite() { (self.density / MAX_SMOKE_DENSITY).clamp(0.0, 1.0) } else { 0.0 }
    }
}

/// The smoke material: the fire's colour and clock, and the two colours the column passes through. Private: a host never builds one.
#[derive(Asset, TypePath, AsBindGroup, Debug, Clone)]
pub struct SmokeMaterial {
    #[uniform(0)]
    base: LinearRgba,
    /// `x` seconds (wrapped hourly), `y` the tag's height scale, `z` 1 on the material of the sites that asked for the depth fade,
    /// `w` the strength.
    #[uniform(0)]
    params: Vec4,
    /// The column's colour just above the flame (`retint(SPARK_ORANGE, base)`).
    #[uniform(0)]
    warm: Vec4,
    /// The column's colour near its top (`retint(SPARK_DULL_RED, base)`).
    #[uniform(0)]
    cool: Vec4,
    /// The trail of a fire put out, from the model's constants so the shader copies none of them: `x` the trail's length in seconds
    /// ([`SMOKE_TAIL_SECONDS`]), `y` the flame's ([`SNUFF_SECONDS`]), `z` how long the wick goes on making smoke ([`EMISSION_SECONDS`])
    /// and `w` the coals' glow ([`AFTERGLOW`]).
    #[uniform(0)]
    tail: Vec4,
}

impl SmokeMaterial {
    /// The material of a fire of colour `mid` at `strength`; `depth_fade` as [`FlameSite::depth_fade`].
    fn new(mid: [f32; 3], strength: f32, max_height: f32, depth_fade: bool) -> Self {
        let mut material = Self {
            base: LinearRgba::NONE,
            params: Vec4::new(0.0, max_height, if depth_fade { 1.0 } else { 0.0 }, strength),
            warm: Vec4::ZERO,
            cool: Vec4::ZERO,
            tail: Vec4::new(SMOKE_TAIL_SECONDS, SNUFF_SECONDS, EMISSION_SECONDS, AFTERGLOW),
        };
        material.recolour(mid, strength);
        material
    }

    /// Writes the fire's colour and the two the column makes.
    fn recolour(&mut self, mid: [f32; 3], strength: f32) {
        let stop = |stop| {
            let [red, green, blue] = retint(stop, mid);
            Vec4::new(red, green, blue, 0.0)
        };
        self.base = LinearRgba { red: mid[0], green: mid[1], blue: mid[2], alpha: strength };
        self.warm = stop(SPARK_ORANGE);
        self.cool = stop(SPARK_DULL_RED);
    }
}

impl Material for SmokeMaterial {
    fn vertex_shader() -> ShaderRef {
        SMOKE_SHADER_PATH.into()
    }

    fn fragment_shader() -> ShaderRef {
        SMOKE_SHADER_PATH.into()
    }

    fn alpha_mode(&self) -> AlphaMode {
        AlphaMode::Add
    }

    fn enable_prepass() -> bool {
        false
    }

    fn enable_shadows() -> bool {
        false
    }

    fn specialize(
        _pipeline: &MaterialPipeline,
        descriptor: &mut RenderPipelineDescriptor,
        _layout: &MeshVertexBufferLayoutRef,
        _key: MaterialPipelineKey<Self>,
    ) -> Result<(), SpecializedMeshPipelineError> {
        if let Some(depth) = descriptor.depth_stencil.as_mut() {
            depth.depth_write_enabled = Some(false);
        }
        descriptor.primitive.cull_mode = None;
        Ok(())
    }
}

/// Registers the smoke's shader, material, assets and systems; [`FlamePlugin`](crate::FlamePlugin) calls it.
pub(crate) fn build(app: &mut App) {
    embedded_asset!(app, "smoke.wesl");
    app.add_plugins(bevy::pbr::MaterialPlugin::<SmokeMaterial>::default())
        .init_resource::<SmokeAssets>()
        .register_type::<FlameSmoke>()
        .add_systems(Startup, build_smoke_assets);
}

/// The quad, the scene's two materials (depth fade off and on) and one more for each colour a site asks for, which every smoke quad
/// shares.
#[derive(Resource, Default)]
pub(crate) struct SmokeAssets {
    mesh: Handle<Mesh>,
    material: Handle<SmokeMaterial>,
    faded_material: Handle<SmokeMaterial>,
    tinted: TintedMaterials<SmokeMaterial>,
    built: bool,
}

impl SmokeAssets {
    fn material_for(&self, depth_fade: bool) -> &Handle<SmokeMaterial> {
        if depth_fade { &self.faded_material } else { &self.material }
    }

    /// The id of the material a site of `color` smokes with, when it exists yet.
    fn material_id(&self, color: Option<Color>, depth_fade: bool) -> Option<AssetId<SmokeMaterial>> {
        match color {
            None => Some(self.material_for(depth_fade).id()),
            Some(color) => self.tinted.id(&TintKey::new(color, depth_fade)),
        }
    }

    /// The material a site of `color` smokes with, made if no quad has used it yet.
    fn material_of(
        &mut self,
        color: Option<Color>,
        depth_fade: bool,
        look: &FlameLook,
        materials: &mut Assets<SmokeMaterial>,
    ) -> Handle<SmokeMaterial> {
        match color {
            None => self.material_for(depth_fade).clone(),
            Some(color) => {
                let key = TintKey::new(color, depth_fade);
                self.tinted.handle(key, materials, || {
                    SmokeMaterial::new(key.rgb(), look.strength, look.max_height, depth_fade)
                })
            }
        }
    }
}

/// The smoke quad of a flame: a child of the [`Flame`], so it inherits the flame's catch and lean.
#[derive(Component)]
pub(crate) struct Smoke;

/// The marker that a [`Flame`] already has its smoke quad.
#[derive(Component)]
pub(crate) struct Smoked;

/// The trail of a fire that was put out, on its smoke quad: the seconds since the fire began to go out, on virtual time (the douse is the
/// fire's state, as its snuff is, so a paused world's trail holds still). While it is there the quad does not follow the flame's catch
/// (the flame is going to nothing); it travels the clock in its scale's `x` instead (see [`tail_scale`]) and says so in its tag
/// ([`TAIL_BIT`]), and `update_smoke_tails` owns it.
#[derive(Component)]
pub(crate) struct SmokeTail {
    elapsed: f32,
}

fn build_smoke_assets(
    mut assets: ResMut<SmokeAssets>,
    look: Res<FlameLook>,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<SmokeMaterial>>,
) {
    assets.mesh = meshes.add(Rectangle::new(1.0, 1.0));
    assets.material =
        materials.add(SmokeMaterial::new(scene_colour(&look), look.strength, look.max_height, false));
    assets.faded_material =
        materials.add(SmokeMaterial::new(scene_colour(&look), look.strength, look.max_height, true));
    assets.built = true;
}

/// The half-extents of the culling box of a smoke quad whose flame stands at `scale`, the instance scale `update_flames` writes
/// (`x` the catch, `y` and `z` one more than the lean). The quad has the sparks' geometry, so its box is theirs
/// ([`ember_cull_extents`]), divided by the scale it inherits.
fn cull_box(height: f32, scale: Vec3) -> Vec3A {
    Vec3A::from(ember_cull_extents(height, scale.x, [scale.y - 1.0, scale.z - 1.0]))
}

/// The scale `x` a trail `elapsed` seconds old travels in, `1 / (1 + elapsed)`, which the vertex stage inverts. It is the quad's
/// *world* scale (the flame's catch times the quad's own, which `update_smoke_tails` sets to make it so). It is positive and no less
/// than `1 / (1 + SMOKE_TAIL_SECONDS)`, so the quad's culling box stays finite, and it needs no copy of the trail's length in the shader.
fn tail_scale(elapsed: f32) -> f32 {
    1.0 / (1.0 + elapsed.max(0.0))
}

/// [`cull_box`] for a trail: the quad is drawn at the height the fire burned at (its catch reads as 1), whatever its scale's `x` says,
/// so the box is the full ball divided by the scale the frustum test will multiply it by.
fn tail_cull_box(height: f32, scale: Vec3) -> Vec3A {
    let [x, y, z] = ember_cull_extents(height, 1.0, [scale.y - 1.0, scale.z - 1.0]);
    Vec3A::new(x / scale.x.max(1.0e-4), y, z)
}

/// A flame that has no smoke quad yet. The extra tongues of a wide fire ([`FlameTongue`](crate::FlameTongue)) have none: the plume leaves
/// the fire once, from the middle flame.
type UnsmokedFlame = (With<Flame>, Without<Smoked>, Without<crate::FlameTongue>);

/// Gives the flame of every [`FlameSmoke`] site one smoke quad, carrying the site's phase and height and, in the tag's brightness
/// byte, the density. The quad's culling box is the crate's own, for the reason the flame's is: the vertex stage draws a quad the
/// unit square's box does not hold, and the scale it inherits is data.
pub(crate) fn dress_smoke(
    mut commands: Commands,
    flames: Query<(Entity, &ChildOf, &Transform), UnsmokedFlame>,
    sites: Query<(&FlameSite, &FlameSmoke)>,
    mut smoke_assets: ResMut<SmokeAssets>,
    mut materials: ResMut<Assets<SmokeMaterial>>,
    look: Res<FlameLook>,
    flame_assets: Res<FlameAssets>,
) {
    if !smoke_assets.built || !flame_assets.built() {
        return;
    }
    for (flame, parent, at) in &flames {
        let Ok((site, smoke)) = sites.get(parent.parent()) else { continue };
        let packed = steady_tag(site, smoke.share(), flame_assets.max_height());
        let tag = MeshTag::new(packed);
        // The flame's scale as it stands: a flame dressed in mid-catch or in a wind is not at the identity.
        let height = unpack_flame_tag(packed, flame_assets.max_height()).1;
        let bound = Aabb { center: Vec3A::ZERO, half_extents: cull_box(height, at.scale) };
        let mesh = smoke_assets.mesh.clone();
        let material = smoke_assets.material_of(site.color, site.depth_fade, &look, &mut materials);
        commands.entity(flame).queue_silenced(move |mut flame: EntityWorldMut| {
            flame.insert(Smoked).with_children(|parent| {
                parent.spawn((
                    Name::new("Smoke"),
                    Smoke,
                    tag,
                    Mesh3d(mesh),
                    MeshMaterial3d(material),
                    Transform::IDENTITY,
                    NotShadowCaster,
                    // The unit square's box neither holds the column's quad nor survives the scale it inherits.
                    bound,
                    NoAutoAabb,
                ));
            });
        });
    }
}

/// A smoke quad that follows its flame's catch: every quad but a trail.
type SteadyQuads = (With<Smoke>, Without<SmokeTail>);

/// A trail's quad: the quad's own `Transform` is written by `update_smoke_tails` and the flames' are read through [`SmokeOwners`], so
/// the two queries must be disjoint.
type TrailQuads = (With<Smoke>, Without<Flame>);

/// What a trail is read and written through: the quad, its flame (its parent), its clock, its local transform, its tag and its box.
type Trail = (
    Entity,
    &'static ChildOf,
    &'static mut SmokeTail,
    &'static mut Transform,
    &'static mut MeshTag,
    &'static mut Aabb,
);

/// What a smoke quad is read through: itself, its flame (its parent), its tag, its culling box and its material.
type SmokeQuad = (
    Entity,
    &'static ChildOf,
    &'static mut MeshTag,
    &'static mut Aabb,
    &'static mut MeshMaterial3d<SmokeMaterial>,
);

/// The flame and the site a smoke quad hangs on, the height scale their tags are packed against, and whether there are smoke quads at all.
#[derive(bevy::ecs::system::SystemParam)]
pub(crate) struct SmokeOwners<'w, 's> {
    flames: Query<'w, 's, (&'static ChildOf, &'static Transform), With<Flame>>,
    sites: Query<'w, 's, (&'static FlameSite, Option<&'static FlameSmoke>)>,
    assets: Res<'w, FlameAssets>,
    quads: Query<'w, 's, (), With<Smoke>>,
}

impl SmokeOwners<'_, '_> {
    /// The site of `flame` and its smoke, and the instance scale `flame` stands at, when `flame` is a flame that hangs on a site.
    fn site_of(&self, flame: Entity) -> Option<(&FlameSite, Option<&FlameSmoke>, Vec3)> {
        let (parent, at) = self.flames.get(flame).ok()?;
        let (site, smoke) = self.sites.get(parent.parent()).ok()?;
        Some((site, smoke, at.scale))
    }

    /// The height scale a flame's tag is packed against ([`FlameLook::max_height`] at `Startup`).
    fn max_height(&self) -> f32 {
        self.assets.max_height()
    }

    /// Whether any smoke quad exists, a steady one or a trail.
    fn has_quads(&self) -> bool {
        !self.quads.is_empty()
    }
}

/// Follows each site's [`FlameSmoke`] and [`FlameSite::depth_fade`] with its quad, takes the quad away when the component goes,
/// keeps the quad's culling box in step with the flame's scale (it runs after `update_flames`, so the box is never a frame behind
/// the scale the frustum test multiplies it by), and ticks the shared clock and a changed [`FlameLook`].
pub(crate) fn update_smoke(
    mut commands: Commands,
    real: Res<Time<Real>>,
    look: Res<FlameLook>,
    mut smoke_assets: ResMut<SmokeAssets>,
    mut materials: ResMut<Assets<SmokeMaterial>>,
    mut quads: Query<SmokeQuad, SteadyQuads>,
    owners: SmokeOwners,
) {
    // The shared clock below ticks while a quad is a trail as well, so the test is for any quad and not the ones this system owns.
    if !owners.has_quads() {
        return;
    }
    let max_height = owners.max_height();
    for (entity, parent, mut tag, mut bound, mut material) in &mut quads {
        let Some((site, Some(wanted), scale)) = owners.site_of(parent.parent()) else {
            // The component is gone (or the flame is): the quad goes, and the flame may be dressed again.
            commands.entity(entity).despawn();
            commands.entity(parent.parent()).remove::<Smoked>();
            continue;
        };
        if smoke_assets.material_id(site.color, site.depth_fade) != Some(material.0.id()) {
            material.0 = smoke_assets.material_of(site.color, site.depth_fade, &look, &mut materials);
        }
        let packed = set_flame_brightness(tag.value, wanted.share());
        if packed != tag.value {
            tag.value = packed;
        }
        // Compared through `Deref`, so a quad whose flame did not change scale is not marked changed.
        let half_extents = cull_box(unpack_flame_tag(tag.value, max_height).1, scale);
        if bound.half_extents != half_extents {
            bound.half_extents = half_extents;
        }
    }
    if !smoke_assets.tinted.is_empty() {
        smoke_assets.tinted.sweep(&materials);
    }
    let elapsed = real.elapsed_secs_wrapped();
    let scene = scene_colour(&look);
    let scene_materials = [smoke_assets.material.id(), smoke_assets.faded_material.id()];
    for (id, is_scene) in scene_materials
        .into_iter()
        .map(|id| (id, true))
        .chain(smoke_assets.tinted.ids().map(|id| (id, false)))
    {
        let Some(mut made) = materials.get_mut(id) else { continue };
        made.params.x = elapsed;
        if look.is_changed() {
            if is_scene {
                made.recolour(scene, look.strength);
            } else {
                made.base.alpha = look.strength;
            }
            made.params.y = look.max_height;
            made.params.w = look.strength;
        }
    }
}

/// Begins a trail on the smoke quad of every flame whose fire has just been put out: a [`Snuff`] added to the light a smoking
/// [`FlameSite::fire`] names, with the flame still going out. A fire loaded as already out ([`Snuff::elapsed`] at [`SNUFF_SECONDS`])
/// begins none, and a site that names no fire has no douse to follow. It does nothing in a frame with no new `Snuff` anywhere.
pub(crate) fn begin_smoke_tails(
    mut commands: Commands,
    snuffed: Query<&Snuff, Added<Snuff>>,
    quads: Query<(Entity, &ChildOf), SteadyQuads>,
    flames: Query<&ChildOf, With<Flame>>,
    sites: Query<&FlameSite>,
) {
    if snuffed.is_empty() {
        return;
    }
    for (quad, parent) in &quads {
        let Ok(on_site) = flames.get(parent.parent()) else { continue };
        let Ok(site) = sites.get(on_site.parent()) else { continue };
        let Some(fire) = site.fire else { continue };
        let Ok(snuff) = snuffed.get(fire) else { continue };
        if snuff.elapsed < SNUFF_SECONDS {
            commands.entity(quad).insert(SmokeTail { elapsed: snuff.elapsed.max(0.0) });
        }
    }
}

/// Drives every trail: advances its clock, writes the scale `x` that carries it (set on the quad so that its world scale is
/// [`tail_scale`], whatever the flame going out has been scaled to), flags the tag and keeps the culling box right. A trail ends when its
/// time is up or when the fire is no longer out (re-lit, or gone), and the quad goes back to following the flame's catch. A trail keeps the
/// material (the colour) its fire had when it was put out: it lasts five seconds.
pub(crate) fn update_smoke_tails(
    mut commands: Commands,
    time: Res<Time>,
    mut quads: Query<Trail, TrailQuads>,
    owners: SmokeOwners,
    snuffs: Query<&Snuff>,
) {
    if quads.is_empty() {
        return;
    }
    let max_height = owners.max_height();
    let dt = time.delta_secs();
    for (entity, parent, mut tail, mut local, mut tag, mut bound) in &mut quads {
        let Some((site, Some(wanted), scale)) = owners.site_of(parent.parent()) else {
            commands.entity(entity).despawn();
            commands.entity(parent.parent()).remove::<Smoked>();
            continue;
        };
        let out = site.fire.is_some_and(|fire| snuffs.contains(fire));
        if !out || tail.elapsed >= SMOKE_TAIL_SECONDS {
            // Over: the quad follows the flame's catch again, from the tag and the box the flame's scale gives it.
            commands.entity(entity).remove::<SmokeTail>();
            local.scale = Vec3::ONE;
            tag.value = steady_tag(site, wanted.share(), max_height);
            bound.half_extents = cull_box(unpack_flame_tag(tag.value, max_height).1, scale);
            continue;
        }
        tail.elapsed += dt;
        let carried = tail_scale(tail.elapsed);
        let wanted_scale = Vec3::new(carried / scale.x.max(1.0e-4), 1.0, 1.0);
        if local.scale != wanted_scale {
            local.scale = wanted_scale;
        }
        let packed = set_flame_brightness(tag.value, wanted.share()) | TAIL_BIT;
        if packed != tag.value {
            tag.value = packed;
        }
        let half_extents =
            tail_cull_box(unpack_flame_tag(tag.value, max_height).1, Vec3::new(carried, scale.y, scale.z));
        if bound.half_extents != half_extents {
            bound.half_extents = half_extents;
        }
    }
}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]
mod tests {
    use super::*;
    use crate::flame::{build_flame_assets, dress_flames, update_flames};
    use crate::model::{FLICKER_DEPTH, ember_reach};

    fn app() -> App {
        let mut app = App::new();
        app.add_plugins(MinimalPlugins)
            .insert_resource(Assets::<Mesh>::default())
            .insert_resource(Assets::<crate::FlameMaterial>::default())
            .insert_resource(Assets::<SmokeMaterial>::default())
            .init_resource::<FlameLook>()
            .init_resource::<FlameAssets>()
            .init_resource::<SmokeAssets>()
            .insert_resource(bevy::time::TimeUpdateStrategy::ManualDuration(
                std::time::Duration::from_secs_f64(1.0 / 60.0),
            ));
        app.add_systems(Startup, (build_flame_assets, build_smoke_assets)).add_systems(
            Update,
            (dress_flames, update_flames, dress_smoke, update_smoke, begin_smoke_tails, update_smoke_tails)
                .chain(),
        );
        app.update();
        app
    }

    fn site(height: f32, phase: f32) -> FlameSite {
        FlameSite {
            color: None,
            height,
            phase,
            kindle: 0.0,
            diameter: None,
            depth: FLICKER_DEPTH,
            depth_fade: false,
            fire: None,
        }
    }

    fn smoke_quads(app: &mut App) -> Vec<(Entity, u32)> {
        app.world_mut()
            .query_filtered::<(&ChildOf, &MeshTag), With<Smoke>>()
            .iter(app.world())
            .map(|(parent, tag)| (parent.parent(), tag.value))
            .collect()
    }

    /// The material a smoke quad is drawn with, copied out.
    fn smoke_of(app: &App, site: Entity) -> SmokeMaterial {
        let flame = app.world().get::<Children>(site).and_then(|c| c.first().copied()).expect("a flame");
        let quad = app.world().get::<Children>(flame).and_then(|c| c.first().copied()).expect("a smoke quad");
        let handle = app.world().get::<MeshMaterial3d<SmokeMaterial>>(quad).expect("a material").0.clone();
        app.world().resource::<Assets<SmokeMaterial>>().get(&handle).expect("it exists").clone()
    }

    #[test]
    fn only_a_site_that_asks_gets_a_smoke_quad_and_it_hangs_on_the_flame() {
        let mut app = app();
        let plain = app.world_mut().spawn((site(0.5, 0.0), Transform::default())).id();
        let smoking =
            app.world_mut().spawn((site(0.5, 1.0), FlameSmoke::default(), Transform::default())).id();
        app.update();
        app.update();
        let quads = smoke_quads(&mut app);
        assert_eq!(quads.len(), 1, "one site asked, so one quad, and a second frame does not twin it");
        let owner = app.world().get::<ChildOf>(quads[0].0).expect("the flame hangs on its site").parent();
        assert_eq!(owner, smoking, "the quad is the smoking site's flame's child");
        assert_ne!(owner, plain);
    }

    #[test]
    fn the_quads_tag_carries_the_sites_height_phase_and_the_density() {
        let mut app = app();
        app.world_mut().spawn((site(0.8, 2.0), FlameSmoke { density: 0.4 }, Transform::default()));
        app.update();
        app.update();
        let (_, tag) = smoke_quads(&mut app)[0];
        let (phase, height, share) = unpack_flame_tag(tag, 4.0);
        assert!((phase - 2.0).abs() < 0.03, "phase {phase}");
        assert!((height - 0.8).abs() < 1e-3, "height {height}");
        assert!((share - 0.4 / MAX_SMOKE_DENSITY).abs() < 0.005, "the density's share {share}");
    }

    #[test]
    fn a_changed_density_rewrites_the_tag_and_a_removed_component_takes_the_quad_away_and_can_return() {
        let mut app = app();
        let id =
            app.world_mut().spawn((site(0.5, 0.0), FlameSmoke { density: 0.2 }, Transform::default())).id();
        app.update();
        app.update();
        let before = smoke_quads(&mut app)[0].1;
        app.world_mut().get_mut::<FlameSmoke>(id).unwrap().density = 0.9;
        app.update();
        let after = smoke_quads(&mut app)[0].1;
        assert_ne!(before, after, "the density is in the tag");
        assert!((unpack_flame_tag(after, 4.0).2 - 0.9 / MAX_SMOKE_DENSITY).abs() < 0.005);

        app.world_mut().entity_mut(id).remove::<FlameSmoke>();
        app.update();
        app.update();
        assert!(smoke_quads(&mut app).is_empty(), "no component, no quad");

        app.world_mut().entity_mut(id).insert(FlameSmoke::default());
        app.update();
        app.update();
        assert_eq!(smoke_quads(&mut app).len(), 1, "added again, dressed again");
    }

    #[test]
    fn a_density_outside_its_range_is_reported_and_clamped_into_the_tag() {
        assert!(FlameSmoke { density: 0.6 }.problems().is_empty());
        assert_eq!(FlameSmoke { density: -0.1 }.problems().len(), 1);
        assert_eq!(FlameSmoke { density: MAX_SMOKE_DENSITY + 0.5 }.problems().len(), 1);
        assert_eq!(FlameSmoke { density: f32::NAN }.problems().len(), 1);
        assert_eq!(FlameSmoke { density: 9.0 }.share(), 1.0);
        assert_eq!(FlameSmoke { density: f32::NAN }.share(), 0.0);
    }

    /// A fire smokes in its own colour, and a scene that sets none smokes in the shipped one.
    #[test]
    fn a_fire_smokes_in_its_own_colour_and_follows_it_when_it_changes() {
        let mut app = app();
        let green = Color::from(LinearRgba::rgb(0.2, 1.0, 0.3));
        let tinted = app
            .world_mut()
            .spawn((FlameSite { color: Some(green), ..site(0.5, 0.0) }, FlameSmoke::default()))
            .id();
        let orange = app.world_mut().spawn((site(0.5, 1.0), FlameSmoke::default())).id();
        app.update();
        app.update();
        let stops = |m: &SmokeMaterial| [[m.warm.x, m.warm.y, m.warm.z], [m.cool.x, m.cool.y, m.cool.z]];
        assert_eq!(
            stops(&smoke_of(&app, orange)),
            [SPARK_ORANGE, SPARK_DULL_RED],
            "the scene's smoke is lit by the shipped fire"
        );
        for stop in stops(&smoke_of(&app, tinted)) {
            assert!(
                stop[1] > stop[0] && stop[1] > stop[2],
                "a green fire's smoke is green at both ends: {stop:?}"
            );
        }
        // A colour the host changes later reaches the smoke too.
        app.world_mut().get_mut::<FlameSite>(tinted).expect("the site").color =
            Some(Color::from(LinearRgba::rgb(0.1, 0.3, 1.0)));
        app.update();
        let [warm, _] = stops(&smoke_of(&app, tinted));
        assert!(warm[2] > warm[1] && warm[1] > warm[0], "now blue: {warm:?}");
    }

    /// The smoke joins no sorting: it only adds the light the fire puts into it.
    #[test]
    fn the_smoke_is_additive_so_it_joins_no_sorting() {
        let material = SmokeMaterial::new([1.0, 0.55, 0.18], 1.0, 4.0, false);
        assert!(matches!(material.alpha_mode(), AlphaMode::Add));
    }

    /// Points on the smoke quad, a 5 x 5 grid of its corners and interior, where `src/smoke.wesl`'s vertex stage puts them: the same
    /// constants, the same extents (the quad widens downwind by the lean at the top of the column), for a camera at `eye` whose right
    /// axis is `camera_right`. `origin` is the flame's foot, `size` the height it is drawn at, `wind` the instance scale's `y` and `z`
    /// less one.
    fn drawn_points(origin: Vec3, size: f32, wind: Vec2, eye: Vec3, camera_right: Vec3) -> Vec<Vec3> {
        const SOURCE_HEIGHT: f32 = 0.35;
        const HALF_WIDTH: f32 = 0.7;
        const RISE_MAX: f32 = 2.6;
        const MARGIN: f32 = 0.35;
        const LEAN_TOP: f32 = 3.9;
        let right = Vec3::new(camera_right.x, 0.0, camera_right.z).normalize();
        let centre = origin + Vec3::Y * (size * SOURCE_HEIGHT);
        let to_eye = eye - centre;
        let sin_e = (to_eye.y / to_eye.length().max(1e-4)).clamp(0.0, 1.0);
        let cos_e = (1.0 - sin_e * sin_e).max(0.0).sqrt();
        let reach = LEAN_TOP * wind.dot(Vec2::new(right.x, right.z));
        let (x_low, x_high) = (-HALF_WIDTH + reach.min(0.0), HALF_WIDTH + reach.max(0.0));
        let (v_low, v_high) = (-MARGIN, RISE_MAX * cos_e + MARGIN);
        let screen_up = to_eye.normalize().cross(right).normalize();
        let mut points = Vec::new();
        for i in 0..5 {
            for j in 0..5 {
                let (u, v) = (i as f32 / 4.0, j as f32 / 4.0);
                let across = x_low + (x_high - x_low) * u;
                let climb = v_low + (v_high - v_low) * v;
                points.push(origin + right * (across * size) + screen_up * (climb * size));
            }
        }
        points
    }

    #[test]
    fn a_smoke_quad_any_part_of_which_is_on_screen_is_never_culled() {
        // The quad the vertex stage draws (`drawn_points`), the box and the scale this crate gives it, and Bevy's own frustum
        // test: a fire whose smoke is culled while any of its quad is inside the frame loses its plume at the screen's edge.
        crate::flame::culling_tests::assert_a_quad_on_screen_is_never_culled(
            ember_cull_extents,
            ember_reach,
            drawn_points,
        );
    }

    /// The smoke quad's box as the frustum test sees it, with the scale it inherits from its flame: the half-extents in the
    /// quad's own axes, the flame's scale, and the box the test builds from the two.
    fn world_box(app: &mut App) -> Option<(Vec3, Vec3)> {
        let (flame, bound) =
            app.world_mut().query_filtered::<(&ChildOf, &Aabb), With<Smoke>>().iter(app.world()).next()?;
        let scale = app.world().get::<Transform>(flame.parent())?.scale;
        Some((scale, Vec3::from(bound.half_extents) * scale))
    }

    #[test]
    fn a_smoke_quads_box_keeps_its_size_through_the_catch_and_the_lean_on_every_frame() {
        // The quad inherits the flame's scale, which is the shader's data (its catch and its lean), and the frustum test
        // multiplies the box by it. The box must have been divided by it first, in the same frame the scale was written, or a
        // gusting fire's smoke is culled on screen for the frame the box lags.
        let mut app = app();
        app.insert_resource(crate::FlameWind { velocity: Vec2::new(3.0, -1.5) });
        let height = 0.9;
        app.world_mut().spawn((
            FlameSite { kindle: crate::KINDLE_SECONDS, ..site(height, 0.0) },
            FlameSmoke::default(),
            Transform::default(),
        ));
        let (mut checked, mut seen_small) = (0, false);
        for frame in 0..(crate::KINDLE_SECONDS * 60.0) as usize + 6 {
            app.update();
            let Some((scale, world)) = world_box(&mut app) else { continue };
            checked += 1;
            // The shader clamps the catch to 1, so the drawn size does too; the box's `x` is divided by the clamped catch
            // and multiplied by the real scale, and may exceed the cube by exactly the overshoot, never fall short of it.
            let size = height * scale.x.min(1.0).powf(2.0 / 3.0);
            let want = Vec3::splat(ember_reach([scale.y - 1.0, scale.z - 1.0]) * size);
            let slack = 1e-4 * (1.0 + want.max_element());
            assert!(
                (world.y - want.y).abs() < slack
                    && (world.z - want.z).abs() < slack
                    && world.x >= want.x - slack
                    && world.x <= want.x * scale.x.max(1.0) + slack,
                "frame {frame}: scale {scale}, the box measures {world} and the quad wants {want}"
            );
            seen_small |= scale.x < 0.3 && (scale.y - 1.0).abs() > 0.1;
        }
        assert!(checked > 30, "only {checked} frames had a smoke quad");
        assert!(
            seen_small,
            "the run never had a small, leaning flame, so it did not test the catch and the lean together"
        );
    }

    #[test]
    fn a_smoke_quad_carries_a_box_of_its_own_and_is_not_left_to_the_units_quad() {
        let mut app = app();
        app.world_mut().spawn((site(0.5, 0.0), FlameSmoke::default(), Transform::default()));
        app.update();
        app.update();
        let quad = app.world_mut().query_filtered::<Entity, With<Smoke>>().single(app.world()).unwrap();
        let entity = app.world().entity(quad);
        assert!(entity.contains::<Aabb>(), "a smoke quad has a culling box");
        assert!(entity.contains::<NoAutoAabb>(), "which Bevy is told not to recompute");
        assert!(
            !entity.contains::<bevy::camera::visibility::NoFrustumCulling>(),
            "and which the frustum test uses: an off-screen fire's smoke is not drawn"
        );
    }

    /// A smoking site whose fire is a bare entity the tests put out by hand: the flicker plugin that advances a `Snuff` is not in this
    /// app. Returns the fire and the site, a few frames after they were spawned, with the flame's catch long since settled.
    fn smoking_site_with_fire(app: &mut App, height: f32) -> (Entity, Entity) {
        let fire = app.world_mut().spawn_empty().id();
        let site_entity = app
            .world_mut()
            .spawn((
                FlameSite { fire: Some(fire), ..site(height, 0.0) },
                FlameSmoke::default(),
                Transform::default(),
            ))
            .id();
        for _ in 0..4 {
            app.update();
        }
        (fire, site_entity)
    }

    /// One frame of a fire going out: the fire's `Snuff` advanced by the frame's time, as the flicker plugin does, then the frame.
    fn burn_down(app: &mut App, fire: Entity) {
        let step = app.world().resource::<Time>().delta_secs().max(1.0 / 60.0);
        if let Some(mut snuff) = app.world_mut().get_mut::<Snuff>(fire) {
            snuff.elapsed = (snuff.elapsed + step).min(SNUFF_SECONDS);
        }
        app.update();
    }

    fn the_quad(app: &mut App) -> Entity {
        app.world_mut().query_filtered::<Entity, With<Smoke>>().single(app.world()).unwrap()
    }

    /// The instance scale the quad is drawn at: its flame's, times its own (this app has no transform propagation, and the shader
    /// reads exactly this product).
    fn drawn_scale(app: &mut App) -> Vec3 {
        let quad = the_quad(app);
        let flame = app.world().get::<ChildOf>(quad).unwrap().parent();
        app.world().get::<Transform>(flame).unwrap().scale * app.world().get::<Transform>(quad).unwrap().scale
    }

    fn flames_scale(app: &mut App) -> Vec3 {
        let quad = the_quad(app);
        let flame = app.world().get::<ChildOf>(quad).unwrap().parent();
        app.world().get::<Transform>(flame).unwrap().scale
    }

    fn is_trail(app: &mut App) -> bool {
        let quad = the_quad(app);
        let entity = app.world().entity(quad);
        let (flagged, begun) =
            (entity.get::<MeshTag>().unwrap().value & TAIL_BIT != 0, entity.contains::<SmokeTail>());
        assert_eq!(flagged, begun, "the tag says trail exactly while the quad has a trail clock");
        begun
    }

    #[test]
    fn a_steady_quads_tag_is_never_read_as_a_trail_whatever_its_height() {
        // The trail bit is the lowest of the tag's sixteen height bits, which half of all heights have set: a steady quad's tag must clear
        // it, or those fires would be drawn as trails (the scale's `x` read as a clock, at once).
        for step in 0..2000 {
            let site = FlameSite { phase: step as f32 * 0.37, ..site(0.001 + step as f32 * 0.001, 0.0) };
            let tag = steady_tag(&site, 0.8, 4.0);
            assert_eq!(tag & TAIL_BIT, 0, "height {} packs {tag:#x}", site.height);
            let (_, height, _) = unpack_flame_tag(tag, 4.0);
            assert!(
                (height - site.height).abs() <= 2.0 * 4.0 / 65535.0 + 1e-6,
                "height {} reads back as {height}",
                site.height
            );
        }
    }

    #[test]
    fn a_fire_put_out_leaves_a_trail_that_outlives_its_flame_and_ends_with_its_clock() {
        let mut app = app();
        let (fire, _) = smoking_site_with_fire(&mut app, 0.8);
        assert!(!is_trail(&mut app), "a burning fire's smoke follows its catch");
        assert_eq!(drawn_scale(&mut app).x, 1.0);

        app.world_mut().entity_mut(fire).insert(Snuff::default());
        burn_down(&mut app, fire);
        assert!(is_trail(&mut app), "a fire put out begins a trail on the frame its Snuff is seen");

        // Three seconds on: the flame is long gone (its catch is the floor) and the trail has not shrunk with it.
        for _ in 0..179 {
            burn_down(&mut app, fire);
        }
        assert!(flames_scale(&mut app).x < 0.0011, "the flame is out: {}", flames_scale(&mut app));
        assert!(is_trail(&mut app), "and the smoke goes on");
        let carried = drawn_scale(&mut app).x;
        assert!(
            ((1.0 / carried - 1.0) - 3.0).abs() < 0.1,
            "the scale carries the seconds since the douse (1 / (1 + t)): {carried} for 3 s"
        );

        // Past the trail's length it ends, and the quad follows the (zero) catch again, from the same tag it had.
        for _ in 0..140 {
            burn_down(&mut app, fire);
        }
        assert!(!is_trail(&mut app), "the trail is over after {SMOKE_TAIL_SECONDS} s");
        let quad = the_quad(&mut app);
        assert_eq!(app.world().get::<Transform>(quad).unwrap().scale, Vec3::ONE);
        let (_, tag) = smoke_quads(&mut app)[0];
        let (phase, height, share) = unpack_flame_tag(tag, 4.0);
        assert!(
            phase.abs() < 0.03 && (height - 0.8).abs() < 1e-3 && share > 0.79,
            "the tag is the steady one again"
        );
    }

    #[test]
    fn only_a_fire_seen_going_out_leaves_a_trail() {
        let mut app = app();
        // A fire loaded as already out: its Snuff is at its end when it is first seen.
        let out = app.world_mut().spawn(Snuff { elapsed: SNUFF_SECONDS }).id();
        app.world_mut().spawn((
            FlameSite { fire: Some(out), ..site(0.5, 0.0) },
            FlameSmoke::default(),
            Transform::default(),
        ));
        for _ in 0..4 {
            app.update();
        }
        assert!(!is_trail(&mut app), "a fire that was already out when the scene loaded begins no trail");

        // A smoking site that names no fire, with some other fire put out in the same world.
        let mut app = self::app();
        app.world_mut().spawn((site(0.5, 0.0), FlameSmoke::default(), Transform::default()));
        let other = app.world_mut().spawn_empty().id();
        for _ in 0..4 {
            app.update();
        }
        app.world_mut().entity_mut(other).insert(Snuff::default());
        for _ in 0..4 {
            burn_down(&mut app, other);
        }
        assert!(!is_trail(&mut app), "a site that names no fire has no douse to follow");
    }

    #[test]
    fn re_lighting_a_fire_ends_its_trail_at_once() {
        let mut app = app();
        let (fire, _) = smoking_site_with_fire(&mut app, 0.5);
        app.world_mut().entity_mut(fire).insert(Snuff::default());
        for _ in 0..90 {
            burn_down(&mut app, fire);
        }
        assert!(is_trail(&mut app));

        app.world_mut().entity_mut(fire).remove::<Snuff>();
        app.update();
        assert!(!is_trail(&mut app), "the fire is lit again: its plume follows the catch");
        let quad = the_quad(&mut app);
        assert_eq!(
            app.world().get::<Transform>(quad).unwrap().scale,
            Vec3::ONE,
            "and the quad is no longer counter-scaled"
        );
        assert!(
            drawn_scale(&mut app).x > 0.99,
            "the settled flame is whole again, so is its smoke: {}",
            drawn_scale(&mut app)
        );
    }

    #[test]
    fn a_paused_worlds_trail_holds_still() {
        let mut app = app();
        let (fire, _) = smoking_site_with_fire(&mut app, 0.5);
        app.world_mut().entity_mut(fire).insert(Snuff::default());
        for _ in 0..30 {
            burn_down(&mut app, fire);
        }
        app.world_mut().resource_mut::<Time<Virtual>>().pause();
        app.update();
        let held = drawn_scale(&mut app);
        for _ in 0..30 {
            app.update();
        }
        assert_eq!(drawn_scale(&mut app), held, "virtual time stopped, so did the trail's clock");
        app.world_mut().resource_mut::<Time<Virtual>>().unpause();
        for _ in 0..3 {
            app.update();
        }
        assert!(drawn_scale(&mut app).x < held.x, "and it runs on when time does");
    }

    #[test]
    fn a_trails_box_holds_the_whole_column_though_its_flame_has_shrunk_to_nothing() {
        // The flame's catch is a point by the end of its snuff, but the trail is drawn at the fire's full height, so a box taken from the
        // flame's scale would cull a trail that is still on screen. The box must be the full ball, divided by the scale the quad is
        // drawn at, on every frame of the trail (and in a wind, which widens it downwind).
        let mut app = app();
        app.insert_resource(crate::FlameWind { velocity: Vec2::new(3.0, -1.5) });
        let height = 0.9;
        let (fire, _) = smoking_site_with_fire(&mut app, height);
        app.world_mut().entity_mut(fire).insert(Snuff::default());
        let mut checked = 0;
        for frame in 0..(SMOKE_TAIL_SECONDS * 60.0) as usize - 6 {
            burn_down(&mut app, fire);
            let scale = drawn_scale(&mut app);
            let quad = the_quad(&mut app);
            let half = Vec3::from(app.world().get::<Aabb>(quad).unwrap().half_extents);
            let world = half * scale;
            let want = Vec3::splat(ember_reach([scale.y - 1.0, scale.z - 1.0]) * height);
            let slack = 1e-3 * (1.0 + want.max_element());
            assert!(
                (world - want).abs().max_element() < slack,
                "frame {frame}: scale {scale}, the box measures {world} and the trail wants {want}"
            );
            checked += 1;
        }
        assert!(checked > 250);
        assert!(flames_scale(&mut app).x < 0.0011, "the flame the box must not be taken from is a point");
    }
}