euv-core 0.56.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
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
use super::*;

/// Finalizes a primitive `Mesh3D` with bounds, meshlets, tangents, and closed-manifold flag.
///
/// # Arguments
///
/// - `&str` - Asset name.
/// - `Vec<Vertex3D>` - Pre-built vertex buffer.
/// - `Vec<[u32; 3]>` - Outward-wound triangle index triplets.
/// - `bool` - Whether the primitive forms a watertight closed volume.
///
/// # Returns
///
/// - `Mesh3D` - Ready primitive mesh with tangents and meshlet clusters.
#[must_use]
fn finalize_primitive(
    name: &str,
    vertices: Vec<Vertex3D>,
    indices: Vec<[u32; 3]>,
    is_closed: bool,
) -> Mesh3D {
    let mut mesh: Mesh3D =
        Mesh3D::from_parts(name.to_string(), vertices, indices, PbrMaterial::default());
    mesh.set_is_closed(is_closed);
    compute_tangents(&mesh)
}

/// Computes spherical equirectangular UV coordinates in `[0, 1]^2` for a unit direction vector.
///
/// # Arguments
///
/// - `Vec3` - Unit direction vector on the sphere.
///
/// # Returns
///
/// - `[f32; 2]` - Clean finite `[u, v]` texture coordinates.
#[must_use]
fn spherical_uv(unit_dir: Vec3) -> [f32; 2] {
    let u: f32 = unit_dir.get_z().atan2(unit_dir.get_x()) / TAU + 0.5;
    let v: f32 = unit_dir.get_y().clamp(-1.0, 1.0).asin() / PI + 0.5;
    [sanitize_scalar(u, 0.5), sanitize_scalar(v, 0.5)]
}

/// Looks up or inserts the normalized midpoint vertex on a sphere edge during geodesic subdivision.
///
/// # Arguments
///
/// - `u32` - First edge endpoint index.
/// - `u32` - Second edge endpoint index.
/// - `&mut Vec<Vec3>` - Mutable list of unit directions.
/// - `&mut HashMap<(u32, u32), u32>` - Edge midpoint deduplication cache.
///
/// # Returns
///
/// - `u32` - Index of the shared normalized midpoint vertex.
fn sphere_midpoint(
    a: u32,
    b: u32,
    dirs: &mut Vec<Vec3>,
    cache: &mut HashMap<(u32, u32), u32>,
) -> u32 {
    let key: (u32, u32) = if a < b { (a, b) } else { (b, a) };
    if let Some(&existing) = cache.get(&key) {
        return existing;
    }
    let mid: Vec3 = safe_unit_normal(dirs[a as usize].add(dirs[b as usize]));
    let idx: u32 = dirs.len() as u32;
    dirs.push(mid);
    cache.insert(key, idx);
    idx
}

/// Builds a watertight latitude-longitude UV sphere centered at the origin with analytic smooth normals.
///
/// # Arguments
///
/// - `f32` - Sphere radius (clamped to `>= 1e-4`).
/// - `u32` - Latitude stack count (clamped to `>= 3`).
/// - `u32` - Longitude slice count (clamped to `>= 4`).
///
/// # Returns
///
/// - `Mesh3D` - Watertight outward-wound UV sphere mesh.
#[must_use]
pub fn uv_sphere(radius: f32, stacks: u32, slices: u32) -> Mesh3D {
    let r: f32 = sanitize_scalar(radius, 1.0).abs().max(PRIM_MIN_RADIUS);
    let st: usize = stacks.max(3) as usize;
    let sl: usize = slices.max(4) as usize;
    let ring_stride: usize = sl + 1;
    let mut vertices: Vec<Vertex3D> = Vec::with_capacity((st + 1) * ring_stride);
    let mut indices: Vec<[u32; 3]> = Vec::with_capacity(st * sl * 2);
    for s in 0..=st {
        let v_frac: f32 = (s as f32) / (st as f32);
        let phi: f32 = v_frac * PI;
        let cos_phi: f32 = phi.cos();
        let sin_phi: f32 = phi.sin();
        for j in 0..=sl {
            let u_frac: f32 = (j as f32) / (sl as f32);
            let theta: f32 = u_frac * TAU;
            let nx: f32 = sin_phi * theta.cos();
            let ny: f32 = cos_phi;
            let nz: f32 = sin_phi * theta.sin();
            let normal: Vec3 = safe_unit_normal(Vec3::new(nx, ny, nz));
            vertices.push(make_textured_vertex(
                normal.scale(r),
                normal,
                [u_frac, 1.0 - v_frac],
            ));
        }
    }
    for s in 0..st {
        let row0: u32 = (s * ring_stride) as u32;
        let row1: u32 = ((s + 1) * ring_stride) as u32;
        for j in 0..sl {
            let ju: u32 = j as u32;
            let i00: u32 = row0 + ju;
            let i01: u32 = row0 + ju + 1;
            let i10: u32 = row1 + ju;
            let i11: u32 = row1 + ju + 1;
            if s > 0 {
                indices.push([i00, i01, i10]);
            }
            if s + 1 < st {
                indices.push([i01, i11, i10]);
            }
        }
    }
    finalize_primitive(PRIM_NAME_UV_SPHERE, vertices, indices, true)
}

/// Builds a watertight geodesic icosphere by recursively subdividing a regular icosahedron.
///
/// # Arguments
///
/// - `f32` - Sphere radius (clamped to `>= 1e-4`).
/// - `u32` - Subdivision depth (clamped to `0..=5`).
///
/// # Returns
///
/// - `Mesh3D` - Watertight outward-wound icosphere mesh with uniform triangle density.
#[must_use]
pub fn icosphere(radius: f32, subdivisions: u32) -> Mesh3D {
    let r: f32 = sanitize_scalar(radius, 1.0).abs().max(PRIM_MIN_RADIUS);
    let levels: u32 = subdivisions.min(PRIM_MAX_SUBDIV);
    let phi: f32 = (1.0 + 5.0_f32.sqrt()) * 0.5;
    let raw_verts: [[f32; 3]; 12] = [
        [-1.0, phi, 0.0],
        [1.0, phi, 0.0],
        [-1.0, -phi, 0.0],
        [1.0, -phi, 0.0],
        [0.0, -1.0, phi],
        [0.0, 1.0, phi],
        [0.0, -1.0, -phi],
        [0.0, 1.0, -phi],
        [phi, 0.0, -1.0],
        [phi, 0.0, 1.0],
        [-phi, 0.0, -1.0],
        [-phi, 0.0, 1.0],
    ];
    let mut dirs: Vec<Vec3> = Vec::with_capacity(12 * (1 << (levels * 2)));
    for coord in raw_verts.iter() {
        dirs.push(safe_unit_normal(Vec3::from_array(*coord)));
    }
    let mut faces: Vec<[u32; 3]> = vec![
        [0, 11, 5],
        [0, 5, 1],
        [0, 1, 7],
        [0, 7, 10],
        [0, 10, 11],
        [1, 5, 9],
        [5, 11, 4],
        [11, 10, 2],
        [10, 7, 6],
        [7, 1, 8],
        [3, 9, 4],
        [3, 4, 2],
        [3, 2, 6],
        [3, 6, 8],
        [3, 8, 9],
        [4, 9, 5],
        [2, 4, 11],
        [6, 2, 10],
        [8, 6, 7],
        [9, 8, 1],
    ];
    for tri in faces.iter_mut() {
        let p0: Vec3 = dirs[tri[0] as usize];
        let p1: Vec3 = dirs[tri[1] as usize];
        let p2: Vec3 = dirs[tri[2] as usize];
        let centroid: Vec3 = p0.add(p1).add(p2);
        if p1.sub(p0).cross(p2.sub(p0)).dot(centroid) < 0.0 {
            tri.swap(1, 2);
        }
    }
    for _ in 0..levels {
        let mut cache: HashMap<(u32, u32), u32> = HashMap::with_capacity(faces.len() * 3);
        let mut next_faces: Vec<[u32; 3]> = Vec::with_capacity(faces.len() * 4);
        for tri in faces.iter() {
            let a: u32 = tri[0];
            let b: u32 = tri[1];
            let c: u32 = tri[2];
            let ab: u32 = sphere_midpoint(a, b, &mut dirs, &mut cache);
            let bc: u32 = sphere_midpoint(b, c, &mut dirs, &mut cache);
            let ca: u32 = sphere_midpoint(c, a, &mut dirs, &mut cache);
            next_faces.push([a, ab, ca]);
            next_faces.push([b, bc, ab]);
            next_faces.push([c, ca, bc]);
            next_faces.push([ab, bc, ca]);
        }
        faces = next_faces;
    }
    let mut vertices: Vec<Vertex3D> = Vec::with_capacity(dirs.len());
    for &unit_dir in dirs.iter() {
        vertices.push(make_textured_vertex(
            unit_dir.scale(r),
            unit_dir,
            spherical_uv(unit_dir),
        ));
    }
    finalize_primitive(PRIM_NAME_ICOSPHERE, vertices, faces, true)
}

/// Builds a watertight vertical capsule along Y consisting of a shaft of length `height` and two hemispherical caps.
///
/// # Arguments
///
/// - `f32` - Capsule radius (clamped to `>= 1e-4`).
/// - `f32` - Cylindrical midsection height (clamped to `>= 0.0`).
/// - `u32` - Radial segment count (clamped to `>= 6`).
///
/// # Returns
///
/// - `Mesh3D` - Watertight outward-wound capsule mesh with smooth normals and UVs.
#[must_use]
pub fn capsule(radius: f32, height: f32, segs: u32) -> Mesh3D {
    let r: f32 = sanitize_scalar(radius, 0.5).abs().max(PRIM_MIN_RADIUS);
    let h: f32 = sanitize_scalar(height, 1.0).max(0.0);
    let half_h: f32 = h * 0.5;
    let sl: usize = segs.max(6) as usize;
    let hemi_rings: usize = (sl / 4).max(3);
    let mut ring_specs: Vec<(f32, f32, f32, f32)> = Vec::with_capacity(hemi_rings * 2 + 2);
    for i in 0..=hemi_rings {
        let frac: f32 = (i as f32) / (hemi_rings as f32);
        let phi: f32 = frac * FRAC_PI_2;
        let cos_p: f32 = phi.cos();
        let sin_p: f32 = phi.sin();
        ring_specs.push((half_h + r * cos_p, r * sin_p, cos_p, sin_p));
    }
    for i in 0..=hemi_rings {
        let frac: f32 = (i as f32) / (hemi_rings as f32);
        let phi: f32 = FRAC_PI_2 + frac * FRAC_PI_2;
        let cos_p: f32 = phi.cos();
        let sin_p: f32 = phi.sin();
        ring_specs.push((-half_h + r * cos_p, r * sin_p, cos_p, sin_p));
    }
    let total_height: f32 = (h + 2.0 * r).max(PRIM_MIN_RADIUS);
    let ring_count: usize = ring_specs.len();
    let ring_stride: usize = sl + 1;
    let mut vertices: Vec<Vertex3D> = Vec::with_capacity(ring_count * ring_stride);
    let mut indices: Vec<[u32; 3]> = Vec::with_capacity((ring_count - 1) * sl * 2);
    for &(y_pos, ring_r, ny, nr) in ring_specs.iter() {
        let v_coord: f32 = ((y_pos + half_h + r) / total_height).clamp(0.0, 1.0);
        for j in 0..=sl {
            let u_coord: f32 = (j as f32) / (sl as f32);
            let theta: f32 = u_coord * TAU;
            let ct: f32 = theta.cos();
            let st: f32 = theta.sin();
            let pos: Vec3 = Vec3::new(ring_r * ct, y_pos, ring_r * st);
            let normal: Vec3 = safe_unit_normal(Vec3::new(nr * ct, ny, nr * st));
            vertices.push(make_textured_vertex(pos, normal, [u_coord, v_coord]));
        }
    }
    for s in 0..(ring_count - 1) {
        let row0: u32 = (s * ring_stride) as u32;
        let row1: u32 = ((s + 1) * ring_stride) as u32;
        let r0_zero: bool = ring_specs[s].1 <= 1e-6;
        let r1_zero: bool = ring_specs[s + 1].1 <= 1e-6;
        for j in 0..sl {
            let ju: u32 = j as u32;
            let i00: u32 = row0 + ju;
            let i01: u32 = row0 + ju + 1;
            let i10: u32 = row1 + ju;
            let i11: u32 = row1 + ju + 1;
            if !r0_zero {
                indices.push([i00, i01, i10]);
            }
            if !r1_zero {
                indices.push([i01, i11, i10]);
            }
        }
    }
    finalize_primitive(PRIM_NAME_CAPSULE, vertices, indices, true)
}

/// Builds a vertical cylinder or tapered frustum centered at the origin with optional top and bottom caps.
///
/// # Arguments
///
/// - `f32` - Bottom radius (clamped to `>= 1e-4`).
/// - `f32` - Top radius (clamped to `>= 1e-4`).
/// - `f32` - Cylinder height along Y (clamped to `>= 1e-4`).
/// - `u32` - Radial segment count (clamped to `>= 3`).
/// - `bool` - Whether to generate watertight top and bottom disk caps.
///
/// # Returns
///
/// - `Mesh3D` - Outward-wound cylinder or frustum mesh.
#[must_use]
pub fn cylinder(r_bottom: f32, r_top: f32, height: f32, segs: u32, capped: bool) -> Mesh3D {
    let rb: f32 = sanitize_scalar(r_bottom, 0.5).abs().max(PRIM_MIN_RADIUS);
    let rt: f32 = sanitize_scalar(r_top, 0.5).abs().max(PRIM_MIN_RADIUS);
    let h: f32 = sanitize_scalar(height, 1.0).abs().max(PRIM_MIN_RADIUS);
    let half_h: f32 = h * 0.5;
    let sl: usize = segs.max(3) as usize;
    let slope_len: f32 = (h * h + (rb - rt) * (rb - rt)).sqrt().max(PRIM_MIN_RADIUS);
    let nr: f32 = h / slope_len;
    let ny: f32 = (rb - rt) / slope_len;
    let extra_verts: usize = if capped { (sl + 2) * 2 } else { 0 };
    let extra_tris: usize = if capped { sl * 2 } else { 0 };
    let mut vertices: Vec<Vertex3D> = Vec::with_capacity((sl + 1) * 2 + extra_verts);
    let mut indices: Vec<[u32; 3]> = Vec::with_capacity(sl * 2 + extra_tris);
    for j in 0..=sl {
        let u: f32 = (j as f32) / (sl as f32);
        let theta: f32 = u * TAU;
        let ct: f32 = theta.cos();
        let st: f32 = theta.sin();
        let normal: Vec3 = safe_unit_normal(Vec3::new(nr * ct, ny, nr * st));
        vertices.push(make_textured_vertex(
            Vec3::new(rt * ct, half_h, rt * st),
            normal,
            [u, 1.0],
        ));
    }
    let bot_row: u32 = (sl + 1) as u32;
    for j in 0..=sl {
        let u: f32 = (j as f32) / (sl as f32);
        let theta: f32 = u * TAU;
        let ct: f32 = theta.cos();
        let st: f32 = theta.sin();
        let normal: Vec3 = safe_unit_normal(Vec3::new(nr * ct, ny, nr * st));
        vertices.push(make_textured_vertex(
            Vec3::new(rb * ct, -half_h, rb * st),
            normal,
            [u, 0.0],
        ));
    }
    for j in 0..sl {
        let ju: u32 = j as u32;
        indices.push([ju, ju + 1, bot_row + ju]);
        indices.push([ju + 1, bot_row + ju + 1, bot_row + ju]);
    }
    if capped {
        let top_center: u32 = vertices.len() as u32;
        let up: Vec3 = Vec3::new(0.0, 1.0, 0.0);
        vertices.push(make_textured_vertex(
            Vec3::new(0.0, half_h, 0.0),
            up,
            [0.5, 0.5],
        ));
        let top_ring: u32 = vertices.len() as u32;
        for j in 0..=sl {
            let theta: f32 = ((j as f32) / (sl as f32)) * TAU;
            let ct: f32 = theta.cos();
            let st: f32 = theta.sin();
            vertices.push(make_textured_vertex(
                Vec3::new(rt * ct, half_h, rt * st),
                up,
                [0.5 + 0.5 * ct, 0.5 + 0.5 * st],
            ));
        }
        for j in 0..sl {
            let ju: u32 = j as u32;
            indices.push([top_center, top_ring + ju + 1, top_ring + ju]);
        }
        let bot_center: u32 = vertices.len() as u32;
        let down: Vec3 = Vec3::new(0.0, -1.0, 0.0);
        vertices.push(make_textured_vertex(
            Vec3::new(0.0, -half_h, 0.0),
            down,
            [0.5, 0.5],
        ));
        let bot_cap_ring: u32 = vertices.len() as u32;
        for j in 0..=sl {
            let theta: f32 = ((j as f32) / (sl as f32)) * TAU;
            let ct: f32 = theta.cos();
            let st: f32 = theta.sin();
            vertices.push(make_textured_vertex(
                Vec3::new(rb * ct, -half_h, rb * st),
                down,
                [0.5 + 0.5 * ct, 0.5 - 0.5 * st],
            ));
        }
        for j in 0..sl {
            let ju: u32 = j as u32;
            indices.push([bot_center, bot_cap_ring + ju, bot_cap_ring + ju + 1]);
        }
    }
    finalize_primitive(PRIM_NAME_CYLINDER, vertices, indices, capped)
}

/// Builds a watertight vertical cone centered at the origin with analytic sloped normals and a flat circular base cap.
///
/// # Arguments
///
/// - `f32` - Base radius (clamped to `>= 1e-4`).
/// - `f32` - Cone height along Y (clamped to `>= 1e-4`).
/// - `u32` - Radial segment count (clamped to `>= 3`).
///
/// # Returns
///
/// - `Mesh3D` - Watertight outward-wound cone mesh.
#[must_use]
pub fn cone(radius: f32, height: f32, segs: u32) -> Mesh3D {
    let r: f32 = sanitize_scalar(radius, 0.5).abs().max(PRIM_MIN_RADIUS);
    let h: f32 = sanitize_scalar(height, 1.0).abs().max(PRIM_MIN_RADIUS);
    let half_h: f32 = h * 0.5;
    let sl: usize = segs.max(3) as usize;
    let slope_len: f32 = (h * h + r * r).sqrt().max(PRIM_MIN_RADIUS);
    let nr: f32 = h / slope_len;
    let ny: f32 = r / slope_len;
    let mut vertices: Vec<Vertex3D> = Vec::with_capacity(sl * 3 + 3);
    let mut indices: Vec<[u32; 3]> = Vec::with_capacity(sl * 2);
    let bot_base: u32 = sl as u32;
    for j in 0..sl {
        let mid_u: f32 = ((j as f32) + 0.5) / (sl as f32);
        let mid_theta: f32 = mid_u * TAU;
        let apex_n: Vec3 =
            safe_unit_normal(Vec3::new(nr * mid_theta.cos(), ny, nr * mid_theta.sin()));
        vertices.push(make_textured_vertex(
            Vec3::new(0.0, half_h, 0.0),
            apex_n,
            [mid_u, 1.0],
        ));
    }
    for j in 0..=sl {
        let u: f32 = (j as f32) / (sl as f32);
        let theta: f32 = u * TAU;
        let ct: f32 = theta.cos();
        let st: f32 = theta.sin();
        let normal: Vec3 = safe_unit_normal(Vec3::new(nr * ct, ny, nr * st));
        vertices.push(make_textured_vertex(
            Vec3::new(r * ct, -half_h, r * st),
            normal,
            [u, 0.0],
        ));
    }
    for j in 0..sl {
        let ju: u32 = j as u32;
        indices.push([ju, bot_base + ju + 1, bot_base + ju]);
    }
    let cap_center: u32 = vertices.len() as u32;
    let down: Vec3 = Vec3::new(0.0, -1.0, 0.0);
    vertices.push(make_textured_vertex(
        Vec3::new(0.0, -half_h, 0.0),
        down,
        [0.5, 0.5],
    ));
    let cap_ring: u32 = vertices.len() as u32;
    for j in 0..=sl {
        let theta: f32 = ((j as f32) / (sl as f32)) * TAU;
        let ct: f32 = theta.cos();
        let st: f32 = theta.sin();
        vertices.push(make_textured_vertex(
            Vec3::new(r * ct, -half_h, r * st),
            down,
            [0.5 + 0.5 * ct, 0.5 - 0.5 * st],
        ));
    }
    for j in 0..sl {
        let ju: u32 = j as u32;
        indices.push([cap_center, cap_ring + ju, cap_ring + ju + 1]);
    }
    finalize_primitive(PRIM_NAME_CONE, vertices, indices, true)
}

/// Builds a watertight torus lying in the XZ plane around the Y axis with analytic smooth normals.
///
/// # Arguments
///
/// - `f32` - Major ring radius from center to tube axis.
/// - `f32` - Minor tube cross-section radius.
/// - `u32` - Major ring segment count (clamped to `>= 6`).
/// - `u32` - Minor tube segment count (clamped to `>= 4`).
///
/// # Returns
///
/// - `Mesh3D` - Watertight outward-wound torus mesh.
#[must_use]
pub fn torus(major_r: f32, minor_r: f32, segs_u: u32, segs_v: u32) -> Mesh3D {
    let maj: f32 = sanitize_scalar(major_r, 1.0)
        .abs()
        .max(PRIM_MIN_RADIUS * 10.0);
    let min_r: f32 = sanitize_scalar(minor_r, 0.3)
        .abs()
        .clamp(PRIM_MIN_RADIUS, maj * 0.99);
    let nu: usize = segs_u.max(6) as usize;
    let nv: usize = segs_v.max(4) as usize;
    let stride: usize = nv + 1;
    let mut vertices: Vec<Vertex3D> = Vec::with_capacity((nu + 1) * stride);
    let mut indices: Vec<[u32; 3]> = Vec::with_capacity(nu * nv * 2);
    for iu in 0..=nu {
        let u_frac: f32 = (iu as f32) / (nu as f32);
        let u: f32 = u_frac * TAU;
        let cu: f32 = u.cos();
        let su: f32 = u.sin();
        for iv in 0..=nv {
            let v_frac: f32 = (iv as f32) / (nv as f32);
            let v: f32 = v_frac * TAU;
            let cv: f32 = v.cos();
            let sv: f32 = v.sin();
            let ring_r: f32 = maj + min_r * cv;
            let pos: Vec3 = Vec3::new(ring_r * cu, min_r * sv, ring_r * su);
            let normal: Vec3 = safe_unit_normal(Vec3::new(cv * cu, sv, cv * su));
            vertices.push(make_textured_vertex(pos, normal, [u_frac, v_frac]));
        }
    }
    for iu in 0..nu {
        let row0: u32 = (iu * stride) as u32;
        let row1: u32 = ((iu + 1) * stride) as u32;
        for iv in 0..nv {
            let jv: u32 = iv as u32;
            let i00: u32 = row0 + jv;
            let i01: u32 = row0 + jv + 1;
            let i10: u32 = row1 + jv;
            let i11: u32 = row1 + jv + 1;
            indices.push([i00, i01, i10]);
            indices.push([i01, i11, i10]);
        }
    }
    finalize_primitive(PRIM_NAME_TORUS, vertices, indices, true)
}

/// Computes the 1D bevel-grid `(inner_offset, unit_dir_tangent, uv_coord)` sample at step `idx`.
///
/// # Arguments
///
/// - `usize` - Grid index along the face axis in `0..=(2 * segs + 1)`.
/// - `usize` - Bevel segment count per rounded corner.
/// - `f32` - Inner flat-core half extent along this axis.
///
/// # Returns
///
/// - `(f32, f32, f32)` - Inner core coordinate, bevel tangent slope in `[-1, 1]`, and UV parameter in `[0, 1]`.
#[must_use]
fn rounded_box_axis_sample(idx: usize, segs: usize, inner_half: f32) -> (f32, f32, f32) {
    let total_steps: f32 = (2 * segs + 1) as f32;
    let uv: f32 = (idx as f32) / total_steps;
    let quarter_pi: f32 = FRAC_PI_2 * 0.5;
    if idx <= segs {
        let frac: f32 = 1.0 - (idx as f32) / (segs as f32);
        (-inner_half, -(frac * quarter_pi).tan(), uv)
    } else {
        let frac: f32 = ((idx - segs - 1) as f32) / (segs as f32);
        (inner_half, (frac * quarter_pi).tan(), uv)
    }
}

/// Builds a watertight beveled box centered at the origin with smooth circular edges and spherical corners.
///
/// # Arguments
///
/// - `Vec3` - Outer box dimensions `(width, height, depth)`.
/// - `f32` - Corner and edge bevel radius (clamped to half the smallest dimension).
/// - `u32` - Bevel arc segment count per corner (clamped to `1..=16`).
///
/// # Returns
///
/// - `Mesh3D` - Watertight outward-wound rounded box mesh.
#[must_use]
pub fn rounded_box(size: Vec3, bevel_radius: f32, bevel_segs: u32) -> Mesh3D {
    let clean_size: Vec3 = sanitize_vec3(size, Vec3::splat(1.0));
    let hx: f32 = clean_size.get_x().abs().max(PRIM_MIN_RADIUS * 2.0) * 0.5;
    let hy: f32 = clean_size.get_y().abs().max(PRIM_MIN_RADIUS * 2.0) * 0.5;
    let hz: f32 = clean_size.get_z().abs().max(PRIM_MIN_RADIUS * 2.0) * 0.5;
    let max_bevel: f32 = hx.min(hy).min(hz) * 0.95;
    let r: f32 = sanitize_scalar(bevel_radius, max_bevel * 0.25).clamp(0.0, max_bevel);
    let segs: usize = bevel_segs.clamp(1, PRIM_MAX_BEVEL_SEGS) as usize;
    let inner: Vec3 = Vec3::new(hx - r, hy - r, hz - r);
    let grid_n: usize = 2 * segs + 2;
    let face_defs: [(Vec3, Vec3, Vec3, f32, f32, f32); 6] = [
        (
            Vec3::new(1.0, 0.0, 0.0),
            Vec3::new(0.0, 1.0, 0.0),
            Vec3::new(0.0, 0.0, 1.0),
            inner.get_x(),
            inner.get_y(),
            inner.get_z(),
        ),
        (
            Vec3::new(-1.0, 0.0, 0.0),
            Vec3::new(0.0, 1.0, 0.0),
            Vec3::new(0.0, 0.0, -1.0),
            inner.get_x(),
            inner.get_y(),
            inner.get_z(),
        ),
        (
            Vec3::new(0.0, 0.0, -1.0),
            Vec3::new(0.0, 1.0, 0.0),
            Vec3::new(1.0, 0.0, 0.0),
            inner.get_z(),
            inner.get_y(),
            inner.get_x(),
        ),
        (
            Vec3::new(0.0, 0.0, 1.0),
            Vec3::new(0.0, 1.0, 0.0),
            Vec3::new(-1.0, 0.0, 0.0),
            inner.get_z(),
            inner.get_y(),
            inner.get_x(),
        ),
        (
            Vec3::new(1.0, 0.0, 0.0),
            Vec3::new(0.0, 0.0, -1.0),
            Vec3::new(0.0, 1.0, 0.0),
            inner.get_x(),
            inner.get_z(),
            inner.get_y(),
        ),
        (
            Vec3::new(1.0, 0.0, 0.0),
            Vec3::new(0.0, 0.0, 1.0),
            Vec3::new(0.0, -1.0, 0.0),
            inner.get_x(),
            inner.get_z(),
            inner.get_y(),
        ),
    ];
    let mut vertices: Vec<Vertex3D> = Vec::with_capacity(6 * grid_n * grid_n);
    let mut indices: Vec<[u32; 3]> = Vec::with_capacity(6 * (grid_n - 1) * (grid_n - 1) * 2);
    for &(u_axis, v_axis, w_axis, iu_half, iv_half, iw_half) in face_defs.iter() {
        let base: u32 = vertices.len() as u32;
        for iv in 0..grid_n {
            let (v_in, v_dir, uv_v): (f32, f32, f32) = rounded_box_axis_sample(iv, segs, iv_half);
            for iu in 0..grid_n {
                let (u_in, u_dir, uv_u): (f32, f32, f32) =
                    rounded_box_axis_sample(iu, segs, iu_half);
                let core_pt: Vec3 = u_axis
                    .scale(u_in)
                    .add(v_axis.scale(v_in))
                    .add(w_axis.scale(iw_half));
                let normal: Vec3 =
                    safe_unit_normal(u_axis.scale(u_dir).add(v_axis.scale(v_dir)).add(w_axis));
                let pos: Vec3 = core_pt.add(normal.scale(r));
                let final_normal: Vec3 = if r > 1e-6 { normal } else { w_axis };
                vertices.push(make_textured_vertex(pos, final_normal, [uv_u, uv_v]));
            }
        }
        for iv in 0..(grid_n - 1) {
            for iu in 0..(grid_n - 1) {
                let i00: u32 = base + (iv * grid_n + iu) as u32;
                let i10: u32 = base + (iv * grid_n + iu + 1) as u32;
                let i01: u32 = base + ((iv + 1) * grid_n + iu) as u32;
                let i11: u32 = base + ((iv + 1) * grid_n + iu + 1) as u32;
                indices.push([i00, i10, i11]);
                indices.push([i00, i11, i01]);
            }
        }
    }
    finalize_primitive(PRIM_NAME_ROUNDED_BOX, vertices, indices, true)
}

/// Builds a watertight geodesic hemisphere resting on `y = 0` with a flat circular base cap.
///
/// # Arguments
///
/// - `f32` - Dome radius (clamped to `>= 1e-4`).
/// - `u32` - Geodesic subdivision depth (clamped to `0..=5`).
///
/// # Returns
///
/// - `Mesh3D` - Watertight outward-wound geodesic dome mesh.
#[must_use]
pub fn geodesic_dome(radius: f32, subdivisions: u32) -> Mesh3D {
    let r: f32 = sanitize_scalar(radius, 1.0).abs().max(PRIM_MIN_RADIUS);
    let levels: u32 = subdivisions.min(PRIM_MAX_SUBDIV);
    let mut dirs: Vec<Vec3> = vec![
        Vec3::new(0.0, 1.0, 0.0),
        Vec3::new(1.0, 0.0, 0.0),
        Vec3::new(0.0, 0.0, 1.0),
        Vec3::new(-1.0, 0.0, 0.0),
        Vec3::new(0.0, 0.0, -1.0),
    ];
    let mut faces: Vec<[u32; 3]> = vec![[0, 2, 1], [0, 3, 2], [0, 4, 3], [0, 1, 4]];
    for _ in 0..levels {
        let mut cache: HashMap<(u32, u32), u32> = HashMap::with_capacity(faces.len() * 3);
        let mut next_faces: Vec<[u32; 3]> = Vec::with_capacity(faces.len() * 4);
        for tri in faces.iter() {
            let a: u32 = tri[0];
            let b: u32 = tri[1];
            let c: u32 = tri[2];
            let ab: u32 = sphere_midpoint(a, b, &mut dirs, &mut cache);
            let bc: u32 = sphere_midpoint(b, c, &mut dirs, &mut cache);
            let ca: u32 = sphere_midpoint(c, a, &mut dirs, &mut cache);
            next_faces.push([a, ab, ca]);
            next_faces.push([b, bc, ab]);
            next_faces.push([c, ca, bc]);
            next_faces.push([ab, bc, ca]);
        }
        faces = next_faces;
    }
    let mut equator: Vec<(f32, Vec3)> = Vec::new();
    for dir in dirs.iter_mut() {
        if dir.get_y().abs() < 1e-4 {
            let flat: Vec3 = safe_unit_normal(Vec3::new(dir.get_x(), 0.0, dir.get_z()));
            *dir = flat;
            let angle: f32 = flat.get_z().atan2(flat.get_x());
            equator.push((angle, flat));
        }
    }
    equator.sort_by(|a: &(f32, Vec3), b: &(f32, Vec3)| a.0.total_cmp(&b.0));
    let mut vertices: Vec<Vertex3D> = Vec::with_capacity(dirs.len() + equator.len() + 1);
    for &unit_dir in dirs.iter() {
        vertices.push(make_textured_vertex(
            unit_dir.scale(r),
            unit_dir,
            spherical_uv(unit_dir),
        ));
    }
    let cap_center: u32 = vertices.len() as u32;
    let down: Vec3 = Vec3::new(0.0, -1.0, 0.0);
    vertices.push(make_textured_vertex(Vec3::zero(), down, [0.5, 0.5]));
    let cap_ring_base: u32 = vertices.len() as u32;
    for &(_, eq_dir) in equator.iter() {
        vertices.push(make_textured_vertex(
            eq_dir.scale(r),
            down,
            [0.5 + 0.5 * eq_dir.get_x(), 0.5 - 0.5 * eq_dir.get_z()],
        ));
    }
    let eq_len: usize = equator.len();
    for i in 0..eq_len {
        let next: usize = (i + 1) % eq_len;
        faces.push([
            cap_center,
            cap_ring_base + (i as u32),
            cap_ring_base + (next as u32),
        ]);
    }
    finalize_primitive(PRIM_NAME_GEODESIC_DOME, vertices, faces, true)
}

/// Builds a watertight regular N-sided prism centered at the origin with crisp flat face normals.
///
/// # Arguments
///
/// - `u32` - Number of lateral polygon sides (clamped to `>= 3`).
/// - `f32` - Circumradius of the regular polygon cross-section.
/// - `f32` - Prism height along Y.
///
/// # Returns
///
/// - `Mesh3D` - Watertight outward-wound regular prism mesh.
#[must_use]
pub fn prism(sides: u32, radius: f32, height: f32) -> Mesh3D {
    let n: usize = sides.max(3) as usize;
    let r: f32 = sanitize_scalar(radius, 0.5).abs().max(PRIM_MIN_RADIUS);
    let h: f32 = sanitize_scalar(height, 1.0).abs().max(PRIM_MIN_RADIUS);
    let half_h: f32 = h * 0.5;
    let mut ring_xz: Vec<(f32, f32)> = Vec::with_capacity(n);
    for i in 0..n {
        let theta: f32 = ((i as f32) / (n as f32)) * TAU;
        ring_xz.push((r * theta.cos(), r * theta.sin()));
    }
    let mut vertices: Vec<Vertex3D> = Vec::with_capacity(n * 6 + 2);
    let mut indices: Vec<[u32; 3]> = Vec::with_capacity(n * 4);
    for i in 0..n {
        let next: usize = (i + 1) % n;
        let (x0, z0): (f32, f32) = ring_xz[i];
        let (x1, z1): (f32, f32) = ring_xz[next];
        let p_t0: Vec3 = Vec3::new(x0, half_h, z0);
        let p_t1: Vec3 = Vec3::new(x1, half_h, z1);
        let p_b0: Vec3 = Vec3::new(x0, -half_h, z0);
        let p_b1: Vec3 = Vec3::new(x1, -half_h, z1);
        let face_n: Vec3 = safe_unit_normal(p_t1.sub(p_t0).cross(p_b0.sub(p_t0)));
        let base: u32 = vertices.len() as u32;
        vertices.push(make_textured_vertex(p_t0, face_n, [0.0, 1.0]));
        vertices.push(make_textured_vertex(p_t1, face_n, [1.0, 1.0]));
        vertices.push(make_textured_vertex(p_b0, face_n, [0.0, 0.0]));
        vertices.push(make_textured_vertex(p_b1, face_n, [1.0, 0.0]));
        indices.push([base, base + 1, base + 2]);
        indices.push([base + 1, base + 3, base + 2]);
    }
    let up: Vec3 = Vec3::new(0.0, 1.0, 0.0);
    let top_center: u32 = vertices.len() as u32;
    vertices.push(make_textured_vertex(
        Vec3::new(0.0, half_h, 0.0),
        up,
        [0.5, 0.5],
    ));
    let top_base: u32 = vertices.len() as u32;
    for &(x, z) in ring_xz.iter() {
        vertices.push(make_textured_vertex(
            Vec3::new(x, half_h, z),
            up,
            [0.5 + 0.5 * (x / r), 0.5 + 0.5 * (z / r)],
        ));
    }
    for i in 0..n {
        let next: usize = (i + 1) % n;
        indices.push([top_center, top_base + (next as u32), top_base + (i as u32)]);
    }
    let down: Vec3 = Vec3::new(0.0, -1.0, 0.0);
    let bot_center: u32 = vertices.len() as u32;
    vertices.push(make_textured_vertex(
        Vec3::new(0.0, -half_h, 0.0),
        down,
        [0.5, 0.5],
    ));
    let bot_base: u32 = vertices.len() as u32;
    for &(x, z) in ring_xz.iter() {
        vertices.push(make_textured_vertex(
            Vec3::new(x, -half_h, z),
            down,
            [0.5 + 0.5 * (x / r), 0.5 - 0.5 * (z / r)],
        ));
    }
    for i in 0..n {
        let next: usize = (i + 1) % n;
        indices.push([bot_center, bot_base + (i as u32), bot_base + (next as u32)]);
    }
    finalize_primitive(PRIM_NAME_PRISM, vertices, indices, true)
}

/// Builds a subdivided horizontal XZ plane grid centered at the origin with `+Y` upward normals.
///
/// # Arguments
///
/// - `f32` - Plane width along X.
/// - `f32` - Plane depth along Z.
/// - `u32` - Grid segment count along X (clamped to `>= 1`).
/// - `u32` - Grid segment count along Z (clamped to `>= 1`).
///
/// # Returns
///
/// - `Mesh3D` - Open subdivided plane grid mesh with clean `[0, 1]^2` UVs.
#[must_use]
pub fn plane_grid(width: f32, height: f32, segs_x: u32, segs_z: u32) -> Mesh3D {
    let w: f32 = sanitize_scalar(width, 1.0).abs().max(PRIM_MIN_RADIUS);
    let d: f32 = sanitize_scalar(height, 1.0).abs().max(PRIM_MIN_RADIUS);
    let sx: usize = segs_x.max(1) as usize;
    let sz: usize = segs_z.max(1) as usize;
    let stride: usize = sx + 1;
    let up: Vec3 = Vec3::new(0.0, 1.0, 0.0);
    let mut vertices: Vec<Vertex3D> = Vec::with_capacity((sz + 1) * stride);
    let mut indices: Vec<[u32; 3]> = Vec::with_capacity(sx * sz * 2);
    for iz in 0..=sz {
        let v: f32 = (iz as f32) / (sz as f32);
        let z: f32 = (v - 0.5) * d;
        for ix in 0..=sx {
            let u: f32 = (ix as f32) / (sx as f32);
            let x: f32 = (u - 0.5) * w;
            vertices.push(make_textured_vertex(Vec3::new(x, 0.0, z), up, [u, v]));
        }
    }
    for iz in 0..sz {
        let row0: u32 = (iz * stride) as u32;
        let row1: u32 = ((iz + 1) * stride) as u32;
        for ix in 0..sx {
            let jx: u32 = ix as u32;
            let i00: u32 = row0 + jx;
            let i10: u32 = row0 + jx + 1;
            let i01: u32 = row1 + jx;
            let i11: u32 = row1 + jx + 1;
            indices.push([i00, i01, i10]);
            indices.push([i01, i11, i10]);
        }
    }
    finalize_primitive(PRIM_NAME_PLANE_GRID, vertices, indices, false)
}