bevy_isomesh 0.0.13

Bevy integration for isomesh: signed distance field in, Bevy Mesh out.
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
//! Writing an extracted surface into a Bevy [`Mesh`](bevy_mesh::Mesh).

use bevy_asset::RenderAssetUsages;
use bevy_mesh::{Indices, Mesh, PrimitiveTopology, VertexAttributeValues};
use isomesh::{MeshBuffer, MeshSink};

/// A [`MeshSink`] whose buffers are exactly the arrays a Bevy [`Mesh`] wants.
///
/// An extractor writes into this directly, so the vertex data is never copied on
/// its way into the asset — [`into_mesh`](Self::into_mesh) hands the `Vec`s over
/// by move. That is the whole point of the type; if you already have an
/// [`isomesh::MeshBuffer`] you are reusing across chunks, use [`to_bevy_mesh`]
/// instead and accept the copy.
///
/// # Example
///
/// ```
/// use bevy_isomesh::MeshBuilder;
/// use isomesh::fields::Sphere;
/// use isomesh::marching_cubes::MarchingCubes;
/// use isomesh::RuntimeShape3;
///
/// let mut builder = MeshBuilder::new();
/// let mut mc = MarchingCubes::<f32>::new();
/// let shape = RuntimeShape3::new([33; 3]).expect("valid shape");
/// mc.extract(&Sphere::<f32>::canonical(), &shape, [-2.0; 3], 0.125, &mut builder).expect("extraction");
///
/// let mesh = builder.into_mesh();
/// assert!(mesh.count_vertices() > 0);
/// ```
#[derive(Clone, Debug)]
pub struct MeshBuilder {
    positions: Vec<[f32; 3]>,
    normals: Vec<[f32; 3]>,
    uvs: Vec<[f32; 2]>,
    colors: Vec<[f32; 4]>,
    indices: Vec<u32>,
    uv_scale: f32,
}

impl MeshBuilder {
    /// An empty builder.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            positions: Vec::new(),
            normals: Vec::new(),
            uvs: Vec::new(),
            colors: Vec::new(),
            indices: Vec::new(),
            uv_scale: 1.0,
        }
    }

    /// How many world units one texture repeat spans. Default `1.0`.
    #[must_use]
    pub const fn with_uv_scale(mut self, scale: f32) -> Self {
        self.uv_scale = scale;
        self
    }

    /// Truncate without releasing capacity, so one builder can serve many chunks.
    pub fn reset(&mut self) {
        self.positions.clear();
        self.normals.clear();
        self.uvs.clear();
        self.colors.clear();
        self.indices.clear();
    }

    /// Vertices written so far.
    #[must_use]
    pub fn vertex_count(&self) -> usize {
        self.positions.len()
    }

    /// Triangles written so far.
    #[must_use]
    pub fn triangle_count(&self) -> usize {
        self.indices.len() / 3
    }

    /// The positions written so far.
    ///
    /// Present so a caller can run the core crate's validity harness on exactly
    /// the data it is about to hand to the renderer, rather than on a
    /// reconstruction of it.
    #[must_use]
    pub fn positions(&self) -> &[[f32; 3]] {
        &self.positions
    }

    /// The normals written so far.
    #[must_use]
    pub fn normals(&self) -> &[[f32; 3]] {
        &self.normals
    }

    /// The flat index triples written so far.
    #[must_use]
    pub fn indices(&self) -> &[u32] {
        &self.indices
    }

    /// The per-vertex colour buffer, to be filled or left alone.
    ///
    /// Handed out mutably so
    /// [`isomesh::paint::shade`] can write straight into
    /// the array the [`Mesh`] will own, on the same no-copy reasoning as the
    /// rest of this type:
    ///
    /// ```ignore
    /// isomesh::paint::shade(builder.positions(), &world, builder.colors_mut());
    /// ```
    ///
    /// The two borrows in that line are one shared and one mutable, so the
    /// compiler will not take it as written. Use
    /// [`positions_and_colors_mut`](Self::positions_and_colors_mut), which hands
    /// out both at once from disjoint fields — **not** a scratch buffer and a
    /// swap, which is an allocation per call and, at re-meshing scale, an
    /// allocation per chunk per edit (B-008).
    ///
    /// A mesh either carries colours or does not, exactly as it either carries
    /// UVs or does not: leave this empty and
    /// [`into_mesh`](Self::into_mesh) omits the attribute entirely. That is one
    /// path writing one attribute, not a fallback — there is no second way to
    /// get a colour onto a vertex here.
    pub fn colors_mut(&mut self) -> &mut Vec<[f32; 4]> {
        &mut self.colors
    }

    /// The positions to read and the colours to write, borrowed together.
    ///
    /// `shade(builder.positions(), world, builder.colors_mut())` is the natural
    /// way to write a shading pass and the compiler rejects it: one shared and
    /// one mutable borrow of the same value. The two obvious workarounds both
    /// cost something — cloning the positions, or shading into a scratch `Vec`
    /// and swapping it in — and at re-meshing scale that is **an allocation per
    /// chunk per edit**, which is the pattern the core crate's rule 6 exists to
    /// prevent, one workspace over (B-008).
    ///
    /// The fields are disjoint, so there is nothing to work around: this hands
    /// out both borrows at once and the pass writes straight into the array the
    /// [`Mesh`] will own.
    ///
    /// ```
    /// # use bevy_isomesh::MeshBuilder;
    /// # let mut builder = MeshBuilder::new();
    /// let (positions, colors) = builder.positions_and_colors_mut();
    /// colors.clear();
    /// colors.extend(positions.iter().map(|p| [p[0], p[1], p[2], 1.0]));
    /// ```
    pub fn positions_and_colors_mut(&mut self) -> (&[[f32; 3]], &mut Vec<[f32; 4]>) {
        (&self.positions, &mut self.colors)
    }

    /// The per-vertex colours written so far.
    #[must_use]
    pub fn colors(&self) -> &[[f32; 4]] {
        &self.colors
    }

    /// Hand the arrays to a Bevy [`Mesh`], by move.
    ///
    /// Consuming rather than borrowing is deliberate: a `Mesh` owns its vertex
    /// data, so the choice is between transferring ownership and copying, and
    /// this is the transfer. Use [`to_bevy_mesh`] when you would rather keep the
    /// buffer and pay for a copy.
    ///
    /// # Colours are present or absent
    ///
    /// [`Mesh::ATTRIBUTE_COLOR`] is inserted when
    /// [`colors_mut`](Self::colors_mut) was filled and omitted when it was not.
    /// `StandardMaterial` multiplies its `base_color` by the vertex colour, so
    /// padding every mesh with opaque white would be a no-op that still costs
    /// 16 bytes a vertex on the twenty-odd examples that do not paint anything.
    ///
    /// A mismatched length is a caller error and is **not** silently repaired.
    /// Bevy would not catch it either: `bevy_mesh` 0.19 only *warns* on a
    /// short attribute and then truncates **every** attribute to the shortest
    /// (`count_vertices`, "all attributes will be truncated to match the
    /// smallest") — while the inserted indices keep referencing the full
    /// vertex range. That is silently corrupted rendering far from the cause,
    /// so the mismatch is refused here, at the door.
    ///
    /// # An empty mesh stays out of the render world
    ///
    /// A builder that received no vertices — a chunk the surface does not
    /// cross — becomes a mesh with [`RenderAssetUsages::MAIN_WORLD`] only; any
    /// other becomes [`RenderAssetUsages::default()`], main **and** render
    /// world. [`to_bevy_mesh`] applies the same rule.
    ///
    /// Issue #10. Bevy extracts a mesh to the render world only when its
    /// usages contain `RENDER_WORLD` (`bevy_render` 0.20, `render_asset.rs:350`),
    /// and its mesh allocator logs `WARN … Mesh … contains no vertices.` for
    /// every extracted mesh whose vertex buffer is empty, then allocates
    /// nothing for it (`mesh/allocator.rs:433`). Empty chunks are common — 102
    /// of the 856 chunks of one shipped destructible wall — so handing them to
    /// the renderer cost a warning per empty chunk per remesh, and an
    /// extraction that could never draw.
    ///
    /// The split follows Lengyel's rule for voxel terrain: every block an edit
    /// touches is regenerated, but only a block the surface intersects "becomes
    /// an individually renderable and individually cullable geometry node" (E.
    /// Lengyel, *Voxel-Based Terrain for Real-Time Virtual Simulations*, UC
    /// Davis 2010, p. 28). Being meshed is the block's; being drawn is the
    /// result's.
    ///
    /// Both kinds keep the main world, because a collider baker, a validity
    /// check or [`from_bevy_mesh`] reads the attributes back on the CPU: an
    /// empty mesh's `count_vertices()` is `0` and its `try_attributes()` is
    /// `Ok`. An entity whose `Mesh3d` names a main-world-only mesh is skipped
    /// by the renderer, not refused.
    ///
    /// **Filling an empty mesh in place defeats this.** `Assets::get_mut`
    /// followed by `insert_attribute` keeps the usages it was built with, so
    /// the filled mesh never reaches the renderer. Build a new `Mesh` and
    /// replace the whole asset instead.
    ///
    /// # Panics
    ///
    /// If colours were written but not one per vertex — shade after the last
    /// extraction into this builder, not before the next one.
    #[must_use]
    pub fn into_mesh(self) -> Mesh {
        assert!(
            self.colors.is_empty() || self.colors.len() == self.positions.len(),
            "colours must be one per vertex: {} colours against {} vertices -- \
             bevy_mesh would warn and truncate every attribute to the shorter \
             length while the indices keep addressing the longer one",
            self.colors.len(),
            self.positions.len(),
        );
        let mut mesh = Mesh::new(
            PrimitiveTopology::TriangleList,
            usages_for(self.positions.len()),
        );
        mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, self.positions);
        mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, self.normals);
        mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, self.uvs);
        if !self.colors.is_empty() {
            mesh.insert_attribute(Mesh::ATTRIBUTE_COLOR, self.colors);
        }
        mesh.insert_indices(Indices::U32(self.indices));
        mesh
    }
}

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

impl MeshSink for MeshBuilder {
    type Scalar = f32;

    #[inline]
    fn vertex(&mut self, position: [f32; 3], normal: [f32; 3]) -> u32 {
        let index = self.positions.len();
        assert!(
            index < u32::MAX as usize,
            "MeshBuilder exceeded the u32 index space at {index} vertices"
        );
        self.uvs.push(triplanar_uv(position, normal, self.uv_scale));
        self.positions.push(position);
        self.normals.push(normal);
        index as u32
    }

    #[inline]
    fn triangle(&mut self, a: u32, b: u32, c: u32) {
        self.indices.push(a);
        self.indices.push(b);
        self.indices.push(c);
    }

    #[inline]
    fn reserve(&mut self, vertices: usize, triangles: usize) {
        self.positions.reserve(vertices);
        self.normals.reserve(vertices);
        self.uvs.reserve(vertices);
        self.indices.reserve(triangles * 3);
    }
}

/// Dominant-axis planar projection.
///
/// An isosurface has no natural parameterisation, so there is no correct UV to
/// emit — the good answer is triplanar blending in the shader, which needs no UV
/// attribute at all. This is the cheap stand-in that lets a plain
/// `StandardMaterial` show something sensible: project along whichever axis the
/// normal points most strongly along, and take the other two coordinates.
///
/// It seams visibly where the dominant axis changes. That is inherent to
/// per-vertex planar projection and is the reason shader-side triplanar exists.
#[inline]
fn triplanar_uv(position: [f32; 3], normal: [f32; 3], scale: f32) -> [f32; 2] {
    let n = [normal[0].abs(), normal[1].abs(), normal[2].abs()];
    let (u, v) = if n[0] >= n[1] && n[0] >= n[2] {
        (position[1], position[2])
    } else if n[1] >= n[2] {
        (position[2], position[0])
    } else {
        (position[0], position[1])
    };
    [u / scale, v / scale]
}

/// The usages a mesh built here gets: main world only when it has no vertices,
/// main and render world otherwise. One rule for both constructors; the why is
/// on [`MeshBuilder::into_mesh`] (issue #10; Lengyel 2010, p. 28).
fn usages_for(vertices: usize) -> RenderAssetUsages {
    if vertices == 0 {
        RenderAssetUsages::MAIN_WORLD
    } else {
        RenderAssetUsages::default()
    }
}

/// Copy an [`isomesh::MeshBuffer`] into a Bevy [`Mesh`].
///
/// This **copies**, because the buffer is the thing you are reusing across
/// chunks and a `Mesh` needs to own its data. When the copy matters, extract
/// into a [`MeshBuilder`] instead and let the extractor write straight into the
/// arrays the asset will take.
///
/// UVs are not emitted here — see this module's `triplanar_uv` note for why
/// there is no correct
/// answer, and note that a buffer carries no information this function could
/// use to invent one.
///
/// An empty buffer becomes a mesh with [`RenderAssetUsages::MAIN_WORLD`] only,
/// any other [`RenderAssetUsages::default()`]: the same rule as
/// [`MeshBuilder::into_mesh`], whose docs say why and the one way to defeat it.
#[must_use]
pub fn to_bevy_mesh(buffer: &MeshBuffer<f32>) -> Mesh {
    let mut mesh = Mesh::new(
        PrimitiveTopology::TriangleList,
        usages_for(buffer.positions.len()),
    );
    mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, buffer.positions.clone());
    mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, buffer.normals.clone());
    mesh.insert_indices(Indices::U32(buffer.indices.clone()));
    mesh
}

/// Why a [`Mesh`] could not be read as a triangle soup.
///
/// Every variant is a property of the asset, not of this crate — which is why
/// this is an enum a caller can match on rather than a `warn!` swallowed here.
/// A scene walker merging many meshes wants to skip the ones it cannot use and
/// say which; only the caller knows whether one bad mesh is a warning or a stop.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum SoupError {
    /// The mesh is not a `TriangleList`.
    ///
    /// Strips, fans and line topologies are **refused rather than converted**.
    /// A strip *can* be expanded into triangles, and doing it silently would
    /// change the winding of every other triangle — which produces a mesh that
    /// looks right until something asks which side is out.
    NotTriangleList(PrimitiveTopology),
    /// No `ATTRIBUTE_POSITION`, or it is not `Float32x3`.
    NoPositions,
    /// No index buffer.
    ///
    /// Refused rather than synthesised. An unindexed `TriangleList` *is* a valid
    /// soup — vertex `3n`, `3n+1`, `3n+2` — but a caller that meant to hand over
    /// an indexed mesh and lost its indices somewhere upstream is better served
    /// by an error than by a silently de-indexed one.
    NoIndices,
    /// The index count is not a multiple of three.
    RaggedIndices(usize),
    /// An index points past the end of the position buffer.
    IndexOutOfRange {
        /// The offending index.
        index: u32,
        /// How many vertices there are.
        vertices: usize,
    },
}

impl core::fmt::Display for SoupError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::NotTriangleList(topology) => {
                write!(f, "topology is {topology:?}, not TriangleList")
            }
            Self::NoPositions => write!(f, "no Float32x3 ATTRIBUTE_POSITION"),
            Self::NoIndices => write!(f, "no index buffer"),
            Self::RaggedIndices(n) => write!(f, "{n} indices is not a multiple of three"),
            Self::IndexOutOfRange { index, vertices } => {
                write!(f, "index {index} but only {vertices} vertices")
            }
        }
    }
}

impl core::error::Error for SoupError {}

/// A Bevy [`Mesh`] as the `(positions, indices)` pair every `isomesh` entry
/// point takes.
///
/// Ticket: B-012. Consumers were each merging scene meshes into one soup by
/// hand; this is that conversion, once.
///
/// # It does not weld, and that is the contract
///
/// `Mesh::from(Cuboid)` has **24** vertices, not 8 — four per face, because each
/// face needs its own normal. This returns all 24. Welding them to 8 would
/// destroy the crease that makes a cube look like a cube, and whether that trade
/// is worth making depends on what the caller is doing with the result. B-014
/// exposes the predicate that decides it; this function does not decide for you.
///
/// # Errors
///
/// [`SoupError`], one variant per property of the asset that makes it
/// unreadable. Nothing is repaired and nothing is guessed — see the variant docs
/// for why each is refused rather than worked around.
///
/// # Example
///
/// ```
/// use bevy_isomesh::from_bevy_mesh;
/// use bevy_shape::Cuboid;
/// use bevy_mesh::Mesh;
///
/// let mesh = Mesh::from(Cuboid::new(1.0, 1.0, 1.0));
/// let (positions, indices) = from_bevy_mesh(&mesh).expect("a cuboid is a triangle list");
///
/// // Four vertices per face, because each face carries its own normal.
/// assert_eq!(positions.len(), 24);
/// assert_eq!(indices.len(), 36);
/// ```
pub fn from_bevy_mesh(mesh: &Mesh) -> Result<(Vec<[f32; 3]>, Vec<u32>), SoupError> {
    let topology = mesh.primitive_topology();
    if topology != PrimitiveTopology::TriangleList {
        return Err(SoupError::NotTriangleList(topology));
    }

    let positions = mesh
        .attribute(Mesh::ATTRIBUTE_POSITION)
        .and_then(|values| values.as_float3())
        .ok_or(SoupError::NoPositions)?;

    // `Indices` is U16 or U32; both widen to the u32 every isomesh entry point
    // takes, so the caller never has to know which one the asset happened to use.
    let indices: Vec<u32> = match mesh.indices().ok_or(SoupError::NoIndices)? {
        Indices::U16(values) => values.iter().map(|&i| u32::from(i)).collect(),
        Indices::U32(values) => values.clone(),
    };

    if !indices.len().is_multiple_of(3) {
        return Err(SoupError::RaggedIndices(indices.len()));
    }
    if let Some(&index) = indices.iter().find(|&&i| i as usize >= positions.len()) {
        return Err(SoupError::IndexOutOfRange {
            index,
            vertices: positions.len(),
        });
    }

    Ok((positions.to_vec(), indices))
}

/// How finely a vertex attribute is bucketed when building a weld key.
///
/// Ticket: B-014.
///
/// # These numbers are conventional, not derived
///
/// **There is no principled source for a normal tolerance.** Every engine picks
/// one by eye, and the convention is a smoothing angle somewhere in 30°–60°.
/// That is said plainly here rather than dressed up: the default below is a
/// choice, it is the caller's to override, and no measurement in this project
/// justifies it over a neighbouring value.
///
/// # Why a quantum and not a smoothing angle
///
/// **Because an angle threshold is pairwise, and pairwise is the defect this
/// crate already measured.** "Merge if the normals are within 30°" is not
/// transitive — `a` within 30° of `b` and `b` within 30° of `c` does not put `a`
/// within 30° of `c` — so it is not an equivalence relation, and applying it to a
/// `k`-way coincidence class refuses some members while merging others. That is
/// exactly E×4: over 56 configurations a pairwise weld gate removed at most 4
/// non-manifold edges and **added up to 791 non-manifold vertices**, because the
/// leftover representative of a partly-merged class is a bowtie.
///
/// Quantising to a lattice *is* an equivalence relation. Two vertices share a key
/// or they do not, transitively, and a class always splits into complete
/// sub-classes. The cost is the usual one for bucketing: two normals a hair apart
/// can straddle a bucket boundary and fail to merge. That is a missed merge —
/// visible as a seam, harmless topologically — and it is the right failure to
/// prefer over a manufactured bowtie.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WeldKeyConfig {
    /// Lattice steps per unit of a normal component.
    ///
    /// `16.0` buckets the `[-1, 1]` range of each component into 32 steps. Two
    /// normals merge when all three components land in the same bucket, so the
    /// worst-case angle this tolerates is comparable to a ~20°–25° smoothing
    /// angle — the same neighbourhood as the convention, reached a different way.
    pub normal_steps: f32,
    /// Lattice steps per unit of a UV component.
    ///
    /// `4096.0` is fine enough that a texel boundary on a 4K atlas separates, and
    /// coarse enough that two copies of one seam vertex do not.
    pub uv_steps: f32,
    /// Whether to include [`Mesh::ATTRIBUTE_UV_0`] at all.
    ///
    /// Off by default. A mesh with no UVs is the common case for extracted
    /// geometry, and including a missing attribute would key every vertex the
    /// same — silently correct, but it costs a pass over the buffer to learn
    /// nothing.
    pub include_uv: bool,
}

impl Default for WeldKeyConfig {
    fn default() -> Self {
        Self {
            normal_steps: 16.0,
            uv_steps: 4096.0,
            include_uv: false,
        }
    }
}

/// FNV-1a over the quantised attribute bytes.
///
/// Spelled out rather than reached for, because the key must be **identical run
/// to run and machine to machine** — `DefaultHasher` is explicitly not stable
/// across Rust releases, and a key that changes under you turns a weld into a
/// different mesh on a different toolchain.
fn fnv1a(bytes: &[u8]) -> u64 {
    let mut hash = 0xcbf2_9ce4_8422_2325u64;
    for &b in bytes {
        hash ^= u64::from(b);
        hash = hash.wrapping_mul(0x1000_0000_01b3);
    }
    hash
}

/// One weld key per vertex, from a [`Mesh`]'s normals and optionally its UVs.
///
/// Ticket: B-014. Feed the result to `isomesh::weld::Welder::weld_split_by`,
/// which refuses to merge vertices whose key differs. **Same mechanism, two
/// predicates**: the weld's own tolerance keeps topology safe, and this key keeps
/// attributes intact. They compose because both are equivalence relations.
///
/// Returns one key per vertex in the mesh's own vertex order, so it lines up with
/// [`from_bevy_mesh`]'s positions without any reindexing.
///
/// # What a missing attribute means
///
/// A vertex with no normal — or a mesh with no `ATTRIBUTE_NORMAL` at all — keys
/// as if its normal were absent, which means every such vertex shares a key and
/// nothing is split on that axis. That is the correct degenerate case: an
/// attribute that does not exist cannot be preserved, and refusing to weld
/// because of it would be inventing a constraint.
///
/// # Example
///
/// ```
/// use bevy_isomesh::{WeldKeyConfig, weld_keys};
/// use bevy_shape::Cuboid;
/// use bevy_mesh::Mesh;
///
/// let mesh = Mesh::from(Cuboid::new(1.0, 1.0, 1.0));
/// let keys = weld_keys(&mesh, WeldKeyConfig::default());
///
/// // 24 vertices, and the three at each corner differ by normal.
/// assert_eq!(keys.len(), 24);
/// let mut distinct = keys.clone();
/// distinct.sort_unstable();
/// distinct.dedup();
/// assert_eq!(distinct.len(), 6, "one key per face of the cube");
/// ```
#[must_use]
pub fn weld_keys(mesh: &Mesh, config: WeldKeyConfig) -> Vec<u64> {
    let count = mesh.count_vertices();
    let normals = mesh
        .attribute(Mesh::ATTRIBUTE_NORMAL)
        .and_then(|values| values.as_float3());
    let uvs = if config.include_uv {
        match mesh.attribute(Mesh::ATTRIBUTE_UV_0) {
            Some(VertexAttributeValues::Float32x2(values)) => Some(values.as_slice()),
            _ => None,
        }
    } else {
        None
    };

    (0..count)
        .map(|i| {
            let mut bytes = [0u8; 20];
            let mut len = 0usize;
            let push = |v: i32, bytes: &mut [u8; 20], len: &mut usize| {
                bytes[*len..*len + 4].copy_from_slice(&v.to_le_bytes());
                *len += 4;
            };
            if let Some(n) = normals.and_then(|n| n.get(i)) {
                for c in n {
                    push(
                        (c * config.normal_steps).round() as i32,
                        &mut bytes,
                        &mut len,
                    );
                }
            }
            if let Some(uv) = uvs.and_then(|u| u.get(i)) {
                for c in uv {
                    push((c * config.uv_steps).round() as i32, &mut bytes, &mut len);
                }
            }
            fnv1a(&bytes[..len])
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use isomesh::RuntimeShape3;
    use isomesh::fields::Sphere;
    use isomesh::marching_cubes::MarchingCubes;

    fn sphere_builder() -> MeshBuilder {
        let mut builder = MeshBuilder::new();
        let mut mc = MarchingCubes::<f32>::new();
        let shape = RuntimeShape3::new([17; 3]).expect("valid shape");
        mc.extract(
            &Sphere::<f32>::canonical(),
            &shape,
            [-2.0; 3],
            4.0 / 16.0,
            &mut builder,
        )
        .expect("extraction");
        builder
    }

    use bevy_shape::Cuboid;

    // ── B-014: the attribute key ────────────────────────────────────────────

    /// B-014's acceptance, end to end: the cuboid keeps all 24 vertices under the
    /// composite predicate and collapses to 8 without it.
    #[test]
    fn the_key_preserves_a_cuboids_creases_and_without_it_they_collapse() {
        use isomesh::MeshBuffer;
        use isomesh::weld::{Welder, epsilon_for};

        let mesh = Mesh::from(Cuboid::new(1.0, 1.0, 1.0));
        let (positions, indices) = from_bevy_mesh(&mesh).expect("triangle list");
        let normals: Vec<[f32; 3]> = mesh
            .attribute(Mesh::ATTRIBUTE_NORMAL)
            .and_then(|v| v.as_float3())
            .expect("a cuboid has normals")
            .to_vec();
        let keys = weld_keys(&mesh, WeldKeyConfig::default());

        let build = || {
            let mut buffer = MeshBuffer::<f32>::new();
            buffer.positions.extend_from_slice(&positions);
            buffer.normals.extend_from_slice(&normals);
            buffer.indices.extend_from_slice(&indices);
            buffer
        };

        // Position only: the eight corners swallow their three copies each.
        let mut plain = build();
        Welder::default()
            .weld(&mut plain, epsilon_for(1.0f32))
            .expect("weld");
        assert_eq!(
            plain.positions.len(),
            8,
            "without the key a cube is eight corners and no creases"
        );

        // With the key: nothing merges, because every coincident triple carries
        // three different face normals.
        let mut kept = build();
        Welder::default()
            .weld_split_by(&mut kept, epsilon_for(1.0f32), &keys)
            .expect("weld");
        assert_eq!(
            kept.positions.len(),
            24,
            "the key is what keeps the crease that makes a cube look like a cube"
        );
    }

    #[test]
    fn one_key_per_face_of_a_cuboid() {
        let mesh = Mesh::from(Cuboid::new(2.0, 3.0, 4.0));
        let keys = weld_keys(&mesh, WeldKeyConfig::default());
        assert_eq!(keys.len(), 24);
        let mut distinct = keys.clone();
        distinct.sort_unstable();
        distinct.dedup();
        assert_eq!(distinct.len(), 6, "six faces, six normals, six keys");
    }

    /// The key must not depend on the toolchain, which is why it is FNV-1a
    /// spelled out rather than `DefaultHasher`.
    #[test]
    fn the_key_is_stable_across_runs() {
        let mesh = Mesh::from(Cuboid::new(1.0, 1.0, 1.0));
        let first = weld_keys(&mesh, WeldKeyConfig::default());
        for _ in 0..32 {
            assert_eq!(weld_keys(&mesh, WeldKeyConfig::default()), first);
        }
    }

    #[test]
    fn a_mesh_with_no_normals_keys_every_vertex_the_same() {
        let mut mesh = Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        );
        mesh.insert_attribute(
            Mesh::ATTRIBUTE_POSITION,
            vec![[0.0f32, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
        );
        let keys = weld_keys(&mesh, WeldKeyConfig::default());
        assert_eq!(keys.len(), 3);
        // An attribute that does not exist cannot be preserved, and refusing to
        // weld over it would be inventing a constraint.
        assert!(keys.windows(2).all(|w| w[0] == w[1]));
    }

    #[test]
    fn a_coarser_quantum_merges_what_a_finer_one_splits() {
        let mut mesh = Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        );
        mesh.insert_attribute(
            Mesh::ATTRIBUTE_POSITION,
            vec![[0.0f32, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
        );
        // Three normals a few degrees apart.
        mesh.insert_attribute(
            Mesh::ATTRIBUTE_NORMAL,
            vec![[0.0f32, 0.0, 1.0], [0.05, 0.0, 0.998], [0.10, 0.0, 0.995]],
        );

        let fine = weld_keys(
            &mesh,
            WeldKeyConfig {
                normal_steps: 256.0,
                ..WeldKeyConfig::default()
            },
        );
        let coarse = weld_keys(
            &mesh,
            WeldKeyConfig {
                normal_steps: 1.0,
                ..WeldKeyConfig::default()
            },
        );

        assert!(fine[0] != fine[1] && fine[1] != fine[2], "fine splits them");
        assert!(
            coarse[0] == coarse[1] && coarse[1] == coarse[2],
            "coarse buckets them together"
        );
    }

    // ── B-012: Mesh -> triangle soup ────────────────────────────────────────

    /// The acceptance criterion: a cuboid round-trips as **24** vertices, not 8.
    #[test]
    fn a_cuboid_keeps_its_twenty_four_vertices() {
        let mesh = Mesh::from(Cuboid::new(2.0, 3.0, 4.0));
        let (positions, indices) = from_bevy_mesh(&mesh).expect("cuboid is a triangle list");

        assert_eq!(
            positions.len(),
            24,
            "welding is the caller's decision, not this function's"
        );
        assert_eq!(indices.len(), 36, "12 triangles");
        assert!(indices.iter().all(|&i| (i as usize) < positions.len()));

        // Only 8 distinct positions underneath, which is exactly why welding
        // would be lossy: the 24 differ by normal, not by position.
        let mut distinct: Vec<[u32; 3]> = positions
            .iter()
            .map(|p| [p[0].to_bits(), p[1].to_bits(), p[2].to_bits()])
            .collect();
        distinct.sort_unstable();
        distinct.dedup();
        assert_eq!(distinct.len(), 8, "a box has eight corners");
    }

    /// The isomesh direction and the Bevy direction compose.
    #[test]
    fn an_extracted_sphere_survives_the_round_trip() {
        let builder = sphere_builder();
        let (want_positions, want_indices) =
            (builder.positions().to_vec(), builder.indices().to_vec());

        let mesh = builder.into_mesh();
        let (got_positions, got_indices) = from_bevy_mesh(&mesh).expect("round trip");

        assert_eq!(got_positions, want_positions);
        assert_eq!(got_indices, want_indices);
    }

    #[test]
    fn a_u16_index_buffer_widens_rather_than_being_refused() {
        let mut mesh = Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        );
        mesh.insert_attribute(
            Mesh::ATTRIBUTE_POSITION,
            vec![[0.0f32, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
        );
        mesh.insert_indices(Indices::U16(vec![0, 1, 2]));

        let (positions, indices) = from_bevy_mesh(&mesh).expect("u16 is a valid index type");
        assert_eq!(positions.len(), 3);
        assert_eq!(indices, vec![0u32, 1, 2]);
    }

    #[test]
    fn a_strip_is_refused_rather_than_expanded() {
        let mut mesh = Mesh::new(
            PrimitiveTopology::TriangleStrip,
            RenderAssetUsages::default(),
        );
        mesh.insert_attribute(
            Mesh::ATTRIBUTE_POSITION,
            vec![[0.0f32, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
        );
        mesh.insert_indices(Indices::U32(vec![0, 1, 2]));

        // Expanding a strip silently would flip every other triangle's winding.
        assert_eq!(
            from_bevy_mesh(&mesh),
            Err(SoupError::NotTriangleList(PrimitiveTopology::TriangleStrip))
        );
    }

    #[test]
    fn missing_positions_and_missing_indices_are_distinguished() {
        let mut no_positions = Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        );
        no_positions.insert_indices(Indices::U32(vec![0, 1, 2]));
        assert_eq!(from_bevy_mesh(&no_positions), Err(SoupError::NoPositions));

        let mut no_indices = Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        );
        no_indices.insert_attribute(
            Mesh::ATTRIBUTE_POSITION,
            vec![[0.0f32, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
        );
        assert_eq!(from_bevy_mesh(&no_indices), Err(SoupError::NoIndices));
    }

    #[test]
    fn a_ragged_or_out_of_range_index_buffer_is_refused() {
        let make = |indices: Vec<u32>| {
            let mut mesh = Mesh::new(
                PrimitiveTopology::TriangleList,
                RenderAssetUsages::default(),
            );
            mesh.insert_attribute(
                Mesh::ATTRIBUTE_POSITION,
                vec![[0.0f32, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
            );
            mesh.insert_indices(Indices::U32(indices));
            mesh
        };

        assert_eq!(
            from_bevy_mesh(&make(vec![0, 1, 2, 0])),
            Err(SoupError::RaggedIndices(4))
        );
        assert_eq!(
            from_bevy_mesh(&make(vec![0, 1, 7])),
            Err(SoupError::IndexOutOfRange {
                index: 7,
                vertices: 3
            })
        );
    }

    #[test]
    fn extraction_writes_straight_into_the_mesh_arrays() {
        let builder = sphere_builder();
        let vertices = builder.vertex_count();
        let triangles = builder.triangle_count();
        assert!(vertices > 0 && triangles > 0);

        let mesh = builder.into_mesh();
        assert_eq!(mesh.count_vertices(), vertices);
        assert_eq!(
            mesh.indices().map(bevy_mesh::Indices::len),
            Some(triangles * 3)
        );
        assert_eq!(mesh.primitive_topology(), PrimitiveTopology::TriangleList);
        assert!(mesh.attribute(Mesh::ATTRIBUTE_POSITION).is_some());
        assert!(mesh.attribute(Mesh::ATTRIBUTE_NORMAL).is_some());
        assert!(mesh.attribute(Mesh::ATTRIBUTE_UV_0).is_some());
    }

    #[test]
    fn indices_are_u32() {
        let mesh = sphere_builder().into_mesh();
        assert!(matches!(mesh.indices(), Some(Indices::U32(_))));
    }

    /// A mesh nobody painted carries no colour attribute — the twenty-odd
    /// examples that predate E-208 do not pay 16 bytes a vertex for white.
    #[test]
    fn an_unpainted_mesh_has_no_color_attribute() {
        let mesh = sphere_builder().into_mesh();
        assert!(mesh.attribute(Mesh::ATTRIBUTE_COLOR).is_none());
    }

    /// E-208's bridge: `paint::shade` writes into the array the `Mesh` ends up
    /// owning, and the attribute appears because it was filled.
    #[test]
    fn shading_the_builder_puts_colors_on_the_mesh() {
        use isomesh::paint::{Edit, PaintStack, Splat};

        let mut builder = sphere_builder();
        let vertices = builder.vertex_count();

        let log: [Edit<Sphere<f32>, Sphere<f32>, f32>; 1] = [Edit::Spray(Splat {
            shape: Sphere {
                center: [0.0, 1.0, 0.0],
                radius: 0.6,
            },
            color: [1.0, 0.0, 0.0, 1.0],
            softness: 0.1,
            depth: 0.1,
        })];
        let world = PaintStack {
            base: Sphere::<f32>::canonical(),
            edits: &log,
            background: [0.5, 0.5, 0.5, 1.0],
        };

        // Straight into the array the Mesh will own, with no scratch buffer and
        // no swap: the two borrows come from disjoint fields (B-008).
        let (positions, colors) = builder.positions_and_colors_mut();
        isomesh::paint::shade(positions, &world, colors);
        assert_eq!(builder.colors().len(), vertices);

        let mesh = builder.into_mesh();
        let attribute = mesh
            .attribute(Mesh::ATTRIBUTE_COLOR)
            .expect("colour attribute");
        assert_eq!(attribute.len(), vertices);
    }

    /// The core crate's own validity harness, run on what Bevy is about to
    /// render. If the bridge reordered or dropped anything this would fail.
    #[test]
    fn the_bridged_mesh_is_still_a_closed_surface() {
        let builder = sphere_builder();
        let positions: Vec<[f32; 3]> = builder.positions.clone();
        let indices = builder.indices.clone();
        let report = isomesh::validate::validate_indexed(
            &positions,
            &indices,
            &isomesh::validate::ValidateConfig::from_cell_size(f64::from(4.0f32 / 16.0))
                .expect("valid cell size"),
        );
        assert!(report.is_closed(), "{report}");
        assert_eq!(report.euler_characteristic, 2, "{report}");
    }

    #[test]
    fn reset_keeps_capacity() {
        let mut builder = sphere_builder();
        let capacity = builder.positions.capacity();
        assert!(capacity > 0);
        builder.reset();
        assert_eq!(builder.vertex_count(), 0);
        assert_eq!(builder.positions.capacity(), capacity);
    }

    #[test]
    fn buffer_conversion_matches_the_builder() {
        let mut buffer = MeshBuffer::<f32>::new();
        let mut mc = MarchingCubes::<f32>::new();
        let shape = RuntimeShape3::new([17; 3]).expect("valid shape");
        mc.extract(
            &Sphere::<f32>::canonical(),
            &shape,
            [-2.0; 3],
            4.0 / 16.0,
            &mut buffer,
        )
        .expect("extraction");
        let mesh = to_bevy_mesh(&buffer);
        assert_eq!(mesh.count_vertices(), buffer.vertex_count());
        assert_eq!(
            mesh.indices().map(bevy_mesh::Indices::len),
            Some(buffer.indices.len())
        );
    }

    // ── Issue #10: an empty mesh is not handed to the renderer ──────────────

    /// Extract a region the canonical sphere never reaches.
    fn extract_nothing<S: MeshSink<Scalar = f32>>(sink: &mut S) {
        let shape = RuntimeShape3::new([17; 3]).expect("valid shape");
        MarchingCubes::<f32>::new()
            .extract(
                &Sphere::<f32>::canonical(),
                &shape,
                [10.0; 3],
                4.0 / 16.0,
                sink,
            )
            .expect("extraction");
    }

    #[test]
    fn into_mesh_keeps_an_empty_mesh_out_of_the_render_world_and_readable() {
        let mut builder = MeshBuilder::new();
        extract_nothing(&mut builder);
        assert_eq!(
            builder.vertex_count(),
            0,
            "the sphere is not in this region"
        );

        let empty = builder.into_mesh();
        assert_eq!(
            empty.asset_usage,
            RenderAssetUsages::MAIN_WORLD,
            "Bevy's mesh allocator warns for every zero-vertex mesh it is handed"
        );
        assert_eq!(empty.count_vertices(), 0);
        assert!(
            empty.try_attributes().is_ok(),
            "the main world still reads it"
        );
        assert_eq!(from_bevy_mesh(&empty), Ok((Vec::new(), Vec::new())));

        let surface = sphere_builder().into_mesh();
        assert!(surface.count_vertices() > 0);
        assert_eq!(
            surface.asset_usage,
            RenderAssetUsages::default(),
            "a mesh with vertices is drawn and still readable"
        );
    }

    #[test]
    fn to_bevy_mesh_keeps_an_empty_mesh_out_of_the_render_world_and_readable() {
        let mut empty = MeshBuffer::<f32>::new();
        extract_nothing(&mut empty);
        assert_eq!(empty.vertex_count(), 0, "the sphere is not in this region");

        let mesh = to_bevy_mesh(&empty);
        assert_eq!(mesh.asset_usage, RenderAssetUsages::MAIN_WORLD);
        assert_eq!(mesh.count_vertices(), 0);
        assert!(
            mesh.try_attributes().is_ok(),
            "the main world still reads it"
        );
        assert_eq!(from_bevy_mesh(&mesh), Ok((Vec::new(), Vec::new())));

        let mut surface = MeshBuffer::<f32>::new();
        MarchingCubes::<f32>::new()
            .extract(
                &Sphere::<f32>::canonical(),
                &RuntimeShape3::new([17; 3]).expect("valid shape"),
                [-2.0; 3],
                4.0 / 16.0,
                &mut surface,
            )
            .expect("extraction");
        assert!(surface.vertex_count() > 0);
        assert_eq!(
            to_bevy_mesh(&surface).asset_usage,
            RenderAssetUsages::default()
        );
    }

    #[test]
    fn uvs_follow_the_dominant_axis() {
        // A +x-facing normal projects the y and z coordinates.
        assert_eq!(
            triplanar_uv([1.0, 2.0, 3.0], [1.0, 0.0, 0.0], 1.0),
            [2.0, 3.0]
        );
        // A +y-facing normal projects z and x.
        assert_eq!(
            triplanar_uv([1.0, 2.0, 3.0], [0.0, 1.0, 0.0], 1.0),
            [3.0, 1.0]
        );
        // A +z-facing normal projects x and y.
        assert_eq!(
            triplanar_uv([1.0, 2.0, 3.0], [0.0, 0.0, 1.0], 1.0),
            [1.0, 2.0]
        );
        // Scale divides.
        assert_eq!(
            triplanar_uv([1.0, 2.0, 3.0], [0.0, 0.0, 1.0], 2.0),
            [0.5, 1.0]
        );
    }
}