Skip to main content

oa/render/
mesh.rs

1//! Stateless mesh math and geometry generation.
2//!
3//! Operates on [`MeshData`] and [`MeshVertex`]. All construction functions
4//! return new values; mutation operations take `&mut MeshData` and leave the
5//! mesh unchanged on failure.
6//!
7//! Donor: `oacpp/source/cpp/include/oa/render/fnMesh.h` (`oa::FnMesh`).
8//! Adaptation: C++ static namespace members become module functions;
9//! trivial size/count queries (`getVertexCount` etc.) are omitted because
10//! callers use `.vertices.len()` and `.indices.len()` directly.
11
12use crate::{
13	Error, Result,
14	vlm::{Mat4, Vec3},
15};
16
17use super::scene::{MeshData, MeshVertex};
18
19// ── Aabb ──────────────────────────────────────────────────────────────────────
20
21/// Axis-aligned bounding box.
22///
23/// Donor: `oa::Aabb` in `oacpp/source/cpp/include/oa/render/fnMesh.h`.
24#[derive(Clone, Copy, Debug, Default, PartialEq)]
25pub struct Aabb {
26	/// Minimum corner (smallest X, Y, Z).
27	pub min: Vec3,
28	/// Maximum corner (largest X, Y, Z).
29	pub max: Vec3,
30}
31
32impl Aabb {
33	/// Return the center of the box.
34	pub fn center(self) -> Vec3 {
35		Vec3 {
36			x: (self.min.x + self.max.x) * 0.5,
37			y: (self.min.y + self.max.y) * 0.5,
38			z: (self.min.z + self.max.z) * 0.5,
39		}
40	}
41
42	/// Return the per-axis extent (max − min).
43	pub fn extent(self) -> Vec3 {
44		Vec3 {
45			x: self.max.x - self.min.x,
46			y: self.max.y - self.min.y,
47			z: self.max.z - self.min.z,
48		}
49	}
50
51	/// Return the signed volume of the box.
52	pub fn volume(self) -> f32 {
53		let e = self.extent();
54		e.x * e.y * e.z
55	}
56
57	/// Return `true` when `point` is within or on the surface of the box.
58	pub fn contains(self, point: Vec3) -> bool {
59		point.x >= self.min.x
60			&& point.x <= self.max.x
61			&& point.y >= self.min.y
62			&& point.y <= self.max.y
63			&& point.z >= self.min.z
64			&& point.z <= self.max.z
65	}
66}
67
68// ── Geometry generation ───────────────────────────────────────────────────────
69
70/// Create a centered quad (2 triangles, 4 vertices) with top-origin image UVs.
71///
72/// UV V=0 is the source-image top and world +Y is the quad top.
73/// For image/video viewing, pass the pixel dimensions (e.g. 1920, 1080).
74///
75/// `width` and `height` must be finite and positive.
76///
77/// Donor: `oa::FnMesh::createQuad`.
78///
79/// # Errors
80///
81/// Returns an error for non-finite or non-positive dimensions.
82pub fn create_quad(width: f32, height: f32) -> Result<MeshData> {
83	if !width.is_finite() || !height.is_finite() || width <= 0.0 || height <= 0.0 {
84		return Err(Error::invalid_argument(
85			"render::create_quad requires finite positive width and height",
86		));
87	}
88	let hx = width * 0.5;
89	let hy = height * 0.5;
90	let n = Vec3 {
91		x: 0.0,
92		y: 0.0,
93		z: 1.0,
94	};
95	let c = crate::vlm::Vec4 {
96		x: 1.0,
97		y: 1.0,
98		z: 1.0,
99		w: 1.0,
100	};
101	let mut mesh = MeshData {
102		vertices: vec![
103			MeshVertex {
104				position: Vec3 {
105					x: -hx,
106					y: hy,
107					z: 0.0,
108				},
109				normal: n,
110				uv: crate::vlm::Vec2 { x: 0.0, y: 0.0 },
111				color: c,
112			},
113			MeshVertex {
114				position: Vec3 {
115					x: hx,
116					y: hy,
117					z: 0.0,
118				},
119				normal: n,
120				uv: crate::vlm::Vec2 { x: 1.0, y: 0.0 },
121				color: c,
122			},
123			MeshVertex {
124				position: Vec3 {
125					x: hx,
126					y: -hy,
127					z: 0.0,
128				},
129				normal: n,
130				uv: crate::vlm::Vec2 { x: 1.0, y: 1.0 },
131				color: c,
132			},
133			MeshVertex {
134				position: Vec3 {
135					x: -hx,
136					y: -hy,
137					z: 0.0,
138				},
139				normal: n,
140				uv: crate::vlm::Vec2 { x: 0.0, y: 1.0 },
141				color: c,
142			},
143		],
144		indices: vec![0, 1, 2, 0, 2, 3],
145		bounds: Aabb::default(),
146		bounds_dirty: true,
147	};
148	compute_bounds(&mut mesh);
149	Ok(mesh)
150}
151
152/// Create a fullscreen NDC quad (2 triangles, 4 vertices) in `[-1, 1]` XY
153/// with top-origin image UVs. Used for post-processing passes.
154///
155/// Donor: `oa::FnMesh::createFullscreenQuad`.
156pub fn create_fullscreen_quad() -> MeshData {
157	let n = Vec3 {
158		x: 0.0,
159		y: 0.0,
160		z: 1.0,
161	};
162	let c = crate::vlm::Vec4 {
163		x: 1.0,
164		y: 1.0,
165		z: 1.0,
166		w: 1.0,
167	};
168	let mut mesh = MeshData {
169		vertices: vec![
170			MeshVertex {
171				position: Vec3 {
172					x: -1.0,
173					y: 1.0,
174					z: 0.0,
175				},
176				normal: n,
177				uv: crate::vlm::Vec2 { x: 0.0, y: 0.0 },
178				color: c,
179			},
180			MeshVertex {
181				position: Vec3 {
182					x: 1.0,
183					y: 1.0,
184					z: 0.0,
185				},
186				normal: n,
187				uv: crate::vlm::Vec2 { x: 1.0, y: 0.0 },
188				color: c,
189			},
190			MeshVertex {
191				position: Vec3 {
192					x: 1.0,
193					y: -1.0,
194					z: 0.0,
195				},
196				normal: n,
197				uv: crate::vlm::Vec2 { x: 1.0, y: 1.0 },
198				color: c,
199			},
200			MeshVertex {
201				position: Vec3 {
202					x: -1.0,
203					y: -1.0,
204					z: 0.0,
205				},
206				normal: n,
207				uv: crate::vlm::Vec2 { x: 0.0, y: 1.0 },
208				color: c,
209			},
210		],
211		indices: vec![0, 1, 2, 0, 2, 3],
212		bounds: Aabb {
213			min: Vec3 {
214				x: -1.0,
215				y: -1.0,
216				z: 0.0,
217			},
218			max: Vec3 {
219				x: 1.0,
220				y: 1.0,
221				z: 0.0,
222			},
223		},
224		bounds_dirty: false,
225	};
226	compute_bounds(&mut mesh);
227	mesh
228}
229
230/// Create a 3D axis-aligned cube (12 triangles, 24 vertices, size × size × size).
231///
232/// Each face has its own four vertices with an outward normal and per-face UVs.
233/// `size` must be finite and positive.
234///
235/// Donor: `oa::FnMesh::createCube`.
236///
237/// # Errors
238///
239/// Returns an error for non-finite or non-positive size.
240pub fn create_cube(size: f32) -> Result<MeshData> {
241	if !size.is_finite() || size <= 0.0 {
242		return Err(Error::invalid_argument(
243			"render::create_cube requires a finite positive size",
244		));
245	}
246	let h = size * 0.5;
247	let c = crate::vlm::Vec4 {
248		x: 1.0,
249		y: 1.0,
250		z: 1.0,
251		w: 1.0,
252	};
253	// 6 faces × 4 vertices each, with explicit normals per face.
254	// Winding: CCW when viewed from outside (front-face default).
255	let face = |nx: f32, ny: f32, nz: f32, p0: [f32; 3], p1: [f32; 3], p2: [f32; 3], p3: [f32; 3]| {
256		let n = Vec3 {
257			x: nx,
258			y: ny,
259			z: nz,
260		};
261		[
262			MeshVertex {
263				position: Vec3 {
264					x: p0[0],
265					y: p0[1],
266					z: p0[2],
267				},
268				normal: n,
269				uv: crate::vlm::Vec2 { x: 0.0, y: 0.0 },
270				color: c,
271			},
272			MeshVertex {
273				position: Vec3 {
274					x: p1[0],
275					y: p1[1],
276					z: p1[2],
277				},
278				normal: n,
279				uv: crate::vlm::Vec2 { x: 1.0, y: 0.0 },
280				color: c,
281			},
282			MeshVertex {
283				position: Vec3 {
284					x: p2[0],
285					y: p2[1],
286					z: p2[2],
287				},
288				normal: n,
289				uv: crate::vlm::Vec2 { x: 1.0, y: 1.0 },
290				color: c,
291			},
292			MeshVertex {
293				position: Vec3 {
294					x: p3[0],
295					y: p3[1],
296					z: p3[2],
297				},
298				normal: n,
299				uv: crate::vlm::Vec2 { x: 0.0, y: 1.0 },
300				color: c,
301			},
302		]
303	};
304	let vertices: Vec<MeshVertex> = [
305		// +Z front
306		face(
307			0.0,
308			0.0,
309			1.0,
310			[-h, h, h],
311			[h, h, h],
312			[h, -h, h],
313			[-h, -h, h],
314		),
315		// -Z back
316		face(
317			0.0,
318			0.0,
319			-1.0,
320			[h, h, -h],
321			[-h, h, -h],
322			[-h, -h, -h],
323			[h, -h, -h],
324		),
325		// +Y top
326		face(
327			0.0,
328			1.0,
329			0.0,
330			[-h, h, -h],
331			[h, h, -h],
332			[h, h, h],
333			[-h, h, h],
334		),
335		// -Y bottom
336		face(
337			0.0,
338			-1.0,
339			0.0,
340			[-h, -h, h],
341			[h, -h, h],
342			[h, -h, -h],
343			[-h, -h, -h],
344		),
345		// +X right
346		face(
347			1.0,
348			0.0,
349			0.0,
350			[h, h, h],
351			[h, h, -h],
352			[h, -h, -h],
353			[h, -h, h],
354		),
355		// -X left
356		face(
357			-1.0,
358			0.0,
359			0.0,
360			[-h, h, -h],
361			[-h, h, h],
362			[-h, -h, h],
363			[-h, -h, -h],
364		),
365	]
366	.into_iter()
367	.flatten()
368	.collect();
369
370	// 6 faces × 2 triangles × 3 indices, base-offset per face.
371	let indices: Vec<u32> = (0u32..6)
372		.flat_map(|face| {
373			let b = face * 4;
374			[b, b + 1, b + 2, b, b + 2, b + 3]
375		})
376		.collect();
377
378	let mut mesh = MeshData {
379		vertices,
380		indices,
381		bounds: Aabb {
382			min: Vec3 {
383				x: -h,
384				y: -h,
385				z: -h,
386			},
387			max: Vec3 { x: h, y: h, z: h },
388		},
389		bounds_dirty: false,
390	};
391	compute_bounds(&mut mesh);
392	Ok(mesh)
393}
394
395// ── Bounds ────────────────────────────────────────────────────────────────────
396
397/// Recompute and store the tight axis-aligned bounding box for `mesh`.
398///
399/// Clears `bounds_dirty`. Empty meshes produce an all-zero `Aabb`.
400///
401/// Donor: `oa::FnMesh::computeBounds`.
402pub fn compute_bounds(mesh: &mut MeshData) {
403	mesh.bounds_dirty = false;
404	if mesh.vertices.is_empty() {
405		mesh.bounds = Aabb::default();
406		return;
407	}
408	let first = mesh.vertices[0].position;
409	let mut mn = first;
410	let mut mx = first;
411	for v in &mesh.vertices {
412		let p = v.position;
413		if p.x < mn.x {
414			mn.x = p.x;
415		}
416		if p.y < mn.y {
417			mn.y = p.y;
418		}
419		if p.z < mn.z {
420			mn.z = p.z;
421		}
422		if p.x > mx.x {
423			mx.x = p.x;
424		}
425		if p.y > mx.y {
426			mx.y = p.y;
427		}
428		if p.z > mx.z {
429			mx.z = p.z;
430		}
431	}
432	mesh.bounds = Aabb { min: mn, max: mx };
433}
434
435// ── Transforms ────────────────────────────────────────────────────────────────
436
437/// Apply an affine matrix to all vertex positions and normals.
438///
439/// The mesh is left unchanged when `matrix` is non-finite, singular, or
440/// produces non-finite vertex positions. On success, `bounds_dirty` is set.
441///
442/// Donor: `oa::FnMesh::transform`.
443///
444/// # Errors
445///
446/// Returns an error when `matrix` is non-finite, singular (no normal matrix),
447/// or produces non-finite vertex positions.
448pub fn transform(mesh: &mut MeshData, matrix: Mat4) -> Result<()> {
449	if !matrix.is_finite() {
450		return Err(Error::invalid_argument(
451			"render::transform requires a finite transformation matrix",
452		));
453	}
454	let normal_matrix = matrix
455		.try_normal_matrix(crate::vlm::INVERSE_TOLERANCE)
456		.ok_or_else(|| {
457			Error::invalid_argument("render::transform requires a non-singular transformation matrix")
458		})?;
459
460	// Compute transformed positions first; verify before writing.
461	let new_positions: Vec<Vec3> = mesh
462		.vertices
463		.iter()
464		.map(|v| matrix.transform_point(v.position))
465		.collect();
466
467	if new_positions.iter().any(|p| !p.is_finite()) {
468		return Err(Error::invalid_argument(
469			"render::transform produced non-finite vertex positions",
470		));
471	}
472
473	for (v, pos) in mesh.vertices.iter_mut().zip(new_positions) {
474		v.position = pos;
475		v.normal = v.normal * normal_matrix;
476	}
477	mesh.bounds_dirty = true;
478	Ok(())
479}
480
481/// Translate all vertex positions in-place.
482///
483/// Always succeeds; bounds are marked dirty.
484///
485/// Donor: `oa::FnMesh::translate`.
486pub fn translate(mesh: &mut MeshData, offset: Vec3) {
487	for v in &mut mesh.vertices {
488		v.position.x += offset.x;
489		v.position.y += offset.y;
490		v.position.z += offset.z;
491	}
492	// Shift the cached bounds when valid.
493	if !mesh.bounds_dirty {
494		mesh.bounds.min.x += offset.x;
495		mesh.bounds.min.y += offset.y;
496		mesh.bounds.min.z += offset.z;
497		mesh.bounds.max.x += offset.x;
498		mesh.bounds.max.y += offset.y;
499		mesh.bounds.max.z += offset.z;
500	}
501}
502
503/// Scale all vertex positions and normals.
504///
505/// Zero or non-finite scale components fail without modifying the mesh.
506///
507/// Donor: `oa::FnMesh::scale`.
508///
509/// # Errors
510///
511/// Returns an error when any scale component is zero or non-finite.
512pub fn scale(mesh: &mut MeshData, s: Vec3) -> Result<()> {
513	if !s.is_finite() || s.x == 0.0 || s.y == 0.0 || s.z == 0.0 {
514		return Err(Error::invalid_argument(
515			"render::scale requires finite non-zero scale components",
516		));
517	}
518	// Inverse scale for normals (transpose-inverse of a diagonal = 1/s).
519	let inv = Vec3 {
520		x: 1.0 / s.x,
521		y: 1.0 / s.y,
522		z: 1.0 / s.z,
523	};
524	for v in &mut mesh.vertices {
525		v.position.x *= s.x;
526		v.position.y *= s.y;
527		v.position.z *= s.z;
528		// Renormalize after applying the inverse-transpose.
529		let nx = v.normal.x * inv.x;
530		let ny = v.normal.y * inv.y;
531		let nz = v.normal.z * inv.z;
532		let len = (nx * nx + ny * ny + nz * nz).sqrt();
533		if len > f32::EPSILON {
534			v.normal = Vec3 {
535				x: nx / len,
536				y: ny / len,
537				z: nz / len,
538			};
539		}
540	}
541	mesh.bounds_dirty = true;
542	Ok(())
543}
544
545/// Flip all vertex UVs vertically (V ← 1 − V).
546///
547/// Used to convert explicitly bottom-origin source content to top-origin.
548/// Never fails.
549///
550/// Donor: `oa::FnMesh::flipUvsY`.
551pub fn flip_uvs_y(mesh: &mut MeshData) {
552	for v in &mut mesh.vertices {
553		v.uv.y = 1.0 - v.uv.y;
554	}
555}