diff --git a/NOTICE b/NOTICE index 889e92cf..87513e73 100644 --- a/NOTICE +++ b/NOTICE @@ -8,3 +8,6 @@ acadrust (https://github.com/hakanaktt/acadrust), MPL-2.0 i_overlay (https://github.com/iShape-Rust/iOverlay), MIT OR Apache-2.0 Abhängigkeit von src-tauri/core (Polygon-Booleans). + +earcutr (https://github.com/frewsxcv/earcutr), ISC License — Rust-Port von mapbox/earcut (ISC) + Abhängigkeit von src-tauri/fileio (IFC-Import: Dreieckszerlegung von Profilen und Flächen), unverändert. diff --git a/TODO.md b/TODO.md index a0492319..2d781de9 100644 --- a/TODO.md +++ b/TODO.md @@ -280,7 +280,7 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]). - ○ **[65] Explosionsaxonometrie.** · S–M - ○ **[66] Präsentationspläne mit einem Klick.** · M - ○ **[67] Skizzenstil.** · M -- ○ **[25] IFC-Import** → [B3]/[B4]. · L +- ◐ **[25] IFC-Import** → [B3] ✅ (Mesh), [B4] ○. · L - ◐ **[26] Dächer über beliebige Grundrisse.** `geometry/roofSkeleton.ts` (Walm/Sattel/Mansarde/ Krüppelwalm auf L/T/U, Kehlen, Giebel); Port nach Rust läuft [K2]. Offen: Innenhöfe, schiefwinklige Grundrisse → [B2]. · M @@ -307,7 +307,15 @@ Ganzes nicht WASM-tauglich (rayon, tempfile, SystemTime) — nur einzelne Module - ○ **[B2] Straight Skeleton** (für [26]), jetzt nach `dossier-core` statt `kernel2d`. `skeleton.rs` (709 Z., 8 Tests inkl. Fuzz): Innenhöfe, schiefwinklige Grundrisse, Giebel auf beliebiger Kante, Neigung je Kante, Arbeitsbudget. · S (Kernel) + M (Einbau) -- ○ **[B3] IFC-Import als Mesh** (erste Stufe von [25]). `step.rs` + Leseteil von `import.rs`. · M +- ✅ **[B3] IFC-Import als Mesh** (erste Stufe von [25]). (28.10.) Eigener Code in `src-tauri/fileio` + (`ifc_step.rs` STEP-Leser inkl. `\X2\`/`\X4\`, `ifc_import.rs` Geometrie), Fassade `io/ifcImport.ts`: + je IfcProduct ein Kontext-Mesh (Ebene = IFC-Klasse; > 2000 Bauteile je Klasse+Geschoss), Menü „IFC + importieren …", Import-Dialog und Drag & Drop (`.ifc`), CLI `import-ifc`. Extrusion (Arbitrary/ + Rechteck/Kreis/I/L/U/T, Löcher, Bögen), FacetedBrep, Tri-/PolygonalFaceSet, MappedItem, mm/Fuss, + IFC2x3/4/4.3. Rundreise und alle buildingSMART-Simple-Scene-Dateien gegen ifcopenshell gleich (Volumen je + Bauteil). Offen: Öffnungen abziehen und Boolesche Körper (nur 1. Operand) → [B4]; IfcAdvancedBrep, + Revolved/SweptDisk; Farbe/GlobalId gelesen, aber `ImportedMesh` hat kein Feld dafür (GlobalId steht im + Namen); Laden im Worker; nur Linux-Container/vitest, nicht in der Tauri-App geprüft. · M - ○ **[B4] IFC-Import zu echten Bauteilen** (zweite Stufe von [25]). · L · nach [B3]. - ◐ **[B5] IFC-Export nachziehen** (`exportIfc.ts`). Stand 27.10.: - ✅ Nicht-ASCII nach ISO 10303-21 (`\X2\`/`\X4\`). diff --git a/scripts/ifc-import-compare.py b/scripts/ifc-import-compare.py new file mode 100644 index 00000000..197ffcc1 --- /dev/null +++ b/scripts/ifc-import-compare.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +"""Gegencheck für den IFC-Import ([B3]): Dreiecke und Volumen je Bauteil aus ifcopenshell.geom. + +Aufruf: python3 scripts/ifc-import-compare.py datei.ifc +Ausgabe (stdout, JSON): {"": {"class": "IfcWall", "triangles": 12, "volume": 1.5}, …} +Volumen in m³ (Weltkoordinaten, Einheiten der Datei umgerechnet). Ausgelassen wie im Import: +IfcOpeningElement, IfcSpace, IfcAnnotation, IfcGrid, IfcVirtualElement, IfcSpatialZone und Bauteile ohne Körper. +Braucht `pip install ifcopenshell` (getestet mit 0.8/0.9). +""" + +import json +import sys + +import ifcopenshell +import ifcopenshell.geom +import ifcopenshell.util.shape + +SKIP = {"IfcOpeningElement", "IfcOpeningStandardCase", "IfcSpace", "IfcAnnotation", "IfcGrid", "IfcVirtualElement", "IfcSpatialZone"} + + +def main(path: str) -> int: + model = ifcopenshell.open(path) + settings = ifcopenshell.geom.settings() + settings.set("use-world-coords", True) + # Öffnungen nicht abziehen — der Mesh-Import [B3] tut es auch nicht. + settings.set("disable-opening-subtractions", True) + out = {} + for product in model.by_type("IfcProduct"): + if product.is_a() in SKIP or product.Representation is None: + continue + try: + shape = ifcopenshell.geom.create_shape(settings, product) + except Exception: # noqa: BLE001 — ohne Körper: auslassen + continue + geom = shape.geometry + out[product.GlobalId] = { + "class": product.is_a(), + "triangles": len(geom.faces) // 3, + "volume": ifcopenshell.util.shape.get_volume(geom), + } + json.dump(out, sys.stdout) + return 0 + + +if __name__ == "__main__": + if len(sys.argv) != 2: + print(__doc__) + sys.exit(2) + sys.exit(main(sys.argv[1])) diff --git a/src-tauri/fileio/Cargo.lock b/src-tauri/fileio/Cargo.lock index 0b11ded5..910ad88d 100644 --- a/src-tauri/fileio/Cargo.lock +++ b/src-tauri/fileio/Cargo.lock @@ -38,6 +38,12 @@ version = "1.0.103" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3" +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + [[package]] name = "bitflags" version = "2.13.0" @@ -112,12 +118,23 @@ version = "0.1.0" dependencies = [ "acadrust", "console_error_panic_hook", + "earcutr", "getrandom", "serde", "serde_json", "wasm-bindgen", ] +[[package]] +name = "earcutr" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afc28d89ac6cb489f679fcf51aaa62b4667bb0fb73a30f1d4d23949069707c07" +dependencies = [ + "itertools", + "num-traits", +] + [[package]] name = "either" version = "1.19.0" @@ -209,6 +226,15 @@ dependencies = [ "hashbrown", ] +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.18" @@ -273,6 +299,15 @@ dependencies = [ "minimal-lexical", ] +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + [[package]] name = "oem_cp" version = "2.1.2" diff --git a/src-tauri/fileio/Cargo.toml b/src-tauri/fileio/Cargo.toml index 2c509394..7ecf5bb9 100644 --- a/src-tauri/fileio/Cargo.toml +++ b/src-tauri/fileio/Cargo.toml @@ -40,3 +40,6 @@ serde_json = { version = "1", optional = true } # WASM-Bindings — nur im Feature "web" aktiv. wasm-bindgen = { version = "0.2", optional = true } console_error_panic_hook = { version = "0.1", optional = true } + +# IFC-Import ([B3]): Dreieckszerlegung von Profilen und Flächen mit Löchern (ISC, Port von mapbox/earcut). +earcutr = "0.5" diff --git a/src-tauri/fileio/src/ifc_import.rs b/src-tauri/fileio/src/ifc_import.rs new file mode 100644 index 00000000..0d7e2d88 --- /dev/null +++ b/src-tauri/fileio/src/ifc_import.rs @@ -0,0 +1,1987 @@ +// IFC-Import als Mesh ([B3], erste Stufe von [25]): liest aus einer IFC-Datei (IFC2x3, IFC4, IFC4.3) +// je Bauteil (IfcProduct mit Körper-Darstellung) GlobalId, Klasse, Name, Geschoss, Farbe und +// Dreiecke in Metern (Weltkoordinaten der Datei, Z = Höhe). Daraus werden auf der TS-Seite +// importierte Kontext-Meshes (`src/io/ifcImport.ts`); echte Bauteile kommen mit [B4]. +// +// Eigener Code (nichts aus BIMCraft `import.rs` übernommen; BIMCraft rechnet in mm, hier Meter). +// +// Unterstützt: +// - Platzierung: IfcLocalPlacement-Ketten mit IfcAxis2Placement3D/2D. +// - Körper: IfcExtrudedAreaSolid, IfcFacetedBrep(+WithVoids), IfcShellBasedSurfaceModel, +// IfcFaceBasedSurfaceModel, IfcTriangulatedFaceSet, IfcPolygonalFaceSet, IfcMappedItem +// (IfcCartesianTransformationOperator3D, auch ungleichmässig), IfcBlock, IfcCsgSolid, +// IfcBooleanResult/IfcBooleanClippingResult (UNION ganz; DIFFERENCE/INTERSECTION nur der erste +// Operand → als „vereinfacht" gezählt). +// - Profile: Arbitrary(+WithVoids), Rectangle(+Hollow, Rounded als Rechteck), Circle(+Hollow), +// I/L/U/T-Profil, Derived, Composite. Kurven: IfcPolyline, IfcIndexedPolyCurve (Linien + Bögen), +// IfcCompositeCurve, IfcTrimmedCurve auf Kreis/Ellipse/Linie, IfcCircle, IfcEllipse. +// - Einheiten: IfcSIUnit mit Präfix, IfcConversionBasedUnit (Fuss, Zoll, Grad). +// - Farbe: IfcStyledItem (IfcSurfaceStyleRendering/Shading) am Körper, sonst am Material. +// - Geschoss: IfcRelContainedInSpatialStructure, aufwärts über IfcRelAggregates. +// Übersprungen und gezählt: alles andere (z. B. IfcAdvancedBrep, IfcRevolvedAreaSolid, +// IfcSweptDiskSolid); IfcOpeningElement/IfcSpace/IfcAnnotation/IfcGrid als Bauteile; Öffnungen +// werden NICHT abgezogen (Boolesche Körper kommen mit [B4]). +// +// Grenzen: Dateigrösse/Instanzen (`ifc_step`), Dreiecke gesamt, Verschachtelung von Mapped Items und +// Platzierungen, Punkte je Fläche. Unsinn ergibt Fehler oder leere Bauteile, nie Panic. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use crate::ifc_step::{self, Entity, StepFile, Value}; + +/// Höchstzahl Dreiecke über alle Bauteile; darüber wird abgebrochen (`truncated`). +pub const MAX_TRIANGLES: usize = 15_000_000; +const MAX_MAP_DEPTH: usize = 8; +const MAX_PLACEMENT_DEPTH: usize = 64; +const MAX_CURVE_DEPTH: usize = 16; +const MAX_LOOP_POINTS: usize = 200_000; +/// Höchstzahl Auswertungen von Darstellungselementen über die ganze Datei. +const MAX_ITEM_EVALS: usize = 5_000_000; +/// Grösster zulässiger Koordinatenbetrag (m); weiter draussen gilt ein Wert als Unsinn. +const MAX_COORD: f64 = 1e8; +/// Sehnenfehler beim Zerlegen von Kreisen/Bögen (m). +const CHORD_TOL: f64 = 0.002; + +type V2 = [f64; 2]; +type V3 = [f64; 3]; + +// --------------------------------------------------------------------------- +// Vektoren und affine Abbildungen +// --------------------------------------------------------------------------- + +fn sub(a: V3, b: V3) -> V3 { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} +fn add(a: V3, b: V3) -> V3 { + [a[0] + b[0], a[1] + b[1], a[2] + b[2]] +} +fn scale(a: V3, s: f64) -> V3 { + [a[0] * s, a[1] * s, a[2] * s] +} +fn dot(a: V3, b: V3) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} +fn cross(a: V3, b: V3) -> V3 { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} +fn len(a: V3) -> f64 { + dot(a, a).sqrt() +} +fn norm(a: V3) -> Option { + let l = len(a); + (l > 1e-12 && l.is_finite()).then(|| scale(a, 1.0 / l)) +} + +/// Affine Abbildung p' = R·p + t (R zeilenweise). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Xf { + r: [[f64; 3]; 3], + t: V3, +} + +impl Xf { + pub const IDENTITY: Xf = Xf { r: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], t: [0.0; 3] }; + + /// Aus Achsen (Spalten) und Ursprung. + fn from_axes(x: V3, y: V3, z: V3, o: V3) -> Xf { + Xf { r: [[x[0], y[0], z[0]], [x[1], y[1], z[1]], [x[2], y[2], z[2]]], t: o } + } + pub fn apply(&self, p: V3) -> V3 { + let r = &self.r; + [ + r[0][0] * p[0] + r[0][1] * p[1] + r[0][2] * p[2] + self.t[0], + r[1][0] * p[0] + r[1][1] * p[1] + r[1][2] * p[2] + self.t[1], + r[2][0] * p[0] + r[2][1] * p[1] + r[2][2] * p[2] + self.t[2], + ] + } + /// self ∘ o (zuerst o, dann self). + fn then_after(&self, o: &Xf) -> Xf { + let mut r = [[0.0; 3]; 3]; + for (i, row) in r.iter_mut().enumerate() { + for (j, cell) in row.iter_mut().enumerate() { + *cell = (0..3).map(|k| self.r[i][k] * o.r[k][j]).sum(); + } + } + let t0 = Xf { r: self.r, t: [0.0; 3] }.apply(o.t); + Xf { r, t: add(t0, self.t) } + } + fn det(&self) -> f64 { + let r = &self.r; + r[0][0] * (r[1][1] * r[2][2] - r[1][2] * r[2][1]) - r[0][1] * (r[1][0] * r[2][2] - r[1][2] * r[2][0]) + + r[0][2] * (r[1][0] * r[2][1] - r[1][1] * r[2][0]) + } + fn is_finite(&self) -> bool { + self.r.iter().flatten().chain(self.t.iter()).all(|v| v.is_finite()) + } +} + +/// 2D-Abbildung p' = A·p + t (für Profil-Lagen). +#[derive(Clone, Copy, Debug)] +struct Xf2 { + a: [[f64; 2]; 2], + t: V2, +} + +impl Xf2 { + const IDENTITY: Xf2 = Xf2 { a: [[1.0, 0.0], [0.0, 1.0]], t: [0.0, 0.0] }; + fn apply(&self, p: V2) -> V2 { + [ + self.a[0][0] * p[0] + self.a[0][1] * p[1] + self.t[0], + self.a[1][0] * p[0] + self.a[1][1] * p[1] + self.t[1], + ] + } + fn det(&self) -> f64 { + self.a[0][0] * self.a[1][1] - self.a[0][1] * self.a[1][0] + } +} + +// --------------------------------------------------------------------------- +// Dreiecksnetz +// --------------------------------------------------------------------------- + +/// Dreiecksnetz: `positions` flach (x,y,z), `indices` je 3. +#[derive(Clone, Debug, Default)] +pub struct Mesh { + pub positions: Vec, + pub indices: Vec, +} + +impl Mesh { + fn vcount(&self) -> u32 { + (self.positions.len() / 3) as u32 + } + fn push_v(&mut self, p: V3) -> u32 { + let i = self.vcount(); + self.positions.extend_from_slice(&p); + i + } + fn tri(&mut self, a: u32, b: u32, c: u32) { + self.indices.extend_from_slice(&[a, b, c]); + } + pub fn triangle_count(&self) -> usize { + self.indices.len() / 3 + } + fn is_empty(&self) -> bool { + self.indices.is_empty() + } + /// Hängt `o` abgebildet mit `xf` an (Spiegelung → Wicklung umkehren). + fn append(&mut self, o: &Mesh, xf: &Xf) { + let base = self.vcount(); + for p in o.positions.chunks_exact(3) { + let q = xf.apply([p[0], p[1], p[2]]); + self.positions.extend_from_slice(&q); + } + let flip = xf.det() < 0.0; + for t in o.indices.chunks_exact(3) { + if flip { + self.tri(base + t[0], base + t[2], base + t[1]); + } else { + self.tri(base + t[0], base + t[1], base + t[2]); + } + } + } + fn flip_all(&mut self) { + for t in self.indices.chunks_exact_mut(3) { + t.swap(1, 2); + } + } +} + +/// Vorzeichenbehaftetes Volumen (Divergenzsatz); bei geschlossenen, aussen orientierten Netzen > 0. +pub fn signed_volume(positions: &[f64], indices: &[u32]) -> f64 { + let p = |i: u32| -> V3 { + let k = i as usize * 3; + match positions.get(k..k + 3) { + Some(s) => [s[0], s[1], s[2]], + None => [0.0; 3], + } + }; + indices.chunks_exact(3).map(|t| dot(p(t[0]), cross(p(t[1]), p(t[2]))) / 6.0).sum() +} + +// --------------------------------------------------------------------------- +// Dreieckszerlegung +// --------------------------------------------------------------------------- + +fn area2(r: &[V2]) -> f64 { + let n = r.len(); + (0..n).map(|i| { + let a = r[i]; + let b = r[(i + 1) % n]; + a[0] * b[1] - b[0] * a[1] + }).sum::() / 2.0 +} + +/// Ring säubern: nur endliche Punkte, keine doppelten Folgepunkte, Schlusspunkt ≠ Startpunkt. +fn clean_ring2(r: &[V2]) -> Vec { + let mut out: Vec = Vec::with_capacity(r.len()); + for &p in r { + if !(p[0].is_finite() && p[1].is_finite()) { + continue; + } + if out.last().is_some_and(|q| (q[0] - p[0]).abs() < 1e-9 && (q[1] - p[1]).abs() < 1e-9) { + continue; + } + out.push(p); + } + while out.len() > 1 { + let (f, l) = (out[0], out[out.len() - 1]); + if (f[0] - l[0]).abs() < 1e-9 && (f[1] - l[1]).abs() < 1e-9 { + out.pop(); + } else { + break; + } + } + out +} + +/// Polygon mit Löchern (Ring 0 = aussen) → Dreiecke als Indizes in die aneinandergehängten Ringe, +/// alle gegen den Uhrzeigersinn. +fn triangulate2d(rings: &[Vec]) -> Vec<[usize; 3]> { + let total: usize = rings.iter().map(|r| r.len()).sum(); + if rings.is_empty() || rings[0].len() < 3 || total > MAX_LOOP_POINTS { + return Vec::new(); + } + let mut flat = Vec::with_capacity(total * 2); + let mut holes = Vec::new(); + let mut pts: Vec = Vec::with_capacity(total); + for (k, r) in rings.iter().enumerate() { + if k > 0 { + holes.push(pts.len()); + } + for p in r { + flat.push(p[0]); + flat.push(p[1]); + pts.push(*p); + } + } + let idx = if rings.len() == 1 && pts.len() == 3 { + vec![0, 1, 2] + } else { + match earcutr::earcut(&flat, &holes, 2) { + Ok(v) => v, + Err(_) => return Vec::new(), + } + }; + let mut out = Vec::with_capacity(idx.len() / 3); + for t in idx.chunks_exact(3) { + let (a, b, c) = (t[0], t[1], t[2]); + if a >= pts.len() || b >= pts.len() || c >= pts.len() { + continue; + } + let (pa, pb, pc) = (pts[a], pts[b], pts[c]); + let cr = (pb[0] - pa[0]) * (pc[1] - pa[1]) - (pb[1] - pa[1]) * (pc[0] - pa[0]); + if cr > 0.0 { + out.push([a, b, c]); + } else if cr < 0.0 { + out.push([a, c, b]); + } + } + out +} + +/// Ebenes 3D-Polygon mit Löchern → Dreiecke, orientiert nach der Newell-Normale des Aussenrings. +fn triangulate3d(rings: &[Vec], out: &mut Mesh) { + let Some(outer) = rings.first() else { return }; + if outer.len() < 3 { + return; + } + if rings.len() == 1 && outer.len() == 3 { + let a = out.push_v(outer[0]); + let b = out.push_v(outer[1]); + let c = out.push_v(outer[2]); + out.tri(a, b, c); + return; + } + let mut n = [0.0; 3]; + for i in 0..outer.len() { + let a = outer[i]; + let b = outer[(i + 1) % outer.len()]; + n[0] += (a[1] - b[1]) * (a[2] + b[2]); + n[1] += (a[2] - b[2]) * (a[0] + b[0]); + n[2] += (a[0] - b[0]) * (a[1] + b[1]); + } + let Some(n) = norm(n) else { return }; + let helper = if n[0].abs() < 0.9 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] }; + let Some(u) = norm(cross(helper, n)) else { return }; + let v = cross(n, u); + let o = outer[0]; + let rings2: Vec> = rings + .iter() + .map(|r| r.iter().map(|p| { + let d = sub(*p, o); + [dot(d, u), dot(d, v)] + }).collect()) + .collect(); + let tris = triangulate2d(&rings2); + if tris.is_empty() { + return; + } + let base = out.vcount(); + for r in rings { + for p in r { + out.push_v(*p); + } + } + for t in tris { + out.tri(base + t[0] as u32, base + t[1] as u32, base + t[2] as u32); + } +} + +/// Extrudiert ein Profil (Ring 0 aussen, weitere Löcher, in der XY-Ebene) entlang `h`. +fn extrude(rings: &[Vec], h: V3) -> Mesh { + let mut mesh = Mesh::default(); + if h[2].abs() < 1e-9 || !h.iter().all(|v| v.is_finite()) { + return mesh; + } + let mut rings: Vec> = rings.iter().map(|r| clean_ring2(r)).filter(|r| r.len() >= 3).collect(); + if rings.is_empty() { + return mesh; + } + // Aussen gegen, Löcher im Uhrzeigersinn. + for (k, r) in rings.iter_mut().enumerate() { + let a = area2(r); + if (k == 0 && a < 0.0) || (k > 0 && a > 0.0) { + r.reverse(); + } + } + let tris = triangulate2d(&rings); + if tris.is_empty() { + return mesh; + } + let flat: Vec = rings.iter().flatten().copied().collect(); + // Boden (Normale −h) und Deckel (+h). + let b0 = mesh.vcount(); + for p in &flat { + mesh.push_v([p[0], p[1], 0.0]); + } + let t0 = mesh.vcount(); + for p in &flat { + mesh.push_v([p[0] + h[0], p[1] + h[1], h[2]]); + } + for t in &tris { + mesh.tri(b0 + t[0] as u32, b0 + t[2] as u32, b0 + t[1] as u32); + mesh.tri(t0 + t[0] as u32, t0 + t[1] as u32, t0 + t[2] as u32); + } + // Mantel: je Kante ein Viereck mit eigenen Ecken (scharfe Kanten für die Schattierung). + for r in &rings { + for i in 0..r.len() { + let a = r[i]; + let b = r[(i + 1) % r.len()]; + let a0 = mesh.push_v([a[0], a[1], 0.0]); + let b0 = mesh.push_v([b[0], b[1], 0.0]); + let b1 = mesh.push_v([b[0] + h[0], b[1] + h[1], h[2]]); + let a1 = mesh.push_v([a[0] + h[0], a[1] + h[1], h[2]]); + mesh.tri(a0, b0, b1); + mesh.tri(a0, b1, a1); + } + } + if h[2] < 0.0 { + mesh.flip_all(); + } + mesh +} + +/// Anzahl Segmente für einen Bogen mit Öffnungswinkel `span` und Radius `r`. +fn arc_segments(span: f64, r: f64) -> usize { + let span = span.abs(); + if !(span.is_finite() && r.is_finite()) || r <= 0.0 { + return 1; + } + let step = if r <= CHORD_TOL { std::f64::consts::FRAC_PI_4 } else { 2.0 * (1.0 - CHORD_TOL / r).acos() }; + let step = step.clamp(std::f64::consts::PI / 64.0, std::f64::consts::FRAC_PI_4); + ((span / step).ceil() as usize).clamp(1, 256) +} + +// --------------------------------------------------------------------------- +// Ergebnis +// --------------------------------------------------------------------------- + +/// Ein importiertes Bauteil. +#[derive(Clone, Debug, Default)] +pub struct IfcProductMesh { + pub global_id: String, + /// IFC-Klasse in Schreibweise des Schemas (`IfcWall`), unbekannte gross (`IFCFOO`). + pub class: String, + pub name: Option, + pub storey: Option, + /// RGBA 0..1. + pub color: Option<[f64; 4]>, + pub mesh: Mesh, +} + +/// Ergebnis eines IFC-Imports mit Bericht. +#[derive(Clone, Debug, Default)] +pub struct IfcImport { + pub schema: String, + /// Meter je Längeneinheit der Datei. + pub length_scale: f64, + pub products: Vec, + /// Übersprungene Geometrie-Elemente je IFC-Typ (gross geschrieben). + pub skipped_items: BTreeMap, + /// Bewusst ausgelassene Bauteile je Klasse (Öffnungen, Räume, …). + pub skipped_products: BTreeMap, + /// Bauteile mit Darstellung, aus der keine Dreiecke wurden. + pub products_without_geometry: usize, + /// Boolesche Körper, von denen nur der erste Operand übernommen wurde. + pub simplified_booleans: usize, + /// IfcRelVoidsElement — Öffnungen, die nicht abgezogen wurden. + pub voids_ignored: usize, + /// Unlesbare STEP-Anweisungen. + pub parse_errors: usize, + /// Abbruch wegen Dreiecks-Obergrenze. + pub truncated: bool, +} + +/// Bauteilklassen, die als Mesh keinen Sinn ergeben (Volumen-Hilfskörper, Beschriftung). +const SKIP_CLASSES: &[&str] = &[ + "IFCOPENINGELEMENT", + "IFCOPENINGSTANDARDCASE", + "IFCSPACE", + "IFCANNOTATION", + "IFCGRID", + "IFCVIRTUALELEMENT", + "IFCSPATIALZONE", +]; + +/// Darstellungen, die keinen Körper zeigen. +const NON_BODY_REPS: &[&str] = &[ + "AXIS", "FOOTPRINT", "BOX", "ANNOTATION", "PROFILE", "CLEARANCE", "COG", "REFERENCE", "LIGHTING", "SURVEYPOINTS", +]; + +// --------------------------------------------------------------------------- +// Leser +// --------------------------------------------------------------------------- + +struct Reader<'a> { + f: &'a StepFile, + len_scale: f64, + angle_scale: f64, + placements: HashMap, + item_colors: HashMap, + skipped: BTreeMap, + simplified: usize, + /// Elemente, die gerade ausgewertet werden (Zyklen in Booleschen/Mapped-Ketten). + active: HashSet, + /// Restbudget an Element-Auswertungen (schützt vor exponentiellen DAGs). + budget: usize, +} + +impl<'a> Reader<'a> { + fn ent(&self, id: u64) -> Option<&'a Entity> { + self.f.get(id) + } + fn ent_v(&self, v: Option<&Value>) -> Option<(u64, &'a Entity)> { + let id = v?.as_ref_id()?; + Some((id, self.ent(id)?)) + } + fn skip(&mut self, ty: &str) { + *self.skipped.entry(if ty.is_empty() { "(komplex)".to_string() } else { ty.to_string() }).or_insert(0) += 1; + } + + /// Punkt in Metern (2D-Punkte bekommen z = 0). + fn point(&self, v: Option<&Value>) -> Option { + let (_, e) = self.ent_v(v)?; + if e.ty != "IFCCARTESIANPOINT" { + return None; + } + let c = e.arg(0)?.as_list()?; + let x = c.first()?.as_f64()?; + let y = c.get(1).and_then(|v| v.as_f64()).unwrap_or(0.0); + let z = c.get(2).and_then(|v| v.as_f64()).unwrap_or(0.0); + let p = scale([x, y, z], self.len_scale); + p.iter().all(|v| v.abs() < MAX_COORD).then_some(p) + } + /// Richtung (ohne Einheit), nicht normiert. + fn direction(&self, v: Option<&Value>) -> Option { + let (_, e) = self.ent_v(v)?; + if e.ty != "IFCDIRECTION" { + return None; + } + let c = e.arg(0)?.as_list()?; + let x = c.first()?.as_f64()?; + let y = c.get(1).and_then(|v| v.as_f64()).unwrap_or(0.0); + let z = c.get(2).and_then(|v| v.as_f64()).unwrap_or(0.0); + Some([x, y, z]) + } + fn length(&self, v: Option<&Value>) -> Option { + v?.as_f64().map(|x| x * self.len_scale).filter(|x| x.abs() < MAX_COORD) + } + + /// IfcAxis2Placement3D/2D → Abbildung (fehlend = Identität). + fn axis_placement(&self, v: Option<&Value>) -> Xf { + let Some((_, e)) = self.ent_v(v) else { return Xf::IDENTITY }; + match e.ty.as_str() { + "IFCAXIS2PLACEMENT3D" => { + let o = self.point(e.arg(0)).unwrap_or([0.0; 3]); + let z = self.direction(e.arg(1)).and_then(norm).unwrap_or([0.0, 0.0, 1.0]); + let xr = self.direction(e.arg(2)).unwrap_or([1.0, 0.0, 0.0]); + // X senkrecht zu Z (Gram-Schmidt); bei paralleler Vorgabe eine Ersatzachse. + let x = norm(sub(xr, scale(z, dot(xr, z)))) + .or_else(|| { + let alt = if z[0].abs() < 0.9 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] }; + norm(sub(alt, scale(z, dot(alt, z)))) + }) + .unwrap_or([1.0, 0.0, 0.0]); + let y = cross(z, x); + Xf::from_axes(x, y, z, o) + } + "IFCAXIS2PLACEMENT2D" => { + let x2 = self.axis2d(e); + Xf::from_axes([x2.a[0][0], x2.a[1][0], 0.0], [x2.a[0][1], x2.a[1][1], 0.0], [0.0, 0.0, 1.0], [x2.t[0], x2.t[1], 0.0]) + } + _ => Xf::IDENTITY, + } + } + + fn axis2d(&self, e: &Entity) -> Xf2 { + let o = self.point(e.arg(0)).unwrap_or([0.0; 3]); + let d = self.direction(e.arg(1)).unwrap_or([1.0, 0.0, 0.0]); + let l = (d[0] * d[0] + d[1] * d[1]).sqrt(); + let (cx, sx) = if l > 1e-12 && l.is_finite() { (d[0] / l, d[1] / l) } else { (1.0, 0.0) }; + Xf2 { a: [[cx, -sx], [sx, cx]], t: [o[0], o[1]] } + } + fn placement2d(&self, v: Option<&Value>) -> Xf2 { + match self.ent_v(v) { + Some((_, e)) if e.ty == "IFCAXIS2PLACEMENT2D" => self.axis2d(e), + _ => Xf2::IDENTITY, + } + } + + /// Objekt-Platzierung in Weltkoordinaten (IfcLocalPlacement-Kette, zwischengespeichert). + fn object_placement(&mut self, id: u64, depth: usize) -> Xf { + if let Some(x) = self.placements.get(&id) { + return *x; + } + let Some(e) = self.ent(id) else { return Xf::IDENTITY }; + let xf = if e.ty == "IFCLOCALPLACEMENT" && depth < MAX_PLACEMENT_DEPTH { + let local = self.axis_placement(e.arg(1)); + match e.arg(0).and_then(|v| v.as_ref_id()) { + Some(parent) if parent != id => self.object_placement(parent, depth + 1).then_after(&local), + _ => local, + } + } else { + if e.ty != "IFCLOCALPLACEMENT" { + let ty = e.ty.clone(); + self.skip(&ty); + } + Xf::IDENTITY + }; + let xf = if xf.is_finite() { xf } else { Xf::IDENTITY }; + self.placements.insert(id, xf); + xf + } + + /// IfcCartesianTransformationOperator3D(+NonUniform) → Abbildung. + fn transform_operator(&self, v: Option<&Value>) -> Xf { + let Some((_, e)) = self.ent_v(v) else { return Xf::IDENTITY }; + match e.ty.as_str() { + "IFCCARTESIANTRANSFORMATIONOPERATOR3D" | "IFCCARTESIANTRANSFORMATIONOPERATOR3DNONUNIFORM" => { + let a1 = self.direction(e.arg(0)); + let a2 = self.direction(e.arg(1)); + let o = self.point(e.arg(2)).unwrap_or([0.0; 3]); + let s = e.arg(3).and_then(|v| v.as_f64()).unwrap_or(1.0); + let a3 = self.direction(e.arg(4)); + let (s2, s3) = if e.ty.ends_with("NONUNIFORM") { + (e.arg(5).and_then(|v| v.as_f64()).unwrap_or(s), e.arg(6).and_then(|v| v.as_f64()).unwrap_or(s)) + } else { + (s, s) + }; + // IfcBaseAxis: U3 = Axis3, U1 = Axis1 ⟂ U3, U2 = Axis2 ⟂ U1,U3 (Richtung behält Spiegelung). + let u3 = a3.and_then(norm).unwrap_or([0.0, 0.0, 1.0]); + let u1 = a1 + .and_then(|a| norm(sub(a, scale(u3, dot(a, u3))))) + .or_else(|| { + let alt = if u3[0].abs() < 0.9 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] }; + norm(sub(alt, scale(u3, dot(alt, u3)))) + }) + .unwrap_or([1.0, 0.0, 0.0]); + let def2 = cross(u3, u1); + let u2 = a2 + .and_then(|a| norm(sub(sub(a, scale(u3, dot(a, u3))), scale(u1, dot(a, u1))))) + .unwrap_or(def2); + Xf::from_axes(scale(u1, s), scale(u2, s2), scale(u3, s3), o) + } + _ => Xf::IDENTITY, + } + } + + /// 2D-Transformationsoperator (für IfcDerivedProfileDef). + fn transform_operator2d(&self, v: Option<&Value>) -> Xf2 { + let Some((_, e)) = self.ent_v(v) else { return Xf2::IDENTITY }; + if !e.ty.starts_with("IFCCARTESIANTRANSFORMATIONOPERATOR2D") { + return Xf2::IDENTITY; + } + let a1 = self.direction(e.arg(0)).unwrap_or([1.0, 0.0, 0.0]); + let o = self.point(e.arg(2)).unwrap_or([0.0; 3]); + let s = e.arg(3).and_then(|v| v.as_f64()).unwrap_or(1.0); + let s2 = if e.ty.ends_with("NONUNIFORM") { e.arg(4).and_then(|v| v.as_f64()).unwrap_or(s) } else { s }; + let l = (a1[0] * a1[0] + a1[1] * a1[1]).sqrt(); + let (c, sn) = if l > 1e-12 && l.is_finite() { (a1[0] / l, a1[1] / l) } else { (1.0, 0.0) }; + let mut u2 = [-sn, c]; + if let Some(a2) = self.direction(e.arg(1)) { + if a2[0] * u2[0] + a2[1] * u2[1] < 0.0 { + u2 = [sn, -c]; + } + } + Xf2 { a: [[c * s, u2[0] * s2], [sn * s, u2[1] * s2]], t: [o[0], o[1]] } + } + + // ---- Kurven (2D, für Profile) ---------------------------------------------------------- + + fn points2d(&self, list: &[Value]) -> Vec { + list.iter().filter_map(|v| self.point(Some(v)).map(|p| [p[0], p[1]])).take(MAX_LOOP_POINTS).collect() + } + + /// Kurve → Punktfolge (offen; Schlusspunkt kann dem Start entsprechen). + fn curve2d(&mut self, v: Option<&Value>, depth: usize) -> Option> { + let (_, e) = self.ent_v(v)?; + if depth > MAX_CURVE_DEPTH { + return None; + } + match e.ty.as_str() { + "IFCPOLYLINE" => Some(self.points2d(e.arg(0)?.as_list()?)), + "IFCINDEXEDPOLYCURVE" => self.indexed_poly_curve(e), + "IFCCOMPOSITECURVE" => { + let mut out: Vec = Vec::new(); + for seg in e.arg(0)?.as_list()? { + let (_, s) = self.ent_v(Some(seg))?; + if !s.ty.ends_with("COMPOSITECURVESEGMENT") { + self.skip(&s.ty.clone()); + return None; + } + let same = s.arg(1).and_then(|v| v.as_enum()) != Some("F"); + let mut pts = self.curve2d(s.arg(2), depth + 1)?; + if !same { + pts.reverse(); + } + if let (Some(l), Some(f)) = (out.last(), pts.first()) { + if (l[0] - f[0]).abs() < 1e-9 && (l[1] - f[1]).abs() < 1e-9 { + pts.remove(0); + } + } + out.extend(pts); + if out.len() > MAX_LOOP_POINTS { + return None; + } + } + Some(out) + } + "IFCTRIMMEDCURVE" => self.trimmed_curve(e, depth), + "IFCCIRCLE" | "IFCELLIPSE" => { + let (pl, rx, ry) = self.conic(e)?; + let n = arc_segments(std::f64::consts::TAU, rx.max(ry)).max(12); + Some((0..n).map(|i| { + let t = std::f64::consts::TAU * i as f64 / n as f64; + pl.apply([rx * t.cos(), ry * t.sin()]) + }).collect()) + } + other => { + let other = other.to_string(); + self.skip(&other); + None + } + } + } + + /// Kreis/Ellipse → (Lage, Halbachse x, Halbachse y). + fn conic(&self, e: &Entity) -> Option<(Xf2, f64, f64)> { + let pl = match self.ent_v(e.arg(0)) { + Some((_, p)) if p.ty == "IFCAXIS2PLACEMENT2D" => self.axis2d(p), + Some((_, p)) if p.ty == "IFCAXIS2PLACEMENT3D" => { + // Kreis in der Profil-Ebene: nur XY der 3D-Lage verwenden. + let x = self.axis_placement(e.arg(0)); + Xf2 { a: [[x.r[0][0], x.r[0][1]], [x.r[1][0], x.r[1][1]]], t: [x.t[0], x.t[1]] } + } + _ => Xf2::IDENTITY, + }; + let rx = self.length(e.arg(1))?; + let ry = if e.ty == "IFCELLIPSE" { self.length(e.arg(2))? } else { rx }; + (rx > 0.0 && ry > 0.0).then_some((pl, rx, ry)) + } + + fn indexed_poly_curve(&self, e: &Entity) -> Option> { + let (_, pl) = self.ent_v(e.arg(0))?; + if pl.ty != "IFCCARTESIANPOINTLIST2D" && pl.ty != "IFCCARTESIANPOINTLIST3D" { + return None; + } + let coords: Vec = pl + .arg(0)? + .as_list()? + .iter() + .take(MAX_LOOP_POINTS) + .map(|c| { + let c = c.as_list().unwrap_or(&[]); + let x = c.first().and_then(|v| v.as_f64()).unwrap_or(f64::NAN); + let y = c.get(1).and_then(|v| v.as_f64()).unwrap_or(f64::NAN); + let p = [x * self.len_scale, y * self.len_scale]; + if p[0].abs() < MAX_COORD && p[1].abs() < MAX_COORD { p } else { [f64::NAN; 2] } + }) + .collect(); + let at = |i: &Value| -> Option { + let k = i.as_i64()?; + (k >= 1).then(|| coords.get(k as usize - 1).copied()).flatten() + }; + let segs = match e.arg(1) { + Some(Value::List(s)) => s, + _ => return Some(coords.clone()), + }; + let mut out: Vec = Vec::new(); + let push = |out: &mut Vec, p: V2| { + if !out.last().is_some_and(|q| (q[0] - p[0]).abs() < 1e-12 && (q[1] - p[1]).abs() < 1e-12) { + out.push(p); + } + }; + for s in segs { + let Value::Typed(name, a) = s else { return None }; + let idx = a.first()?.as_list()?; + match name.as_str() { + "IFCLINEINDEX" => { + for i in idx { + push(&mut out, at(i)?); + } + } + "IFCARCINDEX" if idx.len() == 3 => { + let (p1, p2, p3) = (at(&idx[0])?, at(&idx[1])?, at(&idx[2])?); + for p in arc3(p1, p2, p3) { + push(&mut out, p); + } + } + _ => return None, + } + if out.len() > MAX_LOOP_POINTS { + return None; + } + } + Some(out) + } + + fn trimmed_curve(&mut self, e: &Entity, depth: usize) -> Option> { + let (_, basis) = self.ent_v(e.arg(0))?; + let sense = e.arg(3).and_then(|v| v.as_enum()) != Some("F"); + let master_param = e.arg(4).and_then(|v| v.as_enum()) == Some("PARAMETER"); + let trim = |r: &Self, v: Option<&Value>| -> (Option, Option) { + let mut par = None; + let mut pt = None; + for t in v.and_then(|v| v.as_list()).unwrap_or(&[]) { + match t { + Value::Typed(n, a) if n == "IFCPARAMETERVALUE" => par = a.first().and_then(|x| x.as_f64()), + Value::Ref(_) => pt = r.point(Some(t)).map(|p| [p[0], p[1]]), + _ => {} + } + } + (par, pt) + }; + let (p1, c1) = trim(self, e.arg(1)); + let (p2, c2) = trim(self, e.arg(2)); + match basis.ty.as_str() { + "IFCCIRCLE" | "IFCELLIPSE" => { + let (pl, rx, ry) = self.conic(basis)?; + // Winkel: aus Punkt (in Lage-Koordinaten) oder Parameter (Winkeleinheit der Datei). + let det = pl.det(); + let ang = |par: Option, pt: Option| -> Option { + let from_pt = pt.and_then(|p| { + let d = [p[0] - pl.t[0], p[1] - pl.t[1]]; + if det.abs() < 1e-12 { + return None; + } + // Inverse der orthonormalen Lage. + let lx = (pl.a[1][1] * d[0] - pl.a[0][1] * d[1]) / det; + let ly = (-pl.a[1][0] * d[0] + pl.a[0][0] * d[1]) / det; + Some((ly / ry).atan2(lx / rx)) + }); + let from_par = par.map(|t| t * self.angle_scale); + if master_param { from_par.or(from_pt) } else { from_pt.or(from_par) } + }; + let a1 = ang(p1, c1)?; + let a2 = ang(p2, c2)?; + let tau = std::f64::consts::TAU; + let span = if sense { (a2 - a1).rem_euclid(tau) } else { -((a1 - a2).rem_euclid(tau)) }; + let span = if span.abs() < 1e-12 { if sense { tau } else { -tau } } else { span }; + let n = arc_segments(span, rx.max(ry)); + Some((0..=n).map(|i| { + let t = a1 + span * i as f64 / n as f64; + pl.apply([rx * t.cos(), ry * t.sin()]) + }).collect()) + } + "IFCLINE" => { + let pnt = self.point(basis.arg(0))?; + let (_, vec) = self.ent_v(basis.arg(1))?; + let d = self.direction(vec.arg(0))?; + let m = self.length(vec.arg(1)).unwrap_or(1.0); + let dl = len(d); + if dl < 1e-12 { + return None; + } + let at = |t: f64| [pnt[0] + d[0] / dl * m * t, pnt[1] + d[1] / dl * m * t]; + let a = if master_param { p1.map(at).or(c1) } else { c1.or(p1.map(at)) }?; + let b = if master_param { p2.map(at).or(c2) } else { c2.or(p2.map(at)) }?; + Some(if sense { vec![a, b] } else { vec![b, a] }) + } + _ => { + // Andere Basiskurven: Polyline o. ä. ungetrimmt übernehmen. + let _ = depth; + let ty = basis.ty.clone(); + self.skip(&ty); + None + } + } + } + + // ---- Profile --------------------------------------------------------------------------- + + /// Profil → Flächen (je Fläche Ring 0 aussen, weitere Löcher) in Profil-Koordinaten. + fn profile(&mut self, v: Option<&Value>, depth: usize) -> Option>>> { + let (_, e) = self.ent_v(v)?; + if depth > MAX_CURVE_DEPTH { + return None; + } + let ty = e.ty.as_str(); + let placed = |pl: Xf2, rings: Vec>| -> Vec>> { + vec![rings.into_iter().map(|r| r.into_iter().map(|p| pl.apply(p)).collect()).collect()] + }; + let rect = |w: f64, h: f64| -> Vec { vec![[-w / 2.0, -h / 2.0], [w / 2.0, -h / 2.0], [w / 2.0, h / 2.0], [-w / 2.0, h / 2.0]] }; + let circle = |r: f64| -> Vec { + let n = arc_segments(std::f64::consts::TAU, r).max(12); + (0..n).map(|i| { + let t = std::f64::consts::TAU * i as f64 / n as f64; + [r * t.cos(), r * t.sin()] + }).collect() + }; + match ty { + "IFCARBITRARYCLOSEDPROFILEDEF" => { + let outer = self.curve2d(e.arg(2), depth + 1)?; + Some(vec![vec![outer]]) + } + "IFCARBITRARYPROFILEDEFWITHVOIDS" => { + let outer = self.curve2d(e.arg(2), depth + 1)?; + let mut rings = vec![outer]; + for c in e.arg(3).and_then(|v| v.as_list()).unwrap_or(&[]) { + if let Some(r) = self.curve2d(Some(c), depth + 1) { + rings.push(r); + } + } + Some(vec![rings]) + } + "IFCRECTANGLEPROFILEDEF" | "IFCROUNDEDRECTANGLEPROFILEDEF" => { + let pl = self.placement2d(e.arg(2)); + let (w, h) = (self.length(e.arg(3))?, self.length(e.arg(4))?); + (w > 0.0 && h > 0.0).then(|| placed(pl, vec![rect(w, h)])) + } + "IFCRECTANGLEHOLLOWPROFILEDEF" => { + let pl = self.placement2d(e.arg(2)); + let (w, h, t) = (self.length(e.arg(3))?, self.length(e.arg(4))?, self.length(e.arg(5))?); + let mut rings = vec![rect(w, h)]; + if t > 0.0 && 2.0 * t < w && 2.0 * t < h { + let mut inner = rect(w - 2.0 * t, h - 2.0 * t); + inner.reverse(); + rings.push(inner); + } + (w > 0.0 && h > 0.0).then(|| placed(pl, rings)) + } + "IFCCIRCLEPROFILEDEF" => { + let pl = self.placement2d(e.arg(2)); + let r = self.length(e.arg(3))?; + (r > 0.0).then(|| placed(pl, vec![circle(r)])) + } + "IFCCIRCLEHOLLOWPROFILEDEF" => { + let pl = self.placement2d(e.arg(2)); + let (r, t) = (self.length(e.arg(3))?, self.length(e.arg(4))?); + let mut rings = vec![circle(r)]; + if t > 0.0 && t < r { + let mut inner = circle(r - t); + inner.reverse(); + rings.push(inner); + } + (r > 0.0).then(|| placed(pl, rings)) + } + "IFCISHAPEPROFILEDEF" => { + let pl = self.placement2d(e.arg(2)); + let (w, d, tw, tf) = (self.length(e.arg(3))?, self.length(e.arg(4))?, self.length(e.arg(5))?, self.length(e.arg(6))?); + let (x, y, a, b) = (w / 2.0, d / 2.0, tw / 2.0, d / 2.0 - tf); + let ring = vec![ + [-x, -y], [x, -y], [x, -b], [a, -b], [a, b], [x, b], [x, y], [-x, y], [-x, b], [-a, b], [-a, -b], [-x, -b], + ]; + (w > 0.0 && d > 0.0 && tw > 0.0 && tf > 0.0).then(|| placed(pl, vec![ring])) + } + "IFCLSHAPEPROFILEDEF" => { + let pl = self.placement2d(e.arg(2)); + let d = self.length(e.arg(3))?; + let w = self.length(e.arg(4)).unwrap_or(d); + let t = self.length(e.arg(5))?; + let (x, y) = (w / 2.0, d / 2.0); + let ring = vec![[-x, -y], [x, -y], [x, -y + t], [-x + t, -y + t], [-x + t, y], [-x, y]]; + (w > 0.0 && d > 0.0 && t > 0.0).then(|| placed(pl, vec![ring])) + } + "IFCUSHAPEPROFILEDEF" => { + let pl = self.placement2d(e.arg(2)); + let (d, fw, tw, tf) = (self.length(e.arg(3))?, self.length(e.arg(4))?, self.length(e.arg(5))?, self.length(e.arg(6))?); + let (x, y) = (fw / 2.0, d / 2.0); + let ring = vec![[-x, -y], [x, -y], [x, -y + tf], [-x + tw, -y + tf], [-x + tw, y - tf], [x, y - tf], [x, y], [-x, y]]; + (d > 0.0 && fw > 0.0).then(|| placed(pl, vec![ring])) + } + "IFCTSHAPEPROFILEDEF" => { + let pl = self.placement2d(e.arg(2)); + let (d, fw, tw, tf) = (self.length(e.arg(3))?, self.length(e.arg(4))?, self.length(e.arg(5))?, self.length(e.arg(6))?); + let (x, y, a) = (fw / 2.0, d / 2.0, tw / 2.0); + let ring = vec![[-a, -y], [a, -y], [a, y - tf], [x, y - tf], [x, y], [-x, y], [-x, y - tf], [-a, y - tf]]; + (d > 0.0 && fw > 0.0).then(|| placed(pl, vec![ring])) + } + "IFCDERIVEDPROFILEDEF" => { + let parent = self.profile(e.arg(2), depth + 1)?; + let op = self.transform_operator2d(e.arg(3)); + Some(parent.into_iter().map(|rings| rings.into_iter().map(|r| r.into_iter().map(|p| op.apply(p)).collect()).collect()).collect()) + } + "IFCCOMPOSITEPROFILEDEF" => { + let mut out = Vec::new(); + for p in e.arg(2)?.as_list()? { + out.extend(self.profile(Some(p), depth + 1)?); + } + Some(out) + } + other => { + let other = other.to_string(); + self.skip(&other); + None + } + } + } + + // ---- Körper ---------------------------------------------------------------------------- + + /// Ein Darstellungselement → Dreiecke (in Koordinaten des Elements) an `out` anhängen. + /// `color` sammelt die erste gefundene Elementfarbe. + fn item(&mut self, id: u64, out: &mut Mesh, depth: usize, color: &mut Option<[f64; 4]>) { + if self.budget == 0 || !self.active.insert(id) { + return; + } + self.budget -= 1; + self.item_inner(id, out, depth, color); + self.active.remove(&id); + } + + fn item_inner(&mut self, id: u64, out: &mut Mesh, depth: usize, color: &mut Option<[f64; 4]>) { + let Some(e) = self.ent(id) else { return }; + if color.is_none() { + if let Some(c) = self.item_colors.get(&id) { + *color = Some(*c); + } + } + match e.ty.as_str() { + "IFCEXTRUDEDAREASOLID" => { + let Some(areas) = self.profile(e.arg(0), 0) else { return }; + let pos = self.axis_placement(e.arg(1)); + let Some(dir) = self.direction(e.arg(2)).and_then(norm) else { return }; + let Some(depth_m) = self.length(e.arg(3)) else { return }; + let h = scale(dir, depth_m); + for rings in &areas { + let m = extrude(rings, h); + out.append(&m, &pos); + } + } + "IFCFACETEDBREP" | "IFCFACETEDBREPWITHVOIDS" => { + if let Some(v) = e.arg(0) { + self.shell(v, out); + } + for v in e.arg(1).and_then(|v| v.as_list()).unwrap_or(&[]) { + self.shell(v, out); + } + } + "IFCSHELLBASEDSURFACEMODEL" | "IFCFACEBASEDSURFACEMODEL" => { + for v in e.arg(0).and_then(|v| v.as_list()).unwrap_or(&[]) { + self.shell(v, out); + } + } + "IFCTRIANGULATEDFACESET" | "IFCTRIANGULATEDIRREGULARNETWORK" => self.triangulated_face_set(e, out), + "IFCPOLYGONALFACESET" => self.polygonal_face_set(e, out), + "IFCMAPPEDITEM" => { + if depth >= MAX_MAP_DEPTH { + self.skip("IFCMAPPEDITEM (zu tief)"); + return; + } + let Some((_, map)) = self.ent_v(e.arg(0)) else { return }; + let origin = self.axis_placement(map.arg(0)); + let target = self.transform_operator(e.arg(1)); + let xf = target.then_after(&origin); + let Some((_, rep)) = self.ent_v(map.arg(1)) else { return }; + let items: Vec = rep.arg(3).and_then(|v| v.as_list()).unwrap_or(&[]).iter().filter_map(|v| v.as_ref_id()).collect(); + let mut local = Mesh::default(); + for it in items { + self.item(it, &mut local, depth + 1, color); + } + if xf.is_finite() { + out.append(&local, &xf); + } + } + "IFCBOOLEANRESULT" | "IFCBOOLEANCLIPPINGRESULT" => { + let op = e.arg(0).and_then(|v| v.as_enum()).unwrap_or(""); + if depth >= MAX_MAP_DEPTH * 4 { + return; + } + if let Some(a) = e.arg(1).and_then(|v| v.as_ref_id()) { + self.item(a, out, depth + 1, color); + } + if op == "UNION" { + if let Some(b) = e.arg(2).and_then(|v| v.as_ref_id()) { + self.item(b, out, depth + 1, color); + } + } else { + self.simplified += 1; + } + } + "IFCCSGSOLID" => { + if let Some(a) = e.arg(0).and_then(|v| v.as_ref_id()) { + if depth < MAX_MAP_DEPTH * 4 { + self.item(a, out, depth + 1, color); + } + } + } + "IFCBLOCK" => { + let pos = self.axis_placement(e.arg(0)); + let (Some(x), Some(y), Some(z)) = (self.length(e.arg(1)), self.length(e.arg(2)), self.length(e.arg(3))) else { return }; + if x > 0.0 && y > 0.0 && z > 0.0 { + let m = extrude(&[vec![[0.0, 0.0], [x, 0.0], [x, y], [0.0, y]]], [0.0, 0.0, z]); + out.append(&m, &pos); + } + } + other => { + let other = other.to_string(); + self.skip(&other); + } + } + } + + /// IfcClosedShell/IfcOpenShell/IfcConnectedFaceSet → Flächen. + fn shell(&mut self, v: &Value, out: &mut Mesh) { + let Some((_, sh)) = self.ent_v(Some(v)) else { return }; + let faces = sh.arg(0).and_then(|v| v.as_list()).unwrap_or(&[]); + for f in faces { + let Some((_, face)) = self.ent_v(Some(f)) else { continue }; + if face.ty != "IFCFACE" && face.ty != "IFCFACESURFACE" { + continue; + } + let mut outer: Option> = None; + let mut inner: Vec> = Vec::new(); + for b in face.arg(0).and_then(|v| v.as_list()).unwrap_or(&[]) { + let Some((_, bound)) = self.ent_v(Some(b)) else { continue }; + let Some((_, lp)) = self.ent_v(bound.arg(0)) else { continue }; + if lp.ty != "IFCPOLYLOOP" { + let ty = lp.ty.clone(); + self.skip(&ty); + continue; + } + let mut pts: Vec = lp + .arg(0) + .and_then(|v| v.as_list()) + .unwrap_or(&[]) + .iter() + .take(MAX_LOOP_POINTS) + .filter_map(|p| self.point(Some(p))) + .collect(); + pts.dedup_by(|a, b| len(sub(*a, *b)) < 1e-12); + if pts.len() > 1 && len(sub(pts[0], pts[pts.len() - 1])) < 1e-12 { + pts.pop(); + } + if bound.arg(1).and_then(|v| v.as_enum()) == Some("F") { + pts.reverse(); + } + if pts.len() < 3 { + continue; + } + if bound.ty == "IFCFACEOUTERBOUND" && outer.is_none() { + outer = Some(pts); + } else { + inner.push(pts); + } + } + // Ohne ausgezeichneten Aussenrand: der erste Rand ist aussen. + let outer = match outer { + Some(o) => o, + None if !inner.is_empty() => inner.remove(0), + None => continue, + }; + let mut rings = vec![outer]; + rings.extend(inner); + triangulate3d(&rings, out); + } + } + + /// Koordinatenliste (IfcCartesianPointList3D) in Metern. + fn point_list3d(&self, v: Option<&Value>) -> Option> { + let (_, pl) = self.ent_v(v)?; + if pl.ty != "IFCCARTESIANPOINTLIST3D" { + return None; + } + Some( + pl.arg(0)? + .as_list()? + .iter() + .map(|c| { + let c = c.as_list().unwrap_or(&[]); + let g = |i: usize| { + let v = c.get(i).and_then(|v| v.as_f64()).unwrap_or(f64::NAN) * self.len_scale; + if v.abs() < MAX_COORD { v } else { f64::NAN } + }; + [g(0), g(1), g(2)] + }) + .collect(), + ) + } + + /// PnIndex (IFC4 ADD1+): Liste ganzer Zahlen; die alte NormalIndex (Liste von Listen) wird ignoriert. + fn pn_index(v: Option<&Value>) -> Option> { + let l = v?.as_list()?; + if l.first().is_some_and(|x| x.as_list().is_some()) { + return None; + } + Some(l.iter().map(|x| x.as_i64().unwrap_or(0)).collect()) + } + + fn triangulated_face_set(&mut self, e: &Entity, out: &mut Mesh) { + let Some(coords) = self.point_list3d(e.arg(0)) else { return }; + let pn = Self::pn_index(e.arg(4)); + let base = out.vcount(); + let resolve = |k: i64| -> Option { + let k = match &pn { + Some(pn) => *pn.get(usize::try_from(k - 1).ok()?)?, + None => k, + }; + let i = usize::try_from(k - 1).ok()?; + let p = coords.get(i)?; + p.iter().all(|v| v.is_finite()).then_some(i as u32) + }; + let mut any = false; + for t in e.arg(3).and_then(|v| v.as_list()).unwrap_or(&[]) { + let Some(t) = t.as_list() else { continue }; + if t.len() != 3 { + continue; + } + let ids: Option> = t.iter().map(|x| x.as_i64().and_then(resolve)).collect(); + if let Some(ids) = ids { + if !any { + for p in &coords { + out.push_v(*p); + } + any = true; + } + out.tri(base + ids[0], base + ids[1], base + ids[2]); + } + } + } + + fn polygonal_face_set(&mut self, e: &Entity, out: &mut Mesh) { + let Some(coords) = self.point_list3d(e.arg(0)) else { return }; + let pn = Self::pn_index(e.arg(3)); + let resolve = |k: &Value| -> Option { + let k = k.as_i64()?; + let k = match &pn { + Some(pn) => *pn.get(usize::try_from(k - 1).ok()?)?, + None => k, + }; + let p = *coords.get(usize::try_from(k - 1).ok()?)?; + p.iter().all(|v| v.is_finite()).then_some(p) + }; + let ring = |l: &[Value]| -> Option> { l.iter().take(MAX_LOOP_POINTS).map(resolve).collect() }; + for f in e.arg(2).and_then(|v| v.as_list()).unwrap_or(&[]) { + let Some((_, face)) = self.ent_v(Some(f)) else { continue }; + let Some(outer) = face.arg(0).and_then(|v| v.as_list()).and_then(ring) else { continue }; + let mut rings = vec![outer]; + if face.ty == "IFCINDEXEDPOLYGONALFACEWITHVOIDS" { + for h in face.arg(1).and_then(|v| v.as_list()).unwrap_or(&[]) { + if let Some(r) = h.as_list().and_then(ring) { + rings.push(r); + } + } + } + triangulate3d(&rings, out); + } + } + + // ---- Farben ---------------------------------------------------------------------------- + + fn style_color(&self, styles: &[Value], depth: usize) -> Option<[f64; 4]> { + if depth > 4 { + return None; + } + for s in styles { + let Some((_, st)) = self.ent_v(Some(s)) else { continue }; + let c = match st.ty.as_str() { + "IFCPRESENTATIONSTYLEASSIGNMENT" => st.arg(0).and_then(|v| v.as_list()).and_then(|l| self.style_color(l, depth + 1)), + "IFCSURFACESTYLE" => st.arg(2).and_then(|v| v.as_list()).and_then(|l| { + l.iter().find_map(|el| { + let (_, r) = self.ent_v(Some(el))?; + if r.ty != "IFCSURFACESTYLERENDERING" && r.ty != "IFCSURFACESTYLESHADING" { + return None; + } + let (_, col) = self.ent_v(r.arg(0))?; + if col.ty != "IFCCOLOURRGB" { + return None; + } + let ch = |i: usize| col.arg(i).and_then(|v| v.as_f64()).map(|x| x.clamp(0.0, 1.0)); + let transp = r.arg(1).and_then(|v| v.as_f64()).unwrap_or(0.0).clamp(0.0, 1.0); + Some([ch(1)?, ch(2)?, ch(3)?, 1.0 - transp]) + }) + }), + _ => None, + }; + if c.is_some() { + return c; + } + } + None + } +} + +/// Faktor (Meter bzw. Radiant je Einheit) einer IfcNamedUnit; `None` = andere Art. +fn unit_info(f: &StepFile, id: u64, depth: usize) -> Option<(String, f64)> { + let e = f.get(id)?; + if depth > 4 { + return None; + } + match e.ty.as_str() { + "IFCSIUNIT" => { + let kind = e.arg(1)?.as_enum()?.to_string(); + let prefix = match e.arg(2).and_then(|v| v.as_enum()) { + Some("EXA") => 1e18, + Some("PETA") => 1e15, + Some("TERA") => 1e12, + Some("GIGA") => 1e9, + Some("MEGA") => 1e6, + Some("KILO") => 1e3, + Some("HECTO") => 1e2, + Some("DECA") => 1e1, + Some("DECI") => 1e-1, + Some("CENTI") => 1e-2, + Some("MILLI") => 1e-3, + Some("MICRO") => 1e-6, + Some("NANO") => 1e-9, + Some("PICO") => 1e-12, + _ => 1.0, + }; + Some((kind, prefix)) + } + "IFCCONVERSIONBASEDUNIT" | "IFCCONVERSIONBASEDUNITWITHOFFSET" => { + let kind = e.arg(1)?.as_enum()?.to_string(); + let m = f.get(e.arg(3)?.as_ref_id()?)?; + let v = m.arg(0)?.as_f64()?; + let (_, inner) = unit_info(f, m.arg(1)?.as_ref_id()?, depth + 1)?; + let s = v * inner; + (s.is_finite() && s > 0.0).then_some((kind, s)) + } + _ => None, + } +} + +/// Längen- und Winkelfaktor aus der Einheitenzuweisung des Projekts (sonst aller Einheiten der Datei). +fn units(f: &StepFile, ids: &[u64]) -> (f64, f64) { + let mut unit_ids: Vec = Vec::new(); + if let Some(p) = ids.iter().filter_map(|i| f.get(*i).map(|e| (i, e))).find(|(_, e)| e.ty == "IFCPROJECT") { + if let Some(ua) = p.1.arg(8).and_then(|v| v.as_ref_id()).and_then(|i| f.get(i)) { + unit_ids = ua.arg(0).and_then(|v| v.as_list()).unwrap_or(&[]).iter().filter_map(|v| v.as_ref_id()).collect(); + } + } + if unit_ids.is_empty() { + unit_ids = ids.iter().copied().filter(|i| f.get(*i).is_some_and(|e| e.ty == "IFCSIUNIT")).collect(); + } + let mut len_scale = 1.0; + let mut angle_scale = 1.0; + for u in unit_ids { + match unit_info(f, u, 0) { + Some((k, s)) if k == "LENGTHUNIT" => len_scale = s, + Some((k, s)) if k == "PLANEANGLEUNIT" => angle_scale = s, + _ => {} + } + } + (len_scale, angle_scale) +} + +/// Liest eine IFC-Datei als Meshes je Bauteil. +pub fn import_ifc(bytes: &[u8]) -> Result { + let f = ifc_step::parse(bytes)?; + if !f.schema.is_empty() && !f.schema.starts_with("IFC") { + return Err(format!("kein IFC-Schema: {}", f.schema)); + } + if f.entities.is_empty() { + return Err("keine Instanzen gefunden".into()); + } + let mut ids: Vec = f.entities.keys().copied().collect(); + ids.sort_unstable(); + let (len_scale, angle_scale) = units(&f, &ids); + + let mut r = Reader { + f: &f, + len_scale, + angle_scale, + placements: HashMap::new(), + item_colors: HashMap::new(), + skipped: BTreeMap::new(), + simplified: 0, + active: HashSet::new(), + budget: MAX_ITEM_EVALS, + }; + let mut result = IfcImport { schema: f.schema.clone(), length_scale: len_scale, parse_errors: f.errors, ..Default::default() }; + + // Beziehungen: Geschoss-Zugehörigkeit, Aggregation, Material, Farben. + let mut container: HashMap = HashMap::new(); + let mut parent: HashMap = HashMap::new(); + let mut material_of: HashMap = HashMap::new(); + let mut material_color: HashMap = HashMap::new(); + let refs = |v: Option<&Value>| -> Vec { v.and_then(|v| v.as_list()).unwrap_or(&[]).iter().filter_map(|x| x.as_ref_id()).collect() }; + for &id in &ids { + let e = &f.entities[&id]; + match e.ty.as_str() { + "IFCRELCONTAINEDINSPATIALSTRUCTURE" => { + if let Some(s) = e.arg(5).and_then(|v| v.as_ref_id()) { + for el in refs(e.arg(4)) { + container.entry(el).or_insert(s); + } + } + } + "IFCRELAGGREGATES" => { + if let Some(p) = e.arg(4).and_then(|v| v.as_ref_id()) { + for c in refs(e.arg(5)) { + parent.entry(c).or_insert(p); + } + } + } + "IFCRELASSOCIATESMATERIAL" => { + if let Some(m) = e.arg(5).and_then(|v| v.as_ref_id()) { + for o in refs(e.arg(4)) { + material_of.entry(o).or_insert(m); + } + } + } + "IFCRELVOIDSELEMENT" => result.voids_ignored += 1, + "IFCSTYLEDITEM" => { + if let Some(item) = e.arg(0).and_then(|v| v.as_ref_id()) { + if let Some(c) = e.arg(1).and_then(|v| v.as_list()).and_then(|l| r.style_color(l, 0)) { + r.item_colors.entry(item).or_insert(c); + } + } + } + "IFCMATERIALDEFINITIONREPRESENTATION" => { + if let Some(m) = e.arg(3).and_then(|v| v.as_ref_id()) { + 'reps: for rep in refs(e.arg(2)) { + for it in refs(f.get(rep).and_then(|x| x.arg(3))) { + let Some(si) = f.get(it) else { continue }; + if si.ty != "IFCSTYLEDITEM" { + continue; + } + if let Some(c) = si.arg(1).and_then(|v| v.as_list()).and_then(|l| r.style_color(l, 0)) { + material_color.entry(m).or_insert(c); + break 'reps; + } + } + } + } + } + _ => {} + } + } + + // Material (auch Schichten/Profile/Bestandteile/Listen) → Farbe des ersten Materials. + let resolve_material_color = |mut m: u64| -> Option<[f64; 4]> { + for _ in 0..6 { + if let Some(c) = material_color.get(&m) { + return Some(*c); + } + let e = f.get(m)?; + let next = match e.ty.as_str() { + "IFCMATERIALLAYERSETUSAGE" | "IFCMATERIALPROFILESETUSAGE" | "IFCMATERIALPROFILESETUSAGETAPERING" => e.arg(0), + "IFCMATERIALLAYERSET" | "IFCMATERIALLIST" => e.arg(0).and_then(|v| v.as_list()).and_then(|l| l.first()), + "IFCMATERIALPROFILESET" | "IFCMATERIALCONSTITUENTSET" => e.arg(2).and_then(|v| v.as_list()).and_then(|l| l.first()), + "IFCMATERIALLAYER" => e.arg(0), + "IFCMATERIALPROFILE" | "IFCMATERIALCONSTITUENT" => e.arg(2), + _ => None, + }; + m = next?.as_ref_id()?; + } + None + }; + + let storey_of = |mut id: u64| -> Option { + for _ in 0..32 { + let e = f.get(id)?; + if e.ty == "IFCBUILDINGSTOREY" { + let name = e.arg(2).and_then(|v| v.as_str()).or_else(|| e.arg(7).and_then(|v| v.as_str())); + return Some(name.unwrap_or("").to_string()); + } + id = match container.get(&id) { + Some(s) => *s, + None => *parent.get(&id)?, + }; + } + None + }; + + let mut total_tris = 0usize; + for &id in &ids { + let e = &f.entities[&id]; + // IfcProduct: Representation (Attribut 7) zeigt auf eine IfcProductDefinitionShape. + let Some(shape_id) = e.arg(6).and_then(|v| v.as_ref_id()) else { continue }; + let Some(shape) = f.get(shape_id) else { continue }; + if shape.ty != "IFCPRODUCTDEFINITIONSHAPE" { + continue; + } + if SKIP_CLASSES.contains(&e.ty.as_str()) { + *result.skipped_products.entry(class_name(&e.ty)).or_insert(0) += 1; + continue; + } + if total_tris >= MAX_TRIANGLES { + result.truncated = true; + break; + } + // Körper-Darstellungen wählen: „Body", sonst alle ausser Achse/Grundriss/Box/…. + let reps: Vec<&Entity> = refs(shape.arg(2)).into_iter().filter_map(|i| f.get(i)).filter(|r| r.ty == "IFCSHAPEREPRESENTATION").collect(); + let ident = |r: &Entity| r.arg(1).and_then(|v| v.as_str()).unwrap_or("").to_ascii_uppercase(); + let body: Vec<&Entity> = reps.iter().copied().filter(|r| ident(r) == "BODY").collect(); + let chosen: Vec<&Entity> = + if body.is_empty() { reps.iter().copied().filter(|r| !NON_BODY_REPS.contains(&ident(r).as_str())).collect() } else { body }; + if chosen.is_empty() { + continue; + } + let place = match e.arg(5).and_then(|v| v.as_ref_id()) { + Some(p) => r.object_placement(p, 0), + None => Xf::IDENTITY, + }; + let mut local = Mesh::default(); + let mut color = None; + for rep in chosen { + for it in refs(rep.arg(3)) { + r.item(it, &mut local, 0, &mut color); + if total_tris + local.triangle_count() > MAX_TRIANGLES { + break; + } + } + } + if local.is_empty() { + result.products_without_geometry += 1; + continue; + } + if total_tris + local.triangle_count() > MAX_TRIANGLES { + result.truncated = true; + break; + } + total_tris += local.triangle_count(); + let mut mesh = Mesh::default(); + mesh.append(&local, &place); + if color.is_none() { + color = material_of.get(&id).and_then(|m| resolve_material_color(*m)); + } + result.products.push(IfcProductMesh { + global_id: e.arg(0).and_then(|v| v.as_str()).unwrap_or("").to_string(), + class: class_name(&e.ty), + name: e.arg(2).and_then(|v| v.as_str()).map(str::to_string), + storey: storey_of(id), + color, + mesh, + }); + } + if r.budget == 0 { + result.truncated = true; + } + result.skipped_items = r.skipped; + result.simplified_booleans = r.simplified; + Ok(result) +} + +/// IFC-Klassennamen in Schema-Schreibweise (die Datei schreibt nur Grossbuchstaben). +const CLASS_NAMES: &[&str] = &[ + "IfcActuator", "IfcAirTerminal", "IfcAirTerminalBox", "IfcAlarm", "IfcAnnotation", "IfcBeam", "IfcBeamStandardCase", + "IfcBearing", "IfcBoiler", "IfcBridge", "IfcBridgePart", "IfcBuilding", "IfcBuildingElementPart", + "IfcBuildingElementProxy", "IfcBuildingStorey", "IfcCableCarrierFitting", "IfcCableCarrierSegment", + "IfcCableFitting", "IfcCableSegment", "IfcCaissonFoundation", "IfcChimney", "IfcCivilElement", "IfcColumn", + "IfcColumnStandardCase", "IfcCourse", "IfcCovering", "IfcCurtainWall", "IfcDamper", "IfcDeepFoundation", + "IfcDiscreteAccessory", "IfcDistributionChamberElement", "IfcDistributionControlElement", + "IfcDistributionElement", "IfcDistributionFlowElement", "IfcDoor", "IfcDoorStandardCase", "IfcDuctFitting", + "IfcDuctSegment", "IfcDuctSilencer", "IfcEarthworksCut", "IfcEarthworksElement", "IfcEarthworksFill", + "IfcElectricAppliance", "IfcElectricDistributionBoard", "IfcElementAssembly", "IfcElementComponent", + "IfcEnergyConversionDevice", "IfcFan", "IfcFastener", "IfcFilter", "IfcFireSuppressionTerminal", + "IfcFlowController", "IfcFlowFitting", "IfcFlowMovingDevice", "IfcFlowSegment", "IfcFlowStorageDevice", + "IfcFlowTerminal", "IfcFlowTreatmentDevice", "IfcFooting", "IfcFurnishingElement", "IfcFurniture", + "IfcGeographicElement", "IfcGrid", "IfcKerb", "IfcLamp", "IfcLightFixture", "IfcMechanicalFastener", "IfcMember", + "IfcMemberStandardCase", "IfcOpeningElement", "IfcOpeningStandardCase", "IfcPavement", "IfcPile", + "IfcPipeFitting", "IfcPipeSegment", "IfcPlate", "IfcPlateStandardCase", "IfcProxy", "IfcPump", "IfcRail", + "IfcRailing", "IfcRailway", "IfcRailwayPart", "IfcRamp", "IfcRampFlight", "IfcReinforcingBar", + "IfcReinforcingMesh", "IfcRoad", "IfcRoadPart", "IfcRoof", "IfcSanitaryTerminal", "IfcShadingDevice", "IfcSign", + "IfcSignal", "IfcSite", "IfcSlab", "IfcSlabElementedCase", "IfcSlabStandardCase", "IfcSpace", "IfcSpaceHeater", "IfcSpatialZone", + "IfcStair", "IfcStairFlight", "IfcSurfaceFeature", "IfcSwitchingDevice", "IfcTank", "IfcTendon", + "IfcTrackElement", "IfcTransportElement", "IfcUnitaryEquipment", "IfcValve", "IfcVirtualElement", "IfcWall", + "IfcWallElementedCase", "IfcWallStandardCase", "IfcWasteTerminal", "IfcWindow", "IfcWindowStandardCase", +]; + +fn class_name(upper: &str) -> String { + CLASS_NAMES.iter().find(|c| c.eq_ignore_ascii_case(upper)).map_or_else(|| upper.to_string(), |c| c.to_string()) +} + +/// Bogen durch drei Punkte (Anfang, Zwischenpunkt, Ende) als Punktfolge inkl. Endpunkte. +fn arc3(p1: V2, p2: V2, p3: V2) -> Vec { + let (ax, ay, bx, by, cx, cy) = (p1[0], p1[1], p2[0], p2[1], p3[0], p3[1]); + let d = 2.0 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by)); + if d.abs() < 1e-14 || !d.is_finite() { + return vec![p1, p2, p3]; + } + let a2 = ax * ax + ay * ay; + let b2 = bx * bx + by * by; + let c2 = cx * cx + cy * cy; + let ux = (a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by)) / d; + let uy = (a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax)) / d; + let r = ((ax - ux).powi(2) + (ay - uy).powi(2)).sqrt(); + let t1 = (ay - uy).atan2(ax - ux); + let t2 = (by - uy).atan2(bx - ux); + let t3 = (cy - uy).atan2(cx - ux); + let tau = std::f64::consts::TAU; + // Richtung so wählen, dass der Zwischenpunkt auf dem Bogen liegt. + let ccw13 = (t3 - t1).rem_euclid(tau); + let ccw12 = (t2 - t1).rem_euclid(tau); + let span = if ccw12 <= ccw13 { ccw13 } else { ccw13 - tau }; + let n = arc_segments(span, r).max(2); + let mut out: Vec = (0..n).map(|i| { + let t = t1 + span * i as f64 / n as f64; + [ux + r * t.cos(), uy + r * t.sin()] + }).collect(); + out.push(p3); + out +} + +// --------------------------------------------------------------------------- +// WASM-Fassade (Feature "web"): Geometrie flach (Float64Array/Uint32Array), Bericht als JSON. +// --------------------------------------------------------------------------- + +#[cfg(feature = "web")] +mod web { + use wasm_bindgen::prelude::*; + + /// Ergebnis für JS: `meta` (JSON: Bauteile mit Längen der Puffer, Bericht), `positions()` + /// (alle Bauteile hintereinander, x,y,z in m), `indices()` (je Bauteil ab 0). + #[wasm_bindgen] + pub struct IfcImportResult { + meta: String, + positions: Vec, + indices: Vec, + } + + #[wasm_bindgen] + impl IfcImportResult { + #[wasm_bindgen(getter)] + pub fn meta(&self) -> String { + self.meta.clone() + } + pub fn positions(&self) -> Vec { + self.positions.clone() + } + pub fn indices(&self) -> Vec { + self.indices.clone() + } + } + + /// IFC-Bytes → Meshes je Bauteil. Unlesbare Datei → JS-Fehler mit Meldung (kein Panic). + #[wasm_bindgen] + pub fn import_ifc(bytes: &[u8]) -> Result { + let r = super::import_ifc(bytes).map_err(|e| JsValue::from_str(&e))?; + let mut positions = Vec::new(); + let mut indices = Vec::new(); + let products: Vec = r + .products + .iter() + .map(|p| { + positions.extend_from_slice(&p.mesh.positions); + indices.extend_from_slice(&p.mesh.indices); + serde_json::json!({ + "globalId": p.global_id, + "ifcClass": p.class, + "name": p.name, + "storey": p.storey, + "color": p.color, + "positionCount": p.mesh.positions.len(), + "indexCount": p.mesh.indices.len(), + }) + }) + .collect(); + let meta = serde_json::json!({ + "schema": r.schema, + "lengthScale": r.length_scale, + "products": products, + "skippedItems": r.skipped_items, + "skippedProducts": r.skipped_products, + "productsWithoutGeometry": r.products_without_geometry, + "simplifiedBooleans": r.simplified_booleans, + "voidsIgnored": r.voids_ignored, + "parseErrors": r.parse_errors, + "truncated": r.truncated, + }); + Ok(IfcImportResult { meta: meta.to_string(), positions, indices }) + } +} + +// --------------------------------------------------------------------------- +// Tests: je Geometrietyp ein kleiner, von Hand geschriebener Fall mit bekanntem Volumen. +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + + /// Gerüst: Projekt (Einheit), Gebäude, Geschoss „EG" (z = 3), ein Bauteil mit `items`. + fn file(unit: &str, body: &str, items: &str, class: &str) -> String { + format!( + "ISO-10303-21;\nHEADER;\nFILE_SCHEMA(('IFC4'));\nENDSEC;\nDATA;\n\ +#1=IFCPROJECT('0proj',$,'P',$,$,$,$,$,#2);\n#2=IFCUNITASSIGNMENT((#3,#4));\n{unit}\n\ +#4=IFCSIUNIT(*,.PLANEANGLEUNIT.,$,.RADIAN.);\n\ +#10=IFCCARTESIANPOINT((0.,0.,0.));\n#11=IFCDIRECTION((0.,0.,1.));\n#12=IFCDIRECTION((1.,0.,0.));\n\ +#13=IFCAXIS2PLACEMENT3D(#10,$,$);\n#14=IFCLOCALPLACEMENT($,#13);\n\ +#20=IFCBUILDING('0bldg',$,'B',$,$,#14,$,$,.ELEMENT.,$,$,$);\n\ +#21=IFCCARTESIANPOINT((0.,0.,3.));\n#22=IFCAXIS2PLACEMENT3D(#21,$,$);\n#23=IFCLOCALPLACEMENT(#14,#22);\n\ +#24=IFCBUILDINGSTOREY('0eg',$,'EG',$,$,#23,$,$,.ELEMENT.,3.);\n\ +#25=IFCRELAGGREGATES('0agg',$,$,$,#20,(#24));\n\ +#30=IFCLOCALPLACEMENT(#23,#13);\n\ +{body}\n\ +#90=IFCSHAPEREPRESENTATION($,'Body','SweptSolid',({items}));\n\ +#91=IFCSHAPEREPRESENTATION($,'Axis','Curve2D',(#92));\n#92=IFCPOLYLINE((#10,#21));\n\ +#93=IFCPRODUCTDEFINITIONSHAPE($,$,(#91,#90));\n\ +#94={class}('3aBcDeFgHiJkLmNoPqRsTu',$,'Teil',$,$,#30,#93,$,$);\n\ +#95=IFCRELCONTAINEDINSPATIALSTRUCTURE('0rel',$,$,$,(#94),#24);\n\ +ENDSEC;\nEND-ISO-10303-21;\n" + ) + } + const METRE: &str = "#3=IFCSIUNIT(*,.LENGTHUNIT.,$,.METRE.);"; + const MILLI: &str = "#3=IFCSIUNIT(*,.LENGTHUNIT.,.MILLI.,.METRE.);"; + + fn one(src: &str) -> (IfcImport, IfcProductMesh) { + let r = import_ifc(src.as_bytes()).expect("lesbar"); + assert_eq!(r.products.len(), 1, "{r:?}"); + let p = r.products[0].clone(); + (r, p) + } + fn vol(p: &IfcProductMesh) -> f64 { + signed_volume(&p.mesh.positions, &p.mesh.indices) + } + fn bbox(p: &IfcProductMesh) -> (V3, V3) { + let mut lo = [f64::INFINITY; 3]; + let mut hi = [f64::NEG_INFINITY; 3]; + for c in p.mesh.positions.chunks_exact(3) { + for k in 0..3 { + lo[k] = lo[k].min(c[k]); + hi[k] = hi[k].max(c[k]); + } + } + (lo, hi) + } + fn close(a: f64, b: f64, tol: f64) -> bool { + (a - b).abs() <= tol + } + + #[test] + fn extruded_arbitrary_profile_with_hole_in_mm() { + // 4 m × 2 m Platte mit 1 m × 1 m Loch, 300 mm dick; Einheit mm. + let body = "#40=IFCCARTESIANPOINT((0.,0.));#41=IFCCARTESIANPOINT((4000.,0.));#42=IFCCARTESIANPOINT((4000.,2000.));#43=IFCCARTESIANPOINT((0.,2000.));\ +#44=IFCPOLYLINE((#40,#41,#42,#43,#40));\ +#45=IFCCARTESIANPOINT((1000.,500.));#46=IFCCARTESIANPOINT((2000.,500.));#47=IFCCARTESIANPOINT((2000.,1500.));#48=IFCCARTESIANPOINT((1000.,1500.));\ +#49=IFCPOLYLINE((#45,#46,#47,#48,#45));\ +#50=IFCARBITRARYPROFILEDEFWITHVOIDS(.AREA.,$,#44,(#49));\ +#51=IFCEXTRUDEDAREASOLID(#50,#13,#11,300.);"; + let (r, p) = one(&file(MILLI, body, "#51", "IFCSLAB")); + assert!(close(r.length_scale, 0.001, 1e-15)); + assert!(close(vol(&p), (8.0 - 1.0) * 0.3, 1e-9), "{}", vol(&p)); + assert_eq!(p.class, "IfcSlab"); + assert_eq!(p.storey.as_deref(), Some("EG")); + assert_eq!(p.name.as_deref(), Some("Teil")); + assert_eq!(p.global_id, "3aBcDeFgHiJkLmNoPqRsTu"); + let (lo, hi) = bbox(&p); + // Geschoss-Platzierung z = 3 m (in mm-Datei: 3 mm!) — Platzierung in Dateieinheit. + assert!(close(lo[2], 0.003, 1e-12) && close(hi[2], 0.303, 1e-12), "{lo:?} {hi:?}"); + assert!(close(hi[0], 4.0, 1e-12) && close(hi[1], 2.0, 1e-12)); + } + + #[test] + fn extruded_rectangle_circle_and_shapes() { + let body = "#40=IFCCARTESIANPOINT((1.,2.));#41=IFCDIRECTION((0.,1.));#42=IFCAXIS2PLACEMENT2D(#40,#41);\ +#50=IFCRECTANGLEPROFILEDEF(.AREA.,$,#42,0.4,0.2);#51=IFCEXTRUDEDAREASOLID(#50,$,#11,2.);\ +#52=IFCCIRCLEPROFILEDEF(.AREA.,$,$,0.5);#53=IFCEXTRUDEDAREASOLID(#52,#13,#11,1.);\ +#54=IFCCIRCLEHOLLOWPROFILEDEF(.AREA.,$,$,0.5,0.1);#55=IFCEXTRUDEDAREASOLID(#54,#13,#11,1.);\ +#56=IFCISHAPEPROFILEDEF(.AREA.,$,$,0.2,0.3,0.01,0.02,$,$,$);#57=IFCEXTRUDEDAREASOLID(#56,#13,#11,1.);\ +#58=IFCRECTANGLEHOLLOWPROFILEDEF(.AREA.,$,$,0.4,0.2,0.05,$,$);#59=IFCEXTRUDEDAREASOLID(#58,#13,#11,1.);"; + let rect = 0.4 * 0.2 * 2.0; + let (_, p) = one(&file(METRE, body, "#51", "IFCCOLUMN")); + assert!(close(vol(&p), rect, 1e-12)); + let (lo, hi) = bbox(&p); + // Profil um 90° gedreht und nach (1,2) verschoben: x-Ausdehnung 0.2, y 0.4. + assert!(close(hi[0] - lo[0], 0.2, 1e-12) && close(hi[1] - lo[1], 0.4, 1e-12) && close(lo[0], 0.9, 1e-12)); + let pi = std::f64::consts::PI; + let (_, p) = one(&file(METRE, body, "#53", "IFCCOLUMN")); + assert!((vol(&p) - pi * 0.25).abs() / (pi * 0.25) < 0.01, "{}", vol(&p)); + let (_, p) = one(&file(METRE, body, "#55", "IFCCOLUMN")); + let ring = pi * (0.25 - 0.16); + assert!((vol(&p) - ring).abs() / ring < 0.01, "{}", vol(&p)); + let (_, p) = one(&file(METRE, body, "#57", "IFCBEAM")); + let ishape = 2.0 * 0.2 * 0.02 + (0.3 - 0.04) * 0.01; + assert!(close(vol(&p), ishape, 1e-12), "{}", vol(&p)); + let (_, p) = one(&file(METRE, body, "#59", "IFCMEMBER")); + assert!(close(vol(&p), 0.4 * 0.2 - 0.3 * 0.1, 1e-12)); + // Mehrere Elemente in einer Darstellung addieren sich. + let (_, p) = one(&file(METRE, body, "#51,#57", "IFCCOLUMN")); + assert!(close(vol(&p), rect + ishape, 1e-12)); + } + + #[test] + fn extrusion_slanted_and_downwards() { + // Schräg (Richtung (1,0,1)) und Tiefe 2: Volumen = Fläche × Höhe = 1 × 2/√2. + let body = "#40=IFCRECTANGLEPROFILEDEF(.AREA.,$,$,1.,1.);#41=IFCDIRECTION((1.,0.,1.));#42=IFCEXTRUDEDAREASOLID(#40,#13,#41,2.);\ +#43=IFCDIRECTION((0.,0.,-1.));#44=IFCEXTRUDEDAREASOLID(#40,#13,#43,2.);\ +#45=IFCDIRECTION((1.,0.,0.));#46=IFCEXTRUDEDAREASOLID(#40,#13,#45,2.);"; + let (_, p) = one(&file(METRE, body, "#42", "IFCMEMBER")); + assert!(close(vol(&p), 2.0 / 2f64.sqrt(), 1e-12)); + let (_, p) = one(&file(METRE, body, "#44", "IFCMEMBER")); + assert!(close(vol(&p), 2.0, 1e-12), "nach unten bleibt aussen orientiert: {}", vol(&p)); + // Extrusion in der Profilebene: kein Körper. + let r = import_ifc(file(METRE, body, "#46", "IFCMEMBER").as_bytes()).unwrap(); + assert_eq!(r.products.len(), 0); + assert_eq!(r.products_without_geometry, 1); + } + + #[test] + fn faceted_brep_cube_with_placement_and_rotation() { + // Einheitswürfel als 6 Polyloops; Bauteil-Platzierung gedreht (X → Y) und verschoben. + let mut s = String::new(); + let pts = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0), (0, 0, 1), (1, 0, 1), (1, 1, 1), (0, 1, 1)]; + for (i, p) in pts.iter().enumerate() { + s += &format!("#{}=IFCCARTESIANPOINT(({}.,{}.,{}.));", 100 + i, p.0, p.1, p.2); + } + let faces = [[0, 3, 2, 1], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]; + let mut fids = Vec::new(); + for (k, f) in faces.iter().enumerate() { + let (l, b, fc) = (200 + 3 * k, 201 + 3 * k, 202 + 3 * k); + let ids: Vec = f.iter().map(|i| format!("#{}", 100 + i)).collect(); + s += &format!("#{l}=IFCPOLYLOOP(({}));#{b}=IFCFACEOUTERBOUND(#{l},.T.);#{fc}=IFCFACE((#{b}));", ids.join(",")); + fids.push(format!("#{fc}")); + } + s += &format!("#300=IFCCLOSEDSHELL(({}));#301=IFCFACETEDBREP(#300);", fids.join(",")); + let src = file(METRE, &s, "#301", "IFCBUILDINGELEMENTPROXY") + .replace("#30=IFCLOCALPLACEMENT(#23,#13);", "#30=IFCLOCALPLACEMENT(#23,#31);#31=IFCAXIS2PLACEMENT3D(#32,#11,#33);#32=IFCCARTESIANPOINT((10.,0.,0.));#33=IFCDIRECTION((0.,1.,0.));"); + let (_, p) = one(&src); + assert!(close(vol(&p), 1.0, 1e-12)); + let (lo, hi) = bbox(&p); + assert!(close(lo[0], 9.0, 1e-12) && close(hi[0], 10.0, 1e-12), "{lo:?} {hi:?}"); + assert!(close(lo[2], 3.0, 1e-12) && close(hi[2], 4.0, 1e-12)); + assert_eq!(p.mesh.triangle_count(), 12); + } + + #[test] + fn faceted_brep_face_with_inner_bound() { + // Quadratische Fläche 2×2 mit 1×1-Loch (Fläche, kein Körper): Dreiecksfläche = 3. + let s = "#100=IFCCARTESIANPOINT((0.,0.,0.));#101=IFCCARTESIANPOINT((2.,0.,0.));#102=IFCCARTESIANPOINT((2.,2.,0.));#103=IFCCARTESIANPOINT((0.,2.,0.));\ +#104=IFCCARTESIANPOINT((0.5,0.5,0.));#105=IFCCARTESIANPOINT((1.5,0.5,0.));#106=IFCCARTESIANPOINT((1.5,1.5,0.));#107=IFCCARTESIANPOINT((0.5,1.5,0.));\ +#110=IFCPOLYLOOP((#100,#101,#102,#103));#111=IFCPOLYLOOP((#104,#105,#106,#107));\ +#112=IFCFACEOUTERBOUND(#110,.T.);#113=IFCFACEBOUND(#111,.F.);#114=IFCFACE((#113,#112));\ +#115=IFCOPENSHELL((#114));#116=IFCSHELLBASEDSURFACEMODEL((#115));"; + let (_, p) = one(&file(METRE, s, "#116", "IFCCOVERING")); + let pos = &p.mesh.positions; + let mut area = 0.0; + for t in p.mesh.indices.chunks_exact(3) { + let g = |i: u32| [pos[i as usize * 3], pos[i as usize * 3 + 1], pos[i as usize * 3 + 2]]; + let n = cross(sub(g(t[1]), g(t[0])), sub(g(t[2]), g(t[0]))); + assert!(n[2] > 0.0, "nach oben orientiert"); + area += len(n) / 2.0; + } + assert!(close(area, 3.0, 1e-12), "{area}"); + } + + #[test] + fn triangulated_and_polygonal_face_sets() { + // Tetraeder (Volumen 1/6) als TriangulatedFaceSet, Würfel als PolygonalFaceSet. + let s = "#100=IFCCARTESIANPOINTLIST3D(((0.,0.,0.),(1.,0.,0.),(0.,1.,0.),(0.,0.,1.)),$);\ +#101=IFCTRIANGULATEDFACESET(#100,$,.T.,((1,3,2),(1,2,4),(2,3,4),(3,1,4)),$);\ +#102=IFCTRIANGULATEDFACESET(#100,$,.T.,((1,3,2),(1,2,4),(2,3,4),(3,1,4),(1,2,99)),(1,2,3,4));\ +#110=IFCCARTESIANPOINTLIST3D(((0.,0.,0.),(1.,0.,0.),(1.,1.,0.),(0.,1.,0.),(0.,0.,1.),(1.,0.,1.),(1.,1.,1.),(0.,1.,1.)));\ +#111=IFCINDEXEDPOLYGONALFACE((1,4,3,2));#112=IFCINDEXEDPOLYGONALFACE((5,6,7,8));#113=IFCINDEXEDPOLYGONALFACE((1,2,6,5));\ +#114=IFCINDEXEDPOLYGONALFACE((2,3,7,6));#115=IFCINDEXEDPOLYGONALFACE((3,4,8,7));#116=IFCINDEXEDPOLYGONALFACE((4,1,5,8));\ +#117=IFCPOLYGONALFACESET(#110,.T.,(#111,#112,#113,#114,#115,#116),$);"; + let (_, p) = one(&file(METRE, s, "#101", "IFCFURNITURE")); + assert!(close(vol(&p), 1.0 / 6.0, 1e-12)); + // PnIndex + ungültiger Index (99) wird übersprungen. + let (_, p) = one(&file(METRE, s, "#102", "IFCFURNITURE")); + assert!(close(vol(&p), 1.0 / 6.0, 1e-12)); + assert_eq!(p.mesh.triangle_count(), 4); + let (_, p) = one(&file(METRE, s, "#117", "IFCFURNITURE")); + assert!(close(vol(&p), 1.0, 1e-12)); + } + + #[test] + fn polygonal_face_with_voids() { + let s = "#110=IFCCARTESIANPOINTLIST3D(((0.,0.,0.),(2.,0.,0.),(2.,2.,0.),(0.,2.,0.),(0.5,0.5,0.),(0.5,1.5,0.),(1.5,1.5,0.),(1.5,0.5,0.)));\ +#111=IFCINDEXEDPOLYGONALFACEWITHVOIDS((1,2,3,4),((5,6,7,8)));#117=IFCPOLYGONALFACESET(#110,$,(#111),$);"; + let (_, p) = one(&file(METRE, s, "#117", "IFCPLATE")); + let pos = &p.mesh.positions; + let area: f64 = p.mesh.indices.chunks_exact(3).map(|t| { + let g = |i: u32| [pos[i as usize * 3], pos[i as usize * 3 + 1], pos[i as usize * 3 + 2]]; + len(cross(sub(g(t[1]), g(t[0])), sub(g(t[2]), g(t[0])))) / 2.0 + }).sum(); + assert!(close(area, 3.0, 1e-12)); + } + + #[test] + fn mapped_item_with_scale_and_mirror() { + // Würfel 1 m (TriangulatedFaceSet über PolygonalFaceSet) als Typ-Darstellung, zweimal eingesetzt: + // einmal verschoben, einmal ungleichmässig skaliert (2, 3, 1) und gespiegelt. + let s = "#110=IFCCARTESIANPOINTLIST3D(((0.,0.,0.),(1.,0.,0.),(1.,1.,0.),(0.,1.,0.),(0.,0.,1.),(1.,0.,1.),(1.,1.,1.),(0.,1.,1.)));\ +#111=IFCINDEXEDPOLYGONALFACE((1,4,3,2));#112=IFCINDEXEDPOLYGONALFACE((5,6,7,8));#113=IFCINDEXEDPOLYGONALFACE((1,2,6,5));\ +#114=IFCINDEXEDPOLYGONALFACE((2,3,7,6));#115=IFCINDEXEDPOLYGONALFACE((3,4,8,7));#116=IFCINDEXEDPOLYGONALFACE((4,1,5,8));\ +#117=IFCPOLYGONALFACESET(#110,.T.,(#111,#112,#113,#114,#115,#116),$);\ +#120=IFCSHAPEREPRESENTATION($,'Body','Tessellation',(#117));#121=IFCREPRESENTATIONMAP(#13,#120);\ +#122=IFCCARTESIANPOINT((5.,0.,0.));#123=IFCCARTESIANTRANSFORMATIONOPERATOR3D($,$,#122,$,$);#124=IFCMAPPEDITEM(#121,#123);\ +#125=IFCDIRECTION((-1.,0.,0.));#128=IFCDIRECTION((0.,1.,0.));#126=IFCCARTESIANTRANSFORMATIONOPERATOR3DNONUNIFORM(#125,#128,#10,2.,$,3.,1.);#127=IFCMAPPEDITEM(#121,#126);"; + let (_, p) = one(&file(METRE, s, "#124", "IFCFURNITURE")); + assert!(close(vol(&p), 1.0, 1e-12)); + let (lo, _) = bbox(&p); + assert!(close(lo[0], 5.0, 1e-12)); + let (_, p) = one(&file(METRE, s, "#127", "IFCFURNITURE")); + assert!(close(vol(&p), 6.0, 1e-12), "Spiegelung bleibt aussen orientiert: {}", vol(&p)); + let (lo, hi) = bbox(&p); + assert!(close(lo[0], -2.0, 1e-12) && close(hi[0], 0.0, 1e-12) && close(hi[1] - lo[1], 3.0, 1e-12)); + // Rekursion (Mapped Item zeigt auf sich selbst über eine Darstellung): Abbruch, kein Überlauf. + let rec = s.to_string() + "#130=IFCSHAPEREPRESENTATION($,'Body','MappedRepresentation',(#132));#131=IFCREPRESENTATIONMAP(#13,#130);#132=IFCMAPPEDITEM(#131,#123);"; + let r = import_ifc(file(METRE, &rec, "#132", "IFCFURNITURE").as_bytes()).unwrap(); + assert_eq!(r.products.len(), 0); + } + + #[test] + fn curves_arcs_and_composite() { + // Halbkreis-Profil über IfcIndexedPolyCurve (Linie + Bogen), IfcCompositeCurve mit getrimmtem Kreis + // (Parameter in Grad) und IfcCircle direkt: Fläche π r²/2 bzw. π r². + let pi = std::f64::consts::PI; + let body = "#40=IFCCARTESIANPOINTLIST2D(((-1.,0.),(1.,0.),(0.,1.)));\ +#41=IFCINDEXEDPOLYCURVE(#40,(IFCLINEINDEX((1,2)),IFCARCINDEX((2,3,1))),$);\ +#42=IFCARBITRARYCLOSEDPROFILEDEF(.AREA.,$,#41);#43=IFCEXTRUDEDAREASOLID(#42,#13,#11,1.);\ +#50=IFCCARTESIANPOINT((0.,0.));#51=IFCAXIS2PLACEMENT2D(#50,$);#52=IFCCIRCLE(#51,1.);\ +#53=IFCTRIMMEDCURVE(#52,(IFCPARAMETERVALUE(0.)),(IFCPARAMETERVALUE(180.)),.T.,.PARAMETER.);\ +#54=IFCCARTESIANPOINT((-1.,0.));#55=IFCCARTESIANPOINT((1.,0.));#56=IFCPOLYLINE((#54,#55));\ +#57=IFCCOMPOSITECURVESEGMENT(.CONTINUOUS.,.T.,#53);#58=IFCCOMPOSITECURVESEGMENT(.CONTINUOUS.,.T.,#56);\ +#59=IFCCOMPOSITECURVE((#57,#58),.F.);#60=IFCARBITRARYCLOSEDPROFILEDEF(.AREA.,$,#59);#61=IFCEXTRUDEDAREASOLID(#60,#13,#11,1.);\ +#62=IFCARBITRARYCLOSEDPROFILEDEF(.AREA.,$,#52);#63=IFCEXTRUDEDAREASOLID(#62,#13,#11,1.);"; + let (_, p) = one(&file(METRE, body, "#43", "IFCSLAB")); + assert!((vol(&p) - pi / 2.0).abs() / (pi / 2.0) < 0.01, "{}", vol(&p)); + let deg = file(METRE, body, "#61", "IFCSLAB") + .replace("#4=IFCSIUNIT(*,.PLANEANGLEUNIT.,$,.RADIAN.);", "#4=IFCCONVERSIONBASEDUNIT(#5,.PLANEANGLEUNIT.,'DEGREE',#6);#5=IFCDIMENSIONALEXPONENTS(0,0,0,0,0,0,0);#6=IFCMEASUREWITHUNIT(IFCPLANEANGLEMEASURE(0.017453292519943295),#7);#7=IFCSIUNIT(*,.PLANEANGLEUNIT.,$,.RADIAN.);"); + let (_, p) = one(°); + assert!((vol(&p) - pi / 2.0).abs() / (pi / 2.0) < 0.01, "{}", vol(&p)); + let (_, p) = one(&file(METRE, body, "#63", "IFCSLAB")); + assert!((vol(&p) - pi).abs() / pi < 0.01, "{}", vol(&p)); + } + + #[test] + fn colors_from_styled_item_and_material() { + let body = "#40=IFCRECTANGLEPROFILEDEF(.AREA.,$,$,1.,1.);#41=IFCEXTRUDEDAREASOLID(#40,#13,#11,1.);\ +#60=IFCCOLOURRGB($,0.5,0.25,1.);#61=IFCSURFACESTYLERENDERING(#60,0.2,$,$,$,$,$,$,.NOTDEFINED.);\ +#62=IFCSURFACESTYLE('rot',.BOTH.,(#61));#63=IFCPRESENTATIONSTYLEASSIGNMENT((#62));#64=IFCSTYLEDITEM(#41,(#63),$);"; + let (_, p) = one(&file(METRE, body, "#41", "IFCWALL")); + let c = p.color.unwrap(); + assert!(close(c[0], 0.5, 1e-12) && close(c[1], 0.25, 1e-12) && close(c[2], 1.0, 1e-12) && close(c[3], 0.8, 1e-12)); + // Über Material (IFC4: Stil direkt, ohne PresentationStyleAssignment), Wand mit Schichtsatz. + let body2 = "#40=IFCRECTANGLEPROFILEDEF(.AREA.,$,$,1.,1.);#41=IFCEXTRUDEDAREASOLID(#40,#13,#11,1.);\ +#60=IFCCOLOURRGB($,0.1,0.2,0.3);#61=IFCSURFACESTYLESHADING(#60,$);#62=IFCSURFACESTYLE($,.BOTH.,(#61));#64=IFCSTYLEDITEM($,(#62),$);\ +#65=IFCSTYLEDREPRESENTATION($,'Style','Material',(#64));#66=IFCMATERIAL('Beton',$,$);#67=IFCMATERIALDEFINITIONREPRESENTATION($,$,(#65),#66);\ +#68=IFCMATERIALLAYER(#66,0.2,$,$,$,$,$);#69=IFCMATERIALLAYERSET((#68),'W',$);#70=IFCMATERIALLAYERSETUSAGE(#69,.AXIS2.,.POSITIVE.,0.,$);\ +#71=IFCRELASSOCIATESMATERIAL('0mat',$,$,$,(#94),#70);"; + let (_, p) = one(&file(METRE, body2, "#41", "IFCWALL")); + let c = p.color.unwrap(); + assert!(close(c[0], 0.1, 1e-12) && close(c[2], 0.3, 1e-12) && close(c[3], 1.0, 1e-12)); + } + + #[test] + fn booleans_and_unknown_items_are_counted() { + let body = "#40=IFCRECTANGLEPROFILEDEF(.AREA.,$,$,1.,1.);#41=IFCEXTRUDEDAREASOLID(#40,#13,#11,1.);\ +#42=IFCEXTRUDEDAREASOLID(#40,#13,#11,0.5);#43=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#41,#42);\ +#44=IFCSWEPTDISKSOLID(#92,0.1,$,$,$);#45=IFCBOOLEANRESULT(.UNION.,#41,#42);"; + let (r, p) = one(&file(METRE, body, "#43,#44", "IFCWALL")); + assert!(close(vol(&p), 1.0, 1e-12)); + assert_eq!(r.simplified_booleans, 1); + assert_eq!(r.skipped_items.get("IFCSWEPTDISKSOLID"), Some(&1)); + let (r, p) = one(&file(METRE, body, "#45", "IFCWALL")); + assert!(close(vol(&p), 1.5, 1e-12)); + assert_eq!(r.simplified_booleans, 0); + } + + #[test] + fn skips_openings_and_spaces() { + let body = "#40=IFCRECTANGLEPROFILEDEF(.AREA.,$,$,1.,1.);#41=IFCEXTRUDEDAREASOLID(#40,#13,#11,1.);"; + let r = import_ifc(file(METRE, body, "#41", "IFCOPENINGELEMENT").as_bytes()).unwrap(); + assert!(r.products.is_empty()); + assert_eq!(r.skipped_products.get("IfcOpeningElement"), Some(&1)); + let r = import_ifc(file(METRE, body, "#41", "IFCSPACE").as_bytes()).unwrap(); + assert_eq!(r.skipped_products.get("IfcSpace"), Some(&1)); + } + + #[test] + fn ifc2x3_feet_and_unknown_class() { + // Fuss als Längeneinheit (IFC2x3-Stil), unbekannte Klasse behält Grossschreibung. + let src = file("#3=IFCCONVERSIONBASEDUNIT(#5,.LENGTHUNIT.,'FOOT',#6);#5=IFCDIMENSIONALEXPONENTS(1,0,0,0,0,0,0);#6=IFCMEASUREWITHUNIT(IFCRATIOMEASURE(0.3048),#7);#7=IFCSIUNIT(*,.LENGTHUNIT.,$,.METRE.);", + "#40=IFCRECTANGLEPROFILEDEF(.AREA.,$,$,1.,1.);#41=IFCEXTRUDEDAREASOLID(#40,#13,#11,1.);", "#41", "IFCFOOBAR") + .replace("IFC4", "IFC2X3"); + let (r, p) = one(&src); + assert_eq!(r.schema, "IFC2X3"); + assert!(close(r.length_scale, 0.3048, 1e-15)); + assert!(close(vol(&p), 0.3048f64.powi(3), 1e-12)); + assert_eq!(p.class, "IFCFOOBAR"); + } + + /// Freie Beispieldateien (z. B. buildingSMART Sample-Test-Files), nur wenn `DOSSIER_IFC_SAMPLES` auf + /// ein Verzeichnis zeigt: jede Datei muss lesbar sein und Bauteile liefern. Ausgabe je Datei mit + /// `--nocapture`; der Gegencheck mit ifcopenshell läuft in `scripts/ifc-import-compare.py`. + #[test] + fn sample_files_if_present() { + let Ok(dir) = std::env::var("DOSSIER_IFC_SAMPLES") else { return }; + let mut files = Vec::new(); + let mut stack = vec![std::path::PathBuf::from(dir)]; + while let Some(d) = stack.pop() { + for e in std::fs::read_dir(&d).into_iter().flatten().flatten() { + let p = e.path(); + if p.is_dir() { + stack.push(p); + } else if p.extension().is_some_and(|x| x.eq_ignore_ascii_case("ifc")) { + files.push(p); + } + } + } + files.sort(); + for f in files { + let bytes = std::fs::read(&f).unwrap(); + let r = import_ifc(&bytes).unwrap_or_else(|e| panic!("{}: {e}", f.display())); + let tris: usize = r.products.iter().map(|p| p.mesh.triangle_count()).sum(); + eprintln!( + "{}: {} {} Bauteile, {} Dreiecke, ohne Geometrie {}, übersprungen {:?}, Bauteile ausgelassen {:?}", + f.display(), r.schema, r.products.len(), tris, r.products_without_geometry, r.skipped_items, r.skipped_products + ); + assert!(!r.products.is_empty(), "{}", f.display()); + } + } + + #[test] + fn nonsense_never_panics() { + assert!(import_ifc(b"").is_err()); + assert!(import_ifc(b"not an ifc").is_err()); + assert!(import_ifc(b"ISO-10303-21;HEADER;FILE_SCHEMA(('CONFIG_CONTROL_DESIGN'));ENDSEC;DATA;#1=X();ENDSEC;").is_err()); + // Kaputte Referenzen, Zyklen, NaN, falsche Typen an jeder Stelle. + let bad = [ + "#41=IFCEXTRUDEDAREASOLID(#41,#41,#41,#41);", + "#41=IFCEXTRUDEDAREASOLID(#40,#13,#11,1.);#40=IFCRECTANGLEPROFILEDEF(.AREA.,$,$,-1.,1.);", + "#41=IFCEXTRUDEDAREASOLID(#40,#13,#11,1.);#40=IFCARBITRARYCLOSEDPROFILEDEF(.AREA.,$,#42);#42=IFCPOLYLINE((#10,#10,#10));", + "#41=IFCEXTRUDEDAREASOLID(#40,#13,#11,1.);#40=IFCARBITRARYCLOSEDPROFILEDEF(.AREA.,$,#42);#42=IFCCOMPOSITECURVE((#43),.F.);#43=IFCCOMPOSITECURVESEGMENT(.C.,.T.,#42);", + "#41=IFCTRIANGULATEDFACESET(#42,$,$,((1,2,3),(0,-1,5),('a',2,3)),((1)));#42=IFCCARTESIANPOINTLIST3D(((0.,0.),(1.,1.,1.),()));", + "#41=IFCFACETEDBREP(#42);#42=IFCCLOSEDSHELL((#43,#41,$,1));#43=IFCFACE((#44));#44=IFCFACEOUTERBOUND(#45,.T.);#45=IFCPOLYLOOP((#10,#21,#10));", + "#41=IFCMAPPEDITEM(#42,#43);#42=IFCREPRESENTATIONMAP(#13,#90);#43=IFCCARTESIANTRANSFORMATIONOPERATOR3D(#11,#11,#10,0.,#11);", + "#41=IFCBOOLEANRESULT(.UNION.,#41,#41);", + "#41=IFCPOLYGONALFACESET(#42,$,(#43),(5,6));#42=IFCCARTESIANPOINTLIST3D(((0.,0.,0.)));#43=IFCINDEXEDPOLYGONALFACE((1,2,3));", + "#41=IFCEXTRUDEDAREASOLID(#40,#13,#11,1.);#40=IFCARBITRARYCLOSEDPROFILEDEF(.AREA.,$,#42);#42=IFCINDEXEDPOLYCURVE(#43,(IFCARCINDEX((1,1,1)),IFCLINEINDEX((9))),$);#43=IFCCARTESIANPOINTLIST2D(((0.,0.)));", + "#41=IFCEXTRUDEDAREASOLID(#40,#13,#11,1.E308);#40=IFCCIRCLEPROFILEDEF(.AREA.,$,$,1.E308);", + "#41=IFCEXTRUDEDAREASOLID(#40,#13,#11,1.);#40=IFCCIRCLEPROFILEDEF(.AREA.,$,$,1.E-300);", + ]; + for b in bad { + let _ = import_ifc(file(METRE, b, "#41", "IFCWALL").as_bytes()); + } + // Platzierungs-Zyklus. + let cyc = file(METRE, "#40=IFCRECTANGLEPROFILEDEF(.AREA.,$,$,1.,1.);#41=IFCEXTRUDEDAREASOLID(#40,#13,#11,1.);", "#41", "IFCWALL") + .replace("#14=IFCLOCALPLACEMENT($,#13);", "#14=IFCLOCALPLACEMENT(#30,#13);"); + let r = import_ifc(cyc.as_bytes()).unwrap(); + assert_eq!(r.products.len(), 1); + } +} diff --git a/src-tauri/fileio/src/ifc_step.rs b/src-tauri/fileio/src/ifc_step.rs new file mode 100644 index 00000000..4c5a1220 --- /dev/null +++ b/src-tauri/fileio/src/ifc_step.rs @@ -0,0 +1,617 @@ +// STEP-Klartext-Leser (ISO 10303-21) für IFC ([B3]): zerlegt eine `.ifc`-Datei in Instanzen +// `#id = TYP(argumente);`. Kennt keine Schemata (IFC2x3, IFC4, IFC4.3 laufen gleich durch); +// die Bedeutung der Argumente liest `ifc_import.rs`. +// +// Eigener Code (nichts aus BIMCraft `step.rs` übernommen). +// +// Robustheit: kaputte Instanzen werden übersprungen und gezählt (Lesen geht beim nächsten `;` +// weiter), Verschachtelung und Dateigrösse sind begrenzt, nie Panic. +// +// Zeichenketten nach ISO 10303-21 §6.4.3: `''` → `'`, `\\` → `\`, `\S\c` (ISO 8859 obere Hälfte), +// `\X\hh` (ISO 8859-1), `\X2\hhhh…\X0\` (UTF-16), `\X4\hhhhhhhh…\X0\` (UTF-32), `\P?\` (Codeseite, +// ignoriert). Rohe Nicht-ASCII-Bytes (in der Praxis UTF-8 oder Latin-1) werden toleriert. + +use std::collections::HashMap; + +/// Obergrenze der Dateigrösse (Bytes) — darüber wird gar nicht erst gelesen. +pub const MAX_FILE_BYTES: usize = 400 * 1024 * 1024; +/// Obergrenze der Instanzen. +pub const MAX_ENTITIES: usize = 20_000_000; +/// Obergrenze der Listen-Verschachtelung (schützt den Stack). +const MAX_DEPTH: usize = 64; + +/// Ein Argument einer Instanz. +#[derive(Debug, Clone, PartialEq)] +pub enum Value { + /// `$` — nicht gesetzt. + Null, + /// `*` — abgeleitet (redeklariert). + Derived, + Int(i64), + Real(f64), + Str(String), + /// `.ENUM.` (ohne Punkte, gross). + Enum(String), + /// `#123` + Ref(u64), + /// `"…"` (Binärwert, Inhalt unbeachtet). + Binary, + List(Vec), + /// Typisierter Wert `IFCLABEL('x')`, `IFCLENGTHMEASURE(1.)`. + Typed(String, Vec), +} + +impl Value { + pub fn as_ref_id(&self) -> Option { + match self { + Value::Ref(r) => Some(*r), + _ => None, + } + } + /// Zahl (auch ganzzahlig oder typisiert wie `IFCREAL(1.)`); nur endliche Werte. + pub fn as_f64(&self) -> Option { + let v = match self { + Value::Real(r) => *r, + Value::Int(i) => *i as f64, + Value::Typed(_, a) if a.len() == 1 => return a[0].as_f64(), + _ => return None, + }; + v.is_finite().then_some(v) + } + pub fn as_i64(&self) -> Option { + match self { + Value::Int(i) => Some(*i), + Value::Typed(_, a) if a.len() == 1 => a[0].as_i64(), + _ => None, + } + } + pub fn as_str(&self) -> Option<&str> { + match self { + Value::Str(s) => Some(s), + Value::Typed(_, a) if a.len() == 1 => a[0].as_str(), + _ => None, + } + } + pub fn as_enum(&self) -> Option<&str> { + match self { + Value::Enum(s) => Some(s), + _ => None, + } + } + pub fn as_list(&self) -> Option<&[Value]> { + match self { + Value::List(l) => Some(l), + _ => None, + } + } + pub fn is_null(&self) -> bool { + matches!(self, Value::Null | Value::Derived) + } +} + +/// Eine Instanz `#id = TYP(args)`; komplexe Instanzen `#id = (A(..) B(..))` tragen den Typ +/// `""` und je Teil ein `Value::Typed` in `args`. +#[derive(Debug, Clone)] +pub struct Entity { + pub ty: String, + pub args: Vec, +} + +impl Entity { + pub fn arg(&self, i: usize) -> Option<&Value> { + self.args.get(i) + } +} + +/// Inhalt einer STEP-Datei. +#[derive(Debug, Default)] +pub struct StepFile { + /// Erstes Schema aus `FILE_SCHEMA` (gross, z. B. `IFC2X3`, `IFC4`, `IFC4X3_ADD2`). + pub schema: String, + pub entities: HashMap, + /// Übersprungene, unlesbare Anweisungen. + pub errors: usize, +} + +impl StepFile { + pub fn get(&self, id: u64) -> Option<&Entity> { + self.entities.get(&id) + } +} + +struct Lexer<'a> { + b: &'a [u8], + i: usize, +} + +impl<'a> Lexer<'a> { + fn peek(&self) -> Option { + self.b.get(self.i).copied() + } + + /// Überspringt Leerraum und `/* … */`-Kommentare. + fn ws(&mut self) { + loop { + while let Some(c) = self.peek() { + if c.is_ascii_whitespace() { + self.i += 1; + } else { + break; + } + } + if self.b.get(self.i) == Some(&b'/') && self.b.get(self.i + 1) == Some(&b'*') { + match find(self.b, self.i + 2, b"*/") { + Some(end) => self.i = end + 2, + None => self.i = self.b.len(), + } + } else { + return; + } + } + } + + fn eat(&mut self, c: u8) -> bool { + self.ws(); + if self.peek() == Some(c) { + self.i += 1; + true + } else { + false + } + } + + /// Schlüsselwort (`IFCWALL`, `FILE_SCHEMA`, `END-ISO-10303-21`), gross gemacht. + fn keyword(&mut self) -> Option { + self.ws(); + let start = self.i; + while let Some(c) = self.peek() { + if c.is_ascii_alphanumeric() || c == b'_' || c == b'-' { + self.i += 1; + } else { + break; + } + } + if self.i == start { + return None; + } + Some(String::from_utf8_lossy(&self.b[start..self.i]).to_ascii_uppercase()) + } + + fn integer(&mut self) -> Option { + let start = self.i; + while let Some(c) = self.peek() { + if c.is_ascii_digit() { + self.i += 1; + } else { + break; + } + } + std::str::from_utf8(&self.b[start..self.i]).ok()?.parse().ok() + } + + /// Springt hinter das nächste `;` ausserhalb von Zeichenketten (Fehlererholung). + fn skip_statement(&mut self) { + while let Some(c) = self.peek() { + self.i += 1; + match c { + b';' => return, + b'\'' => { + // Zeichenkette bis zum schliessenden Hochkomma (`''` = Hochkomma). + while let Some(d) = self.peek() { + self.i += 1; + if d == b'\'' { + if self.peek() == Some(b'\'') { + self.i += 1; + } else { + break; + } + } + } + } + b'/' if self.peek() == Some(b'*') => { + self.i = find(self.b, self.i + 1, b"*/").map_or(self.b.len(), |e| e + 2); + } + _ => {} + } + } + } + + /// Argumentliste nach der öffnenden Klammer bis zur schliessenden. + fn args(&mut self, depth: usize) -> Option> { + if depth > MAX_DEPTH { + return None; + } + let mut out = Vec::new(); + if self.eat(b')') { + return Some(out); + } + loop { + out.push(self.value(depth)?); + if self.eat(b',') { + continue; + } + if self.eat(b')') { + return Some(out); + } + return None; + } + } + + fn value(&mut self, depth: usize) -> Option { + self.ws(); + let c = self.peek()?; + match c { + b'$' => { + self.i += 1; + Some(Value::Null) + } + b'*' => { + self.i += 1; + Some(Value::Derived) + } + b'#' => { + self.i += 1; + self.integer().map(Value::Ref) + } + b'\'' => self.string().map(Value::Str), + b'"' => { + self.i += 1; + let end = self.b[self.i..].iter().position(|&d| d == b'"')?; + self.i += end + 1; + Some(Value::Binary) + } + b'.' if self.b.get(self.i + 1).is_some_and(|d| d.is_ascii_alphabetic() || *d == b'_') => { + self.i += 1; + let start = self.i; + while let Some(d) = self.peek() { + if d == b'.' { + break; + } + if !(d.is_ascii_alphanumeric() || d == b'_') { + return None; + } + self.i += 1; + } + let s = String::from_utf8_lossy(&self.b[start..self.i]).to_ascii_uppercase(); + self.i += 1; // schliessender Punkt + Some(Value::Enum(s)) + } + b'(' => { + self.i += 1; + self.args(depth + 1).map(Value::List) + } + b'+' | b'-' | b'.' | b'0'..=b'9' => self.number(), + c if c.is_ascii_alphabetic() => { + let name = self.keyword()?; + if !self.eat(b'(') { + return None; + } + let a = self.args(depth + 1)?; + Some(Value::Typed(name, a)) + } + _ => None, + } + } + + fn number(&mut self) -> Option { + let start = self.i; + let mut real = false; + while let Some(c) = self.peek() { + match c { + b'0'..=b'9' | b'+' | b'-' => {} + b'.' | b'E' | b'e' => real = true, + _ => break, + } + self.i += 1; + } + let s = std::str::from_utf8(&self.b[start..self.i]).ok()?; + if !real { + if let Ok(i) = s.parse::() { + return Some(Value::Int(i)); + } + } + // `1.` und `1.E-5` sind gültiges STEP; Rust liest beides, zur Sicherheit „1.0“-Form. + let fixed; + let t = if let Some(p) = s.find('.') { + let after = s.as_bytes().get(p + 1); + if after.is_none_or(|c| !c.is_ascii_digit()) { + fixed = format!("{}0{}", &s[..=p], &s[p + 1..]); + &fixed + } else { + s + } + } else { + s + }; + let v: f64 = t.parse().ok()?; + Some(Value::Real(v)) + } + + /// Zeichenkette ab dem öffnenden Hochkomma, dekodiert. + fn string(&mut self) -> Option { + self.i += 1; + let mut raw: Vec = Vec::new(); + loop { + let c = self.peek()?; + self.i += 1; + if c == b'\'' { + if self.peek() == Some(b'\'') { + self.i += 1; + raw.push(b'\''); + } else { + break; + } + } else { + raw.push(c); + } + } + Some(decode_string(&raw)) + } +} + +fn find(hay: &[u8], from: usize, needle: &[u8]) -> Option { + if from >= hay.len() { + return None; + } + hay[from..].windows(needle.len()).position(|w| w == needle).map(|p| p + from) +} + +fn hex_val(c: u8) -> Option { + (c as char).to_digit(16) +} + +/// Dekodiert die Steuersequenzen einer STEP-Zeichenkette (Inhalt ohne Hochkommas, `''` bereits +/// aufgelöst). +pub fn decode_string(raw: &[u8]) -> String { + let mut out = String::with_capacity(raw.len()); + let mut i = 0; + // Rohe Nicht-ASCII-Bytes: als UTF-8 lesen, wenn gültig, sonst Latin-1. + let push_raw = |out: &mut String, bytes: &[u8]| match std::str::from_utf8(bytes) { + Ok(s) => out.push_str(s), + Err(_) => out.extend(bytes.iter().map(|&b| b as char)), + }; + let mut plain_start = 0; + while i < raw.len() { + if raw[i] != b'\\' { + i += 1; + continue; + } + push_raw(&mut out, &raw[plain_start..i]); + let rest = &raw[i..]; + if rest.starts_with(b"\\\\") { + out.push('\\'); + i += 2; + } else if rest.starts_with(b"\\S\\") && rest.len() >= 4 { + out.push(char::from_u32(rest[3] as u32 + 128).unwrap_or('?')); + i += 4; + } else if rest.starts_with(b"\\P") && rest.len() >= 4 && rest[3] == b'\\' { + i += 4; + } else if rest.starts_with(b"\\X\\") && rest.len() >= 5 { + match (hex_val(rest[3]), hex_val(rest[4])) { + (Some(h), Some(l)) => out.push(char::from_u32(h * 16 + l).unwrap_or('?')), + _ => out.push('?'), + } + i += 5; + } else if rest.starts_with(b"\\X2\\") || rest.starts_with(b"\\X4\\") { + let width = if rest[2] == b'2' { 4 } else { 8 }; + let body_start = i + 4; + let end = find(raw, body_start, b"\\X0\\").unwrap_or(raw.len()); + let body = &raw[body_start..end]; + let mut units: Vec = Vec::new(); + for chunk in body.chunks(width) { + if chunk.len() < width { + break; + } + let mut v = 0u32; + let mut ok = true; + for &c in chunk { + match hex_val(c) { + Some(h) => v = v.wrapping_mul(16).wrapping_add(h), + None => ok = false, + } + } + if ok { + units.push(v); + } + } + if width == 4 { + let u16s: Vec = units.iter().map(|&u| u as u16).collect(); + out.push_str(&String::from_utf16_lossy(&u16s)); + } else { + out.extend(units.iter().map(|&u| char::from_u32(u).unwrap_or('\u{FFFD}'))); + } + i = (end + 4).min(raw.len()); + } else { + // Unbekannte Sequenz: Backslash wörtlich behalten. + out.push('\\'); + i += 1; + } + plain_start = i; + } + push_raw(&mut out, &raw[plain_start.min(raw.len())..]); + out +} + +/// Liest eine STEP-Datei. Fehler nur bei grundsätzlich unbrauchbarer Eingabe (zu gross, kein +/// STEP); einzelne kaputte Instanzen zählen in `errors`. +pub fn parse(bytes: &[u8]) -> Result { + if bytes.len() > MAX_FILE_BYTES { + return Err(format!("Datei zu gross ({} MB, höchstens {} MB)", bytes.len() >> 20, MAX_FILE_BYTES >> 20)); + } + let head = &bytes[..bytes.len().min(4096)]; + if find(head, 0, b"ISO-10303-21").is_none() { + return Err("keine STEP-Datei (ISO-10303-21 fehlt)".into()); + } + let mut lx = Lexer { b: bytes, i: 0 }; + let mut file = StepFile::default(); + loop { + lx.ws(); + let Some(c) = lx.peek() else { break }; + if c == b'#' { + lx.i += 1; + let start = lx.i; + let parsed = (|| { + let id = lx.integer()?; + if !lx.eat(b'=') { + return None; + } + lx.ws(); + let ent = if lx.peek() == Some(b'(') { + // Komplexe Instanz: Folge von TYP(args) in Klammern. + lx.i += 1; + let mut parts = Vec::new(); + loop { + if lx.eat(b')') { + break; + } + let name = lx.keyword()?; + if !lx.eat(b'(') { + return None; + } + parts.push(Value::Typed(name, lx.args(1)?)); + } + Entity { ty: String::new(), args: parts } + } else { + let ty = lx.keyword()?; + if !lx.eat(b'(') { + return None; + } + Entity { ty, args: lx.args(1)? } + }; + if !lx.eat(b';') { + return None; + } + Some((id, ent)) + })(); + match parsed { + Some((id, ent)) => { + if file.entities.len() >= MAX_ENTITIES { + return Err(format!("zu viele Instanzen (höchstens {MAX_ENTITIES})")); + } + file.entities.insert(id, ent); + } + None => { + file.errors += 1; + lx.i = start; + lx.skip_statement(); + } + } + continue; + } + // Kopf- und Abschnitts-Anweisungen. + let Some(kw) = lx.keyword() else { + lx.i += 1; + file.errors += 1; + lx.skip_statement(); + continue; + }; + match kw.as_str() { + "END-ISO-10303-21" => break, + "FILE_SCHEMA" => { + if lx.eat(b'(') { + if let Some(a) = lx.args(1) { + if let Some(Value::List(l)) = a.first() { + if let Some(s) = l.first().and_then(|v| v.as_str()) { + file.schema = s.trim().to_ascii_uppercase(); + } + } + } + } + lx.skip_statement(); + } + _ => lx.skip_statement(), + } + } + Ok(file) +} + +#[cfg(test)] +mod tests { + use super::*; + + const MINI: &str = "ISO-10303-21;\nHEADER;\nFILE_DESCRIPTION(('ViewDefinition [CoordinationView]'),'2;1');\n\ +FILE_NAME('a.ifc','2024-01-01T00:00:00',(''),(''),'x','y','');\nFILE_SCHEMA(('IFC4'));\nENDSEC;\nDATA;\n\ +#1=IFCCARTESIANPOINT((0.,1.5,-2.E-1));\n/* Kommentar; mit Semikolon */\n\ +#2 = IFCWALL('2O2Fr$t4X7Zf8NOew3FLOH',$,'K\\X2\\00FC\\X0\\che',*,.T.,#1,(#1,#3),IFCLABEL('it''s'));\n\ +#3=IFCDIRECTION((1,0,0));\n#4=(IFCA(1)IFCB('x'));\nENDSEC;\nEND-ISO-10303-21;\n"; + + #[test] + fn parses_header_and_instances() { + let f = parse(MINI.as_bytes()).unwrap(); + assert_eq!(f.schema, "IFC4"); + assert_eq!(f.errors, 0); + let p = f.get(1).unwrap(); + assert_eq!(p.ty, "IFCCARTESIANPOINT"); + let c: Vec = p.args[0].as_list().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + assert_eq!(c, vec![0.0, 1.5, -0.2]); + let w = f.get(2).unwrap(); + assert_eq!(w.ty, "IFCWALL"); + assert_eq!(w.args[2].as_str(), Some("Küche")); + assert_eq!(w.args[3], Value::Derived); + assert_eq!(w.args[4], Value::Enum("T".into())); + assert_eq!(w.args[5], Value::Ref(1)); + assert_eq!(w.args[7].as_str(), Some("it's")); + assert_eq!(f.get(3).unwrap().args[0].as_list().unwrap()[0], Value::Int(1)); + let cx = f.get(4).unwrap(); + assert_eq!(cx.ty, ""); + assert_eq!(cx.args.len(), 2); + } + + #[test] + fn decodes_escapes() { + assert_eq!(decode_string(b"\\X2\\00E400F6\\X0\\"), "äö"); + assert_eq!(decode_string(b"\\X4\\0001F600\\X0\\x"), "😀x"); + assert_eq!(decode_string(b"a\\\\b"), "a\\b"); + assert_eq!(decode_string(b"\\S\\d"), "ä"); // 'd' = 0x64, +128 = 0xE4 + assert_eq!(decode_string(b"\\X\\E9t\\X\\E9"), "été"); + assert_eq!(decode_string(b"\\PA\\Z"), "Z"); + assert_eq!(decode_string("Grüezi".as_bytes()), "Grüezi"); + assert_eq!(decode_string(&[0x47, 0xFC]), "Gü"); // Latin-1 roh + // Kaputt: nie Panic. + assert_eq!(decode_string(b"\\X2\\00E"), ""); + let _ = decode_string(b"\\X\\Z"); + let _ = decode_string(b"\\"); + } + + #[test] + fn recovers_from_broken_instances() { + let s = "ISO-10303-21;\nDATA;\n#1=IFCFOO(1,,2);\n#2=IFCBAR('a;b');\n#3=IFCBAZ((1,2);\n#4=IFCOK(.X.);\nENDSEC;\n"; + let f = parse(s.as_bytes()).unwrap(); + assert!(f.get(1).is_none()); + assert_eq!(f.get(2).unwrap().args[0].as_str(), Some("a;b")); + assert!(f.get(4).is_some()); + assert!(f.errors >= 2); + } + + #[test] + fn rejects_nonsense_without_panic() { + assert!(parse(b"").is_err()); + assert!(parse(b"hello world").is_err()); + for s in [ + "ISO-10303-21;#", + "ISO-10303-21;#1=", + "ISO-10303-21;#1=X(", + "ISO-10303-21;#1=X('unterminated", + "ISO-10303-21;#1=X(\"bin", + "ISO-10303-21;#1=X(.E", + "ISO-10303-21;/* offen", + "ISO-10303-21;#99999999999999999999999=X();", + "ISO-10303-21;#1=X(-);#2=X(1.2.3E);#3=X(+.E);", + ] { + let _ = parse(s.as_bytes()); + } + // Tiefe Verschachtelung: Abbruch statt Stack-Überlauf. + let deep = format!("ISO-10303-21;#1=X({}{});", "(".repeat(10_000), ")".repeat(10_000)); + let f = parse(deep.as_bytes()).unwrap(); + assert!(f.get(1).is_none()); + // Zufallsbytes. + let mut x: u32 = 12345; + let mut buf = b"ISO-10303-21;DATA;".to_vec(); + for _ in 0..20_000 { + x = x.wrapping_mul(1103515245).wrapping_add(12345); + let alphabet = b"#=(),;'$*.ABC0123456789\\X2 \n/*"; + buf.push(alphabet[(x >> 16) as usize % alphabet.len()]); + } + let _ = parse(&buf); + } +} diff --git a/src-tauri/fileio/src/lib.rs b/src-tauri/fileio/src/lib.rs index 0d4e79e4..59d1998e 100644 --- a/src-tauri/fileio/src/lib.rs +++ b/src-tauri/fileio/src/lib.rs @@ -11,6 +11,8 @@ // acadrust: `DxfReader::from_reader(Cursor>)` (Read + Seek + 'static) — ohne Dateisystem, WASM-tauglich. pub mod export; +pub mod ifc_step; +pub mod ifc_import; use std::collections::HashMap; use std::io::Cursor; diff --git a/src/App.tsx b/src/App.tsx index 13c9f710..79620e58 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -54,6 +54,8 @@ import { RecoverAutosaveDialog } from "./ui/RecoverAutosaveDialog"; import { Toast } from "./ui/Toast"; import { isTauriRuntime, PROJECT_TEMPLATE_EXT } from "./native/projectFile"; import { stepTextToImportedMeshes } from "./io/stepImport"; +import { formatIfcReport, ifcBytesToImportedMeshes } from "./io/ifcImport"; +import { projectGeoOrigin } from "./model/geoRebase"; import { applyClashMarkers, runClashCheck } from "./analysis/clash"; import { checkForUpdate } from "./update/checkForUpdate"; import type { PlanViewHandle } from "./views/plan/PlanView"; @@ -547,6 +549,8 @@ export default function App() { const dxfInputRef = useRef(null); // Verstecktes Datei-Input für den STEP-Import (Menü Datei, STEP importieren). const stepInputRef = useRef(null); + // Verstecktes Datei-Input für den IFC-Import ([B3], Menü Datei, IFC importieren). + const ifcInputRef = useRef(null); // Verstecktes Datei-Input für „Bild einfügen" (Werkzeug „image", s. tools.ts- // Kommentar) — akzeptiert auch PDF (jede Seite wird gerastert, s. pdfImport.ts); @@ -1694,6 +1698,26 @@ export default function App() { setRoomStamp, } = useProjectActions(setProject, notify, planViewRef); + // IFC-Import ([B3]): Bauteile als Kontext-Meshes (Format-Modul, `io/ifcImport.ts`), Bericht als Toast. + const importIfcFile = (f: File) => { + void f + .arrayBuffer() + .then((buf) => ifcBytesToImportedMeshes(new Uint8Array(buf), f.name, { geoOrigin: projectGeoOrigin(project) })) + .then(({ meshes, report }) => { + if (meshes.length) addContextObjectsAndFit(meshes); + const warn = meshes.length === 0 || report.truncated || report.productsWithoutGeometry > 0; + notify(formatIfcReport(report, t), warn ? "warning" : "info"); + }) + .catch((err) => + notify(`${t("ifc.import.failed")}: ${err instanceof Error ? err.message : String(err)}`, "error"), + ); + }; + /** Datei aus Import-Dialog oder Drag & Drop: IFC direkt, sonst DXF/DWG-Dialog. */ + const openImportForAnyFile = (f: File) => { + if (/\.ifc$/i.test(f.name)) importIfcFile(f); + else openImportForFile(f); + }; + // 2D-Griff-Editieren (Eckpunkt-/Kanten-Griffe + Feld-Controller) der aktuellen // Auswahl — siehe state/useGripEditing.ts. // Schnitt-/Ansichts-Blatt: geschnittene (bzw. in der Ansicht sichtbare) @@ -2391,6 +2415,7 @@ export default function App() { onExportStl, onExportStep, onImportStep: () => stepInputRef.current?.click(), + onImportIfc: () => ifcInputRef.current?.click(), onClashCheck: () => { const p0 = project; runClashCheck(p0) @@ -3080,7 +3105,7 @@ export default function App() { // App-weites Drag & Drop einer DXF/DWG-Datei — siehe state/useImportHandling.ts. const { onAppDragEnter, onAppDragOver, onAppDragLeave, onAppDrop } = useFileDropImport( setDropActive, - openImportForFile, + openImportForAnyFile, ); // Host-Context für die Panels — siehe state/usePanelHostBase.ts. @@ -3256,11 +3281,11 @@ export default function App() { { const f = e.target.files?.[0]; - if (f) openImportForFile(f); + if (f) openImportForAnyFile(f); e.target.value = ""; }} /> @@ -3283,6 +3308,18 @@ export default function App() { ); }} /> + {/* Verstecktes IFC-Datei-Input (Menü Datei, IFC importieren). */} + { + const f = e.target.files?.[0]; + e.target.value = ""; + if (f) importIfcFile(f); + }} + /> {/* Verstecktes Bild/PDF-Datei-Input (Werkzeug „image"). */} section [--out schnitt.svg] (braucht render3d-WASM) // dossier-cli elevation [--out ansicht.svg] // dossier-cli dxf|dwg|ifc|step|obj|stl|schedule|kennzahlen|sun [--level EG] [--out datei] +// dossier-cli import-ifc [--out neu.obp] [--group product|class] +// IFC als Kontext-Meshes ([B3]); Bericht als JSON auf stdout // dossier-cli model3d [--out modell.json] 3D-Modell fürs Headless-Rendern (render_png) // dossier-cli mcp MCP-Server (stdio): project_info, query, render_svg, apply_ops, validate // dossier-cli bench [--runs 10] Zeitprofil der Ableitungen (ms je Aufruf) @@ -22,6 +24,10 @@ import { buildPlanDxf, buildPlanDwg, loadFileio, + readIfc, + ifcToImportedMeshes, + projectGeoOrigin, + ensureContextCategories, projectToWorldCoords, computeSection, exportIfcSpf, @@ -124,7 +130,7 @@ export async function run(argv: string[]): Promise { const [file, command, ...rest] = args.positional; if (!file || !command) { process.stderr.write( - "Aufruf: dossier-cli [Optionen]\n", + "Aufruf: dossier-cli [Optionen]\n", ); return 2; } @@ -136,7 +142,15 @@ export async function run(argv: string[]): Promise { await initCore(); const project = loadProject(file); const scale = Number(args.flags.get("scale") ?? 100); - const allCodes = new Set(project.layers.map((l) => l.code)); + // Alle Ebenen-Codes inkl. verschachtelter (z. B. „10 Situation" unter „05 Kontext"). + const allCodes = new Set(); + const collectCodes = (ls: Project["layers"]): void => { + for (const l of ls) { + allCodes.add(l.code); + if (l.children) collectCodes(l.children); + } + }; + collectCodes(project.layers); switch (command) { case "info": { @@ -245,6 +259,37 @@ export async function run(argv: string[]): Promise { out(args, r.text, `${project.name || "projekt"}.stp`); return 0; } + case "import-ifc": { + const src = rest[0]; + if (!src) fail("import-ifc: IFC-Datei 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 { products, report } = await readIfc(bytes); + const group = args.flags.get("group"); + const meshes = ifcToImportedMeshes(products, src.split(/[\\/]/).pop() ?? src, { + geoOrigin: projectGeoOrigin(project), + group: group === "product" || group === "class" ? group : "auto", + }); + const byClass: Record = {}; + for (const p of products) byClass[p.ifcClass] = (byClass[p.ifcClass] ?? 0) + 1; + const triangles = products.reduce((s, p) => s + p.indices.length / 3, 0); + process.stdout.write(JSON.stringify({ ...report, byClass, triangles, contextObjects: meshes.length }, null, 2) + "\n"); + const target = args.flags.get("out"); + if (target) { + const next = applyOps(project, diffToOps(project, { + ...project, + context: [...(project.context ?? []), ...meshes], + // Wie in der App (siteSlice): fehlende Kontext-Kategorie als Ebene ergänzen. + layers: ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : []))), + })); + out(args, serializeProject(next), target); + } + return 0; + } case "mcp": await serveStdio(file); return 0; diff --git a/src/core/extra.ts b/src/core/extra.ts index 0d448780..f50ec927 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -6,6 +6,9 @@ export { exportIfcSpf } from "../export/exportIfc"; export { buildPlanDxf } from "../export/exportDxf"; export { buildPlanDwg } from "../export/exportDxf"; export { loadFileio } from "../engine/fileioWasm"; +export { readIfc, ifcToImportedMeshes } from "../io/ifcImport"; +export { projectGeoOrigin } from "../model/geoRebase"; +export { ensureContextCategories } from "../model/contextCategories"; export { projectToWorldCoords } from "../model/geoRebase"; export { exportScheduleCsv } from "../export/exportSchedule"; export { exportObj, exportStl } from "../export/exportMesh"; diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 2de7413e..cef294bd 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -1755,6 +1755,13 @@ export const de = { "step.import.failed": "STEP-Import fehlgeschlagen", "step.import.done": "STEP importiert: {n} Körper", "menu.native.importStep": "STEP importieren …", + "menu.native.importIfc": "IFC importieren …", + "ifc.import.failed": "IFC-Import fehlgeschlagen", + "ifc.import.done": "{schema} importiert: {n} Bauteile als Kontext-Meshes", + "ifc.import.skipped": "{n} Bauteile ohne lesbare Geometrie, übersprungen: {list}", + "ifc.import.voids": "{n} Öffnungen nicht abgezogen", + "ifc.import.booleans": "{n} Boolesche Körper vereinfacht (nur erster Operand)", + "ifc.import.truncated": "abgebrochen: zu viele Dreiecke", "recover.title": "Ungesicherte Arbeit gefunden", "recover.message": "Von „{name}“ gibt es eine automatische Sicherung vom {when}, die nicht gespeichert wurde.", "recover.unsaved": "unbenanntes Projekt", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 74101ef1..a9632e06 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -1716,6 +1716,13 @@ export const en: Record = { "step.import.failed": "STEP import failed", "step.import.done": "STEP imported: {n} solids", "menu.native.importStep": "Import STEP …", + "menu.native.importIfc": "Import IFC …", + "ifc.import.failed": "IFC import failed", + "ifc.import.done": "{schema} imported: {n} elements as context meshes", + "ifc.import.skipped": "{n} elements without readable geometry, skipped: {list}", + "ifc.import.voids": "{n} openings not subtracted", + "ifc.import.booleans": "{n} boolean solids simplified (first operand only)", + "ifc.import.truncated": "aborted: too many triangles", "recover.title": "Unsaved work found", "recover.message": "There is an automatic backup of “{name}” from {when} that was never saved.", "recover.unsaved": "untitled project", diff --git a/src/io/ifcImport.test.ts b/src/io/ifcImport.test.ts new file mode 100644 index 00000000..47c55482 --- /dev/null +++ b/src/io/ifcImport.test.ts @@ -0,0 +1,220 @@ +// IFC-Import ([B3]): Rundreise mit dem eigenen IFC-Export und Gegencheck mit ifcopenshell. +// +// Toleranzen: Wände/Dächer sind im Export Dreiecksnetze (IfcTriangulatedFaceSet) und Decken +// Extrusionen von Polygonen — beides ohne Tessellierung, das Volumen muss bis auf die +// Zahlenformatierung des Exports (R(), ~1e-9 m) stimmen: relativ 1e-6. Gegen ifcopenshell gilt +// dasselbe für ebene Geometrie; Kreise/Bögen werden von beiden Seiten verschieden fein zerlegt +// (hier Sehnenfehler ≤ 2 mm) → dort relativ 3 %. + +import "../engine/fileioWasm.setup"; +import { describe, expect, it } from "vitest"; +import { spawnSync } from "node:child_process"; +import { existsSync, mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { exportIfcSpf } from "../export/exportIfc"; +import { sampleProject } from "../model/sampleProject"; +import { ceilingVerticalExtent } from "../model/wall"; +import { polygonArea } from "../geometry/roomArea"; +import { pickGeometry } from "../plan/toWalls3d"; +import { wallCutMeshes } from "../plan/wallMeshCut"; +import { formatIfcReport, ifcToImportedMeshes, readIfc, type IfcProduct } from "./ifcImport"; + +function volume(pos: ArrayLike, idx: ArrayLike): number { + let v = 0; + for (let i = 0; i + 2 < idx.length; i += 3) { + const a = idx[i] * 3; + const b = idx[i + 1] * 3; + const c = idx[i + 2] * 3; + v += + (pos[a] * (pos[b + 1] * pos[c + 2] - pos[b + 2] * pos[c + 1]) + + pos[a + 1] * (pos[b + 2] * pos[c] - pos[b] * pos[c + 2]) + + pos[a + 2] * (pos[b] * pos[c + 1] - pos[b + 1] * pos[c])) / + 6; + } + return v; +} +const vol = (p: IfcProduct) => volume(p.positions, p.indices); +const bytesOf = (s: string) => new TextEncoder().encode(s); + +/** Bauteile je IFC-Klasse aus dem Export-Text (Zeilen `#n=IFCWALL(`). */ +function exportedCounts(ifc: string): Map { + const m = new Map(); + for (const cls of ["IFCWALL", "IFCSLAB", "IFCROOF", "IFCDOOR", "IFCWINDOW", "IFCSTAIR", "IFCCOLUMN", "IFCBUILDINGELEMENTPROXY"]) { + const n = (ifc.match(new RegExp(`^#\\d+=${cls}\\(`, "gm")) ?? []).length; + if (n) m.set(cls, n); + } + return m; +} + +const relClose = (a: number, b: number, rel: number) => Math.abs(a - b) <= rel * Math.max(Math.abs(a), Math.abs(b), 1e-9); + +describe("IFC-Import: Rundreise mit dem eigenen Export", () => { + const ifc = exportIfcSpf(sampleProject); + + it("gleiche Bauteilzahl je Klasse, Räume ausgelassen", async () => { + const { products, report } = await readIfc(bytesOf(ifc)); + expect(report.schema).toBe("IFC4"); + expect(report.parseErrors).toBe(0); + expect(report.productsWithoutGeometry).toBe(0); + expect(report.skippedItems).toEqual({}); + const got = new Map(); + for (const p of products) got.set(p.ifcClass.toUpperCase(), (got.get(p.ifcClass.toUpperCase()) ?? 0) + 1); + expect(got).toEqual(exportedCounts(ifc)); + const spaces = (ifc.match(/^#\d+=IFCSPACE\(/gm) ?? []).length; + expect(report.skippedProducts.IfcSpace ?? 0).toBe(spaces); + // Alle Körper geschlossen und aussen orientiert. + for (const p of products) expect(vol(p), `${p.ifcClass} ${p.name}`).toBeGreaterThan(0); + // Geschoss und GlobalId gesetzt. + for (const p of products) { + expect(p.globalId).toMatch(/^[0-9A-Za-z_$]{22}$/); + expect(p.storey).toBeTruthy(); + } + }); + + it("Volumen je Wand = Volumen der Wand-Netze, je Decke = Fläche × Dicke", async () => { + const { products } = await readIfc(bytesOf(ifc)); + // Wände: dieselben Ausschnitt-Netze wie der Export (Bänder je Wand). + const bands = pickGeometry(sampleProject).walls; + const byWall = new Map(); + wallCutMeshes(bands).forEach((m, i) => { + byWall.set(bands[i].wallId, (byWall.get(bands[i].wallId) ?? 0) + Math.abs(volume(m.positions, m.indices))); + }); + const wallsExpected = [...byWall.values()].sort((a, b) => a - b); + const wallsGot = products.filter((p) => p.ifcClass === "IfcWall").map(vol).sort((a, b) => a - b); + expect(wallsGot.length).toBe(wallsExpected.length); + wallsGot.forEach((v, i) => expect(relClose(v, wallsExpected[i], 1e-6), `${v} ≠ ${wallsExpected[i]}`).toBe(true)); + + const slabsExpected = (sampleProject.ceilings ?? []) + .filter((c) => c.outline.length >= 3) + .map((c) => { + const { zBottom, zTop } = ceilingVerticalExtent(sampleProject, c); + return Math.abs(polygonArea(c.outline)) * Math.max(zTop - zBottom, 0.001); + }) + .sort((a, b) => a - b); + const slabsGot = products.filter((p) => p.ifcClass === "IfcSlab").map(vol).sort((a, b) => a - b); + expect(slabsGot.length).toBe(slabsExpected.length); + slabsGot.forEach((v, i) => expect(relClose(v, slabsExpected[i], 1e-6), `${v} ≠ ${slabsExpected[i]}`).toBe(true)); + }); + + it("Kontext-Meshes: je Bauteil, Klasse als Ebene; Rückschub auf den Modell-Nullpunkt bei Georeferenz", async () => { + const { products, report } = await readIfc(bytesOf(ifc)); + const meshes = ifcToImportedMeshes(products, "haus.ifc"); + expect(meshes.length).toBe(products.length); + expect(new Set(meshes.map((m) => m.id)).size).toBe(meshes.length); + expect(meshes.every((m) => m.type === "importedMesh" && m.positions.length >= 9 && m.indices.length >= 3)).toBe(true); + expect(meshes.find((m) => m.layer === "IfcWall")).toBeTruthy(); + const grouped = ifcToImportedMeshes(products, "haus.ifc", { group: "class" }); + expect(grouped.length).toBeLessThan(meshes.length); + expect(grouped.reduce((s, m) => s + m.indices.length, 0)).toBe(meshes.reduce((s, m) => s + m.indices.length, 0)); + // Datei in LV95 (Export mit Standort-Bezug) → zurück auf die lokalen Koordinaten. + const origin = { e: 2_600_000, n: 1_200_000 }; + const shifted = products.map((p) => { + const pos = new Float64Array(p.positions); + for (let i = 0; i < pos.length; i += 3) { + pos[i] += origin.e; + pos[i + 1] += origin.n; + } + return { ...p, positions: pos }; + }); + const back = ifcToImportedMeshes(shifted, "haus.ifc", { geoOrigin: origin }); + expect(back[0].positions[0]).toBeCloseTo(meshes[0].positions[0], 6); + // Ohne Bezug in der Datei (lokal) bleibt alles, auch wenn das Projekt einen hat. + const local = ifcToImportedMeshes(products, "haus.ifc", { geoOrigin: origin }); + expect(local[0].positions[0]).toBeCloseTo(meshes[0].positions[0], 9); + const text = formatIfcReport(report, (k, v) => `${k}${JSON.stringify(v ?? {})}`); + expect(text).toContain("ifc.import.done"); + }); + + it("Unsinn ergibt einen Fehler, keinen Absturz des Moduls", async () => { + await expect(readIfc(new Uint8Array())).rejects.toBeTruthy(); + await expect(readIfc(bytesOf("kein IFC"))).rejects.toBeTruthy(); + const broken = ifc.slice(0, Math.floor(ifc.length / 2)); + const r = await readIfc(bytesOf(broken)); + expect(r.products.length).toBeGreaterThanOrEqual(0); + // Modul lebt noch. + expect((await readIfc(bytesOf(ifc))).products.length).toBeGreaterThan(0); + }); +}); + +// ── Gegencheck mit ifcopenshell (ohne Python/ifcopenshell übersprungen) ───────────────────────── +const hasIfcOpenShell = spawnSync("python3", ["-c", "import ifcopenshell, ifcopenshell.geom, ifcopenshell.util.shape"]).status === 0; + +interface OsProduct { + class: string; + triangles: number; + volume: number; +} +function ifcopenshellProducts(file: string): Record { + const r = spawnSync("python3", ["scripts/ifc-import-compare.py", file], { encoding: "utf8", timeout: 120_000, maxBuffer: 64 << 20 }); + if (r.status !== 0) throw new Error(r.stderr); + return JSON.parse(r.stdout) as Record; +} + +/** Vergleich je GlobalId; liefert Abweichungen als Text (leer = gleich). */ +async function compare(file: string, rel: (p: IfcProduct) => number): Promise { + const ref = ifcopenshellProducts(file); + const { products, report } = await readIfc(new Uint8Array(readFileSync(file))); + // ifcopenshell 0.9 liefert bei manchen Dateien in mm (z. B. buildingSMART + // „wall-with-opening-and-window.ifc", IfcSIUnit MILLI) die Geometrie unskaliert in Dateieinheiten, + // obwohl `convert-back-units` aus ist; unser Import rechnet dort richtig in m (Rust-Test mit mm). + const s3 = report.lengthScale ** 3; + const problems: string[] = []; + const ours = new Map(products.map((p) => [p.globalId, p])); + for (const [gid, o] of Object.entries(ref)) { + const p = ours.get(gid); + if (!p) { + problems.push(`${o.class} ${gid}: fehlt im Import`); + continue; + } + if (p.ifcClass !== o.class) problems.push(`${gid}: Klasse ${p.ifcClass} ≠ ${o.class}`); + const v = Math.abs(vol(p)); + const refV = Math.abs(o.volume); + if (!relClose(v, refV, rel(p)) && !(s3 !== 1 && relClose(v, refV * s3, rel(p)))) problems.push(`${o.class} ${gid}: Volumen ${v} ≠ ${o.volume}`); + } + for (const p of products) if (!(p.globalId in ref)) problems.push(`${p.ifcClass} ${p.globalId}: nur im Import`); + return problems; +} + +describe.skipIf(!hasIfcOpenShell)("IFC-Import gegen ifcopenshell", { timeout: 120_000 }, () => { + it("Demo-Haus: gleiche Bauteile, gleiches Volumen je Bauteil", async () => { + const dir = mkdtempSync(join(tmpdir(), "dossier-ifcimp-")); + const file = join(dir, "demo-haus.ifc"); + writeFileSync(file, exportIfcSpf(sampleProject)); + const problems = await compare(file, () => 1e-6); + expect(problems).toEqual([]); + }); + + it("mit runder Stütze (Kreis-Profil): Volumen bis auf Tessellierung", async () => { + const col = { + id: "S2", type: "column" as const, floorId: "eg", categoryCode: "50", position: { x: 1, y: 1 }, + profile: { kind: "round" as const, radius: 0.15 }, rotation: 0, height: 2.5, + }; + const dir = mkdtempSync(join(tmpdir(), "dossier-ifcimp-")); + const file = join(dir, "stuetze.ifc"); + writeFileSync(file, exportIfcSpf({ ...sampleProject, columns: [col] })); + const problems = await compare(file, (p) => (p.ifcClass === "IfcColumn" ? 0.03 : 1e-6)); + expect(problems).toEqual([]); + }); + + // Freie Beispieldateien (z. B. github.com/buildingSMART/Sample-Test-Files, nicht im Repo, Lizenz + // ungeklärt): DOSSIER_IFC_SAMPLES= setzen. + const samples = process.env.DOSSIER_IFC_SAMPLES; + it.skipIf(!samples || !existsSync(samples))("Beispieldateien aus DOSSIER_IFC_SAMPLES", async () => { + const files: string[] = []; + const walk = (d: string) => { + for (const n of readdirSync(d)) { + const p = join(d, n); + if (statSync(p).isDirectory()) walk(p); + else if (/\.ifc$/i.test(n)) files.push(p); + } + }; + walk(samples!); + const all: string[] = []; + for (const f of files) { + // Gekrümmte Geometrie wird verschieden fein zerlegt → 3 %. + for (const p of await compare(f, () => 0.03)) all.push(`${f}: ${p}`); + } + expect(all).toEqual([]); + }); +}); diff --git a/src/io/ifcImport.ts b/src/io/ifcImport.ts new file mode 100644 index 00000000..425e75b6 --- /dev/null +++ b/src/io/ifcImport.ts @@ -0,0 +1,193 @@ +// IFC-Import als Mesh ([B3]): dünne Fassade über `import_ifc` im Format-Modul (`src-tauri/fileio`, +// `ifc_import.rs`). Jedes IFC-Bauteil mit Körper wird zu einem `ImportedMesh` der Kontext-Schicht +// (wie der STEP-Import, `stepImport.ts`); echte Bauteile (Wand, Decke …) kommen mit [B4]. +// +// Gruppierung: je Bauteil ein Mesh (anwählbar, Name/Geschoss/GlobalId bleiben erhalten, im +// Kontext-Panel nach IFC-Klasse gruppiert über `layer`). Bei sehr vielen Bauteilen (> `MAX_SINGLE`) +// werden Bauteile gleicher Klasse und gleichen Geschosses zusammengelegt, damit Projektdatei und +// Kontext-Panel handhabbar bleiben. +// +// Koordinaten: Meter, Z = Höhe, unverändert aus der Datei — ausser die Datei liegt in +// Landeskoordinaten und das Projekt hat einen Standort-Bezug: dann wird auf den Modell-Nullpunkt +// zurückgeschoben (Gegenstück zu `projectToWorldCoords` beim Export). + +import { loadFileio } from "../engine/fileioWasm"; +import { GENERIC_IMPORT_CATEGORY } from "../model/contextCategories"; +import type { ImportedMesh } from "../model/types"; + +/** Ein gelesenes IFC-Bauteil. */ +export interface IfcProduct { + globalId: string; + /** IFC-Klasse, z. B. `IfcWall`. */ + ifcClass: string; + name: string | null; + storey: string | null; + /** RGBA 0..1 aus IfcStyledItem/Material, falls vorhanden. */ + color: [number, number, number, number] | null; + /** x,y,z in Metern (Z = Höhe). */ + positions: Float64Array; + indices: Uint32Array; +} + +/** Bericht des Imports: was gelesen, was übersprungen wurde. */ +export interface IfcImportReport { + schema: string; + lengthScale: number; + products: number; + /** Übersprungene Geometrie je IFC-Typ (z. B. `IFCSWEPTDISKSOLID`). */ + skippedItems: Record; + /** Bewusst ausgelassene Bauteile je Klasse (Öffnungen, Räume …). */ + skippedProducts: Record; + productsWithoutGeometry: number; + simplifiedBooleans: number; + voidsIgnored: number; + parseErrors: number; + truncated: boolean; +} + +interface RawProduct { + globalId: string; + ifcClass: string; + name: string | null; + storey: string | null; + color: [number, number, number, number] | null; + positionCount: number; + indexCount: number; +} + +/** Liest IFC-Bytes. Wirft bei unlesbarer Datei (Meldung aus Rust). */ +export async function readIfc(bytes: Uint8Array): Promise<{ products: IfcProduct[]; report: IfcImportReport }> { + const m = await loadFileio(); + const r = m.import_ifc(bytes); + try { + const meta = JSON.parse(r.meta) as Omit & { products: RawProduct[] }; + const pos = r.positions(); + const idx = r.indices(); + let po = 0; + let io = 0; + const products: IfcProduct[] = []; + for (const p of meta.products) { + products.push({ + globalId: p.globalId, + ifcClass: p.ifcClass, + name: p.name, + storey: p.storey, + color: p.color, + positions: pos.subarray(po, po + p.positionCount), + indices: idx.subarray(io, io + p.indexCount), + }); + po += p.positionCount; + io += p.indexCount; + } + return { products, report: { ...meta, products: products.length } }; + } finally { + r.free(); + } +} + +/** Ab so vielen Bauteilen wird je Klasse + Geschoss zusammengelegt. */ +export const MAX_SINGLE = 2000; + +export interface IfcToMeshesOptions { + /** LV95-Ursprung des Projekts (`projectGeoOrigin`), sonst null. */ + geoOrigin?: { e: number; n: number } | null; + /** "product" = je Bauteil, "class" = je Klasse + Geschoss, "auto" (Standard) nach `MAX_SINGLE`. */ + group?: "product" | "class" | "auto"; +} + +let counter = 0; + +/** Verschiebung, falls die Datei in Landeskoordinaten liegt und das Projekt einen Bezug hat. */ +function geoShift(products: IfcProduct[], origin: { e: number; n: number } | null | undefined): [number, number] { + if (!origin) return [0, 0]; + let sx = 0; + let sy = 0; + let n = 0; + for (const p of products) { + for (let i = 0; i + 2 < p.positions.length; i += 3 * 64) { + sx += p.positions[i]; + sy += p.positions[i + 1]; + n++; + } + } + if (n === 0) return [0, 0]; + const cx = sx / n; + const cy = sy / n; + const nearOrigin = Math.hypot(cx - origin.e, cy - origin.n) < Math.hypot(cx, cy); + return nearOrigin ? [-origin.e, -origin.n] : [0, 0]; +} + +/** Bauteile → Kontext-Meshes (Kategorie „Situation" wie STEP; `layer` = IFC-Klasse). */ +export function ifcToImportedMeshes(products: IfcProduct[], fileName: string, opts: IfcToMeshesOptions = {}): ImportedMesh[] { + const base = fileName.replace(/\.[^.]+$/, "") || "IFC"; + const [dx, dy] = geoShift(products, opts.geoOrigin); + const stamp = Date.now().toString(36); + const group = opts.group ?? "auto"; + const perProduct = group === "product" || (group === "auto" && products.length <= MAX_SINGLE); + + const toArrays = (parts: IfcProduct[]): { 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]); + } + for (let i = 0; i < p.indices.length; i++) indices.push(p.indices[i] + off); + } + return { positions, indices }; + }; + + if (perProduct) { + return products.map((p) => ({ + id: `imported-ifc-${stamp}-${counter++}`, + type: "importedMesh" as const, + name: [p.storey, p.name || p.ifcClass].filter(Boolean).join(": ") + (p.globalId ? ` [${p.globalId}]` : ""), + layer: p.ifcClass, + categoryCode: GENERIC_IMPORT_CATEGORY.code, + ...toArrays([p]), + })); + } + const groups = new Map(); + for (const p of products) { + const key = `${p.ifcClass}\u0000${p.storey ?? ""}`; + const g = groups.get(key); + if (g) g.push(p); + else groups.set(key, [p]); + } + return [...groups.values()].map((parts) => ({ + id: `imported-ifc-${stamp}-${counter++}`, + type: "importedMesh" as const, + name: `${base}: ${[parts[0].storey, parts[0].ifcClass].filter(Boolean).join(" ")} (${parts.length})`, + layer: parts[0].ifcClass, + categoryCode: GENERIC_IMPORT_CATEGORY.code, + ...toArrays(parts), + })); +} + +/** Datei-Bytes → Kontext-Meshes + Bericht. */ +export async function ifcBytesToImportedMeshes( + bytes: Uint8Array, + fileName: string, + opts: IfcToMeshesOptions = {}, +): Promise<{ meshes: ImportedMesh[]; report: IfcImportReport }> { + const { products, report } = await readIfc(bytes); + return { meshes: ifcToImportedMeshes(products, fileName, opts), report }; +} + +/** Bericht als kurzer Text; `tr` übersetzt (Kern kennt kein i18n, die Hülle reicht `t` herein). */ +export function formatIfcReport( + r: IfcImportReport, + tr: (key: "ifc.import.done" | "ifc.import.skipped" | "ifc.import.voids" | "ifc.import.booleans" | "ifc.import.truncated", vars?: Record) => string, +): string { + const parts = [tr("ifc.import.done", { n: r.products, schema: r.schema || "IFC" })]; + const skipped = Object.entries(r.skippedItems) + .map(([k, v]) => `${k} ×${v}`) + .join(", "); + const without = r.productsWithoutGeometry; + if (skipped || without) parts.push(tr("ifc.import.skipped", { n: without, list: skipped || "–" })); + if (r.voidsIgnored) parts.push(tr("ifc.import.voids", { n: r.voidsIgnored })); + if (r.simplifiedBooleans) parts.push(tr("ifc.import.booleans", { n: r.simplifiedBooleans })); + if (r.truncated) parts.push(tr("ifc.import.truncated")); + return parts.join(" · "); +} diff --git a/src/native/appMenu.ts b/src/native/appMenu.ts index 35f5dd4f..da4b9fa2 100644 --- a/src/native/appMenu.ts +++ b/src/native/appMenu.ts @@ -34,6 +34,7 @@ export interface NativeAppMenuHandlers { onExportStl: () => void; onExportStep: () => void; onImportStep: () => void; + onImportIfc: () => void; onClashCheck: () => void; onKennzahlen: () => void; @@ -174,6 +175,10 @@ export function useNativeAppMenu( text: t("menu.native.importStep"), action: () => handlersRef.current.onImportStep(), }), + await MenuItem.new({ + text: t("menu.native.importIfc"), + action: () => handlersRef.current.onImportIfc(), + }), await Submenu.new({ text: t("menu.native.export"), items: [