Merge [C12][B3] Mesh-Import in Rust: OBJ/MTL, STL, PLY, glTF/GLB als Kontext-Meshes; Dialog, Menue, Drag & Drop, CLI import-mesh

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-28 16:17:52 +00:00
commit 28f1f64aa4
19 files changed
+3706 -4

No files matched your search

+28
View File
@@ -733,6 +733,34 @@ Code-Übernahme Lizenz der Abhängigkeiten prüfen, Pflicht [51].
truck-Extrusionen (nur Prisma-Näherung) nicht wie im 3D; Dreieckszahl nicht gegen die GPU-Puffer von render3d gemessen
(Wand-Löcher und Decken aus denselben Ableitungen, Dächer/Stützen/Treppen/Öffnungen identisch); nicht in
Blender/Twinmotion/Enscape geöffnet, nur Validator; nicht in der Tauri-App getestet. · S
- ◐ **[C12] Allgemeiner Mesh-Import als Kontext-Meshes** (Gegenstück zu [C11], 28.10.): Nachbargebäude, Möbel und
Umgebungsmodelle aus SketchUp/Blender/Rhino. Eigener Code in `src-tauri/fileio/src/mesh_import.rs` (OBJ + MTL, STL,
PLY mit Flächen) und `mesh_import_gltf.rs` (glTF 2.0/GLB mit kleinem JSON-Leser, keine neue Abhängigkeit; earcutr
für N-Ecke), Bindung `import_mesh` in `pkgFileIo`. OBJ: `o`/`g`/`usemtl` → je Objekt+Material ein Mesh (Gruppe = Ebene),
Polygone trianguliert (Drehsinn bleibt), negative Indizes, MTL `Kd`/`d`/`Tr` (`.mtl` nur, wenn mitgegeben). STL: ASCII
(mehrere `solid`) und binär, Eckpunkte verschweisst, Farbvarianten VisCAM/SolidView und Magics (`COLOR=`). glTF:
.gltf (Data-URI, externe `.bin` nur wenn mitgegeben) und .glb, Knoten-Hierarchie (Matrix oder TRS, Spiegelung dreht
die Wicklung), TRIANGLES/STRIP/FAN, Indizes u8/u16/u32, normalisierte Ganzzahl-Positionen, `baseColorFactor` → sRGB
als `color`; Draco/Meshopt → Fehlermeldung. PLY ohne Flächen → Fehler `[punktwolke]`, die App öffnet dann den
Punktwolken-Import. Achse: glTF Y-up = Umkehr der Export-Abbildung (Datei (X,Y,Z) → Modell (X,−Z,Y)); OBJ/STL/PLY
Z oben / Y oben / automatisch (Kopfkommentar „Dossier/Blender/Rhinoceros“, dann kleinste Ausdehnung, sonst OBJ Y,
STL/PLY Z; `up_certain` meldet, ob belastbar). Einheit mm/cm/m/inch/foot (glTF immer m). Budget 6 Mio. Dreiecke,
24 Mio. Eckpunkte; NaN/Index ausserhalb/entartet werden verworfen und gezählt, nie Panic. TS: `io/meshImport.ts`
(+ `meshImport.worker.ts`, Rückfall im Thread), Abbildung wie [B3] (`color`, `layer` = Gruppe; > 2000 Objekte je
Gruppe+Farbe zusammengelegt), Dialog `ui/MeshImportDialog.tsx` (Einheit, Achse mit Erkennungsanzeige, Platzierung
„Projekt-Nullpunkt“ = Grundriss-Mitte auf 0 und Unterkante auf z = 0 / „Original-Koordinaten“ mit LV95-Rückschub wie IFC),
Menü „3D-Modell importieren …“ (mehrere Dateien: Modell + `.mtl`/`.bin`), Drag & Drop (auch mehrere Dateien),
CLI `import-mesh <datei> [--unit] [--up] [--placement] [--out]` und `convert` mit obj/stl/gltf/glb/ply als Eingabe
(Begleitdateien aus dem Verzeichnis). Einfügen nur über `setProject`/Ops (`addContextObjectsAndFit`).
Prüfung: 27 Rust-Tests (Rundreise glb/gltf/obj/stl mit den eigenen Schreibern: Dreieckszahl, Volumen, Lage, Farbe;
Quads/konkave N-Ecke, negative Indizes, MTL, Node-Matrizen/TRS, Strip/Fan, externe `.bin`, Budget, jede Kürzung gültiger
Dateien und Müll ohne Panic), 13 vitest (Fassade, Platzierung, Worker-Protokoll) + 4 CLI-Tests. `src/io/swissBuildings3d.ts`
hat keinen eigenen OBJ-Parser (nur DXF/DWG werden gelesen, `.obj` steht nur in der Asset-Prioritätsliste) — dort nichts
umzustellen. **Offen:** keine Texturen/UVs/Normalen/Vertex-Farben (glTF `COLOR_0`, OBJ `v x y z r g b`), keine
Instanzen-Erweiterungen (`EXT_mesh_gpu_instancing`), Sparse-Accessors ignoriert, Draco/Meshopt nicht gelesen,
`KHR_materials_pbrSpecularGlossiness` ignoriert; STL-Magics-Bit-Belegung nach Beschreibung, nicht an echten Dateien geprüft;
Achsen-Erkennung ist eine Heuristik; Dialog und Drag & Drop nicht in der Tauri-App und nicht im Browser angeklickt;
keine Dateien aus echtem SketchUp/Blender/Rhino gelesen (nur Rundreise und synthetische Fälle). · M
## Bewusst nicht übernommen
+2
View File
@@ -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;
File diff suppressed because it is too large. Load diff
+663
View File
@@ -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<Json>),
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<f64> {
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<usize> {
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<Vec<f64>> {
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<Json, String> {
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<Json, String> {
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<u8> = 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::<f64>().map(Json::Num).map_err(|_| "JSON: Zahl ungültig".to_string())
}
}
}
fn hex4(&mut self) -> Result<u32, String> {
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<Json, String> {
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<Vec<u8>, 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<Vec<u8>>,
}
/// 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<Vec<f64>, 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<usize>) -> 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<u8>> = Vec::new();
let mut missing: Vec<String> = 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<usize> = 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<usize> = 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>, 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<u32> = 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(())
}
+579
View File
@@ -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<f64>, String) {
let mut strings: Vec<String> = Vec::new();
let s = |t: &str, strings: &mut Vec<String>| -> 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<f64> = 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<G> {
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::<f64>() - 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<u8> {
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<u8> {
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<u8>)> = 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::<usize>();
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);
}
+22
View File
@@ -57,6 +57,9 @@ import { stepTextToImportedMeshes } from "./io/stepImport";
import { formatIfcReport, ifcBytesToImportedMeshes } from "./io/ifcImport";
import { formatIfcElementsSummary, ifcElementsToProject, readIfcElements } from "./io/ifcElements";
import { IfcImportDialog, type IfcImportMode } from "./ui/IfcImportDialog";
import { MeshImportHost } from "./ui/MeshImportDialog";
import { openMeshFileDialog, requestMeshImport, splitMeshFiles } from "./state/meshImportStore";
import { formatMeshReport, isMeshFile } from "./io/meshImport";
import { projectGeoOrigin } from "./model/geoRebase";
import { applyClashMarkers, runClashCheck } from "./analysis/clash";
import { checkForUpdate } from "./update/checkForUpdate";
@@ -1748,6 +1751,7 @@ export default function App() {
};
/** Datei aus Import-Dialog oder Drag & Drop: IFC direkt, sonst DXF/DWG-Dialog. */
const openImportForAnyFile = (f: File) => {
if (isMeshFile(f.name)) return requestMeshImport(f);
if (isPointCloudFile(f.name)) return requestPointCloudImport(f);
if (/\.ifc$/i.test(f.name)) importIfcFile(f);
else openImportForFile(f);
@@ -2456,6 +2460,7 @@ export default function App() {
onImportStep: () => stepInputRef.current?.click(),
onImportIfc: () => ifcInputRef.current?.click(),
onImportPointCloud: () => openPointCloudFileDialog(),
onImportMesh: () => openMeshFileDialog(),
onClashCheck: () => {
const p0 = project;
runClashCheck(p0)
@@ -3146,6 +3151,13 @@ export default function App() {
const { onAppDragEnter, onAppDragOver, onAppDragLeave, onAppDrop } = useFileDropImport(
setDropActive,
openImportForAnyFile,
(files) => {
// Mehrere Dateien: Modell + Begleitdateien (.mtl/.bin) gemeinsam an den Mesh-Import.
const r = splitMeshFiles(files);
if (!r) return false;
requestMeshImport(r.file, r.sidecars);
return true;
},
);
// Host-Context für die Panels — siehe state/usePanelHostBase.ts.
@@ -3350,6 +3362,15 @@ export default function App() {
/>
{/* Punktwolken-Import ([27]): verstecktes Datei-Feld + Dialog (UI-Store, nicht im Projekt). */}
<PointCloudImportHost project={project} />
{/* 3D-Modell-Import (OBJ/STL/glTF/GLB/PLY): verstecktes Datei-Feld + Dialog. */}
<MeshImportHost
project={project}
notify={notify}
onImport={(meshes, report) => {
if (meshes.length) addContextObjectsAndFit(meshes);
notify(formatMeshReport(report, t), meshes.length === 0 || report.truncated ? "warning" : "info");
}}
/>
{/* Verstecktes IFC-Datei-Input (Menü Datei, IFC importieren). */}
<input
ref={ifcInputRef}
@@ -3437,6 +3458,7 @@ export default function App() {
onSaveProject={onSaveProject}
onImport={() => dxfInputRef.current?.click()}
onImportPointCloud={() => openPointCloudFileDialog()}
onImportMesh={() => openMeshFileDialog()}
onUndo={undo}
onRedo={redo}
canUndo={canUndo}
+66
View File
@@ -0,0 +1,66 @@
// dossier-cli import-mesh und convert mit Mesh-Eingabe: Rundreise über echte Dateien (glb, gltf, obj+mtl, stl).
import { beforeAll, describe, expect, it } from "vitest";
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { run } from "./main";
import { parseProjectFile, sampleProject, serializeProject } from "../core";
import type { Project } from "../core";
const dir = mkdtempSync(join(tmpdir(), "dossier-import-mesh-"));
const p = (name: string) => join(dir, name);
const obp = p("demo.obp");
/** Projektdatei lesen; schlägt der Test fehl, wenn sie ungültig ist. */
function load(path: string): Project {
const r = parseProjectFile(readFileSync(path, "utf8"));
if (!r.ok) throw new Error(r.error);
return r.project;
}
beforeAll(() => {
process.env.DOSSIER_WASM_DIR = join(process.cwd(), "src", "engine");
writeFileSync(obp, serializeProject(sampleProject));
});
describe("dossier-cli: Mesh-Import", () => {
it("convert: glb/gltf/obj/stl → obp mit Kontext-Meshes", async () => {
for (const ext of ["glb", "gltf", "obj", "stl"]) {
expect(await run(["convert", obp, p(`m.${ext}`)]), ext).toBe(0);
const out = p(`von-${ext}.obp`);
expect(await run(["convert", p(`m.${ext}`), out]), ext).toBe(0);
const project = load(out);
const ctx = project.context ?? [];
expect(ctx.length, ext).toBeGreaterThan(0);
expect(ctx.every((c) => c.type === "importedMesh" && c.indices.length > 0), ext).toBe(true);
}
}, 120_000);
it("import-mesh: glTF mit Farbe, --out schreibt das Projekt", async () => {
const out = p("import.obp");
expect(await run([obp, "import-mesh", p("m.glb"), "--out", out, "--placement", "original"])).toBe(0);
const project = load(out);
const before = sampleProject.context?.length ?? 0;
expect((project.context ?? []).length).toBeGreaterThan(before);
// Wände des Beispielprojekts haben Farben aus ihren Bauteilen.
expect((project.context ?? []).some((c) => c.type === "importedMesh" && typeof c.color === "string")).toBe(true);
}, 120_000);
it("import-mesh: OBJ mit MTL aus dem Verzeichnis, Einheit und Achse", async () => {
writeFileSync(p("z.obj"), "mtllib z.mtl\no Kiste\nusemtl rot\nv 0 0 0\nv 1000 0 0\nv 0 1000 0\nv 0 0 2000\nf 1 3 2\nf 1 2 4\nf 2 3 4\nf 3 1 4\n");
writeFileSync(p("z.mtl"), "newmtl rot\nKd 1 0 0\n");
const out = p("z.obp");
expect(await run([obp, "import-mesh", p("z.obj"), "--unit", "mm", "--up", "z", "--placement", "original", "--out", out])).toBe(0);
const project = load(out);
const m = (project.context ?? []).find((c) => c.name === "Kiste");
if (m?.type !== "importedMesh") throw new Error("Kiste fehlt");
expect(m.color).toBe("#ff0000");
expect(Math.max(...m.positions.filter((_, i) => i % 3 === 2))).toBeCloseTo(2, 9);
}, 60_000);
it("ungültige Optionen und kaputte Dateien: Exit-Code ≠ 0", async () => {
expect(await run([obp, "import-mesh", p("z.obj"), "--unit", "km"]).catch(() => 1)).not.toBe(0);
writeFileSync(p("kaputt.glb"), "kein glb");
expect(await run([obp, "import-mesh", p("kaputt.glb")]).catch(() => 1)).not.toBe(0);
}, 60_000);
});
+79 -3
View File
@@ -17,6 +17,8 @@
// dossier-cli <projekt.obp> import-ifc <datei.ifc> [--out neu.obp] [--group product|class] [--elements]
// IFC als Kontext-Meshes ([B3]), mit --elements als echte
// Bauteile ([B4]); Bericht als JSON auf stdout
// dossier-cli <projekt.obp> import-mesh <datei.obj|stl|gltf|glb|ply> [--out neu.obp] [--unit mm|cm|m|inch|foot] [--up z|y|auto]
// [--placement center|original] 3D-Modell als Kontext-Meshes; Bericht als JSON
// dossier-cli <projekt.obp> model3d [--out modell.json] 3D-Modell fürs Headless-Rendern (render_png)
// dossier-cli pointcloud-info <datei.las|laz|e57|ply|xyz|pts> [--voxel 0.05] [--max 2000000]
// Punktwolke lesen ([B9]) und Bericht als JSON (ohne Projekt)
@@ -46,6 +48,10 @@ import {
readIfcElements,
ifcElementsToProject,
ifcToImportedMeshes,
readMesh,
meshObjectsToImportedMeshes,
isMeshFile,
MESH_UNITS,
projectGeoOrigin,
ensureContextCategories,
projectToWorldCoords,
@@ -270,8 +276,8 @@ export async function run(argv: string[]): Promise<number> {
if (file === "pdf-info") return runPdfInfo(args, command);
if (!file || (!command && args.cmds.length === 0)) {
process.stderr.write(
"Aufruf: dossier-cli <projekt.obp> <info|validate|migrate|plan|section|elevation|dxf|dwg|ifc|import-ifc|step|obj|stl|glb|gltf|schedule|kennzahlen|sun|model3d> [Optionen]\n" +
" dossier-cli convert <eingabe.dxf|dwg|ifc|pdf|obp> <ausgabe.obp|dxf|dwg|ifc|obj|stl|glb|gltf|step> [--cmd \"befehl …\"]…\n" +
"Aufruf: dossier-cli <projekt.obp> <info|validate|migrate|plan|section|elevation|dxf|dwg|ifc|import-ifc|import-mesh|step|obj|stl|glb|gltf|schedule|kennzahlen|sun|model3d> [Optionen]\n" +
" dossier-cli convert <eingabe.dxf|dwg|ifc|pdf|obj|stl|gltf|glb|ply|obp> <ausgabe.obp|dxf|dwg|ifc|obj|stl|glb|gltf|step> [--cmd \"befehl …\"]…\n" +
" dossier-cli <projekt.obp> --cmd \"befehl …\" [--cmd …] ({last} = zuletzt geschriebene Datei)\n" +
" dossier-cli pointcloud-info <datei> [--voxel 0.05] [--max 2000000]\n" +
" dossier-cli bcf-info <datei.bcfzip>\n" +
@@ -331,6 +337,7 @@ async function importAny(path: string, args: Args): Promise<Project> {
const fileName = path.split(/[\\/]/).pop() ?? path;
const base: Project = { ...emptyProject, name: fileName.replace(/\.[^.]+$/, "") };
if (ext === "ifc") return (await ifcInto(base, bytes, fileName, args)).next;
if (isMeshFile(fileName)) return (await meshInto(base, bytes, path, args)).next;
if (ext === "dxf" || ext === "dwg" || ext === "pdf") {
await loadFileio();
let parsed;
@@ -363,7 +370,7 @@ async function importAny(path: string, args: Args): Promise<Project> {
];
return applyOps(base, diffToOps(base, { ...base, layers, drawings2d: drawings, context: [...parsed.meshes] }));
}
return fail(`Eingabeformat nicht unterstützt: .${ext} (obp, dxf, dwg, ifc, pdf)`);
return fail(`Eingabeformat nicht unterstützt: .${ext} (obp, dxf, dwg, ifc, pdf, obj, stl, gltf, glb, ply)`);
}
/** `convert <eingabe> <ausgabe>`: Eingabe nach Endung lesen, Ausgabe nach Endung schreiben, dann `--cmd` ausführen. */
@@ -430,6 +437,60 @@ async function ifcInto(project: Project, bytes: Uint8Array, fileName: string, ar
return { next, report: { ...report, byClass, triangles, contextObjects: meshes.length } };
}
/** Begleitdateien eines Mesh-Modells aus demselben Verzeichnis: `.mtl` (OBJ `mtllib`), externe `.bin` (glTF). */
function meshSidecars(path: string, bytes: Uint8Array): { name: string; bytes: Uint8Array }[] {
const names: string[] = [];
const ext = extOf(path);
if (ext === "obj") {
for (const m of new TextDecoder().decode(bytes.subarray(0, Math.min(bytes.length, 1 << 20))).matchAll(/^mtllib[ \t]+(.+)$/gm)) {
names.push(...m[1].trim().split(/\s+/));
}
} else if (ext === "gltf") {
try {
const j = JSON.parse(new TextDecoder().decode(bytes)) as { buffers?: { uri?: string }[] };
for (const b of j.buffers ?? []) if (b.uri && !b.uri.startsWith("data:")) names.push(decodeURIComponent(b.uri));
} catch {
/* kaputtes JSON meldet der Leser */
}
}
const out: { name: string; bytes: Uint8Array }[] = [];
for (const n of names) {
try {
out.push({ name: n, bytes: new Uint8Array(readFileSync(join(dirname(path), n))) });
} catch {
/* fehlende Datei meldet der Leser (MTL: Hinweis, glTF: Fehler) */
}
}
return out;
}
/** 3D-Modell (OBJ/STL/glTF/GLB/PLY) als Kontext-Meshes in ein Projekt übernehmen; `report` = Bericht für `import-mesh`. */
async function meshInto(project: Project, bytes: Uint8Array, path: string, args: Args): Promise<{ next: Project; report: unknown }> {
const fileName = path.split(/[\\/]/).pop() ?? path;
const unit = args.flags.get("unit") ?? "m";
if (!(MESH_UNITS as readonly string[]).includes(unit)) return fail(`--unit: ${MESH_UNITS.join("|")}`);
const up = args.flags.get("up") ?? "auto";
if (up !== "auto" && up !== "z" && up !== "y") return fail("--up: z|y|auto");
const placement = args.flags.get("placement") ?? "original";
if (placement !== "center" && placement !== "original") return fail("--placement: center|original");
let read;
try {
read = await readMesh(bytes, fileName, { unit: unit as (typeof MESH_UNITS)[number], up, files: meshSidecars(path, bytes) });
} catch (e) {
return fail(`${path}: ${e instanceof Error ? e.message : String(e)}`);
}
const meshes = meshObjectsToImportedMeshes(read.objects, fileName, { placement, geoOrigin: projectGeoOrigin(project) });
const next = applyOps(
project,
diffToOps(project, {
...project,
context: [...(project.context ?? []), ...meshes],
layers: ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : []))),
}),
);
return { next, report: { ...read.report, contextObjects: meshes.length } };
}
/** Führt EINEN Befehl gegen ein geladenes Projekt aus (Rückgabe = Exit-Code). */
async function execute(project: Project, file: string, command: string, rest: string[], args: Args): Promise<number> {
const scale = Number(args.flags.get("scale") ?? 100);
@@ -582,6 +643,21 @@ async function execute(project: Project, file: string, command: string, rest: st
if (target) out(args, serializeProject(r.next), target);
return 0;
}
case "import-mesh": {
const src = rest[0];
if (!src) fail("import-mesh: Modelldatei fehlt");
let bytes: Uint8Array;
try {
bytes = new Uint8Array(readFileSync(src));
} catch (e) {
fail(`Datei nicht lesbar: ${src} (${e instanceof Error ? e.message : String(e)})`);
}
const r = await meshInto(project, bytes, src, args);
process.stdout.write(JSON.stringify(r.report, null, 2) + "\n");
const target = args.flags.get("out");
if (target) out(args, serializeProject(r.next), target);
return 0;
}
case "mcp":
await serveStdio(file);
return 0;
+2
View File
@@ -37,3 +37,5 @@ export { readPointCloud, readPointCloudFlat, isPointCloudFile, DEFAULT_MAX_POINT
export type { PointCloudData, PointCloudOptions, PointCloudReport } from "../io/pointCloud";
export { readPdfVectorPage, pdfPageToImport, pdfPageInfo, pdfMetersPerPt, isPdfFile, PDF_SCALES } from "../io/pdfVector";
export type { PdfVectorPage, PdfVectorPath, PdfVectorText } from "../io/pdfVector";
export { readMesh, meshObjectsToImportedMeshes, formatMeshReport, isMeshFile, MESH_UNITS, MESH_UNIT_SCALE } from "../io/meshImport";
export type { MeshObject, MeshImportReport, MeshUnit, MeshUp, MeshPlacement } from "../io/meshImport";
+30
View File
@@ -1848,6 +1848,36 @@ export const de = {
"ifc.importDialog.asElements": "Als Bauteile",
"ifc.importDialog.asElementsHint": "Wände, Decken, Stützen, Türen/Fenster, Räume und Geschosse werden bearbeitbare Dossier-Bauteile; was nicht sicher abbildbar ist, bleibt Mesh.",
"ifc.importDialog.import": "Importieren",
"menu.native.importMesh": "3D-Modell importieren …",
"mesh.import.title": "3D-Modell importieren",
"mesh.import.failed": "3D-Modell-Import fehlgeschlagen",
"mesh.import.done": "{format} importiert: {n} Objekte, {tris} Dreiecke als Kontext-Meshes",
"mesh.import.up": "Achse erkannt: {axis} oben",
"mesh.import.upUncertain": "Achse unsicher, angenommen: {axis} oben (im Import-Dialog wählbar)",
"mesh.import.dropped": "{n} ungültige oder entartete Flächen verworfen",
"mesh.import.truncated": "abgebrochen: zu viele Dreiecke",
"mesh.import.noFaces": "Die PLY-Datei enthält keine Flächen (Punktwolke): sie wird als Punktwolke geöffnet.",
"mesh.import.missingExternal": "Zusätzliche Dateien fehlen: {list}. Wählen Sie sie zusammen mit dem Modell aus (oder ziehen Sie alle Dateien gemeinsam ins Fenster).",
"mesh.importDialog.files": "Begleitdateien: {list}",
"mesh.importDialog.unit": "Einheit der Datei",
"mesh.importDialog.unitFixed": "glTF/GLB ist immer in Metern.",
"mesh.importDialog.unit.mm": "Millimeter",
"mesh.importDialog.unit.cm": "Zentimeter",
"mesh.importDialog.unit.m": "Meter",
"mesh.importDialog.unit.inch": "Zoll (inch)",
"mesh.importDialog.unit.foot": "Fuss (foot)",
"mesh.importDialog.up": "Achse nach oben",
"mesh.importDialog.upFixed": "glTF/GLB ist immer Y oben.",
"mesh.importDialog.up.auto": "Automatisch erkennen",
"mesh.importDialog.up.z": "Z oben (Rhino, CAD, 3D-Druck)",
"mesh.importDialog.up.y": "Y oben (SketchUp, Blender, Spieleformate)",
"mesh.importDialog.detected": "Erkannt: {axis} oben, {n} Objekte, {tris} Dreiecke, {size} m × {depth} m × {height} m",
"mesh.importDialog.detectedUncertain": "Achse unsicher: bitte prüfen. Erkannt: {axis} oben, {n} Objekte, {tris} Dreiecke",
"mesh.importDialog.placement": "Platzierung",
"mesh.importDialog.placement.center": "Am Projekt-Nullpunkt (Mitte im Grundriss, Unterkante auf 0)",
"mesh.importDialog.placement.original": "An Original-Koordinaten (Landeskoordinaten werden bei Standort-Bezug auf den Nullpunkt gerechnet)",
"mesh.importDialog.reading": "Datei wird gelesen …",
"mesh.importDialog.import": "Importieren",
"recover.title": "Ungesicherte Arbeit gefunden",
"recover.message": "Von „{name}“ gibt es eine automatische Sicherung vom {when}, die nicht gespeichert wurde.",
"recover.unsaved": "unbenanntes Projekt",
+30
View File
@@ -1807,6 +1807,36 @@ export const en: Record<TranslationKey, string> = {
"ifc.importDialog.asElements": "As building elements",
"ifc.importDialog.asElementsHint": "Walls, slabs, columns, doors/windows, rooms and storeys become editable Dossier elements; anything not safely mappable stays a mesh.",
"ifc.importDialog.import": "Import",
"menu.native.importMesh": "Import 3D model …",
"mesh.import.title": "Import 3D model",
"mesh.import.failed": "3D model import failed",
"mesh.import.done": "{format} imported: {n} objects, {tris} triangles as context meshes",
"mesh.import.up": "Axis detected: {axis} up",
"mesh.import.upUncertain": "Axis uncertain, assumed: {axis} up (selectable in the import dialog)",
"mesh.import.dropped": "{n} invalid or degenerate faces dropped",
"mesh.import.truncated": "aborted: too many triangles",
"mesh.import.noFaces": "The PLY file has no faces (point cloud): opening it as a point cloud.",
"mesh.import.missingExternal": "Additional files are missing: {list}. Select them together with the model (or drop all files into the window together).",
"mesh.importDialog.files": "Companion files: {list}",
"mesh.importDialog.unit": "File unit",
"mesh.importDialog.unitFixed": "glTF/GLB is always in metres.",
"mesh.importDialog.unit.mm": "Millimetres",
"mesh.importDialog.unit.cm": "Centimetres",
"mesh.importDialog.unit.m": "Metres",
"mesh.importDialog.unit.inch": "Inches",
"mesh.importDialog.unit.foot": "Feet",
"mesh.importDialog.up": "Up axis",
"mesh.importDialog.upFixed": "glTF/GLB is always Y up.",
"mesh.importDialog.up.auto": "Detect automatically",
"mesh.importDialog.up.z": "Z up (Rhino, CAD, 3D printing)",
"mesh.importDialog.up.y": "Y up (SketchUp, Blender, game formats)",
"mesh.importDialog.detected": "Detected: {axis} up, {n} objects, {tris} triangles, {size} m × {depth} m × {height} m",
"mesh.importDialog.detectedUncertain": "Axis uncertain: please check. Detected: {axis} up, {n} objects, {tris} triangles",
"mesh.importDialog.placement": "Placement",
"mesh.importDialog.placement.center": "At the project origin (centred in plan, bottom at 0)",
"mesh.importDialog.placement.original": "At original coordinates (national coordinates are moved to the origin if the project has a site reference)",
"mesh.importDialog.reading": "Reading file …",
"mesh.importDialog.import": "Import",
"recover.title": "Unsaved work found",
"recover.message": "There is an automatic backup of “{name}” from {when} that was never saved.",
"recover.unsaved": "untitled project",
+257
View File
@@ -0,0 +1,257 @@
// Mesh-Import: Rundreise mit dem eigenen OBJ/STL/glTF-Export (`export/exportMesh.ts`) → Rust-Leser →
// Kontext-Meshes; gleiche Dreieckszahl, Lage und Farbe. Sonderfälle (Quads, negative Indizes, kaputte
// Dateien) prüfen die Rust-Tests (`mesh_import_tests.rs`), hier die Fassade.
import "../engine/fileioWasm.setup";
import { describe, expect, it } from "vitest";
import { exportGlb, exportGltf, exportObj, exportStl } from "../export/exportMesh";
import type { ImportedMesh, Project, Wall } from "../model/types";
import {
MESH_UNIT_SCALE,
NO_FACES_PREFIX,
decodeMesh,
formatMeshReport,
handleMeshWorkerRequest,
isMeshFile,
meshColorHex,
meshObjectsToImportedMeshes,
meshShift,
readMesh,
type MeshObject,
type MeshWorkerRequest,
} from "./meshImport";
function baseProject(): Project {
return {
id: "t",
name: "T",
lineStyles: [],
hatches: [],
components: [{ id: "c", name: "C", color: "#ccc", hatchId: "none", joinPriority: 10 }],
wallTypes: [{ id: "aw", name: "Aussenwand", layers: [{ componentId: "c", thickness: 0.4 }] }],
ceilingTypes: [{ id: "dt", name: "Betondecke", layers: [{ componentId: "c", thickness: 0.2 }] }],
drawingLevels: [
{ id: "eg", name: "EG", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1.0, baseElevation: 0 },
],
layers: [{ code: "20", name: "Wände", color: "#0a0a0a", lw: 0.5, visible: true, locked: false }],
walls: [],
openings: [],
ceilings: [],
stairs: [],
extrudedSolids: [],
rooms: [],
drawings2d: [],
context: [],
} as Project;
}
/** Eine Wand (0,0)–(5,0), 2,6 m hoch, und ein orangefarbener Kontext-Würfel bei (20, 30). */
function project(): Project {
const p = baseProject();
const wall: Wall = {
id: "W1",
type: "wall",
floorId: "eg",
categoryCode: "20",
start: { x: 0, y: 0 },
end: { x: 5, y: 0 },
wallTypeId: "aw",
height: 2.6,
};
p.walls = [wall];
const cube: ImportedMesh = {
id: "K1",
type: "importedMesh",
name: "Nachbar",
color: "#ff8000",
positions: [20, 30, 0, 24, 30, 0, 24, 36, 0, 20, 36, 0, 20, 30, 9, 24, 30, 9, 24, 36, 9, 20, 36, 9],
indices: [0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 0, 1, 5, 0, 5, 4, 1, 2, 6, 1, 6, 5, 2, 3, 7, 2, 7, 6, 3, 0, 4, 3, 4, 7],
};
p.context = [cube];
return p;
}
const enc = new TextEncoder();
function bbox(objs: MeshObject[]): { lo: number[]; hi: number[] } {
const lo = [Infinity, Infinity, Infinity];
const hi = [-Infinity, -Infinity, -Infinity];
for (const o of objs) {
for (let i = 0; i < o.positions.length; i += 3) {
for (let a = 0; a < 3; a++) {
lo[a] = Math.min(lo[a], o.positions[i + a]);
hi[a] = Math.max(hi[a], o.positions[i + a]);
}
}
}
return { lo, hi };
}
const tris = (objs: MeshObject[]) => objs.reduce((n, o) => n + o.indices.length / 3, 0);
describe("Mesh-Import: Rundreise mit dem eigenen Export", () => {
it("GLB: Objekte, Dreieckszahl, Lage und Farbe bleiben erhalten", async () => {
const p = project();
const { objects, report } = await readMesh(exportGlb(p), "m.glb");
expect(report.format).toBe("gltf");
expect(report.up).toBe("y");
expect(objects.length).toBeGreaterThanOrEqual(2);
const nachbar = objects.find((o) => o.name.startsWith("Kontext_"));
expect(nachbar).toBeTruthy();
expect(nachbar!.indices.length / 3).toBe(12);
// Lage: Würfel (20..24, 30..36, 0..9) liegt wieder dort.
const b = bbox([nachbar!]);
expect(b.lo[0]).toBeCloseTo(20, 4);
expect(b.hi[0]).toBeCloseTo(24, 4);
expect(b.lo[1]).toBeCloseTo(30, 4);
expect(b.hi[1]).toBeCloseTo(36, 4);
expect(b.hi[2]).toBeCloseTo(9, 4);
// Farbe #ff8000 (sRGB → linear → sRGB).
expect(meshColorHex(nachbar!.color)).toBe("#ff8000");
// Wand: 0..5 in x, Höhe 2,6.
const wall = objects.find((o) => o.name.startsWith("Wand_"))!;
const bw = bbox([wall]);
expect(bw.lo[0]).toBeCloseTo(0, 4);
expect(bw.hi[0]).toBeCloseTo(5, 4);
expect(bw.hi[2]).toBeCloseTo(2.6, 4);
});
it("glTF (eingebettet), OBJ und STL ergeben dieselbe Dreieckszahl und Ausdehnung wie GLB", async () => {
const p = project();
const glb = await readMesh(exportGlb(p), "m.glb");
const gltf = await readMesh(enc.encode(exportGltf(p)), "m.gltf");
const obj = await readMesh(enc.encode(exportObj(p)), "m.obj");
const stl = await readMesh(enc.encode(exportStl(p)), "m.stl");
const n = tris(glb.objects);
expect(tris(gltf.objects)).toBe(n);
expect(tris(obj.objects)).toBe(n);
expect(tris(stl.objects)).toBe(n);
// OBJ trägt den Kopfkommentar (Y oben, sicher); STL wird an der Ausdehnung erkannt.
expect(obj.report.up).toBe("y");
expect(obj.report.upCertain).toBe(true);
expect(stl.report.up).toBe("y");
const ref = bbox(glb.objects);
for (const r of [gltf, obj, stl]) {
const b = bbox(r.objects);
for (let a = 0; a < 3; a++) {
expect(b.lo[a]).toBeCloseTo(ref.lo[a], 3);
expect(b.hi[a]).toBeCloseTo(ref.hi[a], 3);
}
}
});
it("OBJ: Einheit und erzwungene Achse", async () => {
const p = project();
const mm = await readMesh(enc.encode(exportObj(p)), "m.obj", { unit: "mm" });
const m = await readMesh(enc.encode(exportObj(p)), "m.obj");
expect(bbox(mm.objects).hi[0]).toBeCloseTo(bbox(m.objects).hi[0] * MESH_UNIT_SCALE.mm, 6);
const z = await readMesh(enc.encode(exportObj(p)), "m.obj", { up: "z" });
expect(z.report.up).toBe("z");
expect(z.report.upAuto).toBe(false);
});
});
describe("Mesh-Import: Abbildung auf Kontext-Meshes", () => {
it("Farbe ins Feld color, Gruppe als Ebene, Platzierung Mitte/Original", async () => {
const p = project();
const { objects } = await readMesh(exportGlb(p), "Haus.glb");
const orig = meshObjectsToImportedMeshes(objects, "Haus.glb", { placement: "original" });
const nachbar = orig.find((m) => m.name.startsWith("Kontext_"))!;
expect(nachbar.type).toBe("importedMesh");
expect(nachbar.color).toBe("#ff8000");
expect(nachbar.positions.length).toBe(24);
expect(Math.min(...nachbar.positions.filter((_, i) => i % 3 === 0))).toBeCloseTo(20, 4);
// Mitte: Grundriss-Mitte aller Objekte auf (0, 0), Unterkante auf z = 0.
const centered = meshObjectsToImportedMeshes(objects, "Haus.glb", { placement: "center" });
const xs = centered.flatMap((m) => m.positions.filter((_, i) => i % 3 === 0));
const ys = centered.flatMap((m) => m.positions.filter((_, i) => i % 3 === 1));
const zs = centered.flatMap((m) => m.positions.filter((_, i) => i % 3 === 2));
expect((Math.min(...xs) + Math.max(...xs)) / 2).toBeCloseTo(0, 6);
expect((Math.min(...ys) + Math.max(...ys)) / 2).toBeCloseTo(0, 6);
expect(Math.min(...zs)).toBeCloseTo(0, 6);
});
it("Landeskoordinaten werden bei Original-Platzierung auf den Modell-Nullpunkt geschoben", () => {
const o: MeshObject = {
name: "N",
group: "",
color: null,
positions: new Float64Array([2600010, 1200010, 0, 2600020, 1200010, 0, 2600020, 1200020, 5]),
indices: new Uint32Array([0, 1, 2]),
};
const shift = meshShift([o], { placement: "original", geoOrigin: { e: 2600000, n: 1200000 } });
expect(shift).toEqual([-2600000, -1200000, 0]);
expect(meshShift([o], { placement: "original", geoOrigin: null })).toEqual([0, 0, 0]);
});
it("viele Objekte werden je Gruppe und Farbe zusammengelegt", () => {
const objs: MeshObject[] = Array.from({ length: 2100 }, (_, i) => ({
name: `O${i}`,
group: i % 2 ? "A" : "B",
color: [1, 0, 0, 1],
positions: new Float64Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
indices: new Uint32Array([0, 1, 2]),
}));
const m = meshObjectsToImportedMeshes(objs, "x.obj", { placement: "original" });
expect(m).toHaveLength(2);
expect(m[0].indices.length / 3).toBe(1050);
expect(m[0].color).toBe("#ff0000");
});
it("Bericht als Text", async () => {
const { report } = await readMesh(enc.encode(exportObj(project())), "m.obj");
const text = formatMeshReport(report, (k, v) => `${k}${v ? JSON.stringify(v) : ""}`);
expect(text).toContain("mesh.import.done");
expect(text).toContain("mesh.import.up");
});
});
describe("Mesh-Import: Fehler", () => {
it("kaputte Dateien: Fehlermeldung statt Absturz", async () => {
await expect(readMesh(enc.encode("das ist kein Mesh"), "x.obj")).rejects.toThrow();
await expect(readMesh(new Uint8Array([1, 2, 3, 4]), "x.glb")).rejects.toThrow();
await expect(readMesh(new Uint8Array(0), "x.stl")).rejects.toThrow();
const glb = exportGlb(project());
await expect(readMesh(glb.slice(0, 100), "x.glb")).rejects.toThrow();
});
it("PLY ohne Flächen meldet die Punktwolke", async () => {
const ply = "ply\nformat ascii 1.0\nelement vertex 1\nproperty float x\nproperty float y\nproperty float z\nend_header\n0 0 0\n";
await expect(readMesh(enc.encode(ply), "x.ply")).rejects.toThrow(NO_FACES_PREFIX);
});
it("externe .bin: Meldung, dann mit Begleitdatei lesbar", async () => {
const bin = new Uint8Array(new Float32Array([0, 0, 0, 1, 0, 0, 0, 0, 1]).buffer);
const j = JSON.stringify({
asset: { version: "2.0" },
scenes: [{ nodes: [0] }],
nodes: [{ mesh: 0 }],
meshes: [{ primitives: [{ attributes: { POSITION: 0 } }] }],
accessors: [{ bufferView: 0, componentType: 5126, count: 3, type: "VEC3" }],
bufferViews: [{ buffer: 0, byteLength: 36 }],
buffers: [{ uri: "d.bin", byteLength: 36 }],
});
await expect(readMesh(enc.encode(j), "d.gltf")).rejects.toThrow("d.bin");
const { report } = await readMesh(enc.encode(j), "d.gltf", { files: [{ name: "d.bin", bytes: bin }] });
expect(report.triangles).toBe(1);
});
it("decodeMesh verwirft beschädigte Puffer", () => {
expect(() => decodeMesh({ flat: new Float64Array([9, 0]), strings: [] })).toThrow();
});
it("Worker-Protokoll: Antwort und Fehler", async () => {
const data = exportGlb(project()).slice().buffer;
const req: MeshWorkerRequest = { type: "parse", data, name: "m.glb", unit: "m", up: "auto", maxTriangles: 0, files: [] };
const ok = await handleMeshWorkerRequest(req);
expect(ok.res.type).toBe("result");
expect(ok.transfer.length).toBe(1);
const bad = await handleMeshWorkerRequest({ ...req, data: new Uint8Array([1, 2]).buffer });
expect(bad.res.type).toBe("error");
});
it("Endungen", () => {
expect(isMeshFile("a.GLB")).toBe(true);
expect(isMeshFile("a.ifc")).toBe(false);
});
});
+374
View File
@@ -0,0 +1,374 @@
// Allgemeiner Mesh-Import als Kontext-Meshes ([B3]/[C11]): OBJ (+ MTL), STL, glTF/GLB, PLY mit Flächen —
// Nachbargebäude und Umgebungsmodelle aus SketchUp/Blender/Rhino, Möbel. Dünne Fassade über den Rust-Leser
// (`src-tauri/fileio/src/mesh_import.rs`, Modul `pkgFileIo`); hier nur Aufruf, Dekodierung der flachen Puffer
// und die Abbildung auf `ImportedMesh` (wie `ifcImport.ts`, Farbe im Feld `color`).
//
// Laden im Web-Worker (`meshImport.worker.ts`), Rückfall im aufrufenden Thread (Node: CLI, Tests).
//
// Achse und Einheit entscheidet Rust (glTF: Y-up, Meter; OBJ/STL/PLY: Wahl bzw. Erkennung); Ergebnis ist
// Modell-Meter mit Z = Höhe. Platzierung: "center" = Grundriss-Mitte auf den Projekt-Nullpunkt, Unterkante
// auf z = 0; "original" = Koordinaten der Datei (liegen sie in Landeskoordinaten und das Projekt hat einen
// Standort-Bezug: auf den Modell-Nullpunkt zurückgeschoben, wie beim IFC-Import).
import { loadFileio } from "../engine/fileioWasm";
import { GENERIC_IMPORT_CATEGORY } from "../model/contextCategories";
import type { ImportedMesh } from "../model/types";
import { rgbToHex } from "../model/color";
export type MeshUnit = "mm" | "cm" | "m" | "inch" | "foot";
export type MeshUp = "auto" | "z" | "y";
export type MeshPlacement = "center" | "original";
export type MeshFormat = "obj" | "stl" | "gltf" | "ply";
/** Meter je Einheit. */
export const MESH_UNIT_SCALE: Record<MeshUnit, number> = { mm: 0.001, cm: 0.01, m: 1, inch: 0.0254, foot: 0.3048 };
export const MESH_UNITS: readonly MeshUnit[] = ["mm", "cm", "m", "inch", "foot"];
/** Endungen der Hauptdateien (Menü, Drag & Drop); `mtl`/`bin` sind Begleitdateien. */
export const MESH_EXTENSIONS = ["obj", "stl", "gltf", "glb", "ply"] as const;
export const MESH_SIDECAR_EXTENSIONS = ["mtl", "bin"] as const;
/** Ab so vielen Objekten wird je Gruppe + Farbe zusammengelegt (Projektdatei, Kontext-Panel). */
export const MAX_SINGLE = 2000;
/** Präfix des Rust-Fehlers für PLY ohne Flächen. */
export const NO_FACES_PREFIX = "[punktwolke]";
/** Präfix des Rust-Fehlers für fehlende externe glTF-Puffer. */
export const MISSING_EXTERNAL_PREFIX = "[extern]";
const FORMATS: readonly MeshFormat[] = ["obj", "stl", "gltf", "ply"];
export function isMeshFile(name: string): boolean {
const ext = name.toLowerCase().split(".").pop() ?? "";
return (MESH_EXTENSIONS as readonly string[]).includes(ext);
}
export function isMeshSidecar(name: string): boolean {
const ext = name.toLowerCase().split(".").pop() ?? "";
return (MESH_SIDECAR_EXTENSIONS as readonly string[]).includes(ext);
}
export interface MeshReadOptions {
unit?: MeshUnit;
up?: MeshUp;
/** Dreiecksgrenze (0/fehlt = Voreinstellung 6 Mio.). */
maxTriangles?: number;
/** Begleitdateien (`.mtl`, `.bin`). */
files?: { name: string; bytes: Uint8Array }[];
}
/** Ein gelesenes Objekt (Modell-Meter, Z = Höhe). */
export interface MeshObject {
name: string;
group: string;
/** sRGB 0..1 mit Alpha, falls die Datei eine Farbe hat. */
color: [number, number, number, number] | null;
positions: Float64Array;
indices: Uint32Array;
}
export interface MeshImportReport {
format: MeshFormat;
/** Verwendete Achse. */
up: "z" | "y";
/** Achse wurde erkannt (nicht vorgegeben). */
upAuto: boolean;
/** Erkennung belastbar (Kopfkommentar oder eindeutige Ausdehnung). */
upCertain: boolean;
unitScale: number;
triangles: number;
degenerate: number;
badFaces: number;
truncated: boolean;
warnings: string[];
objects: number;
}
/** Rohergebnis aus Rust: Zahlenpuffer + Zeichenketten. */
export interface MeshFlat {
flat: Float64Array;
strings: string[];
}
/** Worker-Protokoll (`meshImport.worker.ts`). */
export type MeshWorkerRequest = {
type: "parse";
data: ArrayBuffer;
name: string;
unit: MeshUnit;
up: MeshUp;
maxTriangles: number;
files: { name: string; data: ArrayBuffer }[];
};
export type MeshWorkerResponse = { type: "result"; flat: MeshFlat } | { type: "error"; message: string };
const FLAT_VERSION = 1;
const HEAD = 12;
/** Flache Puffer → Objekte + Bericht (Aufbau: Kopf von `mesh_import.rs`). */
export function decodeMesh(r: MeshFlat): { objects: MeshObject[]; report: MeshImportReport } {
const f = r.flat;
if (f.length < HEAD || f[0] !== FLAT_VERSION) throw new Error("Mesh-Import: unbekannte Kodierung");
const nWarn = f[10];
const nObj = f[11];
let at = HEAD;
const warnings: string[] = [];
for (let i = 0; i < nWarn; i++) warnings.push(r.strings[f[at++]] ?? "");
const objects: MeshObject[] = [];
for (let k = 0; k < nObj; k++) {
const name = r.strings[f[at]] ?? "";
const group = f[at + 1] >= 0 ? (r.strings[f[at + 1]] ?? "") : "";
const color: MeshObject["color"] = f[at + 2] === 1 ? [f[at + 3], f[at + 4], f[at + 5], f[at + 6]] : null;
const np = f[at + 7];
const ni = f[at + 8];
at += 9;
if (!Number.isInteger(np) || !Number.isInteger(ni) || np < 0 || ni < 0 || at + np + ni > f.length) {
throw new Error("Mesh-Import: Puffer beschädigt");
}
const positions = f.slice(at, at + np);
at += np;
const idx = f.subarray(at, at + ni);
const indices = new Uint32Array(ni);
for (let i = 0; i < ni; i++) indices[i] = idx[i];
at += ni;
objects.push({ name, group, color, positions, indices });
}
const report: MeshImportReport = {
format: FORMATS[f[1]] ?? "obj",
up: f[2] === 1 ? "y" : "z",
upAuto: f[3] === 1,
upCertain: f[4] === 1,
unitScale: f[5],
triangles: f[6],
degenerate: f[7],
badFaces: f[8],
truncated: f[9] === 1,
warnings,
objects: objects.length,
};
return { objects, report };
}
/** Liest Mesh-Bytes mit dem geladenen Format-Modul (Worker oder aufrufender Thread). */
export async function importMeshFlat(
bytes: Uint8Array,
name: string,
opts: Required<Pick<MeshReadOptions, "unit" | "up" | "maxTriangles">> & { files: { name: string; bytes: Uint8Array }[] },
): Promise<MeshFlat> {
const m = await loadFileio();
const sizes = opts.files.map((f) => f.bytes.length);
const blob = new Uint8Array(sizes.reduce((a, b) => a + b, 0));
let o = 0;
for (const f of opts.files) {
blob.set(f.bytes, o);
o += f.bytes.length;
}
const r = m.import_mesh(
bytes,
name,
MESH_UNIT_SCALE[opts.unit],
opts.up === "z" ? 1 : opts.up === "y" ? 2 : 0,
opts.maxTriangles,
opts.files.map((f) => f.name),
new Float64Array(sizes),
blob,
);
try {
return { flat: r.flat(), strings: r.strings() };
} finally {
r.free();
}
}
function resolve(o: MeshReadOptions | undefined) {
return {
unit: o?.unit ?? "m",
up: o?.up ?? "auto",
maxTriangles: o?.maxTriangles && o.maxTriangles > 0 ? o.maxTriangles : 0,
files: o?.files ?? [],
};
}
/** Beantwortet eine Worker-Anfrage; liefert Antwort und zu übertragende Puffer. */
export async function handleMeshWorkerRequest(req: MeshWorkerRequest): Promise<{ res: MeshWorkerResponse; transfer: Transferable[] }> {
try {
if (req?.type !== "parse" || !(req.data instanceof ArrayBuffer)) throw new Error("ungültige Anfrage");
const flat = await importMeshFlat(new Uint8Array(req.data), req.name, {
unit: req.unit,
up: req.up,
maxTriangles: req.maxTriangles,
files: (req.files ?? []).map((f) => ({ name: f.name, bytes: new Uint8Array(f.data) })),
});
return { res: { type: "result", flat }, transfer: [flat.flat.buffer] };
} catch (err) {
return { res: { type: "error", message: err instanceof Error ? err.message : String(err) }, transfer: [] };
}
}
/** Liest im Web-Worker; `null`, wenn kein Worker verfügbar ist oder er nicht startet. */
function readInWorker(bytes: Uint8Array, name: string, o: ReturnType<typeof resolve>): Promise<MeshFlat | null> {
if (typeof Worker === "undefined") return Promise.resolve(null);
return new Promise((resolveP, reject) => {
let worker: Worker;
try {
worker = new Worker(new URL("./meshImport.worker.ts", import.meta.url), { type: "module" });
} catch {
resolveP(null);
return;
}
worker.onmessage = (e: MessageEvent<MeshWorkerResponse>) => {
worker.terminate();
if (e.data?.type === "result") resolveP(e.data.flat);
else reject(new Error(e.data?.type === "error" ? e.data.message : "Unerwartete Worker-Antwort"));
};
worker.onerror = () => {
worker.terminate();
resolveP(null);
};
// Kopien übertragen: der Aufrufer behält seine Bytes.
const data = bytes.slice().buffer;
const files = o.files.map((f) => ({ name: f.name, data: f.bytes.slice().buffer }));
const req: MeshWorkerRequest = { type: "parse", data, name, unit: o.unit, up: o.up, maxTriangles: o.maxTriangles, files };
worker.postMessage(req, [data, ...files.map((f) => f.data)]);
});
}
/** Rohergebnis lesen (im Worker, sonst direkt). */
export async function readMeshFlat(bytes: Uint8Array, name: string, opts?: MeshReadOptions): Promise<MeshFlat> {
const o = resolve(opts);
return (await readInWorker(bytes, name, o)) ?? (await importMeshFlat(bytes, name, o));
}
/** Liest eine Mesh-Datei. Wirft mit der Meldung aus Rust bei unlesbaren Dateien. */
export async function readMesh(
bytes: Uint8Array,
name: string,
opts?: MeshReadOptions,
): Promise<{ objects: MeshObject[]; report: MeshImportReport }> {
return decodeMesh(await readMeshFlat(bytes, name, opts));
}
// ── Abbildung auf Kontext-Meshes ────────────────────────────────────────────
export interface MeshToContextOptions {
placement?: MeshPlacement;
/** LV95-Ursprung des Projekts (`projectGeoOrigin`), sonst null (nur bei "original"). */
geoOrigin?: { e: number; n: number } | null;
/** "object" = je Objekt, "merge" = je Gruppe + Farbe, "auto" (Standard) nach `MAX_SINGLE`. */
group?: "object" | "merge" | "auto";
}
/** Verschiebung (x, y, z) je nach Platzierung. */
export function meshShift(objects: readonly MeshObject[], opts: MeshToContextOptions = {}): [number, number, number] {
let minX = Infinity;
let maxX = -Infinity;
let minY = Infinity;
let maxY = -Infinity;
let minZ = Infinity;
for (const o of objects) {
const p = o.positions;
for (let i = 0; i + 2 < p.length; i += 3) {
if (p[i] < minX) minX = p[i];
if (p[i] > maxX) maxX = p[i];
if (p[i + 1] < minY) minY = p[i + 1];
if (p[i + 1] > maxY) maxY = p[i + 1];
if (p[i + 2] < minZ) minZ = p[i + 2];
}
}
if (!Number.isFinite(minX)) return [0, 0, 0];
const cx = (minX + maxX) / 2;
const cy = (minY + maxY) / 2;
if ((opts.placement ?? "center") === "center") return [-cx, -cy, -minZ];
const origin = opts.geoOrigin;
if (origin && Math.hypot(cx - origin.e, cy - origin.n) < Math.hypot(cx, cy)) return [-origin.e, -origin.n, 0];
return [0, 0, 0];
}
/** sRGB 0..1 → `#rrggbb` (Alpha entfällt). */
export function meshColorHex(c: readonly number[] | null | undefined): string | undefined {
if (!c || c.length < 3 || !c.slice(0, 3).every((v) => Number.isFinite(v))) return undefined;
return rgbToHex({ r: c[0] * 255, g: c[1] * 255, b: c[2] * 255 });
}
let counter = 0;
/** Objekte → Kontext-Meshes (Kategorie „Situation" wie IFC/STEP; `layer` = Gruppe, sonst Dateiname). */
export function meshObjectsToImportedMeshes(objects: readonly MeshObject[], fileName: string, opts: MeshToContextOptions = {}): ImportedMesh[] {
const base = fileName.replace(/\.[^.]+$/, "") || "Mesh";
const [dx, dy, dz] = meshShift(objects, opts);
const stamp = Date.now().toString(36);
const group = opts.group ?? "auto";
const merge = group === "merge" || (group === "auto" && objects.length > MAX_SINGLE);
const toArrays = (parts: readonly MeshObject[]): { positions: number[]; indices: number[] } => {
const positions: number[] = [];
const indices: number[] = [];
for (const p of parts) {
const off = positions.length / 3;
for (let i = 0; i + 2 < p.positions.length; i += 3) {
positions.push(p.positions[i] + dx, p.positions[i + 1] + dy, p.positions[i + 2] + dz);
}
for (let i = 0; i < p.indices.length; i++) indices.push(p.indices[i] + off);
}
return { positions, indices };
};
if (!merge) {
return objects.map((o, i) => {
const color = meshColorHex(o.color);
return {
id: `imported-mesh-${stamp}-${counter++}`,
type: "importedMesh" as const,
name: o.name || `${base} ${i + 1}`,
layer: o.group || base,
categoryCode: GENERIC_IMPORT_CATEGORY.code,
...(color ? { color } : {}),
...toArrays([o]),
};
});
}
const groups = new Map<string, MeshObject[]>();
for (const o of objects) {
const key = `${o.group}\u0000${meshColorHex(o.color) ?? ""}`;
const g = groups.get(key);
if (g) g.push(o);
else groups.set(key, [o]);
}
return [...groups.values()].map((parts) => {
const color = meshColorHex(parts[0].color);
const g = parts[0].group;
return {
id: `imported-mesh-${stamp}-${counter++}`,
type: "importedMesh" as const,
name: `${base}${g ? `: ${g}` : ""} (${parts.length})`,
layer: g || base,
categoryCode: GENERIC_IMPORT_CATEGORY.code,
...(color ? { color } : {}),
...toArrays(parts),
};
});
}
/** Datei-Bytes → Kontext-Meshes + Bericht. */
export async function meshBytesToImportedMeshes(
bytes: Uint8Array,
fileName: string,
read?: MeshReadOptions,
place?: MeshToContextOptions,
): Promise<{ meshes: ImportedMesh[]; report: MeshImportReport }> {
const { objects, report } = await readMesh(bytes, fileName, read);
return { meshes: meshObjectsToImportedMeshes(objects, fileName, place), report };
}
/** Bericht als kurzer Text; `tr` übersetzt (Kern kennt kein i18n, die Hülle reicht `t` herein). */
export function formatMeshReport(
r: MeshImportReport,
tr: (
key: "mesh.import.done" | "mesh.import.up" | "mesh.import.upUncertain" | "mesh.import.dropped" | "mesh.import.truncated",
vars?: Record<string, string | number>,
) => string,
): string {
const parts = [tr("mesh.import.done", { n: r.objects, tris: r.triangles, format: r.format.toUpperCase() })];
if (r.upAuto) parts.push(tr(r.upCertain ? "mesh.import.up" : "mesh.import.upUncertain", { axis: r.up.toUpperCase() }));
const dropped = r.degenerate + r.badFaces;
if (dropped) parts.push(tr("mesh.import.dropped", { n: dropped }));
if (r.truncated) parts.push(tr("mesh.import.truncated"));
return parts.join(" · ");
}
+15
View File
@@ -0,0 +1,15 @@
// Web-Worker für den Mesh-Import: liest die Datei mit dem Format-Modul (`engine/fileioWasm.ts`) AUSSERHALB
// des Haupt-Threads, damit grosse Modelle die UI nicht einfrieren. Ein Worker je Aufruf, danach beendet
// (s. `meshImport.ts::readInWorker`).
//
// → { type: "parse", data, name, unit, up, maxTriangles, files }
// ← { type: "result", flat: { flat, strings } } | { type: "error", message }
//
// Der Zahlenpuffer wird übertragen, nicht kopiert.
import { handleMeshWorkerRequest, type MeshWorkerRequest } from "./meshImport";
self.onmessage = async (e: MessageEvent<MeshWorkerRequest>) => {
const { res, transfer } = await handleMeshWorkerRequest(e.data);
(self as unknown as Worker).postMessage(res, transfer);
};
+6
View File
@@ -38,6 +38,8 @@ export interface NativeAppMenuHandlers {
onImportIfc: () => void;
/** Punktwolke importieren ([27]); optional für ältere Aufrufer. */
onImportPointCloud?: () => void;
/** 3D-Modell importieren (OBJ/STL/glTF/GLB/PLY). */
onImportMesh?: () => void;
onClashCheck: () => void;
onKennzahlen: () => void;
@@ -186,6 +188,10 @@ export function useNativeAppMenu(
text: t("menu.native.importPointCloud"),
action: () => handlersRef.current.onImportPointCloud?.(),
}),
await MenuItem.new({
text: t("menu.native.importMesh"),
action: () => handlersRef.current.onImportMesh?.(),
}),
await Submenu.new({
text: t("menu.native.export"),
items: [
+66
View File
@@ -0,0 +1,66 @@
// Import-Anfrage für 3D-Modelle (OBJ/STL/glTF/GLB/PLY): Menü, Drag & Drop → Dialog (`ui/MeshImportDialog.tsx`).
// Kleiner externer Store (Muster `pointCloudStore.ts`): UI-Zustand, kein Teil des Projekts. Die Anfrage
// besteht aus der Hauptdatei und den mitgegebenen Begleitdateien (`.mtl`, `.bin`).
import { useSyncExternalStore } from "react";
import { isMeshFile, isMeshSidecar } from "../io/meshImport";
export interface MeshImportRequest {
file: File;
sidecars: File[];
}
let pending: MeshImportRequest | null = null;
let fileInput: HTMLInputElement | null = null;
const listeners = new Set<() => void>();
function emit(): void {
for (const l of listeners) l();
}
/** Teilt eine Dateiliste in Hauptdatei (erste Mesh-Datei) und Begleitdateien; `null` ohne Mesh-Datei. */
export function splitMeshFiles(files: readonly File[]): MeshImportRequest | null {
const file = files.find((f) => isMeshFile(f.name));
if (!file) return null;
return { file, sidecars: files.filter((f) => f !== file && isMeshSidecar(f.name)) };
}
/** Öffnet den Import-Dialog. */
export function requestMeshImport(file: File, sidecars: File[] = []): void {
pending = { file, sidecars };
emit();
}
/** Schliesst den Import-Dialog. */
export function closeMeshImport(): void {
if (pending === null) return;
pending = null;
emit();
}
export function useMeshImportRequest(): MeshImportRequest | null {
return useSyncExternalStore(
(l) => {
listeners.add(l);
return () => listeners.delete(l);
},
() => pending,
() => pending,
);
}
/** Der Dialog-Host meldet sein verstecktes Datei-Feld an (oder ab mit `null`). */
export function registerMeshFileInput(el: HTMLInputElement | null): void {
fileInput = el;
}
/** Datei-Auswahl öffnen (Menü „3D-Modell importieren …"). Synchron im Klick, sonst blockt WebKit. */
export function openMeshFileDialog(): void {
fileInput?.click();
}
/** Nur für Tests: Zustand zurücksetzen. */
export function resetMeshImportStoreForTests(): void {
pending = null;
fileInput = null;
}
+5 -1
View File
@@ -122,6 +122,8 @@ export function useImageImportHandling(opts: {
export function useFileDropImport(
setDropActive: (active: boolean) => void,
openImportForFile: (file: File) => void,
/** Mehrere abgelegte Dateien (z. B. .gltf + .bin): `true`, wenn der Aufrufer sie übernommen hat. */
openMany?: (files: File[]) => boolean,
): {
onAppDragEnter: (e: DragEvent) => void;
onAppDragOver: (e: DragEvent) => void;
@@ -152,7 +154,9 @@ export function useFileDropImport(
e.preventDefault();
dragDepthRef.current = 0;
setDropActive(false);
const f = e.dataTransfer.files?.[0];
const all = Array.from(e.dataTransfer.files ?? []);
if (all.length > 1 && openMany?.(all)) return;
const f = all[0];
if (f) openImportForFile(f);
};
return { onAppDragEnter, onAppDragOver, onAppDragLeave, onAppDrop };
+3
View File
@@ -21,6 +21,7 @@ export interface AppMenuBarProps {
onImport: () => void;
/** Datei: Punktwolke importieren ([27]). */
onImportPointCloud?: () => void;
onImportMesh?: () => void;
/** Bearbeiten: Undo/Redo (Store) + Löschen der aktuellen Auswahl. */
onUndo: () => void;
@@ -56,6 +57,7 @@ export function AppMenuBar({
onSaveProject,
onImport,
onImportPointCloud,
onImportMesh,
onUndo,
onRedo,
canUndo,
@@ -83,6 +85,7 @@ export function AppMenuBar({
{ divider: true },
{ label: t("file.import"), onSelect: onImport },
...(onImportPointCloud ? [{ label: t("menu.native.importPointCloud"), onSelect: onImportPointCloud }] : []),
...(onImportMesh ? [{ label: t("menu.native.importMesh"), onSelect: onImportMesh }] : []),
];
const editItems: DropdownItem[] = [
+238
View File
@@ -0,0 +1,238 @@
// 3D-Modell-Import (OBJ/STL/glTF/GLB/PLY → Kontext-Meshes): verstecktes Datei-Feld + Dialog mit Einheit,
// Achse und Platzierung. Einmal in App eingehängt (`MeshImportHost`); geöffnet über Menü
// (`openMeshFileDialog`) oder Drag & Drop (`requestMeshImport`). Die Datei wird beim Öffnen und bei jeder
// Änderung von Einheit/Achse im Web-Worker gelesen (`readMesh`); der Dialog zeigt die erkannte Achse und die
// Ausdehnung, „Importieren" übernimmt das zuletzt gelesene Ergebnis (kein zweites Lesen).
//
// Muster: PointCloudImportDialog (abgedunkeltes Overlay, Esc/Hintergrund schliessen).
import { useEffect, useMemo, useRef, useState } from "react";
import { t } from "../i18n";
import { Dropdown } from "./Dropdown";
import {
MESH_EXTENSIONS,
MESH_SIDECAR_EXTENSIONS,
MESH_UNITS,
MISSING_EXTERNAL_PREFIX,
NO_FACES_PREFIX,
meshObjectsToImportedMeshes,
readMesh,
} from "../io/meshImport";
import type { MeshImportReport, MeshObject, MeshPlacement, MeshUnit, MeshUp } from "../io/meshImport";
import { closeMeshImport, registerMeshFileInput, requestMeshImport, splitMeshFiles, useMeshImportRequest } from "../state/meshImportStore";
import type { MeshImportRequest } from "../state/meshImportStore";
import { requestPointCloudImport } from "../state/pointCloudStore";
import { projectGeoOrigin } from "../core";
import type { ImportedMesh, Project } from "../model/types";
export interface MeshImportHostProps {
project: Project;
onImport: (meshes: ImportedMesh[], report: MeshImportReport) => void;
notify: (message: string, kind?: "info" | "warning" | "error") => void;
}
const fmt = (n: number) => (Math.abs(n) >= 100 ? n.toFixed(0) : n.toFixed(1));
/** Ausdehnung aller Objekte (Meter, Modell-Achsen). */
function extent(objects: readonly MeshObject[]): [number, number, number] {
const lo = [Infinity, Infinity, Infinity];
const hi = [-Infinity, -Infinity, -Infinity];
for (const o of objects) {
for (let i = 0; i + 2 < o.positions.length; i += 3) {
for (let a = 0; a < 3; a++) {
if (o.positions[i + a] < lo[a]) lo[a] = o.positions[i + a];
if (o.positions[i + a] > hi[a]) hi[a] = o.positions[i + a];
}
}
}
return [hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]];
}
/** Namen der fehlenden Begleitdateien aus der Rust-Meldung. */
function missingList(message: string): string {
const m = /fehlen: (.*?) \(mit der/.exec(message);
return m ? m[1] : message;
}
async function bytesOf(f: File): Promise<Uint8Array> {
return new Uint8Array(await f.arrayBuffer());
}
function MeshImportDialog({ req, project, onImport, notify }: { req: MeshImportRequest } & MeshImportHostProps) {
const { file, sidecars } = req;
const isGltf = /\.(gltf|glb)$/i.test(file.name);
const [unit, setUnit] = useState<MeshUnit>("m");
const [up, setUp] = useState<MeshUp>("auto");
const [placement, setPlacement] = useState<MeshPlacement>("center");
const [busy, setBusy] = useState(true);
const [error, setError] = useState<string | null>(null);
const [result, setResult] = useState<{ objects: MeshObject[]; report: MeshImportReport } | null>(null);
const seq = useRef(0);
// Dateiinhalt einmal laden, nicht bei jeder Änderung.
const cache = useRef<{ main: Uint8Array; files: { name: string; bytes: Uint8Array }[] } | null>(null);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") closeMeshImport();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, []);
useEffect(() => {
const id = ++seq.current;
setBusy(true);
setError(null);
void (async () => {
try {
cache.current ??= {
main: await bytesOf(file),
files: await Promise.all(sidecars.map(async (f) => ({ name: f.name, bytes: await bytesOf(f) }))),
};
const r = await readMesh(cache.current.main, file.name, { unit, up, files: cache.current.files });
if (id !== seq.current) return;
setResult(r);
} catch (e) {
if (id !== seq.current) return;
const msg = e instanceof Error ? e.message : String(e);
if (msg.startsWith(NO_FACES_PREFIX)) {
// PLY ohne Flächen = Punktwolke: Dialog wechseln.
closeMeshImport();
notify(t("mesh.import.noFaces"), "info");
requestPointCloudImport(file);
return;
}
setResult(null);
setError(
msg.startsWith(MISSING_EXTERNAL_PREFIX)
? t("mesh.import.missingExternal", { list: missingList(msg) })
: `${t("mesh.import.failed")}: ${msg}`,
);
} finally {
if (id === seq.current) setBusy(false);
}
})();
}, [file, sidecars, unit, up]);
const dims = useMemo(() => (result ? extent(result.objects) : null), [result]);
const r = result?.report;
const onDo = () => {
if (!result) return;
const meshes = meshObjectsToImportedMeshes(result.objects, file.name, { placement, geoOrigin: projectGeoOrigin(project) });
closeMeshImport();
onImport(meshes, result.report);
};
return (
<div className="imp-overlay" onClick={() => closeMeshImport()}>
<div className="imp-dialog" role="dialog" aria-modal="true" aria-label={t("mesh.import.title")} onClick={(e) => e.stopPropagation()}>
<header className="imp-head">
<span className="imp-head-title">{t("mesh.import.title")}</span>
<button className="imp-close" onClick={() => closeMeshImport()} aria-label={t("export.close")}>
×
</button>
</header>
<div className="imp-body">
<div className="imp-file">
<span className="imp-file-name" title={file.name}>
{file.name} · {(file.size / 1e6).toFixed(1)} MB
</span>
</div>
{sidecars.length > 0 && <div className="imp-note">{t("mesh.importDialog.files", { list: sidecars.map((f) => f.name).join(", ") })}</div>}
<section className="imp-section">
<div className="imp-section-title">{t("mesh.importDialog.unit")}</div>
<Dropdown
value={isGltf ? "m" : unit}
onChange={(v) => setUnit(v as MeshUnit)}
title={t("mesh.importDialog.unit")}
options={MESH_UNITS.map((u) => ({ value: u, label: t(`mesh.importDialog.unit.${u}`), disabled: isGltf && u !== "m" }))}
/>
{isGltf && <div className="imp-note">{t("mesh.importDialog.unitFixed")}</div>}
</section>
<section className="imp-section">
<div className="imp-section-title">{t("mesh.importDialog.up")}</div>
{(["auto", "z", "y"] as const).map((u) => (
<label key={u} className="imp-radio">
<input type="radio" name="mesh-up" disabled={isGltf} checked={(isGltf ? "y" : up) === u} onChange={() => setUp(u)} />
<span>{t(`mesh.importDialog.up.${u}`)}</span>
</label>
))}
{isGltf && <div className="imp-note">{t("mesh.importDialog.upFixed")}</div>}
</section>
<section className="imp-section">
<div className="imp-section-title">{t("mesh.importDialog.placement")}</div>
{(["center", "original"] as const).map((p) => (
<label key={p} className="imp-radio">
<input type="radio" name="mesh-placement" checked={placement === p} onChange={() => setPlacement(p)} />
<span>{t(`mesh.importDialog.placement.${p}`)}</span>
</label>
))}
</section>
{busy && <div className="imp-note">{t("mesh.importDialog.reading")}</div>}
{error && <div className="imp-warn">{error}</div>}
{r && dims && !busy && (
<section className="imp-section" data-testid="mesh-report">
<div className={r.upAuto && !r.upCertain ? "imp-warn" : "imp-note"}>
{r.upAuto && !r.upCertain
? t("mesh.importDialog.detectedUncertain", { axis: r.up.toUpperCase(), n: r.objects, tris: r.triangles })
: t("mesh.importDialog.detected", {
axis: r.up.toUpperCase(),
n: r.objects,
tris: r.triangles,
size: fmt(dims[0]),
depth: fmt(dims[1]),
height: fmt(dims[2]),
})}
</div>
{r.truncated && <div className="imp-warn">{t("mesh.import.truncated")}</div>}
{r.warnings.map((w) => (
<div key={w} className="imp-note">
{w}
</div>
))}
</section>
)}
</div>
<footer className="imp-foot">
<button className="imp-btn" onClick={() => closeMeshImport()}>
{t("export.cancel")}
</button>
<button className="imp-btn primary" onClick={onDo} disabled={!result || busy}>
{t("mesh.importDialog.import")}
</button>
</footer>
</div>
</div>
);
}
/** Verstecktes Datei-Feld (mehrere Dateien: Modell + `.mtl`/`.bin`) + Dialog; einmal in der App einhängen. */
export function MeshImportHost(props: MeshImportHostProps) {
const req = useMeshImportRequest();
return (
<>
<input
ref={registerMeshFileInput}
type="file"
multiple
accept={[...MESH_EXTENSIONS, ...MESH_SIDECAR_EXTENSIONS].map((e) => "." + e).join(",")}
style={{ display: "none" }}
data-testid="mesh-input"
onChange={(e) => {
const files = Array.from(e.target.files ?? []);
e.target.value = "";
const r = splitMeshFiles(files);
if (r) requestMeshImport(r.file, r.sidecars);
}}
/>
{req && <MeshImportDialog key={req.file.name + req.file.size + req.file.lastModified} req={req} {...props} />}
</>
);
}