From b158b334a243986a65deeeccb40231efb1e2e78d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 11:59:51 +0000 Subject: [PATCH] =?UTF-8?q?[B3]=20IFC-Import:=20=C3=96ffnungen=20abziehen,?= =?UTF-8?q?=20Boolesche=20K=C3=B6rper=20und=20Halbr=C3=A4ume,=20Rotation/S?= =?UTF-8?q?weeps,=20Laden=20im=20Worker?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - csg.rs: BSP-CSG (Verfahren csg.js, MIT, in Rust neu geschrieben: iterativ, Budget, Ursprung verschoben); Vereinigung/Differenz/Schnitt, Unsinn → None statt Panic. NOTICE ergänzt. - ifc_import.rs: IfcRelVoidsElement wird abgezogen (auch Öffnungen am Ganzen, z. B. IfcRoof → Platten); IfcBooleanResult/ClippingResult mit allen drei Operationen, Halbräume (HalfSpace, Boxed, PolygonalBounded auf IfcPlane) als Quader/Prisma um den Wirt; Kurven jetzt räumlich (3D-Bögen, Leitkurven); Ausrundungen bei RoundedRectangle/I/L/U/T; Bericht `voidsApplied`. - ifc_sweep.rs: IfcRevolvedAreaSolid, IfcSweptDiskSolid(+Polygonal), IfcFixedReferenceSweptAreaSolid, IfcSurfaceCurveSweptAreaSolid auf Ebene (Gehrung an Knicken). - ifcImport.ts/.worker.ts: Lesen im Web-Worker (Puffer übertragen), Rückfall im aufrufenden Thread. - Tests: Rust je Fall mit Sollvolumen; Rundreise des [B5]-Exports jetzt mit ausgeschnittenem Volumen für alle Wände; synthetische Testdatei io/testdata/ifc-geometry-cases.ifc, Gegencheck mit ifcopenshell (Skript zieht Öffnungen jetzt ab, stdout-Meldungen umgelenkt); Worker mit Attrappe. Geprüft: npm run check grün, build:cli, CLI import-ifc; gegen ifcopenshell alle 35 buildingSMART-Sample-Test-Files und 39/46 IFC4.3-sample-models (lokal, nicht eingecheckt). Nicht geprüft: Tauri-App/Browser (Worker nur als Attrappe in vitest), macOS. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- NOTICE | 4 + TODO.md | 28 +- scripts/ifc-import-compare.py | 31 +- src-tauri/fileio/src/csg.rs | 486 ++++++++++++++++++ src-tauri/fileio/src/ifc_import.rs | 681 +++++++++++++++++++------ src-tauri/fileio/src/ifc_sweep.rs | 276 ++++++++++ src-tauri/fileio/src/lib.rs | 2 + src/io/ifcImport.test.ts | 118 ++++- src/io/ifcImport.ts | 108 +++- src/io/ifcImport.worker.ts | 15 + src/io/testdata/ifc-geometry-cases.ifc | 84 +++ 11 files changed, 1639 insertions(+), 194 deletions(-) create mode 100644 src-tauri/fileio/src/csg.rs create mode 100644 src-tauri/fileio/src/ifc_sweep.rs create mode 100644 src/io/ifcImport.worker.ts create mode 100644 src/io/testdata/ifc-geometry-cases.ifc diff --git a/NOTICE b/NOTICE index 87513e73..022774cd 100644 --- a/NOTICE +++ b/NOTICE @@ -11,3 +11,7 @@ i_overlay (https://github.com/iShape-Rust/iOverlay), MIT OR Apache-2.0 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. + +csg.js (https://github.com/evanw/csg.js, Datei csg.js), Copyright (c) 2011 Evan Wallace, MIT License + Verfahren (BSP-Bäume, Ebenen-Teilung, clipTo/invert, Vereinigung/Differenz/Schnitt) in Rust neu + geschrieben und angepasst: src-tauri/fileio/src/csg.rs (IFC-Import: Öffnungen, Boolesche Körper). diff --git a/TODO.md b/TODO.md index 395d5efd..9dd72e2d 100644 --- a/TODO.md +++ b/TODO.md @@ -291,7 +291,7 @@ Alle ○: [27] Punktwolken · [28] Phasen · [29] Bauteillisten (◐, Export vor Modelle · [44] Aus Datei einfügen · [45] Favoriten · [68] Gelände mit Baugrube (= [T6]) · [71] U-Werte · [72] Graue Energie KBOB · [73] eBKP-H · [74] SIA 500 · [75] Fluchtwege VKF · [83] Befehlspalette · [84] Undo-Verlauf · [85] Makro-Rekorder · [86] Pipette · [87] Fang mit Begründung · [48] Web-Worker -(◐, nur DXF-Parser) · [52] Icons (◐, `CommandIcon.tsx`) · [56] Startparameter · [89] Git-freundliches +(◐, DXF-Parser, IFC-Import) · [52] Icons (◐, `CommandIcon.tsx`) · [56] Startparameter · [89] Git-freundliches Format · [90] Versionsvergleich · [91] Assistent · [92] Speckle. ## Übernahme aus BIMCraft [B] @@ -313,10 +313,24 @@ Ganzes nicht WASM-tauglich (rayon, tempfile, SystemTime) — nur einzelne Module 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]. + Bauteil). (28.10., 2. Schritt) Öffnungen (IfcRelVoidsElement, auch am Ganzen, z. B. IfcRoof → + Platten) und IfcBooleanResult/ClippingResult (alle drei Operationen, Halbräume IfcHalfSpaceSolid/ + Boxed/PolygonalBounded als Ebenen-Schnitt) über BSP-CSG `fileio/src/csg.rs` (Verfahren csg.js, neu + geschrieben, iterativ, Budget; scheitert er → Öffnung gezählt, Wirt ganz); IfcRevolvedAreaSolid, + IfcSweptDiskSolid(+Polygonal), IfcFixedReferenceSweptAreaSolid, IfcSurfaceCurveSweptAreaSolid auf + Ebene (`ifc_sweep.rs`, Gehrung an Knicken), 3D-Leitkurven inkl. räumlicher Bögen; Ausrundungen bei + RoundedRectangle/I/L/U/T. Laden im Web-Worker (`io/ifcImport.worker.ts`, Rückfall im Thread). + Gegencheck ifcopenshell (Öffnungen jetzt abgezogen): Rundreise (alle Wände ausgeschnitten), + synthetische Fälle `io/testdata/ifc-geometry-cases.ifc`, alle 35 buildingSMART-Sample-Test-Files + und 39 von 46 IFC4.3-sample-models gleich (≤ 3 %; nur lokal, nicht eingecheckt). Offen: + IfcAdvancedBrep (NURBS), IFC4.3-Ausrichtung (IfcGradientCurve, IfcLinearPlacement, + IfcSectionedSolidHorizontal), IfcGridPlacement, B-Spline-Kurven, StartParam/EndParam der Sweeps, + Profil-Kantenradien/Neigungen; Farbe/GlobalId gelesen, aber `ImportedMesh` hat kein Feld dafür + (GlobalId steht im Namen); CSG bei sehr grossen Netzen (> 200 000 Dreiecke) übersprungen; nur + Linux-Container/vitest, nicht in der Tauri-App geprüft (Worker nur mit Attrappe getestet). · M +- ○ **[B4] IFC-Import zu echten Bauteilen** (zweite Stufe von [25]). · L · nach [B3]. Stand 28.10.: + Geometrie-Grundlage steht (Öffnungen/Booleans/Sweeps als Mesh, [B3]); offen: Wand/Decke/Stütze aus + Extrusion + Achse erkennen, Öffnungen als `Opening` statt abgezogen, Material/Typ übernehmen. - ◐ **[B5] IFC-Export nachziehen** (`exportIfc.ts`). Stand 28.10.: - ✅ Nicht-ASCII nach ISO 10303-21 (`\X2\`/`\X4\`). - ✅ Materialschichten: Wand-/Decken-/Dachtypen als IfcWallType/IfcSlabType/IfcRoofType mit @@ -341,8 +355,8 @@ Ganzes nicht WASM-tauglich (rayon, tempfile, SystemTime) — nur einzelne Module Modellfelder (z. B. am Wandtyp tragend/aussen, λ je Bauteil → U-Wert). · S–M - ○ Offen: IfcMaterialLayerSetUsage + Achs-Darstellung („Axis") an Extrusions-Wänden; Tür/Fenster mit Rahmen/Blatt statt Box; Bogenwände als echte Kurve. · M - - ○ Offen: eigener IFC-Import ([B3]) zieht Öffnungen noch nicht ab → Rundreise des eigenen - Exports zeigt Extrusions-Wände ohne Löcher, bis [B4] (Test `ifcImport.test.ts` angepasst). · M + - ✅ Eigener IFC-Import ([B3]) zieht Öffnungen ab (28.10.): Rundreise vergleicht alle Wände mit dem + ausgeschnittenen Volumen (`ifcImport.test.ts`). - ○ Folgepunkt: Export nach Rust (`src-tauri/fileio`, wie der Import) portieren; TS-Fassung `exportIfc.ts` dann löschen. · L - Geprüft nur im Linux-Container (vitest + ifcopenshell 0.9: 0 Befunde, Volumen), nicht in diff --git a/scripts/ifc-import-compare.py b/scripts/ifc-import-compare.py index 197ffcc1..058dea88 100644 --- a/scripts/ifc-import-compare.py +++ b/scripts/ifc-import-compare.py @@ -1,7 +1,7 @@ #!/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 +Aufruf: python3 scripts/ifc-import-compare.py datei.ifc [--no-openings] 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. @@ -9,6 +9,7 @@ Braucht `pip install ifcopenshell` (getestet mit 0.8/0.9). """ import json +import os import sys import ifcopenshell @@ -19,11 +20,27 @@ SKIP = {"IfcOpeningElement", "IfcOpeningStandardCase", "IfcSpace", "IfcAnnotatio def main(path: str) -> int: + # ifcopenshell schreibt bei manchen Dateien Meldungen auf stdout (C++): stdout während des Lesens + # auf stderr umlenken, damit nur das JSON auf stdout landet. + sys.stdout.flush() + real_stdout = os.dup(1) + os.dup2(2, 1) + try: + out = shapes(path) + finally: + sys.stdout.flush() + os.dup2(real_stdout, 1) + os.close(real_stdout) + json.dump(out, sys.stdout) + return 0 + + +def shapes(path: str) -> dict: 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) + # Öffnungen werden abgezogen (wie im Import); `--no-openings` schaltet das ab. + settings.set("disable-opening-subtractions", "--no-openings" in sys.argv) out = {} for product in model.by_type("IfcProduct"): if product.is_a() in SKIP or product.Representation is None: @@ -38,12 +55,12 @@ def main(path: str) -> int: "triangles": len(geom.faces) // 3, "volume": ifcopenshell.util.shape.get_volume(geom), } - json.dump(out, sys.stdout) - return 0 + return out if __name__ == "__main__": - if len(sys.argv) != 2: + files = [a for a in sys.argv[1:] if not a.startswith("--")] + if len(files) != 1: print(__doc__) sys.exit(2) - sys.exit(main(sys.argv[1])) + sys.exit(main(files[0])) diff --git a/src-tauri/fileio/src/csg.rs b/src-tauri/fileio/src/csg.rs new file mode 100644 index 00000000..300f7769 --- /dev/null +++ b/src-tauri/fileio/src/csg.rs @@ -0,0 +1,486 @@ +// Boolesche Operationen auf geschlossenen Dreiecksnetzen über BSP-Bäume ([B3]: IFC-Öffnungen, +// IfcBooleanResult, Halbräume). +// +// Herkunft: Verfahren von csg.js (Evan Wallace, https://github.com/evanw/csg.js, Datei `csg.js`, +// MIT License, Copyright (c) 2011 Evan Wallace) — Ebenen-Teilung der Polygone, BSP-Aufbau, +// `clipTo`/`invert` und die drei Operationen. In Rust neu geschrieben und angepasst: Bäume in einem +// Feld statt rekursiver Knoten, alle Durchläufe iterativ (tiefe Bäume würden im WASM den Stapel +// sprengen), Arbeitsbudget statt unbeschränkter Teilung, Ursprung in die Mitte des ersten Körpers +// geschoben (Landeskoordinaten), Ebenen über die Newell-Normale. Siehe NOTICE. +// +// Eigenschaften: Eingaben müssen geschlossen und aussen orientiert sein; das Ergebnis ist +// geschlossen (mit T-Stössen, für Anzeige und Volumen ohne Belang). Über dem Budget oder bei +// unbrauchbarer Eingabe → `None`, der Aufrufer behält dann den ersten Operanden. + +type V3 = [f64; 3]; + +/// Abstand, ab dem ein Punkt nicht mehr auf einer Ebene liegt (m). +const EPS: f64 = 1e-5; +/// Höchstzahl Polygon-Teilungsschritte je Operation. +const BUDGET: usize = 3_000_000; +/// Höchstzahl Dreiecke je Operand. +const MAX_INPUT_TRIS: usize = 200_000; + +fn sub(a: V3, b: V3) -> V3 { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} +fn dot(a: V3, b: V3) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} +fn lerp(a: V3, b: V3, t: f64) -> V3 { + [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t] +} + +#[derive(Clone, Copy, Debug)] +struct Plane { + n: V3, + w: f64, +} + +impl Plane { + /// Ebene eines (konvexen) Polygons über die Newell-Normale; entartet → `None`. + fn of(pts: &[V3]) -> Option { + let mut n = [0.0; 3]; + for i in 0..pts.len() { + let a = pts[i]; + let b = pts[(i + 1) % pts.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 l = dot(n, n).sqrt(); + // Fläche = l/2; unter ~1e-12 m² ist die Normale nicht verlässlich. + if !(l.is_finite() && l > 2e-12) { + return None; + } + let n = [n[0] / l, n[1] / l, n[2] / l]; + Some(Plane { n, w: dot(n, pts[0]) }) + } + fn flip(&mut self) { + self.n = [-self.n[0], -self.n[1], -self.n[2]]; + self.w = -self.w; + } +} + +#[derive(Clone, Debug)] +struct Poly { + pts: Vec, + plane: Plane, +} + +impl Poly { + fn flip(&mut self) { + self.pts.reverse(); + self.plane.flip(); + } +} + +const COPLANAR: u8 = 0; +const FRONT: u8 = 1; +const BACK: u8 = 2; +const SPANNING: u8 = 3; + +/// Ergebnis einer Teilung an einer Ebene. +#[derive(Default)] +struct Split { + co_front: Vec, + co_back: Vec, + front: Vec, + back: Vec, +} + +/// Teilt `poly` an `plane` (wie `CSG.Plane.splitPolygon`). +fn split(plane: &Plane, poly: Poly, out: &mut Split) { + let mut kind = 0u8; + let types: Vec = poly + .pts + .iter() + .map(|p| { + let t = dot(plane.n, *p) - plane.w; + let k = if t < -EPS { + BACK + } else if t > EPS { + FRONT + } else { + COPLANAR + }; + kind |= k; + k + }) + .collect(); + match kind { + COPLANAR => { + if dot(plane.n, poly.plane.n) > 0.0 { + out.co_front.push(poly); + } else { + out.co_back.push(poly); + } + } + FRONT => out.front.push(poly), + BACK => out.back.push(poly), + _ => { + let n = poly.pts.len(); + let mut f = Vec::with_capacity(n + 1); + let mut b = Vec::with_capacity(n + 1); + for i in 0..n { + let j = (i + 1) % n; + let (ti, tj) = (types[i], types[j]); + let (vi, vj) = (poly.pts[i], poly.pts[j]); + if ti != BACK { + f.push(vi); + } + if ti != FRONT { + b.push(vi); + } + if (ti | tj) == SPANNING { + let den = dot(plane.n, sub(vj, vi)); + let t = if den.abs() > 1e-300 { (plane.w - dot(plane.n, vi)) / den } else { 0.5 }; + let v = lerp(vi, vj, t.clamp(0.0, 1.0)); + f.push(v); + b.push(v); + } + } + if f.len() >= 3 { + out.front.push(Poly { pts: f, plane: poly.plane }); + } + if b.len() >= 3 { + out.back.push(Poly { pts: b, plane: poly.plane }); + } + } + } +} + +#[derive(Default)] +struct Node { + plane: Option, + front: Option, + back: Option, + polys: Vec, +} + +/// BSP-Baum; Knoten 0 ist die Wurzel. +struct Bsp { + nodes: Vec, +} + +struct OutOfBudget; + +fn spend(budget: &mut usize, n: usize) -> Result<(), OutOfBudget> { + *budget = budget.checked_sub(n).ok_or(OutOfBudget)?; + Ok(()) +} + +impl Bsp { + fn new(polys: Vec, budget: &mut usize) -> Result { + let mut b = Bsp { nodes: vec![Node::default()] }; + b.build(polys, budget)?; + Ok(b) + } + + fn child(&mut self, ni: usize, front: bool) -> usize { + let existing = if front { self.nodes[ni].front } else { self.nodes[ni].back }; + if let Some(c) = existing { + return c; + } + let c = self.nodes.len(); + self.nodes.push(Node::default()); + if front { + self.nodes[ni].front = Some(c); + } else { + self.nodes[ni].back = Some(c); + } + c + } + + /// Fügt Polygone ein (`CSG.Node.build`). + fn build(&mut self, polys: Vec, budget: &mut usize) -> Result<(), OutOfBudget> { + let mut stack = vec![(0usize, polys)]; + while let Some((ni, polys)) = stack.pop() { + if polys.is_empty() { + continue; + } + spend(budget, polys.len())?; + let plane = *self.nodes[ni].plane.get_or_insert(polys[0].plane); + let mut s = Split::default(); + for p in polys { + split(&plane, p, &mut s); + } + self.nodes[ni].polys.append(&mut s.co_front); + self.nodes[ni].polys.append(&mut s.co_back); + if !s.front.is_empty() { + let c = self.child(ni, true); + stack.push((c, s.front)); + } + if !s.back.is_empty() { + let c = self.child(ni, false); + stack.push((c, s.back)); + } + } + Ok(()) + } + + /// Entfernt die Teile von `polys`, die in diesem Körper liegen (`CSG.Node.clipPolygons`). + fn clip_polygons(&self, polys: Vec, budget: &mut usize) -> Result, OutOfBudget> { + if self.nodes[0].plane.is_none() { + return Ok(polys); + } + let mut out = Vec::new(); + let mut stack = vec![(0usize, polys)]; + while let Some((ni, polys)) = stack.pop() { + let node = &self.nodes[ni]; + let Some(plane) = node.plane else { + out.extend(polys); + continue; + }; + spend(budget, polys.len())?; + let mut s = Split::default(); + for p in polys { + split(&plane, p, &mut s); + } + let mut front = s.front; + front.append(&mut s.co_front); + let mut back = s.back; + back.append(&mut s.co_back); + match node.front { + Some(c) => stack.push((c, front)), + None => out.extend(front), + } + if let Some(c) = node.back { + stack.push((c, back)); + } + } + Ok(out) + } + + /// Entfernt aus allen Knoten die Teile innerhalb von `other` (`CSG.Node.clipTo`). + fn clip_to(&mut self, other: &Bsp, budget: &mut usize) -> Result<(), OutOfBudget> { + for i in 0..self.nodes.len() { + let ps = std::mem::take(&mut self.nodes[i].polys); + self.nodes[i].polys = other.clip_polygons(ps, budget)?; + } + Ok(()) + } + + /// Innen ↔ aussen (`CSG.Node.invert`). + fn invert(&mut self) { + for n in &mut self.nodes { + for p in &mut n.polys { + p.flip(); + } + if let Some(pl) = &mut n.plane { + pl.flip(); + } + std::mem::swap(&mut n.front, &mut n.back); + } + } + + fn all(&self) -> Vec { + self.nodes.iter().flat_map(|n| n.polys.iter().cloned()).collect() + } +} + +/// Boolesche Operation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Op { + Union, + Difference, + Intersection, +} + +fn bbox(pos: &[f64]) -> Option<(V3, V3)> { + let mut lo = [f64::INFINITY; 3]; + let mut hi = [f64::NEG_INFINITY; 3]; + for c in pos.chunks_exact(3) { + for k in 0..3 { + lo[k] = lo[k].min(c[k]); + hi[k] = hi[k].max(c[k]); + } + } + (lo[0] <= hi[0]).then_some((lo, hi)) +} + +fn to_polys(pos: &[f64], idx: &[u32], shift: V3) -> Vec { + let p = |i: u32| -> Option { + let k = i as usize * 3; + let s = pos.get(k..k + 3)?; + Some([s[0] - shift[0], s[1] - shift[1], s[2] - shift[2]]) + }; + idx.chunks_exact(3) + .filter_map(|t| { + let pts = vec![p(t[0])?, p(t[1])?, p(t[2])?]; + let plane = Plane::of(&pts)?; + Some(Poly { pts, plane }) + }) + .collect() +} + +/// `a op b` für zwei Netze (`positions` flach x,y,z, `indices` je 3). Ergebnis als neues Netz; +/// `None` bei unbrauchbarer Eingabe oder überschrittenem Budget. +pub fn boolean(a_pos: &[f64], a_idx: &[u32], b_pos: &[f64], b_idx: &[u32], op: Op) -> Option<(Vec, Vec)> { + if a_idx.len() / 3 > MAX_INPUT_TRIS || b_idx.len() / 3 > MAX_INPUT_TRIS { + return None; + } + if !a_pos.iter().chain(b_pos.iter()).all(|v| v.is_finite()) { + return None; + } + let (alo, ahi) = bbox(a_pos)?; + let Some((blo, bhi)) = bbox(b_pos) else { + // Leerer zweiter Operand. + return match op { + Op::Union | Op::Difference => Some((a_pos.to_vec(), a_idx.to_vec())), + Op::Intersection => Some((Vec::new(), Vec::new())), + }; + }; + let disjoint = (0..3).any(|k| alo[k] > bhi[k] + EPS || blo[k] > ahi[k] + EPS); + if disjoint { + return match op { + Op::Difference => Some((a_pos.to_vec(), a_idx.to_vec())), + Op::Intersection => Some((Vec::new(), Vec::new())), + Op::Union => { + let base = (a_pos.len() / 3) as u32; + let mut pos = a_pos.to_vec(); + pos.extend_from_slice(b_pos); + let mut idx = a_idx.to_vec(); + idx.extend(b_idx.iter().map(|i| i + base)); + Some((pos, idx)) + } + }; + } + // Ursprung in die Mitte von a: kleine Zahlen auch in Landeskoordinaten. + let shift = [(alo[0] + ahi[0]) / 2.0, (alo[1] + ahi[1]) / 2.0, (alo[2] + ahi[2]) / 2.0]; + let pa = to_polys(a_pos, a_idx, shift); + let pb = to_polys(b_pos, b_idx, shift); + if pa.is_empty() { + return Some((Vec::new(), Vec::new())); + } + let mut budget = BUDGET; + let polys = run(pa, pb, op, &mut budget).ok()?; + let mut pos = Vec::new(); + let mut idx = Vec::new(); + for p in polys { + let base = (pos.len() / 3) as u32; + for v in &p.pts { + pos.extend_from_slice(&[v[0] + shift[0], v[1] + shift[1], v[2] + shift[2]]); + } + for k in 1..p.pts.len() as u32 - 1 { + idx.extend_from_slice(&[base, base + k, base + k + 1]); + } + } + Some((pos, idx)) +} + +fn run(pa: Vec, pb: Vec, op: Op, budget: &mut usize) -> Result, OutOfBudget> { + let mut a = Bsp::new(pa, budget)?; + let mut b = Bsp::new(pb, budget)?; + match op { + Op::Union => { + a.clip_to(&b, budget)?; + b.clip_to(&a, budget)?; + b.invert(); + b.clip_to(&a, budget)?; + b.invert(); + a.build(b.all(), budget)?; + } + Op::Difference => { + a.invert(); + a.clip_to(&b, budget)?; + b.clip_to(&a, budget)?; + b.invert(); + b.clip_to(&a, budget)?; + b.invert(); + a.build(b.all(), budget)?; + a.invert(); + } + Op::Intersection => { + a.invert(); + b.clip_to(&a, budget)?; + b.invert(); + a.clip_to(&b, budget)?; + b.clip_to(&a, budget)?; + a.build(b.all(), budget)?; + a.invert(); + } + } + Ok(a.all()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Quader [lo, hi] als 12 Dreiecke, aussen orientiert. + fn cuboid(lo: V3, hi: V3) -> (Vec, Vec) { + let c = |i: usize| [if i & 1 == 0 { lo[0] } else { hi[0] }, if i & 2 == 0 { lo[1] } else { hi[1] }, if i & 4 == 0 { lo[2] } else { hi[2] }]; + let pos: Vec = (0..8).flat_map(c).collect(); + let quads = [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]]; + let idx = quads.iter().flat_map(|q| [q[0], q[1], q[2], q[0], q[2], q[3]]).collect(); + (pos, idx) + } + fn vol(m: &(Vec, Vec)) -> f64 { + crate::ifc_import::signed_volume(&m.0, &m.1) + } + + #[test] + fn cuboid_helper_is_outward() { + assert!((vol(&cuboid([0.0; 3], [1.0, 2.0, 3.0])) - 6.0).abs() < 1e-12); + } + + #[test] + fn wall_minus_flush_opening() { + // Wand 4 × 0.3 × 3, Öffnung bündig mit beiden Wandflächen und dem Boden: 3.6 − 0.6. + let wall = cuboid([0.0, 0.0, 0.0], [4.0, 0.3, 3.0]); + let open = cuboid([1.0, 0.0, 0.0], [2.0, 0.3, 2.0]); + let r = boolean(&wall.0, &wall.1, &open.0, &open.1, Op::Difference).unwrap(); + assert!((vol(&r) - 3.0).abs() < 1e-9, "{}", vol(&r)); + // Öffnung länger als die Wand dick ist (häufig): gleiches Ergebnis. + let open = cuboid([1.0, -0.1, 0.5], [2.0, 0.4, 2.0]); + let r = boolean(&wall.0, &wall.1, &open.0, &open.1, Op::Difference).unwrap(); + assert!((vol(&r) - (3.6 - 0.3 * 1.5)).abs() < 1e-9, "{}", vol(&r)); + } + + #[test] + fn union_and_intersection_of_overlapping_cuboids() { + let a = cuboid([0.0; 3], [2.0, 2.0, 2.0]); + let b = cuboid([1.0, 1.0, 1.0], [3.0, 3.0, 3.0]); + let u = boolean(&a.0, &a.1, &b.0, &b.1, Op::Union).unwrap(); + assert!((vol(&u) - 15.0).abs() < 1e-9, "{}", vol(&u)); + let i = boolean(&a.0, &a.1, &b.0, &b.1, Op::Intersection).unwrap(); + assert!((vol(&i) - 1.0).abs() < 1e-9, "{}", vol(&i)); + let d = boolean(&a.0, &a.1, &b.0, &b.1, Op::Difference).unwrap(); + assert!((vol(&d) - 7.0).abs() < 1e-9, "{}", vol(&d)); + } + + #[test] + fn far_from_origin_and_disjoint() { + // Landeskoordinaten: Ursprung wird verschoben, Ergebnis bleibt genau. + let o = [2_600_000.0, 1_200_000.0, 500.0]; + let at = |lo: V3, hi: V3| cuboid([lo[0] + o[0], lo[1] + o[1], lo[2] + o[2]], [hi[0] + o[0], hi[1] + o[1], hi[2] + o[2]]); + let wall = at([0.0, 0.0, 0.0], [4.0, 0.3, 3.0]); + let open = at([1.0, -0.1, 0.5], [2.0, 0.4, 2.0]); + let mut r = boolean(&wall.0, &wall.1, &open.0, &open.1, Op::Difference).unwrap(); + // Volumen erst nach Rückschub rechnen (sonst Auslöschung in der Volumenformel selbst). + for c in r.0.chunks_exact_mut(3) { + for k in 0..3 { + c[k] -= o[k]; + } + } + assert!((vol(&r) - 3.15).abs() < 1e-6, "{}", vol(&r)); + let far = cuboid([10.0; 3], [11.0; 3]); + let r = boolean(&wall.0, &wall.1, &far.0, &far.1, Op::Difference).unwrap(); + assert_eq!(r.1.len(), wall.1.len()); + let r = boolean(&wall.0, &wall.1, &far.0, &far.1, Op::Intersection).unwrap(); + assert!(r.1.is_empty()); + } + + #[test] + fn nonsense_gives_none_or_empty() { + let a = cuboid([0.0; 3], [1.0; 3]); + assert!(boolean(&[f64::NAN; 9], &[0, 1, 2], &a.0, &a.1, Op::Difference).is_none()); + assert!(boolean(&[], &[], &a.0, &a.1, Op::Difference).is_none()); + // Kaputte Indizes werden übergangen. + let r = boolean(&a.0, &[0, 1, 99], &a.0, &a.1, Op::Difference); + assert!(r.is_some_and(|r| r.1.is_empty())); + let (r, _) = boolean(&a.0, &a.1, &[], &[], Op::Difference).unwrap(); + assert_eq!(r.len(), a.0.len()); + } +} diff --git a/src-tauri/fileio/src/ifc_import.rs b/src-tauri/fileio/src/ifc_import.rs index 0d7e2d88..e29bc041 100644 --- a/src-tauri/fileio/src/ifc_import.rs +++ b/src-tauri/fileio/src/ifc_import.rs @@ -10,24 +10,31 @@ // - 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), +// IfcBooleanResult/IfcBooleanClippingResult (alle drei Operationen über BSP-CSG `csg.rs`; zweiter +// Operand auch IfcHalfSpaceSolid/IfcBoxedHalfSpace/IfcPolygonalBoundedHalfSpace auf IfcPlane), +// IfcRevolvedAreaSolid, IfcSweptDiskSolid(+Polygonal), IfcFixedReferenceSweptAreaSolid, +// IfcSurfaceCurveSweptAreaSolid auf Ebene (`ifc_sweep.rs`; StartParam/EndParam nicht ausgewertet). +// - Öffnungen: IfcRelVoidsElement — der Körper der IfcOpeningElement wird vom Wirt abgezogen (auch +// vom Teil eines Ganzen, z. B. Platten eines IfcRoof). Scheitert der Boolean → Öffnung gezählt +// und ausgelassen, Wirt bleibt ganz. +// - Profile: Arbitrary(+WithVoids), Rectangle(+Hollow, Rounded), Circle(+Hollow), +// I/L/U/T-Profil (mit Ausrundung, ohne Kantenradien/Neigungen), Derived, Composite. +// - Kurven (2D und räumlich): 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]). +// Übersprungen und gezählt: alles andere (z. B. IfcAdvancedBrep, B-Spline-Kurven, IfcSectionedSpine); +// IfcOpeningElement/IfcSpace/IfcAnnotation/IfcGrid als Bauteile. // // 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::csg; use crate::ifc_step::{self, Entity, StepFile, Value}; +use crate::ifc_sweep::{self, Frame}; /// Höchstzahl Dreiecke über alle Bauteile; darüber wird abgebrochen (`truncated`). pub const MAX_TRIANGLES: usize = 15_000_000; @@ -42,8 +49,8 @@ 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]; +pub(crate) type V2 = [f64; 2]; +pub(crate) type V3 = [f64; 3]; // --------------------------------------------------------------------------- // Vektoren und affine Abbildungen @@ -105,6 +112,27 @@ impl Xf { let t0 = Xf { r: self.r, t: [0.0; 3] }.apply(o.t); Xf { r, t: add(t0, self.t) } } + /// Umkehrabbildung; nicht umkehrbar → `None`. + fn inverse(&self) -> Option { + let d = self.det(); + if !(d.is_finite() && d.abs() > 1e-15) { + return None; + } + let r = &self.r; + let c = |i: usize, j: usize| { + let (i1, i2, j1, j2) = ((i + 1) % 3, (i + 2) % 3, (j + 1) % 3, (j + 2) % 3); + r[j1][i1] * r[j2][i2] - r[j1][i2] * r[j2][i1] + }; + let mut inv = [[0.0; 3]; 3]; + for (i, row) in inv.iter_mut().enumerate() { + for (j, cell) in row.iter_mut().enumerate() { + *cell = c(i, j) / d; + } + } + let m = Xf { r: inv, t: [0.0; 3] }; + let t = m.apply(self.t); + Some(Xf { r: inv, t: scale(t, -1.0) }) + } 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]) @@ -130,9 +158,6 @@ impl Xf2 { 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] - } } // --------------------------------------------------------------------------- @@ -147,21 +172,21 @@ pub struct Mesh { } impl Mesh { - fn vcount(&self) -> u32 { + pub(crate) fn vcount(&self) -> u32 { (self.positions.len() / 3) as u32 } - fn push_v(&mut self, p: V3) -> u32 { + pub(crate) 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) { + pub(crate) 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 { + pub(crate) fn is_empty(&self) -> bool { self.indices.is_empty() } /// Hängt `o` abgebildet mit `xf` an (Spiegelung → Wicklung umkehren). @@ -180,13 +205,26 @@ impl Mesh { } } } - fn flip_all(&mut self) { + pub(crate) fn flip_all(&mut self) { for t in self.indices.chunks_exact_mut(3) { t.swap(1, 2); } } } +/// Achsparalleler Hüllquader eines Netzes. +fn mesh_bbox(m: &Mesh) -> Option<(V3, V3)> { + let mut lo = [f64::INFINITY; 3]; + let mut hi = [f64::NEG_INFINITY; 3]; + for c in m.positions.chunks_exact(3) { + for k in 0..3 { + lo[k] = lo[k].min(c[k]); + hi[k] = hi[k].max(c[k]); + } + } + (lo[0] <= hi[0] && lo.iter().chain(hi.iter()).all(|v| v.is_finite())).then_some((lo, hi)) +} + /// Vorzeichenbehaftetes Volumen (Divergenzsatz); bei geschlossenen, aussen orientierten Netzen > 0. pub fn signed_volume(positions: &[f64], indices: &[u32]) -> f64 { let p = |i: u32| -> V3 { @@ -328,17 +366,13 @@ fn triangulate3d(rings: &[Vec], out: &mut Mesh) { } } -/// 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; - } +/// Profilringe (Ring 0 aussen, weitere Löcher) säubern, ausrichten (aussen gegen, Löcher im +/// Uhrzeigersinn) und in Dreiecke zerlegen; nichts Brauchbares → `None`. +pub(crate) fn prepare_rings(rings: &[Vec]) -> Option<(Vec>, Vec<[usize; 3]>)> { let mut rings: Vec> = rings.iter().map(|r| clean_ring2(r)).filter(|r| r.len() >= 3).collect(); if rings.is_empty() { - return mesh; + return None; } - // 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) { @@ -346,9 +380,16 @@ fn extrude(rings: &[Vec], h: V3) -> Mesh { } } let tris = triangulate2d(&rings); - if tris.is_empty() { + (!tris.is_empty()).then_some((rings, tris)) +} + +/// 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 Some((rings, tris)) = prepare_rings(rings) else { return mesh }; let flat: Vec = rings.iter().flatten().copied().collect(); // Boden (Normale −h) und Deckel (+h). let b0 = mesh.vcount(); @@ -383,7 +424,7 @@ fn extrude(rings: &[Vec], h: V3) -> Mesh { } /// Anzahl Segmente für einen Bogen mit Öffnungswinkel `span` und Radius `r`. -fn arc_segments(span: f64, r: f64) -> usize { +pub(crate) fn arc_segments(span: f64, r: f64) -> usize { let span = span.abs(); if !(span.is_finite() && r.is_finite()) || r <= 0.0 { return 1; @@ -423,9 +464,12 @@ pub struct IfcImport { 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. + /// Boolesche Körper, von denen nur der erste Operand übernommen wurde (Boolean gescheitert oder + /// zweiter Operand unlesbar). pub simplified_booleans: usize, - /// IfcRelVoidsElement — Öffnungen, die nicht abgezogen wurden. + /// Öffnungen (IfcRelVoidsElement), die abgezogen wurden (je Wirt und Öffnung). + pub voids_applied: usize, + /// Öffnungen, die nicht abgezogen werden konnten (ohne Körper, Boolean gescheitert). pub voids_ignored: usize, /// Unlesbare STEP-Anweisungen. pub parse_errors: usize, @@ -629,21 +673,22 @@ impl<'a> Reader<'a> { // ---- 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 in der Profilebene (z der 3D-Kurve verworfen). + fn curve2d(&mut self, v: Option<&Value>, depth: usize) -> Option> { + Some(self.curve(v, depth)?.into_iter().map(|p| [p[0], p[1]]).collect()) } - /// Kurve → Punktfolge (offen; Schlusspunkt kann dem Start entsprechen). - fn curve2d(&mut self, v: Option<&Value>, depth: usize) -> Option> { + /// Kurve → Punktfolge (offen; Schlusspunkt kann dem Start entsprechen); 2D-Kurven mit z = 0. + fn curve(&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()?)), + "IFCPOLYLINE" => Some(e.arg(0)?.as_list()?.iter().filter_map(|v| self.point(Some(v))).take(MAX_LOOP_POINTS).collect()), "IFCINDEXEDPOLYCURVE" => self.indexed_poly_curve(e), "IFCCOMPOSITECURVE" => { - let mut out: Vec = Vec::new(); + 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") { @@ -651,12 +696,12 @@ impl<'a> Reader<'a> { 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)?; + let mut pts = self.curve(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 { + if len(sub(*l, *f)) < 1e-9 { pts.remove(0); } } @@ -667,13 +712,13 @@ impl<'a> Reader<'a> { } Some(out) } - "IFCTRIMMEDCURVE" => self.trimmed_curve(e, depth), + "IFCTRIMMEDCURVE" => self.trimmed_curve(e), "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()]) + pl.apply([rx * t.cos(), ry * t.sin(), 0.0]) }).collect()) } other => { @@ -685,27 +730,19 @@ impl<'a> Reader<'a> { } /// 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, - }; + fn conic(&self, e: &Entity) -> Option<(Xf, f64, f64)> { + let pl = self.axis_placement(e.arg(0)); 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> { + 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 + let coords: Vec = pl .arg(0)? .as_list()? .iter() @@ -714,11 +751,12 @@ impl<'a> Reader<'a> { 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] } + let z = c.get(2).and_then(|v| v.as_f64()).unwrap_or(0.0); + let p = scale([x, y, z], self.len_scale); + if p.iter().all(|v| v.abs() < MAX_COORD) { p } else { [f64::NAN; 3] } }) .collect(); - let at = |i: &Value| -> Option { + let at = |i: &Value| -> Option { let k = i.as_i64()?; (k >= 1).then(|| coords.get(k as usize - 1).copied()).flatten() }; @@ -726,9 +764,9 @@ impl<'a> Reader<'a> { 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) { + let mut out: Vec = Vec::new(); + let push = |out: &mut Vec, p: V3| { + if !out.last().is_some_and(|q| len(sub(*q, p)) < 1e-12) { out.push(p); } }; @@ -756,17 +794,17 @@ impl<'a> Reader<'a> { Some(out) } - fn trimmed_curve(&mut self, e: &Entity, depth: usize) -> Option> { + fn trimmed_curve(&mut self, e: &Entity) -> 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 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]]), + Value::Ref(_) => pt = r.point(Some(t)), _ => {} } } @@ -777,18 +815,12 @@ impl<'a> Reader<'a> { match basis.ty.as_str() { "IFCCIRCLE" | "IFCELLIPSE" => { let (pl, rx, ry) = self.conic(basis)?; + let inv = pl.inverse(); // Winkel: aus Punkt (in Lage-Koordinaten) oder Parameter (Winkeleinheit der Datei). - let det = pl.det(); - let ang = |par: Option, pt: Option| -> Option { + 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 l = inv?.apply(p); + Some((l[1] / ry).atan2(l[0] / 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) } @@ -801,26 +833,21 @@ impl<'a> Reader<'a> { 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()]) + pl.apply([rx * t.cos(), ry * t.sin(), 0.0]) }).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 d = norm(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 at = |t: f64| add(pnt, scale(d, 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; + // Andere Basiskurven (B-Splines, Klothoiden …) nicht unterstützt. let ty = basis.ty.clone(); self.skip(&ty); None @@ -866,7 +893,8 @@ impl<'a> Reader<'a> { "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)])) + let r = if ty == "IFCROUNDEDRECTANGLEPROFILEDEF" { self.length(e.arg(5)).unwrap_or(0.0) } else { 0.0 }; + (w > 0.0 && h > 0.0).then(|| placed(pl, vec![fillet_ring(&rect(w, h), &[r; 4])])) } "IFCRECTANGLEHOLLOWPROFILEDEF" => { let pl = self.placement2d(e.arg(2)); @@ -902,6 +930,9 @@ impl<'a> Reader<'a> { 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], ]; + // Ausrundung Steg/Flansch (FilletRadius) an den vier inneren Ecken. + let fr = self.length(e.arg(7)).unwrap_or(0.0); + let ring = fillet_ring(&ring, &[0.0, 0.0, 0.0, fr, fr, 0.0, 0.0, 0.0, 0.0, fr, fr, 0.0]); (w > 0.0 && d > 0.0 && tw > 0.0 && tf > 0.0).then(|| placed(pl, vec![ring])) } "IFCLSHAPEPROFILEDEF" => { @@ -911,6 +942,8 @@ impl<'a> Reader<'a> { 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]]; + let fr = self.length(e.arg(6)).unwrap_or(0.0); + let ring = fillet_ring(&ring, &[0.0, 0.0, 0.0, fr, 0.0, 0.0]); (w > 0.0 && d > 0.0 && t > 0.0).then(|| placed(pl, vec![ring])) } "IFCUSHAPEPROFILEDEF" => { @@ -918,6 +951,8 @@ impl<'a> Reader<'a> { 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]]; + let fr = self.length(e.arg(7)).unwrap_or(0.0); + let ring = fillet_ring(&ring, &[0.0, 0.0, 0.0, fr, fr, 0.0, 0.0, 0.0]); (d > 0.0 && fw > 0.0).then(|| placed(pl, vec![ring])) } "IFCTSHAPEPROFILEDEF" => { @@ -925,6 +960,8 @@ impl<'a> Reader<'a> { 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]]; + let fr = self.length(e.arg(7)).unwrap_or(0.0); + let ring = fillet_ring(&ring, &[0.0, 0.0, fr, 0.0, 0.0, 0.0, 0.0, fr]); (d > 0.0 && fw > 0.0).then(|| placed(pl, vec![ring])) } "IFCDERIVEDPROFILEDEF" => { @@ -1014,19 +1051,95 @@ impl<'a> Reader<'a> { } } "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); + let op = match e.arg(0).and_then(|v| v.as_enum()) { + Some("UNION") => csg::Op::Union, + Some("INTERSECTION") => csg::Op::Intersection, + _ => csg::Op::Difference, + }; + let mut a = Mesh::default(); + if let Some(id) = e.arg(1).and_then(|v| v.as_ref_id()) { + self.item(id, &mut a, 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); + let b = match e.arg(2).and_then(|v| v.as_ref_id()) { + Some(id) => self.operand(id, &a, depth + 1), + None => Mesh::default(), + }; + if a.is_empty() && op != csg::Op::Union { + return; + } + match csg::boolean(&a.positions, &a.indices, &b.positions, &b.indices, op) { + Some((positions, indices)) if !b.is_empty() => out.append(&Mesh { positions, indices }, &Xf::IDENTITY), + _ => { + // Rückfall: erster Operand (Vereinigung: beide nebeneinander). + out.append(&a, &Xf::IDENTITY); + if op == csg::Op::Union { + out.append(&b, &Xf::IDENTITY); + } else { + self.simplified += 1; + } } + } + } + "IFCREVOLVEDAREASOLID" => { + let Some(areas) = self.profile(e.arg(0), 0) else { return }; + let pos = self.axis_placement(e.arg(1)); + let Some((_, ax)) = self.ent_v(e.arg(2)) else { return }; + let o = self.point(ax.arg(0)).unwrap_or([0.0; 3]); + let Some(d) = self.direction(ax.arg(1)) else { return }; + let Some(angle) = e.arg(3).and_then(|v| v.as_f64()).map(|a| a * self.angle_scale) else { return }; + for rings in &areas { + let m = ifc_sweep::revolve(rings, [o[0], o[1]], [d[0], d[1]], angle); + out.append(&m, &pos); + } + } + "IFCSWEPTDISKSOLID" | "IFCSWEPTDISKSOLIDPOLYGONAL" => { + // StartParam/EndParam und Ausrundungen (Polygonal) werden nicht ausgewertet. + let Some(path) = self.curve(e.arg(0), 0) else { return }; + let Some(r) = self.length(e.arg(1)).filter(|r| *r > 0.0) else { return }; + let n = arc_segments(std::f64::consts::TAU, r).max(24); + let circle = |r: f64| -> Vec { + (0..n).map(|i| { + let t = std::f64::consts::TAU * i as f64 / n as f64; + [r * t.cos(), r * t.sin()] + }).collect() + }; + let mut rings = vec![circle(r)]; + if let Some(ri) = self.length(e.arg(2)).filter(|ri| *ri > 0.0 && *ri < r) { + let mut inner = circle(ri); + inner.reverse(); + rings.push(inner); + } + let m = ifc_sweep::sweep(&rings, &path, Frame::Transport); + out.append(&m, &Xf::IDENTITY); + } + "IFCFIXEDREFERENCESWEPTAREASOLID" | "IFCSURFACECURVESWEPTAREASOLID" => { + // Leitkurve im System von Position; StartParam/EndParam werden nicht ausgewertet. + let Some(areas) = self.profile(e.arg(0), 0) else { return }; + let pos = self.axis_placement(e.arg(1)); + let Some(path) = self.curve(e.arg(2), 0) else { return }; + let frame = if e.ty == "IFCFIXEDREFERENCESWEPTAREASOLID" { + Frame::FixedX(self.direction(e.arg(5)).unwrap_or([1.0, 0.0, 0.0])) } else { - self.simplified += 1; + // Bezugsfläche: nur Ebenen; deren Normale wird Profil-X (Gegencheck ifcopenshell). + match self.ent_v(e.arg(5)) { + Some((_, pl)) if pl.ty == "IFCPLANE" => { + let x = self.axis_placement(pl.arg(0)); + Frame::FixedX([x.r[0][2], x.r[1][2], x.r[2][2]]) + } + Some((_, other)) => { + let ty = other.ty.clone(); + self.skip(&format!("IFCSURFACECURVESWEPTAREASOLID ({ty})")); + return; + } + None => return, + } + }; + for rings in &areas { + let m = ifc_sweep::sweep(rings, &path, frame); + out.append(&m, &pos); } } "IFCCSGSOLID" => { @@ -1051,6 +1164,66 @@ impl<'a> Reader<'a> { } } + /// Zweiter Operand eines Booleschen Körpers: Halbräume als endliche Körper um `host`, sonst das + /// Element selbst (eigene Farbe bleibt unbeachtet). + fn operand(&mut self, id: u64, host: &Mesh, depth: usize) -> Mesh { + let Some(e) = self.ent(id) else { return Mesh::default() }; + match e.ty.as_str() { + "IFCHALFSPACESOLID" | "IFCBOXEDHALFSPACE" | "IFCPOLYGONALBOUNDEDHALFSPACE" => { + if self.budget == 0 || !self.active.insert(id) { + return Mesh::default(); + } + self.budget -= 1; + let m = self.half_space(e, host).unwrap_or_default(); + self.active.remove(&id); + m + } + _ => { + let mut m = Mesh::default(); + self.item(id, &mut m, depth, &mut None); + m + } + } + } + + /// Halbraum (IfcHalfSpaceSolid, IfcBoxedHalfSpace, IfcPolygonalBoundedHalfSpace) als Quader bzw. + /// Prisma, gross genug, um `host` ganz zu überdecken. Nur Ebenen als Grundfläche. + fn half_space(&mut self, e: &Entity, host: &Mesh) -> Option { + let (_, surf) = self.ent_v(e.arg(0))?; + if surf.ty != "IFCPLANE" { + let ty = format!("{} ({})", e.ty, surf.ty); + self.skip(&ty); + return None; + } + let plane = self.axis_placement(surf.arg(0)); + // AgreementFlag .T.: die Normale der Ebene zeigt vom Material weg → Material bei z ≤ 0. + let below = e.arg(1).and_then(|v| v.as_enum()) != Some("F"); + let (lo, hi) = mesh_bbox(host)?; + let c = scale(add(lo, hi), 0.5); + let r = len(sub(hi, lo)) + 1.0; + let lc = plane.inverse()?.apply(c); + let zr = lc[2].abs() + r; + let square = |cx: f64, cy: f64| vec![[cx - r, cy - r], [cx + r, cy - r], [cx + r, cy + r], [cx - r, cy + r]]; + let slab = extrude(&[square(lc[0], lc[1])], [0.0, 0.0, zr]); + let lift = Xf { r: Xf::IDENTITY.r, t: [0.0, 0.0, if below { -zr } else { 0.0 }] }; + let mut half = Mesh::default(); + half.append(&slab, &plane.then_after(&lift)); + if e.ty != "IFCPOLYGONALBOUNDEDHALFSPACE" { + return Some(half); + } + // Prisma der Begrenzung (2D-Kurve in der XY-Ebene von Position) entlang Position-Z. + let pos = self.axis_placement(e.arg(2)); + let boundary = self.curve2d(e.arg(3), 0)?; + let pc = pos.inverse()?.apply(c); + let l = pc[2].abs() + r; + let prism = extrude(&[boundary], [0.0, 0.0, 2.0 * l]); + let shift = Xf { r: Xf::IDENTITY.r, t: [0.0, 0.0, -l] }; + let mut bound = Mesh::default(); + bound.append(&prism, &pos.then_after(&shift)); + let (positions, indices) = csg::boolean(&half.positions, &half.indices, &bound.positions, &bound.indices, csg::Op::Intersection)?; + Some(Mesh { positions, indices }) + } + /// IfcClosedShell/IfcOpenShell/IfcConnectedFaceSet → Flächen. fn shell(&mut self, v: &Value, out: &mut Mesh) { let Some((_, sh)) = self.ent_v(Some(v)) else { return }; @@ -1197,6 +1370,47 @@ impl<'a> Reader<'a> { } } + // ---- Bauteile --------------------------------------------------------------------------- + + /// Körper eines Bauteils in Weltkoordinaten (ohne Öffnungen) und erste Elementfarbe; `None` ohne + /// Körper-Darstellung. Hört nach etwa `max_tris` Dreiecken auf. + fn product_body(&mut self, id: u64, max_tris: usize) -> Option<(Mesh, Option<[f64; 4]>)> { + let f = self.f; + let e = f.get(id)?; + // IfcProduct: Representation (Attribut 7) zeigt auf eine IfcProductDefinitionShape. + let shape = f.get(e.arg(6)?.as_ref_id()?)?; + if shape.ty != "IFCPRODUCTDEFINITIONSHAPE" { + return None; + } + let refs = |v: Option<&Value>| -> Vec { v.and_then(|v| v.as_list()).unwrap_or(&[]).iter().filter_map(|x| x.as_ref_id()).collect() }; + // 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() { + return None; + } + let place = match e.arg(5).and_then(|v| v.as_ref_id()) { + Some(p) => self.object_placement(p, 0), + None => Xf::IDENTITY, + }; + let mut local = Mesh::default(); + let mut color = None; + 'reps: for rep in chosen { + for it in refs(rep.arg(3)) { + self.item(it, &mut local, 0, &mut color); + if local.triangle_count() > max_tris { + break 'reps; + } + } + } + let mut mesh = Mesh::default(); + mesh.append(&local, &place); + Some((mesh, color)) + } + // ---- Farben ---------------------------------------------------------------------------- fn style_color(&self, styles: &[Value], depth: usize) -> Option<[f64; 4]> { @@ -1326,6 +1540,7 @@ pub fn import_ifc(bytes: &[u8]) -> Result { let mut parent: HashMap = HashMap::new(); let mut material_of: HashMap = HashMap::new(); let mut material_color: HashMap = HashMap::new(); + let mut voids: 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]; @@ -1351,7 +1566,11 @@ pub fn import_ifc(bytes: &[u8]) -> Result { } } } - "IFCRELVOIDSELEMENT" => result.voids_ignored += 1, + "IFCRELVOIDSELEMENT" => { + if let (Some(h), Some(o)) = (e.arg(4).and_then(|v| v.as_ref_id()), e.arg(5).and_then(|v| v.as_ref_id())) { + voids.entry(h).or_default().push(o); + } + } "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)) { @@ -1417,10 +1636,8 @@ pub fn import_ifc(bytes: &[u8]) -> Result { 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" { + let has_shape = e.arg(6).and_then(|v| v.as_ref_id()).and_then(|i| f.get(i)).is_some_and(|s| s.ty == "IFCPRODUCTDEFINITIONSHAPE"); + if !has_shape { continue; } if SKIP_CLASSES.contains(&e.ty.as_str()) { @@ -1431,40 +1648,38 @@ pub fn import_ifc(bytes: &[u8]) -> Result { 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() { + let Some((mut mesh, mut color)) = r.product_body(id, MAX_TRIANGLES - total_tris) else { continue }; + if mesh.is_empty() { result.products_without_geometry += 1; continue; } - if total_tris + local.triangle_count() > MAX_TRIANGLES { + if total_tris + mesh.triangle_count() > MAX_TRIANGLES { result.truncated = true; break; } - total_tris += local.triangle_count(); - let mut mesh = Mesh::default(); - mesh.append(&local, &place); + // Öffnungen abziehen: eigene und die des Ganzen, zu dem das Bauteil gehört (IfcRoof → Platten). + let mut host = Some(id); + for _ in 0..4 { + let Some(h) = host else { break }; + for &o in voids.get(&h).map(Vec::as_slice).unwrap_or(&[]) { + let cut = match r.product_body(o, MAX_TRIANGLES) { + Some((om, _)) if !om.is_empty() => csg::boolean(&mesh.positions, &mesh.indices, &om.positions, &om.indices, csg::Op::Difference), + _ => None, + }; + match cut { + Some((positions, indices)) => { + mesh = Mesh { positions, indices }; + result.voids_applied += 1; + } + None => result.voids_ignored += 1, + } + } + host = parent.get(&h).copied(); + } + if mesh.is_empty() { + continue; + } + total_tris += mesh.triangle_count(); if color.is_none() { color = material_of.get(&id).and_then(|m| resolve_material_color(*m)); } @@ -1514,31 +1729,71 @@ 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() { +/// Rundet die Ecken eines Rings mit den Radien `radii` (je Ecke, 0 = scharf). Passt ein Radius nicht +/// (Kanten zu kurz, Ecke gestreckt), bleibt die Ecke scharf. +fn fillet_ring(ring: &[V2], radii: &[f64]) -> Vec { + let n = ring.len(); + let mut out = Vec::with_capacity(n); + for i in 0..n { + let c = ring[i]; + let r = radii.get(i).copied().unwrap_or(0.0); + let (p, q) = (ring[(i + n - 1) % n], ring[(i + 1) % n]); + let u1 = norm([p[0] - c[0], p[1] - c[1], 0.0]); + let u2 = norm([q[0] - c[0], q[1] - c[1], 0.0]); + let (Some(u1), Some(u2)) = (u1, u2) else { + out.push(c); + continue; + }; + let theta = dot(u1, u2).clamp(-1.0, 1.0).acos(); + let t = if theta > 1e-6 && theta < std::f64::consts::PI - 1e-6 { r / (theta / 2.0).tan() } else { f64::INFINITY }; + let lp = len([p[0] - c[0], p[1] - c[1], 0.0]); + let lq = len([q[0] - c[0], q[1] - c[1], 0.0]); + if !(r > 0.0 && r.is_finite() && t.is_finite() && t <= lp / 2.0 + 1e-12 && t <= lq / 2.0 + 1e-12) { + out.push(c); + continue; + } + let Some(bis) = norm(add(u1, u2)) else { + out.push(c); + continue; + }; + let m = r / (theta / 2.0).sin(); + let o = [c[0] + bis[0] * m, c[1] + bis[1] * m]; + let a1 = (c[1] + u1[1] * t - o[1]).atan2(c[0] + u1[0] * t - o[0]); + let a2 = (c[1] + u2[1] * t - o[1]).atan2(c[0] + u2[0] * t - o[0]); + // Kürzerer Bogen von a1 nach a2. + let mut span = (a2 - a1).rem_euclid(std::f64::consts::TAU); + if span > std::f64::consts::PI { + span -= std::f64::consts::TAU; + } + let k = arc_segments(span, r).max(8); // kleine Radien: Sehnen sonst zu grob für die Fläche + for j in 0..=k { + let a = a1 + span * j as f64 / k as f64; + out.push([o[0] + r * a.cos(), o[1] + r * a.sin()]); + } + } + out +} + +/// Bogen durch drei Punkte (Anfang, Zwischenpunkt, Ende) als Punktfolge inkl. Endpunkte, auch räumlich. +fn arc3(p1: V3, p2: V3, p3: V3) -> Vec { + let u = sub(p2, p1); + let w = sub(p3, p1); + let n = cross(u, w); + let nn = dot(n, n); + if !(nn.is_finite() && nn > 1e-24) { 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 }; + // Umkreismittelpunkt; p1 → p2 → p3 läuft gegen den Uhrzeigersinn um n. + let c = add(p1, scale(add(scale(cross(n, u), dot(w, w)), scale(cross(w, n), dot(u, u))), 1.0 / (2.0 * nn))); + let r = len(sub(p1, c)); + let (Some(e1), Some(nz)) = (norm(sub(p1, c)), norm(n)) else { return vec![p1, p2, p3] }; + let e2 = cross(nz, e1); + let d3 = sub(p3, c); + let span = dot(d3, e2).atan2(dot(d3, e1)).rem_euclid(std::f64::consts::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()] + let mut out: Vec = (0..n).map(|i| { + let t = span * i as f64 / n as f64; + add(c, add(scale(e1, r * t.cos()), scale(e2, r * t.sin()))) }).collect(); out.push(p3); out @@ -1606,6 +1861,7 @@ mod web { "skippedProducts": r.skipped_products, "productsWithoutGeometry": r.products_without_geometry, "simplifiedBooleans": r.simplified_booleans, + "voidsApplied": r.voids_applied, "voidsIgnored": r.voids_ignored, "parseErrors": r.parse_errors, "truncated": r.truncated, @@ -1723,6 +1979,28 @@ ENDSEC;\nEND-ISO-10303-21;\n" assert!(close(vol(&p), rect + ishape, 1e-12)); } + #[test] + fn rounded_rectangle_and_i_shape_fillets() { + let pi = std::f64::consts::PI; + let body = "#40=IFCROUNDEDRECTANGLEPROFILEDEF(.AREA.,$,$,1.8,0.6,0.2);#41=IFCEXTRUDEDAREASOLID(#40,#13,#11,1.);\ +#42=IFCISHAPEPROFILEDEF(.AREA.,$,$,0.1,0.2,0.0056,0.0085,0.012,$,$);#43=IFCEXTRUDEDAREASOLID(#42,#13,#11,1.);\ +#44=IFCROUNDEDRECTANGLEPROFILEDEF(.AREA.,$,$,1.,1.,0.9);#45=IFCEXTRUDEDAREASOLID(#44,#13,#11,1.);"; + let (_, p) = one(&file(METRE, body, "#41", "IFCSLAB")); + let want = 1.8 * 0.6 - (4.0 - pi) * 0.04; + assert!((vol(&p) - want).abs() / want < 0.002, "{}", vol(&p)); + let (_, p) = one(&file(METRE, body, "#43", "IFCCOLUMN")); + let want = 2.0 * 0.1 * 0.0085 + (0.2 - 0.017) * 0.0056 + (4.0 - pi) * 0.012f64.powi(2); + assert!((vol(&p) - want).abs() / want < 0.002, "{}", vol(&p)); + // T-Profil (halbes IPE300) mit Ausrundung: zwei Ecken. + let t = "#40=IFCTSHAPEPROFILEDEF(.AREA.,$,$,0.15,0.15,0.0071,0.0107,0.015,$,$,$,$);#41=IFCEXTRUDEDAREASOLID(#40,#13,#11,1.);"; + let (_, p) = one(&file(METRE, t, "#41", "IFCBEAM")); + let want = 0.15 * 0.0107 + (0.15 - 0.0107) * 0.0071 + (4.0 - pi) / 4.0 * 2.0 * 0.015f64.powi(2); + assert!((vol(&p) - want).abs() / want < 0.002, "{}", vol(&p)); + // Radius grösser als die halbe Kante: Ecken bleiben scharf. + let (_, p) = one(&file(METRE, body, "#45", "IFCSLAB")); + assert!(close(vol(&p), 1.0, 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. @@ -1888,17 +2166,115 @@ ENDSEC;\nEND-ISO-10303-21;\n" } #[test] - fn booleans_and_unknown_items_are_counted() { + fn booleans_difference_union_intersection() { + // Würfel 1 m und obere Hälfte versetzt: A − B = 0.75, A ∪ B = 1.75, A ∩ B = 0.25. 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")); +#46=IFCCARTESIANPOINT((0.5,0.,0.5));#47=IFCAXIS2PLACEMENT3D(#46,$,$);#42=IFCEXTRUDEDAREASOLID(#40,#47,#11,1.);\ +#43=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#41,#42);#45=IFCBOOLEANRESULT(.UNION.,#41,#42);#48=IFCBOOLEANRESULT(.INTERSECTION.,#41,#42);\ +#49=IFCBOOLEANRESULT(.DIFFERENCE.,#41,#99);#99=IFCBEZIERCURVE(1,(#10),.UNSPECIFIED.,.F.,.F.);"; + for (it, want) in [("#43", 0.75), ("#45", 1.75), ("#48", 0.25)] { + let (r, p) = one(&file(METRE, body, it, "IFCWALL")); + assert!(close(vol(&p), want, 1e-9), "{it}: {}", vol(&p)); + assert_eq!(r.simplified_booleans, 0); + } + // Unlesbarer zweiter Operand: erster Operand bleibt, gezählt. + let (r, p) = one(&file(METRE, body, "#49", "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)); + } + + #[test] + fn half_spaces_clip_like_a_roof() { + // Wand 4 × 0.3 × 3, oben schräg abgeschnitten: Ebene durch (0,0,2) mit Normale (−1,0,2)/√5, + // Material darunter (.T.) wird abgezogen → bleibt unterhalb: Trapez (2 … 4 hoch). + let body = "#40=IFCCARTESIANPOINT((2.,0.15));#41=IFCAXIS2PLACEMENT2D(#40,$);#42=IFCRECTANGLEPROFILEDEF(.AREA.,$,#41,4.,0.3);\ +#43=IFCEXTRUDEDAREASOLID(#42,#13,#11,5.);\ +#50=IFCCARTESIANPOINT((0.,0.,2.));#51=IFCDIRECTION((-1.,0.,2.));#52=IFCAXIS2PLACEMENT3D(#50,#51,$);#53=IFCPLANE(#52);\ +#54=IFCHALFSPACESOLID(#53,.F.);#55=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#43,#54);\ +#56=IFCHALFSPACESOLID(#53,.T.);#57=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#43,#56);\ +#60=IFCCARTESIANPOINT((0.,0.));#61=IFCCARTESIANPOINT((2.,0.));#62=IFCCARTESIANPOINT((2.,1.));#63=IFCCARTESIANPOINT((0.,1.));\ +#64=IFCPOLYLINE((#60,#61,#62,#63,#60));#65=IFCPOLYGONALBOUNDEDHALFSPACE(#53,.F.,#13,#64);#66=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#43,#65);\ +#67=IFCBOXEDHALFSPACE(#53,.F.,$);#68=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#43,#67);"; + // Unter der Ebene: z ≤ 2 + x/2 → Fläche (2 + 4) / 2 · 4 = 12, mal 0.3. + let (r, p) = one(&file(METRE, body, "#55", "IFCWALL")); + assert!(close(vol(&p), 12.0 * 0.3, 1e-9), "{}", vol(&p)); assert_eq!(r.simplified_booleans, 0); + let (_, p) = one(&file(METRE, body, "#68", "IFCWALL")); + assert!(close(vol(&p), 12.0 * 0.3, 1e-9), "{}", vol(&p)); + // Gegenteil: oberhalb bleibt 20 − 12 = 8. + let (_, p) = one(&file(METRE, body, "#57", "IFCWALL")); + assert!(close(vol(&p), 8.0 * 0.3, 1e-9), "{}", vol(&p)); + // Begrenzt auf x ∈ [0,2]: nur dort abgeschnitten (über 2 + x/2, x ∈ [0,2] → 5·2 − 5 = 5 weg). + let (_, p) = one(&file(METRE, body, "#66", "IFCWALL")); + assert!(close(vol(&p), (20.0 - 5.0) * 0.3, 1e-9), "{}", vol(&p)); + } + + #[test] + fn openings_are_subtracted_from_host_and_aggregate_parts() { + // Wand 4 × 0.3 × 3 mit Öffnung 1 × 2 (eigene Platzierung relativ zur Wand, tiefer als die Wand). + let body = "#40=IFCCARTESIANPOINT((2.,0.15));#41=IFCAXIS2PLACEMENT2D(#40,$);#42=IFCRECTANGLEPROFILEDEF(.AREA.,$,#41,4.,0.3);\ +#43=IFCEXTRUDEDAREASOLID(#42,#13,#11,3.);\ +#500=IFCCARTESIANPOINT((1.,-0.1,0.5));#501=IFCAXIS2PLACEMENT3D(#500,$,$);#502=IFCLOCALPLACEMENT(#30,#501);\ +#503=IFCCARTESIANPOINT((0.5,0.25));#504=IFCAXIS2PLACEMENT2D(#503,$);#505=IFCRECTANGLEPROFILEDEF(.AREA.,$,#504,1.,0.5);\ +#506=IFCEXTRUDEDAREASOLID(#505,#13,#11,2.);#507=IFCSHAPEREPRESENTATION($,'Body','SweptSolid',(#506));\ +#508=IFCPRODUCTDEFINITIONSHAPE($,$,(#507));#509=IFCOPENINGELEMENT('0open',$,'Loch',$,$,#502,#508,$,.OPENING.);"; + let voids = "#510=IFCRELVOIDSELEMENT('0void',$,$,$,#94,#509);"; + let src = file(METRE, &format!("{body}{voids}"), "#43", "IFCWALL"); + let (r, p) = one(&src); + assert!(close(vol(&p), 3.6 - 0.3 * 2.0, 1e-9), "{}", vol(&p)); + assert_eq!((r.voids_applied, r.voids_ignored), (1, 0)); + assert_eq!(r.skipped_products.get("IfcOpeningElement"), Some(&1)); + // Öffnung am Ganzen (IfcRoof ohne eigenen Körper), Bauteil ist Teil davon. + let agg = "#600=IFCROOF('0roof',$,'Dach',$,$,#30,$,$,$);#601=IFCRELAGGREGATES('0ra',$,$,$,#600,(#94));\ +#510=IFCRELVOIDSELEMENT('0void',$,$,$,#600,#509);"; + let (r, p) = one(&file(METRE, &format!("{body}{agg}"), "#43", "IFCSLAB")); + assert!(close(vol(&p), 3.0, 1e-9), "{}", vol(&p)); + assert_eq!(r.voids_applied, 1); + // Öffnung ohne Körper: gezählt, Wirt bleibt ganz. + let none = "#510=IFCRELVOIDSELEMENT('0void',$,$,$,#94,#511);#511=IFCOPENINGELEMENT('0o2',$,$,$,$,#502,$,$,$);"; + let (r, p) = one(&file(METRE, &format!("{body}{none}"), "#43", "IFCWALL")); + assert!(close(vol(&p), 3.6, 1e-9)); + assert_eq!((r.voids_applied, r.voids_ignored), (0, 1)); + } + + #[test] + fn revolved_and_swept_solids() { + let pi = std::f64::consts::PI; + // Rechteck x ∈ [2,3], y ∈ [0,1], 90° um die Profil-y-Achse: Pappus π/2 · 2.5 · 1. + let body = "#40=IFCCARTESIANPOINT((2.5,0.5));#41=IFCAXIS2PLACEMENT2D(#40,$);#42=IFCRECTANGLEPROFILEDEF(.AREA.,$,#41,1.,1.);\ +#43=IFCDIRECTION((0.,1.,0.));#44=IFCAXIS1PLACEMENT(#10,#43);#45=IFCREVOLVEDAREASOLID(#42,#13,#44,1.5707963267948966);\ +#50=IFCCARTESIANPOINT((4.,0.,0.));#51=IFCCARTESIANPOINT((4.,3.,0.));#52=IFCCARTESIANPOINT((4.,3.,2.));\ +#53=IFCPOLYLINE((#10,#50,#51,#52));#54=IFCSWEPTDISKSOLID(#53,0.1,0.05,$,$);\ +#55=IFCRECTANGLEPROFILEDEF(.AREA.,$,$,0.4,0.2);#56=IFCFIXEDREFERENCESWEPTAREASOLID(#55,#13,#53,$,$,#11);\ +#57=IFCPLANE(#13);#58=IFCSURFACECURVESWEPTAREASOLID(#55,#13,#53,$,$,#57);\ +#59=IFCCARTESIANPOINTLIST3D(((0.,0.,0.),(1.,1.,0.),(2.,0.,0.)));#60=IFCINDEXEDPOLYCURVE(#59,(IFCARCINDEX((1,2,3))),$);\ +#61=IFCSWEPTDISKSOLID(#60,0.1,$,$,$);"; + let (r, p) = one(&file(METRE, body, "#45", "IFCMEMBER")); + let want = pi / 2.0 * 2.5; + assert!((vol(&p) - want).abs() / want < 0.01, "{}", vol(&p)); + assert!(r.skipped_items.is_empty(), "{:?}", r.skipped_items); + // Rohr 0.1/0.05 entlang 4 + 3 + 2 m: Kreisring-Fläche (n-Eck, ≥ 24 Ecken) × 9. + let (_, p) = one(&file(METRE, body, "#54", "IFCREINFORCINGBAR")); + let want = pi * (0.01 - 0.0025) * 9.0; + assert!((vol(&p) - want).abs() / want < 0.03, "{}", vol(&p)); + // Rechteck 0.4 × 0.2 entlang derselben Leitkurve: 0.08 × 9. + for it in ["#56", "#58"] { + let (r, p) = one(&file(METRE, body, it, "IFCRAILING")); + assert!(close(vol(&p), 0.08 * 9.0, 1e-9), "{it}: {}", vol(&p)); + assert!(r.skipped_items.is_empty(), "{:?}", r.skipped_items); + } + // Halbkreis-Bogen (Radius 1) als räumliche Leitkurve: Länge π. + let (_, p) = one(&file(METRE, body, "#61", "IFCRAILING")); + let want = pi * 0.01 * pi; + assert!((vol(&p) - want).abs() / want < 0.03, "{}", vol(&p)); + } + + #[test] + fn unknown_items_are_counted() { + let body = "#44=IFCADVANCEDBREP(#45);#45=IFCCLOSEDSHELL(());"; + let r = import_ifc(file(METRE, body, "#44", "IFCWALL").as_bytes()).unwrap(); + assert_eq!(r.skipped_items.get("IFCADVANCEDBREP"), Some(&1)); + assert_eq!(r.products_without_geometry, 1); } #[test] @@ -1970,6 +2346,12 @@ ENDSEC;\nEND-ISO-10303-21;\n" "#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=IFCBOOLEANRESULT(.DIFFERENCE.,#42,#43);#42=IFCBOOLEANRESULT(.DIFFERENCE.,#41,#43);#43=IFCHALFSPACESOLID(#44,.T.);#44=IFCPLANE(#41);", + "#41=IFCBOOLEANRESULT(.DIFFERENCE.,#42,#43);#42=IFCBLOCK(#13,1.,1.,1.);#43=IFCPOLYGONALBOUNDEDHALFSPACE(#44,.T.,#13,#45);#44=IFCPLANE(#13);#45=IFCPOLYLINE((#10,#10));", + "#41=IFCREVOLVEDAREASOLID(#40,#13,#42,1.E300);#40=IFCCIRCLEPROFILEDEF(.AREA.,$,$,1.);#42=IFCAXIS1PLACEMENT(#10,#11);", + "#41=IFCSWEPTDISKSOLID(#42,1.E-9,1.,$,$);#42=IFCPOLYLINE((#10,#10,#21));", + "#41=IFCSWEPTDISKSOLID(#41,1.,$,$,$);", + "#41=IFCSURFACECURVESWEPTAREASOLID(#40,#13,#92,$,$,#41);#40=IFCCIRCLEPROFILEDEF(.AREA.,$,$,1.);", "#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);", @@ -1985,3 +2367,4 @@ ENDSEC;\nEND-ISO-10303-21;\n" assert_eq!(r.products.len(), 1); } } + diff --git a/src-tauri/fileio/src/ifc_sweep.rs b/src-tauri/fileio/src/ifc_sweep.rs new file mode 100644 index 00000000..66e6b6ef --- /dev/null +++ b/src-tauri/fileio/src/ifc_sweep.rs @@ -0,0 +1,276 @@ +// IFC-Import ([B3]): Körper aus Profil-Querschnitten — Rotation (IfcRevolvedAreaSolid) und Sweep +// entlang einer Leitkurve (IfcSweptDiskSolid, IfcFixedReferenceSweptAreaSolid, +// IfcSurfaceCurveSweptAreaSolid). Eigener Code. +// +// Gemeinsamer Kern ist `loft`: dieselben Profilringe (Ring 0 aussen gegen den Uhrzeigersinn, Löcher +// im Uhrzeigersinn, wie bei der Extrusion) werden an `n` Querschnitten in den Raum gesetzt, benachbarte +// Querschnitte mit Vierecken verbunden und Anfang/Ende mit der Profil-Dreieckszerlegung gedeckelt. +// Die Orientierung wird zuletzt über das Volumen geprüft (negativ → umdrehen); so spielt es keine +// Rolle, ob ein Rahmen links- oder rechtshändig ausfällt. +// +// Knicke der Leitkurve werden auf Gehrung geschnitten: der Querschnitt am Knick liegt in der Ebene +// mit der Winkelhalbierenden als Normale, entlang der ankommenden Richtung dorthin verschoben. Das +// Volumen eines Rohrs ist dann Querschnittsfläche × Länge der Leitkurve (wie bei ifcopenshell). + +use crate::ifc_import::{arc_segments, prepare_rings, signed_volume, Mesh, V2, V3}; + +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 norm(a: V3) -> Option { + let l = dot(a, a).sqrt(); + (l > 1e-12 && l.is_finite()).then(|| scale(a, 1.0 / l)) +} +/// Dreht `v` um die Einheitsachse `k` um `phi` (Rodrigues). +fn rotate(v: V3, k: V3, phi: f64) -> V3 { + let (s, c) = phi.sin_cos(); + add(add(scale(v, c), scale(cross(k, v), s)), scale(k, dot(k, v) * (1.0 - c))) +} +/// Irgendeine Einheitsrichtung senkrecht zu `t`. +fn any_perp(t: V3) -> V3 { + let h = if t[0].abs() < 0.9 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] }; + norm(cross(h, t)).unwrap_or([0.0, 0.0, 1.0]) +} + +/// Höchstzahl Querschnitte × Profilpunkte je Körper. +const MAX_LOFT_POINTS: usize = 2_000_000; + +/// Setzt die (vorbereiteten) Ringe an `nsec` Querschnitten ab (`place(i, p)`), verbindet sie und +/// deckelt Anfang und Ende, wenn `caps`. +fn loft(rings: &[Vec], tris: &[[usize; 3]], nsec: usize, place: impl Fn(usize, V2) -> V3, caps: bool) -> Mesh { + let mut mesh = Mesh::default(); + let npts: usize = rings.iter().map(|r| r.len()).sum(); + if nsec < 2 || npts.saturating_mul(nsec) > MAX_LOFT_POINTS { + return mesh; + } + // Mantel: je Profilkante ein Streifen mit eigenen Ecken (scharfe Profilkanten), entlang der + // Leitkurve gemeinsam. + for r in rings { + for e in 0..r.len() { + let (a, b) = (r[e], r[(e + 1) % r.len()]); + let base = mesh.vcount(); + for i in 0..nsec { + mesh.push_v(place(i, a)); + mesh.push_v(place(i, b)); + } + for i in 0..nsec as u32 - 1 { + let (a0, b0, a1, b1) = (base + 2 * i, base + 2 * i + 1, base + 2 * i + 2, base + 2 * i + 3); + mesh.tri(a0, b0, b1); + mesh.tri(a0, b1, a1); + } + } + } + if caps { + let flat: Vec = rings.iter().flatten().copied().collect(); + let s0 = mesh.vcount(); + for p in &flat { + mesh.push_v(place(0, *p)); + } + let s1 = mesh.vcount(); + for p in &flat { + mesh.push_v(place(nsec - 1, *p)); + } + for t in tris { + mesh.tri(s0 + t[0] as u32, s0 + t[2] as u32, s0 + t[1] as u32); + mesh.tri(s1 + t[0] as u32, s1 + t[1] as u32, s1 + t[2] as u32); + } + } + if mesh.positions.iter().any(|v| !v.is_finite()) { + return Mesh::default(); + } + if signed_volume(&mesh.positions, &mesh.indices) < 0.0 { + mesh.flip_all(); + } + mesh +} + +/// Rotationskörper: Profil in der XY-Ebene, gedreht um die Achse durch `o` mit Richtung `d` (beide in +/// der Profilebene) um `angle` (rad, Vorzeichen = Drehsinn um `d`). +pub(crate) fn revolve(rings: &[Vec], o: V2, d: V2, angle: f64) -> Mesh { + let Some(k) = norm([d[0], d[1], 0.0]) else { return Mesh::default() }; + if !(angle.is_finite() && angle.abs() > 1e-9) { + return Mesh::default(); + } + let angle = angle.clamp(-std::f64::consts::TAU, std::f64::consts::TAU); + let Some((rings, tris)) = prepare_rings(rings) else { return Mesh::default() }; + let a = [o[0], o[1], 0.0]; + // Grösster Abstand zur Achse bestimmt die Unterteilung. + let rmax = rings.iter().flatten().map(|p| { + let v = sub([p[0], p[1], 0.0], a); + let r = sub(v, scale(k, dot(v, k))); + dot(r, r).sqrt() + }).fold(0.0, f64::max); + let n = arc_segments(angle, rmax).max(if angle.abs() > 3.0 { 12 } else { 2 }); + let full = (angle.abs() - std::f64::consts::TAU).abs() < 1e-6; + let place = |i: usize, p: V2| -> V3 { + let phi = angle * i as f64 / n as f64; + add(a, rotate(sub([p[0], p[1], 0.0], a), k, phi)) + }; + loft(&rings, &tris, n + 1, place, !full) +} + +/// Rahmen-Vorgabe eines Sweeps. +#[derive(Clone, Copy, Debug)] +pub(crate) enum Frame { + /// Profil-X = Vorgabe senkrecht zur Tangente projiziert (IfcFixedReferenceSweptAreaSolid; bei + /// IfcSurfaceCurveSweptAreaSolid auf einer Ebene deren Normale, wie ifcopenshell). + FixedX(V3), + /// Mitgeführt ohne Verdrehung (IfcSweptDiskSolid: gleichgültig, Kreis). + Transport, +} + +/// Sweep des Profils entlang der Leitkurve `path` (Profil-Z = Tangente). +pub(crate) fn sweep(rings: &[Vec], path: &[V3], frame: Frame) -> Mesh { + let mut pts: Vec = Vec::with_capacity(path.len()); + for p in path { + if !p.iter().all(|v| v.is_finite()) { + continue; + } + if pts.last().is_some_and(|q| dot(sub(*p, *q), sub(*p, *q)) < 1e-18) { + continue; + } + pts.push(*p); + } + if pts.len() < 2 { + return Mesh::default(); + } + let Some((rings, tris)) = prepare_rings(rings) else { return Mesh::default() }; + let n = pts.len(); + let tang: Vec = (0..n - 1).map(|k| norm(sub(pts[k + 1], pts[k])).unwrap_or([0.0, 0.0, 1.0])).collect(); + // Rahmen (X, Y) je Abschnitt, rechtshändig mit T = X × Y. + let mut frames: Vec<(V3, V3)> = Vec::with_capacity(n - 1); + for (k, &t) in tang.iter().enumerate() { + let prev = frames.last().map(|f| f.0); + let proj = |v: V3| norm(sub(v, scale(t, dot(v, t)))); + let x = match frame { + Frame::FixedX(r) => proj(r).or(prev.and_then(proj)).unwrap_or_else(|| any_perp(t)), + Frame::Transport => match prev { + None => any_perp(t), + Some(px) => { + // Kleinste Drehung von der vorigen Tangente auf diese. + let t0 = tang[k - 1]; + let ax = cross(t0, t); + let s = dot(ax, ax).sqrt(); + let rotated = match norm(ax) { + Some(axn) => rotate(px, axn, s.atan2(dot(t0, t))), + None => px, + }; + proj(rotated).unwrap_or_else(|| any_perp(t)) + } + }, + }; + frames.push((x, cross(t, x))); + } + // Querschnitte als (Knoten, Abschnitt): mitgeführte Rahmen passen an jedem Knick zueinander (ein + // Querschnitt je Knoten); feste Rahmen nicht — dort je Abschnitt eigener Anfang und eigenes Ende, + // verbunden durch einen flachen Streifen in der Gehrungsebene (ohne Volumen). + let secs: Vec<(usize, usize)> = match frame { + Frame::Transport => (0..n).map(|i| (i, i.saturating_sub(1))).collect(), + _ => (0..n - 1).flat_map(|k| [(k, k), (k + 1, k)]).collect(), + }; + let place = |s: usize, p: V2| -> V3 { + let (i, k) = secs[s]; + let (x, y) = frames[k]; + let q = add(pts[i], add(scale(x, p[0]), scale(y, p[1]))); + if i == 0 || i == n - 1 { + return q; + } + // Gehrung: entlang der Abschnitts-Tangente in die Halbierungsebene des Knotens schieben. + let t = tang[k]; + let m = norm(add(tang[i - 1], tang[i])).unwrap_or(t); + let c = dot(t, m).max(0.1); + sub(q, scale(t, dot(sub(q, pts[i]), m) / c)) + }; + loft(&rings, &tris, secs.len(), place, true) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn vol(m: &Mesh) -> f64 { + signed_volume(&m.positions, &m.indices) + } + fn square(lo: V2, hi: V2) -> Vec> { + vec![vec![lo, [hi[0], lo[1]], hi, [lo[0], hi[1]]]] + } + fn circle(r: f64, n: usize) -> Vec { + (0..n).map(|i| { + let t = std::f64::consts::TAU * i as f64 / n as f64; + [r * t.cos(), r * t.sin()] + }).collect() + } + + #[test] + fn revolve_full_and_partial() { + // Rechteck x ∈ [2,3], y ∈ [0,1] um die y-Achse: Pappus 2π · 2.5 · 1. + let pi = std::f64::consts::PI; + let full = revolve(&square([2.0, 0.0], [3.0, 1.0]), [0.0, 0.0], [0.0, 1.0], 2.0 * pi); + let want = 2.0 * pi * 2.5; + assert!((vol(&full) - want).abs() / want < 0.01, "{}", vol(&full)); + // Viertel, beide Drehsinne, Deckel geschlossen. + for a in [pi / 2.0, -pi / 2.0] { + let q = revolve(&square([2.0, 0.0], [3.0, 1.0]), [0.0, 0.0], [0.0, 1.0], a); + assert!((vol(&q) - want / 4.0).abs() / (want / 4.0) < 0.01, "{}", vol(&q)); + } + // Profil auf der anderen Seite der Achse und Achse verschoben. + let q = revolve(&square([-3.0, 0.0], [-2.0, 1.0]), [0.0, 5.0], [0.0, -1.0], pi); + assert!((vol(&q) - want / 2.0).abs() / (want / 2.0) < 0.01, "{}", vol(&q)); + assert!(revolve(&square([0.0, 0.0], [1.0, 1.0]), [0.0, 0.0], [0.0, 0.0], 1.0).is_empty()); + assert!(revolve(&square([0.0, 0.0], [1.0, 1.0]), [0.0, 0.0], [0.0, 1.0], f64::NAN).is_empty()); + } + + #[test] + fn sweep_bent_tube_volume_is_area_times_length() { + // Rohr (Kreis 48 Ecken, Polygon-Fläche exakt bekannt) entlang eines räumlichen Polygonzugs. + let n = 48; + let ring = circle(0.05, n); + let area = 0.5 * n as f64 * 0.05f64.powi(2) * (std::f64::consts::TAU / n as f64).sin(); + let path = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [2.0, 3.0, 0.0], [2.0, 3.0, 1.0], [4.0, 5.0, 2.0]]; + let length: f64 = path.windows(2).map(|w| dot(sub(w[1], w[0]), sub(w[1], w[0])).sqrt()).sum(); + for f in [Frame::Transport, Frame::FixedX([0.0, 0.0, 1.0])] { + let m = sweep(&[ring.clone()], &path, f); + assert!((vol(&m) - area * length).abs() < 1e-9, "{f:?}: {} ≠ {}", vol(&m), area * length); + } + // Hohlrohr. + let mut inner = circle(0.03, n); + inner.reverse(); + let ia = 0.5 * n as f64 * 0.03f64.powi(2) * (std::f64::consts::TAU / n as f64).sin(); + let m = sweep(&[ring, inner], &path, Frame::Transport); + assert!((vol(&m) - (area - ia) * length).abs() < 1e-9, "{}", vol(&m)); + } + + #[test] + fn sweep_fixed_reference_orients_profile() { + // Rechteck 0.4 (x) × 0.1 (y) entlang +X, Referenz X = Welt-Z: Profil-x steht senkrecht. + let m = sweep(&square([-0.2, -0.05], [0.2, 0.05]), &[[0.0; 3], [3.0, 0.0, 0.0]], Frame::FixedX([0.0, 0.0, 1.0])); + let zs: Vec = m.positions.chunks_exact(3).map(|c| c[2]).collect(); + let ys: Vec = m.positions.chunks_exact(3).map(|c| c[1]).collect(); + let span = |v: &[f64]| v.iter().cloned().fold(f64::MIN, f64::max) - v.iter().cloned().fold(f64::MAX, f64::min); + assert!((span(&zs) - 0.4).abs() < 1e-12 && (span(&ys) - 0.1).abs() < 1e-12); + assert!((vol(&m) - 0.12).abs() < 1e-12); + } + + #[test] + fn sweep_nonsense_is_empty() { + let r = square([0.0, 0.0], [1.0, 1.0]); + assert!(sweep(&r, &[[0.0; 3]], Frame::Transport).is_empty()); + assert!(sweep(&r, &[[0.0; 3], [0.0; 3], [f64::NAN; 3]], Frame::Transport).is_empty()); + assert!(sweep(&[vec![[0.0, 0.0], [1.0, 1.0]]], &[[0.0; 3], [1.0, 0.0, 0.0]], Frame::Transport).is_empty()); + // Umkehr der Leitkurve (180°): kein Panic, endlich. + let m = sweep(&r, &[[0.0; 3], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0]], Frame::Transport); + assert!(m.positions.iter().all(|v| v.is_finite())); + } +} diff --git a/src-tauri/fileio/src/lib.rs b/src-tauri/fileio/src/lib.rs index 13741fd6..e677cd6e 100644 --- a/src-tauri/fileio/src/lib.rs +++ b/src-tauri/fileio/src/lib.rs @@ -18,6 +18,8 @@ pub mod split; mod web_import; pub mod ifc_step; pub mod ifc_import; +pub mod csg; +mod ifc_sweep; use std::collections::HashMap; use std::io::Cursor; diff --git a/src/io/ifcImport.test.ts b/src/io/ifcImport.test.ts index 11fdd841..0e8a635b 100644 --- a/src/io/ifcImport.test.ts +++ b/src/io/ifcImport.test.ts @@ -7,7 +7,7 @@ // (hier Sehnenfehler ≤ 2 mm) → dort relativ 3 %. import "../engine/fileioWasm.setup"; -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { spawnSync } from "node:child_process"; import { existsSync, mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -18,7 +18,7 @@ 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"; +import { formatIfcReport, handleIfcWorkerRequest, ifcToImportedMeshes, readIfc, type IfcProduct, type IfcWorkerRequest } from "./ifcImport"; function volume(pos: ArrayLike, idx: ArrayLike): number { let v = 0; @@ -73,16 +73,14 @@ describe("IFC-Import: Rundreise mit dem eigenen Export", () => { }); 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). - // [B5]: einfache Wände kommen als ungeschnittene Extrusion + IfcOpeningElement; der Import zieht - // Öffnungen noch nicht ab ([B3] offen) → dort das Volumen der vollen Bänder. + const { products, report } = await readIfc(bytesOf(ifc)); + // Wände: dieselben Ausschnitt-Netze wie der Export (Bänder je Wand). [B5] schreibt einfache Wände als + // ungeschnittene Extrusion + IfcOpeningElement, der Import zieht die Öffnungen ab ([B3]) → bei allen + // Wänden das ausgeschnittene Volumen. const bands = pickGeometry(sampleProject).walls; const cut = new Map(); - const full = new Map(); const add = (m: Map, id: string, v: number) => m.set(id, (m.get(id) ?? 0) + Math.abs(v)); wallCutMeshes(bands).forEach((m, i) => add(cut, bands[i].wallId, volume(m.positions, m.indices))); - wallCutMeshes(bands.map((b) => ({ ...b, holes: [] }))).forEach((m, i) => add(full, bands[i].wallId, volume(m.positions, m.indices))); const lines = new Map(ifc.split("\n").map((l) => [l.slice(0, l.indexOf("=")), l] as const)); const wallsGot = products.filter((p) => p.ifcClass === "IfcWall"); expect(wallsGot.length).toBe(sampleProject.walls.length); @@ -95,10 +93,13 @@ describe("IFC-Import: Rundreise mit dem eigenen Export", () => { const rep = lines.get(/\(\(?(#\d+)\)\);$/.exec(shape)![1])!; const isSwept = rep.includes("'SweptSolid'"); if (isSwept) swept++; - const expected = (isSwept ? full : cut).get(wall.id)!; + const expected = cut.get(wall.id)!; expect(relClose(vol(p), expected, 1e-6), `${wall.id}: ${vol(p)} ≠ ${expected}`).toBe(true); } expect(swept).toBeGreaterThan(0); + expect(report.voidsApplied).toBeGreaterThan(0); + expect(report.voidsIgnored).toBe(0); + expect(report.simplifiedBooleans).toBe(0); const slabsExpected = (sampleProject.ceilings ?? []) .filter((c) => c.outline.length >= 3) @@ -152,6 +153,99 @@ describe("IFC-Import: Rundreise mit dem eigenen Export", () => { }); }); +// Synthetische Fälle (`testdata/ifc-geometry-cases.ifc`, von Hand erzeugt, ein Bauteil je Fall): Wände +// mit Öffnung (tiefer als die Wand bzw. bündig), Halbräume (.T./.F., polygonal begrenzt), Boolean +// UNION/INTERSECTION/DIFFERENCE, Rotation 90°/360°, Rohr (hohl, dünn), Sweep mit fester Referenz und +// auf Ebene, Bogen-Leitkurve. Sollwerte von Hand; ifcopenshell bestätigt sie unten. +const casesFile = new URL("./testdata/ifc-geometry-cases.ifc", import.meta.url); + +describe("IFC-Import: Öffnungen, Boolesche Körper, Rotation, Sweeps", () => { + it("alle Fälle gelesen, Volumen von Hand", async () => { + const { products, report } = await readIfc(new Uint8Array(readFileSync(casesFile))); + expect(report.skippedItems).toEqual({}); + expect(report.simplifiedBooleans).toBe(0); + expect(report.voidsApplied).toBe(2); + expect(report.voidsIgnored).toBe(0); + expect(report.skippedProducts.IfcOpeningElement).toBe(2); + const v = products.map((p) => [p.ifcClass, Math.round(vol(p) * 1e4) / 1e4] as const); + const pi = Math.PI; + const want: Array<[string, number, number]> = [ + ["IfcWall", 3.6 - 0.3 * 2, 1e-6], + ["IfcWall", 3.6 - 0.3 * 2, 1e-6], + ["IfcWall", 8 * 0.3, 1e-6], + ["IfcWall", 12 * 0.3, 1e-6], + ["IfcWall", 15 * 0.3, 1e-6], + ["IfcBuildingElementProxy", 1.75, 1e-6], + ["IfcBuildingElementProxy", 0.25, 1e-6], + ["IfcBuildingElementProxy", 0.75, 1e-6], + ["IfcMember", (pi / 2) * 2.5, 0.01], + ["IfcMember", 2 * pi * 2.5, 0.01], + ["IfcReinforcingBar", pi * (0.01 - 0.0025) * 9, 0.03], + ["IfcReinforcingBar", pi * 0.006 ** 2 * 9, 0.03], + ["IfcRailing", 0.08 * 7.1, 1e-6], + ["IfcRailing", 0.08 * 7.1, 1e-6], + ["IfcRailing", pi * 0.01 * pi, 0.03], + ]; + expect(products.length).toBe(want.length); + want.forEach(([cls, w, rel], i) => { + expect(products[i].ifcClass).toBe(cls); + expect(relClose(vol(products[i]), w, rel), `${i} ${cls}: ${vol(products[i])} ≠ ${w} (${JSON.stringify(v[i])})`).toBe(true); + }); + }); + + describe("Laden im Web-Worker", () => { + afterEach(() => vi.unstubAllGlobals()); + + /** Nachbau eines Workers im selben Thread: gleiche Nachrichten, gleiche Übertragung. */ + class FakeWorker { + static started = 0; + onmessage: ((e: { data: unknown }) => void) | null = null; + onerror: ((e: unknown) => void) | null = null; + constructor(url: URL) { + expect(String(url)).toContain("ifcImport.worker"); + FakeWorker.started++; + } + postMessage(req: IfcWorkerRequest, transfer: Transferable[]) { + expect(transfer).toEqual([req.data]); + void handleIfcWorkerRequest(req).then(({ res, transfer: back }) => { + if (res.type === "result") expect(back).toEqual([res.flat.positions.buffer, res.flat.indices.buffer]); + this.onmessage?.({ data: res }); + }); + } + terminate() {} + } + + it("liest über den Worker, Aufrufer behält seine Bytes; Fehler kommen als Ablehnung zurück", async () => { + vi.stubGlobal("Worker", FakeWorker); + const bytes = new Uint8Array(readFileSync(casesFile)); + const before = FakeWorker.started; + const { products, report } = await readIfc(bytes); + expect(FakeWorker.started).toBe(before + 1); + expect(products.length).toBe(15); + expect(report.voidsApplied).toBe(2); + expect(bytes.byteLength).toBeGreaterThan(0); + await expect(readIfc(bytesOf("kein IFC"))).rejects.toThrow(); + const bad = await handleIfcWorkerRequest({ type: "nonsense" } as unknown as IfcWorkerRequest); + expect(bad.res.type).toBe("error"); + }); + + it("startet der Worker nicht, wird im aufrufenden Thread gelesen", async () => { + vi.stubGlobal( + "Worker", + class { + onerror: ((e: unknown) => void) | null = null; + postMessage() { + setTimeout(() => this.onerror?.(new Error("kein Worker")), 0); + } + terminate() {} + }, + ); + const { products } = await readIfc(new Uint8Array(readFileSync(casesFile))); + expect(products.length).toBe(15); + }); + }); +}); + // ── Gegencheck mit ifcopenshell (ohne Python/ifcopenshell übersprungen) ───────────────────────── const hasIfcOpenShell = spawnSync("python3", ["-c", "import ifcopenshell, ifcopenshell.geom, ifcopenshell.util.shape"]).status === 0; @@ -212,6 +306,12 @@ describe.skipIf(!hasIfcOpenShell)("IFC-Import gegen ifcopenshell", { timeout: 12 expect(problems).toEqual([]); }); + it("synthetische Fälle: Öffnungen, Halbräume, Booleans, Rotation, Sweeps", async () => { + // Rohre/Bögen werden verschieden fein zerlegt → 3 %. + const problems = await compare(casesFile.pathname, () => 0.03); + 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; diff --git a/src/io/ifcImport.ts b/src/io/ifcImport.ts index 425e75b6..a6d71a6a 100644 --- a/src/io/ifcImport.ts +++ b/src/io/ifcImport.ts @@ -7,6 +7,10 @@ // werden Bauteile gleicher Klasse und gleichen Geschosses zusammengelegt, damit Projektdatei und // Kontext-Panel handhabbar bleiben. // +// Lesen im Web-Worker (`ifcImport.worker.ts`), damit grosse Dateien die UI nicht blockieren: zurück +// kommen nur der JSON-Bericht und zwei flache Puffer (übertragen, nicht kopiert). Ohne `Worker` (Node: +// CLI, Tests) oder wenn der Worker nicht startet, wird im aufrufenden Thread gelesen. +// // 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). @@ -40,6 +44,9 @@ export interface IfcImportReport { skippedProducts: Record; productsWithoutGeometry: number; simplifiedBooleans: number; + /** Abgezogene Öffnungen (je Wirt und Öffnung). */ + voidsApplied: number; + /** Öffnungen, die nicht abgezogen werden konnten. */ voidsIgnored: number; parseErrors: number; truncated: boolean; @@ -55,36 +62,93 @@ interface RawProduct { indexCount: number; } -/** Liest IFC-Bytes. Wirft bei unlesbarer Datei (Meldung aus Rust). */ -export async function readIfc(bytes: Uint8Array): Promise<{ products: IfcProduct[]; report: IfcImportReport }> { +/** Rohergebnis aus Rust: Bericht (JSON) und alle Bauteile hintereinander in zwei flachen Puffern. */ +export interface IfcFlat { + meta: string; + positions: Float64Array; + indices: Uint32Array; +} + +/** Worker-Protokoll (`ifcImport.worker.ts`). */ +export type IfcWorkerRequest = { type: "parse"; data: ArrayBuffer }; +export type IfcWorkerResponse = { type: "result"; flat: IfcFlat } | { type: "error"; message: string }; + +/** Liest IFC-Bytes mit dem geladenen Format-Modul (Worker oder aufrufender Thread). */ +export async function importIfcFlat(bytes: Uint8Array): Promise { 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 } }; + return { meta: r.meta, positions: r.positions(), indices: r.indices() }; } finally { r.free(); } } +/** Beantwortet eine Worker-Anfrage; liefert Antwort und zu übertragende Puffer. */ +export async function handleIfcWorkerRequest(req: IfcWorkerRequest): Promise<{ res: IfcWorkerResponse; transfer: Transferable[] }> { + try { + if (req?.type !== "parse" || !(req.data instanceof ArrayBuffer)) throw new Error("ungültige Anfrage"); + const flat = await importIfcFlat(new Uint8Array(req.data)); + return { res: { type: "result", flat }, transfer: [flat.positions.buffer, flat.indices.buffer] }; + } catch (err) { + return { res: { type: "error", message: err instanceof Error ? err.message : String(err) }, transfer: [] }; + } +} + +/** Liest im Web-Worker; `null`, wenn kein Worker verfügbar ist oder er nicht startet. */ +function readInWorker(bytes: Uint8Array): Promise { + if (typeof Worker === "undefined") return Promise.resolve(null); + return new Promise((resolve, reject) => { + let worker: Worker; + try { + worker = new Worker(new URL("./ifcImport.worker.ts", import.meta.url), { type: "module" }); + } catch { + resolve(null); + return; + } + worker.onmessage = (e: MessageEvent) => { + worker.terminate(); + if (e.data?.type === "result") resolve(e.data.flat); + else reject(new Error(e.data?.type === "error" ? e.data.message : "Unerwartete Worker-Antwort")); + }; + worker.onerror = () => { + worker.terminate(); + resolve(null); + }; + // Kopie übertragen: der Aufrufer behält seine Bytes. + const data = bytes.slice().buffer; + worker.postMessage({ type: "parse", data } satisfies IfcWorkerRequest, [data]); + }); +} + +/** Rohergebnis → Bauteile (Ansichten in die flachen Puffer) + Bericht. */ +export function decodeIfc(flat: IfcFlat): { products: IfcProduct[]; report: IfcImportReport } { + const meta = JSON.parse(flat.meta) as Omit & { products: RawProduct[] }; + 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: flat.positions.subarray(po, po + p.positionCount), + indices: flat.indices.subarray(io, io + p.indexCount), + }); + po += p.positionCount; + io += p.indexCount; + } + return { products, report: { ...meta, products: products.length } }; +} + +/** Liest IFC-Bytes (im Worker, sonst direkt). Wirft bei unlesbarer Datei (Meldung aus Rust). */ +export async function readIfc(bytes: Uint8Array): Promise<{ products: IfcProduct[]; report: IfcImportReport }> { + const flat = (await readInWorker(bytes)) ?? (await importIfcFlat(bytes)); + return decodeIfc(flat); +} + /** Ab so vielen Bauteilen wird je Klasse + Geschoss zusammengelegt. */ export const MAX_SINGLE = 2000; diff --git a/src/io/ifcImport.worker.ts b/src/io/ifcImport.worker.ts new file mode 100644 index 00000000..cac1844d --- /dev/null +++ b/src/io/ifcImport.worker.ts @@ -0,0 +1,15 @@ +// Web-Worker für den IFC-Import ([B3]): liest die Datei mit dem Format-Modul (`engine/fileioWasm.ts`) +// AUSSERHALB des Haupt-Threads, damit grosse Modelle die UI nicht einfrieren. Ein Worker je Aufruf, +// danach beendet (s. `ifcImport.ts::readIfc`). +// +// → { type: "parse", data: ArrayBuffer } +// ← { type: "result", flat: { meta, positions, indices } } | { type: "error", message } +// +// Die beiden Puffer werden übertragen, nicht kopiert. + +import { handleIfcWorkerRequest, type IfcWorkerRequest } from "./ifcImport"; + +self.onmessage = async (e: MessageEvent) => { + const { res, transfer } = await handleIfcWorkerRequest(e.data); + (self as unknown as Worker).postMessage(res, transfer); +}; diff --git a/src/io/testdata/ifc-geometry-cases.ifc b/src/io/testdata/ifc-geometry-cases.ifc new file mode 100644 index 00000000..26c8e56e --- /dev/null +++ b/src/io/testdata/ifc-geometry-cases.ifc @@ -0,0 +1,84 @@ +ISO-10303-21; +HEADER; +FILE_DESCRIPTION(('ViewDefinition [CoordinationView]'),'2;1'); +FILE_NAME('t.ifc','2026-10-28T00:00:00',(''),(''),'','',''); +FILE_SCHEMA(('IFC4')); +ENDSEC; +DATA; +#1=IFCPROJECT('0proj000000000000000a1',$,'P',$,$,$,$,(#8),#2); +#2=IFCUNITASSIGNMENT((#3,#4)); +#3=IFCSIUNIT(*,.LENGTHUNIT.,$,.METRE.); +#4=IFCSIUNIT(*,.PLANEANGLEUNIT.,$,.RADIAN.); +#8=IFCGEOMETRICREPRESENTATIONCONTEXT($,'Model',3,1.E-05,#13,$); +#9=IFCGEOMETRICREPRESENTATIONSUBCONTEXT('Body','Model',*,*,*,*,#8,$,.MODEL_VIEW.,$); +#10=IFCCARTESIANPOINT((0.,0.,0.));#11=IFCDIRECTION((0.,0.,1.));#12=IFCDIRECTION((1.,0.,0.)); +#13=IFCAXIS2PLACEMENT3D(#10,$,$);#14=IFCLOCALPLACEMENT($,#13); +#20=IFCBUILDING('0bldg00000000000000001',$,'B',$,$,#14,$,$,.ELEMENT.,$,$,$); +#24=IFCBUILDINGSTOREY('0eg0000000000000000001',$,'EG',$,$,#14,$,$,.ELEMENT.,0.); +#25=IFCRELAGGREGATES('0agg000000000000000001',$,$,$,#20,(#24)); +#26=IFCRELAGGREGATES('0agg000000000000000002',$,$,$,#1,(#20)); +#100101=IFCCARTESIANPOINT((2.,0.15));#100102=IFCAXIS2PLACEMENT2D(#100101,$);#100103=IFCRECTANGLEPROFILEDEF(.AREA.,$,#100102,4.,0.3);#100104=IFCEXTRUDEDAREASOLID(#100103,#13,#11,3.); +#100191=IFCCARTESIANPOINT((10.0,0.,0.));#100192=IFCAXIS2PLACEMENT3D(#100191,$,$);#100190=IFCLOCALPLACEMENT(#14,#100192); +#100193=IFCSHAPEREPRESENTATION(#9,'Body','SweptSolid',(#100104));#100194=IFCPRODUCTDEFINITIONSHAPE($,$,(#100193)); +#100195=IFCWALL('100100wallxxxxxxxxxxxx',$,'T',$,$,#100190,#100194,$,$); +#100301=IFCCARTESIANPOINT((1.,-0.1,0.5));#100302=IFCAXIS2PLACEMENT3D(#100301,$,$);#100303=IFCLOCALPLACEMENT(#100190,#100302);#100304=IFCCARTESIANPOINT((0.5,0.25));#100305=IFCAXIS2PLACEMENT2D(#100304,$);#100306=IFCRECTANGLEPROFILEDEF(.AREA.,$,#100305,1.,0.5);#100307=IFCEXTRUDEDAREASOLID(#100306,#13,#11,2.);#100308=IFCSHAPEREPRESENTATION(#9,'Body','SweptSolid',(#100307));#100309=IFCPRODUCTDEFINITIONSHAPE($,$,(#100308));#100310=IFCOPENINGELEMENT('0open100300xxxxxxxxxxxx',$,'O',$,$,#100303,#100309,$,.OPENING.);#100311=IFCRELVOIDSELEMENT('0void100300xxxxxxxxxxxx',$,$,$,#100195,#100310); +#100401=IFCCARTESIANPOINT((2.,0.15));#100402=IFCAXIS2PLACEMENT2D(#100401,$);#100403=IFCRECTANGLEPROFILEDEF(.AREA.,$,#100402,4.,0.3);#100404=IFCEXTRUDEDAREASOLID(#100403,#13,#11,3.); +#100491=IFCCARTESIANPOINT((20.0,0.,0.));#100492=IFCAXIS2PLACEMENT3D(#100491,$,$);#100490=IFCLOCALPLACEMENT(#14,#100492); +#100493=IFCSHAPEREPRESENTATION(#9,'Body','SweptSolid',(#100404));#100494=IFCPRODUCTDEFINITIONSHAPE($,$,(#100493)); +#100495=IFCWALL('100400wallxxxxxxxxxxxx',$,'T',$,$,#100490,#100494,$,$); +#100601=IFCCARTESIANPOINT((1.,0.0,0.5));#100602=IFCAXIS2PLACEMENT3D(#100601,$,$);#100603=IFCLOCALPLACEMENT(#100490,#100602);#100604=IFCCARTESIANPOINT((0.5,0.15));#100605=IFCAXIS2PLACEMENT2D(#100604,$);#100606=IFCRECTANGLEPROFILEDEF(.AREA.,$,#100605,1.,0.3);#100607=IFCEXTRUDEDAREASOLID(#100606,#13,#11,2.);#100608=IFCSHAPEREPRESENTATION(#9,'Body','SweptSolid',(#100607));#100609=IFCPRODUCTDEFINITIONSHAPE($,$,(#100608));#100610=IFCOPENINGELEMENT('0open100600xxxxxxxxxxxx',$,'O',$,$,#100603,#100609,$,.OPENING.);#100611=IFCRELVOIDSELEMENT('0void100600xxxxxxxxxxxx',$,$,$,#100495,#100610); +#100701=IFCCARTESIANPOINT((2.,0.15));#100702=IFCAXIS2PLACEMENT2D(#100701,$);#100703=IFCRECTANGLEPROFILEDEF(.AREA.,$,#100702,4.,0.3);#100704=IFCEXTRUDEDAREASOLID(#100703,#13,#11,5.);#100750=IFCCARTESIANPOINT((0.,0.,2.));#100751=IFCDIRECTION((-1.,0.,2.));#100752=IFCAXIS2PLACEMENT3D(#100750,#100751,$);#100753=IFCPLANE(#100752);#100754=IFCHALFSPACESOLID(#100753,.T.);#100755=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#100704,#100754); +#100791=IFCCARTESIANPOINT((30.0,0.,0.));#100792=IFCAXIS2PLACEMENT3D(#100791,$,$);#100790=IFCLOCALPLACEMENT(#14,#100792); +#100793=IFCSHAPEREPRESENTATION(#9,'Body','SweptSolid',(#100755));#100794=IFCPRODUCTDEFINITIONSHAPE($,$,(#100793)); +#100795=IFCWALL('100700wallxxxxxxxxxxxx',$,'T',$,$,#100790,#100794,$,$); +#100901=IFCCARTESIANPOINT((2.,0.15));#100902=IFCAXIS2PLACEMENT2D(#100901,$);#100903=IFCRECTANGLEPROFILEDEF(.AREA.,$,#100902,4.,0.3);#100904=IFCEXTRUDEDAREASOLID(#100903,#13,#11,5.);#100950=IFCCARTESIANPOINT((0.,0.,2.));#100951=IFCDIRECTION((-1.,0.,2.));#100952=IFCAXIS2PLACEMENT3D(#100950,#100951,$);#100953=IFCPLANE(#100952);#100954=IFCHALFSPACESOLID(#100953,.F.);#100955=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#100904,#100954); +#100991=IFCCARTESIANPOINT((40.0,0.,0.));#100992=IFCAXIS2PLACEMENT3D(#100991,$,$);#100990=IFCLOCALPLACEMENT(#14,#100992); +#100993=IFCSHAPEREPRESENTATION(#9,'Body','SweptSolid',(#100955));#100994=IFCPRODUCTDEFINITIONSHAPE($,$,(#100993)); +#100995=IFCWALL('100900wallxxxxxxxxxxxx',$,'T',$,$,#100990,#100994,$,$); +#101101=IFCCARTESIANPOINT((2.,0.15));#101102=IFCAXIS2PLACEMENT2D(#101101,$);#101103=IFCRECTANGLEPROFILEDEF(.AREA.,$,#101102,4.,0.3);#101104=IFCEXTRUDEDAREASOLID(#101103,#13,#11,5.);#101150=IFCCARTESIANPOINT((0.,0.,2.));#101151=IFCDIRECTION((-1.,0.,2.));#101152=IFCAXIS2PLACEMENT3D(#101150,#101151,$);#101153=IFCPLANE(#101152);#101160=IFCCARTESIANPOINT((0.,0.));#101161=IFCCARTESIANPOINT((2.,0.));#101162=IFCCARTESIANPOINT((2.,1.));#101163=IFCCARTESIANPOINT((0.,1.));#101164=IFCPOLYLINE((#101160,#101161,#101162,#101163,#101160));#101165=IFCPOLYGONALBOUNDEDHALFSPACE(#101153,.F.,#13,#101164);#101166=IFCBOOLEANCLIPPINGRESULT(.DIFFERENCE.,#101104,#101165); +#101191=IFCCARTESIANPOINT((50.0,0.,0.));#101192=IFCAXIS2PLACEMENT3D(#101191,$,$);#101190=IFCLOCALPLACEMENT(#14,#101192); +#101193=IFCSHAPEREPRESENTATION(#9,'Body','SweptSolid',(#101166));#101194=IFCPRODUCTDEFINITIONSHAPE($,$,(#101193)); +#101195=IFCWALL('101100wallxxxxxxxxxxxx',$,'T',$,$,#101190,#101194,$,$); +#101301=IFCRECTANGLEPROFILEDEF(.AREA.,$,$,1.,1.);#101302=IFCEXTRUDEDAREASOLID(#101301,#13,#11,1.);#101303=IFCCARTESIANPOINT((0.5,0.,0.5));#101304=IFCAXIS2PLACEMENT3D(#101303,$,$);#101305=IFCEXTRUDEDAREASOLID(#101301,#101304,#11,1.);#101306=IFCBOOLEANRESULT(.UNION.,#101302,#101305); +#101391=IFCCARTESIANPOINT((60.0,0.,0.));#101392=IFCAXIS2PLACEMENT3D(#101391,$,$);#101390=IFCLOCALPLACEMENT(#14,#101392); +#101393=IFCSHAPEREPRESENTATION(#9,'Body','SweptSolid',(#101306));#101394=IFCPRODUCTDEFINITIONSHAPE($,$,(#101393)); +#101395=IFCBUILDINGELEMENTPROXY('101300buildingelementp',$,'T',$,$,#101390,#101394,$,$); +#101501=IFCRECTANGLEPROFILEDEF(.AREA.,$,$,1.,1.);#101502=IFCEXTRUDEDAREASOLID(#101501,#13,#11,1.);#101503=IFCCARTESIANPOINT((0.5,0.,0.5));#101504=IFCAXIS2PLACEMENT3D(#101503,$,$);#101505=IFCEXTRUDEDAREASOLID(#101501,#101504,#11,1.);#101506=IFCBOOLEANRESULT(.INTERSECTION.,#101502,#101505); +#101591=IFCCARTESIANPOINT((70.0,0.,0.));#101592=IFCAXIS2PLACEMENT3D(#101591,$,$);#101590=IFCLOCALPLACEMENT(#14,#101592); +#101593=IFCSHAPEREPRESENTATION(#9,'Body','SweptSolid',(#101506));#101594=IFCPRODUCTDEFINITIONSHAPE($,$,(#101593)); +#101595=IFCBUILDINGELEMENTPROXY('101500buildingelementp',$,'T',$,$,#101590,#101594,$,$); +#101701=IFCRECTANGLEPROFILEDEF(.AREA.,$,$,1.,1.);#101702=IFCEXTRUDEDAREASOLID(#101701,#13,#11,1.);#101703=IFCCARTESIANPOINT((0.5,0.,0.5));#101704=IFCAXIS2PLACEMENT3D(#101703,$,$);#101705=IFCEXTRUDEDAREASOLID(#101701,#101704,#11,1.);#101706=IFCBOOLEANRESULT(.DIFFERENCE.,#101702,#101705); +#101791=IFCCARTESIANPOINT((80.0,0.,0.));#101792=IFCAXIS2PLACEMENT3D(#101791,$,$);#101790=IFCLOCALPLACEMENT(#14,#101792); +#101793=IFCSHAPEREPRESENTATION(#9,'Body','SweptSolid',(#101706));#101794=IFCPRODUCTDEFINITIONSHAPE($,$,(#101793)); +#101795=IFCBUILDINGELEMENTPROXY('101700buildingelementp',$,'T',$,$,#101790,#101794,$,$); +#101901=IFCCARTESIANPOINT((2.5,0.5));#101902=IFCAXIS2PLACEMENT2D(#101901,$);#101903=IFCRECTANGLEPROFILEDEF(.AREA.,$,#101902,1.,1.);#101904=IFCDIRECTION((0.,1.,0.));#101905=IFCAXIS1PLACEMENT(#10,#101904);#101906=IFCREVOLVEDAREASOLID(#101903,#13,#101905,1.5707963267948966); +#101991=IFCCARTESIANPOINT((90.0,0.,0.));#101992=IFCAXIS2PLACEMENT3D(#101991,$,$);#101990=IFCLOCALPLACEMENT(#14,#101992); +#101993=IFCSHAPEREPRESENTATION(#9,'Body','SweptSolid',(#101906));#101994=IFCPRODUCTDEFINITIONSHAPE($,$,(#101993)); +#101995=IFCMEMBER('101900memberxxxxxxxxxx',$,'T',$,$,#101990,#101994,$,$); +#102101=IFCCARTESIANPOINT((2.5,0.5));#102102=IFCAXIS2PLACEMENT2D(#102101,$);#102103=IFCRECTANGLEPROFILEDEF(.AREA.,$,#102102,1.,1.);#102104=IFCDIRECTION((0.,1.,0.));#102105=IFCAXIS1PLACEMENT(#10,#102104);#102106=IFCREVOLVEDAREASOLID(#102103,#13,#102105,6.283185307179586); +#102191=IFCCARTESIANPOINT((100.0,0.,0.));#102192=IFCAXIS2PLACEMENT3D(#102191,$,$);#102190=IFCLOCALPLACEMENT(#14,#102192); +#102193=IFCSHAPEREPRESENTATION(#9,'Body','SweptSolid',(#102106));#102194=IFCPRODUCTDEFINITIONSHAPE($,$,(#102193)); +#102195=IFCMEMBER('102100memberxxxxxxxxxx',$,'T',$,$,#102190,#102194,$,$); +#102350=IFCCARTESIANPOINT((4.,0.,0.));#102351=IFCCARTESIANPOINT((4.,3.,0.));#102352=IFCCARTESIANPOINT((4.,3.,2.));#102353=IFCPOLYLINE((#10,#102350,#102351,#102352));#102354=IFCSWEPTDISKSOLID(#102353,0.1,0.05,$,$); +#102391=IFCCARTESIANPOINT((110.0,0.,0.));#102392=IFCAXIS2PLACEMENT3D(#102391,$,$);#102390=IFCLOCALPLACEMENT(#14,#102392); +#102393=IFCSHAPEREPRESENTATION(#9,'Body','SweptSolid',(#102354));#102394=IFCPRODUCTDEFINITIONSHAPE($,$,(#102393)); +#102395=IFCREINFORCINGBAR('102300reinforcingbarxx',$,'T',$,$,#102390,#102394,$,$); +#102550=IFCCARTESIANPOINT((4.,0.,0.));#102551=IFCCARTESIANPOINT((4.,3.,0.));#102552=IFCCARTESIANPOINT((4.,3.,2.));#102553=IFCPOLYLINE((#10,#102550,#102551,#102552));#102554=IFCSWEPTDISKSOLID(#102553,0.006,$,$,$); +#102591=IFCCARTESIANPOINT((120.0,0.,0.));#102592=IFCAXIS2PLACEMENT3D(#102591,$,$);#102590=IFCLOCALPLACEMENT(#14,#102592); +#102593=IFCSHAPEREPRESENTATION(#9,'Body','SweptSolid',(#102554));#102594=IFCPRODUCTDEFINITIONSHAPE($,$,(#102593)); +#102595=IFCREINFORCINGBAR('102500reinforcingbarxx',$,'T',$,$,#102590,#102594,$,$); +#102750=IFCCARTESIANPOINT((4.,0.,0.));#102751=IFCCARTESIANPOINT((4.,3.,0.));#102753=IFCPOLYLINE((#10,#102750,#102751));#102760=IFCCARTESIANPOINT((0.3,0.05));#102761=IFCAXIS2PLACEMENT2D(#102760,$);#102755=IFCRECTANGLEPROFILEDEF(.AREA.,$,#102761,0.4,0.2);#102756=IFCFIXEDREFERENCESWEPTAREASOLID(#102755,#13,#102753,$,$,#11); +#102791=IFCCARTESIANPOINT((130.0,0.,0.));#102792=IFCAXIS2PLACEMENT3D(#102791,$,$);#102790=IFCLOCALPLACEMENT(#14,#102792); +#102793=IFCSHAPEREPRESENTATION(#9,'Body','SweptSolid',(#102756));#102794=IFCPRODUCTDEFINITIONSHAPE($,$,(#102793)); +#102795=IFCRAILING('102700railingxxxxxxxxx',$,'T',$,$,#102790,#102794,$,$); +#102950=IFCCARTESIANPOINT((4.,0.,0.));#102951=IFCCARTESIANPOINT((4.,3.,0.));#102953=IFCPOLYLINE((#10,#102950,#102951));#102960=IFCCARTESIANPOINT((0.3,0.05));#102961=IFCAXIS2PLACEMENT2D(#102960,$);#102955=IFCRECTANGLEPROFILEDEF(.AREA.,$,#102961,0.4,0.2);#102957=IFCPLANE(#13);#102958=IFCSURFACECURVESWEPTAREASOLID(#102955,#13,#102953,$,$,#102957); +#102991=IFCCARTESIANPOINT((140.0,0.,0.));#102992=IFCAXIS2PLACEMENT3D(#102991,$,$);#102990=IFCLOCALPLACEMENT(#14,#102992); +#102993=IFCSHAPEREPRESENTATION(#9,'Body','SweptSolid',(#102958));#102994=IFCPRODUCTDEFINITIONSHAPE($,$,(#102993)); +#102995=IFCRAILING('102900railingxxxxxxxxx',$,'T',$,$,#102990,#102994,$,$); +#103101=IFCCARTESIANPOINTLIST3D(((0.,0.,0.),(1.,1.,0.),(2.,0.,0.)));#103102=IFCINDEXEDPOLYCURVE(#103101,(IFCARCINDEX((1,2,3))),$);#103103=IFCSWEPTDISKSOLID(#103102,0.1,$,$,$); +#103191=IFCCARTESIANPOINT((150.0,0.,0.));#103192=IFCAXIS2PLACEMENT3D(#103191,$,$);#103190=IFCLOCALPLACEMENT(#14,#103192); +#103193=IFCSHAPEREPRESENTATION(#9,'Body','SweptSolid',(#103103));#103194=IFCPRODUCTDEFINITIONSHAPE($,$,(#103193)); +#103195=IFCRAILING('103100railingxxxxxxxxx',$,'T',$,$,#103190,#103194,$,$); +#99=IFCRELCONTAINEDINSPATIALSTRUCTURE('0rel000000000000000001',$,$,$,(#100195,#100495,#100795,#100995,#101195,#101395,#101595,#101795,#101995,#102195,#102395,#102595,#102795,#102995,#103195),#24); +ENDSEC; +END-ISO-10303-21;