voxel-framework 0.13.0

A reusable voxel engine framework built on Bevy
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
//! Point lights recorded by voxel position, with a nearest-N budget.

use std::collections::{HashMap, HashSet};

use bevy::prelude::*;

use super::LightingSystems;
use crate::chunk::{CHUNK_SIZE, ChunkCoord, VOXEL_SIZE};
use crate::world::{ChunkManager, ViewerPosition};

// ─── Records ──────────────────────────────────────────────────────────────────

/// One light recorded in [`PlacedLights`].
///
/// The default mirrors Bevy's `PointLight::default()`, centered in its voxel.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PlacedLight {
    /// Light color. **Default: `Color::WHITE`.**
    pub color: Color,
    /// Luminous power in lumens. **Default: `1_000_000.0`.**
    pub intensity: f32,
    /// Distance at which the light stops, in world units. **Default: `20.0`.**
    pub range: f32,
    /// Radius of the light source, for specular highlights. **Default: `0.0`.**
    pub radius: f32,
    /// Whether the light casts shadows. **Default: `false`.**
    pub shadows_enabled: bool,
    /// Offset of the light from the center of its voxel, in world units. Use
    /// it to move the light out of a solid voxel, toward the face it hangs
    /// on. **Default: `Vec3::ZERO`.**
    pub offset: Vec3,
}

impl Default for PlacedLight {
    fn default() -> Self {
        Self {
            color: Color::WHITE,
            intensity: 1_000_000.0,
            range: 20.0,
            radius: 0.0,
            shadows_enabled: false,
            offset: Vec3::ZERO,
        }
    }
}

impl PlacedLight {
    /// World-space position of this light when recorded at `voxel`: the
    /// center of the voxel plus [`PlacedLight::offset`].
    ///
    /// ```
    /// use bevy::prelude::*;
    /// use voxel_framework::lighting::PlacedLight;
    ///
    /// let light = PlacedLight {
    ///     offset: Vec3::new(0.0, 0.25, 0.0),
    ///     ..default()
    /// };
    /// assert_eq!(
    ///     light.world_position(IVec3::new(2, -1, 0)),
    ///     Vec3::new(2.5, -0.25, 0.5)
    /// );
    /// ```
    pub fn world_position(&self, voxel: IVec3) -> Vec3 {
        (voxel.as_vec3() + Vec3::splat(0.5)) * VOXEL_SIZE + self.offset
    }

    /// Copies the light values into `light`, leaving its other fields as they
    /// are.
    fn apply(&self, light: &mut PointLight) {
        light.color = self.color;
        light.intensity = self.intensity;
        light.range = self.range;
        light.radius = self.radius;
        light.shadows_enabled = self.shadows_enabled;
    }
}

/// Voxel position that contains the world-space point `world_pos`.
///
/// ```
/// use bevy::prelude::*;
/// use voxel_framework::lighting::placed_light_voxel;
///
/// assert_eq!(placed_light_voxel(Vec3::new(3.7, 0.0, -0.2)), IVec3::new(3, 0, -1));
/// ```
pub fn placed_light_voxel(world_pos: Vec3) -> IVec3 {
    (world_pos / VOXEL_SIZE).floor().as_ivec3()
}

/// Chunk that contains the voxel position `voxel`.
///
/// ```
/// use bevy::prelude::*;
/// use voxel_framework::lighting::placed_light_chunk;
///
/// assert_eq!(placed_light_chunk(IVec3::new(17, 0, -1)), IVec3::new(1, 0, -1));
/// ```
pub fn placed_light_chunk(voxel: IVec3) -> ChunkCoord {
    voxel.div_euclid(IVec3::splat(CHUNK_SIZE as i32))
}

/// The lights placed in the world, keyed by voxel position.
///
/// This resource is the source of truth. A record is plain data: adding one
/// spawns nothing by itself. [`PlacedLightsPlugin`] spawns a point light only
/// for the records that are *active* (see [`PlacedLightBudget`]), and despawns
/// it when the record stops being active or is removed.
///
/// # When a chunk unloads
///
/// A record is not tied to a chunk entity, so it survives its chunk being
/// unloaded. While the chunk is not loaded the record is inactive and has no
/// light entity; when the chunk loads again the light comes back with the same
/// values. Records are removed only by [`PlacedLights::remove`] or
/// [`PlacedLights::clear`].
///
/// The framework does not link a record to the voxel at its position and does
/// not save the records. The game removes the record when the voxel that
/// holds the light is broken, and stores and restores the records with its
/// own save data, using [`PlacedLights::iter`] and [`PlacedLights::insert`].
///
/// ```
/// use bevy::prelude::*;
/// use voxel_framework::lighting::{PlacedLight, PlacedLights, placed_light_voxel};
///
/// let mut lights = PlacedLights::default();
/// let voxel = placed_light_voxel(Vec3::new(4.2, 10.9, -2.5));
/// assert_eq!(voxel, IVec3::new(4, 10, -3));
///
/// assert!(lights.insert(voxel, PlacedLight::default()).is_none());
/// assert!(lights.contains(voxel));
/// assert_eq!(lights.len(), 1);
///
/// lights.get_mut(voxel).unwrap().range = 12.0;
/// assert_eq!(lights.remove(voxel).unwrap().range, 12.0);
/// assert!(lights.is_empty());
/// ```
#[derive(Resource, Debug, Clone, Default)]
pub struct PlacedLights {
    lights: HashMap<IVec3, PlacedLight>,
}

impl PlacedLights {
    /// Records `light` at `voxel`, replacing and returning the previous record
    /// at that position, if any.
    pub fn insert(&mut self, voxel: IVec3, light: PlacedLight) -> Option<PlacedLight> {
        self.lights.insert(voxel, light)
    }

    /// Removes and returns the record at `voxel`.
    pub fn remove(&mut self, voxel: IVec3) -> Option<PlacedLight> {
        self.lights.remove(&voxel)
    }

    /// The record at `voxel`.
    pub fn get(&self, voxel: IVec3) -> Option<&PlacedLight> {
        self.lights.get(&voxel)
    }

    /// Mutable access to the record at `voxel`.
    pub fn get_mut(&mut self, voxel: IVec3) -> Option<&mut PlacedLight> {
        self.lights.get_mut(&voxel)
    }

    /// Whether a light is recorded at `voxel`.
    pub fn contains(&self, voxel: IVec3) -> bool {
        self.lights.contains_key(&voxel)
    }

    /// Number of recorded lights, active or not.
    pub fn len(&self) -> usize {
        self.lights.len()
    }

    /// Whether no light is recorded.
    pub fn is_empty(&self) -> bool {
        self.lights.is_empty()
    }

    /// Every record with its voxel position, in no particular order.
    pub fn iter(&self) -> impl Iterator<Item = (IVec3, &PlacedLight)> + '_ {
        self.lights.iter().map(|(voxel, light)| (*voxel, light))
    }

    /// Removes every record.
    pub fn clear(&mut self) {
        self.lights.clear();
    }
}

// ─── Budget ───────────────────────────────────────────────────────────────────

/// How many placed lights may be active at once, and how far away.
///
/// Among the records whose chunk is loaded and whose light is within
/// [`max_distance`](Self::max_distance) of the
/// [`ViewerPosition`], the [`max_active`](Self::max_active) nearest ones are
/// active. Only active records have a point light entity.
#[derive(Resource, Debug, Clone, Copy, PartialEq)]
pub struct PlacedLightBudget {
    /// Maximum number of active lights. `0` disables every placed light.
    ///
    /// **Default: `16`.**
    pub max_active: usize,
    /// Maximum distance from the viewer to an active light, in world units.
    /// A negative value disables every placed light; `NaN` counts as no
    /// limit.
    ///
    /// **Default: `f32::INFINITY`** (no limit).
    pub max_distance: f32,
}

impl Default for PlacedLightBudget {
    fn default() -> Self {
        Self {
            max_active: 16,
            max_distance: f32::INFINITY,
        }
    }
}

/// Picks the lights that should be active: the `budget.max_active` candidates
/// nearest to `viewer` that are within `budget.max_distance`, nearest first.
///
/// Each candidate is a voxel position and the world-space position of its
/// light. Candidates at the same distance are ordered by voxel position, so
/// the result does not depend on the order of `candidates`. A candidate whose
/// position is not finite is never selected.
///
/// ```
/// use bevy::prelude::*;
/// use voxel_framework::lighting::{PlacedLightBudget, select_active_lights};
///
/// let candidates = [
///     (IVec3::new(9, 0, 0), Vec3::new(9.5, 0.5, 0.5)),
///     (IVec3::new(1, 0, 0), Vec3::new(1.5, 0.5, 0.5)),
///     (IVec3::new(4, 0, 0), Vec3::new(4.5, 0.5, 0.5)),
/// ];
/// let budget = PlacedLightBudget { max_active: 2, max_distance: 100.0 };
/// let active = select_active_lights(candidates, Vec3::ZERO, &budget);
/// assert_eq!(active, vec![IVec3::new(1, 0, 0), IVec3::new(4, 0, 0)]);
/// ```
pub fn select_active_lights(
    candidates: impl IntoIterator<Item = (IVec3, Vec3)>,
    viewer: Vec3,
    budget: &PlacedLightBudget,
) -> Vec<IVec3> {
    if budget.max_active == 0 || budget.max_distance < 0.0 {
        return Vec::new();
    }
    let max_distance_squared = if budget.max_distance.is_nan() {
        f32::INFINITY
    } else {
        budget.max_distance * budget.max_distance
    };

    let mut ranked: Vec<(f32, IVec3)> = candidates
        .into_iter()
        .filter_map(|(voxel, position)| {
            let distance_squared = position.distance_squared(viewer);
            // A NaN distance fails the comparison and is dropped.
            (distance_squared <= max_distance_squared).then_some((distance_squared, voxel))
        })
        .collect();
    ranked.sort_by(|a, b| {
        a.0.total_cmp(&b.0)
            .then_with(|| a.1.to_array().cmp(&b.1.to_array()))
    });
    ranked.truncate(budget.max_active);
    ranked.into_iter().map(|(_, voxel)| voxel).collect()
}

// ─── Entities ─────────────────────────────────────────────────────────────────

/// Marker on a point light entity spawned by [`PlacedLightsPlugin`] for an
/// active record of [`PlacedLights`].
///
/// These entities are owned by the plugin: it despawns them when their record
/// stops being active. Change the light through its record, not through the
/// entity.
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PlacedLightSource {
    /// Voxel position of the record this entity shows.
    pub voxel: IVec3,
}

fn sync_placed_lights(
    mut commands: Commands,
    lights: Res<PlacedLights>,
    budget: Res<PlacedLightBudget>,
    viewer: Option<Res<ViewerPosition>>,
    manager: Option<Res<ChunkManager>>,
    mut spawned: Query<(Entity, &PlacedLightSource, &mut PointLight, &mut Transform)>,
) {
    if lights.is_empty() && spawned.is_empty() {
        return;
    }

    let viewer = viewer.map_or(Vec3::ZERO, |viewer| viewer.position);
    let candidates = lights.iter().filter_map(|(voxel, light)| {
        let loaded = match &manager {
            Some(manager) => manager.is_loaded(placed_light_chunk(voxel)),
            None => true,
        };
        loaded.then(|| (voxel, light.world_position(voxel)))
    });
    let active: HashSet<IVec3> = select_active_lights(candidates, viewer, &budget)
        .into_iter()
        .collect();

    let records_changed = lights.is_changed();
    let mut shown: HashSet<IVec3> = HashSet::new();
    for (entity, source, mut point, mut transform) in &mut spawned {
        let record = lights
            .get(source.voxel)
            .filter(|_| active.contains(&source.voxel));
        match record {
            // `insert` is false for a second entity of the same record.
            Some(light) if shown.insert(source.voxel) => {
                if records_changed {
                    light.apply(&mut point);
                    transform.translation = light.world_position(source.voxel);
                }
            }
            _ => commands.entity(entity).try_despawn(),
        }
    }

    for voxel in active {
        if shown.contains(&voxel) {
            continue;
        }
        if let Some(light) = lights.get(voxel) {
            let mut point = PointLight::default();
            light.apply(&mut point);
            commands.spawn((
                PlacedLightSource { voxel },
                point,
                Transform::from_translation(light.world_position(voxel)),
            ));
        }
    }
}

// ─── Plugin ───────────────────────────────────────────────────────────────────

/// Default Implementation plugin that shows the lights recorded in
/// [`PlacedLights`] as point lights, within [`PlacedLightBudget`].
///
/// It is explicit: no bundle adds it, and it spawns nothing until the game
/// records a light. It initializes [`PlacedLights`] and [`PlacedLightBudget`]
/// without replacing values the game inserted earlier. Its system runs every
/// frame in `Update`, in [`LightingSystems::Placed`].
///
/// A record is active when all of these hold:
///
/// 1. the chunk that contains its voxel is loaded according to
///    [`ChunkManager`];
/// 2. its light is within [`PlacedLightBudget::max_distance`] of the
///    [`ViewerPosition`];
/// 3. it is among the [`PlacedLightBudget::max_active`] nearest such lights.
///
/// Each active record has exactly one entity with a `PointLight` and a
/// [`PlacedLightSource`]. When a chunk unloads, the lights in it are despawned
/// and their records are kept; they come back when the chunk loads again.
///
/// Without a [`ChunkManager`] resource (no
/// [`WorldPlugin`](crate::world::WorldPlugin)) every chunk counts as loaded,
/// and without a [`ViewerPosition`] the viewer is at the origin.
///
/// ```no_run
/// use bevy::prelude::*;
/// use voxel_framework::lighting::{
///     PlacedLight, PlacedLightBudget, PlacedLights, PlacedLightsPlugin, placed_light_voxel,
/// };
///
/// // Called from the game's own placement logic.
/// fn place_light(lights: &mut PlacedLights, world_pos: Vec3) {
///     lights.insert(
///         placed_light_voxel(world_pos),
///         PlacedLight {
///             color: Color::srgb(1.0, 0.8, 0.5),
///             intensity: 60_000.0,
///             range: 12.0,
///             ..default()
///         },
///     );
/// }
///
/// App::new()
///     .add_plugins(DefaultPlugins)
///     .insert_resource(PlacedLightBudget {
///         max_active: 8,
///         max_distance: 96.0,
///     })
///     .add_plugins(PlacedLightsPlugin)
///     .run();
/// ```
pub struct PlacedLightsPlugin;

impl Plugin for PlacedLightsPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<PlacedLights>();
        app.init_resource::<PlacedLightBudget>();
        app.add_systems(Update, sync_placed_lights.in_set(LightingSystems::Placed));
    }
}

// ─── Tests ────────────────────────────────────────────────────────────────────

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

    fn budget(max_active: usize, max_distance: f32) -> PlacedLightBudget {
        PlacedLightBudget {
            max_active,
            max_distance,
        }
    }

    /// Candidates on the X axis, one per given voxel X coordinate.
    fn on_x_axis(xs: &[i32]) -> Vec<(IVec3, Vec3)> {
        xs.iter()
            .map(|&x| {
                let voxel = IVec3::new(x, 0, 0);
                (voxel, PlacedLight::default().world_position(voxel))
            })
            .collect()
    }

    fn app() -> App {
        let mut app = App::new();
        app.add_plugins(PlacedLightsPlugin);
        app
    }

    /// Voxel positions that currently have a light entity, sorted.
    fn shown(app: &mut App) -> Vec<IVec3> {
        let mut query = app.world_mut().query::<&PlacedLightSource>();
        let mut voxels: Vec<IVec3> = query.iter(app.world()).map(|s| s.voxel).collect();
        voxels.sort_by_key(|v| v.to_array());
        voxels
    }

    fn place(app: &mut App, voxel: IVec3, light: PlacedLight) {
        app.world_mut()
            .resource_mut::<PlacedLights>()
            .insert(voxel, light);
    }

    // ── Pure logic ──

    #[test]
    fn defaults_match_the_engine_point_light() {
        let light = PlacedLight::default();
        let engine = PointLight::default();
        assert_eq!(light.color, engine.color);
        assert_eq!(light.intensity, engine.intensity);
        assert_eq!(light.range, engine.range);
        assert_eq!(light.radius, engine.radius);
        assert_eq!(light.shadows_enabled, engine.shadows_enabled);
        assert_eq!(light.offset, Vec3::ZERO);

        let budget = PlacedLightBudget::default();
        assert_eq!(budget.max_active, 16);
        assert_eq!(budget.max_distance, f32::INFINITY);
    }

    #[test]
    fn voxel_and_chunk_helpers_handle_negative_positions() {
        assert_eq!(
            placed_light_voxel(Vec3::new(0.0, 15.99, 16.0)),
            IVec3::new(0, 15, 16)
        );
        assert_eq!(
            placed_light_voxel(Vec3::new(-0.01, -1.0, -16.5)),
            IVec3::new(-1, -1, -17)
        );
        assert_eq!(
            placed_light_chunk(IVec3::new(0, 15, 16)),
            IVec3::new(0, 0, 1)
        );
        assert_eq!(
            placed_light_chunk(IVec3::new(-1, -16, -17)),
            IVec3::new(-1, -1, -2)
        );
        // Same chunk as the framework computes for the voxel's center.
        for voxel in [IVec3::new(-1, 31, 5), IVec3::new(-33, 0, 16)] {
            let center = PlacedLight::default().world_position(voxel);
            assert_eq!(
                placed_light_chunk(voxel),
                crate::chunk::world_to_chunk_coord(center)
            );
        }
    }

    #[test]
    fn registry_inserts_replaces_and_removes() {
        let mut lights = PlacedLights::default();
        let voxel = IVec3::new(1, 2, 3);
        assert!(lights.is_empty());
        assert!(lights.insert(voxel, PlacedLight::default()).is_none());
        let replaced = lights.insert(
            voxel,
            PlacedLight {
                range: 5.0,
                ..default()
            },
        );
        assert_eq!(replaced, Some(PlacedLight::default()));
        assert_eq!(lights.len(), 1);
        assert_eq!(lights.get(voxel).unwrap().range, 5.0);
        assert_eq!(lights.iter().count(), 1);
        assert!(!lights.contains(IVec3::ZERO));
        assert!(lights.remove(IVec3::ZERO).is_none());
        assert!(lights.remove(voxel).is_some());
        lights.insert(voxel, PlacedLight::default());
        lights.clear();
        assert!(lights.is_empty());
    }

    #[test]
    fn selection_keeps_the_nearest_within_the_budget() {
        let candidates = on_x_axis(&[30, 2, -5, 12, 1]);
        let active = select_active_lights(candidates, Vec3::ZERO, &budget(3, f32::INFINITY));
        assert_eq!(
            active,
            vec![
                IVec3::new(1, 0, 0),
                IVec3::new(2, 0, 0),
                IVec3::new(-5, 0, 0)
            ]
        );
    }

    #[test]
    fn selection_follows_the_viewer() {
        let candidates = on_x_axis(&[0, 10, 20, 30]);
        let active = select_active_lights(
            candidates,
            Vec3::new(29.0, 0.5, 0.5),
            &budget(2, f32::INFINITY),
        );
        assert_eq!(active, vec![IVec3::new(30, 0, 0), IVec3::new(20, 0, 0)]);
    }

    #[test]
    fn selection_drops_lights_beyond_the_distance() {
        let candidates = on_x_axis(&[1, 5, 50]);
        let active = select_active_lights(candidates, Vec3::new(0.0, 0.5, 0.5), &budget(10, 6.0));
        assert_eq!(active, vec![IVec3::new(1, 0, 0), IVec3::new(5, 0, 0)]);
    }

    #[test]
    fn selection_with_zero_budget_or_negative_distance_is_empty() {
        let candidates = on_x_axis(&[1, 2]);
        assert!(select_active_lights(candidates.clone(), Vec3::ZERO, &budget(0, 100.0)).is_empty());
        assert!(select_active_lights(candidates, Vec3::ZERO, &budget(4, -1.0)).is_empty());
    }

    #[test]
    fn selection_treats_nan_distance_as_no_limit_and_skips_bad_positions() {
        let mut candidates = on_x_axis(&[1, 1000]);
        candidates.push((IVec3::new(7, 7, 7), Vec3::splat(f32::NAN)));
        let active = select_active_lights(candidates, Vec3::ZERO, &budget(10, f32::NAN));
        assert_eq!(active, vec![IVec3::new(1, 0, 0), IVec3::new(1000, 0, 0)]);
    }

    #[test]
    fn selection_breaks_ties_by_voxel_position() {
        // Four lights at the same distance from the viewer.
        let voxels = [
            IVec3::new(3, 0, 0),
            IVec3::new(-3, 0, 0),
            IVec3::new(0, 3, 0),
            IVec3::new(0, -3, 0),
        ];
        let forward: Vec<(IVec3, Vec3)> = voxels.iter().map(|&v| (v, v.as_vec3())).collect();
        let mut backward = forward.clone();
        backward.reverse();

        let a = select_active_lights(forward, Vec3::ZERO, &budget(2, f32::INFINITY));
        let b = select_active_lights(backward, Vec3::ZERO, &budget(2, f32::INFINITY));
        assert_eq!(a, b);
        assert_eq!(a, vec![IVec3::new(-3, 0, 0), IVec3::new(0, -3, 0)]);
    }

    // ── System ──

    #[test]
    fn a_record_becomes_one_point_light_at_its_position() {
        let mut app = app();
        let voxel = IVec3::new(2, 3, -4);
        let light = PlacedLight {
            color: Color::srgb(1.0, 0.5, 0.0),
            intensity: 777.0,
            range: 9.0,
            radius: 0.25,
            shadows_enabled: true,
            offset: Vec3::new(0.0, 0.5, 0.0),
        };
        place(&mut app, voxel, light);
        app.update();
        app.update();

        let mut query = app
            .world_mut()
            .query::<(&PlacedLightSource, &PointLight, &Transform)>();
        let found: Vec<_> = query.iter(app.world()).collect();
        assert_eq!(found.len(), 1);
        let (source, point, transform) = found[0];
        assert_eq!(source.voxel, voxel);
        assert_eq!(point.color, light.color);
        assert_eq!(point.intensity, 777.0);
        assert_eq!(point.range, 9.0);
        assert_eq!(point.radius, 0.25);
        assert!(point.shadows_enabled);
        assert_eq!(transform.translation, Vec3::new(2.5, 4.0, -3.5));
    }

    #[test]
    fn no_records_means_no_entities() {
        let mut app = app();
        app.update();
        assert!(shown(&mut app).is_empty());
    }

    #[test]
    fn only_the_nearest_lights_within_the_budget_are_shown() {
        let mut app = app();
        app.insert_resource(budget(2, f32::INFINITY));
        app.insert_resource(ViewerPosition {
            position: Vec3::new(0.0, 0.5, 0.5),
        });
        for x in [1, 10, 20] {
            place(&mut app, IVec3::new(x, 0, 0), PlacedLight::default());
        }
        app.update();
        assert_eq!(
            shown(&mut app),
            vec![IVec3::new(1, 0, 0), IVec3::new(10, 0, 0)]
        );

        // The viewer moves: the far light replaces the near one.
        app.world_mut().resource_mut::<ViewerPosition>().position = Vec3::new(25.0, 0.5, 0.5);
        app.update();
        assert_eq!(
            shown(&mut app),
            vec![IVec3::new(10, 0, 0), IVec3::new(20, 0, 0)]
        );
    }

    #[test]
    fn a_light_in_an_unloaded_chunk_is_despawned_and_returns_on_reload() {
        let mut app = app();
        let chunk = IVec3::new(1, 0, 0);
        let chunk_entity = app.world_mut().spawn_empty().id();
        let mut manager = ChunkManager::default();
        manager.register(chunk, chunk_entity);
        app.insert_resource(manager);

        let voxel = IVec3::new(20, 3, 3); // inside chunk (1, 0, 0)
        let elsewhere = IVec3::new(-5, 3, 3); // chunk (-1, 0, 0), never loaded
        place(&mut app, voxel, PlacedLight::default());
        place(&mut app, elsewhere, PlacedLight::default());
        app.update();
        assert_eq!(shown(&mut app), vec![voxel]);

        // Unload: the entity goes, the record stays.
        app.world_mut()
            .resource_mut::<ChunkManager>()
            .unregister(chunk);
        app.update();
        assert!(shown(&mut app).is_empty());
        assert!(app.world().resource::<PlacedLights>().contains(voxel));

        // Reload: the light comes back.
        app.world_mut()
            .resource_mut::<ChunkManager>()
            .register(chunk, chunk_entity);
        app.update();
        assert_eq!(shown(&mut app), vec![voxel]);
    }

    #[test]
    fn removing_a_record_despawns_its_light() {
        let mut app = app();
        let voxel = IVec3::new(0, 0, 0);
        place(&mut app, voxel, PlacedLight::default());
        place(&mut app, IVec3::new(1, 0, 0), PlacedLight::default());
        app.update();
        assert_eq!(shown(&mut app).len(), 2);

        app.world_mut().resource_mut::<PlacedLights>().remove(voxel);
        app.update();
        assert_eq!(shown(&mut app), vec![IVec3::new(1, 0, 0)]);

        app.world_mut().resource_mut::<PlacedLights>().clear();
        app.update();
        assert!(shown(&mut app).is_empty());
    }

    #[test]
    fn changing_a_record_updates_the_same_entity() {
        let mut app = app();
        let voxel = IVec3::new(4, 4, 4);
        place(&mut app, voxel, PlacedLight::default());
        app.update();
        let mut query = app
            .world_mut()
            .query_filtered::<Entity, With<PlacedLightSource>>();
        let entity = query.single(app.world()).expect("one light");

        {
            let mut lights = app.world_mut().resource_mut::<PlacedLights>();
            let record = lights.get_mut(voxel).unwrap();
            record.intensity = 3.0;
            record.offset = Vec3::new(0.25, 0.0, 0.0);
        }
        app.update();

        assert_eq!(query.single(app.world()).expect("one light"), entity);
        assert_eq!(
            app.world().get::<PointLight>(entity).unwrap().intensity,
            3.0
        );
        assert_eq!(
            app.world().get::<Transform>(entity).unwrap().translation,
            Vec3::new(4.75, 4.5, 4.5)
        );
    }

    #[test]
    fn a_budget_change_applies_on_the_next_frame() {
        let mut app = app();
        for x in [1, 2, 3] {
            place(&mut app, IVec3::new(x, 0, 0), PlacedLight::default());
        }
        app.update();
        assert_eq!(shown(&mut app).len(), 3);

        app.world_mut()
            .resource_mut::<PlacedLightBudget>()
            .max_active = 1;
        app.update();
        assert_eq!(shown(&mut app), vec![IVec3::new(1, 0, 0)]);

        app.world_mut()
            .resource_mut::<PlacedLightBudget>()
            .max_active = 0;
        app.update();
        assert!(shown(&mut app).is_empty());
    }
}