diff --git a/TODO.md b/TODO.md index c5efcda0..369dbd06 100644 --- a/TODO.md +++ b/TODO.md @@ -3461,6 +3461,31 @@ Ganzes nicht WASM-tauglich (rayon, tempfile, SystemTime) — nur einzelne Module SIA-416-Kategorie des Raums, wenn er keine eigene `CH_Raum`-Eigenschaft hat: `CH_Zone.SIA416`, sonst der Zonenname (HNF, NNF, VF, FF, KGF/KF, AGF; kein Raten bei anderen Namen). Rundreise Export → Import geprüft. Offen: Klassifikation als Feld am Bauteil, IfcGrid (Modell ohne Raster). + (6.11., ArchiCAD-Exporte) Testdaten (nur lokal, nicht im Repo): KIT-Beispiele aus ArchiCAD 20, IFC4 („for unrestricted + use", Quelle IAI/KIT nennen: AC20-FZK-Haus, AC20-Institute-Var-2, AC-20-Smiley-West-10-Bldg) und Schependomlaan + (ArchiCAD 18, IFC2x3, TU Eindhoven, Datenfreigabe nur für Forschung/Lehre). Frei lizenzierte Vectorworks-Exporte + nicht gefunden. Neu in Rust (`fileio/src/ifc_shapes.rs`, `ifc_semantic.rs`): Dach aus IfcRoof (Platten) bzw. + IfcSlab ROOF (je Geschoss nach Berührung gruppiert) → Dossier-Dach Flach/Pult/Sattel/Walm (achsparalleles Rechteck, + gleiche Neigung, jede Dachflächen-Ecke ±3 cm auf der Dossier-Fläche, Dicke senkrecht, Traufhöhe, Dachtyp nur mit + Material); Giebel-/Pultwände = Wand bis zum höchsten Punkt, wenn ein erkanntes Dach die Krone genau so kappt wie + Dossier (Volumenvergleich, Dachanschluss automatisch); gerade Treppe (IfcStair ohne Geländer/IfcStairFlight: + Trittflächen gleichmässig, Belag über Rohbau zusammengefasst) → Antritt, Richtung, Laufbreite, Steigung, Auftritt; + Bogenwand (Ringausschnitt ohne Öffnungen) → `bulge`; runde Öffnung → `shape: "rund"`; Türen/Fenster ohne + IfcRelFillsElement → Wirt über die Lage (Loch schon im Wandkörper: fehlendes Volumen = Kästen der Füllungen); + IfcSpace nur mit „FootPrint"/„Box" (ArchiCAD 2x3) → Raum; Dreiecksnetze mit T-Stössen (Kanten an Punkten geteilt); + IfcMapConversion (Bericht `mapConversion`) → Rückschub auf den LV95-Projektnullpunkt (ungedreht, Massstab 1). + Kern (`import_ifc.rs`): Dächer, Treppen, `bulge`, `shape`, Tür-/Fenstertyp nach Typnamen der Datei (gleichnamig + wiederverwendet, sonst Kopie des passenden; „Tür …"/„Fenster …" des eigenen Exports zählen nicht), Gründe je Klasse + (`keptReasons`). Dialog: Bericht nach dem Import (`IfcImportReportDialog`: erkannt je Bauteilart, als Mesh geblieben + mit Grund, `ifc.reason.*`). Quote (Bauteile vorher → nachher): FZK-Haus Wände 9 → 13/13, Öffnungen 14 → 16/16, + Dach 0 → 1 (2 Platten), Räume 5/7 (Dachraum kein Prisma), Wendeltreppe Mesh; Institute Wände 111/121 (8 unter dem + Tonnendach, 2 nicht rechteckig), Dächer 6, 15 Tonnendach-Platten Mesh, Podesttreppen 4 Mesh; Smiley West Wände + 270/281 (11 Ständerwände), Dächer 11 (10 Pult + 1 Flach), 30 Podesttreppen Mesh; Schependomlaan Wände 770 → 795, + Öffnungen 60 → 93, Räume 6 → 100, Dächer 19, Treppen 6/9. Rundreise Demo-Haus jetzt auch Dach und Treppe als + Bauteile. Bilder (lokal): FZK-Haus Grundriss EG/DG und Schnitt, vorher Meshes/nachher Bauteile. Offen: Pultdach + fallend nach +x/+y (Dossier-Pult steigt nur dorthin), gedrehte/nicht rechteckige Dächer, Tonnen-/Mansarddächer, + Podest-, L- und Wendeltreppen, Bogenwände mit Öffnungen, Ständerwände (Rahmen + Beplankung), gedrehte Georeferenz, + Träger/Geländer; nur Linux-Container (CLI-SVG + Chromium), nicht in der Tauri-App, 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/core/src/import_ifc.rs b/src-tauri/core/src/import_ifc.rs index b9dd2d7e..cbe78509 100644 --- a/src-tauri/core/src/import_ifc.rs +++ b/src-tauri/core/src/import_ifc.rs @@ -22,6 +22,8 @@ const OPENING_CATEGORY: &str = "21"; const CEILING_CATEGORY: &str = "30"; const COLUMN_CATEGORY: &str = "50"; const ROOM_CATEGORY: &str = "60"; +const ROOF_CATEGORY: &str = "35"; +const STAIR_CATEGORY: &str = "40"; const ROOM_COLOR: &str = "#6b7280"; const SIA: [&str; 6] = ["HNF", "NNF", "VF", "FF", "KGF", "AGF"]; const LEVEL_TOL: f64 = 0.005; @@ -69,6 +71,8 @@ struct WallData { z0: f64, z1: f64, thickness: f64, + /// Bogenwand ([T2]), 0 = gerade. + bulge: f64, } struct OpeningData { @@ -82,6 +86,8 @@ struct OpeningData { operation: Option, swing: f64, hinge: f64, + /// Umriss in der Wandebene (`Opening.shape`), z. B. "rund". + shape: Option, } struct SlabData { @@ -112,6 +118,27 @@ struct SpaceData { z0: f64, } +struct RoofData { + info: Info, + outline: Vec<[f64; 2]>, + shape: String, + ridge_axis: String, + pitch_deg: f64, + eave_z: f64, + thickness: f64, +} + +struct StairData { + info: Info, + start: [f64; 2], + dir: [f64; 2], + run_length: f64, + width: f64, + step_count: f64, + z0: f64, + total_rise: f64, +} + struct Storey { name: String, elevation: f64, @@ -125,7 +152,11 @@ struct Elements { slabs: Vec, columns: Vec, spaces: Vec, + roofs: Vec, + stairs: Vec, kept: Map, + /// Je Klasse die Gründe, weshalb Kandidaten Mesh blieben (`{"IfcWall": {"slopedTop": 3}}`). + kept_reasons: Map, } fn s_of(v: Option<&Value>) -> Option { @@ -189,6 +220,7 @@ fn decode_elements(meta: &Value, data: &[f64]) -> Elements { }) .unwrap_or_default(); out.kept = raw.get("kept").and_then(Value::as_object).cloned().unwrap_or_default(); + out.kept_reasons = raw.get("keptReasons").and_then(Value::as_object).cloned().unwrap_or_default(); let mut wall_index: HashMap = HashMap::new(); let mut rust_wall: i64 = 0; for e in raw.get("elements").and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]) { @@ -206,9 +238,10 @@ fn decode_elements(meta: &Value, data: &[f64]) -> Elements { let info = info_of(e); match kind { "wall" => { - if v.len() == 7 { + if v.len() == 7 || v.len() == 8 { wall_index.insert(rust_wall, out.walls.len()); - out.walls.push(WallData { info, start: [v[0], v[1]], end: [v[2], v[3]], z0: v[4], z1: v[5], thickness: v[6] }); + let bulge = v.get(7).copied().filter(|b| b.abs() <= 1e6).unwrap_or(0.0); + out.walls.push(WallData { info, start: [v[0], v[1]], end: [v[2], v[3]], z0: v[4], z1: v[5], thickness: v[6], bulge }); } rust_wall += 1; } @@ -227,6 +260,7 @@ fn decode_elements(meta: &Value, data: &[f64]) -> Elements { operation: s_of(e.get("operation")), swing: v[4].signum() * (v[4] != 0.0) as u8 as f64, hinge: v[5].signum() * (v[5] != 0.0) as u8 as f64, + shape: s_of(e.get("shape")), }); } } @@ -243,6 +277,29 @@ fn decode_elements(meta: &Value, data: &[f64]) -> Elements { out.columns.push(ColumnData { info, center: [v[0], v[1]], rotation: v[2], z0: v[3], z1: v[4], round, a: v[5], b: v[6] }); } } + "roof" => { + if let Some(mut r) = rings(v, 3, 1.0) { + let shape = s_of(e.get("shape")).filter(|x| ["flach", "pult", "sattel", "walm"].contains(&x.as_str())); + let axis = s_of(e.get("ridgeAxis")).filter(|x| x == "x" || x == "y"); + if let (Some(shape), Some(ridge_axis)) = (shape, axis) { + out.roofs.push(RoofData { info, outline: r.remove(0), shape, ridge_axis, eave_z: v[0], pitch_deg: v[1], thickness: v[2] }); + } + } + } + "stair" => { + if v.len() == 9 && v[6] >= 2.0 && v[6] <= 200.0 && v[4] > 0.0 && v[5] > 0.0 { + out.stairs.push(StairData { + info, + start: [v[0], v[1]], + dir: [v[2], v[3]], + run_length: v[4], + width: v[5], + step_count: v[6].round(), + z0: v[7], + total_rise: v[8], + }); + } + } "space" => { if let Some(mut r) = rings(v, 2, 1.0) { out.spaces.push(SpaceData { @@ -424,18 +481,41 @@ fn type_for(ctx: &mut Ctx, types: &mut Vec<(Value, bool)>, e: &Info, t: f64, kin id } +/// Allgemeiner Name eines Tür-/Fensterstils (eigener Export: "Tür", "Fenster SINGLE_PANEL" …). +fn generic_fill_name(n: &str) -> bool { + let rest = n.strip_prefix("Tür").or_else(|| n.strip_prefix("Fenster")).or_else(|| n.strip_prefix("Door")).or_else(|| n.strip_prefix("Window")); + rest.is_some_and(|r| r.is_empty() || (r.starts_with(' ') && r.trim().chars().all(|c| c.is_ascii_uppercase() || c == '_'))) +} + +/// Tür-/Fenstertyp nach Namen: vorhanden (ohne Gross-/Kleinschreibung) oder neu als Kopie von `template`. +fn typed_by_name(ctx: &mut Ctx, types: &mut Vec<(Value, bool)>, name: Option<&str>, template: Option<&Value>, kind: &str, counter: &str) -> Option { + let Some(name) = name else { return template.and_then(|t| t.get("id")).and_then(Value::as_str).map(str::to_string) }; + let key = name.to_lowercase(); + if let Some((t, _)) = types.iter().find(|(t, _)| t.get("name").and_then(Value::as_str).is_some_and(|n| n.trim().to_lowercase() == key)) { + return Some(id_of(t).to_string()); + } + let mut t = template?.clone(); + let id = ctx.new_id(kind); + t["id"] = id.clone().into(); + t["name"] = name.into(); + types.push((t, true)); + ctx.bump(counter); + Some(id) +} + fn list_of(root: &Map, key: &str) -> Vec<(Value, bool)> { root.get(key).and_then(Value::as_array).map(|a| a.iter().map(|v| (v.clone(), false)).collect()).unwrap_or_default() } /// Bauteile + übrige Kontext-Meshes ins Projekt `root` (vorher `ifcElementsToProject`). -fn elements_ops(root: &Map, products: &[IfcProduct], el: &Elements, opts: &IfcOptions, now: f64) -> (Vec, Value, usize) { +fn elements_ops(root: &Map, meta: &Value, products: &[IfcProduct], el: &Elements, opts: &IfcOptions, now: f64) -> (Vec, Value, usize) { let kept: f64 = el.kept.values().map(|v| v.as_f64().unwrap_or(f64::NAN)).sum(); let mut summary = Map::new(); - for k in ["walls", "openings", "ceilings", "columns", "rooms", "floors", "wallTypes", "ceilingTypes", "components", "meshes", "classified"] { + for k in ["walls", "openings", "ceilings", "columns", "rooms", "roofs", "stairs", "floors", "wallTypes", "ceilingTypes", "roofTypes", "doorTypes", "windowTypes", "components", "meshes", "classified"] { summary.insert(k.into(), 0.into()); } summary.insert("kept".into(), js_num(kept)); + summary.insert("keptReasons".into(), Value::Object(el.kept_reasons.clone())); let hatches = root.get("hatches").and_then(Value::as_array).cloned().unwrap_or_default(); let hatch_id = hatches.iter().find(|h| id_of(h) == "none").or(hatches.first()).and_then(|h| h.get("id").and_then(Value::as_str)).unwrap_or("none").to_string(); let mut ctx = Ctx { stamp: stamp36(now), summary, levels: list_of(root, "drawingLevels"), components: list_of(root, "components"), hatch_id, root }; @@ -454,7 +534,13 @@ fn elements_ops(root: &Map, products: &[IfcProduct], el: &Element for s in &el.spaces { s.boundary.iter().for_each(|p| extra.extend(p)); } - let [dx, dy] = geo_shift(products, project_geo_origin(root), &extra); + for r in &el.roofs { + r.outline.iter().for_each(|p| extra.extend(p)); + } + for s in &el.stairs { + extra.extend(s.start); + } + let [dx, dy] = map_shift(meta, root).unwrap_or_else(|| geo_shift(products, project_geo_origin(root), &extra)); let mv = |p: [f64; 2]| pt([round(p[0] + dx, 1e-9), round(p[1] + dy, 1e-9)]); // ── Geschosse ── @@ -528,6 +614,9 @@ fn elements_ops(root: &Map, products: &[IfcProduct], el: &Element let id = ctx.new_id("wall"); let wt = type_for(&mut ctx, &mut wall_types, &w.info, w.thickness, "walltype", "wallTypes"); let mut o = json!({"id": id, "type": "wall", "floorId": fid, "categoryCode": WALL_CATEGORY, "start": mv(w.start), "end": mv(w.end), "wallTypeId": wt, "height": js_num(height)}); + if w.bulge.abs() > 1e-9 { + o["bulge"] = js_num(round(w.bulge, 1e-9)); + } if bottom.abs() > LEVEL_TOL { o["bottom"] = json!({"mode": "floor", "floorId": fid, "offset": js_num(bottom)}); } @@ -539,8 +628,8 @@ fn elements_ops(root: &Map, products: &[IfcProduct], el: &Element } walls.push(o); } - let door_types = root.get("doorTypes").and_then(Value::as_array).cloned().unwrap_or_default(); - let window_types = root.get("windowTypes").and_then(Value::as_array).cloned().unwrap_or_default(); + let mut door_types: Vec<(Value, bool)> = list_of(root, "doorTypes"); + let mut window_types: Vec<(Value, bool)> = list_of(root, "windowTypes"); let mut openings: Vec = Vec::new(); for o in &el.openings { let Some(host) = walls.get(o.host) else { continue }; @@ -550,24 +639,36 @@ fn elements_ops(root: &Map, products: &[IfcProduct], el: &Element let leaves = if op.starts_with("DOUBLE_DOOR") { 2.0 } else { 1.0 }; let door_type = (!op.is_empty()) .then(|| { - door_types.iter().find(|t| { + door_types.iter().map(|x| &x.0).find(|t| { t.get("kind").and_then(Value::as_str) == Some(if sliding { "schiebe" } else { "dreh" }) && t.get("leafCount").and_then(Value::as_f64) == Some(leaves) }) }) .flatten() - .or(door_types.first()); + .or(door_types.first().map(|x| &x.0)) + .cloned(); let wings: Option = match op { "SINGLE_PANEL" => Some(1.0), "DOUBLE_PANEL_VERTICAL" => Some(2.0), "TRIPLE_PANEL_VERTICAL" => Some(3.0), _ => None, }; - let window_type = wings.and_then(|w| window_types.iter().find(|t| t.get("wingCount").and_then(Value::as_f64) == Some(w))).or(window_types.first()); - let type_id = match o.kind.as_str() { - "door" => door_type.and_then(|t| t.get("id")).and_then(Value::as_str), - "window" => window_type.and_then(|t| t.get("id")).and_then(Value::as_str), + let window_type = wings + .and_then(|w| window_types.iter().map(|x| &x.0).find(|t| t.get("wingCount").and_then(Value::as_f64) == Some(w))) + .or(window_types.first().map(|x| &x.0)) + .cloned(); + // Typ aus der Datei (IfcDoorType/IfcWindowType, IFC2x3 Style): gleichnamiger Dossier-Typ, sonst ein + // neuer nach dem Vorbild des passenden ([B4]). Allgemeine Namen ("Tür", "Fenster SINGLE_PANEL" aus + // dem eigenen Export) zählen nicht. + let named = o.info.type_name.as_deref().map(str::trim).filter(|n| !n.is_empty() && !generic_fill_name(n)).map(str::to_string); + let type_id: Option = match o.kind.as_str() { + "door" => typed_by_name(&mut ctx, &mut door_types, named.as_deref(), door_type.as_ref(), "doortype", "doorTypes"), + "window" => typed_by_name(&mut ctx, &mut window_types, named.as_deref(), window_type.as_ref(), "windowtype", "windowTypes"), _ => None, }; + let window_type = match (&type_id, o.kind.as_str()) { + (Some(id), "window") => window_types.iter().map(|x| &x.0).find(|t| id_of(t) == id).cloned(), + _ => window_type, + }; let mut v = Map::new(); v.insert("id".into(), ctx.new_id("opening").into()); v.insert("type".into(), "opening".into()); @@ -581,6 +682,9 @@ fn elements_ops(root: &Map, products: &[IfcProduct], el: &Element if o.kind == "hole" { v.insert("doorType".into(), "wandoeffnung".into()); } + if let Some(sh) = o.shape.as_deref().filter(|x| ["rund", "rundbogen", "segmentbogen", "spitzbogen", "schraeg", "giebel"].contains(x)) { + v.insert("shape".into(), sh.into()); + } if let Some(t) = type_id.filter(|t| !t.is_empty()) { v.insert("typeId".into(), t.into()); } @@ -593,7 +697,7 @@ fn elements_ops(root: &Map, products: &[IfcProduct], el: &Element } } if let (true, Some(w)) = (o.kind == "window", wings) { - if window_type.and_then(|t| t.get("wingCount")).and_then(Value::as_f64).unwrap_or(1.0) != w { + if window_type.as_ref().and_then(|t| t.get("wingCount")).and_then(Value::as_f64).unwrap_or(1.0) != w { v.insert("wingCount".into(), js_num(w)); } } @@ -698,6 +802,33 @@ fn elements_ops(root: &Map, products: &[IfcProduct], el: &Element })); } + let mut roof_types = list_of(root, "roofTypes"); + let mut roofs: Vec = Vec::new(); + for r in &el.roofs { + let (fid, _, _) = floor_of(&mut ctx, r.info.storey, r.eave_z); + let mut v = json!({ + "id": ctx.new_id("roof"), "type": "roof", "floorId": fid, "categoryCode": ROOF_CATEGORY, + "outline": r.outline.iter().map(|&p| mv(p)).collect::>(), + "shape": r.shape, "pitchDeg": js_num(round(r.pitch_deg, 1e-6)), "overhang": 0, "ridgeAxis": r.ridge_axis, + "baseElevation": js_num(round(r.eave_z, 1e-6)), "thickness": js_num(round(r.thickness, 1e-6)), + }); + // Dachtyp nur mit Material aus der Datei; sonst einschichtig über `thickness`. + if r.info.layers.iter().any(|l| !l.material.trim().is_empty()) { + v["roofTypeId"] = type_for(&mut ctx, &mut roof_types, &r.info, r.thickness, "rooftype", "roofTypes").into(); + } + roofs.push(v); + } + let mut stairs: Vec = Vec::new(); + for s in &el.stairs { + let (fid, _, _) = floor_of(&mut ctx, s.info.storey, s.z0); + stairs.push(json!({ + "id": ctx.new_id("stair"), "type": "stair", "floorId": fid, "categoryCode": STAIR_CATEGORY, "shape": "straight", + "start": mv(s.start), "dir": {"x": js_num(round(s.dir[0], 1e-9)), "y": js_num(round(s.dir[1], 1e-9))}, + "runLength": js_num(round(s.run_length, 1e-6)), "width": js_num(round(s.width, 1e-6)), + "totalRise": js_num(round(s.total_rise, 1e-6)), "stepCount": js_num(s.step_count), "up": true, + })); + } + // ── Übrige Bauteile als Kontext-Mesh ── let meshes = ifc_meshes(products, &opts.file_name, opts.group.as_deref().unwrap_or("auto"), [dx, dy], now); let n_meshes = meshes.len(); @@ -706,8 +837,10 @@ fn elements_ops(root: &Map, products: &[IfcProduct], el: &Element + el.slabs.iter().filter(|s| s.info.classified).count() + el.columns.iter().filter(|c| c.info.classified).count() + el.spaces.iter().filter(|s| s.info.classified).count() + + el.roofs.iter().filter(|r| r.info.classified).count() + + el.stairs.iter().filter(|s| s.info.classified).count() + products.iter().filter(|p| !p.classifications.is_empty()).count(); - for (k, n) in [("walls", walls.len()), ("openings", openings.len()), ("ceilings", ceilings.len()), ("columns", columns.len()), ("rooms", rooms.len()), ("meshes", n_meshes), ("classified", classified)] { + for (k, n) in [("walls", walls.len()), ("openings", openings.len()), ("ceilings", ceilings.len()), ("columns", columns.len()), ("rooms", rooms.len()), ("roofs", roofs.len()), ("stairs", stairs.len()), ("meshes", n_meshes), ("classified", classified)] { ctx.summary.insert(k.into(), n.into()); } @@ -718,10 +851,15 @@ fn elements_ops(root: &Map, products: &[IfcProduct], el: &Element if !ceiling_types.is_empty() || root.get("ceilingTypes").is_some_and(|v| crate::json_util::truthy(Some(v))) { ops.extend(grown_list_ops("ceilingTypes", root.get("ceilingTypes"), ceiling_types)); } + for (key, list) in [("roofTypes", roof_types), ("doorTypes", door_types), ("windowTypes", window_types)] { + if list.iter().any(|x| x.1) { + ops.extend(grown_list_ops(key, root.get(key), list)); + } + } if !walls.is_empty() { ops.push(Op::Add { collection: "walls".into(), items: walls, at: None }); } - for (key, items) in [("openings", openings), ("ceilings", ceilings), ("columns", columns), ("rooms", rooms)] { + for (key, items) in [("openings", openings), ("ceilings", ceilings), ("columns", columns), ("rooms", rooms), ("roofs", roofs), ("stairs", stairs)] { if root.get(key).is_some_and(|v| crate::json_util::truthy(Some(v))) { if !items.is_empty() { ops.push(Op::Add { collection: key.into(), items, at: None }); @@ -737,6 +875,23 @@ fn elements_ops(root: &Map, products: &[IfcProduct], el: &Element (ops, Value::Object(ctx.summary), n_meshes) } +/// Rückschub über die Georeferenz der Datei (IfcMapConversion, [B4]): die Datei liegt lokal, die Karte +/// = lokal + (Ost, Nord). Hat das Projekt einen LV95-Bezug, landet das Modell an seinem Kartenort +/// relativ zum Projekt-Nullpunkt. Nur ungedreht und Massstab 1 und nur bei LV95 (EPSG:2056) oder ohne +/// Angabe des Systems; sonst `None` (dann wie bisher über die Lage der Punkte). +fn map_shift(meta: &Value, root: &Map) -> Option<[f64; 2]> { + let m = meta.get("mapConversion")?; + let num = |k: &str| m.get(k).and_then(Value::as_f64); + let (e, n) = (num("eastings")?, num("northings")?); + let axis = m.get("xAxis").and_then(Value::as_array)?; + let ax = [axis.first()?.as_f64()?, axis.get(1)?.as_f64()?]; + let crs = m.get("crs").and_then(Value::as_str).unwrap_or(""); + let lv95 = crs.is_empty() || crs.contains("2056") || crs.to_uppercase().contains("LV95"); + let plain = (ax[0] - 1.0).abs() < 1e-9 && ax[1].abs() < 1e-9 && (num("scale").unwrap_or(1.0) - 1.0).abs() < 1e-9; + let o = project_geo_origin(root)?; + (lv95 && plain && o[0].is_finite() && o[1].is_finite() && e.is_finite() && n.is_finite()).then(|| [e - o[0], n - o[1]]) +} + /// IFC ins Projekt `root`: als Kontext-Meshes oder (mit `opts.elements`) als Bauteile. pub fn ifc_import(root: &Map, meta_json: &str, positions: &[f64], indices: &[f64], element_data: &[f64], opts: &IfcOptions, now: f64) -> Result { let meta: Value = serde_json::from_str(meta_json).map_err(|e| format!("IFC-Bericht: {e}"))?; @@ -745,7 +900,7 @@ pub fn ifc_import(root: &Map, meta_json: &str, positions: &[f64], if opts.elements { let el = decode_elements(&meta, element_data); let kept = el.kept.clone(); - let (ops, summary, n) = elements_ops(root, &products, &el, opts, now); + let (ops, summary, n) = elements_ops(root, &meta, &products, &el, opts, now); // Statt der Roh-Bauteile die Zusammenfassung (an derselben Stelle des Berichts). let mut report = report; if let Some(r) = report.as_object_mut() { @@ -753,8 +908,132 @@ pub fn ifc_import(root: &Map, meta_json: &str, positions: &[f64], } return Ok(IfcResult { ops, summary: Some(summary), report, kept, context_objects: n }); } - let shift = geo_shift(&products, project_geo_origin(root), &[]); + let shift = map_shift(&meta, root).unwrap_or_else(|| geo_shift(&products, project_geo_origin(root), &[])); let meshes = ifc_meshes(&products, &opts.file_name, opts.group.as_deref().unwrap_or("auto"), shift, now); let n = meshes.len(); Ok(IfcResult { ops: context_ops(root, meshes), summary: None, report, kept: Map::new(), context_objects: n }) } + +#[cfg(test)] +mod tests { + use super::*; + + fn added<'a>(ops: &'a [Op], key: &str) -> Vec<&'a Value> { + let mut out = Vec::new(); + for op in ops { + match op { + Op::Add { collection, items, .. } if collection == key => out.extend(items.iter()), + Op::SetField { key: k, value: Some(Value::Array(a)), .. } if k == key => out.extend(a.iter()), + _ => {} + } + } + out + } + + fn at(v: &Value, x: f64, y: f64) -> bool { + (v["x"].as_f64().unwrap_or(f64::NAN) - x).abs() < 1e-9 && (v["y"].as_f64().unwrap_or(f64::NAN) - y).abs() < 1e-9 + } + + /// Erkannte Bauteile wie aus `fileio` (`ifc_semantic::encode`): Bogenwand mit runder Öffnung, + /// Satteldach, gerade Treppe, Tür mit eigenem Typnamen; Georeferenz LV95. + fn meta(door_type: &str) -> (Value, Vec) { + let data = vec![ + // Wand: sx, sy, ex, ey, z0, z1, t, bulge + 5.0, 0.0, 0.0, 5.0, 0.0, 2.5, 0.3, -0.41421356237, + // Öffnung: position, width, sill, height, swing, hinge + 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, + // Gerade Wand für die Tür + 0.0, -2.0, 4.0, -2.0, 0.0, 2.5, 0.2, 0.0, + 1.0, 0.9, 0.0, 2.1, 0.0, 0.0, + // Dach: eaveZ, pitch, t, n, Ring + 3.0, 45.0, 0.2, 4.0, 0.0, 0.0, 10.0, 0.0, 10.0, 8.0, 0.0, 8.0, + // Treppe: sx, sy, dx, dy, lauf, breite, stufen, z0, steighöhe + 1.0, 2.55, 1.0, 0.0, 1.68, 1.1, 6.0, 0.0, 1.05, + ]; + let info = |kind: &str, at: usize, n: usize| json!({"kind": kind, "at": at, "n": n, "storey": 0, "layers": [], "classifications": [], "common": {}}); + let mut op1 = info("opening", 8, 6); + op1["host"] = 0.into(); + op1["openingKind"] = "hole".into(); + op1["shape"] = "rund".into(); + let mut op2 = info("opening", 22, 6); + op2["host"] = 1.into(); + op2["openingKind"] = "door".into(); + op2["typeName"] = door_type.into(); + let mut roof = info("roof", 28, 12); + roof["shape"] = "sattel".into(); + roof["ridgeAxis"] = "x".into(); + let meta = json!({ + "schema": "IFC4", "lengthScale": 1, "products": [], "skippedItems": {}, "skippedProducts": {}, + "productsWithoutGeometry": 0, "simplifiedBooleans": 0, "voidsApplied": 0, "voidsIgnored": 0, "parseErrors": 0, "truncated": false, + "mapConversion": {"eastings": 2600100.0, "northings": 1200050.0, "height": 0.0, "xAxis": [1.0, 0.0], "scale": 1.0, "crs": "EPSG:2056"}, + "elements": { + "storeys": [{"globalId": "s", "name": "EG", "elevation": 0.0}], + "elements": [info("wall", 0, 8), op1, info("wall", 14, 8), op2, roof, info("stair", 40, 9)], + "kept": {"IfcStair": 1}, + "keptReasons": {"IfcStair": {"stairForm": 1}}, + }, + }); + (meta, data) + } + + fn root() -> Map { + json!({ + "drawingLevels": [], "components": [], "wallTypes": [], "hatches": [{"id": "none"}], + "doorTypes": [{"id": "dt1", "name": "Drehtür", "kind": "dreh", "leafCount": 1, "leafStyle": "glatt", "frameThickness": 0.05}], + "windowTypes": [{"id": "wt1", "name": "Fenster", "kind": "dreh", "wingCount": 1}], + "geoAnchor": {"lv95": {"e": 2600000.0, "n": 1200000.0}, "model": {"x": 0.0, "y": 0.0}}, + }) + .as_object() + .cloned() + .unwrap() + } + + #[test] + fn roof_stair_arc_wall_round_opening_type_by_name_and_map_shift() { + let (m, data) = meta("Haustür Eiche"); + let opts = IfcOptions { file_name: "a.ifc".into(), group: None, elements: true }; + let r = ifc_import(&root(), &m.to_string(), &[], &[], &data, &opts, 0.0).unwrap(); + let walls = added(&r.ops, "walls"); + assert_eq!(walls.len(), 2); + // Verschiebung aus der Georeferenz: Karte − Projekt-Nullpunkt = (100, 50). + assert!(at(&walls[0]["start"], 105.0, 50.0), "{}", walls[0]); + assert!((walls[0]["bulge"].as_f64().unwrap() + 0.41421356237).abs() < 1e-9); + assert!(walls[1].get("bulge").is_none()); + let openings = added(&r.ops, "openings"); + assert_eq!(openings[0]["shape"], "rund"); + // Neuer Türtyp mit dem Namen aus der Datei, nach dem Vorbild des vorhandenen. + let doors = added(&r.ops, "doorTypes"); + assert_eq!(doors.len(), 1, "{:?}", r.ops); + assert_eq!((doors[0]["name"].as_str(), doors[0]["kind"].as_str()), (Some("Haustür Eiche"), Some("dreh"))); + assert_eq!(openings[1]["typeId"], doors[0]["id"]); + let roofs = added(&r.ops, "roofs"); + assert_eq!(roofs.len(), 1); + assert_eq!( + (roofs[0]["shape"].as_str(), roofs[0]["ridgeAxis"].as_str(), roofs[0]["pitchDeg"].as_f64(), roofs[0]["baseElevation"].as_f64()), + (Some("sattel"), Some("x"), Some(45.0), Some(3.0)) + ); + assert!(at(&roofs[0]["outline"][2], 110.0, 58.0)); + // Ohne Material in der Datei: kein Dachtyp, einschichtig über die Dicke. + assert!(added(&r.ops, "roofTypes").is_empty() && roofs[0].get("roofTypeId").is_none()); + assert!((roofs[0]["thickness"].as_f64().unwrap() - 0.2).abs() < 1e-9); + let stairs = added(&r.ops, "stairs"); + assert_eq!((stairs[0]["stepCount"].as_f64(), stairs[0]["shape"].as_str()), (Some(6.0), Some("straight"))); + assert!(at(&stairs[0]["start"], 101.0, 52.55)); + let s = r.summary.unwrap(); + assert_eq!((s["roofs"].as_f64(), s["stairs"].as_f64(), s["doorTypes"].as_f64()), (Some(1.0), Some(1.0), Some(1.0))); + assert_eq!(s["keptReasons"], json!({"IfcStair": {"stairForm": 1}})); + + // Allgemeiner Stilname aus dem eigenen Export: kein neuer Typ; vorhandener Name: wiederverwendet. + for name in ["Tür SINGLE_SWING_LEFT", "drehtür"] { + let (m, data) = meta(name); + let r = ifc_import(&root(), &m.to_string(), &[], &[], &data, &opts, 0.0).unwrap(); + assert!(added(&r.ops, "doorTypes").is_empty(), "{name}"); + assert_eq!(added(&r.ops, "openings")[1]["typeId"], "dt1"); + } + // Ohne Projekt-Bezug: lokal (keine Verschiebung). + let mut bare = root(); + bare.remove("geoAnchor"); + let r = ifc_import(&bare, &m.to_string(), &[], &[], &data, &opts, 0.0).unwrap(); + assert!(at(&added(&r.ops, "walls")[0]["start"], 5.0, 0.0)); + } +} diff --git a/src-tauri/fileio/src/ifc_import.rs b/src-tauri/fileio/src/ifc_import.rs index ef3d5fc6..81867135 100644 --- a/src-tauri/fileio/src/ifc_import.rs +++ b/src-tauri/fileio/src/ifc_import.rs @@ -515,6 +515,52 @@ pub struct IfcImport { pub truncated: bool, /// Erkannte Bauteile ([B4]), nur mit [`import_ifc_opts`]`(…, true)`. pub elements: Option, + /// Georeferenz (IfcMapConversion, IFC4): Kartenkoordinaten = Drehung·Massstab·lokal + Versatz. + pub map_conversion: Option, +} + +/// IfcMapConversion ([B4]): Versatz in Kartenmetern, Drehung der lokalen x-Achse, Massstab, Zielsystem. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct MapConversion { + pub eastings: f64, + pub northings: f64, + pub height: f64, + /// Richtung der lokalen x-Achse im Kartensystem (Abszisse, Ordinate; normiert). + pub x_axis: [f64; 2], + pub scale: f64, + /// Name des Zielsystems (IfcProjectedCRS.Name, z. B. `EPSG:2056`). + pub crs: Option, +} + +/// Erste IfcMapConversion der Datei; Kartenwerte in Metern (MapUnit des IfcProjectedCRS, sonst m). +fn map_conversion(f: &StepFile, ids: &[u64]) -> Option { + let e = ids.iter().filter_map(|i| f.get(*i)).find(|e| e.ty == "IFCMAPCONVERSION")?; + let num = |k: usize| e.arg(k).and_then(|v| v.as_f64()); + let crs = e.arg(1).and_then(|v| v.as_ref_id()).and_then(|i| f.get(i)); + // MapUnit (IfcProjectedCRS, 7. Attribut): IfcSIUnit mit Vorsatz. + let unit = crs + .and_then(|c| c.arg(6)) + .and_then(|v| v.as_ref_id()) + .and_then(|u| f.get(u)) + .filter(|u| u.ty == "IFCSIUNIT") + .map(|u| match u.arg(2).and_then(|v| v.as_enum()) { + Some("MILLI") => 0.001, + Some("CENTI") => 0.01, + Some("KILO") => 1000.0, + _ => 1.0, + }) + .unwrap_or(1.0); + let (ax, ay) = (num(5).unwrap_or(1.0), num(6).unwrap_or(0.0)); + let l = ax.hypot(ay); + let m = MapConversion { + eastings: num(2)? * unit, + northings: num(3)? * unit, + height: num(4).unwrap_or(0.0) * unit, + x_axis: if l > 1e-12 { [ax / l, ay / l] } else { [1.0, 0.0] }, + scale: num(7).filter(|s| *s > 0.0).unwrap_or(1.0), + crs: crs.and_then(|c| c.arg(0)).and_then(|v| v.as_str()).map(str::to_string), + }; + (m.eastings.is_finite() && m.northings.is_finite() && m.height.is_finite() && m.scale.is_finite()).then_some(m) } /// Bauteilklassen, die als Mesh keinen Sinn ergeben (Volumen-Hilfskörper, Beschriftung). @@ -1557,6 +1603,37 @@ impl<'a> Reader<'a> { Some((mesh, color)) } + /// Grundriss eines Bauteils ohne Körper ([B4], z. B. ArchiCAD-IfcSpace nur mit „FootPrint" und „Box"): + /// geschlossener Umriss in Weltkoordinaten (erste Kurve der FootPrint-Darstellung) und Höhenbereich + /// aus der BoundingBox-Darstellung. + pub(crate) fn product_footprint(&mut self, id: u64) -> Option<(Vec, f64, f64)> { + let f = self.f; + let e = f.get(id)?; + let shape = f.get(e.arg(6)?.as_ref_id()?)?; + if shape.ty != "IFCPRODUCTDEFINITIONSHAPE" { + return None; + } + let reps: Vec<&Entity> = shape.arg(2)?.as_list()?.iter().filter_map(|x| f.get(x.as_ref_id()?)).filter(|r| r.ty == "IFCSHAPEREPRESENTATION").collect(); + let ident = |r: &Entity| r.arg(1).and_then(|v| v.as_str()).unwrap_or("").to_ascii_uppercase(); + let first = |r: &Entity| r.arg(3).and_then(|v| v.as_list()).and_then(|l| l.first()).and_then(|v| v.as_ref_id()); + let foot = reps.iter().find(|r| ident(r) == "FOOTPRINT").and_then(|r| first(r))?; + let bbox = reps.iter().find(|r| ident(r) == "BOX").and_then(|r| first(r)).and_then(|b| f.get(b)).filter(|b| b.ty == "IFCBOUNDINGBOX")?; + let corner = self.point(bbox.arg(0))?; + let zdim = bbox.arg(3)?.as_f64()? * self.len_scale; + let curve_id = match f.get(foot)? { + c if c.ty == "IFCGEOMETRICCURVESET" || c.ty == "IFCGEOMETRICSET" => c.arg(0)?.as_list()?.first()?.as_ref_id()?, + _ => foot, + }; + let pts = self.curve2d(Some(&Value::Ref(curve_id)), 0)?; + let place = match e.arg(5).and_then(|v| v.as_ref_id()) { + Some(p) => self.object_placement(p, 0), + None => Xf::IDENTITY, + }; + let ring: Vec = pts.iter().map(|p| place.apply([p[0], p[1], corner[2]])).map(|q| [q[0], q[1]]).collect(); + let z0 = place.apply([0.0, 0.0, corner[2]])[2]; + (ring.len() >= 3 && zdim.is_finite() && zdim > 0.0 && ring.iter().all(|p| p[0].is_finite() && p[1].is_finite())).then_some((ring, z0, z0 + zdim)) + } + /// 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 { @@ -1879,7 +1956,7 @@ pub fn import_ifc_opts(bytes: &[u8], elements: bool) -> Result, } #[derive(Clone, Debug, Default)] @@ -165,6 +179,40 @@ pub struct Space { pub z1: f64, } +/// Dach ([B4]): Dossier-Dach aus IfcRoof (samt Platten) bzw. IfcSlab ROOF. +#[derive(Clone, Debug, Default)] +pub struct Roof { + pub info: Info, + /// Umriss der Traufe (aussen, gegen den Uhrzeigersinn, Rechteck bei Sattel/Walm/Pult). + pub outline: Vec, + /// Dossier-Dachform: "flach", "pult", "sattel", "walm". + pub shape: &'static str, + pub pitch_deg: f64, + /// Firstrichtung ("x"/"y"), bei Pult die Richtung der Traufkanten. + pub ridge_axis: &'static str, + /// Höhe der Traufe (Unterkante der Dachhaut an der Aussenkante). + pub eave_z: f64, + /// Dachdicke senkrecht zur Fläche. + pub thickness: f64, + /// Bauteile, aus denen das Dach besteht (IfcRoof + Platten). + pub parts: Vec, +} + +/// Gerade Treppe ([B4]) aus IfcStair/IfcStairFlight. +#[derive(Clone, Debug, Default)] +pub struct Stair { + pub info: Info, + /// Mitte der Antrittskante (unten). + pub start: V2, + /// Einheits-Laufrichtung (aufwärts). + pub dir: V2, + pub run_length: f64, + pub width: f64, + pub step_count: usize, + pub z0: f64, + pub total_rise: f64, +} + /// Erkannte Bauteile einer Datei. #[derive(Clone, Debug, Default)] pub struct Semantic { @@ -175,12 +223,46 @@ pub struct Semantic { pub slabs: Vec, pub columns: Vec, pub spaces: Vec, - /// Kandidaten (Wand, Decke, Stütze, Raum), die nicht sicher abbildbar waren, je Klasse. + pub roofs: Vec, + pub stairs: Vec, + /// Kandidaten (Wand, Decke, Stütze, Raum, Dach, Treppe), die nicht sicher abbildbar waren, je Klasse. pub kept: BTreeMap, + /// Dieselben je Klasse und Grund (Kennwort, s. [`Reason`]). + pub kept_reasons: BTreeMap>, /// Bauteile, die nicht mehr als Mesh kommen (erkannte Bauteile, Füllungen, Öffnungen). pub converted: HashSet, } +impl Semantic { + /// Kandidat bleibt Mesh: zählt je Klasse und Grund. + fn keep(&mut self, class: &str, why: &str) { + *self.kept.entry(class.to_string()).or_insert(0) += 1; + *self.kept_reasons.entry(class.to_string()).or_default().entry(why.to_string()).or_insert(0) += 1; + } +} + +// Gründe, weshalb ein Kandidat Mesh bleibt (Kennwörter; die Hülle übersetzt `ifc.reason.`). +/// Kein lesbarer Körper. +const R_NO_BODY: &str = "noBody"; +/// Körper unbrauchbar (zu flach, kaputt). +const R_SHAPE: &str = "shape"; +/// Masse ausserhalb des Plausiblen (Wand > 2 m dick, Decke > 3 m …). +const R_DIMENSIONS: &str = "dimensions"; +/// Grundriss kein Rechteck (Wand) bzw. Körper kein Quader. +const R_NOT_RECT: &str = "notRectangular"; +/// Wand mit schräger/abgetreppter Krone ohne erkanntes Dach darüber. +const R_SLOPED_TOP: &str = "slopedTop"; +/// Kein senkrechtes Prisma (Decke, Stütze, Raum). +const R_NOT_PRISM: &str = "notPrism"; +/// Öffnung nicht abbildbar (Nische, schräg, mehrere Füllungen …). +const R_OPENING: &str = "opening"; +/// Querschnitt weder Rechteck noch Kreis. +const R_PROFILE: &str = "profile"; +/// Raum mit Loch. +const R_HOLES: &str = "holes"; +/// Teil eines anderen Bauteils (Vorhangfassade, Baugruppe …). +const R_PART: &str = "part"; + // --------------------------------------------------------------------------- // 2D-Hilfen // --------------------------------------------------------------------------- @@ -248,7 +330,7 @@ fn convex_hull(pts: &[V2]) -> Vec { /// 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)> { +pub(crate) fn min_area_rect(pts: &[V2]) -> Option<(V2, f64, f64, f64, f64)> { let hull = convex_hull(pts); if hull.len() < 3 { return None; @@ -381,16 +463,46 @@ fn boundary_loops(tris: &[[V2; 3]]) -> Vec> { pts.len() - 1 }) }; - let mut edges: HashMap<(usize, usize), i32> = HashMap::new(); + let mut idx: Vec<[usize; 3]> = Vec::with_capacity(tris.len()); 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; + if a != b && b != c && a != c { + idx.push([a, b, c]); } + } + // T-Stösse (Dreiecksnetze aus Exporten): Punkte, die auf einer Kante liegen, teilen sie, damit sich + // die Teilkanten mit den Gegenkanten aufheben. Bis 3000 Punkte (sonst ohne Teilung). + let split = |u: usize, v: usize| -> Vec { + let mut on: Vec<(f64, usize)> = Vec::new(); + if pts.len() <= 3000 { + let (a, b) = (pts[u], pts[v]); + let ab = sub2(b, a); + let l2 = dot2(ab, ab); + for (w, &p) in pts.iter().enumerate() { + if w == u || w == v { + continue; + } + let s = dot2(sub2(p, a), ab) / l2; + if s > 1e-9 && s < 1.0 - 1e-9 && cross2(ab, sub2(p, a)).abs() <= 1e-5 * l2.sqrt() { + on.push((s, w)); + } + } + on.sort_by(|x, y| x.0.total_cmp(&y.0)); + } + let mut chain = vec![u]; + chain.extend(on.into_iter().map(|x| x.1)); + chain.push(v); + chain + }; + let mut edges: HashMap<(usize, usize), i32> = HashMap::new(); + for [a, b, c] in idx { 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, + for w in split(u, v).windows(2) { + let (u, v) = (w[0], w[1]); + match edges.get_mut(&(v, u)) { + Some(n) if *n > 0 => *n -= 1, + _ => *edges.entry((u, v)).or_insert(0) += 1, + } } } } @@ -491,11 +603,13 @@ struct WallCand { z1: f64, thickness: f64, /// Öffnungen: (IfcOpeningElement, Füllung, Art, Körper). - openings: Vec<(u64, Option, OpeningKind, Mesh)>, + openings: Vec<(u64, Option, OpeningKind, Mesh, Option<&'static str>)>, /// Seite der ersten Schicht laut IfcMaterialLayerSetUsage: Richtung in Weltkoordinaten. usage_side: Option, /// Darstellungselemente einzeln (Schicht-Bänder). items: Vec, + /// Bogenwand: Bulge der Achse start → end (Modell-Konvention, + = Scheitel links); 0 = gerade. + bulge: f64, } struct Ctx<'r, 'a> { @@ -506,6 +620,10 @@ struct Ctx<'r, 'a> { sia: HashMap, common: HashMap>, storey_index: HashMap, + /// Erkannte Dächer (vor den Wänden): schräge Wandkronen darunter sind Dachanschluss. + roofs: Vec, + /// Türen/Fenster ohne IfcRelFillsElement mit Körper (Kandidaten für ausgeschnittene Wandlöcher). + loose: Vec<(u64, OpeningKind, Mesh)>, } impl Ctx<'_, '_> { @@ -669,24 +787,60 @@ impl Ctx<'_, '_> { fn body(&mut self, id: u64) -> Option<(Mesh, Option<[f64; 4]>)> { let (m, c) = self.r.product_body(id, MAX_BODY_TRIS)?; + #[cfg(test)] + if std::env::var("DOSSIER_IFC_DEBUG").is_ok() && (m.is_empty() || m.triangle_count() > MAX_BODY_TRIS) { + eprintln!("Körper #{id}: {} Dreiecke", m.triangle_count()); + } (!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)?; + fn wall(&mut self, id: u64) -> Result { + let (mesh, color) = self.body(id).ok_or(R_NO_BODY)?; + let s = shape(&mesh).ok_or(R_SHAPE)?; + let (d, u0, u1, v0, v1) = min_area_rect(&s.plan).ok_or(R_SHAPE)?; 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; + return Err(R_DIMENSIONS); } 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 vc0 = (v0 + v1) / 2.0; + let o = lerp_dir([n[0] * vc0, n[1] * vc0], d, u0); + let mut loose_in: Vec = Vec::new(); + if !((0.7..=1.0 + 1e-3).contains(&ratio) && s.top_area >= 0.35 * rect && s.bottom_area >= 0.6 * rect) { + // Türen/Fenster ohne Öffnungsbeziehung, deren Löcher schon im Wandkörper sind: das fehlende + // Volumen muss genau ihren Kästen über die Wanddicke entsprechen. + let mut cut = 0.0; + for (k, (_, _, m)) in self.loose.iter().enumerate() { + let Some((b, _)) = box_in_frame(m, o, d) else { continue }; + // Rahmen dürfen über die Wand stehen, die Mitte liegt in der Wanddicke. + let inside = b[0] >= -0.01 + && b[1] <= len + 0.01 + && b[4] >= s.z0 - 0.01 + && b[5] <= s.z1 + 0.01 + && ((b[2] + b[3]) / 2.0).abs() <= t / 2.0 + 0.02 + && b[3] - b[2] <= t + 0.3; + if inside { + loose_in.push(k); + cut += (b[1].min(len) - b[0].max(0.0)) * t * (b[5].min(s.z1) - b[4].max(s.z0)); + } + } + let explained = !loose_in.is_empty() && s.top_area >= 0.35 * rect && (rect * h - cut - s.volume).abs() <= 0.03 * rect * h; + if explained { + // Wand mit den Löchern der Füllungen (unten). + } else if s.bottom_area >= 0.6 * rect && ratio <= 1.0 + 1e-3 && ratio >= 0.2 { + // Schräge Krone (Giebel, Pult): abbildbar, wenn ein erkanntes Dach sie genau so kappt + // (Dossier schneidet die Wand an der Dach-Unterkante, `Wall.roofAttach` automatisch). + let capped = crate::ifc_shapes::capped_volume(o, d, len, t, s.z0, s.z1, &self.roofs); + if self.roofs.is_empty() || (capped - s.volume).abs() > 0.03 * s.volume.max(1e-6) { + return Err(R_SLOPED_TOP); + } + } else { + return self.arc_wall(id, &s, color); + } + } let vc = (v0 + v1) / 2.0; let base = [n[0] * vc, n[1] * vc]; let start = lerp_dir(base, d, u0); @@ -695,12 +849,18 @@ impl Ctx<'_, '_> { // Ö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 (om, _) = self.body(o).ok_or(R_OPENING)?; + let (b, fill) = box_in_frame(&om, start, d).ok_or(R_OPENING)?; 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; + // Rund (Dossier `shape: "rund"`, Ellipse im Rechteck): Füllgrad π/4, alle Punkte auf der Ellipse. + let round = (0.76..=0.81).contains(&fill) && on_ellipse(&om, start, d, &b); + if !(through && inside && ((0.95..=1.0 + 1e-3).contains(&fill) || round)) { + #[cfg(test)] + if std::env::var("DOSSIER_IFC_DEBUG").is_ok() { + eprintln!("Öffnung #{o} in #{id}: Quader {b:?} Füllgrad {fill:.3} Wand len {len:.3} t {t:.3} z {:.3}..{:.3}", s.z0, s.z1); + } + return Err(R_OPENING); } let fillings = self.fills.get(&o).cloned().unwrap_or_default(); let (filling, kind) = match fillings.as_slice() { @@ -712,12 +872,16 @@ impl Ctx<'_, '_> { } else if ty.starts_with("IFCWINDOW") { (Some(*x), OpeningKind::Window) } else { - return None; + return Err(R_OPENING); } } - _ => return None, + _ => return Err(R_OPENING), }; - openings.push((o, filling, kind, om)); + openings.push((o, filling, kind, om, round.then_some("rund"))); + } + for k in loose_in { + let (x, kind, m) = &self.loose[k]; + openings.push((*x, Some(*x), *kind, m.clone(), None)); } let (layers, sense, _) = self.layers(id); @@ -736,40 +900,56 @@ impl Ctx<'_, '_> { _ => 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 }) + Ok(WallCand { info: self.info(id, color), start, end, z0: s.z0, z1: s.z1, thickness: t, openings, usage_side, items, bulge: 0.0 }) } - 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; + /// Bogenwand ([T2]): senkrechtes Prisma mit einem Ringausschnitt als Grundriss, ohne Öffnungen. + fn arc_wall(&mut self, id: u64, s: &Shape, color: Option<[f64; 4]>) -> Result { + let (ring, holes) = prism(s).ok_or(R_NOT_RECT)?; + if !holes.is_empty() { + return Err(R_NOT_RECT); } - let (outline, mut holes) = prism(&s)?; + let a = crate::ifc_shapes::fit_arc_ring(&ring).ok_or(R_NOT_RECT)?; + if self.rels.voids.get(&id).is_some_and(|v| !v.is_empty()) { + return Err(R_OPENING); + } + let at = |w: f64| [a.center[0] + a.radius * w.cos(), a.center[1] + a.radius * w.sin()]; + // Gegen den Uhrzeigersinn: Scheitel rechts der Sehne → Bulge negativ. + let bulge = -((a.a1 - a.a0) / 4.0).tan(); + Ok(WallCand { info: self.info(id, color), start: at(a.a0), end: at(a.a1), z0: s.z0, z1: s.z1, thickness: a.thickness, openings: Vec::new(), usage_side: None, items: Vec::new(), bulge }) + } + + fn slab(&mut self, id: u64) -> Result { + let (mesh, color) = self.body(id).ok_or(R_NO_BODY)?; + let s = shape(&mesh).ok_or(R_SHAPE)?; + if s.z1 - s.z0 > 3.0 { + return Err(R_DIMENSIONS); + } + let (outline, mut holes) = prism(&s).ok_or(R_NOT_PRISM)?; 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; + return Err(R_OPENING); } - let (om, _) = self.body(o)?; - let os = shape(&om)?; + let (om, _) = self.body(o).ok_or(R_OPENING)?; + let os = shape(&om).ok_or(R_OPENING)?; if !(os.z0 <= s.z0 + 1e-3 && os.z1 >= s.z1 - 1e-3) { - return None; + return Err(R_OPENING); } - let (ring, inner) = prism(&os)?; + let (ring, inner) = prism(&os).ok_or(R_OPENING)?; if !inner.is_empty() { - return None; + return Err(R_OPENING); } holes.push(ring); } - Some(Slab { info: self.info(id, color), outline, holes, z0: s.z0, z1: s.z1 }) + Ok(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)?; + fn column(&mut self, id: u64) -> Result { + let (mesh, color) = self.body(id).ok_or(R_NO_BODY)?; + let s = shape(&mesh).ok_or(R_SHAPE)?; + let (ring, holes) = prism(&s).ok_or(R_NOT_PRISM)?; if !holes.is_empty() { - return None; + return Err(R_PROFILE); } 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]); @@ -780,14 +960,15 @@ impl Ctx<'_, '_> { 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; + return Err(R_PROFILE); } // 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))) - })?; + }) + .ok_or(R_PROFILE)?; 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; @@ -798,34 +979,63 @@ impl Ctx<'_, '_> { 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; + return Err(R_PROFILE); } center = c; profile = Profile::Round { radius: rs.iter().copied().fold(0.0, f64::max) }; } else { - return None; + return Err(R_PROFILE); } - Some(Column { info: self.info(id, color), center, rotation, profile, z0: s.z0, z1: s.z1 }) + Ok(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; - } + fn space(&mut self, id: u64) -> Result { + let (boundary, z0, z1, color) = match self.body(id) { + Some((mesh, color)) => { + let s = shape(&mesh).ok_or(R_SHAPE)?; + let (boundary, holes) = prism(&s).ok_or(R_NOT_PRISM)?; + if !holes.is_empty() { + return Err(R_HOLES); + } + (boundary, s.z0, s.z1, color) + } + // Ohne Körper (ArchiCAD IFC2x3: nur „FootPrint" + „Box"): Grundriss-Umriss. + None => { + let (ring, z0, z1) = self.r.product_footprint(id).ok_or(R_NO_BODY)?; + let mut ring = simplify_ring(&ring); + if area2(&ring) < 0.0 { + ring.reverse(); + } + if ring.len() < 3 || area2(&ring) < 1e-4 { + return Err(R_SHAPE); + } + (ring, z0, z1, 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().or_else(|| self.zone_sia(id)), boundary, z0: s.z0, z1: s.z1 }) + Ok(Space { info: self.info(id, color), long_name, sia: self.sia.get(&id).cloned().or_else(|| self.zone_sia(id)), boundary, z0, z1 }) } } +/// Alle Punkte eines Öffnungskörpers liegen (in der Wandebene u/z) auf der Ellipse im Rechteck `b`. +fn on_ellipse(m: &Mesh, o: V2, d: V2, b: &[f64; 6]) -> bool { + let (uc, zc, a, c) = ((b[0] + b[1]) / 2.0, (b[4] + b[5]) / 2.0, (b[1] - b[0]) / 2.0, (b[5] - b[4]) / 2.0); + a > 0.01 && c > 0.01 && m.positions.chunks_exact(3).all(|p| { + let u = dot2(sub2([p[0], p[1]], o), d); + let r = ((u - uc) / a).powi(2) + ((p[2] - zc) / c).powi(2); + (r - 1.0).abs() <= 0.03 + }) +} + /// 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]; + if walls[i].bulge != 0.0 { + continue; + } let Some(di) = unit2(sub2(b, a)) else { continue }; let li = len2(sub2(b, a)); for end in 0..2 { @@ -833,6 +1043,7 @@ fn snap_ends(walls: &mut [WallCand]) { let mut best: Option<(f64, V2)> = None; for (j, &(c, e, tj)) in orig.iter().enumerate() { if i == j + || walls[j].bulge != 0.0 || walls[i].info.storey != walls[j].info.storey || walls[i].z1.min(walls[j].z1) - walls[i].z0.max(walls[j].z0) < 0.01 { @@ -904,6 +1115,187 @@ fn side_from_bands(w: &WallCand, d: V2) -> i32 { (l as i32 - r as i32).signum() } +/// Körper der Bauteile, die einen haben. +fn bodies(cx: &mut Ctx, ids: &[u64]) -> Vec<(u64, Mesh, Option<[f64; 4]>)> { + let f = cx.r.f; + ids.iter() + .filter(|&&id| f.get(id).and_then(|e| e.arg(6)).and_then(|v| v.as_ref_id()).and_then(|i| f.get(i)).is_some_and(|s| s.ty == "IFCPRODUCTDEFINITIONSHAPE")) + .filter_map(|&id| cx.body(id).map(|(m, c)| (id, m, c))) + .collect() +} + +fn is_spatial(f: &crate::ifc_step::StepFile, id: u64) -> bool { + f.get(id).is_some_and(|e| matches!(e.ty.as_str(), "IFCBUILDINGSTOREY" | "IFCBUILDING" | "IFCSITE" | "IFCSPACE")) +} + +/// Dächer ([B4]): IfcRoof (eigener Körper, sonst seine Platten) und frei stehende IfcSlab ROOF (je +/// Geschoss die sich berührenden zusammen). Liefert für Platten, die kein Dach wurden, den Grund. +fn roofs(cx: &mut Ctx, out: &mut Semantic, ids: &[u64], children: &HashMap>) -> HashMap { + let f = cx.r.f; + let rels = cx.rels; + let is_roof_slab = |id: u64| f.get(id).is_some_and(|e| matches!(e.ty.as_str(), "IFCSLAB" | "IFCSLABSTANDARDCASE") && e.arg(8).and_then(|v| v.as_enum()) == Some("ROOF")); + let free_standing = |id: u64| !rels.parent.get(&id).is_some_and(|p| !is_spatial(f, *p)); + // (Hauptbauteil, Teile mit Körper, IfcRoof?) + let mut groups: Vec<(u64, Vec, bool)> = Vec::new(); + for &id in ids { + let Some(e) = f.get(id) else { continue }; + if e.ty != "IFCROOF" || !free_standing(id) { + continue; + } + let own = e.arg(6).and_then(|v| v.as_ref_id()).is_some(); + let parts: Vec = if own { + vec![id] + } else { + let plate = |c: &u64| f.get(*c).is_some_and(|e| matches!(e.ty.as_str(), "IFCSLAB" | "IFCSLABSTANDARDCASE" | "IFCPLATE")); + children.get(&id).map(|c| c.iter().copied().filter(plate).collect()).unwrap_or_default() + }; + if !parts.is_empty() { + groups.push((id, parts, true)); + } + } + // Frei stehende Dachplatten: je Geschoss nach Berührung (±5 cm im Grundriss) gruppiert. + let free: Vec = ids.iter().copied().filter(|&id| is_roof_slab(id) && free_standing(id)).collect(); + let mut boxes: Vec<(u64, Option, [f64; 4])> = Vec::new(); + for (id, m, _) in bodies(cx, &free) { + let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY]; + for c in m.positions.chunks_exact(3) { + b = [b[0].min(c[0]), b[1].min(c[1]), b[2].max(c[0]), b[3].max(c[1])]; + } + boxes.push((id, rels.storey_id(f, id), b)); + } + fn root(g: &mut [usize], mut i: usize) -> usize { + while g[i] != i { + g[i] = g[g[i]]; + i = g[i]; + } + i + } + let mut group_of: Vec = (0..boxes.len()).collect(); + for i in 0..boxes.len() { + for j in i + 1..boxes.len() { + let (a, b) = (boxes[i].2, boxes[j].2); + if boxes[i].1 == boxes[j].1 && a[0] <= b[2] + 0.05 && b[0] <= a[2] + 0.05 && a[1] <= b[3] + 0.05 && b[1] <= a[3] + 0.05 { + let (ri, rj) = (root(&mut group_of, i), root(&mut group_of, j)); + group_of[ri.max(rj)] = ri.min(rj); + } + } + } + let mut by_root: BTreeMap> = BTreeMap::new(); + for i in 0..boxes.len() { + let r = root(&mut group_of, i); + by_root.entry(r).or_default().push(boxes[i].0); + } + for (_, parts) in by_root { + groups.push((parts[0], parts, false)); + } + + let mut fail = HashMap::new(); + for (main, parts, is_roof) in groups { + let mut todo = vec![parts]; + // Mehrere frei stehende Platten, die zusammen kein Dach ergeben: jede einzeln versuchen. + let mut tried_single = false; + while let Some(group) = todo.pop() { + let main = if is_roof { main } else { group[0] }; + let has_voids = group.iter().chain([&main]).any(|p| rels.voids.get(p).is_some_and(|v| !v.is_empty())); + let b = if has_voids { Vec::new() } else { bodies(cx, &group) }; + let color = b.iter().find_map(|x| x.2); + let res = if has_voids { + Err(R_OPENING) + } else if b.len() != group.len() { + Err(R_NO_BODY) + } else { + let meshes: Vec = b.into_iter().map(|x| x.1).collect(); + crate::ifc_shapes::fit_roof(&meshes) + }; + match res { + Ok(fit) => { + let [x0, y0, x1, y1] = fit.bbox; + let mut info = cx.info(main, color); + if info.storey.is_none() { + info.storey = group.iter().find_map(|p| cx.info(*p, None).storey); + } + if info.layers.is_empty() { + let l = cx.info(group[0], None); + info.layers = l.layers; + info.type_name = info.type_name.or(l.type_name); + } + out.converted.insert(main); + out.converted.extend(group.iter().copied()); + out.roofs.push(Roof { + info, + outline: vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]], + shape: fit.shape, + pitch_deg: fit.pitch_deg, + ridge_axis: fit.ridge_axis, + eave_z: fit.eave_z, + thickness: fit.thickness, + parts: group.clone(), + }); + cx.roofs.push(fit); + } + Err(why) => { + if !is_roof && group.len() > 1 && !tried_single { + tried_single = true; + todo.extend(group.iter().map(|p| vec![*p])); + continue; + } + for p in &group { + fail.insert(*p, why); + } + if is_roof { + out.keep("IfcRoof", why); + } + } + } + } + } + fail +} + +/// Treppen ([B4]): IfcStair (eigener Körper und Teile ausser Geländern) bzw. frei stehender +/// IfcStairFlight → gerade Dossier-Treppe. +fn stairs(cx: &mut Ctx, out: &mut Semantic, ids: &[u64], children: &HashMap>) { + let f = cx.r.f; + let rels = cx.rels; + let elevations: Vec = out.storeys.iter().map(|s| s.elevation).collect(); + for &id in ids { + let Some(e) = f.get(id) else { continue }; + if !matches!(e.ty.as_str(), "IFCSTAIR" | "IFCSTAIRFLIGHT") || rels.parent.get(&id).is_some_and(|p| !is_spatial(f, *p)) { + continue; + } + let mut parts = vec![id]; + parts.extend(children.get(&id).map(Vec::as_slice).unwrap_or(&[]).iter().copied().filter(|c| f.get(*c).is_some_and(|e| e.ty != "IFCRAILING"))); + let b = bodies(cx, &parts); + if b.is_empty() { + continue; + } + let color = b.iter().find_map(|x| x.2); + let used: Vec = b.iter().map(|x| x.0).collect(); + let meshes: Vec = b.into_iter().map(|x| x.1).collect(); + match crate::ifc_shapes::fit_stair(&meshes) { + Ok(st) => { + // Oberster Tritt auf Geschosshöhe: er ist der Austritt; sonst kommt dieser noch dazu. + let top = st.z0 + st.riser * st.treads as f64; + let steps = if st.top_is_exit || elevations.iter().any(|z| (z - top).abs() <= 0.02) { st.treads } else { st.treads + 1 }; + out.converted.insert(id); + out.converted.extend(used); + let info = cx.info(id, color); + out.stairs.push(Stair { + info, + start: st.start, + dir: st.dir, + run_length: st.going * steps as f64, + width: st.width, + step_count: steps, + z0: st.z0, + total_rise: st.riser * steps as f64, + }); + } + Err(why) => out.keep(&class_name(&e.ty), why), + } + } +} + /// Erkennt alle sicher abbildbaren Bauteile. pub(crate) fn analyze(r: &mut Reader, rels: &Rels, ids: &[u64]) -> Semantic { let f = r.f; @@ -989,8 +1381,19 @@ pub(crate) fn analyze(r: &mut Reader, rels: &Rels, ids: &[u64]) -> Semantic { } 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, common, storey_index }; + let mut cx = Ctx { r, rels, type_of, fills, sia, common, storey_index, roofs: Vec::new(), loose: Vec::new() }; let mut out = Semantic { storeys, ..Default::default() }; + let mut children: HashMap> = HashMap::new(); + for (&c, &p) in &rels.parent { + children.entry(p).or_default().push(c); + } + for v in children.values_mut() { + v.sort_unstable(); + } + cx.loose = loose_fillings(&mut cx, ids); + // Dächer zuerst: schräge Wandkronen darunter werden zum Dachanschluss. + let roof_fail = roofs(&mut cx, &mut out, ids, &children); + stairs(&mut cx, &mut out, ids, &children); 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(); @@ -999,23 +1402,27 @@ pub(crate) fn analyze(r: &mut Reader, rels: &Rels, ids: &[u64]) -> Semantic { 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 { + if !candidate || !has_shape || out.converted.contains(&id) { 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(&[])); + let res = if part { + Err(roof_fail.get(&id).copied().unwrap_or(R_PART)) } else { - *out.kept.entry(class_name(ty)).or_insert(0) += 1; + match ty { + "IFCWALL" | "IFCWALLSTANDARDCASE" => cx.wall(id).map(|w| walls.push(w)), + "IFCSLAB" | "IFCSLABSTANDARDCASE" => cx.slab(id).map(|s| out.slabs.push(s)), + "IFCCOLUMN" | "IFCCOLUMNSTANDARDCASE" => cx.column(id).map(|c| out.columns.push(c)), + _ => cx.space(id).map(|s| out.spaces.push(s)), + } + }; + match res { + Ok(()) => { + out.converted.insert(id); + out.converted.extend(rels.voids.get(&id).map(Vec::as_slice).unwrap_or(&[])); + } + Err(why) => out.keep(&class_name(ty), roof_fail.get(&id).copied().unwrap_or(why)), } } @@ -1058,7 +1465,7 @@ pub(crate) fn analyze(r: &mut Reader, rels: &Rels, ids: &[u64]) -> Semantic { 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 { + for (o, filling, kind, mesh, form) 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); @@ -1083,20 +1490,103 @@ pub(crate) fn analyze(r: &mut Reader, rels: &Rels, ids: &[u64]) -> Semantic { operation, swing, hinge, + shape: *form, }); } - out.walls.push(Wall { info: w.info, start, end, z0: w.z0, z1: w.z1, thickness: w.thickness }); + let bulge = if side > 0 { -w.bulge } else { w.bulge }; + out.walls.push(Wall { info: w.info, start, end, z0: w.z0, z1: w.z1, thickness: w.thickness, bulge }); + } + unhosted_fillings(&mut cx, &mut out, ids); + out +} + +/// Türen/Fenster ohne IfcRelFillsElement, mit Körper. +fn loose_fillings(cx: &mut Ctx, ids: &[u64]) -> Vec<(u64, OpeningKind, Mesh)> { + let f = cx.r.f; + let filled: HashSet = cx.fills.values().flatten().copied().collect(); + let mut out = Vec::new(); + for &id in ids { + let Some(e) = f.get(id) else { continue }; + let kind = match e.ty.as_str() { + "IFCDOOR" | "IFCDOORSTANDARDCASE" => OpeningKind::Door, + "IFCWINDOW" | "IFCWINDOWSTANDARDCASE" => OpeningKind::Window, + _ => continue, + }; + if filled.contains(&id) { + continue; + } + if let Some((_, m, _)) = bodies(cx, &[id]).pop() { + out.push((id, kind, m)); + } } out } +/// Türen/Fenster ohne IfcRelFillsElement (z. B. ArchiCAD-IFC2x3 mit ausgeschnittenen Wandkörpern): Wirt +/// ist die erkannte gerade Wand, in deren Körper das Bauteil liegt (Mitte in der Wanddicke, ganz +/// innerhalb von Länge und Höhe); Öffnung = Ausdehnung des Bauteils. Überlappt sie eine vorhandene +/// Öffnung derselben Wand, bleibt das Bauteil Mesh. +fn unhosted_fillings(cx: &mut Ctx, out: &mut Semantic, ids: &[u64]) { + let f = cx.r.f; + let filled: HashSet = cx.fills.values().flatten().copied().collect(); + for &id in ids { + let Some(e) = f.get(id) else { continue }; + let kind = match e.ty.as_str() { + "IFCDOOR" | "IFCDOORSTANDARDCASE" => OpeningKind::Door, + "IFCWINDOW" | "IFCWINDOWSTANDARDCASE" => OpeningKind::Window, + _ => continue, + }; + if filled.contains(&id) || out.converted.contains(&id) { + continue; + } + let Some((m, _)) = bodies(cx, &[id]).pop().map(|x| (x.1, x.2)) else { continue }; + let mut best: Option<(f64, usize, [f64; 6])> = None; + for (i, w) in out.walls.iter().enumerate() { + let Some(d) = unit2(sub2(w.end, w.start)) else { continue }; + if w.bulge != 0.0 { + continue; + } + let Some((b, _)) = box_in_frame(&m, w.start, d) else { continue }; + let len = len2(sub2(w.end, w.start)); + let vc = (b[2] + b[3]) / 2.0; + let fits = vc.abs() <= w.thickness / 2.0 + 0.02 + && b[3] - b[2] <= w.thickness + 0.3 + && b[0] >= -0.01 + && b[1] <= len + 0.01 + && b[4] >= w.z0 - 0.01 + && b[5] <= w.z1 + 0.01 + && b[1] - b[0] >= 0.1 + && b[5] - b[4] >= 0.1; + if fits && best.is_none_or(|(bv, _, _)| vc.abs() < bv) { + best = Some((vc.abs(), i, b)); + } + } + let Some((_, host, b)) = best else { continue }; + let w = &out.walls[host]; + let (u0, u1) = (b[0].max(0.0), b[1].min(len2(sub2(w.end, w.start)))); + let (z0, z1) = (b[4].max(w.z0), b[5].min(w.z1)); + let overlaps = out.openings.iter().any(|o| o.host == host && o.position < u1 - 0.01 && o.position + o.width > u0 + 0.01 && w.z0 + o.sill < z1 - 0.01 && w.z0 + o.sill + o.height > z0 + 0.01); + if overlaps { + continue; + } + let Some(d) = unit2(sub2(w.end, w.start)) else { continue }; + let wz0 = w.z0; + let info = cx.info(id, None); + let (operation, swing, hinge) = cx.operation(id, d); + out.converted.insert(id); + out.openings.push(Opening { info, host, kind, position: u0, width: u1 - u0, sill: z0 - wz0, height: z1 - z0, operation, swing, hinge, shape: None }); + } +} + // --------------------------------------------------------------------------- // Flache Kodierung für JS: Texte/Verweise als JSON, Zahlen in einem Float64Array. -// wall: sx, sy, ex, ey, z0, z1, thickness +// wall: sx, sy, ex, ey, z0, z1, thickness, bulge // opening: position, width, sill, height, swing (±1/0), hinge (±1/0) // 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, … +// roof: eaveZ, pitchDeg, thickness, nPts, x, y, … (Form, Firstrichtung im JSON) +// stair: sx, sy, dx, dy, runLength, width, stepCount, z0, totalRise // --------------------------------------------------------------------------- #[cfg(feature = "web")] @@ -1138,7 +1628,7 @@ pub(crate) fn encode(s: &Semantic) -> (serde_json::Value, Vec) { } }; 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); + push("wall", &w.info, json!({}), vec![w.start[0], w.start[1], w.end[0], w.end[1], w.z0, w.z1, w.thickness, w.bulge], &mut data); } for o in &s.openings { let kind = match o.kind { @@ -1149,7 +1639,7 @@ pub(crate) fn encode(s: &Semantic) -> (serde_json::Value, Vec) { push( "opening", &o.info, - json!({ "host": o.host, "openingKind": kind, "operation": o.operation }), + json!({ "host": o.host, "openingKind": kind, "operation": o.operation, "shape": o.shape }), vec![o.position, o.width, o.sill, o.height, o.swing as f64, o.hinge as f64], &mut data, ); @@ -1174,6 +1664,15 @@ pub(crate) fn encode(s: &Semantic) -> (serde_json::Value, Vec) { ring(&sp.boundary, &mut nums); push("space", &sp.info, json!({ "longName": sp.long_name, "sia": sp.sia }), nums, &mut data); } + for r in &s.roofs { + let mut nums = vec![r.eave_z, r.pitch_deg, r.thickness]; + ring(&r.outline, &mut nums); + push("roof", &r.info, json!({ "shape": r.shape, "ridgeAxis": r.ridge_axis }), nums, &mut data); + } + for st in &s.stairs { + let nums = vec![st.start[0], st.start[1], st.dir[0], st.dir[1], st.run_length, st.width, st.step_count as f64, st.z0, st.total_rise]; + push("stair", &st.info, json!({}), 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() { @@ -1181,7 +1680,7 @@ pub(crate) fn encode(s: &Semantic) -> (serde_json::Value, Vec) { *v = 0.0; } } - (json!({ "storeys": storeys, "elements": elements, "kept": s.kept }), data) + (json!({ "storeys": storeys, "elements": elements, "kept": s.kept, "keptReasons": s.kept_reasons }), data) } // --------------------------------------------------------------------------- @@ -1517,9 +2016,9 @@ ENDSEC;\nEND-ISO-10303-21;\n" #[test] fn classification_references_of_element_type_and_mesh() { // Stütze (Bauteil) mit eBKP-H, Raum mit Klassifikation über verschachtelte Referenz, BKP am Typ, - // dazu ein Dach (bleibt Mesh) mit Klassifikation. + // dazu ein Geländer (bleibt Mesh) mit Klassifikation. let col = rect_product(40, "IFCCOLUMN", (1.0, 1.0, 0.0), (1.0, 0.0), (0.4, 0.4), 2.75, ""); - let roof = rect_product(41, "IFCROOF", (1.0, 1.0, 3.0), (1.0, 0.0), (4.0, 3.0), 0.3, ""); + let roof = rect_product(41, "IFCRAILING", (1.0, 1.0, 3.0), (1.0, 0.0), (4.0, 3.0), 0.3, ""); let cls = "#700=IFCCLASSIFICATION('CRB','2020',$,'eBKP-H',$,$,$);\ #701=IFCCLASSIFICATIONREFERENCE($,'C','Konstruktion Geb\\X2\\00E4\\X0\\ude',#700,$,$);\ #702=IFCRELASSOCIATESCLASSIFICATION('c1',$,$,$,(#40),#701);\ @@ -1534,8 +2033,8 @@ ENDSEC;\nEND-ISO-10303-21;\n" // Leerer Code und ein blosses IfcClassification (ohne Code) zählen nicht. assert_eq!(c.len(), 1, "{c:?}"); assert_eq!((c[0].system.as_str(), c[0].code.as_str(), c[0].name.as_deref()), ("eBKP-H", "C", Some("Konstruktion Gebäude"))); - // Roof bleibt Mesh, die Klassifikation kommt trotzdem mit (verschachtelte Referenz: System von oben). - let p = r.products.iter().find(|p| p.class == "IfcRoof").expect("Dach als Mesh"); + // Geländer bleibt Mesh, die Klassifikation kommt trotzdem mit (verschachtelte Referenz: System von oben). + let p = r.products.iter().find(|p| p.class == "IfcRailing").expect("Geländer als Mesh"); assert_eq!(p.classifications.len(), 1); assert_eq!((p.classifications[0].system.as_str(), p.classifications[0].code.as_str(), p.classifications[0].name.as_deref()), ("eBKP-H", "C02", None)); } @@ -1588,4 +2087,247 @@ ENDSEC;\nEND-ISO-10303-21;\n" let _ = import_ifc_opts(src.as_bytes(), true); } } + + /// Bauteil `class` mit id `#n` als IfcFacetedBrep aus Flächen (je Polygon, von aussen gegen den + /// Uhrzeigersinn), Platzierung = EG (#22), im EG enthalten; `extra` = Attribute ab dem 9. + fn brep_product(n: u64, class: &str, faces: &[Vec<[f64; 3]>], extra: &str) -> String { + let mut s = String::new(); + let mut k = n * 100; + let mut face_ids = Vec::new(); + for f in faces { + let mut pids = Vec::new(); + for p in f { + k += 1; + s += &format!("#{k}=IFCCARTESIANPOINT(({:?},{:?},{:?}));", p[0], p[1], p[2]); + pids.push(format!("#{k}")); + } + k += 1; + s += &format!("#{k}=IFCPOLYLOOP(({}));", pids.join(",")); + k += 1; + s += &format!("#{k}=IFCFACEOUTERBOUND(#{},.T.);", k - 1); + k += 1; + s += &format!("#{k}=IFCFACE((#{}));", k - 1); + face_ids.push(format!("#{k}")); + } + let (sh, br, rep, pds) = (k + 1, k + 2, k + 3, k + 4); + s += &format!( + "#{sh}=IFCCLOSEDSHELL(({}));#{br}=IFCFACETEDBREP(#{sh});#{rep}=IFCSHAPEREPRESENTATION($,'Body','Brep',(#{br}));\ +#{pds}=IFCPRODUCTDEFINITIONSHAPE($,$,(#{rep}));#{n}={class}('g{n}',$,'E{n}',$,$,#22,#{pds},$,{extra});\ +#{rc}=IFCRELCONTAINEDINSPATIALSTRUCTURE('r{n}',$,$,$,(#{n}),#23);\n", + face_ids.join(","), + rc = k + 5 + ); + s + } + + /// Flächen eines Körpers über dem Grundriss-Polygon `ring` (gegen den Uhrzeigersinn) zwischen z0 und + /// der Oberkante `top(x, y)` (eben je Fläche: Ring-Punkte direkt). + fn prism_faces(ring: &[[f64; 2]], z0: f64, top: impl Fn(f64, f64) -> f64) -> Vec> { + let n = ring.len(); + let mut f = vec![ring.iter().map(|p| [p[0], p[1], top(p[0], p[1])]).collect::>(), ring.iter().rev().map(|p| [p[0], p[1], z0]).collect()]; + for i in 0..n { + let (a, b) = (ring[i], ring[(i + 1) % n]); + f.push(vec![[a[0], a[1], z0], [b[0], b[1], z0], [b[0], b[1], top(b[0], b[1])], [a[0], a[1], top(a[0], a[1])]]); + } + f + } + + /// Geneigte Dachplatte über [x0,x1] × [ya,yb] (Traufe bei ya auf `ze`, steigt mit `tan` zur Mitte), + /// Dicke senkrecht `t`, Stirnseiten senkrecht. + fn roof_plate(x0: f64, x1: f64, ya: f64, yb: f64, ze: f64, tan: f64, t: f64) -> Vec> { + let zt = |y: f64| ze + (y - ya).abs() * tan; + let dz = t * (1.0 + tan * tan).sqrt(); + let (lo, hi) = (ya.min(yb), ya.max(yb)); + let ring = [[x0, lo], [x1, lo], [x1, hi], [x0, hi]]; + let mut f = vec![ring.iter().map(|p| [p[0], p[1], zt(p[1])]).collect::>(), ring.iter().rev().map(|p| [p[0], p[1], zt(p[1]) - dz]).collect()]; + for i in 0..4 { + let (a, b) = (ring[i], ring[(i + 1) % 4]); + f.push(vec![[a[0], a[1], zt(a[1]) - dz], [b[0], b[1], zt(b[1]) - dz], [b[0], b[1], zt(b[1])], [a[0], a[1], zt(a[1])]]); + } + f + } + + #[test] + fn saddle_roof_from_roof_slabs_and_gable_wall() { + // Satteldach 10 × 8 (First entlang x in y = 4), Traufe z = 3, 45°, Dicke 0.2; Giebelwand + // x ∈ [0, 0.3], y ∈ [0, 8], Krone an der Dach-Unterkante. + let (t, dz) = (0.2, 0.2 * 2f64.sqrt()); + let a = brep_product(100, "IFCSLAB", &roof_plate(0.0, 10.0, 0.0, 4.0, 3.0, 1.0, t), ".ROOF."); + let b = brep_product(200, "IFCSLAB", &roof_plate(0.0, 10.0, 8.0, 4.0, 3.0, 1.0, t), ".ROOF."); + let under = |_: f64, y: f64| 3.0 + y.min(8.0 - y) - dz; + // Giebelwand als Fünfeck-Prisma (Grundriss Rechteck, Krone unter dem Dach). + let mut gable = Vec::new(); + let ring = [[0.0, 0.0], [0.3, 0.0], [0.3, 8.0], [0.0, 8.0]]; + gable.push(vec![[0.3, 0.0, 0.0], [0.3, 8.0, 0.0], [0.3, 8.0, under(0.0, 8.0)], [0.3, 4.0, under(0.0, 4.0)], [0.3, 0.0, under(0.0, 0.0)]]); + gable.push(vec![[0.0, 8.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, under(0.0, 0.0)], [0.0, 4.0, under(0.0, 4.0)], [0.0, 8.0, under(0.0, 8.0)]]); + gable.push(ring.iter().rev().map(|p| [p[0], p[1], 0.0]).collect()); + gable.push(vec![[0.0, 0.0, 0.0], [0.3, 0.0, 0.0], [0.3, 0.0, under(0.0, 0.0)], [0.0, 0.0, under(0.0, 0.0)]]); + gable.push(vec![[0.3, 8.0, 0.0], [0.0, 8.0, 0.0], [0.0, 8.0, under(0.0, 8.0)], [0.3, 8.0, under(0.0, 8.0)]]); + gable.push(vec![[0.0, 0.0, under(0.0, 0.0)], [0.3, 0.0, under(0.0, 0.0)], [0.3, 4.0, under(0.0, 4.0)], [0.0, 4.0, under(0.0, 4.0)]]); + gable.push(vec![[0.0, 4.0, under(0.0, 4.0)], [0.3, 4.0, under(0.0, 4.0)], [0.3, 8.0, under(0.0, 8.0)], [0.0, 8.0, under(0.0, 8.0)]]); + let w = brep_product(300, "IFCWALL", &gable, "$"); + let (r, s) = sem(&file(METRE, &format!("{a}{b}{w}"))); + assert_eq!(s.roofs.len(), 1, "{:?}", s.kept_reasons); + let rf = &s.roofs[0]; + assert_eq!((rf.shape, rf.ridge_axis), ("sattel", "x")); + assert!(close(rf.pitch_deg, 45.0) && close(rf.eave_z, 3.0) && close(rf.thickness, 0.2), "{rf:?}"); + assert!(close(area2(&rf.outline), 80.0)); + assert_eq!(rf.parts.len(), 2); + // Giebelwand: Rechteck bis zum First (Dossier kappt sie an der Dach-Unterkante). + assert_eq!(s.walls.len(), 1, "{:?}", s.kept_reasons); + assert!(close(s.walls[0].z1, under(0.0, 4.0)) && close(s.walls[0].thickness, 0.3)); + assert!(r.products.is_empty(), "{:?}", r.products.iter().map(|p| &p.class).collect::>()); + // Ohne Dach bleibt die Giebelwand Mesh (Grund: schräge Krone). + let (_, s) = sem(&file(METRE, &w)); + assert_eq!(s.kept_reasons.get("IfcWall").and_then(|m| m.get("slopedTop")), Some(&1)); + } + + #[test] + fn straight_stair_from_ifc_stair() { + // 6 Klötze à 0.175 × 0.28, Breite 1.1, Lauf in +x ab x = 1; 7. Steigung führt aufs OG? Nein: OG + // liegt auf 3.0, oberster Tritt 1.05 → Austritt kommt dazu (7 Steigungen). + let mut faces = Vec::new(); + for i in 0..6 { + let (x0, x1) = (1.0 + 0.28 * i as f64, 1.0 + 0.28 * (i + 1) as f64); + let z = 0.175 * (i + 1) as f64; + faces.extend(prism_faces(&[[x0, 2.0], [x1, 2.0], [x1, 3.1], [x0, 3.1]], 0.0, |_, _| z)); + } + let st = brep_product(100, "IFCSTAIR", &faces, "$"); + let (r, s) = sem(&file(METRE, &st)); + assert_eq!(s.stairs.len(), 1, "{:?}", s.kept_reasons); + let t = &s.stairs[0]; + assert!(close2(t.start, [1.0, 2.55]) && close2(t.dir, [1.0, 0.0]) && close(t.width, 1.1), "{t:?}"); + // Oberster Tritt ist die höchste Stelle des Körpers → er ist der Austritt (6 Steigungen). + assert_eq!(t.step_count, 6); + assert!(close(t.total_rise, 1.05) && close(t.run_length, 6.0 * 0.28) && close(t.z0, 0.0)); + assert!(r.products.is_empty()); + } + + #[test] + fn arc_wall_round_opening_footprint_space_loose_door() { + // Bogenwand: Viertelring um (0,0), Radien 4.85 … 5.15, 2.5 hoch (Polygon aus 33 Punkten je Bogen). + let mut ring = Vec::new(); + for i in 0..=32 { + let a = std::f64::consts::FRAC_PI_2 * i as f64 / 32.0; + ring.push([5.15 * a.cos(), 5.15 * a.sin()]); + } + for i in (0..=32).rev() { + let a = std::f64::consts::FRAC_PI_2 * i as f64 / 32.0; + ring.push([4.85 * a.cos(), 4.85 * a.sin()]); + } + let arc = brep_product(100, "IFCWALL", &prism_faces(&ring, 0.0, |_, _| 2.5), "$"); + let (r, s) = sem(&file(METRE, &arc)); + assert_eq!(s.walls.len(), 1, "{:?}", s.kept_reasons); + let w = &s.walls[0]; + assert!(close(w.thickness, 0.3) && close(w.z1, 2.5)); + let (a, b) = (w.start, w.end); + // Achse R = 5 von (5, 0) nach (0, 5) (oder umgekehrt), Viertelkreis: |bulge| = tan(22.5°). + assert!((close2(a, [5.0, 0.0]) && close2(b, [0.0, 5.0])) || (close2(a, [0.0, 5.0]) && close2(b, [5.0, 0.0])), "{w:?}"); + assert!(close(w.bulge.abs(), (std::f64::consts::PI / 8.0).tan())); + // Scheitel (3.54, 3.54) liegt links der Sehne start → end bei bulge > 0. + let chord = sub2(b, a); + let apex_left = cross2(chord, sub2([5.0 * 0.5f64.sqrt(), 5.0 * 0.5f64.sqrt()], a)) > 0.0; + assert_eq!(apex_left, w.bulge > 0.0); + assert!(r.products.is_empty()); + + // Runde Öffnung (Durchmesser 1, Mitte auf 1.5 m) in einer geraden Wand. + let wall = rect_product(200, "IFCWALL", (0.0, 0.0, 0.0), (1.0, 0.0), (4.0, 0.3), 2.5, ""); + let round = "#501=IFCCARTESIANPOINT((2.,0.4,1.5));#502=IFCDIRECTION((0.,-1.,0.));#503=IFCAXIS2PLACEMENT3D(#501,#502,#12);\ +#504=IFCLOCALPLACEMENT(#22,#503);#505=IFCCIRCLEPROFILEDEF(.AREA.,$,$,0.5);#506=IFCEXTRUDEDAREASOLID(#505,#13,#11,0.8);\ +#507=IFCSHAPEREPRESENTATION($,'Body','SweptSolid',(#506));#508=IFCPRODUCTDEFINITIONSHAPE($,$,(#507));\ +#500=IFCOPENINGELEMENT('o',$,$,$,$,#504,#508,$,.OPENING.);#509=IFCRELVOIDSELEMENT('v',$,$,$,#200,#500);"; + let (_, s) = sem(&file(METRE, &format!("{wall}{round}"))); + assert_eq!((s.walls.len(), s.openings.len()), (1, 1), "{:?}", s.kept_reasons); + let o = &s.openings[0]; + assert_eq!((o.kind, o.shape), (OpeningKind::Hole, Some("rund"))); + assert!((o.width - 1.0).abs() < 0.01 && (o.height - 1.0).abs() < 0.01 && (o.sill - 1.0).abs() < 0.01, "{o:?}"); + + // Raum nur mit „FootPrint" + „Box" (ArchiCAD IFC2x3), in mm. + let space = "#601=IFCCARTESIANPOINT((0.,0.));#602=IFCCARTESIANPOINT((3000.,0.));#603=IFCCARTESIANPOINT((3000.,2000.));\ +#604=IFCCARTESIANPOINT((1000.,2000.));#605=IFCCARTESIANPOINT((0.,1000.));#606=IFCPOLYLINE((#601,#602,#603,#604,#605,#601));\ +#607=IFCGEOMETRICCURVESET((#606));#608=IFCSHAPEREPRESENTATION($,'FootPrint','GeometricCurveSet',(#607));\ +#609=IFCCARTESIANPOINT((0.,0.,0.));#610=IFCBOUNDINGBOX(#609,3000.,2000.,2600.);#611=IFCSHAPEREPRESENTATION($,'Box','BoundingBox',(#610));\ +#612=IFCPRODUCTDEFINITIONSHAPE($,$,(#611,#608));#613=IFCCARTESIANPOINT((1000.,500.,0.));#614=IFCAXIS2PLACEMENT3D(#613,$,$);\ +#615=IFCLOCALPLACEMENT(#22,#614);#600=IFCSPACE('sp',$,'0.01',$,$,#615,#612,'Bad',.ELEMENT.,.INTERNAL.,$);\ +#616=IFCRELAGGREGATES('as',$,$,$,#23,(#600));"; + let (_, s) = sem(&file(MILLI, space)); + assert_eq!(s.spaces.len(), 1, "{:?}", s.kept_reasons); + let sp = &s.spaces[0]; + assert!(close(area2(&sp.boundary), 5.5) && close(sp.z1 - sp.z0, 2.6) && close2(sp.boundary[0], [1.0, 0.5]), "{sp:?}"); + + // Tür ohne Öffnungsbeziehung, Loch schon im Wandkörper (Wand 4 × 0.3 × 2.5, Loch x ∈ [1, 2], z ≤ 2). + let mut faces = prism_faces(&[[0.0, 0.0], [1.0, 0.0], [1.0, 0.3], [0.0, 0.3]], 0.0, |_, _| 2.5); + faces.extend(prism_faces(&[[2.0, 0.0], [4.0, 0.0], [4.0, 0.3], [2.0, 0.3]], 0.0, |_, _| 2.5)); + faces.extend(prism_faces(&[[1.0, 0.0], [2.0, 0.0], [2.0, 0.3], [1.0, 0.3]], 2.0, |_, _| 2.5)); + let holed = brep_product(300, "IFCWALL", &faces, "$"); + let door = brep_product(400, "IFCDOOR", &prism_faces(&[[1.0, 0.1], [2.0, 0.1], [2.0, 0.2], [1.0, 0.2]], 0.0, |_, _| 2.0), "$,$,$,$,$"); + let (r, s) = sem(&file(METRE, &format!("{holed}{door}"))); + assert_eq!((s.walls.len(), s.openings.len()), (1, 1), "{:?}", s.kept_reasons); + let o = &s.openings[0]; + assert_eq!(o.kind, OpeningKind::Door); + assert!(close(o.width, 1.0) && close(o.height, 2.0) && close(o.sill, 0.0), "{o:?}"); + assert!(r.products.is_empty(), "{:?}", r.products.iter().map(|p| &p.class).collect::>()); + } + + #[test] + fn map_conversion_is_read() { + let geo = "#700=IFCPROJECTEDCRS('EPSG:2056',$,$,$,$,$,#701);#701=IFCSIUNIT(*,.LENGTHUNIT.,$,.METRE.);\ +#702=IFCMAPCONVERSION(#5,#700,2600000.,1200000.,400.,0.,1.,$);"; + let col = rect_product(40, "IFCCOLUMN", (1.0, 1.0, 0.0), (1.0, 0.0), (0.4, 0.4), 2.75, ""); + let (r, _) = sem(&file(METRE, &format!("{col}{geo}"))); + let m = r.map_conversion.expect("Georeferenz"); + assert_eq!((m.eastings, m.northings, m.height, m.x_axis, m.scale, m.crs.as_deref()), (2600000.0, 1200000.0, 400.0, [0.0, 1.0], 1.0, Some("EPSG:2056"))); + let (r, _) = sem(&file(METRE, &col)); + assert!(r.map_conversion.is_none()); + } + + #[test] + fn slab_from_mesh_with_t_junctions() { + // Decke 4 × 2, 0.2 dick: Oberseite aus zwei Dreiecken links und vier rechts (T-Stoss bei x = 2, + // y = 1 auf der langen Diagonale gibt es nicht, aber auf der Kante x = 2). + let top = vec![ + vec![[0.0, 0.0, 3.0], [2.0, 0.0, 3.0], [2.0, 2.0, 3.0]], + vec![[0.0, 0.0, 3.0], [2.0, 2.0, 3.0], [0.0, 2.0, 3.0]], + vec![[2.0, 0.0, 3.0], [4.0, 0.0, 3.0], [2.0, 1.0, 3.0]], + vec![[4.0, 0.0, 3.0], [4.0, 2.0, 3.0], [2.0, 1.0, 3.0]], + vec![[4.0, 2.0, 3.0], [2.0, 2.0, 3.0], [2.0, 1.0, 3.0]], + ]; + let mut faces = top; + let ring = [[0.0, 0.0], [4.0, 0.0], [4.0, 2.0], [0.0, 2.0]]; + faces.push(ring.iter().rev().map(|p| [p[0], p[1], 2.8]).collect()); + for i in 0..4 { + let (a, b) = (ring[i], ring[(i + 1) % 4]); + faces.push(vec![[a[0], a[1], 2.8], [b[0], b[1], 2.8], [b[0], b[1], 3.0], [a[0], a[1], 3.0]]); + } + let slab = brep_product(100, "IFCSLAB", &faces, ".FLOOR."); + let (_, s) = sem(&file(METRE, &slab)); + assert_eq!(s.slabs.len(), 1, "{:?}", s.kept_reasons); + assert_eq!(s.slabs[0].outline.len(), 4); + assert!(close(area2(&s.slabs[0].outline), 8.0)); + } + + /// Freie Beispieldateien (ArchiCAD/Vectorworks-Exporte …), nur wenn `DOSSIER_IFC_ELEMENT_SAMPLES` auf + /// ein Verzeichnis zeigt: je Datei erkannte Bauteile, als Mesh gebliebene Kandidaten mit Grund und + /// übrige Meshes je Klasse (Ausgabe mit `--nocapture`). Prüft nur, dass nichts scheitert. + #[test] + fn element_samples_if_present() { + let Ok(dir) = std::env::var("DOSSIER_IFC_ELEMENT_SAMPLES") else { return }; + let mut files: Vec<_> = std::fs::read_dir(&dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("ifc"))).collect(); + files.sort(); + for f in files { + let t = std::time::Instant::now(); + let r = import_ifc_opts(&std::fs::read(&f).unwrap(), true).unwrap_or_else(|e| panic!("{}: {e}", f.display())); + let s = r.elements.as_ref().unwrap(); + let mut meshes: BTreeMap<&str, usize> = BTreeMap::new(); + for p in &r.products { + *meshes.entry(p.class.as_str()).or_insert(0) += 1; + } + eprintln!( + "== {} ({}, {:.1}s{})\n Geschosse {} · Wände {} · Öffnungen {} · Decken {} · Stützen {} · Räume {} · Dächer {} · Treppen {}\n als Mesh behalten (Grund): {:?}\n Meshes je Klasse: {:?}", + f.file_name().unwrap().to_string_lossy(), r.schema, t.elapsed().as_secs_f64(), if r.truncated { ", abgebrochen" } else { "" }, + s.storeys.len(), s.walls.len(), s.openings.len(), s.slabs.len(), s.columns.len(), s.spaces.len(), s.roofs.len(), s.stairs.len(), + s.kept_reasons, meshes + ); + } + } } diff --git a/src-tauri/fileio/src/ifc_shapes.rs b/src-tauri/fileio/src/ifc_shapes.rs new file mode 100644 index 00000000..7fc2f457 --- /dev/null +++ b/src-tauri/fileio/src/ifc_shapes.rs @@ -0,0 +1,548 @@ +// IFC-Import zu Bauteilen ([B4]): Formerkennung für Dächer, Treppen und Bogenwände aus Dreiecksnetzen +// (Weltkoordinaten, Meter, z = Höhe). Wird von `ifc_semantic.rs` benutzt; hier nur Geometrie, keine +// IFC-Beziehungen. +// +// Eigener Code. +// - Dach: Dachflächen = nach oben zeigende Dreiecke, nach Ebene gruppiert (je Normale die oberste; +// Schicht-Körper übereinander zählen einmal). Grundriss = achsparalleles Rechteck, ganz bedeckt; +// Form nach Zahl und Richtung der Flächen: 1 waagrecht = Flach, 1 geneigt = Pult (steigt nach +x/+y, +// wie das Dossier-Pultdach), 2 gegenläufig = Sattel, 4 = Walm; alle gleich geneigt. Jeder Punkt +// der Dachflächen muss auf der Dossier-Dachfläche liegen (±3 cm), sonst kein Dach. +// - Treppe: gerader Lauf — Trittflächen (waagrechte Oberseiten) in gleichen Höhenschritten, deren +// Vorderkanten linear entlang der Laufrichtung fortschreiten. +// - Bogenwand: senkrechtes Prisma, Umriss auf zwei konzentrischen Kreisen (Ringausschnitt). +// +// Unsinn ergibt `Err(Grund)`, nie Panic. + +use crate::ifc_import::{Mesh, V2, V3}; + +/// Grund: Dachform nicht abbildbar. +pub(crate) const R_ROOF_FORM: &str = "roofForm"; +/// Grund: Treppe nicht gerade/gleichmässig. +pub(crate) const R_STAIR_FORM: &str = "stairForm"; + +fn sub3(a: V3, b: V3) -> V3 { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} +fn cross3(a: V3, b: V3) -> V3 { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} +fn dot3(a: V3, b: V3) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +/// Dreiecke eines Netzes: (Eckpunkte, Einheitsnormale, Fläche); entartete ausgelassen. +pub(crate) fn triangles(m: &Mesh) -> Vec<([V3; 3], V3, f64)> { + let p = |i: u32| -> Option { + let k = i as usize * 3; + m.positions.get(k..k + 3).map(|s| [s[0], s[1], s[2]]) + }; + let mut out = Vec::with_capacity(m.indices.len() / 3); + for t in m.indices.chunks_exact(3) { + let (Some(a), Some(b), Some(c)) = (p(t[0]), p(t[1]), p(t[2])) else { continue }; + let n = cross3(sub3(b, a), sub3(c, a)); + let l = dot3(n, n).sqrt(); + if !(l.is_finite() && l > 1e-12) || !a.iter().chain(&b).chain(&c).all(|x| x.is_finite()) { + continue; + } + out.push(([a, b, c], [n[0] / l, n[1] / l, n[2] / l], l / 2.0)); + } + out +} + +/// Ebene aus gleich orientierten Dreiecken. +struct Plane { + n: V3, + d: f64, + area: f64, + pts: Vec, +} + +/// Gruppiert Dreiecke nach Ebene (Normale ±0.8°, Abstand ±5 mm). +fn planes(tris: &[&([V3; 3], V3, f64)]) -> Vec { + let mut out: Vec = Vec::new(); + for (pts, n, a) in tris.iter().map(|t| (&t.0, t.1, t.2)) { + let c = [(pts[0][0] + pts[1][0] + pts[2][0]) / 3.0, (pts[0][1] + pts[1][1] + pts[2][1]) / 3.0, (pts[0][2] + pts[1][2] + pts[2][2]) / 3.0]; + let d = dot3(n, c); + match out.iter_mut().find(|p| dot3(p.n, n) > 0.9999 && (p.d - d).abs() <= 0.005) { + Some(p) => { + p.area += a; + p.pts.extend_from_slice(pts); + } + None => out.push(Plane { n, d, area: a, pts: pts.to_vec() }), + } + if out.len() > 4000 { + break; + } + } + out +} + +/// Erkanntes Dach (Dossier-Parameter, Überstand 0: der Umriss ist schon die Traufe). +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct RoofFit { + /// x0, y0, x1, y1. + pub bbox: [f64; 4], + pub shape: &'static str, + pub pitch_deg: f64, + pub ridge_axis: &'static str, + pub eave_z: f64, + /// Dicke senkrecht zur Dachfläche. + pub thickness: f64, +} + +impl RoofFit { + /// Höhe der Dach-Oberseite im Grundrisspunkt (Dossier-Dachfläche, ohne Grenze auf den Umriss). + pub fn top_at(&self, x: f64, y: f64) -> f64 { + let [x0, y0, x1, y1] = self.bbox; + // Im Kanon läuft der First entlang u; v quer dazu. + let (u, v, u0, u1, v0, v1) = if self.ridge_axis == "x" { (x, y, x0, x1, y0, y1) } else { (y, x, y0, y1, x0, x1) }; + let tan = (self.pitch_deg.to_radians()).tan(); + let rise = match self.shape { + "pult" => v - v0, + "sattel" => (v - v0).min(v1 - v), + "walm" => (v - v0).min(v1 - v).min(u - u0).min(u1 - u), + _ => 0.0, + }; + self.eave_z + rise * tan + } + + /// Dach-Unterkante im Grundrisspunkt; `None` ausserhalb. + pub fn underside_at(&self, x: f64, y: f64) -> Option { + let [x0, y0, x1, y1] = self.bbox; + if !(x >= x0 - 1e-6 && x <= x1 + 1e-6 && y >= y0 - 1e-6 && y <= y1 + 1e-6) { + return None; + } + Some(self.top_at(x, y) - self.thickness / self.pitch_deg.to_radians().cos().max(0.05)) + } +} + +/// Dach aus den Körpern seiner Teile. +pub(crate) fn fit_roof(meshes: &[Mesh]) -> Result { + let tris: Vec<_> = meshes.iter().flat_map(triangles).collect(); + let up: Vec<_> = tris.iter().filter(|t| t.1[2] > 0.08).collect(); + let down: Vec<_> = tris.iter().filter(|t| t.1[2] < -0.08).collect(); + if up.is_empty() || down.is_empty() { + return Err(R_ROOF_FORM); + } + let top_all = planes(&up); + let bottom = planes(&down); + let largest = top_all.iter().map(|p| p.area).fold(0.0, f64::max); + // Je Richtung nur die oberste Ebene (Schicht-Körper übereinander), kleine Flächen (Firstabdeckung, + // rechtwinklige Stirnschnitte der Platten) nicht. + let mut top: Vec<&Plane> = Vec::new(); + for p in top_all.iter().filter(|p| p.area >= 0.1 * largest) { + match top.iter_mut().find(|q| dot3(q.n, p.n) > 0.9999) { + Some(q) => { + if p.d > q.d { + *q = p; + } + } + None => top.push(p), + } + } + #[cfg(test)] + if std::env::var("DOSSIER_IFC_DEBUG").is_ok() { + let pr: f64 = top.iter().map(|p| p.area * p.n[2]).sum(); + let (mut b0, mut b1) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]); + for q in top.iter().flat_map(|p| p.pts.iter()) { + for k in 0..3 { + b0[k] = b0[k].min(q[k]); + b1[k] = b1[k].max(q[k]); + } + } + eprintln!( + "Dach: {} Flächen oben (alle {}), proj {pr:.2} bbox {:.2}×{:.2} z {:.2}..{:.2}, Normalen {:?}", + top.len(), + top_all.len(), + b1[0] - b0[0], + b1[1] - b0[1], + b0[2], + b1[2], + top.iter().map(|p| ([p.n[0] as f32, p.n[1] as f32, p.n[2] as f32], p.area as f32)).collect::>() + ); + } + if top.is_empty() || top.len() > 4 { + return Err(R_ROOF_FORM); + } + let pts: Vec = top.iter().flat_map(|p| p.pts.iter().copied()).collect(); + let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + let mut eave_z = f64::INFINITY; + for q in &pts { + x0 = x0.min(q[0]); + y0 = y0.min(q[1]); + x1 = x1.max(q[0]); + y1 = y1.max(q[1]); + eave_z = eave_z.min(q[2]); + } + let box_area = (x1 - x0) * (y1 - y0); + // Projizierte Fläche der Dachflächen = Rechteck (achsparallel, ganz bedeckt, keine Doppelung). + let projected: f64 = top.iter().map(|p| p.area * p.n[2]).sum(); + if !(box_area > 0.01 && (projected - box_area).abs() <= 0.03 * box_area) { + return Err(R_ROOF_FORM); + } + let pitch = |p: &Plane| p.n[2].clamp(-1.0, 1.0).acos().to_degrees(); + let pitch_deg = pitch(top[0]); + if top.iter().any(|p| (pitch(p) - pitch_deg).abs() > 0.3) { + return Err(R_ROOF_FORM); + } + // Steigrichtung je Fläche (gegen die waagrechte Normale): 0 = +x, 1 = −x, 2 = +y, 3 = −y. + let flat = pitch_deg < 0.3; + let mut dirs = Vec::new(); + if !flat { + for p in &top { + let (hx, hy) = (-p.n[0], -p.n[1]); + let l = hx.hypot(hy); + let (hx, hy) = (hx / l, hy / l); + let k = if hx > 0.9995 { + 0 + } else if hx < -0.9995 { + 1 + } else if hy > 0.9995 { + 2 + } else if hy < -0.9995 { + 3 + } else { + return Err(R_ROOF_FORM); + }; + if dirs.contains(&k) { + return Err(R_ROOF_FORM); + } + dirs.push(k); + } + dirs.sort_unstable(); + } + let longer_x = x1 - x0 >= y1 - y0; + let (shape, ridge_axis, pitch_deg) = match (flat, dirs.as_slice()) { + (true, _) if top.len() == 1 => ("flach", if longer_x { "x" } else { "y" }, 0.0), + (false, [2]) => ("pult", "x", pitch_deg), + (false, [0]) => ("pult", "y", pitch_deg), + (false, [2, 3]) => ("sattel", "x", pitch_deg), + (false, [0, 1]) => ("sattel", "y", pitch_deg), + (false, [0, 1, 2, 3]) => ("walm", if longer_x { "x" } else { "y" }, pitch_deg), + _ => return Err(R_ROOF_FORM), + }; + // Dicke: Abstand zur untersten Gegenfläche der grössten Dachfläche. + let main = top.iter().max_by(|a, b| a.area.total_cmp(&b.area)).ok_or(R_ROOF_FORM)?; + let thickness = bottom.iter().filter(|b| dot3(b.n, main.n) < -0.9999).map(|b| main.d + b.d).fold(f64::NAN, f64::max); + if !(thickness > 0.01 && thickness <= 2.0) { + return Err(R_ROOF_FORM); + } + let fit = RoofFit { bbox: [x0, y0, x1, y1], shape, pitch_deg, ridge_axis, eave_z, thickness }; + if pts.iter().any(|q| (q[2] - fit.top_at(q[0], q[1])).abs() > 0.03) { + return Err(R_ROOF_FORM); + } + Ok(fit) +} + +/// Volumen eines senkrechten Quaders über dem Rechteck (Ursprung `o`, Richtung `d`, Länge `len`, Dicke +/// `t` symmetrisch zur Achse), unten `z0`, oben `z1`, von den Dächern auf ihre Unterkante gekappt +/// (numerisch, 64 × 4 Stützstellen). So schneidet Dossier eine Wand mit Dachanschluss. +pub(crate) fn capped_volume(o: V2, d: V2, len: f64, t: f64, z0: f64, z1: f64, roofs: &[RoofFit]) -> f64 { + let (nu, nv) = (64, 4); + let n = [-d[1], d[0]]; + let mut sum = 0.0; + for i in 0..nu { + let u = (i as f64 + 0.5) / nu as f64 * len; + for j in 0..nv { + let v = ((j as f64 + 0.5) / nv as f64 - 0.5) * t; + let (x, y) = (o[0] + d[0] * u + n[0] * v, o[1] + d[1] * u + n[1] * v); + let cap = roofs.iter().filter_map(|r| r.underside_at(x, y)).fold(z1, f64::min); + sum += (cap - z0).max(0.0); + } + } + sum / (nu * nv) as f64 * len * t +} + +/// Erkannte gerade Treppe. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct StairFit { + /// Mitte der ersten Setzstufe (Antritt). + pub start: V2, + pub dir: V2, + pub width: f64, + /// Auftritt (Abstand der Vorderkanten). + pub going: f64, + /// Steigung (Höhe je Stufe). + pub riser: f64, + /// Anzahl Trittflächen im Körper. + pub treads: usize, + /// Antrittshöhe (erster Tritt − Steigung). + pub z0: f64, + /// Der oberste Tritt ist die höchste Stelle des Körpers (Austritt aufs Podest/Geschoss). + pub top_is_exit: bool, +} + +/// Gerade Treppe aus den Körpern ihrer Teile (Läufe, Wangen …). +pub(crate) fn fit_stair(meshes: &[Mesh]) -> Result { + let tris: Vec<_> = meshes.iter().flat_map(triangles).collect(); + let mut plan: Vec = Vec::new(); + let (mut z0, mut z1) = (f64::INFINITY, f64::NEG_INFINITY); + for t in &tris { + for p in &t.0 { + plan.push([p[0], p[1]]); + z0 = z0.min(p[2]); + z1 = z1.max(p[2]); + } + } + let (d, u0, u1, v0, v1) = crate::ifc_semantic::min_area_rect(&plan).ok_or(R_STAIR_FORM)?; + // Trittflächen: waagrechte Oberseiten, nach Höhe gruppiert (±5 mm), je Höhe die u-Ausdehnung. + let n = [-d[1], d[0]]; + let mut levels: Vec<(f64, f64, f64, f64)> = Vec::new(); // (z, umin, umax, Fläche) + for (pts, nrm, a) in tris.iter().filter(|t| t.1[2] > 0.999) { + let _ = nrm; + let z = (pts[0][2] + pts[1][2] + pts[2][2]) / 3.0; + let us = pts.iter().map(|p| p[0] * d[0] + p[1] * d[1]); + let (lo, hi) = us.fold((f64::INFINITY, f64::NEG_INFINITY), |(l, h), u| (l.min(u), h.max(u))); + match levels.iter_mut().find(|l| (l.0 - z).abs() <= 0.005) { + Some(l) => { + l.1 = l.1.min(lo); + l.2 = l.2.max(hi); + l.3 += a; + } + None => levels.push((z, lo, hi, *a)), + } + if levels.len() > 400 { + return Err(R_STAIR_FORM); + } + } + let width = v1 - v0; + // Nur Flächen, die über die Laufbreite reichen (keine Handlauf-Oberseiten, Wangenköpfe). + #[cfg(test)] + if std::env::var("DOSSIER_IFC_DEBUG").is_ok() { + let mut l = levels.clone(); + l.sort_by(|a, b| a.0.total_cmp(&b.0)); + eprintln!("Treppe z0 {z0:.3} z1 {z1:.3} Breite {width:.3} Länge {:.3} Ebenen {:?}", u1 - u0, l.iter().map(|x| ((x.0 - z0) as f32, (x.1 - u0) as f32, (x.2 - u0) as f32, x.3 as f32)).collect::>()); + } + levels.retain(|l| l.3 >= 0.06 * width && l.0 > z0 + 0.02); + levels.sort_by(|a, b| a.0.total_cmp(&b.0)); + // Belag über dem Rohbau (zwei Flächen wenige cm übereinander): die obere zählt. + let mut merged: Vec<(f64, f64, f64, f64)> = Vec::new(); + for l in levels { + match merged.last_mut() { + Some(m) if l.0 - m.0 < 0.08 => *m = l, + _ => merged.push(l), + } + } + let levels = merged; + if levels.len() < 2 || !(0.4..=6.0).contains(&width) { + return Err(R_STAIR_FORM); + } + let k = levels.len(); + let mut diffs: Vec = levels.windows(2).map(|w| w[1].0 - w[0].0).collect(); + diffs.sort_by(f64::total_cmp); + let riser = diffs[diffs.len() / 2]; + if !(0.1..=0.25).contains(&riser) { + return Err(R_STAIR_FORM); + } + // Gleichmässige Steigung und Vorderkanten linear in der Stufennummer (aufwärts entlang +d oder −d). + for (i, l) in levels.iter().enumerate() { + if (l.0 - (levels[0].0 + riser * i as f64)).abs() > 0.01 { + return Err(R_STAIR_FORM); + } + } + // Genauer als der Median: Mittel über den ganzen Lauf. + let riser = (levels[k - 1].0 - levels[0].0) / (k - 1) as f64; + let top_is_exit = (z1 - levels[k - 1].0).abs() <= 0.03; + let z0 = levels[0].0 - riser; + let up = levels[k - 1].1 + levels[k - 1].2 > levels[0].1 + levels[0].2; + // Vorderkante: bei Lauf in +d das untere u-Ende, sonst das obere. + let front = |l: &(f64, f64, f64, f64)| if up { l.1 } else { -l.2 }; + let going = (front(&levels[k - 1]) - front(&levels[0])) / (k - 1) as f64; + if !(0.15..=0.45).contains(&going) { + return Err(R_STAIR_FORM); + } + for (i, l) in levels.iter().enumerate() { + if (front(l) - (front(&levels[0]) + going * i as f64)).abs() > 0.03 { + return Err(R_STAIR_FORM); + } + } + // Antritt = Vorderkante des ersten Tritts (Dossier: Tritt i über [i·a, (i+1)·a], Oberkante (i+1)·h). + let dir = if up { d } else { [-d[0], -d[1]] }; + let s_world = if up { front(&levels[0]) } else { -front(&levels[0]) }; + if s_world < u0 - 0.05 || s_world > u1 + 0.05 { + return Err(R_STAIR_FORM); + } + let vc = (v0 + v1) / 2.0; + let start = [d[0] * s_world + n[0] * vc, d[1] * s_world + n[1] * vc]; + Ok(StairFit { start, dir, width, going, riser, treads: k, z0, top_is_exit }) +} + +/// Bogen einer Bogenwand: Achse (Mitte der Dicke) von `start` nach `end` gegen den Uhrzeigersinn um +/// `center`. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct ArcFit { + pub center: V2, + pub radius: f64, + pub thickness: f64, + /// Winkel (rad) von Start und Ende, `a1 > a0`. + pub a0: f64, + pub a1: f64, +} + +/// Ringausschnitt: Umriss (aussen) einer senkrechten Prisma-Wand auf zwei konzentrischen Kreisen. +pub(crate) fn fit_arc_ring(ring: &[V2]) -> Option { + let n = ring.len(); + if n < 8 { + return None; + } + // Mittelpunkt: häufigster Umkreismittelpunkt dreier aufeinanderfolgender Punkte (Raster 1 mm). + let mut votes: std::collections::HashMap<(i64, i64), (usize, V2)> = std::collections::HashMap::new(); + for i in 0..n { + let (a, b, c) = (ring[i], ring[(i + 1) % n], ring[(i + 2) % n]); + let dd = 2.0 * (a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1])); + if dd.abs() < 1e-12 { + continue; + } + let (a2, b2, c2) = (a[0] * a[0] + a[1] * a[1], b[0] * b[0] + b[1] * b[1], c[0] * c[0] + c[1] * c[1]); + let cx = (a2 * (b[1] - c[1]) + b2 * (c[1] - a[1]) + c2 * (a[1] - b[1])) / dd; + let cy = (a2 * (c[0] - b[0]) + b2 * (a[0] - c[0]) + c2 * (b[0] - a[0])) / dd; + if !(cx.is_finite() && cy.is_finite()) { + continue; + } + let e = votes.entry(((cx * 1000.0).round() as i64, (cy * 1000.0).round() as i64)).or_insert((0, [cx, cy])); + e.0 += 1; + } + let (count, center) = votes.values().max_by(|a, b| a.0.cmp(&b.0).then(b.1[0].total_cmp(&a.1[0])).then(b.1[1].total_cmp(&a.1[1])))?.to_owned(); + if count < n / 3 { + return None; + } + let rs: Vec = ring.iter().map(|p| (p[0] - center[0]).hypot(p[1] - center[1])).collect(); + let r_in = rs.iter().copied().fold(f64::INFINITY, f64::min); + let r_out = rs.iter().copied().fold(0.0, f64::max); + let t = r_out - r_in; + if !(t >= 0.01 && t <= 2.0 && r_in > 0.05) || rs.iter().any(|r| (r - r_in).abs() > 0.002 && (r - r_out).abs() > 0.002) { + return None; + } + // Winkelbereich: grösste Lücke zwischen den sortierten Winkeln liegt ausserhalb der Wand. + let mut ang: Vec = ring.iter().map(|p| (p[1] - center[1]).atan2(p[0] - center[0])).collect(); + ang.sort_by(f64::total_cmp); + let mut gap = (ang[0] + std::f64::consts::TAU - ang[ang.len() - 1], ang.len() - 1); + for i in 0..ang.len() - 1 { + if ang[i + 1] - ang[i] > gap.0 { + gap = (ang[i + 1] - ang[i], i); + } + } + let a0 = ang[(gap.1 + 1) % ang.len()]; + let mut a1 = ang[gap.1]; + while a1 <= a0 { + a1 += std::f64::consts::TAU; + } + let sweep = a1 - a0; + if !(sweep > 0.05 && sweep < std::f64::consts::TAU - 0.05) { + return None; + } + Some(ArcFit { center, radius: (r_in + r_out) / 2.0, thickness: t, a0, a1 }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn quad(m: &mut Mesh, p: [V3; 4]) { + let b = m.positions.len() as u32 / 3; + for q in p { + m.positions.extend_from_slice(&q); + } + m.indices.extend_from_slice(&[b, b + 1, b + 2, b, b + 2, b + 3]); + } + + /// Geneigte Platte über [x0,x1] × [ya,yb], Oberseite von za (bei ya) nach zb (bei yb), Dicke + /// senkrecht `t` (Unterseite parallel), Stirnseiten senkrecht. + fn plate(x0: f64, x1: f64, ya: f64, yb: f64, za: f64, zb: f64, t: f64) -> Mesh { + let mut m = Mesh::default(); + let (dy, dz) = (yb - ya, zb - za); + let l = dy.hypot(dz); + // Normale der Oberseite (zeigt nach oben): (0, −dz, dy)/l bei dy > 0. + let (ny, nz) = (-dz / l * dy.signum(), dy.abs() / l); + let off = |p: V3| [p[0], p[1] - ny * t, p[2] - nz * t]; + let top = [[x0, ya, za], [x1, ya, za], [x1, yb, zb], [x0, yb, zb]]; + let top = if dy > 0.0 { top } else { [top[1], top[0], top[3], top[2]] }; + let bot: Vec = top.iter().map(|p| off(*p)).collect(); + quad(&mut m, top); + quad(&mut m, [bot[3], bot[2], bot[1], bot[0]]); + for i in 0..4 { + let j = (i + 1) % 4; + quad(&mut m, [top[j], top[i], bot[i], bot[j]]); + } + m + } + + #[test] + fn saddle_roof_from_two_plates() { + // Satteldach 10 × 8, First entlang x in y = 4, Traufe z = 3, 30°. + let tan = 30f64.to_radians().tan(); + let a = plate(0.0, 10.0, 0.0, 4.0, 3.0, 3.0 + 4.0 * tan, 0.2); + let b = plate(0.0, 10.0, 8.0, 4.0, 3.0, 3.0 + 4.0 * tan, 0.2); + let f = fit_roof(&[a.clone(), b]).unwrap(); + assert_eq!((f.shape, f.ridge_axis), ("sattel", "x")); + assert!((f.pitch_deg - 30.0).abs() < 1e-6 && (f.eave_z - 3.0).abs() < 1e-9 && (f.thickness - 0.2).abs() < 1e-6, "{f:?}"); + assert_eq!(f.bbox, [0.0, 0.0, 10.0, 8.0]); + assert!((f.top_at(5.0, 4.0) - (3.0 + 4.0 * tan)).abs() < 1e-9); + // Eine Platte allein: Pultdach steigt nach +y. + let p = fit_roof(&[a]).unwrap(); + assert_eq!((p.shape, p.ridge_axis), ("pult", "x")); + // Fallend nach +y kann das Dossier-Pultdach nicht. + let c = plate(0.0, 10.0, 8.0, 4.0, 3.0, 3.0 + 4.0 * tan, 0.2); + assert_eq!(fit_roof(&[c]), Err(R_ROOF_FORM)); + // Ungleiche Neigung: kein Satteldach. + let a = plate(0.0, 10.0, 0.0, 4.0, 3.0, 3.0 + 4.0 * tan, 0.2); + let b = plate(0.0, 10.0, 8.0, 4.0, 3.0, 3.0 + 3.0 * tan, 0.2); + assert!(fit_roof(&[a, b]).is_err()); + } + + #[test] + fn flat_roof_and_capped_wall_volume() { + let mut m = Mesh::default(); + quad(&mut m, [[0.0, 0.0, 3.3], [4.0, 0.0, 3.3], [4.0, 2.0, 3.3], [0.0, 2.0, 3.3]]); + quad(&mut m, [[0.0, 2.0, 3.0], [4.0, 2.0, 3.0], [4.0, 0.0, 3.0], [0.0, 0.0, 3.0]]); + let f = fit_roof(&[m]).unwrap(); + assert_eq!((f.shape, f.ridge_axis, f.pitch_deg), ("flach", "x", 0.0)); + assert!((f.thickness - 0.3).abs() < 1e-9); + // Giebelwand unter Satteldach (Traufe 3, 45°, Dicke 0.2 → Unterkante 3 − 0.2·√2 an der Traufe). + let r = RoofFit { bbox: [0.0, 0.0, 10.0, 8.0], shape: "sattel", pitch_deg: 45.0, ridge_axis: "x", eave_z: 3.0, thickness: 0.2 }; + let u = 3.0 - 0.2 * 2f64.sqrt(); + // Wand in x = 0.1 entlang y, 0 … 8, bis 10 hoch: gekappt auf Dreieck + Rechteck. + let v = capped_volume([0.1, 0.0], [0.0, 1.0], 8.0, 0.2, 0.0, 10.0, &[r]); + let want = (u * 8.0 + 4.0 * 4.0) * 0.2; + assert!((v - want).abs() / want < 0.005, "{v} {want}"); + } + + #[test] + fn straight_stair_from_steps() { + // 5 Stufen à 0.18 × 0.28, 1.0 breit, Lauf in −y ab y = 3; Klötze von z = 0 bis zur Trittfläche. + let mut m = Mesh::default(); + for i in 0..5 { + let (ya, yb) = (3.0 - 0.28 * (i + 1) as f64, 3.0 - 0.28 * i as f64); + let z = 0.18 * (i + 1) as f64; + quad(&mut m, [[2.0, ya, z], [3.0, ya, z], [3.0, yb, z], [2.0, yb, z]]); + quad(&mut m, [[2.0, yb, 0.0], [3.0, yb, 0.0], [3.0, ya, 0.0], [2.0, ya, 0.0]]); + } + let s = fit_stair(&[m]).unwrap(); + assert!((s.going - 0.28).abs() < 1e-9 && (s.riser - 0.18).abs() < 1e-9 && s.treads == 5, "{s:?}"); + assert!((s.dir[0]).abs() < 1e-9 && (s.dir[1] + 1.0).abs() < 1e-9); + // Antritt = Vorderkante des ersten Tritts (Dossier: Tritt i über [i·a, (i+1)·a]). + assert!((s.start[0] - 2.5).abs() < 1e-9 && (s.start[1] - 3.0).abs() < 1e-9, "{s:?}"); + assert!((s.width - 1.0).abs() < 1e-9); + } + + #[test] + fn arc_ring_center_radius_sweep() { + // Viertelring um (1, 2), Radien 4.9 … 5.1, von 0° bis 90°. + let mut ring = Vec::new(); + for i in 0..=16 { + let a = std::f64::consts::FRAC_PI_2 * i as f64 / 16.0; + ring.push([1.0 + 5.1 * a.cos(), 2.0 + 5.1 * a.sin()]); + } + for i in (0..=16).rev() { + let a = std::f64::consts::FRAC_PI_2 * i as f64 / 16.0; + ring.push([1.0 + 4.9 * a.cos(), 2.0 + 4.9 * a.sin()]); + } + let f = fit_arc_ring(&ring).unwrap(); + assert!((f.center[0] - 1.0).abs() < 1e-6 && (f.center[1] - 2.0).abs() < 1e-6); + assert!((f.radius - 5.0).abs() < 1e-9 && (f.thickness - 0.2).abs() < 1e-9); + assert!(f.a0.abs() < 1e-9 && (f.a1 - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "{f:?}"); + // Rechteck ist kein Ring. + assert!(fit_arc_ring(&[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]).is_none()); + } +} diff --git a/src-tauri/fileio/src/lib.rs b/src-tauri/fileio/src/lib.rs index 7f077471..e8bda97c 100644 --- a/src-tauri/fileio/src/lib.rs +++ b/src-tauri/fileio/src/lib.rs @@ -24,6 +24,7 @@ mod web_pointcloud; pub mod ifc_step; pub mod ifc_import; pub mod ifc_semantic; +mod ifc_shapes; pub mod ifc_export; pub mod ifc_openings; pub mod mesh_export; diff --git a/src/App.tsx b/src/App.tsx index fc2048b6..f582ab56 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -48,8 +48,8 @@ import { RecoverAutosaveDialog } from "./ui/RecoverAutosaveDialog"; import { Toast } from "./ui/Toast"; import { isTauriRuntime, PROJECT_TEMPLATE_EXT } from "./native/projectFile"; import { readStepFlat } from "./engine/truckSolid"; -import { formatIfcElementsSummary, formatIfcReport, readIfcFlat } from "./io/ifcImport"; -import { IfcImportDialog, type IfcImportMode } from "./ui/IfcImportDialog"; +import { formatIfcElementsSummary, formatIfcReport, readIfcFlat, type IfcElementsSummary } from "./io/ifcImport"; +import { IfcImportDialog, IfcImportReportDialog, type IfcImportMode } from "./ui/IfcImportDialog"; import { MeshImportHost } from "./ui/MeshImportDialog"; import { openMeshFileDialog, requestMeshImport, splitMeshFiles } from "./state/meshImportStore"; import { formatMeshReport, isMeshFile, type MeshPlacement, type MeshRead } from "./io/meshImport"; @@ -1050,6 +1050,8 @@ export default function App() { // IFC-Import: erst die Wahl Mesh/Bauteile (`IfcImportDialog`), dann liest das Format-Modul (Web-Worker) und der // Kern übernimmt [B3] Kontext-Meshes oder [B4] echte Bauteile als EINEN Undo-Schritt ([K4] S4, `importIfc`). const [pendingIfc, setPendingIfc] = useState(null); + // Bericht nach dem Bauteil-Import ([B4]): erkannt je Bauteilart, als Mesh geblieben mit Grund. + const [ifcReport, setIfcReport] = useState<{ fileName: string; summary: IfcElementsSummary } | null>(null); const importIfcFile = (f: File) => setPendingIfc(f); const runIfcImport = (f: File, mode: IfcImportMode) => { const elements = mode === "elements"; @@ -1066,6 +1068,7 @@ export default function App() { const s = r.summary; const empty = s.walls + s.ceilings + s.columns + s.rooms + s.meshes === 0; notify(formatIfcElementsSummary(s, report, t), empty || report.truncated ? "warning" : "info"); + setIfcReport({ fileName: f.name, summary: s }); return; } fitToContextObjects(addedItems(r.ops, "context") as ContextObject[]); @@ -2804,6 +2807,10 @@ export default function App() { /> )} + {ifcReport && ( + setIfcReport(null)} /> + )} + {pendingDiscard && ( setPendingDiscard(null)} diff --git a/src/export/exportIfc.classification.test.ts b/src/export/exportIfc.classification.test.ts index 6e85dd1c..b1ff4339 100644 --- a/src/export/exportIfc.classification.test.ts +++ b/src/export/exportIfc.classification.test.ts @@ -105,8 +105,9 @@ describe("Rundreise Export → Import", () => { expect(window.classifications?.map((c) => `${c.system}:${c.code}`).sort()).toEqual(["Dossier-Ebenen:21", "eBKP-H:E"]); const door = raw.find((o) => o.kind === "opening" && o.openingKind === "door")!; expect(door.classifications?.map((c) => c.system)).toEqual(["Dossier-Ebenen"]); - // Dach bleibt Mesh, trägt aber seine Klassifikation. - const roof = products.find((p) => p.ifcClass === "IfcRoof")!; + // Dach wird Bauteil ([B4], 6.11.) und trägt seine Klassifikation. + expect(products.find((p) => p.ifcClass === "IfcRoof")).toBeUndefined(); + const roof = raw.find((e) => e.kind === "roof")!; expect(roof.classifications?.map((c) => c.code).sort()).toEqual(["31", "F"]); // Räume: Kategorie bleibt (auch über die Zone). expect(raw.filter((e) => e.kind === "space").map((s) => s.sia).sort()).toEqual(["HNF", "HNF", "NNF", "VF"]); diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 123b69a8..214cb9a0 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -2455,15 +2455,42 @@ 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.import.elements": "{schema} importiert: {walls} Wände, {openings} Türen/Fenster, {ceilings} Decken, {columns} Stützen, {rooms} Räume, {roofs} Dächer, {stairs} Treppen, {floors} neue Geschosse; {meshes} Bauteile als Kontext-Meshes", + "ifc.import.kept": "{n} Kandidaten (Wände, Decken, Dächer, Treppen …) nicht sicher abbildbar, als Mesh übernommen", "ifc.import.classified": "{n} Bauteile mit Klassifikation (eBKP-H …); bei Kontext-Meshes im Namen vermerkt", "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.asElementsHint": "Wände (auch Bogen- und Giebelwände), Decken, Dächer, gerade Treppen, Stützen, Türen/Fenster, Räume und Geschosse werden bearbeitbare Dossier-Bauteile; was nicht sicher abbildbar ist, bleibt Mesh.", "ifc.importDialog.import": "Importieren", + "ifc.importReport.title": "IFC-Import: Bericht", + "ifc.importReport.recognized": "Als Bauteile übernommen", + "ifc.importReport.kept": "Als Mesh geblieben (Grund)", + "ifc.importReport.keptNone": "Alle Kandidaten wurden Bauteile.", + "ifc.importReport.walls": "Wände", + "ifc.importReport.openings": "Türen, Fenster, Öffnungen", + "ifc.importReport.ceilings": "Decken", + "ifc.importReport.columns": "Stützen", + "ifc.importReport.rooms": "Räume", + "ifc.importReport.roofs": "Dächer", + "ifc.importReport.stairs": "Treppen", + "ifc.importReport.floors": "Neue Geschosse", + "ifc.importReport.types": "Neue Typen (Wand, Decke, Dach, Tür, Fenster)", + "ifc.importReport.meshes": "Übrige Bauteile als Kontext-Mesh", + "ifc.importReport.close": "Schliessen", + "ifc.reason.noBody": "kein lesbarer Körper", + "ifc.reason.shape": "Körper unbrauchbar", + "ifc.reason.dimensions": "Masse ausserhalb des Abbildbaren", + "ifc.reason.notRectangular": "Grundriss weder Rechteck noch Kreisring", + "ifc.reason.slopedTop": "schräge Krone ohne erkanntes Dach darüber", + "ifc.reason.notPrism": "kein senkrechtes Prisma", + "ifc.reason.opening": "Öffnung nicht abbildbar", + "ifc.reason.profile": "Querschnitt weder Rechteck noch Kreis", + "ifc.reason.holes": "Raum mit Loch", + "ifc.reason.part": "Teil eines anderen Bauteils", + "ifc.reason.roofForm": "Dachform nicht Flach/Pult/Sattel/Walm (achsparallel)", + "ifc.reason.stairForm": "keine gerade, gleichmässige Treppe", "menu.native.importMesh": "3D-Modell importieren …", "mesh.import.title": "3D-Modell importieren", "mesh.import.failed": "3D-Modell-Import fehlgeschlagen", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 7dc1df6f..7f7e9489 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -2405,15 +2405,42 @@ 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.import.elements": "{schema} imported: {walls} walls, {openings} doors/windows, {ceilings} slabs, {columns} columns, {rooms} rooms, {roofs} roofs, {stairs} stairs, {floors} new storeys; {meshes} elements as context meshes", + "ifc.import.kept": "{n} candidates (walls, slabs, roofs, stairs …) not safely mappable, kept as mesh", "ifc.import.classified": "{n} elements with a classification (eBKP-H …); noted in the name of context meshes", "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.asElementsHint": "Walls (including curved and gable walls), slabs, roofs, straight stairs, columns, doors/windows, rooms and storeys become editable Dossier elements; anything not safely mappable stays a mesh.", "ifc.importDialog.import": "Import", + "ifc.importReport.title": "IFC import: report", + "ifc.importReport.recognized": "Imported as building elements", + "ifc.importReport.kept": "Kept as mesh (reason)", + "ifc.importReport.keptNone": "All candidates became building elements.", + "ifc.importReport.walls": "Walls", + "ifc.importReport.openings": "Doors, windows, openings", + "ifc.importReport.ceilings": "Slabs", + "ifc.importReport.columns": "Columns", + "ifc.importReport.rooms": "Rooms", + "ifc.importReport.roofs": "Roofs", + "ifc.importReport.stairs": "Stairs", + "ifc.importReport.floors": "New storeys", + "ifc.importReport.types": "New types (wall, slab, roof, door, window)", + "ifc.importReport.meshes": "Other elements as context mesh", + "ifc.importReport.close": "Close", + "ifc.reason.noBody": "no readable body", + "ifc.reason.shape": "body unusable", + "ifc.reason.dimensions": "dimensions out of range", + "ifc.reason.notRectangular": "plan neither rectangle nor ring segment", + "ifc.reason.slopedTop": "sloped top without a recognised roof above", + "ifc.reason.notPrism": "not a vertical prism", + "ifc.reason.opening": "opening not mappable", + "ifc.reason.profile": "cross-section neither rectangle nor circle", + "ifc.reason.holes": "room with a hole", + "ifc.reason.part": "part of another element", + "ifc.reason.roofForm": "roof shape not flat/mono-pitch/gable/hip (axis-aligned)", + "ifc.reason.stairForm": "not a straight, regular stair", "menu.native.importMesh": "Import 3D model …", "mesh.import.title": "Import 3D model", "mesh.import.failed": "3D model import failed", diff --git a/src/io/ifcImport.elements.test.ts b/src/io/ifcImport.elements.test.ts index 3136a9e9..47317753 100644 --- a/src/io/ifcImport.elements.test.ts +++ b/src/io/ifcImport.elements.test.ts @@ -33,9 +33,25 @@ describe("IFC-Import als Bauteile: Rundreise Demo-Haus", () => { 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 Treppenlauf (die IfcStair selbst hat keine Darstellung) bleiben Kontext-Mesh. - expect((p.context ?? []).map((c) => (c as { layer?: string }).layer).sort()).toEqual(["IfcRoof", "IfcStairFlight"]); + // (6.11.) Dach und Treppe kommen als Bauteile zurück, kein Kontext-Mesh mehr. + expect(summary).toMatchObject({ roofs: 1, stairs: 1, roofTypes: 0, doorTypes: 0, windowTypes: 0 }); + expect(p.context ?? []).toEqual([]); expect(validateProject(p)).toEqual([]); + // Satteldach: Umriss = Traufe samt Überstand (0.4), Überstand 0, Traufhöhe = OK OG (5.2), 30°, First x. + const roof = p.roofs![0]; + expect([roof.shape, roof.ridgeAxis, roof.overhang]).toEqual(["sattel", "x", 0]); + expect(roof.pitchDeg).toBeCloseTo(30, 4); + expect(roof.baseElevation!).toBeCloseTo(5.2, 6); + expect(roof.thickness).toBeCloseTo(0.2, 6); + for (const q of [{ x: -0.4, y: -0.4 }, { x: 5.4, y: 4.4 }]) expect(roof.outline.some((g) => near(g, q, 1e-6)), JSON.stringify(roof.outline)).toBe(true); + // Gerade Treppe: gleicher Antritt, Richtung, Breite, Stufen, Steighöhe und Lauflänge. + const st0 = sampleProject.stairs![0]; + const st = p.stairs![0]; + expect([st.shape, st.floorId, st.stepCount]).toEqual(["straight", st0.floorId, st0.stepCount]); + expect(near(st.start, st0.start, 1e-6) && near(st.dir, st0.dir, 1e-9), JSON.stringify(st)).toBe(true); + expect(st.width).toBeCloseTo(st0.width, 6); + expect(st.runLength).toBeCloseTo(st0.runLength, 6); + expect(st.totalRise!).toBeCloseTo(st0.totalRise!, 5); const byOrig = new Map(); for (const w of sampleProject.walls) { diff --git a/src/io/ifcImport.ts b/src/io/ifcImport.ts index b82b3eb6..4937b0a7 100644 --- a/src/io/ifcImport.ts +++ b/src/io/ifcImport.ts @@ -119,10 +119,17 @@ export interface IfcElementsSummary { ceilings: number; columns: number; rooms: number; + /** Dächer (Flach/Pult/Sattel/Walm) und gerade Treppen ([B4]). */ + roofs: number; + stairs: number; /** Neu angelegte Geschosse. */ floors: number; wallTypes: number; ceilingTypes: number; + roofTypes: number; + /** Neue Tür-/Fenstertypen nach dem Typnamen der Datei (IfcDoorType/IfcWindowType). */ + doorTypes: number; + windowTypes: number; components: number; /** Bauteile als Kontext-Mesh. */ meshes: number; @@ -130,6 +137,8 @@ export interface IfcElementsSummary { classified: number; /** Davon Kandidaten, die nicht sicher abbildbar waren. */ kept: number; + /** Je IFC-Klasse die Gründe (Kennwort → Anzahl), weshalb Kandidaten Mesh blieben; Text `ifc.reason.`. */ + keptReasons: Record>; } /** IFC-Import als Ops im Kern ([K4] S4): Antwort von `ProjectDocument.importIfc`. */ @@ -171,6 +180,8 @@ export function formatIfcElementsSummary( ceilings: s.ceilings, columns: s.columns, rooms: s.rooms, + roofs: s.roofs ?? 0, + stairs: s.stairs ?? 0, floors: s.floors, meshes: s.meshes, }), diff --git a/src/ui/IfcImportDialog.tsx b/src/ui/IfcImportDialog.tsx index 1a32bf61..636f7f2b 100644 --- a/src/ui/IfcImportDialog.tsx +++ b/src/ui/IfcImportDialog.tsx @@ -3,6 +3,7 @@ import { useEffect, useState } from "react"; import { t } from "../i18n"; +import type { IfcElementsSummary } from "../io/ifcImport"; export type IfcImportMode = "mesh" | "elements"; @@ -67,3 +68,100 @@ export function IfcImportDialog({ fileName, onImport, onCancel }: IfcImportDialo ); } + +/** Zeilen „erkannt" des Berichts: Zähler aus der Zusammenfassung des Kerns. */ +const RECOGNIZED: ReadonlyArray<[string, (s: IfcElementsSummary) => number]> = [ + ["ifc.importReport.walls", (s) => s.walls], + ["ifc.importReport.openings", (s) => s.openings], + ["ifc.importReport.ceilings", (s) => s.ceilings], + ["ifc.importReport.roofs", (s) => s.roofs ?? 0], + ["ifc.importReport.stairs", (s) => s.stairs ?? 0], + ["ifc.importReport.columns", (s) => s.columns], + ["ifc.importReport.rooms", (s) => s.rooms], + ["ifc.importReport.floors", (s) => s.floors], + [ + "ifc.importReport.types", + (s) => s.wallTypes + s.ceilingTypes + (s.roofTypes ?? 0) + (s.doorTypes ?? 0) + (s.windowTypes ?? 0), + ], + ["ifc.importReport.meshes", (s) => s.meshes], +]; + +/** Bericht nach dem Bauteil-Import ([B4]): was erkannt wurde und was mit welchem Grund Mesh blieb. */ +export function IfcImportReportDialog({ + fileName, + summary, + onClose, +}: { + fileName: string; + summary: IfcElementsSummary; + onClose: () => void; +}) { + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape" || e.key === "Enter") onClose(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [onClose]); + const kept = Object.entries(summary.keptReasons ?? {}).flatMap(([cls, reasons]) => + Object.entries(reasons).map(([why, n]) => ({ cls, why, n })), + ); + return ( +
+
e.stopPropagation()} + > +
+ {t("ifc.importReport.title")} + +
+
+
+
+ {fileName} · {t("ifc.importReport.recognized")} +
+ + + {RECOGNIZED.map(([key, n]) => ( + + + + + ))} + +
{t(key)}{n(summary)}
+
+
+
{t("ifc.importReport.kept")}
+ {kept.length === 0 ? ( +
{t("ifc.importReport.keptNone")}
+ ) : ( + + + {kept.map(({ cls, why, n }) => ( + + + + + + ))} + +
{cls}{t(`ifc.reason.${why}`)}{n}
+ )} +
+
+ +
+
+ ); +}