[K4] S2: IFC-Export in Rust (export_ifc.rs, js_fmt.rs, geo_rebase.rs), byte-genau zur TS-Fassung; exportIfc.ts nur noch Fassade

This commit is contained in:
karim committed 2026-10-28 02:19:53 +01:00
1 parent e53fb21eb6
commit aaa7fae812
10 files changed
+1056 -919

No files matched your search

+4 -1
View File
@@ -135,7 +135,10 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
(`queries.rs`), nur die truck-Körper (async) fügt TS ein; TS-Sammler `toWalls3d/{bands,ceilings,columns,openings,stairs,roofs}.ts`
gelöscht, unbenutzte Bindungen/Kodierer entfernt. Hin-und-her-Vergleich mit der TS-Fassung lief über Zufallsprojekte, danach
prüft die bestehende Suite (2123 Tests) den neuen Weg. Das Modell ist tolerant (fehlende Felder = Standardwert).
Nächste: Plan/Schnitt/Ansicht-Sammler (generatePlan, toSection, toElevation), Export (IFC/DXF/SVG), Raumprogramm.
Pick-Geometrie und 2D-Boden-Spuren im 3D ebenfalls im Kern. **IFC-Export** (`export_ifc.rs`, `js_fmt.rs` für JS-`toFixed`, `geo_rebase.rs`)
byte-genau zur TS-Fassung (Vergleich über Zufallsprojekte; das Salz der GUID-Ableitung beginnt mit U+0001 — so seit jeher, bleibt für
stabile GUIDs). Modell verlustfrei (`Extra`-Felder), typisierte Sicht wird nach Ops feldweise nachgeführt.
Nächste: Export (Schedule/CSV, STL/OBJ, STEP), Plan/Schnitt/Ansicht-Sammler (generatePlan, toSection, toElevation) — hängt an Plan-Puffer v2.
Ziel: Plan/Schnitt/Ansicht, 3D, Export rechnen mit `doc`-Handle statt flach gesammelter Arrays; TS-Sammler/-Adapter werden gelöscht
([K3d] hängt hier dran: Plan-Puffer v2 mit Pick-IDs und vollem Primitive-Umfang).
- ○ **S3 Änderungen kommen aus Rust**: Befehle (Zustandsautomaten, Werkzeuge) erzeugen Ops im Kern; Undo/Redo, Validierung
+768
View File
@@ -0,0 +1,768 @@
//! IFC4-Export (STEP Physical File, ISO-10303-21) des Modells ([K4] S2, vorher
//! `src/export/exportIfc.ts`): Project → Site → Building → Storeys; Wände als öffnungsgenaue
//! Dreiecks-Netze (gleicher Loch-Ausschnitt wie STL/OBJ), Decken/Treppen/Körper/Stützen/Räume als
//! Profil-Extrusionen, Dächer als Schicht-Netze, Wand-/Deckentypen mit Materialschichten.
//! GUIDs deterministisch aus der Element-ID (zwei FNV-1a-64-Läufe, IFC-Base64-Kompression).
//! Geometrie in realen Weltkoordinaten (LV95), wenn `geoAnchor` gesetzt ist. Einheit: Meter.
//! Byte-genau wie die TS-Fassung (Zahlenformat über [`crate::js_fmt::to_fixed`]).
use crate::geo_rebase::project_to_world_coords;
use crate::js_fmt::to_fixed;
use crate::model::*;
use crate::model3d;
use crate::wall_mesh_cut::{is_watertight, wall_cut_mesh, CutWall};
use std::collections::HashMap;
// ── IFC-GUID ────────────────────────────────────────────────────────────────
const IFC_GUID_CHARS: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_$";
fn guid_b64(v: u64, len: usize) -> String {
(0..len).rev().map(|i| IFC_GUID_CHARS[((v / 64u64.pow(i as u32)) % 64) as usize] as char).collect()
}
fn compress_guid(bytes: [u8; 16]) -> String {
let mut out = guid_b64(bytes[0] as u64, 2);
let mut i = 1;
while i < 16 {
let v = ((bytes[i] as u64) << 16) + ((bytes[i + 1] as u64) << 8) + bytes[i + 2] as u64;
out.push_str(&guid_b64(v, 4));
i += 3;
}
out
}
fn fnv1a64(s: &str, seed: u64) -> u64 {
let mut hash = seed;
// Wie TS: über UTF-16-Code-Einheiten (`charCodeAt`).
for u in s.encode_utf16() {
hash ^= u as u64;
hash = hash.wrapping_mul(0x100000001b3);
}
hash
}
/// Deterministische 22-stellige IFC-GUID aus einer beliebigen Element-ID.
pub fn ifc_guid(id: &str) -> String {
let h1 = fnv1a64(id, 0xcbf29ce484222325);
// Das Salz beginnt mit U+0001 (so steht es seit jeher in der TS-Fassung); beibehalten, damit
// GUIDs über Re-Exporte und Versionen stabil bleiben.
let h2 = fnv1a64(&format!("{id}\u{1}salt"), 0x9e3779b97f4a7c15);
let mut bytes = [0u8; 16];
bytes[..8].copy_from_slice(&h1.to_be_bytes());
bytes[8..].copy_from_slice(&h2.to_be_bytes());
compress_guid(bytes)
}
// ── STEP-Formatierung ───────────────────────────────────────────────────────
/// STEP-String-Literal: druckbares ASCII bleibt, `\` und `'` werden verdoppelt, alles andere als
/// `\X2\HHHH…\X0\` (BMP) bzw. `\X4\HHHHHHHH…\X0\`.
pub fn ifc_string(s: &str) -> String {
let mut out = String::new();
let mut run: Vec<u32> = Vec::new();
fn flush(out: &mut String, run: &mut Vec<u32>) {
if run.is_empty() {
return;
}
let wide = run.iter().any(|&c| c > 0xffff);
let hex: String = run.iter().map(|c| if wide { format!("{c:08X}") } else { format!("{c:04X}") }).collect();
out.push_str(if wide { "\\X4\\" } else { "\\X2\\" });
out.push_str(&hex);
out.push_str("\\X0\\");
run.clear();
}
for ch in s.chars() {
let c = ch as u32;
if (0x20..=0x7e).contains(&c) {
flush(&mut out, &mut run);
match ch {
'\\' => out.push_str("\\\\"),
'\'' => out.push_str("''"),
_ => out.push(ch),
}
} else {
if !run.is_empty() && (run[0] > 0xffff) != (c > 0xffff) {
flush(&mut out, &mut run);
}
run.push(c);
}
}
flush(&mut out, &mut run);
format!("'{out}'")
}
fn s(x: &str) -> String {
ifc_string(x)
}
/// STEP-REAL — immer mit Dezimalpunkt, ohne unnötige Nachkommastellen.
fn r(x: f64) -> String {
let v = if x == 0.0 { 0.0 } else { x };
let mut t = to_fixed(v, 6);
let trimmed = t.trim_end_matches('0').len();
t.truncate(trimmed);
if t.ends_with('.') {
t.push('0');
}
if !t.contains('.') {
t.push_str(".0");
}
t
}
fn en(v: &str) -> String {
format!(".{v}.")
}
fn list(items: &[String]) -> String {
format!("({})", items.join(","))
}
fn refs(ids: &[usize]) -> String {
list(&ids.iter().map(|i| format!("#{i}")).collect::<Vec<_>>())
}
struct StepWriter {
lines: Vec<String>,
next_id: usize,
}
impl StepWriter {
fn add(&mut self, ty: &str, params: String) -> usize {
let id = self.next_id;
self.next_id += 1;
self.lines.push(format!("#{id}={ty}({params});"));
id
}
}
// ── Geometrie-Helfer ────────────────────────────────────────────────────────
fn normalize(v: Vec2) -> Vec2 {
let len = crate::jsmath::hypot2(v.x, v.y);
let len = if len == 0.0 || len.is_nan() { 1.0 } else { len };
Vec2 { x: v.x / len, y: v.y / len }
}
fn left_normal(u: Vec2) -> Vec2 {
Vec2 { x: -u.y, y: u.x }
}
fn add_scaled(p: Vec2, d: Vec2, k: f64) -> Vec2 {
Vec2 { x: p.x + d.x * k, y: p.y + d.y * k }
}
/// Rechteck-Footprint einer Öffnung im Wandloch (volle Wanddicke tief), CCW.
fn opening_footprint(p: &Project, wall: &Wall, o: &Opening) -> Vec<Vec2> {
let u = normalize(Vec2 { x: wall.end.x - wall.start.x, y: wall.end.y - wall.start.y });
let n = left_normal(u);
let t = p.wall_type(wall).map_or(0.0, |wt| Project::type_thickness(&wt.layers));
let off = crate::joins::reference_offset(model3d_reference(wall), t);
let inner = -t / 2.0 + off;
let outer = t / 2.0 + off;
let a = add_scaled(wall.start, u, o.position);
let b = add_scaled(wall.start, u, o.position + o.width);
vec![add_scaled(a, n, inner), add_scaled(b, n, inner), add_scaled(b, n, outer), add_scaled(a, n, outer)]
}
fn model3d_reference(w: &Wall) -> crate::joins::Reference {
use crate::joins::Reference;
match (w.reference_offset, w.reference_line) {
(Some(v), _) => Reference::Offset(v),
(None, Some(WallReferenceLine::Left)) => Reference::Left,
(None, Some(WallReferenceLine::Right)) => Reference::Right,
_ => Reference::Center,
}
}
/// Vereinfachter Bounding-Footprint einer Treppe (Lauf-Rechteck bzw. Box der Kontrollpunkte).
fn stair_footprint(st: &Stair) -> Vec<Vec2> {
let half_w = st.width.max(0.0) / 2.0;
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 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)) = (st.run2_length.filter(|v| *v != 0.0), st.turn.filter(|v| *v != 0.0)) {
let n = left_normal(u);
let turn_dir = Vec2 { x: n.x * turn, y: n.y * turn };
pts.push(add_scaled(corner, turn_dir, run2));
}
}
if st.shape == StairShape::Spiral {
if let Some(c) = st.center {
let rr = st.radius.unwrap_or(0.0) + half_w;
return vec![
Vec2 { x: c.x - rr, y: c.y - rr },
Vec2 { x: c.x + rr, y: c.y - rr },
Vec2 { x: c.x + rr, y: c.y + rr },
Vec2 { x: c.x - rr, y: c.y + rr },
];
}
}
let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
for q in &pts {
min_x = min_x.min(q.x);
min_y = min_y.min(q.y);
max_x = max_x.max(q.x);
max_y = max_y.max(q.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 opening_label(o: &Opening) -> String {
format!("{} {}×{}", if o.kind == ElementKind::Door { "Tür" } else { "Fenster" }, to_fixed(o.width * 100.0, 0), to_fixed(o.height * 100.0, 0))
}
fn column_label(c: &Column) -> String {
match &c.profile {
ColumnProfile::Round { radius } => format!("Stütze Ø{}", to_fixed(radius * 200.0, 0)),
ColumnProfile::Rect { width, depth } => format!("Stütze {}×{}", to_fixed(width * 100.0, 0), to_fixed(depth * 100.0, 0)),
}
}
#[derive(Clone, Copy)]
struct Structure {
entity_id: usize,
placement_id: usize,
base_elevation: f64,
}
struct ElementTypeRef {
type_id: usize,
occurrences: Vec<usize>,
}
/// Unix-Sekunden/ISO-Zeit aus Millisekunden seit 1970 (UTC), wie `Date.now()` / `toISOString()`.
fn iso_from_ms(ms: f64) -> String {
let secs = (ms / 1000.0).floor() as i64;
let days = secs.div_euclid(86_400);
let tod = secs.rem_euclid(86_400);
// Zivildatum aus Tagen (Howard Hinnant).
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = if m <= 2 { y + 1 } else { y };
format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}", tod / 3600, (tod % 3600) / 60, tod % 60)
}
/// Baut aus einem Projekt einen vollständigen IFC4-SPF-String. `now_ms`: Zeitpunkt des Exports
/// (ms seit 1970). Leeres Projekt ⇒ valider Minimal-IFC. `Err`: das Modell lässt sich nicht
/// ableiten (z. B. unbekannter Wandtyp bei der Verschneidung).
pub fn export_ifc_spf(project_in: &Project, now_ms: f64) -> Result<String, String> {
let project = project_to_world_coords(project_in);
let p = &project;
let mut w = StepWriter { lines: Vec::new(), next_id: 1 };
let origin_point = w.add("IFCCARTESIANPOINT", list(&[r(0.0), r(0.0), r(0.0)]));
let extrude_dir = w.add("IFCDIRECTION", list(&[r(0.0), r(0.0), r(1.0)]));
let identity_axis = w.add("IFCAXIS2PLACEMENT3D", format!("#{origin_point},$,$"));
let org = w.add("IFCORGANIZATION", format!("$,{},$,$,$", s("dossier")));
let person = w.add("IFCPERSON", format!("{},$,$,$,$,$,$,$", s("dossier")));
let person_org = w.add("IFCPERSONANDORGANIZATION", format!("#{person},#{org},$"));
let app = w.add("IFCAPPLICATION", format!("#{org},{},{},{}", s("1.0"), s("dossier"), s("dossier")));
let now = (now_ms / 1000.0).floor() as i64;
let owner_history = w.add("IFCOWNERHISTORY", format!("#{person_org},#{app},$,{},{now},$,$,{now}", en("ADDED")));
let len_unit = w.add("IFCSIUNIT", format!("*,{},$,{}", en("LENGTHUNIT"), en("METRE")));
let area_unit = w.add("IFCSIUNIT", format!("*,{},$,{}", en("AREAUNIT"), en("SQUARE_METRE")));
let vol_unit = w.add("IFCSIUNIT", format!("*,{},$,{}", en("VOLUMEUNIT"), en("CUBIC_METRE")));
let angle_unit = w.add("IFCSIUNIT", format!("*,{},$,{}", en("PLANEANGLEUNIT"), en("RADIAN")));
let unit_assignment = w.add("IFCUNITASSIGNMENT", refs(&[len_unit, area_unit, vol_unit, angle_unit]));
let context = w.add("IFCGEOMETRICREPRESENTATIONCONTEXT", format!("$,{},3,{},#{identity_axis},$", s("Model"), r(0.00001)));
if p.geo_anchor.is_some() {
let crs = w.add(
"IFCPROJECTEDCRS",
format!("{},{},{},$,{},$,#{len_unit}", s("EPSG:2056"), s("CH1903+ / LV95"), s("CH1903+"), s("Swiss Oblique Mercator")),
);
w.add("IFCMAPCONVERSION", format!("#{context},#{crs},{},{},{},{},{},{}", r(0.0), r(0.0), r(0.0), r(1.0), r(0.0), r(1.0)));
}
let site_axis = w.add("IFCAXIS2PLACEMENT3D", format!("#{origin_point},$,$"));
let site_placement = w.add("IFCLOCALPLACEMENT", format!("$,#{site_axis}"));
let building_axis = w.add("IFCAXIS2PLACEMENT3D", format!("#{origin_point},$,$"));
let building_placement = w.add("IFCLOCALPLACEMENT", format!("#{site_placement},#{building_axis}"));
let project_id = w.add(
"IFCPROJECT",
format!(
"{},#{owner_history},{},$,$,$,$,{},#{unit_assignment}",
s(&ifc_guid(&format!("{}:project", p.id))),
s(if p.name.is_empty() { "Projekt" } else { &p.name }),
refs(&[context])
),
);
let site_ref_elev = p.geo_anchor.as_ref().and_then(|a| a.height).map_or("$".to_string(), r);
let site_id = w.add(
"IFCSITE",
format!(
"{},#{owner_history},{},$,$,#{site_placement},$,$,{},$,$,{site_ref_elev},$,$",
s(&ifc_guid(&format!("{}:site", p.id))),
s("Standort"),
en("ELEMENT")
),
);
let building_id = w.add(
"IFCBUILDING",
format!(
"{},#{owner_history},{},$,$,#{building_placement},$,$,{},$,$,$",
s(&ifc_guid(&format!("{}:building", p.id))),
s(if p.name.is_empty() { "Gebäude" } else { &p.name }),
en("ELEMENT")
),
);
w.add("IFCRELAGGREGATES", format!("{},#{owner_history},$,$,#{project_id},{}", s(&ifc_guid(&format!("{}:agg-site", p.id))), refs(&[site_id])));
w.add("IFCRELAGGREGATES", format!("{},#{owner_history},$,$,#{site_id},{}", s(&ifc_guid(&format!("{}:agg-building", p.id))), refs(&[building_id])));
let floors: Vec<&DrawingLevel> = p.drawing_levels.iter().filter(|l| l.kind == DrawingLevelKind::Floor).collect();
let mut storey_by_floor: HashMap<&str, Structure> = HashMap::new();
let mut storey_ids = Vec::new();
for floor in &floors {
let base = floor.base_elevation.unwrap_or(0.0);
let pt = w.add("IFCCARTESIANPOINT", list(&[r(0.0), r(0.0), r(base)]));
let axis = w.add("IFCAXIS2PLACEMENT3D", format!("#{pt},$,$"));
let placement_id = w.add("IFCLOCALPLACEMENT", format!("#{building_placement},#{axis}"));
let entity_id = w.add(
"IFCBUILDINGSTOREY",
format!("{},#{owner_history},{},$,$,#{placement_id},$,$,{},{}", s(&ifc_guid(&format!("{}:storey", floor.id))), s(&floor.name), en("ELEMENT"), r(base)),
);
storey_by_floor.entry(floor.id.as_str()).or_insert(Structure { entity_id, placement_id, base_elevation: base });
storey_ids.push(entity_id);
}
if !storey_ids.is_empty() {
w.add("IFCRELAGGREGATES", format!("{},#{owner_history},$,$,#{building_id},{}", s(&ifc_guid(&format!("{}:agg-storeys", p.id))), refs(&storey_ids)));
}
let resolve_structure = |floor_id: &str| -> Structure {
storey_by_floor.get(floor_id).copied().unwrap_or(Structure { entity_id: building_id, placement_id: building_placement, base_elevation: 0.0 })
};
// Räumliche Eingliederung je Trägerstruktur, in Einfüge-Reihenfolge.
let mut containment: Vec<(usize, Vec<usize>)> = Vec::new();
let mut add_to_containment = |structure: usize, element: usize| match containment.iter_mut().find(|(k, _)| *k == structure) {
Some((_, v)) => v.push(element),
None => containment.push((structure, vec![element])),
};
macro_rules! emit_box_product {
($footprint:expr, $z_bottom_rel:expr, $depth:expr, $placement_rel_to:expr) => {{
let footprint: &[Vec2] = $footprint;
let mut closed: Vec<Vec2> = footprint.to_vec();
closed.push(footprint[0]);
let pt_ids: Vec<usize> = closed.iter().map(|q| w.add("IFCCARTESIANPOINT", list(&[r(q.x), r(q.y)]))).collect();
let polyline = w.add("IFCPOLYLINE", refs(&pt_ids));
let profile = w.add("IFCARBITRARYCLOSEDPROFILEDEF", format!("{},$,#{polyline}", en("AREA")));
let solid = w.add("IFCEXTRUDEDAREASOLID", format!("#{profile},#{identity_axis},#{extrude_dir},{}", r(($depth as f64).max(0.001))));
let shape_rep = w.add("IFCSHAPEREPRESENTATION", format!("#{context},{},{},{}", s("Body"), s("SweptSolid"), refs(&[solid])));
let shape = w.add("IFCPRODUCTDEFINITIONSHAPE", format!("$,$,{}", refs(&[shape_rep])));
let elem_origin = w.add("IFCCARTESIANPOINT", list(&[r(0.0), r(0.0), r($z_bottom_rel)]));
let elem_axis = w.add("IFCAXIS2PLACEMENT3D", format!("#{elem_origin},$,$"));
let placement = w.add("IFCLOCALPLACEMENT", format!("#{},#{elem_axis}", $placement_rel_to));
(placement, shape)
}};
}
macro_rules! emit_triangulated_product {
($positions:expr, $indices:expr, $placement_rel_to:expr, $closed:expr) => {{
let positions: &[f64] = $positions;
let indices: &[u32] = $indices;
let coords: Vec<String> = positions.chunks_exact(3).map(|c| format!("({},{},{})", r(c[0]), r(c[1]), r(c[2]))).collect();
let point_list = w.add("IFCCARTESIANPOINTLIST3D", format!("({})", coords.join(",")));
let tris: Vec<String> = indices.chunks_exact(3).map(|t| format!("({},{},{})", t[0] + 1, t[1] + 1, t[2] + 1)).collect();
let closed_flag = if $closed { ".T." } else { "$" };
let face_set = w.add("IFCTRIANGULATEDFACESET", format!("#{point_list},$,{closed_flag},({}),$", tris.join(",")));
let shape_rep = w.add("IFCSHAPEREPRESENTATION", format!("#{context},{},{},{}", s("Body"), s("Tessellation"), refs(&[face_set])));
let shape = w.add("IFCPRODUCTDEFINITIONSHAPE", format!("$,$,{}", refs(&[shape_rep])));
let elem_origin = w.add("IFCCARTESIANPOINT", list(&[r(0.0), r(0.0), r(0.0)]));
let elem_axis = w.add("IFCAXIS2PLACEMENT3D", format!("#{elem_origin},$,$"));
let placement = w.add("IFCLOCALPLACEMENT", format!("#{},#{elem_axis}", $placement_rel_to));
(placement, shape)
}};
}
macro_rules! emit_building_element {
($ty:expr, $guid:expr, $name:expr, $placement:expr, $shape:expr, $predefined:expr) => {
w.add($ty, format!("{},#{owner_history},{},$,$,#{},#{},$,{}", s(&$guid), s(&$name), $placement, $shape, $predefined.unwrap_or_else(|| "$".to_string())))
};
}
// ── Bauteiltypen mit Materialschichten ──
let mut material_by_component: HashMap<String, usize> = HashMap::new();
let mut element_types: Vec<(String, ElementTypeRef)> = Vec::new();
macro_rules! material_of {
($component_id:expr) => {{
let cid: &str = $component_id;
match material_by_component.get(cid) {
Some(&id) => id,
None => {
let name = p.component(cid).map_or(cid.to_string(), |c| c.name.clone());
let id = w.add("IFCMATERIAL", format!("{},$,$", s(&name)));
material_by_component.insert(cid.to_string(), id);
id
}
}
}};
}
macro_rules! type_for {
($ifc_type:expr, $predefined:expr, $t_id:expr, $t_name:expr, $layers:expr) => {{
let key = format!("{}:{}", $ifc_type, $t_id);
match element_types.iter().position(|(k, _)| *k == key) {
Some(i) => i,
None => {
let layers: &[Layer] = $layers;
let layer_ids: Vec<usize> = layers
.iter()
.map(|l| {
let mat = material_of!(&l.component_id);
let th = if l.thickness.is_finite() { l.thickness } else { 0.0 };
w.add("IFCMATERIALLAYER", format!("#{mat},{},$,$,$,$,$", r(th.max(0.0))))
})
.collect();
let type_id = w.add($ifc_type, format!("{},#{owner_history},{},$,$,$,$,$,$,{}", s(&ifc_guid(&key)), s($t_name), en($predefined)));
if !layer_ids.is_empty() {
let set = w.add("IFCMATERIALLAYERSET", format!("{},{},$", refs(&layer_ids), s($t_name)));
w.add("IFCRELASSOCIATESMATERIAL", format!("{},#{owner_history},$,$,{},#{set}", s(&ifc_guid(&format!("{key}:material"))), refs(&[type_id])));
}
element_types.push((key, ElementTypeRef { type_id, occurrences: vec![] }));
element_types.len() - 1
}
}
}};
}
// ── Wände (öffnungsgenaues Dreiecks-Mesh) ──
let bands = model3d::emit_walls(p, true)?;
let mut bands_by_wall: HashMap<&str, Vec<usize>> = HashMap::new();
for (i, b) in bands.iter().enumerate() {
bands_by_wall.entry(b.wall_id.as_str()).or_default().push(i);
}
let mut wall_entity_by_id: HashMap<&str, usize> = HashMap::new();
for wall in &p.walls {
let Some(idxs) = bands_by_wall.get(wall.id.as_str()).filter(|v| !v.is_empty()) else { continue };
let structure = resolve_structure(&wall.floor_id);
let mut positions: Vec<f64> = Vec::new();
let mut indices: Vec<u32> = Vec::new();
for &bi in idxs {
let b = &bands[bi];
let cw = CutWall {
start: b.start,
end: b.end,
thickness: b.thickness,
base_elevation: b.base_elevation,
height: b.height,
holes: b.holes.as_ref().map_or(vec![], |hs| hs.iter().map(|h| [h.from, h.to, h.z_bottom, h.z_top]).collect()),
};
let finite = cw.start.iter().chain(&cw.end).all(|v| v.is_finite()) && [cw.thickness, cw.base_elevation, cw.height].iter().all(|v| v.is_finite()) && cw.holes.iter().flatten().all(|v| v.is_finite());
let cut = if finite { wall_cut_mesh(&cw) } else { Vec::new() };
let base = (positions.len() / 3) as u32;
for c in cut.chunks_exact(3) {
positions.extend([c[0], c[2], c[1] - structure.base_elevation]);
}
// Wicklung umkehren (Reflexions-Ausgleich des Achsentauschs): (a, b, c) → (a, c, b).
let n_tris = (cut.len() / 3) as u32 / 3;
for t in 0..n_tris {
let i = t * 3;
indices.extend([base + i, base + i + 2, base + i + 1]);
}
}
if indices.is_empty() {
continue;
}
let closed = is_watertight(&positions, &indices, 1e-6);
let (placement, shape) = emit_triangulated_product!(&positions, &indices, structure.placement_id, closed);
let mut name = wall.id.clone();
let mut type_idx = None;
if let Some(wt) = p.wall_type(wall) {
name = wt.name.clone();
type_idx = Some(type_for!("IFCWALLTYPE", "STANDARD", wt.id, &wt.name, &wt.layers));
}
let entity = emit_building_element!("IFCWALL", ifc_guid(&wall.id), name, placement, shape, None::<String>);
if let Some(i) = type_idx {
element_types[i].1.occurrences.push(entity);
}
wall_entity_by_id.insert(wall.id.as_str(), entity);
add_to_containment(structure.entity_id, entity);
}
// ── Decken ──
for ceiling in p.ceilings.as_deref().unwrap_or(&[]) {
if ceiling.outline.len() < 3 {
continue;
}
let (z_bottom, z_top) = p.ceiling_vertical_extent(ceiling);
let structure = resolve_structure(&ceiling.floor_id);
let (placement, shape) = emit_box_product!(&ceiling.outline, z_bottom - structure.base_elevation, z_top - z_bottom, structure.placement_id);
let mut name = ceiling.id.clone();
let mut type_idx = None;
if let Some((tid, tname, layers)) = ceiling_type_of(p, ceiling) {
name = tname.to_string();
type_idx = Some(type_for!("IFCSLABTYPE", "FLOOR", tid, tname, layers));
}
let entity = emit_building_element!("IFCSLAB", ifc_guid(&ceiling.id), name, placement, shape, Some(en("FLOOR")));
if let Some(i) = type_idx {
element_types[i].1.occurrences.push(entity);
}
add_to_containment(structure.entity_id, entity);
}
// ── Fenster/Türen als eigene Objekte ──
for opening in p.openings.as_deref().unwrap_or(&[]) {
let Some(wall) = p.walls.iter().find(|wl| wl.id == opening.host_wall_id) else { continue };
if !wall_entity_by_id.contains_key(wall.id.as_str()) {
continue;
}
let (wall_z_bottom, _) = p.wall_vertical_extent(wall);
let structure = resolve_structure(&wall.floor_id);
let footprint = opening_footprint(p, wall, opening);
let z_sill_abs = wall_z_bottom + opening.sill_height;
let (fill_placement, fill_shape) = emit_box_product!(&footprint, z_sill_abs - structure.base_elevation, opening.height, structure.placement_id);
let fill_guid = ifc_guid(&format!("{}:fill", opening.id));
let fill_name = opening_label(opening);
let entity = if opening.kind == ElementKind::Door {
w.add(
"IFCDOOR",
format!("{},#{owner_history},{},$,$,#{fill_placement},#{fill_shape},$,{},{},{},$,$", s(&fill_guid), s(&fill_name), r(opening.height), r(opening.width), en("DOOR")),
)
} else {
w.add(
"IFCWINDOW",
format!("{},#{owner_history},{},$,$,#{fill_placement},#{fill_shape},$,{},{},{},$,$", s(&fill_guid), s(&fill_name), r(opening.height), r(opening.width), en("WINDOW")),
)
};
add_to_containment(structure.entity_id, entity);
}
// ── Treppen ──
for stair in p.stairs.as_deref().unwrap_or(&[]) {
let footprint = stair_footprint(stair);
if footprint.len() < 3 {
continue;
}
let (z_bottom, z_top) = p.stair_vertical_extent(stair);
let structure = resolve_structure(&stair.floor_id);
let (placement, shape) = emit_box_product!(&footprint, z_bottom - structure.base_elevation, z_top - z_bottom, structure.placement_id);
let predefined = match stair.shape {
StairShape::Straight => en("STRAIGHT_RUN_STAIR"),
StairShape::Spiral => en("SPIRAL_STAIR"),
StairShape::L => en("QUARTER_TURN_STAIR"),
};
let entity = emit_building_element!("IFCSTAIR", ifc_guid(&stair.id), "Treppe".to_string(), placement, shape, Some(predefined));
add_to_containment(structure.entity_id, entity);
}
// ── Extrudierte Körper ──
for solid in p.extruded_solids.as_deref().unwrap_or(&[]) {
if solid.points.len() < 3 {
continue;
}
let base = floors.iter().find(|f| f.id == solid.level_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0));
let structure = resolve_structure(&solid.level_id);
let (placement, shape) = emit_box_product!(&solid.points, base - structure.base_elevation, solid.height, structure.placement_id);
let entity = emit_building_element!("IFCBUILDINGELEMENTPROXY", ifc_guid(&solid.id), "Extrusion".to_string(), placement, shape, None::<String>);
add_to_containment(structure.entity_id, entity);
}
// ── Räume → IfcSpace ──
let mut spaces_by_structure: Vec<(usize, Vec<usize>)> = Vec::new();
for room in p.rooms.as_deref().unwrap_or(&[]) {
if room.boundary.len() < 3 {
continue;
}
let structure = resolve_structure(&room.floor_id);
let height = floors.iter().find(|f| f.id == room.floor_id).and_then(|f| f.floor_height).filter(|h| *h > 0.0).unwrap_or(2.5);
let (placement, shape) = emit_box_product!(&room.boundary, 0.0, height, structure.placement_id);
let number = room.stamp.as_ref().and_then(|st| st.number.as_deref()).filter(|n| !n.is_empty()).unwrap_or(&room.id);
let space_id = w.add(
"IFCSPACE",
format!("{},#{owner_history},{},$,$,#{placement},#{shape},{},{},{},$", s(&ifc_guid(&room.id)), s(number), s(&room.name), en("ELEMENT"), en("INTERNAL")),
);
match spaces_by_structure.iter_mut().find(|(k, _)| *k == structure.entity_id) {
Some((_, v)) => v.push(space_id),
None => spaces_by_structure.push((structure.entity_id, vec![space_id])),
}
let pts: Vec<[f64; 2]> = room.boundary.iter().map(|v| [v.x, v.y]).collect();
let area = crate::room_area::evaluate(&pts, 0.0);
let q_net = w.add("IFCQUANTITYAREA", format!("{},$,$,{},$", s("NetFloorArea"), r(area.net)));
let q_gross = w.add("IFCQUANTITYAREA", format!("{},$,$,{},$", s("GrossFloorArea"), r(area.gross)));
let q_height = w.add("IFCQUANTITYLENGTH", format!("{},$,$,{},$", s("Height"), r(height)));
let qto = w.add(
"IFCELEMENTQUANTITY",
format!("{},#{owner_history},{},$,$,{}", s(&ifc_guid(&format!("{}:qto", room.id))), s("Qto_SpaceBaseQuantities"), refs(&[q_net, q_gross, q_height])),
);
w.add("IFCRELDEFINESBYPROPERTIES", format!("{},#{owner_history},$,$,{},#{qto}", s(&ifc_guid(&format!("{}:rel-qto", room.id))), refs(&[space_id])));
let sia_name = serde_json::to_value(room.sia_category).ok().and_then(|v| v.as_str().map(str::to_owned)).unwrap_or_default();
let sia = w.add("IFCPROPERTYSINGLEVALUE", format!("{},$,IFCLABEL({}),$", s("SIA416"), s(&sia_name)));
let pset = w.add("IFCPROPERTYSET", format!("{},#{owner_history},{},$,{}", s(&ifc_guid(&format!("{}:pset", room.id))), s("CH_Raum"), refs(&[sia])));
w.add("IFCRELDEFINESBYPROPERTIES", format!("{},#{owner_history},$,$,{},#{pset}", s(&ifc_guid(&format!("{}:rel-pset", room.id))), refs(&[space_id])));
}
for (structure_id, space_ids) in &spaces_by_structure {
w.add("IFCRELAGGREGATES", format!("{},#{owner_history},$,$,#{structure_id},{}", s(&ifc_guid(&format!("spaces:{structure_id}"))), refs(space_ids)));
}
// ── Dächer → IfcRoof ──
for roof in p.roofs.as_deref().unwrap_or(&[]) {
let structure = resolve_structure(&roof.floor_id);
let mut positions: Vec<f64> = Vec::new();
let mut indices: Vec<u32> = Vec::new();
for mesh in model3d::emit_roofs(p, Some(&roof.id))? {
let base = (positions.len() / 3) as u32;
for c in mesh.positions.chunks_exact(3) {
positions.extend([c[0], c[1], c[2] - structure.base_elevation]);
}
indices.extend(mesh.indices.iter().map(|ix| base + ix));
}
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 (placement, shape) = emit_triangulated_product!(&positions, &indices, structure.placement_id, closed);
let predefined = match roof.shape {
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",
};
let roof_type = roof.roof_type_id.as_deref().and_then(|id| p.roof_types.as_deref()?.iter().find(|t| t.id == id));
let name = roof_type.map_or("Dach".to_string(), |t| t.name.clone());
let entity = emit_building_element!("IFCROOF", ifc_guid(&roof.id), name, placement, shape, Some(en(predefined)));
if let Some(rt) = roof_type {
let i = type_for!("IFCROOFTYPE", predefined, rt.id, &rt.name, &rt.layers);
element_types[i].1.occurrences.push(entity);
}
add_to_containment(structure.entity_id, entity);
}
// ── Stützen → IfcColumn ──
let mut material_assoc: Vec<(usize, Vec<usize>)> = Vec::new();
for col in p.columns.as_deref().unwrap_or(&[]) {
let footprint = model3d::column_footprint(col);
if footprint.len() < 3 {
continue;
}
let (z_bottom, z_top) = p.column_vertical_extent(col);
if !(z_top > z_bottom) {
continue;
}
let structure = resolve_structure(&col.floor_id);
let (placement, shape) = emit_box_product!(&footprint, z_bottom - structure.base_elevation, z_top - z_bottom, structure.placement_id);
let entity = emit_building_element!("IFCCOLUMN", ifc_guid(&col.id), column_label(col), placement, shape, Some(en("COLUMN")));
add_to_containment(structure.entity_id, entity);
if let Some(cid) = col.component_id.as_deref().filter(|c| !c.is_empty()) {
let mat = material_of!(cid);
match material_assoc.iter_mut().find(|(k, _)| *k == mat) {
Some((_, v)) => v.push(entity),
None => material_assoc.push((mat, vec![entity])),
}
}
}
for (mat, ids) in &material_assoc {
w.add("IFCRELASSOCIATESMATERIAL", format!("{},#{owner_history},$,$,{},#{mat}", s(&ifc_guid(&format!("material:{mat}"))), refs(ids)));
}
// ── Typ-Zuordnung ──
for (key, rf) in &element_types {
if rf.occurrences.is_empty() {
continue;
}
w.add("IFCRELDEFINESBYTYPE", format!("{},#{owner_history},$,$,{},#{}", s(&ifc_guid(&format!("{key}:occurrences"))), refs(&rf.occurrences), rf.type_id));
}
// ── Räumliche Eingliederung ──
for (structure_id, element_ids) in &containment {
w.add("IFCRELCONTAINEDINSPATIALSTRUCTURE", format!("{},#{owner_history},$,$,{},#{structure_id}", s(&ifc_guid(&format!("contain:{structure_id}"))), refs(element_ids)));
}
// ── Kopf + Zusammenbau ──
let iso = iso_from_ms(now_ms);
let file_name = format!("{}.ifc", if p.name.is_empty() { "modell" } else { &p.name });
let mut out = vec![
"ISO-10303-21;".to_string(),
"HEADER;".to_string(),
format!("FILE_DESCRIPTION({},{});", list(&[s("")]), s("2;1")),
format!("FILE_NAME({},{},{},{},{},{},{});", s(&file_name), s(&iso), list(&[s("dossier")]), list(&[s("dossier")]), s("dossier"), s("dossier"), s("")),
"FILE_SCHEMA(('IFC4'));".to_string(),
"ENDSEC;".to_string(),
String::new(),
"DATA;".to_string(),
];
out.extend(w.lines);
out.push("ENDSEC;".to_string());
out.push("END-ISO-10303-21;".to_string());
Ok(out.join("\n") + "\n")
}
/// Deckentyp (id, Name, Schichten): Deckentyp, sonst Wandtyp (`getCeilingType`).
fn ceiling_type_of<'a>(p: &'a Project, c: &Ceiling) -> Option<(&'a str, &'a str, &'a [Layer])> {
if let Some(id) = c.ceiling_type_id.as_deref() {
if let Some(t) = p.ceiling_types.as_deref().and_then(|v| v.iter().find(|t| t.id == id)) {
return Some((&t.id, &t.name, &t.layers));
}
}
p.wall_types.iter().find(|t| t.id == c.wall_type_id).map(|t| (t.id.as_str(), t.name.as_str(), t.layers.as_slice()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn guid_ist_stabil_und_22_zeichen_lang() {
let g = ifc_guid("wall-1");
assert_eq!(g.len(), 22);
assert_eq!(g, ifc_guid("wall-1"));
assert_ne!(g, ifc_guid("wall-2"));
}
#[test]
fn string_und_zahl_literale() {
assert_eq!(ifc_string("A'b\\ü😀"), "'A''b\\\\\\X2\\00FC\\X0\\\\X4\\0001F600\\X0\\'");
assert_eq!(r(1.0), "1.0");
assert_eq!(r(-0.0), "0.0");
assert_eq!(r(0.1234567), "0.123457");
assert_eq!(r(2.5), "2.5");
}
#[test]
fn iso_datum() {
assert_eq!(iso_from_ms(0.0), "1970-01-01T00:00:00");
assert_eq!(iso_from_ms(1_700_000_000_000.0), "2023-11-14T22:13:20");
}
#[test]
fn beispielprojekt_exportiert() {
let p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap();
let ifc = export_ifc_spf(&p, 1_700_000_000_000.0).unwrap();
assert!(ifc.starts_with("ISO-10303-21;\nHEADER;"));
assert!(ifc.contains("IFCWALL("));
assert!(ifc.ends_with("END-ISO-10303-21;\n"));
}
}
+158
View File
@@ -0,0 +1,158 @@
//! Ursprungs-Verschiebung des ganzen Projekts ([K4] S2, vorher `model/geoRebase.ts`): reine,
//! verlustfreie Translation aller Modell-Koordinaten um einen festen Vektor. `geoAnchor` wandert
//! mit, damit der LV95-Bezug exakt erhalten bleibt. Nur Translation — keine Rotation (Achsen- und
//! Winkelfelder blieben sonst falsch). Richtungsvektoren (z. B. `Stair.dir`) bleiben unangetastet.
use crate::model::*;
fn shift(p: Vec2, dx: f64, dy: f64) -> Vec2 {
Vec2 { x: p.x + dx, y: p.y + dy }
}
fn shift_all(pts: &mut [Vec2], dx: f64, dy: f64) {
for p in pts {
*p = shift(*p, dx, dy);
}
}
fn shift_geom(g: &mut Drawing2DGeom, dx: f64, dy: f64) {
use Drawing2DGeom::*;
match g {
Line { a, b } | Xline { a, b } | Ray { a, b } => {
*a = shift(*a, dx, dy);
*b = shift(*b, dx, dy);
}
Polyline { pts, .. } | Bezier { pts } | Spline { pts, .. } | Dimension { pts, .. } => shift_all(pts, dx, dy),
Rect { min, max } | Image { min, max, .. } => {
*min = shift(*min, dx, dy);
*max = shift(*max, dx, dy);
}
Circle { center, .. } | Arc { center, .. } | Ellipse { center, .. } => *center = shift(*center, dx, dy),
Kote { at, .. } | Detailref { at, .. } | Scalebar { at, .. } | Pointmarker { at } | Block { at, .. } => *at = shift(*at, dx, dy),
Text { at, leader_target, leader_bend_points, path_pts, .. } => {
*at = shift(*at, dx, dy);
if let Some(t) = leader_target {
*t = shift(*t, dx, dy);
}
if let Some(v) = leader_bend_points {
shift_all(v, dx, dy);
}
if let Some(v) = path_pts {
shift_all(v, dx, dy);
}
}
}
}
fn shift_context(o: &mut ContextObject, dx: f64, dy: f64) {
match o {
ContextObject::ContourSet(s) => {
for c in &mut s.contours {
shift_all(&mut c.pts, dx, dy);
if let Some(cv) = &mut c.curve {
cv.cx += dx;
cv.cy += dy;
}
}
}
ContextObject::Image(i) => {
i.min = shift(i.min, dx, dy);
i.max = shift(i.max, dx, dy);
}
ContextObject::ImportedMesh(m) => shift_positions(&mut m.positions, dx, dy),
ContextObject::TerrainMesh(m) => shift_positions(&mut m.positions, dx, dy),
}
}
/// Nur x/y (Grundriss) verschieben, die Höhe bleibt.
fn shift_positions(pos: &mut [f64], dx: f64, dy: f64) {
for c in pos.chunks_exact_mut(3) {
c[0] += dx;
c[1] += dy;
}
}
/// Verschiebt sämtliche Modell-Koordinaten (`translateProject`).
pub fn translate_project(p: &Project, dx: f64, dy: f64) -> Project {
if dx == 0.0 && dy == 0.0 {
return p.clone();
}
let mut out = p.clone();
for w in &mut out.walls {
w.start = shift(w.start, dx, dy);
w.end = shift(w.end, dx, dy);
}
for c in out.ceilings.iter_mut().flatten() {
shift_all(&mut c.outline, dx, dy);
for h in c.openings.iter_mut().flatten() {
shift_all(h, dx, dy);
}
}
for r in out.roofs.iter_mut().flatten() {
shift_all(&mut r.outline, dx, dy);
}
for s in out.stairs.iter_mut().flatten() {
s.start = shift(s.start, dx, dy);
s.center = s.center.map(|c| shift(c, dx, dy));
}
for r in out.rooms.iter_mut().flatten() {
shift_all(&mut r.boundary, dx, dy);
r.stamp_anchor = r.stamp_anchor.map(|a| shift(a, dx, dy));
}
for c in out.columns.iter_mut().flatten() {
c.position = shift(c.position, dx, dy);
}
for s in out.extruded_solids.iter_mut().flatten() {
shift_all(&mut s.points, dx, dy);
if let Some(c) = &mut s.circle {
c.center = shift(c.center, dx, dy);
}
}
for d in &mut out.drawings2d {
shift_geom(&mut d.geom, dx, dy);
}
for o in out.context.iter_mut().flatten() {
shift_context(o, dx, dy);
}
for l in &mut out.drawing_levels {
if let Some(pts) = &mut l.line_points {
pts[0] = shift(pts[0], dx, dy);
pts[1] = shift(pts[1], dx, dy);
}
}
if let Some(a) = &mut out.geo_anchor {
a.model = shift(a.model, dx, dy);
}
out
}
/// LV95-Ursprung: die reale Landeskoordinate, die auf den Modell-Nullpunkt abgebildet wird.
pub fn project_geo_origin(p: &Project) -> Option<(f64, f64)> {
let a = p.geo_anchor.as_ref()?;
Some((a.lv95.e - a.model.x, a.lv95.n - a.model.y))
}
/// Kopie mit Geometrie in realen Weltkoordinaten (LV95) für Modell-Exporte; ohne Bezug unverändert.
pub fn project_to_world_coords(p: &Project) -> Project {
match project_geo_origin(p) {
Some((e, n)) => translate_project(p, e, n),
None => p.clone(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn verschiebt_alles_und_haelt_den_anker() {
let mut p: Project = serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap();
p.geo_anchor = Some(ProjectGeoAnchor { lv95: ProjectGeoAnchorLv95 { e: 2_600_000.0, n: 1_200_000.0, ..Default::default() }, model: Vec2 { x: 1.0, y: 2.0 }, ..Default::default() });
let w = project_to_world_coords(&p);
assert_eq!(w.walls[0].start.x, p.walls[0].start.x + 2_599_999.0);
assert_eq!(w.walls[0].start.y, p.walls[0].start.y + 1_199_998.0);
// Der Anker wandert mit: das verschobene Modell liegt bereits in Landeskoordinaten (Ursprung 0, 0).
assert_eq!(project_geo_origin(&w), Some((0.0, 0.0)));
assert_eq!(project_to_world_coords(&Project { geo_anchor: None, ..p.clone() }), Project { geo_anchor: None, ..p });
}
}
+70
View File
@@ -0,0 +1,70 @@
//! Zahlenformatierung wie JavaScript: `Number.prototype.toFixed` rundet exakte Halbwerte AUF
//! (`pick the larger n`), Rusts `{:.N}` zum geraden Nachbarn — bei dyadischen Werten wie 0.0078125
//! (6 Nachkommastellen) verschieden. Exporte (IFC, CSV) müssen byteweise wie die TS-Fassung sein.
/// `x.toFixed(d)` (|x| < 1e21).
pub fn to_fixed(x: f64, d: usize) -> String {
if x.is_nan() {
return "NaN".into();
}
if x.is_infinite() {
return if x > 0.0 { "Infinity".into() } else { "-Infinity".into() };
}
let neg = x < 0.0;
let ax = x.abs();
if ax >= 1e21 {
return format!("{}{}", if neg { "-" } else { "" }, ax);
}
// 25 Stellen mehr als nötig: ein exakter Halbwert zeigt sich als '5' gefolgt von Nullen.
let wide = format!("{:.*}", d + 25, ax);
let (int_part, frac) = wide.split_once('.').expect("Nachkommastellen");
let mut digits: Vec<u8> = int_part.bytes().chain(frac.bytes().take(d)).collect();
let round_up = frac.as_bytes().get(d).is_some_and(|&c| c >= b'5');
if round_up {
let mut i = digits.len();
loop {
if i == 0 {
digits.insert(0, b'1');
break;
}
i -= 1;
if digits[i] == b'9' {
digits[i] = b'0';
} else {
digits[i] += 1;
break;
}
}
}
let int_len = digits.len() - d;
let mut s = String::new();
if neg {
s.push('-');
}
s.push_str(std::str::from_utf8(&digits[..int_len]).expect("ASCII"));
if d > 0 {
s.push('.');
s.push_str(std::str::from_utf8(&digits[int_len..]).expect("ASCII"));
}
s
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rundet_halbwerte_auf_wie_js() {
assert_eq!(to_fixed(0.0078125, 6), "0.007813"); // JS: "0.007813"; Rust {:.6}: 0.007812
assert_eq!(to_fixed(12.5, 0), "13");
assert_eq!(to_fixed(-2.5, 0), "-3");
assert_eq!(to_fixed(0.5, 0), "1");
assert_eq!(to_fixed(1.0, 6), "1.000000");
assert_eq!(to_fixed(0.0, 6), "0.000000");
assert_eq!(to_fixed(-1e-7, 6), "-0.000000");
assert_eq!(to_fixed(9.9999996, 6), "10.000000");
assert_eq!(to_fixed(123.456, 2), "123.46");
assert_eq!(to_fixed(2.675, 2), "2.67"); // 2.675 ist binär 2.67499999… — JS: "2.67"
assert_eq!(to_fixed(1e-9, 6), "0.000000");
}
}
+3
View File
@@ -4,7 +4,9 @@
//!
//! Datenübergabe: flache `f64`-Puffer (s. [`flat`]), kein JSON — schnell und ohne Serde-Kosten.
pub mod export_ifc;
pub mod flat;
pub mod geo_rebase;
pub mod flat_write;
pub mod polygon_bool;
pub mod roof;
@@ -21,6 +23,7 @@ pub mod wall_bands;
pub mod room_area;
pub mod room_boundary;
pub mod polygon_holes;
pub mod js_fmt;
pub mod jsmath;
pub mod stairs3d;
pub mod mesh3d;
+14
View File
@@ -90,3 +90,17 @@ pub fn doc_query_args(h: u32, name: &str, args: &[f64], text: &str) -> String {
pub fn doc_drawing_line_verts(h: u32) -> Vec<f32> {
with_doc(h, |d| d.project().ok().map(|p| crate::model3d::drawing_line_verts(&p))).flatten().unwrap_or_default()
}
/// IFC4-Datei des Projekts (`now_ms`: Zeitpunkt des Exports); Fehler mit vorangestelltem `\u{1}`.
#[wasm_bindgen]
pub fn doc_export_ifc(h: u32, now_ms: f64) -> String {
let result = with_doc(h, |d| {
let p = d.project().map_err(|e| format!("Projekt passt nicht zum Kern-Modell: {e}"))?;
crate::export_ifc::export_ifc_spf(p, now_ms)
})
.unwrap_or_else(|| Err("Dokument nicht offen".to_string()));
match result {
Ok(text) => text,
Err(e) => format!("\u{1}{e}"),
}
}
+15
View File
@@ -0,0 +1,15 @@
//! Bindungen kleiner IFC-Bausteine (`crate::export_ifc`); die Datei selbst liefert `doc_export_ifc`.
use wasm_bindgen::prelude::wasm_bindgen;
/// Deterministische 22-stellige IFC-GUID aus einer Element-ID.
#[wasm_bindgen]
pub fn ifc_guid(id: &str) -> String {
crate::export_ifc::ifc_guid(id)
}
/// STEP-String-Literal (ISO 10303-21) mit Escapes.
#[wasm_bindgen]
pub fn ifc_string(s: &str) -> String {
crate::export_ifc::ifc_string(s)
}
+1
View File
@@ -24,6 +24,7 @@ mod plan_stairs;
mod plan_walls;
mod plan_openings;
mod delaunay;
mod export_ifc;
mod document;
mod mesh_section;
mod plan_elevation;
+8
View File
@@ -82,6 +82,14 @@ export class ProjectDocument {
return out;
}
/** IFC4-Datei (STEP-Text) des Projekts; `nowMs` = Zeitpunkt des Exports. */
exportIfc(nowMs: number): string {
if (!this.handle) throw new Error("IFC-Export: Dokument nicht offen");
const out = core().doc_export_ifc(this.handle, nowMs);
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
return out;
}
/** Boden-Spuren der 2D-Zeichnungen als LineList-Vertices `[px, py, pz, r, g, b]`. */
drawingLineVerts(): Float32Array {
return this.handle ? core().doc_drawing_line_verts(this.handle) : new Float32Array(0);
+15 -918
View File
@@ -1,932 +1,29 @@
// IFC4-Export (STEP Physical File / ISO-10303-21) des semantischen Modells.
// Reiner Rechen-/Serialisierungskern: keine UI, kein Datei-IO, kein WASM, keine
// neue Dependency — IFC wird direkt als Text geschrieben (analog exportDxf.ts/
// exportSchedule.ts). Der Download (Blob+Anchor) passiert im App-Layer.
//
// Abbildung (erste vollständige Scheibe):
// Project → IfcProject → IfcSite → IfcBuilding → je "floor"-Geschoss ein
// IfcBuildingStorey (IfcRelAggregates-Kette). Bauteile hängen über
// IfcRelContainedInSpatialStructure am jeweiligen Geschoss (verwaiste
// Geschossreferenzen fallen defensiv auf IfcBuilding zurück).
//
// Decken/Treppen/Extrusionen als IfcExtrudedAreaSolid (unser Modell IST
// Extrusion): Profil = IfcArbitraryClosedProfileDef(IfcPolyline) in der
// XY-Ebene, extrudiert entlang +Z. Die horizontale Objekt-Platzierungskette
// (Site/Building/Storey/Element) trägt bewusst NUR die Z-Verschiebung
// (Geschoss-Elevation); die Profilpunkte tragen direkt die Welt-X/Y-Koordinaten.
//
// • Wand → IfcWall mit ÖFFNUNGSGENAUEM Dreiecks-Mesh (IfcTriangulatedFace
// Set, IFC4: IfcCartesianPointList3D + CoordIndex) statt einer Profil-
// Extrusion. Gespeist aus DEMSELBEN Loch-Ausschnitt-Mesh wie STL/OBJ
// (`pickGeometry` → `plan/wallMeshCut.ts`): Joins/Gehrungen UND ausgeschnittene
// Fenster/Türen (inkl. Laibungen) sind im Körper enthalten. ABWÄGUNG (bewusst,
// Nutzer-Priorität "so wie im 3D"): dadurch verliert die Wand die parametrische
// IfcWall-Profil-Extrusion + IfcOpeningElement-Void-Semantik zugunsten
// VISUELLER PARITÄT in JEDEM Viewer (der Loch schon im Mesh sieht, ohne eine
// Boolean-Subtraktion ausführen zu müssen — genau der Bug des Nutzers: "das
// Fenster ist als Objekt da im IFC, aber die Löcher sind nicht da").
// • Decke → IfcSlab (outline-Polygon, PredefinedType FLOOR).
// • Öffnung → KEIN IfcOpeningElement/Void mehr (das Loch steckt im Wand-Mesh);
// Tür/Fenster bleiben als eigenes Objekt IfcDoor/IfcWindow mit eigener Box-
// Geometrie erhalten (füllt das ausgeschnittene Loch, "sieht aus wie 3D").
// • Extrusion → IfcBuildingElementProxy aus points+height.
// • Dach → IfcRoof (Schicht-Meshes wie im 3D), Dachtyp → IfcRoofType mit Schichten.
// • Stütze → IfcColumn (Profil-Extrusion), Bauteil → IfcMaterial.
// • Raum → IfcSpace (im Geschoss aggregiert) mit Qto_SpaceBaseQuantities und SIA-416-Kategorie.
// • Treppe → IfcStair, GEOMETRISCH bewusst vereinfacht auf einen
// extrudierten Bounding-Footprint (Lauf-Rechteck bei "straight"; Achsen-
// ausgerichtete Bounding-Box der Kontrollpunkte bei "L"/"spiral") — die
// echte Stufengeometrie ist ausgelassen (siehe stairFootprint()).
//
// Material-Schichten: je Wand-/Deckentyp ein IfcWallType/IfcSlabType mit
// IfcMaterialLayerSet, die Exemplare erben ihn über IfcRelDefinesByType. KEIN
// IfcMaterialLayerSetUsage am Exemplar: Richtung/Versatz der Usage beziehen sich
// auf eine Achs-Darstellung, die das Wand-Mesh nicht hat.
//
// GUIDs: deterministisch aus der Element-ID über einen 128-Bit-Hash (zwei
// FNV-1a-64-Läufe) + Standard-IFC-GUID-Kompression (Base64-Variante,
// Zeichensatz 0-9,A-Z,a-z,_,$) — stabil über Re-Exporte hinweg.
//
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). Einheit: METER.
// Gerechnet wird im Rust-Kern (`src-tauri/core/src/export_ifc.rs`, [K4] S2) auf dem Projekt-Dokument:
// Project → Site → Building → Storeys, Wände als öffnungsgenaue Dreiecks-Netze, Decken/Treppen/
// Körper/Stützen/Räume als Profil-Extrusionen, Dächer als Schicht-Netze, Wand-/Deckentypen mit
// Materialschichten; GUIDs deterministisch aus der Element-ID; bei gesetztem `geoAnchor` in LV95-
// Weltkoordinaten. Der Download (Blob + Anchor) passiert im App-Layer.
import type {
Opening,
Project,
Stair,
Vec2,
Wall,
} from "../model/types";
import {
columnLabel,
getCeilingType,
getWallType,
openingLabel,
wallTypeThickness,
} from "../model/types";
import { projectToWorldCoords } from "../model/geoRebase";
import {
ceilingVerticalExtent,
columnVerticalExtent,
stairVerticalExtent,
wallReferenceOffset,
wallVerticalExtent,
} from "../model/wall";
import { pickGeometry } from "../plan/toWalls3d";
import type { RWall } from "../plan/toWalls3d";
import { isWatertight, wallCutMeshes, type CutMesh } from "../plan/wallMeshCut";
import { evaluateRoom } from "../geometry/roomArea";
import { columnFootprint } from "../geometry/column";
import { roofMeshes } from "../plan/toWalls3d";
// ── IFC-GUID (Base64-Kompression, 22 Zeichen) ───────────────────────────────
// Standard-Kompressionsalgorithmus (IfcOpenShell guid.compress): das erste
// Byte des 128-Bit-Werts wird auf 2 Zeichen abgebildet, die restlichen 15
// Byte in 5 Dreiergruppen zu je 4 Zeichen — macht 2 + 5×4 = 22 Zeichen.
const IFC_GUID_CHARS =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_$";
/** Kodiert `v` big-endian in `len` IFC-GUID-Zeichen (Basis 64). */
function ifcGuidB64(v: number, len: number): string {
let out = "";
for (let i = len - 1; i >= 0; i--) {
out += IFC_GUID_CHARS[Math.floor(v / 64 ** i) % 64];
}
return out;
}
/** Komprimiert einen 128-Bit-Wert (32 Hex-Zeichen) zur 22-stelligen IFC-GUID. */
function compressGuidHex(hex32: string): string {
const bytes: number[] = [];
for (let i = 0; i < 32; i += 2) bytes.push(parseInt(hex32.slice(i, i + 2), 16));
let out = ifcGuidB64(bytes[0], 2);
for (let i = 1; i < 16; i += 3) {
const v = (bytes[i] << 16) + (bytes[i + 1] << 8) + bytes[i + 2];
out += ifcGuidB64(v, 4);
}
return out;
}
/** FNV-1a-64 (BigInt) — reines Determinismus-/Streuungs-Werkzeug, keine Kryptografie. */
function fnv1a64(str: string, seed: bigint): bigint {
const prime = 0x100000001b3n;
const mask = 0xffffffffffffffffn;
let hash = seed & mask;
for (let i = 0; i < str.length; i++) {
hash ^= BigInt(str.charCodeAt(i));
hash = (hash * prime) & mask;
}
return hash;
}
/** Leitet aus einer stabilen Element-ID einen deterministischen 128-Bit-Hex-Wert ab. */
function idToHex32(id: string): string {
const h1 = fnv1a64(id, 0xcbf29ce484222325n);
const h2 = fnv1a64(`${id}salt`, 0x9e3779b97f4a7c15n);
return h1.toString(16).padStart(16, "0") + h2.toString(16).padStart(16, "0");
}
import type { Project } from "../model/types";
import { core } from "../engine/coreWasm";
import { documentFor } from "../core/document";
/** Deterministische 22-stellige IFC-GUID aus einer beliebigen Element-ID. */
export function ifcGuid(id: string): string {
return compressGuidHex(idToHex32(id));
return core().ifc_guid(id);
}
// ── STEP-Formatierung ───────────────────────────────────────────────────────
/**
* STEP-String-Literal (ISO 10303-21): druckbares ASCII bleibt, Backslash und Apostroph werden
* verdoppelt, alles andere (Umlaute, Steuerzeichen) als \X2\HHHH…\X0\ (BMP) bzw.
* \X4\HHHHHHHH…\X0\ (ausserhalb der BMP). Die Datei bleibt so reines ASCII.
*/
/** STEP-String-Literal (ISO 10303-21): druckbares ASCII bleibt, alles andere wird als \X2\…\X0\ kodiert. */
export function ifcString(s: string): string {
let out = "";
let run: number[] = [];
const flush = () => {
if (run.length === 0) return;
const wide = run.some((c) => c > 0xffff);
const hex = run.map((c) => c.toString(16).toUpperCase().padStart(wide ? 8 : 4, "0")).join("");
out += `${wide ? "\\X4\\" : "\\X2\\"}${hex}\\X0\\`;
run = [];
};
for (const ch of s) {
const c = ch.codePointAt(0)!;
if (c >= 0x20 && c <= 0x7e) {
flush();
out += ch === "\\" ? "\\\\" : ch === "'" ? "''" : ch;
} else {
// \X2\ und \X4\ nicht mischen: Wechsel der Breite beginnt einen neuen Block.
if (run.length > 0 && (run[0] > 0xffff) !== (c > 0xffff)) flush();
run.push(c);
}
}
flush();
return `'${out}'`;
}
const S = ifcString;
/** STEP-REAL-Literal — immer mit Dezimalpunkt, ohne unnötige Nachkommastellen. */
function R(x: number): string {
const v = Object.is(x, -0) ? 0 : x;
let s = v.toFixed(6);
s = s.replace(/0+$/, "");
if (s.endsWith(".")) s += "0";
if (!s.includes(".")) s += ".0";
return s;
}
/** STEP-Enumerationswert `.WERT.`. */
function ENUM(v: string): string {
return `.${v}.`;
}
/** STEP-Liste `(a,b,c)`. */
function LIST(items: string[]): string {
return `(${items.join(",")})`;
}
// ── STEP-Writer ──────────────────────────────────────────────────────────────
class StepWriter {
private lines: string[] = [];
private nextId = 1;
/** Schreibt eine neue Entity-Zeile und liefert ihre `#id`. */
add(type: string, params: string): number {
const id = this.nextId++;
this.lines.push(`#${id}=${type}(${params});`);
return id;
}
get entityLines(): readonly string[] {
return this.lines;
}
}
// ── Geometrie-Helfer (reines 2D-Vec2-Rechnen, Welt-Meter) ───────────────────
function sub(a: Vec2, b: Vec2): Vec2 {
return { x: a.x - b.x, y: a.y - b.y };
}
function normalize(v: Vec2): Vec2 {
const len = Math.hypot(v.x, v.y) || 1;
return { x: v.x / len, y: v.y / len };
}
function leftNormal(u: Vec2): Vec2 {
return { x: -u.y, y: u.x };
}
function addScaled(p: Vec2, d: Vec2, s: number): Vec2 {
return { x: p.x + d.x * s, y: p.y + d.y * s };
}
/** Rechteck-Footprint einer Öffnung im Wandloch (volle Wanddicke tief), CCW. */
function openingFootprint(project: Project, wall: Wall, opening: Opening): Vec2[] {
const u = normalize(sub(wall.end, wall.start));
const n = leftNormal(u);
const t = wallTypeThickness(getWallType(project, wall));
const off = wallReferenceOffset(wall, t);
const inner = -t / 2 + off;
const outer = t / 2 + off;
const a = addScaled(wall.start, u, opening.position);
const b = addScaled(wall.start, u, opening.position + opening.width);
return [
addScaled(a, n, inner),
addScaled(b, n, inner),
addScaled(b, n, outer),
addScaled(a, n, outer),
];
return core().ifc_string(s);
}
/**
* Vereinfachter Bounding-Footprint einer Treppe (bewusst NICHT die echte
* Stufen-/Podestkontur, siehe Dateikopf):
* • "straight" — echtes, ausgerichtetes Lauf-Rechteck (Länge × Breite).
* • "L"/"spiral" — achsenausgerichtete Bounding-Box der Kontrollpunkte
* (Start/Eckpunkt/Ende bzw. Wendel-Zentrum±Radius), um die halbe
* Laufbreite erweitert.
* Baut aus einem Projekt einen vollständigen IFC4-SPF-String (STEP Physical File). Leeres Projekt ⇒
* valider Minimal-IFC. Wirft, wenn sich das Modell nicht ableiten lässt (z. B. unbekannter Wandtyp).
*/
function stairFootprint(stair: Stair): Vec2[] {
const halfW = Math.max(stair.width, 0) / 2;
if (stair.shape === "straight") {
const u = normalize(stair.dir);
const n = leftNormal(u);
const end = addScaled(stair.start, u, stair.runLength);
return [
addScaled(stair.start, n, -halfW),
addScaled(end, n, -halfW),
addScaled(end, n, halfW),
addScaled(stair.start, n, halfW),
];
}
const pts: Vec2[] = [stair.start];
const u = normalize(stair.dir);
const corner = addScaled(stair.start, u, stair.runLength);
pts.push(corner);
if (stair.shape === "L" && stair.run2Length && stair.turn) {
const n = leftNormal(u);
const turnDir: Vec2 = { x: n.x * stair.turn, y: n.y * stair.turn };
pts.push(addScaled(corner, turnDir, stair.run2Length));
}
if (stair.shape === "spiral" && stair.center) {
const r = (stair.radius ?? 0) + halfW;
const c = stair.center;
return [
{ x: c.x - r, y: c.y - r },
{ x: c.x + r, y: c.y - r },
{ x: c.x + r, y: c.y + r },
{ x: c.x - r, y: c.y + r },
];
}
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
for (const p of pts) {
minX = Math.min(minX, p.x);
minY = Math.min(minY, p.y);
maxX = Math.max(maxX, p.x);
maxY = Math.max(maxY, p.y);
}
minX -= halfW;
minY -= halfW;
maxX += halfW;
maxY += halfW;
return [
{ x: minX, y: minY },
{ x: maxX, y: minY },
{ x: maxX, y: maxY },
{ x: minX, y: maxY },
];
}
// ── IFC4-Export ──────────────────────────────────────────────────────────────
interface StoreyRef {
entityId: number;
placementId: number;
baseElevation: number;
}
interface Structure {
entityId: number;
placementId: number;
baseElevation: number;
}
/**
* Baut aus einem Projekt einen vollständigen IFC4-SPF-String (STEP Physical
* File). Reiner Rechenkern — kein Datei-IO. Leeres Projekt ⇒ valider Minimal-
* IFC (Project/Site/Building, kein Crash).
*/
export function exportIfcSpf(projectIn: Project): string {
// Georeferenziert exportieren: ist ein Standort-Bezug gesetzt (geoAnchor),
// wird die gesamte Geometrie auf die ECHTEN LV95-Weltkoordinaten verschoben,
// damit die IFC-Datei in anderer Software lagerichtig sitzt — auch wenn das
// Modell lokal nahe (0,0) bearbeitet wurde (s. projectToWorldCoords / der
// „Neuer Bezugspunkt"-Workflow). Ohne Bezug bleibt alles lokal (Identität).
const project = projectToWorldCoords(projectIn);
const w = new StepWriter();
// Geteilte Grundgeometrie: Ursprung, Z-Extrusionsrichtung, Identitäts-
// Placement (Position aller ExtrudedAreaSolid — Profile tragen direkt
// Welt-X/Y, siehe Dateikopf).
const originPoint = w.add("IFCCARTESIANPOINT", LIST([R(0), R(0), R(0)]));
const extrudeDir = w.add("IFCDIRECTION", LIST([R(0), R(0), R(1)]));
const identityAxis = w.add("IFCAXIS2PLACEMENT3D", `#${originPoint},$,$`);
// Owner-History (minimal, aber vorhanden — manche Importer verlangen sie).
const org = w.add("IFCORGANIZATION", `$,${S("dossier")},$,$,$`);
const person = w.add(
"IFCPERSON",
`${S("dossier")},$,$,$,$,$,$,$`,
);
const personOrg = w.add("IFCPERSONANDORGANIZATION", `#${person},#${org},$`);
const app = w.add(
"IFCAPPLICATION",
`#${org},${S("1.0")},${S("dossier")},${S("dossier")}`,
);
// ChangeAction ADDED verlangt ein LastModifiedDate (IFC4-Regel IfcOwnerHistory.CorrectChangeAction):
// beim frischen Export ist es der Erstellungszeitpunkt.
const now = Math.floor(Date.now() / 1000);
const ownerHistory = w.add(
"IFCOWNERHISTORY",
`#${personOrg},#${app},$,${ENUM("ADDED")},${now},$,$,${now}`,
);
// Einheiten (Meter, Radiant, m², m³).
const lenUnit = w.add("IFCSIUNIT", `*,${ENUM("LENGTHUNIT")},$,${ENUM("METRE")}`);
const areaUnit = w.add("IFCSIUNIT", `*,${ENUM("AREAUNIT")},$,${ENUM("SQUARE_METRE")}`);
const volUnit = w.add("IFCSIUNIT", `*,${ENUM("VOLUMEUNIT")},$,${ENUM("CUBIC_METRE")}`);
const angleUnit = w.add(
"IFCSIUNIT",
`*,${ENUM("PLANEANGLEUNIT")},$,${ENUM("RADIAN")}`,
);
const unitAssignment = w.add(
"IFCUNITASSIGNMENT",
LIST([`#${lenUnit}`, `#${areaUnit}`, `#${volUnit}`, `#${angleUnit}`]),
);
// Geometrischer Kontext (3D, Precision 1e-5).
const context = w.add(
"IFCGEOMETRICREPRESENTATIONCONTEXT",
`$,${S("Model")},3,${R(0.00001)},#${identityAxis},$`,
);
// Georeferenz: Die Geometrie liegt bereits in LV95-Weltkoordinaten (s. oben), die Abbildung
// lokal→Welt ist daher die Identität; das Koordinatensystem wird trotzdem deklariert, damit
// Importer die Datei als EPSG:2056 erkennen (IFC4 IfcProjectedCRS + IfcMapConversion).
if (project.geoAnchor) {
const crs = w.add(
"IFCPROJECTEDCRS",
`${S("EPSG:2056")},${S("CH1903+ / LV95")},${S("CH1903+")},$,${S("Swiss Oblique Mercator")},$,#${lenUnit}`,
);
w.add("IFCMAPCONVERSION", `#${context},#${crs},${R(0)},${R(0)},${R(0)},${R(1)},${R(0)},${R(1)}`);
}
// Räumliche Hierarchie: Project → Site → Building → Storeys.
const siteAxis = w.add("IFCAXIS2PLACEMENT3D", `#${originPoint},$,$`);
const sitePlacement = w.add("IFCLOCALPLACEMENT", `$,#${siteAxis}`);
const buildingAxis = w.add("IFCAXIS2PLACEMENT3D", `#${originPoint},$,$`);
const buildingPlacement = w.add(
"IFCLOCALPLACEMENT",
`#${sitePlacement},#${buildingAxis}`,
);
const projectId = w.add(
"IFCPROJECT",
`${S(ifcGuid(`${project.id}:project`))},#${ownerHistory},${S(project.name || "Projekt")},$,$,$,$,${LIST([`#${context}`])},#${unitAssignment}`,
);
// RefElevation (m ü. M.): reale Datumshöhe des Standorts aus dem
// Georeferenzierungs-Bezug (wie ArchiCADs Vermessungspunkt). Rein informativ —
// die Geometrie wird NICHT verschoben (das Terrain trägt bereits reale Höhen).
const refElevation = project.geoAnchor?.height;
const siteRefElev = typeof refElevation === "number" ? R(refElevation) : "$";
const siteId = w.add(
"IFCSITE",
`${S(ifcGuid(`${project.id}:site`))},#${ownerHistory},${S("Standort")},$,$,#${sitePlacement},$,$,${ENUM("ELEMENT")},$,$,${siteRefElev},$,$`,
);
const buildingId = w.add(
"IFCBUILDING",
`${S(ifcGuid(`${project.id}:building`))},#${ownerHistory},${S(project.name || "Gebäude")},$,$,#${buildingPlacement},$,$,${ENUM("ELEMENT")},$,$,$`,
);
w.add(
"IFCRELAGGREGATES",
`${S(ifcGuid(`${project.id}:agg-site`))},#${ownerHistory},$,$,#${projectId},${LIST([`#${siteId}`])}`,
);
w.add(
"IFCRELAGGREGATES",
`${S(ifcGuid(`${project.id}:agg-building`))},#${ownerHistory},$,$,#${siteId},${LIST([`#${buildingId}`])}`,
);
// Je "floor"-Geschoss ein IfcBuildingStorey (Elevation = baseElevation).
const floors = project.drawingLevels.filter((l) => l.kind === "floor");
const storeyByFloorId = new Map<string, StoreyRef>();
const storeyEntityIds: number[] = [];
for (const floor of floors) {
const base = floor.baseElevation ?? 0;
const pt = w.add("IFCCARTESIANPOINT", LIST([R(0), R(0), R(base)]));
const axis = w.add("IFCAXIS2PLACEMENT3D", `#${pt},$,$`);
const placementId = w.add("IFCLOCALPLACEMENT", `#${buildingPlacement},#${axis}`);
const entityId = w.add(
"IFCBUILDINGSTOREY",
`${S(ifcGuid(`${floor.id}:storey`))},#${ownerHistory},${S(floor.name)},$,$,#${placementId},$,$,${ENUM("ELEMENT")},${R(base)}`,
);
storeyByFloorId.set(floor.id, { entityId, placementId, baseElevation: base });
storeyEntityIds.push(entityId);
}
if (storeyEntityIds.length > 0) {
w.add(
"IFCRELAGGREGATES",
`${S(ifcGuid(`${project.id}:agg-storeys`))},#${ownerHistory},$,$,#${buildingId},${LIST(storeyEntityIds.map((id) => `#${id}`))}`,
);
}
/** Geschoss → Trägerstruktur (Storey), oder defensiv das Gebäude (verwaiste floorId). */
const resolveStructure = (floorId: string): Structure => {
const s = storeyByFloorId.get(floorId);
if (s) return { entityId: s.entityId, placementId: s.placementId, baseElevation: s.baseElevation };
return { entityId: buildingId, placementId: buildingPlacement, baseElevation: 0 };
};
// Räumliche Eingliederung sammelt sich je Trägerstruktur (Storey/Building)
// und wird am Ende in EINE IfcRelContainedInSpatialStructure je Struktur
// gebündelt (Öffnungen NICHT — die hängen nur über RelVoidsElement an ihrer
// Wand, wie in IFC üblich).
const containment = new Map<number, number[]>();
const addToContainment = (structureId: number, elementId: number): void => {
const arr = containment.get(structureId);
if (arr) arr.push(elementId);
else containment.set(structureId, [elementId]);
};
/** Baut Profil+Extrusion+Shape+Placement für einen geschlossenen Footprint. */
const emitBoxProduct = (
footprint: Vec2[],
zBottomRel: number,
depth: number,
placementRelTo: number,
): { placementId: number; shapeId: number } => {
const closed = [...footprint, footprint[0]];
const ptIds = closed.map((p) => w.add("IFCCARTESIANPOINT", LIST([R(p.x), R(p.y)])));
const polylineId = w.add("IFCPOLYLINE", LIST(ptIds.map((id) => `#${id}`)));
const profileId = w.add(
"IFCARBITRARYCLOSEDPROFILEDEF",
`${ENUM("AREA")},$,#${polylineId}`,
);
const solidId = w.add(
"IFCEXTRUDEDAREASOLID",
`#${profileId},#${identityAxis},#${extrudeDir},${R(Math.max(depth, 0.001))}`,
);
const shapeRepId = w.add(
"IFCSHAPEREPRESENTATION",
`#${context},${S("Body")},${S("SweptSolid")},${LIST([`#${solidId}`])}`,
);
const shapeId = w.add("IFCPRODUCTDEFINITIONSHAPE", `$,$,${LIST([`#${shapeRepId}`])}`);
const elemOrigin = w.add("IFCCARTESIANPOINT", LIST([R(0), R(0), R(zBottomRel)]));
const elemAxis = w.add("IFCAXIS2PLACEMENT3D", `#${elemOrigin},$,$`);
const placementId = w.add("IFCLOCALPLACEMENT", `#${placementRelTo},#${elemAxis}`);
return { placementId, shapeId };
};
/**
* Baut aus einem Dreiecks-Mesh (`positions` flach x,y,z in IFC-Koordinaten —
* bereits Z-up und relativ zur `placementRelTo`-Herkunft, `indices` je 3 =
* 1-basiert-1 CoordIndex-Tripel) ein IfcTriangulatedFaceSet + Shape + Placement.
* IFC4-Tessellierung: IfcCartesianPointList3D (CoordList) + IfcTriangulatedFace
* Set (CoordIndex, 1-basiert). Das Element-Placement sitzt im Ursprung der
* Trägerstruktur (die Punkte tragen die Geometrie bereits absolut in deren Frame).
*/
const emitTriangulatedProduct = (
positions: number[],
indices: number[],
placementRelTo: number,
closed: boolean,
): { placementId: number; shapeId: number } => {
const coords: string[] = [];
for (let i = 0; i < positions.length; i += 3) {
coords.push(`(${R(positions[i])},${R(positions[i + 1])},${R(positions[i + 2])})`);
}
const pointListId = w.add("IFCCARTESIANPOINTLIST3D", `(${coords.join(",")})`);
const tris: string[] = [];
for (let i = 0; i < indices.length; i += 3) {
tris.push(`(${indices[i] + 1},${indices[i + 1] + 1},${indices[i + 2] + 1})`);
}
// Closed=.T. NUR wenn das Mesh nachweislich ein dichtes, aussen orientiertes
// Volumen ist (siehe isWatertight): Wände sind extrudierte Querschnitts-
// Polygone (Fenster = Durchgangsloch, Tür = umlaufende П-Kerbe) → geschlossene
// Körper → `.T.` (Viewer rendern sie als Solid statt als offene Fläche). Der
// Guard fängt echte Defekte ab (invertierte Wicklung → Volumen < 0 → `$`).
// Normals=$ (Viewer leitet sie aus der — jetzt aussen orientierten — Wicklung ab).
const closedFlag = closed ? ".T." : "$";
const faceSetId = w.add("IFCTRIANGULATEDFACESET", `#${pointListId},$,${closedFlag},(${tris.join(",")}),$`);
const shapeRepId = w.add(
"IFCSHAPEREPRESENTATION",
`#${context},${S("Body")},${S("Tessellation")},${LIST([`#${faceSetId}`])}`,
);
const shapeId = w.add("IFCPRODUCTDEFINITIONSHAPE", `$,$,${LIST([`#${shapeRepId}`])}`);
const elemOrigin = w.add("IFCCARTESIANPOINT", LIST([R(0), R(0), R(0)]));
const elemAxis = w.add("IFCAXIS2PLACEMENT3D", `#${elemOrigin},$,$`);
const placementId = w.add("IFCLOCALPLACEMENT", `#${placementRelTo},#${elemAxis}`);
return { placementId, shapeId };
};
/** Baut ein IfcBuildingElement-Subtyp mit dem üblichen 9-Attribut-Flatten. */
const emitBuildingElement = (
type: string,
guid: string,
name: string,
placementId: number,
shapeId: number,
predefinedType: string | null,
): number =>
w.add(
type,
`${S(guid)},#${ownerHistory},${S(name)},$,$,#${placementId},#${shapeId},$,${predefinedType ?? "$"}`,
);
// ── Bauteiltypen mit Materialschichten ─────────────────────────────────
// Je Wand-/Deckentyp ein IfcWallType/IfcSlabType mit IfcMaterialLayerSet (Schichten in der
// Reihenfolge des Typs, Material = Bauteil). Die Wände/Decken erben ihn über
// IfcRelDefinesByType. Bewusst KEIN IfcMaterialLayerSetUsage am Exemplar: die Wand-Geometrie ist
// ein Mesh ohne Achs-Darstellung, eine Usage (Richtung/Versatz zur Bezugslinie) hätte keinen
// Bezug (s. Dateikopf).
const materialIdByComponent = new Map<string, number>();
const materialOf = (componentId: string): number => {
const hit = materialIdByComponent.get(componentId);
if (hit !== undefined) return hit;
const name = project.components.find((c) => c.id === componentId)?.name ?? componentId;
const id = w.add("IFCMATERIAL", `${S(name)},$,$`);
materialIdByComponent.set(componentId, id);
return id;
};
interface ElementTypeRef {
typeId: number;
occurrences: number[];
}
const elementTypes = new Map<string, ElementTypeRef>();
const typeFor = (
ifcType: "IFCWALLTYPE" | "IFCSLABTYPE" | "IFCROOFTYPE",
predefined: string,
t: { id: string; name: string; layers: { componentId: string; thickness: number }[] },
): ElementTypeRef => {
const key = `${ifcType}:${t.id}`;
const hit = elementTypes.get(key);
if (hit) return hit;
const layerIds = t.layers.map((l) =>
w.add("IFCMATERIALLAYER", `#${materialOf(l.componentId)},${R(Math.max(0, Number.isFinite(l.thickness) ? l.thickness : 0))},$,$,$,$,$`),
);
const typeId = w.add(
ifcType,
`${S(ifcGuid(key))},#${ownerHistory},${S(t.name)},$,$,$,$,$,$,${ENUM(predefined)}`,
);
if (layerIds.length > 0) {
const setId = w.add("IFCMATERIALLAYERSET", `${LIST(layerIds.map((id) => `#${id}`))},${S(t.name)},$`);
w.add(
"IFCRELASSOCIATESMATERIAL",
`${S(ifcGuid(`${key}:material`))},#${ownerHistory},$,$,${LIST([`#${typeId}`])},#${setId}`,
);
}
const ref = { typeId, occurrences: [] };
elementTypes.set(key, ref);
return ref;
};
// ── Wände (öffnungsgenaues Dreiecks-Mesh statt Profil-Extrusion) ────────
// Die Wand-Schicht-Bänder kommen aus DEMSELBEN geflachten Modell wie STL/OBJ
// (`pickGeometry`, Joins/Gehrungen + Öffnungs-`holes` bereits aufgelöst). Alle
// Bänder einer Wand-Id werden zu EINEM Face-Set vereint. IFC-Koordinaten: das
// Mesh liegt in Welt (Modell-x, Höhe, Modell-y) mit Y-up → IFC (x, y, z=Höhe)
// mit Z-up, also (mx, mz, my); Z relativ zur Geschoss-UK, damit die Storey-
// Placement-Elevation nicht doppelt zählt.
//
// WICHTIG — WICKLUNG: der Achsen-Swap (x,y,z)→(x,z,y) ist eine REFLEXION
// (Determinante −1) und KEHRT die Dreiecks-Wicklung UM → aus aussen orientierten
// würden innen orientierte Normalen, der Viewer cullt dann die Vorderseiten und
// die Wand wirkt HOHL/offen (genau der gemeldete Bug). Deshalb wird beim Swap
// die Wicklung jedes Dreiecks umgedreht (i0,i2,i1), damit die Aussen-Normalen
// aussen bleiben. Watertightness (isWatertight) misst das anschliessend am
// fertigen IFC-Mesh → treibt das Closed-Flag des Face-Sets.
const bandsByWallId = new Map<string, RWall[]>();
const allBands = pickGeometry(project).walls;
// Loch-Ausschnitte aller Bänder in EINEM Kern-Aufruf.
const cutOf = new Map<RWall, CutMesh>();
wallCutMeshes(allBands).forEach((m, i) => cutOf.set(allBands[i], m));
for (const band of allBands) {
const list = bandsByWallId.get(band.wallId);
if (list) list.push(band);
else bandsByWallId.set(band.wallId, [band]);
}
const wallEntityIdByWallId = new Map<string, number>();
for (const wall of project.walls ?? []) {
const bands = bandsByWallId.get(wall.id);
if (!bands || bands.length === 0) continue; // degenerierte Wand / keine Geometrie
const structure = resolveStructure(wall.floorId);
const positions: number[] = [];
const indices: number[] = [];
for (const band of bands) {
const cut = cutOf.get(band);
if (!cut) continue;
const base = positions.length / 3;
for (let i = 0; i < cut.positions.length; i += 3) {
positions.push(
cut.positions[i],
cut.positions[i + 2],
cut.positions[i + 1] - structure.baseElevation,
);
}
// Wicklung umkehren (Reflexions-Ausgleich, s. o.): (a,b,c) → (a,c,b).
for (let i = 0; i < cut.indices.length; i += 3) {
indices.push(base + cut.indices[i], base + cut.indices[i + 2], base + cut.indices[i + 1]);
}
}
if (indices.length === 0) continue;
const closed = isWatertight({ positions, indices });
const { placementId, shapeId } = emitTriangulatedProduct(positions, indices, structure.placementId, closed);
let name = wall.id;
let wallType: ElementTypeRef | null = null;
try {
const wt = getWallType(project, wall);
name = wt.name;
wallType = typeFor("IFCWALLTYPE", "STANDARD", wt);
} catch {
/* verwaister Wandtyp — Roh-ID als Name, kein Typ */
}
const entityId = emitBuildingElement("IFCWALL", ifcGuid(wall.id), name, placementId, shapeId, null);
wallType?.occurrences.push(entityId);
wallEntityIdByWallId.set(wall.id, entityId);
addToContainment(structure.entityId, entityId);
}
// ── Decken ─────────────────────────────────────────────────────────────
for (const ceiling of project.ceilings ?? []) {
if (ceiling.outline.length < 3) continue;
const { zBottom, zTop } = ceilingVerticalExtent(project, ceiling);
const structure = resolveStructure(ceiling.floorId);
const { placementId, shapeId } = emitBoxProduct(
ceiling.outline,
zBottom - structure.baseElevation,
zTop - zBottom,
structure.placementId,
);
let name: string = ceiling.id;
let slabType: ElementTypeRef | null = null;
try {
const ct = getCeilingType(project, ceiling);
name = ct.name;
slabType = typeFor("IFCSLABTYPE", "FLOOR", ct);
} catch {
/* verwaister Deckentyp — Roh-ID als Name, kein Typ */
}
const entityId = emitBuildingElement(
"IFCSLAB",
ifcGuid(ceiling.id),
name,
placementId,
shapeId,
ENUM("FLOOR"),
);
slabType?.occurrences.push(entityId);
addToContainment(structure.entityId, entityId);
}
// ── Fenster/Türen als eigene Objekte (IfcDoor/IfcWindow) ────────────────
// KEIN IfcOpeningElement/IfcRelVoidsElement/IfcRelFillsElement mehr: das Loch
// steckt bereits im Wand-Face-Set (s. o.). Eine Void-Relation beschriebe eine
// Boolean-Subtraktion gegen einen Swept-Solid, den es nicht mehr gibt — sie
// brächte in den Viewern nur Verwirrung (der Nutzer-Bug war genau, dass die
// Void nicht subtrahiert wurde). Tür/Fenster bleiben als EIGENES Objekt mit
// eigener Box-Geometrie erhalten, die das ausgeschnittene Loch füllt ("sieht
// aus wie 3D"): kein Blatt-/Rahmendetail (bewusste Vereinfachung).
for (const opening of project.openings ?? []) {
const wall = (project.walls ?? []).find((wl) => wl.id === opening.hostWallId);
if (!wall) continue; // verwaiste Wirtswand — keine Geometrie ableitbar
if (!wallEntityIdByWallId.has(wall.id)) continue; // Wirtswand übersprungen (degeneriert)
const wallExtent = wallVerticalExtent(project, wall);
const structure = resolveStructure(wall.floorId);
const footprint = openingFootprint(project, wall, opening);
const zSillAbs = wallExtent.zBottom + opening.sillHeight;
const { placementId: fillPlacement, shapeId: fillShape } = emitBoxProduct(
footprint,
zSillAbs - structure.baseElevation,
opening.height,
structure.placementId,
);
const fillGuid = ifcGuid(`${opening.id}:fill`);
const fillName = openingLabel(opening);
const fillEntityId =
opening.kind === "door"
? w.add(
"IFCDOOR",
`${S(fillGuid)},#${ownerHistory},${S(fillName)},$,$,#${fillPlacement},#${fillShape},$,${R(opening.height)},${R(opening.width)},${ENUM("DOOR")},$,$`,
)
: w.add(
"IFCWINDOW",
`${S(fillGuid)},#${ownerHistory},${S(fillName)},$,$,#${fillPlacement},#${fillShape},$,${R(opening.height)},${R(opening.width)},${ENUM("WINDOW")},$,$`,
);
addToContainment(structure.entityId, fillEntityId);
}
// ── Treppen (vereinfachter Bounding-Footprint, siehe Dateikopf) ────────
for (const stair of project.stairs ?? []) {
const footprint = stairFootprint(stair);
if (footprint.length < 3) continue;
const { zBottom, zTop } = stairVerticalExtent(project, stair);
const structure = resolveStructure(stair.floorId);
const { placementId, shapeId } = emitBoxProduct(
footprint,
zBottom - structure.baseElevation,
zTop - zBottom,
structure.placementId,
);
const predefinedType =
stair.shape === "straight"
? ENUM("STRAIGHT_RUN_STAIR")
: stair.shape === "spiral"
? ENUM("SPIRAL_STAIR")
: ENUM("QUARTER_TURN_STAIR");
const entityId = emitBuildingElement(
"IFCSTAIR",
ifcGuid(stair.id),
"Treppe",
placementId,
shapeId,
predefinedType,
);
addToContainment(structure.entityId, entityId);
}
// ── Extrudierte Körper (truck-Integration) → IfcBuildingElementProxy ───
for (const solid of project.extrudedSolids ?? []) {
if (solid.points.length < 3) continue;
const floor = floors.find((f) => f.id === solid.levelId);
const base = floor?.baseElevation ?? 0;
const structure = resolveStructure(solid.levelId);
const { placementId, shapeId } = emitBoxProduct(
solid.points,
base - structure.baseElevation,
solid.height,
structure.placementId,
);
const entityId = emitBuildingElement(
"IFCBUILDINGELEMENTPROXY",
ifcGuid(solid.id),
"Extrusion",
placementId,
shapeId,
null,
);
addToContainment(structure.entityId, entityId);
}
// ── Räume → IfcSpace ───────────────────────────────────────────────────
// Je Raum ein IfcSpace (Name = Raumnummer, LongName = Raumname), als Extrusion der lichten
// Innenkontur über die lichte Geschosshöhe. Räume sind räumliche Elemente: sie werden im
// Geschoss AGGREGIERT (IfcRelAggregates), nicht enthalten. Dazu Basismengen
// (Qto_SpaceBaseQuantities) und die SIA-416-Kategorie als Eigenschaft.
const spacesByStructure = new Map<number, number[]>();
for (const room of project.rooms ?? []) {
if (room.boundary.length < 3) continue;
const structure = resolveStructure(room.floorId);
const floor = floors.find((f) => f.id === room.floorId);
const height = floor?.floorHeight && floor.floorHeight > 0 ? floor.floorHeight : 2.5;
const { placementId, shapeId } = emitBoxProduct(room.boundary, 0, height, structure.placementId);
const spaceId = w.add(
"IFCSPACE",
`${S(ifcGuid(room.id))},#${ownerHistory},${S(room.stamp?.number || room.id)},$,$,#${placementId},#${shapeId},${S(room.name)},${ENUM("ELEMENT")},${ENUM("INTERNAL")},$`,
);
const list = spacesByStructure.get(structure.entityId);
if (list) list.push(spaceId);
else spacesByStructure.set(structure.entityId, [spaceId]);
const area = evaluateRoom(room.boundary, room.siaCategory);
const qNet = w.add("IFCQUANTITYAREA", `${S("NetFloorArea")},$,$,${R(area.netArea)},$`);
const qGross = w.add("IFCQUANTITYAREA", `${S("GrossFloorArea")},$,$,${R(area.grossArea)},$`);
const qHeight = w.add("IFCQUANTITYLENGTH", `${S("Height")},$,$,${R(height)},$`);
const qto = w.add(
"IFCELEMENTQUANTITY",
`${S(ifcGuid(`${room.id}:qto`))},#${ownerHistory},${S("Qto_SpaceBaseQuantities")},$,$,${LIST([`#${qNet}`, `#${qGross}`, `#${qHeight}`])}`,
);
w.add(
"IFCRELDEFINESBYPROPERTIES",
`${S(ifcGuid(`${room.id}:rel-qto`))},#${ownerHistory},$,$,${LIST([`#${spaceId}`])},#${qto}`,
);
const sia = w.add("IFCPROPERTYSINGLEVALUE", `${S("SIA416")},$,IFCLABEL(${S(room.siaCategory)}),$`);
const pset = w.add(
"IFCPROPERTYSET",
`${S(ifcGuid(`${room.id}:pset`))},#${ownerHistory},${S("CH_Raum")},$,${LIST([`#${sia}`])}`,
);
w.add(
"IFCRELDEFINESBYPROPERTIES",
`${S(ifcGuid(`${room.id}:rel-pset`))},#${ownerHistory},$,$,${LIST([`#${spaceId}`])},#${pset}`,
);
}
for (const [structureId, spaceIds] of spacesByStructure) {
w.add(
"IFCRELAGGREGATES",
`${S(ifcGuid(`spaces:${structureId}`))},#${ownerHistory},$,$,#${structureId},${LIST(spaceIds.map((id) => `#${id}`))}`,
);
}
// ── Dächer → IfcRoof ───────────────────────────────────────────────────
// Dieselben geschlossenen Schicht-Meshes wie das 3D (`roofMeshes`: Dachflächen je Schicht,
// an First/Grat gehrt), zu EINEM Face-Set je Dach vereint. Modell-Koordinaten sind bereits
// Z-oben (kein Achsentausch wie bei den Wänden); die Wicklung wird so gewählt, dass das Volumen
// positiv ist — nur dann ist das Face-Set als geschlossen markiert.
const ROOF_PREDEFINED: Record<string, string> = {
flach: "FLAT_ROOF",
pult: "SHED_ROOF",
sattel: "GABLE_ROOF",
walm: "HIP_ROOF",
mansarde: "MANSARD_ROOF",
zelt: "HIPPED_GABLE_ROOF",
};
for (const roof of project.roofs ?? []) {
const structure = resolveStructure(roof.floorId);
const positions: number[] = [];
const indices: number[] = [];
for (const mesh of roofMeshes(project, roof.id)) {
const base = positions.length / 3;
for (let i = 0; i < mesh.positions.length; i += 3) {
positions.push(mesh.positions[i], mesh.positions[i + 1], mesh.positions[i + 2] - structure.baseElevation);
}
for (const ix of mesh.indices) indices.push(base + ix);
}
if (indices.length === 0) continue;
let closed = isWatertight({ positions, indices });
if (!closed) {
const flipped: number[] = [];
for (let i = 0; i < indices.length; i += 3) flipped.push(indices[i], indices[i + 2], indices[i + 1]);
if (isWatertight({ positions, indices: flipped })) {
indices.splice(0, indices.length, ...flipped);
closed = true;
}
}
const { placementId, shapeId } = emitTriangulatedProduct(positions, indices, structure.placementId, closed);
const predefined = ROOF_PREDEFINED[roof.shape] ?? "NOTDEFINED";
const roofType = roof.roofTypeId ? (project.roofTypes ?? []).find((t) => t.id === roof.roofTypeId) : undefined;
const entityId = emitBuildingElement("IFCROOF", ifcGuid(roof.id), roofType?.name ?? "Dach", placementId, shapeId, ENUM(predefined));
if (roofType) typeFor("IFCROOFTYPE", predefined, roofType).occurrences.push(entityId);
addToContainment(structure.entityId, entityId);
}
// ── Stützen → IfcColumn (Profil-Extrusion, Material = Bauteil) ──────────
const materialAssoc = new Map<number, number[]>();
for (const col of project.columns ?? []) {
const footprint = columnFootprint(col);
if (footprint.length < 3) continue;
const { zBottom, zTop } = columnVerticalExtent(project, col);
if (!(zTop > zBottom)) continue;
const structure = resolveStructure(col.floorId);
const { placementId, shapeId } = emitBoxProduct(footprint, zBottom - structure.baseElevation, zTop - zBottom, structure.placementId);
const entityId = emitBuildingElement("IFCCOLUMN", ifcGuid(col.id), columnLabel(col), placementId, shapeId, ENUM("COLUMN"));
addToContainment(structure.entityId, entityId);
if (col.componentId) {
const mat = materialOf(col.componentId);
const list = materialAssoc.get(mat);
if (list) list.push(entityId);
else materialAssoc.set(mat, [entityId]);
}
}
for (const [mat, ids] of materialAssoc) {
w.add(
"IFCRELASSOCIATESMATERIAL",
`${S(ifcGuid(`material:${mat}`))},#${ownerHistory},$,$,${LIST(ids.map((id) => `#${id}`))},#${mat}`,
);
}
// ── Typ-Zuordnung (je Bauteiltyp eine IfcRelDefinesByType) ─────────────
for (const [key, ref] of elementTypes) {
if (ref.occurrences.length === 0) continue;
w.add(
"IFCRELDEFINESBYTYPE",
`${S(ifcGuid(`${key}:occurrences`))},#${ownerHistory},$,$,${LIST(ref.occurrences.map((id) => `#${id}`))},#${ref.typeId}`,
);
}
// ── Räumliche Eingliederung (gebündelt je Trägerstruktur) ──────────────
for (const [structureId, elementIds] of containment) {
w.add(
"IFCRELCONTAINEDINSPATIALSTRUCTURE",
`${S(ifcGuid(`contain:${structureId}`))},#${ownerHistory},$,$,${LIST(elementIds.map((id) => `#${id}`))},#${structureId}`,
);
}
// ── Kopf + Zusammenbau ───────────────────────────────────────────────────
const iso = new Date().toISOString().replace(/\.\d+Z$/, "");
const fileName = `${project.name || "modell"}.ifc`;
const header = [
"ISO-10303-21;",
"HEADER;",
`FILE_DESCRIPTION(${LIST([S("")])},${S("2;1")});`,
`FILE_NAME(${S(fileName)},${S(iso)},${LIST([S("dossier")])},${LIST([S("dossier")])},${S("dossier")},${S("dossier")},${S("")});`,
"FILE_SCHEMA(('IFC4'));",
"ENDSEC;",
"",
"DATA;",
];
const footer = ["ENDSEC;", "END-ISO-10303-21;"];
return [...header, ...w.entityLines, ...footer].join("\n") + "\n";
export function exportIfcSpf(project: Project): string {
return documentFor(project).exportIfc(Date.now());
}