voxel-framework 0.13.1

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
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
//! Core greedy meshing algorithm for voxel chunks.
//!
//! # Algorithm
//!
//! Greedy meshing eliminates redundant geometry by merging adjacent coplanar
//! faces of identical voxel type into a single large quad.  The implementation
//! follows the classic Mikola Lysenko approach adapted for a cubic grid:
//!
//! 1. **Iterate over face directions** — the six cardinal axes (`±X`, `±Y`,
//!    `±Z`) are processed independently via [`FACE_DIRS`].
//! 2. **Build a 2-D mask** per slice — for each depth `d` along the face's
//!    primary axis, a `size × size` mask records `Some(voxel)` when the
//!    super-voxel at that cell is solid *and* its outward face is visible
//!    (i.e., the neighbor cell is air).  The `face_visible` callback is
//!    injected so the neighbor-aware variant can plug in its own logic without
//!    duplicating the merge loop.
//! 3. **Greedy merge** — the mask is scanned row by row.  For each non-empty
//!    cell the algorithm extends a rectangle as wide as possible in `u`, then
//!    as tall as possible in `v`, while every cell in the rectangle matches the
//!    same voxel type.  The merged region is cleared in the mask and a single
//!    quad is emitted.
//!
//! # LOD super-voxels
//!
//! The `step` parameter coarsens the grid: each super-voxel covers a
//! `step × step × step` region.  [`super_voxel`] picks the first solid voxel
//! within the region, so a coarser LOD level collapses fine detail but retains
//! the presence of solid material.  This is a "representative sample" strategy
//! chosen for its O(step³) simplicity and acceptable visual quality at distance.

use bevy::asset::RenderAssetUsages;
use bevy::mesh::{Indices, Mesh, MeshVertexAttribute, PrimitiveTopology, VertexFormat};

use crate::chunk::{CHUNK_SIZE, Chunk, VOXEL_SIZE};
use crate::voxel::{TerrainMaterialId, VoxelType};

/// Custom mesh vertex attribute carrying the texture array layer index.
///
/// Each vertex stores a `u32` that selects which layer of the GPU texture
/// array the `ChunkMaterial` shader samples when rendering that vertex.
/// The value comes from [`crate::voxel::VoxelType::texture_layer`].
pub const ATTRIBUTE_TEXTURE_LAYER: MeshVertexAttribute =
    MeshVertexAttribute::new("Vertex_TextureLayer", 988540919, VertexFormat::Uint32);

/// Custom mesh vertex attribute that tells a face uncovered by an edit from a
/// face of the generated surface.
///
/// `1.0` on every vertex of a face recorded in
/// [`Chunk::exposed_faces`](crate::chunk::Chunk::exposed_faces), `0.0` on
/// every other vertex. The framework only reports it: a terrain material
/// reads it to draw fresh faces differently. Built-in materials ignore it.
pub const ATTRIBUTE_FACE_EXPOSED: MeshVertexAttribute =
    MeshVertexAttribute::new("Vertex_FaceExposed", 988540920, VertexFormat::Float32);

/// Face direction descriptor used by the greedy mesher.
///
/// Each of the 6 faces has a primary axis, a sign (positive or negative),
/// and two tangent axes (u and v) that span the 2D slice plane.
pub(crate) struct FaceDir {
    /// Primary axis index: 0=X, 1=Y, 2=Z.
    pub axis: usize,
    /// `true` for positive direction (+X, +Y, +Z).
    pub positive: bool,
    /// First tangent axis index.
    pub u_axis: usize,
    /// Second tangent axis index.
    pub v_axis: usize,
    /// Face normal as `[f32; 3]`.
    normal: [f32; 3],
}

/// The six cardinal face directions in project convention order.
pub(crate) const FACE_DIRS: [FaceDir; 6] = [
    // Face 0: +Y (top) — axis=Y(1), u=X(0), v=Z(2)
    FaceDir {
        axis: 1,
        positive: true,
        u_axis: 0,
        v_axis: 2,
        normal: [0.0, 1.0, 0.0],
    },
    // Face 1: -Y (bottom) — axis=Y(1), u=X(0), v=Z(2)
    FaceDir {
        axis: 1,
        positive: false,
        u_axis: 0,
        v_axis: 2,
        normal: [0.0, -1.0, 0.0],
    },
    // Face 2: +X (right) — axis=X(0), u=Z(2), v=Y(1)
    FaceDir {
        axis: 0,
        positive: true,
        u_axis: 2,
        v_axis: 1,
        normal: [1.0, 0.0, 0.0],
    },
    // Face 3: -X (left) — axis=X(0), u=Z(2), v=Y(1)
    FaceDir {
        axis: 0,
        positive: false,
        u_axis: 2,
        v_axis: 1,
        normal: [-1.0, 0.0, 0.0],
    },
    // Face 4: +Z (front) — axis=Z(2), u=X(0), v=Y(1)
    FaceDir {
        axis: 2,
        positive: true,
        u_axis: 0,
        v_axis: 1,
        normal: [0.0, 0.0, 1.0],
    },
    // Face 5: -Z (back) — axis=Z(2), u=X(0), v=Y(1)
    FaceDir {
        axis: 2,
        positive: false,
        u_axis: 0,
        v_axis: 1,
        normal: [0.0, 0.0, -1.0],
    },
];

/// Returns the representative voxel for a `step × step × step` region rooted
/// at `(sx, sy, sz)`.
///
/// Iterates over the region in XYZ order and returns the first solid voxel
/// found.  If the entire region is air or out of bounds, returns [`VoxelType::air`].
///
/// This "first-visible-wins" strategy returns the first voxel with non-zero
/// alpha (solid OR non-solid but colored, e.g. water).  Solid voxels are still
/// preferred over transparent-but-colored ones when both exist in the region.
#[inline]
pub(crate) fn super_voxel<V: VoxelType>(
    chunk: &Chunk<V>,
    sx: usize,
    sy: usize,
    sz: usize,
    step: usize,
) -> V {
    let mut first_visible = V::air();
    for dx in 0..step {
        for dy in 0..step {
            for dz in 0..step {
                let x = sx + dx;
                let y = sy + dy;
                let z = sz + dz;
                if x < CHUNK_SIZE && y < CHUNK_SIZE && z < CHUNK_SIZE {
                    let v = chunk.get(x, y, z);
                    if v.is_solid() {
                        return v; // solid wins immediately
                    }
                    if first_visible.color()[3] == 0.0 && v.color()[3] > 0.0 {
                        first_visible = v; // remember first non-air non-solid (e.g. water)
                    }
                }
            }
        }
    }
    first_visible
}

/// Generates a [`Mesh`] for a single chunk using greedy meshing.
///
/// This is the standalone variant: border faces that exit the chunk boundary
/// are always emitted as visible.  When adjacent chunks are loaded and their
/// data is available, prefer [`super::generate_chunk_mesh_with_neighbors`] to
/// avoid single-voxel gaps at chunk seams.
///
/// # Parameters
///
/// - `chunk` — The [`Chunk<V>`] to mesh.
/// - `step` — LOD step size.  `1` produces one voxel per grid cell (full
///   detail, LOD 0).  `2` groups each `2×2×2` block into a single super-voxel
///   (half detail, LOD 1).  Use [`super::lod::lod_to_step`] to convert a LOD
///   level to this value.
///
/// # Returns
///
/// A Bevy [`Mesh`] with [`bevy::mesh::PrimitiveTopology::TriangleList`]
/// topology.  The mesh contains the following vertex attributes:
///
/// - `ATTRIBUTE_POSITION` (`Float32x3`) — positions in chunk-local space.
/// - `ATTRIBUTE_NORMAL` (`Float32x3`) — outward face normals.
/// - `ATTRIBUTE_UV_0` (`Float32x2`) — UVs scaled by the merged quad size in
///   voxels, suitable for tiling textures.
/// - `ATTRIBUTE_COLOR` (`Float32x4`) — per-vertex color from [`VoxelType::color`].
/// - `U32` index buffer — CCW triangle winding in Bevy's right-hand coordinate system.
///
/// An all-air chunk produces a mesh with zero vertices and no index buffer entries.
///
/// # Examples
///
/// ```rust,no_run
/// use voxel_framework::{chunk::Chunk, mesh::generate_chunk_mesh, voxel::DefaultVoxel};
///
/// let mut chunk = Chunk::<DefaultVoxel>::new();
/// // ... fill chunk with voxel data ...
/// let mesh = generate_chunk_mesh(&chunk, 1); // full detail
/// let mesh_lod1 = generate_chunk_mesh(&chunk, 2); // half detail
/// ```
pub fn generate_chunk_mesh<V: VoxelType>(chunk: &Chunk<V>, step: usize) -> Mesh {
    crate::profile_span!("voxel::mesh::greedy");
    build_mesh(chunk, step, &default_face_visible::<V>)
}

/// The default face-visibility test: a face is visible if the neighbor in
/// the given direction does not fully occlude it.
///
/// A neighbor occludes a face only when it is both solid (`is_solid()`) **and**
/// fully opaque (`color()[3] >= 1.0`).  This matches the condition used in
/// [`build_mask`] — a voxel generates geometry when `color()[3] > 0.0` —
/// ensuring consistency: a neighbor that would itself generate no geometry
/// (alpha = 0) should never hide the current face.
///
/// At chunk borders, the neighbor is always treated as air (face visible).
#[inline]
fn default_face_visible<V: VoxelType>(
    chunk: &Chunk<V>,
    x: usize,
    y: usize,
    z: usize,
    face: &FaceDir,
    step: usize,
) -> bool {
    let (nx, ny, nz) = neighbor_coords(x, y, z, face, step);
    if nx >= CHUNK_SIZE || ny >= CHUNK_SIZE || nz >= CHUNK_SIZE {
        // Outside chunk bounds — treat as air (face visible).
        return true;
    }
    let neighbor = super_voxel(chunk, nx, ny, nz, step);
    !neighbor.is_solid() || neighbor.color()[3] < 1.0
}

/// Computes the neighbor coordinates in the direction of `face`, offset by `step`.
///
/// Uses wrapping arithmetic so that underflow (e.g., `0 - 1`) wraps to
/// `usize::MAX`, which is always `>= CHUNK_SIZE` and detected as out-of-bounds.
#[inline]
fn neighbor_coords(
    x: usize,
    y: usize,
    z: usize,
    face: &FaceDir,
    step: usize,
) -> (usize, usize, usize) {
    let mut result = [x, y, z];
    if face.positive {
        result[face.axis] = result[face.axis].wrapping_add(step);
    } else {
        result[face.axis] = result[face.axis].wrapping_sub(step);
    }
    (result[0], result[1], result[2])
}

/// Vertex and index data of one mesh being built.
#[derive(Default)]
pub(crate) struct MeshBuffers {
    positions: Vec<[f32; 3]>,
    normals: Vec<[f32; 3]>,
    uvs: Vec<[f32; 2]>,
    colors: Vec<[f32; 4]>,
    texture_layers: Vec<u32>,
    /// One value per vertex; filled after each quad, see `greedy_merge`.
    exposed: Vec<f32>,
    indices: Vec<u32>,
}

impl MeshBuffers {
    fn into_mesh(self) -> Mesh {
        Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        )
        .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, self.positions)
        .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, self.normals)
        .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, self.uvs)
        .with_inserted_attribute(Mesh::ATTRIBUTE_COLOR, self.colors)
        .with_inserted_attribute(ATTRIBUTE_TEXTURE_LAYER, self.texture_layers)
        .with_inserted_attribute(ATTRIBUTE_FACE_EXPOSED, self.exposed)
        .with_inserted_indices(Indices::U32(self.indices))
    }
}

/// Edge-chamfer settings of one mesh build.
pub(crate) struct Chamfer<'a, V> {
    /// Width of the cut on each face, in world units. Greater than zero.
    pub width: f32,
    /// The voxel at chunk-local coordinates, which may lie outside the chunk.
    /// `None` when the voxel is not known (a chunk that is not a face
    /// neighbor).
    pub sample: &'a dyn Fn([i32; 3]) -> Option<V>,
}

/// Edge bits of a mask cell: the edge of the face on that side is convex and
/// gets a chamfer.
const EDGE_LOW_U: u8 = 1;
const EDGE_HIGH_U: u8 = 2;
const EDGE_LOW_V: u8 = 4;
const EDGE_HIGH_V: u8 = 8;
/// Bit of a mask cell, next to the edge bits: the face was uncovered by an
/// edit. Cells only merge when it is equal.
const FACE_EXPOSED: u8 = 16;

/// A cell of the slice mask: the voxel, its state byte and its edge bits
/// (plus [`FACE_EXPOSED`]).
type MaskCell<V> = Option<(V, u8, u8)>;

/// Whether the voxel at `coords` is known to draw nothing.
#[inline]
fn is_empty_at<V: VoxelType>(chamfer: &Chamfer<V>, coords: [i32; 3]) -> bool {
    (chamfer.sample)(coords).is_some_and(|voxel| voxel.color()[3] <= 0.0)
}

/// Whether a voxel can have chamfered edges: only solid, opaque voxels.
#[inline]
fn is_chamferable<V: VoxelType>(voxel: V) -> bool {
    voxel.is_solid() && voxel.color()[3] >= 1.0
}

/// `coords` moved by `amount` along `axis`.
#[inline]
fn offset(mut coords: [i32; 3], axis: usize, amount: i32) -> [i32; 3] {
    coords[axis] += amount;
    coords
}

/// Whether the edge between two faces of the voxel at `coords` is chamfered.
/// The faces look along `axis_a` and `axis_b` with the given signs. The edge
/// is convex when the voxel is chamferable and nothing is drawn in front of
/// either face. The rule is the same seen from both faces, so the two halves
/// of a chamfer always agree.
#[inline]
fn is_convex_edge<V: VoxelType>(
    chamfer: &Chamfer<V>,
    coords: [i32; 3],
    (axis_a, sign_a): (usize, i32),
    (axis_b, sign_b): (usize, i32),
) -> bool {
    (chamfer.sample)(coords).is_some_and(is_chamferable)
        && is_empty_at(chamfer, offset(coords, axis_a, sign_a))
        && is_empty_at(chamfer, offset(coords, axis_b, sign_b))
}

/// The face-visibility callback of the mesh builders: chunk, voxel
/// coordinates, face direction and LOD step.
pub(crate) type FaceVisible<'a, V> =
    &'a dyn Fn(&Chunk<V>, usize, usize, usize, &FaceDir, usize) -> bool;

/// Core greedy mesh builder. The `face_visible` callback determines whether
/// a particular face should be emitted, allowing neighbor-aware variants to
/// plug in their own logic.
///
/// Every face goes into one mesh, whatever [`VoxelType::material`] says.
pub(crate) fn build_mesh<V: VoxelType>(
    chunk: &Chunk<V>,
    step: usize,
    face_visible: FaceVisible<V>,
) -> Mesh {
    build_material_meshes(chunk, step, face_visible, None, &|_| {
        TerrainMaterialId::DEFAULT
    })
    .pop()
    .map(|(_, mesh)| mesh)
    .unwrap_or_else(|| MeshBuffers::default().into_mesh())
}

/// Greedy mesh builder that returns one mesh per group of voxel types.
///
/// `material_of` routes each voxel to a group, normally its terrain material.
/// Only groups with at least one visible face are returned, sorted by key.
/// Merging never crosses a group, because quads only merge within one voxel
/// type.
pub(crate) fn build_material_meshes<V: VoxelType, K: Copy + Ord>(
    chunk: &Chunk<V>,
    step: usize,
    face_visible: FaceVisible<V>,
    chamfer: Option<&Chamfer<V>>,
    material_of: &dyn Fn(V) -> K,
) -> Vec<(K, Mesh)> {
    // Chamfers are full-detail geometry: coarse LOD meshes stay sharp.
    let chamfer = chamfer.filter(|chamfer| step == 1 && chamfer.width > 0.0);
    let size = CHUNK_SIZE / step;
    // A chunk holds few materials, so a small vector beats a map.
    let mut sections: Vec<(K, MeshBuffers)> = Vec::new();

    // Temporary mask buffer, reused across slices.
    // Each cell stores `Some((voxel, state, edges))` when the face is visible,
    // or `None` when it should be skipped.  Two cells are only merged when both
    // the voxel type AND the state byte match, ensuring that blocks placed
    // against different faces (which may use different textures) are never
    // incorrectly merged into a single quad.  The edge bits are all zero
    // unless edges are chamfered.
    let mut mask: Vec<MaskCell<V>> = vec![None; size * size];

    for (face_index, face) in FACE_DIRS.iter().enumerate() {
        for d in 0..size {
            // Build the 2D mask for this slice.
            build_mask(
                chunk,
                face,
                face_index,
                d,
                step,
                size,
                &mut mask,
                face_visible,
                chamfer,
            );

            // Greedy merge the mask into quads.
            greedy_merge(
                chunk,
                &mut mask,
                size,
                face,
                face_index,
                d,
                step,
                &mut sections,
                material_of,
                chamfer,
            );
        }
    }

    sections.sort_by_key(|(id, _)| *id);
    sections
        .into_iter()
        .map(|(id, buffers)| (id, buffers.into_mesh()))
        .collect()
}

/// Builds the 2D visibility mask for a single slice.
///
/// For each cell `(u, v)` in the slice plane, the mask contains
/// `Some((voxel, state))` if the super-voxel is solid and its face in the
/// current direction is visible (neighbor is air), or `None` otherwise.
/// The state byte is used by the greedy merge step to prevent cells with
/// different states from being merged into the same quad.
#[allow(clippy::too_many_arguments)] // Slice description plus the callbacks.
#[inline]
fn build_mask<V: VoxelType>(
    chunk: &Chunk<V>,
    face: &FaceDir,
    face_index: usize,
    d: usize,
    step: usize,
    size: usize,
    mask: &mut [MaskCell<V>],
    face_visible: FaceVisible<V>,
    chamfer: Option<&Chamfer<V>>,
) {
    for v in 0..size {
        for u in 0..size {
            // Convert (d, u, v) in slice space to (x, y, z) in chunk space.
            let (x, y, z) = slice_to_chunk(face, d * step, u * step, v * step);
            let voxel = super_voxel(chunk, x, y, z, step);
            // Render solid voxels AND non-solid voxels that have visible color
            // (e.g. water: alpha > 0 but is_solid = false).  Air (alpha = 0)
            // is always skipped.
            let has_color = voxel.color()[3] > 0.0;
            if has_color && face_visible(chunk, x, y, z, face, step) {
                let state = chunk.get_state(x, y, z);
                let mut edges = chamfer.map_or(0, |chamfer| {
                    convex_edges(chamfer, face, [x as i32, y as i32, z as i32])
                });
                if chunk.exposed_faces(x, y, z) & (1 << face_index) != 0 {
                    edges |= FACE_EXPOSED;
                }
                mask[v * size + u] = Some((voxel, state, edges));
            } else {
                mask[v * size + u] = None;
            }
        }
    }
}

/// The edge bits of the face `face` of the voxel at `coords`: which of its
/// four edges are convex and get a chamfer.
fn convex_edges<V: VoxelType>(chamfer: &Chamfer<V>, face: &FaceDir, coords: [i32; 3]) -> u8 {
    let front = (face.axis, if face.positive { 1 } else { -1 });
    let mut edges = 0;
    for (bit, side) in [
        (EDGE_LOW_U, (face.u_axis, -1)),
        (EDGE_HIGH_U, (face.u_axis, 1)),
        (EDGE_LOW_V, (face.v_axis, -1)),
        (EDGE_HIGH_V, (face.v_axis, 1)),
    ] {
        if is_convex_edge(chamfer, coords, front, side) {
            edges |= bit;
        }
    }
    edges
}

/// Converts slice-space coordinates `(d, u, v)` to chunk-space `(x, y, z)`.
#[inline]
fn slice_to_chunk(face: &FaceDir, d: usize, u: usize, v: usize) -> (usize, usize, usize) {
    let mut coords = [0usize; 3];
    coords[face.axis] = d;
    coords[face.u_axis] = u;
    coords[face.v_axis] = v;
    (coords[0], coords[1], coords[2])
}

/// Greedy-merges the mask and emits quads into the output buffers.
///
/// Two cells are merged only when both the voxel type AND the state byte are
/// identical.  This ensures that blocks placed against different faces — which
/// may map to different texture layers via
/// [`crate::voxel::VoxelType::texture_layer_for_state`] — are never collapsed
/// into a single quad that would display the wrong texture on part of it.
#[allow(clippy::too_many_arguments)] // Slice description plus the output; a wrapper struct adds no clarity.
fn greedy_merge<V: VoxelType, K: Copy + Ord>(
    chunk: &Chunk<V>,
    mask: &mut [MaskCell<V>],
    size: usize,
    face: &FaceDir,
    face_index: usize,
    d: usize,
    step: usize,
    sections: &mut Vec<(K, MeshBuffers)>,
    material_of: &dyn Fn(V) -> K,
    chamfer: Option<&Chamfer<V>>,
) {
    // A chamfered edge of a cell can only lie on the outline of a quad: a
    // convex edge has nothing drawn beside it, so the cell beside it is not in
    // the mask. A quad may therefore span cells with different edge bits, as
    // long as each of its four sides is convex along its whole length or not
    // at all. Without chamfers every edge bit is zero and the rules below
    // reduce to "same voxel, same state".
    const U_EDGES: u8 = EDGE_LOW_U | EDGE_HIGH_U;
    const V_EDGES: u8 = EDGE_LOW_V | EDGE_HIGH_V;

    for v in 0..size {
        let mut u = 0;
        while u < size {
            let (voxel, state, first_edges) = match mask[v * size + u] {
                Some(entry) => entry,
                None => {
                    u += 1;
                    continue;
                }
            };

            // Find width: extend in u while same voxel type AND same state,
            // and the sides along u (low v, high v) stay uniform.
            let mut width = 1;
            while u + width < size {
                match mask[v * size + u + width] {
                    Some((next_voxel, next_state, next_edges))
                        if next_voxel == voxel
                            && next_state == state
                            && next_edges & (V_EDGES | FACE_EXPOSED)
                                == first_edges & (V_EDGES | FACE_EXPOSED) =>
                    {
                        width += 1;
                    }
                    _ => break,
                }
            }
            let last_edges = mask[v * size + u + width - 1].map_or(0, |cell| cell.2);
            let mut quad_edges =
                (first_edges & (EDGE_LOW_U | V_EDGES)) | (last_edges & EDGE_HIGH_U);

            // Find height: extend in v while the entire row of width matches
            // and keeps the low-u and high-u sides as they are. A row whose
            // high-v side is convex only in part cannot join the quad.
            let mut height = 1;
            'outer: while v + height < size {
                let row = (v + height) * size + u;
                let mut row_high_v = None;
                for du in 0..width {
                    let Some((next_voxel, next_state, next_edges)) = mask[row + du] else {
                        break 'outer;
                    };
                    if next_voxel != voxel
                        || next_state != state
                        || next_edges & FACE_EXPOSED != first_edges & FACE_EXPOSED
                    {
                        break 'outer;
                    }
                    let mut expected_u = 0;
                    if du == 0 {
                        expected_u |= quad_edges & EDGE_LOW_U;
                    }
                    if du == width - 1 {
                        expected_u |= quad_edges & EDGE_HIGH_U;
                    }
                    if next_edges & U_EDGES != expected_u {
                        break 'outer;
                    }
                    let high_v = next_edges & EDGE_HIGH_V;
                    if *row_high_v.get_or_insert(high_v) != high_v {
                        break 'outer;
                    }
                }
                quad_edges = (quad_edges & !EDGE_HIGH_V) | row_high_v.unwrap_or(0);
                height += 1;
            }

            // Clear the merged region in the mask.
            for dv in 0..height {
                for du in 0..width {
                    mask[(v + dv) * size + u + du] = None;
                }
            }

            // Emit the quad into the mesh of the voxel's material.
            let material = material_of(voxel);
            let section = match sections.iter().position(|(id, _)| *id == material) {
                Some(index) => index,
                None => {
                    sections.push((material, MeshBuffers::default()));
                    sections.len() - 1
                }
            };
            emit_quad(
                chunk,
                face,
                face_index,
                d,
                u,
                v,
                width,
                height,
                step,
                voxel,
                state,
                quad_edges,
                chamfer,
                &mut sections[section].1,
            );
            // Every vertex of the quad, chamfer included, carries the flag.
            let buffers = &mut sections[section].1;
            let exposed = if first_edges & FACE_EXPOSED != 0 {
                1.0
            } else {
                0.0
            };
            buffers.exposed.resize(buffers.positions.len(), exposed);

            u += width;
        }
    }
}

/// Returns `true` if the voxel at `coords` (indexed by axis) is solid.
///
/// Any coordinate outside `[0, CHUNK_SIZE)` is treated as air (not solid),
/// using wrapping arithmetic so that `usize` underflow is detected as
/// out-of-bounds.
#[inline]
fn ao_neighbor_solid<V: VoxelType>(chunk: &Chunk<V>, coords: [usize; 3]) -> bool {
    if coords[0] >= CHUNK_SIZE || coords[1] >= CHUNK_SIZE || coords[2] >= CHUNK_SIZE {
        return false;
    }
    chunk.get(coords[0], coords[1], coords[2]).is_solid()
}

/// Computes the ambient occlusion factor for a single vertex corner.
///
/// Queries the two edge neighbors (`side1`, `side2`) and the diagonal
/// corner neighbor around the vertex in the tangent plane at the face
/// surface.  The classic voxel AO formula maps 0–3 occluders to the range
/// `[1.0, 0.4]`:
///
/// | Occluders | AO factor |
/// |-----------|-----------|
/// | 0         | 1.0       |
/// | 1         | 0.8       |
/// | 2         | 0.6       |
/// | 3         | 0.4       |
///
/// When both side neighbors are solid the corner is always fully occluded
/// (`0.4`) regardless of the actual corner voxel, matching standard voxel
/// AO behavior.
#[inline]
fn compute_ao(side1: bool, side2: bool, corner: bool) -> f32 {
    match side1 as u8 + side2 as u8 + corner as u8 {
        0 => 1.0,
        1 => 0.8,
        2 => 0.6,
        _ => 0.4,
    }
}

/// Computes the AO factor for one vertex of a quad.
///
/// `d_voxel` is the voxel-space coordinate along the face's primary axis
/// where the AO neighbors live (just beyond the face surface).
/// `cu_voxel` and `cv_voxel` are the corner's integer voxel coordinates
/// in the u and v tangent axes respectively.
///
/// The three neighbors are sampled using wrapping arithmetic; any sample
/// that falls outside `[0, CHUNK_SIZE)` on any axis is treated as air.
#[inline]
fn vertex_ao<V: VoxelType>(
    chunk: &Chunk<V>,
    face: &FaceDir,
    d_voxel: usize,
    cu_voxel: usize,
    cv_voxel: usize,
    high_u: bool,
    high_v: bool,
) -> f32 {
    // Four cells of the layer in front of the face meet at this corner. One of
    // them is in front of the quad itself (`own`) and is known to be empty;
    // the other three are the two sides and the diagonal. `wrapping_sub` turns
    // an underflow into usize::MAX, which reads as out of bounds (air).
    let (own_u, other_u) = if high_u {
        (cu_voxel.wrapping_sub(1), cu_voxel)
    } else {
        (cu_voxel, cu_voxel.wrapping_sub(1))
    };
    let (own_v, other_v) = if high_v {
        (cv_voxel.wrapping_sub(1), cv_voxel)
    } else {
        (cv_voxel, cv_voxel.wrapping_sub(1))
    };
    let solid_at = |u: usize, v: usize| {
        let mut coords = [0usize; 3];
        coords[face.axis] = d_voxel;
        coords[face.u_axis] = u;
        coords[face.v_axis] = v;
        ao_neighbor_solid(chunk, coords)
    };

    compute_ao(
        solid_at(other_u, own_v),
        solid_at(own_u, other_v),
        solid_at(other_u, other_v),
    )
}

/// Emits a single quad (4 vertices, 6 indices) for a merged rectangle.
///
/// Per-vertex ambient occlusion is computed by sampling the three voxels
/// surrounding each corner in the tangent plane at the face surface.  The AO
/// factor darkens the vertex color's RGB channels while leaving alpha intact.
/// The quad's triangulation is flipped when needed to avoid the AO anisotropy
/// seam artifact described in Mikola Lysenko's original voxel AO paper.
#[allow(clippy::too_many_arguments)] // The quad's place in the slice plus the output.
#[inline]
fn emit_quad<V: VoxelType>(
    chunk: &Chunk<V>,
    face: &FaceDir,
    face_index: usize,
    d: usize,
    u: usize,
    v: usize,
    width: usize,
    height: usize,
    step: usize,
    voxel: V,
    state: u8,
    edges: u8,
    chamfer: Option<&Chamfer<V>>,
    out: &mut MeshBuffers,
) {
    let MeshBuffers {
        positions,
        normals,
        uvs,
        colors,
        texture_layers,
        indices,
        ..
    } = out;
    let s = step as f32 * VOXEL_SIZE;

    // The slice position along the primary axis.
    // For positive faces, the quad sits at (d + 1) * step (the far side of the voxel).
    // For negative faces, the quad sits at d * step (the near side).
    let d_pos = if face.positive {
        (d as f32 + 1.0) * s
    } else {
        d as f32 * s
    };

    // The voxel-space depth coordinate for AO sampling.
    // For a positive face, the visible surface is the +face.axis side of voxel d*step,
    // so the AO neighbors live at (d+1)*step (the first layer beyond the surface).
    // For a negative face, the surface is the -face.axis side of voxel d*step,
    // so AO neighbors live at d*step - 1 (wrapping; out-of-bounds → treated as air).
    let ao_depth: usize = if face.positive {
        (d + 1) * step
    } else {
        // At d == 0 this underflows to usize::MAX, which is out of bounds, so
        // every AO neighbor reads as air.
        (d * step).wrapping_sub(1)
    };

    let u_start = u as f32 * s;
    let v_start = v as f32 * s;
    let u_end = (u + width) as f32 * s;
    let v_end = (v + height) as f32 * s;

    // AO for each of the 4 corners, sampled in the layer in front of the face.
    // The flags say whether the corner is at the high-u / high-v end of the
    // quad, which tells `vertex_ao` on which side of the corner the quad lies.
    let (u0, v0) = (u * step, v * step);
    let (u1, v1) = ((u + width) * step, (v + height) * step);
    let ao_v0 = vertex_ao(chunk, face, ao_depth, u0, v0, false, false);
    let ao_v1 = vertex_ao(chunk, face, ao_depth, u1, v0, true, false);
    let ao_v2 = vertex_ao(chunk, face, ao_depth, u1, v1, true, true);
    let ao_v3 = vertex_ao(chunk, face, ao_depth, u0, v1, false, true);

    // With chamfered edges the face ends short of each convex side.
    let cut = chamfer.map_or(0.0, |chamfer| chamfer.width);
    let inset = |bit: u8| if edges & bit != 0 { cut } else { 0.0 };
    let face_u = [u_start + inset(EDGE_LOW_U), u_end - inset(EDGE_HIGH_U)];
    let face_v = [v_start + inset(EDGE_LOW_V), v_end - inset(EDGE_HIGH_V)];

    // Build the 4 corner positions in chunk-local space.
    // Corners in (u, v) order: (low, low), (high, low), (high, high), (low, high)
    let corners = [
        (face_u[0], face_v[0], ao_v0),
        (face_u[1], face_v[0], ao_v1),
        (face_u[1], face_v[1], ao_v2),
        (face_u[0], face_v[1], ao_v3),
    ];

    let base_idx = positions.len() as u32;
    // VoxelType::color() returns sRGB values (as humans define them).
    // The ChunkMaterial shader treats ATTRIBUTE_COLOR as linear RGB (used for AO),
    // so we convert here. The shader multiplies texture color by vertex color to
    // apply the baked AO.
    let srgb = voxel.color();
    let to_linear = |c: f32| -> f32 {
        if c <= 0.04045 {
            c / 12.92
        } else {
            ((c + 0.055) / 1.055).powf(2.4)
        }
    };
    let base_color = [
        to_linear(srgb[0]),
        to_linear(srgb[1]),
        to_linear(srgb[2]),
        srgb[3],
    ];

    // Texture layer for this face — same for all 4 vertices.
    // Uses texture_layer_for_state so that voxels with different placement
    // states can map to different texture layers (e.g. a log showing end-grain
    // on its top/bottom faces).  The default implementation ignores state and
    // delegates to texture_layer, so existing code is unaffected.
    let layer = voxel.texture_layer_for_state(face_index, state);

    for &(cu, cv, ao) in &corners {
        let mut pos = [0.0f32; 3];
        pos[face.axis] = d_pos;
        pos[face.u_axis] = cu;
        pos[face.v_axis] = cv;
        positions.push(pos);
        normals.push(face.normal);
        // Multiply linear RGB by the AO factor; alpha is left unchanged.
        // When ChunkMaterial is active the RGB carries the AO value (1.0 = no
        // occlusion, 0.4 = fully occluded). The shader multiplies the sampled
        // texture color by this value to apply AO.
        colors.push([
            base_color[0] * ao,
            base_color[1] * ao,
            base_color[2] * ao,
            base_color[3],
        ]);
        texture_layers.push(layer);
    }

    // UVs fixed to 0→1 per quad so the texture is displayed once per face
    // regardless of the merged quad size.  Tiling is intentionally disabled —
    // the texture array layers already contain the correct per-voxel texture.
    // A face cut by a chamfer keeps the part of the texture it still covers.
    let uv_of = |cu: f32, cv: f32| {
        [
            (cu - u_start) / (u_end - u_start),
            (cv - v_start) / (v_end - v_start),
        ]
    };
    for &(cu, cv, _) in &corners {
        uvs.push(uv_of(cu, cv));
    }

    // Two triangles with CCW winding when viewed from the normal direction.
    // Bevy uses a right-hand coordinate system with CCW front faces.
    //
    // Cross-product analysis per face:
    //   axis=0 (+X/-X) and axis=1 (+Y/-Y): positive faces need (0,2,1),(0,3,2)
    //   and negative faces need (0,1,2),(0,2,3).
    //
    //   axis=2 (+Z/-Z): the u=X, v=Y tangent frame is left-handed relative to
    //   +Z, so the winding must be inverted — positive Z needs (0,1,2),(0,2,3)
    //   and negative Z needs (0,2,1),(0,3,2).
    //
    // A single XOR captures this: flip when (positive XOR axis==2) is false,
    // i.e. use the "CCW" branch when face.positive != (face.axis == 2).
    //
    // Additionally, flip the triangulation when ao_v0 + ao_v2 < ao_v1 + ao_v3.
    // This avoids the AO anisotropy seam artifact (Mikola Lysenko's fix).
    //
    // IMPORTANT: the flip must switch the DIAGONAL used to split the quad, NOT
    // the winding direction.  Inverting the winding would reverse the face
    // normal and cause Bevy's back-face culling to discard the triangle —
    // producing transparent holes.  Each case below independently maintains
    // correct CCW / CW winding while using the other diagonal (v1-v3 instead
    // of the default v0-v2) when `ao_flip` is true.
    //
    // Quad vertex layout (u increases right, v increases up):
    //   v3 --- v2
    //   |       |
    //   v0 --- v1
    //
    // Default diagonal v0-v2: triangles (v0,v2,v1) + (v0,v3,v2)  [CCW]
    //                                or (v0,v1,v2) + (v0,v2,v3)  [CW]
    // Alt diagonal    v1-v3: triangles (v0,v3,v1) + (v1,v3,v2)  [CCW]
    //                                or (v0,v1,v3) + (v1,v2,v3)  [CW]
    let ao_flip = ao_v0 + ao_v2 < ao_v1 + ao_v3;
    let ccw = face.positive != (face.axis == 2);
    match (ccw, ao_flip) {
        (true, false) => {
            // Default diagonal, CCW winding.
            indices.push(base_idx);
            indices.push(base_idx + 2);
            indices.push(base_idx + 1);
            indices.push(base_idx);
            indices.push(base_idx + 3);
            indices.push(base_idx + 2);
        }
        (true, true) => {
            // Alt diagonal (v1-v3), CCW winding — avoids AO seam.
            indices.push(base_idx);
            indices.push(base_idx + 3);
            indices.push(base_idx + 1);
            indices.push(base_idx + 1);
            indices.push(base_idx + 3);
            indices.push(base_idx + 2);
        }
        (false, false) => {
            // Default diagonal, CW winding.
            indices.push(base_idx);
            indices.push(base_idx + 1);
            indices.push(base_idx + 2);
            indices.push(base_idx);
            indices.push(base_idx + 2);
            indices.push(base_idx + 3);
        }
        (false, true) => {
            // Alt diagonal (v1-v3), CW winding — avoids AO seam.
            indices.push(base_idx);
            indices.push(base_idx + 1);
            indices.push(base_idx + 3);
            indices.push(base_idx + 1);
            indices.push(base_idx + 2);
            indices.push(base_idx + 3);
        }
    }

    let Some(chamfer) = chamfer.filter(|_| edges != 0) else {
        return;
    };

    // ── Chamfers ─────────────────────────────────────────────────────────
    //
    // Each face draws its own half of every chamfer on its convex sides: a
    // strip from the cut edge of the face to the middle of the chamfer, a
    // piece of the triangle where three chamfers meet at a corner, and half
    // of the cap that closes a chamfer ending against another voxel. The
    // neighboring face draws the other halves by the same rules.
    let sign = if face.positive { 1.0 } else { -1.0 };
    let face_sign = if face.positive { 1 } else { -1 };
    // A point at tangent coordinates (cu, cv), `depth` below the face plane.
    let point = |cu: f32, cv: f32, depth: f32| {
        let mut pos = [0.0f32; 3];
        pos[face.axis] = d_pos - sign * depth;
        pos[face.u_axis] = cu;
        pos[face.v_axis] = cv;
        pos
    };
    // A direction: `along_u` and `along_v` in the tangent plane, `out` along
    // the face normal.
    let direction = |along_u: f32, along_v: f32, out: f32| {
        let mut dir = [0.0f32; 3];
        dir[face.axis] = sign * out;
        dir[face.u_axis] = along_u;
        dir[face.v_axis] = along_v;
        dir
    };
    let ao_at = |high_u: bool, high_v: bool| match (high_u, high_v) {
        (false, false) => ao_v0,
        (true, false) => ao_v1,
        (true, true) => ao_v2,
        (false, true) => ao_v3,
    };
    let color_at = |high_u: bool, high_v: bool| {
        let ao = ao_at(high_u, high_v);
        [
            base_color[0] * ao,
            base_color[1] * ao,
            base_color[2] * ao,
            base_color[3],
        ]
    };
    let half = cut * 0.5;
    let third = cut * 2.0 / 3.0;
    // Voxel coordinates of the cell at a corner of the quad.
    let cell_at = |high_u: bool, high_v: bool| {
        let mut coords = [0i32; 3];
        coords[face.axis] = d as i32;
        coords[face.u_axis] = if high_u { u + width - 1 } else { u } as i32;
        coords[face.v_axis] = if high_v { v + height - 1 } else { v } as i32;
        coords
    };
    let mut push = |points: &[[f32; 3]], normal: [f32; 3], vertices: &[([f32; 2], [f32; 4])]| {
        push_polygon(
            positions,
            normals,
            uvs,
            colors,
            texture_layers,
            indices,
            points,
            normal,
            vertices,
            layer,
        );
    };

    // The two sides along v (low u, high u).
    for (high_u, bit) in [(false, EDGE_LOW_U), (true, EDGE_HIGH_U)] {
        if edges & bit == 0 {
            continue;
        }
        let (edge_u, inward) = if high_u {
            (u_end, -1.0)
        } else {
            (u_start, 1.0)
        };
        let cut_u = edge_u + inward * cut;
        let mid_u = edge_u + inward * half;
        let low = (uv_of(cut_u, face_v[0]), color_at(high_u, false));
        let high = (uv_of(cut_u, face_v[1]), color_at(high_u, true));
        push(
            &[
                point(cut_u, face_v[0], 0.0),
                point(cut_u, face_v[1], 0.0),
                point(mid_u, face_v[1], half),
                point(mid_u, face_v[0], half),
            ],
            direction(-inward, 0.0, 1.0),
            &[low, high, high, low],
        );
        // Ends of the strip: a corner piece where the other side is convex
        // too, otherwise a cap unless the chamfer goes on in the next voxel.
        for (high_v, end_bit) in [(false, EDGE_LOW_V), (true, EDGE_HIGH_V)] {
            let (edge_v, inward_v) = if high_v {
                (v_end, -1.0)
            } else {
                (v_start, 1.0)
            };
            let vertex = (
                uv_of(cut_u, if high_v { face_v[1] } else { face_v[0] }),
                color_at(high_u, high_v),
            );
            if edges & end_bit != 0 {
                // Drawn once per corner, by the low-u/high-u loop.
                push(
                    &[
                        point(cut_u, edge_v + inward_v * cut, 0.0),
                        point(mid_u, edge_v + inward_v * cut, half),
                        point(edge_u + inward * third, edge_v + inward_v * third, third),
                        point(cut_u, edge_v + inward_v * half, half),
                    ],
                    direction(-inward, -inward_v, 1.0),
                    &[vertex; 4],
                );
            } else {
                let beyond = offset(
                    cell_at(high_u, high_v),
                    face.v_axis,
                    if high_v { 1 } else { -1 },
                );
                let continues = is_convex_edge(
                    chamfer,
                    beyond,
                    (face.axis, face_sign),
                    (face.u_axis, if high_u { 1 } else { -1 }),
                );
                if !continues {
                    push(
                        &[
                            point(edge_u, edge_v, 0.0),
                            point(cut_u, edge_v, 0.0),
                            point(mid_u, edge_v, half),
                        ],
                        // The cap faces the open end of the chamfer.
                        direction(0.0, inward_v, 0.0),
                        &[vertex; 3],
                    );
                }
            }
        }
    }

    // The two sides along u (low v, high v).
    for (high_v, bit) in [(false, EDGE_LOW_V), (true, EDGE_HIGH_V)] {
        if edges & bit == 0 {
            continue;
        }
        let (edge_v, inward) = if high_v {
            (v_end, -1.0)
        } else {
            (v_start, 1.0)
        };
        let cut_v = edge_v + inward * cut;
        let mid_v = edge_v + inward * half;
        let low = (uv_of(face_u[0], cut_v), color_at(false, high_v));
        let high = (uv_of(face_u[1], cut_v), color_at(true, high_v));
        push(
            &[
                point(face_u[0], cut_v, 0.0),
                point(face_u[1], cut_v, 0.0),
                point(face_u[1], mid_v, half),
                point(face_u[0], mid_v, half),
            ],
            direction(0.0, -inward, 1.0),
            &[low, high, high, low],
        );
        for (high_u, end_bit) in [(false, EDGE_LOW_U), (true, EDGE_HIGH_U)] {
            if edges & end_bit != 0 {
                continue; // The corner piece is already drawn.
            }
            let (edge_u, inward_u) = if high_u {
                (u_end, -1.0)
            } else {
                (u_start, 1.0)
            };
            let beyond = offset(
                cell_at(high_u, high_v),
                face.u_axis,
                if high_u { 1 } else { -1 },
            );
            let continues = is_convex_edge(
                chamfer,
                beyond,
                (face.axis, face_sign),
                (face.v_axis, if high_v { 1 } else { -1 }),
            );
            if !continues {
                let vertex = (uv_of(edge_u, cut_v), color_at(high_u, high_v));
                push(
                    &[
                        point(edge_u, edge_v, 0.0),
                        point(edge_u, cut_v, 0.0),
                        point(edge_u, mid_v, half),
                    ],
                    direction(inward_u, 0.0, 0.0),
                    &[vertex; 3],
                );
            }
        }
    }
}

/// Appends a flat triangle or quad with the given facet normal. The winding
/// is chosen so the front of the polygon faces along `normal`. `vertices`
/// holds the UV and color of each point.
#[allow(clippy::too_many_arguments)] // The output buffers of one mesh.
fn push_polygon(
    positions: &mut Vec<[f32; 3]>,
    normals: &mut Vec<[f32; 3]>,
    uvs: &mut Vec<[f32; 2]>,
    colors: &mut Vec<[f32; 4]>,
    texture_layers: &mut Vec<u32>,
    indices: &mut Vec<u32>,
    points: &[[f32; 3]],
    normal: [f32; 3],
    vertices: &[([f32; 2], [f32; 4])],
    layer: u32,
) {
    let sub = |a: [f32; 3], b: [f32; 3]| [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
    let ab = sub(points[1], points[0]);
    let ac = sub(points[2], points[0]);
    let cross = [
        ab[1] * ac[2] - ab[2] * ac[1],
        ab[2] * ac[0] - ab[0] * ac[2],
        ab[0] * ac[1] - ab[1] * ac[0],
    ];
    let facing = cross[0] * normal[0] + cross[1] * normal[1] + cross[2] * normal[2];
    let length = (normal[0] * normal[0] + normal[1] * normal[1] + normal[2] * normal[2]).sqrt();
    let unit = [normal[0] / length, normal[1] / length, normal[2] / length];

    let base = positions.len() as u32;
    for (point, (uv, color)) in points.iter().zip(vertices) {
        positions.push(*point);
        normals.push(unit);
        uvs.push(*uv);
        colors.push(*color);
        texture_layers.push(layer);
    }
    for i in 1..points.len() as u32 - 1 {
        if facing >= 0.0 {
            indices.extend([base, base + i, base + i + 1]);
        } else {
            indices.extend([base, base + i + 1, base + i]);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::voxel::DefaultVoxel;
    use bevy::mesh::VertexAttributeValues;

    /// Helper to extract vertex count from a mesh.
    fn vertex_count(mesh: &Mesh) -> usize {
        match mesh.attribute(Mesh::ATTRIBUTE_POSITION).expect("positions") {
            VertexAttributeValues::Float32x3(v) => v.len(),
            _ => panic!("unexpected attribute type"),
        }
    }

    /// Helper to extract index count from a mesh.
    fn index_count(mesh: &Mesh) -> usize {
        match mesh.indices().expect("indices") {
            Indices::U32(idx) => idx.len(),
            _ => panic!("expected U32 indices"),
        }
    }

    /// AO factors of the four vertices of the quad with this normal lying on
    /// the plane `coordinate == plane` along the normal's axis, sorted.
    fn quad_ao(mesh: &Mesh, normal: [f32; 3], plane: f32) -> Vec<f32> {
        let axis = normal.iter().position(|n| *n != 0.0).expect("axis normal");
        let Some(VertexAttributeValues::Float32x3(positions)) =
            mesh.attribute(Mesh::ATTRIBUTE_POSITION)
        else {
            panic!("positions");
        };
        let Some(VertexAttributeValues::Float32x3(normals)) =
            mesh.attribute(Mesh::ATTRIBUTE_NORMAL)
        else {
            panic!("normals");
        };
        let Some(VertexAttributeValues::Float32x4(colors)) = mesh.attribute(Mesh::ATTRIBUTE_COLOR)
        else {
            panic!("colors");
        };
        let brightest = colors.iter().map(|c| c[0]).fold(0.0f32, f32::max);
        let mut ao: Vec<f32> = (0..positions.len())
            .filter(|&i| normals[i] == normal && positions[i][axis] == plane)
            .map(|i| (colors[i][0] / brightest * 10.0).round() / 10.0)
            .collect();
        assert_eq!(ao.len(), 4, "expected exactly one quad on that plane");
        ao.sort_by(f32::total_cmp);
        ao
    }

    /// A chunk with one voxel at (5, 5, 5) and one occluder.
    fn voxel_with_occluder(occluder: [usize; 3]) -> Chunk<DefaultVoxel> {
        let mut chunk = Chunk::<DefaultVoxel>::new();
        chunk.set(5, 5, 5, DefaultVoxel::Rock);
        chunk.set(occluder[0], occluder[1], occluder[2], DefaultVoxel::Rock);
        chunk
    }

    #[test]
    fn a_voxel_beside_a_face_darkens_the_two_vertices_on_that_edge() {
        // Each case: the face normal, the plane of the face of (5, 5, 5), and
        // an occluder in the layer in front of that face, beside it.
        let cases: [([f32; 3], f32, [usize; 3]); 12] = [
            ([0.0, 1.0, 0.0], 6.0, [6, 6, 5]),
            ([0.0, 1.0, 0.0], 6.0, [4, 6, 5]),
            ([0.0, 1.0, 0.0], 6.0, [5, 6, 6]),
            ([0.0, 1.0, 0.0], 6.0, [5, 6, 4]),
            ([0.0, -1.0, 0.0], 5.0, [6, 4, 5]),
            ([0.0, -1.0, 0.0], 5.0, [5, 4, 4]),
            ([1.0, 0.0, 0.0], 6.0, [6, 6, 5]),
            ([1.0, 0.0, 0.0], 6.0, [6, 5, 4]),
            ([-1.0, 0.0, 0.0], 5.0, [4, 6, 5]),
            ([-1.0, 0.0, 0.0], 5.0, [4, 5, 6]),
            ([0.0, 0.0, 1.0], 6.0, [6, 5, 6]),
            ([0.0, 0.0, -1.0], 5.0, [5, 4, 4]),
        ];
        for (normal, plane, occluder) in cases {
            let mesh = generate_chunk_mesh(&voxel_with_occluder(occluder), 1);
            assert_eq!(
                quad_ao(&mesh, normal, plane),
                vec![0.8, 0.8, 1.0, 1.0],
                "normal {normal:?}, occluder {occluder:?}"
            );
        }
    }

    #[test]
    fn a_voxel_diagonal_to_a_face_darkens_only_the_vertex_at_that_corner() {
        let cases: [([f32; 3], f32, [usize; 3]); 8] = [
            ([0.0, 1.0, 0.0], 6.0, [4, 6, 4]),
            ([0.0, 1.0, 0.0], 6.0, [6, 6, 4]),
            ([0.0, 1.0, 0.0], 6.0, [6, 6, 6]),
            ([0.0, 1.0, 0.0], 6.0, [4, 6, 6]),
            ([0.0, -1.0, 0.0], 5.0, [6, 4, 6]),
            ([-1.0, 0.0, 0.0], 5.0, [4, 6, 6]),
            ([1.0, 0.0, 0.0], 6.0, [6, 4, 4]),
            ([0.0, 0.0, -1.0], 5.0, [6, 6, 4]),
        ];
        for (normal, plane, occluder) in cases {
            let mesh = generate_chunk_mesh(&voxel_with_occluder(occluder), 1);
            assert_eq!(
                quad_ao(&mesh, normal, plane),
                vec![0.8, 1.0, 1.0, 1.0],
                "normal {normal:?}, occluder {occluder:?}"
            );
        }
    }

    #[test]
    fn a_lone_voxel_has_no_ambient_occlusion() {
        let mut chunk = Chunk::<DefaultVoxel>::new();
        chunk.set(5, 5, 5, DefaultVoxel::Rock);
        let mesh = generate_chunk_mesh(&chunk, 1);
        for (normal, plane) in [
            ([0.0, 1.0, 0.0], 6.0),
            ([0.0, -1.0, 0.0], 5.0),
            ([1.0, 0.0, 0.0], 6.0),
            ([-1.0, 0.0, 0.0], 5.0),
            ([0.0, 0.0, 1.0], 6.0),
            ([0.0, 0.0, -1.0], 5.0),
        ] {
            assert_eq!(quad_ao(&mesh, normal, plane), vec![1.0; 4]);
        }
    }

    #[test]
    fn empty_chunk_produces_empty_mesh() {
        let chunk = Chunk::<DefaultVoxel>::new();
        let mesh = generate_chunk_mesh(&chunk, 1);
        assert_eq!(
            vertex_count(&mesh),
            0,
            "empty chunk should produce 0 vertices"
        );
    }

    #[test]
    fn fully_solid_chunk_produces_six_quads() {
        let mut chunk = Chunk::<DefaultVoxel>::new();
        for x in 0..CHUNK_SIZE {
            for y in 0..CHUNK_SIZE {
                for z in 0..CHUNK_SIZE {
                    chunk.set(x, y, z, DefaultVoxel::Rock);
                }
            }
        }
        let mesh = generate_chunk_mesh(&chunk, 1);

        assert_eq!(
            vertex_count(&mesh),
            24,
            "fully solid chunk should have 24 vertices (4 per face x 6 faces)"
        );
        assert_eq!(
            index_count(&mesh),
            36,
            "fully solid chunk should have 36 indices (6 per face x 6 faces)"
        );
    }

    #[test]
    fn single_voxel_produces_six_faces() {
        let mut chunk = Chunk::<DefaultVoxel>::new();
        chunk.set(0, 0, 0, DefaultVoxel::Rock);
        let mesh = generate_chunk_mesh(&chunk, 1);

        assert_eq!(
            vertex_count(&mesh),
            24,
            "single voxel should have 24 vertices (4 per face x 6 faces)"
        );
        assert_eq!(
            index_count(&mesh),
            36,
            "single voxel should have 36 indices (6 per face x 6 faces)"
        );
    }

    #[test]
    fn lod_mesh_has_fewer_vertices() {
        // Create a chunk with a checkerboard pattern of two different voxel
        // types. At LOD 0, the greedy mesher cannot merge across different
        // types, producing many quads. At LOD 1, each 2x2x2 super-voxel
        // collapses to a single type, enabling much more merging.
        let mut chunk = Chunk::<DefaultVoxel>::new();
        for x in 0..CHUNK_SIZE {
            for y in 0..CHUNK_SIZE {
                for z in 0..CHUNK_SIZE {
                    if (x + y + z) % 2 == 0 {
                        chunk.set(x, y, z, DefaultVoxel::Rock);
                    } else {
                        chunk.set(x, y, z, DefaultVoxel::IronOre);
                    }
                }
            }
        }

        let mesh_lod0 = generate_chunk_mesh(&chunk, 1);
        let mesh_lod1 = generate_chunk_mesh(&chunk, 2);

        let count_lod0 = vertex_count(&mesh_lod0);
        let count_lod1 = vertex_count(&mesh_lod1);

        assert!(
            count_lod1 < count_lod0,
            "LOD 1 ({count_lod1} verts) should have fewer vertices than LOD 0 ({count_lod0} verts)"
        );
    }
}