From 357dc3fb73a1ecb0696edcb36bf6b2e30234bcdf Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:37:23 +0000 Subject: [PATCH] Support strict FBX geometry and final polygons --- crates/mesh/src/fbx.rs | 37 ++++++++++++++++++++++++++++++++++-- crates/mesh/src/tests/fbx.rs | 13 ++++++++++++- 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/crates/mesh/src/fbx.rs b/crates/mesh/src/fbx.rs index 0494c8e9c..a2e97f59c 100644 --- a/crates/mesh/src/fbx.rs +++ b/crates/mesh/src/fbx.rs @@ -677,6 +677,8 @@ pub struct SceneOptions { /// Apply pre/post rotations even when `RotationActive` is missing or zero. Some importers /// retain these values regardless of the flag. pub apply_inactive_rotation: bool, + /// Refuse malformed geometry arrays and accept an unterminated final polygon. + pub strict_geometry: bool, } impl Document { @@ -743,6 +745,7 @@ impl Document { let objects = self.top("Objects").ok_or_else(|| malformed(KIND, "no Objects section"))?; let mut b = Build { limits, + strict_geometry: options.strict_geometry, budget: Budget { left: Cell::new(self.left), limit: limits.max_data_bytes }, resolve, by_key: objects.children.iter().filter_map(|o| Some((key(o.props.first())?, o))).collect(), @@ -955,6 +958,7 @@ fn material(name: &str, record: &Record) -> Material { /// A scene under construction. struct Build<'a, 'r> { limits: &'a Limits, + strict_geometry: bool, budget: Budget, resolve: Resolver<'r>, by_key: HashMap, &'a Record>, @@ -1087,6 +1091,32 @@ impl<'a> Build<'a, '_> { fn mesh(&mut self, name: &str, geom: &Record, materials: &[usize]) -> Result> { let limits = self.limits; let (Some(vertices), Some(pvi)) = (geom.child("Vertices"), geom.child("PolygonVertexIndex")) else { return Ok(None) }; + if self.strict_geometry { + let valid = |record: &Record, integers: bool| { + let values = record.child("a").unwrap_or(record); + values.props.iter().all(|p| match p { + Prop::Int(_) | Prop::Ints(_) => true, + Prop::Float(f) => f.is_finite() && (!integers || f.fract() == 0.0), + Prop::Floats(a) => a.iter().all(|f| f.is_finite() && (!integers || f.fract() == 0.0)), + _ => false, + }) + }; + if !valid(vertices, false) || !valid(pvi, true) { + return Err(malformed(KIND, "mesh array contains a non-numeric, non-finite or fractional index value")); + } + for (element, names) in [ + ("LayerElementNormal", &["Normals", "NormalsIndex"][..]), + ("LayerElementUV", &["UV", "UVIndex"][..]), + ("LayerElementMaterial", &["Materials"][..]), + ("LayerElementColor", &["Colors", "ColorIndex"][..]), + ] { + if let Some(layer) = geom.children_named(element).min_by_key(|e| e.props.first().and_then(Prop::as_i64) != Some(0)) { + if names.iter().filter_map(|n| layer.child(n)).any(|r| !valid(r, false)) { + return Err(malformed(KIND, "mesh array contains a non-numeric or non-finite value")); + } + } + } + } let pool = |what: &str, n: usize| { if n > limits.max_vertices { Err(too_large(KIND, format!("more than {} {what}", limits.max_vertices))) } else { Ok(()) } }; @@ -1104,15 +1134,18 @@ impl<'a> Build<'a, '_> { let mut part_of: HashMap, usize> = HashMap::new(); let mut face: Vec = vec![]; let (mut broken, mut poly) = (false, 0usize); - for (pv, raw) in pvi.ints().into_iter().enumerate() { + let polygon_indices = pvi.ints(); + let index_count = polygon_indices.len(); + for (pv, raw) in polygon_indices.into_iter().enumerate() { // The last corner of a polygon is stored as `-index - 1`. - let (v, last) = if raw < 0 { (!raw, true) } else { (raw, false) }; + let (v, last) = if raw < 0 { (!raw, true) } else { (raw, self.strict_geometry && pv + 1 == index_count) }; match u32::try_from(v).ok().filter(|v| (*v as usize) < positions.len()) { Some(p) => face.push(Corner { position: p, normal: Layer::at(normal_layer, pv, p as usize, poly), uv: Layer::at(uv_layer, pv, p as usize, poly), }), + None if self.strict_geometry => return Err(malformed(KIND, format!("polygon vertex index {raw} out of range"))), None => broken = true, } if face.len() > limits.max_face_corners { diff --git a/crates/mesh/src/tests/fbx.rs b/crates/mesh/src/tests/fbx.rs index 9d4eec9c9..7f19c7d52 100644 --- a/crates/mesh/src/tests/fbx.rs +++ b/crates/mesh/src/tests/fbx.rs @@ -633,10 +633,21 @@ fn optional_inactive_pre_rotation_keeps_legacy_placements() { let text = "FBXHeaderExtension: { FBXVersion: 7400 } Objects: { Model: 1, \"Model::A\", \"Null\" { Properties70: { P: \"PreRotation\", \"\", \"\", \"\", 0,0,90 } } }"; let doc = document(text.as_bytes()); let normal = doc.scene(&Limits::default(), &mut no_external).unwrap(); - let options = crate::fbx::SceneOptions { apply_inactive_rotation: true }; + let options = crate::fbx::SceneOptions { apply_inactive_rotation: true, ..Default::default() }; let legacy = doc.scene_with_options(&Limits::default(), &mut no_external, &options).unwrap(); let p = [1.0, 0.0, 0.0]; assert_eq!(transform_point(&normal.nodes[0].transform, p), p); let turned = transform_point(&legacy.nodes[0].transform, p); assert!((turned[0]).abs() < 1e-12 && (turned[1] - 1.0).abs() < 1e-12); } + +#[test] +fn strict_geometry_rejects_bad_arrays_and_keeps_final_polygon() { + let options = crate::fbx::SceneOptions { strict_geometry: true, ..Default::default() }; + let read_strict = |s: &str| document(s.as_bytes()).scene_with_options(&Limits::default(), &mut no_external, &options); + let unterminated = ASCII.replace("a: 0,1,2,-4,0,1,-5", "a: 0,1,2,-4,0,1,4"); + assert_eq!(read_strict(&unterminated).unwrap().meshes[0].triangle_count(), 3); + for bad in ["a: 0,1,2,-4,0,1,200", "a: 0,1,2,-4,0,1,1.5", "a: 0,1,2,-4,0,1,NaN"] { + assert!(read_strict(&ASCII.replace("a: 0,1,2,-4,0,1,-5", bad)).is_err()); + } +}