fabrilis/crates/scene/src/import/obj.rs
loki5512344 93075ab1fd
Some checks failed
ci / check (macos-latest) (push) Has been cancelled
ci / check (ubuntu-latest) (push) Has been cancelled
ci / check (windows-latest) (push) Has been cancelled
Add design persistence, world rendering, metrics overlay and logs
M3: STL/OBJ import with mesh validation, mass/COM/inertia, material database, RON scene with content-addressed blobs and v0->v1 migration. M4: deterministic heightmap terrain, trimesh colliders, wgpu renderer with instancing and depth, winit app with 1 kHz physics, fly camera, on-screen metrics overlay and per-frame CSV/dev logs. Docs: UI, logging, network and headless CLI plans.
2026-11-16 23:34:05 +01:00

134 lines
3.9 KiB
Rust

//! OBJ import: the `v` and `f` subset needed for rigid parts.
//!
//! Supported statements:
//!
//! - `v x y z` — vertex position; extra components such as `w` are ignored;
//! - `f ...` — a polygon with three or more corners, fan-triangulated; a corner
//! may be written as `v`, `v/vt`, `v//vn` or `v/vt/vn`, and the vertex index
//! may be positive (one-based) or negative (relative to the vertices seen so
//! far).
//!
//! Comments and the `vt`, `vn`, `o`, `g`, `s`, `usemtl` and `mtllib` statements
//! are ignored. Any other statement is rejected as unsupported: this is a
//! documented subset, not a full OBJ reader. Units and axes are not stored in
//! OBJ; apply [`Mesh::scaled`] with the project factor (docs/COORDINATES.md).
use core::str::SplitWhitespace;
use fabrilis_core::vec::Vec3;
use super::mesh::{Mesh, MeshError};
/// Imports the vertex and face subset of a Wavefront OBJ file.
pub fn from_obj(text: &str) -> Result<Mesh, MeshError> {
let mut positions = Vec::new();
let mut indices = Vec::new();
for (index, line) in text.lines().enumerate() {
parse_line(line, index + 1, &mut positions, &mut indices)?;
}
if indices.is_empty() {
return Err(MeshError::Empty);
}
Mesh::new(positions, indices)
}
fn parse_line(
line: &str,
number: usize,
positions: &mut Vec<Vec3>,
indices: &mut Vec<[u32; 3]>,
) -> Result<(), MeshError> {
let content = line.split('#').next().unwrap_or_default();
let mut words = content.split_whitespace();
let Some(keyword) = words.next() else {
return Ok(());
};
match keyword {
"v" => parse_vertex(words, number, positions),
"f" => parse_face(words, number, positions.len(), indices),
"vt" | "vn" | "o" | "g" | "s" | "usemtl" | "mtllib" => Ok(()),
other => Err(malformed(
number,
format!("unsupported OBJ statement `{other}`"),
)),
}
}
fn parse_vertex(
mut words: SplitWhitespace<'_>,
number: usize,
positions: &mut Vec<Vec3>,
) -> Result<(), MeshError> {
let x = coordinate(&mut words, number)?;
let y = coordinate(&mut words, number)?;
let z = coordinate(&mut words, number)?;
positions.push(Vec3::new(x, y, z));
Ok(())
}
fn parse_face(
words: SplitWhitespace<'_>,
number: usize,
vertex_count: usize,
indices: &mut Vec<[u32; 3]>,
) -> Result<(), MeshError> {
let mut corners = Vec::new();
for word in words {
corners.push(parse_corner(word, number, vertex_count)?);
}
let Some((&first, rest)) = corners.split_first() else {
return Err(short_face(number));
};
if rest.len() < 2 {
return Err(short_face(number));
}
for pair in rest.windows(2) {
if let [a, b] = pair {
indices.push([first, *a, *b]);
}
}
Ok(())
}
/// Resolves one face corner such as `7`, `7/2`, `7//3` or `7/2/3`.
fn parse_corner(word: &str, number: usize, vertex_count: usize) -> Result<u32, MeshError> {
let mut parts = word.split('/');
let vertex = parts.next().unwrap_or_default();
if vertex.is_empty() || parts.count() > 2 {
return Err(bad_corner(word, number));
}
let Ok(raw) = vertex.parse::<i64>() else {
return Err(bad_corner(word, number));
};
let resolved = match raw {
0 => return Err(malformed(number, "OBJ vertex indices are one-based")),
relative if relative < 0 => vertex_count as i64 + relative,
absolute => absolute - 1,
};
if resolved < 0 {
return Err(bad_corner(word, number));
}
u32::try_from(resolved).map_err(|_| bad_corner(word, number))
}
fn coordinate(words: &mut SplitWhitespace<'_>, line: usize) -> Result<f64, MeshError> {
let Some(word) = words.next() else {
return Err(malformed(line, "missing vertex coordinate"));
};
word.parse()
.map_err(|_| malformed(line, format!("`{word}` is not a valid coordinate")))
}
fn short_face(line: usize) -> MeshError {
malformed(line, "face needs at least three vertices".to_string())
}
fn bad_corner(word: &str, line: usize) -> MeshError {
malformed(line, format!("`{word}` is not a valid face corner"))
}
fn malformed(line: usize, reason: impl Into<String>) -> MeshError {
MeshError::Malformed {
line,
reason: reason.into(),
}
}