diff --git a/src-tauri/fileio/src/lib.rs b/src-tauri/fileio/src/lib.rs index 7985ef7c..39109191 100644 --- a/src-tauri/fileio/src/lib.rs +++ b/src-tauri/fileio/src/lib.rs @@ -26,6 +26,8 @@ pub mod ifc_semantic; pub mod ifc_export; pub mod ifc_openings; pub mod mesh_export; +pub mod mesh_import; +mod mesh_import_gltf; pub mod bcf; pub mod csg; mod ifc_sweep; diff --git a/src-tauri/fileio/src/mesh_import.rs b/src-tauri/fileio/src/mesh_import.rs new file mode 100644 index 00000000..2d57616d --- /dev/null +++ b/src-tauri/fileio/src/mesh_import.rs @@ -0,0 +1,1241 @@ +// Allgemeiner Mesh-Import als Kontext-Meshes ([B3]/[C11], 28.10.): OBJ (+ MTL), STL (ASCII/binär, Farbvarianten), +// PLY mit Flächen und glTF 2.0 / GLB (`mesh_import_gltf.rs`). Eigener Code, keine Abhängigkeit ausser earcutr +// (schon im Baum) für Polygone mit mehr als drei Ecken. +// +// Ergebnis: je Objekt (OBJ `o`/`g` und Material, glTF-Knoten und Material, STL-`solid`, PLY-Flächenfarbe) +// ein Mesh mit Name, Gruppe (= Ebene im Kontext-Panel) und Farbe. Koordinaten am Ende der Lesung in +// Modell-Meter, Z = Höhe: +// * Einheit: `unit_scale` (Meter je Dateieinheit) für OBJ/STL/PLY; glTF ist laut Spezifikation immer Meter. +// * Achse: glTF ist Y-up und rechtshändig — Umkehr der Abbildung in `mesh_export.rs` (Modell (x, y, z) → +// Datei (x, z, −y)), also Datei (X, Y, Z) → Modell (X, −Z, Y). Das ist eine Drehung (keine Spiegelung), die +// Dreiecks-Wicklung bleibt. OBJ/STL/PLY: `Up::Z` unverändert, `Up::Y` wie glTF, `Up::Auto` per Erkennung +// (Kopfkommentar, dann Ausdehnung, dann Formatvorgabe) — `up_certain` sagt, ob sie belastbar war. +// * Ungültiges (NaN, Index ausserhalb, entartete Dreiecke) wird verworfen und gezählt, nie ein Panic. +// * Budget: `max_triangles` (Rest wird abgeschnitten, `truncated`), Eckpunkte höchstens `MAX_VERTICES`. +// +// Flache Ausgabe (`encode`): Zahlen als f64-Puffer, Zeichenketten als Tabelle: +// [VERSION, format, up_used (0 Z, 1 Y), up_auto, up_certain, unit_scale, triangles, degenerate, bad_faces, +// truncated, n_warnings, n_objects, warning-Index × n_warnings, +// (name, group (−1 = keine), has_color, r, g, b, a (sRGB 0..1), n_pos, n_idx, pos…, idx…) × n_objects] + +use std::collections::HashMap; + +use crate::mesh_import_gltf::read_gltf; + +pub const FLAT_VERSION: f64 = 1.0; +/// Höchstzahl Eckpunkte je Datei (Speicherbudget im WASM). +pub const MAX_VERTICES: usize = 24_000_000; +/// Voreinstellung für die Dreiecksgrenze. +pub const DEFAULT_MAX_TRIANGLES: usize = 6_000_000; +/// Fehlertext (Präfix) für PLY ohne Flächen: die TS-Seite verweist dann auf den Punktwolken-Import. +pub const NO_FACES: &str = "[punktwolke]"; + +/// Welche Achse oben liegt (Dateikoordinaten). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Up { + Auto, + Z, + Y, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Format { + Obj, + Stl, + Gltf, + Ply, +} + +impl Format { + fn code(self) -> f64 { + match self { + Format::Obj => 0.0, + Format::Stl => 1.0, + Format::Gltf => 2.0, + Format::Ply => 3.0, + } + } +} + +pub struct Options { + /// Meter je Dateieinheit (OBJ/STL/PLY); nicht endlich oder ≤ 0 gilt als 1. + pub unit_scale: f64, + pub up: Up, + pub max_triangles: usize, + /// Mitgegebene Nachbardateien (`.bin` zu `.gltf`, `.mtl` zu `.obj`), Name ohne Verzeichnis. + pub files: Vec<(String, Vec)>, +} + +impl Default for Options { + fn default() -> Self { + Options { unit_scale: 1.0, up: Up::Auto, max_triangles: DEFAULT_MAX_TRIANGLES, files: Vec::new() } + } +} + +/// Ein importiertes Objekt in Modell-Koordinaten (Meter, Z oben). +#[derive(Clone, Debug, Default)] +pub struct MeshObject { + pub name: String, + /// Übergeordnete Gruppe (OBJ `o` über `g`, glTF-Eltern-Knoten); leer = keine. + pub group: String, + /// sRGB 0..1 mit Alpha. + pub color: Option<[f32; 4]>, + pub positions: Vec, + pub indices: Vec, +} + +#[derive(Debug)] +pub struct MeshImport { + pub format: Format, + pub objects: Vec, + pub up_used: Up, + /// Achse wurde erkannt (nicht vorgegeben). + pub up_auto: bool, + /// Erkennung belastbar (Kopfkommentar oder eindeutige Ausdehnung). + pub up_certain: bool, + pub unit_scale: f64, + pub triangles: usize, + pub degenerate: usize, + pub bad_faces: usize, + pub truncated: bool, + pub warnings: Vec, +} + +// ── gemeinsame Zwischenform ───────────────────────────────────────────────── + +/// Objekt vor dem Verdichten: Dreiecke als Indizes in den gemeinsamen Eckpunkt-Pool. +pub(crate) struct Raw { + pub name: String, + pub group: String, + pub color: Option<[f32; 4]>, + pub tris: Vec<[u32; 3]>, +} + +/// Lesestand: Pool (x, y, z je Eckpunkt, Dateikoordinaten), Objekte, Zähler. +pub(crate) struct Parsed { + pub pool: Vec, + pub objects: Vec, + pub bad_faces: usize, + pub truncated: bool, + pub warnings: Vec, + pub tri_count: usize, + pub max_triangles: usize, + /// Hinweis aus dem Dateikopf auf die Achse (`Some(true)` = Y-up). + pub up_hint: Option, + /// Achse ist durch das Format festgelegt (glTF). + pub up_fixed: Option, +} + +impl Parsed { + pub fn new(max_triangles: usize) -> Parsed { + Parsed { + pool: Vec::new(), + objects: Vec::new(), + bad_faces: 0, + truncated: false, + warnings: Vec::new(), + tri_count: 0, + max_triangles, + up_hint: None, + up_fixed: None, + } + } + pub fn vertex_count(&self) -> usize { + self.pool.len() / 3 + } + /// Noch Platz für `n` Dreiecke? Sonst wird abgeschnitten. + pub fn room(&mut self, n: usize) -> bool { + if self.tri_count.saturating_add(n) > self.max_triangles { + self.truncated = true; + return false; + } + self.tri_count += n; + true + } + pub fn warn(&mut self, w: String) { + if self.warnings.len() < 20 && !self.warnings.contains(&w) { + self.warnings.push(w); + } + } +} + +// ── Eintritt ──────────────────────────────────────────────────────────────── + +fn extension(name: &str) -> String { + let base = name.rsplit(['/', '\\']).next().unwrap_or(name); + match base.rsplit_once('.') { + Some((_, e)) => e.to_ascii_lowercase(), + None => String::new(), + } +} + +fn stem(name: &str) -> String { + let base = name.rsplit(['/', '\\']).next().unwrap_or(name); + match base.rsplit_once('.') { + Some((s, _)) if !s.is_empty() => s.to_string(), + _ => base.to_string(), + } +} + +/// Format am Inhalt erkennen, die Endung nur als Hinweis. +pub fn detect_format(bytes: &[u8], name: &str) -> Option { + if bytes.starts_with(b"glTF") { + return Some(Format::Gltf); + } + if bytes.starts_with(b"ply") && bytes.get(3).is_some_and(|c| *c == b'\n' || *c == b'\r') { + return Some(Format::Ply); + } + let head = &bytes[..bytes.len().min(4096)]; + let first = head.iter().copied().find(|c| !c.is_ascii_whitespace() && *c != 0xEF && *c != 0xBB && *c != 0xBF); + let ext = extension(name); + if first == Some(b'{') && (ext == "gltf" || ext == "json" || head.windows(5).any(|w| w == b"\"asse")) { + return Some(Format::Gltf); + } + match ext.as_str() { + "stl" => return Some(Format::Stl), + "obj" => return Some(Format::Obj), + "ply" => return Some(Format::Ply), + "gltf" | "glb" => return Some(Format::Gltf), + _ => {} + } + if is_binary_stl(bytes) || (head.starts_with(b"solid") && head.windows(5).any(|w| w == b"facet")) { + return Some(Format::Stl); + } + let text = String::from_utf8_lossy(head); + if text.lines().any(|l| l.starts_with("v ") || l.starts_with("f ") || l.starts_with("o ") || l.starts_with("g ")) { + return Some(Format::Obj); + } + None +} + +/// Mesh-Datei lesen. `name` = Dateiname (Endung als Hinweis, Stamm als Vorgabename). +pub fn import_mesh(bytes: &[u8], name: &str, opts: &Options) -> Result { + let format = detect_format(bytes, name).ok_or("Dateiformat nicht erkannt (erwartet: OBJ, STL, glTF/GLB oder PLY)")?; + if bytes.is_empty() { + return Err("Datei ist leer".into()); + } + let max = opts.max_triangles.max(1); + let mut parsed = Parsed::new(max); + match format { + Format::Obj => read_obj(bytes, opts, &mut parsed)?, + Format::Stl => read_stl(bytes, &mut parsed)?, + Format::Ply => read_ply_mesh(bytes, &mut parsed)?, + Format::Gltf => read_gltf(bytes, opts, &mut parsed)?, + } + finish(parsed, format, &stem(name), opts) +} + +/// Verdichten (nur benutzte Eckpunkte), Achse und Einheit anwenden. +fn finish(parsed: Parsed, format: Format, default_name: &str, opts: &Options) -> Result { + let Parsed { pool, objects, bad_faces, truncated, mut warnings, up_hint, up_fixed, .. } = parsed; + let mut bad = bad_faces; + let mut degenerate = 0usize; + let mut out: Vec = Vec::new(); + let nverts = pool.len() / 3; + for raw in objects { + let mut remap: HashMap = HashMap::new(); + let mut positions: Vec = Vec::new(); + let mut indices: Vec = Vec::with_capacity(raw.tris.len() * 3); + for t in &raw.tris { + let ok = t.iter().all(|&i| { + let i = i as usize; + i < nverts && pool[i * 3..i * 3 + 3].iter().all(|v| v.is_finite()) + }); + if !ok { + bad += 1; + continue; + } + if t[0] == t[1] || t[1] == t[2] || t[0] == t[2] { + degenerate += 1; + continue; + } + for &i in t { + let n = remap.len() as u32; + let k = *remap.entry(i).or_insert_with(|| { + let b = i as usize * 3; + positions.extend_from_slice(&pool[b..b + 3]); + n + }); + indices.push(k); + } + } + if indices.is_empty() { + continue; + } + let name = if raw.name.is_empty() { default_name.to_string() } else { raw.name }; + out.push(MeshObject { name, group: raw.group, color: raw.color, positions, indices }); + } + if out.is_empty() { + return Err(if truncated { "Keine Dreiecke gelesen (Budget erschöpft)".into() } else { "Die Datei enthält keine Dreiecke".into() }); + } + + // Achse. + let (up_used, up_auto, up_certain) = match (up_fixed, opts.up) { + (Some(u), _) => (u, false, true), + (None, Up::Z) => (Up::Z, false, true), + (None, Up::Y) => (Up::Y, false, true), + (None, Up::Auto) => { + let (u, certain) = detect_up(&out, up_hint, format); + (u, true, certain) + } + }; + let scale = if format == Format::Gltf { + 1.0 + } else if opts.unit_scale.is_finite() && opts.unit_scale > 0.0 { + opts.unit_scale + } else { + 1.0 + }; + for o in &mut out { + for v in o.positions.chunks_exact_mut(3) { + let (x, y, z) = (v[0] * scale, v[1] * scale, v[2] * scale); + if up_used == Up::Y { + // Datei (X, Y, Z) → Modell (X, −Z, Y); `0.0 - z` verhindert −0. + v[0] = x; + v[1] = 0.0 - z; + v[2] = y; + } else { + v[0] = x; + v[1] = y; + v[2] = z; + } + } + } + let triangles = out.iter().map(|o| o.indices.len() / 3).sum(); + if degenerate > 0 { + warnings.push(format!("{degenerate} entartete Dreiecke verworfen")); + } + if bad > 0 { + warnings.push(format!("{bad} ungültige Flächen verworfen (Index ausserhalb, NaN oder zu wenige Ecken)")); + } + if truncated { + warnings.push("Dreiecksgrenze erreicht: Rest der Datei nicht gelesen".into()); + } + Ok(MeshImport { + format, + objects: out, + up_used, + up_auto, + up_certain, + unit_scale: scale, + triangles, + degenerate, + bad_faces: bad, + truncated, + warnings, + }) +} + +/// Achse erkennen: Kopfkommentar, dann die kleinste Ausdehnung (Gebäude, Möbel und Gelände sind in der +/// Regel niedriger als breit), sonst Formatvorgabe (OBJ Y-up wie Blender/SketchUp-Voreinstellung, STL/PLY Z-up). +fn detect_up(objs: &[MeshObject], hint: Option, format: Format) -> (Up, bool) { + if let Some(h) = hint { + return (h, true); + } + let (mut lo, mut hi) = ([f64::MAX; 3], [f64::MIN; 3]); + for o in objs { + for v in o.positions.chunks_exact(3) { + for a in 0..3 { + lo[a] = lo[a].min(v[a]); + hi[a] = hi[a].max(v[a]); + } + } + } + let e = [hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]]; + if e.iter().all(|v| v.is_finite()) { + if e[2] < 0.8 * e[0].min(e[1]) { + return (Up::Z, true); + } + if e[1] < 0.8 * e[0].min(e[2]) { + return (Up::Y, true); + } + } + (if format == Format::Obj { Up::Y } else { Up::Z }, false) +} + +// ── Polygone triangulieren ────────────────────────────────────────────────── + +/// Polygon (Indizes in den Pool) → Dreiecke; Drehsinn bleibt wie im Polygon. Ohne gültige Zerlegung: Fächer. +pub(crate) fn triangulate(pool: &[f64], poly: &[u32], out: &mut Vec<[u32; 3]>) { + let n = poly.len(); + if n < 3 { + return; + } + if n == 3 { + out.push([poly[0], poly[1], poly[2]]); + return; + } + let fan = |out: &mut Vec<[u32; 3]>| { + for k in 1..n - 1 { + out.push([poly[0], poly[k], poly[k + 1]]); + } + }; + let pt = |i: u32| -> Option<[f64; 3]> { + let b = i as usize * 3; + let s = pool.get(b..b + 3)?; + Some([s[0], s[1], s[2]]) + }; + let pts: Option> = poly.iter().map(|&i| pt(i)).collect(); + let Some(pts) = pts else { + fan(out); + return; + }; + // Newell-Normale. + let mut nrm = [0.0f64; 3]; + for i in 0..n { + let (a, b) = (pts[i], pts[(i + 1) % n]); + nrm[0] += (a[1] - b[1]) * (a[2] + b[2]); + nrm[1] += (a[2] - b[2]) * (a[0] + b[0]); + nrm[2] += (a[0] - b[0]) * (a[1] + b[1]); + } + if !nrm.iter().all(|v| v.is_finite()) || nrm.iter().all(|v| v.abs() < 1e-300) { + fan(out); + return; + } + // Eben und konvex ⇒ Fächer reicht (häufigster Fall: Vierecke). + let drop = if nrm[0].abs() >= nrm[1].abs() && nrm[0].abs() >= nrm[2].abs() { + 0 + } else if nrm[1].abs() >= nrm[2].abs() { + 1 + } else { + 2 + }; + let (ua, va) = match drop { + 0 => (1, 2), + 1 => (2, 0), + _ => (0, 1), + }; + let mut flat = Vec::with_capacity(n * 2); + for p in &pts { + flat.push(p[ua]); + flat.push(p[va]); + } + let idx = match earcutr::earcut(&flat, &[], 2) { + Ok(v) if !v.is_empty() => v, + _ => { + fan(out); + return; + } + }; + for t in idx.chunks_exact(3) { + if t.iter().any(|&k| k >= n) { + continue; + } + let (a, b, c) = (pts[t[0]], pts[t[1]], pts[t[2]]); + let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; + let w = [c[0] - a[0], c[1] - a[1], c[2] - a[2]]; + let cr = [u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]]; + let dot = cr[0] * nrm[0] + cr[1] * nrm[1] + cr[2] * nrm[2]; + if dot >= 0.0 { + out.push([poly[t[0]], poly[t[1]], poly[t[2]]]); + } else { + out.push([poly[t[0]], poly[t[2]], poly[t[1]]]); + } + } +} + +// ── OBJ + MTL ─────────────────────────────────────────────────────────────── + +/// Zeilen mit Fortsetzung (`\` am Ende) zusammensetzen. +fn logical_lines(text: &str) -> impl Iterator> { + let mut it = text.lines(); + std::iter::from_fn(move || { + let first = it.next()?; + if !first.trim_end().ends_with('\\') { + return Some(std::borrow::Cow::Borrowed(first)); + } + let mut s = first.trim_end().trim_end_matches('\\').to_string(); + for next in it.by_ref() { + let t = next.trim_end(); + if let Some(stripped) = t.strip_suffix('\\') { + s.push(' '); + s.push_str(stripped); + } else { + s.push(' '); + s.push_str(t); + break; + } + } + Some(std::borrow::Cow::Owned(s)) + }) +} + +type Materials = HashMap; + +/// MTL lesen: `newmtl`, `Kd` (Grundfarbe), `d`/`Tr` (Deckkraft). +fn read_mtl(text: &str, into: &mut Materials) { + let mut cur: Option = None; + let mut kd: HashMap = HashMap::new(); + for line in text.lines() { + let l = line.trim(); + let mut w = l.split_whitespace(); + match w.next() { + Some("newmtl") => { + let n = l["newmtl".len()..].trim().to_string(); + if !n.is_empty() { + kd.entry(n.clone()).or_insert([0.8, 0.8, 0.8, 1.0]); + cur = Some(n); + } + } + Some("Kd") => { + let v: Vec = w.filter_map(|s| s.parse::().ok()).collect(); + if let (Some(n), true) = (&cur, v.len() >= 3 && v.iter().all(|c| c.is_finite())) { + if let Some(c) = kd.get_mut(n) { + c[0] = v[0].clamp(0.0, 1.0); + c[1] = v[1].clamp(0.0, 1.0); + c[2] = v[2].clamp(0.0, 1.0); + } + } + } + Some("d") => { + if let (Some(n), Some(a)) = (&cur, w.next().and_then(|s| s.parse::().ok())) { + if let (Some(c), true) = (kd.get_mut(n), a.is_finite()) { + c[3] = a.clamp(0.0, 1.0); + } + } + } + Some("Tr") => { + if let (Some(n), Some(a)) = (&cur, w.next().and_then(|s| s.parse::().ok())) { + if let (Some(c), true) = (kd.get_mut(n), a.is_finite()) { + c[3] = (1.0 - a).clamp(0.0, 1.0); + } + } + } + _ => {} + } + } + into.extend(kd); +} + +fn find_file<'a>(files: &'a [(String, Vec)], name: &str) -> Option<&'a [u8]> { + let base = |s: &str| s.rsplit(['/', '\\']).next().unwrap_or(s).to_ascii_lowercase(); + let want = base(name.trim()); + files.iter().find(|(n, _)| base(n) == want).map(|(_, b)| b.as_slice()) +} + +/// OBJ-Objektschlüssel: (`o`, `g`, Material). +struct ObjSlots { + index: HashMap<(String, String, String), usize>, +} + +fn read_obj(bytes: &[u8], opts: &Options, p: &mut Parsed) -> Result<(), String> { + let text = String::from_utf8_lossy(bytes); + let mut materials = Materials::new(); + let (mut o_name, mut g_name, mut mtl) = (String::new(), String::new(), String::new()); + let mut slots = ObjSlots { index: HashMap::new() }; + // Reihenfolge der Objekte je (o, g) für die Namensergänzung bei mehreren Materialien. + let mut keys: Vec<(String, String, String)> = Vec::new(); + let mut poly: Vec = Vec::new(); + let mut scratch: Vec<[u32; 3]> = Vec::new(); + let mut seen_header = false; + let mut face_lines = 0usize; + for line in logical_lines(&text) { + let l = line.trim(); + if l.is_empty() { + continue; + } + if let Some(c) = l.strip_prefix('#') { + if !seen_header { + let c = c.to_ascii_lowercase(); + if c.contains("dossier") || c.contains("blender") { + p.up_hint = Some(Up::Y); + } else if c.contains("rhinoceros") || c.contains("rhino ") { + p.up_hint = Some(Up::Z); + } + } + continue; + } + seen_header = true; + let (cmd, rest) = match l.split_once(char::is_whitespace) { + Some((c, r)) => (c, r.trim()), + None => (l, ""), + }; + match cmd { + "v" => { + if p.vertex_count() >= MAX_VERTICES { + p.truncated = true; + continue; + } + let mut it = rest.split_whitespace().map(|s| s.parse::().unwrap_or(f64::NAN)); + let (x, y, z) = (it.next().unwrap_or(f64::NAN), it.next().unwrap_or(f64::NAN), it.next().unwrap_or(f64::NAN)); + p.pool.extend_from_slice(&[x, y, z]); + } + "o" => { + o_name = rest.to_string(); + g_name.clear(); + } + "g" => g_name = rest.split_whitespace().next().unwrap_or("").to_string(), + "usemtl" => mtl = rest.to_string(), + "mtllib" => { + for f in rest.split_whitespace() { + match find_file(&opts.files, f) { + Some(b) => read_mtl(&String::from_utf8_lossy(b), &mut materials), + None => p.warn(format!("Materialdatei fehlt: {f} (Farben entfallen; mit der OBJ-Datei zusammen wählen)")), + } + } + } + "f" => { + face_lines += 1; + poly.clear(); + let n = p.vertex_count() as i64; + let mut bad = false; + for tok in rest.split_whitespace() { + let first = tok.split('/').next().unwrap_or(""); + match first.parse::() { + Ok(i) if i > 0 && i <= n => poly.push((i - 1) as u32), + Ok(i) if i < 0 && -i <= n => poly.push((n + i) as u32), + _ => { + bad = true; + break; + } + } + } + if bad || poly.len() < 3 { + p.bad_faces += 1; + continue; + } + scratch.clear(); + triangulate(&p.pool, &poly, &mut scratch); + if scratch.is_empty() || !p.room(scratch.len()) { + continue; + } + let key = (o_name.clone(), g_name.clone(), mtl.clone()); + let at = match slots.index.get(&key) { + Some(&i) => i, + None => { + let i = p.objects.len(); + slots.index.insert(key.clone(), i); + keys.push(key.clone()); + p.objects.push(Raw { name: String::new(), group: String::new(), color: materials.get(&mtl).copied(), tris: Vec::new() }); + i + } + }; + p.objects[at].tris.extend_from_slice(&scratch); + } + _ => {} + } + } + if p.vertex_count() == 0 { + return Err("OBJ ohne Eckpunkte (kein „v“)".into()); + } + if face_lines == 0 { + return Err("OBJ ohne Flächen (kein „f“)".into()); + } + // Namen: g (sonst o) als Objektname, o als Gruppe, Material als Zusatz bei mehreren je (o, g). + let mut per: HashMap<(String, String), usize> = HashMap::new(); + for k in &keys { + *per.entry((k.0.clone(), k.1.clone())).or_insert(0) += 1; + } + for (i, k) in keys.iter().enumerate() { + let base = if !k.1.is_empty() { k.1.clone() } else { k.0.clone() }; + let many = per.get(&(k.0.clone(), k.1.clone())).copied().unwrap_or(1) > 1; + let mut name = base; + if many && !k.2.is_empty() { + name = if name.is_empty() { k.2.clone() } else { format!("{name} ({})", k.2) }; + } + let obj = &mut p.objects[i]; + obj.name = name; + if !k.0.is_empty() && !k.1.is_empty() && k.0 != k.1 { + obj.group = k.0.clone(); + } + // Material ist erst nach `mtllib` bekannt, aber `usemtl` darf davor stehen: nachträglich auflösen. + if obj.color.is_none() { + obj.color = materials.get(&k.2).copied(); + } + } + Ok(()) +} + +// ── STL ───────────────────────────────────────────────────────────────────── + +fn is_binary_stl(bytes: &[u8]) -> bool { + if bytes.len() < 84 { + return false; + } + let n = u32::from_le_bytes([bytes[80], bytes[81], bytes[82], bytes[83]]) as usize; + n.checked_mul(50).and_then(|v| v.checked_add(84)) == Some(bytes.len()) +} + +/// Eckpunkte je Bitmuster zusammenführen (STL kennt keine gemeinsamen Eckpunkte). +struct Welder { + map: HashMap<[u32; 3], u32>, +} + +impl Welder { + fn vertex(&mut self, p: &mut Parsed, v: [f32; 3]) -> Option { + // −0 und +0 gleich behandeln. + let key = [(v[0] + 0.0).to_bits(), (v[1] + 0.0).to_bits(), (v[2] + 0.0).to_bits()]; + if let Some(&i) = self.map.get(&key) { + return Some(i); + } + if p.vertex_count() >= MAX_VERTICES { + p.truncated = true; + return None; + } + let i = p.vertex_count() as u32; + p.pool.extend_from_slice(&[f64::from(v[0]), f64::from(v[1]), f64::from(v[2])]); + self.map.insert(key, i); + Some(i) + } +} + +/// Objekt je Farbe (Schlüssel = RGBA-Bytes); höchstens 256 Farben, danach farblos. +struct ColorSlots { + index: HashMap, + plain: Option, +} + +fn color_slot(p: &mut Parsed, slots: &mut ColorSlots, name: &str, rgba: Option<[u8; 4]>) -> usize { + match rgba { + Some(c) if slots.index.len() < 256 || slots.index.contains_key(&u32::from_le_bytes(c)) => { + let key = u32::from_le_bytes(c); + if let Some(&i) = slots.index.get(&key) { + return i; + } + let i = p.objects.len(); + let col = [f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, f32::from(c[3]) / 255.0]; + p.objects.push(Raw { name: name.to_string(), group: String::new(), color: Some(col), tris: Vec::new() }); + slots.index.insert(key, i); + i + } + _ => { + if let Some(i) = slots.plain { + return i; + } + let i = p.objects.len(); + p.objects.push(Raw { name: name.to_string(), group: String::new(), color: None, tris: Vec::new() }); + slots.plain = Some(i); + i + } + } +} + +fn read_stl(bytes: &[u8], p: &mut Parsed) -> Result<(), String> { + if is_binary_stl(bytes) { + return read_stl_binary(bytes, p); + } + let head = &bytes[..bytes.len().min(512)]; + let looks_ascii = head.starts_with(b"solid") || String::from_utf8_lossy(head).contains("facet"); + if looks_ascii { + return read_stl_ascii(bytes, p); + } + // Binär mit falschem Zähler (manche Schreiber): so viele Facetten, wie in die Datei passen. + if bytes.len() >= 84 + 50 { + p.warn("STL-Facettenzahl im Kopf passt nicht zur Dateigrösse; nach Dateigrösse gelesen".into()); + return read_stl_binary(bytes, p); + } + Err("STL nicht lesbar (weder ASCII noch binär)".into()) +} + +fn read_stl_binary(bytes: &[u8], p: &mut Parsed) -> Result<(), String> { + let header = &bytes[..80]; + let htext = String::from_utf8_lossy(header); + let declared = u32::from_le_bytes([bytes[80], bytes[81], bytes[82], bytes[83]]) as usize; + let fit = (bytes.len() - 84) / 50; + let n = declared.min(fit); + // Farbvarianten: Magics („COLOR=r g b a“ im Kopf, Bit 15 = 0 → Facettenfarbe, R in Bits 0–4) und + // VisCAM/SolidView (Bit 15 = 1 → Facettenfarbe, B in Bits 0–4). Beide 5 Bit je Kanal. + let magics = htext.contains("COLOR="); + let mut default_color: Option<[u8; 4]> = None; + if let Some(at) = header.windows(6).position(|w| w == b"COLOR=") { + if let Some(c) = header.get(at + 6..at + 10) { + default_color = Some([c[0], c[1], c[2], c[3]]); + } + } + let mut slots = ColorSlots { index: HashMap::new(), plain: None }; + let mut weld = Welder { map: HashMap::new() }; + let f32at = |o: usize| f32::from_le_bytes([bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3]]); + for k in 0..n { + let base = 84 + k * 50; + let attr = u16::from_le_bytes([bytes[base + 48], bytes[base + 49]]); + let to8 = |v: u16| ((u32::from(v & 31) * 255 + 15) / 31) as u8; + let rgba = if magics { + if attr & 0x8000 == 0 && attr != 0 { + Some([to8(attr), to8(attr >> 5), to8(attr >> 10), 255]) + } else { + default_color + } + } else if attr & 0x8000 != 0 { + Some([to8(attr >> 10), to8(attr >> 5), to8(attr), 255]) + } else { + None + }; + if !p.room(1) { + break; + } + let mut ids = [0u32; 3]; + let mut ok = true; + for (c, id) in ids.iter_mut().enumerate() { + let o = base + 12 + c * 12; + match weld.vertex(p, [f32at(o), f32at(o + 4), f32at(o + 8)]) { + Some(i) => *id = i, + None => ok = false, + } + } + if !ok { + break; + } + let at = color_slot(p, &mut slots, "", rgba); + p.objects[at].tris.push(ids); + } + if n == 0 { + return Err("STL ohne Facetten".into()); + } + Ok(()) +} + +fn read_stl_ascii(bytes: &[u8], p: &mut Parsed) -> Result<(), String> { + let text = String::from_utf8_lossy(bytes); + let mut weld = Welder { map: HashMap::new() }; + let mut cur: Option = None; + let mut name = String::new(); + let mut tri: Vec = Vec::with_capacity(3); + let mut facets = 0usize; + let mut stopped = false; + for line in text.lines() { + let l = line.trim(); + let low_start = l.get(..l.len().min(8)).unwrap_or("").to_ascii_lowercase(); + if low_start.starts_with("solid") && !low_start.starts_with("endsolid") { + name = l[5.min(l.len())..].trim().to_string(); + cur = None; + } else if low_start.starts_with("vertex") { + if stopped { + continue; + } + let v: Vec = l[6..].split_whitespace().map(|s| s.parse::().unwrap_or(f32::NAN)).collect(); + if v.len() < 3 { + tri.push(u32::MAX); + continue; + } + match weld.vertex(p, [v[0], v[1], v[2]]) { + Some(i) => tri.push(i), + None => stopped = true, + } + } else if low_start.starts_with("endfacet") { + if tri.len() == 3 && !tri.contains(&u32::MAX) && !stopped { + if !p.room(1) { + stopped = true; + continue; + } + let at = match cur { + Some(i) => i, + None => { + let i = p.objects.len(); + p.objects.push(Raw { name: name.clone(), group: String::new(), color: None, tris: Vec::new() }); + cur = Some(i); + i + } + }; + p.objects[at].tris.push([tri[0], tri[1], tri[2]]); + facets += 1; + } else { + p.bad_faces += 1; + } + tri.clear(); + } + } + if facets == 0 { + return Err("STL ohne Facetten".into()); + } + Ok(()) +} + +// ── PLY (Flächen) ─────────────────────────────────────────────────────────── + +#[derive(Clone, Copy, PartialEq, Debug)] +enum Ty { + I8, + U8, + I16, + U16, + I32, + U32, + F32, + F64, +} + +impl Ty { + fn parse(s: &str) -> Option { + Some(match s { + "char" | "int8" => Ty::I8, + "uchar" | "uint8" => Ty::U8, + "short" | "int16" => Ty::I16, + "ushort" | "uint16" => Ty::U16, + "int" | "int32" => Ty::I32, + "uint" | "uint32" => Ty::U32, + "float" | "float32" => Ty::F32, + "double" | "float64" => Ty::F64, + _ => return None, + }) + } + fn size(self) -> usize { + match self { + Ty::I8 | Ty::U8 => 1, + Ty::I16 | Ty::U16 => 2, + Ty::I32 | Ty::U32 | Ty::F32 => 4, + Ty::F64 => 8, + } + } + fn is_float(self) -> bool { + matches!(self, Ty::F32 | Ty::F64) + } + /// Wert lesen; `None`, wenn der Puffer zu kurz ist. + fn read(self, b: &[u8], at: usize, big: bool) -> Option { + let s = b.get(at..at.checked_add(self.size())?)?; + macro_rules! rd { + ($t:ty, $n:expr) => {{ + let a: [u8; $n] = s.try_into().ok()?; + (if big { <$t>::from_be_bytes(a) } else { <$t>::from_le_bytes(a) }) as f64 + }}; + } + Some(match self { + Ty::I8 => s[0] as i8 as f64, + Ty::U8 => s[0] as f64, + Ty::I16 => rd!(i16, 2), + Ty::U16 => rd!(u16, 2), + Ty::I32 => rd!(i32, 4), + Ty::U32 => rd!(u32, 4), + Ty::F32 => rd!(f32, 4), + Ty::F64 => rd!(f64, 8), + }) + } +} + +#[derive(Clone)] +struct PlyProp { + name: String, + ty: Ty, + /// Listen: (Zähler-Typ); `ty` ist dann der Elementtyp. + list: Option, +} + +struct PlyElement { + name: String, + count: usize, + props: Vec, +} + +fn find_sub(h: &[u8], n: &[u8]) -> Option { + h.windows(n.len()).position(|w| w == n) +} + +fn read_ply_mesh(bytes: &[u8], p: &mut Parsed) -> Result<(), String> { + let end = find_sub(bytes, b"end_header").ok_or("PLY ohne end_header")?; + let mut body = end + b"end_header".len(); + if bytes.get(body) == Some(&b'\r') { + body += 1; + } + if bytes.get(body) == Some(&b'\n') { + body += 1; + } + let header = String::from_utf8_lossy(&bytes[..end]); + let mut format = String::new(); + let mut elements: Vec = Vec::new(); + for line in header.lines().skip(1) { + let w: Vec<&str> = line.split_whitespace().collect(); + match w.as_slice() { + ["format", f, ..] => format = f.to_string(), + ["comment", rest @ ..] => { + let c = rest.join(" ").to_ascii_lowercase(); + if c.contains("dossier") || c.contains("blender") { + p.up_hint = Some(Up::Y); + } + } + ["element", name, n] => { + let count: usize = n.parse().map_err(|_| "PLY: Elementzahl ungültig")?; + elements.push(PlyElement { name: name.to_string(), count, props: Vec::new() }); + } + ["property", "list", ct, it, name] => { + let (Some(ct), Some(it)) = (Ty::parse(ct), Ty::parse(it)) else { + return Err("PLY: Datentyp der Liste unbekannt".into()); + }; + elements.last_mut().ok_or("PLY: property vor element")?.props.push(PlyProp { name: name.to_string(), ty: it, list: Some(ct) }); + } + ["property", ty, name] => { + let ty = Ty::parse(ty).ok_or_else(|| format!("PLY: Datentyp {ty} unbekannt"))?; + elements.last_mut().ok_or("PLY: property vor element")?.props.push(PlyProp { name: name.to_string(), ty, list: None }); + } + _ => {} + } + } + let big = match format.as_str() { + "ascii" => false, + "binary_little_endian" => false, + "binary_big_endian" => true, + _ => return Err("PLY: Format (ascii/binary_little_endian/binary_big_endian) nicht erkannt".into()), + }; + let ascii = format == "ascii"; + let vi = elements.iter().position(|e| e.name == "vertex").ok_or("PLY ohne Element vertex")?; + let face_idx = elements.iter().position(|e| e.name == "face"); + let nfaces = face_idx.map(|i| elements[i].count).unwrap_or(0); + if nfaces == 0 { + return Err(format!("{NO_FACES} PLY enthält keine Flächen (Punktwolke): bitte über den Punktwolken-Import öffnen")); + } + if elements[vi].count > MAX_VERTICES { + return Err("PLY: zu viele Eckpunkte".into()); + } + let vprops = elements[vi].props.clone(); + let pos_of = |n: &str| vprops.iter().position(|q| q.name == n && q.list.is_none()); + let (Some(ix), Some(iy), Some(iz)) = (pos_of("x"), pos_of("y"), pos_of("z")) else { + return Err("PLY: x/y/z fehlen".into()); + }; + let vcol = [pos_of("red"), pos_of("green"), pos_of("blue")]; + let has_vcol = vcol.iter().all(Option::is_some); + + let data = &bytes[body.min(bytes.len())..]; + let text; + let mut lines: std::str::Lines = "".lines(); + let mut cursor = 0usize; + if ascii { + text = String::from_utf8_lossy(data); + lines = text.lines(); + } + // Wert-Quelle: ASCII-Zeile bzw. Binärzeiger. + let scale_col = |ty: Ty, v: f64| -> f32 { + if ty.is_float() { + v.clamp(0.0, 1.0) as f32 + } else if ty == Ty::U16 { + (v / 65535.0).clamp(0.0, 1.0) as f32 + } else { + (v / 255.0).clamp(0.0, 1.0) as f32 + } + }; + let (mut vsum, mut vn) = ([0.0f64; 3], 0usize); + let mut slots = ColorSlots { index: HashMap::new(), plain: None }; + let mut poly: Vec = Vec::new(); + let mut scratch: Vec<[u32; 3]> = Vec::new(); + for (ei, el) in elements.iter().enumerate() { + let is_v = ei == vi; + let is_f = Some(ei) == face_idx; + for _ in 0..el.count { + let mut vals: Vec = Vec::new(); + let mut list: Vec = Vec::new(); + let mut ascii_line: Vec<&str> = Vec::new(); + if ascii { + let Some(l) = lines.next() else { break }; + ascii_line = l.split_whitespace().collect(); + } + let mut ai = 0usize; + let mut short = false; + for pr in &el.props { + let get = |ty: Ty, cursor: &mut usize, ai: &mut usize| -> Option { + if ascii { + let v = ascii_line.get(*ai)?.parse::().ok(); + *ai += 1; + v + } else { + let v = ty.read(data, *cursor, big)?; + *cursor += ty.size(); + Some(v) + } + }; + if let Some(ct) = pr.list { + let Some(n) = get(ct, &mut cursor, &mut ai) else { + short = true; + break; + }; + if !(0.0..=1_000_000.0).contains(&n) { + return Err("PLY: Listenlänge ungültig".into()); + } + let mut l: Vec = Vec::with_capacity(n as usize); + for _ in 0..n as usize { + match get(pr.ty, &mut cursor, &mut ai) { + Some(v) => l.push(v), + None => { + short = true; + break; + } + } + } + if short { + break; + } + if is_f && (pr.name == "vertex_indices" || pr.name == "vertex_index") { + list = l; + } + vals.push(f64::NAN); + } else { + match get(pr.ty, &mut cursor, &mut ai) { + Some(v) => vals.push(v), + None => { + short = true; + break; + } + } + } + } + if short { + if is_v || is_f { + p.warn("PLY: Datei endet vor der angegebenen Elementzahl".into()); + } + break; + } + if is_v { + p.pool.extend_from_slice(&[vals[ix], vals[iy], vals[iz]]); + if has_vcol { + for k in 0..3 { + let i = vcol[k].unwrap_or(0); + vsum[k] += f64::from(scale_col(vprops[i].ty, vals[i])); + } + vn += 1; + } + } else if is_f { + let nv = p.vertex_count() as f64; + poly.clear(); + let mut bad = false; + for &i in &list { + if i >= 0.0 && i < nv && i.fract() == 0.0 { + poly.push(i as u32); + } else { + bad = true; + } + } + if bad || poly.len() < 3 { + p.bad_faces += 1; + continue; + } + // Flächenfarbe, falls als red/green/blue am Element face. + let fp = |n: &str| el.props.iter().position(|q| q.name == n && q.list.is_none()); + let fc = match (fp("red"), fp("green"), fp("blue")) { + (Some(r), Some(g), Some(b)) => { + let c = |i: usize| (scale_col(el.props[i].ty, vals[i]) * 255.0).round() as u8; + let a = fp("alpha").map(|i| (scale_col(el.props[i].ty, vals[i]) * 255.0).round() as u8).unwrap_or(255); + Some([c(r), c(g), c(b), a]) + } + _ => None, + }; + scratch.clear(); + triangulate(&p.pool, &poly, &mut scratch); + if scratch.is_empty() || !p.room(scratch.len()) { + continue; + } + let at = color_slot(p, &mut slots, "", fc); + p.objects[at].tris.extend_from_slice(&scratch); + } + } + } + // Eckpunktfarbe: Mittel über alle Eckpunkte als Objektfarbe (Scans haben Millionen Farben). + if has_vcol && vn > 0 && slots.index.is_empty() { + let c = [(vsum[0] / vn as f64) as f32, (vsum[1] / vn as f64) as f32, (vsum[2] / vn as f64) as f32, 1.0]; + for o in &mut p.objects { + o.color = Some(c); + } + } + if p.objects.is_empty() { + return Err("PLY: keine gültigen Flächen".into()); + } + Ok(()) +} + +// ── flache Kodierung ──────────────────────────────────────────────────────── + +/// Ergebnis → (Zahlenpuffer, Zeichenketten), Aufbau s. Dateikopf. +pub fn encode(m: &MeshImport) -> (Vec, Vec) { + let mut strings: Vec = Vec::new(); + let intern = |s: &str, strings: &mut Vec| -> f64 { + strings.push(s.to_string()); + (strings.len() - 1) as f64 + }; + let mut flat: Vec = vec![ + FLAT_VERSION, + m.format.code(), + if m.up_used == Up::Y { 1.0 } else { 0.0 }, + if m.up_auto { 1.0 } else { 0.0 }, + if m.up_certain { 1.0 } else { 0.0 }, + m.unit_scale, + m.triangles as f64, + m.degenerate as f64, + m.bad_faces as f64, + if m.truncated { 1.0 } else { 0.0 }, + m.warnings.len() as f64, + m.objects.len() as f64, + ]; + for w in &m.warnings { + let i = intern(w, &mut strings); + flat.push(i); + } + for o in &m.objects { + let n = intern(&o.name, &mut strings); + let g = if o.group.is_empty() { -1.0 } else { intern(&o.group, &mut strings) }; + flat.push(n); + flat.push(g); + match o.color { + Some(c) => flat.extend_from_slice(&[1.0, f64::from(c[0]), f64::from(c[1]), f64::from(c[2]), f64::from(c[3])]), + None => flat.extend_from_slice(&[0.0, 0.0, 0.0, 0.0, 0.0]), + } + flat.push(o.positions.len() as f64); + flat.push(o.indices.len() as f64); + flat.extend_from_slice(&o.positions); + flat.extend(o.indices.iter().map(|&i| f64::from(i))); + } + (flat, strings) +} + +// ── WASM-Fassade ──────────────────────────────────────────────────────────── + +#[cfg(feature = "web")] +mod web { + use super::*; + use wasm_bindgen::prelude::*; + + /// Ergebnis; die Getter geben die Daten je einmal heraus (danach leer). + #[wasm_bindgen] + pub struct MeshImportResult { + flat: Vec, + strings: Vec, + } + + #[wasm_bindgen] + impl MeshImportResult { + /// Zahlenpuffer, Aufbau s. `mesh_import.rs`. + pub fn flat(&mut self) -> Vec { + std::mem::take(&mut self.flat) + } + /// Zeichenketten (Hinweise, Namen, Gruppen), per Index aus `flat`. + pub fn strings(&mut self) -> Vec { + std::mem::take(&mut self.strings) + } + } + + /// Mesh-Datei lesen (OBJ/STL/glTF/GLB/PLY, erkannt am Inhalt). + /// `up`: 0 = erkennen, 1 = Z oben, 2 = Y oben. `unit_scale` = Meter je Dateieinheit (glTF ignoriert es). + /// `max_triangles` 0 = Voreinstellung. Nachbardateien (.bin, .mtl): Namen, Längen und alle Bytes hintereinander. + #[wasm_bindgen] + pub fn import_mesh( + bytes: &[u8], + name: &str, + unit_scale: f64, + up: u32, + max_triangles: f64, + ext_names: Vec, + ext_sizes: Vec, + ext_blob: &[u8], + ) -> Result { + let mut files = Vec::new(); + let mut at = 0usize; + for (n, s) in ext_names.iter().zip(ext_sizes.iter()) { + let len = if s.is_finite() && *s >= 0.0 { *s as usize } else { 0 }; + let Some(end) = at.checked_add(len) else { break }; + let Some(b) = ext_blob.get(at..end) else { break }; + files.push((n.clone(), b.to_vec())); + at = end; + } + let opts = Options { + unit_scale, + up: match up { + 1 => Up::Z, + 2 => Up::Y, + _ => Up::Auto, + }, + max_triangles: if max_triangles.is_finite() && max_triangles >= 1.0 { max_triangles.min(4.0e9) as usize } else { DEFAULT_MAX_TRIANGLES }, + files, + }; + let m = super::import_mesh(bytes, name, &opts).map_err(|e| JsValue::from_str(&e))?; + let (flat, strings) = encode(&m); + Ok(MeshImportResult { flat, strings }) + } +} + +#[cfg(test)] +#[path = "mesh_import_tests.rs"] +mod tests; diff --git a/src-tauri/fileio/src/mesh_import_gltf.rs b/src-tauri/fileio/src/mesh_import_gltf.rs new file mode 100644 index 00000000..86c8c5d3 --- /dev/null +++ b/src-tauri/fileio/src/mesh_import_gltf.rs @@ -0,0 +1,663 @@ +// glTF 2.0 / GLB lesen ([C11]-Gegenstück zu `mesh_export.rs`): kleiner JSON-Leser (eigener Code, `serde_json` +// gibt es nur im Web-Feature), Puffer (GLB-BIN-Chunk, Base64-Data-URI, mitgegebene .bin-Dateien), +// Accessors (u8/i8/u16/i16/u32/f32, normalisiert, byteStride), Primitives TRIANGLES/STRIP/FAN, Knoten- +// Hierarchie mit Matrix oder TRS. Farbe = `baseColorFactor` (linear → sRGB). Nicht unterstützt (Fehler bzw. +// Hinweis): Draco/Meshopt-Kompression, Sparse-Accessors (ignoriert, Hinweis), Texturen, Skinning/Morphing. +// +// Koordinaten bleiben Datei-Koordinaten (Y-up, Knoten-Transformationen angewendet); die Umrechnung nach +// Modell (Z oben) macht `mesh_import::finish`. + +use crate::mesh_import::{Options, Parsed, Raw, Up, MAX_VERTICES}; + +// ── JSON ──────────────────────────────────────────────────────────────────── + +#[derive(Debug, Clone)] +pub(crate) enum Json { + Null, + Bool(#[allow(dead_code)] bool), + Num(f64), + Str(String), + Arr(Vec), + Obj(Vec<(String, Json)>), +} + +impl Json { + pub fn get(&self, k: &str) -> Option<&Json> { + match self { + Json::Obj(v) => v.iter().find(|(n, _)| n == k).map(|(_, v)| v), + _ => None, + } + } + pub fn arr(&self) -> &[Json] { + match self { + Json::Arr(v) => v, + _ => &[], + } + } + pub fn num(&self) -> Option { + match self { + Json::Num(n) if n.is_finite() => Some(*n), + _ => None, + } + } + pub fn str(&self) -> Option<&str> { + match self { + Json::Str(s) => Some(s), + _ => None, + } + } + /// Nicht negative ganze Zahl (für Indizes und Grössen). + pub fn idx(&self) -> Option { + let n = self.num()?; + if n >= 0.0 && n.fract() == 0.0 && n < 9.0e15 { + Some(n as usize) + } else { + None + } + } + fn nums(&self, n: usize) -> Option> { + let a = self.arr(); + if a.len() != n { + return None; + } + a.iter().map(Json::num).collect() + } +} + +struct JsonParser<'a> { + b: &'a [u8], + at: usize, +} + +const MAX_DEPTH: usize = 96; + +impl JsonParser<'_> { + fn ws(&mut self) { + while self.at < self.b.len() && matches!(self.b[self.at], b' ' | b'\t' | b'\n' | b'\r') { + self.at += 1; + } + } + fn lit(&mut self, s: &str, v: Json) -> Result { + if self.b[self.at..].starts_with(s.as_bytes()) { + self.at += s.len(); + Ok(v) + } else { + Err("JSON ungültig".into()) + } + } + fn value(&mut self, depth: usize) -> Result { + if depth > MAX_DEPTH { + return Err("JSON zu tief verschachtelt".into()); + } + self.ws(); + match self.b.get(self.at).copied() { + None => Err("JSON endet unerwartet".into()), + Some(b'{') => { + self.at += 1; + let mut v = Vec::new(); + self.ws(); + if self.b.get(self.at) == Some(&b'}') { + self.at += 1; + return Ok(Json::Obj(v)); + } + loop { + self.ws(); + let k = match self.value(depth + 1)? { + Json::Str(s) => s, + _ => return Err("JSON: Schlüssel ist keine Zeichenkette".into()), + }; + self.ws(); + if self.b.get(self.at) != Some(&b':') { + return Err("JSON: „:“ erwartet".into()); + } + self.at += 1; + let val = self.value(depth + 1)?; + v.push((k, val)); + self.ws(); + match self.b.get(self.at) { + Some(b',') => self.at += 1, + Some(b'}') => { + self.at += 1; + return Ok(Json::Obj(v)); + } + _ => return Err("JSON: „,“ oder „}“ erwartet".into()), + } + } + } + Some(b'[') => { + self.at += 1; + let mut v = Vec::new(); + self.ws(); + if self.b.get(self.at) == Some(&b']') { + self.at += 1; + return Ok(Json::Arr(v)); + } + loop { + v.push(self.value(depth + 1)?); + self.ws(); + match self.b.get(self.at) { + Some(b',') => self.at += 1, + Some(b']') => { + self.at += 1; + return Ok(Json::Arr(v)); + } + _ => return Err("JSON: „,“ oder „]“ erwartet".into()), + } + } + } + Some(b'"') => { + self.at += 1; + let mut out: Vec = Vec::new(); + loop { + let c = *self.b.get(self.at).ok_or("JSON: Zeichenkette nicht beendet")?; + self.at += 1; + match c { + b'"' => break, + b'\\' => { + let e = *self.b.get(self.at).ok_or("JSON: Escape unvollständig")?; + self.at += 1; + match e { + b'n' => out.push(b'\n'), + b't' => out.push(b'\t'), + b'r' => out.push(b'\r'), + b'b' => out.push(8), + b'f' => out.push(12), + b'/' | b'\\' | b'"' => out.push(e), + b'u' => { + let mut cp = self.hex4()?; + if (0xD800..0xDC00).contains(&cp) && self.b[self.at..].starts_with(b"\\u") { + self.at += 2; + let lo = self.hex4()?; + if (0xDC00..0xE000).contains(&lo) { + cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00); + } + } + let ch = char::from_u32(cp).unwrap_or('\u{FFFD}'); + let mut buf = [0u8; 4]; + out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes()); + } + _ => return Err("JSON: unbekannter Escape".into()), + } + } + _ => out.push(c), + } + } + Ok(Json::Str(String::from_utf8_lossy(&out).into_owned())) + } + Some(b't') => self.lit("true", Json::Bool(true)), + Some(b'f') => self.lit("false", Json::Bool(false)), + Some(b'n') => self.lit("null", Json::Null), + Some(_) => { + let start = self.at; + while self.at < self.b.len() && matches!(self.b[self.at], b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9') { + self.at += 1; + } + let s = std::str::from_utf8(&self.b[start..self.at]).map_err(|_| "JSON ungültig")?; + s.parse::().map(Json::Num).map_err(|_| "JSON: Zahl ungültig".to_string()) + } + } + } + fn hex4(&mut self) -> Result { + let s = self.b.get(self.at..self.at + 4).ok_or("JSON: \\u unvollständig")?; + self.at += 4; + u32::from_str_radix(std::str::from_utf8(s).map_err(|_| "JSON: \\u ungültig")?, 16).map_err(|_| "JSON: \\u ungültig".to_string()) + } +} + +pub(crate) fn parse_json(b: &[u8]) -> Result { + let b = b.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(b); + let mut p = JsonParser { b, at: 0 }; + let v = p.value(0)?; + p.ws(); + if p.at != b.len() { + return Err("JSON: Text nach dem Wert".into()); + } + Ok(v) +} + +// ── Base64 / URI ──────────────────────────────────────────────────────────── + +fn base64_decode(s: &str) -> Result, String> { + let mut out = Vec::with_capacity(s.len() / 4 * 3); + let (mut acc, mut bits) = (0u32, 0u32); + for c in s.bytes() { + let v = match c { + b'A'..=b'Z' => c - b'A', + b'a'..=b'z' => c - b'a' + 26, + b'0'..=b'9' => c - b'0' + 52, + b'+' | b'-' => 62, + b'/' | b'_' => 63, + b'=' | b'\n' | b'\r' | b' ' => continue, + _ => return Err("Base64 ungültig".into()), + }; + acc = (acc << 6) | u32::from(v); + bits += 6; + if bits >= 8 { + bits -= 8; + out.push((acc >> bits) as u8); + acc &= (1 << bits) - 1; + } + } + Ok(out) +} + +fn percent_decode(s: &str) -> String { + let b = s.as_bytes(); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + if b[i] == b'%' && i + 2 < b.len() { + if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) { + out.push(v); + i += 3; + continue; + } + } + out.push(b[i]); + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +// ── Dokument ──────────────────────────────────────────────────────────────── + +struct Doc { + json: Json, + buffers: Vec>, +} + +/// Zugriff auf einen Accessor als f64-Liste (je Element `comps` Werte); `None` + Meldung bei Unsinn. +fn read_accessor(doc: &Doc, idx: usize, comps: usize, budget: usize) -> Result, String> { + let acc = doc.json.get("accessors").map(Json::arr).and_then(|a| a.get(idx)).ok_or("glTF: Accessor fehlt")?; + let count = acc.get("count").and_then(Json::idx).ok_or("glTF: Accessor ohne count")?; + let ty = acc.get("type").and_then(Json::str).unwrap_or(""); + let n = match ty { + "SCALAR" => 1, + "VEC2" => 2, + "VEC3" => 3, + "VEC4" => 4, + _ => return Err("glTF: Accessor-Typ nicht unterstützt".into()), + }; + if n < comps { + return Err("glTF: Accessor hat zu wenige Komponenten".into()); + } + let total = count.checked_mul(n).filter(|t| *t <= budget).ok_or("glTF: Accessor zu gross")?; + let ct = acc.get("componentType").and_then(Json::idx).unwrap_or(0); + let (size, normalized_max): (usize, f64) = match ct { + 5120 => (1, 127.0), + 5121 => (1, 255.0), + 5122 => (2, 32767.0), + 5123 => (2, 65535.0), + 5125 => (4, 4294967295.0), + 5126 => (4, 0.0), + _ => return Err("glTF: componentType nicht unterstützt".into()), + }; + let normalized = matches!(acc.get("normalized"), Some(Json::Bool(true))); + let Some(view_i) = acc.get("bufferView").and_then(Json::idx) else { + // Ohne bufferView: Nullen (Sparse-Basis). + return Ok(vec![0.0; count * n]); + }; + if acc.get("sparse").is_some() { + // Wird als Nullbasis + Hinweis nicht ausgewertet; Daten bleiben die Basis. + } + let view = doc.json.get("bufferViews").map(Json::arr).and_then(|a| a.get(view_i)).ok_or("glTF: bufferView fehlt")?; + let buf_i = view.get("buffer").and_then(Json::idx).ok_or("glTF: bufferView ohne buffer")?; + let buf = doc.buffers.get(buf_i).ok_or("glTF: buffer fehlt")?; + let vo = view.get("byteOffset").and_then(Json::idx).unwrap_or(0); + let vlen = view.get("byteLength").and_then(Json::idx).ok_or("glTF: bufferView ohne byteLength")?; + let ao = acc.get("byteOffset").and_then(Json::idx).unwrap_or(0); + let stride = view.get("byteStride").and_then(Json::idx).filter(|s| *s > 0).unwrap_or(size * n); + let view_end = vo.checked_add(vlen).filter(|e| *e <= buf.len()).ok_or("glTF: bufferView ausserhalb des Puffers")?; + let mut out = Vec::with_capacity(total); + for k in 0..count { + let base = k + .checked_mul(stride) + .and_then(|o| o.checked_add(ao)) + .and_then(|o| o.checked_add(vo)) + .ok_or("glTF: Offset-Überlauf")?; + for c in 0..n { + let at = base + c * size; + let end = at.checked_add(size).filter(|e| *e <= view_end).ok_or("glTF: Accessor ausserhalb des bufferViews")?; + let s = &buf[at..end]; + let v = match ct { + 5120 => f64::from(s[0] as i8), + 5121 => f64::from(s[0]), + 5122 => f64::from(i16::from_le_bytes([s[0], s[1]])), + 5123 => f64::from(u16::from_le_bytes([s[0], s[1]])), + 5125 => f64::from(u32::from_le_bytes([s[0], s[1], s[2], s[3]])), + _ => f64::from(f32::from_le_bytes([s[0], s[1], s[2], s[3]])), + }; + out.push(if normalized && normalized_max > 0.0 { (v / normalized_max).max(-1.0) } else { v }); + } + } + Ok(out) +} + +// ── Matrizen (spaltenweise wie glTF) ──────────────────────────────────────── + +type Mat = [f64; 16]; +const IDENT: Mat = [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]; + +fn mul(a: &Mat, b: &Mat) -> Mat { + let mut r = [0.0; 16]; + for c in 0..4 { + for row in 0..4 { + let mut s = 0.0; + for k in 0..4 { + s += a[k * 4 + row] * b[c * 4 + k]; + } + r[c * 4 + row] = s; + } + } + r +} + +fn node_matrix(node: &Json) -> Mat { + if let Some(m) = node.get("matrix").and_then(|m| m.nums(16)) { + let mut a = IDENT; + a.copy_from_slice(&m); + return a; + } + let t = node.get("translation").and_then(|v| v.nums(3)).unwrap_or(vec![0.0, 0.0, 0.0]); + let r = node.get("rotation").and_then(|v| v.nums(4)).unwrap_or(vec![0.0, 0.0, 0.0, 1.0]); + let s = node.get("scale").and_then(|v| v.nums(3)).unwrap_or(vec![1.0, 1.0, 1.0]); + let (mut x, mut y, mut z, mut w) = (r[0], r[1], r[2], r[3]); + let len = (x * x + y * y + z * z + w * w).sqrt(); + if len > 0.0 { + x /= len; + y /= len; + z /= len; + w /= len; + } else { + w = 1.0; + } + // Drehmatrix aus dem Quaternion, Spalten skaliert, Verschiebung in Spalte 3. + let (xx, yy, zz, xy, xz, yz, wx, wy, wz) = (x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z); + [ + (1.0 - 2.0 * (yy + zz)) * s[0], + 2.0 * (xy + wz) * s[0], + 2.0 * (xz - wy) * s[0], + 0.0, + 2.0 * (xy - wz) * s[1], + (1.0 - 2.0 * (xx + zz)) * s[1], + 2.0 * (yz + wx) * s[1], + 0.0, + 2.0 * (xz + wy) * s[2], + 2.0 * (yz - wx) * s[2], + (1.0 - 2.0 * (xx + yy)) * s[2], + 0.0, + t[0], + t[1], + t[2], + 1.0, + ] +} + +fn det3(m: &Mat) -> f64 { + m[0] * (m[5] * m[10] - m[9] * m[6]) - m[4] * (m[1] * m[10] - m[9] * m[2]) + m[8] * (m[1] * m[6] - m[5] * m[2]) +} + +// ── Farbe ─────────────────────────────────────────────────────────────────── + +fn linear_to_srgb(c: f64) -> f32 { + let c = c.clamp(0.0, 1.0); + (if c <= 0.003_130_8 { c * 12.92 } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 }) as f32 +} + +fn material_color(doc: &Doc, mat: Option) -> Option<[f32; 4]> { + let m = doc.json.get("materials")?.arr().get(mat?)?; + let f = m.get("pbrMetallicRoughness")?.get("baseColorFactor")?.nums(4)?; + Some([linear_to_srgb(f[0]), linear_to_srgb(f[1]), linear_to_srgb(f[2]), f[3].clamp(0.0, 1.0) as f32]) +} + +// ── Lesen ─────────────────────────────────────────────────────────────────── + +pub(crate) fn read_gltf(bytes: &[u8], opts: &Options, p: &mut Parsed) -> Result<(), String> { + p.up_fixed = Some(Up::Y); + let (json_bytes, glb_bin): (&[u8], Option<&[u8]>) = if bytes.starts_with(b"glTF") { + if bytes.len() < 20 { + return Err("GLB abgeschnitten".into()); + } + let version = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]); + if version != 2 { + return Err(format!("GLB-Version {version} nicht unterstützt (nur 2)")); + } + let mut at = 12usize; + let (mut json, mut bin) = (None, None); + while at + 8 <= bytes.len() { + let len = u32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]) as usize; + let ty = u32::from_le_bytes([bytes[at + 4], bytes[at + 5], bytes[at + 6], bytes[at + 7]]); + let end = (at + 8).checked_add(len).filter(|e| *e <= bytes.len()).ok_or("GLB: Chunk ragt über das Dateiende")?; + let chunk = &bytes[at + 8..end]; + match ty { + 0x4E4F_534A if json.is_none() => json = Some(chunk), + 0x004E_4942 if bin.is_none() => bin = Some(chunk), + _ => {} + } + at = (end + 3) & !3; + } + (json.ok_or("GLB ohne JSON-Chunk")?, bin) + } else { + (bytes, None) + }; + let json = parse_json(json_bytes)?; + if !matches!(json, Json::Obj(_)) { + return Err("glTF: JSON-Wurzel ist kein Objekt".into()); + } + let version = json.get("asset").and_then(|a| a.get("version")).and_then(Json::str).unwrap_or(""); + if !version.starts_with('2') { + return Err(format!("glTF-Version „{version}“ nicht unterstützt (nur 2.0)")); + } + for ext in json.get("extensionsRequired").map(Json::arr).unwrap_or(&[]) { + if let Some(e) = ext.str() { + if matches!(e, "KHR_draco_mesh_compression" | "EXT_meshopt_compression") { + return Err(format!("glTF-Erweiterung {e} (Kompression) nicht unterstützt: bitte unkomprimiert exportieren")); + } + } + } + + // Puffer. + let mut buffers: Vec> = Vec::new(); + let mut missing: Vec = Vec::new(); + for (i, b) in json.get("buffers").map(Json::arr).unwrap_or(&[]).iter().enumerate() { + match b.get("uri").and_then(Json::str) { + None => buffers.push(if i == 0 { glb_bin.map(<[u8]>::to_vec).unwrap_or_default() } else { Vec::new() }), + Some(uri) if uri.starts_with("data:") => { + let (_, data) = uri.split_once(',').ok_or("glTF: Data-URI ohne Daten")?; + buffers.push(base64_decode(data)?); + } + Some(uri) => { + let name = percent_decode(uri); + let base = name.rsplit(['/', '\\']).next().unwrap_or(&name).to_ascii_lowercase(); + match opts.files.iter().find(|(n, _)| n.rsplit(['/', '\\']).next().unwrap_or(n).to_ascii_lowercase() == base) { + Some((_, d)) => buffers.push(d.clone()), + None => { + missing.push(name); + buffers.push(Vec::new()); + } + } + } + } + } + if !missing.is_empty() { + return Err(format!("[extern] glTF verweist auf externe Datei(en), die fehlen: {} (mit der .gltf-Datei zusammen wählen)", missing.join(", "))); + } + let doc = Doc { json, buffers }; + + // Gemeinsamer Eckpunkt-Pool je Mesh-Primitive wird beim Besuch eines Knotens transformiert eingetragen. + let nodes = doc.json.get("nodes").map(Json::arr).unwrap_or(&[]); + let mut roots: Vec = Vec::new(); + let scenes = doc.json.get("scenes").map(Json::arr).unwrap_or(&[]); + let scene_i = doc.json.get("scene").and_then(Json::idx).unwrap_or(0); + if let Some(sc) = scenes.get(scene_i) { + roots.extend(sc.get("nodes").map(Json::arr).unwrap_or(&[]).iter().filter_map(Json::idx)); + } else if !nodes.is_empty() { + let mut child = vec![false; nodes.len()]; + for n in nodes { + for c in n.get("children").map(Json::arr).unwrap_or(&[]).iter().filter_map(Json::idx) { + if c < child.len() { + child[c] = true; + } + } + } + roots.extend((0..nodes.len()).filter(|i| !child[*i])); + } + let mut state = Walk { visited: 0 }; + if nodes.is_empty() { + // Ohne Knoten: jedes Mesh einmal, Einheitsmatrix. + let n = doc.json.get("meshes").map(Json::arr).unwrap_or(&[]).len(); + for mi in 0..n { + add_mesh(&doc, mi, &IDENT, "", "", p, mi)?; + } + } else { + for r in roots { + walk(&doc, r, &IDENT, "", 0, p, &mut state)?; + } + } + if p.objects.is_empty() && !p.truncated { + return Err("glTF enthält keine Dreiecks-Meshes".into()); + } + Ok(()) +} + +struct Walk { + visited: usize, +} + +fn walk(doc: &Doc, ni: usize, parent: &Mat, parent_name: &str, depth: usize, p: &mut Parsed, st: &mut Walk) -> Result<(), String> { + if depth > 64 { + return Err("glTF: Knotenhierarchie zu tief (Zyklus?)".into()); + } + st.visited += 1; + if st.visited > 400_000 || p.truncated { + p.truncated = true; + return Ok(()); + } + let Some(node) = doc.json.get("nodes").map(Json::arr).and_then(|a| a.get(ni)) else { + p.bad_faces += 1; + return Ok(()); + }; + let m = mul(parent, &node_matrix(node)); + let name = node.get("name").and_then(Json::str).unwrap_or(""); + if let Some(mi) = node.get("mesh").and_then(Json::idx) { + add_mesh(doc, mi, &m, name, parent_name, p, ni)?; + } + let children: Vec = node.get("children").map(Json::arr).unwrap_or(&[]).iter().filter_map(Json::idx).collect(); + let next_parent = if name.is_empty() { parent_name } else { name }; + for c in children { + walk(doc, c, &m, next_parent, depth + 1, p, st)?; + } + Ok(()) +} + +/// Ein Knoten mit Mesh → je Material (Farbe) ein Objekt. +fn add_mesh(doc: &Doc, mi: usize, m: &Mat, node_name: &str, group: &str, p: &mut Parsed, node_i: usize) -> Result<(), String> { + let Some(mesh) = doc.json.get("meshes").map(Json::arr).and_then(|a| a.get(mi)) else { + p.bad_faces += 1; + return Ok(()); + }; + let name = if !node_name.is_empty() { + node_name.to_string() + } else if let Some(n) = mesh.get("name").and_then(Json::str).filter(|n| !n.is_empty()) { + n.to_string() + } else { + format!("Knoten {node_i}") + }; + let flip = det3(m) < 0.0; + // (Material, Objektindex) + let mut by_mat: Vec<(Option, usize)> = Vec::new(); + for prim in mesh.get("primitives").map(Json::arr).unwrap_or(&[]) { + let mode = prim.get("mode").and_then(Json::idx).unwrap_or(4); + if !matches!(mode, 4..=6) { + p.warn("glTF: Linien/Punkte übersprungen (nur Dreiecke)".into()); + continue; + } + if prim.get("extensions").and_then(|e| e.get("KHR_draco_mesh_compression")).is_some() { + return Err("glTF: Draco-komprimierte Geometrie nicht unterstützt: bitte unkomprimiert exportieren".into()); + } + let Some(pos_i) = prim.get("attributes").and_then(|a| a.get("POSITION")).and_then(Json::idx) else { + p.bad_faces += 1; + continue; + }; + let remaining = MAX_VERTICES.saturating_sub(p.vertex_count()); + let pos = read_accessor(doc, pos_i, 3, remaining.saturating_mul(3))?; + let nv = pos.len() / 3; + if nv > remaining { + p.truncated = true; + break; + } + let base = p.vertex_count() as u32; + for v in pos.chunks_exact(3) { + // Spaltenmatrix: x' = m0·x + m4·y + m8·z + m12. + p.pool.push(m[0] * v[0] + m[4] * v[1] + m[8] * v[2] + m[12]); + p.pool.push(m[1] * v[0] + m[5] * v[1] + m[9] * v[2] + m[13]); + p.pool.push(m[2] * v[0] + m[6] * v[1] + m[10] * v[2] + m[14]); + } + let idx: Vec = match prim.get("indices").and_then(Json::idx) { + Some(ai) => read_accessor(doc, ai, 1, 60_000_000)? + .into_iter() + .map(|v| if v >= 0.0 && (v as usize) < nv { base + v as u32 } else { u32::MAX }) + .collect(), + None => (0..nv as u32).map(|i| base + i).collect(), + }; + let mut tris: Vec<[u32; 3]> = Vec::new(); + match mode { + 4 => { + for t in idx.chunks_exact(3) { + tris.push([t[0], t[1], t[2]]); + } + } + 5 => { + for k in 0..idx.len().saturating_sub(2) { + // Jedes zweite Dreieck umgekehrt, damit die Wicklung gleich bleibt. + if k % 2 == 0 { + tris.push([idx[k], idx[k + 1], idx[k + 2]]); + } else { + tris.push([idx[k + 1], idx[k], idx[k + 2]]); + } + } + } + _ => { + for k in 1..idx.len().saturating_sub(1) { + tris.push([idx[0], idx[k], idx[k + 1]]); + } + } + } + // Reservierte Indizes (u32::MAX) → ungültig zählen. + let before = tris.len(); + tris.retain(|t| !t.contains(&u32::MAX)); + p.bad_faces += before - tris.len(); + if flip { + for t in &mut tris { + t.swap(1, 2); + } + } + if tris.is_empty() || !p.room(tris.len()) { + continue; + } + let mat = prim.get("material").and_then(Json::idx); + let color = material_color(doc, mat); + // Gleiche Farbe (nicht nur gleicher Material-Index) → ein Objekt. + let at = match by_mat.iter().find(|(mm, _)| *mm == mat || (color.is_some() && material_color(doc, *mm) == color)) { + Some((_, oi)) => *oi, + None => { + let oi = p.objects.len(); + p.objects.push(Raw { name: String::new(), group: group.to_string(), color, tris: Vec::new() }); + by_mat.push((mat, oi)); + oi + } + }; + p.objects[at].tris.extend_from_slice(&tris); + } + // Namen: bei mehreren Farben je Knoten das Material anhängen. + let many = by_mat.len() > 1; + for (mat, oi) in &by_mat { + let mname = mat + .and_then(|i| doc.json.get("materials").map(Json::arr).and_then(|a| a.get(i))) + .and_then(|m| m.get("name")) + .and_then(Json::str) + .unwrap_or(""); + p.objects[*oi].name = if many && !mname.is_empty() { format!("{name} ({mname})") } else { name.clone() }; + } + Ok(()) +} diff --git a/src-tauri/fileio/src/mesh_import_tests.rs b/src-tauri/fileio/src/mesh_import_tests.rs new file mode 100644 index 00000000..be695450 --- /dev/null +++ b/src-tauri/fileio/src/mesh_import_tests.rs @@ -0,0 +1,579 @@ +// Tests des Mesh-Imports: Rundreise mit den eigenen Schreibern (`mesh_export.rs`), Sonderfälle je Format, +// kaputte Dateien ohne Panic. + +use super::*; +use crate::mesh_export::{export_glb, export_gltf, export_obj, export_stl}; + +// ── Hilfen ────────────────────────────────────────────────────────────────── + +/// Eine Gruppe für den Export: Modell-Koordinaten (x, y, z-hoch), Dreiecke gegen den Uhrzeigersinn von aussen. +struct G { + name: &'static str, + rgba: Option<[f64; 4]>, + pos: Vec<[f64; 3]>, + tris: Vec<[u32; 3]>, +} + +/// Flacher Puffer wie die TS-Seite (Welt = (x, z, y), Wicklung vertauscht). +fn flat(groups: &[G]) -> (Vec, String) { + let mut strings: Vec = Vec::new(); + let s = |t: &str, strings: &mut Vec| -> f64 { + strings.push(t.to_string()); + (strings.len() - 1) as f64 + }; + let mut mats: Vec<[f64; 4]> = Vec::new(); + let mut nums = vec![1.0, 0.0]; + let mut body: Vec = Vec::new(); + for g in groups { + let mi = match g.rgba { + Some(c) => { + let at = mats.iter().position(|m| *m == c).unwrap_or_else(|| { + mats.push(c); + mats.len() - 1 + }); + at as f64 + } + None => -1.0, + }; + let n = s(g.name, &mut strings); + let k = s("wall", &mut strings); + let id = s("x", &mut strings); + body.extend([n, k, id, -1.0, 1.0, mi, g.pos.len() as f64]); + for p in &g.pos { + body.extend([p[0], p[2], p[1]]); + } + body.push(g.tris.len() as f64); + for t in &g.tris { + body.extend([f64::from(t[0]), f64::from(t[2]), f64::from(t[1])]); + } + } + nums.push(mats.len() as f64); + for (i, c) in mats.iter().enumerate() { + let n = s(&format!("M{i}"), &mut strings); + nums.extend([n, c[0], c[1], c[2], c[3], 0.0, 0.8]); + } + nums.push(0.0); + nums.push(groups.len() as f64); + nums.extend(body); + (nums, strings.join("\0")) +} + +/// Quader (Mass b × t × h) ab (x0, y0, z0), 12 Dreiecke gegen den Uhrzeigersinn von aussen. +fn cuboid(x0: f64, y0: f64, z0: f64, b: f64, t: f64, h: f64) -> (Vec<[f64; 3]>, Vec<[u32; 3]>) { + let mut pos = Vec::new(); + for i in 0..8u32 { + pos.push([x0 + b * f64::from(i & 1), y0 + t * f64::from((i >> 1) & 1), z0 + h * f64::from((i >> 2) & 1)]); + } + let quads: [[u32; 4]; 6] = [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]]; + let mut tris = Vec::new(); + for q in quads { + tris.push([q[0], q[1], q[2]]); + tris.push([q[0], q[2], q[3]]); + } + (pos, tris) +} + +fn volume(o: &MeshObject) -> f64 { + let mut v = 0.0; + for t in o.indices.chunks_exact(3) { + let p = |i: u32| &o.positions[i as usize * 3..i as usize * 3 + 3]; + let (a, b, c) = (p(t[0]), p(t[1]), p(t[2])); + v += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6.0; + } + v +} + +fn bbox(o: &MeshObject) -> ([f64; 3], [f64; 3]) { + let (mut lo, mut hi) = ([f64::MAX; 3], [f64::MIN; 3]); + for v in o.positions.chunks_exact(3) { + for a in 0..3 { + lo[a] = lo[a].min(v[a]); + hi[a] = hi[a].max(v[a]); + } + } + (lo, hi) +} + +fn close(a: [f64; 3], b: [f64; 3], eps: f64) -> bool { + (0..3).all(|i| (a[i] - b[i]).abs() < eps) +} + +fn two_boxes() -> Vec { + let (p1, t1) = cuboid(2.0, 3.0, 0.0, 4.0, 5.0, 3.0); + let (p2, t2) = cuboid(-10.0, 1.0, 0.5, 1.0, 1.0, 1.0); + vec![ + G { name: "Wand_W1", rgba: Some([0.8, 0.2, 0.1, 1.0]), pos: p1, tris: t1 }, + G { name: "Stuetze_S1", rgba: None, pos: p2, tris: t2 }, + ] +} + +fn check_boxes(m: &MeshImport, color: bool) { + assert_eq!(m.objects.len(), 2); + assert_eq!(m.triangles, 24); + let a = m.objects.iter().find(|o| o.name.contains("W1")).expect("Wand"); + let (lo, hi) = bbox(a); + assert!(close(lo, [2.0, 3.0, 0.0], 1e-5), "{lo:?}"); + assert!(close(hi, [6.0, 8.0, 3.0], 1e-5), "{hi:?}"); + assert!((volume(a) - 60.0).abs() < 1e-3, "Volumen {}", volume(a)); + let b = m.objects.iter().find(|o| o.name.contains("S1")).expect("Stütze"); + assert!((volume(b) - 1.0).abs() < 1e-3); + if color { + let c = a.color.expect("Farbe"); + assert!((c[0] - 0.8).abs() < 0.01 && (c[1] - 0.2).abs() < 0.01 && (c[2] - 0.1).abs() < 0.01, "{c:?}"); + } +} + +fn opts() -> Options { + Options::default() +} + +// ── Rundreise ─────────────────────────────────────────────────────────────── + +#[test] +fn rundreise_glb() { + let (f, s) = flat(&two_boxes()); + let bytes = export_glb(&f, &s).expect("glb"); + let m = import_mesh(&bytes, "x.glb", &opts()).expect("import"); + assert_eq!(m.format, Format::Gltf); + assert_eq!(m.up_used, Up::Y); + check_boxes(&m, true); +} + +#[test] +fn rundreise_gltf_data_uri() { + let (f, s) = flat(&two_boxes()); + let text = export_gltf(&f, &s).expect("gltf"); + let m = import_mesh(text.as_bytes(), "x.gltf", &opts()).expect("import"); + check_boxes(&m, true); +} + +#[test] +fn rundreise_obj_y_up_aus_kopf() { + let (f, s) = flat(&two_boxes()); + let obj = export_obj(&f, &s).expect("obj"); + let m = import_mesh(obj.as_bytes(), "x.obj", &opts()).expect("import"); + assert_eq!(m.format, Format::Obj); + assert_eq!(m.up_used, Up::Y); + assert!(m.up_auto && m.up_certain); + check_boxes(&m, false); +} + +#[test] +fn rundreise_stl_achse_aus_ausdehnung() { + let (f, s) = flat(&two_boxes()); + let stl = export_stl(&f, &s).expect("stl"); + // Beide Körper zusammen: 16 × 8 in der Grundfläche, 3 hoch → Höhe ist die kleinste Ausdehnung. + let m = import_mesh(stl.as_bytes(), "x.stl", &opts()).expect("import"); + assert_eq!(m.format, Format::Stl); + assert_eq!(m.up_used, Up::Y); + assert!(m.up_certain); + assert_eq!(m.triangles, 24); + assert!((m.objects.iter().map(volume).sum::() - 61.0).abs() < 1e-3); + let z = import_mesh(stl.as_bytes(), "x.stl", &Options { up: Up::Z, ..opts() }).expect("import"); + assert_eq!(z.up_used, Up::Z); + assert!(!z.up_auto); +} + +#[test] +fn einheit_skaliert_ausser_gltf() { + let (f, s) = flat(&two_boxes()); + let obj = export_obj(&f, &s).expect("obj"); + let m = import_mesh(obj.as_bytes(), "x.obj", &Options { unit_scale: 0.001, ..opts() }).expect("import"); + let v: f64 = m.objects.iter().map(volume).sum(); + assert!((v - 61.0e-9).abs() < 1e-12, "{v}"); + let glb = export_glb(&f, &s).expect("glb"); + let g = import_mesh(&glb, "x.glb", &Options { unit_scale: 0.001, ..opts() }).expect("import"); + assert_eq!(g.unit_scale, 1.0); +} + +// ── OBJ ───────────────────────────────────────────────────────────────────── + +#[test] +fn obj_quads_ngons_negative_indizes() { + let obj = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nf 1 2 3 4\n\ + v 2 0 0\nv 3 0 0\nv 3 1 0\nv 2.5 0.4 0\nv 2 1 0\nf -5 -4 -3 -2 -1\n"; + let m = import_mesh(obj.as_bytes(), "q.obj", &Options { up: Up::Z, ..opts() }).expect("import"); + // Quad → 2, konkaves Fünfeck → 3 Dreiecke. + assert_eq!(m.triangles, 5); + let o = &m.objects[0]; + let mut area = 0.0; + for t in o.indices.chunks_exact(3) { + let p = |i: u32| &o.positions[i as usize * 3..i as usize * 3 + 3]; + let (a, b, c) = (p(t[0]), p(t[1]), p(t[2])); + let cz = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); + assert!(cz > 0.0, "Wicklung bleibt gegen den Uhrzeigersinn"); + area += cz / 2.0; + } + // Quadrat 1 + Fünfeck (Quadrat 1 minus Keil: Grundlinie 1 × Tiefe 0,6 / 2). + assert!((area - (1.0 + (1.0 - 0.5 * 1.0 * 0.6))).abs() < 1e-9, "{area}"); +} + +#[test] +fn obj_gruppen_materialien_mtl() { + let obj = "mtllib m.mtl\no Haus\ng Dach\nusemtl rot\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n\ + g Wand\nusemtl blau\nf 1 2 3\nusemtl rot\nf 3 2 1\n"; + let mtl = "newmtl rot\nKd 1 0 0\nnewmtl blau\nKd 0 0 1\nd 0.5\n"; + let o = Options { up: Up::Z, files: vec![("M.MTL".into(), mtl.as_bytes().to_vec())], ..opts() }; + let m = import_mesh(obj.as_bytes(), "h.obj", &o).expect("import"); + assert_eq!(m.objects.len(), 3); + let dach = m.objects.iter().find(|x| x.name == "Dach").expect("Dach"); + assert_eq!(dach.group, "Haus"); + assert_eq!(dach.color, Some([1.0, 0.0, 0.0, 1.0])); + let blau = m.objects.iter().find(|x| x.name == "Wand (blau)").expect("blau"); + assert_eq!(blau.color, Some([0.0, 0.0, 1.0, 0.5])); + assert!(m.objects.iter().any(|x| x.name == "Wand (rot)")); + // Ohne MTL: Hinweis, keine Farbe. + let m2 = import_mesh(obj.as_bytes(), "h.obj", &Options { up: Up::Z, ..opts() }).expect("import"); + assert!(m2.objects.iter().all(|x| x.color.is_none())); + assert!(m2.warnings.iter().any(|w| w.contains("m.mtl"))); +} + +#[test] +fn obj_ungueltiges_wird_gezaehlt() { + let obj = "v 0 0 0\nv 1 0 0\nv 0 1 0\nv nan 0 0\nf 1 2 3\nf 1 2 99\nf 1 2\nf 1 2 4\nf 1 1 2\nf 0 1 2\n"; + let m = import_mesh(obj.as_bytes(), "b.obj", &Options { up: Up::Z, ..opts() }).expect("import"); + assert_eq!(m.triangles, 1); + assert!(m.bad_faces >= 4, "{}", m.bad_faces); + assert_eq!(m.degenerate, 1); +} + +#[test] +fn obj_ohne_flaechen_fehler() { + assert!(import_mesh(b"v 0 0 0\nv 1 0 0\n", "x.obj", &opts()).is_err()); +} + +// ── STL ───────────────────────────────────────────────────────────────────── + +fn binary_stl(header: &[u8], facets: &[([[f32; 3]; 3], u16)]) -> Vec { + let mut b = vec![0u8; 80]; + b[..header.len()].copy_from_slice(header); + b.extend((facets.len() as u32).to_le_bytes()); + for (t, attr) in facets { + b.extend([0u8; 12]); + for v in t { + for c in v { + b.extend(c.to_le_bytes()); + } + } + b.extend(attr.to_le_bytes()); + } + b +} + +#[test] +fn stl_binaer_verschweisst_und_farben_viscam() { + let red = 0x8000u16 | (31 << 10); // VisCAM: Rot in Bits 10–14 + let t1 = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]; + let t2 = [[1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]]; + let bytes = binary_stl(b"binary", &[(t1, red), (t2, 0)]); + let m = import_mesh(&bytes, "a.stl", &Options { up: Up::Z, ..opts() }).expect("import"); + assert_eq!(m.triangles, 2); + assert_eq!(m.objects.len(), 2); + let farbig = m.objects.iter().find(|o| o.color.is_some()).expect("rot"); + assert_eq!(farbig.color, Some([1.0, 0.0, 0.0, 1.0])); + assert_eq!(farbig.positions.len(), 9); +} + +#[test] +fn stl_binaer_magics_vorgabefarbe() { + let t1 = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]; + let bytes = binary_stl(b"COLOR=\x00\xff\x00\xff", &[(t1, 0)]); + let m = import_mesh(&bytes, "a.stl", &Options { up: Up::Z, ..opts() }).expect("import"); + assert_eq!(m.objects[0].color, Some([0.0, 1.0, 0.0, 1.0])); +} + +#[test] +fn stl_ascii_mehrere_solids() { + let s = "solid A\nfacet normal 0 0 1\nouter loop\nvertex 0 0 0\nvertex 1 0 0\nvertex 0 1 0\nendloop\nendfacet\nendsolid A\n\ + solid B\nfacet normal 0 0 1\nouter loop\nvertex 0 0 1\nvertex 1 0 1\nvertex 0 1 1\nendloop\nendfacet\nendsolid B\n"; + let m = import_mesh(s.as_bytes(), "x.stl", &Options { up: Up::Z, ..opts() }).expect("import"); + assert_eq!(m.objects.len(), 2); + assert_eq!(m.objects[0].name, "A"); + assert_eq!(m.objects[1].name, "B"); +} + +#[test] +fn stl_binaer_mit_solid_im_kopf_wird_binaer_gelesen() { + let t1 = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]; + let bytes = binary_stl(b"solid exportiert von X", &[(t1, 0)]); + let m = import_mesh(&bytes, "a.stl", &Options { up: Up::Z, ..opts() }).expect("import"); + assert_eq!(m.triangles, 1); +} + +// ── PLY ───────────────────────────────────────────────────────────────────── + +#[test] +fn ply_ascii_mit_quad_und_flaechenfarbe() { + let ply = "ply\nformat ascii 1.0\nelement vertex 4\nproperty float x\nproperty float y\nproperty float z\n\ + element face 1\nproperty list uchar int vertex_indices\nproperty uchar red\nproperty uchar green\nproperty uchar blue\nend_header\n\ + 0 0 0\n1 0 0\n1 1 0\n0 1 0\n4 0 1 2 3 0 255 0\n"; + let m = import_mesh(ply.as_bytes(), "x.ply", &Options { up: Up::Z, ..opts() }).expect("import"); + assert_eq!(m.format, Format::Ply); + assert_eq!(m.triangles, 2); + assert_eq!(m.objects[0].color, Some([0.0, 1.0, 0.0, 1.0])); +} + +#[test] +fn ply_binaer_big_endian() { + let mut b = b"ply\nformat binary_big_endian 1.0\nelement vertex 3\nproperty float x\nproperty float y\nproperty float z\n\ + element face 1\nproperty list uchar uint vertex_index\nend_header\n" + .to_vec(); + for v in [[0.0f32, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 2.0, 0.0]] { + for c in v { + b.extend(c.to_be_bytes()); + } + } + b.push(3); + for i in [0u32, 1, 2] { + b.extend(i.to_be_bytes()); + } + let m = import_mesh(&b, "x.ply", &Options { up: Up::Z, ..opts() }).expect("import"); + assert_eq!(m.triangles, 1); + assert_eq!(bbox(&m.objects[0]).1, [2.0, 2.0, 0.0]); +} + +#[test] +fn ply_punktwolke_gibt_hinweis() { + let ply = "ply\nformat ascii 1.0\nelement vertex 2\nproperty float x\nproperty float y\nproperty float z\nend_header\n0 0 0\n1 1 1\n"; + let e = import_mesh(ply.as_bytes(), "x.ply", &opts()).unwrap_err(); + assert!(e.starts_with(NO_FACES), "{e}"); +} + +// ── glTF von Hand ─────────────────────────────────────────────────────────── + +fn b64(bytes: &[u8]) -> String { + const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut s = String::new(); + for c in bytes.chunks(3) { + let n = (u32::from(c[0]) << 16) | (u32::from(*c.get(1).unwrap_or(&0)) << 8) | u32::from(*c.get(2).unwrap_or(&0)); + for k in 0..4 { + if k <= c.len() { + s.push(T[((n >> (18 - 6 * k)) & 63) as usize] as char); + } else { + s.push('='); + } + } + } + s +} + +/// Einheitsquadrat in der XZ-Ebene (Y-up), 4 Eckpunkte (48 Byte) + 4 Indizes u16 (8 Byte) als Streifen 0,1,2,3. +/// Dreieck (v0,v1,v2): (v1−v0)×(v2−v0) = (0,0,1)×(1,0,0) = (0,1,0) → Normale +Y. +fn quad_buffer() -> Vec { + let mut b = Vec::new(); + for v in [[0.0f32, 0.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 1.0]] { + for c in v { + b.extend(c.to_le_bytes()); + } + } + for i in [0u16, 1, 2, 3] { + b.extend(i.to_le_bytes()); + } + b +} + +fn gltf_quad(mode: u32, nodes: &str, extra: &str, uri: &str) -> String { + format!( + "{{\"asset\":{{\"version\":\"2.0\"}},\"scene\":0,\"scenes\":[{{\"nodes\":[0]}}],\"nodes\":{nodes},\ + \"meshes\":[{{\"name\":\"Quad\",\"primitives\":[{{\"attributes\":{{\"POSITION\":0}},\"indices\":1,\"mode\":{mode},\"material\":0}}]}}],\ + \"materials\":[{{\"name\":\"Rot\",\"pbrMetallicRoughness\":{{\"baseColorFactor\":[1,0,0,1]}}}}],\ + \"accessors\":[{{\"bufferView\":0,\"componentType\":5126,\"count\":4,\"type\":\"VEC3\"}},\ + {{\"bufferView\":1,\"componentType\":5123,\"count\":4,\"type\":\"SCALAR\"}}],\ + \"bufferViews\":[{{\"buffer\":0,\"byteOffset\":0,\"byteLength\":48}},{{\"buffer\":0,\"byteOffset\":48,\"byteLength\":8}}],\ + \"buffers\":[{{{uri}\"byteLength\":56}}]{extra}}}", + ) +} + +fn data_uri() -> String { + format!("\"uri\":\"data:application/octet-stream;base64,{}\",", b64(&quad_buffer())) +} + +/// Alle Dreiecks-Normalen zeigen nach +Z (Modell: nach oben). +fn all_up(o: &MeshObject) -> bool { + o.indices.chunks_exact(3).all(|t| { + let p = |i: u32| &o.positions[i as usize * 3..i as usize * 3 + 3]; + let (a, b, c) = (p(t[0]), p(t[1]), p(t[2])); + (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) > 0.0 + }) +} + +#[test] +fn gltf_knoten_hierarchie_trs() { + // Eltern: Verschiebung (10, 0, 0); Kind: Skalierung 2 und 90° um Y. + let s = std::f64::consts::FRAC_1_SQRT_2; + let nodes = format!( + "[{{\"name\":\"Eltern\",\"translation\":[10,0,0],\"children\":[1]}},\ + {{\"name\":\"Kind\",\"mesh\":0,\"scale\":[2,2,2],\"rotation\":[0,{s},0,{s}]}}]" + ); + let j = gltf_quad(4, &nodes, "", &data_uri()); + // Modus 4 mit 4 Indizes: ein Dreieck (0,1,2), der Rest fällt weg. + let m = import_mesh(j.as_bytes(), "q.gltf", &opts()).expect("import"); + assert_eq!(m.objects.len(), 1); + let o = &m.objects[0]; + assert_eq!(o.name, "Kind"); + assert_eq!(o.group, "Eltern"); + assert_eq!(o.color, Some([1.0, 0.0, 0.0, 1.0])); + // Eckpunkt 1 (0,0,1)·2 → (0,0,2); 90° um Y: (x,y,z) → (z,y,−x) = (2,0,0); + (10,0,0) → glTF (12,0,0) + // → Modell (X, −Z, Y) = (12, 0, 0). + let found = o.positions.chunks_exact(3).any(|v| close([v[0], v[1], v[2]], [12.0, 0.0, 0.0], 1e-6)); + assert!(found, "{:?}", o.positions); + assert!(all_up(o), "Normale nach oben"); +} + +#[test] +fn gltf_matrix_streifen_und_faecher() { + let nodes = "[{\"name\":\"N\",\"mesh\":0,\"matrix\":[1,0,0,0, 0,1,0,0, 0,0,1,0, 5,6,7,1]}]"; + let strip = import_mesh(gltf_quad(5, nodes, "", &data_uri()).as_bytes(), "q.gltf", &opts()).expect("strip"); + assert_eq!(strip.triangles, 2); + // Verschiebung (5,6,7) glTF → Modell (5, −7, 6); Quadrat 1 × 1 in glTF-Z → Modell −Y. + let (lo, hi) = bbox(&strip.objects[0]); + assert!(close(lo, [5.0, -8.0, 6.0], 1e-9), "{lo:?}"); + assert!(close(hi, [6.0, -7.0, 6.0], 1e-9), "{hi:?}"); + assert!(all_up(&strip.objects[0])); + let fan = import_mesh(gltf_quad(6, nodes, "", &data_uri()).as_bytes(), "q.gltf", &opts()).expect("fan"); + assert_eq!(fan.triangles, 2); +} + +#[test] +fn gltf_spiegelung_dreht_wicklung() { + let nodes = "[{\"mesh\":0,\"scale\":[-1,1,1]}]"; + let m = import_mesh(gltf_quad(5, nodes, "", &data_uri()).as_bytes(), "q.gltf", &opts()).expect("import"); + assert!(all_up(&m.objects[0])); +} + +#[test] +fn gltf_externe_bin() { + let j = gltf_quad(5, "[{\"mesh\":0}]", "", "\"uri\":\"q%20x.bin\","); + let e = import_mesh(j.as_bytes(), "q.gltf", &opts()).unwrap_err(); + assert!(e.contains("q x.bin"), "{e}"); + let o = Options { files: vec![("Q X.bin".into(), quad_buffer())], ..opts() }; + let m = import_mesh(j.as_bytes(), "q.gltf", &o).expect("import"); + assert_eq!(m.triangles, 2); +} + +#[test] +fn gltf_ohne_indizes() { + let j = gltf_quad(5, "[{\"mesh\":0}]", "", &data_uri()).replace(",\"indices\":1", ""); + let m = import_mesh(j.as_bytes(), "q.gltf", &opts()).expect("import"); + assert_eq!(m.triangles, 2); +} + +#[test] +fn glb_aus_gltf_bauen_und_kuerzen() { + let j = gltf_quad(5, "[{\"mesh\":0}]", "", ""); + let mut json = j.into_bytes(); + while json.len() % 4 != 0 { + json.push(b' '); + } + let bin = quad_buffer(); + let mut glb = b"glTF".to_vec(); + glb.extend(2u32.to_le_bytes()); + glb.extend(((12 + 8 + json.len() + 8 + bin.len()) as u32).to_le_bytes()); + glb.extend((json.len() as u32).to_le_bytes()); + glb.extend(0x4E4F534Au32.to_le_bytes()); + glb.extend(&json); + glb.extend((bin.len() as u32).to_le_bytes()); + glb.extend(0x004E4942u32.to_le_bytes()); + glb.extend(&bin); + let m = import_mesh(&glb, "q.glb", &opts()).expect("import"); + assert_eq!(m.triangles, 2); + // Jede Kürzung ergibt einen Fehler oder ein Ergebnis, nie einen Panic. + for n in 0..glb.len() { + let _ = import_mesh(&glb[..n], "q.glb", &opts()); + } +} + +#[test] +fn gltf_draco_abgelehnt() { + let j = gltf_quad(4, "[{\"mesh\":0}]", ",\"extensionsRequired\":[\"KHR_draco_mesh_compression\"]", &data_uri()); + let e = import_mesh(j.as_bytes(), "q.gltf", &opts()).unwrap_err(); + assert!(e.contains("KHR_draco"), "{e}"); +} + +// ── Budget, kaputte Dateien, Kodierung ────────────────────────────────────── + +#[test] +fn dreiecksbudget() { + let (p, t) = cuboid(0.0, 0.0, 0.0, 1.0, 1.0, 1.0); + let (f, s) = flat(&[G { name: "K", rgba: None, pos: p, tris: t }]); + let obj = export_obj(&f, &s).expect("obj"); + let m = import_mesh(obj.as_bytes(), "x.obj", &Options { max_triangles: 5, ..opts() }).expect("import"); + assert!(m.truncated); + assert_eq!(m.triangles, 5); +} + +#[test] +fn kaputte_dateien_ohne_panic() { + let samples: Vec<(&str, Vec)> = vec![ + ("a.obj", b"f 1 2 3\nv 1\nv a b c\nf x/y/z 1 2\n".to_vec()), + ("a.stl", b"solid\nfacet\nvertex 1 2\nendfacet\n".to_vec()), + ("a.stl", vec![0u8; 84]), + ("a.stl", { + let mut v = vec![0u8; 84]; + v[80] = 255; + v + }), + ("a.ply", b"ply\nformat ascii 1.0\nelement vertex 99999999999\nproperty float x\nend_header\n".to_vec()), + ( + "a.ply", + b"ply\nformat binary_little_endian 1.0\nelement vertex 3\nproperty float x\nproperty float y\nproperty float z\nelement face 1\nproperty list uchar int vertex_index\nend_header\n\x00\x00".to_vec(), + ), + ("a.gltf", b"{\"asset\":{\"version\":\"2.0\"},\"nodes\":[{\"children\":[0]}],\"scenes\":[{\"nodes\":[0]}]}".to_vec()), + ("a.gltf", b"{\"asset\":{\"version\":\"2.0\"},\"meshes\":[{\"primitives\":[{\"attributes\":{\"POSITION\":7}}]}]}".to_vec()), + ("a.gltf", b"{{{{{{{".to_vec()), + ("a.gltf", "[".repeat(5000).into_bytes()), + ("a.glb", b"glTF\x02\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff".to_vec()), + ("a.bin", vec![1, 2, 3, 4]), + ("a.obj", Vec::new()), + ]; + for (n, b) in samples { + let _ = import_mesh(&b, n, &opts()); + } + let (p, t) = cuboid(0.0, 0.0, 0.0, 1.0, 1.0, 1.0); + let (f, s) = flat(&[G { name: "K", rgba: Some([0.5; 4]), pos: p, tris: t }]); + let obj = export_obj(&f, &s).expect("obj"); + for n in 0..obj.len() { + let _ = import_mesh(&obj.as_bytes()[..n], "x.obj", &opts()); + } + let stl = binary_stl(b"x", &[([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], 0)]); + for n in 0..stl.len() { + let _ = import_mesh(&stl[..n], "x.stl", &opts()); + } + let mut ply = b"ply\nformat binary_little_endian 1.0\nelement vertex 3\nproperty float x\nproperty float y\nproperty float z\nelement face 1\nproperty list uchar int vertex_index\nend_header\n".to_vec(); + for c in [0.0f32, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0] { + ply.extend(c.to_le_bytes()); + } + ply.push(3); + for i in [0i32, 1, 2] { + ply.extend(i.to_le_bytes()); + } + assert_eq!(import_mesh(&ply, "x.ply", &opts()).expect("ply").triangles, 1); + for n in 0..ply.len() { + let _ = import_mesh(&ply[..n], "x.ply", &opts()); + } +} + +#[test] +fn flache_kodierung() { + let (f, s) = flat(&two_boxes()); + let m = import_mesh(&export_glb(&f, &s).expect("glb"), "x.glb", &opts()).expect("import"); + let (flat, strings) = encode(&m); + assert_eq!(flat[0], FLAT_VERSION); + assert_eq!(flat[1], 2.0); + assert_eq!(flat[2], 1.0); // Y oben + assert_eq!(flat[6], 24.0); + assert_eq!(flat[11], 2.0); + let name0 = strings[flat[12] as usize].clone(); + assert!(name0.starts_with("Wand_") || name0.starts_with("Stuetze_")); + let expect: usize = 12 + m.objects.iter().map(|o| 9 + o.positions.len() + o.indices.len()).sum::(); + assert_eq!(flat.len(), expect); +} + +#[test] +fn formaterkennung() { + assert_eq!(detect_format(b"glTF....", "x.bin"), Some(Format::Gltf)); + assert_eq!(detect_format(b"ply\nformat", "x"), Some(Format::Ply)); + assert_eq!(detect_format(b"v 0 0 0\nf 1 1 1", "datei"), Some(Format::Obj)); + assert_eq!(detect_format(b"solid a\nfacet normal 0 0 1", "datei"), Some(Format::Stl)); + assert_eq!(detect_format(b"\x00\x01\x02", "x.dat"), None); +}