ferravex_render/
mesh.rs

1//! Reusable geometry with face normals for lit 3D scenes.
2use crate::prelude::*;
3
4/// Construct once and draw many times. Mesh dimensions are baked into vertices;
5/// draw transforms use only rotation/translation to keep normals correct.
6pub struct Mesh3d {
7    pub mesh: Mesh,
8    cached: std::cell::OnceCell<crate::retained::ResidentMesh>,
9}
10
11impl Mesh3d {
12    pub fn from_mesh(mesh: Mesh) -> Self {
13        Self {
14            mesh,
15            cached: Default::default(),
16        }
17    }
18    /// Bake opaque, untextured static parts into one bounded resident mesh.
19    /// Group nearby parts so the combined bounds remain useful for culling.
20    /// Transforms must be finite, invertible and affine; reflections reverse
21    /// triangle winding and use inverse-transpose normals. Source meshes survive
22    /// any error. Build once at load time, never per frame.
23    pub fn combine<'a>(
24        parts: impl IntoIterator<Item = (&'a Mesh, Mat4)>,
25    ) -> Result<Self, &'static str> {
26        let mut vertices = Vec::new();
27        let mut indices = Vec::new();
28        for (mesh, model) in parts {
29            if mesh.texture.is_some()
30                || !mesh.indices.len().is_multiple_of(3)
31                || mesh
32                    .indices
33                    .iter()
34                    .any(|&i| i as usize >= mesh.vertices.len())
35                || mesh
36                    .vertices
37                    .iter()
38                    .any(|v| !v.position.is_finite() || !v.normal.is_finite() || v.color[3] != 255)
39                || !model.is_finite()
40                || model.row(3) != Vec4::W
41            {
42                return Err("static batches require valid opaque untextured affine meshes");
43            }
44            if vertices.len() + mesh.vertices.len() > u16::MAX as usize {
45                return Err("static batch exceeds 65535 vertices");
46            }
47            let normal = model
48                .try_inverse()
49                .ok_or("singular static transform")?
50                .transpose();
51            let base = vertices.len() as u16;
52            for source in &mesh.vertices {
53                let mut v = *source;
54                v.position = model.transform_point3(v.position);
55                v.normal = normal
56                    .transform_vector3(v.normal.truncate())
57                    .normalize_or_zero()
58                    .extend(0.);
59                if !v.position.is_finite() || !v.normal.is_finite() {
60                    return Err("static transform overflow");
61                }
62                vertices.push(v);
63            }
64            let mirrored = model.determinant() < 0.;
65            for &[a, b, c] in mesh.indices.as_chunks::<3>().0 {
66                indices.extend(if mirrored {
67                    [base + a, base + c, base + b]
68                } else {
69                    [base + a, base + b, base + c]
70                });
71            }
72        }
73        if indices.is_empty() {
74            return Err("empty static batch");
75        }
76        Ok(Self::from_mesh(Mesh {
77            vertices,
78            indices,
79            texture: None,
80        }))
81    }
82    /// Invalidate the GPU snapshot after editing the public source mesh.
83    pub fn invalidate_gpu(&mut self) {
84        self.cached.take();
85    }
86    pub fn resident(&self) -> &crate::retained::ResidentMesh {
87        self.cached.get_or_init(|| {
88            crate::retained::ResidentMesh::new(&self.mesh).expect("valid retained Mesh3d")
89        })
90    }
91    pub fn draw_transformed(&self, model: Mat4) {
92        crate::draw_resident(self.resident(), model);
93    }
94    /// CPU path for geometry whose exact submission order must be preserved.
95    pub fn draw_immediate(&self, model: Mat4) {
96        crate::draw_mesh_transformed(&self.mesh, model);
97    }
98
99    /// Tessellated XZ ground plane centered at the origin, facing positive Y.
100    /// Subdivision provides nearby vertices for vertex lighting/distance fog on large surfaces.
101    /// Bounded to 1..=28 cells per side to keep low-poly scenes inexpensive.
102    pub fn plane(size: Vec2, color: Color, subdivisions: u16) -> Self {
103        assert!(
104            size.is_finite() && size.min_element() > 0.0,
105            "plane size must be finite and positive"
106        );
107        let n = subdivisions.clamp(1, 28);
108        let stride = n + 1;
109        let mut vertices = Vec::with_capacity(stride as usize * stride as usize);
110        let mut indices = Vec::with_capacity(n as usize * n as usize * 6);
111        for z in 0..=n {
112            for x in 0..=n {
113                let uv = vec2(x as f32, z as f32) / n as f32;
114                let position = (uv - Vec2::splat(0.5)) * size;
115                let mut vertex = Vertex::new2(vec3(position.x, 0.0, position.y), uv, color);
116                vertex.normal = Vec3::Y.extend(0.0);
117                vertices.push(vertex);
118            }
119        }
120        for z in 0..n {
121            for x in 0..n {
122                let a = z * stride + x;
123                let b = a + stride;
124                indices.extend([a, b, a + 1, a + 1, b, b + 1]);
125            }
126        }
127        Self {
128            cached: Default::default(),
129            mesh: Mesh {
130                vertices,
131                indices,
132                texture: None,
133            },
134        }
135    }
136
137    /// Flat-shaded, capped cylinder along Y. Construct once and reuse for props.
138    pub fn cylinder(radius: f32, height: f32, color: Color, segments: u16) -> Self {
139        Self::frustum(radius, radius, height, color, segments)
140    }
141
142    /// Flat-shaded cone along Y, with its tip at positive Y.
143    pub fn cone(radius: f32, height: f32, color: Color, segments: u16) -> Self {
144        Self::frustum(radius, 0.0, height, color, segments)
145    }
146
147    /// Capped tapered prism; radii are at negative/positive Y respectively.
148    /// Zero-radius caps are omitted. Tessellation is bounded to 3..=128 sides.
149    pub fn frustum(bottom: f32, top: f32, height: f32, color: Color, segments: u16) -> Self {
150        assert!(
151            bottom.is_finite()
152                && top.is_finite()
153                && bottom >= 0.0
154                && top >= 0.0
155                && bottom.max(top) > 0.0
156                && height.is_finite()
157                && height > 0.0,
158            "frustum dimensions must be finite with positive height and at least one positive radius"
159        );
160        let segments = segments.clamp(3, 128);
161        let mut vertices = Vec::with_capacity(segments as usize * 12);
162        let mut triangle = |a: Vec3, b: Vec3, c: Vec3| {
163            let cross = (b - a).cross(c - a);
164            if cross.length_squared() < 1e-16 {
165                return;
166            }
167            let normal = cross.normalize().extend(0.0);
168            for position in [a, b, c] {
169                let mut vertex = Vertex::new2(position, Vec2::ZERO, color);
170                vertex.normal = normal;
171                vertices.push(vertex);
172            }
173        };
174        let y = height * 0.5;
175        for i in 0..segments {
176            let angle = |n: u16| n as f32 / segments as f32 * std::f32::consts::TAU;
177            let ring = |theta: f32, radius: f32, y: f32| {
178                vec3(theta.cos() * radius, y, theta.sin() * radius)
179            };
180            let a = ring(angle(i), bottom, -y);
181            let b = ring(angle(i + 1), bottom, -y);
182            let c = ring(angle(i), top, y);
183            let d = ring(angle(i + 1), top, y);
184            triangle(a, c, b);
185            triangle(b, c, d);
186            triangle(vec3(0.0, -y, 0.0), a, b);
187            triangle(vec3(0.0, y, 0.0), d, c);
188        }
189        let indices = (0..vertices.len() as u16).collect();
190        Self {
191            cached: Default::default(),
192            mesh: Mesh {
193                vertices,
194                indices,
195                texture: None,
196            },
197        }
198    }
199
200    pub fn cuboid(size: Vec3, color: Color) -> Self {
201        assert!(
202            size.is_finite() && size.min_element() > 0.0,
203            "cuboid size must be finite and positive"
204        );
205        let mut vertices = Vec::with_capacity(24);
206        let mut indices = Vec::with_capacity(36);
207        let faces = [
208            (Vec3::X, Vec3::Y, Vec3::Z),
209            (-Vec3::X, Vec3::Y, -Vec3::Z),
210            (Vec3::Y, Vec3::Z, Vec3::X),
211            (-Vec3::Y, Vec3::Z, -Vec3::X),
212            (Vec3::Z, Vec3::X, Vec3::Y),
213            (-Vec3::Z, Vec3::X, -Vec3::Y),
214        ];
215        for (normal, u, v) in faces {
216            let base = vertices.len() as u16;
217            for (a, b) in [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)] {
218                let mut vertex = Vertex::new2(
219                    (normal + u * a + v * b) * size * 0.5,
220                    vec2((a + 1.0) * 0.5, (b + 1.0) * 0.5),
221                    color,
222                );
223                vertex.normal = normal.extend(0.0);
224                vertices.push(vertex);
225            }
226            indices.extend([base, base + 1, base + 2, base, base + 2, base + 3]);
227        }
228        Self {
229            cached: Default::default(),
230            mesh: Mesh {
231                vertices,
232                indices,
233                texture: None,
234            },
235        }
236    }
237
238    /// Faceted sphere. Latitude rings are bounded to retain a low-poly budget.
239    pub fn sphere(radius: f32, color: Color, segments: u16, rings: u16) -> Self {
240        assert!(
241            radius.is_finite() && radius > 0.0,
242            "sphere radius must be finite and positive"
243        );
244        let segments = segments.clamp(3, 64);
245        // A flat sphere has 6 * segments * (rings - 1) nondegenerate vertices/indices.
246        // Retain the original examples' 5,000-index budget even at maximum detail.
247        let rings = rings.clamp(2, 64).min(1 + 4998 / (6 * segments));
248        let mut vertices = Vec::with_capacity((segments as usize + 1) * (rings as usize + 1));
249        let mut indices = Vec::with_capacity(segments as usize * rings as usize * 6);
250        for y in 0..=rings {
251            let v = y as f32 / rings as f32;
252            let phi = v * std::f32::consts::PI;
253            for x in 0..=segments {
254                let u = x as f32 / segments as f32;
255                let theta = u * std::f32::consts::TAU;
256                let normal = if y == 0 {
257                    Vec3::Y
258                } else if y == rings {
259                    -Vec3::Y
260                } else {
261                    vec3(phi.sin() * theta.cos(), phi.cos(), phi.sin() * theta.sin())
262                };
263                let mut vertex = Vertex::new2(normal * radius, vec2(u, v), color);
264                vertex.normal = normal.extend(0.0);
265                vertices.push(vertex);
266            }
267        }
268        for y in 0..rings {
269            for x in 0..segments {
270                let a = y * (segments + 1) + x;
271                let b = a + segments + 1;
272                indices.extend([a, b, a + 1, a + 1, b, b + 1]);
273            }
274        }
275        // Duplicate triangle vertices so each facet receives its own normal.
276        // This intentionally preserves a low-poly silhouette and flat lighting.
277        let mut flat_vertices = Vec::with_capacity(indices.len());
278        for triangle in indices.as_chunks::<3>().0 {
279            // Calculate on the unit sphere so degeneracy tests and face normals
280            // remain stable for both small projectiles and large scenery.
281            let a = vertices[triangle[0] as usize].normal.truncate();
282            let b = vertices[triangle[1] as usize].normal.truncate();
283            let c = vertices[triangle[2] as usize].normal.truncate();
284            let cross = (b - a).cross(c - a);
285            if cross.length_squared() < 1e-12 {
286                continue;
287            }
288            let outward = cross.dot(a + b + c) >= 0.0;
289            let normal = if outward { cross } else { -cross }.normalize();
290            // Winding agrees with the face normal, including on back-face-culling hosts.
291            let order = if outward {
292                *triangle
293            } else {
294                [triangle[0], triangle[2], triangle[1]]
295            };
296            for i in order {
297                let mut vertex = vertices[i as usize];
298                vertex.normal = normal.extend(0.0);
299                flat_vertices.push(vertex);
300            }
301        }
302        // Also catches unexpected extra triangles at the poles from numeric drift.
303        assert!(
304            flat_vertices.len() < 5000,
305            "sphere tessellation exceeds the low-poly index budget"
306        );
307        let flat_indices = (0..flat_vertices.len() as u16).collect();
308        Self {
309            cached: Default::default(),
310            mesh: Mesh {
311                vertices: flat_vertices,
312                indices: flat_indices,
313                texture: None,
314            },
315        }
316    }
317
318    pub fn draw(&self, position: Vec3, rotation: Quat) {
319        self.draw_transformed(Mat4::from_rotation_translation(rotation, position));
320    }
321}
322
323#[cfg(test)]
324mod tests {
325    use super::*;
326
327    #[test]
328    fn maximum_sphere_requests_remain_complete_within_renderer_limits() {
329        for (segments, rings) in [(64, 64), (u16::MAX, u16::MAX), (3, 64), (16, 64)] {
330            let sphere = Mesh3d::sphere(1.0, WHITE, segments, rings);
331            assert!(sphere.mesh.indices.len() < 5000);
332            assert!(sphere.mesh.vertices.len() < 10000);
333            for axis in [Vec3::X, Vec3::Y, Vec3::Z, -Vec3::X, -Vec3::Y, -Vec3::Z] {
334                assert!(
335                    sphere
336                        .mesh
337                        .vertices
338                        .iter()
339                        .any(|v| v.position.dot(axis) > 0.4)
340                );
341            }
342        }
343        for radius in [0.001, 1.0, 1000.0] {
344            let sphere = Mesh3d::sphere(radius, WHITE, 64, 64);
345            assert_eq!(sphere.mesh.indices.len(), 4992);
346            assert!(sphere.mesh.vertices.iter().all(|v| v.normal.is_finite()));
347        }
348    }
349
350    #[test]
351    fn mesh_indices_and_normals_are_valid() {
352        for shape in [
353            Mesh3d::cuboid(vec3(1.0, 2.0, 3.0), WHITE),
354            Mesh3d::sphere(1.0, WHITE, 16, 12),
355            Mesh3d::cylinder(1.0, 2.0, WHITE, 12),
356            Mesh3d::cone(1.0, 2.0, WHITE, 6),
357            Mesh3d::plane(vec2(100.0, 100.0), WHITE, 20),
358        ] {
359            assert!(
360                shape
361                    .mesh
362                    .indices
363                    .iter()
364                    .all(|&i| (i as usize) < shape.mesh.vertices.len())
365            );
366            assert!(
367                shape
368                    .mesh
369                    .vertices
370                    .iter()
371                    .all(|v| (v.normal.truncate().length() - 1.0).abs() < 0.0001)
372            );
373        }
374    }
375
376    #[test]
377    fn triangle_winding_matches_outward_flat_normals() {
378        for shape in [
379            Mesh3d::cuboid(vec3(1.0, 2.0, 3.0), WHITE),
380            Mesh3d::sphere(1.0, WHITE, 12, 8),
381            Mesh3d::sphere(0.001, WHITE, 64, 64),
382            Mesh3d::cylinder(1.0, 2.0, WHITE, 12),
383            Mesh3d::cone(1.0, 2.0, WHITE, 6),
384            Mesh3d::frustum(0.0, 1.0, 2.0, WHITE, 6),
385            Mesh3d::plane(vec2(20.0, 10.0), WHITE, 8),
386        ] {
387            for triangle in shape.mesh.indices.as_chunks::<3>().0 {
388                let [a, b, c] = triangle.map(|i| shape.mesh.vertices[i as usize]);
389                let winding = (b.position - a.position).cross(c.position - a.position);
390                assert!(winding.dot(a.normal.truncate()) > 0.0);
391                assert!(a.normal.abs_diff_eq(b.normal, 0.0001));
392                assert!(a.normal.abs_diff_eq(c.normal, 0.0001));
393            }
394        }
395    }
396
397    #[test]
398    fn cylinder_and_cone_segments_are_bounded_without_broken_caps() {
399        for segments in [0, 1, 2, 128, u16::MAX] {
400            let expected = usize::from(segments.clamp(3, 128));
401            for (shape, per_segment) in [
402                (Mesh3d::cylinder(1.0, 2.0, WHITE, segments), 12),
403                (Mesh3d::cone(1.0, 2.0, WHITE, segments), 6),
404            ] {
405                assert_eq!(shape.mesh.indices.len(), expected * per_segment);
406                assert_eq!(shape.mesh.indices.len(), shape.mesh.vertices.len());
407                assert!(shape.mesh.vertices.iter().all(|v| v.normal.is_finite()));
408            }
409        }
410    }
411
412    #[test]
413    fn invalid_mesh_dimensions_are_rejected_before_recording() {
414        for invalid in [0.0, -1.0, f32::INFINITY, f32::NAN] {
415            assert!(std::panic::catch_unwind(|| Mesh3d::sphere(invalid, WHITE, 8, 6)).is_err());
416            assert!(
417                std::panic::catch_unwind(|| Mesh3d::cuboid(Vec3::splat(invalid), WHITE)).is_err()
418            );
419            assert!(
420                std::panic::catch_unwind(|| Mesh3d::plane(Vec2::splat(invalid), WHITE, 4)).is_err()
421            );
422            assert!(std::panic::catch_unwind(|| Mesh3d::cylinder(1.0, invalid, WHITE, 8)).is_err());
423        }
424    }
425
426    #[test]
427    fn tapered_mesh_faces_point_outward_and_caps_close() {
428        for shape in [
429            Mesh3d::cylinder(1.0, 2.0, WHITE, 8),
430            Mesh3d::cone(1.0, 2.0, WHITE, 8),
431        ] {
432            for face in shape.mesh.vertices.as_chunks::<3>().0 {
433                let center = (face[0].position + face[1].position + face[2].position) / 3.0;
434                let normal = face[0].normal.truncate();
435                assert!(normal.dot(center) > 0.0);
436            }
437        }
438        assert_eq!(
439            Mesh3d::cylinder(1.0, 2.0, WHITE, 8).mesh.indices.len(),
440            8 * 12
441        );
442        assert_eq!(Mesh3d::cone(1.0, 2.0, WHITE, 8).mesh.indices.len(), 8 * 6);
443    }
444
445    #[test]
446    fn ground_plane_has_nearby_vertices_correct_winding_and_bounded_batches() {
447        let plane = Mesh3d::plane(vec2(440.0, 440.0), WHITE, 22);
448        assert!(
449            plane
450                .mesh
451                .vertices
452                .iter()
453                .any(|v| v.position.length() < 0.001)
454        );
455        for triangle in plane.mesh.indices.as_chunks::<3>().0 {
456            let [a, b, c] = [triangle[0], triangle[1], triangle[2]]
457                .map(|i| plane.mesh.vertices[i as usize].position);
458            assert!((b - a).cross(c - a).y > 0.0);
459        }
460        assert!(Mesh3d::plane(Vec2::ONE, WHITE, u16::MAX).mesh.indices.len() < 5000);
461    }
462}
463
464#[cfg(test)]
465mod static_batch_tests {
466    use super::*;
467    #[test]
468    fn reflected_static_parts_keep_outward_normals_and_source_geometry() {
469        let a = Mesh3d::cuboid(Vec3::ONE, WHITE);
470        let transform = Mat4::from_scale_rotation_translation(
471            vec3(-2., 1., 0.5),
472            Quat::from_rotation_y(0.3),
473            Vec3::X * 3.,
474        );
475        let combined = Mesh3d::combine([(&a.mesh, Mat4::IDENTITY), (&a.mesh, transform)]).unwrap();
476        assert_eq!(combined.mesh.vertices.len(), a.mesh.vertices.len() * 2);
477        assert_eq!(combined.mesh.indices.len(), a.mesh.indices.len() * 2);
478        for triangle in combined.mesh.indices.as_chunks::<3>().0 {
479            let [a, b, c] = triangle.map(|i| combined.mesh.vertices[i as usize]);
480            let normal = (b.position - a.position)
481                .cross(c.position - a.position)
482                .normalize();
483            assert!(normal.dot(a.normal.truncate()) > 0.999);
484        }
485        assert!(Mesh3d::combine([(&a.mesh, Mat4::from_scale(Vec3::ZERO))]).is_err());
486        assert!(Mesh3d::combine(std::iter::empty()).is_err());
487        assert!(Mesh3d::combine(std::iter::repeat_n((&a.mesh, Mat4::IDENTITY), 3000)).is_err());
488    }
489}