From 786643c7b2d1ae69a873239f7886131b8af1d56b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 12:56:50 +0000 Subject: [PATCH] =?UTF-8?q?[B5]=20IFC-Export:=20T=C3=BCren=20und=20Fenster?= =?UTF-8?q?=20mit=20Rahmen,=20Blatt=20und=20Glas=20statt=20Box?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fenster: Blendrahmen, Mittelpfosten und eine Scheibe je Flügel; Tür: Zarge und Blatt (Glastür mit Glasanteil, Oberlicht). Getrennte Körper in einer Darstellung mit Stil je Rolle, eigenes Füllungs-Placement, OperationType/PartitioningType. Masse aus dem Modell, sonst die Konstanten des 3D. ifcopenshell: 0 Befunde, Volumen und Lage stimmen. Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- TODO.md | 13 +- src-tauri/fileio/src/ifc_export.rs | 251 ++++++++++++++++++++----- src/export/exportIfc.ts | 27 ++- src/export/exportIfc.validate.test.ts | 106 +++++++++++ src/export/ifcOpenings.test.ts | 204 ++++++++++++++++++++ src/export/ifcOpenings.ts | 260 ++++++++++++++++++++++++++ 6 files changed, 808 insertions(+), 53 deletions(-) create mode 100644 src/export/ifcOpenings.test.ts create mode 100644 src/export/ifcOpenings.ts diff --git a/TODO.md b/TODO.md index 7fc8803e..fa9089dd 100644 --- a/TODO.md +++ b/TODO.md @@ -360,7 +360,18 @@ Ganzes nicht WASM-tauglich (rayon, tempfile, SystemTime) — nur einzelne Module füllen. Mesh-Wände (schräge Oberkante, Laibung) bleiben ohne Achse/Usage. ifcopenshell liest Achse = Wandachse (auch schräg/rückwärts gezeichnet) und die Bänder in Schichtreihenfolge ab Offset. Offen: nicht in Revit/ArchiCAD geöffnet. - - ○ Offen: Tür/Fenster mit Rahmen/Blatt statt Box; Bogenwände als echte Kurve. · M + - ✅ Tür/Fenster mit echter Geometrie statt Box. (28.10.) `export/ifcOpenings.ts`: Fenster = Blendrahmen + (4 Teile) + Mittelpfosten + eine Glasscheibe je Flügel (Flügeltabelle/`wingCount`), Tür = Zarge (3 Teile) + + Blatt/Blätter (Glastür: Rahmen um eine Glasfläche = `glazingRatio`, Oberlicht mit Kämpfer); getrennte + Körper in einer Darstellung, je mit IfcStyledItem (Rahmen/Blatt/Glas mit Transparenz). Masse aus dem + Modell (Rahmenbreite/-tiefe, Schichteinzug, Verglasung), sonst die Konstanten des 3D (6 cm, 7 cm, Blatt + 4 cm; Glaspaket 6/24/36 mm). Eigenes Füllungs-Placement (Tür: Y = Aufschlagrichtung). OperationType + (Blattzahl, Scharnierseite, Schiebe) und PartitioningType (1–3 Flügel). Reine Wandöffnung: kein Körper. + Geprüft: ifcopenshell (0 Befunde; Volumen Rahmen + Glas, Welt-Lage, Stile je Körper), Modell-Rechnung + in `ifcOpenings.test.ts`. Offen: LEFT/RIGHT der Tür nach IFC-Konvention (Blick von der Aufschlagseite) + gelesen, nicht in Revit/ArchiCAD gegengeprüft; ohne Sprossen, Fensterbank, Rollladenkasten, Schwelle, + Flügelrahmen. + - ○ Offen: Bogenwände als echte Kurve. · M - ✅ Eigener IFC-Import ([B3]) zieht Öffnungen ab (28.10.): Rundreise vergleicht alle Wände mit dem ausgeschnittenen Volumen (`ifcImport.test.ts`). - ✅ Export nach Rust. (28.10.) `src-tauri/fileio/src/ifc_export.rs` schreibt die STEP-Datei diff --git a/src-tauri/fileio/src/ifc_export.rs b/src-tauri/fileio/src/ifc_export.rs index a1024ade..cbfed233 100644 --- a/src-tauri/fileio/src/ifc_export.rs +++ b/src-tauri/fileio/src/ifc_export.rs @@ -378,6 +378,24 @@ impl<'a> Reader<'a> { let s = self.take(n.checked_mul(2).ok_or("Überlauf")?)?; Ok(s.chunks_exact(2).map(|c| (c[0], c[1])).collect()) } + /// Teile einer Füllung: n, (Rolle 0 Rahmen / 1 Blatt / 2 Glas, PTS, z_rel, depth) × n. + fn parts(&mut self) -> Result, String> { + let n = self.idx()?; + if n > MAX_PARTS { + return Err(format!("zu viele Teile ({n}) bei {}", self.pos - 1)); + } + let mut out = Vec::with_capacity(n); + for _ in 0..n { + let role = self.idx()?; + if role > 2 { + return Err(format!("unbekannte Teilrolle {role} bei {}", self.pos - 1)); + } + let pts = self.pts()?; + let (z_rel, depth) = (self.f()?, self.f()?); + out.push(Part { role, pts, z_rel, depth }); + } + Ok(out) + } fn mesh(&mut self) -> Result { let nv = self.idx()?; let positions = self.take(nv.checked_mul(3).ok_or("Überlauf")?)?.to_vec(); @@ -440,6 +458,37 @@ impl<'a> Reader<'a> { } } +/// Obergrenze der Körper je Tür/Fenster (Rahmenteile, Scheiben, Pfosten). +const MAX_PARTS: usize = 256; + +/// Ein Körper einer Tür/eines Fensters (Welt-XY-Profil, Unterkante ab Öffnungs-UK). +struct Part { + /// 0 Rahmen/Zarge, 1 Türblatt, 2 Glas. + role: usize, + pts: Vec<(f64, f64)>, + z_rel: f64, + depth: f64, +} + +/// IfcDoorTypeOperationEnum / IfcWindowTypePartitioningEnum (IFC4): nur gültige Namen kommen durch. +const DOOR_OPERATIONS: &[&str] = &[ + "SINGLE_SWING_LEFT", "SINGLE_SWING_RIGHT", "DOUBLE_DOOR_SINGLE_SWING", "DOUBLE_DOOR_SINGLE_SWING_OPPOSITE_LEFT", + "DOUBLE_DOOR_SINGLE_SWING_OPPOSITE_RIGHT", "DOUBLE_SWING_LEFT", "DOUBLE_SWING_RIGHT", "DOUBLE_DOOR_DOUBLE_SWING", + "SWING_FIXED_LEFT", "SWING_FIXED_RIGHT", "SLIDING_TO_LEFT", "SLIDING_TO_RIGHT", "DOUBLE_DOOR_SLIDING", + "FOLDING_TO_LEFT", "FOLDING_TO_RIGHT", "DOUBLE_DOOR_FOLDING", "REVOLVING", "ROLLINGUP", "NOTDEFINED", +]; +const WINDOW_PARTITIONINGS: &[&str] = &[ + "SINGLE_PANEL", "DOUBLE_PANEL_VERTICAL", "DOUBLE_PANEL_HORIZONTAL", "TRIPLE_PANEL_VERTICAL", "TRIPLE_PANEL_BOTTOM", + "TRIPLE_PANEL_TOP", "TRIPLE_PANEL_LEFT", "TRIPLE_PANEL_RIGHT", "TRIPLE_PANEL_HORIZONTAL", "NOTDEFINED", +]; + +/// Farbe und Durchsichtigkeit je Teilrolle (wie `PART_RGB` im 3D: Rahmen hellgrau, Blatt warm, Glas bläulich). +const PART_STYLES: [(&str, [f64; 3], f64); 3] = [ + ("Rahmen", [0.85, 0.85, 0.83], 0.0), + ("Türblatt", [0.93, 0.90, 0.85], 0.0), + ("Glas", [0.62, 0.76, 0.85], 0.6), +]; + /// Lokales Wand-/Füllungssystem in Welt-XY: Ursprung und Richtung der X-Achse (Y = linke Normale). #[derive(Clone, Copy)] struct Frame { @@ -466,6 +515,12 @@ impl Frame { fn local_pts(&self, pts: &[(f64, f64)]) -> Vec<(f64, f64)> { pts.iter().map(|&(x, y)| self.local(x, y)).collect() } + + /// Dieses System (in Welt-XY) im System `parent` ausgedrückt: Ursprung abbilden, Richtung nur drehen. + fn relative_to(&self, parent: &Frame) -> Frame { + let (ox, oy) = parent.local(self.ox, self.oy); + Frame { ox, oy, ux: self.ux * parent.ux + self.uy * parent.uy, uy: -self.ux * parent.uy + self.uy * parent.ux } + } } struct Mesh { @@ -570,6 +625,8 @@ struct Builder { type_index: HashMap, /// Wand-id → (Entität, Placement, Wandsystem) für die Öffnungen. walls: HashMap, + /// Oberflächenstil je Teilrolle (Rahmen, Blatt, Glas), beim ersten Gebrauch angelegt (0 = noch nicht). + styles: [usize; 3], /// Untergeordneter Kontext „Axis“ (GRAPH_VIEW), beim ersten Gebrauch angelegt (0 = noch nicht). axis_context: usize, @@ -678,6 +735,36 @@ impl Builder { self.add("IFCLOCALPLACEMENT", format!("#{relative_to},#{axis}")) } + /// Oberflächenstil der Teilrolle (einmal je Datei): IfcSurfaceStyle mit IfcSurfaceStyleRendering. + fn part_style(&mut self, role: usize) -> usize { + if self.styles[role] == 0 { + let (name, rgb, transparency) = PART_STYLES[role]; + let colour = self.add("IFCCOLOURRGB", format!("$,{},{},{}", fmt_real(rgb[0]), fmt_real(rgb[1]), fmt_real(rgb[2]))); + let rendering = self.add( + "IFCSURFACESTYLERENDERING", + format!("#{colour},{},$,$,$,$,$,$,{}", fmt_real(transparency), enum_("NOTDEFINED")), + ); + self.styles[role] = self.add( + "IFCSURFACESTYLE", + format!("{},{},{}", ifc_string(name), enum_("BOTH"), refs(&[rendering])), + ); + } + self.styles[role] + } + + /// Körper einer Tür/eines Fensters: je Teil eine Extrusion mit eigenem Stil, alle in EINER + /// SweptSolid-Darstellung (getrennte Körper im selben Bauteil). Profile kommen im Füllungssystem. + fn emit_parts_shape(&mut self, parts: &[Part], frame: &Frame) -> usize { + let mut solids = Vec::with_capacity(parts.len()); + for p in parts { + let solid = self.emit_extrusion(&frame.local_pts(&p.pts), p.z_rel, p.depth); + let style = self.part_style(p.role); + self.add("IFCSTYLEDITEM", format!("#{solid},{},$", refs(&[style]))); + solids.push(solid); + } + self.emit_swept_shape(&solids) + } + /// Untergeordneter Darstellungskontext „Axis“ (GRAPH_VIEW), einmal je Datei. fn axis_context(&mut self) -> usize { if self.axis_context == 0 { @@ -901,6 +988,7 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { type_index: HashMap::new(), walls: HashMap::new(), axis_context: 0, + styles: [0; 3], spaces: Vec::new(), column_materials: Vec::new(), }; @@ -1133,18 +1221,26 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { let void_pts = r.pts()?; let void_z = r.f()?; let depth = r.f()?; - let fill_pts = r.pts()?; let width = r.f()?; + let kind = r.opt_string()?; + let (fox, foy, fux, fuy) = (r.f()?, r.f()?, r.f()?, r.f()?); + if ((fux * fux + fuy * fuy) - 1.0).abs() > 1e-6 { + return Err(format!("Füllungsrichtung nicht normiert bei {}", r.pos - 1)); + } + let fill_frame = Frame { ox: fox, oy: foy, ux: fux, uy: fuy }; + let parts = r.parts()?; let psets = r.psets()?; + let allowed = if is_door { DOOR_OPERATIONS } else { WINDOW_PARTITIONINGS }; + if let Some(k) = &kind { + if !allowed.contains(&k.as_str()) { + return Err(format!("unbekannte Ausführung {k:?} bei {}", r.pos - 1)); + } + } let Some(&(host_entity, host_placement, host_frame)) = w.walls.get(&wall_id) else { continue; // Wirtswand nicht geschrieben (degeneriert) }; // Die Geometrie kommt in Welt-XY; Wände mit eigenem Placement rechnen wir ins Wandsystem. - let (void_pts, fill_pts) = if host_frame.is_world() { - (void_pts, fill_pts) - } else { - (host_frame.local_pts(&void_pts), host_frame.local_pts(&fill_pts)) - }; + let void_pts = if host_frame.is_world() { void_pts } else { host_frame.local_pts(&void_pts) }; let (opening_placement, opening_shape) = w.emit_box_product(&void_pts, void_z, depth, host_placement); let g = w.gid(&format!("opening/{opening_id}")); let opening_entity = w.add( @@ -1161,12 +1257,16 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { "IFCRELVOIDSELEMENT", format!("{g},#{},$,$,#{host_entity},#{opening_entity}", w.owner_history), ); - let (fill_placement, fill_shape) = w.emit_box_product(&fill_pts, 0.0, depth, opening_placement); + // Füllung: eigenes Placement (Ursprung/Richtung aus dem Modell, relativ zur Öffnung = zur Wand), + // Körper in diesem System; ohne Teile (reine Wandöffnung) keine Darstellung. + let fill_placement = w.emit_placement_frame(&fill_frame.relative_to(&host_frame), opening_placement); + let fill_shape = if parts.is_empty() { "$".to_string() } else { format!("#{}", w.emit_parts_shape(&parts, &fill_frame)) }; let g = w.gid(&format!("fill/{opening_id}")); + let operation = kind.as_deref().map(enum_).unwrap_or_else(|| "$".to_string()); let fill_entity = w.add( if is_door { "IFCDOOR" } else { "IFCWINDOW" }, format!( - "{g},#{},{},$,$,#{fill_placement},#{fill_shape},$,{},{},{},$,$", + "{g},#{},{},$,$,#{fill_placement},{fill_shape},$,{},{},{},{operation},$", w.owner_history, ifc_string(&fill_name), fmt_real(depth), @@ -1516,6 +1616,43 @@ mod tests { fn no_type(&mut self) { self.f.push(0.0); } + /// OPENING-Datensatz im neuen Format (Gegenstück zu `FlatIfc.opening`). + #[allow(clippy::too_many_arguments)] + fn opening( + &mut self, + wall: &str, + id: &str, + is_door: bool, + name: &str, + void_pts: &[(f64, f64)], + void_z: f64, + depth: f64, + width: f64, + kind: Option<&str>, + frame: [f64; 4], + parts: &[(f64, &[(f64, f64)], f64, f64)], + ) { + self.n(&[REC_OPENING]); + self.str(wall); + self.n(&[-1.0]); + self.str(id); + self.n(&[if is_door { 1.0 } else { 0.0 }]); + self.str(name); + self.pts(void_pts); + self.n(&[void_z, depth, width]); + match kind { + Some(k) => self.str(k), + None => self.f.push(-1.0), + } + self.n(&frame); + self.f.push(parts.len() as f64); + for (role, pts, z, d) in parts { + self.f.push(*role); + self.pts(pts); + self.n(&[*z, *d]); + } + self.no_psets(); + } fn wall_type(&mut self) { self.n(&[1.0, 0.0]); self.str("T1"); @@ -1578,18 +1715,17 @@ mod tests { b.pts(&SQUARE); b.n(&[0.0, 2.6]); } - // Öffnung in W1: Tür. - b.n(&[REC_OPENING]); - b.str("W1"); - b.n(&[0.0]); - b.str("T1"); - b.n(&[1.0]); - b.str("Haustür"); - b.pts(&[(1.0, -0.02), (1.9, -0.02), (1.9, 0.42), (1.0, 0.42)]); - b.n(&[0.0, 2.1]); - b.pts(&[(1.0, 0.0), (1.9, 0.0), (1.9, 0.4), (1.0, 0.4)]); - b.n(&[0.9]); - b.ref_pset("Pset_DoorCommon", "Tür 90"); + // Öffnung in W1: Tür mit Zarge, Blatt und Glas. + b.opening( + "W1", "T1", true, "Haustür", + &[(1.0, -0.02), (1.9, -0.02), (1.9, 0.42), (1.0, 0.42)], 0.0, 2.1, 0.9, + Some("SINGLE_SWING_LEFT"), [1.45, 0.0, 0.0, 1.0], + &[ + (0.0, &[(1.0, 0.0), (1.06, 0.0), (1.06, 0.07), (1.0, 0.07)], 0.0, 2.1), + (1.0, &[(1.06, 0.015), (1.84, 0.015), (1.84, 0.055), (1.06, 0.055)], 0.0, 2.04), + (2.0, &[(1.2, 0.02), (1.6, 0.02), (1.6, 0.05), (1.2, 0.05)], 0.5, 1.0), + ], + ); // Decke, Treppe, Extrusion. b.n(&[REC_CEILING, 0.0]); b.str("D1"); @@ -1729,7 +1865,7 @@ mod tests { assert_eq!(count(&ifc, "IFCMATERIALLAYERSET"), 2); // Wandtyp + Dachtyp assert_eq!(count(&ifc, "IFCMATERIAL"), 2); // Beton (geteilt mit Dachtyp und Stütze) + Dämmung assert_eq!(count(&ifc, "IFCRELDEFINESBYTYPE"), 2); - assert_eq!(count(&ifc, "IFCPROPERTYSET"), 6); // Wall, Door, Space, Roof, Column + CH_Raum + assert_eq!(count(&ifc, "IFCPROPERTYSET"), 5); // Wall, Space, Roof, Column + CH_Raum (Tür ohne Pset) // Eingliederung: Geschoss (Wände, Decke, Treppe, Tür, Dach, Stütze) und Gebäude (Extrusion). assert_eq!(count(&ifc, "IFCRELCONTAINEDINSPATIALSTRUCTURE"), 2); // Project→Site, Site→Building, Building→Storeys, Geschoss→Räume. @@ -1784,17 +1920,12 @@ mod tests { b.n(&[1.0]); b.pts(&[(10.2, 20.0), (10.2, 25.0), (9.8, 25.0), (9.8, 20.0)]); b.n(&[0.0, 2.6]); - b.n(&[REC_OPENING]); - b.str("W"); - b.n(&[-1.0]); - b.str("O"); - b.n(&[0.0]); - b.str("Fenster"); - b.pts(&[(10.3, 21.0), (10.3, 22.0), (9.7, 22.0), (9.7, 21.0)]); - b.n(&[0.9, 1.2]); - b.pts(&[(10.2, 21.0), (10.2, 22.0), (9.8, 22.0), (9.8, 21.0)]); - b.n(&[1.0]); - b.no_psets(); + b.opening( + "W", "O", false, "Fenster", + &[(10.3, 21.0), (10.3, 22.0), (9.7, 22.0), (9.7, 21.0)], 0.9, 1.2, 1.0, + Some("SINGLE_PANEL"), [10.0, 21.5, 0.0, 1.0], + &[(0.0, &[(10.2, 21.0), (10.2, 22.0), (9.8, 22.0), (9.8, 21.0)], 0.0, 1.2)], + ); let ifc = build(&b).unwrap(); check_structure(&ifc); // Wandprofil lokal: x = Länge entlang u, y = linke Normale (10.2 → −0.2, 9.8 → 0.2). @@ -1809,6 +1940,50 @@ mod tests { assert!(ifc.contains("'Axis','Curve2D'")); } + #[test] + fn tuer_hat_getrennte_koerper_mit_stilen_und_operation() { + let ifc = build(&full_house(false)).unwrap(); + check_structure(&ifc); + let door = first_line(&ifc, "IFCDOOR"); + assert!(door.contains(".DOOR.,.SINGLE_SWING_LEFT.,$);"), "{door}"); + // Drei Körper (Zarge, Blatt, Glas) in EINER Darstellung, je ein IfcStyledItem, drei Stile. + assert_eq!(count(&ifc, "IFCSTYLEDITEM"), 3); + assert_eq!(count(&ifc, "IFCSURFACESTYLE"), 3); + assert_eq!(count(&ifc, "IFCSURFACESTYLERENDERING"), 3); + assert!(ifc.contains("IFCSURFACESTYLE('Glas',.BOTH.,")); + assert!(ifc.contains("IFCSURFACESTYLERENDERING(#")); + let shapes = ifc.lines().filter(|l| l.contains("IFCSHAPEREPRESENTATION") && l.contains("'SweptSolid'") && l.matches('#').count() == 5).count(); + assert!(shapes >= 1, "Darstellung mit 3 Körpern fehlt"); + // Füllungs-Placement mit Richtung (0,1,0) relativ zur Öffnung; Ursprung lokal. + assert!(ifc.contains("IFCCARTESIANPOINT((1.45,0.0,0.0))")); + } + + #[test] + fn fenster_ohne_teile_hat_keine_darstellung_und_enum_ist_geprueft() { + let mut b = full_house(false); + b.opening("W1", "F1", false, "Fenster", &SQUARE, 0.9, 1.2, 1.2, Some("DOUBLE_PANEL_VERTICAL"), [2.0, 0.0, 1.0, 0.0], &[]); + b.opening("W1", "T2", true, "Wandöffnung", &SQUARE, 0.0, 2.1, 1.0, None, [3.0, 0.0, 1.0, 0.0], &[]); + let ifc = build(&b).unwrap(); + check_structure(&ifc); + let win = first_line(&ifc, "IFCWINDOW"); + assert!(win.contains(".WINDOW.,.DOUBLE_PANEL_VERTICAL.,$);"), "{win}"); + assert!(win.contains(",$,$,1.2,1.2,.WINDOW."), "ohne Teile keine Darstellung: {win}"); + // Ungültige Ausführung (Fenster-Wert an der Tür und umgekehrt) ist ein Fehler, nie Panic. + let mut bad = full_house(false); + bad.opening("W1", "T3", true, "Tür", &SQUARE, 0.0, 2.1, 1.0, Some("SINGLE_PANEL"), [1.0, 0.0, 1.0, 0.0], &[]); + assert!(build(&bad).is_err()); + let mut bad = full_house(false); + bad.opening("W1", "F3", false, "Fenster", &SQUARE, 0.9, 1.2, 1.2, Some("SINGLE_SWING_LEFT"), [1.0, 0.0, 1.0, 0.0], &[]); + assert!(build(&bad).is_err()); + // Unbekannte Teilrolle, schiefe Richtung: Fehler. + let mut bad = full_house(false); + bad.opening("W1", "F4", false, "Fenster", &SQUARE, 0.9, 1.2, 1.2, None, [1.0, 0.0, 1.0, 0.0], &[(3.0, &SQUARE, 0.0, 1.0)]); + assert!(build(&bad).is_err()); + let mut bad = full_house(false); + bad.opening("W1", "F5", false, "Fenster", &SQUARE, 0.9, 1.2, 1.2, None, [1.0, 0.0, 3.0, 0.0], &[]); + assert!(build(&bad).is_err()); + } + #[test] fn schiefe_achsrichtung_ist_fehler() { let mut b = mini(); @@ -1866,17 +2041,7 @@ mod tests { b.n(&[1.0]); b.str("iso"); b.n(&[0.0, f64::NAN, 0.0]); - b.n(&[REC_OPENING]); - b.str("gibt-es-nicht"); - b.n(&[-1.0]); - b.str("O1"); - b.n(&[0.0]); - b.str("Fenster"); - b.pts(&SQUARE); - b.n(&[0.0, 1.0]); - b.pts(&SQUARE); - b.n(&[1.0]); - b.no_psets(); + b.opening("gibt-es-nicht", "O1", false, "Fenster", &SQUARE, 0.0, 1.0, 1.0, None, [0.0, 0.0, 1.0, 0.0], &[]); let ifc = build(&b).unwrap(); check_structure(&ifc); assert_eq!(count(&ifc, "IFCOPENINGELEMENT"), 0); diff --git a/src/export/exportIfc.ts b/src/export/exportIfc.ts index 58529252..3dde5c4a 100644 --- a/src/export/exportIfc.ts +++ b/src/export/exportIfc.ts @@ -31,8 +31,12 @@ // werden trotzdem als Beziehung angelegt; die Öffnung liegt im Loch und zieht nichts ab. // • Decke → IfcSlab (outline-Polygon, PredefinedType FLOOR). // • Öffnung → IfcOpeningElement (Quader über die ganze Wanddicke, etwas vorstehend) in der -// Wand (IfcRelVoidsElement), darin IfcDoor/IfcWindow (IfcRelFillsElement) mit eigener -// Box-Geometrie; kein Blatt-/Rahmendetail (bewusste Vereinfachung). +// Wand (IfcRelVoidsElement), darin IfcDoor/IfcWindow (IfcRelFillsElement) aus getrennten Körpern +// ([B5], 28.10., `ifcOpenings.ts`): Rahmen/Zarge + Türblatt bzw. Glas je Flügel, mit Farbe/ +// Transparenz je Rolle; OperationType (Tür: Blattzahl, Scharnierseite, Schiebe) und +// PartitioningType (Fenster: Flügelzahl). Masse aus dem Modell (Rahmenbreite/-tiefe, Einzug, +// Verglasung, Glasanteil, Oberlicht), sonst die Konstanten des 3D. Ohne Sprossen, Fensterbank, +// Schwelle; reine Wandöffnung ohne Körper. // • Extrusion → IfcBuildingElementProxy aus points+height. // • Dach → IfcRoof (Schicht-Meshes wie im 3D), Dachtyp → IfcRoofType mit Schichten. // • Stütze → IfcColumn (Profil-Extrusion), Bauteil → IfcMaterial. @@ -83,6 +87,7 @@ import { columnFootprint } from "../geometry/column"; import { openingInterval, openingVerticalExtent } from "../geometry/opening"; import { emitRoofs } from "../plan/toWalls3d/roofs"; import { fileio } from "../engine/fileioWasm"; +import { fillGeometry, type FillGeometry } from "./ifcOpenings"; /** Deterministische 22-stellige IFC-GUID aus einem Namen (Rust, `ifc_export.rs::ifc_guid`). */ export function ifcGuid(name: string): string { @@ -240,15 +245,19 @@ class FlatIfc { voidRect: Vec2[]; voidZRel: number; depth: number; - fillRect: Vec2[]; width: number; + fill: FillGeometry; psets: PsetIn[]; }): void { this.nums.push(REC_OPENING, this.str(o.wallId), o.structure, this.str(o.openingId), o.isDoor ? 1 : 0, this.str(o.fillName)); this.pts(o.voidRect); - this.nums.push(o.voidZRel, o.depth); - this.pts(o.fillRect); - this.nums.push(o.width); + this.nums.push(o.voidZRel, o.depth, o.width, o.fill.kind === null ? -1 : this.str(o.fill.kind)); + this.nums.push(o.fill.origin.x, o.fill.origin.y, o.fill.u.x, o.fill.u.y, o.fill.parts.length); + for (const p of o.fill.parts) { + this.nums.push(p.role); + this.pts(p.pts); + this.nums.push(p.zRel, p.depth); + } this.psets(o.psets); } @@ -670,8 +679,8 @@ export function exportIfcSpf(projectIn: Project): string { // ── Öffnungen: IfcOpeningElement in der Wand, IfcDoor/IfcWindow darin ─── // Der Öffnungskörper ist ein Quader über das Achs-Intervall und die Höhe, wie sie das 3D // stanzt (`openingInterval`/`openingVerticalExtent`), quer über alle Bänder der Wand plus - // OPENING_OVERSHOOT. Die Füllung (Tür/Fenster) sitzt im Öffnungs-Placement, über die - // Banddicke, ohne Blatt-/Rahmendetail. + // OPENING_OVERSHOOT. Die Füllung (Tür/Fenster) hat ein eigenes Placement + // (Öffnungsmitte, Achse bzw. Aufschlagrichtung) und liegt in der Rahmentiefe (`ifcOpenings.ts`). for (const wall of project.walls ?? []) { const host = hostExtent.get(wall.id); if (!host) continue; // Wirtswand übersprungen (degeneriert) @@ -705,8 +714,8 @@ export function exportIfcSpf(projectIn: Project): string { voidRect: axisRect(wall, c.from, c.to, host.nLo - OPENING_OVERSHOOT, host.nHi + OPENING_OVERSHOOT), voidZRel: c.zBottom - baseOf(structure), depth, - fillRect: axisRect(wall, c.from, c.to, host.nLo, host.nHi), width: c.to - c.from, + fill: fillGeometry(project, wall, opening, c, host), psets: [{ name: psetName, props }], }); } diff --git a/src/export/exportIfc.validate.test.ts b/src/export/exportIfc.validate.test.ts index d1470060..c25507c4 100644 --- a/src/export/exportIfc.validate.test.ts +++ b/src/export/exportIfc.validate.test.ts @@ -94,6 +94,53 @@ function wallAxes(name: string, ifc: string): Record { return JSON.parse(r.stdout); } +// Türen/Fenster nach ifcopenshell: Körper je Darstellungselement (Volumen, Welt-Bounding-Box), Stil je +// Element und Ausführung. +const FILL_INFO = ` +import json, sys +import ifcopenshell, ifcopenshell.geom, ifcopenshell.util.shape as us +m = ifcopenshell.open(sys.argv[1]) +s = ifcopenshell.geom.settings() +s.set("use-world-coords", True) +out = [] +for e in m.by_type("IfcDoor") + m.by_type("IfcWindow"): + sh = ifcopenshell.geom.create_shape(s, e) + v = sh.geometry.verts + xs, ys, zs = v[0::3], v[1::3], v[2::3] + items = [] + rep = [r for r in e.Representation.Representations if r.RepresentationIdentifier == "Body"][0] + for it in rep.Items: + solid = ifcopenshell.geom.create_shape(s, it) + styles = [st.Name for si in it.StyledByItem for ps in si.Styles for st in [ps]] + items.append({"volume": us.get_volume(solid), "styles": styles, + "z": [min(solid.verts[2::3]), max(solid.verts[2::3])]}) + out.append({"type": e.is_a(), "name": e.Name, "volume": us.get_volume(sh.geometry), + "bbox": [min(xs), max(xs), min(ys), max(ys), min(zs), max(zs)], "items": items, + "op": getattr(e, "OperationType", None) or getattr(e, "PartitioningType", None), + "predefined": e.PredefinedType, "h": e.OverallHeight, "w": e.OverallWidth, + "filled": len(e.FillsVoids)}) +print(json.dumps(out)) +`; + +interface FillInfo { + type: string; + name: string; + volume: number; + bbox: number[]; + items: { volume: number; styles: string[]; z: number[] }[]; + op: string | null; + predefined: string; + h: number; + w: number; + filled: number; +} + +function fillInfo(name: string, ifc: string): FillInfo[] { + const r = spawnSync("python3", ["-c", FILL_INFO, writeIfc(name, ifc)], { encoding: "utf8", timeout: 120_000 }); + expect(r.status, r.stderr).toBe(0); + return JSON.parse(r.stdout); +} + /** Eine freistehende Wand 5 × 0.4 × 2.6 m mit einem Fenster 1.2 × 1.2 m (Brüstung 0.9 m). */ function singleWall(recess: boolean): Project { return { @@ -237,4 +284,63 @@ describe.skipIf(!hasIfcOpenShell)("IFC-Export gegen ifcopenshell", { timeout: 60 } expect(withAxis).toBeGreaterThan(0); }); + + it("[B5] Fenster: Rahmen + Glas als getrennte Körper, Volumen und Lage = Modell", () => { + const ifc = exportIfcSpf(singleWall(false)); // Fenster 1.2 × 1.2 bei x 1…2.2, Brüstung 0.9, Wand 0.4 dick, dreifach + expect(validate("fenster-koerper", ifc).out).toContain("0 Befunde"); + const [f] = fillInfo("fenster-koerper", ifc); + expect(f.type).toBe("IfcWindow"); + expect(f.filled).toBe(1); + expect(f.op).toBe("SINGLE_PANEL"); + expect(f.items.map((i) => i.styles[0]).sort()).toEqual(["Glas", "Rahmen", "Rahmen", "Rahmen", "Rahmen"]); + const fw = 0.06; + const frame = (1.2 * 1.2 - (1.2 - 2 * fw) ** 2) * 0.07; + const glass = (1.2 - 2 * fw) ** 2 * 0.036; // dreifach: 36 mm + expect(f.volume).toBeCloseTo(frame + glass, 6); + const glassItem = f.items.find((i) => i.styles[0] === "Glas")!; + expect(glassItem.volume).toBeCloseTo(glass, 6); + // Welt-Lage: x 1…2.2, Wandaussenseite y −0.2 + Rahmentiefe, z = Brüstung … Brüstung + 1.2 (Geschoss-UK 0). + expect(f.bbox[0]).toBeCloseTo(1, 6); + expect(f.bbox[1]).toBeCloseTo(2.2, 6); + expect(f.bbox[2]).toBeCloseTo(-0.2, 6); + expect(f.bbox[3]).toBeCloseTo(-0.2 + 0.07, 6); + expect(f.bbox[4]).toBeCloseTo(0.9, 6); + expect(f.bbox[5]).toBeCloseTo(2.1, 6); + expect(f.h).toBeCloseTo(1.2, 9); + expect(f.w).toBeCloseTo(1.2, 9); + }); + it("[B5] Tür (Wand schräg gestellt): Zarge, zwei Glasblätter, OperationType; Körper liegen in der Öffnung", () => { + const base = singleWall(false); + const dtype = { id: "dt", name: "Glastür", kind: "dreh", leafCount: 2, leafStyle: "glas", glazingRatio: 0.5, frameThickness: 0.06, defaultWidth: 1.6, defaultHeight: 2.1 }; + const p: Project = { + ...base, + walls: [{ ...base.walls[0], start: { x: 3, y: 1 }, end: { x: 3, y: 6 } }], // entlang +Y, linke Normale = −X + doorTypes: [dtype], + windowTypes: [], + openings: [{ id: "T1", type: "opening", hostWallId: "W1", categoryCode: "21", kind: "door", position: 1, width: 1.6, height: 2.1, sillHeight: 0, typeId: "dt", hinge: "end", swing: "left" }], + } as unknown as Project; + const ifc = exportIfcSpf(p); + expect(validate("tuer-koerper", ifc).out).toContain("0 Befunde"); + const [d] = fillInfo("tuer-koerper", ifc); + expect(d.type).toBe("IfcDoor"); + expect(d.filled).toBe(1); + // Wand entlang +Y: n = (−1, 0); swing links/innen → Aufschlag −X; Scharnier am Ende, zweiflügelig → DOUBLE_DOOR_SINGLE_SWING. + expect(d.op).toBe("DOUBLE_DOOR_SINGLE_SWING"); + // Rahmen: 3 Teile; Blätter: 2 × (4 Rahmenteile) mit Stil „Türblatt"; Glas: 2. + const roles = d.items.map((i) => i.styles[0]); + expect(roles.filter((r) => r === "Rahmen").length).toBe(3); + expect(roles.filter((r) => r === "Türblatt").length).toBe(8); + expect(roles.filter((r) => r === "Glas").length).toBe(2); + // Lage: Achse y 2…3.6 (Öffnung ab 1 m), quer zur Wand (x) innerhalb der Wanddicke 2.8…3.2, Boden z = 0. + expect(d.bbox[2]).toBeCloseTo(2, 6); + expect(d.bbox[3]).toBeCloseTo(3.6, 6); + expect(d.bbox[0]).toBeGreaterThanOrEqual(2.8 - 1e-6); + expect(d.bbox[1]).toBeLessThanOrEqual(3.2 + 1e-6); + expect(d.bbox[4]).toBeCloseTo(0, 6); + expect(d.bbox[5]).toBeCloseTo(2.1, 6); + // Glasanteil je Blatt = 50 % der Blattfläche (Blatt 0.74 × 2.04 je Flügel). + const leafArea = 0.74 * (2.1 - 0.06); + const glassVol = d.items.filter((i) => i.styles[0] === "Glas").reduce((a, i) => a + i.volume, 0); + expect(glassVol).toBeCloseTo(2 * leafArea * 0.5 * 0.024, 6); + }); }); diff --git a/src/export/ifcOpenings.test.ts b/src/export/ifcOpenings.test.ts new file mode 100644 index 00000000..3d1a3366 --- /dev/null +++ b/src/export/ifcOpenings.test.ts @@ -0,0 +1,204 @@ +// Geometrie der Türen/Fenster im IFC-Export ([B5]): Rahmen, Blatt, Glas, Ausführung. Reine Rechnung, +// kein WASM nötig. + +import { describe, expect, it } from "vitest"; +import { fillGeometry, DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_DEPTH, DOOR_LEAF_THICK } from "./ifcOpenings"; +import type { DoorType, Opening, Project, Wall, WindowType } from "../model/types"; + +const wall = { id: "W", start: { x: 0, y: 0 }, end: { x: 5, y: 0 } } as Wall; +const host = { nLo: -0.2, nHi: 0.2 }; + +function proj(over: { doorTypes?: DoorType[]; windowTypes?: WindowType[] }): Project { + return { doorTypes: over.doorTypes ?? [], windowTypes: over.windowTypes ?? [] } as unknown as Project; +} +function door(over: Partial = {}): Opening { + return { id: "D", type: "opening", hostWallId: "W", categoryCode: "21", kind: "door", position: 1, width: 1, height: 2.1, sillHeight: 0, ...over } as Opening; +} +function win(over: Partial = {}): Opening { + return { id: "F", type: "opening", hostWallId: "W", categoryCode: "21", kind: "window", position: 1, width: 1.2, height: 1.2, sillHeight: 0.9, ...over } as Opening; +} +const cut = (o: Opening) => ({ from: o.position, to: o.position + o.width, zBottom: o.sillHeight, zTop: o.sillHeight + o.height }); +const wt = (over: Partial = {}): WindowType => + ({ id: "wt", name: "Fenster", kind: "dreh", wingCount: 1, glazing: "zweifach", frameThickness: 0.08, defaultSillHeight: 0.9, defaultWidth: 1.2, defaultHeight: 1.2, ...over }) as WindowType; +const dtp = (over: Partial = {}): DoorType => + ({ id: "dt", name: "Tür", kind: "dreh", leafCount: 1, leafStyle: "glatt", frameThickness: 0.06, defaultWidth: 1, defaultHeight: 2.1, ...over }) as DoorType; + +const bbox = (pts: { x: number; y: number }[]) => ({ + x0: Math.min(...pts.map((p) => p.x)), + x1: Math.max(...pts.map((p) => p.x)), + y0: Math.min(...pts.map((p) => p.y)), + y1: Math.max(...pts.map((p) => p.y)), +}); +const volume = (parts: { pts: { x: number; y: number }[]; depth: number }[]) => + parts.reduce((a, p) => { + const b = bbox(p.pts); + return a + (b.x1 - b.x0) * (b.y1 - b.y0) * p.depth; + }, 0); + +describe("fillGeometry — Fenster", () => { + it("Blendrahmen aus 4 Teilen + eine Glasscheibe, Masse aus Konstanten, Glas = Paketdicke", () => { + const o = win({ typeId: "wt" }); + const g = fillGeometry(proj({ windowTypes: [wt()] }), wall, o, cut(o), host); + const frame = g.parts.filter((p) => p.role === 0); + const glass = g.parts.filter((p) => p.role === 2); + expect(frame.length).toBe(4); + expect(glass.length).toBe(1); + expect(g.kind).toBe("SINGLE_PANEL"); + // Rahmenvolumen = (W·H − lichtes Mass) · Tiefe + const fw = DEFAULT_FRAME_WIDTH; + expect(volume(frame)).toBeCloseTo((1.2 * 1.2 - (1.2 - 2 * fw) * (1.2 - 2 * fw)) * DEFAULT_FRAME_DEPTH, 9); + // Glas füllt das lichte Mass, 24 mm (zweifach), mittig in der Rahmentiefe (aussen = nLo). + const gb = bbox(glass[0].pts); + expect(gb.x1 - gb.x0).toBeCloseTo(1.2 - 2 * fw, 9); + expect(gb.y1 - gb.y0).toBeCloseTo(0.024, 9); + expect((gb.y0 + gb.y1) / 2).toBeCloseTo(-0.2 + DEFAULT_FRAME_DEPTH / 2, 9); + expect(glass[0].zRel).toBeCloseTo(fw, 9); + expect(glass[0].depth).toBeCloseTo(1.2 - 2 * fw, 9); + }); + it("Rahmenbreite/-tiefe/Einzug/Verglasung aus dem Typ; Einzug von innen", () => { + const o = win({ typeId: "wt" }); + const t = wt({ frameWidth: 0.09, frameDepth: 0.1, insetFromFace: 0.05, insetFace: "innen", glazing: "dreifach" }); + const g = fillGeometry(proj({ windowTypes: [t] }), wall, o, cut(o), host); + const frame = g.parts.filter((p) => p.role === 0); + const b = bbox(frame[0].pts); + // innen = nHi: Vorderkante 5 cm eingezogen → Rahmen von 0.05 bis 0.15 (Tiefe 10 cm nach aussen) + expect(b.y0).toBeCloseTo(0.05, 9); + expect(b.y1).toBeCloseTo(0.15, 9); + expect(bbox(frame[2].pts).y1 - bbox(frame[2].pts).y0).toBeCloseTo(0.1, 9); + const gl = bbox(g.parts.find((p) => p.role === 2)!.pts); + expect(gl.y1 - gl.y0).toBeCloseTo(0.036, 9); + expect(gl.x1 - gl.x0).toBeCloseTo(1.2 - 0.18, 9); + }); + it("Rahmentiefe wird auf die Wanddicke geklemmt", () => { + const o = win({ typeId: "wt" }); + const g = fillGeometry(proj({ windowTypes: [wt({ frameDepth: 1 })] }), wall, o, cut(o), host); + const b = bbox(g.parts[0].pts); + expect(b.y0).toBeCloseTo(-0.2, 9); + expect(b.y1).toBeCloseTo(0.2, 9); + }); + it("Flügelzahl → Mittelpfosten + eine Scheibe je Flügel, PartitioningType", () => { + for (const [wing, kind] of [ + [2, "DOUBLE_PANEL_VERTICAL"], + [3, "TRIPLE_PANEL_VERTICAL"], + [4, "NOTDEFINED"], + ] as const) { + const o = win({ typeId: "wt", wingCount: wing }); + const g = fillGeometry(proj({ windowTypes: [wt()] }), wall, o, cut(o), host); + expect(g.parts.filter((p) => p.role === 2).length, `${wing}`).toBe(wing); + expect(g.parts.filter((p) => p.role === 0).length, `${wing}`).toBe(4 + (wing - 1)); + expect(g.kind).toBe(kind); + } + }); + it("Flügeltabelle mit Pfosten und fester Breite: Gläser abgrenzend, keine Überlappung", () => { + const o = win({ typeId: "wt" }); + const t = wt({ + sashes: [ + { kind: "fluegel", autoWidth: false, width: 0.5 }, + { kind: "pfosten", postWidth: 0.1 }, + { kind: "fluegel" }, + ], + }); + const g = fillGeometry(proj({ windowTypes: [t] }), wall, o, cut(o), host); + const glass = g.parts.filter((p) => p.role === 2).map((p) => bbox(p.pts)); + expect(glass.length).toBe(2); + expect(glass[0].x1 - glass[0].x0).toBeCloseTo(0.5, 9); + const clear = 1.2 - 2 * 0.06; + expect(glass[1].x1 - glass[1].x0).toBeCloseTo(clear - 0.6, 9); + expect(glass[1].x0).toBeCloseTo(glass[0].x1 + 0.1, 9); + expect(g.kind).toBe("DOUBLE_PANEL_VERTICAL"); + }); + it("ohne Typ: Standardmasse, zweifach, Flügelzahl der Öffnung", () => { + const o = win({ wingCount: 2 }); + const g = fillGeometry(proj({}), wall, o, cut(o), host); + const glass = g.parts.filter((p) => p.role === 2); + expect(glass.length).toBe(2); + const b = bbox(glass[0].pts); + expect(b.y1 - b.y0).toBeCloseTo(0.024, 9); + }); + it("alle Teile liegen innerhalb der Öffnung und der Wand", () => { + const o = win({ typeId: "wt", wingCount: 2 }); + const g = fillGeometry(proj({ windowTypes: [wt()] }), wall, o, cut(o), host); + for (const p of g.parts) { + const b = bbox(p.pts); + expect(b.x0).toBeGreaterThanOrEqual(1 - 1e-9); + expect(b.x1).toBeLessThanOrEqual(2.2 + 1e-9); + expect(b.y0).toBeGreaterThanOrEqual(-0.2 - 1e-9); + expect(b.y1).toBeLessThanOrEqual(0.2 + 1e-9); + expect(p.zRel).toBeGreaterThanOrEqual(-1e-9); + expect(p.zRel + p.depth).toBeLessThanOrEqual(1.2 + 1e-9); + } + }); +}); + +describe("fillGeometry — Tür", () => { + it("Zarge (3 Teile) + Blatt, Blatt 4 cm mittig, Höhe bis unter den Sturz", () => { + const o = door({ typeId: "dt" }); + const g = fillGeometry(proj({ doorTypes: [dtp()] }), wall, o, cut(o), host); + expect(g.parts.filter((p) => p.role === 0).length).toBe(3); + const leaf = g.parts.filter((p) => p.role === 1); + expect(leaf.length).toBe(1); + const lb = bbox(leaf[0].pts); + expect(lb.y1 - lb.y0).toBeCloseTo(DOOR_LEAF_THICK, 9); + expect(lb.x1 - lb.x0).toBeCloseTo(1 - 2 * DEFAULT_FRAME_WIDTH, 9); + expect(leaf[0].zRel).toBe(0); + expect(leaf[0].depth).toBeCloseTo(2.1 - DEFAULT_FRAME_WIDTH, 9); + expect(g.parts.some((p) => p.role === 2)).toBe(false); + }); + it("zweiflügelig: zwei Blätter, DOUBLE_DOOR_SINGLE_SWING", () => { + const o = door({ typeId: "dt" }); + const g = fillGeometry(proj({ doorTypes: [dtp({ leafCount: 2 })] }), wall, o, cut(o), host); + expect(g.parts.filter((p) => p.role === 1).length).toBe(2); + expect(g.kind).toBe("DOUBLE_DOOR_SINGLE_SWING"); + }); + it("Glastür: Glasfläche = glazingRatio des Blatts, Blatt als Rahmen darum, ohne Überlappung", () => { + const o = door({ typeId: "dt" }); + const g = fillGeometry(proj({ doorTypes: [dtp({ leafStyle: "glas", glazingRatio: 0.36 })] }), wall, o, cut(o), host); + const glass = g.parts.filter((p) => p.role === 2); + expect(glass.length).toBe(1); + const gb = bbox(glass[0].pts); + const leafW = 1 - 2 * DEFAULT_FRAME_WIDTH; + const leafH = 2.1 - DEFAULT_FRAME_WIDTH; + expect(((gb.x1 - gb.x0) * glass[0].depth) / (leafW * leafH)).toBeCloseTo(0.36, 9); + const leaf = g.parts.filter((p) => p.role === 1); + expect(leaf.length).toBe(4); + // Blatt ohne Glasfläche = volle Blattfläche − Glasfläche, über 4 cm + expect(volume(leaf)).toBeCloseTo((leafW * leafH - (gb.x1 - gb.x0) * glass[0].depth) * DOOR_LEAF_THICK, 9); + }); + it("Oberlicht: Riegel + Glasstreifen, Blatt entsprechend kürzer", () => { + const o = door({ typeId: "dt" }); + const g = fillGeometry(proj({ doorTypes: [dtp({ transomHeight: 0.4 })] }), wall, o, cut(o), host); + const glass = g.parts.filter((p) => p.role === 2); + expect(glass.length).toBe(1); + expect(glass[0].depth).toBeCloseTo(0.4, 9); + expect(glass[0].zRel + glass[0].depth).toBeCloseTo(2.1 - DEFAULT_FRAME_WIDTH, 9); + const leaf = g.parts.find((p) => p.role === 1)!; + expect(leaf.zRel + leaf.depth).toBeCloseTo(2.1 - DEFAULT_FRAME_WIDTH - 0.4 - DEFAULT_FRAME_WIDTH, 9); + }); + it("reine Wandöffnung (Typ oder Inline): kein Körper, keine Ausführung", () => { + const o = door({ typeId: "dt" }); + expect(fillGeometry(proj({ doorTypes: [dtp({ kind: "wandoeffnung" })] }), wall, o, cut(o), host)).toMatchObject({ kind: null, parts: [] }); + const o2 = door({ doorType: "wandoeffnung" }); + expect(fillGeometry(proj({}), wall, o2, cut(o2), host)).toMatchObject({ kind: null, parts: [] }); + }); + it("Scharnierseite und Aufschlag → LEFT/RIGHT (von der Aufschlagseite gesehen), Schiebetür", () => { + // Wand entlang +X, linke Normale +Y. Standard: Aufschlag nach +Y, Scharnier am Anfang (x klein): + // von +Y nach −Y gesehen liegt x klein rechts → RIGHT. + const kind = (o: Opening, t: DoorType = dtp()) => fillGeometry(proj({ doorTypes: [t] }), wall, o, cut(o), host).kind; + expect(kind(door({ typeId: "dt" }))).toBe("SINGLE_SWING_RIGHT"); + expect(kind(door({ typeId: "dt", hinge: "end" }))).toBe("SINGLE_SWING_LEFT"); + // Aufschlag nach aussen (−Y): Blickrichtung dreht → Seiten tauschen. + expect(kind(door({ typeId: "dt", openingDir: "out" }))).toBe("SINGLE_SWING_LEFT"); + expect(kind(door({ typeId: "dt", swing: "right" }))).toBe("SINGLE_SWING_LEFT"); + expect(kind(door({ typeId: "dt" }), dtp({ kind: "schiebe" }))).toBe("SLIDING_TO_RIGHT"); + expect(kind(door({ typeId: "dt" }), dtp({ kind: "schiebe", leafCount: 2 }))).toBe("DOUBLE_DOOR_SLIDING"); + }); + it("Füllungssystem: Y = Aufschlagrichtung, Ursprung = Öffnungsmitte auf der Achse", () => { + const o = door({ typeId: "dt" }); + const g = fillGeometry(proj({ doorTypes: [dtp()] }), wall, o, cut(o), host); + expect(g.origin).toEqual({ x: 1.5, y: 0 }); + expect(g.u.x).toBeCloseTo(1, 12); // Aufschlag +Y → X = (swing.y, −swing.x) = (1, 0) + expect(g.u.y).toBeCloseTo(0, 12); + const out = fillGeometry(proj({ doorTypes: [dtp()] }), wall, door({ typeId: "dt", openingDir: "out" }), cut(o), host); + expect(out.u.x).toBeCloseTo(-1, 12); + }); +}); diff --git a/src/export/ifcOpenings.ts b/src/export/ifcOpenings.ts new file mode 100644 index 00000000..9594763f --- /dev/null +++ b/src/export/ifcOpenings.ts @@ -0,0 +1,260 @@ +// Geometrie der Türen und Fenster für den IFC-Export ([B5], 28.10.): statt einer Box getrennte Körper im +// selben Bauteil — Rahmen/Zarge, Türblatt bzw. Glas — plus OperationType (Tür) und PartitioningType +// (Fenster). Alles sind vertikale Extrusionen von Grundriss-Rechtecken (wie die Wände), Profile in +// Welt-XY, Höhen ab Öffnungs-Unterkante; Rust (`ifc_export.rs`) rechnet sie ins Füllungssystem. +// +// Masse kommen aus dem Modell, soweit es sie hergibt (Rahmenbreite/-tiefe, Schichteinzug, Flügelzahl und +// -tabelle, Verglasung, Blattzahl, Glasanteil, Oberlicht). Fehlendes füllen dieselben Konstanten wie das +// 3D (`src-tauri/core/src/openings3d.rs`), damit IFC und Ansicht dasselbe zeigen: +// - Rahmenbreite 6 cm (`DEFAULT_FRAME_WIDTH`), Rahmentiefe 7 cm (`DEFAULT_FRAME_DEPTH`: reale Rahmen +// sind 70–90 mm tief, nicht so dick wie die Wand), Türblatt 4 cm (`DOOR_LEAF_THICK`). +// - Glaspaket: nur im IFC nötig, das 3D zeichnet Einzelscheiben. 1 Scheibe 6 mm, 2 Scheiben 24 mm +// (4-16-4, übliches Isolierglas), 3 Scheiben 36 mm (4-12-4-12-4 ≈ 36 mm). +// Nicht abgebildet (bewusst einfach): Sprossen, Fensterbank/Rollladenkasten, Schwelle, Flügelrahmen im +// Blendrahmen, Kassettenfelder, Schiebe-Laufschiene — die Körper stehen im geschlossenen Zustand. + +import type { Opening, Project, SashDef, Vec2, Wall } from "../model/types"; +import { getDoorType, getWindowType, glazingPanesOf } from "../model/types"; + +/** Rolle eines Körpers: 0 Rahmen/Zarge, 1 Türblatt, 2 Glas (Kodierung `ifc_export.rs`). */ +export type FillRole = 0 | 1 | 2; + +export interface FillPart { + role: FillRole; + /** Profil in Welt-XY (Rechteck, gegen den Uhrzeigersinn in Achs-/Normalenrichtung). */ + pts: Vec2[]; + /** Unterkante ab Öffnungs-Unterkante (m). */ + zRel: number; + /** Höhe des Körpers (m). */ + depth: number; +} + +export interface FillGeometry { + /** Ursprung des Füllungssystems (Welt-XY): Öffnungsmitte auf der Wandachse. */ + origin: Vec2; + /** X-Richtung des Füllungssystems (Einheitsvektor); Y = linke Normale davon. */ + u: Vec2; + /** IfcDoorTypeOperationEnum bzw. IfcWindowTypePartitioningEnum; null = Modell gibt nichts her. */ + kind: string | null; + parts: FillPart[]; +} + +export const DEFAULT_FRAME_WIDTH = 0.06; +export const DEFAULT_FRAME_DEPTH = 0.07; +export const DOOR_LEAF_THICK = 0.04; +/** Glaspaket-Dicke je Scheibenzahl (1, 2, 3). */ +export const GLASS_PACKAGE_THICKNESS = [0.006, 0.024, 0.036] as const; +/** Glasanteil des Türblatts, wenn der Typ keinen angibt (`glas` ohne `glazingRatio`). */ +const DEFAULT_GLAZING_RATIO = 0.5; +/** Kleinste Teilabmessung, damit nie ein flaches Profil entsteht (Meter). */ +const MIN_DIM = 0.005; + +const sub = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x - b.x, y: a.y - b.y }); +const norm = (v: Vec2): Vec2 => { + const len = Math.hypot(v.x, v.y) || 1; + return { x: v.x / len, y: v.y / len }; +}; +const leftOf = (u: Vec2): Vec2 => ({ x: -u.y, y: u.x }); +const dotv = (a: Vec2, b: Vec2): number => a.x * b.x + a.y * b.y; + +/** Flügeleinteilung eines Fensters, auf die Achsbreite aufgelöst: (von, bis, Pfosten?) ab Laibungsanfang. */ +interface SashSpan { + from: number; + to: number; + post: boolean; +} + +/** + * Löst Flügel (`fluegel`) und Pfosten (`pfosten`) zu Intervallen auf: Pfosten und Flügel mit fester Breite + * behalten sie, die übrigen teilen den Rest gleichmässig (gleiche Regel wie `sashSegments` im 2D). Ohne + * Tabelle: `wingCount` gleiche Flügel. + */ +function sashSpans(sashes: readonly SashDef[] | undefined, wingCount: number, total: number): SashSpan[] { + const list: readonly SashDef[] = + sashes && sashes.length > 0 + ? sashes + : Array.from({ length: Math.max(1, Math.round(wingCount)) }, (): SashDef => ({ kind: "fluegel" })); + const postW = (s: SashDef): number => Math.max(0, s.postWidth ?? 0.06); + const fixedW = (s: SashDef): number | null => (s.kind === "pfosten" ? postW(s) : s.autoWidth === false ? Math.max(0, s.width ?? 0) : null); + let fixed = 0; + let auto = 0; + for (const s of list) { + const w = fixedW(s); + if (w === null) auto++; + else fixed += w; + } + const autoW = auto > 0 ? Math.max(0, total - fixed) / auto : 0; + const out: SashSpan[] = []; + let at = 0; + for (const s of list) { + const w = fixedW(s) ?? autoW; + out.push({ from: at, to: at + w, post: s.kind === "pfosten" }); + at += w; + } + return out; +} + +/** + * Körper und Ausführung der Füllung einer Öffnung. + * + * `c` = Achs-Intervall (`from`/`to`, Abstand ab `wall.start`) und absolute Höhen der Öffnung, `host` = + * Querausdehnung der ganzen Wand (`nLo`/`nHi` entlang der linken Normalen ab `wall.start`; `nLo` ist die + * Aussenseite, wie im 2D/3D). + */ +export function fillGeometry( + project: Project, + wall: Wall, + opening: Opening, + c: { from: number; to: number; zBottom: number; zTop: number }, + host: { nLo: number; nHi: number }, +): FillGeometry { + const u = norm(sub(wall.end, wall.start)); + const n = leftOf(u); + const isDoor = opening.kind === "door"; + const W = c.to - c.from; + const H = c.zTop - c.zBottom; + const at = (a: number, b: number): Vec2 => ({ + x: wall.start.x + u.x * a + n.x * b, + y: wall.start.y + u.y * a + n.y * b, + }); + /** Rechteck [a0,a1] entlang der Achse × [b0,b1] quer dazu (Welt-XY). */ + const rect = (a0: number, a1: number, b0: number, b1: number): Vec2[] => [at(a0, b0), at(a1, b0), at(a1, b1), at(a0, b1)]; + const center = c.from + W / 2; + const origin = at(center, 0); + const parts: FillPart[] = []; + const add = (role: FillRole, a0: number, a1: number, b0: number, b1: number, z0: number, z1: number): void => { + if (a1 - a0 < 1e-6 || b1 - b0 < 1e-6 || z1 - z0 < 1e-6) return; + parts.push({ role, pts: rect(a0, a1, b0, b1), zRel: z0, depth: z1 - z0 }); + }; + + const dt = isDoor ? getDoorType(project, opening) : undefined; + const wt = isDoor ? undefined : getWindowType(project, opening); + const t = dt ?? wt; + + // Querlage des Rahmens: Tiefe (Typ oder 7 cm), Schichteinzug von der gewählten Wandfläche, auf die + // Wanddicke geklemmt — dieselbe Rechnung wie `windowSymbol` (2D) und `resolveFrameNormalRange` (3D). + const total = host.nHi - host.nLo; + const frameDepth = Math.min(total, t?.frameDepth && t.frameDepth > 1e-9 ? t.frameDepth : DEFAULT_FRAME_DEPTH); + const inset = Math.max(0, t?.insetFromFace ?? 0); + const outside = (t?.insetFace ?? "aussen") === "aussen"; + const front = outside ? host.nLo + inset : host.nHi - inset; + const back = outside ? front + frameDepth : front - frameDepth; + let b0 = Math.max(host.nLo, Math.min(host.nHi, Math.min(front, back))); + let b1 = Math.max(host.nLo, Math.min(host.nHi, Math.max(front, back))); + if (b1 - b0 < MIN_DIM) { + b0 = host.nLo; + b1 = host.nHi; + } + const bMid = (b0 + b1) / 2; + + // Sichtbare Rahmenbreite: höchstens ein Viertel der kleineren Öffnungsabmessung, sonst bliebe nichts offen. + const fw = Math.max(MIN_DIM, Math.min(t?.frameWidth && t.frameWidth > 1e-9 ? t.frameWidth : DEFAULT_FRAME_WIDTH, Math.min(W, H) / 4)); + const aIn0 = c.from + fw; + const aIn1 = c.to - fw; + + if (!isDoor) { + // ── Fenster: Blendrahmen (Pfosten links/rechts, Sturz, Sohlbank), Mittelpfosten, Glas je Flügel ── + const wing = opening.wingCount ?? wt?.wingCount ?? 1; + add(0, c.from, aIn0, b0, b1, 0, H); + add(0, aIn1, c.to, b0, b1, 0, H); + add(0, aIn0, aIn1, b0, b1, H - fw, H); + add(0, aIn0, aIn1, b0, b1, 0, fw); + const panes = wt ? glazingPanesOf(wt) : 2; + const gt = Math.min(GLASS_PACKAGE_THICKNESS[panes - 1], b1 - b0); + const g0 = bMid - gt / 2; + const g1 = bMid + gt / 2; + const spans = sashSpans(wt?.sashes, wing, aIn1 - aIn0); + let glassCount = 0; + spans.forEach((s, i) => { + const x0 = aIn0 + s.from; + const x1 = aIn0 + s.to; + if (s.post) { + add(0, x0, x1, b0, b1, fw, H - fw); + return; + } + // Zwischen zwei Flügeln ohne Pfosten steht ein Mittelpfosten (Breite = Rahmenbreite) auf der Grenze. + const prev = spans[i - 1]; + const next = spans[i + 1]; + const gx0 = i === 0 || prev.post ? x0 : x0 + fw / 2; + const gx1 = i === spans.length - 1 || next.post ? x1 : x1 - fw / 2; + if (next && !next.post) add(0, x1 - fw / 2, x1 + fw / 2, b0, b1, fw, H - fw); + add(2, gx0, gx1, g0, g1, fw, H - fw); + glassCount++; + }); + // Teilung nach IFC: nur die senkrechten Standardfälle sind benannt (sonst NOTDEFINED, das Modell + // kennt Sprossen und Seitenverhältnisse, die IFC nicht als Enum führt). + const kind = glassCount === 1 ? "SINGLE_PANEL" : glassCount === 2 ? "DOUBLE_PANEL_VERTICAL" : glassCount === 3 ? "TRIPLE_PANEL_VERTICAL" : "NOTDEFINED"; + return { origin, u, kind, parts }; + } + + // ── Tür ── + const kind = dt?.kind ?? (opening.doorType === "wandoeffnung" ? "wandoeffnung" : "dreh"); + const leafCount = dt?.leafCount ?? 1; + // Aufschlagrichtung wie `doorSymbol`: linke Achsnormale, `openingDir: "out"` spiegelt sie. + const swingSign = (opening.swing ?? "left") === "left" ? 1 : -1; + const dirSign = (opening.openingDir ?? "in") === "in" ? 1 : -1; + const swingDir: Vec2 = { x: n.x * swingSign * dirSign, y: n.y * swingSign * dirSign }; + // Füllungssystem der Tür: Y = Aufschlagrichtung (IFC: die Tür schlägt nach +Y auf), X = Y × Z. + const doorU: Vec2 = { x: swingDir.y, y: -swingDir.x }; + if (kind === "wandoeffnung") return { origin, u: doorU, kind: null, parts: [] }; + + // Zarge: Pfosten links/rechts über die ganze Höhe und Sturz (keine Schwelle). + add(0, c.from, aIn0, b0, b1, 0, H); + add(0, aIn1, c.to, b0, b1, 0, H); + add(0, aIn0, aIn1, b0, b1, H - fw, H); + + // Oberlicht: fester Glasstreifen über einem Kämpfer (Riegel in Rahmenbreite) innerhalb der Öffnungshöhe. + const th = dt?.transomHeight ?? 0; + const hasTransom = th > MIN_DIM && th < H - fw - 0.5; + const leafTop = hasTransom ? H - fw - th - fw : H - fw; + if (hasTransom) { + add(0, aIn0, aIn1, b0, b1, leafTop, leafTop + fw); + const gt = Math.min(GLASS_PACKAGE_THICKNESS[1], b1 - b0); + add(2, aIn0, aIn1, bMid - gt / 2, bMid + gt / 2, leafTop + fw, H - fw); + } + + // Türblatt/-blätter im lichten Mass der Zarge, mittig in der Rahmentiefe. + const lt = Math.min(DOOR_LEAF_THICK, b1 - b0); + const l0 = bMid - lt / 2; + const l1 = bMid + lt / 2; + const leafSpans: [number, number][] = + leafCount >= 2 + ? [ + [aIn0, (aIn0 + aIn1) / 2], + [(aIn0 + aIn1) / 2, aIn1], + ] + : [[aIn0, aIn1]]; + const glazed = dt?.leafStyle === "glas"; + const ratio = Math.min(0.9, Math.max(0.05, dt?.glazingRatio ?? DEFAULT_GLAZING_RATIO)); + for (const [x0, x1] of leafSpans) { + if (!glazed) { + add(1, x0, x1, l0, l1, 0, leafTop); + continue; + } + // Glastür: Glasfläche = `glazingRatio` des Blatts (gleichmässig verkleinert um die Blattmitte), das + // Blatt als umlaufender Rahmen darum; das Glas füllt die Blattdicke zu 60 % (4–24 mm, mittig). + const s = Math.sqrt(ratio); + const cx = (x0 + x1) / 2; + const cz = leafTop / 2; + const gw = (x1 - x0) * s; + const gh = leafTop * s; + const [px0, px1, pz0, pz1] = [cx - gw / 2, cx + gw / 2, cz - gh / 2, cz + gh / 2]; + add(1, x0, x1, l0, l1, 0, pz0); + add(1, x0, x1, l0, l1, pz1, leafTop); + add(1, x0, px0, l0, l1, pz0, pz1); + add(1, px1, x1, l0, l1, pz0, pz1); + const gt = Math.min(GLASS_PACKAGE_THICKNESS[1], lt * 0.6); + add(2, px0, px1, bMid - gt / 2, bMid + gt / 2, pz0, pz1); + } + + // OperationType: Blattzahl und Scharnierseite. IFC blickt von der Aufschlagseite (+Y des Füllungssystems) + // auf die Tür; "links" = Scharnier auf der +X-Seite des Systems (X = Y × Z, von +Y aus gesehen links). + const hingeAtStart = (opening.hinge ?? "start") === "start"; + const hingeAxis = hingeAtStart ? c.from : c.to; + const hingeLocalX = dotv(sub(at(hingeAxis, 0), origin), doorU); + const left = hingeLocalX > 0; + let op: string; + if (kind === "schiebe") op = leafCount >= 2 ? "DOUBLE_DOOR_SLIDING" : left ? "SLIDING_TO_LEFT" : "SLIDING_TO_RIGHT"; + else op = leafCount >= 2 ? "DOUBLE_DOOR_SINGLE_SWING" : left ? "SINGLE_SWING_LEFT" : "SINGLE_SWING_RIGHT"; + return { origin, u: doorU, kind: op, parts }; +}