Skip to main content

oa/render/
scene.rs

1//! CPU semantic mesh, material, and scene snapshots, independent of renderer
2//! storage.
3
4use std::collections::{HashMap, HashSet};
5
6use crate::{
7	Error, Result,
8	core::transform::Transform,
9	vlm::{Mat4, Vec2, Vec3, Vec4},
10};
11
12use super::{
13	material::{Material, MaterialId},
14	mesh::Aabb,
15};
16
17/// Stable identity of one mesh in a [`Scene`]. Zero is invalid.
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
19pub struct SceneMeshId(pub u64);
20
21/// Stable identity of one node in a [`Scene`]. Zero is invalid.
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
23pub struct SceneNodeId(pub u64);
24
25/// CPU vertex contract used by the first scene compiler.
26#[derive(Clone, Copy, Debug, PartialEq)]
27pub struct MeshVertex {
28	pub position: Vec3,
29	pub normal: Vec3,
30	pub uv: Vec2,
31	pub color: Vec4,
32}
33
34/// Indexed triangle-list mesh snapshot.
35///
36/// `bounds` and `bounds_dirty` mirror the OA donor fields. Constructed values
37/// from `mesh::create_*` have up-to-date bounds; directly assembled `MeshData`
38/// values start with `bounds_dirty = true` and `bounds = Aabb::default()`.
39#[derive(Clone, Debug, PartialEq)]
40pub struct MeshData {
41	pub vertices: Vec<MeshVertex>,
42	pub indices: Vec<u32>,
43	/// Cached tight AABB; valid when `bounds_dirty` is `false`.
44	pub bounds: Aabb,
45	/// Set to `true` when vertices have changed since the last `compute_bounds`.
46	pub bounds_dirty: bool,
47}
48
49impl Default for MeshData {
50	fn default() -> Self {
51		Self {
52			vertices: Vec::new(),
53			indices: Vec::new(),
54			bounds: Aabb::default(),
55			bounds_dirty: true,
56		}
57	}
58}
59
60/// Named immutable mesh value in a semantic scene.
61#[derive(Clone, Debug, PartialEq)]
62pub struct SceneMesh {
63	pub id: SceneMeshId,
64	pub name: String,
65	pub data: MeshData,
66}
67
68/// Named material entry in a semantic scene.
69#[derive(Clone, Debug, PartialEq)]
70pub struct SceneMaterial {
71	/// Unique non-zero material identity within this scene.
72	pub id: MaterialId,
73	pub name: String,
74	pub data: Material,
75}
76
77/// One hierarchy node that optionally instances a mesh.
78///
79/// `local_transform` is the donor `oa::Transform localTransform` — a TRS
80/// semantic value, not a raw matrix.
81///
82/// `material` overrides the renderer's default material for this node.
83/// `None` falls back to `FlatColor { color: [0.8, 0.8, 0.8, 1.0] }` at draw
84/// time.
85#[derive(Clone, Debug, PartialEq)]
86pub struct SceneNode {
87	pub id: SceneNodeId,
88	pub name: String,
89	pub parent: SceneNodeId,
90	pub mesh: SceneMeshId,
91	/// Optional material override. References a [`SceneMaterial`] in the same
92	/// [`Scene`] by identity.
93	pub material: Option<MaterialId>,
94	pub local_transform: Transform,
95	pub visible: bool,
96}
97
98/// Caller-owned CPU semantic scene snapshot.
99#[derive(Clone, Debug, Default, PartialEq)]
100pub struct Scene {
101	pub meshes: Vec<SceneMesh>,
102	/// Material library for this scene.
103	pub materials: Vec<SceneMaterial>,
104	pub nodes: Vec<SceneNode>,
105}
106
107/// Validate one scene without retaining or uploading it.
108pub fn validate_scene(scene: &Scene) -> Result<()> {
109	// ── Meshes ────────────────────────────────────────────────────────────────
110	let mut meshes = HashSet::new();
111	for mesh in &scene.meshes {
112		if mesh.id.0 == 0 || !meshes.insert(mesh.id) {
113			return Err(Error::invalid_argument(
114				"render::Scene mesh IDs must be non-zero and unique",
115			));
116		}
117		validate_mesh(&mesh.data)?;
118	}
119
120	// ── Materials ─────────────────────────────────────────────────────────────
121	let mut materials = HashSet::new();
122	for mat in &scene.materials {
123		if mat.id.0 == 0 || !materials.insert(mat.id) {
124			return Err(Error::invalid_argument(
125				"render::Scene material IDs must be non-zero and unique",
126			));
127		}
128		mat.data.validate().map_err(|e| {
129			Error::invalid_argument(format!("render::Scene material '{}': {}", mat.name, e))
130		})?;
131	}
132
133	// ── Nodes ─────────────────────────────────────────────────────────────────
134	let mut nodes = HashSet::new();
135	for node in &scene.nodes {
136		// Transform is always finite by construction (validate catches
137		// any degenerate rotation introduced through set_matrix).
138		if node.id.0 == 0 || !nodes.insert(node.id) || !node.local_transform.is_finite() {
139			return Err(Error::invalid_argument(
140				"render::Scene nodes require unique non-zero IDs and finite transforms",
141			));
142		}
143		if node.mesh.0 != 0 && !meshes.contains(&node.mesh) {
144			return Err(Error::invalid_argument(
145				"render::Scene node references a missing mesh",
146			));
147		}
148		if node
149			.material
150			.is_some_and(|mat_id| !materials.contains(&mat_id))
151		{
152			return Err(Error::invalid_argument(
153				"render::Scene node references a missing material",
154			));
155		}
156	}
157
158	// ── Hierarchy ─────────────────────────────────────────────────────────────
159	for node in &scene.nodes {
160		if node.parent.0 != 0 && (!nodes.contains(&node.parent) || node.parent == node.id) {
161			return Err(Error::invalid_argument(
162				"render::Scene node parent is missing or self-referential",
163			));
164		}
165		let mut seen = HashSet::new();
166		let mut parent = node.parent;
167		while parent.0 != 0 {
168			if !seen.insert(parent) {
169				return Err(Error::invalid_argument(
170					"render::Scene hierarchy contains a cycle",
171				));
172			}
173			parent = scene
174				.nodes
175				.iter()
176				.find(|candidate| candidate.id == parent)
177				.expect("validated parent")
178				.parent;
179		}
180	}
181	Ok(())
182}
183
184/// Compile visible scene instances into one deterministic indexed mesh snapshot.
185pub fn compile_scene(scene: &Scene) -> Result<MeshData> {
186	let (mesh, _) = compile_scene_packets(scene)?;
187	Ok(mesh)
188}
189
190/// Per-node draw range produced by [`compile_scene_packets`].
191///
192/// `index_start` and `index_count` are byte-aligned offsets into the merged
193/// index buffer returned alongside this packet.
194#[derive(Clone, Debug, PartialEq)]
195pub struct SceneDrawPacket {
196	/// First index in the merged index buffer for this node.
197	pub index_start: u32,
198	/// Number of indices (must be a multiple of 3).
199	pub index_count: u32,
200	/// The material assigned to this node; `None` means use the renderer
201	/// default.
202	pub material_id: Option<MaterialId>,
203}
204
205/// Compile visible scene nodes into a merged `MeshData` and one
206/// [`SceneDrawPacket`] per visible node that contributes geometry.
207///
208/// The returned mesh has world-space positions and normals; each packet
209/// records the index range within the merged buffer that belongs to that
210/// node. Draw order is deterministic (depth-first scene-node order).
211pub fn compile_scene_packets(scene: &Scene) -> Result<(MeshData, Vec<SceneDrawPacket>)> {
212	validate_scene(scene)?;
213	let node_by_id: HashMap<_, _> = scene.nodes.iter().map(|node| (node.id, node)).collect();
214	let mesh_by_id: HashMap<_, _> = scene.meshes.iter().map(|mesh| (mesh.id, mesh)).collect();
215	let mut output = MeshData::default();
216	let mut packets: Vec<SceneDrawPacket> = Vec::new();
217	for node in &scene.nodes {
218		if !is_visible(node, &node_by_id) || node.mesh.0 == 0 {
219			continue;
220		}
221		let world = world_transform(node, &node_by_id);
222		let normal_matrix = world
223			.try_normal_matrix(crate::vlm::INVERSE_TOLERANCE)
224			.ok_or_else(|| Error::invalid_argument("render::Scene world transform is singular"))?;
225		let base = u32::try_from(output.vertices.len())
226			.map_err(|_| Error::out_of_range("render::Scene vertex count exceeds u32"))?;
227		let index_start = u32::try_from(output.indices.len())
228			.map_err(|_| Error::out_of_range("render::Scene index count exceeds u32"))?;
229		let mesh = mesh_by_id[&node.mesh];
230		output
231			.vertices
232			.extend(mesh.data.vertices.iter().map(|vertex| MeshVertex {
233				position: world.transform_point(vertex.position),
234				normal: vertex.normal * normal_matrix,
235				..*vertex
236			}));
237		let new_indices: Vec<u32> = mesh
238			.data
239			.indices
240			.iter()
241			.map(|index| {
242				base
243					.checked_add(*index)
244					.ok_or_else(|| Error::out_of_range("render::Scene index overflows u32"))
245			})
246			.collect::<Result<Vec<_>>>()?;
247		let index_count = u32::try_from(new_indices.len())
248			.map_err(|_| Error::out_of_range("render::Scene index count exceeds u32"))?;
249		output.indices.extend(new_indices);
250		packets.push(SceneDrawPacket {
251			index_start,
252			index_count,
253			material_id: node.material,
254		});
255	}
256	Ok((output, packets))
257}
258
259fn validate_mesh(mesh: &MeshData) -> Result<()> {
260	if !mesh.indices.len().is_multiple_of(3)
261		|| mesh
262			.indices
263			.iter()
264			.any(|index| *index as usize >= mesh.vertices.len())
265		|| mesh.vertices.iter().any(|v| {
266			!v.position.is_finite() || !v.normal.is_finite() || !v.uv.is_finite() || !v.color.is_finite()
267		}) {
268		return Err(Error::invalid_argument(
269			"render::MeshData requires finite vertices and in-range triangle indices",
270		));
271	}
272	Ok(())
273}
274
275/// Accumulate local transforms up to the root, returning a world-space Mat4.
276fn world_transform(node: &SceneNode, nodes: &HashMap<SceneNodeId, &SceneNode>) -> Mat4 {
277	let mut result = node.local_transform.get_matrix();
278	let mut parent = node.parent;
279	while parent.0 != 0 {
280		let value = nodes[&parent];
281		result *= value.local_transform.get_matrix();
282		parent = value.parent;
283	}
284	result
285}
286
287fn is_visible(node: &SceneNode, nodes: &HashMap<SceneNodeId, &SceneNode>) -> bool {
288	if !node.visible {
289		return false;
290	}
291	let mut parent = node.parent;
292	while parent.0 != 0 {
293		let value = nodes[&parent];
294		if !value.visible {
295			return false;
296		}
297		parent = value.parent;
298	}
299	true
300}