diff --git a/TODO.md b/TODO.md index 3108a78f..7fc8803e 100644 --- a/TODO.md +++ b/TODO.md @@ -353,8 +353,14 @@ Ganzes nicht WASM-tauglich (rayon, tempfile, SystemTime) — nur einzelne Module - ✅ Georeferenz [69]. - ○ Offen: IsExternal/LoadBearing/ThermalTransmittance für Wand/Decke/Tür/Fenster brauchen Modellfelder (z. B. am Wandtyp tragend/aussen, λ je Bauteil → U-Wert). · S–M - - ○ Offen: IfcMaterialLayerSetUsage + Achs-Darstellung („Axis") an Extrusions-Wänden; - Tür/Fenster mit Rahmen/Blatt statt Box; Bogenwände als echte Kurve. · M + - ✅ IfcMaterialLayerSetUsage + Achs-Darstellung an Extrusions-Wänden. (28.10.) Wand-Placement am + Wandanfang, X = Achse, Y = linke Normale (Rust rechnet die Welt-Profile und die Öffnungen ins + Wandsystem); „Axis“-Darstellung (IfcPolyline, Unterkontext GRAPH_VIEW) + Usage (AXIS2, POSITIVE, + Offset = Abstand der Aussenschicht von der Achse), nur wenn die Typ-Schichten den Bandquerschnitt + 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 - ✅ 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 b3a595c1..a1024ade 100644 --- a/src-tauri/fileio/src/ifc_export.rs +++ b/src-tauri/fileio/src/ifc_export.rs @@ -20,11 +20,22 @@ // 2 = IfcPositiveRatioMeasure (value = Zahl) // structure= Geschoss-Index oder −1 (Gebäude) // -// WALL_SOLIDS = 1, structure, id, name, TYPEREF, PSETS, n_solids, (PTS, z_rel, depth) × n_solids +// WALL_SOLIDS = 1, structure, id, name, TYPEREF, PSETS, FRAME, n_solids, (PTS, z_rel, depth) × n_solids +// FRAME = has_frame (0/1); wenn 1: ox, oy, ux, uy (Wandanfang und Achsrichtung in Welt-XY, ux²+uy² = 1), +// axis_len, usage (0/1), offset. Mit Rahmen sitzt das Placement am Wandanfang, X = Achse, Y = linke +// Normale ([B5]: so ordnen Revit/ArchiCAD die Schichten der Achse zu); die PTS bleiben Welt-XY und +// werden hier ins Wandsystem gerechnet. Dazu eine „Axis“-Darstellung (IfcPolyline 0 … axis_len) +// und, bei usage = 1 und vorhandenem Typ, IfcMaterialLayerSetUsage (AXIS2, POSITIVE, `offset` = +// Abstand der ersten Schicht von der Achse entlang +Y). Ohne Rahmen: Placement ohne Drehung wie bisher. // WALL_MESH = 2, structure, id, name, TYPEREF, PSETS, MESH // CEILING = 3, structure, id, name, TYPEREF, PSETS, PTS, z_rel, depth // OPENING = 4, wall_id, structure, opening_id, is_door (0/1), fill_name, PTS (Öffnungskörper), z_rel, -// depth, PTS (Füllung), width, PSETS +// depth, width, kind_text (Text oder −1 = keine: Tür OperationType, Fenster PartitioningType, +// IFC-Enum-Name), FILL_FRAME, n_parts, (role, PTS, z_rel, depth) × n_parts, PSETS +// FILL_FRAME = ox, oy, ux, uy (Welt-XY): Placement der Füllung (X = u, Y = linke Normale von u). Die +// Teile-PTS bleiben Welt-XY, z_rel zählt ab Öffnungs-Unterkante. n_parts = 0: kein Körper. +// role: 0 Rahmen/Zarge, 1 Türblatt, 2 Glas. Alle Teile eines Bauteils sind getrennte Körper in EINER +// Darstellung, je mit eigenem IfcStyledItem (Farbe/Transparenz je Rolle). // STAIR = 5, structure, id, predefined (Text), PTS, z_rel, depth // EXTRUSION = 6, structure, id, PTS, z_rel, depth // SPACE = 7, structure, id, name, long_name, external (0/1), height, PTS, net_area, gross_area, @@ -429,6 +440,34 @@ impl<'a> Reader<'a> { } } +/// Lokales Wand-/Füllungssystem in Welt-XY: Ursprung und Richtung der X-Achse (Y = linke Normale). +#[derive(Clone, Copy)] +struct Frame { + ox: f64, + oy: f64, + ux: f64, + uy: f64, +} + +impl Frame { + /// Identität (Welt-Koordinaten). + const WORLD: Frame = Frame { ox: 0.0, oy: 0.0, ux: 1.0, uy: 0.0 }; + + fn is_world(&self) -> bool { + self.ox == 0.0 && self.oy == 0.0 && self.ux == 1.0 && self.uy == 0.0 + } + + /// Welt-XY → lokal (X = u, Y = linke Normale (−uy, ux)). + fn local(&self, x: f64, y: f64) -> (f64, f64) { + let (dx, dy) = (x - self.ox, y - self.oy); + (dx * self.ux + dy * self.uy, -dx * self.uy + dy * self.ux) + } + + fn local_pts(&self, pts: &[(f64, f64)]) -> Vec<(f64, f64)> { + pts.iter().map(|&(x, y)| self.local(x, y)).collect() + } +} + struct Mesh { positions: Vec, indices: Vec, @@ -506,6 +545,8 @@ struct PsetAcc { struct TypeAcc { key: String, type_id: usize, + /// IfcMaterialLayerSet des Typs (0 = keiner) für die LayerSetUsage der Exemplare. + layer_set: usize, occurrences: Vec, } @@ -527,8 +568,11 @@ struct Builder { materials: HashMap, types: Vec, type_index: HashMap, - /// Wand-id → (Entität, Placement) für die Öffnungen. - walls: HashMap, + /// Wand-id → (Entität, Placement, Wandsystem) für die Öffnungen. + walls: HashMap, + /// Untergeordneter Kontext „Axis“ (GRAPH_VIEW), beim ersten Gebrauch angelegt (0 = noch nicht). + axis_context: usize, + spaces: Vec<(i64, Vec)>, column_materials: Vec<(String, String, Vec)>, } @@ -625,6 +669,43 @@ impl Builder { self.add("IFCLOCALPLACEMENT", format!("#{relative_to},#{axis}")) } + /// Placement am Punkt (`frame.ox`, `frame.oy`, 0) mit gedrehter X-Achse relativ zu `relative_to`. + fn emit_placement_frame(&mut self, frame: &Frame, relative_to: usize) -> usize { + let origin = self.add("IFCCARTESIANPOINT", list(&[fmt_real(frame.ox), fmt_real(frame.oy), fmt_real(0.0)])); + let dir = self.add("IFCDIRECTION", list(&[fmt_real(frame.ux), fmt_real(frame.uy), fmt_real(0.0)])); + // IFC4: Axis und RefDirection stehen nur zusammen (Axis = +Z). + let axis = self.add("IFCAXIS2PLACEMENT3D", format!("#{origin},#{},#{dir}", self.extrude_dir)); + self.add("IFCLOCALPLACEMENT", format!("#{relative_to},#{axis}")) + } + + /// Untergeordneter Darstellungskontext „Axis“ (GRAPH_VIEW), einmal je Datei. + fn axis_context(&mut self) -> usize { + if self.axis_context == 0 { + self.axis_context = self.add( + "IFCGEOMETRICREPRESENTATIONSUBCONTEXT", + format!("{},{},*,*,*,*,#{},$,{},$", ifc_string("Axis"), ifc_string("Model"), self.context, enum_("GRAPH_VIEW")), + ); + } + self.axis_context + } + + /// Wand-Darstellung: „Axis“ (IfcPolyline 0 … `len` in lokal X) und „Body“ (SweptSolid aus `solids`). + fn emit_wall_shape(&mut self, solids: &[usize], len: f64) -> usize { + let p0 = self.add("IFCCARTESIANPOINT", list(&[fmt_real(0.0), fmt_real(0.0)])); + let p1 = self.add("IFCCARTESIANPOINT", list(&[fmt_real(len), fmt_real(0.0)])); + let curve = self.add("IFCPOLYLINE", refs(&[p0, p1])); + let axis_ctx = self.axis_context(); + let axis = self.add( + "IFCSHAPEREPRESENTATION", + format!("#{axis_ctx},{},{},{}", ifc_string("Axis"), ifc_string("Curve2D"), refs(&[curve])), + ); + let body = self.add( + "IFCSHAPEREPRESENTATION", + format!("#{},{},{},{}", self.context, ifc_string("Body"), ifc_string("SweptSolid"), refs(solids)), + ); + self.add("IFCPRODUCTDEFINITIONSHAPE", format!("$,$,{}", refs(&[axis, body]))) + } + /// SweptSolid-Körper aus Extrusionen. fn emit_swept_shape(&mut self, solids: &[usize]) -> usize { let rep = self.add( @@ -708,6 +789,7 @@ impl Builder { t.kind.ifc(), format!("{guid},#{},{},$,$,$,$,$,$,{}", self.owner_history, ifc_string(&t.name), enum_(&t.predefined)), ); + let mut layer_set = 0; if !layer_ids.is_empty() { let set = self.add("IFCMATERIALLAYERSET", format!("{},{},$", refs(&layer_ids), ifc_string(&t.name))); let rel_guid = self.gid(&format!("{key}/material")); @@ -715,12 +797,20 @@ impl Builder { "IFCRELASSOCIATESMATERIAL", format!("{rel_guid},#{},$,$,{},#{set}", self.owner_history, refs(&[type_id])), ); + layer_set = set; } self.type_index.insert(key.clone(), self.types.len()); - self.types.push(TypeAcc { key, type_id, occurrences: Vec::new() }); + self.types.push(TypeAcc { key, type_id, layer_set, occurrences: Vec::new() }); self.types.len() - 1 } + /// IfcMaterialLayerSet eines schon angelegten Typs (`finish_typed` legt ihn an). + fn layer_set_of(&self, t: &TypeRef) -> Option { + let key = format!("type/{}/{}", t.kind.ifc(), t.id); + let set = self.types[*self.type_index.get(&key)?].layer_set; + (set != 0).then_some(set) + } + /// Gemeinsamer Abschluss der Bauteile mit Typ und Psets: Typ (falls vorhanden) anlegen, Entität /// schreiben, Typ-Exemplar, Eingliederung und Psets vormerken. #[allow(clippy::too_many_arguments)] @@ -810,6 +900,7 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { types: Vec::new(), type_index: HashMap::new(), walls: HashMap::new(), + axis_context: 0, spaces: Vec::new(), column_materials: Vec::new(), }; @@ -966,18 +1057,49 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { let name = r.string()?; let ty = r.type_ref()?; let psets = r.psets()?; + let has_frame = r.flag()?; + let (frame, axis_len, usage, offset) = if has_frame { + let (ox, oy, ux, uy) = (r.f()?, r.f()?, r.f()?, r.f()?); + if ((ux * ux + uy * uy) - 1.0).abs() > 1e-6 { + return Err(format!("Achsrichtung nicht normiert bei {}", r.pos - 1)); + } + let (len, usage, offset) = (r.f()?, r.flag()?, r.f()?); + (Frame { ox, oy, ux, uy }, len, usage, offset) + } else { + (Frame::WORLD, 0.0, false, 0.0) + }; let n = r.idx()?; let mut solids = Vec::new(); for _ in 0..n { - let pts = r.pts()?; + let pts = frame.local_pts(&r.pts()?); let z_rel = r.f()?; let depth = r.f()?; solids.push(w.emit_extrusion(&pts, z_rel, depth)); } - let placement = w.emit_placement(0.0, w.placement_of(structure)); - let shape = w.emit_swept_shape(&solids); + let parent = w.placement_of(structure); + let (placement, shape) = if has_frame { + (w.emit_placement_frame(&frame, parent), w.emit_wall_shape(&solids, axis_len)) + } else { + (w.emit_placement(0.0, parent), w.emit_swept_shape(&solids)) + }; let entity = w.finish_typed("IFCWALL", format!("wall/{id}"), &name, &ty, &psets, structure, placement, shape, None, true); - w.walls.insert(id, (entity, placement)); + if has_frame && usage { + // Schichten des Typs der Wandachse zuordnen: erste Schicht (aussen) liegt bei `offset` + // von der Achse, die übrigen folgen in +Y (linke Normale). + let set = ty.as_ref().and_then(|t| w.layer_set_of(t)); + if let Some(set) = set { + let u = w.add( + "IFCMATERIALLAYERSETUSAGE", + format!("#{set},{},{},{},$", enum_("AXIS2"), enum_("POSITIVE"), fmt_real(offset)), + ); + let g = w.gid(&format!("wall/{id}/material")); + w.add( + "IFCRELASSOCIATESMATERIAL", + format!("{g},#{},$,$,{},#{u}", w.owner_history, refs(&[entity])), + ); + } + } + w.walls.insert(id, (entity, placement, frame)); } c if c == REC_WALL_MESH => { let structure = r.structure(n_storeys)?; @@ -988,7 +1110,7 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { let mesh = r.mesh()?; let (placement, shape) = w.emit_triangulated_product(&mesh, w.placement_of(structure)); let entity = w.finish_typed("IFCWALL", format!("wall/{id}"), &name, &ty, &psets, structure, placement, shape, None, true); - w.walls.insert(id, (entity, placement)); + w.walls.insert(id, (entity, placement, Frame::WORLD)); } c if c == REC_CEILING => { let structure = r.structure(n_storeys)?; @@ -1014,9 +1136,15 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result { let fill_pts = r.pts()?; let width = r.f()?; let psets = r.psets()?; - let Some(&(host_entity, host_placement)) = w.walls.get(&wall_id) else { + 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 (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( @@ -1440,6 +1568,12 @@ mod tests { b.str("Aussenwand"); b.wall_type(); b.ref_pset("Pset_WallCommon", "Aussenwand"); + // W1 mit Wandsystem (Achse, LayerSetUsage), W2 ohne (altes Verhalten). + if wid == "W1" { + b.n(&[1.0, 0.0, 0.0, 1.0, 0.0, 5.0, 1.0, -0.2]); + } else { + b.n(&[0.0]); + } b.n(&[1.0]); b.pts(&SQUARE); b.n(&[0.0, 2.6]); @@ -1602,6 +1736,91 @@ mod tests { assert_eq!(count(&ifc, "IFCRELAGGREGATES"), 4); } + /// Zeile der ersten Entität eines Typs. + fn first_line<'a>(ifc: &'a str, ty: &str) -> &'a str { + let head = format!("{ty}("); + ifc.lines().find(|l| l.split_once('=').is_some_and(|(_, b)| b.starts_with(&head))).unwrap_or_else(|| panic!("{ty} fehlt")) + } + + /// Kopf (META) eines Mini-Projekts ohne Geschoss. + fn mini() -> B { + let mut b = B::new(); + b.str("t"); + b.str("H"); + b.n(&[1_700_000_000.0]); + b.str("2026-10-28T12:00:00"); + b.n(&[0.0, f64::NAN, 0.0]); + b + } + + #[test] + fn wand_mit_achse_und_layer_set_usage() { + let ifc = build(&full_house(false)).unwrap(); + check_structure(&ifc); + // Nur W1 hat Wandsystem: eine Usage, eine Axis-Darstellung, ein Axis-Kontext. + assert_eq!(count(&ifc, "IFCMATERIALLAYERSETUSAGE"), 1); + assert_eq!(count(&ifc, "IFCGEOMETRICREPRESENTATIONSUBCONTEXT"), 1); + let usage = first_line(&ifc, "IFCMATERIALLAYERSETUSAGE"); + assert!(usage.contains(".AXIS2.,.POSITIVE.,-0.2,$"), "{usage}"); + // Die Usage verweist auf das LayerSet des Typs (dasselbe wie die Typ-Zuordnung). + let set_no: usize = usage.split("(#").nth(1).unwrap().split(',').next().unwrap().parse().unwrap(); + assert!(ifc.contains(&format!("#{set_no}=IFCMATERIALLAYERSET("))); + // Axis: IfcPolyline von (0,0) nach (5,0) in Kurve2D. + assert!(ifc.contains("'Axis','Curve2D'")); + assert!(ifc.contains("IFCCARTESIANPOINT((5.0,0.0))")); + assert!(ifc.contains("IFCDIRECTION((1.0,0.0,0.0))")); + } + + #[test] + fn gedrehte_wand_rechnet_profil_und_oeffnung_ins_wandsystem() { + // Wand von (10,20) nach (10,25): u = (0,1), linke Normale = (−1,0). + let mut b = mini(); + b.n(&[REC_WALL_SOLIDS, -1.0]); + b.str("W"); + b.str("Wand"); + b.no_type(); + b.no_psets(); + b.n(&[1.0, 10.0, 20.0, 0.0, 1.0, 5.0, 0.0, 0.0]); + 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(); + 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). + assert!(ifc.contains("IFCCARTESIANPOINT((0.0,-0.2))")); + assert!(ifc.contains("IFCCARTESIANPOINT((5.0,0.2))")); + // Öffnung lokal bei x = 1…2, quer −0.3…0.3. + assert!(ifc.contains("IFCCARTESIANPOINT((1.0,-0.3))")); + assert!(ifc.contains("IFCCARTESIANPOINT((2.0,0.3))")); + assert!(ifc.contains("IFCDIRECTION((0.0,1.0,0.0))")); + // Ohne Typ keine Usage, trotzdem Axis. + assert_eq!(count(&ifc, "IFCMATERIALLAYERSETUSAGE"), 0); + assert!(ifc.contains("'Axis','Curve2D'")); + } + + #[test] + fn schiefe_achsrichtung_ist_fehler() { + let mut b = mini(); + b.n(&[REC_WALL_SOLIDS, -1.0]); + b.str("W"); + b.str("Wand"); + b.no_type(); + b.no_psets(); + b.n(&[1.0, 0.0, 0.0, 2.0, 0.0, 5.0, 0.0, 0.0, 0.0]); + assert!(build(&b).is_err()); + } + #[test] fn ohne_georeferenz_und_deterministisch() { let b = full_house(false); diff --git a/src/export/exportIfc.ts b/src/export/exportIfc.ts index dd1e5630..58529252 100644 --- a/src/export/exportIfc.ts +++ b/src/export/exportIfc.ts @@ -43,8 +43,12 @@ // echte Stufengeometrie ist ausgelassen (siehe stairFootprint()). // // Material-Schichten: je Wand-/Deckentyp ein IfcWallType/IfcSlabType mit -// IfcMaterialLayerSet, die Exemplare erben ihn über IfcRelDefinesByType. (Noch) KEIN -// IfcMaterialLayerSetUsage am Exemplar: die Wand hat keine Achs-Darstellung. +// IfcMaterialLayerSet, die Exemplare erben ihn über IfcRelDefinesByType. Extrusions-Wände +// ([B5], 28.10.) tragen zusätzlich eine „Axis"-Darstellung (IfcPolyline entlang der Wandachse) +// und eine IfcMaterialLayerSetUsage (AXIS2, POSITIVE, Offset = Abstand der Aussenschicht von der +// Achse), damit Revit/ArchiCAD die Schichten der Achse zuordnen: das Wand-Placement sitzt am +// Wandanfang, X = Achse, Y = linke Normale (Rust rechnet die Welt-Profile ins Wandsystem). Mesh- +// Wände (schräge Oberkante, Laibungs-Rücksprung) haben weder Achse noch Usage. // // Eigenschaften ([B5]): Pset_WallCommon/SlabCommon/RoofCommon/ColumnCommon/DoorCommon/ // WindowCommon/SpaceCommon nur mit Werten, die das Modell hergibt (Reference = Typname, @@ -187,10 +191,24 @@ class FlatIfc { for (const s of m.storeys) this.nums.push(this.str(s.id), this.str(s.name), s.base); } - wallSolids(structure: number, id: string, name: string, ty: TypeRefIn | null, psets: PsetIn[], solids: { pts: Vec2[]; zRel: number; depth: number }[]): void { + /** + * Extrusions-Wand. `frame`: Wandanfang, Achsrichtung (Einheitsvektor), Länge und — wenn die Schichten + * des Typs genau den Wandquerschnitt füllen — der Abstand `offset` der ersten Schicht von der + * Wandachse entlang der linken Normalen (→ IfcMaterialLayerSetUsage). + */ + wallSolids( + structure: number, + id: string, + name: string, + ty: TypeRefIn | null, + psets: PsetIn[], + frame: { origin: Vec2; u: Vec2; length: number; offset: number | null }, + solids: { pts: Vec2[]; zRel: number; depth: number }[], + ): void { this.nums.push(REC_WALL_SOLIDS, structure, this.str(id), this.str(name)); this.typeRef(ty); this.psets(psets); + this.nums.push(1, frame.origin.x, frame.origin.y, frame.u.x, frame.u.y, frame.length, frame.offset === null ? 0 : 1, frame.offset ?? 0); this.nums.push(solids.length); for (const s of solids) { this.pts(s.pts); @@ -583,8 +601,22 @@ export function exportIfcSpf(projectIn: Project): string { return { pts: rect, zRel: b.baseElevation - baseOf(structure), depth: b.height }; }); const id = wallIdentity(wall); - flat.wallSolids(structure, wall.id, id.name, id.ty, id.psets, solids); - hostExtent.set(wall.id, crossExtent(wall, bands)); + // Wandsystem: Placement am Wandanfang, X = Achse, Y = linke Normale; die Schichten des Typs + // stehen ab der Aussenfläche (negative Normale) nebeneinander — IfcMaterialLayerSetUsage nur, + // wenn ihre Summe dem Querschnitt der Bänder entspricht (sonst wäre der Offset gelogen). + const extent = crossExtent(wall, bands); + const layerSum = id.ty?.layers.reduce((a, l) => a + l.thickness, 0) ?? 0; + const usage = id.ty !== null && layerSum > 0 && Math.abs(extent.nHi - extent.nLo - layerSum) < 1e-3; + flat.wallSolids( + structure, + wall.id, + id.name, + id.ty, + id.psets, + { origin: wall.start, u: normalize(sub(wall.end, wall.start)), length: Math.hypot(wall.end.x - wall.start.x, wall.end.y - wall.start.y), offset: usage ? extent.nLo : null }, + solids, + ); + hostExtent.set(wall.id, extent); } // Mesh-Weg: Loch-Ausschnitte aller betroffenen Bänder in EINEM Kern-Aufruf. const meshBands = meshWalls.flatMap((m) => m.bands); diff --git a/src/export/exportIfc.validate.test.ts b/src/export/exportIfc.validate.test.ts index e02e19a8..d1470060 100644 --- a/src/export/exportIfc.validate.test.ts +++ b/src/export/exportIfc.validate.test.ts @@ -39,7 +39,7 @@ for w in m.by_type("IfcWall"): sh = ifcopenshell.geom.create_shape(s, w) out[w.GlobalId] = {"volume": us.get_volume(sh.geometry), "openings": len(w.HasOpenings), "fills": sum(len(r.RelatedOpeningElement.HasFillings) for r in w.HasOpenings), - "rep": w.Representation.Representations[0].RepresentationType} + "rep": [r for r in w.Representation.Representations if r.RepresentationIdentifier == "Body"][0].RepresentationType} print(json.dumps(out)) `; @@ -52,6 +52,48 @@ function wallVolumes(name: string, ifc: string): Record { return JSON.parse(r.stdout); } +// Achse und IfcMaterialLayerSetUsage je IfcWall: Placement, Achs-Polylinie (lokal), Usage und je +// Körper (Extrusion) der Bereich quer zur Achse (lokal Y) — alles unabhängig vom Exporter gelesen. +const WALL_AXES = ` +import json, sys +import ifcopenshell, ifcopenshell.util.placement as up +m = ifcopenshell.open(sys.argv[1]) +out = {} +for w in m.by_type("IfcWall"): + reps = {r.RepresentationIdentifier: r for r in w.Representation.Representations} + mat = up.get_local_placement(w.ObjectPlacement) + item = {"identifiers": sorted(reps), "usage": None, "axis": None, "items": []} + if "Axis" in reps: + pts = [p.Coordinates for p in reps["Axis"].Items[0].Points] + a = mat @ [pts[0][0], pts[0][1], 0, 1] + b = mat @ [pts[1][0], pts[1][1], 0, 1] + item["axis"] = [[a[0], a[1]], [b[0], b[1]], reps["Axis"].RepresentationType, [list(p) for p in pts]] + for e in reps["Body"].Items: + if e.is_a("IfcExtrudedAreaSolid"): + ys = [p.Coordinates[1] for p in e.SweptArea.OuterCurve.Points] + item["items"].append([min(ys), max(ys)]) + for rel in w.HasAssociations: + if rel.is_a("IfcRelAssociatesMaterial") and rel.RelatingMaterial.is_a("IfcMaterialLayerSetUsage"): + u = rel.RelatingMaterial + item["usage"] = {"dir": u.LayerSetDirection, "sense": u.DirectionSense, "offset": u.OffsetFromReferenceLine, + "layers": [l.LayerThickness for l in u.ForLayerSet.MaterialLayers]} + out[w.GlobalId] = item +print(json.dumps(out)) +`; + +interface WallAxis { + identifiers: string[]; + usage: { dir: string; sense: string; offset: number; layers: number[] } | null; + axis: [number[], number[], string, number[][]] | null; + items: number[][]; +} + +function wallAxes(name: string, ifc: string): Record { + const r = spawnSync("python3", ["-c", WALL_AXES, 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 { @@ -134,4 +176,65 @@ describe.skipIf(!hasIfcOpenShell)("IFC-Export gegen ifcopenshell", { timeout: 60 } expect(swept).toBeGreaterThan(0); }); + + it("[B5] Wandachse + LayerSetUsage: Achse = Wandachse, Schichten ab Aussenfläche in Normalenrichtung", () => { + // Zwei Schichten (0.1 aussen, 0.3 innen), Wand schräg gestellt und rückwärts gezeichnet. + const [c0, c1] = sampleProject.components; + const base = singleWall(false); + const rotated: Project = { + ...base, + walls: [{ ...base.walls[0], start: { x: 12, y: 7 }, end: { x: 9, y: 3 } }], + wallTypes: [...base.wallTypes.filter((t) => t.id !== "solo"), { id: "solo", name: "Zweischicht", layers: [{ componentId: c0.id, thickness: 0.1 }, { componentId: c1.id, thickness: 0.3 }] }], + openings: [], + }; + const ifc = exportIfcSpf(rotated); + expect(validate("achse", ifc).out).toContain("0 Befunde"); + const [w] = Object.values(wallAxes("achse", ifc)); + expect(w.identifiers).toEqual(["Axis", "Body"]); + expect(w.axis![2]).toBe("Curve2D"); + expect(w.axis![0][0]).toBeCloseTo(12, 6); + expect(w.axis![0][1]).toBeCloseTo(7, 6); + expect(w.axis![1][0]).toBeCloseTo(9, 6); + expect(w.axis![1][1]).toBeCloseTo(3, 6); + expect(w.axis![3][1]).toEqual([5, 0]); // Länge √(9+16) = 5 entlang lokal X + expect(w.usage).toMatchObject({ dir: "AXIS2", sense: "POSITIVE", layers: [0.1, 0.3] }); + // Referenzlinie in der Mitte (Standard) → Offset −total/2; Körper je Schicht in Reihenfolge. + const off = w.usage!.offset; + let y = off; + expect(w.items.length).toBe(2); + w.items.forEach(([lo, hi], i) => { + expect(lo).toBeCloseTo(y, 6); + y += w.usage!.layers[i]; + expect(hi).toBeCloseTo(y, 6); + }); + }); + it("[B5] Demo-Haus: jede Extrusions-Wand hat Achse und Usage, Körper-Bänder = Schichten in Reihenfolge", () => { + const project = sampleProject; + const axes = wallAxes("demo-achsen", exportIfcSpf(project)); + let withAxis = 0; + for (const wall of project.walls) { + const w = axes[ifcGuid(`${project.id}/wall/${wall.id}`)]; + expect(w, wall.id).toBeDefined(); + if (!w.axis) { + expect(w.usage, wall.id).toBeNull(); // Mesh-Wand + continue; + } + withAxis++; + expect(w.axis[0][0], wall.id).toBeCloseTo(wall.start.x, 6); + expect(w.axis[0][1], wall.id).toBeCloseTo(wall.start.y, 6); + expect(w.axis[1][0], wall.id).toBeCloseTo(wall.end.x, 6); + expect(w.axis[1][1], wall.id).toBeCloseTo(wall.end.y, 6); + if (!w.usage) continue; // Schichtsumme passt nicht zum Querschnitt + // Mehrere Bänder je Schicht möglich (Joins): die verschiedenen Querbereiche ergeben die Schichten. + const spans = [...new Map(w.items.map(([lo, hi]) => [`${lo.toFixed(6)}/${hi.toFixed(6)}`, [lo, hi]])).values()].sort((a, b) => a[0] - b[0]); + expect(spans.length, wall.id).toBe(w.usage.layers.length); + let y = w.usage.offset; + spans.forEach(([lo, hi], i) => { + expect(lo, `${wall.id} Schicht ${i}`).toBeCloseTo(y, 6); + y += w.usage!.layers[i]; + expect(hi, `${wall.id} Schicht ${i}`).toBeCloseTo(y, 6); + }); + } + expect(withAxis).toBeGreaterThan(0); + }); }); diff --git a/src/io/ifcImport.test.ts b/src/io/ifcImport.test.ts index 0e8a635b..81d9c501 100644 --- a/src/io/ifcImport.test.ts +++ b/src/io/ifcImport.test.ts @@ -90,7 +90,7 @@ describe("IFC-Import: Rundreise mit dem eigenen Export", () => { expect(p, wall.id).toBeDefined(); const wallLine = [...lines.values()].find((l) => l.includes(`=IFCWALL('${p.globalId}'`))!; const shape = lines.get(/,(#\d+),\$,\$\);$/.exec(wallLine)![1])!; - const rep = lines.get(/\(\(?(#\d+)\)\);$/.exec(shape)![1])!; + const rep = lines.get(/(#\d+)\)\);$/.exec(shape)![1])!; // letzte Darstellung = Body (davor ggf. Axis) const isSwept = rep.includes("'SweptSolid'"); if (isSwept) swept++; const expected = cut.get(wall.id)!;