voxel-framework 0.12.3

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
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
//! Mesh generation system that responds to chunk modification events.
//!
//! [`chunk_mesh_system`] listens for [`ChunkModified`] messages, retrieves
//! the chunk entity from [`ChunkManager`], runs the greedy mesher at the
//! appropriate LOD level, and either updates an existing [`Mesh`] asset handle
//! or inserts the full set of render components (`Mesh3d`, `MeshMaterial3d`,
//! `Transform`, `Visibility`, AABB, [`ChunkLod`]).
//!
//! [`lod_update_system`] runs every frame, recomputes the LOD level for every
//! rendered chunk based on distance to the viewer, and emits [`ChunkModified`]
//! when the level changes so that `chunk_mesh_system` regenerates the mesh.

use bevy::camera::primitives::Aabb;
use bevy::prelude::*;

use crate::chunk::{CHUNK_SIZE, Chunk, ChunkCoord, ChunkCoordComp, ChunkLod};
use crate::render::material::{ChunkMaterial, ChunkMaterialHandle, ChunkRendered};
use crate::voxel::VoxelType;
use crate::world::persistence::{PersistenceConfig, save_chunk_to_dir};
use crate::world::{ChunkManager, ChunkModified, ChunkUnloadRequest, ViewerPosition};

use super::lod::{compute_lod, compute_lod_with_hysteresis, lod_to_step};
use super::{ChunkNeighbors, generate_chunk_mesh_with_neighbors};

// ─── EmptyMesh ────────────────────────────────────────────────────────────────

/// Marker component attached to chunk entities whose last meshing pass produced
/// zero vertices (all faces were culled by loaded neighbors).
///
/// When a neighbor subsequently loads and triggers a re-mesh that produces
/// geometry, [`chunk_mesh_system`] removes this marker and propagates a
/// [`ChunkModified`] event to all six neighbors so they too can re-evaluate
/// their border faces.  This enables recursive multi-layer propagation: each
/// chunk that transitions from empty → non-empty signals its neighbors, which
/// may then transition themselves the following frame.
#[derive(Component)]
pub struct EmptyMesh;

// ─── PendingNeighborRemesh ────────────────────────────────────────────────────

/// Staging buffer for neighbor re-mesh requests emitted by [`chunk_mesh_system`].
///
/// `chunk_mesh_system` reads `MessageReader<ChunkModified>` (which requires
/// `Res` access to the message storage) and therefore cannot hold a
/// `MessageWriter<ChunkModified>` (which requires `ResMut`) in the same system
/// without triggering a Bevy B0002 access-conflict panic.
///
/// Instead, newly-rendered chunks push their six neighbor coords here, and
/// [`flush_neighbor_remesh_system`] drains the buffer and emits the
/// `ChunkModified` messages in a separate, sequentially-ordered system.
#[derive(Resource, Default)]
pub struct PendingNeighborRemesh(pub Vec<ChunkCoord>);

// ─── ChunkMeshBudget ──────────────────────────────────────────────────────────

/// Upper bound on how many chunks [`chunk_mesh_system`] meshes in one frame.
///
/// Building a mesh runs on the main thread. When a whole region finishes
/// loading at once (the initial load, or a fast move into unloaded terrain)
/// thousands of chunks ask for a mesh in the same frame; without a bound that
/// frame takes as long as all of them together. With the budget, the excess
/// waits in [`PendingChunkMeshes`] and is meshed on the following frames,
/// nearest to the viewer first.
///
/// [`MeshPlugin`](crate::mesh::MeshPlugin) inserts the default. Insert your own
/// value to trade load time against frame time:
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::prelude::*;
///
/// App::new()
///     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
///     // Smoother frames, slower fill-in.
///     .insert_resource(ChunkMeshBudget::new(16));
/// ```
#[derive(Resource, Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct ChunkMeshBudget {
    /// Meshes built per frame at most. `0` is treated as `1`, so meshing
    /// always makes progress. Chunks that turn out to need no geometry (all
    /// air, or no longer loaded) do not count.
    pub max_chunks_per_frame: usize,
}

impl ChunkMeshBudget {
    /// Default number of chunks meshed per frame.
    pub const DEFAULT_MAX_CHUNKS_PER_FRAME: usize = 64;

    /// How many chunks without geometry to build (all air, unloaded, or not
    /// attached yet) may be visited for each unit of the budget. Those cost a
    /// small fraction of a real mesh.
    const CHEAP_CHUNKS_PER_MESH: usize = 16;

    /// No bound: every requested chunk is meshed in the frame it was
    /// requested, as before this budget existed.
    pub const UNLIMITED: Self = Self {
        max_chunks_per_frame: usize::MAX,
    };

    /// Meshes at most `max_chunks_per_frame` chunks per frame.
    pub const fn new(max_chunks_per_frame: usize) -> Self {
        Self {
            max_chunks_per_frame,
        }
    }
}

impl Default for ChunkMeshBudget {
    fn default() -> Self {
        Self::new(Self::DEFAULT_MAX_CHUNKS_PER_FRAME)
    }
}

// ─── PendingChunkMeshes ───────────────────────────────────────────────────────

/// Chunks waiting for [`chunk_mesh_system`] to (re)build their mesh.
///
/// Every [`ChunkModified`] coord enters this queue once (duplicates are
/// merged) and leaves it when the mesh system reaches it under
/// [`ChunkMeshBudget`]. Neighbour remeshes staged by the mesh system are
/// queued here as soon as they are flushed, so the queue is empty only when
/// meshing has caught up, which is what [`loading_progress_system`](crate::world::loading::loading_progress_system)
/// waits for before it reports the world ready.
#[derive(Resource, Debug, Default)]
pub struct PendingChunkMeshes {
    order: Vec<ChunkCoord>,
    queued: bevy::platform::collections::HashSet<ChunkCoord>,
    /// Set while the mesh system cannot build anything (no chunk material).
    stalled: bool,
}

impl PendingChunkMeshes {
    /// Number of chunks waiting for a mesh.
    pub fn len(&self) -> usize {
        self.order.len()
    }

    /// `true` when no chunk is waiting for a mesh.
    pub fn is_empty(&self) -> bool {
        self.order.is_empty()
    }

    /// `true` while meshing cannot proceed because no chunk material exists
    /// (for example a headless app with [`MeshPlugin`](crate::mesh::MeshPlugin)
    /// but no render setup). Requests are kept, but nothing will consume them,
    /// so callers waiting for the queue to drain should not wait.
    pub fn is_stalled(&self) -> bool {
        self.stalled
    }

    /// `true` if `coord` is waiting for a mesh.
    pub fn contains(&self, coord: ChunkCoord) -> bool {
        self.queued.contains(&coord)
    }

    /// Queues `coord` unless it is already waiting.
    pub(crate) fn push(&mut self, coord: ChunkCoord) {
        if self.queued.insert(coord) {
            self.order.push(coord);
        }
    }

    /// Orders the backlog nearest to `viewer` first.
    ///
    /// Skipped while everything fits in one frame (`len() <= max`): then the
    /// chunks are processed in the order they were requested.
    fn prioritize(&mut self, max: usize, viewer: Vec3) {
        if self.order.len() <= max {
            return;
        }
        let chunk_size = CHUNK_SIZE as f32;
        let distance = |coord: &ChunkCoord| {
            let center = coord.as_vec3() * chunk_size + Vec3::splat(chunk_size * 0.5);
            center.distance_squared(viewer)
        };
        self.order
            .sort_unstable_by(|a, b| distance(a).total_cmp(&distance(b)));
    }

    /// Keeps only the queued chunks for which `keep` returns `true`.
    fn retain(&mut self, mut keep: impl FnMut(ChunkCoord) -> bool) {
        let queued = &mut self.queued;
        self.order.retain(|&coord| {
            let kept = keep(coord);
            if !kept {
                queued.remove(&coord);
            }
            kept
        });
    }

    /// Drops the first `count` chunks of the backlog: the ones just processed.
    fn finish(&mut self, count: usize) {
        for coord in self.order.drain(..count) {
            self.queued.remove(&coord);
        }
    }
}

// ─── chunk_mesh_system ────────────────────────────────────────────────────────

/// Regenerates the mesh for any chunk that received a [`ChunkModified`] message.
///
/// Requests are first merged into [`PendingChunkMeshes`]. Each frame at most
/// [`ChunkMeshBudget::max_chunks_per_frame`] of them are processed, nearest to
/// the viewer first; the rest wait for the following frames. This keeps a
/// frame short when a whole region asks for meshes at once. Without a
/// [`ChunkMeshBudget`] resource the default budget applies, and without a
/// [`PendingChunkMeshes`] resource the backlog is kept inside the system.
///
/// For each processed coord this system:
///
/// 1. Looks up the entity in [`ChunkManager`].
/// 2. Fetches its [`Chunk<V>`] component.
/// 3. Computes the LOD level from the viewer distance using [`compute_lod`].
/// 4. Builds a [`ChunkNeighbors`] struct from the six adjacent chunks.
/// 5. Runs [`generate_chunk_mesh_with_neighbors`] at the step size for that LOD level.
/// 6. **Update path** — if the entity already has a `Mesh3d` handle, replaces
///    the mesh asset data in-place and updates the [`ChunkLod`] component.
/// 7. **First-time path** — otherwise, allocates a new handle and inserts
///    `Mesh3d`, `MeshMaterial3d<StandardMaterial>` or `MeshMaterial3d<ChunkMaterial>`,
///    `Transform`, `Visibility`, AABB, [`ChunkRendered`], and [`ChunkLod`].
///
/// If the chunk material has not been created yet, requests stay queued and
/// are processed once it exists. A request for a chunk that is no longer
/// loaded is dropped.
pub fn chunk_mesh_system<V: VoxelType>(
    mut commands: Commands,
    mut modified_reader: MessageReader<ChunkModified>,
    mut pending_neighbors: ResMut<PendingNeighborRemesh>,
    manager: Res<ChunkManager>,
    chunk_material: Res<ChunkMaterialHandle>,
    viewer: Res<ViewerPosition>,
    mut meshes: ResMut<Assets<Mesh>>,
    chunks: Query<(
        &Chunk<V>,
        Option<&Mesh3d>,
        Option<&ChunkLod>,
        Has<EmptyMesh>,
    )>,
    budget: Option<Res<ChunkMeshBudget>>,
    shared_queue: Option<ResMut<PendingChunkMeshes>>,
    mut local_queue: Local<PendingChunkMeshes>,
) {
    crate::profile_span!("voxel::mesh::chunk_mesh");

    // Merge this frame's requests into the backlog before anything can return
    // early, so a request is never lost with its message.
    let mut shared_queue = shared_queue;
    let queue: &mut PendingChunkMeshes = match shared_queue.as_deref_mut() {
        Some(queue) => queue,
        None => &mut local_queue,
    };
    for &ChunkModified(coord) in modified_reader.read() {
        queue.push(coord);
    }

    // Determine which material path is active.
    // Custom (texture array) takes priority; fall back to StandardMaterial.
    let use_custom = chunk_material.custom.is_some();
    let has_material = chunk_material.custom.is_some() || chunk_material.standard.is_some();
    queue.stalled = !has_material;
    if !has_material {
        // Material not set up: keep the requests for later, but forget the
        // chunks that were unloaded meanwhile so the backlog stays bounded.
        queue.retain(|coord| manager.is_loaded(coord));
        return;
    }

    let chunk_size_f = CHUNK_SIZE as f32;

    // Face direction offsets: index matches ChunkNeighbors.faces convention.
    // [+Y, -Y, +X, -X, +Z, -Z]
    const NEIGHBOR_OFFSETS: [IVec3; 6] = [
        IVec3::new(0, 1, 0),  // 0: +Y
        IVec3::new(0, -1, 0), // 1: -Y
        IVec3::new(1, 0, 0),  // 2: +X
        IVec3::new(-1, 0, 0), // 3: -X
        IVec3::new(0, 0, 1),  // 4: +Z
        IVec3::new(0, 0, -1), // 5: -Z
    ];

    // For each face index i, the adjacent chunk's face that touches ours is
    // the opposite direction. The face convention pairs are (0,1), (2,3), (4,5),
    // so opposite = i ^ 1.

    let max_chunks = budget
        .map(|budget| budget.max_chunks_per_frame)
        .unwrap_or(ChunkMeshBudget::DEFAULT_MAX_CHUNKS_PER_FRAME)
        .max(1);

    // Chunks with nothing to mesh (unloaded, not attached yet, all air) cost
    // very little, so they get a much larger allowance than real meshes.
    let max_visited = max_chunks.saturating_mul(ChunkMeshBudget::CHEAP_CHUNKS_PER_MESH);

    queue.prioritize(max_chunks, viewer.position);
    let mut visited = 0;
    let mut meshed = 0;

    while visited < queue.order.len() && meshed < max_chunks && visited < max_visited {
        let coord = queue.order[visited];
        visited += 1;

        let Some(entity) = manager.get_entity(coord) else {
            // Entity not registered — task may have been cancelled or coord
            // arrived out of order; ignore.
            continue;
        };

        let Ok((chunk, maybe_mesh3d, _maybe_lod, has_empty_mesh)) = chunks.get(entity) else {
            // Chunk component not yet attached — deferred command not flushed yet.
            // Re-queue so we retry next frame when the component is available.
            pending_neighbors.0.push(coord);
            continue;
        };

        // Helper: remove all material-related render components from an entity.
        // Both MeshMaterial3d variants must be removed regardless of which path
        // is currently active, because the entity might have been created under
        // the other path (e.g. if ChunkTextureArray was inserted mid-session).
        let remove_render = |cmd: &mut EntityCommands| {
            cmd.remove::<(
                Mesh3d,
                MeshMaterial3d<StandardMaterial>,
                MeshMaterial3d<ChunkMaterial>,
                ChunkRendered,
                ChunkLod,
            )>();
        };

        // Skip meshing entirely for all-air chunks — no render components needed.
        if chunk.is_empty() {
            if maybe_mesh3d.is_some() {
                // Chunk was previously non-empty (e.g. all voxels mined out);
                // strip render components so it becomes invisible.
                let mut ec = commands.entity(entity);
                remove_render(&mut ec);
                // Notify neighbors — they may now have exposed border faces.
                for &offset in &NEIGHBOR_OFFSETS {
                    let neighbor_coord = coord + offset;
                    if manager.is_loaded(neighbor_coord) {
                        pending_neighbors.0.push(neighbor_coord);
                    }
                }
            } else if !has_empty_mesh {
                // First time seeing this air chunk — notify neighbors so they
                // can generate faces that border this empty space.
                commands.entity(entity).insert(EmptyMesh);
                for &offset in &NEIGHBOR_OFFSETS {
                    let neighbor_coord = coord + offset;
                    if manager.is_loaded(neighbor_coord) {
                        pending_neighbors.0.push(neighbor_coord);
                    }
                }
            }
            continue;
        }

        // Compute LOD from the chunk center to the viewer.
        let chunk_center = coord.as_vec3() * chunk_size_f + Vec3::splat(chunk_size_f * 0.5);
        let lod = compute_lod(chunk_center, viewer.position);
        let lod_step = lod_to_step(lod);

        // Clamp the step to the minimum among this chunk and all loaded neighbors
        // to prevent border cracks when adjacent chunks have finer LOD levels.
        let effective_step = {
            let mut min_step = lod_step;
            for &offset in &NEIGHBOR_OFFSETS {
                let neighbor_coord = coord + offset;
                if let Some(neighbor_entity) = manager.get_entity(neighbor_coord) {
                    if let Ok((_, _, Some(neighbor_lod), _)) = chunks.get(neighbor_entity) {
                        let neighbor_step = lod_to_step(neighbor_lod.0);
                        min_step = min_step.min(neighbor_step);
                    }
                }
            }
            min_step
        };

        // Build ChunkNeighbors from the six adjacent loaded chunks.
        let mut neighbors = ChunkNeighbors::<V>::default();
        for (face_index, &offset) in NEIGHBOR_OFFSETS.iter().enumerate() {
            let neighbor_coord = coord + offset;
            if let Some(neighbor_entity) = manager.get_entity(neighbor_coord) {
                if let Ok((neighbor_chunk, _, _, _)) = chunks.get(neighbor_entity) {
                    // The face of the neighbor that is adjacent to our face_index
                    // is the opposite direction: face_index ^ 1.
                    let opposite_face = face_index ^ 1;
                    neighbors.faces[face_index] = Some(neighbor_chunk.border_slice(opposite_face));
                }
            }
        }

        // Run the neighbor-aware greedy mesher at the effective LOD step.
        meshed += 1;
        let new_mesh = generate_chunk_mesh_with_neighbors(chunk, &neighbors, effective_step);

        if new_mesh.count_vertices() == 0 {
            // Mesher produced no geometry (e.g. all faces are hidden by neighbors).
            // Remove render components if they were previously attached.
            if maybe_mesh3d.is_some() {
                let mut ec = commands.entity(entity);
                remove_render(&mut ec);
            }
            // Tag this entity so we know its mesh is empty. When a neighbor
            // loads later and triggers another re-mesh that produces geometry,
            // we propagate the signal to our own neighbors at that point.
            if !has_empty_mesh {
                commands.entity(entity).insert(EmptyMesh);
            }
            continue;
        }

        if let Some(mesh3d) = maybe_mesh3d {
            // Update path: reuse the existing handle, replace asset data.
            if let Some(existing) = meshes.get_mut(&mesh3d.0) {
                *existing = new_mesh;
            }
            // Update the LOD component to reflect the current level.
            commands.entity(entity).insert(ChunkLod(lod));

            // If this chunk was previously empty (all faces culled) and now has
            // geometry, its border faces changed from invisible to visible.
            // Propagate to neighbors so they can re-evaluate their own faces.
            // This enables multi-layer propagation: each depth level transitions
            // one frame at a time until all chunks converge.
            if has_empty_mesh {
                commands.entity(entity).remove::<EmptyMesh>();
                for &offset in &NEIGHBOR_OFFSETS {
                    let neighbor_coord = coord + offset;
                    if manager.is_loaded(neighbor_coord) {
                        pending_neighbors.0.push(neighbor_coord);
                    }
                }
            }
        } else {
            // First-time path: allocate new handle and attach all render components.
            let mesh_handle = meshes.add(new_mesh);

            // World-space origin of this chunk's minimum corner.
            let translation = coord.as_vec3() * chunk_size_f;

            // AABB sized to the full chunk extent for frustum culling.
            let aabb = Aabb::from_min_max(Vec3::ZERO, Vec3::splat(chunk_size_f));

            let mut entity_cmd = commands.entity(entity);

            if use_custom {
                // Texture-array path.
                let mat = chunk_material.custom.as_ref().unwrap().clone();
                entity_cmd.insert((
                    Mesh3d(mesh_handle),
                    MeshMaterial3d(mat),
                    Transform::from_translation(translation),
                    Visibility::default(),
                    aabb,
                    ChunkRendered,
                    ChunkLod(lod),
                ));
            } else {
                // Fallback StandardMaterial path.
                let mat = chunk_material.standard.as_ref().unwrap().clone();
                entity_cmd.insert((
                    Mesh3d(mesh_handle),
                    MeshMaterial3d(mat),
                    Transform::from_translation(translation),
                    Visibility::default(),
                    aabb,
                    ChunkRendered,
                    ChunkLod(lod),
                ));
            }

            // If this chunk had EmptyMesh from a previous 0-vertex pass, remove it.
            if has_empty_mesh {
                commands.entity(entity).remove::<EmptyMesh>();
            }

            // A newly rendered chunk changes the border visibility of every
            // adjacent chunk.  Stage ChunkModified for each loaded neighbor so
            // they re-mesh and cull (or un-cull) the faces that touch this chunk.
            // Messages are emitted by flush_neighbor_remesh_system (runs after
            // this system) to avoid a ResMut/Res conflict on the message storage.
            // This is only done on the first-time path to avoid cascading
            // re-meshes on every LOD or voxel-edit update.
            for &offset in &NEIGHBOR_OFFSETS {
                let neighbor_coord = coord + offset;
                if manager.is_loaded(neighbor_coord) {
                    pending_neighbors.0.push(neighbor_coord);
                }
            }
        }
    }

    queue.finish(visited);
}

// ─── flush_neighbor_remesh_system ────────────────────────────────────────────

/// Drains [`PendingNeighborRemesh`] and emits a [`ChunkModified`] message for
/// each staged coord.
///
/// This system exists solely to decouple the *write* of `ChunkModified` from
/// [`chunk_mesh_system`], which holds a `MessageReader<ChunkModified>` (i.e.
/// `Res` access to the message store).  Having both `Res` and `ResMut` on the
/// same resource in one system triggers Bevy's B0002 access-conflict panic.
///
/// By staging neighbor coords in [`PendingNeighborRemesh`] and draining them
/// here — after `chunk_mesh_system` has finished — we keep the two accesses in
/// separate systems, which Bevy schedules sequentially via `.after()`.
///
/// The coords are also added to [`PendingChunkMeshes`] right away. The mesh
/// system would queue them from the messages on the next frame anyway; doing
/// it here keeps the queue non-empty in between, so a system that waits for an
/// empty queue does not see a false "meshing done".
pub fn flush_neighbor_remesh_system(
    mut pending: ResMut<PendingNeighborRemesh>,
    mut modified_writer: MessageWriter<ChunkModified>,
    mut queue: Option<ResMut<PendingChunkMeshes>>,
) {
    for coord in pending.0.drain(..) {
        modified_writer.write(ChunkModified(coord));
        if let Some(queue) = queue.as_deref_mut() {
            queue.push(coord);
        }
    }
}

// ─── lod_update_system ────────────────────────────────────────────────────────

/// Every frame, recomputes the LOD level for every rendered chunk.
///
/// For each chunk entity that has a [`Transform`] and a [`ChunkLod`] component,
/// this system:
///
/// 1. Reads the chunk's world-space center from its [`ChunkCoordComp`] (or
///    falls back to the entity's [`Transform`] translation).
/// 2. Calls [`compute_lod`] with the current [`ViewerPosition`].
/// 3. If the computed LOD differs from the stored one, emits [`ChunkModified`]
///    so that [`chunk_mesh_system`] regenerates the mesh at the new level.
///
/// The [`ChunkLod`] component is NOT updated here; `chunk_mesh_system` updates
/// it once the new mesh has actually been built.
pub fn lod_update_system<V: VoxelType>(
    viewer: Res<ViewerPosition>,
    chunks: Query<(Entity, &Transform, &ChunkLod, Option<&ChunkCoordComp>), With<ChunkRendered>>,
    mut modified_writer: MessageWriter<ChunkModified>,
    manager: Res<ChunkManager>,
) {
    let chunk_size_f = CHUNK_SIZE as f32;

    for (entity, transform, current_lod, maybe_coord_comp) in &chunks {
        // Determine the chunk's world-space center.
        // Prefer the ChunkCoordComp (grid coord → center) over raw Transform
        // translation, since the transform is at the minimum corner.
        let chunk_center = if let Some(coord_comp) = maybe_coord_comp {
            coord_comp.coord().as_vec3() * chunk_size_f + Vec3::splat(chunk_size_f * 0.5)
        } else {
            // Fallback: treat the transform translation as the minimum corner
            // and offset to find the center.
            transform.translation + Vec3::splat(chunk_size_f * 0.5)
        };

        let new_lod =
            compute_lod_with_hysteresis(chunk_center, viewer.position, current_lod.0, 5.0);

        if new_lod != current_lod.0 {
            // Find the coord for this entity so we can emit ChunkModified(coord).
            // Chunks spawned by the framework carry a ChunkCoordComp, so this is
            // a direct lookup; only entities without one fall back to an O(n)
            // scan of the manager's loaded set.
            let registered_coord = maybe_coord_comp
                .map(|c| c.coord())
                .filter(|&c| manager.get_entity(c) == Some(entity))
                .or_else(|| {
                    manager
                        .iter_loaded()
                        .find_map(|(coord, e)| if e == entity { Some(coord) } else { None })
                });
            if let Some(coord) = registered_coord {
                modified_writer.write(ChunkModified(coord));

                // Also remesh each loaded neighbor: their effective_step may
                // change now that this chunk's LOD has changed.
                const NEIGHBOR_OFFSETS: [IVec3; 6] = [
                    IVec3::new(0, 1, 0),
                    IVec3::new(0, -1, 0),
                    IVec3::new(1, 0, 0),
                    IVec3::new(-1, 0, 0),
                    IVec3::new(0, 0, 1),
                    IVec3::new(0, 0, -1),
                ];
                for &offset in &NEIGHBOR_OFFSETS {
                    let neighbor_coord = coord + offset;
                    if manager.is_loaded(neighbor_coord) {
                        modified_writer.write(ChunkModified(neighbor_coord));
                    }
                }
            }
        }
    }
}

// ─── chunk_despawn_system ─────────────────────────────────────────────────────

/// Responds to [`ChunkUnloadRequest`] messages by saving and despawning chunk entities.
///
/// For each unload request this system:
/// 1. If [`PersistenceConfig::auto_save`] is `true` and the chunk has unsaved
///    changes ([`Chunk::is_dirty`]), saves it to disk before the entity is
///    despawned. Unmodified chunks are not written: they can be generated or
///    restored again.
/// 2. Removes the chunk from [`ChunkManager`] so the streaming system can
///    re-request the same coord if the viewer returns.
/// 3. Despawns the entity.
///
/// Save errors are reported with `eprintln!` and do not panic.
///
/// This system is generic over `V` because it must query the [`Chunk<V>`]
/// component to serialise voxel data. It is registered by [`MeshPlugin`](crate::mesh::MeshPlugin).
pub fn chunk_despawn_system<V: VoxelType>(
    mut commands: Commands,
    mut unload_reader: MessageReader<ChunkUnloadRequest>,
    mut manager: ResMut<ChunkManager>,
    config: Option<Res<PersistenceConfig>>,
    chunks: Query<&Chunk<V>>,
) {
    crate::profile_span!("voxel::world::chunk_unload");
    for &ChunkUnloadRequest(coord) in unload_reader.read() {
        // Save before unregistering so the entity is still valid.
        if let Some(config) = config.as_ref().filter(|c| c.auto_save)
            && let Some(entity) = manager.get_entity(coord)
            && let Ok(chunk) = chunks.get(entity)
            && chunk.is_dirty()
        {
            save_chunk_to_dir(chunk, coord, &config.save_dir, " on unload");
        }

        if let Some(entity) = manager.unregister(coord) {
            commands.entity(entity).despawn();
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::chunk::persistence as chunk_persistence;
    use crate::mesh::MeshPlugin;
    use crate::test_support::{filled_chunk, world_with_chunks};
    use crate::voxel::DefaultVoxel;
    use bevy::ecs::message::Messages;
    use bevy::ecs::system::RunSystemOnce;

    type V = DefaultVoxel;

    /// World with the resources the mesh systems read, plus a standard
    /// material so `chunk_mesh_system` does not early-return.
    fn mesh_world(chunks: impl IntoIterator<Item = (IVec3, Chunk<V>)>) -> World {
        let mut world = world_with_chunks(chunks);
        world.init_resource::<Messages<ChunkModified>>();
        world.init_resource::<Messages<ChunkUnloadRequest>>();
        world.init_resource::<PendingNeighborRemesh>();
        world.init_resource::<PendingChunkMeshes>();
        world.init_resource::<ViewerPosition>();
        world.init_resource::<Assets<Mesh>>();
        let mut materials = Assets::<StandardMaterial>::default();
        let standard = materials.add(StandardMaterial::default());
        world.insert_resource(materials);
        world.insert_resource(ChunkMaterialHandle {
            standard: Some(standard),
            custom: None,
        });
        world
    }

    fn entity_at(world: &World, coord: IVec3) -> Entity {
        world
            .resource::<ChunkManager>()
            .get_entity(coord)
            .expect("chunk should be registered")
    }

    fn modify(world: &mut World, coord: IVec3) {
        world.write_message(ChunkModified(coord));
    }

    fn run_mesh(world: &mut World) {
        world
            .run_system_once(chunk_mesh_system::<V>)
            .expect("chunk_mesh_system should run");
    }

    /// Clears the message buffer so the next run only sees new messages.
    fn clear_modified(world: &mut World) {
        world.resource_mut::<Messages<ChunkModified>>().clear();
    }

    fn pending(world: &World) -> Vec<IVec3> {
        let mut coords = world.resource::<PendingNeighborRemesh>().0.clone();
        coords.sort_by_key(|c| (c.x, c.y, c.z));
        coords
    }

    fn written_modified(world: &World) -> Vec<IVec3> {
        let messages = world.resource::<Messages<ChunkModified>>();
        let mut coords: Vec<IVec3> = messages
            .iter_current_update_messages()
            .map(|m| m.0)
            .collect();
        coords.sort_by_key(|c| (c.x, c.y, c.z));
        coords
    }

    fn mesh_vertex_count(world: &World, entity: Entity) -> usize {
        let handle = &world.entity(entity).get::<Mesh3d>().expect("Mesh3d").0;
        world
            .resource::<Assets<Mesh>>()
            .get(handle)
            .expect("mesh asset")
            .count_vertices()
    }

    fn single_voxel_chunk() -> Chunk<V> {
        let mut chunk = Chunk::<V>::new();
        chunk.set(8, 8, 8, DefaultVoxel::Rock);
        chunk
    }

    // ── mesh budget ──────────────────────────────────────────────────────────

    /// Five single-voxel chunks in a row along +X, far enough apart that they
    /// are not neighbours of each other.
    fn row_coords() -> [IVec3; 5] {
        [0, 2, 4, 6, 8].map(|x| IVec3::new(x, 0, 0))
    }

    fn row_world() -> World {
        mesh_world(row_coords().map(|coord| (coord, single_voxel_chunk())))
    }

    fn meshed(world: &World) -> Vec<IVec3> {
        row_coords()
            .into_iter()
            .filter(|&coord| world.entity(entity_at(world, coord)).contains::<Mesh3d>())
            .collect()
    }

    #[test]
    fn budget_bounds_the_meshes_built_in_one_frame() {
        let mut world = row_world();
        world.insert_resource(ChunkMeshBudget::new(2));
        for coord in row_coords() {
            modify(&mut world, coord);
        }

        run_mesh(&mut world);
        assert_eq!(meshed(&world).len(), 2);
        assert_eq!(world.resource::<PendingChunkMeshes>().len(), 3);

        clear_modified(&mut world);
        run_mesh(&mut world);
        assert_eq!(meshed(&world).len(), 4);
        run_mesh(&mut world);
        assert_eq!(meshed(&world).len(), 5);
        assert!(world.resource::<PendingChunkMeshes>().is_empty());
    }

    #[test]
    fn budget_meshes_the_chunks_nearest_to_the_viewer_first() {
        let mut world = row_world();
        world.insert_resource(ChunkMeshBudget::new(1));
        // Viewer inside the chunk at x = 6.
        world.resource_mut::<ViewerPosition>().position = Vec3::new(6.5 * 16.0, 8.0, 8.0);
        for coord in row_coords() {
            modify(&mut world, coord);
        }

        run_mesh(&mut world);
        assert_eq!(meshed(&world), vec![IVec3::new(6, 0, 0)]);

        clear_modified(&mut world);
        run_mesh(&mut world);
        run_mesh(&mut world);
        assert_eq!(
            meshed(&world),
            vec![
                IVec3::new(4, 0, 0),
                IVec3::new(6, 0, 0),
                IVec3::new(8, 0, 0)
            ]
        );
    }

    #[test]
    fn repeated_requests_for_a_chunk_are_queued_once() {
        let mut world = row_world();
        world.insert_resource(ChunkMeshBudget::new(1));
        let far = IVec3::new(8, 0, 0);
        for _ in 0..3 {
            modify(&mut world, far);
        }
        modify(&mut world, IVec3::ZERO);

        run_mesh(&mut world);

        let pending = world.resource::<PendingChunkMeshes>();
        assert_eq!(pending.len(), 1);
        assert!(pending.contains(far));
    }

    #[test]
    fn zero_budget_still_makes_progress() {
        let mut world = row_world();
        world.insert_resource(ChunkMeshBudget::new(0));
        modify(&mut world, IVec3::ZERO);
        modify(&mut world, IVec3::new(2, 0, 0));

        run_mesh(&mut world);

        assert_eq!(meshed(&world).len(), 1);
    }

    #[test]
    fn unlimited_budget_meshes_everything_at_once() {
        // More chunks than the default budget, so the default would stop early.
        let count = ChunkMeshBudget::DEFAULT_MAX_CHUNKS_PER_FRAME as i32 + 6;
        let coords: Vec<IVec3> = (0..count).map(|i| IVec3::new(i * 2, 0, 0)).collect();
        let mut world = mesh_world(coords.iter().map(|&c| (c, single_voxel_chunk())));
        world.insert_resource(ChunkMeshBudget::UNLIMITED);
        for &coord in &coords {
            modify(&mut world, coord);
        }

        run_mesh(&mut world);

        let meshed = coords
            .iter()
            .filter(|&&c| world.entity(entity_at(&world, c)).contains::<Mesh3d>())
            .count();
        assert_eq!(meshed, coords.len());
        assert!(world.resource::<PendingChunkMeshes>().is_empty());
    }

    #[test]
    fn chunks_without_geometry_do_not_use_the_budget() {
        // Three all-air chunks and one unloaded coord nearer to the viewer
        // than the only chunk with geometry.
        let air = [1, 2, 3].map(|x| IVec3::new(x, 0, 0));
        let solid = IVec3::new(9, 0, 0);
        let unloaded = IVec3::new(0, 5, 0);
        let mut world = mesh_world(
            air.map(|c| (c, Chunk::<V>::new()))
                .into_iter()
                .chain([(solid, single_voxel_chunk())]),
        );
        world.insert_resource(ChunkMeshBudget::new(1));
        for coord in air.into_iter().chain([unloaded, solid]) {
            modify(&mut world, coord);
        }

        run_mesh(&mut world);

        assert!(
            world.entity(entity_at(&world, solid)).contains::<Mesh3d>(),
            "the one real mesh must fit in a budget of one"
        );
        let pending = world.resource::<PendingChunkMeshes>();
        assert!(pending.is_empty());
        assert!(!pending.contains(unloaded), "unloaded coords are dropped");
    }

    #[test]
    fn neighbour_remeshes_are_queued_as_soon_as_they_are_flushed() {
        let a = IVec3::ZERO;
        let b = IVec3::new(1, 0, 0);
        let mut world = mesh_world([(a, single_voxel_chunk()), (b, single_voxel_chunk())]);
        modify(&mut world, a);
        run_mesh(&mut world);
        assert!(world.resource::<PendingChunkMeshes>().is_empty());

        world
            .run_system_once(flush_neighbor_remesh_system)
            .expect("flush_neighbor_remesh_system should run");

        // `a` just got its first mesh, so its neighbour `b` needs a remesh.
        // It must already be visible as pending, not only next frame.
        assert!(world.resource::<PendingChunkMeshes>().contains(b));
    }

    #[test]
    fn queue_reports_stalled_and_forgets_unloaded_chunks_without_a_material() {
        let mut world = row_world();
        world.insert_resource(ChunkMaterialHandle::default());
        let unloaded = IVec3::new(0, 7, 0);
        modify(&mut world, IVec3::ZERO);
        modify(&mut world, unloaded);

        run_mesh(&mut world);

        let pending = world.resource::<PendingChunkMeshes>();
        assert!(pending.is_stalled());
        assert!(pending.contains(IVec3::ZERO));
        assert!(!pending.contains(unloaded));
    }

    #[test]
    fn requests_made_before_the_material_exists_are_kept() {
        let mut world = row_world();
        let material = world.remove_resource::<ChunkMaterialHandle>().unwrap();
        world.insert_resource(ChunkMaterialHandle::default());
        modify(&mut world, IVec3::ZERO);

        run_mesh(&mut world);
        assert!(meshed(&world).is_empty());
        // The message is gone by the time the material is ready.
        clear_modified(&mut world);
        world.insert_resource(material);

        run_mesh(&mut world);
        assert_eq!(meshed(&world), vec![IVec3::ZERO]);
        assert!(!world.resource::<PendingChunkMeshes>().is_stalled());
    }

    #[test]
    fn system_works_without_the_budget_and_queue_resources() {
        // A game that registers the system by hand, without `MeshPlugin`.
        let mut app = App::new();
        app.add_message::<ChunkModified>();
        app.init_resource::<PendingNeighborRemesh>();
        app.init_resource::<ViewerPosition>();
        app.init_resource::<Assets<Mesh>>();
        let mut materials = Assets::<StandardMaterial>::default();
        let standard = materials.add(StandardMaterial::default());
        app.insert_resource(materials);
        app.insert_resource(ChunkMaterialHandle {
            standard: Some(standard),
            custom: None,
        });
        let mut manager = ChunkManager::default();
        let mut entities = Vec::new();
        for i in 0..(ChunkMeshBudget::DEFAULT_MAX_CHUNKS_PER_FRAME as i32 + 3) {
            let coord = IVec3::new(i * 2, 0, 0);
            let entity = app.world_mut().spawn(single_voxel_chunk()).id();
            manager.register(coord, entity);
            entities.push((coord, entity));
        }
        app.insert_resource(manager);
        app.add_systems(Update, chunk_mesh_system::<V>);
        for &(coord, _) in &entities {
            app.world_mut().write_message(ChunkModified(coord));
        }
        let meshed = |app: &App| {
            entities
                .iter()
                .filter(|(_, entity)| app.world().entity(*entity).contains::<Mesh3d>())
                .count()
        };

        app.update();
        assert_eq!(meshed(&app), ChunkMeshBudget::DEFAULT_MAX_CHUNKS_PER_FRAME);

        // The backlog survives between frames without a queue resource.
        app.update();
        assert_eq!(meshed(&app), entities.len());
    }

    #[test]
    fn mesh_plugin_installs_the_budget_and_the_queue() {
        let mut app = App::new();
        app.add_plugins(MeshPlugin::<V>::new());
        assert_eq!(
            *app.world().resource::<ChunkMeshBudget>(),
            ChunkMeshBudget::default()
        );
        assert!(app.world().resource::<PendingChunkMeshes>().is_empty());
    }

    // ── chunk_mesh_system ────────────────────────────────────────────────────

    #[test]
    fn solid_chunk_gets_render_components_at_its_world_position() {
        let coord = IVec3::new(1, -2, 3);
        let mut world = mesh_world([(coord, single_voxel_chunk())]);
        modify(&mut world, coord);
        run_mesh(&mut world);

        let entity = entity_at(&world, coord);
        let e = world.entity(entity);
        assert!(e.contains::<MeshMaterial3d<StandardMaterial>>());
        assert!(e.contains::<ChunkRendered>());
        assert!(e.contains::<Aabb>());
        assert!(!e.contains::<EmptyMesh>());
        // ~65 units from the viewer at the origin → full-detail LOD 0.
        assert_eq!(e.get::<ChunkLod>().map(|l| l.0), Some(0));
        assert_eq!(
            e.get::<Transform>().unwrap().translation,
            coord.as_vec3() * CHUNK_SIZE as f32
        );
        // One isolated voxel → 6 quads → 24 vertices.
        assert_eq!(mesh_vertex_count(&world, entity), 24);
    }

    #[test]
    fn new_mesh_queues_loaded_neighbors_for_remesh() {
        let coord = IVec3::ZERO;
        let neighbor_x = IVec3::X;
        let neighbor_down = IVec3::NEG_Y;
        let mut world = mesh_world([
            (coord, single_voxel_chunk()),
            (neighbor_x, Chunk::<V>::new()),
            (neighbor_down, Chunk::<V>::new()),
        ]);
        modify(&mut world, coord);
        run_mesh(&mut world);

        assert_eq!(pending(&world), vec![IVec3::NEG_Y, IVec3::X]);
    }

    #[test]
    fn no_material_means_no_meshing() {
        let coord = IVec3::ZERO;
        let mut world = mesh_world([(coord, single_voxel_chunk())]);
        world.insert_resource(ChunkMaterialHandle {
            standard: None,
            custom: None,
        });
        modify(&mut world, coord);
        run_mesh(&mut world);

        assert!(!world.entity(entity_at(&world, coord)).contains::<Mesh3d>());
    }

    #[test]
    fn empty_chunk_is_marked_empty_without_a_mesh() {
        let coord = IVec3::ZERO;
        let mut world = mesh_world([(coord, Chunk::<V>::new()), (IVec3::Z, Chunk::<V>::new())]);
        modify(&mut world, coord);
        run_mesh(&mut world);

        let e = world.entity(entity_at(&world, coord));
        assert!(e.contains::<EmptyMesh>());
        assert!(!e.contains::<Mesh3d>());
        assert_eq!(pending(&world), vec![IVec3::Z]);
    }

    #[test]
    fn chunk_emptied_after_meshing_loses_its_render_components() {
        let coord = IVec3::ZERO;
        let mut world = mesh_world([(coord, single_voxel_chunk())]);
        modify(&mut world, coord);
        run_mesh(&mut world);
        let entity = entity_at(&world, coord);
        assert!(world.entity(entity).contains::<Mesh3d>());

        // Mine the only voxel and remesh.
        world
            .get_mut::<Chunk<V>>(entity)
            .unwrap()
            .set(8, 8, 8, DefaultVoxel::Air);
        clear_modified(&mut world);
        modify(&mut world, coord);
        run_mesh(&mut world);

        let e = world.entity(entity);
        assert!(!e.contains::<Mesh3d>());
        assert!(!e.contains::<MeshMaterial3d<StandardMaterial>>());
        assert!(!e.contains::<ChunkRendered>());
        assert!(!e.contains::<ChunkLod>());
    }

    #[test]
    fn remesh_updates_the_existing_mesh_asset_in_place() {
        let coord = IVec3::ZERO;
        let mut world = mesh_world([(coord, single_voxel_chunk())]);
        modify(&mut world, coord);
        run_mesh(&mut world);
        let entity = entity_at(&world, coord);
        let handle_before = world.entity(entity).get::<Mesh3d>().unwrap().0.id();
        let assets_before = world.resource::<Assets<Mesh>>().len();

        // A second, separate voxel adds 6 more quads.
        world
            .get_mut::<Chunk<V>>(entity)
            .unwrap()
            .set(2, 2, 2, DefaultVoxel::Rock);
        clear_modified(&mut world);
        modify(&mut world, coord);
        run_mesh(&mut world);

        let handle_after = world.entity(entity).get::<Mesh3d>().unwrap().0.id();
        assert_eq!(handle_before, handle_after, "mesh handle must be reused");
        assert_eq!(world.resource::<Assets<Mesh>>().len(), assets_before);
        assert_eq!(mesh_vertex_count(&world, entity), 48);
    }

    #[test]
    fn fully_enclosed_solid_chunk_produces_no_mesh() {
        // A solid chunk surrounded by solid chunks on all six faces has no
        // visible face, so it must be marked empty instead of rendered.
        let center = IVec3::ZERO;
        let mut chunks = vec![(center, filled_chunk(DefaultVoxel::Rock))];
        for offset in [
            IVec3::X,
            IVec3::NEG_X,
            IVec3::Y,
            IVec3::NEG_Y,
            IVec3::Z,
            IVec3::NEG_Z,
        ] {
            chunks.push((offset, filled_chunk(DefaultVoxel::Rock)));
        }
        let mut world = mesh_world(chunks);
        modify(&mut world, center);
        run_mesh(&mut world);

        let e = world.entity(entity_at(&world, center));
        assert!(e.contains::<EmptyMesh>());
        assert!(!e.contains::<Mesh3d>());
    }

    #[test]
    fn modified_entity_without_chunk_data_is_retried() {
        // The coord is registered but the generator has not inserted the
        // Chunk component yet: the coord goes back to the pending queue.
        let coord = IVec3::new(4, 0, 0);
        let mut world = mesh_world(std::iter::empty());
        let entity = world.spawn_empty().id();
        world.resource_mut::<ChunkManager>().register(coord, entity);
        modify(&mut world, coord);
        run_mesh(&mut world);

        assert_eq!(pending(&world), vec![coord]);
    }

    // ── flush_neighbor_remesh_system ─────────────────────────────────────────

    #[test]
    fn flush_turns_pending_coords_into_chunk_modified_messages() {
        let mut world = mesh_world(std::iter::empty());
        world.resource_mut::<PendingNeighborRemesh>().0 = vec![IVec3::X, IVec3::NEG_Z];
        world
            .run_system_once(flush_neighbor_remesh_system)
            .expect("flush should run");

        assert!(pending(&world).is_empty());
        assert_eq!(written_modified(&world), vec![IVec3::NEG_Z, IVec3::X]);
    }

    // ── lod_update_system ────────────────────────────────────────────────────

    fn rendered_chunk_world(coord: IVec3, lod: u8, with_coord_comp: bool) -> World {
        let mut world = mesh_world([
            (coord, single_voxel_chunk()),
            (coord + IVec3::Y, Chunk::new()),
        ]);
        let entity = entity_at(&world, coord);
        let mut e = world.entity_mut(entity);
        e.insert((
            Transform::from_translation(coord.as_vec3() * CHUNK_SIZE as f32),
            ChunkLod(lod),
            ChunkRendered,
        ));
        if with_coord_comp {
            e.insert(ChunkCoordComp(coord));
        }
        world
    }

    fn run_lod(world: &mut World) {
        world
            .run_system_once(lod_update_system::<V>)
            .expect("lod_update_system should run");
    }

    #[test]
    fn lod_change_remeshes_the_chunk_and_its_loaded_neighbors() {
        for with_coord_comp in [true, false] {
            // Viewer at the origin, chunk ~0 units away, but stored as LOD 1.
            let coord = IVec3::ZERO;
            let mut world = rendered_chunk_world(coord, 1, with_coord_comp);
            run_lod(&mut world);

            assert_eq!(
                written_modified(&world),
                vec![IVec3::ZERO, IVec3::Y],
                "with_coord_comp = {with_coord_comp}"
            );
        }
    }

    #[test]
    fn unchanged_lod_emits_nothing() {
        let coord = IVec3::ZERO;
        let mut world = rendered_chunk_world(coord, 0, true);
        run_lod(&mut world);

        assert!(written_modified(&world).is_empty());
    }

    #[test]
    fn far_chunk_downgrades_to_coarse_lod() {
        // 20 chunks away = 320 units, well past the 200-unit threshold.
        let coord = IVec3::new(20, 0, 0);
        let mut world = rendered_chunk_world(coord, 0, true);
        run_lod(&mut world);

        assert_eq!(written_modified(&world), vec![coord, coord + IVec3::Y]);
    }

    // ── chunk_despawn_system ─────────────────────────────────────────────────

    fn run_despawn(world: &mut World, coord: IVec3) {
        world.write_message(ChunkUnloadRequest(coord));
        world
            .run_system_once(chunk_despawn_system::<V>)
            .expect("chunk_despawn_system should run");
    }

    #[test]
    fn unload_with_auto_save_writes_the_chunk_and_despawns_it() {
        let temp = tempfile::tempdir().unwrap();
        let save_dir = temp.path().join("nested").join("world");
        let coord = IVec3::new(-3, 1, 2);
        let mut world = mesh_world([(coord, single_voxel_chunk())]);
        world.insert_resource(PersistenceConfig {
            save_dir: save_dir.to_string_lossy().into_owned(),
            auto_save: true,
        });
        let entity = entity_at(&world, coord);

        run_despawn(&mut world, coord);

        assert!(
            world.get_entity(entity).is_err(),
            "entity should be despawned"
        );
        assert!(!world.resource::<ChunkManager>().is_loaded(coord));
        let path = save_dir.join(chunk_persistence::chunk_filename(coord));
        let saved: Chunk<V> = chunk_persistence::load_chunk(&path).expect("chunk saved on unload");
        assert_eq!(saved.get(8, 8, 8), DefaultVoxel::Rock);
        assert_eq!(saved.get(0, 0, 0), DefaultVoxel::Air);
    }

    #[test]
    fn unload_of_an_unmodified_chunk_writes_nothing() {
        let temp = tempfile::tempdir().unwrap();
        let coord = IVec3::new(2, 0, -1);
        let mut chunk = single_voxel_chunk();
        // As handed out by the generator pipeline: nothing to save.
        chunk.mark_clean();
        let mut world = mesh_world([(coord, chunk)]);
        world.insert_resource(PersistenceConfig {
            save_dir: temp.path().to_string_lossy().into_owned(),
            auto_save: true,
        });
        let entity = entity_at(&world, coord);

        run_despawn(&mut world, coord);

        assert!(world.get_entity(entity).is_err());
        assert!(!world.resource::<ChunkManager>().is_loaded(coord));
        assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 0);
    }

    #[test]
    fn unload_writes_a_chunk_whose_only_change_is_a_state_byte() {
        let temp = tempfile::tempdir().unwrap();
        let coord = IVec3::ZERO;
        let mut chunk = single_voxel_chunk();
        chunk.mark_clean();
        // State-only edits emit no ChunkModified, so unload is their only save.
        chunk.set_state(8, 8, 8, 9);
        let mut world = mesh_world([(coord, chunk)]);
        world.insert_resource(PersistenceConfig {
            save_dir: temp.path().to_string_lossy().into_owned(),
            auto_save: true,
        });

        run_despawn(&mut world, coord);

        let path = temp.path().join(chunk_persistence::chunk_filename(coord));
        let saved: Chunk<V> = chunk_persistence::load_chunk(&path).expect("chunk saved on unload");
        assert_eq!(saved.get_state(8, 8, 8), 9);
    }

    #[test]
    fn unload_without_auto_save_despawns_without_writing() {
        let temp = tempfile::tempdir().unwrap();
        let coord = IVec3::ZERO;
        let mut world = mesh_world([(coord, single_voxel_chunk())]);
        world.insert_resource(PersistenceConfig {
            save_dir: temp.path().to_string_lossy().into_owned(),
            auto_save: false,
        });
        let entity = entity_at(&world, coord);

        run_despawn(&mut world, coord);

        assert!(world.get_entity(entity).is_err());
        assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 0);
    }

    #[test]
    fn unload_without_persistence_config_still_despawns() {
        let coord = IVec3::ZERO;
        let mut world = mesh_world([(coord, single_voxel_chunk())]);
        let entity = entity_at(&world, coord);

        run_despawn(&mut world, coord);

        assert!(world.get_entity(entity).is_err());
        assert!(!world.resource::<ChunkManager>().is_loaded(coord));
    }
}