Alle drei Beispielprojekte (Musterhaus, komplex, Wettbewerb) mit ifcopenshell 0.9 geprüft: validate-ifc.py 0 Befunde und die neue inhaltliche Prüfung scripts/check-ifc-fachplaner.py (Struktur Project → Site → Building → Storey, jedes Bauteil genau einmal eingeordnet, Öffnungen gefüllt und im Geschoss des Wirts, Räume mit Name/Nummer, Pset_SpaceCommon, Qto_SpaceBaseQuantities, SIA-416-Kategorie, Wandschichten, Mengen ±1 % gegen die Geometrie, Georeferenz) als vitest src/export/exportIfc.fachplaner.test.ts. Behoben: - Georeferenz: Geometrie lag in LV95-Millionen (Revit/Archicad warnen); jetzt lokal, IfcMapConversion mit dem LV95-Versatz des Ursprungs und OrthogonalHeight = ±0.00 m ü. M. (referenceElevationMasl, sonst Höhe des Bezugspunkts), gleich IfcSite.RefElevation; IFC2x3 ePSet_MapConversion ebenso. Flache Kodierung Version 5. - Bögen in Decken- und Raumumrissen lagen an der Sehne gespiegelt (Modell: positiv = Scheitel links, Schreiber: DXF-Sinn) und wurden mit nur kartesischer Trimmung von ifcopenshell als Sehne gelesen: Vorzeichen gedreht, Trimmung Punkt + Winkel, massgebend PARAMETER. Erker komplex: Raum 51.5 → 57.4 m² (= Flächenbilanz), Bodenplatte/Decken-Volumen = Menge. - Geschoss-GF war gleich NGF (KGF 0): Mengen jetzt aus der Flächentabelle (GF = NGF + Konstruktionsfläche), dazu GrossHeight/GrossVolume; Summen am Gebäude (Qto_BuildingBaseQuantities, CH_Qto_SIA416). - Wandmengen: Bogenwände (volle Höhe über alle Schichten, 5–23 % zu viel) aus den geschriebenen Profilen bzw. dem dichten Netz; Formöffnungen ziehen den Umriss statt des Rechtecks ab. - Netz-Wände mit mehreren Bändern oder Formöffnungs-Füllkörpern als ein Körper (Manifold); Füllkörper waren verdreht gewickelt; Netze verschweisst (komplex 2.3 → 1.6 MB). Neu: Option „Kontext mitgeben" (Export-Dialog, CLI --kontext, Vorgabe aus): Gelände → IfcGeographicElement TERRAIN, Netze auf Umgebungsklassen → IfcBuildingElementProxy „Kontext", am IfcSite. Entscheid: 2D-Objektbibliothek ([253]) wird nicht exportiert (kein falscher Körper, kein geometrieloses IfcFurniture), Test: Datei mit/ohne Objekte zeichengleich. Grösse/Zeit (Linux-Container unter Last): komplex 1.6 MB / 2.5 s, Wettbewerb 0.9 MB / 0.5 s, sampleProjectBig 19.8 MB / 5.8 s. Offen: nicht in Archicad/Revit/Solibri/BIMcollab geöffnet (Prüfzeile 13.14 in doc/RELEASE-1.0.md); Anbauwand OG Ost im Beispiel komplex (Netz unter dem Pultdach mit Fenster): ifcopenshell scheitert am Abzug der Öffnung (30.4 statt 7.5 m³, in der Prüfung als bekannt markiert). Geprüft: cargo test core (1683+) und fileio (344), tsc, vitest src/export + src/io, Goldens, i18n/Boundary, validate und fachplaner (ifcopenshell). Nur im Linux-Container.
2352 lines
119 KiB
Rust
2352 lines
119 KiB
Rust
//! IFC-Export: Sammler im Kern ([K4] S2, [B5]; vorher `src/export/exportIfc.ts`, `ifcOpenings.ts`,
|
||
//! `ifcClassification.ts`). Liest das Projekt-Dokument und erzeugt den flachen Puffer, den der
|
||
//! Schreiber in `src-tauri/fileio/src/ifc_export/mod.rs` zur STEP-Datei macht (Kodierung dort im Kopf,
|
||
//! FLAT_VERSION 5). TS gibt nur noch Optionen (Schema, Klassifikation) und den Zeitstempel weiter und
|
||
//! reicht die Bytes an `fileio` (zwei WASM-Module, keine gemischten Crates).
|
||
//!
|
||
//! Abbildung (Einzelheiten im Kopf von `ifc_export/mod.rs` und in `TODO.md` [B5]):
|
||
//! • Geschosse: je "floor"-Ebene ein IfcBuildingStorey; Bauteile mit verwaister Geschoss-id hängen
|
||
//! am Gebäude (Struktur −1, Basis 0).
|
||
//! • Wand: Schicht-Bänder wie im 3D (`emit_walls`). Extrusion je Band + IfcOpeningElement, wenn das
|
||
//! exakt dasselbe ergibt wie das 3D (`bands_match_openings`), sonst öffnungsgenaues Netz
|
||
//! (`wall_cut_mesh`, Achsentausch mit Wicklungsumkehr, Closed nach `is_watertight`).
|
||
//! • Decke, Öffnung (Füllungs-Parameter für `ifc_openings.rs`), Treppe (`ifc_stairs.rs`),
|
||
//! Extrusion, Raum (SIA 416), Zonen, Geschoss-Kennwerte, Dach (Schicht-Netze wie im 3D), Stütze.
|
||
//! • Basismengen (`ifc_quantities.rs`), Psets nur mit Modellwerten.
|
||
//! • Klassifikation (Option): eBKP-H-Hauptgruppen je Bauteilart (Quelle CRB, SN 506 511:2020;
|
||
//! Wand/Decke/Stütze/Treppe = C, Dach = F, Fenster = E, Tür und Raum ohne — nicht geraten) und/oder
|
||
//! die Ebene des Modells als System „Dossier-Ebenen" (Code = `categoryCode`, Name = Ebenenname).
|
||
//! Das Modell führt KEINEN eBKP-H-Code; `categoryCode` ist die Grafik-Ebene.
|
||
//! Georeferenz ([259]): die Geometrie bleibt lokal; `geoAnchor` ergibt den Versatz des Modell-Ursprungs in LV95
|
||
//! (IfcMapConversion Eastings/Northings), `referenceElevationMasl` die Höhe von ±0.00 (OrthogonalHeight).
|
||
//! Zahlsemantik und Reihenfolge wie die frühere TS-Fassung: die Dateien bleiben zeichengleich.
|
||
|
||
use crate::export_flat::{js_trim, Flat};
|
||
use crate::geo_rebase::lv95_to_wgs84;
|
||
use crate::ifc_quantities::{self as qty, Cutout, Qty, QtyKind};
|
||
use crate::ifc_stairs::{stair_parts, FlightBody, StairParts};
|
||
use crate::jsmath::hypot2;
|
||
use crate::jsnum::{max, min};
|
||
use crate::model::*;
|
||
use crate::model3d::{self, RWall};
|
||
use crate::wall_mesh_cut::{is_watertight, wall_cut_mesh_checked, CutWall};
|
||
use std::collections::HashMap;
|
||
|
||
const FLAT_VERSION: f64 = 5.0;
|
||
const REC_WALL_SOLIDS: f64 = 1.0;
|
||
const REC_WALL_MESH: f64 = 2.0;
|
||
const REC_CEILING: f64 = 3.0;
|
||
const REC_OPENING: f64 = 4.0;
|
||
const REC_STAIR: f64 = 5.0;
|
||
const REC_EXTRUSION: f64 = 6.0;
|
||
const REC_SPACE: f64 = 7.0;
|
||
const REC_END_SPACES: f64 = 8.0;
|
||
const REC_ROOF: f64 = 9.0;
|
||
const REC_COLUMN: f64 = 10.0;
|
||
const REC_END_COLUMNS: f64 = 11.0;
|
||
const REC_CLASSIFICATION: f64 = 12.0;
|
||
const REC_ZONE: f64 = 13.0;
|
||
const REC_ATTACH: f64 = 14.0;
|
||
const REC_OPENING_SOLID: f64 = 15.0;
|
||
const REC_WALL_ARC: f64 = 16.0;
|
||
const REC_WALL_ARC_SOLID: f64 = 17.0;
|
||
const REC_GRID: f64 = 18.0;
|
||
const REC_TREE: f64 = 19.0;
|
||
const REC_COLUMN_PIECES: f64 = 20.0;
|
||
const REC_CEILING_ARC: f64 = 21.0;
|
||
const REC_SPACE_ARC: f64 = 22.0;
|
||
const REC_GUIDS: f64 = 23.0;
|
||
const REC_CONTEXT: f64 = 24.0;
|
||
|
||
/// Toleranz des Kerns (`wall_bands.rs::EPS`) für „Öffnung trifft Band".
|
||
const BAND_EPS: f64 = 1e-4;
|
||
/// Wie weit der Öffnungskörper beidseits über die Wandflächen vorsteht (keine koplanaren Booleans).
|
||
const OPENING_OVERSHOOT: f64 = 0.02;
|
||
|
||
/// Optionen des IFC-Exports.
|
||
#[derive(Debug, Clone, Default, PartialEq)]
|
||
pub struct IfcOptions {
|
||
/// IFC2x3 statt IFC4.
|
||
pub ifc2x3: bool,
|
||
/// eBKP-H-Hauptgruppen je Bauteilart.
|
||
pub ebkph: bool,
|
||
/// `categoryCode` als System „Dossier-Ebenen".
|
||
pub layer_codes: bool,
|
||
/// [259] Kontext mitgeben: Gelände-Netze (IfcGeographicElement TERRAIN) und Netze auf Umgebungsklassen
|
||
/// (Nachbargebäude → IfcBuildingElementProxy), am IfcSite. Fachplaner wollen oft nur das Gebäude: Vorgabe aus.
|
||
pub context: bool,
|
||
/// Zeitstempel (Sekunden seit 1970) und dieselbe Zeit als ISO-Text ohne Sekundenbruchteil.
|
||
pub now: f64,
|
||
pub iso: String,
|
||
}
|
||
|
||
// ── Puffer-Bausteine (Reihenfolge der Aufrufe = Reihenfolge der Zeichenketten) ─────────────────
|
||
|
||
/// Pset-Eigenschaft (0 IfcIdentifier, 1 IfcBoolean, 2 IfcPositiveRatioMeasure, 3–5 Mengen, 6 IfcLabel,
|
||
/// 7 IfcThermalTransmittanceMeasure).
|
||
enum Prop {
|
||
Ident(&'static str, String),
|
||
Bool(&'static str, bool),
|
||
Ratio(&'static str, f64),
|
||
/// IfcLabel (Freitext wie Feuerwiderstand).
|
||
Label(&'static str, String),
|
||
/// IfcThermalTransmittanceMeasure, W/(m²K).
|
||
Thermal(&'static str, f64),
|
||
Qty(&'static str, QtyKind, f64),
|
||
}
|
||
|
||
struct Pset {
|
||
name: &'static str,
|
||
props: Vec<Prop>,
|
||
}
|
||
|
||
struct TypeRef<'a> {
|
||
kind: f64,
|
||
id: &'a str,
|
||
name: &'a str,
|
||
predefined: &'a str,
|
||
layers: Vec<(&'a str, &'a str, f64)>,
|
||
}
|
||
|
||
/// Typ (id, Name, Schichten: Bauteil-id, Bauteilname, Dicke) als Datensatz-Verweis.
|
||
type TypeData = (String, String, Vec<(String, String, f64)>);
|
||
|
||
fn type_ref<'a>(t: &'a TypeData, kind: f64, predefined: &'a str) -> TypeRef<'a> {
|
||
TypeRef { kind, id: &t.0, name: &t.1, predefined, layers: t.2.iter().map(|(a, b, c)| (a.as_str(), b.as_str(), *c)).collect() }
|
||
}
|
||
|
||
/// `IsExternal`/`LoadBearing` für Wand und Decke, nur mit Angabe im Modell.
|
||
fn structure_props(external: Option<bool>, load_bearing: Option<bool>) -> Vec<Prop> {
|
||
let mut v = Vec::new();
|
||
v.extend(external.map(|e| Prop::Bool("IsExternal", e)));
|
||
v.extend(load_bearing.map(|b| Prop::Bool("LoadBearing", b)));
|
||
v
|
||
}
|
||
|
||
fn ident(name: &'static str, v: &str) -> Prop {
|
||
Prop::Ident(name, v.to_string())
|
||
}
|
||
|
||
/// Basismengen als Pset `Qto_…` (nur wenn Mengen vorliegen).
|
||
fn qto(name: &'static str, quantities: Vec<Qty>) -> Vec<Pset> {
|
||
if quantities.is_empty() {
|
||
return vec![];
|
||
}
|
||
vec![Pset { name, props: quantities.into_iter().map(|q| Prop::Qty(q.name, q.kind, q.value)).collect() }]
|
||
}
|
||
|
||
fn w_pts(f: &mut Flat, pts: &[Vec2]) {
|
||
f.num(pts.len() as f64);
|
||
for p in pts {
|
||
f.nums(&[p.x, p.y]);
|
||
}
|
||
}
|
||
|
||
/// [191] Ring mit Bögen: `n, (x, y, bulge) × n` (Bulge zur nächsten Ecke; fehlend = gerade). Der Schreiber liest den
|
||
/// Bulge im DXF-Sinn (positiv = Gegenuhrzeigersinn, Scheitel rechts der Kante); das Modell zählt umgekehrt
|
||
/// (`ring_arc`: positiv = Scheitel links, wie bei Wänden) — daher das Vorzeichen ([259]: vorher lagen die Bögen von
|
||
/// Decken und Räumen gespiegelt an der Sehne, Fläche/Volumen nach ifcopenshell ≠ Mengen).
|
||
fn w_bpts(f: &mut Flat, pts: &[Vec2], bulge: Option<&[f64]>) {
|
||
f.num(pts.len() as f64);
|
||
for (i, p) in pts.iter().enumerate() {
|
||
f.nums(&[p.x, p.y, -crate::ring_arc::bulge_at(bulge, i)]);
|
||
}
|
||
}
|
||
|
||
fn w_mesh(f: &mut Flat, positions: &[f64], indices: &[u32], closed: bool) {
|
||
f.num((positions.len() / 3) as f64).nums(positions);
|
||
f.num((indices.len() / 3) as f64);
|
||
for &i in indices {
|
||
f.num(i as f64);
|
||
}
|
||
f.num(if closed { 1.0 } else { 0.0 });
|
||
}
|
||
|
||
fn w_type(f: &mut Flat, t: Option<&TypeRef>) {
|
||
let Some(t) = t else {
|
||
f.num(0.0);
|
||
return;
|
||
};
|
||
let (id, name, pre) = (f.str(t.id), f.str(t.name), f.str(t.predefined));
|
||
f.nums(&[1.0, t.kind, id, name, pre, t.layers.len() as f64]);
|
||
for &(cid, cname, thickness) in &t.layers {
|
||
let (a, b) = (f.str(cid), f.str(cname));
|
||
f.nums(&[a, b, thickness]);
|
||
}
|
||
}
|
||
|
||
fn w_psets(f: &mut Flat, list: &[Pset]) {
|
||
f.num(list.len() as f64);
|
||
for ps in list {
|
||
let n = f.str(ps.name);
|
||
f.nums(&[n, ps.props.len() as f64]);
|
||
for p in &ps.props {
|
||
match p {
|
||
Prop::Ident(name, v) => {
|
||
let (a, b) = (f.str(name), f.str(v));
|
||
f.nums(&[a, 0.0, b]);
|
||
}
|
||
Prop::Bool(name, v) => {
|
||
let a = f.str(name);
|
||
f.nums(&[a, 1.0, if *v { 1.0 } else { 0.0 }]);
|
||
}
|
||
Prop::Ratio(name, v) => {
|
||
let a = f.str(name);
|
||
f.nums(&[a, 2.0, *v]);
|
||
}
|
||
Prop::Label(name, v) => {
|
||
let (a, b) = (f.str(name), f.str(v));
|
||
f.nums(&[a, 6.0, b]);
|
||
}
|
||
Prop::Thermal(name, v) => {
|
||
let a = f.str(name);
|
||
f.nums(&[a, 7.0, *v]);
|
||
}
|
||
Prop::Qty(name, kind, v) => {
|
||
let a = f.str(name);
|
||
let code = match kind {
|
||
QtyKind::Length => 3.0,
|
||
QtyKind::Area => 4.0,
|
||
QtyKind::Volume => 5.0,
|
||
};
|
||
f.nums(&[a, code, *v]);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Kopf eines Bauteil-Datensatzes: `[art, struktur, id, name]`.
|
||
fn w_head(f: &mut Flat, rec: f64, structure: f64, id: &str, name: &str) {
|
||
let (a, b) = (f.str(id), f.str(name));
|
||
f.nums(&[rec, structure, a, b]);
|
||
}
|
||
|
||
// ── Geometrie-Helfer (Welt-Meter) ───────────────────────────────────────────
|
||
|
||
fn sub(a: Vec2, b: Vec2) -> Vec2 {
|
||
Vec2 { x: a.x - b.x, y: a.y - b.y }
|
||
}
|
||
fn normalize(v: Vec2) -> Vec2 {
|
||
let l = hypot2(v.x, v.y);
|
||
let l = if l == 0.0 || l.is_nan() { 1.0 } else { l };
|
||
Vec2 { x: v.x / l, y: v.y / l }
|
||
}
|
||
fn left_normal(u: Vec2) -> Vec2 {
|
||
Vec2 { x: -u.y, y: u.x }
|
||
}
|
||
fn add_scaled(p: Vec2, d: Vec2, s: f64) -> Vec2 {
|
||
Vec2 { x: p.x + d.x * s, y: p.y + d.y * s }
|
||
}
|
||
fn dot(a: Vec2, b: Vec2) -> f64 {
|
||
a.x * b.x + a.y * b.y
|
||
}
|
||
fn v2(p: [f64; 2]) -> Vec2 {
|
||
Vec2 { x: p[0], y: p[1] }
|
||
}
|
||
|
||
/// Rechteck `[from,to]` entlang der Wandachse × `[n_lo,n_hi]` quer dazu (Welt-XY, CCW).
|
||
fn axis_rect(wall: &Wall, from: f64, to: f64, n_lo: f64, n_hi: f64) -> Vec<Vec2> {
|
||
let u = normalize(sub(wall.end, wall.start));
|
||
let n = left_normal(u);
|
||
let a = add_scaled(wall.start, u, from);
|
||
let b = add_scaled(wall.start, u, to);
|
||
vec![add_scaled(a, n, n_lo), add_scaled(b, n, n_lo), add_scaled(b, n, n_hi), add_scaled(a, n, n_hi)]
|
||
}
|
||
|
||
/// [T2] Öffnung in der Bogenwand als gerade Ersatzwand (Sehne der Achse zwischen den Laibungen):
|
||
/// (Ersatzwand, Intervall 0…Sehne, Querbereich zur Sehne, Einzug je Ende damit der Öffnungskörper
|
||
/// auch an den Flächen innerhalb des radialen Lochs bleibt).
|
||
fn arc_opening_chord(wall: &Wall, a: &crate::wall_arc::WallArc, c: &Cutout, host: (f64, f64)) -> (Wall, Cutout, (f64, f64), f64, f64) {
|
||
let (ps, pe) = (a.point(c.from, 0.0), a.point(c.to, 0.0));
|
||
let mid = a.point((c.from + c.to) / 2.0, 0.0);
|
||
let chord = (pe.x - ps.x).hypot(pe.y - ps.y);
|
||
let mut vw = wall.clone();
|
||
vw.start = Vec2 { x: ps.x, y: ps.y };
|
||
vw.end = Vec2 { x: pe.x, y: pe.y };
|
||
vw.bulge = None;
|
||
let u = normalize(sub(vw.end, vw.start));
|
||
let n = left_normal(u);
|
||
let delta = (mid.x - (ps.x + pe.x) / 2.0) * n.x + (mid.y - (ps.y + pe.y) / 2.0) * n.y;
|
||
let half_angle = (c.to - c.from) / a.r / 2.0;
|
||
let shrink = (host.0.abs().max(host.1.abs()) + delta.abs()) * half_angle.tan();
|
||
(vw, Cutout { from: 0.0, to: chord, z_bottom: c.z_bottom, z_top: c.z_top }, (host.0 + delta, host.1 + delta), shrink.min(chord / 4.0), delta.abs())
|
||
}
|
||
|
||
/// [T2] Bogenwand als Profil-Extrusion: je Schicht ein Profil (Ecken mit Bulge zur nächsten, DXF-Sinn:
|
||
/// positiv = Gegenuhrzeigersinn) aus den Sehnen-Teilkörpern der Wand OHNE Öffnungen — Kreisbögen innen
|
||
/// und aussen, dazwischen die Anschluss-Schnitte (Ecken aus `model3d::wall_footprint`, radial auf den
|
||
/// Schicht-Radius gesetzt). `None` (Netz-Weg): Dachanschluss, Aussparungen, Löcher oder Lücken.
|
||
fn arc_wall_profiles(arc: &crate::wall_arc::WallArc, pieces: &[RWall], base: f64) -> Option<Vec<(Vec<[f64; 3]>, f64, f64)>> {
|
||
if pieces.is_empty() || pieces.iter().any(|b| b.top_plane.is_some() || b.top_drop.is_some_and(|d| d.iter().any(|x| x.abs() > 1e-12)) || b.holes.as_ref().is_some_and(|h| !h.is_empty())) {
|
||
return None;
|
||
}
|
||
let kv = |q: [f64; 2]| kernel2d::Vec2::new(q[0], q[1]);
|
||
// Schichtband = gleicher Querversatz, gleiche Dicke, gleiche Höhe.
|
||
let mut groups: Vec<((i64, i64, i64, i64), Vec<(f64, f64, &RWall)>)> = Vec::new();
|
||
for b in pieces {
|
||
let (s0, n0) = arc.local(kv(b.start));
|
||
let (s1, n1) = arc.local(kv(b.end));
|
||
let q = |v: f64| (v * 1e5).round() as i64;
|
||
let key = (q((n0 + n1) / 2.0), q(b.thickness), q(b.base_elevation), q(b.height));
|
||
match groups.iter_mut().find(|g| g.0 == key) {
|
||
Some(g) => g.1.push((s0.min(s1), s0.max(s1), b)),
|
||
None => groups.push((key, vec![(s0.min(s1), s0.max(s1), b)])),
|
||
}
|
||
}
|
||
let mut out = Vec::new();
|
||
for (_, mut list) in groups {
|
||
list.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
|
||
// Zusammenhängende Ketten (Eckstücke an den Anschlüssen, Teilungen an Decken = eigene Ketten).
|
||
let mut chains: Vec<Vec<&RWall>> = Vec::new();
|
||
let near = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6;
|
||
for (_, _, b) in list {
|
||
let fp = model3d::wall_footprint(b)?;
|
||
let joins = chains.last().and_then(|c| c.last()).and_then(|l| model3d::wall_footprint(l)).is_some_and(|lf| near(lf[1], fp[0]) && near(lf[2], fp[3]));
|
||
match chains.last_mut() {
|
||
Some(c) if joins => c.push(b),
|
||
_ => chains.push(vec![b]),
|
||
}
|
||
}
|
||
for chain in chains {
|
||
let (first, last) = (chain[0], chain[chain.len() - 1]);
|
||
let (fa, fb) = (model3d::wall_footprint(first)?, model3d::wall_footprint(last)?);
|
||
let n_mid = (arc.local(kv(first.start)).1 + arc.local(kv(first.end)).1) / 2.0;
|
||
let h = first.thickness / 2.0;
|
||
// Ecken: Anfang +n, Ende +n, Ende −n, Anfang −n; Bogen zwischen gleichem Querversatz.
|
||
let corners = [(fa[0], n_mid + h), (fb[1], n_mid + h), (fb[2], n_mid - h), (fa[3], n_mid - h)];
|
||
let s: Vec<f64> = corners.iter().map(|(q, _)| arc.local(kv(*q)).0).collect();
|
||
let pts: Vec<kernel2d::Vec2> = corners.iter().zip(&s).map(|((_, n), s)| arc.point(*s, *n)).collect();
|
||
let bulge = |sa: f64, sb: f64| (arc.sigma() * (sb - sa) / arc.r / 4.0).tan();
|
||
let ring = vec![[pts[0].x, pts[0].y, bulge(s[0], s[1])], [pts[1].x, pts[1].y, 0.0], [pts[2].x, pts[2].y, bulge(s[2], s[3])], [pts[3].x, pts[3].y, 0.0]];
|
||
if ring.iter().flatten().any(|v| !v.is_finite()) {
|
||
return None;
|
||
}
|
||
out.push((ring, first.base_elevation - base, first.height));
|
||
}
|
||
}
|
||
Some(out)
|
||
}
|
||
|
||
/// [T2] Öffnungskörper in der Bogenwand mit Profil-Körper: radiale Laibungen; die Ecken auf der
|
||
/// äusseren Seite so weit hinaus, dass die Sehne dazwischen ausserhalb der Wandfläche bleibt.
|
||
fn arc_opening_quad(a: &crate::wall_arc::WallArc, from: f64, to: f64, host: (f64, f64)) -> Vec<Vec2> {
|
||
let half = (to - from) / a.r / 2.0;
|
||
let k = 1.0 / half.cos().max(0.5);
|
||
let (mut lo, mut hi) = (host.0 - OPENING_OVERSHOOT, host.1 + OPENING_OVERSHOOT);
|
||
let push_out = |n: f64| a.sigma() * (a.r - a.radius_at(n) * k);
|
||
if a.radius_at(lo) > a.radius_at(hi) {
|
||
lo = push_out(lo);
|
||
} else {
|
||
hi = push_out(hi);
|
||
}
|
||
let p = |s: f64, n: f64| {
|
||
let q = a.point(s, n);
|
||
Vec2 { x: q.x, y: q.y }
|
||
};
|
||
vec![p(from, lo), p(to, lo), p(to, hi), p(from, hi)]
|
||
}
|
||
|
||
/// Sortierung `byFrom` (Anfang, dann Unterkante; NaN gilt als gleich wie in `Array.sort`).
|
||
fn by_from(p: &[f64; 4], q: &[f64; 4]) -> std::cmp::Ordering {
|
||
let d = p[0] - q[0];
|
||
let d = if d != 0.0 && !d.is_nan() { d } else { p[2] - q[2] };
|
||
if d < 0.0 {
|
||
std::cmp::Ordering::Less
|
||
} else if d > 0.0 {
|
||
std::cmp::Ordering::Greater
|
||
} else {
|
||
std::cmp::Ordering::Equal
|
||
}
|
||
}
|
||
|
||
/// Ob die Schicht-Bänder einer Wand exakt „Quader minus Öffnungen" sind: kein Band mit schräger
|
||
/// Oberkante, und jedes Band trägt genau die Öffnungen als Löcher, die es in der Höhe trifft — in
|
||
/// derselben Grösse. Dann ergibt Extrusion je Band minus IfcOpeningElement denselben Körper wie das 3D.
|
||
fn bands_match_openings(wall: &Wall, bands: &[&RWall], cutouts: &[Cutout]) -> bool {
|
||
let u = normalize(sub(wall.end, wall.start));
|
||
for b in bands {
|
||
if b.top_plane.is_some() || b.top_drop.is_some_and(|d| d[0].abs() > 1e-9 || d[1].abs() > 1e-9) {
|
||
return false;
|
||
}
|
||
let a = dot(Vec2 { x: b.start[0] - wall.start.x, y: b.start[1] - wall.start.y }, u);
|
||
let zb = b.base_elevation;
|
||
let zt = b.base_elevation + b.height;
|
||
let mut expected: Vec<[f64; 4]> =
|
||
cutouts.iter().filter(|h| h.z_top > zb + BAND_EPS && h.z_bottom < zt - BAND_EPS).map(|h| [h.from - a, h.to - a, h.z_bottom, h.z_top]).collect();
|
||
expected.sort_by(by_from);
|
||
let mut actual: Vec<[f64; 4]> = b.holes.as_deref().unwrap_or(&[]).iter().map(|h| [h.from, h.to, h.z_bottom, h.z_top]).collect();
|
||
actual.sort_by(by_from);
|
||
if expected.len() != actual.len() {
|
||
return false;
|
||
}
|
||
for (e, x) in expected.iter().zip(&actual) {
|
||
for k in 0..4 {
|
||
if !((e[k] - x[k]).abs() <= 1e-6) {
|
||
return false;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
true
|
||
}
|
||
|
||
/// [168] Rahmenlage quer zur Wand (Versatz entlang der linken Normalen ab `wall.start`, wie
|
||
/// `cross_extent`), wenn der Schichteinzug der Öffnung Stücke in die Öffnung setzt; sonst `None`.
|
||
fn reveal_frame_slice(p: &Project, wall: &Wall, o: &Opening) -> Option<(f64, f64)> {
|
||
let r = crate::opening_detail::opening_reveal(p, wall, o)?;
|
||
if r.sides.iter().flatten().all(|a| a.pieces.is_empty()) {
|
||
return None;
|
||
}
|
||
let total: f64 = r.thick.iter().sum();
|
||
let (lo, hi) = crate::opening_detail::frame_of(p, o)?.range(total);
|
||
let face = crate::joins::reference_offset(model3d::wall_reference(wall), total) - total / 2.0;
|
||
(hi - lo > 1e-4).then_some((face + lo, face + hi))
|
||
}
|
||
|
||
/// [168] Bänder einer Wand als EIN Körper (Manifold, exakt): je Band der volle Quader (Enden an den
|
||
/// Schnittlinien wie das 3D) minus die Löcher, dann alle vereinigt — IFC-Koordinaten (x, y, z − `base`).
|
||
/// [259] Auch die Füllkörper von Formöffnungen (`boxes`, Quader wie `push_box`) und jede Wand mit mehreren Bändern:
|
||
/// sonst lagen mehrere sich berührende Schalen in einem Face-Set (Kanten 4- bis 8-fach), und ifcopenshell rechnete
|
||
/// beim Abzug der Öffnungen falsch (Füllkörper waren zudem verdreht gewickelt). `None` bei Bändern mit schräger oder
|
||
/// ebener Dach-Oberkante (`top_drop`, `top_plane`) oder wenn Manifold ablehnt (dann bleibt das Schalen-Netz).
|
||
fn union_bands(bands: &[&RWall], base: f64, boxes: &[[f64; 24]]) -> Option<(Vec<f64>, Vec<u32>)> {
|
||
use crate::solid_bool::{Mesh, Solid};
|
||
let solid = |w: &CutWall, shift: Option<&RWall>| -> Option<Solid> {
|
||
let mut cut = wall_cut_mesh_checked(w);
|
||
if let Some(b) = shift {
|
||
crate::mesh_data::shift_cut_ends(&mut cut, b);
|
||
}
|
||
let positions: Vec<f64> = cut.chunks_exact(3).flat_map(|c| [c[0], c[2], c[1] - base]).collect();
|
||
let n = (positions.len() / 3) as u32;
|
||
Solid::new(&Mesh { positions, indices: (0..n).collect() }).ok()
|
||
};
|
||
let mut acc: Option<Solid> = None;
|
||
let mut add = |acc: &mut Option<Solid>, m: Solid| -> Option<()> {
|
||
*acc = Some(match acc.take() {
|
||
None => m,
|
||
Some(a) => a.union(&m).ok()?,
|
||
});
|
||
Some(())
|
||
};
|
||
for b in bands {
|
||
if b.top_drop.is_some_and(|d| d[0].abs() > 1e-9 || d[1].abs() > 1e-9) {
|
||
return None;
|
||
}
|
||
// Ebene Oberkante unter einem Dach: nicht vereinigt (die Prismen berühren die Nachbarbänder nur an Kanten;
|
||
// der vereinigte Körper war dicht, aber ifcopenshell scheiterte am Abzug der Öffnung — Volumen 0).
|
||
if b.top_plane.is_some() {
|
||
return None;
|
||
}
|
||
let mut m = solid(&CutWall { start: b.start, end: b.end, thickness: b.thickness, base_elevation: b.base_elevation, height: b.height, holes: vec![] }, Some(b))?;
|
||
let (dx, dy) = (b.end[0] - b.start[0], b.end[1] - b.start[1]);
|
||
let len = hypot2(dx, dy);
|
||
if !(len > 1e-9) {
|
||
return None;
|
||
}
|
||
let (ux, uy) = (dx / len, dy / len);
|
||
for h in b.holes.as_deref().unwrap_or(&[]) {
|
||
let at = |d: f64| [b.start[0] + ux * d, b.start[1] + uy * d];
|
||
// Bündig mit Band-UK/-OK (Tür): über die Fläche hinaus, keine deckungsgleichen Flächen.
|
||
let (z0, z1) = (b.base_elevation, b.base_elevation + b.height);
|
||
let lo = if h.z_bottom <= z0 + 1e-6 { z0 - 0.1 } else { h.z_bottom };
|
||
let hi = if h.z_top >= z1 - 1e-6 { z1 + 0.1 } else { h.z_top };
|
||
let hole = solid(&CutWall { start: at(h.from), end: at(h.to), thickness: b.thickness + 0.1, base_elevation: lo, height: hi - lo, holes: vec![] }, None)?;
|
||
m = m.difference(&hole).ok()?;
|
||
}
|
||
add(&mut acc, m)?;
|
||
}
|
||
for b in boxes {
|
||
let positions: Vec<f64> = b.chunks_exact(3).flat_map(|c| [c[0], c[1], c[2] - base]).collect();
|
||
let solid = Solid::new(&Mesh { positions, indices: box_tris_outward(b).to_vec() }).ok()?;
|
||
add(&mut acc, solid)?;
|
||
}
|
||
let m = acc?.to_mesh();
|
||
(!m.indices.is_empty()).then_some((m.positions, m.indices))
|
||
}
|
||
|
||
/// Ausdehnung aller Bänder quer zur Wandachse (entlang der linken Normalen ab `wall.start`).
|
||
fn cross_extent(wall: &Wall, bands: &[&RWall]) -> (f64, f64) {
|
||
let n = left_normal(normalize(sub(wall.end, wall.start)));
|
||
let (mut n_lo, mut n_hi) = (f64::INFINITY, f64::NEG_INFINITY);
|
||
for b in bands {
|
||
let off = dot(Vec2 { x: b.start[0] - wall.start.x, y: b.start[1] - wall.start.y }, n);
|
||
n_lo = min(n_lo, off - b.thickness / 2.0);
|
||
n_hi = max(n_hi, off + b.thickness / 2.0);
|
||
}
|
||
(n_lo, n_hi)
|
||
}
|
||
|
||
/// Vereinfachter Bounding-Footprint einer Treppe (gerade: Lauf-Rechteck; sonst achsparallele Box der
|
||
/// Kontrollpunkte bzw. des Wendel-Kreises, um die halbe Laufbreite erweitert).
|
||
fn stair_footprint(st: &Stair) -> Vec<Vec2> {
|
||
let half_w = max(st.width, 0.0) / 2.0;
|
||
// [151] U / gerade mit Podest: Box um die Aussenlinie.
|
||
if matches!(st.shape, StairShape::U | StairShape::StraightLanding) {
|
||
if let Some(poly) = crate::stair::decode_params(&st.encode()).and_then(|p| kernel2d::stair_outline(&p).polygon) {
|
||
let (mut lo, mut hi) = (Vec2 { x: f64::INFINITY, y: f64::INFINITY }, Vec2 { x: f64::NEG_INFINITY, y: f64::NEG_INFINITY });
|
||
for q in &poly {
|
||
lo = Vec2 { x: min(lo.x, q.x), y: min(lo.y, q.y) };
|
||
hi = Vec2 { x: max(hi.x, q.x), y: max(hi.y, q.y) };
|
||
}
|
||
return vec![lo, Vec2 { x: hi.x, y: lo.y }, hi, Vec2 { x: lo.x, y: hi.y }];
|
||
}
|
||
}
|
||
if st.shape == StairShape::Straight {
|
||
let u = normalize(st.dir);
|
||
let n = left_normal(u);
|
||
let end = add_scaled(st.start, u, st.run_length);
|
||
return vec![add_scaled(st.start, n, -half_w), add_scaled(end, n, -half_w), add_scaled(end, n, half_w), add_scaled(st.start, n, half_w)];
|
||
}
|
||
let truthy = |v: Option<f64>| v.filter(|x| *x != 0.0 && !x.is_nan());
|
||
let mut pts = vec![st.start];
|
||
let u = normalize(st.dir);
|
||
let corner = add_scaled(st.start, u, st.run_length);
|
||
pts.push(corner);
|
||
if st.shape == StairShape::L {
|
||
if let (Some(run2), Some(turn)) = (truthy(st.run2_length), truthy(st.turn)) {
|
||
let n = left_normal(u);
|
||
pts.push(add_scaled(corner, Vec2 { x: n.x * turn, y: n.y * turn }, run2));
|
||
}
|
||
}
|
||
if st.shape == StairShape::Spiral {
|
||
if let Some(c) = st.center {
|
||
let r = st.radius.unwrap_or(0.0) + half_w;
|
||
return vec![Vec2 { x: c.x - r, y: c.y - r }, Vec2 { x: c.x + r, y: c.y - r }, Vec2 { x: c.x + r, y: c.y + r }, Vec2 { x: c.x - r, y: c.y + r }];
|
||
}
|
||
}
|
||
let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
|
||
for p in &pts {
|
||
min_x = min(min_x, p.x);
|
||
min_y = min(min_y, p.y);
|
||
max_x = max(max_x, p.x);
|
||
max_y = max(max_y, p.y);
|
||
}
|
||
min_x -= half_w;
|
||
min_y -= half_w;
|
||
max_x += half_w;
|
||
max_y += half_w;
|
||
vec![Vec2 { x: min_x, y: min_y }, Vec2 { x: max_x, y: min_y }, Vec2 { x: max_x, y: max_y }, Vec2 { x: min_x, y: max_y }]
|
||
}
|
||
|
||
fn roof_predefined(s: RoofShape) -> &'static str {
|
||
match s {
|
||
RoofShape::Flach => "FLAT_ROOF",
|
||
RoofShape::Pult => "SHED_ROOF",
|
||
RoofShape::Sattel => "GABLE_ROOF",
|
||
RoofShape::Walm => "HIP_ROOF",
|
||
RoofShape::Mansarde => "MANSARD_ROOF",
|
||
RoofShape::Zelt => "HIPPED_GABLE_ROOF",
|
||
RoofShape::Unknown => "NOTDEFINED",
|
||
}
|
||
}
|
||
|
||
// ── Türen und Fenster (Parameter für `fileio/src/ifc_openings.rs`) ─────────────────────────────
|
||
|
||
|
||
/// Ein Eintrag der Flügeltabelle (`SashDef`): Pfosten?, Pfostenbreite, feste Breite?, Breite.
|
||
#[derive(Debug, Clone, PartialEq)]
|
||
struct FillSash {
|
||
post: bool,
|
||
post_width: Option<f64>,
|
||
fixed: bool,
|
||
width: Option<f64>,
|
||
}
|
||
|
||
/// Parameter der Füllung einer Öffnung (Kodierung FILL im Kopf von `ifc_export/mod.rs`), aus Typ und
|
||
/// Öffnung; fehlende Typwerte bleiben „keine", die Standardmasse kennt nur `fileio`.
|
||
#[derive(Debug, Clone, PartialEq)]
|
||
struct FillParams {
|
||
frame_depth: Option<f64>,
|
||
inset: Option<f64>,
|
||
inset_outside: bool,
|
||
frame_width: Option<f64>,
|
||
/// Fenster: Flügelzahl, Scheiben (1–3), Flügeltabelle.
|
||
wing_count: f64,
|
||
panes: f64,
|
||
sashes: Vec<FillSash>,
|
||
/// Tür: 0 Dreh, 1 Schiebe (auch Hebeschiebe), 2 reine Wandöffnung, 3 Pendel.
|
||
door_kind: f64,
|
||
leaf_count: f64,
|
||
/// +1 Aufschlag links der Achse, −1 rechts; Richtung +1 innen, −1 aussen.
|
||
swing_sign: f64,
|
||
dir_sign: f64,
|
||
hinge_at_start: bool,
|
||
transom_height: f64,
|
||
glazed: bool,
|
||
glazing_ratio: Option<f64>,
|
||
}
|
||
|
||
fn fill_params(p: &Project, o: &Opening) -> FillParams {
|
||
let is_door = o.kind == ElementKind::Door;
|
||
let dt = if is_door { p.door_type(o) } else { None };
|
||
let wt = if is_door { None } else { p.window_type(o) };
|
||
let mut fp = FillParams {
|
||
frame_depth: dt.map_or(wt.and_then(|t| t.frame_depth), |t| t.frame_depth),
|
||
inset: dt.map_or(wt.and_then(|t| t.inset_from_face), |t| t.inset_from_face).or_else(|| crate::opening_detail::default_frame_inset(p, o)),
|
||
inset_outside: match (dt, wt) {
|
||
(Some(t), _) => matches!(t.inset_face, None | Some(DoorTypeInsetFace::Aussen)),
|
||
(None, Some(t)) => matches!(t.inset_face, None | Some(WindowTypeInsetFace::Aussen)),
|
||
_ => true,
|
||
},
|
||
frame_width: dt.map_or(wt.and_then(|t| t.frame_width), |t| t.frame_width),
|
||
wing_count: o.wing_count.or(wt.map(|t| t.wing_count)).unwrap_or(1.0),
|
||
panes: wt.map_or(2.0, |t| match t.glazing_panes {
|
||
Some(v) if v != 0.0 && !v.is_nan() => v,
|
||
_ => match t.glazing {
|
||
WindowTypeGlazing::Dreifach => 3.0,
|
||
WindowTypeGlazing::Zweifach => 2.0,
|
||
_ => 1.0,
|
||
},
|
||
}),
|
||
sashes: wt
|
||
.and_then(|t| t.sashes.as_deref())
|
||
.unwrap_or(&[])
|
||
.iter()
|
||
.map(|s| FillSash { post: s.kind == SashDefKind::Pfosten, post_width: s.post_width, fixed: s.auto_width == Some(false), width: s.width })
|
||
.collect(),
|
||
// Türart: Typ vor Öffnung.
|
||
door_kind: match dt.map(|t| t.kind) {
|
||
Some(DoorTypeKind::Schiebe | DoorTypeKind::Hebeschiebe | DoorTypeKind::Tasche) => 1.0,
|
||
Some(DoorTypeKind::Pendel) => 3.0,
|
||
Some(DoorTypeKind::Wandoeffnung) => 2.0,
|
||
Some(_) => 0.0,
|
||
None if o.door_type == Some(OpeningDoorType::Wandoeffnung) => 2.0,
|
||
None => 0.0,
|
||
},
|
||
leaf_count: dt.map_or(1.0, |t| t.leaf_count),
|
||
swing_sign: if matches!(o.swing, None | Some(SwingSide::Left)) { 1.0 } else { -1.0 },
|
||
dir_sign: if matches!(o.opening_dir, None | Some(OpeningOpeningDir::In)) { 1.0 } else { -1.0 },
|
||
hinge_at_start: matches!(o.hinge, None | Some(OpeningHinge::Start)),
|
||
transom_height: dt.and_then(|t| t.transom_height).unwrap_or(0.0),
|
||
glazed: dt.is_some_and(|t| t.leaf_style == DoorTypeLeafStyle::Glas),
|
||
glazing_ratio: dt.and_then(|t| t.glazing_ratio),
|
||
};
|
||
// [105] Türzarge mit Profil: Rahmenlage quer = Profil in der Wand (Zarge über die ganze Leibung,
|
||
// Blockrahmen nach Typ); das Blatt sitzt dann wie im 3D im Falz der Aufschlagseite.
|
||
if let Some((lo, hi)) = door_frame_extent(p, o) {
|
||
fp.frame_depth = Some(hi - lo);
|
||
fp.inset = Some(lo);
|
||
fp.inset_outside = true;
|
||
}
|
||
fp
|
||
}
|
||
|
||
/// Querlage `(lo, hi)` ab der Aussenfläche der Zarge/des Rahmens einer Tür mit Profil ([105]), ohne
|
||
/// Bekleidung und Spiegel vor den Wandflächen; `None` ohne Profil oder ganz vor der Wand (Blendrahmen).
|
||
fn door_frame_extent(p: &Project, o: &Opening) -> Option<(f64, f64)> {
|
||
use crate::opening_detail as od;
|
||
let df = od::door_frame_of(p, o)?;
|
||
let wall = p.walls.iter().find(|w| w.id == o.host_wall_id)?;
|
||
let total = p.wall_thickness(wall, 0.2);
|
||
if !(total > 1e-6) {
|
||
return None;
|
||
}
|
||
let innen = od::aufschlag_innen(o);
|
||
let (mut d0, mut d1) = (f64::INFINITY, f64::NEG_INFINITY);
|
||
for (part, poly) in od::door_frame_profile(&df, total, innen) {
|
||
if part == od::FramePart::Casing {
|
||
continue;
|
||
}
|
||
for q in poly {
|
||
let d = q[1].max(0.0).min(total);
|
||
d0 = d0.min(d);
|
||
d1 = d1.max(d);
|
||
}
|
||
}
|
||
if !(d1 - d0 > 1e-3) {
|
||
return None;
|
||
}
|
||
Some(if innen { (total - d1, total - d0) } else { (d0, d1) })
|
||
}
|
||
|
||
/// FILL schreiben: Wandachse, Achs-Intervall und Höhen der Öffnung, Querausdehnung der Wand
|
||
/// (`host` = n_lo aussen, n_hi), dann die Parameter.
|
||
/// Psets und Basismengen einer Tür/eines Fensters (Kennwerte nur mit Angabe im Modell).
|
||
fn fill_psets(p: &Project, o: &Opening, width: f64, height: f64) -> Vec<Pset> {
|
||
let is_door = o.kind == ElementKind::Door;
|
||
let mut props: Vec<Prop> = Vec::new();
|
||
let pset_name = if is_door {
|
||
let dt = p.door_type(o);
|
||
if let Some(dt) = dt {
|
||
props.push(ident("Reference", &dt.name));
|
||
if dt.leaf_style == DoorTypeLeafStyle::Glas {
|
||
if let Some(ratio) = dt.glazing_ratio.filter(|r| *r > 0.0 && *r <= 1.0) {
|
||
props.push(Prop::Ratio("GlazingAreaFraction", ratio));
|
||
}
|
||
}
|
||
}
|
||
"Pset_DoorCommon"
|
||
} else {
|
||
if let Some(wt) = p.window_type(o) {
|
||
props.push(ident("Reference", &wt.name));
|
||
}
|
||
"Pset_WindowCommon"
|
||
};
|
||
// Nummer ersetzt den Typnamen als Reference; Kennwerte nur mit Angabe im Modell.
|
||
if let Some(mark) = o.mark.as_deref().map(str::trim).filter(|m| !m.is_empty()) {
|
||
props.retain(|x| !matches!(x, Prop::Ident("Reference", _)));
|
||
props.insert(0, ident("Reference", mark));
|
||
}
|
||
if let Some(e) = crate::opening_schedule::opening_external(p, o) {
|
||
props.push(Prop::Bool("IsExternal", e));
|
||
}
|
||
let label = |name: &'static str, v: &Option<String>| v.as_deref().map(str::trim).filter(|x| !x.is_empty()).map(|x| Prop::Label(name, x.to_string()));
|
||
props.extend(label("FireRating", &o.fire_rating));
|
||
props.extend(label("AcousticRating", &o.sound_class));
|
||
props.extend(o.u_value.filter(|u| *u > 0.0).map(|u| Prop::Thermal("ThermalTransmittance", u)));
|
||
props.extend(label("SecurityRating", &o.burglary_class));
|
||
let mut psets = vec![Pset { name: pset_name, props }];
|
||
psets.extend(qto(if is_door { "Qto_DoorBaseQuantities" } else { "Qto_WindowBaseQuantities" }, qty::opening_quantities(width, height)));
|
||
psets
|
||
}
|
||
|
||
/// Öffnungskörper einer Form-/Dachöffnung ([G3]/[103]): Profil in (x, y) des Systems `origin`/`x_dir`/
|
||
/// `z_dir`, entlang `z_dir` um `depth` extrudiert (Welt relativ zur Geschoss-UK).
|
||
struct SolidOpening {
|
||
host: String,
|
||
profile: Vec<[f64; 2]>,
|
||
origin: [f64; 3],
|
||
x_dir: [f64; 3],
|
||
z_dir: [f64; 3],
|
||
depth: f64,
|
||
}
|
||
|
||
|
||
/// Gauben eines Dachs (Index) für die Mengen ([G5]): je Gaube Breite, Stirnhöhe, geneigte Fläche des
|
||
/// Ausschnitts im Hauptdach, Volumen der Wände (Stirn/Wangen) und des Gaubendachs aus den Körpern.
|
||
/// Dach-Basismengen (IfcRoof) aus denselben Dachflächen wie 3D/Schnitt ([148]: Flach-/Pultdach auf dem
|
||
/// echten Umriss) und die Gaubenmengen. Nettofläche ohne Gauben-Ausschnitte und Dachfenster.
|
||
fn roof_base_quantities(p: &Project, roof: &Roof) -> (Vec<qty::Qty>, Vec<qty::Qty>) {
|
||
let planes = crate::roof::roof_geometry(&roof.params(), p.roof_base_elevation(roof)).planes;
|
||
let mut roof_q = qty::roof_quantities(&planes);
|
||
let ri = p.roofs.as_deref().unwrap_or(&[]).iter().position(|r| r.id == roof.id);
|
||
// Gauben ([G5]): Ausschnitt im Hauptdach (geneigt) von der Nettofläche ab, eigene Mengen der Gauben.
|
||
let dormer_q = ri.map_or_else(Vec::new, |ri| qty::dormer_quantities(&dormer_parts(p, ri, roof)));
|
||
let mut cut = dormer_q.iter().find(|q| q.name == "OpeningArea").map_or(0.0, |q| q.value);
|
||
// Dachfenster ([103]): Loch in der Dachfläche (Breite × Höhe auf der Fläche).
|
||
cut += ri.map_or(0.0, |ri| crate::opening_shape::roof_openings(p, ri).iter().map(|(o, _)| max(0.0, o.width) * max(0.0, o.height)).sum());
|
||
if let Some(net) = roof_q.iter_mut().find(|q| q.name == "NetArea") {
|
||
net.value = max(0.0, net.value - cut);
|
||
}
|
||
(roof_q, dormer_q)
|
||
}
|
||
|
||
fn dormer_parts(p: &Project, ri: usize, roof: &Roof) -> Vec<qty::DormerIn> {
|
||
let solids = crate::roof_assembly::roof_solids(p, ri);
|
||
let vol = |id: &str, role: crate::roof_assembly::Role| -> f64 {
|
||
solids.as_ref().map_or(0.0, |s| s.parts.iter().filter(|x| x.role == role && x.dormer.as_deref() == Some(id)).map(|x| x.mesh.volume().abs()).sum())
|
||
};
|
||
roof.dormers
|
||
.as_deref()
|
||
.unwrap_or(&[])
|
||
.iter()
|
||
.filter_map(|d| {
|
||
let g = crate::dormer::geometry(p, roof, d)?;
|
||
let hole = g.hole();
|
||
let n = hole.len();
|
||
let proj = (0..n).map(|i| hole[i][0] * hole[(i + 1) % n][1] - hole[(i + 1) % n][0] * hole[i][1]).sum::<f64>().abs() / 2.0;
|
||
Some(qty::DormerIn {
|
||
width: d.width,
|
||
front_height: g.front_height,
|
||
opening_area: proj * (1.0 + g.frame.tan_main * g.frame.tan_main).sqrt(),
|
||
wall_volume: vol(&d.id, crate::roof_assembly::Role::DormerWall),
|
||
roof_volume: vol(&d.id, crate::roof_assembly::Role::DormerRoof),
|
||
})
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
/// [259] Formöffnungen ([G3]) in den Wandmengen: die Rechteck-Rechnung zieht das ganze Rechteck ab, geschnitten wird
|
||
/// aber der Umriss (Rund-/Spitzbogen, Kreis). Liefert (Fläche, Volumen) zwischen Rechteck und Umriss, die netto
|
||
/// wieder dazukommen — dann stimmen die Mengen mit dem Körper nach ifcopenshell überein (±1 %).
|
||
fn shaped_cut_back(p: &Project, wall: &Wall, cutouts: &[(usize, Cutout)], openings: &[Opening]) -> (f64, f64) {
|
||
let total = p.wall_thickness(wall, 0.2);
|
||
let mut area = 0.0;
|
||
for &(k, c) in cutouts {
|
||
let (w, h) = (c.to - c.from, c.z_top - c.z_bottom);
|
||
if let Some(poly) = crate::opening_shape::opening_outline(&openings[k], w, h) {
|
||
let pts: Vec<Vec2> = poly.iter().map(|q| Vec2 { x: q[0], y: q[1] }).collect();
|
||
area += max(0.0, w * h - qty::ring_area(&pts));
|
||
}
|
||
}
|
||
(area, area * total)
|
||
}
|
||
|
||
/// [259] Formöffnungs-Rückgabe ([`shaped_cut_back`]) auf NetSideArea/NetVolume (Brutto mindestens netto).
|
||
fn add_back(quantities: &mut [Qty], (area, volume): (f64, f64)) {
|
||
for q in quantities.iter_mut() {
|
||
match q.name {
|
||
"NetSideArea" => q.value += area,
|
||
"NetVolume" => q.value += volume,
|
||
_ => {}
|
||
}
|
||
}
|
||
let net = quantities.iter().find(|q| q.name == "NetVolume").map_or(0.0, |q| q.value);
|
||
if let Some(g) = quantities.iter_mut().find(|q| q.name == "GrossVolume") {
|
||
g.value = max(g.value, net);
|
||
}
|
||
}
|
||
|
||
fn push_box(positions: &mut Vec<f64>, indices: &mut Vec<u32>, b: &[f64; 24], base: f64) {
|
||
let at = (positions.len() / 3) as u32;
|
||
for c in b.chunks_exact(3) {
|
||
positions.extend_from_slice(&[c[0], c[1], c[2] - base]);
|
||
}
|
||
indices.extend(box_tris_outward(b).iter().map(|i| at + i));
|
||
}
|
||
|
||
/// Sechsfaches Volumen mit Vorzeichen (positiv = nach aussen gewickelt; `mesh_volume` liefert den Betrag).
|
||
fn signed_volume6(positions: &[f64], indices: &[u32]) -> f64 {
|
||
let p = |i: u32| [positions[i as usize * 3], positions[i as usize * 3 + 1], positions[i as usize * 3 + 2]];
|
||
indices
|
||
.chunks_exact(3)
|
||
.map(|x| {
|
||
let (a, c, d) = (p(x[0]), p(x[1]), p(x[2]));
|
||
a[0] * (c[1] * d[2] - c[2] * d[1]) - a[1] * (c[0] * d[2] - c[2] * d[0]) + a[2] * (c[0] * d[1] - c[1] * d[0])
|
||
})
|
||
.sum()
|
||
}
|
||
|
||
/// [259] Dreiecke eines 8-Ecken-Quaders (Ecke i = Bits Achse 0/1/2 wie `model3d::OPENING_BOX_TRIS`) einheitlich nach
|
||
/// aussen gewickelt. `OPENING_BOX_TRIS` (3D, beidseitig gezeichnet; vorher auch hier) wickelt gegenüberliegende Flächen gleich — als Körper nicht
|
||
/// geschlossen: Manifold lehnt ab, IFC-Leser sehen eine verdrehte Schale.
|
||
fn box_tris_outward(b: &[f64; 24]) -> [u32; 36] {
|
||
// Je Fläche das Viereck im Umlauf; die erste der Paar-Flächen liegt bei Bit = 0 und wird umgedreht.
|
||
const QUADS: [([u32; 4], bool); 6] = [([0, 1, 3, 2], true), ([4, 5, 7, 6], false), ([0, 1, 5, 4], false), ([2, 3, 7, 6], true), ([0, 2, 6, 4], true), ([1, 3, 7, 5], false)];
|
||
let mut t = [0u32; 36];
|
||
for (k, (q, flip)) in QUADS.iter().enumerate() {
|
||
let tri = if *flip { [q[0], q[2], q[1], q[0], q[3], q[2]] } else { [q[0], q[1], q[2], q[0], q[2], q[3]] };
|
||
t[k * 6..k * 6 + 6].copy_from_slice(&tri);
|
||
}
|
||
if signed_volume6(b, &t) < 0.0 {
|
||
for tri in t.chunks_exact_mut(3) {
|
||
tri.swap(1, 2);
|
||
}
|
||
}
|
||
t
|
||
}
|
||
|
||
/// Füllung (Rahmen, Glas/Blatt) einer Formöffnung als Netz, Z relativ zur Geschoss-UK.
|
||
fn shaped_fill_mesh(p: &Project, wall: &Wall, o: &Opening, c: &Cutout, base: f64) -> (Vec<f64>, Vec<u32>) {
|
||
let total = p.wall_thickness(wall, 0.2);
|
||
let wr = crate::opening_geom::WallRef {
|
||
start: crate::opening_geom::v(wall.start.x, wall.start.y),
|
||
end: crate::opening_geom::v(wall.end.x, wall.end.y),
|
||
total,
|
||
ref_off: crate::joins::reference_offset(model3d::wall_reference(wall), total),
|
||
};
|
||
let wall_rgb = model3d::shaped_wall_opening_meshes(p, wall, &wr, o, [c.from, c.to, c.z_bottom, c.z_top]);
|
||
let (mut positions, mut indices) = (Vec::new(), Vec::new());
|
||
// Die Füllkörper (Wandfarbe) gehören zur Wand, nicht zur Füllung: die Öffnung schneidet sie ohnehin nicht.
|
||
let fills = model3d::shaped_fill_count(p, wall, o, c.to - c.from, c.z_top - c.z_bottom);
|
||
for m in wall_rgb.iter().skip(fills) {
|
||
if let Ok(b) = <[f64; 24]>::try_from(m.positions.as_slice()) {
|
||
push_box(&mut positions, &mut indices, &b, base);
|
||
}
|
||
}
|
||
(positions, indices)
|
||
}
|
||
|
||
#[allow(clippy::too_many_arguments)]
|
||
fn w_solid_opening(f: &mut Flat, s: &SolidOpening, structure: f64, o: &Opening, label: &str, (width, height): (f64, f64), psets: &[Pset], fill: &(Vec<f64>, Vec<u32>)) {
|
||
let (h, oid, lab) = (f.str(&s.host), f.str(&o.id), f.str(label));
|
||
f.nums(&[REC_OPENING_SOLID, h, structure, oid, if o.kind == ElementKind::Door { 1.0 } else { 0.0 }, lab]);
|
||
f.num(s.profile.len() as f64);
|
||
for q in &s.profile {
|
||
f.nums(q);
|
||
}
|
||
f.nums(&s.origin).nums(&s.x_dir).nums(&s.z_dir).nums(&[s.depth, height, width]);
|
||
w_psets(f, psets);
|
||
w_mesh(f, &fill.0, &fill.1, false);
|
||
}
|
||
|
||
fn w_fill(f: &mut Flat, wall: &Wall, c: &Cutout, host: (f64, f64), x: &FillParams) {
|
||
let opt = |f: &mut Flat, v: Option<f64>| {
|
||
f.nums(&[if v.is_some() { 1.0 } else { 0.0 }, v.unwrap_or(0.0)]);
|
||
};
|
||
let flag = |b: bool| if b { 1.0 } else { 0.0 };
|
||
f.nums(&[wall.start.x, wall.start.y, wall.end.x, wall.end.y, c.from, c.to, c.z_bottom, c.z_top, host.0, host.1]);
|
||
opt(f, x.frame_depth);
|
||
opt(f, x.inset);
|
||
f.num(flag(x.inset_outside));
|
||
opt(f, x.frame_width);
|
||
f.nums(&[x.wing_count, x.panes, x.sashes.len() as f64]);
|
||
for s in &x.sashes {
|
||
f.num(flag(s.post));
|
||
opt(f, s.post_width);
|
||
f.num(flag(s.fixed));
|
||
opt(f, s.width);
|
||
}
|
||
f.nums(&[x.door_kind, x.leaf_count, x.swing_sign, x.dir_sign, flag(x.hinge_at_start), x.transom_height, flag(x.glazed)]);
|
||
opt(f, x.glazing_ratio);
|
||
}
|
||
|
||
/// Ebene (Code, Name) eines Bauteils als Klassifikation; ohne Code `None`, ohne bekannte Ebene der
|
||
/// Code als Name.
|
||
fn layer_classification(p: &Project, category_code: &str) -> Option<(String, String)> {
|
||
let code = js_trim(category_code);
|
||
if code.is_empty() {
|
||
return None;
|
||
}
|
||
Some((code.to_string(), p.layer_category(code).map_or(code, |l| l.name.as_str()).to_string()))
|
||
}
|
||
|
||
|
||
// ── Klassifikation ──────────────────────────────────────────────────────────
|
||
|
||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||
enum Kind {
|
||
Wall,
|
||
Slab,
|
||
Roof,
|
||
Column,
|
||
Stair,
|
||
Window,
|
||
Door,
|
||
Space,
|
||
/// [259] Kontext (Gelände, Nachbargebäude): keine eBKP-H-Gruppe, nur die Ebene.
|
||
Context,
|
||
}
|
||
|
||
/// eBKP-H-Hauptgruppe zur Bauteilart, oder `None` (Tür, Raum: nicht eindeutig).
|
||
fn ebkph_group(k: Kind) -> Option<(&'static str, &'static str)> {
|
||
match k {
|
||
Kind::Wall | Kind::Slab | Kind::Column | Kind::Stair => Some(("C", "Konstruktion Gebäude")),
|
||
Kind::Roof => Some(("F", "Bedachung Gebäude")),
|
||
Kind::Window => Some(("E", "Äussere Wandbekleidung Gebäude")),
|
||
Kind::Door | Kind::Space | Kind::Context => None,
|
||
}
|
||
}
|
||
|
||
fn w_classification(f: &mut Flat, system: (&str, &str, &str), refs: &[(String, String, String)]) {
|
||
if refs.is_empty() {
|
||
return;
|
||
}
|
||
let (a, b, c) = (f.str(system.0), f.str(system.1), f.str(system.2));
|
||
f.nums(&[REC_CLASSIFICATION, a, b, c, refs.len() as f64]);
|
||
for (key, code, name) in refs {
|
||
let (a, b, c) = (f.str(key), f.str(code), f.str(name));
|
||
f.nums(&[a, b, c]);
|
||
}
|
||
}
|
||
|
||
fn sia_key(c: SiaCategory) -> String {
|
||
serde_json::to_value(c).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default()
|
||
}
|
||
|
||
fn sia_label(key: &str) -> &'static str {
|
||
match key {
|
||
"HNF" => "Hauptnutzfläche",
|
||
"NNF" => "Nebennutzfläche",
|
||
"VF" => "Verkehrsfläche",
|
||
"FF" => "Funktionsfläche",
|
||
"KGF" => "Konstruktionsfläche",
|
||
"AGF" => "Aussengeschossfläche",
|
||
_ => "",
|
||
}
|
||
}
|
||
|
||
const SIA_CATEGORIES: [SiaCategory; 6] = [SiaCategory::HNF, SiaCategory::NNF, SiaCategory::VF, SiaCategory::FF, SiaCategory::KGF, SiaCategory::AGF];
|
||
|
||
/// Der flache IFC-Puffer aus dem Projekt (s. Modulkopf).
|
||
pub fn ifc_export_data(src: &Project, opt: &IfcOptions) -> Result<Flat, String> {
|
||
// [259] Geometrie bleibt lokal (Modell-Meter); die Georeferenz trägt IfcMapConversion (Versatz zu LV95 und
|
||
// Höhe von ±0.00). LV95-Millionen in der Geometrie lassen Revit/Archicad warnen und kosten Genauigkeit.
|
||
let mut p = src.clone();
|
||
let mut f = Flat::new(FLAT_VERSION);
|
||
|
||
// Je "floor"-Ebene ein IfcBuildingStorey (Elevation = baseElevation).
|
||
let floors: Vec<DrawingLevel> = p.drawing_levels.iter().filter(|l| l.kind == DrawingLevelKind::Floor).cloned().collect();
|
||
let mut storey_of: HashMap<&str, usize> = HashMap::new();
|
||
let storey_base: Vec<f64> = floors.iter().map(|l| l.base_elevation.unwrap_or(0.0)).collect();
|
||
for (i, fl) in floors.iter().enumerate() {
|
||
storey_of.insert(fl.id.as_str(), i);
|
||
}
|
||
let structure_of = |floor_id: &str| -> f64 { storey_of.get(floor_id).map_or(-1.0, |&i| i as f64) };
|
||
let base_of = |structure: f64| -> f64 { if structure < 0.0 { 0.0 } else { storey_base[structure as usize] } };
|
||
|
||
// Kopf: RefElevation = reale Datumshöhe (informativ), RefLatitude/-Longitude des Bezugspunkts.
|
||
let anchor = p.geo_anchor.clone().filter(|a| a.lv95.e.is_finite() && a.lv95.n.is_finite() && a.model.x.is_finite() && a.model.y.is_finite());
|
||
// Höhe von Modell-z 0 (±0.00) über Meer: `referenceElevationMasl` ([131]), sonst die Höhe des Bezugspunkts.
|
||
let ref_elevation = p.reference_elevation_masl.or_else(|| anchor.as_ref().and_then(|a| a.height)).filter(|h| h.is_finite()).unwrap_or(f64::NAN);
|
||
let lat_lon = anchor.as_ref().map(|a| (a.lv95.e - a.model.x, a.lv95.n - a.model.y)).filter(|(e, n)| e.is_finite() && n.is_finite()).map(|(e, n)| lv95_to_wgs84(e, n)).filter(|(la, lo)| la.is_finite() && lo.is_finite());
|
||
// Anonyme Abgabe ([208]): Kennwort statt Projektname, fester Zeitstempel; leerer `iso` heisst für den Schreiber
|
||
// „anonym" (neutrale Erzeuger-/Autorangaben, `fileio/ifc_export`).
|
||
let anon = crate::competition::anonymous_keyword(&p);
|
||
let (pid, pname) = (f.str(&p.id), f.str(anon.as_deref().unwrap_or(&p.name)));
|
||
let (now, iso) = if anon.is_some() { (crate::competition::NEUTRAL_EPOCH, f.str("")) } else { (opt.now, f.str(&opt.iso)) };
|
||
f.nums(&[
|
||
pid,
|
||
pname,
|
||
now,
|
||
iso,
|
||
if anchor.is_some() { 1.0 } else { 0.0 },
|
||
ref_elevation,
|
||
lat_lon.map_or(f64::NAN, |x| x.0),
|
||
lat_lon.map_or(f64::NAN, |x| x.1),
|
||
anchor.as_ref().map_or(0.0, |a| a.lv95.e - a.model.x),
|
||
anchor.as_ref().map_or(0.0, |a| a.lv95.n - a.model.y),
|
||
if opt.ifc2x3 { 1.0 } else { 0.0 },
|
||
floors.len() as f64,
|
||
]);
|
||
for (i, fl) in floors.iter().enumerate() {
|
||
let (a, b) = (f.str(&fl.id), f.str(&fl.name));
|
||
f.nums(&[a, b, storey_base[i]]);
|
||
}
|
||
|
||
// [201] Übernommene GlobalIds (IFC-Import) vor allen Bauteilen; jede GlobalId höchstens einmal
|
||
// (Kopien tragen sie nicht, doppelt importierte Dateien würden sonst kollidieren).
|
||
{
|
||
let mut guids: Vec<(String, String)> = Vec::new();
|
||
let mut push = |key: String, g: &Option<String>| {
|
||
if let Some(g) = g.as_deref().filter(|g| !g.is_empty()) {
|
||
guids.push((key, g.to_string()));
|
||
}
|
||
};
|
||
p.walls.iter().for_each(|x| push(format!("wall/{}", x.id), &x.ifc_global_id));
|
||
p.ceilings.iter().flatten().for_each(|x| push(format!("slab/{}", x.id), &x.ifc_global_id));
|
||
p.roofs.iter().flatten().for_each(|x| push(format!("roof/{}", x.id), &x.ifc_global_id));
|
||
p.columns.iter().flatten().for_each(|x| push(format!("column/{}", x.id), &x.ifc_global_id));
|
||
p.stairs.iter().flatten().for_each(|x| push(format!("stair/{}", x.id), &x.ifc_global_id));
|
||
p.rooms.iter().flatten().for_each(|x| push(format!("space/{}", x.id), &x.ifc_global_id));
|
||
p.extruded_solids.iter().flatten().for_each(|x| push(format!("extrusion/{}", x.id), &x.ifc_global_id));
|
||
p.openings.iter().flatten().for_each(|x| push(format!("fill/{}", x.id), &x.ifc_global_id));
|
||
let mut seen = std::collections::HashSet::new();
|
||
guids.retain(|(_, g)| seen.insert(g.clone()));
|
||
if !guids.is_empty() {
|
||
f.nums(&[REC_GUIDS, guids.len() as f64]);
|
||
for (k, g) in guids {
|
||
let (a, b) = (f.str(&k), f.str(&g));
|
||
f.nums(&[a, b]);
|
||
}
|
||
}
|
||
}
|
||
|
||
// Klassifikation: je geschriebenem Bauteil Schlüssel (wie für die GUID), Art und Ebene; `fileio`
|
||
// überspringt Schlüssel ohne geschriebenes Bauteil.
|
||
let mut classified: Vec<(String, Kind, String)> = Vec::new();
|
||
|
||
let component_name = |p: &Project, id: &str| -> String { p.component(id).map_or_else(|| id.to_string(), |c| c.name.clone()) };
|
||
|
||
// ── Wände ──────────────────────────────────────────────────────────────
|
||
let all_bands = model3d::emit_walls(&p, true)?;
|
||
let mut bands_by_wall: HashMap<&str, Vec<&RWall>> = HashMap::new();
|
||
for b in &all_bands {
|
||
bands_by_wall.entry(b.wall_id.as_str()).or_default().push(b);
|
||
}
|
||
// [T2] Bogenwände ohne Öffnungen: Körper als Bogenprofil-Extrusion, die Öffnungen schneiden als
|
||
// IfcOpeningElement (Netz-Weg nur noch mit Dachanschluss/Aussparungen).
|
||
let arc_plain: HashMap<String, Vec<RWall>> = {
|
||
let ids: std::collections::HashSet<&str> = p.walls.iter().filter(|w| crate::wall_arc::is_arc_bulge(w.bulge)).map(|w| w.id.as_str()).collect();
|
||
let mut m: HashMap<String, Vec<RWall>> = HashMap::new();
|
||
if !ids.is_empty() {
|
||
let mut q = p.clone();
|
||
q.openings = p.openings.as_ref().map(|v| v.iter().filter(|o| !ids.contains(o.host_wall_id.as_str())).cloned().collect());
|
||
for b in model3d::emit_walls(&q, true)? {
|
||
if ids.contains(b.wall_id.as_str()) {
|
||
m.entry(b.wall_id.clone()).or_default().push(b);
|
||
}
|
||
}
|
||
}
|
||
m
|
||
};
|
||
let mut arc_solid: std::collections::HashSet<String> = std::collections::HashSet::new();
|
||
let no_bands: Vec<&RWall> = Vec::new();
|
||
let mut host_extent: HashMap<String, (f64, f64)> = HashMap::new();
|
||
let mut cutouts_by_wall: HashMap<String, Vec<(usize, Cutout)>> = HashMap::new();
|
||
let mut mesh_walls: Vec<usize> = Vec::new();
|
||
let openings: Vec<Opening> = p.openings.clone().unwrap_or_default();
|
||
let wall_ident = |p: &Project, wall: &Wall, quantities: Vec<Qty>| -> (String, Option<TypeData>, Vec<Pset>) {
|
||
let q = qto("Qto_WallBaseQuantities", quantities);
|
||
// Aussen/tragend nur mit Angabe im Modell (nichts erfunden).
|
||
let mut props: Vec<Prop> = Vec::new();
|
||
match p.wall_type(wall) {
|
||
Some(wt) => {
|
||
let layers = wt.layers.iter().map(|l| (l.component_id.clone(), component_name(p, &l.component_id), l.thickness)).collect();
|
||
props.push(ident("Reference", &wt.name));
|
||
props.extend(structure_props(wall.is_external, wall.load_bearing));
|
||
props.extend(crate::u_value::wall_u_value(p, wall).and_then(|u| u.u).map(|u| Prop::Thermal("ThermalTransmittance", u)));
|
||
let mut ps = vec![Pset { name: "Pset_WallCommon", props }];
|
||
ps.extend(q);
|
||
(wt.name.clone(), Some((wt.id.clone(), wt.name.clone(), layers)), ps)
|
||
}
|
||
None => {
|
||
props.extend(structure_props(wall.is_external, wall.load_bearing));
|
||
let mut ps = if props.is_empty() { Vec::new() } else { vec![Pset { name: "Pset_WallCommon", props }] };
|
||
ps.extend(q);
|
||
(wall.id.clone(), None, ps)
|
||
}
|
||
}
|
||
};
|
||
let cutouts_of = |p: &Project, wall: &Wall| -> Vec<(usize, Cutout)> {
|
||
let mut out = Vec::new();
|
||
let (zb, zt) = p.wall_vertical_extent(wall);
|
||
let axis = crate::wall_arc::axis_length(wall);
|
||
for (k, o) in openings.iter().enumerate().filter(|(_, o)| o.host_wall_id == wall.id) {
|
||
let from = max(0.0, min(o.position, axis));
|
||
let to = max(from, min(o.position + o.width, axis));
|
||
if to - from < 1e-4 {
|
||
continue;
|
||
}
|
||
let bottom = zb + max(0.0, o.sill_height);
|
||
let top = min(zt, bottom + o.height);
|
||
out.push((k, Cutout { from, to, z_bottom: bottom, z_top: top }));
|
||
}
|
||
out
|
||
};
|
||
|
||
for (wi, wall) in p.walls.iter().enumerate() {
|
||
let all = bands_by_wall.get(wall.id.as_str()).unwrap_or(&no_bands);
|
||
let bands: Vec<&RWall> = all.iter().copied().filter(|b| hypot2(b.end[0] - b.start[0], b.end[1] - b.start[1]) > 1e-9 && b.height > 1e-9 && b.thickness > 1e-9).collect();
|
||
if bands.is_empty() {
|
||
continue; // degenerierte Wand / keine Geometrie
|
||
}
|
||
let cutouts = cutouts_of(&p, wall);
|
||
let plain: Vec<Cutout> = cutouts.iter().map(|x| x.1).collect();
|
||
cutouts_by_wall.insert(wall.id.clone(), cutouts);
|
||
classified.push((format!("wall/{}", wall.id), Kind::Wall, wall.category_code.clone()));
|
||
// Bogenwand ([T2]): immer als Netz (Sehnen-Körper) mit Kreisbogen-Achse.
|
||
if crate::wall_arc::WallArc::of_wall(wall).is_some() || !bands_match_openings(wall, &bands, &plain) {
|
||
mesh_walls.push(wi);
|
||
continue;
|
||
}
|
||
let structure = structure_of(&wall.floor_id);
|
||
let mut quantities = qty::wall_quantities(wall.start, wall.end, &bands, &plain, None);
|
||
add_back(&mut quantities, shaped_cut_back(&p, wall, cutouts_by_wall.get(&wall.id).map_or(&[][..], |v| v.as_slice()), &openings));
|
||
let (name, ty, psets) = wall_ident(&p, wall, quantities);
|
||
// Wandsystem: Placement am Wandanfang, X = Achse, Y = linke Normale; IfcMaterialLayerSetUsage nur,
|
||
// wenn die Typ-Schichten den Querschnitt der Bänder füllen (sonst wäre der Offset gelogen).
|
||
let extent = cross_extent(wall, &bands);
|
||
let layer_sum = ty.as_ref().map_or(0.0, |t| t.2.iter().fold(0.0, |a, l| a + l.2));
|
||
let usage = ty.is_some() && layer_sum > 0.0 && (extent.1 - extent.0 - layer_sum).abs() < 1e-3;
|
||
w_head(&mut f, REC_WALL_SOLIDS, structure, &wall.id, &name);
|
||
w_type(&mut f, ty.as_ref().map(|t| type_ref(t, 0.0, "STANDARD")).as_ref());
|
||
w_psets(&mut f, &psets);
|
||
let u = normalize(sub(wall.end, wall.start));
|
||
f.nums(&[1.0, wall.start.x, wall.start.y, u.x, u.y, hypot2(wall.end.x - wall.start.x, wall.end.y - wall.start.y), if usage { 1.0 } else { 0.0 }, if usage { extent.0 } else { 0.0 }]);
|
||
f.num(bands.len() as f64);
|
||
let base = base_of(structure);
|
||
for b in &bands {
|
||
// Grundriss-Viereck an den Schnittlinien (Gehrung, schräger Stoss, [108]) wie das 3D.
|
||
match model3d::wall_footprint(b) {
|
||
Some(q) => w_pts(&mut f, &[v2(q[3]), v2(q[2]), v2(q[1]), v2(q[0])]),
|
||
None => {
|
||
let (s, e) = (v2(b.start), v2(b.end));
|
||
let n = left_normal(normalize(sub(e, s)));
|
||
let h = b.thickness / 2.0;
|
||
w_pts(&mut f, &[add_scaled(s, n, -h), add_scaled(e, n, -h), add_scaled(e, n, h), add_scaled(s, n, h)]);
|
||
}
|
||
}
|
||
f.nums(&[b.base_elevation - base, b.height]);
|
||
}
|
||
host_extent.insert(wall.id.clone(), extent);
|
||
}
|
||
// Netz-Weg: alle Bänder einer Wand zu EINEM Face-Set; Modell-Welt (x, Höhe, y) → IFC (x, y, z),
|
||
// die Spiegelung kehrt die Wicklung um, daher (a, c, b). Z relativ zur Geschoss-UK.
|
||
for &wi in &mesh_walls {
|
||
let wall = &p.walls[wi];
|
||
let structure = structure_of(&wall.floor_id);
|
||
let base = base_of(structure);
|
||
let bands = bands_by_wall.get(wall.id.as_str()).unwrap_or(&no_bands);
|
||
// [T2] Bogenwand als Profil-Extrusion (Kreisbögen), Kreisachse dazu.
|
||
if let Some(a) = crate::wall_arc::WallArc::of_wall(wall) {
|
||
if let Some(profiles) = arc_plain.get(&wall.id).and_then(|v| arc_wall_profiles(&a, v, base)) {
|
||
let total = p.wall_thickness(wall, 0.2);
|
||
let ro = crate::joins::reference_offset(model3d::wall_reference(wall), total);
|
||
let (zb, zt) = p.wall_vertical_extent(wall);
|
||
let plain: Vec<Cutout> = cutouts_by_wall.get(&wall.id).map_or_else(Vec::new, |v| v.iter().map(|x| x.1).collect());
|
||
// [259] Mengen aus den geschriebenen Profilen (Schichten enden an der Decke, Eckstücke): Brutto = Σ
|
||
// Profilfläche × Höhe (exakt mit Bögen; Profil-Bulge im DXF-Sinn → Modell-Sinn), netto abzüglich der
|
||
// Öffnungen als Ringsektoren — vorher volle Wandhöhe über alle Schichten (Erker 5 % zu viel).
|
||
let gross: f64 = profiles
|
||
.iter()
|
||
.map(|(ring, _, depth)| {
|
||
let pts: Vec<Vec2> = ring.iter().map(|v| Vec2 { x: v[0], y: v[1] }).collect();
|
||
let bulge: Vec<f64> = ring.iter().map(|v| -v[2]).collect();
|
||
crate::ring_arc::signed_area(&pts, Some(&bulge)).abs() * depth
|
||
})
|
||
.sum();
|
||
let mut quantities = qty::arc_wall_quantities(&a, ro - total / 2.0, ro + total / 2.0, zb, zt, &plain, None);
|
||
let exact = qty::arc_wall_quantities(&a, ro - total / 2.0, ro + total / 2.0, zb, zt, &[], None);
|
||
let full = exact.iter().find(|q| q.name == "GrossVolume").map_or(0.0, |q| q.value);
|
||
let cut = full - quantities.iter().find(|q| q.name == "NetVolume").map_or(full, |q| q.value);
|
||
for q in quantities.iter_mut() {
|
||
match q.name {
|
||
"GrossVolume" => q.value = gross,
|
||
"NetVolume" => q.value = max(0.0, gross - cut),
|
||
_ => {}
|
||
}
|
||
}
|
||
let (name, ty, psets) = wall_ident(&p, wall, quantities);
|
||
w_head(&mut f, REC_WALL_ARC_SOLID, structure, &wall.id, &name);
|
||
w_type(&mut f, ty.as_ref().map(|t| type_ref(t, 0.0, "STANDARD")).as_ref());
|
||
w_psets(&mut f, &psets);
|
||
f.nums(&[a.center.x, a.center.y, a.r, a.a0, a.sweep]);
|
||
f.num(profiles.len() as f64);
|
||
for (ring, z_rel, depth) in &profiles {
|
||
f.num(ring.len() as f64);
|
||
for v in ring {
|
||
f.nums(v);
|
||
}
|
||
f.nums(&[*z_rel, *depth]);
|
||
}
|
||
host_extent.insert(wall.id.clone(), (ro - total / 2.0, ro + total / 2.0));
|
||
arc_solid.insert(wall.id.clone());
|
||
continue;
|
||
}
|
||
}
|
||
let (mut positions, mut indices) = (Vec::<f64>::new(), Vec::<u32>::new());
|
||
for b in bands {
|
||
// Ebene Oberkante unter einem Dach ([G2]): Prisma bis an die Dachunterkante.
|
||
if b.top_plane.is_some() && b.holes.as_ref().is_none_or(|h| h.is_empty()) {
|
||
if let Some(m) = model3d::wall_piece_mesh(b) {
|
||
let at = (positions.len() / 3) as u32;
|
||
for c in m.positions.chunks_exact(3) {
|
||
positions.extend_from_slice(&[c[0], c[1], c[2] - base]);
|
||
}
|
||
indices.extend(m.indices.iter().map(|i| at + i));
|
||
}
|
||
continue;
|
||
}
|
||
let mut cut = wall_cut_mesh_checked(&CutWall {
|
||
start: b.start,
|
||
end: b.end,
|
||
thickness: b.thickness,
|
||
base_elevation: b.base_elevation,
|
||
height: b.height,
|
||
holes: b.holes.as_deref().unwrap_or(&[]).iter().map(|h| [h.from, h.to, h.z_bottom, h.z_top]).collect(),
|
||
});
|
||
// Enden auf die Schnittlinien (Gehrung, schräger Stoss, [108]) wie OBJ/STL/GLB.
|
||
crate::mesh_data::shift_cut_ends(&mut cut, b);
|
||
let at = (positions.len() / 3) as u32;
|
||
for c in cut.chunks_exact(3) {
|
||
positions.extend_from_slice(&[c[0], c[2], c[1] - base]);
|
||
}
|
||
let n = (cut.len() / 3) as u32;
|
||
let mut i = 0;
|
||
while i + 2 < n {
|
||
indices.extend_from_slice(&[at + i, at + i + 2, at + i + 1]);
|
||
i += 3;
|
||
}
|
||
}
|
||
let arc = crate::wall_arc::WallArc::of_wall(wall);
|
||
// [168] Schichteinzug-Stücke (Überdämmung, Leibungsputz) berühren die Bänder nur teilweise: dann die
|
||
// Bänder zu EINEM Körper vereinigen (Manifold, exakt) — mehrere sich teilweise berührende Schalen
|
||
// verrechnet ein IFC-Leser beim Abzug der Öffnungskörper (ifcopenshell: Volumen falsch).
|
||
// Formöffnungen ([G3]): Füllkörper zwischen Rechteck-Loch und Umriss gehören zur Wand (nicht bei
|
||
// Bogenwänden: dort bleibt das Rechteck-Loch).
|
||
let mut boxes: Vec<[f64; 24]> = Vec::new();
|
||
for &(k, c) in cutouts_by_wall.get(&wall.id).map_or(&[][..], |v| v.as_slice()).iter().filter(|_| arc.is_none()) {
|
||
let o = &openings[k];
|
||
let n = model3d::shaped_fill_count(&p, wall, o, c.to - c.from, c.z_top - c.z_bottom);
|
||
if n == 0 {
|
||
continue;
|
||
}
|
||
let total = p.wall_thickness(wall, 0.2);
|
||
let wr = crate::opening_geom::WallRef {
|
||
start: crate::opening_geom::v(wall.start.x, wall.start.y),
|
||
end: crate::opening_geom::v(wall.end.x, wall.end.y),
|
||
total,
|
||
ref_off: crate::joins::reference_offset(model3d::wall_reference(wall), total),
|
||
};
|
||
for m in model3d::shaped_wall_opening_meshes(&p, wall, &wr, o, [c.from, c.to, c.z_bottom, c.z_top]).iter().take(n) {
|
||
if let Ok(b) = <[f64; 24]>::try_from(m.positions.as_slice()) {
|
||
boxes.push(b);
|
||
}
|
||
}
|
||
}
|
||
// [259] Mehrere Schalen (Bänder, Stücke, Füllkörper) zu einem Körper; lehnt Manifold ab, bleiben die Schalen.
|
||
let shells = bands.len() + boxes.len();
|
||
match (arc.is_none() && shells > 1).then(|| union_bands(bands, base, &boxes)).flatten() {
|
||
Some((up, ui)) => (positions, indices) = (up, ui),
|
||
None => {
|
||
for b in &boxes {
|
||
push_box(&mut positions, &mut indices, b, base);
|
||
}
|
||
}
|
||
}
|
||
if indices.is_empty() {
|
||
continue;
|
||
}
|
||
// Closed nur, wenn das Netz nachweislich dicht und aussen orientiert ist.
|
||
let closed = is_watertight(&positions, &indices, 1e-6);
|
||
let net = closed.then(|| crate::export_flat::mesh_volume(&positions, &indices));
|
||
let plain: Vec<Cutout> = cutouts_by_wall.get(&wall.id).map_or_else(Vec::new, |v| v.iter().map(|x| x.1).collect());
|
||
let total = p.wall_thickness(wall, 0.2);
|
||
let ro = crate::joins::reference_offset(model3d::wall_reference(wall), total);
|
||
let mut quantities = match &arc {
|
||
Some(a) => {
|
||
let (zb, zt) = p.wall_vertical_extent(wall);
|
||
// Längen/Flächen exakt aus dem Kreis. [259] Volumen: dichtes Netz = geschriebener Körper (Schichten enden
|
||
// an der Decke; vorher volle Höhe über alle Schichten, Erker OG 23 % zu viel), Brutto = netto + Öffnungen.
|
||
let mut q = qty::arc_wall_quantities(a, ro - total / 2.0, ro + total / 2.0, zb, zt, &plain, None);
|
||
if let Some(nv) = net {
|
||
let full = qty::arc_wall_quantities(a, ro - total / 2.0, ro + total / 2.0, zb, zt, &[], None);
|
||
let gross = full.iter().find(|x| x.name == "GrossVolume").map_or(0.0, |x| x.value);
|
||
let cut = gross - q.iter().find(|x| x.name == "NetVolume").map_or(gross, |x| x.value);
|
||
for x in q.iter_mut() {
|
||
match x.name {
|
||
"GrossVolume" => x.value = nv + cut,
|
||
"NetVolume" => x.value = nv,
|
||
_ => {}
|
||
}
|
||
}
|
||
}
|
||
q
|
||
}
|
||
None => qty::wall_quantities(wall.start, wall.end, bands, &plain, net),
|
||
};
|
||
if net.is_none() && arc.is_none() {
|
||
let gross = quantities.iter().find(|x| x.name == "GrossVolume").map_or(f64::NAN, |x| x.value);
|
||
if let Some(nv) = quantities.iter_mut().find(|x| x.name == "NetVolume") {
|
||
nv.value = max(0.0, gross - qty::hole_volume(bands));
|
||
}
|
||
}
|
||
if arc.is_none() {
|
||
// Geschlossenes Netz: Volumen enthält die Füllkörper der Formöffnung schon, nur die Ansichtsfläche nicht.
|
||
let (area, volume) = shaped_cut_back(&p, wall, cutouts_by_wall.get(&wall.id).map_or(&[][..], |v| v.as_slice()), &openings);
|
||
add_back(&mut quantities, (area, if net.is_some() { 0.0 } else { volume }));
|
||
}
|
||
let (name, ty, psets) = wall_ident(&p, wall, quantities);
|
||
w_head(&mut f, if arc.is_some() { REC_WALL_ARC } else { REC_WALL_MESH }, structure, &wall.id, &name);
|
||
w_type(&mut f, ty.as_ref().map(|t| type_ref(t, 0.0, "STANDARD")).as_ref());
|
||
w_psets(&mut f, &psets);
|
||
if let Some(a) = &arc {
|
||
f.nums(&[a.center.x, a.center.y, a.r, a.a0, a.sweep]);
|
||
}
|
||
w_mesh(&mut f, &positions, &indices, closed);
|
||
host_extent.insert(wall.id.clone(), if arc.is_some() { (ro - total / 2.0, ro + total / 2.0) } else { cross_extent(wall, bands) });
|
||
}
|
||
|
||
// ── Decken ─────────────────────────────────────────────────────────────
|
||
for c in p.ceilings.as_deref().unwrap_or(&[]) {
|
||
if c.outline.len() < 3 {
|
||
continue;
|
||
}
|
||
let (z_bottom, z_top) = p.ceiling_vertical_extent(c);
|
||
let structure = structure_of(&c.floor_id);
|
||
classified.push((format!("slab/{}", c.id), Kind::Slab, c.category_code.clone()));
|
||
let mut name = c.id.clone();
|
||
let mut ty: Option<TypeData> = None;
|
||
let mut psets: Vec<Pset> = Vec::new();
|
||
let mut slab_props: Vec<Prop> = Vec::new();
|
||
if let Some((id, tname, layers)) = model3d::ceiling_type_ref(&p, c) {
|
||
name = tname.to_string();
|
||
ty = Some((id.to_string(), tname.to_string(), layers.iter().map(|l| (l.component_id.clone(), component_name(&p, &l.component_id), l.thickness)).collect()));
|
||
slab_props.push(ident("Reference", tname));
|
||
}
|
||
slab_props.extend(crate::u_value::ceiling_u_value(&p, c).and_then(|u| u.u).map(|u| Prop::Thermal("ThermalTransmittance", u)));
|
||
slab_props.extend(structure_props(c.is_external, c.load_bearing));
|
||
if !slab_props.is_empty() {
|
||
psets.push(Pset { name: "Pset_SlabCommon", props: slab_props });
|
||
}
|
||
// Aussparungen (wie im 3D) als innere Ringe des Profils; Netto zieht sie ab.
|
||
let hole_rings = crate::opening_shape::ceiling_hole_rings(&p, c);
|
||
let inner: Vec<&[Vec2]> = hole_rings.iter().filter(|r| r.len() >= 3).map(|r| r.as_slice()).collect();
|
||
// [191] Bögen im Umriss: Mengen auf dem fein geteilten Ring, Profil mit echten Bögen (s. unten).
|
||
let outline = c.ring();
|
||
psets.extend(qto("Qto_SlabBaseQuantities", qty::slab_quantities(&outline, &inner, z_top - z_bottom)));
|
||
// Mit Bögen: Profil als IfcCompositeCurve (CEILING_ARC); die gehosteten Fensteröffnungen sind gerade.
|
||
let arcs = c.has_arcs();
|
||
w_head(&mut f, if arcs { REC_CEILING_ARC } else { REC_CEILING }, structure, &c.id, &name);
|
||
w_type(&mut f, ty.as_ref().map(|t| type_ref(t, 1.0, "FLOOR")).as_ref());
|
||
w_psets(&mut f, &psets);
|
||
if arcs {
|
||
w_bpts(&mut f, &c.outline, c.outline_bulge.as_deref());
|
||
let drawn = c.openings.as_deref().unwrap_or(&[]);
|
||
let rest = hole_rings.iter().skip(drawn.len()).filter(|r| r.len() >= 3);
|
||
let n = drawn.iter().filter(|r| r.len() >= 3).count() + rest.clone().count();
|
||
f.num(n as f64);
|
||
for (i, h) in drawn.iter().enumerate().filter(|(_, h)| h.len() >= 3) {
|
||
w_bpts(&mut f, h, c.openings_bulge.as_deref().and_then(|b| b.get(i)).map(Vec::as_slice));
|
||
}
|
||
for r in rest {
|
||
w_bpts(&mut f, r, None);
|
||
}
|
||
} else {
|
||
w_pts(&mut f, &outline);
|
||
f.num(inner.len() as f64);
|
||
for r in &inner {
|
||
w_pts(&mut f, r);
|
||
}
|
||
}
|
||
f.nums(&[z_bottom - base_of(structure), z_top - z_bottom]);
|
||
}
|
||
|
||
// ── Öffnungen: IfcOpeningElement in der Wand, IfcDoor/IfcWindow darin ───
|
||
for wall in &p.walls {
|
||
let Some(&host) = host_extent.get(&wall.id) else { continue };
|
||
let structure = structure_of(&wall.floor_id);
|
||
let arc = crate::wall_arc::WallArc::of_wall(wall);
|
||
for &(k, c) in cutouts_by_wall.get(&wall.id).map_or(&[][..], |v| v.as_slice()) {
|
||
let o = &openings[k];
|
||
// Bogenwand ([T2]): Ersatzwand = Sehne zwischen den Laibungen; Öffnungskörper innerhalb des
|
||
// (radialen) Lochs, Füllung um den Achsversatz der Sehne verschoben.
|
||
let solid_arc = arc_solid.contains(&wall.id);
|
||
let radial = arc.filter(|_| solid_arc).map(|a| arc_opening_quad(&a, c.from, c.to, host));
|
||
let chord = arc.map(|a| arc_opening_chord(wall, &a, &c, host));
|
||
let (wall, c, host, shrink, sag) = match &chord {
|
||
Some((vw, vc, vh, e, d)) => (vw, *vc, *vh, *e, *d),
|
||
None => (wall, c, host, 0.0, 0.0),
|
||
};
|
||
let depth = c.z_top - c.z_bottom;
|
||
if !(depth > 1e-6) {
|
||
continue;
|
||
}
|
||
let is_door = o.kind == ElementKind::Door;
|
||
classified.push((format!("fill/{}", o.id), if is_door { Kind::Door } else { Kind::Window }, o.category_code.clone()));
|
||
let psets = fill_psets(&p, o, c.to - c.from, depth);
|
||
let label = crate::plan::walls::opening_label(o);
|
||
// Formöffnung ([G3]): Öffnungskörper = Umriss quer durch die Wand, Füllung als Netz (Bogenwand
|
||
// mit Profil-Körper: auf der Sehne, quer um den Pfeil verlängert).
|
||
if let Some(poly) = crate::opening_shape::opening_outline(o, c.to - c.from, depth).filter(|_| chord.is_none() || solid_arc) {
|
||
let u = normalize(sub(wall.end, wall.start));
|
||
let ln = left_normal(u);
|
||
let extra = OPENING_OVERSHOOT + sag;
|
||
let at = add_scaled(add_scaled(wall.start, u, c.from), ln, host.1 + extra);
|
||
let solid = SolidOpening {
|
||
host: format!("wall/{}", wall.id),
|
||
profile: poly,
|
||
origin: [at.x, at.y, c.z_bottom - base_of(structure)],
|
||
x_dir: [u.x, u.y, 0.0],
|
||
z_dir: [-ln.x, -ln.y, 0.0],
|
||
depth: host.1 - host.0 + 2.0 * extra,
|
||
};
|
||
let fill = shaped_fill_mesh(&p, wall, o, &c, base_of(structure));
|
||
w_solid_opening(&mut f, &solid, structure, o, &label, (c.to - c.from, depth), &psets, &fill);
|
||
continue;
|
||
}
|
||
let a = f.str(&wall.id);
|
||
let oid = f.str(&o.id);
|
||
let lab = f.str(&label);
|
||
f.nums(&[REC_OPENING, a, structure, oid, if is_door { 1.0 } else { 0.0 }, lab]);
|
||
// [168] Schichteinzug mit Stücken in der Öffnung (Überdämmung, Leibungsputz): das Wandnetz trägt
|
||
// die Löcher schon; der Öffnungskörper bleibt in der Rahmenlage (frei von Stücken), sonst schnitte
|
||
// er die Stücke wieder aus der Wand.
|
||
let (vlo, vhi) = match reveal_frame_slice(&p, wall, o).filter(|_| chord.is_none()) {
|
||
Some(s) => s,
|
||
None => (host.0 - sag - OPENING_OVERSHOOT, host.1 + sag + OPENING_OVERSHOOT),
|
||
};
|
||
match &radial {
|
||
Some(q) => w_pts(&mut f, q),
|
||
None => w_pts(&mut f, &axis_rect(wall, c.from + shrink, c.to - shrink, vlo, vhi)),
|
||
}
|
||
f.nums(&[c.z_bottom - base_of(structure), depth, c.to - c.from]);
|
||
w_fill(&mut f, wall, &c, host, &fill_params(&p, o));
|
||
w_psets(&mut f, &psets);
|
||
}
|
||
}
|
||
|
||
// ── Treppen: Läufe, Podest, Geländer wie im 3D; ohne Teile der Fussabdruck-Quader ──
|
||
let stairs = p.stairs.take();
|
||
for st in stairs.as_deref().unwrap_or(&[]) {
|
||
let footprint = stair_footprint(st);
|
||
if footprint.len() < 3 {
|
||
continue;
|
||
}
|
||
let (z_bottom, z_top) = p.stair_vertical_extent(st);
|
||
let structure = structure_of(&st.floor_id);
|
||
classified.push((format!("stair/{}", st.id), Kind::Stair, st.category_code.clone()));
|
||
let predefined = crate::ifc_stairs::stair_predefined(st);
|
||
let base = base_of(structure);
|
||
p.stairs = Some(vec![st.clone()]);
|
||
let parts = stair_parts(&p, st, base);
|
||
w_stair(&mut f, structure, &st.id, predefined, &footprint, z_bottom - base, z_top - z_bottom, &parts);
|
||
}
|
||
p.stairs = stairs;
|
||
|
||
// ── Extrudierte Körper → IfcBuildingElementProxy ───────────────────────
|
||
for s in p.extruded_solids.as_deref().unwrap_or(&[]) {
|
||
if s.points.len() < 3 {
|
||
continue;
|
||
}
|
||
let base = floors.iter().find(|fl| fl.id == s.level_id).and_then(|fl| fl.base_elevation).unwrap_or(0.0);
|
||
let structure = structure_of(&s.level_id);
|
||
let id = f.str(&s.id);
|
||
f.nums(&[REC_EXTRUSION, structure, id]);
|
||
w_pts(&mut f, &s.points);
|
||
f.nums(&[base - base_of(structure), s.height]);
|
||
}
|
||
|
||
// ── Räume → IfcSpace (im Geschoss aggregiert), Basismengen, SIA-416-Kategorie ──
|
||
let mut room_areas: Vec<(String, String, SiaCategory, f64)> = Vec::new();
|
||
for room in p.rooms.as_deref().unwrap_or(&[]) {
|
||
if room.boundary.len() < 3 {
|
||
continue;
|
||
}
|
||
let structure = structure_of(&room.floor_id);
|
||
let height = floors.iter().find(|fl| fl.id == room.floor_id).and_then(|fl| fl.floor_height).filter(|h| *h != 0.0 && !h.is_nan() && *h > 0.0).unwrap_or(2.5);
|
||
let external = room.sia_category == SiaCategory::AGF;
|
||
let area = crate::ring_arc::evaluate(&room.boundary, room.boundary_bulge.as_deref(), 0.0);
|
||
room_areas.push((room.id.clone(), room.floor_id.clone(), room.sia_category, area.net));
|
||
classified.push((format!("space/{}", room.id), Kind::Space, room.category_code.clone()));
|
||
let number = room.stamp.as_ref().and_then(|s| s.number.as_deref()).filter(|n| !n.is_empty());
|
||
let mut common: Vec<Prop> = Vec::new();
|
||
if let Some(n) = number {
|
||
common.push(ident("Reference", n));
|
||
}
|
||
common.push(Prop::Bool("IsExternal", external));
|
||
let (id, name, long) = (f.str(&room.id), f.str(number.unwrap_or(&room.id)), f.str(&room.name));
|
||
let arcs = crate::ring_arc::has_arcs(room.boundary_bulge.as_deref(), room.boundary.len());
|
||
f.nums(&[if arcs { REC_SPACE_ARC } else { REC_SPACE }, structure, id, name, long, if external { 1.0 } else { 0.0 }, height]);
|
||
if arcs {
|
||
w_bpts(&mut f, &room.boundary, room.boundary_bulge.as_deref());
|
||
} else {
|
||
w_pts(&mut f, &room.ring());
|
||
}
|
||
let cat = f.str(&sia_key(room.sia_category));
|
||
f.nums(&[area.net, area.gross, cat]);
|
||
// [158] Raumbuch: Oberflächen als Pset_SpaceCoveringRequirements (IFC2x3: in Pset_SpaceCommon),
|
||
// Nutzung und Bodenaufbau im eigenen Pset; nur mit Angaben im Modell.
|
||
let label = |v: Option<&str>| crate::room_book::finish_label(&p, v);
|
||
let coverings: Vec<Prop> = [("FloorCovering", label(room.floor_finish.as_deref())), ("WallCovering", label(room.wall_finish.as_deref())), ("CeilingCovering", label(room.ceiling_finish.as_deref()))]
|
||
.into_iter()
|
||
.filter(|(_, v)| !v.is_empty())
|
||
.map(|(k, v)| Prop::Label(k, v))
|
||
.collect();
|
||
let mut psets = Vec::new();
|
||
if opt.ifc2x3 {
|
||
common.extend(coverings);
|
||
psets.push(Pset { name: "Pset_SpaceCommon", props: common });
|
||
} else {
|
||
psets.push(Pset { name: "Pset_SpaceCommon", props: common });
|
||
if !coverings.is_empty() {
|
||
psets.push(Pset { name: "Pset_SpaceCoveringRequirements", props: coverings });
|
||
}
|
||
}
|
||
let mut book: Vec<Prop> = Vec::new();
|
||
book.extend(room.usage.map(|u| u.key()).filter(|k| !k.is_empty()).map(|k| Prop::Label("Usage", k.to_string())));
|
||
book.extend(room.floor_build_up.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(|s| Prop::Label("FloorBuildUp", s.to_string())));
|
||
if !book.is_empty() {
|
||
psets.push(Pset { name: "Dossier_RoomBook", props: book });
|
||
}
|
||
w_psets(&mut f, &psets);
|
||
}
|
||
f.num(REC_END_SPACES);
|
||
|
||
// SIA 416: je vorkommender Kategorie eine IfcZone mit den Räumen.
|
||
for cat in SIA_CATEGORIES {
|
||
let members: Vec<&(String, String, SiaCategory, f64)> = room_areas.iter().filter(|r| r.2 == cat).collect();
|
||
if members.is_empty() {
|
||
continue;
|
||
}
|
||
let net = members.iter().fold(0.0, |a, r| a + r.3);
|
||
let key = sia_key(cat);
|
||
let (k, n, l) = (f.str(&format!("sia416/{key}")), f.str(&key), f.str(sia_label(&key)));
|
||
f.nums(&[REC_ZONE, k, n, l, members.len() as f64]);
|
||
for r in &members {
|
||
let id = f.str(&r.0);
|
||
f.num(id);
|
||
}
|
||
w_psets(
|
||
&mut f,
|
||
&[
|
||
Pset { name: "CH_Zone", props: vec![ident("SIA416", &key)] },
|
||
Pset { name: "CH_Qto_SIA416", props: vec![Prop::Qty("NetFloorArea", QtyKind::Area, max(0.0, net))] },
|
||
],
|
||
);
|
||
}
|
||
// Geschoss-Kennwerte ([259]: aus der Flächentabelle wie Kennzahlen/Flächenbilanz, GF = NGF + KF mit der
|
||
// Konstruktionsfläche der Wände): GF/NGF/Höhe/GV als Basismenge des IfcBuildingStorey, alle SIA-416-Flächen als
|
||
// CH_Qto_SIA416; Summen am IfcBuilding.
|
||
let table = crate::flaechen::area_table(&p);
|
||
for row in &table.levels {
|
||
if row.rooms == 0 && row.kf <= 0.0 {
|
||
continue;
|
||
}
|
||
let key = f.str(&format!("storey/{}", row.level_id));
|
||
f.nums(&[REC_ATTACH, key]);
|
||
let mut base = vec![Prop::Qty("GrossFloorArea", QtyKind::Area, max(0.0, row.gf)), Prop::Qty("NetFloorArea", QtyKind::Area, max(0.0, row.ngf))];
|
||
if row.height > 0.0 {
|
||
base.push(Prop::Qty("GrossHeight", QtyKind::Length, row.height));
|
||
base.push(Prop::Qty("GrossVolume", QtyKind::Volume, max(0.0, row.gv)));
|
||
}
|
||
let sia = [("HNF", row.hnf), ("NNF", row.nnf), ("NF", row.nf), ("VF", row.vf), ("FF", row.ff), ("NGF", row.ngf), ("KGF", row.kf), ("AGF", row.agf), ("GF", row.gf)];
|
||
w_psets(
|
||
&mut f,
|
||
&[
|
||
Pset { name: "Qto_BuildingStoreyBaseQuantities", props: base },
|
||
Pset { name: "CH_Qto_SIA416", props: sia.iter().map(|(k, v)| Prop::Qty(k, QtyKind::Area, max(0.0, *v))).collect() },
|
||
],
|
||
);
|
||
}
|
||
if table.total.gf > 0.0 {
|
||
let key = f.str("building");
|
||
f.nums(&[REC_ATTACH, key]);
|
||
let t = &table.total;
|
||
let sia = [("HNF", t.hnf), ("NNF", t.nnf), ("NF", t.nf), ("VF", t.vf), ("FF", t.ff), ("NGF", t.ngf), ("KGF", t.kf), ("AGF", t.agf), ("GF", t.gf), ("GV", table.gv)];
|
||
w_psets(
|
||
&mut f,
|
||
&[
|
||
Pset {
|
||
name: "Qto_BuildingBaseQuantities",
|
||
props: vec![Prop::Qty("GrossFloorArea", QtyKind::Area, max(0.0, t.gf)), Prop::Qty("NetFloorArea", QtyKind::Area, max(0.0, t.ngf)), Prop::Qty("GrossVolume", QtyKind::Volume, max(0.0, table.gv))],
|
||
},
|
||
Pset { name: "CH_Qto_SIA416", props: sia.iter().map(|(k, v)| Prop::Qty(k, if *k == "GV" { QtyKind::Volume } else { QtyKind::Area }, max(0.0, *v))).collect() },
|
||
],
|
||
);
|
||
}
|
||
|
||
// ── Dächer → IfcRoof (Schicht-Netze wie im 3D, ein Face-Set je Dach, Modell ist Z-oben) ──
|
||
let roofs = p.roofs.take();
|
||
for roof in roofs.as_deref().unwrap_or(&[]) {
|
||
let structure = structure_of(&roof.floor_id);
|
||
let base = base_of(structure);
|
||
classified.push((format!("roof/{}", roof.id), Kind::Roof, roof.category_code.clone()));
|
||
// Alle Dächer im Projekt lassen (Verschneidung [G5] braucht die Nachbarn), nur dieses ausgeben.
|
||
p.roofs = roofs.clone();
|
||
let meshes = model3d::emit_roofs(&p, Some(&roof.id))?;
|
||
let (mut positions, mut indices) = (Vec::<f64>::new(), Vec::<u32>::new());
|
||
for m in &meshes {
|
||
let at = (positions.len() / 3) as u32;
|
||
for c in m.positions.chunks_exact(3) {
|
||
positions.extend_from_slice(&[c[0], c[1], c[2] - base]);
|
||
}
|
||
indices.extend(m.indices.iter().map(|i| at + i));
|
||
}
|
||
if indices.is_empty() {
|
||
continue;
|
||
}
|
||
let mut closed = is_watertight(&positions, &indices, 1e-6);
|
||
if !closed {
|
||
let flipped: Vec<u32> = indices.chunks_exact(3).flat_map(|t| [t[0], t[2], t[1]]).collect();
|
||
if is_watertight(&positions, &flipped, 1e-6) {
|
||
indices = flipped;
|
||
closed = true;
|
||
}
|
||
}
|
||
let predefined = roof_predefined(roof.shape);
|
||
let roof_type = roof.roof_type_id.as_deref().filter(|s| !s.is_empty()).and_then(|id| p.roof_types.as_deref().unwrap_or(&[]).iter().find(|t| t.id == id));
|
||
// Ein Dach ist Gebäudehülle: IsExternal folgt aus der Bauteilart.
|
||
let mut props: Vec<Prop> = Vec::new();
|
||
if let Some(t) = roof_type {
|
||
props.push(ident("Reference", &t.name));
|
||
}
|
||
props.push(Prop::Bool("IsExternal", true));
|
||
props.extend(crate::u_value::roof_u_value(&p, roof).and_then(|u| u.u).map(|u| Prop::Thermal("ThermalTransmittance", u)));
|
||
let mut psets = vec![Pset { name: "Pset_RoofCommon", props }];
|
||
let (roof_q, dormer_q) = roof_base_quantities(&p, roof);
|
||
psets.extend(qto("Qto_RoofBaseQuantities", roof_q));
|
||
psets.extend(qto("Qto_DossierDormerQuantities", dormer_q));
|
||
let ty = roof_type.map(|t| (t.id.clone(), t.name.clone(), t.layers.iter().map(|l| (l.component_id.clone(), component_name(&p, &l.component_id), l.thickness)).collect::<Vec<_>>()));
|
||
let (id, name, pre) = (f.str(&roof.id), f.str(roof_type.map_or("Dach", |t| t.name.as_str())), f.str(predefined));
|
||
f.nums(&[REC_ROOF, structure, id, name, pre]);
|
||
w_type(&mut f, ty.as_ref().map(|t| type_ref(t, 2.0, predefined)).as_ref());
|
||
w_psets(&mut f, &psets);
|
||
w_mesh(&mut f, &positions, &indices, closed);
|
||
}
|
||
p.roofs = roofs;
|
||
|
||
// ── Dach-/Deckenfenster ([103]): IfcOpeningElement im Dach bzw. in der Decke, IfcWindow/IfcDoor darin ──
|
||
for o in openings.iter() {
|
||
let Some(fr) = crate::opening_shape::host_frame(&p, o) else { continue };
|
||
let (host_key, floor_id) = if fr.plane.is_some() || fr.dormer {
|
||
let r = &p.roofs.as_deref().unwrap_or(&[])[fr.host];
|
||
(format!("roof/{}", r.id), r.floor_id.clone())
|
||
} else {
|
||
let c = &p.ceilings.as_deref().unwrap_or(&[])[fr.host];
|
||
(format!("slab/{}", c.id), c.floor_id.clone())
|
||
};
|
||
let structure = structure_of(&floor_id);
|
||
let base = base_of(structure);
|
||
let is_door = o.kind == ElementKind::Door;
|
||
classified.push((format!("fill/{}", o.id), if is_door { Kind::Door } else { Kind::Window }, o.category_code.clone()));
|
||
let (w, h) = (o.width, o.height);
|
||
// Profil-Y = Z × X = −eh: Ursprung an der oberen Ecke, das Profil läuft das Gefälle hinab.
|
||
let corner = fr.at(-w / 2.0, h / 2.0, -0.5);
|
||
let solid = SolidOpening {
|
||
host: host_key,
|
||
profile: vec![[0.0, 0.0], [w, 0.0], [w, h], [0.0, h]],
|
||
origin: [corner[0], corner[1], corner[2] - base],
|
||
x_dir: fr.ew,
|
||
z_dir: [-fr.n[0], -fr.n[1], -fr.n[2]],
|
||
depth: fr.thickness + 1.0,
|
||
};
|
||
let (mut positions, mut indices) = (Vec::new(), Vec::new());
|
||
for (_, b) in crate::opening_shape::surface_window_boxes(&p, o, &fr) {
|
||
push_box(&mut positions, &mut indices, &b, base);
|
||
}
|
||
let psets = fill_psets(&p, o, w, h);
|
||
let label = crate::plan::walls::opening_label(o);
|
||
w_solid_opening(&mut f, &solid, structure, o, &label, (w, h), &psets, &(positions, indices));
|
||
}
|
||
|
||
// ── Stützen → IfcColumn (Profil-Extrusion, Material = Bauteil) ──────────
|
||
for col in p.columns.as_deref().unwrap_or(&[]) {
|
||
// [141] Von einer prioritäreren Wand beschnitten: je Höhenabschnitt ein eigenes Profil (wie im 3D),
|
||
// als Datensatz COLUMN_PIECES mit mehreren Extrusionen in einer Darstellung; ein Abschnitt = COLUMN.
|
||
let pieces: Vec<(Vec<Vec2>, f64, f64)> = model3d::column_pieces(&p, col).into_iter().filter(|(fp, zb, zt)| fp.len() >= 3 && zt > zb).collect();
|
||
let pieces = if pieces.is_empty() {
|
||
let (zb, zt) = p.column_vertical_extent(col);
|
||
vec![(model3d::column_footprint(col), zb, zt)]
|
||
} else {
|
||
pieces
|
||
};
|
||
let z_bottom = pieces.iter().fold(f64::INFINITY, |m, q| m.min(q.1));
|
||
let z_top = pieces.iter().fold(f64::NEG_INFINITY, |m, q| m.max(q.2));
|
||
if pieces.iter().any(|(fp, zb, zt)| fp.len() < 3 || !(zt > zb)) {
|
||
continue;
|
||
}
|
||
let structure = structure_of(&col.floor_id);
|
||
classified.push((format!("column/{}", col.id), Kind::Column, col.category_code.clone()));
|
||
let label = crate::plan::domains::column_label(col);
|
||
let mut psets = vec![Pset { name: "Pset_ColumnCommon", props: vec![ident("Reference", &label)] }];
|
||
let quantities = if let [(footprint, zb, zt)] = pieces.as_slice() {
|
||
qty::column_quantities(footprint, zt - zb)
|
||
} else {
|
||
qty::column_pieces_quantities(&pieces)
|
||
};
|
||
psets.extend(qto("Qto_ColumnBaseQuantities", quantities));
|
||
let (id, lab) = (f.str(&col.id), f.str(&label));
|
||
if let [(footprint, _, _)] = pieces.as_slice() {
|
||
f.nums(&[REC_COLUMN, structure, id, lab]);
|
||
w_pts(&mut f, footprint);
|
||
f.nums(&[z_bottom - base_of(structure), z_top - z_bottom]);
|
||
} else {
|
||
f.nums(&[REC_COLUMN_PIECES, structure, id, lab, pieces.len() as f64]);
|
||
for (footprint, zb, zt) in &pieces {
|
||
w_pts(&mut f, footprint);
|
||
f.nums(&[zb - base_of(structure), zt - zb]);
|
||
}
|
||
}
|
||
let comp = col.component_id.as_deref().filter(|s| !s.is_empty());
|
||
let cid = comp.map_or(-1.0, |c| f.str(c));
|
||
let cname = comp.map_or(-1.0, |c| {
|
||
let n = component_name(&p, c);
|
||
f.str(&n)
|
||
});
|
||
f.nums(&[cid, cname]);
|
||
w_psets(&mut f, &psets);
|
||
}
|
||
f.num(REC_END_COLUMNS);
|
||
|
||
// ── Bäume ([149]) → IfcGeographicElement (IFC2x3: IfcBuildingElementProxy), Netz Stamm + Krone ──
|
||
let trees = p.trees.as_deref().unwrap_or(&[]);
|
||
for (i, g) in crate::tree::geoms(&p) {
|
||
let t = &trees[i];
|
||
let structure = structure_of(&t.floor_id);
|
||
let base = base_of(structure);
|
||
let (mut positions, mut indices) = g.trunk_mesh(8);
|
||
let (cp, ci) = g.crown_mesh(8, 12);
|
||
let at = (positions.len() / 3) as u32;
|
||
positions.extend(cp);
|
||
indices.extend(ci.iter().map(|k| at + k));
|
||
for z in positions.iter_mut().skip(2).step_by(3) {
|
||
*z -= base;
|
||
}
|
||
let status = match t.status {
|
||
TreeStatus::New => "new",
|
||
TreeStatus::Remove => "remove",
|
||
_ => "existing",
|
||
};
|
||
let mut props = vec![ident("Status", status), ident("Foliage", if t.foliage == TreeFoliage::Conifer { "conifer" } else { "deciduous" })];
|
||
if let Some(sp) = t.species.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
|
||
props.push(Prop::Label("Species", sp.to_string()));
|
||
}
|
||
let mut psets = vec![Pset { name: "Dossier_Tree", props }];
|
||
psets.extend(qto(
|
||
"Dossier_Qto_Tree",
|
||
vec![
|
||
Qty { name: "Height", kind: QtyKind::Length, value: g.top - g.base },
|
||
Qty { name: "CrownDiameter", kind: QtyKind::Length, value: 2.0 * g.crown_r },
|
||
Qty { name: "TrunkDiameter", kind: QtyKind::Length, value: 2.0 * g.trunk_r },
|
||
Qty { name: "CrownBaseHeight", kind: QtyKind::Length, value: g.crown_bottom - g.base },
|
||
],
|
||
));
|
||
let (id, name) = (f.str(&t.id), f.str(&crate::tree::label(t)));
|
||
f.nums(&[REC_TREE, structure, id, name]);
|
||
w_psets(&mut f, &psets);
|
||
// Zwei getrennte geschlossene Körper: nicht als ein dichtes Netz melden (IFC2x3: Flächenmodell).
|
||
w_mesh(&mut f, &positions, &indices, false);
|
||
}
|
||
|
||
// ── [259] Kontext (Option): Gelände und Nachbarn am IfcSite, Höhen absolut (Modell-z, ±0.00 = 0) ──
|
||
if opt.context {
|
||
for c in p.context.iter().flatten() {
|
||
let (kind, id, name, code, positions, indices) = match c {
|
||
ContextObject::TerrainMesh(m) => (1.0, &m.id, &m.name, &m.category_code, &m.positions, &m.indices),
|
||
ContextObject::ImportedMesh(m) if crate::import_context::is_context_class(&m.category_code) => (0.0, &m.id, &m.name, &m.category_code, &m.positions, &m.indices),
|
||
_ => continue,
|
||
};
|
||
let n = positions.len() / 3;
|
||
if n < 3 || indices.len() < 3 || positions.iter().any(|v| !v.is_finite()) {
|
||
continue;
|
||
}
|
||
let tris: Vec<u32> = indices
|
||
.chunks_exact(3)
|
||
.filter(|t| t.iter().all(|i| i.is_finite() && *i >= 0.0 && (*i as usize) < n) && t[0] != t[1] && t[1] != t[2] && t[0] != t[2])
|
||
.flat_map(|t| t.iter().map(|i| *i as u32).collect::<Vec<_>>())
|
||
.collect();
|
||
if tris.is_empty() {
|
||
continue;
|
||
}
|
||
classified.push((format!("context/{id}"), Kind::Context, code.clone()));
|
||
// Klasse als Beschreibung („12 Gebäude"), damit sie im Fremdprogramm ohne Klassifikation lesbar bleibt.
|
||
let class = layer_classification(&p, code).map(|(c, n)| format!("{c} {n}")).unwrap_or_default();
|
||
let (a, b, c) = (f.str(id), f.str(if name.is_empty() { id } else { name }), f.str(&class));
|
||
f.nums(&[REC_CONTEXT, kind, a, b, c]);
|
||
w_mesh(&mut f, &positions[..n * 3], &tris, false);
|
||
}
|
||
}
|
||
|
||
// ── Achsraster ([112]) → IfcGrid (U-/V-Achsen als Linienzüge in Welt-XY) ──
|
||
for d in &p.drawings2d {
|
||
let Some(spec) = crate::grid::Spec::of(&d.geom) else { continue };
|
||
let Drawing2DGeom::Grid { levels, .. } = &d.geom else { continue };
|
||
// Ein Geschoss: dort enthalten; mehrere oder alle: am Gebäude.
|
||
let only = match levels.as_deref() {
|
||
Some([one]) => Some(one.as_str()),
|
||
_ => None,
|
||
};
|
||
let structure = only.map_or(-1.0, structure_of);
|
||
let axes = spec.axes();
|
||
if axes.is_empty() {
|
||
continue;
|
||
}
|
||
let (id, name) = (f.str(&d.id), f.str(&format!("Achsraster {}", d.id)));
|
||
f.nums(&[REC_GRID, structure, id, name, spec.a.len() as f64, (axes.len() - spec.a.len()) as f64]);
|
||
for ax in &axes {
|
||
let pts: Vec<Vec2> = crate::grid::polyline(ax).into_iter().map(|(x, y)| Vec2 { x, y }).collect();
|
||
let lab = f.str(&ax.label);
|
||
f.nums(&[lab]);
|
||
w_pts(&mut f, &pts);
|
||
}
|
||
}
|
||
|
||
// ── Klassifikation (Optionen), am Ende: alle Bauteile sind geschrieben ──
|
||
if opt.ebkph {
|
||
let refs: Vec<(String, String, String)> =
|
||
classified.iter().filter_map(|(key, kind, _)| ebkph_group(*kind).map(|(c, n)| (key.clone(), c.to_string(), n.to_string()))).collect();
|
||
w_classification(&mut f, ("eBKP-H", "CRB Schweizerische Zentralstelle für Baurationalisierung", "SN 506 511:2020"), &refs);
|
||
}
|
||
if opt.layer_codes {
|
||
let refs: Vec<(String, String, String)> =
|
||
classified.iter().filter_map(|(key, _, code)| layer_classification(&p, code).map(|(c, n)| (key.clone(), c, n))).collect();
|
||
w_classification(&mut f, ("Dossier-Ebenen", "Dossier", ""), &refs);
|
||
}
|
||
Ok(f)
|
||
}
|
||
|
||
#[allow(clippy::too_many_arguments)]
|
||
fn w_stair(f: &mut Flat, structure: f64, id: &str, predefined: &str, footprint: &[Vec2], z_rel: f64, depth: f64, parts: &StairParts) {
|
||
let (a, b) = (f.str(id), f.str(predefined));
|
||
f.nums(&[REC_STAIR, structure, a, b]);
|
||
w_pts(f, footprint);
|
||
f.nums(&[z_rel, depth]);
|
||
w_psets(f, &[]);
|
||
f.num(parts.flights.len() as f64);
|
||
for fl in &parts.flights {
|
||
let n = f.str(&fl.name);
|
||
f.nums(&[n, fl.risers, fl.treads, fl.riser_height, fl.tread_length]);
|
||
let p = f.str(fl.predefined);
|
||
f.num(p);
|
||
let mut psets = qto("Qto_StairFlightBaseQuantities", fl.quantities.clone());
|
||
if let Some(a) = fl.soffit_area {
|
||
psets.extend(qto("Dossier_Qto_StairFlight", vec![Qty { name: "SoffitArea", kind: QtyKind::Area, value: a }]));
|
||
}
|
||
w_psets(f, &psets);
|
||
match &fl.body {
|
||
FlightBody::Mesh(m) => {
|
||
f.num(1.0);
|
||
w_mesh(f, &m.positions, &m.indices, false);
|
||
}
|
||
FlightBody::Solids(solids) => {
|
||
f.nums(&[0.0, solids.len() as f64]);
|
||
for s in solids {
|
||
w_pts(f, &s.pts);
|
||
f.nums(&[s.z_rel, s.depth]);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
// Podeste: Anzahl, dann je Podest (ein Podest heisst „Podest“, mehrere „Podest 1“, „Podest 2“).
|
||
f.num(parts.landings.len() as f64);
|
||
for (k, l) in parts.landings.iter().enumerate() {
|
||
let n = f.str(&if parts.landings.len() > 1 { format!("Podest {}", k + 1) } else { "Podest".to_string() });
|
||
f.num(n);
|
||
w_pts(f, &l.pts);
|
||
f.nums(&[l.z_rel, l.depth]);
|
||
w_psets(f, &qto("Qto_SlabBaseQuantities", l.quantities.clone()));
|
||
}
|
||
// Geländer: Anzahl, dann je Geländer (Handlauf der Treppe, [155] Absturzsicherung am Deckenloch).
|
||
let rails: Vec<(&str, &str, &crate::ifc_stairs::Rail)> = parts.rail.iter().map(|r| ("Handlauf", "HANDRAIL", r)).chain(parts.guard.iter().map(|r| ("Absturzsicherung", "GUARDRAIL", r))).collect();
|
||
f.num(rails.len() as f64);
|
||
for (name, predefined, r) in rails {
|
||
let (n, pre) = (f.str(name), f.str(predefined));
|
||
f.nums(&[n, pre]);
|
||
w_psets(f, &qto("Qto_RailingBaseQuantities", r.quantities.clone()));
|
||
w_mesh(f, &r.mesh.positions, &r.mesh.indices, false);
|
||
}
|
||
match &parts.column {
|
||
Some(c) => {
|
||
let n = f.str("Spindel");
|
||
f.nums(&[1.0, n]);
|
||
w_pts(f, &c.pts);
|
||
f.nums(&[c.z_rel, c.depth]);
|
||
w_psets(f, &qto("Qto_ColumnBaseQuantities", c.quantities.clone()));
|
||
}
|
||
None => {
|
||
f.num(0.0);
|
||
}
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use crate::export_flat::from_bytes;
|
||
|
||
fn sample() -> Project {
|
||
serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap()
|
||
}
|
||
|
||
fn strings(f: &Flat) -> Vec<String> {
|
||
let (_, text) = from_bytes(&f.to_bytes()).unwrap();
|
||
text.split('\0').map(String::from).collect()
|
||
}
|
||
|
||
/// [259] Kontext nur mit Option: Gelände (jede Klasse) und Netze auf Umgebungsklassen; ein Netz auf einer
|
||
/// Bauteil-Klasse (z. B. importierte Möblierung) bleibt draussen, ebenso kaputte Dreiecke.
|
||
#[test]
|
||
fn kontext_nur_mit_option() {
|
||
let mut p = sample();
|
||
let tri = |id: &str, code: &str| ImportedMesh { id: id.into(), name: format!("Netz {id}"), category_code: code.into(), positions: vec![0.0, 0.0, 0.0, 9.0, 0.0, 0.0, 0.0, 9.0, 3.0], indices: vec![0.0, 1.0, 2.0, 0.0, 0.0, 1.0, 0.0, 1.0, 7.0], ..Default::default() };
|
||
let terrain = TerrainMesh { id: "gel".into(), name: "Gelände".into(), category_code: "02".into(), positions: vec![0.0, 0.0, -1.0, 50.0, 0.0, -1.0, 0.0, 50.0, 0.5], indices: vec![0.0, 1.0, 2.0], ..Default::default() };
|
||
p.context = Some(vec![ContextObject::ImportedMesh(tri("nb", "12")), ContextObject::ImportedMesh(tri("moebel", "20")), ContextObject::TerrainMesh(terrain)]);
|
||
let count = |f: &Flat| f.nums.iter().filter(|v| **v == REC_CONTEXT).count();
|
||
let off = ifc_export_data(&p, &IfcOptions::default()).unwrap();
|
||
assert!(!strings(&off).iter().any(|s| s == "nb" || s == "gel"));
|
||
let on = ifc_export_data(&p, &IfcOptions { context: true, ..Default::default() }).unwrap();
|
||
let s = strings(&on);
|
||
assert!(count(&on) >= 2);
|
||
for want in ["nb", "Netz nb", "12 Gebäude", "gel", "Gelände"] {
|
||
assert!(s.iter().any(|x| x == want), "fehlt: {want}");
|
||
}
|
||
assert!(!s.iter().any(|x| x == "moebel"), "Netz auf Bauteil-Klasse ist kein Kontext");
|
||
// Datei: Nachbar mit einem gültigen Dreieck (die beiden kaputten fallen weg), Gelände am Grundstück.
|
||
let (nums, text) = from_bytes(&on.to_bytes()).unwrap();
|
||
let ifc = fileio_like_check(&nums, &text);
|
||
assert_eq!(ifc, 2);
|
||
}
|
||
|
||
/// Zählt die CONTEXT-Datensätze mit gültigem Dreiecksnetz im Puffer (Kopf: 24, kind, id, name, class, MESH).
|
||
fn fileio_like_check(nums: &[f64], text: &str) -> usize {
|
||
let strs: Vec<&str> = text.split('\0').collect();
|
||
let mut n = 0;
|
||
for i in 0..nums.len().saturating_sub(6) {
|
||
if nums[i] == REC_CONTEXT && (nums[i + 1] == 0.0 || nums[i + 1] == 1.0) && strs.get(nums[i + 2] as usize).is_some_and(|s| *s == "nb" || *s == "gel") {
|
||
let nv = nums[i + 5] as usize;
|
||
let nt = nums[i + 6 + nv * 3] as usize;
|
||
assert_eq!(nt, 1, "ein Dreieck je Netz");
|
||
n += 1;
|
||
}
|
||
}
|
||
n
|
||
}
|
||
|
||
/// [259] Geschoss-Mengen wie die Flächentabelle: GF = NGF + Konstruktionsfläche (Wände), nicht nur die Räume.
|
||
#[test]
|
||
fn geschoss_mengen_mit_konstruktionsflaeche() {
|
||
let p = sample();
|
||
let t = crate::flaechen::area_table(&p);
|
||
let row = t.levels.iter().find(|r| r.kf > 0.0 && r.rooms > 0).expect("Geschoss mit Wänden und Räumen");
|
||
let f = ifc_export_data(&p, &IfcOptions::default()).unwrap();
|
||
let (nums, _) = from_bytes(&f.to_bytes()).unwrap();
|
||
assert!(row.gf > row.ngf);
|
||
assert!(nums.iter().any(|v| (*v - row.gf).abs() < 1e-9), "GF {} fehlt", row.gf);
|
||
assert!(nums.iter().any(|v| (*v - row.kf).abs() < 1e-9), "KGF {} fehlt", row.kf);
|
||
let s = strings(&f);
|
||
assert!(s.iter().any(|x| x == "building") && s.iter().any(|x| x == "Qto_BuildingBaseQuantities"));
|
||
}
|
||
|
||
/// [259] Quader der Formöffnungs-Füllkörper: einheitlich nach aussen gewickelt (dicht, Volumen positiv), auch
|
||
/// bei gespiegelter Eckenreihenfolge.
|
||
#[test]
|
||
fn quader_nach_aussen_gewickelt() {
|
||
let corner = |i: usize, sx: f64| [sx * (i & 1) as f64 * 2.0, ((i >> 1) & 1) as f64 * 3.0, ((i >> 2) & 1) as f64 * 0.5];
|
||
for sx in [1.0, -1.0] {
|
||
let b: [f64; 24] = std::array::from_fn(|k| corner(k / 3, sx)[k % 3]);
|
||
let t = box_tris_outward(&b);
|
||
assert!((crate::export_flat::mesh_volume(&b, &t) - 3.0).abs() < 1e-12);
|
||
assert!(is_watertight(&b, &t, 1e-9));
|
||
assert!(crate::solid_bool::Solid::new(&crate::solid_bool::Mesh { positions: b.to_vec(), indices: t.to_vec() }).is_ok());
|
||
}
|
||
}
|
||
|
||
/// [208] Anonyme Abgabe: Kopf trägt Kennwort, festen Zeitstempel und leeren ISO-Text, nie den Projektnamen.
|
||
#[test]
|
||
fn anonyme_abgabe_kopf() {
|
||
let mut p = sample();
|
||
p.name = "BUEROXY Haus".into();
|
||
let opt = IfcOptions { now: 1_794_583_435.0, iso: "2026-11-13T15:23:55".into(), ..Default::default() };
|
||
let plain = ifc_export_data(&p, &opt).unwrap();
|
||
assert!(strings(&plain).iter().any(|s| s == "BUEROXY Haus"));
|
||
p.competition = Some(crate::model::CompetitionSettings { anonymous: true, keyword: "FALKE 7".into(), ..Default::default() });
|
||
let f = ifc_export_data(&p, &opt).unwrap();
|
||
let s = strings(&f);
|
||
assert!(!s.iter().any(|x| x.contains("BUEROXY")), "{s:?}");
|
||
assert!(s.iter().any(|x| x == "FALKE 7"));
|
||
assert!(!s.iter().any(|x| x.starts_with("2026-")));
|
||
assert_eq!(f.nums[3], crate::competition::NEUTRAL_EPOCH);
|
||
}
|
||
|
||
/// [149] Baum als eigener Datensatz (nach den Stützen): Name = Art, Netz Stamm + Krone relativ zur
|
||
/// Geschoss-UK, Höhe als Menge.
|
||
#[test]
|
||
fn baum_datensatz() {
|
||
let mut p = sample();
|
||
let floor = p.drawing_levels.iter().find(|l| l.kind == DrawingLevelKind::Floor).unwrap().id.clone();
|
||
let mut t = Tree { id: "T1".into(), r#type: "tree".into(), floor_id: "eg".into(), category_code: "13".into(), position: Vec2 { x: 20.0, y: 5.0 }, trunk_diameter: 0.4, crown_diameter: 6.0, crown_base: 3.0, height: 12.0, species: Some("Quercus robur".into()), ..Default::default() };
|
||
t.floor_id = floor;
|
||
p.trees = Some(vec![t]);
|
||
let f = ifc_export_data(&p, &IfcOptions::default()).unwrap();
|
||
let s = strings(&f);
|
||
assert!(s.iter().any(|x| x == "T1") && s.iter().any(|x| x == "Quercus robur") && s.iter().any(|x| x == "Dossier_Qto_Tree"));
|
||
assert!(f.nums.windows(2).any(|w| w == [REC_END_COLUMNS, REC_TREE]), "Baum direkt nach den Stützen");
|
||
// Ohne Bäume kein Datensatz.
|
||
p.trees = None;
|
||
assert!(!strings(&ifc_export_data(&p, &IfcOptions::default()).unwrap()).iter().any(|x| x == "Dossier_Qto_Tree"));
|
||
}
|
||
|
||
/// [G3]/[103] Formöffnung und Dachfenster als Öffnungskörper-Datensatz mit Wirt.
|
||
#[test]
|
||
fn formoeffnung_und_dachfenster() {
|
||
let mut p = sample();
|
||
for o in p.openings.iter_mut().flatten().filter(|o| o.id == "O1") {
|
||
o.shape = Some(OpeningShape::Spitzbogen);
|
||
}
|
||
p.openings.as_mut().unwrap().push(Opening { id: "DF".into(), kind: ElementKind::Window, width: 0.78, height: 1.18, host_roof_id: Some("RF1".into()), host_point: Some(Vec2 { x: 2.5, y: 1.0 }), ..Default::default() });
|
||
let f = ifc_export_data(&p, &IfcOptions::default()).unwrap();
|
||
let s = strings(&f);
|
||
assert!(s.iter().any(|x| x == "wall/W1") && s.iter().any(|x| x == "roof/RF1"));
|
||
assert_eq!(f.nums.iter().filter(|v| **v == REC_OPENING_SOLID).count() >= 2, true);
|
||
}
|
||
|
||
/// [148] Flachdach auf L-Umriss: IFC-Mengen aus dem echten Umriss (60 m², nicht 66 m² Bounding-Box),
|
||
/// Nettofläche ohne Dachfenster.
|
||
#[test]
|
||
fn flachdach_l_mengen() {
|
||
let mut p = sample();
|
||
{
|
||
let r = &mut p.roofs.as_mut().unwrap()[0];
|
||
r.outline = [(0.0, 0.0), (11.0, 0.0), (11.0, 4.0), (8.0, 4.0), (8.0, 6.0), (0.0, 6.0)].iter().map(|&(x, y)| Vec2 { x, y }).collect();
|
||
r.shape = crate::model::RoofShape::Flach;
|
||
r.pitch_deg = 0.0;
|
||
r.overhang = 0.0;
|
||
}
|
||
p.openings.as_mut().unwrap().push(Opening { id: "DF".into(), kind: ElementKind::Window, width: 1.0, height: 1.5, host_roof_id: Some("RF1".into()), host_point: Some(Vec2 { x: 3.0, y: 4.5 }), ..Default::default() });
|
||
let (q, _) = roof_base_quantities(&p, &p.roofs.as_ref().unwrap()[0]);
|
||
let get = |n: &str| q.iter().find(|x| x.name == n).map(|x| x.value).unwrap();
|
||
assert!((get("ProjectedArea") - 60.0).abs() < 1e-6 && (get("GrossArea") - 60.0).abs() < 1e-6, "{q:?}");
|
||
assert!((get("NetArea") - 58.5).abs() < 1e-6, "{q:?}");
|
||
assert!(ifc_export_data(&p, &IfcOptions::default()).is_ok());
|
||
}
|
||
|
||
/// [G5] Gauben-Mengen: Ausschnitt geneigt, Wand- und Dachvolumen aus den Körpern.
|
||
#[test]
|
||
fn gauben_mengen() {
|
||
let p = crate::dormer::tests::gable_project();
|
||
let roof = &p.roofs.as_ref().unwrap()[0];
|
||
let d = dormer_parts(&p, 0, roof);
|
||
assert_eq!(d.len(), 1);
|
||
assert!(d[0].opening_area > 2.4 * 1.6 * 2f64.sqrt() && d[0].opening_area < 2.4 * 3.0 * 2f64.sqrt(), "{d:?}");
|
||
assert!(d[0].wall_volume > 0.1 && d[0].roof_volume > 0.1, "{d:?}");
|
||
let q = qty::dormer_quantities(&d);
|
||
assert_eq!(q.len(), 5);
|
||
assert!(qty::dormer_quantities(&[]).is_empty());
|
||
}
|
||
|
||
/// [191] Decke und Raum mit Bogenkante: eigene Datensätze CEILING_ARC/SPACE_ARC mit Bulge je Ecke
|
||
/// (statt fein geteiltem Linienzug); ohne Bögen bleiben CEILING/SPACE.
|
||
#[test]
|
||
fn decke_und_raum_mit_bogenkante_als_bulge_datensatz() {
|
||
let mut p = sample();
|
||
let c = &mut p.ceilings.as_mut().unwrap()[0];
|
||
let n = c.outline.len();
|
||
let mut b = vec![0.0; n];
|
||
b[0] = 0.5;
|
||
let first = c.outline[0];
|
||
c.outline_bulge = Some(b);
|
||
let r = &mut p.rooms.as_mut().unwrap()[0];
|
||
let mut rb = vec![0.0; r.boundary.len()];
|
||
rb[0] = -0.5;
|
||
r.boundary_bulge = Some(rb);
|
||
let f = ifc_export_data(&p, &IfcOptions::default()).unwrap();
|
||
for rec in [REC_CEILING_ARC, REC_SPACE_ARC] {
|
||
assert!(f.nums.contains(&rec), "{rec}");
|
||
}
|
||
// Die Bulge-Werte stehen im Datensatz (Ring: x, y, bulge), im DXF-Sinn des Schreibers (Vorzeichen gedreht).
|
||
assert!(f.nums.windows(3).any(|w| w[0] == first.x && w[1] == first.y && w[2] == -0.5));
|
||
assert!(f.nums.iter().any(|&v| v == 0.5));
|
||
}
|
||
|
||
/// [T2] Bogenwand: Datensatz WALL_ARC_SOLID mit Kreisachse (Mitte, Radius, Startwinkel, Schwenk) und
|
||
/// je Schicht einem Bogenprofil (Ecken mit Bulge); Öffnungskörper mit radialen Laibungen.
|
||
#[test]
|
||
fn bogenwand_als_bogenprofil_mit_kreisachse() {
|
||
let mut p = sample();
|
||
p.walls[0].bulge = Some(1.0); // W1 (0,0)→(5,0): Halbkreis, Mitte (2.5,0), Uhrzeigersinn
|
||
let f = ifc_export_data(&p, &IfcOptions::default()).unwrap();
|
||
let pi = std::f64::consts::PI;
|
||
let at = f.nums.windows(6).position(|w| w[0] == 2.5 && w[1] == 0.0 && (w[2] - 2.5).abs() < 1e-12 && (w[3] - pi).abs() < 1e-12 && (w[4] + pi).abs() < 1e-12);
|
||
let at = at.expect("Kreisachse fehlt");
|
||
assert!(f.nums.contains(&REC_WALL_ARC_SOLID));
|
||
// Profile je Schicht-Kette (Hauptbänder, Eckstücke an den Anschlüssen, Teilung an der Decke), je
|
||
// 4 Ecken; Bögen auf gleichem Radius, durchgehende Bänder über den ganzen Halbkreis (Bulge −1).
|
||
let n = f.nums[at + 5] as usize;
|
||
assert!(n >= 4, "{n}");
|
||
let mut k = at + 6;
|
||
let mut full = 0;
|
||
for _ in 0..n {
|
||
assert_eq!(f.nums[k], 4.0);
|
||
let v = &f.nums[k + 1..k + 13];
|
||
let r = |i: usize| ((v[3 * i] - 2.5).powi(2) + v[3 * i + 1].powi(2)).sqrt();
|
||
assert!((r(0) - r(1)).abs() < 1e-9 && (r(2) - r(3)).abs() < 1e-9 && (r(0) - r(2)).abs() > 0.01);
|
||
if (v[2] + 1.0).abs() < 2e-2 {
|
||
full += 1;
|
||
}
|
||
k += 15;
|
||
}
|
||
assert!(full >= 3, "{full}"); // Innenputz durch den T-Anschluss von W9 geteilt
|
||
}
|
||
|
||
/// [108] Schräges L (60°): die Wand-Profile (SweptSolid je Band) tragen die Gehrung des 3D-Körpers
|
||
/// statt Rechtecken; Summe der Extrusionen = Dicke × Höhe × (L1 + L2), keine Lücke an der Aussenecke.
|
||
#[test]
|
||
fn schraeges_l_profile_mit_gehrung() {
|
||
let p = crate::solid_specs::tests::schraeges_l();
|
||
let f = ifc_export_data(&p, &IfcOptions::default()).unwrap();
|
||
// Profile: [4, x0, y0, …, x3, y3, z_rel, Tiefe] mit Tiefe 2.5.
|
||
let profiles: Vec<&[f64]> = f.nums.windows(11).filter(|w| w[0] == 4.0 && w[9] == 0.0 && w[10] == 2.5).collect();
|
||
assert_eq!(profiles.len(), 2, "zwei Wände, je ein Band");
|
||
let area = |w: &[f64]| (0..4).map(|i| { let j = (i + 1) % 4; w[1 + 2 * i] * w[2 + 2 * j] - w[1 + 2 * j] * w[2 + 2 * i] }).sum::<f64>() / 2.0;
|
||
let vol: f64 = profiles.iter().map(|w| area(w) * 2.5).sum();
|
||
assert!((vol - 0.3 * 2.5 * 7.0).abs() < 1e-9, "{vol}");
|
||
assert!(profiles.iter().all(|w| area(w) > 0.0), "CCW");
|
||
// Aussenecke der Gehrung (−0.15·√3, −0.15) in beiden Profilen, Innenecke (+0.15·√3, +0.15) auch.
|
||
let has = |w: &[f64], x: f64, y: f64| (0..4).any(|i| (w[1 + 2 * i] - x).abs() < 1e-9 && (w[2 + 2 * i] - y).abs() < 1e-9);
|
||
let (x, y) = (0.15 * 3f64.sqrt(), 0.15);
|
||
assert!(profiles.iter().all(|w| has(w, -x, -y) && has(w, x, y)), "{profiles:?}");
|
||
}
|
||
|
||
/// [71] U-Wert aus dem Schichtaufbau landet als ThermalTransmittance in Pset_WallCommon (nur mit λ).
|
||
#[test]
|
||
fn u_wert_der_wand_im_pset() {
|
||
let count = |p: &Project| {
|
||
let f = ifc_export_data(p, &IfcOptions::default()).unwrap();
|
||
strings(&f).iter().filter(|x| *x == "ThermalTransmittance").count()
|
||
};
|
||
let mut p = sample();
|
||
for c in p.components.iter_mut() {
|
||
c.lambda = None;
|
||
}
|
||
p.openings = None;
|
||
let ohne = count(&p);
|
||
for c in p.components.iter_mut() {
|
||
c.lambda = Some(1.0);
|
||
}
|
||
assert!(count(&p) > ohne, "mit λ kommt der Wert dazu");
|
||
}
|
||
|
||
#[test]
|
||
fn beispielprojekt_alle_bauteile() {
|
||
let opt = IfcOptions { ebkph: true, layer_codes: true, now: 1.0, iso: "2026-10-29T10:00:00".into(), ..Default::default() };
|
||
let f = ifc_export_data(&sample(), &opt).unwrap();
|
||
assert_eq!(f.nums[0], FLAT_VERSION);
|
||
let s = strings(&f);
|
||
for want in ["W1", "Pset_WallCommon", "Qto_WallBaseQuantities", "Pset_DoorCommon", "Qto_SlabBaseQuantities", "Qto_StairFlightBaseQuantities", "Pset_RoofCommon", "sia416/HNF", "storey/eg", "eBKP-H", "Dossier-Ebenen", "Wände"] {
|
||
assert!(s.iter().any(|x| x == want), "fehlt: {want}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn georeferenz_verschiebt_und_setzt_breite() {
|
||
let mut p = sample();
|
||
p.geo_anchor = Some(ProjectGeoAnchor { lv95: ProjectGeoAnchorLv95 { e: 2_683_000.0, n: 1_247_000.0, ..Default::default() }, model: Vec2 { x: 0.0, y: 0.0 }, height: Some(400.0), ..Default::default() });
|
||
let f = ifc_export_data(&p, &IfcOptions::default()).unwrap();
|
||
// Kopf: [Version, id, name, now, iso, hasGeo, refElevation, lat, lon, eastings, northings, schema, nStoreys …]
|
||
assert_eq!(f.nums[5], 1.0);
|
||
assert_eq!(f.nums[6], 400.0);
|
||
assert!((f.nums[7] - 47.37).abs() < 0.1 && (f.nums[8] - 8.54).abs() < 0.1, "{} {}", f.nums[7], f.nums[8]);
|
||
assert_eq!((f.nums[9], f.nums[10]), (2_683_000.0, 1_247_000.0));
|
||
// [259] Geometrie bleibt lokal: keine LV95-Millionen im Puffer ausser dem Versatz.
|
||
assert_eq!(f.nums.iter().filter(|v| v.abs() > 1_000_000.0).count(), 2);
|
||
// Bezugspunkt nicht im Ursprung: Versatz des Ursprungs; Höhe von ±0.00 vor der Höhe des Bezugspunkts.
|
||
p.geo_anchor.as_mut().unwrap().model = Vec2 { x: 10.0, y: -5.0 };
|
||
p.reference_elevation_masl = Some(441.3);
|
||
let f = ifc_export_data(&p, &IfcOptions::default()).unwrap();
|
||
assert_eq!((f.nums[6], f.nums[9], f.nums[10]), (441.3, 2_682_990.0, 1_247_005.0));
|
||
}
|
||
|
||
#[test]
|
||
fn achsraster_als_datensatz() {
|
||
let mut p = sample();
|
||
let a = |l: &str, pos: f64| GridAxis { label: l.into(), pos, ..Default::default() };
|
||
let geom = Drawing2DGeom::Grid {
|
||
origin: Vec2 { x: 0.0, y: 0.0 },
|
||
angle: 0.0,
|
||
radial: None,
|
||
a: vec![a("1", 0.0), a("2", 5.0)],
|
||
b: vec![a("A", 0.0)],
|
||
extend: None,
|
||
bubbles: None,
|
||
bubble_mm: None,
|
||
levels: None,
|
||
show_3d: None,
|
||
};
|
||
p.drawings2d.push(Drawing2D { id: "g".into(), r#type: "drawing2d".into(), level_id: p.drawing_levels[0].id.clone(), category_code: "00".into(), geom, ..Default::default() });
|
||
let f = ifc_export_data(&p, &IfcOptions::default()).unwrap();
|
||
let at = f.nums.windows(2).position(|w| w == [REC_END_COLUMNS, REC_GRID]).map(|i| i + 1);
|
||
assert!(at.is_some(), "kein Rasterdatensatz");
|
||
// structure, id, name, n_u = 2, n_v = 1
|
||
let i = at.unwrap();
|
||
assert_eq!((f.nums[i + 4], f.nums[i + 5]), (2.0, 1.0));
|
||
// Ohne Raster kein Datensatz.
|
||
assert!(!ifc_export_data(&sample(), &IfcOptions::default()).unwrap().nums.windows(2).any(|w| w == [REC_END_COLUMNS, REC_GRID]));
|
||
}
|
||
|
||
#[test]
|
||
fn leeres_projekt_und_unbekannter_wandtyp() {
|
||
let mut p = Project { id: "leer".into(), ..Default::default() };
|
||
let f = ifc_export_data(&p, &IfcOptions::default()).unwrap();
|
||
assert_eq!(f.nums.last(), Some(&REC_END_COLUMNS));
|
||
// Hängender Wandtyp (Datei/Import): Export mit dem Rückfall-Typ statt Abbruch.
|
||
p = sample();
|
||
p.walls[0].wall_type_id = "fehlt".into();
|
||
let f = ifc_export_data(&p, &IfcOptions::default()).unwrap();
|
||
assert_eq!(f.nums.last(), Some(&REC_END_COLUMNS));
|
||
}
|
||
|
||
#[test]
|
||
fn treppen_fussabdruck() {
|
||
let st = Stair { shape: StairShape::Spiral, center: Some(Vec2 { x: 1.0, y: 1.0 }), radius: Some(1.0), width: 1.0, ..Default::default() };
|
||
assert_eq!(stair_footprint(&st)[0], Vec2 { x: -0.5, y: -0.5 });
|
||
let st = Stair { shape: StairShape::Straight, dir: Vec2 { x: 0.0, y: 2.0 }, run_length: 3.0, width: 1.0, ..Default::default() };
|
||
assert_eq!(stair_footprint(&st)[2], Vec2 { x: -0.5, y: 3.0 });
|
||
}
|
||
|
||
fn opening(kind: ElementKind, type_id: Option<&str>) -> Opening {
|
||
Opening { id: "O".into(), host_wall_id: "W".into(), kind, position: 1.0, width: 1.2, height: 1.2, type_id: type_id.map(String::from), ..Default::default() }
|
||
}
|
||
|
||
#[test]
|
||
fn fenster_parameter_aus_typ_und_oeffnung() {
|
||
let mut p = Project::default();
|
||
p.window_types = Some(vec![WindowType {
|
||
id: "wt".into(),
|
||
kind: OpeningKind::Dreh,
|
||
wing_count: 3.0,
|
||
glazing: WindowTypeGlazing::Dreifach,
|
||
frame_width: Some(0.09),
|
||
frame_depth: Some(0.1),
|
||
inset_from_face: Some(0.05),
|
||
inset_face: Some(WindowTypeInsetFace::Innen),
|
||
sashes: Some(vec![
|
||
SashDef { kind: SashDefKind::Fluegel, auto_width: Some(false), width: Some(0.5), ..Default::default() },
|
||
SashDef { kind: SashDefKind::Pfosten, post_width: Some(0.1), ..Default::default() },
|
||
SashDef { kind: SashDefKind::Fluegel, ..Default::default() },
|
||
]),
|
||
..Default::default()
|
||
}]);
|
||
let o = Opening { wing_count: Some(2.0), ..opening(ElementKind::Window, Some("wt")) };
|
||
let x = fill_params(&p, &o);
|
||
assert_eq!((x.frame_depth, x.frame_width, x.inset, x.inset_outside, x.wing_count, x.panes), (Some(0.1), Some(0.09), Some(0.05), false, 2.0, 3.0));
|
||
assert_eq!(
|
||
x.sashes,
|
||
vec![
|
||
FillSash { post: false, post_width: None, fixed: true, width: Some(0.5) },
|
||
FillSash { post: true, post_width: Some(0.1), fixed: false, width: None },
|
||
FillSash { post: false, post_width: None, fixed: false, width: None },
|
||
]
|
||
);
|
||
// Ohne Typ: nichts vom Typ, zwei Scheiben, ein Flügel.
|
||
let x = fill_params(&p, &opening(ElementKind::Window, None));
|
||
assert_eq!((x.frame_depth, x.inset_outside, x.wing_count, x.panes, x.sashes.len()), (None, true, 1.0, 2.0, 0));
|
||
}
|
||
|
||
#[test]
|
||
fn tuer_parameter() {
|
||
let mut p = Project::default();
|
||
let dt = |kind| DoorType { id: "dt".into(), kind, leaf_count: 2.0, leaf_style: DoorTypeLeafStyle::Glas, glazing_ratio: Some(0.36), transom_height: Some(0.4), ..Default::default() };
|
||
p.door_types = Some(vec![dt(DoorTypeKind::Schiebe)]);
|
||
let o = Opening { hinge: Some(OpeningHinge::End), swing: Some(SwingSide::Right), opening_dir: Some(OpeningOpeningDir::Out), ..opening(ElementKind::Door, Some("dt")) };
|
||
let x = fill_params(&p, &o);
|
||
assert_eq!((x.door_kind, x.leaf_count, x.swing_sign, x.dir_sign, x.hinge_at_start, x.transom_height, x.glazed, x.glazing_ratio), (1.0, 2.0, -1.0, -1.0, false, 0.4, true, Some(0.36)));
|
||
let x = fill_params(&p, &opening(ElementKind::Door, None));
|
||
assert_eq!((x.door_kind, x.leaf_count, x.swing_sign, x.dir_sign, x.hinge_at_start, x.transom_height, x.glazed), (0.0, 1.0, 1.0, 1.0, true, 0.0, false));
|
||
let wo = Opening { door_type: Some(OpeningDoorType::Wandoeffnung), ..opening(ElementKind::Door, None) };
|
||
assert_eq!(fill_params(&p, &wo).door_kind, 2.0);
|
||
p.door_types = Some(vec![dt(DoorTypeKind::Wandoeffnung)]);
|
||
assert_eq!(fill_params(&p, &opening(ElementKind::Door, Some("dt"))).door_kind, 2.0);
|
||
// [95] Taschen-Schiebetür: IFC wie Schiebetür (SLIDING_TO_LEFT/RIGHT nach Bandseite).
|
||
p.door_types = Some(vec![DoorType { leaf_count: 1.0, ..dt(DoorTypeKind::Tasche) }]);
|
||
let x = fill_params(&p, &o);
|
||
assert_eq!((x.door_kind, x.leaf_count, x.hinge_at_start), (1.0, 1.0, false));
|
||
}
|
||
|
||
/// [105] Zarge (Profil über die ganze Leibung) und Blockrahmen: Rahmenlage der Füllung aus dem Profil,
|
||
/// damit IFC das Blatt wie das 3D im Falz der Aufschlagseite trägt.
|
||
#[test]
|
||
fn tuer_zarge_rahmenlage_aus_dem_profil() {
|
||
let mut p = Project::default();
|
||
p.wall_types.push(WallType { id: "iw".into(), layers: vec![Layer { thickness: 0.15, ..Default::default() }], ..Default::default() });
|
||
p.walls.push(Wall { id: "W".into(), wall_type_id: "iw".into(), end: Vec2 { x: 5.0, y: 0.0 }, height: 2.6, ..Default::default() });
|
||
p.door_types = Some(vec![DoorType { id: "dt".into(), frame_kind: Some(DoorTypeFrameKind::Zarge), frame_width: Some(0.06), ..Default::default() }]);
|
||
let x = fill_params(&p, &opening(ElementKind::Door, Some("dt")));
|
||
assert_eq!((x.frame_depth, x.inset, x.inset_outside), (Some(0.15), Some(0.0), true));
|
||
p.door_types = Some(vec![DoorType { id: "dt".into(), frame_kind: Some(DoorTypeFrameKind::Blockrahmen), frame_depth: Some(0.08), inset_face: Some(DoorTypeInsetFace::Innen), inset_from_face: Some(0.02), ..Default::default() }]);
|
||
let x = fill_params(&p, &opening(ElementKind::Door, Some("dt")));
|
||
let (d, i) = (x.frame_depth.unwrap(), x.inset.unwrap());
|
||
assert!((d - 0.08).abs() < 1e-12 && (i - 0.05).abs() < 1e-12 && x.inset_outside, "{d} {i}");
|
||
// Hebeschiebetür behält das Rahmenband des Typs.
|
||
p.door_types = Some(vec![DoorType { id: "dt".into(), kind: DoorTypeKind::Hebeschiebe, frame_depth: Some(0.16), ..Default::default() }]);
|
||
assert_eq!(fill_params(&p, &opening(ElementKind::Door, Some("dt"))).frame_depth, Some(0.16));
|
||
}
|
||
|
||
#[test]
|
||
fn klassifikation_ebkph_und_ebenen() {
|
||
assert_eq!(ebkph_group(Kind::Wall), Some(("C", "Konstruktion Gebäude")));
|
||
for k in [Kind::Slab, Kind::Column, Kind::Stair] {
|
||
assert_eq!(ebkph_group(k).map(|g| g.0), Some("C"));
|
||
}
|
||
assert_eq!(ebkph_group(Kind::Roof), Some(("F", "Bedachung Gebäude")));
|
||
assert_eq!(ebkph_group(Kind::Window), Some(("E", "Äussere Wandbekleidung Gebäude")));
|
||
assert_eq!(ebkph_group(Kind::Door), None);
|
||
assert_eq!(ebkph_group(Kind::Space), None);
|
||
let p = sample();
|
||
assert_eq!(layer_classification(&p, "20").map(|x| x.0), Some("20".to_string()));
|
||
assert_eq!(layer_classification(&p, "25").map(|x| x.1), Some("Stützen".to_string()));
|
||
assert_eq!(layer_classification(&p, "777"), Some(("777".to_string(), "777".to_string())));
|
||
assert_eq!(layer_classification(&p, ""), None);
|
||
assert_eq!(layer_classification(&p, " "), None);
|
||
}
|
||
|
||
/// [168] Wand mit Schichteinzug-Stücken (Beispiel W1: Vorgabe bei Aussendämmung, Dämmung überdeckt
|
||
/// den Rahmen): die Bänder als EIN geschlossener Körper mit dem Volumen der 3D-Bänder; der
|
||
/// Öffnungskörper bleibt in der Rahmenlage (schneidet die Stücke nicht weg).
|
||
#[test]
|
||
fn schichteinzug_wand_als_ein_koerper() {
|
||
let p = sample();
|
||
let all = model3d::emit_walls(&p, true).unwrap();
|
||
let bands: Vec<&RWall> = all.iter().filter(|b| b.wall_id == "W1").collect();
|
||
let shells: f64 = bands
|
||
.iter()
|
||
.map(|b| {
|
||
let cut = wall_cut_mesh_checked(&CutWall { start: b.start, end: b.end, thickness: b.thickness, base_elevation: b.base_elevation, height: b.height, holes: b.holes.as_deref().unwrap_or(&[]).iter().map(|h| [h.from, h.to, h.z_bottom, h.z_top]).collect() });
|
||
let n = (cut.len() / 3) as u32;
|
||
crate::export_flat::mesh_volume(&cut, &(0..n).collect::<Vec<_>>()).abs()
|
||
})
|
||
.sum();
|
||
assert!(bands.iter().any(|b| b.holes.as_ref().is_none_or(|h| h.is_empty()) && b.thickness < 0.2), "Stücke fehlen");
|
||
let (pos, idx) = union_bands(&bands, 0.0, &[]).expect("ein Körper");
|
||
assert!(is_watertight(&pos, &idx, 1e-6));
|
||
let v = crate::export_flat::mesh_volume(&pos, &idx);
|
||
assert!((v - shells).abs() < 1e-6, "{v} vs {shells}");
|
||
let w1 = p.walls.iter().find(|w| w.id == "W1").unwrap();
|
||
let o = p.openings.as_ref().unwrap().iter().find(|o| o.host_wall_id == "W1" && o.kind == ElementKind::Window).unwrap();
|
||
let (lo, hi) = reveal_frame_slice(&p, w1, o).expect("Stücke ⇒ Rahmenlage");
|
||
assert!(hi > lo);
|
||
}
|
||
}
|