diff --git a/TODO.md b/TODO.md index eccbaa30..8a715eb5 100644 --- a/TODO.md +++ b/TODO.md @@ -280,7 +280,7 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]). - ○ **[65] Explosionsaxonometrie.** · S–M - ○ **[66] Präsentationspläne mit einem Klick.** · M - ○ **[67] Skizzenstil.** · M -- ◐ **[25] IFC-Import** → [B3] ✅ (Mesh), [B4] ○. · L +- ◐ **[25] IFC-Import** → [B3] ✅ (Mesh), [B4] ◐ (Bauteile). · L - ◐ **[26] Dächer über beliebige Grundrisse.** `geometry/roofSkeleton.ts` (Walm/Sattel/Mansarde/ Krüppelwalm auf L/T/U, Kehlen, Giebel); Port nach Rust läuft [K2]. Offen: Innenhöfe, schiefwinklige Grundrisse → [B2]. · M @@ -325,12 +325,34 @@ Ganzes nicht WASM-tauglich (rayon, tempfile, SystemTime) — nur einzelne Module 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. + Profil-Kantenradien/Neigungen; 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). + (28.10., 3. Schritt) `ImportedMesh.color` (`#rrggbb` aus Stil/Material) und `ifcGlobalId` gefüllt, + Name ohne GlobalId; Rundreise Speichern/Laden getestet. Offen: Anzeige der Farbe in 3D — + `plan/toWalls3d.ts::emitMeshes` setzt für Kontext-Meshes fest `IMPORTED_RGB`; Vorschlag: dort + `obj.color` (über `hexToRgb`/255) nehmen, falls gesetzt (der Plan zeichnet nur Umrisse in der + Ebenenfarbe). · M +- ◐ **[B4] IFC-Import zu echten Bauteilen** (zweite Stufe von [25]). · L · nach [B3]. Stand 28.10.: + Wahl im Import-Dialog (`ui/IfcImportDialog.tsx`: Kontext-Meshes = Standard | Bauteile), CLI + `import-ifc … --elements`. Erkennung in Rust (`fileio/src/ifc_semantic.rs`, `import_ifc_elements`), + über die Körperform statt den Darstellungstyp: Wand = Rechteck im Grundriss (kleinstes umschliessendes + Rechteck, unten eben, oben ≥ 35 % eben, Volumen 70–100 %), Achse = Mitte, Enden auf die Achse + anstossender Wände gezogen (L/T), Schichten aus IfcMaterialLayerSet(Usage) von Bauteil oder Typ, + Seite der Aussenschicht aus Usage, sonst Schicht-Bändern, sonst „weg vom Geschoss-Schwerpunkt"; + Öffnungen (quaderförmig, durch die ganze Wand) → Tür/Fenster/Wanddurchbruch (sonst bleibt die Wand + Mesh); IfcSlab als senkrechtes Prisma → Decke (Löcher + durchgehende Öffnungen als + Deckenöffnungen, nicht Teil eines Daches); IfcColumn Rechteck/Kreis → Stütze; IfcSpace (Prisma ohne + Loch) → Raum (LongName, SIA 416 aus `CH_Raum`); Geschosse nach Höhe wiederverwendet (±5 mm) oder + angelegt. TS (`io/ifcElements.ts`) ordnet nur zu: Wand-/Deckentyp nach Schichten (Material + Dicke) + wiederverwenden oder anlegen, Materialien nach Namen; Projekt über `setProject` (Ops). Rundreise + Demo-Haus (Export → Import als Bauteile in `emptyProject`): alle 9 Wände (Achse, Richtung, Typ, Höhe, + Geschoss), 3 Öffnungen (Lage, Grösse, Brüstung, Typ), Decke, Raum gleich, keine neuen Typen; + Dach/Treppe bleiben Mesh. buildingSMART Sample-Test-Files (35, lokal): alle lesbar, Ergebnis gültig; + erkannt v. a. Räume, Stützen, `wall-with-opening-and-window` (Wand + Fenster); die Simple-Scene-Wände + sind Giebelwände (bleiben Mesh). Offen: Dächer, Treppen, Träger, schräge/gekrümmte Wände, Wände mit + Profiländerung, Decken aus Dreiecksnetzen mit T-Stössen (zwei Teilflächen → Mesh), Tür-Anschlag/ + Öffnungsrichtung, Tür-/Fenstertyp aus IfcDoorType/IfcWindowType, Farbe der Bauteile; nur Linux- + Container/vitest, nicht in der Tauri-App geprüft (Dialog nur per tsc). - ◐ **[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 diff --git a/src-tauri/fileio/src/ifc_import.rs b/src-tauri/fileio/src/ifc_import.rs index e29bc041..5a6c3eba 100644 --- a/src-tauri/fileio/src/ifc_import.rs +++ b/src-tauri/fileio/src/ifc_import.rs @@ -1,7 +1,8 @@ // IFC-Import als Mesh ([B3], erste Stufe von [25]): liest aus einer IFC-Datei (IFC2x3, IFC4, IFC4.3) // je Bauteil (IfcProduct mit Körper-Darstellung) GlobalId, Klasse, Name, Geschoss, Farbe und // Dreiecke in Metern (Weltkoordinaten der Datei, Z = Höhe). Daraus werden auf der TS-Seite -// importierte Kontext-Meshes (`src/io/ifcImport.ts`); echte Bauteile kommen mit [B4]. +// importierte Kontext-Meshes (`src/io/ifcImport.ts`); echte Bauteile erkennt auf Wunsch +// `ifc_semantic.rs` ([B4], `import_ifc_opts(…, true)`), sie fehlen dann unter den Meshes. // // Eigener Code (nichts aus BIMCraft `import.rs` übernommen; BIMCraft rechnet in mm, hier Meter). // @@ -141,6 +142,14 @@ impl Xf { fn is_finite(&self) -> bool { self.r.iter().flatten().chain(self.t.iter()).all(|v| v.is_finite()) } + /// Ursprung (Verschiebung) der Abbildung. + pub(crate) fn origin(&self) -> V3 { + self.t + } + /// Bildet eine Richtung ab (ohne Verschiebung). + pub(crate) fn apply_dir(&self, v: V3) -> V3 { + Xf { r: self.r, t: [0.0; 3] }.apply(v) + } } /// 2D-Abbildung p' = A·p + t (für Profil-Lagen). @@ -475,6 +484,8 @@ pub struct IfcImport { pub parse_errors: usize, /// Abbruch wegen Dreiecks-Obergrenze. pub truncated: bool, + /// Erkannte Bauteile ([B4]), nur mit [`import_ifc_opts`]`(…, true)`. + pub elements: Option, } /// Bauteilklassen, die als Mesh keinen Sinn ergeben (Volumen-Hilfskörper, Beschriftung). @@ -497,9 +508,9 @@ const NON_BODY_REPS: &[&str] = &[ // Leser // --------------------------------------------------------------------------- -struct Reader<'a> { - f: &'a StepFile, - len_scale: f64, +pub(crate) struct Reader<'a> { + pub(crate) f: &'a StepFile, + pub(crate) len_scale: f64, angle_scale: f64, placements: HashMap, item_colors: HashMap, @@ -593,7 +604,7 @@ impl<'a> Reader<'a> { } /// Objekt-Platzierung in Weltkoordinaten (IfcLocalPlacement-Kette, zwischengespeichert). - fn object_placement(&mut self, id: u64, depth: usize) -> Xf { + pub(crate) fn object_placement(&mut self, id: u64, depth: usize) -> Xf { if let Some(x) = self.placements.get(&id) { return *x; } @@ -1372,9 +1383,9 @@ 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]>)> { + /// Platzierung und Körper-Elemente (ids der Darstellungselemente) eines Bauteils; `None` ohne + /// Körper-Darstellung. + fn body_items(&mut self, id: u64) -> Option<(Xf, Vec)> { let f = self.f; let e = f.get(id)?; // IfcProduct: Representation (Attribut 7) zeigt auf eine IfcProductDefinitionShape. @@ -1396,14 +1407,19 @@ impl<'a> Reader<'a> { Some(p) => self.object_placement(p, 0), None => Xf::IDENTITY, }; + Some((place, chosen.iter().flat_map(|rep| refs(rep.arg(3))).collect())) + } + + /// Körper eines Bauteils in Weltkoordinaten (ohne Öffnungen) und erste Elementfarbe; `None` ohne + /// Körper-Darstellung. Hört nach etwa `max_tris` Dreiecken auf. + pub(crate) fn product_body(&mut self, id: u64, max_tris: usize) -> Option<(Mesh, Option<[f64; 4]>)> { + let (place, items) = self.body_items(id)?; 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; - } + for it in items { + self.item(it, &mut local, 0, &mut color); + if local.triangle_count() > max_tris { + break; } } let mut mesh = Mesh::default(); @@ -1411,6 +1427,27 @@ impl<'a> Reader<'a> { Some((mesh, color)) } + /// Wie [`Self::product_body`], aber je Darstellungselement ein eigenes Netz (Weltkoordinaten) — + /// für den Bauteil-Import ([B4]), der z. B. die Schicht-Bänder einer Wand einzeln braucht. + pub(crate) fn product_item_meshes(&mut self, id: u64, max_tris: usize) -> Vec { + let Some((place, items)) = self.body_items(id) else { return Vec::new() }; + let mut out = Vec::new(); + let mut total = 0; + for it in items { + let mut local = Mesh::default(); + let mut color = None; + self.item(it, &mut local, 0, &mut color); + total += local.triangle_count(); + let mut mesh = Mesh::default(); + mesh.append(&local, &place); + out.push(mesh); + if total > max_tris { + break; + } + } + out + } + // ---- Farben ---------------------------------------------------------------------------- fn style_color(&self, styles: &[Value], depth: usize) -> Option<[f64; 4]> { @@ -1509,8 +1546,128 @@ fn units(f: &StepFile, ids: &[u64]) -> (f64, f64) { (len_scale, angle_scale) } +/// Beziehungen der Datei, die Mesh- und Bauteil-Import ([B4]) brauchen. +#[derive(Default)] +pub(crate) struct Rels { + /// Bauteil → räumliche Struktur (IfcRelContainedInSpatialStructure). + pub container: HashMap, + /// Teil → Ganzes (IfcRelAggregates). + pub parent: HashMap, + /// Objekt (auch Typ) → Material (IfcRelAssociatesMaterial). + pub material_of: HashMap, + /// Material → Farbe (IfcMaterialDefinitionRepresentation). + pub material_color: HashMap, + /// Wirt → Öffnungen (IfcRelVoidsElement). + pub voids: HashMap>, +} + +impl Rels { + /// Material (auch Schichten/Profile/Bestandteile/Listen) → Farbe des ersten Materials. + pub(crate) fn resolve_material_color(&self, f: &StepFile, mut m: u64) -> Option<[f64; 4]> { + for _ in 0..6 { + if let Some(c) = self.material_color.get(&m) { + return Some(*c); + } + let e = f.get(m)?; + let next = match e.ty.as_str() { + "IFCMATERIALLAYERSETUSAGE" | "IFCMATERIALPROFILESETUSAGE" | "IFCMATERIALPROFILESETUSAGETAPERING" => e.arg(0), + "IFCMATERIALLAYERSET" | "IFCMATERIALLIST" => e.arg(0).and_then(|v| v.as_list()).and_then(|l| l.first()), + "IFCMATERIALPROFILESET" | "IFCMATERIALCONSTITUENTSET" => e.arg(2).and_then(|v| v.as_list()).and_then(|l| l.first()), + "IFCMATERIALLAYER" => e.arg(0), + "IFCMATERIALPROFILE" | "IFCMATERIALCONSTITUENT" => e.arg(2), + _ => None, + }; + m = next?.as_ref_id()?; + } + None + } + + /// Geschoss (IfcBuildingStorey-id) eines Bauteils: Enthaltensein, sonst aufwärts über Aggregation. + pub(crate) fn storey_id(&self, f: &StepFile, mut id: u64) -> Option { + for _ in 0..32 { + let e = f.get(id)?; + if e.ty == "IFCBUILDINGSTOREY" { + return Some(id); + } + id = match self.container.get(&id) { + Some(s) => *s, + None => *self.parent.get(&id)?, + }; + } + None + } + + fn gather(f: &StepFile, ids: &[u64], r: &mut Reader) -> Rels { + let mut rels = Rels::default(); + let refs = |v: Option<&Value>| -> Vec { v.and_then(|v| v.as_list()).unwrap_or(&[]).iter().filter_map(|x| x.as_ref_id()).collect() }; + for &id in ids { + let e = &f.entities[&id]; + match e.ty.as_str() { + "IFCRELCONTAINEDINSPATIALSTRUCTURE" => { + if let Some(s) = e.arg(5).and_then(|v| v.as_ref_id()) { + for el in refs(e.arg(4)) { + rels.container.entry(el).or_insert(s); + } + } + } + "IFCRELAGGREGATES" => { + if let Some(p) = e.arg(4).and_then(|v| v.as_ref_id()) { + for c in refs(e.arg(5)) { + rels.parent.entry(c).or_insert(p); + } + } + } + "IFCRELASSOCIATESMATERIAL" => { + if let Some(m) = e.arg(5).and_then(|v| v.as_ref_id()) { + for o in refs(e.arg(4)) { + rels.material_of.entry(o).or_insert(m); + } + } + } + "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())) { + rels.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)) { + r.item_colors.entry(item).or_insert(c); + } + } + } + "IFCMATERIALDEFINITIONREPRESENTATION" => { + if let Some(m) = e.arg(3).and_then(|v| v.as_ref_id()) { + 'reps: for rep in refs(e.arg(2)) { + for it in refs(f.get(rep).and_then(|x| x.arg(3))) { + let Some(si) = f.get(it) else { continue }; + if si.ty != "IFCSTYLEDITEM" { + continue; + } + if let Some(c) = si.arg(1).and_then(|v| v.as_list()).and_then(|l| r.style_color(l, 0)) { + rels.material_color.entry(m).or_insert(c); + break 'reps; + } + } + } + } + } + _ => {} + } + } + rels + } +} + /// Liest eine IFC-Datei als Meshes je Bauteil. pub fn import_ifc(bytes: &[u8]) -> Result { + import_ifc_opts(bytes, false) +} + +/// Wie [`import_ifc`]; mit `elements` werden zusätzlich echte Bauteile erkannt ([B4], +/// `ifc_semantic.rs`): Wände, Decken, Stützen, Türen/Fenster in Wandöffnungen, Räume, Geschosse. +/// Erkannte Bauteile (und ihre Türen/Fenster) fehlen dann in `products`. +pub fn import_ifc_opts(bytes: &[u8], elements: bool) -> Result { let f = ifc_step::parse(bytes)?; if !f.schema.is_empty() && !f.schema.starts_with("IFC") { return Err(format!("kein IFC-Schema: {}", f.schema)); @@ -1536,108 +1693,26 @@ pub fn import_ifc(bytes: &[u8]) -> Result { let mut result = IfcImport { schema: f.schema.clone(), length_scale: len_scale, parse_errors: f.errors, ..Default::default() }; // Beziehungen: Geschoss-Zugehörigkeit, Aggregation, Material, Farben. - let mut container: HashMap = HashMap::new(); - let mut parent: HashMap = HashMap::new(); - let mut material_of: HashMap = HashMap::new(); - let mut material_color: HashMap = HashMap::new(); - let 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]; - match e.ty.as_str() { - "IFCRELCONTAINEDINSPATIALSTRUCTURE" => { - if let Some(s) = e.arg(5).and_then(|v| v.as_ref_id()) { - for el in refs(e.arg(4)) { - container.entry(el).or_insert(s); - } - } - } - "IFCRELAGGREGATES" => { - if let Some(p) = e.arg(4).and_then(|v| v.as_ref_id()) { - for c in refs(e.arg(5)) { - parent.entry(c).or_insert(p); - } - } - } - "IFCRELASSOCIATESMATERIAL" => { - if let Some(m) = e.arg(5).and_then(|v| v.as_ref_id()) { - for o in refs(e.arg(4)) { - material_of.entry(o).or_insert(m); - } - } - } - "IFCRELVOIDSELEMENT" => { - 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)) { - r.item_colors.entry(item).or_insert(c); - } - } - } - "IFCMATERIALDEFINITIONREPRESENTATION" => { - if let Some(m) = e.arg(3).and_then(|v| v.as_ref_id()) { - 'reps: for rep in refs(e.arg(2)) { - for it in refs(f.get(rep).and_then(|x| x.arg(3))) { - let Some(si) = f.get(it) else { continue }; - if si.ty != "IFCSTYLEDITEM" { - continue; - } - if let Some(c) = si.arg(1).and_then(|v| v.as_list()).and_then(|l| r.style_color(l, 0)) { - material_color.entry(m).or_insert(c); - break 'reps; - } - } - } - } - } - _ => {} - } - } - - // Material (auch Schichten/Profile/Bestandteile/Listen) → Farbe des ersten Materials. - let resolve_material_color = |mut m: u64| -> Option<[f64; 4]> { - for _ in 0..6 { - if let Some(c) = material_color.get(&m) { - return Some(*c); - } - let e = f.get(m)?; - let next = match e.ty.as_str() { - "IFCMATERIALLAYERSETUSAGE" | "IFCMATERIALPROFILESETUSAGE" | "IFCMATERIALPROFILESETUSAGETAPERING" => e.arg(0), - "IFCMATERIALLAYERSET" | "IFCMATERIALLIST" => e.arg(0).and_then(|v| v.as_list()).and_then(|l| l.first()), - "IFCMATERIALPROFILESET" | "IFCMATERIALCONSTITUENTSET" => e.arg(2).and_then(|v| v.as_list()).and_then(|l| l.first()), - "IFCMATERIALLAYER" => e.arg(0), - "IFCMATERIALPROFILE" | "IFCMATERIALCONSTITUENT" => e.arg(2), - _ => None, - }; - m = next?.as_ref_id()?; - } - None + let rels = Rels::gather(&f, &ids, &mut r); + let voids = &rels.voids; + let parent = &rels.parent; + let material_of = &rels.material_of; + let resolve_material_color = |m: u64| rels.resolve_material_color(&f, m); + let storey_of = |id: u64| -> Option { + let s = f.get(rels.storey_id(&f, id)?)?; + let name = s.arg(2).and_then(|v| v.as_str()).or_else(|| s.arg(7).and_then(|v| v.as_str())); + Some(name.unwrap_or("").to_string()) }; - let storey_of = |mut id: u64| -> Option { - for _ in 0..32 { - let e = f.get(id)?; - if e.ty == "IFCBUILDINGSTOREY" { - let name = e.arg(2).and_then(|v| v.as_str()).or_else(|| e.arg(7).and_then(|v| v.as_str())); - return Some(name.unwrap_or("").to_string()); - } - id = match container.get(&id) { - Some(s) => *s, - None => *parent.get(&id)?, - }; - } - None - }; + // Bauteil-Import ([B4]): erkannte Bauteile kommen nicht als Mesh. + let semantic = elements.then(|| crate::ifc_semantic::analyze(&mut r, &rels, &ids)); + let converted: HashSet = semantic.as_ref().map(|s| s.converted.clone()).unwrap_or_default(); let mut total_tris = 0usize; for &id in &ids { let e = &f.entities[&id]; 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 { + if !has_shape || converted.contains(&id) { continue; } if SKIP_CLASSES.contains(&e.ty.as_str()) { @@ -1697,6 +1772,7 @@ pub fn import_ifc(bytes: &[u8]) -> Result { } result.skipped_items = r.skipped; result.simplified_booleans = r.simplified; + result.elements = semantic; Ok(result) } @@ -1725,7 +1801,7 @@ const CLASS_NAMES: &[&str] = &[ "IfcWallElementedCase", "IfcWallStandardCase", "IfcWasteTerminal", "IfcWindow", "IfcWindowStandardCase", ]; -fn class_name(upper: &str) -> String { +pub(crate) 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()) } @@ -1808,12 +1884,14 @@ mod web { use wasm_bindgen::prelude::*; /// Ergebnis für JS: `meta` (JSON: Bauteile mit Längen der Puffer, Bericht), `positions()` - /// (alle Bauteile hintereinander, x,y,z in m), `indices()` (je Bauteil ab 0). + /// (alle Bauteile hintereinander, x,y,z in m), `indices()` (je Bauteil ab 0), `elementData()` + /// (Zahlen der erkannten Bauteile, [B4], s. `ifc_semantic::encode`; leer beim reinen Mesh-Import). #[wasm_bindgen] pub struct IfcImportResult { meta: String, positions: Vec, indices: Vec, + element_data: Vec, } #[wasm_bindgen] @@ -1828,12 +1906,27 @@ mod web { pub fn indices(&self) -> Vec { self.indices.clone() } + #[wasm_bindgen(js_name = elementData)] + pub fn element_data(&self) -> Vec { + self.element_data.clone() + } } /// IFC-Bytes → Meshes je Bauteil. Unlesbare Datei → JS-Fehler mit Meldung (kein Panic). #[wasm_bindgen] pub fn import_ifc(bytes: &[u8]) -> Result { - let r = super::import_ifc(bytes).map_err(|e| JsValue::from_str(&e))?; + encode(super::import_ifc(bytes).map_err(|e| JsValue::from_str(&e))?) + } + + /// Wie `import_ifc`, dazu echte Bauteile ([B4]): `meta.elements` (Wände, Öffnungen, Decken, + /// Stützen, Räume; Texte und Verweise) mit Zahlen in `elementData()`, `meta.storeys`; erkannte + /// Bauteile fehlen in den Meshes. + #[wasm_bindgen] + pub fn import_ifc_elements(bytes: &[u8]) -> Result { + encode(super::import_ifc_opts(bytes, true).map_err(|e| JsValue::from_str(&e))?) + } + + fn encode(r: super::IfcImport) -> Result { let mut positions = Vec::new(); let mut indices = Vec::new(); let products: Vec = r @@ -1853,7 +1946,7 @@ mod web { }) }) .collect(); - let meta = serde_json::json!({ + let mut meta = serde_json::json!({ "schema": r.schema, "lengthScale": r.length_scale, "products": products, @@ -1866,7 +1959,13 @@ mod web { "parseErrors": r.parse_errors, "truncated": r.truncated, }); - Ok(IfcImportResult { meta: meta.to_string(), positions, indices }) + let mut element_data = Vec::new(); + if let Some(sem) = &r.elements { + let (v, data) = crate::ifc_semantic::encode(sem); + meta["elements"] = v; + element_data = data; + } + Ok(IfcImportResult { meta: meta.to_string(), positions, indices, element_data }) } } diff --git a/src-tauri/fileio/src/ifc_semantic.rs b/src-tauri/fileio/src/ifc_semantic.rs new file mode 100644 index 00000000..b4f56d2e --- /dev/null +++ b/src-tauri/fileio/src/ifc_semantic.rs @@ -0,0 +1,1338 @@ +// IFC-Import zu echten Bauteilen ([B4], zweite Stufe von [25]): erkennt in einer IFC-Datei Bauteile, +// die sich sicher als Dossier-Objekte abbilden lassen, und liefert deren Kennwerte (Achse, Dicke, +// Höhe, Umriss …) in Metern. Die TS-Seite (`src/io/ifcElements.ts`) baut daraus Wände, Decken, +// Stützen, Öffnungen, Räume und Geschosse; alles andere bleibt Kontext-Mesh (`ifc_import.rs`). +// +// Eigener Code. Erkannt wird über die Form des Körpers (Weltkoordinaten, ohne Öffnungen), nicht über +// den Darstellungstyp — so gilt dasselbe für Extrusionen, B-Reps und Dreiecksnetze: +// - Wand (IfcWall, IfcWallStandardCase): Grundriss-Hülle → kleinstes umschliessendes Rechteck +// (Länge ≥ Dicke), unten eben (≥ 60 % des Rechtecks), oben eben auf mindestens 35 % (Giebel- und +// Pultwände fallen heraus, vom Dach angeschnittene Aussenschichten nicht), Volumen 70–100 % von +// Rechteck × Höhe (Gehrungen, Schicht-Bänder). Achse = Mittellinie; Enden, die in einer +// anderen Wand desselben Geschosses liegen, werden auf deren Achse gezogen (L-Ecke, T-Stoss). +// Schichten aus IfcMaterialLayerSet(Usage) des Bauteils oder seines Typs. Die Seite der ersten +// Schicht (Dossier: rechts der Achsrichtung): aus IfcMaterialLayerSetUsage, sonst aus einzeln +// extrudierten Schicht-Bändern, sonst aussen (weg vom Schwerpunkt aller Wände des Geschosses). +// - Öffnungen der Wand (IfcRelVoidsElement): Körper quaderförmig in Wandrichtung, durch die ganze +// Wanddicke → Tür (IfcDoor als Füllung), Fenster (IfcWindow) oder Wanddurchbruch (ohne Füllung). +// Ist eine Öffnung nicht so abbildbar, bleibt die ganze Wand (samt Füllungen) Mesh. +// - Decke (IfcSlab, nicht Teil eines Daches o. Ä.): senkrechtes Prisma — Ober- und Unterseite +// eben und gleich gross, Volumen = Fläche × Dicke; ein Umriss, Löcher und durchgehende Öffnungen +// werden Deckenöffnungen. +// - Stütze (IfcColumn): Prisma mit Rechteck- oder Kreis-Querschnitt. +// - Raum (IfcSpace): Prisma mit einem Umriss ohne Löcher; Name (LongName), SIA-416-Kategorie aus +// der Eigenschaft `SIA416` (Dossier-Export) falls vorhanden. +// - Geschosse (IfcBuildingStorey): Name, Höhe (Platzierung, sonst Elevation). +// +// Unsinn ergibt „nicht erkannt" (bleibt Mesh), nie Panic. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use crate::ifc_import::{class_name, signed_volume, Mesh, Reader, Rels, V2}; +use crate::ifc_step::Value; + +/// Höchstzahl Dreiecke je untersuchtem Körper. +const MAX_BODY_TRIS: usize = 400_000; +/// Toleranz für „gleiche Höhe" (m). +const ZTOL: f64 = 1e-4; +/// Rasterweite beim Verschweissen von Punkten (1/m → 0.01 mm). +const WELD: f64 = 1e5; + +// --------------------------------------------------------------------------- +// Ergebnis +// --------------------------------------------------------------------------- + +#[derive(Clone, Debug, Default)] +pub struct Storey { + pub id: u64, + pub global_id: String, + pub name: String, + /// Höhe der Geschoss-Platzierung (m). + pub elevation: f64, +} + +/// Eine Materialschicht; `thickness` 0 = einziges Material ohne Schichtdicke (ganze Dicke). +#[derive(Clone, Debug, Default)] +pub struct MatLayer { + pub material: String, + pub thickness: f64, + pub color: Option<[f64; 4]>, +} + +/// Gemeinsame Angaben eines erkannten Bauteils. +#[derive(Clone, Debug, Default)] +pub struct Info { + pub product: u64, + pub global_id: String, + pub class: String, + pub name: Option, + /// Index in [`Semantic::storeys`]. + pub storey: Option, + pub color: Option<[f64; 4]>, + /// Name des Typs (IfcWallType …) oder des Schichtaufbaus. + pub type_name: Option, + pub layers: Vec, +} + +#[derive(Clone, Debug, Default)] +pub struct Wall { + pub info: Info, + /// Achse (Mitte der Wanddicke); die erste Schicht liegt rechts der Richtung start → end. + pub start: V2, + pub end: V2, + pub z0: f64, + pub z1: f64, + pub thickness: f64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum OpeningKind { + #[default] + Door, + Window, + /// Öffnung ohne Füllung. + Hole, +} + +#[derive(Clone, Debug, Default)] +pub struct Opening { + /// Füllung (Tür/Fenster), bei `Hole` die IfcOpeningElement. + pub info: Info, + /// Index in [`Semantic::walls`]. + pub host: usize, + pub kind: OpeningKind, + /// Abstand vom Wand-Start entlang der Achse (m). + pub position: f64, + pub width: f64, + /// Brüstung über Wand-Unterkante. + pub sill: f64, + pub height: f64, +} + +#[derive(Clone, Debug, Default)] +pub struct Slab { + pub info: Info, + pub outline: Vec, + pub holes: Vec>, + pub z0: f64, + pub z1: f64, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Profile { + Rect { width: f64, depth: f64 }, + Round { radius: f64 }, +} + +#[derive(Clone, Debug)] +pub struct Column { + pub info: Info, + pub center: V2, + /// Drehung des Rechtecks (rad, Breite entlang der gedrehten x-Achse). + pub rotation: f64, + pub profile: Profile, + pub z0: f64, + pub z1: f64, +} + +#[derive(Clone, Debug, Default)] +pub struct Space { + pub info: Info, + pub long_name: Option, + pub sia: Option, + pub boundary: Vec, + pub z0: f64, + pub z1: f64, +} + +/// Erkannte Bauteile einer Datei. +#[derive(Clone, Debug, Default)] +pub struct Semantic { + /// Nach Höhe sortiert. + pub storeys: Vec, + pub walls: Vec, + pub openings: Vec, + pub slabs: Vec, + pub columns: Vec, + pub spaces: Vec, + /// Kandidaten (Wand, Decke, Stütze, Raum), die nicht sicher abbildbar waren, je Klasse. + pub kept: BTreeMap, + /// Bauteile, die nicht mehr als Mesh kommen (erkannte Bauteile, Füllungen, Öffnungen). + pub converted: HashSet, +} + +// --------------------------------------------------------------------------- +// 2D-Hilfen +// --------------------------------------------------------------------------- + +fn sub2(a: V2, b: V2) -> V2 { + [a[0] - b[0], a[1] - b[1]] +} +fn dot2(a: V2, b: V2) -> f64 { + a[0] * b[0] + a[1] * b[1] +} +fn cross2(a: V2, b: V2) -> f64 { + a[0] * b[1] - a[1] * b[0] +} +fn len2(a: V2) -> f64 { + a[0].hypot(a[1]) +} +fn lerp_dir(o: V2, d: V2, s: f64) -> V2 { + [o[0] + d[0] * s, o[1] + d[1] * s] +} +/// Linke Normale. +fn left(d: V2) -> V2 { + [-d[1], d[0]] +} +fn unit2(a: V2) -> Option { + let l = len2(a); + (l.is_finite() && l > 1e-12).then(|| [a[0] / l, a[1] / l]) +} +/// Fläche mit Vorzeichen (gegen den Uhrzeigersinn > 0). +fn area2(r: &[V2]) -> f64 { + let n = r.len(); + (0..n).map(|i| cross2(r[i], r[(i + 1) % n])).sum::() / 2.0 +} + +fn weld_key(p: V2) -> (i64, i64) { + ((p[0] * WELD).round() as i64, (p[1] * WELD).round() as i64) +} + +/// Konvexe Hülle (Andrew), gegen den Uhrzeigersinn, ohne kollineare Punkte. +fn convex_hull(pts: &[V2]) -> Vec { + let mut seen = HashSet::new(); + let mut p: Vec = pts.iter().copied().filter(|q| q[0].is_finite() && q[1].is_finite() && seen.insert(weld_key(*q))).collect(); + if p.len() < 3 { + return p; + } + p.sort_by(|a, b| a[0].total_cmp(&b[0]).then(a[1].total_cmp(&b[1]))); + let mut lower: Vec = Vec::new(); + for &q in &p { + while lower.len() >= 2 && cross2(sub2(lower[lower.len() - 1], lower[lower.len() - 2]), sub2(q, lower[lower.len() - 2])) <= 1e-12 { + lower.pop(); + } + lower.push(q); + } + let mut upper: Vec = Vec::new(); + for &q in p.iter().rev() { + while upper.len() >= 2 && cross2(sub2(upper[upper.len() - 1], upper[upper.len() - 2]), sub2(q, upper[upper.len() - 2])) <= 1e-12 { + upper.pop(); + } + upper.push(q); + } + lower.pop(); + upper.pop(); + lower.extend(upper); + lower +} + +/// Kleinstes umschliessendes Rechteck: Richtung `d` (entlang der längeren Seite, nach +x bzw. +y +/// gedreht) und Ausdehnung [u0,u1] × [v0,v1] in (d, left(d)). +fn min_area_rect(pts: &[V2]) -> Option<(V2, f64, f64, f64, f64)> { + let hull = convex_hull(pts); + if hull.len() < 3 { + return None; + } + let mut best: Option<(f64, V2, f64, f64, f64, f64)> = None; + for i in 0..hull.len() { + let Some(d) = unit2(sub2(hull[(i + 1) % hull.len()], hull[i])) else { continue }; + let n = left(d); + let (mut u0, mut u1, mut v0, mut v1) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY); + for &q in &hull { + let (u, v) = (dot2(q, d), dot2(q, n)); + u0 = u0.min(u); + u1 = u1.max(u); + v0 = v0.min(v); + v1 = v1.max(v); + } + let a = (u1 - u0) * (v1 - v0); + if best.as_ref().is_none_or(|b| a < b.0 * (1.0 - 1e-9)) { + best = Some((a, d, u0, u1, v0, v1)); + } + } + let (_, mut d, mut u0, mut u1, mut v0, mut v1) = best?; + if v1 - v0 > u1 - u0 { + // Längere Seite als Richtung: d' = left(d) → u' = v, v' = −u. + d = left(d); + let (a0, a1) = (v0, v1); + v0 = -u1; + v1 = -u0; + u0 = a0; + u1 = a1; + } + if d[0] < -1e-9 || (d[0].abs() <= 1e-9 && d[1] < 0.0) { + d = [-d[0], -d[1]]; + (u0, u1) = (-u1, -u0); + (v0, v1) = (-v1, -v0); + } + Some((d, u0, u1, v0, v1)) +} + +/// Entfernt doppelte und kollineare Punkte eines geschlossenen Rings. +fn simplify_ring(r: &[V2]) -> Vec { + let mut out: Vec = Vec::with_capacity(r.len()); + for &p in r { + if out.last().is_none_or(|q| len2(sub2(p, *q)) > 1e-7) { + out.push(p); + } + } + while out.len() > 1 && len2(sub2(out[0], out[out.len() - 1])) <= 1e-7 { + out.pop(); + } + let mut changed = true; + while changed && out.len() >= 3 { + changed = false; + let n = out.len(); + for i in 0..n { + let (a, b, c) = (out[(i + n - 1) % n], out[i], out[(i + 1) % n]); + let (ab, bc) = (sub2(b, a), sub2(c, b)); + if cross2(ab, bc).abs() <= 1e-9 * (len2(ab) * len2(bc)).max(1e-12) && dot2(ab, bc) >= 0.0 { + out.remove(i); + changed = true; + break; + } + } + } + out +} + +// --------------------------------------------------------------------------- +// Körperform +// --------------------------------------------------------------------------- + +/// Kennwerte eines (möglichen) senkrechten Prismas. +struct Shape { + z0: f64, + z1: f64, + /// Fläche der nach oben zeigenden Dreiecke auf z1 bzw. nach unten auf z0. + top_area: f64, + bottom_area: f64, + volume: f64, + /// Randschleifen der Oberseite (aussen gegen den Uhrzeigersinn, Löcher im Uhrzeigersinn). + loops: Vec>, + /// Alle Punkte im Grundriss. + plan: Vec, +} + +fn shape(m: &Mesh) -> Option { + if m.indices.len() < 12 || m.positions.len() < 12 { + return None; + } + let (mut z0, mut z1) = (f64::INFINITY, f64::NEG_INFINITY); + let mut plan = Vec::with_capacity(m.positions.len() / 3); + for c in m.positions.chunks_exact(3) { + if !(c[0].is_finite() && c[1].is_finite() && c[2].is_finite()) { + return None; + } + z0 = z0.min(c[2]); + z1 = z1.max(c[2]); + plan.push([c[0], c[1]]); + } + if !(z1 - z0 > 1e-3) { + return None; + } + let p = |i: u32| -> Option<[f64; 3]> { + let k = i as usize * 3; + m.positions.get(k..k + 3).map(|s| [s[0], s[1], s[2]]) + }; + let (mut top_area, mut bottom_area) = (0.0, 0.0); + let mut top: Vec<[V2; 3]> = Vec::new(); + for t in m.indices.chunks_exact(3) { + let (a, b, c) = (p(t[0])?, p(t[1])?, p(t[2])?); + let nz = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); + let at = |z: f64| (a[2] - z).abs() <= ZTOL && (b[2] - z).abs() <= ZTOL && (c[2] - z).abs() <= ZTOL; + if at(z1) && nz > 0.0 { + top_area += nz / 2.0; + top.push([[a[0], a[1]], [b[0], b[1]], [c[0], c[1]]]); + } else if at(z0) && nz < 0.0 { + bottom_area -= nz / 2.0; + } + } + Some(Shape { z0, z1, top_area, bottom_area, volume: signed_volume(&m.positions, &m.indices), loops: boundary_loops(&top), plan }) +} + +/// Randschleifen einer Dreiecksmenge (gleich orientiert): Kanten ohne Gegenkante, verkettet. +fn boundary_loops(tris: &[[V2; 3]]) -> Vec> { + let mut index: HashMap<(i64, i64), usize> = HashMap::new(); + let mut pts: Vec = Vec::new(); + let mut id = |p: V2| -> usize { + *index.entry(weld_key(p)).or_insert_with(|| { + pts.push(p); + pts.len() - 1 + }) + }; + let mut edges: HashMap<(usize, usize), i32> = HashMap::new(); + for t in tris { + let (a, b, c) = (id(t[0]), id(t[1]), id(t[2])); + if a == b || b == c || a == c { + continue; + } + for (u, v) in [(a, b), (b, c), (c, a)] { + match edges.get_mut(&(v, u)) { + Some(n) if *n > 0 => *n -= 1, + _ => *edges.entry((u, v)).or_insert(0) += 1, + } + } + } + let mut next: HashMap> = HashMap::new(); + let mut count = 0; + let mut keys: Vec<(usize, usize)> = edges.iter().filter(|(_, n)| **n > 0).map(|(k, _)| *k).collect(); + keys.sort_unstable(); + for (u, v) in keys { + next.entry(u).or_default().push(v); + count += 1; + } + let mut loops = Vec::new(); + let mut starts: Vec = next.keys().copied().collect(); + starts.sort_unstable(); + for s in starts { + while next.get(&s).is_some_and(|l| !l.is_empty()) { + let mut ring = vec![pts[s]]; + let mut cur = s; + let mut ok = false; + for _ in 0..=count { + let Some(v) = next.get_mut(&cur).and_then(|l| l.pop()) else { break }; + if v == s { + ok = true; + break; + } + ring.push(pts[v]); + cur = v; + } + if ok { + let r = simplify_ring(&ring); + if r.len() >= 3 { + loops.push(r); + } + } + } + } + loops +} + +/// Senkrechtes Prisma: Ober-/Unterseite gleich, Volumen = Fläche × Höhe. Liefert Umriss (aussen, +/// gegen den Uhrzeigersinn) und Löcher; `None`, wenn nicht so oder mehr als ein Umriss. +fn prism(s: &Shape) -> Option<(Vec, Vec>)> { + let h = s.z1 - s.z0; + let a = s.top_area; + if !(a > 1e-4 && (s.bottom_area - a).abs() <= 0.01 * a && (s.volume - a * h).abs() <= 0.01 * a * h) { + return None; + } + let mut outer: Option> = None; + let mut holes = Vec::new(); + for l in &s.loops { + if area2(l) > 0.0 { + if outer.is_some() { + return None; + } + outer = Some(l.clone()); + } else { + holes.push(l.iter().rev().copied().collect::>()); + } + } + let outer = outer?; + // Flächen der Schleifen müssen die Oberseite ergeben. + let sum = area2(&outer) - holes.iter().map(|h| area2(h)).sum::(); + ((sum - a).abs() <= 0.01 * a).then_some((outer, holes)) +} + +/// Ausdehnung eines Körpers im Rahmen (Ursprung `o`, Richtung `d`, Normale `left(d)`): +/// [u0,u1,v0,v1,z0,z1] und Füllgrad (Volumen / Quader). +fn box_in_frame(m: &Mesh, o: V2, d: V2) -> Option<([f64; 6], f64)> { + let n = left(d); + let mut b = [f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY]; + for c in m.positions.chunks_exact(3) { + let q = sub2([c[0], c[1]], o); + let (u, v) = (dot2(q, d), dot2(q, n)); + b[0] = b[0].min(u); + b[1] = b[1].max(u); + b[2] = b[2].min(v); + b[3] = b[3].max(v); + b[4] = b[4].min(c[2]); + b[5] = b[5].max(c[2]); + } + let bv = (b[1] - b[0]) * (b[3] - b[2]) * (b[5] - b[4]); + if !(bv.is_finite() && bv > 1e-9) { + return None; + } + Some((b, signed_volume(&m.positions, &m.indices) / bv)) +} + +// --------------------------------------------------------------------------- +// Erkennung +// --------------------------------------------------------------------------- + +/// Wand in Arbeit (vor dem Ziehen der Enden). +struct WallCand { + info: Info, + start: V2, + end: V2, + z0: f64, + z1: f64, + thickness: f64, + /// Öffnungen: (IfcOpeningElement, Füllung, Art, Körper). + openings: Vec<(u64, Option, OpeningKind, Mesh)>, + /// Seite der ersten Schicht laut IfcMaterialLayerSetUsage: Richtung in Weltkoordinaten. + usage_side: Option, + /// Darstellungselemente einzeln (Schicht-Bänder). + items: Vec, +} + +struct Ctx<'r, 'a> { + r: &'r mut Reader<'a>, + rels: &'r Rels, + type_of: HashMap, + fills: HashMap>, + sia: HashMap, + storey_index: HashMap, +} + +impl Ctx<'_, '_> { + fn info(&self, id: u64, color: Option<[f64; 4]>) -> Info { + let f = self.r.f; + let Some(e) = f.get(id) else { return Info::default() }; + let mat = self.material_id(id); + let (layers, _, set_name) = self.layers(id); + let type_name = self + .type_of + .get(&id) + .and_then(|t| f.get(*t)) + .and_then(|t| t.arg(2)) + .and_then(|v| v.as_str()) + .map(str::to_string) + .or(set_name); + Info { + product: id, + global_id: e.arg(0).and_then(|v| v.as_str()).unwrap_or("").to_string(), + class: class_name(&e.ty), + name: e.arg(2).and_then(|v| v.as_str()).map(str::to_string), + storey: self.rels.storey_id(f, id).and_then(|s| self.storey_index.get(&s).copied()), + color: color.or_else(|| mat.and_then(|m| self.rels.resolve_material_color(f, m))), + type_name, + layers, + } + } + + /// Material des Bauteils, sonst seines Typs. + fn material_id(&self, id: u64) -> Option { + self.rels.material_of.get(&id).or_else(|| self.type_of.get(&id).and_then(|t| self.rels.material_of.get(t))).copied() + } + + /// Schichten, Richtungssinn (POSITIVE = true) der IfcMaterialLayerSetUsage, Name des Aufbaus. + fn layers(&self, id: u64) -> (Vec, Option, Option) { + let f = self.r.f; + let scale = self.r.len_scale; + let Some(mut m) = self.material_id(id) else { return (Vec::new(), None, None) }; + let mut sense = None; + let mat_name = |mid: Option| -> Option<(String, Option<[f64; 4]>)> { + let mid = mid?; + let e = f.get(mid)?; + (e.ty == "IFCMATERIAL").then(|| (e.arg(0).and_then(|v| v.as_str()).unwrap_or("").to_string(), self.rels.resolve_material_color(f, mid))) + }; + let single = |mid: Option| -> Vec { + mat_name(mid).map(|(material, color)| vec![MatLayer { material, thickness: 0.0, color }]).unwrap_or_default() + }; + for _ in 0..4 { + let Some(e) = f.get(m) else { break }; + match e.ty.as_str() { + "IFCMATERIALLAYERSETUSAGE" => { + sense = e.arg(2).and_then(|v| v.as_enum()).map(|s| s != "NEGATIVE"); + match e.arg(0).and_then(|v| v.as_ref_id()) { + Some(n) => m = n, + None => break, + } + } + "IFCMATERIALLAYERSET" => { + let mut out = Vec::new(); + for l in e.arg(0).and_then(|v| v.as_list()).unwrap_or(&[]) { + let Some(le) = l.as_ref_id().and_then(|i| f.get(i)) else { continue }; + if le.ty != "IFCMATERIALLAYER" { + continue; + } + let t = le.arg(1).and_then(|v| v.as_f64()).map(|t| t * scale).unwrap_or(0.0); + let (material, color) = mat_name(le.arg(0).and_then(|v| v.as_ref_id())).unwrap_or_default(); + if t.is_finite() && t >= 0.0 { + out.push(MatLayer { material, thickness: t, color }); + } + } + let name = e.arg(1).and_then(|v| v.as_str()).map(str::to_string); + return (out, sense, name); + } + "IFCMATERIAL" => return (single(Some(m)), sense, None), + "IFCMATERIALLIST" => { + return (single(e.arg(0).and_then(|v| v.as_list()).and_then(|l| l.first()).and_then(|v| v.as_ref_id())), sense, None) + } + "IFCMATERIALCONSTITUENTSET" | "IFCMATERIALPROFILESET" => { + let first = e.arg(2).and_then(|v| v.as_list()).and_then(|l| l.first()).and_then(|v| v.as_ref_id()).and_then(|i| f.get(i)); + let name = e.arg(0).and_then(|v| v.as_str()).map(str::to_string); + return (single(first.and_then(|c| c.arg(2)).and_then(|v| v.as_ref_id())), sense, name); + } + "IFCMATERIALPROFILESETUSAGE" => match e.arg(0).and_then(|v| v.as_ref_id()) { + Some(n) => m = n, + None => break, + }, + _ => break, + } + } + (Vec::new(), sense, None) + } + + fn body(&mut self, id: u64) -> Option<(Mesh, Option<[f64; 4]>)> { + let (m, c) = self.r.product_body(id, MAX_BODY_TRIS)?; + (!m.is_empty() && m.triangle_count() <= MAX_BODY_TRIS).then_some((m, c)) + } + + /// Wand aus dem Körper; `None` = nicht sicher abbildbar. + fn wall(&mut self, id: u64) -> Option { + let (mesh, color) = self.body(id)?; + let s = shape(&mesh)?; + let (d, u0, u1, v0, v1) = min_area_rect(&s.plan)?; + let (len, t, h) = (u1 - u0, v1 - v0, s.z1 - s.z0); + if !(t >= 0.01 && t <= 2.0 && len >= t.max(0.05) && h >= 0.05) { + return None; + } + let rect = len * t; + let ratio = s.volume / (rect * h); + if !((0.7..=1.0 + 1e-3).contains(&ratio) && s.top_area >= 0.35 * rect && s.bottom_area >= 0.6 * rect) { + return None; + } + let n = left(d); + let vc = (v0 + v1) / 2.0; + let base = [n[0] * vc, n[1] * vc]; + let start = lerp_dir(base, d, u0); + let end = lerp_dir(base, d, u1); + + // Öffnungen: quaderförmig, durch die ganze Wand, Füllung Tür/Fenster oder keine. + let mut openings = Vec::new(); + for &o in self.rels.voids.get(&id).map(Vec::as_slice).unwrap_or(&[]) { + let (om, _) = self.body(o)?; + let (b, fill) = box_in_frame(&om, start, d)?; + let through = b[2] <= -t / 2.0 + 1e-3 && b[3] >= t / 2.0 - 1e-3; + let inside = b[0] >= -0.01 && b[1] <= len + 0.01 && b[5] > s.z0 + 0.01 && b[4] < s.z1 - 0.01; + if !(through && inside && (0.95..=1.0 + 1e-3).contains(&fill)) { + return None; + } + let fillings = self.fills.get(&o).cloned().unwrap_or_default(); + let (filling, kind) = match fillings.as_slice() { + [] => (None, OpeningKind::Hole), + [x] => { + let ty = self.r.f.get(*x).map(|e| e.ty.as_str()).unwrap_or(""); + if ty.starts_with("IFCDOOR") { + (Some(*x), OpeningKind::Door) + } else if ty.starts_with("IFCWINDOW") { + (Some(*x), OpeningKind::Window) + } else { + return None; + } + } + _ => return None, + }; + openings.push((o, filling, kind, om)); + } + + let (layers, sense, _) = self.layers(id); + // IfcMaterialLayerSetUsage: Schichten ab der Referenzlinie in +y (POSITIVE) bzw. −y der + // Bauteil-Platzierung → erste Schicht auf der −y- bzw. +y-Seite. + let usage_side = match (sense, layers.len() > 1) { + (Some(pos), true) => { + let f = self.r.f; + let place = f.get(id).and_then(|e| e.arg(5)).and_then(|v| v.as_ref_id()); + let xf = place.map(|p| self.r.object_placement(p, 0)); + xf.and_then(|x| { + let y = x.apply_dir([0.0, 1.0, 0.0]); + unit2([y[0], y[1]]).map(|y| if pos { [-y[0], -y[1]] } else { y }) + }) + } + _ => None, + }; + let items = if layers.len() > 1 && usage_side.is_none() { self.r.product_item_meshes(id, MAX_BODY_TRIS) } else { Vec::new() }; + Some(WallCand { info: self.info(id, color), start, end, z0: s.z0, z1: s.z1, thickness: t, openings, usage_side, items }) + } + + fn slab(&mut self, id: u64) -> Option { + let (mesh, color) = self.body(id)?; + let s = shape(&mesh)?; + if s.z1 - s.z0 > 3.0 { + return None; + } + let (outline, mut holes) = prism(&s)?; + for &o in self.rels.voids.get(&id).map(Vec::as_slice).unwrap_or(&[]) { + if self.fills.get(&o).is_some_and(|l| !l.is_empty()) { + return None; + } + let (om, _) = self.body(o)?; + let os = shape(&om)?; + if !(os.z0 <= s.z0 + 1e-3 && os.z1 >= s.z1 - 1e-3) { + return None; + } + let (ring, inner) = prism(&os)?; + if !inner.is_empty() { + return None; + } + holes.push(ring); + } + Some(Slab { info: self.info(id, color), outline, holes, z0: s.z0, z1: s.z1 }) + } + + fn column(&mut self, id: u64) -> Option { + let (mesh, color) = self.body(id)?; + let s = shape(&mesh)?; + let (ring, holes) = prism(&s)?; + if !holes.is_empty() { + return None; + } + let n = ring.len(); + let c = ring.iter().fold([0.0, 0.0], |a, p| [a[0] + p[0] / n as f64, a[1] + p[1] / n as f64]); + let profile; + let mut rotation = 0.0; + let mut center = c; + if n == 4 { + let e: Vec = (0..4).map(|i| sub2(ring[(i + 1) % 4], ring[i])).collect(); + let square = (0..4).all(|i| dot2(e[i], e[(i + 1) % 4]).abs() <= 1e-6 * len2(e[i]) * len2(e[(i + 1) % 4])); + if !square { + return None; + } + // Breite entlang der Kante, deren Winkel am nächsten bei 0 liegt. + let pick = (0..2).min_by(|&i, &j| { + let a = |k: usize| e[k][1].atan2(e[k][0]).rem_euclid(std::f64::consts::PI); + let dist = |x: f64| x.min(std::f64::consts::PI - x); + dist(a(i)).total_cmp(&dist(a(j))) + })?; + let mut ang = e[pick][1].atan2(e[pick][0]).rem_euclid(std::f64::consts::PI); + if ang > std::f64::consts::FRAC_PI_2 { + ang -= std::f64::consts::PI; + } + rotation = if ang.abs() < 1e-9 { 0.0 } else { ang }; + profile = Profile::Rect { width: len2(e[pick]), depth: len2(e[(pick + 1) % 4]) }; + } else if n >= 8 { + let rs: Vec = ring.iter().map(|p| len2(sub2(*p, c))).collect(); + let r = rs.iter().sum::() / n as f64; + if !(r > 1e-3 && rs.iter().all(|x| (x - r).abs() <= 0.01 * r)) { + return None; + } + center = c; + profile = Profile::Round { radius: rs.iter().copied().fold(0.0, f64::max) }; + } else { + return None; + } + Some(Column { info: self.info(id, color), center, rotation, profile, z0: s.z0, z1: s.z1 }) + } + + fn space(&mut self, id: u64) -> Option { + let (mesh, color) = self.body(id)?; + let s = shape(&mesh)?; + let (boundary, holes) = prism(&s)?; + if !holes.is_empty() { + return None; + } + let f = self.r.f; + let long_name = f.get(id).and_then(|e| e.arg(7)).and_then(|v| v.as_str()).filter(|s| !s.is_empty()).map(str::to_string); + Some(Space { info: self.info(id, color), long_name, sia: self.sia.get(&id).cloned(), boundary, z0: s.z0, z1: s.z1 }) + } +} + +/// Zieht Wand-Enden, die in einer anderen Wand desselben Geschosses liegen, auf deren Achse. +fn snap_ends(walls: &mut [WallCand]) { + let orig: Vec<(V2, V2, f64)> = walls.iter().map(|w| (w.start, w.end, w.thickness)).collect(); + for i in 0..walls.len() { + let (a, b, ti) = orig[i]; + let Some(di) = unit2(sub2(b, a)) else { continue }; + let li = len2(sub2(b, a)); + for end in 0..2 { + let p = if end == 0 { a } else { b }; + let mut best: Option<(f64, V2)> = None; + for (j, &(c, e, tj)) in orig.iter().enumerate() { + if i == j + || walls[i].info.storey != walls[j].info.storey + || walls[i].z1.min(walls[j].z1) - walls[i].z0.max(walls[j].z0) < 0.01 + { + continue; + } + let Some(dj) = unit2(sub2(e, c)) else { continue }; + let lj = len2(sub2(e, c)); + let sin = cross2(di, dj); + if sin.abs() < 0.17 { + continue; + } + let s = cross2(sub2(c, a), dj) / sin; + let x = lerp_dir(a, di, s); + let dist = len2(sub2(p, x)); + if dist > tj / 2.0 / sin.abs() + 0.03 { + continue; + } + // Schnittpunkt auf der anderen Wand (verlängert um die halbe eigene Dicke) und auf + // der richtigen Hälfte der eigenen Wand. + let tx = dot2(sub2(x, c), dj); + let reach = ti / 2.0 / sin.abs() + 0.03; + if tx < -reach || tx > lj + reach || (end == 0 && s > li / 2.0) || (end == 1 && s < li / 2.0) { + continue; + } + if best.is_none_or(|(bd, _)| dist < bd) { + best = Some((dist, x)); + } + } + if let Some((_, x)) = best { + if end == 0 { + walls[i].start = x; + } else { + walls[i].end = x; + } + } + } + } +} + +/// Seite der ersten Schicht als Vorzeichen bezüglich `left(d)`: +1 links, −1 rechts, 0 unbekannt — +/// aus einzeln extrudierten Schicht-Bändern (jedes Band = genau eine Schicht). +fn side_from_bands(w: &WallCand, d: V2) -> i32 { + let total: f64 = w.info.layers.iter().map(|l| l.thickness).sum(); + if w.items.len() < 2 || (total - w.thickness).abs() > 0.005 { + return 0; + } + let mid = [(w.start[0] + w.end[0]) / 2.0, (w.start[1] + w.end[1]) / 2.0]; + // Grenzen der Schichten, erste Schicht links (+v) bzw. rechts (−v). + let bands = |sign: f64| -> Vec<(f64, f64)> { + let mut acc = total / 2.0; + w.info + .layers + .iter() + .map(|l| { + let (o0, o1) = (acc - l.thickness, acc); + acc -= l.thickness; + if sign > 0.0 { (o0, o1) } else { (-o1, -o0) } + }) + .collect() + }; + let score = |b: &[(f64, f64)]| -> usize { + w.items + .iter() + .filter_map(|m| box_in_frame(m, mid, d)) + .filter(|(r, _)| b.iter().any(|(o0, o1)| (r[2] - o0).abs() <= 0.002 && (r[3] - o1).abs() <= 0.002)) + .count() + }; + let (l, r) = (score(&bands(1.0)), score(&bands(-1.0))); + (l as i32 - r as i32).signum() +} + +/// Erkennt alle sicher abbildbaren Bauteile. +pub(crate) fn analyze(r: &mut Reader, rels: &Rels, ids: &[u64]) -> Semantic { + let f = r.f; + let refs = |v: Option<&Value>| -> Vec { v.and_then(|v| v.as_list()).unwrap_or(&[]).iter().filter_map(|x| x.as_ref_id()).collect() }; + let mut type_of = HashMap::new(); + let mut fills: HashMap> = HashMap::new(); + let mut sia = HashMap::new(); + let mut storeys = Vec::new(); + for &id in ids { + let Some(e) = f.get(id) else { continue }; + match e.ty.as_str() { + "IFCRELDEFINESBYTYPE" => { + if let Some(t) = e.arg(5).and_then(|v| v.as_ref_id()) { + for o in refs(e.arg(4)) { + type_of.entry(o).or_insert(t); + } + } + } + "IFCRELFILLSELEMENT" => { + if let (Some(o), Some(x)) = (e.arg(4).and_then(|v| v.as_ref_id()), e.arg(5).and_then(|v| v.as_ref_id())) { + fills.entry(o).or_default().push(x); + } + } + "IFCRELDEFINESBYPROPERTIES" => { + let Some(ps) = e.arg(5).and_then(|v| v.as_ref_id()).and_then(|i| f.get(i)) else { continue }; + if ps.ty != "IFCPROPERTYSET" { + continue; + } + for p in refs(ps.arg(4)) { + let Some(pe) = f.get(p) else { continue }; + if pe.ty != "IFCPROPERTYSINGLEVALUE" || pe.arg(0).and_then(|v| v.as_str()) != Some("SIA416") { + continue; + } + let val = match pe.arg(2) { + Some(Value::Typed(_, args)) => args.first().and_then(|v| v.as_str()), + Some(v) => v.as_str(), + None => None, + }; + if let Some(val) = val { + for o in refs(e.arg(4)) { + sia.entry(o).or_insert_with(|| val.to_string()); + } + } + } + } + "IFCBUILDINGSTOREY" => { + let elevation = match e.arg(5).and_then(|v| v.as_ref_id()) { + Some(p) if f.get(p).is_some() => r.object_placement(p, 0).origin()[2], + _ => e.arg(9).and_then(|v| v.as_f64()).map(|z| z * r.len_scale).unwrap_or(0.0), + }; + if elevation.is_finite() { + storeys.push(Storey { + id, + global_id: e.arg(0).and_then(|v| v.as_str()).unwrap_or("").to_string(), + name: e.arg(2).and_then(|v| v.as_str()).or_else(|| e.arg(7).and_then(|v| v.as_str())).unwrap_or("").to_string(), + elevation, + }); + } + } + _ => {} + } + } + storeys.sort_by(|a, b| a.elevation.total_cmp(&b.elevation)); + let storey_index = storeys.iter().enumerate().map(|(i, s)| (s.id, i)).collect(); + let mut cx = Ctx { r, rels, type_of, fills, sia, storey_index }; + let mut out = Semantic { storeys, ..Default::default() }; + + let spatial = |id: u64| f.get(id).is_some_and(|e| matches!(e.ty.as_str(), "IFCBUILDINGSTOREY" | "IFCBUILDING" | "IFCSITE" | "IFCSPACE")); + let mut walls = Vec::new(); + for &id in ids { + let Some(e) = f.get(id) else { continue }; + let ty = e.ty.as_str(); + let candidate = matches!(ty, "IFCWALL" | "IFCWALLSTANDARDCASE" | "IFCSLAB" | "IFCSLABSTANDARDCASE" | "IFCCOLUMN" | "IFCCOLUMNSTANDARDCASE" | "IFCSPACE"); + 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 !candidate || !has_shape { + continue; + } + // Teil eines anderen Bauteils (Dachplatte, Wand einer Vorhangfassade …) bleibt Mesh. + let part = rels.parent.get(&id).is_some_and(|p| !spatial(*p)); + let ok = !part + && match ty { + "IFCWALL" | "IFCWALLSTANDARDCASE" => cx.wall(id).map(|w| walls.push(w)).is_some(), + "IFCSLAB" | "IFCSLABSTANDARDCASE" => cx.slab(id).map(|s| out.slabs.push(s)).is_some(), + "IFCCOLUMN" | "IFCCOLUMNSTANDARDCASE" => cx.column(id).map(|c| out.columns.push(c)).is_some(), + _ => cx.space(id).map(|s| out.spaces.push(s)).is_some(), + }; + if ok { + out.converted.insert(id); + out.converted.extend(rels.voids.get(&id).map(Vec::as_slice).unwrap_or(&[])); + } else { + *out.kept.entry(class_name(ty)).or_insert(0) += 1; + } + } + + snap_ends(&mut walls); + // Schwerpunkt der Wände je Geschoss (für „aussen"). + let mut centers: HashMap, (V2, f64)> = HashMap::new(); + for w in &walls { + let l = len2(sub2(w.end, w.start)); + let e = centers.entry(w.info.storey).or_insert(([0.0, 0.0], 0.0)); + e.0[0] += (w.start[0] + w.end[0]) / 2.0 * l; + e.0[1] += (w.start[1] + w.end[1]) / 2.0 * l; + e.1 += l; + } + for w in walls { + let Some(d) = unit2(sub2(w.end, w.start)) else { continue }; + let n = left(d); + let asymmetric = { + let l = &w.info.layers; + (0..l.len()).any(|i| (l[i].thickness - l[l.len() - 1 - i].thickness).abs() > 1e-6 || l[i].material != l[l.len() - 1 - i].material) + }; + // Seite der ersten Schicht (+1 = links von d); Dossier legt sie rechts. + let mut side = 0; + if asymmetric { + if let Some(u) = w.usage_side { + side = dot2(u, n).signum() as i32; + } + if side == 0 { + side = side_from_bands(&w, d); + } + } + if side == 0 { + // Aussen = weg vom Schwerpunkt aller Wände des Geschosses. + if let Some((c, l)) = centers.get(&w.info.storey).filter(|(_, l)| *l > 0.0) { + let mid = [(w.start[0] + w.end[0]) / 2.0, (w.start[1] + w.end[1]) / 2.0]; + let to = sub2(mid, [c[0] / l, c[1] / l]); + side = if dot2(to, n) > 1e-9 { 1 } else { -1 }; + } + } + let (start, end) = if side > 0 { (w.end, w.start) } else { (w.start, w.end) }; + let d = if side > 0 { [-d[0], -d[1]] } else { d }; + let host = out.walls.len(); + let len = len2(sub2(end, start)); + for (o, filling, kind, mesh) in &w.openings { + let Some((b, _)) = box_in_frame(mesh, start, d) else { continue }; + let u0 = b[0].max(0.0); + let u1 = b[1].min(len); + let z0 = b[4].max(w.z0); + let z1 = b[5].min(w.z1); + let info = cx.info(filling.unwrap_or(*o), None); + if let Some(x) = filling { + out.converted.insert(*x); + } + out.openings.push(Opening { info, host, kind: *kind, position: u0, width: u1 - u0, sill: z0 - w.z0, height: z1 - z0 }); + } + out.walls.push(Wall { info: w.info, start, end, z0: w.z0, z1: w.z1, thickness: w.thickness }); + } + out +} + +// --------------------------------------------------------------------------- +// Flache Kodierung für JS: Texte/Verweise als JSON, Zahlen in einem Float64Array. +// wall: sx, sy, ex, ey, z0, z1, thickness +// opening: position, width, sill, height +// slab: z0, z1, nRings, (nPts, x, y, …)* (erster Ring = Umriss) +// column: cx, cy, rotation, z0, z1, a, b (rect: Breite, Tiefe; round: Radius, 0) +// space: z0, z1, nPts, x, y, … +// --------------------------------------------------------------------------- + +#[cfg(feature = "web")] +pub(crate) fn encode(s: &Semantic) -> (serde_json::Value, Vec) { + use serde_json::json; + let mut data: Vec = Vec::new(); + let mut elements = Vec::new(); + let info = |i: &Info| { + json!({ + "globalId": i.global_id, + "ifcClass": i.class, + "name": i.name, + "storey": i.storey, + "color": i.color, + "typeName": i.type_name, + "layers": i.layers.iter().map(|l| json!({ "material": l.material, "thickness": l.thickness, "color": l.color })).collect::>(), + }) + }; + let mut push = |kind: &str, i: &Info, extra: serde_json::Value, nums: Vec, data: &mut Vec| { + let mut v = info(i); + let at = data.len(); + data.extend(nums); + v["kind"] = json!(kind); + v["at"] = json!(at); + v["n"] = json!(data.len() - at); + if let (Some(o), Some(x)) = (v.as_object_mut(), extra.as_object()) { + for (k, val) in x { + o.insert(k.clone(), val.clone()); + } + } + elements.push(v); + }; + let ring = |r: &[V2], out: &mut Vec| { + out.push(r.len() as f64); + for p in r { + out.extend_from_slice(p); + } + }; + for w in &s.walls { + push("wall", &w.info, json!({}), vec![w.start[0], w.start[1], w.end[0], w.end[1], w.z0, w.z1, w.thickness], &mut data); + } + for o in &s.openings { + let kind = match o.kind { + OpeningKind::Door => "door", + OpeningKind::Window => "window", + OpeningKind::Hole => "hole", + }; + push("opening", &o.info, json!({ "host": o.host, "openingKind": kind }), vec![o.position, o.width, o.sill, o.height], &mut data); + } + for sl in &s.slabs { + let mut nums = vec![sl.z0, sl.z1, (1 + sl.holes.len()) as f64]; + ring(&sl.outline, &mut nums); + for h in &sl.holes { + ring(h, &mut nums); + } + push("slab", &sl.info, json!({}), nums, &mut data); + } + for c in &s.columns { + let (kind, a, b) = match c.profile { + Profile::Rect { width, depth } => ("rect", width, depth), + Profile::Round { radius } => ("round", radius, 0.0), + }; + push("column", &c.info, json!({ "profile": kind }), vec![c.center[0], c.center[1], c.rotation, c.z0, c.z1, a, b], &mut data); + } + for sp in &s.spaces { + let mut nums = vec![sp.z0, sp.z1]; + ring(&sp.boundary, &mut nums); + push("space", &sp.info, json!({ "longName": sp.long_name, "sia": sp.sia }), nums, &mut data); + } + let storeys: Vec<_> = s.storeys.iter().map(|st| json!({ "globalId": st.global_id, "name": st.name, "elevation": st.elevation })).collect(); + // Nicht endliche Zahlen gäbe es nur bei Unsinn; JSON/JS-Seite verwirft sie. + for v in data.iter_mut() { + if !v.is_finite() { + *v = 0.0; + } + } + (json!({ "storeys": storeys, "elements": elements, "kept": s.kept }), data) +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::ifc_import::import_ifc_opts; + + fn close(a: f64, b: f64) -> bool { + (a - b).abs() <= 1e-6 + } + fn close2(a: V2, b: V2) -> bool { + close(a[0], b[0]) && close(a[1], b[1]) + } + + /// Gerüst: Projekt in `unit`, Gebäude, Geschosse EG (z = 0) und OG (z = 3), dazu `body`. + fn file(unit: &str, body: &str) -> String { + format!( + "ISO-10303-21;\nHEADER;\nFILE_SCHEMA(('IFC4'));\nENDSEC;\nDATA;\n\ +#1=IFCPROJECT('0proj',$,'P',$,$,$,$,$,#2);\n#2=IFCUNITASSIGNMENT((#3,#4));\n{unit}\n\ +#4=IFCSIUNIT(*,.PLANEANGLEUNIT.,$,.RADIAN.);\n\ +#10=IFCCARTESIANPOINT((0.,0.,0.));\n#11=IFCDIRECTION((0.,0.,1.));\n#12=IFCDIRECTION((1.,0.,0.));\n\ +#13=IFCAXIS2PLACEMENT3D(#10,$,$);\n#14=IFCLOCALPLACEMENT($,#13);\n\ +#20=IFCBUILDING('0bldg',$,'B',$,$,#14,$,$,.ELEMENT.,$,$,$);\n\ +#22=IFCLOCALPLACEMENT(#14,#13);\n#23=IFCBUILDINGSTOREY('0eg',$,'EG',$,$,#22,$,$,.ELEMENT.,0.);\n\ +#24=IFCCARTESIANPOINT((0.,0.,3.));\n#25=IFCAXIS2PLACEMENT3D(#24,$,$);\n#26=IFCLOCALPLACEMENT(#14,#25);\n\ +#27=IFCBUILDINGSTOREY('0og',$,'OG',$,$,#26,$,$,.ELEMENT.,3.);\n\ +#28=IFCRELAGGREGATES('0agg',$,$,$,#20,(#23,#27));\n\ +{body}\n\ +ENDSEC;\nEND-ISO-10303-21;\n" + ) + } + const METRE: &str = "#3=IFCSIUNIT(*,.LENGTHUNIT.,$,.METRE.);"; + const MILLI: &str = "#3=IFCSIUNIT(*,.LENGTHUNIT.,.MILLI.,.METRE.);"; + + /// Rechteck-Extrusion als Bauteil `class` mit id `#n`, Platzierung relativ zu `#22` (EG). + /// Profil: Mitte (cx,cy), Grösse (x,y), Höhe h, Drehung der Platzierung um z (Richtung dx,dy). + #[allow(clippy::too_many_arguments)] + fn rect_product(n: u64, class: &str, at: (f64, f64, f64), dir: (f64, f64), size: (f64, f64), h: f64, extra: &str) -> String { + let b = n * 10; + format!( + "#{p}=IFCCARTESIANPOINT(({x},{y},{z}));#{d}=IFCDIRECTION(({dx},{dy},0.));#{a}=IFCAXIS2PLACEMENT3D(#{p},#11,#{d});\ +#{lp}=IFCLOCALPLACEMENT(#22,#{a});#{pp}=IFCCARTESIANPOINT(({cx},{cy}));#{a2}=IFCAXIS2PLACEMENT2D(#{pp},$);\ +#{pr}=IFCRECTANGLEPROFILEDEF(.AREA.,$,#{a2},{sx},{sy});#{ex}=IFCEXTRUDEDAREASOLID(#{pr},#13,#11,{h});\ +#{rep}=IFCSHAPEREPRESENTATION($,'Body','SweptSolid',(#{ex}));#{ps}=IFCPRODUCTDEFINITIONSHAPE($,$,(#{rep}));\ +#{n}={class}('g{n}',$,'E{n}',$,$,#{lp},#{ps},$,${extra});#{rc}=IFCRELCONTAINEDINSPATIALSTRUCTURE('r{n}',$,$,$,(#{n}),#23);\n", + p = b + 1, + d = b + 2, + a = b + 3, + lp = b + 4, + pp = b + 5, + a2 = b + 6, + pr = b + 7, + ex = b + 8, + rep = b + 9, + ps = b + 10_000, + rc = b + 20_000, + x = at.0, + y = at.1, + z = at.2, + dx = dir.0, + dy = dir.1, + cx = size.0 / 2.0, + cy = 0.0, + sx = size.0, + sy = size.1, + ) + } + + fn sem(src: &str) -> (crate::ifc_import::IfcImport, Semantic) { + let r = import_ifc_opts(src.as_bytes(), true).expect("lesbar"); + let s = r.elements.clone().expect("Bauteile"); + (r, s) + } + + #[test] + fn rectangle_walls_with_l_corner_and_t_junction() { + // Wand A: (−0.15,0) → (5.15,0), 0.3 dick, 2.5 hoch; Wand B: (5,0) → (5,4), über die Ecke gezogen + // (Körper bis zur Aussenkante); Wand C: Innenwand x = 2, endet an der Innenfläche von A. + let a = rect_product(100, "IFCWALL", (-0.15, 0.0, 0.0), (1.0, 0.0), (5.3, 0.3), 2.5, ""); + let b = rect_product(200, "IFCWALLSTANDARDCASE", (5.0, -0.15, 0.0), (0.0, 1.0), (4.15, 0.3), 2.5, ""); + let c = rect_product(300, "IFCWALL", (2.0, 0.15, 0.0), (0.0, 1.0), (2.0, 0.1), 2.5, ""); + let (r, s) = sem(&file(METRE, &format!("{a}{b}{c}"))); + assert_eq!(s.walls.len(), 3, "{:?}", s.kept); + assert!(r.products.is_empty(), "erkannte Wände nicht als Mesh"); + assert_eq!(s.storeys.len(), 2); + assert_eq!((s.storeys[0].name.as_str(), s.storeys[1].elevation), ("EG", 3.0)); + let find = |g: &str| s.walls.iter().find(|w| w.info.global_id == g).unwrap(); + let wa = find("g100"); + let ends = |w: &Wall| { + let mut e = [w.start, w.end]; + e.sort_by(|p, q| p[0].total_cmp(&q[0]).then(p[1].total_cmp(&q[1]))); + e + }; + // Links ohne Partner: bleibt bis zur Körperkante; rechts auf die Achse von B gezogen. + assert!(close2(ends(wa)[0], [-0.15, 0.0]) && close2(ends(wa)[1], [5.0, 0.0]), "{wa:?}"); + assert!(close(wa.thickness, 0.3) && close(wa.z0, 0.0) && close(wa.z1, 2.5)); + assert_eq!(wa.info.storey, Some(0)); + let wb = find("g200"); + assert!(close2(ends(wb)[0], [5.0, 0.0]) && close2(ends(wb)[1], [5.0, 4.0]), "{wb:?}"); + let wc = find("g300"); + assert!(close2(ends(wc)[0], [2.0, 0.0]) && close2(ends(wc)[1], [2.0, 2.15]), "{wc:?}"); + assert!(close(wc.thickness, 0.1)); + } + + #[test] + fn door_window_and_hole_in_wall_with_layer_set_usage() { + // Wand (0,0) → (6,0), 0.3 dick (in mm), Schichten 0.02 / 0.28 mit Usage POSITIVE → erste + // Schicht auf −y der Platzierung = rechts der Richtung +x. + let wall = rect_product(100, "IFCWALL", (0.0, 0.0, 0.0), (1.0, 0.0), (6000.0, 300.0), 2800.0, ""); + // Öffnungen: Platzierung relativ zur Wand; Quader x ∈ [1,1.9], y über die Wand, z ∈ [0,2.1]. + let opening = |n: u64, x0: f64, w: f64, z0: f64, h: f64| -> String { + let b = n * 10; + format!( + "#{p}=IFCCARTESIANPOINT(({x0},-200.,{z0}));#{a}=IFCAXIS2PLACEMENT3D(#{p},$,$);#{lp}=IFCLOCALPLACEMENT(#1004,#{a});\ +#{pp}=IFCCARTESIANPOINT(({cx},200.));#{a2}=IFCAXIS2PLACEMENT2D(#{pp},$);#{pr}=IFCRECTANGLEPROFILEDEF(.AREA.,$,#{a2},{w},400.);\ +#{ex}=IFCEXTRUDEDAREASOLID(#{pr},#13,#11,{h});#{rep}=IFCSHAPEREPRESENTATION($,'Body','SweptSolid',(#{ex}));\ +#{ps}=IFCPRODUCTDEFINITIONSHAPE($,$,(#{rep}));#{n}=IFCOPENINGELEMENT('o{n}',$,$,$,$,#{lp},#{ps},$,.OPENING.);\ +#{rv}=IFCRELVOIDSELEMENT('v{n}',$,$,$,#100,#{n});\n", + p = b + 1, + a = b + 2, + lp = b + 3, + pp = b + 4, + a2 = b + 5, + pr = b + 6, + ex = b + 7, + rep = b + 8, + ps = b + 9, + rv = b + 10_000, + cx = w / 2.0, + ) + }; + let fill = |n: u64, o: u64, class: &str| format!("#{n}={class}('f{n}',$,'F{n}',$,$,#1004,$,$,$,$,$,$,$);#{r}=IFCRELFILLSELEMENT('rf{n}',$,$,$,#{o},#{n});\n", r = n + 1); + let layers = "#900=IFCMATERIAL('Putz',$,$);#901=IFCMATERIAL('Beton',$,$);#902=IFCMATERIALLAYER(#900,20.,$,$,$,$,$);\ +#903=IFCMATERIALLAYER(#901,280.,$,$,$,$,$);#904=IFCMATERIALLAYERSET((#902,#903),'AW 30',$);\ +#905=IFCMATERIALLAYERSETUSAGE(#904,.AXIS2.,.POSITIVE.,-150.,$);#906=IFCRELASSOCIATESMATERIAL('m',$,$,$,(#100),#905);\n"; + let src = file( + MILLI, + &format!( + "{wall}{}{}{}{}{}{layers}", + opening(500, 1000.0, 900.0, 0.0, 2100.0), + opening(600, 3000.0, 1200.0, 900.0, 1300.0), + opening(700, 5000.0, 800.0, 0.0, 2000.0), + fill(800, 500, "IFCDOOR"), + fill(810, 600, "IFCWINDOW"), + ), + ); + let (r, s) = sem(&src); + assert_eq!(s.walls.len(), 1, "{:?}", s.kept); + let w = &s.walls[0]; + // Erste Schicht (Putz) auf −y der Platzierung, Dossier: rechts → Richtung +x bleibt. + assert!(close2(w.start, [0.0, 0.0]) && close2(w.end, [6.0, 0.0]), "{w:?}"); + assert_eq!(w.info.layers.len(), 2); + assert!(close(w.info.layers[0].thickness, 0.02) && w.info.layers[0].material == "Putz"); + assert_eq!(w.info.type_name.as_deref(), Some("AW 30")); + assert_eq!(s.openings.len(), 3); + let o: Vec<_> = s.openings.iter().map(|o| (o.kind, (o.position * 1e6).round() / 1e6, (o.width * 1e6).round() / 1e6, (o.sill * 1e6).round() / 1e6, (o.height * 1e6).round() / 1e6)).collect(); + assert_eq!(o[0], (OpeningKind::Door, 1.0, 0.9, 0.0, 2.1)); + assert_eq!(o[1], (OpeningKind::Window, 3.0, 1.2, 0.9, 1.3)); + assert_eq!(o[2], (OpeningKind::Hole, 5.0, 0.8, 0.0, 2.0)); + assert_eq!(s.openings[0].info.global_id, "f800"); + assert_eq!(s.openings[2].info.global_id, "o700"); + assert!(r.products.is_empty()); + assert!(r.skipped_products.is_empty(), "{:?}", r.skipped_products); + + // NEGATIVE → erste Schicht links von +x → Richtung umgekehrt, Positionen ab dem neuen Start. + let (_, s) = sem(&src.replace(".POSITIVE.", ".NEGATIVE.")); + let w = &s.walls[0]; + assert!(close2(w.start, [6.0, 0.0]) && close2(w.end, [0.0, 0.0]), "{w:?}"); + assert!(close(s.openings[0].position, 6.0 - 1.9)); + } + + #[test] + fn wall_with_niche_or_round_shape_stays_mesh() { + // Öffnung nur halb durch die Wand (Nische): ganze Wand bleibt Mesh, samt Füllung. + let wall = rect_product(100, "IFCWALL", (0.0, 0.0, 0.0), (1.0, 0.0), (4.0, 0.3), 2.5, ""); + let niche = "#501=IFCCARTESIANPOINT((1.,0.,0.5));#502=IFCAXIS2PLACEMENT3D(#501,$,$);#503=IFCLOCALPLACEMENT(#1004,#502);\ +#504=IFCCARTESIANPOINT((0.5,0.));#505=IFCAXIS2PLACEMENT2D(#504,$);#506=IFCRECTANGLEPROFILEDEF(.AREA.,$,#505,1.,0.2);\ +#507=IFCEXTRUDEDAREASOLID(#506,#13,#11,1.);#508=IFCSHAPEREPRESENTATION($,'Body','SweptSolid',(#507));\ +#509=IFCPRODUCTDEFINITIONSHAPE($,$,(#508));#500=IFCOPENINGELEMENT('o',$,$,$,$,#503,#509,$,.RECESS.);\ +#510=IFCRELVOIDSELEMENT('v',$,$,$,#100,#500);"; + let (r, s) = sem(&file(METRE, &format!("{wall}{niche}"))); + assert!(s.walls.is_empty()); + assert_eq!(s.kept.get("IfcWall"), Some(&1)); + assert_eq!(r.products.len(), 1); + assert_eq!(r.voids_applied, 1); + // Runde Wand (Kreisprofil) ist kein Rechteck. + let round = "#101=IFCCARTESIANPOINT((0.,0.));#102=IFCAXIS2PLACEMENT2D(#101,$);#103=IFCCIRCLEHOLLOWPROFILEDEF(.AREA.,$,#102,3.,0.3);\ +#104=IFCEXTRUDEDAREASOLID(#103,#13,#11,2.5);#105=IFCSHAPEREPRESENTATION($,'Body','SweptSolid',(#104));\ +#106=IFCPRODUCTDEFINITIONSHAPE($,$,(#105));#100=IFCWALL('w',$,$,$,$,#22,#106,$,$);"; + let (r, s) = sem(&file(METRE, round)); + assert!(s.walls.is_empty()); + assert_eq!(r.products.len(), 1); + } + + #[test] + fn slab_with_hole_and_opening_columns_and_space() { + // Decke 6 × 4, 0.25 dick, OK auf 3.0, Loch 1 × 1 im Profil und Öffnung 0.5 × 0.5 durch. + let slab = "#101=IFCCARTESIANPOINT((0.,0.));#102=IFCCARTESIANPOINT((6.,0.));#103=IFCCARTESIANPOINT((6.,4.));#104=IFCCARTESIANPOINT((0.,4.));\ +#105=IFCPOLYLINE((#101,#102,#103,#104,#101));#106=IFCCARTESIANPOINT((1.,1.));#107=IFCCARTESIANPOINT((2.,1.));#108=IFCCARTESIANPOINT((2.,2.));\ +#109=IFCCARTESIANPOINT((1.,2.));#110=IFCPOLYLINE((#106,#107,#108,#109,#106));#111=IFCARBITRARYPROFILEDEFWITHVOIDS(.AREA.,$,#105,(#110));\ +#112=IFCCARTESIANPOINT((0.,0.,2.75));#113=IFCAXIS2PLACEMENT3D(#112,$,$);#114=IFCEXTRUDEDAREASOLID(#111,#113,#11,0.25);\ +#115=IFCSHAPEREPRESENTATION($,'Body','SweptSolid',(#114));#116=IFCPRODUCTDEFINITIONSHAPE($,$,(#115));\ +#100=IFCSLAB('s',$,'Decke',$,$,#22,#116,$,.FLOOR.);#117=IFCRELCONTAINEDINSPATIALSTRUCTURE('rs',$,$,$,(#100,#300,#400,#500),#23);\ +#201=IFCCARTESIANPOINT((4.,2.,2.5));#202=IFCAXIS2PLACEMENT3D(#201,$,$);#203=IFCLOCALPLACEMENT(#22,#202);\ +#204=IFCRECTANGLEPROFILEDEF(.AREA.,$,$,0.5,0.5);#205=IFCEXTRUDEDAREASOLID(#204,#13,#11,1.);\ +#206=IFCSHAPEREPRESENTATION($,'Body','SweptSolid',(#205));#207=IFCPRODUCTDEFINITIONSHAPE($,$,(#206));\ +#200=IFCOPENINGELEMENT('o',$,$,$,$,#203,#207,$,.OPENING.);#208=IFCRELVOIDSELEMENT('v',$,$,$,#100,#200);\ +#301=IFCCARTESIANPOINT((3.,3.,0.));#302=IFCDIRECTION((0.,1.,0.));#303=IFCAXIS2PLACEMENT3D(#301,#11,#302);#304=IFCLOCALPLACEMENT(#22,#303);\ +#305=IFCRECTANGLEPROFILEDEF(.AREA.,$,$,0.4,0.3);#306=IFCEXTRUDEDAREASOLID(#305,#13,#11,2.75);\ +#307=IFCSHAPEREPRESENTATION($,'Body','SweptSolid',(#306));#308=IFCPRODUCTDEFINITIONSHAPE($,$,(#307));\ +#300=IFCCOLUMN('c1',$,'S1',$,$,#304,#308,$,$);\ +#401=IFCCARTESIANPOINT((1.,3.,0.));#402=IFCAXIS2PLACEMENT3D(#401,$,$);#403=IFCLOCALPLACEMENT(#22,#402);\ +#404=IFCCIRCLEPROFILEDEF(.AREA.,$,$,0.15);#405=IFCEXTRUDEDAREASOLID(#404,#13,#11,2.75);\ +#406=IFCSHAPEREPRESENTATION($,'Body','SweptSolid',(#405));#407=IFCPRODUCTDEFINITIONSHAPE($,$,(#406));\ +#400=IFCCOLUMN('c2',$,'S2',$,$,#403,#407,$,$);\ +#501=IFCCARTESIANPOINT((0.,0.));#502=IFCCARTESIANPOINT((3.,0.));#503=IFCCARTESIANPOINT((3.,2.));#504=IFCCARTESIANPOINT((0.,2.));\ +#505=IFCPOLYLINE((#501,#502,#503,#504,#501));#506=IFCARBITRARYCLOSEDPROFILEDEF(.AREA.,$,#505);#507=IFCEXTRUDEDAREASOLID(#506,#13,#11,2.5);\ +#508=IFCSHAPEREPRESENTATION($,'Body','SweptSolid',(#507));#509=IFCPRODUCTDEFINITIONSHAPE($,$,(#508));\ +#500=IFCSPACE('sp',$,'1.01',$,$,#22,#509,'K\\X2\\00FC\\X0\\che',.ELEMENT.,.INTERNAL.,$);\ +#510=IFCPROPERTYSINGLEVALUE('SIA416',$,IFCLABEL('HNF'),$);#511=IFCPROPERTYSET('ps',$,'CH_Raum',$,(#510));\ +#512=IFCRELDEFINESBYPROPERTIES('rp',$,$,$,(#500),#511);"; + let (r, s) = sem(&file(METRE, slab)); + assert!(r.products.is_empty(), "{:?}", r.products.iter().map(|p| &p.class).collect::>()); + assert_eq!(s.slabs.len(), 1, "{:?}", s.kept); + let sl = &s.slabs[0]; + assert!(close(sl.z0, 2.75) && close(sl.z1, 3.0)); + assert_eq!(sl.outline.len(), 4); + assert!(close(area2(&sl.outline), 24.0)); + assert_eq!(sl.holes.len(), 2); + let mut ha: Vec = sl.holes.iter().map(|h| area2(h).abs()).collect(); + ha.sort_by(f64::total_cmp); + assert!(close(ha[0], 0.25) && close(ha[1], 1.0), "{ha:?}"); + assert_eq!(s.columns.len(), 2); + let c1 = s.columns.iter().find(|c| c.info.global_id == "c1").unwrap(); + // Profil 0.4 (x) × 0.3, Platzierung um 90° gedreht → Breite 0.3 entlang x, Tiefe 0.4. + assert!(close2(c1.center, [3.0, 3.0]) && close(c1.rotation, 0.0), "{c1:?}"); + assert_eq!(c1.profile.round(), Profile::Rect { width: 0.3, depth: 0.4 }); + let c2 = s.columns.iter().find(|c| c.info.global_id == "c2").unwrap(); + match c2.profile { + Profile::Round { radius } => assert!(close(radius, 0.15)), + p => panic!("{p:?}"), + } + assert!(close2(c2.center, [1.0, 3.0])); + assert_eq!(s.spaces.len(), 1); + let sp = &s.spaces[0]; + assert_eq!((sp.long_name.as_deref(), sp.sia.as_deref(), sp.info.name.as_deref()), (Some("Küche"), Some("HNF"), Some("1.01"))); + assert!(close(area2(&sp.boundary), 6.0)); + assert!(r.skipped_products.is_empty(), "{:?}", r.skipped_products); + } + + impl Profile { + /// Auf 1e-9 gerundet (Vergleich in Tests). + fn round(self) -> Profile { + let r = |x: f64| (x * 1e9).round() / 1e9; + match self { + Profile::Rect { width, depth } => Profile::Rect { width: r(width), depth: r(depth) }, + Profile::Round { radius } => Profile::Round { radius: r(radius) }, + } + } + } + + #[test] + fn helpers_rect_hull_loops() { + let pts = [[0.0, 0.0], [4.0, 1.0], [3.5, 3.0], [-0.5, 2.0], [1.0, 1.0]]; + let (d, u0, u1, v0, v1) = min_area_rect(&pts).unwrap(); + assert!((u1 - u0) >= (v1 - v0) && d[0] >= 0.0); + assert!(convex_hull(&[[0.0, 0.0]]).len() == 1); + assert!(min_area_rect(&[[0.0, 0.0], [1.0, 1.0]]).is_none()); + assert!(simplify_ring(&[[0.0, 0.0], [1.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0], [0.0, 0.0]]).len() == 4); + assert!(boundary_loops(&[]).is_empty()); + } + + #[test] + fn nonsense_never_panics() { + for src in [ + file(METRE, "#100=IFCWALL('w',$,$,$,$,#999,#998,$,$);#998=IFCPRODUCTDEFINITIONSHAPE($,$,(#997));#997=IFCSHAPEREPRESENTATION($,'Body',$,(#1));"), + file(METRE, "#100=IFCSLAB('s',$,$,$,$,$,$,$,$);#101=IFCRELVOIDSELEMENT('v',$,$,$,#100,#100);#102=IFCRELFILLSELEMENT('f',$,$,$,#100,#100);"), + file(METRE, "#100=IFCMATERIALLAYERSETUSAGE(#100,.AXIS2.,.POSITIVE.,0.,$);#101=IFCRELASSOCIATESMATERIAL('m',$,$,$,(#102),#100);#102=IFCWALL('w',$,$,$,$,$,$,$,$);"), + file(METRE, "#100=IFCBUILDINGSTOREY('x',$,$,$,$,#100,$,$,$,1e400);"), + ] { + let _ = import_ifc_opts(src.as_bytes(), true); + } + } +} diff --git a/src-tauri/fileio/src/lib.rs b/src-tauri/fileio/src/lib.rs index 726204fb..d9a772db 100644 --- a/src-tauri/fileio/src/lib.rs +++ b/src-tauri/fileio/src/lib.rs @@ -18,6 +18,7 @@ pub mod split; mod web_import; pub mod ifc_step; pub mod ifc_import; +pub mod ifc_semantic; pub mod ifc_export; pub mod csg; mod ifc_sweep; diff --git a/src/App.tsx b/src/App.tsx index 79620e58..e2e9dbbc 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -55,6 +55,8 @@ import { Toast } from "./ui/Toast"; import { isTauriRuntime, PROJECT_TEMPLATE_EXT } from "./native/projectFile"; import { stepTextToImportedMeshes } from "./io/stepImport"; import { formatIfcReport, ifcBytesToImportedMeshes } from "./io/ifcImport"; +import { formatIfcElementsSummary, ifcElementsToProject, readIfcElements } from "./io/ifcElements"; +import { IfcImportDialog, type IfcImportMode } from "./ui/IfcImportDialog"; import { projectGeoOrigin } from "./model/geoRebase"; import { applyClashMarkers, runClashCheck } from "./analysis/clash"; import { checkForUpdate } from "./update/checkForUpdate"; @@ -1698,8 +1700,37 @@ export default function App() { setRoomStamp, } = useProjectActions(setProject, notify, planViewRef); - // IFC-Import ([B3]): Bauteile als Kontext-Meshes (Format-Modul, `io/ifcImport.ts`), Bericht als Toast. - const importIfcFile = (f: File) => { + // IFC-Import: erst die Wahl Mesh/Bauteile (`IfcImportDialog`), dann [B3] Kontext-Meshes + // (`io/ifcImport.ts`) oder [B4] echte Bauteile (`io/ifcElements.ts`, übernommen über setProject). + const [pendingIfc, setPendingIfc] = useState(null); + const importIfcFile = (f: File) => setPendingIfc(f); + const runIfcImport = (f: File, mode: IfcImportMode) => { + if (mode === "elements") { + void f + .arrayBuffer() + .then((buf) => readIfcElements(new Uint8Array(buf))) + .then(({ products, report, elements }) => { + let summary: ReturnType["summary"] | null = null; + let bounds: { x: number; y: number }[] = []; + setProject((p) => { + const r = ifcElementsToProject(p, products, elements, { fileName: f.name, geoOrigin: projectGeoOrigin(p) }); + summary = r.summary; + const added = new Set(p.walls.map((w) => w.id)); + bounds = r.project.walls.filter((w) => !added.has(w.id)).flatMap((w) => [w.start, w.end]); + return r.project; + }); + if (bounds.length) planViewRef.current?.fitBounds(bounds); + if (summary) { + const s: ReturnType["summary"] = summary; + const empty = s.walls + s.ceilings + s.columns + s.rooms + s.meshes === 0; + notify(formatIfcElementsSummary(s, report, t), empty || report.truncated ? "warning" : "info"); + } + }) + .catch((err) => + notify(`${t("ifc.import.failed")}: ${err instanceof Error ? err.message : String(err)}`, "error"), + ); + return; + } void f .arrayBuffer() .then((buf) => ifcBytesToImportedMeshes(new Uint8Array(buf), f.name, { geoOrigin: projectGeoOrigin(project) })) @@ -3998,6 +4029,18 @@ export default function App() { /> )} + {pendingIfc && ( + setPendingIfc(null)} + onImport={(mode) => { + const f = pendingIfc; + setPendingIfc(null); + runIfcImport(f, mode); + }} + /> + )} + {pendingDiscard && ( setPendingDiscard(null)} diff --git a/src/cli/main.ts b/src/cli/main.ts index 698b4b25..23d0defd 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -9,8 +9,9 @@ // dossier-cli section [--out schnitt.svg] (braucht render3d-WASM) // dossier-cli elevation [--out ansicht.svg] // dossier-cli dxf|dwg|ifc|step|obj|stl|schedule|kennzahlen|sun [--level EG] [--out datei] -// dossier-cli import-ifc [--out neu.obp] [--group product|class] -// IFC als Kontext-Meshes ([B3]); Bericht als JSON auf stdout +// dossier-cli import-ifc [--out neu.obp] [--group product|class] [--elements] +// IFC als Kontext-Meshes ([B3]), mit --elements als echte +// Bauteile ([B4]); Bericht als JSON auf stdout // dossier-cli model3d [--out modell.json] 3D-Modell fürs Headless-Rendern (render_png) // dossier-cli mcp MCP-Server (stdio): project_info, query, render_svg, apply_ops, validate // dossier-cli bench [--runs 10] Zeitprofil der Ableitungen (ms je Aufruf) @@ -25,6 +26,8 @@ import { buildPlanDwg, loadFileio, readIfc, + readIfcElements, + ifcElementsToProject, ifcToImportedMeshes, projectGeoOrigin, ensureContextCategories, @@ -269,9 +272,22 @@ export async function run(argv: string[]): Promise { } catch (e) { fail(`Datei nicht lesbar: ${src} (${e instanceof Error ? e.message : String(e)})`); } - const { products, report } = await readIfc(bytes); const group = args.flags.get("group"); - const meshes = ifcToImportedMeshes(products, src.split(/[\\/]/).pop() ?? src, { + const fileName = src.split(/[\\/]/).pop() ?? src; + if (args.flags.has("elements")) { + const { products, report, elements } = await readIfcElements(bytes); + const r = ifcElementsToProject(project, products, elements, { + fileName, + geoOrigin: projectGeoOrigin(project), + group: group === "product" || group === "class" ? group : "auto", + }); + process.stdout.write(JSON.stringify({ ...report, products: undefined, elements: r.summary, kept: elements.kept }, null, 2) + "\n"); + const target = args.flags.get("out"); + if (target) out(args, serializeProject(applyOps(project, diffToOps(project, r.project))), target); + return 0; + } + const { products, report } = await readIfc(bytes); + const meshes = ifcToImportedMeshes(products, fileName, { geoOrigin: projectGeoOrigin(project), group: group === "product" || group === "class" ? group : "auto", }); diff --git a/src/core/extra.ts b/src/core/extra.ts index f50ec927..fa7c5bb9 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -7,6 +7,7 @@ export { buildPlanDxf } from "../export/exportDxf"; export { buildPlanDwg } from "../export/exportDxf"; export { loadFileio } from "../engine/fileioWasm"; export { readIfc, ifcToImportedMeshes } from "../io/ifcImport"; +export { readIfcElements, ifcElementsToProject } from "../io/ifcElements"; export { projectGeoOrigin } from "../model/geoRebase"; export { ensureContextCategories } from "../model/contextCategories"; export { projectToWorldCoords } from "../model/geoRebase"; diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 95548559..7dd94e6c 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -1763,6 +1763,14 @@ export const de = { "ifc.import.voids": "{n} Öffnungen nicht abgezogen", "ifc.import.booleans": "{n} Boolesche Körper vereinfacht (nur erster Operand)", "ifc.import.truncated": "abgebrochen: zu viele Dreiecke", + "ifc.import.elements": "{schema} importiert: {walls} Wände, {openings} Türen/Fenster, {ceilings} Decken, {columns} Stützen, {rooms} Räume, {floors} neue Geschosse; {meshes} Bauteile als Kontext-Meshes", + "ifc.import.kept": "{n} Wände/Decken/Stützen/Räume nicht sicher abbildbar, als Mesh übernommen", + "ifc.importDialog.title": "IFC importieren", + "ifc.importDialog.asMesh": "Als Kontext-Meshes (Standard)", + "ifc.importDialog.asMeshHint": "Jedes Bauteil als nicht bearbeitbares Mesh der Kontext-Schicht, wie in der Datei.", + "ifc.importDialog.asElements": "Als Bauteile", + "ifc.importDialog.asElementsHint": "Wände, Decken, Stützen, Türen/Fenster, Räume und Geschosse werden bearbeitbare Dossier-Bauteile; was nicht sicher abbildbar ist, bleibt Mesh.", + "ifc.importDialog.import": "Importieren", "recover.title": "Ungesicherte Arbeit gefunden", "recover.message": "Von „{name}“ gibt es eine automatische Sicherung vom {when}, die nicht gespeichert wurde.", "recover.unsaved": "unbenanntes Projekt", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index e4b7c3d6..21a94d02 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -1724,6 +1724,14 @@ export const en: Record = { "ifc.import.voids": "{n} openings not subtracted", "ifc.import.booleans": "{n} boolean solids simplified (first operand only)", "ifc.import.truncated": "aborted: too many triangles", + "ifc.import.elements": "{schema} imported: {walls} walls, {openings} doors/windows, {ceilings} slabs, {columns} columns, {rooms} rooms, {floors} new storeys; {meshes} elements as context meshes", + "ifc.import.kept": "{n} walls/slabs/columns/rooms not safely mappable, kept as mesh", + "ifc.importDialog.title": "Import IFC", + "ifc.importDialog.asMesh": "As context meshes (default)", + "ifc.importDialog.asMeshHint": "Every element as a non-editable mesh on the context layer, as in the file.", + "ifc.importDialog.asElements": "As building elements", + "ifc.importDialog.asElementsHint": "Walls, slabs, columns, doors/windows, rooms and storeys become editable Dossier elements; anything not safely mappable stays a mesh.", + "ifc.importDialog.import": "Import", "recover.title": "Unsaved work found", "recover.message": "There is an automatic backup of “{name}” from {when} that was never saved.", "recover.unsaved": "untitled project", diff --git a/src/io/ifcElements.test.ts b/src/io/ifcElements.test.ts new file mode 100644 index 00000000..04eeec5c --- /dev/null +++ b/src/io/ifcElements.test.ts @@ -0,0 +1,201 @@ +// IFC-Import zu echten Bauteilen ([B4]): Rundreise eigener Export → Import als Bauteile → gleiche +// Wände/Öffnungen/Decken/Räume (Lage, Dicke, Höhe, Typ) wie das Original (Demo-Haus); dazu Farbe und +// GlobalId am Kontext-Mesh ([B3]-Nachtrag) und die Speichern/Laden-Rundreise. + +import "../engine/fileioWasm.setup"; +import { describe, expect, it } from "vitest"; +import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"; +import { join } from "node:path"; +import { applyOps, diffToOps, validateProject } from "../core/ops"; +import { exportIfcSpf } from "../export/exportIfc"; +import { emptyProject, sampleProject } from "../model/sampleProject"; +import type { Column, Opening, Project, Vec2, Wall } from "../model/types"; +import { wallTypeThickness } from "../model/types"; +import { formatIfcElementsSummary, ifcElementsToProject, readIfcElements } from "./ifcElements"; +import { ifcToImportedMeshes, readIfc, type IfcProduct } from "./ifcImport"; +import { parseProjectFile, serializeProject } from "./projectFormat"; + +const bytesOf = (s: string) => new TextEncoder().encode(s); +const near = (a: Vec2, b: Vec2, tol = 1e-6) => Math.hypot(a.x - b.x, a.y - b.y) <= tol; +const symmetric = (p: Project, wallTypeId: string) => { + const l = p.wallTypes.find((t) => t.id === wallTypeId)!.layers; + return l.every((x, i) => x.componentId === l[l.length - 1 - i].componentId && Math.abs(x.thickness - l[l.length - 1 - i].thickness) < 1e-9); +}; + +async function importInto(base: Project, src: Project) { + const { products, report, elements } = await readIfcElements(bytesOf(exportIfcSpf(src))); + const r = ifcElementsToProject(base, products, elements, { fileName: "haus.ifc" }); + return { ...r, report, elements, products }; +} + +describe("IFC-Import als Bauteile: Rundreise Demo-Haus", () => { + it("gleiche Wände (Achse, Typ, Höhe, Geschoss), Öffnungen, Decke, Raum; Rest als Mesh", async () => { + const { project: p, summary, report } = await importInto(emptyProject, sampleProject); + expect(report.parseErrors).toBe(0); + expect(summary).toMatchObject({ walls: 9, openings: 3, ceilings: 1, columns: 0, rooms: 1, floors: 0, wallTypes: 0, ceilingTypes: 0, components: 0, kept: 0 }); + // Dach und Treppe bleiben Kontext-Mesh. + expect((p.context ?? []).map((c) => (c as { layer?: string }).layer).sort()).toEqual(["IfcRoof", "IfcStair"]); + expect(validateProject(p)).toEqual([]); + + const byOrig = new Map(); + for (const w of sampleProject.walls) { + const sym = symmetric(sampleProject, w.wallTypeId); + const got = p.walls.find( + (g) => + g.floorId === w.floorId && + ((near(g.start, w.start) && near(g.end, w.end)) || (sym && near(g.start, w.end) && near(g.end, w.start))), + ); + expect(got, `${w.id} ${JSON.stringify(p.walls.map((x) => [x.start, x.end]))}`).toBeDefined(); + expect(got!.wallTypeId).toBe(w.wallTypeId); + expect(got!.height).toBeCloseTo(w.height, 9); + expect(got!.bottom).toBeUndefined(); + expect(got!.categoryCode).toBe("20"); + byOrig.set(w.id, got!); + } + for (const o of sampleProject.openings ?? []) { + const host = byOrig.get(o.hostWallId)!; + const got = (p.openings ?? []).find((g) => g.hostWallId === host.id && Math.abs(g.width - o.width) < 1e-6 && g.kind === o.kind) as Opening; + expect(got, o.id).toBeDefined(); + const orig = sampleProject.walls.find((w) => w.id === o.hostWallId)!; + const len = Math.hypot(orig.end.x - orig.start.x, orig.end.y - orig.start.y); + const pos = near(host.start, orig.start) ? o.position : len - o.position - o.width; + expect(got.position).toBeCloseTo(pos, 6); + expect(got.height).toBeCloseTo(o.height, 6); + expect(got.sillHeight).toBeCloseTo(o.sillHeight, 6); + expect(got.typeId).toBe(o.typeId); + } + const c = sampleProject.ceilings![0]; + const gc = p.ceilings![0]; + expect(gc.floorId).toBe(c.floorId); + expect(gc.ceilingTypeId).toBe(c.ceilingTypeId); + expect(gc.top).toBeUndefined(); + expect(gc.outline.length).toBe(c.outline.length); + for (const q of c.outline) expect(gc.outline.some((g) => near(g, q)), JSON.stringify(q)).toBe(true); + const room = sampleProject.rooms![0]; + const gr = p.rooms![0]; + expect([gr.name, gr.siaCategory, gr.floorId]).toEqual([room.name, room.siaCategory, room.floorId]); + for (const q of room.boundary) expect(gr.boundary.some((g) => near(g, q))).toBe(true); + const text = formatIfcElementsSummary(summary, report, (k, v) => `${k}${JSON.stringify(v ?? {})}`); + expect(text).toContain('"walls":9'); + }); + + it("in ein Projekt ohne Geschosse/Typen: legt Geschosse, Wand-/Deckentypen und Materialien an", async () => { + const bare: Project = { + ...emptyProject, + drawingLevels: emptyProject.drawingLevels.filter((l) => l.kind !== "floor"), + wallTypes: [], + ceilingTypes: [], + components: [], + }; + const { project: p, summary } = await importInto(bare, sampleProject); + expect(summary).toMatchObject({ walls: 9, openings: 3, ceilings: 1, rooms: 1, floors: 2, wallTypes: 2, ceilingTypes: 1 }); + // Materialien: Aussenputz, Wärmedämmung, Backstein, Innenputz, Zementestrich, Beton. + expect(summary.components).toBe(6); + const floors = p.drawingLevels.filter((l) => l.kind === "floor"); + expect(floors.map((f) => [f.name, f.baseElevation, f.floorHeight])).toEqual([ + ["Erdgeschoss", 0, 2.6], + ["Obergeschoss", 2.6, 2.6], + ]); + const aw = p.wallTypes.find((t) => t.name === "Aussenwand 34.5 cm")!; + expect(wallTypeThickness(aw)).toBeCloseTo(0.345, 9); + expect(aw.layers.map((l) => p.components.find((c) => c.id === l.componentId)!.name)).toEqual([ + "Aussenputz", "Wärmedämmung", "Backstein", "Innenputz", + ]); + expect(p.walls.filter((w) => w.wallTypeId === aw.id).length).toBe(8); + expect(validateProject(p)).toEqual([]); + }); + + it("über Ops angewandt und gespeichert/geladen bleibt alles gleich", async () => { + const { project: next } = await importInto(emptyProject, sampleProject); + const applied = applyOps(emptyProject, diffToOps(emptyProject, next)); + expect(applied.walls).toEqual(next.walls); + expect(applied.openings).toEqual(next.openings); + const back = parseProjectFile(serializeProject(applied)); + expect(back.ok).toBe(true); + if (!back.ok) return; + expect(back.warnings).toEqual([]); + expect(back.project.walls).toEqual(next.walls); + expect(back.project.ceilings).toEqual(next.ceilings); + expect(back.project.context).toEqual(next.context); + }); + + it("Stützen (rechteckig gedreht, rund) und abgesetzte Wand-Unterkante", async () => { + const cols: Column[] = [ + { id: "S1", type: "column", floorId: "eg", categoryCode: "50", position: { x: 1, y: 1 }, profile: { kind: "rect", width: 0.3, depth: 0.5 }, rotation: 0, height: 2.4 }, + { id: "S2", type: "column", floorId: "og", categoryCode: "50", position: { x: 3, y: 2 }, profile: { kind: "round", radius: 0.15 }, rotation: 0, height: 2.5 }, + ]; + const src: Project = { ...sampleProject, columns: cols }; + const { project: p, summary } = await importInto(emptyProject, src); + expect(summary.columns).toBe(2); + const s1 = p.columns!.find((c) => c.profile.kind === "rect")!; + expect(s1.floorId).toBe("eg"); + expect(near(s1.position, { x: 1, y: 1 })).toBe(true); + expect(s1.profile).toEqual({ kind: "rect", width: 0.3, depth: 0.5 }); + expect(s1.rotation).toBeCloseTo(0, 9); + expect(s1.height).toBeCloseTo(2.4, 9); + const s2 = p.columns!.find((c) => c.profile.kind === "round")!; + expect(s2.floorId).toBe("og"); + expect(near(s2.position, { x: 3, y: 2 }, 1e-4)).toBe(true); + expect(s2.profile.kind === "round" && s2.profile.radius).toBeCloseTo(0.15, 6); + }); +}); + +describe("Kontext-Mesh: Farbe und GlobalId", () => { + const product = (color: IfcProduct["color"], globalId = "2O2Fr$t4X7Zf8NOew3FLOH"): IfcProduct => ({ + globalId, + ifcClass: "IfcWall", + name: "Wand", + storey: "EG", + color, + positions: new Float64Array([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1]), + indices: new Uint32Array([0, 2, 1, 0, 1, 3, 0, 3, 2, 1, 2, 3]), + }); + + it("Farbe als #rrggbb, GlobalId als Feld, Name ohne GlobalId", () => { + const [m] = ifcToImportedMeshes([product([1, 0.5, 0, 0.8])], "x.ifc", { group: "product" }); + expect(m.color).toBe("#ff8000"); + expect(m.ifcGlobalId).toBe("2O2Fr$t4X7Zf8NOew3FLOH"); + expect(m.name).toBe("EG: Wand"); + const [n] = ifcToImportedMeshes([product(null, "")], "x.ifc", { group: "product" }); + expect(n.color).toBeUndefined(); + expect(n.ifcGlobalId).toBeUndefined(); + // Zusammengelegt: gemeinsame Farbe nur, wenn alle gleich. + expect(ifcToImportedMeshes([product([1, 0, 0, 1]), product([1, 0, 0, 1])], "x.ifc", { group: "class" })[0].color).toBe("#ff0000"); + expect(ifcToImportedMeshes([product([1, 0, 0, 1]), product([0, 0, 1, 1])], "x.ifc", { group: "class" })[0].color).toBeUndefined(); + }); + + it("Farbe aus der Datei (IfcStyledItem) kommt am Mesh an und übersteht Speichern/Laden", async () => { + const { products } = await readIfc(new Uint8Array(readFileSync(new URL("./testdata/ifc-geometry-cases.ifc", import.meta.url)))); + const meshes = ifcToImportedMeshes(products, "cases.ifc"); + expect(meshes.every((m) => m.ifcGlobalId && !m.name.includes("["))).toBe(true); + const withColor = { ...meshes[0], color: "#336699" }; + const proj: Project = { ...emptyProject, context: [withColor] }; + const back = parseProjectFile(serializeProject(proj)); + expect(back.ok && back.project.context?.[0]).toEqual(withColor); + }); +}); + +// Freie Beispieldateien (github.com/buildingSMART/Sample-Test-Files u. a., nicht im Repo): +// DOSSIER_IFC_SAMPLES=. Prüft: kein Absturz, gültiges Projekt, Zählung je Datei. +const samples = process.env.DOSSIER_IFC_SAMPLES; +describe.skipIf(!samples || !existsSync(samples))("IFC-Import als Bauteile: Beispieldateien", { timeout: 600_000 }, () => { + it("alle Dateien lesbar, Ergebnis gültig", async () => { + const files: string[] = []; + const walk = (d: string) => { + for (const n of readdirSync(d)) { + const f = join(d, n); + if (statSync(f).isDirectory()) walk(f); + else if (/\.ifc$/i.test(n)) files.push(f); + } + }; + walk(samples!); + const rows: string[] = []; + for (const f of files) { + const { products, elements } = await readIfcElements(new Uint8Array(readFileSync(f))); + const { project, summary } = ifcElementsToProject(emptyProject, products, elements, { fileName: f }); + expect(validateProject(project), f).toEqual([]); + rows.push(`${f.slice(samples!.length + 1)}: ${JSON.stringify(summary)}`); + } + process.stderr.write(rows.join("\n") + "\n"); + }); +}); diff --git a/src/io/ifcElements.ts b/src/io/ifcElements.ts new file mode 100644 index 00000000..35a1cd2a --- /dev/null +++ b/src/io/ifcElements.ts @@ -0,0 +1,550 @@ +// IFC-Import zu echten Bauteilen ([B4], zweite Stufe von [25]): baut aus dem, was das Format-Modul +// erkannt hat (`src-tauri/fileio/src/ifc_semantic.rs`: Achse, Dicke, Höhe, Umriss … in Metern), +// Dossier-Objekte — Geschosse, Wände (Wandtyp aus den Materialschichten, wiederverwendet oder neu), +// Türen/Fenster/Wanddurchbrüche, Decken (Deckentyp), Stützen, Räume. Was Rust nicht sicher abbilden +// konnte, kommt wie beim Mesh-Import als Kontext-Mesh (`ifcImport.ts`). +// +// Keine Geometrie-Rechnung hier: TS ordnet nur zu (Geschoss nach Höhe, Typ nach Schichten) und setzt +// die Objekte zusammen. Das Projekt wird nicht verändert — der Aufrufer übernimmt das Ergebnis über +// `setProject` (App) bzw. `diffToOps`/`applyOps` (CLI), also über Ops. + +import { ensureContextCategories } from "../model/contextCategories"; +import type { + Ceiling, + CeilingType, + Column, + Component, + DrawingLevel, + ImportedMesh, + LayerCategory, + Opening, + Project, + Room, + SiaCategory, + Vec2, + Wall, + WallType, +} from "../model/types"; +import { + decodeIfc, + geoShift, + ifcColorHex, + ifcToImportedMeshes, + readIfcFlat, + type IfcFlat, + type IfcImportReport, + type IfcProduct, +} from "./ifcImport"; + +// ── Rohdaten aus Rust ──────────────────────────────────────────────────────────────────────── + +export interface IfcMatLayer { + material: string; + /** 0 = einziges Material ohne Schichtdicke (gilt für die ganze Dicke). */ + thickness: number; + color: [number, number, number, number] | null; +} + +interface IfcInfo { + globalId: string; + ifcClass: string; + name: string | null; + /** Index in `storeys`. */ + storey: number | null; + color: [number, number, number, number] | null; + typeName: string | null; + layers: IfcMatLayer[]; +} + +export interface IfcStoreyData { + globalId: string; + name: string; + elevation: number; +} +export interface IfcWallData extends IfcInfo { + /** Achse; erste Schicht rechts der Richtung start → end (wie Dossier). */ + start: Vec2; + end: Vec2; + z0: number; + z1: number; + thickness: number; +} +export interface IfcOpeningData extends IfcInfo { + /** Index in `walls`. */ + host: number; + kind: "door" | "window" | "hole"; + position: number; + width: number; + sill: number; + height: number; +} +export interface IfcSlabData extends IfcInfo { + outline: Vec2[]; + holes: Vec2[][]; + z0: number; + z1: number; +} +export interface IfcColumnData extends IfcInfo { + center: Vec2; + rotation: number; + profile: { kind: "rect"; width: number; depth: number } | { kind: "round"; radius: number }; + z0: number; + z1: number; +} +export interface IfcSpaceData extends IfcInfo { + longName: string | null; + sia: string | null; + boundary: Vec2[]; + z0: number; + z1: number; +} + +/** Erkannte Bauteile einer Datei. */ +export interface IfcElementsData { + storeys: IfcStoreyData[]; + walls: IfcWallData[]; + openings: IfcOpeningData[]; + slabs: IfcSlabData[]; + columns: IfcColumnData[]; + spaces: IfcSpaceData[]; + /** Nicht sicher abbildbare Kandidaten je Klasse (bleiben Mesh). */ + kept: Record; +} + +interface RawElement extends IfcInfo { + kind: "wall" | "opening" | "slab" | "column" | "space"; + at: number; + n: number; + host?: number; + openingKind?: "door" | "window" | "hole"; + profile?: "rect" | "round"; + longName?: string | null; + sia?: string | null; +} + +/** Erkannte Bauteile aus dem Rohergebnis; `null`, wenn ohne Bauteil-Erkennung gelesen. */ +export function decodeIfcElements(flat: IfcFlat): IfcElementsData | null { + const meta = JSON.parse(flat.meta) as { elements?: { storeys: IfcStoreyData[]; elements: RawElement[]; kept: Record } }; + const raw = meta.elements; + const data = flat.elementData; + if (!raw || !data) return null; + const out: IfcElementsData = { storeys: raw.storeys, walls: [], openings: [], slabs: [], columns: [], spaces: [], kept: raw.kept ?? {} }; + // Wand-Index in Rust → Index in `out.walls` (verworfene Wände fallen heraus). + const wallIndex = new Map(); + let rustWall = 0; + for (const e of raw.elements) { + const v = data.subarray(e.at, e.at + e.n); + if (v.length !== e.n || !v.every(Number.isFinite)) { + if (e.kind === "wall") rustWall++; + continue; + } + const info: IfcInfo = { + globalId: e.globalId, + ifcClass: e.ifcClass, + name: e.name, + storey: e.storey, + color: e.color, + typeName: e.typeName, + layers: e.layers ?? [], + }; + const rings = (start: number, count: number): { rings: Vec2[][]; ok: boolean } => { + const res: Vec2[][] = []; + let i = start; + for (let r = 0; r < count; r++) { + const n = v[i++]; + if (!(n >= 3) || i + 2 * n > v.length) return { rings: res, ok: false }; + const ring: Vec2[] = []; + for (let k = 0; k < n; k++) ring.push({ x: v[i + 2 * k], y: v[i + 2 * k + 1] }); + i += 2 * n; + res.push(ring); + } + return { rings: res, ok: true }; + }; + switch (e.kind) { + case "wall": + if (v.length === 7) { + wallIndex.set(rustWall, out.walls.length); + out.walls.push({ ...info, start: { x: v[0], y: v[1] }, end: { x: v[2], y: v[3] }, z0: v[4], z1: v[5], thickness: v[6] }); + } + rustWall++; + break; + case "opening": { + const host = wallIndex.get(e.host ?? -1); + if (host !== undefined && v.length === 4) { + out.openings.push({ ...info, host, kind: e.openingKind ?? "hole", position: v[0], width: v[1], sill: v[2], height: v[3] }); + } + break; + } + case "slab": { + const r = rings(3, v[2]); + if (r.ok && r.rings.length >= 1) out.slabs.push({ ...info, z0: v[0], z1: v[1], outline: r.rings[0], holes: r.rings.slice(1) }); + break; + } + case "column": + if (v.length === 7) { + const profile = + e.profile === "round" ? { kind: "round" as const, radius: v[5] } : { kind: "rect" as const, width: v[5], depth: v[6] }; + out.columns.push({ ...info, center: { x: v[0], y: v[1] }, rotation: v[2], z0: v[3], z1: v[4], profile }); + } + break; + case "space": { + const r = rings(2, 1); + if (r.ok) out.spaces.push({ ...info, longName: e.longName ?? null, sia: e.sia ?? null, z0: v[0], z1: v[1], boundary: r.rings[0] }); + break; + } + } + } + return out; +} + +/** Liest IFC-Bytes mit Bauteil-Erkennung (im Worker, sonst direkt). */ +export async function readIfcElements( + bytes: Uint8Array, +): Promise<{ products: IfcProduct[]; report: IfcImportReport; elements: IfcElementsData }> { + const flat = await readIfcFlat(bytes, true); + const { products, report } = decodeIfc(flat); + const elements = decodeIfcElements(flat) ?? { storeys: [], walls: [], openings: [], slabs: [], columns: [], spaces: [], kept: {} }; + return { products, report, elements }; +} + +// ── Aufbau der Dossier-Objekte ─────────────────────────────────────────────────────────────── + +export interface IfcElementsOptions { + /** Dateiname (für die Namen der Kontext-Meshes). */ + fileName: string; + /** LV95-Ursprung des Projekts (`projectGeoOrigin`), sonst null. */ + geoOrigin?: { e: number; n: number } | null; + group?: "product" | "class" | "auto"; +} + +/** Was übernommen wurde (für Meldung und Tests). */ +export interface IfcElementsSummary { + walls: number; + openings: number; + ceilings: number; + columns: number; + rooms: number; + /** Neu angelegte Geschosse. */ + floors: number; + wallTypes: number; + ceilingTypes: number; + components: number; + /** Bauteile als Kontext-Mesh. */ + meshes: number; + /** Davon Kandidaten, die nicht sicher abbildbar waren. */ + kept: number; +} + +const WALL_CATEGORY = "20"; +const OPENING_CATEGORY = "21"; +const CEILING_CATEGORY = "30"; +const COLUMN_CATEGORY = "50"; +const ROOM_CATEGORY = "60"; +const ROOM_COLOR = "#6b7280"; +const SIA: readonly SiaCategory[] = ["HNF", "NNF", "VF", "FF", "KGF", "AGF"]; +/** Toleranzen (m): gleiche Höhe eines Geschosses, gleiche Schichtdicke. */ +const LEVEL_TOL = 0.005; +const LAYER_TOL = 0.0005; + +let counter = 0; + +const round = (x: number, step = 1e-9) => Math.round(x / step) * step; + +function flatCategories(list: LayerCategory[], out: LayerCategory[] = []): LayerCategory[] { + for (const c of list) { + out.push(c); + if (c.children) flatCategories(c.children, out); + } + return out; +} + +/** + * Setzt die erkannten Bauteile und die übrigen Kontext-Meshes ins Projekt (neues Objekt, das alte + * bleibt unverändert). Geschosse werden nach Höhe wiederverwendet (±5 mm) oder angelegt, Wand- und + * Deckentypen nach Schichten (Material + Dicke) wiederverwendet oder angelegt, Materialien nach Namen. + */ +export function ifcElementsToProject( + project: Project, + products: IfcProduct[], + elements: IfcElementsData, + opts: IfcElementsOptions, +): { project: Project; summary: IfcElementsSummary } { + const stamp = Date.now().toString(36); + const newId = (kind: string) => `ifc-${kind}-${stamp}-${counter++}`; + const summary: IfcElementsSummary = { + walls: 0, openings: 0, ceilings: 0, columns: 0, rooms: 0, floors: 0, wallTypes: 0, ceilingTypes: 0, components: 0, meshes: 0, + kept: Object.values(elements.kept).reduce((s, n) => s + n, 0), + }; + + // Verschiebung bei Landeskoordinaten: gemeinsam für Bauteile und Meshes. + const extra: number[] = []; + for (const w of elements.walls) extra.push(w.start.x, w.start.y, w.end.x, w.end.y); + for (const s of elements.slabs) for (const p of s.outline) extra.push(p.x, p.y); + for (const c of elements.columns) extra.push(c.center.x, c.center.y); + for (const s of elements.spaces) for (const p of s.boundary) extra.push(p.x, p.y); + const [dx, dy] = geoShift(products, opts.geoOrigin, extra); + const mv = (p: Vec2): Vec2 => ({ x: round(p.x + dx), y: round(p.y + dy) }); + + // ── Geschosse ── + const levels: DrawingLevel[] = [...project.drawingLevels]; + const floorsSorted = () => levels.filter((l) => l.kind === "floor").sort((a, b) => (a.baseElevation ?? 0) - (b.baseElevation ?? 0)); + const topOf = new Map(); + const noteTop = (storey: number | null, z: number) => { + if (storey !== null) topOf.set(storey, Math.max(topOf.get(storey) ?? -Infinity, z)); + }; + for (const w of elements.walls) noteTop(w.storey, w.z1); + for (const c of elements.columns) noteTop(c.storey, c.z1); + const storeyFloor = elements.storeys.map((s, i) => { + const existing = levels.find((l) => l.kind === "floor" && Math.abs((l.baseElevation ?? 0) - s.elevation) <= LEVEL_TOL); + if (existing) return existing.id; + const next = elements.storeys[i + 1]; + const top = topOf.get(i); + const height = next ? next.elevation - s.elevation : top !== undefined && top > s.elevation + 0.5 ? top - s.elevation : 2.6; + const level: DrawingLevel = { + id: newId("floor"), + name: s.name || `IFC ${round(s.elevation, 0.001)}`, + kind: "floor", + visible: true, + locked: false, + floorHeight: round(height, 1e-6), + cutHeight: 1, + baseElevation: round(s.elevation, 1e-6), + }; + // Einfügen vor dem ersten höheren Geschoss, sonst nach dem letzten. + const floors = floorsSorted(); + const higher = floors.find((l) => (l.baseElevation ?? 0) > s.elevation); + const at = higher ? levels.indexOf(higher) : floors.length ? levels.indexOf(floors[floors.length - 1]) + 1 : 0; + levels.splice(at, 0, level); + summary.floors++; + return level.id; + }); + /** Geschoss eines Bauteils: aus der Datei, sonst das höchste mit OK FB ≤ Unterkante. */ + const floorOf = (storey: number | null, z0: number): DrawingLevel => { + const id = storey !== null ? storeyFloor[storey] : undefined; + const byId = id ? levels.find((l) => l.id === id) : undefined; + if (byId) return byId; + const floors = floorsSorted(); + const below = floors.filter((l) => (l.baseElevation ?? 0) <= z0 + LEVEL_TOL); + const f = below[below.length - 1] ?? floors[0]; + if (f) return f; + const level: DrawingLevel = { id: newId("floor"), name: "IFC", kind: "floor", visible: true, locked: false, floorHeight: 2.6, cutHeight: 1, baseElevation: 0 }; + levels.push(level); + summary.floors++; + return level; + }; + const anchorOffset = (z: number, f: DrawingLevel) => round(z - (f.baseElevation ?? 0), 1e-6); + + // ── Materialien und Typen ── + const components: Component[] = [...project.components]; + const hatchId = project.hatches.find((h) => h.id === "none")?.id ?? project.hatches[0]?.id ?? "none"; + const componentFor = (name: string, color: string | undefined): string => { + const key = name.trim().toLowerCase(); + const found = components.find((c) => c.name.trim().toLowerCase() === key); + if (found) return found.id; + const c: Component = { id: newId("component"), name: name.trim() || "IFC", color: color ?? "#b0b0b0", hatchId, joinPriority: 50 }; + components.push(c); + summary.components++; + return c.id; + }; + /** Schichten eines Bauteils der Dicke `t`: die der Datei, wenn sie aufgehen, sonst eine Schicht. */ + const layerSpec = (e: IfcInfo, t: number): { material: string; thickness: number; color?: string }[] => { + const ls = e.layers; + const sum = ls.reduce((s, l) => s + l.thickness, 0); + if (ls.length > 0 && ls.every((l) => l.thickness > 0) && Math.abs(sum - t) <= 0.005) { + return ls.map((l) => ({ material: l.material, thickness: round(l.thickness, 1e-6), color: ifcColorHex(l.color) })); + } + const first = ls.length === 1 ? ls[0] : undefined; + return [{ material: first?.material ?? "", thickness: round(t, 1e-6), color: ifcColorHex(first?.color ?? e.color) }]; + }; + const sameLayers = ( + have: { componentId: string; thickness: number }[], + want: { material: string; thickness: number }[], + ): boolean => + have.length === want.length && + have.every((l, i) => { + if (Math.abs(l.thickness - want[i].thickness) > LAYER_TOL) return false; + const name = components.find((c) => c.id === l.componentId)?.name.trim().toLowerCase() ?? ""; + return want[i].material ? name === want[i].material.trim().toLowerCase() : true; + }); + const typeName = (e: IfcInfo, t: number) => e.typeName?.trim() || `IFC ${round(t * 100, 0.1)} cm`; + const wallTypes: WallType[] = [...project.wallTypes]; + const wallTypeFor = (e: IfcInfo, t: number): string => { + const spec = layerSpec(e, t); + const name = typeName(e, t); + // Ohne Material: nur ein gleich benannter, gleich dicker Typ passt. + const found = wallTypes.find((wt) => sameLayers(wt.layers, spec) && (spec.some((l) => l.material) || wt.name === name)); + if (found) return found.id; + const wt: WallType = { + id: newId("walltype"), + name, + layers: spec.map((l) => ({ componentId: componentFor(l.material, l.color), thickness: l.thickness })), + }; + wallTypes.push(wt); + summary.wallTypes++; + return wt.id; + }; + const ceilingTypes: CeilingType[] = [...(project.ceilingTypes ?? [])]; + const ceilingTypeFor = (e: IfcInfo, t: number): string => { + const spec = layerSpec(e, t); + const name = typeName(e, t); + const found = ceilingTypes.find((ct) => sameLayers(ct.layers, spec) && (spec.some((l) => l.material) || ct.name === name)); + if (found) return found.id; + const ct: CeilingType = { + id: newId("ceilingtype"), + name, + layers: spec.map((l) => ({ componentId: componentFor(l.material, l.color), thickness: l.thickness })), + }; + ceilingTypes.push(ct); + summary.ceilingTypes++; + return ct.id; + }; + + // ── Wände und Öffnungen ── + const walls: Wall[] = []; + for (const w of elements.walls) { + const f = floorOf(w.storey, w.z0); + const height = round(w.z1 - w.z0, 1e-6); + const bottom = anchorOffset(w.z0, f); + walls.push({ + id: newId("wall"), + type: "wall", + floorId: f.id, + categoryCode: WALL_CATEGORY, + start: mv(w.start), + end: mv(w.end), + wallTypeId: wallTypeFor(w, w.thickness), + height, + ...(Math.abs(bottom) > LEVEL_TOL ? { bottom: { mode: "floor" as const, floorId: f.id, offset: bottom } } : {}), + }); + } + const openings: Opening[] = []; + for (const o of elements.openings) { + const host = walls[o.host]; + if (!host) continue; + const kind = o.kind === "window" ? "window" : "door"; + const typeId = o.kind === "door" ? project.doorTypes?.[0]?.id : o.kind === "window" ? project.windowTypes?.[0]?.id : undefined; + openings.push({ + id: newId("opening"), + type: "opening", + hostWallId: host.id, + categoryCode: OPENING_CATEGORY, + kind, + position: round(o.position, 1e-6), + width: round(o.width, 1e-6), + height: round(o.height, 1e-6), + sillHeight: round(o.sill, 1e-6), + ...(o.kind === "hole" ? { doorType: "wandoeffnung" as const } : {}), + ...(typeId ? { typeId } : {}), + }); + } + + // ── Decken, Stützen, Räume ── + const ceilings: Ceiling[] = []; + for (const s of elements.slabs) { + const f = floorOf(s.storey, s.z0); + const t = s.z1 - s.z0; + const floorTop = (f.baseElevation ?? 0) + (f.floorHeight ?? 0); + ceilings.push({ + id: newId("ceiling"), + type: "ceiling", + floorId: f.id, + categoryCode: CEILING_CATEGORY, + outline: s.outline.map(mv), + ...(s.holes.length ? { openings: s.holes.map((h) => h.map(mv)) } : {}), + wallTypeId: project.wallTypes[0]?.id ?? wallTypes[0]?.id ?? "", + ceilingTypeId: ceilingTypeFor(s, t), + ...(Math.abs(s.z1 - floorTop) > LEVEL_TOL ? { top: { mode: "floor" as const, floorId: f.id, offset: anchorOffset(s.z1, f) } } : {}), + }); + } + const columns: Column[] = []; + for (const c of elements.columns) { + const f = floorOf(c.storey, c.z0); + const bottom = anchorOffset(c.z0, f); + const material = c.layers[0]?.material; + columns.push({ + id: newId("column"), + type: "column", + floorId: f.id, + categoryCode: COLUMN_CATEGORY, + position: mv(c.center), + profile: + c.profile.kind === "round" + ? { kind: "round", radius: round(c.profile.radius, 1e-6) } + : { kind: "rect", width: round(c.profile.width, 1e-6), depth: round(c.profile.depth, 1e-6) }, + rotation: c.rotation, + height: round(c.z1 - c.z0, 1e-6), + ...(material ? { componentId: componentFor(material, ifcColorHex(c.layers[0].color ?? c.color)) } : {}), + ...(Math.abs(bottom) > LEVEL_TOL ? { bottom: { mode: "floor" as const, floorId: f.id, offset: bottom } } : {}), + }); + } + const roomColor = flatCategories(project.layers).find((c) => c.code === ROOM_CATEGORY)?.color ?? ROOM_COLOR; + const rooms: Room[] = []; + for (const s of elements.spaces) { + const f = floorOf(s.storey, s.z0); + const boundary = s.boundary.map(mv); + const sia = SIA.find((c) => c === s.sia?.trim().toUpperCase()); + const n = boundary.length; + rooms.push({ + id: newId("room"), + type: "room", + floorId: f.id, + categoryCode: ROOM_CATEGORY, + siaCategory: sia ?? "HNF", + name: s.longName || s.name || `Raum ${(project.rooms?.length ?? 0) + rooms.length + 1}`, + boundary, + color: roomColor, + stampAnchor: { x: boundary.reduce((a, p) => a + p.x, 0) / n, y: boundary.reduce((a, p) => a + p.y, 0) / n }, + }); + } + + // ── Übrige Bauteile als Kontext-Mesh ── + const meshes: ImportedMesh[] = ifcToImportedMeshes(products, opts.fileName, { geoOrigin: opts.geoOrigin, group: opts.group, shift: [dx, dy] }); + summary.walls = walls.length; + summary.openings = openings.length; + summary.ceilings = ceilings.length; + summary.columns = columns.length; + summary.rooms = rooms.length; + summary.meshes = meshes.length; + + const next: Project = { + ...project, + drawingLevels: levels, + components, + wallTypes, + ...(ceilingTypes.length || project.ceilingTypes ? { ceilingTypes } : {}), + walls: [...project.walls, ...walls], + openings: [...(project.openings ?? []), ...openings], + ceilings: [...(project.ceilings ?? []), ...ceilings], + columns: [...(project.columns ?? []), ...columns], + rooms: [...(project.rooms ?? []), ...rooms], + ...(meshes.length + ? { + context: [...(project.context ?? []), ...meshes], + layers: ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : []))), + } + : {}), + }; + return { project: next, summary }; +} + +/** Meldung zum Bauteil-Import; `tr` übersetzt (Kern kennt kein i18n). */ +export function formatIfcElementsSummary( + s: IfcElementsSummary, + r: IfcImportReport, + tr: (key: "ifc.import.elements" | "ifc.import.kept", vars?: Record) => string, +): string { + const parts = [ + tr("ifc.import.elements", { + schema: r.schema || "IFC", + walls: s.walls, + openings: s.openings, + ceilings: s.ceilings, + columns: s.columns, + rooms: s.rooms, + floors: s.floors, + meshes: s.meshes, + }), + ]; + if (s.kept) parts.push(tr("ifc.import.kept", { n: s.kept })); + return parts.join(" · "); +} diff --git a/src/io/ifcImport.ts b/src/io/ifcImport.ts index a6d71a6a..0106aacc 100644 --- a/src/io/ifcImport.ts +++ b/src/io/ifcImport.ts @@ -1,9 +1,10 @@ // IFC-Import als Mesh ([B3]): dünne Fassade über `import_ifc` im Format-Modul (`src-tauri/fileio`, // `ifc_import.rs`). Jedes IFC-Bauteil mit Körper wird zu einem `ImportedMesh` der Kontext-Schicht -// (wie der STEP-Import, `stepImport.ts`); echte Bauteile (Wand, Decke …) kommen mit [B4]. +// (wie der STEP-Import, `stepImport.ts`); echte Bauteile (Wand, Decke …) baut auf Wunsch +// `ifcElements.ts` ([B4]) aus `import_ifc_elements`. // -// Gruppierung: je Bauteil ein Mesh (anwählbar, Name/Geschoss/GlobalId bleiben erhalten, im -// Kontext-Panel nach IFC-Klasse gruppiert über `layer`). Bei sehr vielen Bauteilen (> `MAX_SINGLE`) +// Gruppierung: je Bauteil ein Mesh (anwählbar, Name/Geschoss bleiben erhalten, GlobalId in +// `ifcGlobalId`, Farbe in `color`; im Kontext-Panel nach IFC-Klasse gruppiert über `layer`). Bei sehr vielen Bauteilen (> `MAX_SINGLE`) // werden Bauteile gleicher Klasse und gleichen Geschosses zusammengelegt, damit Projektdatei und // Kontext-Panel handhabbar bleiben. // @@ -18,6 +19,7 @@ import { loadFileio } from "../engine/fileioWasm"; import { GENERIC_IMPORT_CATEGORY } from "../model/contextCategories"; import type { ImportedMesh } from "../model/types"; +import { rgbToHex } from "../model/color"; /** Ein gelesenes IFC-Bauteil. */ export interface IfcProduct { @@ -62,23 +64,27 @@ interface RawProduct { indexCount: number; } -/** Rohergebnis aus Rust: Bericht (JSON) und alle Bauteile hintereinander in zwei flachen Puffern. */ +/** Rohergebnis aus Rust: Bericht (JSON) und alle Bauteile hintereinander in zwei flachen Puffern; + * mit `elements` dazu die Zahlen der erkannten Bauteile ([B4], `ifcElements.ts`). */ export interface IfcFlat { meta: string; positions: Float64Array; indices: Uint32Array; + elementData?: Float64Array; } -/** Worker-Protokoll (`ifcImport.worker.ts`). */ -export type IfcWorkerRequest = { type: "parse"; data: ArrayBuffer }; +/** Worker-Protokoll (`ifcImport.worker.ts`); `elements` = echte Bauteile erkennen ([B4]). */ +export type IfcWorkerRequest = { type: "parse"; data: ArrayBuffer; elements?: boolean }; 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 { +export async function importIfcFlat(bytes: Uint8Array, elements = false): Promise { const m = await loadFileio(); - const r = m.import_ifc(bytes); + const r = elements ? m.import_ifc_elements(bytes) : m.import_ifc(bytes); try { - return { meta: r.meta, positions: r.positions(), indices: r.indices() }; + const flat: IfcFlat = { meta: r.meta, positions: r.positions(), indices: r.indices() }; + if (elements) flat.elementData = r.elementData(); + return flat; } finally { r.free(); } @@ -88,15 +94,17 @@ export async function importIfcFlat(bytes: Uint8Array): Promise { 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] }; + const flat = await importIfcFlat(new Uint8Array(req.data), req.elements === true); + const transfer: Transferable[] = [flat.positions.buffer, flat.indices.buffer]; + if (flat.elementData) transfer.push(flat.elementData.buffer); + return { res: { type: "result", flat }, transfer }; } 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 { +function readInWorker(bytes: Uint8Array, elements: boolean): Promise { if (typeof Worker === "undefined") return Promise.resolve(null); return new Promise((resolve, reject) => { let worker: Worker; @@ -117,7 +125,8 @@ function readInWorker(bytes: Uint8Array): Promise { }; // Kopie übertragen: der Aufrufer behält seine Bytes. const data = bytes.slice().buffer; - worker.postMessage({ type: "parse", data } satisfies IfcWorkerRequest, [data]); + const req: IfcWorkerRequest = elements ? { type: "parse", data, elements } : { type: "parse", data }; + worker.postMessage(req, [data]); }); } @@ -145,8 +154,18 @@ export function decodeIfc(flat: IfcFlat): { products: IfcProduct[]; report: IfcI /** 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); + return decodeIfc(await readIfcFlat(bytes)); +} + +/** Rohergebnis lesen (im Worker, sonst direkt); `elements` = echte Bauteile erkennen ([B4]). */ +export async function readIfcFlat(bytes: Uint8Array, elements = false): Promise { + return (await readInWorker(bytes, elements)) ?? (await importIfcFlat(bytes, elements)); +} + +/** RGBA 0..1 → `#rrggbb` (Alpha entfällt). */ +export function ifcColorHex(c: readonly number[] | null | undefined): string | undefined { + if (!c || c.length < 3 || !c.slice(0, 3).every((v) => Number.isFinite(v))) return undefined; + return rgbToHex({ r: c[0] * 255, g: c[1] * 255, b: c[2] * 255 }); } /** Ab so vielen Bauteilen wird je Klasse + Geschoss zusammengelegt. */ @@ -157,12 +176,19 @@ export interface IfcToMeshesOptions { geoOrigin?: { e: number; n: number } | null; /** "product" = je Bauteil, "class" = je Klasse + Geschoss, "auto" (Standard) nach `MAX_SINGLE`. */ group?: "product" | "class" | "auto"; + /** Feste Verschiebung statt der aus den Bauteilen geschätzten ([B4]: gemeinsam mit den Bauteilen). */ + shift?: [number, number]; } let counter = 0; -/** Verschiebung, falls die Datei in Landeskoordinaten liegt und das Projekt einen Bezug hat. */ -function geoShift(products: IfcProduct[], origin: { e: number; n: number } | null | undefined): [number, number] { +/** Verschiebung, falls die Datei in Landeskoordinaten liegt und das Projekt einen Bezug hat; + * `extra` = weitere Punkte (x,y flach, z. B. erkannte Bauteile [B4]). */ +export function geoShift( + products: IfcProduct[], + origin: { e: number; n: number } | null | undefined, + extra: readonly number[] = [], +): [number, number] { if (!origin) return [0, 0]; let sx = 0; let sy = 0; @@ -174,6 +200,11 @@ function geoShift(products: IfcProduct[], origin: { e: number; n: number } | nul n++; } } + for (let i = 0; i + 1 < extra.length; i += 2) { + sx += extra[i]; + sy += extra[i + 1]; + n++; + } if (n === 0) return [0, 0]; const cx = sx / n; const cy = sy / n; @@ -184,7 +215,7 @@ function geoShift(products: IfcProduct[], origin: { e: number; n: number } | nul /** Bauteile → Kontext-Meshes (Kategorie „Situation" wie STEP; `layer` = IFC-Klasse). */ export function ifcToImportedMeshes(products: IfcProduct[], fileName: string, opts: IfcToMeshesOptions = {}): ImportedMesh[] { const base = fileName.replace(/\.[^.]+$/, "") || "IFC"; - const [dx, dy] = geoShift(products, opts.geoOrigin); + const [dx, dy] = opts.shift ?? geoShift(products, opts.geoOrigin); const stamp = Date.now().toString(36); const group = opts.group ?? "auto"; const perProduct = group === "product" || (group === "auto" && products.length <= MAX_SINGLE); @@ -203,14 +234,19 @@ export function ifcToImportedMeshes(products: IfcProduct[], fileName: string, op }; if (perProduct) { - return products.map((p) => ({ - id: `imported-ifc-${stamp}-${counter++}`, - type: "importedMesh" as const, - name: [p.storey, p.name || p.ifcClass].filter(Boolean).join(": ") + (p.globalId ? ` [${p.globalId}]` : ""), - layer: p.ifcClass, - categoryCode: GENERIC_IMPORT_CATEGORY.code, - ...toArrays([p]), - })); + return products.map((p) => { + const color = ifcColorHex(p.color); + return { + id: `imported-ifc-${stamp}-${counter++}`, + type: "importedMesh" as const, + name: [p.storey, p.name || p.ifcClass].filter(Boolean).join(": "), + layer: p.ifcClass, + categoryCode: GENERIC_IMPORT_CATEGORY.code, + ...(color ? { color } : {}), + ...(p.globalId ? { ifcGlobalId: p.globalId } : {}), + ...toArrays([p]), + }; + }); } const groups = new Map(); for (const p of products) { @@ -219,14 +255,20 @@ export function ifcToImportedMeshes(products: IfcProduct[], fileName: string, op if (g) g.push(p); else groups.set(key, [p]); } - return [...groups.values()].map((parts) => ({ - id: `imported-ifc-${stamp}-${counter++}`, - type: "importedMesh" as const, - name: `${base}: ${[parts[0].storey, parts[0].ifcClass].filter(Boolean).join(" ")} (${parts.length})`, - layer: parts[0].ifcClass, - categoryCode: GENERIC_IMPORT_CATEGORY.code, - ...toArrays(parts), - })); + return [...groups.values()].map((parts) => { + // Gemeinsame Farbe nur, wenn alle Teile dieselbe haben. + const colors = new Set(parts.map((p) => ifcColorHex(p.color) ?? "")); + const color = colors.size === 1 ? [...colors][0] : ""; + return { + id: `imported-ifc-${stamp}-${counter++}`, + type: "importedMesh" as const, + name: `${base}: ${[parts[0].storey, parts[0].ifcClass].filter(Boolean).join(" ")} (${parts.length})`, + layer: parts[0].ifcClass, + categoryCode: GENERIC_IMPORT_CATEGORY.code, + ...(color ? { color } : {}), + ...toArrays(parts), + }; + }); } /** Datei-Bytes → Kontext-Meshes + Bericht. */ diff --git a/src/model/types.ts b/src/model/types.ts index aef202f5..0877a69a 100644 --- a/src/model/types.ts +++ b/src/model/types.ts @@ -2380,6 +2380,10 @@ export interface ImportedMesh { * IMMER sichtbar (Rückwärtskompatibilität), s. `generatePlan/context.ts`. */ categoryCode?: string; + /** Farbe aus der Quelldatei (`#rrggbb`, z. B. IFC-Oberflächenstil/Material); fehlt sie, gilt die Kontext-Grundfarbe. */ + color?: string; + /** IFC-GlobalId des Quell-Bauteils (IFC-Import je Bauteil). */ + ifcGlobalId?: string; positions: number[]; indices: number[]; } diff --git a/src/ui/IfcImportDialog.tsx b/src/ui/IfcImportDialog.tsx new file mode 100644 index 00000000..eba9ecf0 --- /dev/null +++ b/src/ui/IfcImportDialog.tsx @@ -0,0 +1,69 @@ +// Auswahl beim IFC-Import ([B3]/[B4]): als Kontext-Meshes (Standard, wie bisher) oder als echte +// Bauteile (`io/ifcElements.ts`). Overlay-Muster wie `UnsavedChangesDialog` (kein `window.confirm`). + +import { useEffect, useState } from "react"; +import { t } from "../i18n"; + +export type IfcImportMode = "mesh" | "elements"; + +export interface IfcImportDialogProps { + fileName: string; + onImport: (mode: IfcImportMode) => void; + onCancel: () => void; +} + +export function IfcImportDialog({ fileName, onImport, onCancel }: IfcImportDialogProps) { + const [mode, setMode] = useState("mesh"); + + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") onCancel(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [onCancel]); + + return ( +
+
e.stopPropagation()} + > +
+ {t("ifc.importDialog.title")} + +
+ +
+
+
{fileName}
+ +
{t("ifc.importDialog.asMeshHint")}
+ +
{t("ifc.importDialog.asElementsHint")}
+
+
+ + +
+
+ ); +}