Merge [C11][B5] Mesh-Export vollstaendig (Daecher, Treppen, Stuetzen, Kontext, Oeffnungen je Knoten, Achsen rechtshaendig); IFC-Basismengen, Treppenlaeufe/Podeste/Gelaender, Deckenaussparungen

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-28 15:04:39 +00:00
commit 96720c29c3
16 files changed
+1878 -145

No files matched your search

+1 -1
View File
@@ -176,7 +176,7 @@ Liste beschreibt den Ist-Zustand des Codes, nicht eine Zusage._
| DXF | Linien, Bögen, Füllungen und Verläufe |
| IFC4 | Geschossstruktur, Bauteile mit Schichten, Öffnungen als echte Löcher |
| STEP | B-Rep-Körper je Wandschicht, Decke, Dach, Treppe und Extrusion (in mm) |
| STL, OBJ | Dreiecksnetz des 3D-Modells, Öffnungen ausgeschnitten |
| STL, OBJ, glTF/GLB | Dreiecksnetz des 3D-Modells (Wände mit Öffnungen, Decken, Dächer, Treppen, Stützen, Fenster/Türen, Gelände und Kontext), rechtshändig Y-up |
| CSV | Bauteilliste und SIA-416-Raumbilanz |
### Desktop-Integration
+34 -5
View File
@@ -445,6 +445,26 @@ Ganzes nicht WASM-tauglich (rayon, tempfile, SystemTime) — nur einzelne Module
ist jetzt ein Fehler statt „NaN“ in der Datei. Rundung wie `toFixed(6)` (Gleichstand auf).
Offen: Laden von pkgFileIo ist beim ersten IFC-Export neu (bisher synchron ohne Wartezeit);
Export im Worker; nur Linux-Container/vitest, nicht in der Tauri-App geprüft. · L
- ✅ Basismengen für Kostenplanung/Mengenermittlung. (28.10.) `Qto_WallBaseQuantities` (Length, Width, Height,
GrossSideArea, NetSideArea, GrossVolume, NetVolume), `Qto_SlabBaseQuantities` (Decke und Podest: Width, Perimeter,
Gross-/NetArea, Gross-/NetVolume), `Qto_RoofBaseQuantities` (GrossArea, NetArea, ProjectedArea),
`Qto_ColumnBaseQuantities`, `Qto_DoorBaseQuantities`/`Qto_WindowBaseQuantities` (Width, Height, Perimeter, Area),
`Qto_StairFlightBaseQuantities`, `Qto_RailingBaseQuantities`; als IfcElementQuantity je Bauteil (nie geteilt), GUID
dauerhaft. Werte aus der Geometrie der Datei (`export/ifcQuantities.ts`, reine Rechnung), Netto = abzüglich
Öffnungen (Wand: je Schicht-Band, Netz-Wände: Volumen des Netzes). Height nur bei konstanter Oberkante (IFC-Vorgabe).
Mit ifcopenshell nachgerechnet (`exportIfc.quantities.test.ts`, ± 1 %): Wand-Netto und -Brutto (Demo-Haus: exakt),
Decke/Podest/Stütze/Läufe = Volumen, Dach = nach oben zeigende Netz-Dreiecke (geneigt und projiziert),
Tür/Fenster = Öffnungskörper; `validate-ifc.py` 0 Befunde. Rechnung bewusst in TS (Modell bleibt bis [K4] TS), die
Entitäten schreibt Rust (Pset-Arten 3–5, `FLAT_VERSION` 3).
- ✅ Deckenaussparungen als echte Löcher (IfcArbitraryProfileDefWithVoids statt Volldecke), wie im 3D. (28.10.)
- ✅ Treppen mit Läufen. (28.10.) IfcStair ohne Darstellung, per IfcRelAggregates mit IfcStairFlight (Prismen der
Tritte oder glatte Ortbeton-Laufplatte als Netz; NumberOfRisers/Treads, RiserHeight, TreadLength), IfcSlab(LANDING)
(Podest bei „L“) und IfcRailing(HANDRAIL) (Handlauf + Pfosten, wo das 3D sie zeigt: gerade Läufe). Quelle: dieselben
`emitStairs`/`emitStairMeshes`/`emitStairRailings` wie das 3D, je Treppe mit Ein-Treppen-Projekt (`export/ifcStairs.ts`).
Der eigene IFC-Import sieht jetzt `IfcStairFlight` statt `IfcStair` als Bauteil (Tests angepasst). Offen: Lauflänge
ist eine Näherung (Weg zwischen den Tritt-Schwerpunkten + Auftritt, mit Steigung), Wendeltreppe ein Lauf inkl.
Mitte, Geländer von L-/Wendeltreppen fehlt wie im 3D, Geländer-Länge = Lauflänge × Seiten; Pfosten nicht
als IfcMember; nicht in Revit/ArchiCAD geöffnet.
- Geprüft nur im Linux-Container (vitest + ifcopenshell 0.9: 0 Befunde, Volumen), nicht in
Solibri/BIMcollab und nicht in der Tauri-App.
- ◐ **[BCF] BCF 2.1/3.0 (BIM Collaboration Format).** (28.10.) Koordinations-Themen mit Solibri, BIMcollab,
@@ -630,11 +650,20 @@ Code-Übernahme Lizenz der Abhängigkeiten prüfen, Pflicht [51].
**Y-up rechtshändig: Modell (x, y, z-hoch) → (x, z, −y)**, Norden = −Z. TS (`src/export/exportMesh.ts`) sammelt nur
flach. Export-Dialog „glTF 2.0 (GLB)“, Tauri-Menü, CLI `glb`/`gltf`. Prüfung: Khronos-Validator
(`gltf-validator`, devDependency, Apache-2.0) ohne Fehler, Rundreise Knoten-/Dreieckszahl gegen OBJ,
8 Rust-Tests. **Offen:** Dächer, Treppen, Stützen, Kontext-Meshes/Gelände fehlen auch in OBJ/STL (nur Wände,
Decken, Extrusionen, im glTF zusätzlich Öffnungsteile); Fenster-Verglasung und Rahmen sind je ein Sammelknoten
ohne Öffnungs-id; keine Normalen (Flat-Shading), keine Texturen, keine Instanzen; OBJ/STL bleiben beim
älteren gespiegelten Achsen-Bezug (x, Höhe, +y); nicht in Blender/Twinmotion/Enscape geöffnet, nur Validator;
nicht in der Tauri-App getestet. · S
8 Rust-Tests. **Nachgeführt 28.10. (zweiter Schritt):** Dächer (`Dach_<id>`), Treppen (`Treppe_<id>`: Tritt-Prismen,
Ortbeton-Laufplatte, Handlauf), Stützen (`Stuetze_<id>`), Gelände (`Gelaende_<id>`) und importierte IFC/DXF-Meshes
(`Kontext_<id>`, mit `color`, falls gesetzt) in OBJ, STL und glTF; Verglasung/Rahmen je Öffnung ein Knoten
(`Fenster_<id>`/`Tuer_<id>`, `extras` = Öffnungs-id; die Sammelknoten `glazing`/`frame` gibt es nicht mehr, Öffnungsteile
jetzt auch in OBJ/STL). Quelle sind dieselben `emit*`-Ableitungen wie im 3D (`projectToModel3d`), je Bauteil mit einem
Ein-Bauteil-Projekt aufgerufen (die Ableitungen liefern keine ids; `src/plan` unverändert). Wicklung: `orientOutward`
(verschweisste Kanten, Komponenten, Volumenvorzeichen), da render3d doppelseitig zeichnet. **Achsen OBJ/STL geändert:**
rechtshändig wie glTF, Modell (x, y, z-hoch) → (x, z, −y), Norden = −Z (vorher gespiegelt (x, z, +y)); niemand ausser dem
eigenen Test hat die alte Abbildung erwartet. Optionen `openingParts`/`context` (Standard an). Prüfung: Validator 0 Fehler,
Volumen aller Teile > 0, Dreieckszahl je Art = Summe der Ableitungen, Rundreise OBJ = glTF. **Offen:** keine Normalen
(Flat-Shading), keine Texturen/Instanzen, Gelände ohne Vertex-Farben (Luftbild), Abzugskörper-Booleans (`voids`) und
truck-Extrusionen (nur Prisma-Näherung) nicht wie im 3D; Dreieckszahl nicht gegen die GPU-Puffer von render3d gemessen
(Wand-Löcher und Decken aus denselben Ableitungen, Dächer/Stützen/Treppen/Öffnungen identisch); nicht in
Blender/Twinmotion/Enscape geöffnet, nur Validator; nicht in der Tauri-App getestet. · S
## Bewusst nicht übernommen
+438 -22
View File
@@ -17,7 +17,10 @@
// n_layers, (component_id, component_name, thickness) × n_layers
// PSETS = n, (name, n_props, (prop_name, kind, value) × n_props) × n
// kind 0 = IfcIdentifier (value = Zeichenketten-Index), 1 = IfcBoolean (0/1),
// 2 = IfcPositiveRatioMeasure (value = Zahl)
// 2 = IfcPositiveRatioMeasure (value = Zahl),
// 3 = IfcQuantityLength, 4 = IfcQuantityArea, 5 = IfcQuantityVolume (value = Zahl, ≥ 0).
// Heisst der Satz `Qto_…`, entsteht je Bauteil ein eigener IfcElementQuantity (Basismengen,
// nie geteilt); sonst ein IfcPropertySet (gleicher Inhalt = ein Pset für alle Bauteile).
// structure= Geschoss-Index oder −1 (Gebäude)
//
// WALL_SOLIDS = 1, structure, id, name, TYPEREF, PSETS, FRAME, n_solids, (PTS, z_rel, depth) × n_solids
@@ -28,7 +31,8 @@
// und, bei usage = 1 und vorhandenem Typ, IfcMaterialLayerSetUsage (AXIS2, POSITIVE, `offset` =
// Abstand der ersten Schicht von der Achse entlang +Y). Ohne Rahmen: Placement ohne Drehung wie bisher.
// WALL_MESH = 2, structure, id, name, TYPEREF, PSETS, MESH
// CEILING = 3, structure, id, name, TYPEREF, PSETS, PTS, z_rel, depth
// CEILING = 3, structure, id, name, TYPEREF, PSETS, PTS, n_inner, PTS × n_inner, z_rel, depth
// (innere Ringe = Deckenaussparungen, IfcArbitraryProfileDefWithVoids)
// OPENING = 4, wall_id, structure, opening_id, is_door (0/1), fill_name, PTS (Öffnungskörper), z_rel,
// depth, width, FILL, PSETS
// FILL (Parameter aus dem Modell; Körper, Placement und OperationType/PartitioningType rechnet
@@ -42,7 +46,14 @@
// Normale von u; Tür: Y = Aufschlagrichtung); ohne Teile (Wandöffnung) kein Körper. Alle Teile
// (0 Rahmen/Zarge, 1 Türblatt, 2 Glas) sind getrennte Körper in EINER Darstellung, je mit eigenem
// IfcStyledItem (Farbe/Transparenz je Rolle).
// STAIR = 5, structure, id, predefined (Text), PTS, z_rel, depth
// STAIR = 5, structure, id, predefined (Text), PTS, z_rel, depth (Ersatzkörper, nur ohne Läufe/Podest),
// PSETS, n_flights, FLIGHT × n_flights, has_landing, [LANDING], has_rail, [RAIL]
// FLIGHT = name, n_risers, n_treads, riser_height, tread_length, predefined (Text, IfcStairFlightTypeEnum),
// PSETS, shape (0 = Extrusionen, 1 = Dreiecks-Mesh), 0: n, (PTS, z_rel, depth) × n | 1: MESH
// LANDING = name, PTS, z_rel, depth, PSETS (IfcSlab, PredefinedType LANDING)
// RAIL = name, predefined (Text, IfcRailingTypeEnum), PSETS, MESH
// Mit mindestens einem Lauf/Podest/Geländer ist die IfcStair selbst ohne Darstellung und fasst Läufe,
// Podest und Geländer per IfcRelAggregates zusammen (nur die Treppe liegt im Geschoss).
// EXTRUSION = 6, structure, id, PTS, z_rel, depth
// SPACE = 7, structure, id, name, long_name, external (0/1), height, PTS, net_area, gross_area,
// sia_category, PSETS
@@ -64,8 +75,8 @@ use std::collections::HashMap;
use crate::ifc_openings::{fill_geometry, DoorKind, FillParams, FillPart, Sash, MAX_SASHES};
/// Version der flachen Kodierung (erstes Element des Puffers).
pub const FLAT_VERSION: f64 = 2.0;
/// Version der flachen Kodierung (erstes Element des Puffers). 3 seit 28.10.: Basismengen (Pset-Arten 3–5), Deckenaussparungen, Treppen mit Läufen.
pub const FLAT_VERSION: f64 = 3.0;
pub const REC_WALL_SOLIDS: f64 = 1.0;
pub const REC_WALL_MESH: f64 = 2.0;
@@ -475,6 +486,46 @@ impl<'a> Reader<'a> {
let closed = self.flag()?;
Ok(Mesh { positions, indices, closed })
}
/// Treppenlauf (s. Kopf, STAIR).
fn stair_flight(&mut self) -> Result<StairFlight, String> {
let name = self.string()?;
let risers = self.idx()?;
let treads = self.idx()?;
let riser_height = self.f()?;
let tread_length = self.f()?;
let predefined = self.string()?;
let psets = self.psets()?;
let shape = match self.idx()? {
0 => {
let n = self.idx()?;
let mut solids = Vec::new();
for _ in 0..n {
let pts = self.pts()?;
solids.push((pts, self.f()?, self.f()?));
}
FlightShape::Solids(solids)
}
1 => FlightShape::Mesh(self.mesh()?),
k => return Err(format!("unbekannte Lauf-Form {k}")),
};
Ok(StairFlight { name, risers, treads, riser_height, tread_length, predefined, psets, shape })
}
/// Podest (s. Kopf, STAIR).
fn stair_landing(&mut self) -> Result<StairLanding, String> {
let name = self.string()?;
let pts = self.pts()?;
let (z_rel, depth) = (self.f()?, self.f()?);
let psets = self.psets()?;
Ok(StairLanding { name, pts, z_rel, depth, psets })
}
/// Geländer (s. Kopf, STAIR).
fn stair_rail(&mut self) -> Result<StairRail, String> {
let name = self.string()?;
let predefined = self.string()?;
let psets = self.psets()?;
let mesh = self.mesh()?;
Ok(StairRail { name, predefined, psets, mesh })
}
fn type_ref(&mut self) -> Result<Option<TypeRef>, String> {
if !self.flag()? {
return Ok(None);
@@ -511,6 +562,9 @@ impl<'a> Reader<'a> {
0 => PropVal::Ident(self.string()?),
1 => PropVal::Bool(self.flag()?),
2 => PropVal::Ratio(self.f()?),
3 => PropVal::Length(self.f()?),
4 => PropVal::Area(self.f()?),
5 => PropVal::Volume(self.f()?),
k => return Err(format!("unbekannte Eigenschaftsart {k}")),
};
props.push((pname, value));
@@ -571,6 +625,38 @@ struct Mesh {
closed: bool,
}
enum FlightShape {
/// Prismen (Profil in Welt-XY, Unterkante relativ zum Geschoss, Tiefe).
Solids(Vec<(Vec<(f64, f64)>, f64, f64)>),
Mesh(Mesh),
}
struct StairFlight {
name: String,
risers: usize,
treads: usize,
riser_height: f64,
tread_length: f64,
predefined: String,
psets: Vec<Pset>,
shape: FlightShape,
}
struct StairLanding {
name: String,
pts: Vec<(f64, f64)>,
z_rel: f64,
depth: f64,
psets: Vec<Pset>,
}
struct StairRail {
name: String,
predefined: String,
psets: Vec<Pset>,
mesh: Mesh,
}
#[derive(Clone, Copy, PartialEq)]
enum TypeKind {
Wall,
@@ -606,6 +692,10 @@ enum PropVal {
Ident(String),
Bool(bool),
Ratio(f64),
/// Basismengen (`Qto_…`): Länge, Fläche, Volumen.
Length(f64),
Area(f64),
Volume(f64),
}
impl PropVal {
@@ -615,6 +705,17 @@ impl PropVal {
PropVal::Ident(s) => format!("IFCIDENTIFIER({})", ifc_string(s)),
PropVal::Bool(b) => format!("IFCBOOLEAN({})", if *b { ".T." } else { ".F." }),
PropVal::Ratio(r) => format!("IFCPOSITIVERATIOMEASURE({})", fmt_real(*r)),
PropVal::Length(_) | PropVal::Area(_) | PropVal::Volume(_) => String::new(),
}
}
/// Mengen-Entität und Wert (nur Basismengen), sonst `None`.
fn quantity(&self) -> Option<(&'static str, f64)> {
match self {
PropVal::Length(v) => Some(("IFCQUANTITYLENGTH", *v)),
PropVal::Area(v) => Some(("IFCQUANTITYAREA", *v)),
PropVal::Volume(v) => Some(("IFCQUANTITYVOLUME", *v)),
_ => None,
}
}
}
@@ -639,6 +740,15 @@ struct PsetAcc {
related: Vec<usize>,
}
/// Basismengen eines Bauteils (`Qto_…`), am Ende als IfcElementQuantity geschrieben.
struct QtoAcc {
/// Schlüssel des Bauteils (wie für seine GlobalId) — Grundlage der dauerhaften GUIDs.
owner_key: String,
name: String,
quantities: Vec<(&'static str, String, f64)>,
element: usize,
}
struct TypeAcc {
key: String,
type_id: usize,
@@ -662,6 +772,7 @@ struct Builder {
containment: Vec<(i64, Vec<usize>)>,
psets: Vec<PsetAcc>,
pset_index: HashMap<String, usize>,
qtos: Vec<QtoAcc>,
materials: HashMap<String, usize>,
types: Vec<TypeAcc>,
type_index: HashMap<String, usize>,
@@ -722,10 +833,24 @@ impl Builder {
}
/// Eigenschaftssatz vormerken: gleicher Inhalt ⇒ EIN Pset für alle Bauteile (GUID aus dem Inhalt).
fn add_pset(&mut self, pset: &Pset, element: usize) {
///
/// Basismengen (`Qto_…`) sind dagegen je Bauteil eigen: `owner_key` (Schlüssel des Bauteils, wie für
/// seine GlobalId) bestimmt die GUIDs von Menge und Beziehung.
fn add_pset(&mut self, pset: &Pset, element: usize, owner_key: &str) {
if pset.props.is_empty() {
return; // IfcPropertySet verlangt mindestens eine Eigenschaft
}
if pset.name.starts_with("Qto_") {
let quantities: Vec<(&'static str, String, f64)> = pset
.props
.iter()
.filter_map(|(n, v)| v.quantity().map(|(ty, x)| (ty, n.clone(), x)))
.collect();
if !quantities.is_empty() {
self.qtos.push(QtoAcc { owner_key: owner_key.to_string(), name: pset.name.clone(), quantities, element });
}
return;
}
let props: Vec<(String, String)> = pset.props.iter().map(|(n, v)| (n.clone(), v.expr())).collect();
// Schlüssel wie in der TS-Fassung: `<Name>/<JSON der [Name, Wert]-Paare>`.
let json: Vec<String> = props
@@ -741,15 +866,30 @@ impl Builder {
}
}
/// Profil (geschlossenes Polygon) als IfcExtrudedAreaSolid, Unterkante `z_rel` in `+Z`.
fn emit_extrusion(&mut self, footprint: &[(f64, f64)], z_rel: f64, depth: f64) -> usize {
let mut pt_ids = Vec::with_capacity(footprint.len() + 1);
for p in footprint.iter().chain(footprint.first()) {
/// Geschlossener Linienzug (erster Punkt am Ende wiederholt) als IfcPolyline.
fn emit_closed_polyline(&mut self, ring: &[(f64, f64)]) -> usize {
let mut pt_ids = Vec::with_capacity(ring.len() + 1);
for p in ring.iter().chain(ring.first()) {
let id = self.add("IFCCARTESIANPOINT", list(&[fmt_real(p.0), fmt_real(p.1)]));
pt_ids.push(id);
}
let polyline = self.add("IFCPOLYLINE", refs(&pt_ids));
let profile = self.add("IFCARBITRARYCLOSEDPROFILEDEF", format!("{},$,#{polyline}", enum_("AREA")));
self.add("IFCPOLYLINE", refs(&pt_ids))
}
/// Profil (geschlossenes Polygon) als IfcExtrudedAreaSolid, Unterkante `z_rel` in `+Z`.
fn emit_extrusion(&mut self, footprint: &[(f64, f64)], z_rel: f64, depth: f64) -> usize {
self.emit_extrusion_voids(footprint, &[], z_rel, depth)
}
/// Wie {@link emit_extrusion}, mit inneren Ringen (Aussparungen) als IfcArbitraryProfileDefWithVoids.
fn emit_extrusion_voids(&mut self, footprint: &[(f64, f64)], inner: &[Vec<(f64, f64)>], z_rel: f64, depth: f64) -> usize {
let polyline = self.emit_closed_polyline(footprint);
let profile = if inner.is_empty() {
self.add("IFCARBITRARYCLOSEDPROFILEDEF", format!("{},$,#{polyline}", enum_("AREA")))
} else {
let holes: Vec<usize> = inner.iter().map(|ring| self.emit_closed_polyline(ring)).collect();
self.add("IFCARBITRARYPROFILEDEFWITHVOIDS", format!("{},$,#{polyline},{}", enum_("AREA"), refs(&holes)))
};
let mut position = self.identity_axis;
if z_rel != 0.0 {
let pt = self.add("IFCCARTESIANPOINT", list(&[fmt_real(0.0), fmt_real(0.0), fmt_real(z_rel)]));
@@ -846,7 +986,12 @@ impl Builder {
/// Profil+Extrusion+Shape+Placement für einen geschlossenen Footprint; liefert (Placement, Shape).
fn emit_box_product(&mut self, footprint: &[(f64, f64)], z_bottom_rel: f64, depth: f64, relative_to: usize) -> (usize, usize) {
let solid = self.emit_extrusion(footprint, 0.0, depth);
self.emit_box_product_voids(footprint, &[], z_bottom_rel, depth, relative_to)
}
/// Wie {@link emit_box_product}, mit Aussparungen im Profil.
fn emit_box_product_voids(&mut self, footprint: &[(f64, f64)], inner: &[Vec<(f64, f64)>], z_bottom_rel: f64, depth: f64, relative_to: usize) -> (usize, usize) {
let solid = self.emit_extrusion_voids(footprint, inner, 0.0, depth);
let shape = self.emit_swept_shape(&[solid]);
let placement = self.emit_placement(z_bottom_rel, relative_to);
(placement, shape)
@@ -968,7 +1113,7 @@ impl Builder {
}
self.add_to_containment(structure, entity);
for p in psets {
self.add_pset(p, entity);
self.add_pset(p, entity, &guid_key);
}
entity
}
@@ -1025,6 +1170,7 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result<String, String> {
containment: Vec::new(),
psets: Vec::new(),
pset_index: HashMap::new(),
qtos: Vec::new(),
materials: HashMap::new(),
types: Vec::new(),
type_index: HashMap::new(),
@@ -1249,9 +1395,14 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result<String, String> {
let ty = r.type_ref()?;
let psets = r.psets()?;
let pts = r.pts()?;
let n_inner = r.idx()?;
let mut inner = Vec::new();
for _ in 0..n_inner {
inner.push(r.pts()?);
}
let z_rel = r.f()?;
let depth = r.f()?;
let (placement, shape) = w.emit_box_product(&pts, z_rel, depth, w.placement_of(structure));
let (placement, shape) = w.emit_box_product_voids(&pts, &inner, z_rel, depth, w.placement_of(structure));
w.finish_typed("IFCSLAB", format!("slab/{id}"), &name, &ty, &psets, structure, placement, shape, Some(enum_("FLOOR")), true);
}
c if c == REC_OPENING => {
@@ -1320,7 +1471,7 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result<String, String> {
);
w.add_to_containment(structure, fill_entity);
for p in &psets {
w.add_pset(p, fill_entity);
w.add_pset(p, fill_entity, &format!("fill/{opening_id}"));
}
}
c if c == REC_STAIR => {
@@ -1330,10 +1481,85 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result<String, String> {
let pts = r.pts()?;
let z_rel = r.f()?;
let depth = r.f()?;
let (placement, shape) = w.emit_box_product(&pts, z_rel, depth, w.placement_of(structure));
let g = w.gid(&format!("stair/{id}"));
let entity = w.emit_building_element("IFCSTAIR", g, "Treppe", placement, shape, Some(enum_(&predefined)));
let psets = r.psets()?;
let mut flights = Vec::new();
for _ in 0..r.idx()? {
flights.push(r.stair_flight()?);
}
let landing = if r.flag()? { Some(r.stair_landing()?) } else { None };
let rail = if r.flag()? { Some(r.stair_rail()?) } else { None };
let key = format!("stair/{id}");
let parent = w.placement_of(structure);
let g = w.gid(&key);
let entity = if flights.is_empty() && landing.is_none() && rail.is_none() {
// Ohne Teile: ein Ersatzkörper (Fussabdruck) wie bisher.
let (placement, shape) = w.emit_box_product(&pts, z_rel, depth, parent);
w.emit_building_element("IFCSTAIR", g, "Treppe", placement, shape, Some(enum_(&predefined)))
} else {
// Treppe ohne eigene Darstellung; Läufe, Podest und Geländer hängen per IfcRelAggregates daran.
let stair_placement = w.emit_placement(0.0, parent);
let stair = w.add(
"IFCSTAIR",
format!("{g},#{},{},$,$,#{stair_placement},$,$,{}", w.owner_history, ifc_string("Treppe"), enum_(&predefined)),
);
let mut parts = Vec::new();
for (k, f) in flights.iter().enumerate() {
let (placement, shape) = match &f.shape {
FlightShape::Solids(solids) => {
let ids: Vec<usize> = solids.iter().map(|(pts, z, d)| w.emit_extrusion(pts, *z, *d)).collect();
let shape = w.emit_swept_shape(&ids);
(w.emit_placement(0.0, stair_placement), shape)
}
FlightShape::Mesh(mesh) => w.emit_triangulated_product(mesh, stair_placement),
};
let fkey = format!("{key}/flight/{k}");
let guid = w.gid(&fkey);
let flight = w.add(
"IFCSTAIRFLIGHT",
format!(
"{guid},#{},{},$,$,#{placement},#{shape},$,{},{},{},{},{}",
w.owner_history,
ifc_string(&f.name),
f.risers,
f.treads,
fmt_real(f.riser_height),
fmt_real(f.tread_length),
enum_(&f.predefined)
),
);
for p in &f.psets {
w.add_pset(p, flight, &fkey);
}
parts.push(flight);
}
if let Some(l) = &landing {
let (placement, shape) = w.emit_box_product(&l.pts, l.z_rel, l.depth, stair_placement);
let lkey = format!("{key}/landing");
let guid = w.gid(&lkey);
let slab = w.emit_building_element("IFCSLAB", guid, &l.name, placement, shape, Some(enum_("LANDING")));
for p in &l.psets {
w.add_pset(p, slab, &lkey);
}
parts.push(slab);
}
if let Some(rl) = &rail {
let (placement, shape) = w.emit_triangulated_product(&rl.mesh, stair_placement);
let rkey = format!("{key}/railing");
let guid = w.gid(&rkey);
let railing = w.emit_building_element("IFCRAILING", guid, &rl.name, placement, shape, Some(enum_(&rl.predefined)));
for p in &rl.psets {
w.add_pset(p, railing, &rkey);
}
parts.push(railing);
}
let g = w.gid(&format!("aggregates/{key}"));
w.add("IFCRELAGGREGATES", format!("{g},#{},$,$,#{stair},{}", w.owner_history, refs(&parts)));
stair
};
w.add_to_containment(structure, entity);
for p in &psets {
w.add_pset(p, entity, &key);
}
}
c if c == REC_EXTRUSION => {
let structure = r.structure(n_storeys)?;
@@ -1409,7 +1635,7 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result<String, String> {
format!("{g},#{},$,$,{},#{pset}", w.owner_history, refs(&[space])),
);
for p in &psets {
w.add_pset(p, space);
w.add_pset(p, space, &format!("space/{id}"));
}
}
c if c == REC_END_SPACES => {
@@ -1448,7 +1674,7 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result<String, String> {
let entity = w.emit_building_element("IFCCOLUMN", g, &label, placement, shape, Some(enum_("COLUMN")));
w.add_to_containment(structure, entity);
for p in &psets {
w.add_pset(p, entity);
w.add_pset(p, entity, &format!("column/{id}"));
}
if let Some(cid) = component {
if let Some((_, _, v)) = w.column_materials.iter_mut().find(|(c, _, _)| *c == cid) {
@@ -1506,6 +1732,20 @@ pub fn build_ifc(flat: &[f64], strings: &str) -> Result<String, String> {
);
}
// ── Basismengen (je Bauteil ein IfcElementQuantity) ──
let qtos = std::mem::take(&mut w.qtos);
for q in &qtos {
let mut ids = Vec::with_capacity(q.quantities.len());
for (ty, name, value) in &q.quantities {
// IFC verlangt Mengen ≥ 0.
ids.push(w.add(ty, format!("{},$,$,{},$", ifc_string(name), fmt_real(value.max(0.0)))));
}
let g = w.gid(&format!("{}/{}", q.owner_key, q.name));
let set = w.add("IFCELEMENTQUANTITY", format!("{g},#{},{},$,$,{}", w.owner_history, ifc_string(&q.name), refs(&ids)));
let g = w.gid(&format!("{}/{}/rel", q.owner_key, q.name));
w.add("IFCRELDEFINESBYPROPERTIES", format!("{g},#{},$,$,{},#{set}", w.owner_history, refs(&[q.element])));
}
// ── Räumliche Eingliederung (gebündelt je Trägerstruktur) ──
let containment = std::mem::take(&mut w.containment);
for (structure, ids) in &containment {
@@ -1717,6 +1957,16 @@ mod tests {
fn no_psets(&mut self) {
self.f.push(0.0);
}
/// Ein Satz mit Mengen (`kind` 3 Länge, 4 Fläche, 5 Volumen).
fn qto(&mut self, set: &str, q: &[(&str, f64, f64)]) {
self.f.push(1.0);
self.str(set);
self.f.push(q.len() as f64);
for (n, kind, v) in q {
self.str(n);
self.n(&[*kind, *v]);
}
}
fn mesh_tetra(&mut self) {
self.n(&[4.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]);
self.n(&[4.0, 0.0, 2.0, 1.0, 0.0, 1.0, 3.0, 1.0, 2.0, 3.0, 2.0, 0.0, 3.0]);
@@ -1793,12 +2043,14 @@ mod tests {
b.no_type();
b.no_psets();
b.pts(&SQUARE);
b.n(&[2.6, 0.2]);
b.n(&[0.0, 2.6, 0.2]);
b.n(&[REC_STAIR, 0.0]);
b.str("S1");
b.str("STRAIGHT_RUN_STAIR");
b.pts(&SQUARE);
b.n(&[0.0, 2.6]);
b.no_psets();
b.n(&[0.0, 0.0, 0.0]);
b.n(&[REC_EXTRUSION, -1.0]);
b.str("X1");
b.pts(&SQUARE);
@@ -2084,6 +2336,170 @@ mod tests {
assert!(seen.len() > 20);
}
#[test]
fn basismengen_je_bauteil_eigen_mit_dauerhafter_guid() {
let mut b = mini();
for id in ["W1", "W2"] {
b.n(&[REC_WALL_SOLIDS, -1.0]);
b.str(id);
b.str("Wand");
b.no_type();
b.qto("Qto_WallBaseQuantities", &[("Length", 3.0, 5.0), ("GrossSideArea", 4.0, 13.0), ("NetVolume", 5.0, 3.25), ("Width", 3.0, -1e-9)]);
b.n(&[0.0, 1.0]);
b.pts(&SQUARE);
b.n(&[0.0, 2.6]);
}
let ifc = build(&b).unwrap();
check_structure(&ifc);
// Gleicher Inhalt, trotzdem je Wand ein eigener Satz (Mengen gehören dem Bauteil).
assert_eq!(count(&ifc, "IFCELEMENTQUANTITY"), 2);
assert_eq!(count(&ifc, "IFCPROPERTYSET"), 0);
assert_eq!(count(&ifc, "IFCQUANTITYLENGTH"), 4);
assert_eq!(count(&ifc, "IFCQUANTITYAREA"), 2);
assert_eq!(count(&ifc, "IFCQUANTITYVOLUME"), 2);
assert!(ifc.contains("IFCQUANTITYLENGTH('Length',$,$,5.0,$)"));
assert!(ifc.contains("IFCQUANTITYAREA('GrossSideArea',$,$,13.0,$)"));
assert!(ifc.contains("IFCQUANTITYVOLUME('NetVolume',$,$,3.25,$)"));
// Negative (Rundungs-)Werte werden auf 0 geklemmt (IFC verlangt ≥ 0).
assert!(ifc.contains("IFCQUANTITYLENGTH('Width',$,$,0.0,$)"));
assert_eq!(count(&ifc, "IFCRELDEFINESBYPROPERTIES"), 2);
let set = first_line(&ifc, "IFCELEMENTQUANTITY");
assert!(set.contains("'Qto_WallBaseQuantities',$,$,("), "{set}");
// Deterministisch, GUIDs verschieden je Wand.
assert_eq!(ifc, build(&b).unwrap());
let guids: Vec<&str> = ifc.lines().filter(|l| l.contains("=IFCELEMENTQUANTITY(")).map(|l| &l[l.find('(').unwrap() + 2..][..22]).collect();
assert_eq!(guids.len(), 2);
assert_ne!(guids[0], guids[1]);
// Eine andere Reihenfolge der Bauteile ändert die GUIDs nicht.
assert!(ifc.contains(&ifc_guid("t/wall/W1/Qto_WallBaseQuantities")));
assert!(ifc.contains(&ifc_guid("t/wall/W2/Qto_WallBaseQuantities")));
}
#[test]
fn decke_mit_aussparung_hat_profil_mit_loechern() {
let mut b = mini();
b.n(&[REC_CEILING, -1.0]);
b.str("D1");
b.str("Decke");
b.no_type();
b.qto("Qto_SlabBaseQuantities", &[("GrossArea", 4.0, 2.0), ("NetArea", 4.0, 1.5)]);
b.pts(&SQUARE);
b.n(&[2.0]);
b.pts(&[(1.0, 0.1), (2.0, 0.1), (2.0, 0.3), (1.0, 0.3)]);
b.pts(&[(3.0, 0.1), (4.0, 0.1), (4.0, 0.3)]);
b.n(&[2.6, 0.2]);
let ifc = build(&b).unwrap();
check_structure(&ifc);
assert_eq!(count(&ifc, "IFCARBITRARYPROFILEDEFWITHVOIDS"), 1);
assert_eq!(count(&ifc, "IFCARBITRARYCLOSEDPROFILEDEF"), 0);
let prof = first_line(&ifc, "IFCARBITRARYPROFILEDEFWITHVOIDS");
assert!(prof.contains(".AREA.,$,#"), "{prof}");
// Aussen- und zwei Innenkurven, jede geschlossen (Punkt 1 wiederholt).
assert_eq!(count(&ifc, "IFCPOLYLINE"), 3);
assert_eq!(count(&ifc, "IFCEXTRUDEDAREASOLID"), 1);
// Ohne Aussparung bleibt es das einfache Profil.
let plain = build(&full_house(false)).unwrap();
assert_eq!(count(&plain, "IFCARBITRARYPROFILEDEFWITHVOIDS"), 0);
}
/// Treppe mit zwei Läufen (Prismen), Podest und Geländer (Mesh).
fn stair_with_parts(b: &mut B) {
b.n(&[REC_STAIR, -1.0]);
b.str("S1");
b.str("QUARTER_TURN_STAIR");
b.pts(&SQUARE);
b.n(&[0.0, 2.6]);
b.no_psets();
b.n(&[2.0]);
for (k, name) in ["Lauf 1", "Lauf 2"].iter().enumerate() {
b.str(name);
b.n(&[7.0, 7.0, 0.1857, 0.28]);
b.str("STRAIGHT");
b.qto("Qto_StairFlightBaseQuantities", &[("Length", 3.0, 2.0), ("GrossVolume", 5.0, 1.0)]);
b.n(&[0.0, 2.0]);
b.pts(&SQUARE);
b.n(&[0.0, 0.2 * (k + 1) as f64]);
b.pts(&SQUARE);
b.n(&[0.5, 0.4]);
}
b.n(&[1.0]);
b.str("Podest");
b.pts(&SQUARE);
b.n(&[0.0, 1.3]);
b.no_psets();
b.n(&[1.0]);
b.str("Handlauf");
b.str("HANDRAIL");
b.no_psets();
b.mesh_tetra();
}
#[test]
fn treppe_mit_laeufen_podest_und_gelaender() {
let b = full_house(false);
let mut m = mini();
stair_with_parts(&mut m);
let ifc = build(&m).unwrap();
check_structure(&ifc);
assert_eq!(count(&ifc, "IFCSTAIR"), 1);
assert_eq!(count(&ifc, "IFCSTAIRFLIGHT"), 2);
assert_eq!(count(&ifc, "IFCRAILING"), 1);
assert_eq!(count(&ifc, "IFCSLAB"), 1);
assert!(ifc.contains(".LANDING.);"), "Podest als IfcSlab(LANDING)");
let stair = first_line(&ifc, "IFCSTAIR");
assert!(stair.contains(",$,$,.QUARTER_TURN_STAIR.);") && !stair.contains("#,#"), "{stair}");
let flight = first_line(&ifc, "IFCSTAIRFLIGHT");
assert!(flight.contains(",7,7,0.1857,0.28,.STRAIGHT.);"), "{flight}");
// Beide Läufe: Menge je Lauf; Treppe, Läufe, Podest, Geländer in EINER Aggregation, nur die Treppe im Geschoss/Gebäude.
assert_eq!(count(&ifc, "IFCELEMENTQUANTITY"), 2);
let agg = ifc.lines().find(|l| l.contains("IFCRELAGGREGATES(") && l.matches('#').count() == 7).expect("Aggregation der Treppe");
assert!(agg.contains(",#"), "{agg}");
let contained = first_line(&ifc, "IFCRELCONTAINEDINSPATIALSTRUCTURE");
assert_eq!(contained.matches('#').count(), 4, "nur die Treppe (Nummer, Owner, Treppe, Gebäude): {contained}");
// Läufe als Prismen, Geländer als Dreiecks-Netz.
assert_eq!(count(&ifc, "IFCEXTRUDEDAREASOLID"), 5); // 2 Läufe × 2 Prismen + Podest
assert_eq!(count(&ifc, "IFCTRIANGULATEDFACESET"), 1);
// Ohne Teile: Ersatzkörper (Fussabdruck) wie vorher.
let fallback = build(&b).unwrap();
assert_eq!(count(&fallback, "IFCSTAIRFLIGHT"), 0);
assert_eq!(count(&fallback, "IFCSTAIR"), 1);
// Lauf mit Mesh-Form.
let mut g = mini();
g.n(&[REC_STAIR, -1.0]);
g.str("S2");
g.str("STRAIGHT_RUN_STAIR");
g.pts(&SQUARE);
g.n(&[0.0, 2.6]);
g.no_psets();
g.n(&[1.0]);
g.str("Lauf");
g.n(&[15.0, 14.0, 0.17, 0.29]);
g.str("STRAIGHT");
g.no_psets();
g.n(&[1.0]);
g.mesh_tetra();
g.n(&[0.0, 0.0]);
let mesh = build(&g).unwrap();
check_structure(&mesh);
assert_eq!(count(&mesh, "IFCSTAIRFLIGHT"), 1);
assert_eq!(count(&mesh, "IFCTRIANGULATEDFACESET"), 1);
// Kaputte Lauf-Form: Fehler, nie Panic.
let mut bad = mini();
bad.n(&[REC_STAIR, -1.0]);
bad.str("S3");
bad.str("STRAIGHT_RUN_STAIR");
bad.pts(&SQUARE);
bad.n(&[0.0, 2.6]);
bad.no_psets();
bad.n(&[1.0]);
bad.str("Lauf");
bad.n(&[1.0, 1.0, 0.17, 0.29]);
bad.str("STRAIGHT");
bad.no_psets();
bad.n(&[9.0]);
assert!(build(&bad).is_err());
}
#[test]
fn leeres_projekt_ist_gueltig() {
let mut b = B::new();
+23 -13
View File
@@ -14,9 +14,9 @@
// GROUP = name (Knoten-/Objektname), kind (Text, z. B. "wall"), id (Bauteil-id), level (Index oder −1),
// n_prims, (material (Index oder −1), n_verts, x, y, z, …, n_tris, i0, i1, i2, …) × n_prims
//
// Koordinaten: Welt, Meter, Y-up, wie `selectionHighlightLines` (Modell (x, y, z) → (x, z, y)). OBJ und STL
// schreiben sie unverändert. glTF verlangt ein rechtshändiges Y-up-System: der Schreiber spiegelt Z
// (v → (x, y, −z)) und vertauscht die Dreiecks-Wicklung; Gesamtabbildung vom Modell:
// Koordinaten: Welt, Meter, Y-up, wie `selectionHighlightLines` (Modell (x, y, z) → (x, z, y); eine Spiegelung). Alle Formate
// (OBJ, STL, glTF; OBJ/STL seit 28.10. — vorher ungespiegelt) verlangen ein rechtshändiges Y-up-System:
// der Schreiber spiegelt Z (v → (x, y, −z)) und vertauscht die Dreiecks-Wicklung; Gesamtabbildung vom Modell:
// (x, y, z-hoch) → (x, z, −y), Norden liegt bei −Z (glTF-„vorne“), Ost bei +X.
//
// glTF: ein Knoten je Bauteil (Name = Gruppenname, `extras` = Typ und id), je Material eine Primitive,
@@ -165,14 +165,21 @@ fn tri_count(g: &Group) -> usize {
g.prims.iter().map(|p| p.indices.len() / 3).sum()
}
/// Szene-Welt (x, Höhe, y) → rechtshändige Datei (x, Höhe, −y) — Modell (x, y, z-hoch) → (x, z, −y). `0.0 - z`
/// statt `-z`: aus +0 wird so kein „-0.0“ in der Datei.
fn to_file(x: f64, y: f64, z: f64) -> [f64; 3] {
[x, y, 0.0 - z]
}
// ── OBJ ─────────────────────────────────────────────────────────────────────
fn write_obj(s: &Scene) -> String {
let mut out = String::new();
out.push_str("# DOSSIER OBJ-Export - Dreiecks-Mesh des 3D-Gebaeudemodells\n");
out.push_str("# Achsen: rechtshaendig, Y-up (Y = Hoehe ueber OKFF), wie der 3D-Viewer.\n");
out.push_str("# Achsen: rechtshaendig, Y-up (Y = Hoehe ueber OKFF), Modell (x,y,z) -> (x,z,-y), Norden = -Z.\n");
out.push_str("# Waende: Schicht-Baender mit oeffnungsgenau ausgeschnittenen Loechern (inkl. Laibungen).\n");
out.push_str("# Decken/Extrusionen: Umriss-Prisma (Ear-Clipping-Triangulierung).\n");
out.push_str("# Daecher, Treppen, Stuetzen, Fenster/Tueren (je Oeffnung ein Objekt), Gelaende und Kontext-Meshes wie im 3D.\n");
let mut offset = 0usize;
for g in s.groups.iter().filter(|g| tri_count(g) > 0) {
out.push_str("o ");
@@ -181,13 +188,15 @@ fn write_obj(s: &Scene) -> String {
let mut local = 0usize;
for p in &g.prims {
for v in p.positions.chunks_exact(3) {
out.push_str(&format!("v {} {} {}\n", fmt_real(v[0]), fmt_real(v[1]), fmt_real(v[2])));
let f = to_file(v[0], v[1], v[2]);
out.push_str(&format!("v {} {} {}\n", fmt_real(f[0]), fmt_real(f[1]), fmt_real(f[2])));
}
}
for p in &g.prims {
for t in p.indices.chunks_exact(3) {
let (a, b, c) = (t[0] as usize, t[1] as usize, t[2] as usize);
out.push_str(&format!("f {} {} {}\n", a + 1 + offset + local, b + 1 + offset + local, c + 1 + offset + local));
// Z gespiegelt ⇒ Wicklung vertauschen (Normalen zeigen weiter nach aussen).
out.push_str(&format!("f {} {} {}\n", a + 1 + offset + local, c + 1 + offset + local, b + 1 + offset + local));
}
local += p.positions.len() / 3;
}
@@ -204,10 +213,10 @@ fn write_stl(s: &Scene) -> String {
for p in &g.prims {
let v = |i: u32| {
let k = i as usize * 3;
[p.positions[k], p.positions[k + 1], p.positions[k + 2]]
to_file(p.positions[k], p.positions[k + 1], p.positions[k + 2])
};
for t in p.indices.chunks_exact(3) {
let (a, b, c) = (v(t[0]), v(t[1]), v(t[2]));
let (a, b, c) = (v(t[0]), v(t[2]), v(t[1]));
let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
let w = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
let mut n = [u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]];
@@ -638,8 +647,8 @@ mod tests {
let obj = export_obj(&n, &s).unwrap();
assert!(obj.starts_with("# DOSSIER OBJ-Export"));
assert!(obj.contains("o Wand_W1\nv 0.0 0.0 0.0\nv 1.0 0.0 0.0\n"));
// Zweite Gruppe: Indizes global (8 Vertices davor, 1-basiert).
assert!(obj.contains("o Decke_D\"1\nv 0.0 2.5 0.0\nv 1.0 2.5 0.0\nv 0.0 2.5 1.0\nf 9 10 11\n"), "{obj}");
// Zweite Gruppe: Indizes global (8 Vertices davor, 1-basiert). Rechtshändig: Z gespiegelt, Wicklung vertauscht.
assert!(obj.contains("o Decke_D\"1\nv 0.0 2.5 0.0\nv 1.0 2.5 0.0\nv 0.0 2.5 -1.0\nf 9 11 10\n"), "{obj}");
assert_eq!(obj.matches("\nf ").count(), 13);
}
@@ -651,8 +660,9 @@ mod tests {
assert!(stl.ends_with("endloop\nendfacet\nendsolid dossier\n"));
assert_eq!(stl.matches("facet normal").count(), 13);
assert_eq!(stl.matches("vertex ").count(), 39);
// Dreieck (0,2.5,0)(1,2.5,0)(0,2.5,1): Normale (0, -1, 0).
assert!(stl.contains("facet normal 0.0 -1.0 0.0\nouter loop\nvertex 0.0 2.5 0.0\n"), "{stl}");
// Welt-Dreieck (0,2.5,0)(1,2.5,0)(0,2.5,1) ⇒ Datei (x, y, −z) mit vertauschter Wicklung: Normale (0, -1, 0)
// bleibt (Wicklung und Spiegelung heben sich in der Normale auf), Ecken (0,2.5,0)(0,2.5,-1)(1,2.5,0).
assert!(stl.contains("facet normal 0.0 -1.0 0.0\nouter loop\nvertex 0.0 2.5 0.0\nvertex 0.0 2.5 -1.0\nvertex 1.0 2.5 0.0\n"), "{stl}");
}
fn json_of_glb(glb: &[u8]) -> (String, usize) {
@@ -713,7 +723,7 @@ mod tests {
let (json, bl) = json_of_glb(&glb);
assert_eq!(bl, 0);
assert!(json.trim_end().ends_with("\"scene\":0,\"scenes\":[{\"nodes\":[]}]}"));
assert_eq!(export_obj(&n, "").unwrap().lines().count(), 4);
assert_eq!(export_obj(&n, "").unwrap().lines().count(), 5);
assert_eq!(export_stl(&n, "").unwrap(), "solid dossier\nendsolid dossier\n");
}
+4 -4
View File
@@ -43,13 +43,13 @@ describe("glTF-Export", () => {
expect(report.issues.numErrors).toBe(0);
});
it("Rundreise: ein Knoten je Bauteil, Dreiecke wie im OBJ (plus Öffnungsteile)", () => {
it("Rundreise: ein Knoten je Bauteil, Dreiecke und Objekte wie im OBJ", () => {
const g = glbJson(exportGlb(sampleProject));
const obj = exportObj(sampleProject);
const objGroups = obj.split("\n").filter((l) => l.startsWith("o "));
const objFaces = obj.split("\n").filter((l) => l.startsWith("f ")).length;
const parts = g.nodes.filter((n) => n.mesh !== undefined);
const element = parts.filter((n) => ["wall", "slab", "extrusion"].includes(n.extras?.type ?? ""));
const element = parts;
expect(element.length).toBe(objGroups.length);
for (const n of element) expect(objGroups).toContain(`o ${n.name}`);
const elementTris = element.reduce(
@@ -57,7 +57,7 @@ describe("glTF-Export", () => {
0,
);
expect(elementTris).toBe(objFaces);
expect(triangles(g)).toBeGreaterThanOrEqual(objFaces);
expect(triangles(g)).toBe(objFaces);
});
it("Geschosse sind Eltern-Knoten der Bauteile; ohne byLevel liegen alle an der Wurzel", () => {
@@ -77,7 +77,7 @@ describe("glTF-Export", () => {
const glass = g.materials.find((m) => m.name === "Glas");
expect(glass?.alphaMode).toBe("BLEND");
expect(glass!.pbrMetallicRoughness.baseColorFactor[3]).toBeLessThan(1);
expect(g.nodes.some((n) => n.extras?.type === "glazing")).toBe(true);
expect(g.nodes.some((n) => n.extras?.type === "window")).toBe(true);
// Wandmaterial trägt den Namen der Komponente.
const names = sampleProject.components.map((c) => c.name);
expect(g.materials.some((m) => names.includes(m.name))).toBe(true);
+257
View File
@@ -0,0 +1,257 @@
// Basismengen im IFC-Export ([B5], 28.10.): Qto_Wall/Slab/Roof/Column/Door/Window/StairFlight/Railing
// werden gegen die Geometrie geprüft, die ifcopenshell aus derselben Datei liest (± 1 %), dazu Schema und
// Express-Regeln (`scripts/validate-ifc.py`, 0 Befunde). Ohne Python/ifcopenshell wird der zweite Teil übersprungen.
import { describe, expect, it } from "vitest";
import { spawnSync } from "node:child_process";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import "../engine/fileioWasm.setup";
import { exportIfcSpf } from "./exportIfc";
import { sampleProject } from "../model/sampleProject";
import type { Column, Project, Stair } from "../model/types";
const hasIfcOpenShell = spawnSync("python3", ["-c", "import ifcopenshell, ifcopenshell.validate, numpy"]).status === 0;
/** Das Demo-Haus plus Stütze, Deckenaussparung, L-Treppe (massiv) und gerade Treppe mit Geländer. */
function project(): Project {
const eg = "eg";
const column: Column = { id: "C1", type: "column", floorId: eg, categoryCode: "50", position: { x: 6.5, y: 1 }, profile: { kind: "rect", width: 0.3, depth: 0.2 }, rotation: 0.3, height: 2.5 };
const st0 = sampleProject.stairs![0];
const lStair: Stair = { ...st0, id: "ST-L", typeId: "stair-massiv", shape: "L", start: { x: 7.5, y: 0.4 }, run2Length: 1.5, turn: 1, stepCount: 14 };
const railed: Stair = { ...st0, id: "ST-R", typeId: "stair-rail", start: { x: 10, y: 0.4 } };
return {
...sampleProject,
ceilings: sampleProject.ceilings!.map((c) => ({ ...c, openings: [[{ x: 1, y: 1 }, { x: 2.5, y: 1 }, { x: 2.5, y: 2 }, { x: 1, y: 2 }]] })),
columns: [column],
stairTypes: [...sampleProject.stairTypes!, { id: "stair-rail", name: "Massiv mit Handlauf", structure: "massiv", closedRisers: true, treadThickness: 0.04, nosing: 0.03, railing: "beide", defaultWidth: 1 }],
stairs: [...sampleProject.stairs!, lStair, railed],
} as Project;
}
function writeIfc(name: string, ifc: string): string {
const dir = mkdtempSync(join(tmpdir(), "dossier-qto-"));
const file = join(dir, `${name}.ifc`);
writeFileSync(file, ifc);
return file;
}
/**
* Je Bauteil mit Basismengen: Klasse, Name, Mengen und unabhängig aus der Geometrie gelesene Werte
* (Volumen mit/ohne Öffnungsabzug, nach oben zeigende Fläche, Bounding-Box lokal).
*/
const QTO_INFO = `
import json, sys
import numpy as np
import ifcopenshell, ifcopenshell.geom, ifcopenshell.util.element as ue, ifcopenshell.util.shape as us
m = ifcopenshell.open(sys.argv[1])
net = ifcopenshell.geom.settings()
gross = ifcopenshell.geom.settings()
gross.set("disable-opening-subtractions", True)
local = ifcopenshell.geom.settings()
local.set("use-world-coords", False)
def up_areas(geom):
v = np.array(geom.verts).reshape(-1, 3)
f = np.array(geom.faces).reshape(-1, 3)
n = np.cross(v[f[:, 1]] - v[f[:, 0]], v[f[:, 2]] - v[f[:, 0]])
area = np.linalg.norm(n, axis=1) / 2
nz = n[:, 2] / np.maximum(np.linalg.norm(n, axis=1), 1e-12)
up = nz > 0.1
return float(area[up].sum()), float((area[up] * nz[up]).sum())
def opening_dims(wall):
out = []
for rel in wall.HasOpenings:
e = rel.RelatedOpeningElement
g = ifcopenshell.geom.create_shape(local, e).geometry
v = np.array(g.verts).reshape(-1, 3)
d = v.max(axis=0) - v.min(axis=0)
out.append([float(x) for x in d])
return out
out = []
for el in m.by_type("IfcElement"):
qtos = ue.get_psets(el, qtos_only=True)
if not qtos:
continue
item = {"cls": el.is_a(), "name": el.Name, "predefined": getattr(el, "PredefinedType", None), "qto": qtos}
if el.Representation is not None:
shape = ifcopenshell.geom.create_shape(net, el)
item["volume"] = us.get_volume(shape.geometry)
item["area"] = us.get_area(shape.geometry)
item["up"] = up_areas(shape.geometry)
item["rep"] = [r for r in el.Representation.Representations if r.RepresentationIdentifier == "Body"][0].RepresentationType
if el.is_a("IfcWall"):
item["grossVolume"] = us.get_volume(ifcopenshell.geom.create_shape(gross, el).geometry)
item["openings"] = opening_dims(el)
g = shape.geometry
v = np.array(g.verts).reshape(-1, 3)
item["zExtent"] = float(v[:, 2].max() - v[:, 2].min())
if el.is_a("IfcSlab"):
prof = [r for r in el.Representation.Representations if r.RepresentationIdentifier == "Body"][0].Items[0].SweptArea
holes = []
if prof.is_a("IfcArbitraryProfileDefWithVoids"):
for c in prof.InnerCurves:
p = np.array([q.Coordinates for q in c.Points])
holes.append(float(abs(0.5 * np.sum(p[:-1, 0] * p[1:, 1] - p[1:, 0] * p[:-1, 1]))))
item["holeAreas"] = holes
item["depth"] = float(el.Representation.Representations[0].Items[0].Depth)
if el.is_a("IfcDoor") or el.is_a("IfcWindow"):
host = [r.RelatingOpeningElement for r in el.FillsVoids]
g = ifcopenshell.geom.create_shape(local, host[0]).geometry
v = np.array(g.verts).reshape(-1, 3)
item["openingDims"] = [float(x) for x in (v.max(axis=0) - v.min(axis=0))]
out.append(item)
print(json.dumps(out))
`;
interface Item {
cls: string;
name: string;
predefined: string | null;
qto: Record<string, Record<string, number>>;
volume?: number;
area?: number;
up?: [number, number];
rep?: string;
grossVolume?: number;
openings?: number[][];
zExtent?: number;
holeAreas?: number[];
depth?: number;
openingDims?: number[];
}
function info(name: string, ifc: string): Item[] {
const r = spawnSync("python3", ["-c", QTO_INFO, writeIfc(name, ifc)], { encoding: "utf8", timeout: 120_000 });
expect(r.status, r.stderr).toBe(0);
return JSON.parse(r.stdout);
}
const rel = (a: number, b: number) => Math.abs(a - b) / Math.max(Math.abs(a), Math.abs(b), 1e-9);
const close = (a: number, b: number, tol = 0.01) => expect(rel(a, b), `${a} ≠ ${b}`).toBeLessThanOrEqual(tol);
const qof = (it: Item, set: string) => it.qto[set] ?? {};
describe("Basismengen im Export (ohne ifcopenshell)", () => {
it("jedes Bauteil trägt seine Mengen; Treppe mit Läufen, Podest und Geländer; Deckenaussparung", () => {
const ifc = exportIfcSpf(project());
const count = (cls: string) => (ifc.match(new RegExp(`^#\\d+=${cls}\\(`, "gm")) ?? []).length;
const sets = (name: string) => (ifc.match(new RegExp(`IFCELEMENTQUANTITY\\('[^']*',#\\d+,'${name}'`, "g")) ?? []).length;
expect(sets("Qto_WallBaseQuantities")).toBe(count("IFCWALL"));
expect(sets("Qto_SlabBaseQuantities")).toBe(count("IFCSLAB")); // Decke + Podest der L-Treppe
expect(sets("Qto_RoofBaseQuantities")).toBe(1);
expect(sets("Qto_ColumnBaseQuantities")).toBe(1);
expect(sets("Qto_DoorBaseQuantities")).toBe(count("IFCDOOR"));
expect(sets("Qto_WindowBaseQuantities")).toBe(count("IFCWINDOW"));
expect(sets("Qto_StairFlightBaseQuantities")).toBe(count("IFCSTAIRFLIGHT"));
expect(sets("Qto_RailingBaseQuantities")).toBe(count("IFCRAILING"));
expect(count("IFCSTAIR")).toBe(3);
expect(count("IFCSTAIRFLIGHT")).toBe(1 /* Beton: Netz */ + 2 /* L */ + 1);
expect(count("IFCRAILING")).toBe(1);
expect(count("IFCARBITRARYPROFILEDEFWITHVOIDS")).toBe(1);
expect(ifc).toContain(".LANDING.);");
});
it("Export ist deterministisch (GUIDs der Mengen stabil)", () => {
const strip = (s: string) => s.replace(/FILE_NAME\([^\n]*\n/, "").replace(/IFCOWNERHISTORY\([^\n]*\n/, "");
expect(strip(exportIfcSpf(project()))).toBe(strip(exportIfcSpf(project())));
});
});
describe.skipIf(!hasIfcOpenShell)("Basismengen gegen ifcopenshell", { timeout: 120_000 }, () => {
const ifc = exportIfcSpf(project());
const items = info("qto", ifc);
const of = (cls: string) => items.filter((i) => i.cls === cls);
it("schema- und regelkonform, alle Körper erzeugbar (0 Befunde)", () => {
const r = spawnSync("python3", ["scripts/validate-ifc.py", writeIfc("qto-validate", ifc)], { encoding: "utf8", timeout: 120_000 });
expect(`${r.stdout}\n${r.stderr}`).toContain("0 Befunde");
expect(r.status).toBe(0);
});
it("Wände: Netto-Volumen = Geometrie mit Öffnungsabzug, Brutto = ohne (Extrusions-Wände), Länge/Höhe/Seitenfläche", () => {
const walls = of("IfcWall");
expect(walls.length).toBe(9);
for (const w of walls) {
const q = qof(w, "Qto_WallBaseQuantities");
close(q.NetVolume, w.volume!);
if (w.rep === "SweptSolid") {
close(q.GrossVolume, w.grossVolume!);
// Seitenfläche brutto = Länge × Höhe; netto zieht die Öffnungen ab (Breite × Höhe der Öffnungskörper).
close(q.GrossSideArea, q.Length * q.Height);
const holes = (w.openings ?? []).reduce((s, d) => s + Math.max(...d.slice(0, 2)) * d[2], 0);
// Öffnungsquader sind quer 4 cm dicker als die Wand: die längere der zwei Grundrissmasse ist die Öffnungsbreite,
// sofern sie grösser als die Wanddicke ist.
if ((w.openings ?? []).every((d) => Math.max(d[0], d[1]) > q.Width + 0.05)) close(q.NetSideArea, q.GrossSideArea - holes);
close(q.Height, w.zExtent!);
} else {
// Netz-Wand: Brutto ≥ Netto, Seitenfläche netto ≤ brutto.
expect(q.GrossVolume).toBeGreaterThanOrEqual(q.NetVolume);
}
expect(q.NetSideArea).toBeLessThanOrEqual(q.GrossSideArea + 1e-9);
}
expect(walls.some((w) => w.rep === "SweptSolid")).toBe(true);
expect(walls.some((w) => w.rep === "Tessellation")).toBe(true);
// Mindestens eine Wand mit Öffnung: Netto < Brutto.
expect(walls.some((w) => qof(w, "Qto_WallBaseQuantities").NetVolume < qof(w, "Qto_WallBaseQuantities").GrossVolume - 1e-6)).toBe(true);
});
it("Decken und Podest: Volumen nach ifcopenshell, Aussparung = Brutto − Netto", () => {
const slabs = of("IfcSlab");
const floor = slabs.find((s) => s.predefined === "FLOOR")!;
const q = qof(floor, "Qto_SlabBaseQuantities");
close(q.NetVolume, floor.volume!);
const holes = floor.holeAreas!.reduce((a, b) => a + b, 0);
expect(holes).toBeCloseTo(1.5, 9);
close(q.GrossVolume - q.NetVolume, holes * floor.depth!);
close(q.GrossArea - q.NetArea, holes);
close(q.Width, floor.depth!);
const landing = slabs.find((s) => s.predefined === "LANDING")!;
const ql = qof(landing, "Qto_SlabBaseQuantities");
close(ql.NetVolume, landing.volume!);
close(ql.GrossArea * ql.Width, ql.GrossVolume);
});
it("Dach: Grundrissprojektion und geneigte Fläche = nach oben zeigende Netz-Dreiecke", () => {
const [roof] = of("IfcRoof");
const q = qof(roof, "Qto_RoofBaseQuantities");
close(q.GrossArea, roof.up![0]);
close(q.ProjectedArea, roof.up![1]);
expect(q.GrossArea).toBeGreaterThan(q.ProjectedArea);
});
it("Stütze: Volumen, Querschnitt × Länge", () => {
const [col] = of("IfcColumn");
const q = qof(col, "Qto_ColumnBaseQuantities");
close(q.GrossVolume, col.volume!);
close(q.CrossSectionArea * q.Length, q.GrossVolume);
close(q.CrossSectionArea, 0.3 * 0.2);
expect(q.Length).toBeCloseTo(2.5, 9);
});
it("Türen und Fenster: Breite/Höhe wie der Öffnungskörper, Fläche = Breite × Höhe", () => {
const fills = [...of("IfcDoor"), ...of("IfcWindow")];
expect(fills.length).toBe(3);
for (const f of fills) {
const q = qof(f, f.cls === "IfcDoor" ? "Qto_DoorBaseQuantities" : "Qto_WindowBaseQuantities");
close(q.Area, q.Width * q.Height);
close(q.Height, f.openingDims![2]);
expect([f.openingDims![0], f.openingDims![1]].some((d) => rel(d, q.Width) <= 0.01), `${f.name} Breite ${q.Width}`).toBe(true);
}
});
it("Treppenläufe: Brutto-Volumen = Geometrie; Geländer mit Länge", () => {
const flights = of("IfcStairFlight");
expect(flights.length).toBe(4);
for (const f of flights) {
const q = qof(f, "Qto_StairFlightBaseQuantities");
// Massive Treppen: Prismen können sich an den Nasen überlappen — ifcopenshell vereinigt nicht, Summe stimmt.
close(q.GrossVolume, f.volume!, 0.011);
expect(q.Length).toBeGreaterThan(1);
}
const [rail] = of("IfcRailing");
expect(qof(rail, "Qto_RailingBaseQuantities").Length).toBeGreaterThan(3);
});
});
+115 -22
View File
@@ -41,10 +41,11 @@
// • 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()).
// • Treppe → IfcStair ohne eigene Darstellung, zusammengefasst (IfcRelAggregates) aus Läufen
// (IfcStairFlight: Prismen der Tritte bzw. glatte Ortbeton-Laufplatte als Netz, Steigungs-/Auftrittsmasse),
// Podest (IfcSlab LANDING, nur "L") und Handlauf/Pfosten (IfcRailing HANDRAIL, wo das 3D sie zeigt) —
// dieselben Ableitungen wie das 3D (`ifcStairs.ts`). Ohne Teile bleibt der Fussabdruck-Quader
// (`stairFootprint()`).
//
// Material-Schichten: je Wand-/Deckentyp ein IfcWallType/IfcSlabType mit
// IfcMaterialLayerSet, die Exemplare erben ihn über IfcRelDefinesByType. Extrusions-Wände
@@ -54,6 +55,12 @@
// Wandanfang, X = Achse, Y = linke Normale (Rust rechnet die Welt-Profile ins Wandsystem). Mesh-
// Wände (schräge Oberkante, Laibungs-Rücksprung) haben weder Achse noch Usage.
//
// Basismengen ([B5], 28.10.): Qto_WallBaseQuantities (Length, Width, Height, GrossSideArea, NetSideArea,
// GrossVolume, NetVolume), Qto_SlabBaseQuantities, Qto_RoofBaseQuantities, Qto_ColumnBaseQuantities,
// Qto_DoorBaseQuantities/Qto_WindowBaseQuantities (Width, Height, Perimeter, Area), Qto_StairFlightBaseQuantities
// und Qto_RailingBaseQuantities — aus der Geometrie (`ifcQuantities.ts`), Netto = abzüglich Öffnungen;
// Rust schreibt je Bauteil einen IfcElementQuantity. Deckenaussparungen sind echte Löcher im Profil.
//
// Eigenschaften ([B5]): Pset_WallCommon/SlabCommon/RoofCommon/ColumnCommon/DoorCommon/
// WindowCommon/SpaceCommon nur mit Werten, die das Modell hergibt (Reference = Typname,
// IsExternal beim Dach und bei SIA-416-AGF-Räumen, Glasanteil der Glastür). Kein U-Wert,
@@ -68,6 +75,7 @@
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). Einheit: METER.
import type { Opening, Project, Stair, Vec2, Wall } from "../model/types";
import type { StairParts } from "./ifcStairs";
import {
columnLabel,
getCeilingType,
@@ -88,6 +96,18 @@ import { openingInterval, openingVerticalExtent } from "../geometry/opening";
import { emitRoofs } from "../plan/toWalls3d/roofs";
import { fileio } from "../engine/fileioWasm";
import { fillParams, type FillParams } from "./ifcOpenings";
import { stairParts } from "./ifcStairs";
import {
columnQuantities,
holeVolume,
meshVolume,
openingQuantities,
roofQuantities,
slabQuantities,
wallQuantities,
type Qty,
} from "./ifcQuantities";
import { roofBaseElevation, roofGeometry } from "../geometry/roof";
/** Deterministische 22-stellige IFC-GUID aus einem Namen (Rust, `ifc_export.rs::ifc_guid`). */
export function ifcGuid(name: string): string {
@@ -101,7 +121,7 @@ export function ifcString(s: string): string {
// ── Flacher Puffer (Gegenstück zu src-tauri/fileio/src/ifc_export.rs, dort die Kodierung) ─────
const FLAT_VERSION = 2;
const FLAT_VERSION = 3;
const REC_WALL_SOLIDS = 1;
const REC_WALL_MESH = 2;
const REC_CEILING = 3;
@@ -125,8 +145,17 @@ interface TypeRefIn {
layers: { componentId: string; componentName: string; thickness: number }[];
}
/** Pset-Eigenschaft: Kennung, Art (IfcIdentifier, IfcBoolean, IfcPositiveRatioMeasure) und Wert. */
type PropIn = { name: string; ident: string } | { name: string; bool: boolean } | { name: string; ratio: number };
/**
* Pset-Eigenschaft: Kennung, Art (IfcIdentifier, IfcBoolean, IfcPositiveRatioMeasure) und Wert; in einem Satz
* `Qto_…` Mengen (Länge, Fläche, Volumen) — Rust schreibt daraus je Bauteil einen IfcElementQuantity.
*/
type PropIn =
| { name: string; ident: string }
| { name: string; bool: boolean }
| { name: string; ratio: number }
| { name: string; length: number }
| { name: string; area: number }
| { name: string; volume: number };
interface PsetIn {
name: string;
props: PropIn[];
@@ -170,7 +199,10 @@ class FlatIfc {
for (const p of ps.props) {
if ("ident" in p) this.nums.push(this.str(p.name), 0, this.str(p.ident));
else if ("bool" in p) this.nums.push(this.str(p.name), 1, p.bool ? 1 : 0);
else this.nums.push(this.str(p.name), 2, p.ratio);
else if ("ratio" in p) this.nums.push(this.str(p.name), 2, p.ratio);
else if ("length" in p) this.nums.push(this.str(p.name), 3, p.length);
else if ("area" in p) this.nums.push(this.str(p.name), 4, p.area);
else this.nums.push(this.str(p.name), 5, p.volume);
}
}
}
@@ -228,11 +260,13 @@ class FlatIfc {
this.mesh(positions, indices, closed);
}
ceiling(structure: number, id: string, name: string, ty: TypeRefIn | null, psets: PsetIn[], outline: Vec2[], zRel: number, depth: number): void {
ceiling(structure: number, id: string, name: string, ty: TypeRefIn | null, psets: PsetIn[], outline: Vec2[], inner: readonly (readonly Vec2[])[], zRel: number, depth: number): void {
this.nums.push(REC_CEILING, structure, this.str(id), this.str(name));
this.typeRef(ty);
this.psets(psets);
this.pts(outline);
this.nums.push(inner.length);
for (const ring of inner) this.pts(ring);
this.nums.push(zRel, depth);
}
@@ -272,10 +306,44 @@ class FlatIfc {
this.psets(o.psets);
}
stair(structure: number, id: string, predefined: string, footprint: Vec2[], zRel: number, depth: number): void {
stair(structure: number, id: string, predefined: string, footprint: Vec2[], zRel: number, depth: number, parts: StairParts): void {
this.nums.push(REC_STAIR, structure, this.str(id), this.str(predefined));
this.pts(footprint);
this.nums.push(zRel, depth);
this.psets([]);
this.nums.push(parts.flights.length);
for (const f of parts.flights) {
this.nums.push(this.str(f.name), f.risers, f.treads, f.riserHeight, f.treadLength, this.str(f.predefined));
this.psets(qto("Qto_StairFlightBaseQuantities", f.quantities));
if (f.mesh) {
this.nums.push(1);
this.mesh(f.mesh.positions, f.mesh.indices, false);
} else {
const solids = f.solids ?? [];
this.nums.push(0, solids.length);
for (const s of solids) {
this.pts(s.pts);
this.nums.push(s.zRel, s.depth);
}
}
}
if (parts.landing) {
const l = parts.landing;
this.nums.push(1, this.str(l.name));
this.pts(l.pts);
this.nums.push(l.zRel, l.depth);
this.psets(qto("Qto_SlabBaseQuantities", l.quantities));
} else {
this.nums.push(0);
}
if (parts.rail) {
const r = parts.rail;
this.nums.push(1, this.str(r.name), this.str(r.predefined));
this.psets(qto("Qto_RailingBaseQuantities", r.quantities));
this.mesh(r.mesh.positions, r.mesh.indices, false);
} else {
this.nums.push(0);
}
}
extrusion(structure: number, id: string, pts: Vec2[], zRel: number, depth: number): void {
@@ -485,6 +553,17 @@ const ROOF_PREDEFINED: Record<string, string> = {
const identifier = (name: string, v: string): PropIn => ({ name, ident: v });
/** Basismengen als Pset `Qto_…` (nur wenn Mengen vorliegen). */
function qto(name: string, quantities: readonly Qty[]): PsetIn[] {
if (quantities.length === 0) return [];
return [
{
name,
props: quantities.map((x): PropIn => (x.kind === "length" ? { name: x.name, length: x.value } : x.kind === "area" ? { name: x.name, area: x.value } : { name: x.name, volume: x.value })),
},
];
}
/**
* Baut aus einem Projekt einen vollständigen IFC4-SPF-String (STEP Physical
* File). Kein Datei-IO. Leeres Projekt ⇒ valider Minimal-IFC (Project/Site/Building, kein Crash).
@@ -571,17 +650,18 @@ export function exportIfcSpf(projectIn: Project): string {
}
return out;
};
/** Name, Typ und Pset einer Wand (verwaister Wandtyp: Roh-ID als Name, kein Typ). */
const wallIdentity = (wall: Wall): { name: string; ty: TypeRefIn | null; psets: PsetIn[] } => {
/** Name, Typ und Pset einer Wand (verwaister Wandtyp: Roh-ID als Name, kein Typ); `quantities` = Basismengen. */
const wallIdentity = (wall: Wall, quantities: readonly Qty[]): { name: string; ty: TypeRefIn | null; psets: PsetIn[] } => {
const qtoSets = qto("Qto_WallBaseQuantities", quantities);
try {
const wt = getWallType(project, wall);
return {
name: wt.name,
ty: typeRef(0, "STANDARD", wt),
psets: [{ name: "Pset_WallCommon", props: [identifier("Reference", wt.name)] }],
psets: [{ name: "Pset_WallCommon", props: [identifier("Reference", wt.name)] }, ...qtoSets],
};
} catch {
return { name: wall.id, ty: null, psets: [] };
return { name: wall.id, ty: null, psets: qtoSets };
}
};
/** Ausdehnung aller Bänder quer zur Wandachse (entlang der linken Normalen ab `wall.start`). */
@@ -620,7 +700,7 @@ export function exportIfcSpf(projectIn: Project): string {
const rect = [addScaled(s, n, -h), addScaled(e, n, -h), addScaled(e, n, h), addScaled(s, n, h)];
return { pts: rect, zRel: b.baseElevation - baseOf(structure), depth: b.height };
});
const id = wallIdentity(wall);
const id = wallIdentity(wall, wallQuantities(wall, bands, cutouts));
// Wandsystem: Placement am Wandanfang, X = Achse, Y = linke Normale; die Schichten des Typs
// stehen ab der Aussenfläche (negative Normale) nebeneinander — IfcMaterialLayerSetUsage nur,
// wenn ihre Summe dem Querschnitt der Bänder entspricht (sonst wäre der Offset gelogen).
@@ -663,7 +743,15 @@ export function exportIfcSpf(projectIn: Project): string {
// (Wände sind extrudierte Querschnitts-Polygone → geschlossene Körper); der Guard fängt echte
// Defekte ab (invertierte Wicklung → Volumen < 0 → `$`).
const closed = isWatertight({ positions, indices });
const id = wallIdentity(wall);
// Netto: Volumen des Netzes (Öffnungen samt Laibungen schon ausgestanzt); ohne dichtes Netz Quader minus Löcher.
const meshBandsOfWall = bandsByWallId.get(wall.id)!;
const net = closed ? meshVolume(positions, indices) : undefined;
const quantities = wallQuantities(wall, meshBandsOfWall, cutoutsByWallId.get(wall.id) ?? [], net);
if (net === undefined) {
const gross = quantities.find((x) => x.name === "GrossVolume")!.value;
quantities.find((x) => x.name === "NetVolume")!.value = Math.max(0, gross - holeVolume(meshBandsOfWall));
}
const id = wallIdentity(wall, quantities);
flat.wallMesh(structure, wall.id, id.name, id.ty, id.psets, positions, indices, closed);
hostExtent.set(wall.id, crossExtent(wall, bandsByWallId.get(wall.id)!));
}
@@ -684,7 +772,10 @@ export function exportIfcSpf(projectIn: Project): string {
} catch {
/* verwaister Deckentyp — Roh-ID als Name, kein Typ */
}
flat.ceiling(structure, ceiling.id, name, ty, psets, ceiling.outline, zBottom - baseOf(structure), zTop - zBottom);
// Aussparungen (wie im 3D) als innere Ringe des Profils; Mengen: Netto zieht sie ab.
const inner = (ceiling.openings ?? []).filter((ring) => ring.length >= 3);
psets.push(...qto("Qto_SlabBaseQuantities", slabQuantities(ceiling.outline, inner, zTop - zBottom)));
flat.ceiling(structure, ceiling.id, name, ty, psets, ceiling.outline, inner, zBottom - baseOf(structure), zTop - zBottom);
}
// ── Öffnungen: IfcOpeningElement in der Wand, IfcDoor/IfcWindow darin ───
@@ -727,19 +818,19 @@ export function exportIfcSpf(projectIn: Project): string {
depth,
width: c.to - c.from,
fill: fillParams(project, wall, opening, c, host),
psets: [{ name: psetName, props }],
psets: [{ name: psetName, props }, ...qto(isDoor ? "Qto_DoorBaseQuantities" : "Qto_WindowBaseQuantities", openingQuantities(c.to - c.from, depth))],
});
}
}
// ── Treppen (vereinfachter Bounding-Footprint, siehe Dateikopf) ────────
// ── Treppen: Läufe, Podest, Geländer wie im 3D (`ifcStairs.ts`); ohne Teile der Fussabdruck-Quader ──
for (const stair of project.stairs ?? []) {
const footprint = stairFootprint(stair);
if (footprint.length < 3) continue;
const { zBottom, zTop } = stairVerticalExtent(project, stair);
const structure = structureOf(stair.floorId);
const predefined = stair.shape === "straight" ? "STRAIGHT_RUN_STAIR" : stair.shape === "spiral" ? "SPIRAL_STAIR" : "QUARTER_TURN_STAIR";
flat.stair(structure, stair.id, predefined, footprint, zBottom - baseOf(structure), zTop - zBottom);
flat.stair(structure, stair.id, predefined, footprint, zBottom - baseOf(structure), zTop - zBottom, stairParts(project, stair, baseOf(structure)));
}
// ── Extrudierte Körper (truck-Integration) → IfcBuildingElementProxy ───
@@ -815,13 +906,15 @@ export function exportIfcSpf(projectIn: Project): string {
const props: PropIn[] = [];
if (roofType) props.push(identifier("Reference", roofType.name));
props.push({ name: "IsExternal", bool: true });
// Mengen aus den geneigten Dachflächen (Aussenseite), wie sie auch das Netz erzeugen.
const planes = roofGeometry(roof, roofBaseElevation(project, roof)).planes.map((pl) => pl.pts);
flat.roof(
structure,
roof.id,
roofType?.name ?? "Dach",
predefined,
roofType ? typeRef(2, predefined, roofType) : null,
[{ name: "Pset_RoofCommon", props }],
[{ name: "Pset_RoofCommon", props }, ...qto("Qto_RoofBaseQuantities", roofQuantities(planes))],
positions,
indices,
closed,
@@ -844,7 +937,7 @@ export function exportIfcSpf(projectIn: Project): string {
zRel: zBottom - baseOf(structure),
depth: zTop - zBottom,
component: col.componentId ? { id: col.componentId, name: componentName(col.componentId) } : null,
psets: [{ name: "Pset_ColumnCommon", props: [identifier("Reference", label)] }],
psets: [{ name: "Pset_ColumnCommon", props: [identifier("Reference", label)] }, ...qto("Qto_ColumnBaseQuantities", columnQuantities(footprint, zTop - zBottom))],
});
}
flat.endColumns();
+215
View File
@@ -0,0 +1,215 @@
// Mesh-Export vollständig ([C11], 28.10.): Dächer, Treppen, Stützen, Kontext-Meshes, ein Knoten je Öffnung,
// rechtshändige Achsen in OBJ/STL/glTF, Dreieckszahl wie die 3D-Ableitung, Khronos-Validator.
import { describe, it, expect } from "vitest";
import "../engine/fileioWasm.setup";
import validator from "gltf-validator";
import { exportGlb, exportGltf, exportObj, exportStl } from "./exportMesh";
import { orientOutward } from "./meshOrient";
import { sampleProject } from "../model/sampleProject";
import type { Column, ImportedMesh, Project, TerrainMesh } from "../model/types";
import { emitOpeningMeshes } from "../plan/toWalls3d/openings";
import { emitRoofs } from "../plan/toWalls3d/roofs";
import { emitColumns } from "../plan/toWalls3d/columns";
import { emitStairMeshes, emitStairRailings, emitStairs } from "../plan/toWalls3d/stairs";
interface Gltf {
nodes: { name: string; mesh?: number; children?: number[]; extras?: { type: string; id: string } }[];
meshes: { primitives: { attributes: { POSITION: number }; indices: number; material: number }[] }[];
accessors: { count: number; min?: number[]; max?: number[] }[];
materials: { name: string; pbrMetallicRoughness: { baseColorFactor: number[] } }[];
}
function glbJson(glb: Uint8Array): Gltf {
const dv = new DataView(glb.buffer, glb.byteOffset, glb.byteLength);
const len = dv.getUint32(12, true);
return JSON.parse(new TextDecoder().decode(glb.subarray(20, 20 + len))) as Gltf;
}
const nodeTris = (g: Gltf, n: { mesh?: number }): number =>
n.mesh === undefined ? 0 : g.meshes[n.mesh].primitives.reduce((t, p) => t + g.accessors[p.indices].count / 3, 0);
/** Würfel 2 m (x, y, z-hoch ab z = 0) mit Wicklung nach aussen im Modell (rechtshändig, z hoch). */
const CUBE_POS = [0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 2, 0, 0, 0, 2, 2, 0, 2, 2, 2, 2, 0, 2, 2];
const CUBE_IDX = [0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 0, 1, 5, 0, 5, 4, 1, 2, 6, 1, 6, 5, 2, 3, 7, 2, 7, 6, 3, 0, 4, 3, 4, 7];
function withContext(base: Project): Project {
const imported: ImportedMesh = {
id: "IM1",
type: "importedMesh",
name: "Nachbar",
color: "#ff0000",
positions: CUBE_POS.map((v, i) => (i % 3 === 0 ? v + 20 : v)),
indices: CUBE_IDX,
};
const terrain: TerrainMesh = {
id: "TM1",
type: "terrainMesh",
name: "Gelände",
positions: [-5, -5, 0, 25, -5, 0, 25, 25, 0, -5, 25, 0],
indices: [0, 1, 2, 0, 2, 3],
};
const column: Column = {
id: "C1",
type: "column",
floorId: base.drawingLevels.find((l) => l.kind === "floor")!.id,
categoryCode: "50",
position: { x: 8, y: 1 },
profile: { kind: "rect", width: 0.3, depth: 0.3 },
rotation: 0,
height: 2.6,
} as Column;
// Zweite Treppe ohne Typ ⇒ massives Tritt-Prisma (die Beispieltreppe ist Ortbeton: glatte Laufplatte als Mesh).
const massive = { ...base.stairs![0], id: "ST2", typeId: undefined, start: { x: 6, y: 0.4 } };
return {
...base,
context: [...(base.context ?? []), imported, terrain],
columns: [...(base.columns ?? []), column],
stairs: [...(base.stairs ?? []), massive],
};
}
/** Signiertes Volumen je OBJ-Objekt ({@code o}-Zeilen), aus den Weltkoordinaten der Datei. */
function objVolumes(obj: string): Map<string, number> {
const verts: number[][] = [];
const out = new Map<string, number>();
let cur = "";
for (const l of obj.split("\n")) {
if (l.startsWith("v ")) verts.push(l.slice(2).trim().split(/\s+/).map(Number));
else if (l.startsWith("o ")) {
cur = l.slice(2).trim();
out.set(cur, 0);
} else if (l.startsWith("f ")) {
const [a, b, c] = l.slice(2).trim().split(/\s+/).map((i) => verts[Number(i) - 1]);
const v =
a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0]);
out.set(cur, (out.get(cur) ?? 0) + v / 6);
}
}
return out;
}
describe("orientOutward", () => {
it("dreht einen innen gewickelten Würfel nach aussen und gleicht gemischte Wicklung an", () => {
const pos = CUBE_POS;
const mixed = CUBE_IDX.slice();
// ein Dreieck umdrehen ⇒ widersprüchliche Wicklung
[mixed[1], mixed[2]] = [mixed[2], mixed[1]];
const inward: number[] = [];
for (let i = 0; i < CUBE_IDX.length; i += 3) inward.push(CUBE_IDX[i], CUBE_IDX[i + 2], CUBE_IDX[i + 1]);
const vol = (idx: number[]) => {
let v = 0;
for (let i = 0; i < idx.length; i += 3) {
const [a, b, c] = [idx[i] * 3, idx[i + 1] * 3, idx[i + 2] * 3];
v +=
pos[a] * (pos[b + 1] * pos[c + 2] - pos[b + 2] * pos[c + 1]) -
pos[a + 1] * (pos[b] * pos[c + 2] - pos[b + 2] * pos[c]) +
pos[a + 2] * (pos[b] * pos[c + 1] - pos[b + 1] * pos[c]);
}
return v / 6;
};
expect(vol(CUBE_IDX)).toBeCloseTo(8, 9);
expect(vol(orientOutward(pos, inward))).toBeCloseTo(8, 9);
expect(vol(orientOutward(pos, mixed))).toBeCloseTo(8, 9);
});
});
describe("Mesh-Export vollständig", () => {
const project = withContext(sampleProject);
it("Achsen rechtshändig: Norden (Modell +y) liegt bei −Z, Höhe bei Y, Ost bei +X — OBJ, STL und glTF", () => {
const obj = exportObj(sampleProject);
const zs = obj.split("\n").filter((l) => l.startsWith("v ")).map((l) => Number(l.split(" ")[3]));
const ys = obj.split("\n").filter((l) => l.startsWith("v ")).map((l) => Number(l.split(" ")[2]));
// Das Beispielhaus liegt bei y = 0 … 4 (Norden), Höhe bis über das Dach.
expect(Math.max(...zs)).toBeLessThan(0.7);
expect(Math.min(...zs)).toBeLessThan(-3.9);
expect(Math.min(...ys)).toBeGreaterThan(-0.5);
expect(Math.max(...ys)).toBeGreaterThan(4);
// STL: gleiche Spanne
const stlZ = exportStl(sampleProject)
.split("\n")
.filter((l) => l.startsWith("vertex "))
.map((l) => Number(l.split(" ")[3]));
expect(Math.min(...stlZ)).toBeCloseTo(Math.min(...zs), 6);
// glTF: Positionen min/max aller Knoten
const g = glbJson(exportGlb(sampleProject));
const minZ = Math.min(...g.accessors.filter((a) => a.min).map((a) => a.min![2]));
expect(minZ).toBeCloseTo(Math.min(...zs), 4);
});
it("alle Bauteile haben ein positives Volumen (Wicklung nach aussen) in OBJ", () => {
const vols = objVolumes(exportObj(project));
expect(vols.size).toBeGreaterThan(10);
for (const [name, v] of vols) {
// Offene Flächen (Gelände) haben kein Volumen.
if (name.startsWith("Gelaende_")) continue;
expect(v, name).toBeGreaterThan(0);
}
expect(vols.get("Kontext_IM1")).toBeCloseTo(8, 6);
});
it("Dächer, Treppen, Stützen, Kontext und Gelände sind Knoten mit Bauteil-id", () => {
const g = glbJson(exportGlb(project));
const by = (type: string) => g.nodes.filter((n) => n.extras?.type === type).map((n) => n.extras!.id);
expect(by("roof")).toEqual((project.roofs ?? []).map((r) => r.id));
expect(by("stair")).toEqual((project.stairs ?? []).map((s) => s.id));
expect(by("column")).toEqual(["C1"]);
expect(by("context")).toEqual(["IM1"]);
expect(by("terrain")).toEqual(["TM1"]);
for (const n of g.nodes.filter((x) => x.extras && x.extras.type !== "level")) expect(nodeTris(g, n)).toBeGreaterThan(0);
});
it("importiertes Mesh trägt seine Farbe (linear umgerechnet), Gelände die Grundfarbe", () => {
const g = glbJson(exportGlb(project));
const node = g.nodes.find((n) => n.extras?.id === "IM1")!;
const mat = g.meshes[node.mesh!].primitives[0].material;
const c = g.materials[mat].pbrMetallicRoughness.baseColorFactor;
expect(c[0]).toBeCloseTo(1, 6);
expect(c[1]).toBeCloseTo(0, 6);
expect(c[2]).toBeCloseTo(0, 6);
});
it("je Öffnung ein Knoten (Fenster_/Tuer_) mit Glas bzw. Rahmen; kein Sammelknoten mehr", () => {
const g = glbJson(exportGlb(project));
const ops = project.openings ?? [];
expect(ops.length).toBeGreaterThan(2);
for (const op of ops) {
const n = g.nodes.find((x) => x.extras?.id === op.id);
expect(n, op.id).toBeDefined();
expect(n!.extras!.type).toBe(op.kind);
expect(n!.name).toBe(`${op.kind === "window" ? "Fenster" : "Tuer"}_${op.id}`);
}
expect(g.nodes.some((n) => n.extras?.type === "glazing" || n.extras?.type === "frame")).toBe(false);
});
it("Dreieckszahl je Bauteilart = Summe der 3D-Ableitungen (Dach, Treppe, Stütze, Öffnungsteile)", () => {
const g = glbJson(exportGlb(project));
const tris = (type: string) => g.nodes.filter((n) => n.extras?.type === type).reduce((s, n) => s + nodeTris(g, n), 0);
const meshTris = (ms: { indices: number[] }[]) => ms.reduce((s, m) => s + m.indices.length / 3, 0);
expect(tris("roof")).toBe(meshTris(emitRoofs(project)));
expect(tris("column")).toBe(meshTris(emitColumns(project)));
expect(tris("window") + tris("door")).toBe(meshTris(emitOpeningMeshes(project, "mittel")));
const stairMeshes = meshTris(emitStairMeshes(project)) + meshTris(emitStairRailings(project));
// Stufen-Prismen: jede Stufe wird zu einem Prisma (2 Kappen + Mantel) — mindestens die Mesh-Dreiecke.
expect(emitStairs(project).length).toBeGreaterThan(0);
expect(tris("stair")).toBeGreaterThanOrEqual(stairMeshes + emitStairs(project).length * 12);
// OBJ und glTF enthalten dieselben Dreiecke
const faces = exportObj(project).split("\n").filter((l) => l.startsWith("f ")).length;
const all = g.nodes.reduce((s, n) => s + nodeTris(g, n), 0);
expect(all).toBe(faces);
});
it("openingParts:false / context:false lassen die Teile weg", () => {
const g = glbJson(exportGlb(project, { openingParts: false, context: false }));
expect(g.nodes.some((n) => n.extras?.type === "window" || n.extras?.type === "door")).toBe(false);
expect(g.nodes.some((n) => n.extras?.type === "context" || n.extras?.type === "terrain")).toBe(false);
expect(g.nodes.some((n) => n.extras?.type === "roof")).toBe(true);
});
it("GLB und .gltf bestehen den Khronos-Validator ohne Fehler", async () => {
const r1 = await validator.validateBytes(exportGlb(project), { maxIssues: 50 });
expect(r1.issues.messages.filter((m) => m.severity === 0)).toEqual([]);
const r2 = await validator.validateString(exportGltf(project), { maxIssues: 50 });
expect(r2.issues.numErrors).toBe(0);
});
});
+7 -4
View File
@@ -9,6 +9,9 @@ import "../engine/fileioWasm.setup";
import { exportObj, exportStl } from "./exportMesh";
import type { Project, Wall, Ceiling, ExtrudedSolid, Opening } from "../model/types";
/** Nur die Wand (ohne Rahmen/Glas der Öffnung): die Tests zählen die Dreiecke des ausgeschnittenen Wandkörpers. */
const WALL_ONLY = { openingParts: false };
/** Gemeinsame Ressourcen-Basis (Komponente/Wandtyp/Deckentyp/Geschoss/Ebene). */
function baseProject(): Project {
return {
@@ -262,14 +265,14 @@ describe("exportStl — ASCII-STL-Export", () => {
// (= Rust-Zerlegung `extrude_layer_segment_with_holes`): 8 solide Langseiten-
// Teilrechtecke (3×3-Gitter minus Loch) × 2 Seiten × 2 Dreiecke = 32,
// + Deckel/Boden/2 Stirnkappen = 8, + 4 Laibungen × 2 = 8 → 48 Dreiecke.
const stl = exportStl(projectWithOpening("window"));
const stl = exportStl(projectWithOpening("window"), WALL_ONLY);
const facetCount = stl.split("\n").filter((l) => l.startsWith("facet normal")).length;
expect(facetCount).toBe(48);
// Die volle Box hätte NUR Ecken bei y∈{0,2.6}, x∈{0,5}. Der Ausschnitt
// führt echte Vertices an den Loch-Rändern ein — Beweis, dass das Loch
// wirklich in der Fläche steckt (nicht bloss eine übergelegte Scheibe).
const verts = parseObjVertices(exportObj(projectWithOpening("window")));
const verts = parseObjVertices(exportObj(projectWithOpening("window"), WALL_ONLY));
const near = (a: number, b: number) => Math.abs(a - b) < 1e-6;
expect(verts.some((v) => near(v[1], 0.9))).toBe(true); // Brüstungs-OK
expect(verts.some((v) => near(v[1], 2.4))).toBe(true); // Sturz-UK
@@ -283,10 +286,10 @@ describe("exportStl — ASCII-STL-Export", () => {
// Tür [x 2..3] × [y 0..2.1]: Boden bekommt die Lücke [2,3] (statt einer
// unteren Laibung) → 5 Langseiten-Teilrechtecke × 2 × 2 = 20, Deckel(1)=2,
// Boden(2 Streifen)=4, 2 Stirnkappen=4, 3 Laibungen (links/rechts/oben)=6 → 36.
const stl = exportStl(projectWithOpening("door"));
const stl = exportStl(projectWithOpening("door"), WALL_ONLY);
const facetCount = stl.split("\n").filter((l) => l.startsWith("facet normal")).length;
expect(facetCount).toBe(36);
const verts = parseObjVertices(exportObj(projectWithOpening("door")));
const verts = parseObjVertices(exportObj(projectWithOpening("door"), WALL_ONLY));
const near = (a: number, b: number) => Math.abs(a - b) < 1e-6;
// Sturz-UK bei y=2.1 vorhanden, aber KEIN Brüstungsvertex (Tür sitzt am Boden).
expect(verts.some((v) => near(v[1], 2.1))).toBe(true);
+140 -71
View File
@@ -30,10 +30,18 @@
// gunsten der pure-Modul-Architektur — ehrlich dokumentiert, kein
// Stillschweigen.
//
// ACHSEN-KONVENTION: identisch zur bestehenden 3D-Pick-/Highlight-Geometrie
// (siehe `selectionHighlightLines` in toWalls3d.ts): Modell (x, y) → Welt
// (x, Höhe, y), Y-UP, rechtshändig. Ein Weltvertex (vx,vy,vz) entspricht also
// (Modell-x, Meter-Höhe, Modell-y) — exakt wie im 3D-Viewer.
// ACHSEN-KONVENTION (intern, Weg zum Schreiber): Modell (x, y, z-hoch) → Welt (x, z, y) wie die
// Pick-/Highlight-Geometrie in toWalls3d.ts (`selectionHighlightLines`). Das ist eine Spiegelung
// des Modells; der Rust-Schreiber stellt für ALLE Formate (OBJ, STL, glTF) die Rechtshändigkeit
// her: Gesamtabbildung Modell (x, y, z-hoch) → Datei (x, z, −y), Norden = −Z.
//
// WEITERE BAUTEILE ([C11], 28.10.): Dächer, Treppen (Tritte, Laufplatte, Handlauf), Stützen,
// Öffnungsteile (je Öffnung ein Knoten), Gelände und importierte Kontext-Meshes. Quelle sind
// dieselben `emit*`-Ableitungen wie im 3D-Viewer (`projectToModel3d`). Diese liefern keine
// Bauteil-ids; deshalb wird jede Ableitung je Bauteil mit einem Projekt aufgerufen, das nur dieses
// Bauteil enthält (reines Lesen, `src/plan` bleibt unverändert). Die Ableitungen schreiben keine
// verlässliche Wicklung (render3d zeichnet doppelseitig): {@link orientOutward} richtet jedes
// geschlossene Teil nach aussen aus.
import type { Project, Vec2 } from "../model/types";
import { getFloor } from "../model/types";
@@ -42,7 +50,13 @@ import type { RWall } from "../plan/toWalls3d";
import { wallCutMeshes, type CutMesh } from "../plan/wallMeshCut";
import { triangulate } from "../plan/glPlan/glPlanCompile";
import { emitOpeningMeshes } from "../plan/toWalls3d/openings";
import { emitRoofs } from "../plan/toWalls3d/roofs";
import { emitColumns } from "../plan/toWalls3d/columns";
import { emitStairMeshes, emitStairRailings, emitStairs } from "../plan/toWalls3d/stairs";
import type { RMesh } from "../plan/toWalls3d/shared";
import { IMPORTED_RGB, TERRAIN_RGB, hexToRgb } from "../plan/toWalls3d/shared";
import { fileio } from "../engine/fileioWasm";
import { orientOutward } from "./meshOrient";
/**
* Ein Teil-Mesh mit EINEM Material und LOKALEN (0-basierten) Vertex-/Dreiecks-Indizes. Der Rust-Schreiber
@@ -57,10 +71,10 @@ interface MeshPrim {
indices: number[];
}
/** Eine Mesh-Gruppe = ein Bauteil-Vorkommen (Wand/Decke/Extrusion/Öffnungsteile) mit ≥ 1 Teil-Mesh. */
/** Eine Mesh-Gruppe = ein Bauteil-Vorkommen (Wand, Decke, Dach, Treppe, Öffnung …) mit ≥ 1 Teil-Mesh. */
interface MeshGroup {
name: string;
/** Bauteilart für glTF-`extras` ("wall", "slab", "extrusion", "glazing", "frame"). */
/** Bauteilart für glTF-`extras` ("wall", "slab", "extrusion", "roof", "stair", "column", "window", "door", "terrain", "context"). */
kind: string;
/** Bauteil-id im Modell ("" bei Sammelgruppen). */
id: string;
@@ -231,6 +245,30 @@ function pushPrism(
}
}
/**
* Hängt ein Modell-Mesh (x, y, z-hoch) an ein Teil-Mesh: Achsen nach Welt (x, z, y) und Wicklung
* nach aussen. `closed`: geschlossener Körper ⇒ {@link orientOutward}; sonst (Gelände, offene
* Importe) bleibt die Wicklung des Modells erhalten — die Achsenspiegelung kehrt sie um.
*/
function appendModelMesh(prim: MeshPrim, positions: readonly number[], indices: readonly number[], closed: boolean): void {
const pos: number[] = [];
for (let i = 0; i + 2 < positions.length; i += 3) pos.push(positions[i], positions[i + 2], positions[i + 1]);
const nv = pos.length / 3;
const tri: number[] = [];
for (let i = 0; i + 2 < indices.length; i += 3) {
const a = indices[i];
const b = indices[i + 1];
const c = indices[i + 2];
// Indizes ausserhalb (kaputter Import) und entartete Dreiecke weglassen.
if (!(a >= 0 && a < nv && b >= 0 && b < nv && c >= 0 && c < nv)) continue;
tri.push(a, c, b);
}
const idx = closed ? orientOutward(pos, tri) : tri;
const base = prim.positions.length / 3;
for (const v of pos) prim.positions.push(v);
for (const i of idx) prim.indices.push(base + i);
}
type Rgb = [number, number, number];
/** Material der Szene: Farbe sRGB 0..1, `rgba[3]` < 1 = transparent (Glas). */
@@ -278,27 +316,19 @@ const OPENING_PART_NAMES: Array<[Rgb, string]> = [
];
const sameRgb = (a: readonly number[], b: readonly number[]) => a.length === 3 && b.length === 3 && a.every((v, i) => Math.abs(v - b[i]) < 1e-9);
/** Vorzeichen des Volumens eines Dreiecks-Meshes (Weltkoordinaten): < 0 = Wicklung zeigt nach innen. */
function signedVolume(pos: readonly number[], idx: readonly number[]): number {
let v = 0;
for (let i = 0; i < idx.length; i += 3) {
const a = idx[i] * 3;
const b = idx[i + 1] * 3;
const c = idx[i + 2] * 3;
v +=
pos[a] * (pos[b + 1] * pos[c + 2] - pos[b + 2] * pos[c + 1]) -
pos[a + 1] * (pos[b] * pos[c + 2] - pos[b + 2] * pos[c]) +
pos[a + 2] * (pos[b] * pos[c + 1] - pos[b + 1] * pos[c]);
}
return v;
/** Was in die Szene kommt. Alles standardmässig an (vollständiges 3D-Modell). */
export interface MeshOptions {
/** Verglasung und Rahmenteile je Öffnung als eigener Knoten (Standard: ja). */
openingParts?: boolean;
/** Gelände und importierte Kontext-Meshes (IFC/DXF) mitnehmen (Standard: ja). */
context?: boolean;
}
/**
* Baut alle Mesh-Gruppen (Wände, Decken, Extrusionen; mit `parts` zusätzlich Verglasung und
* Rahmenteile der Öffnungen) und die Materialtabelle. OBJ/STL bleiben beim Bestand (`parts` aus, nur
* Dreiecke, Materialien ungenutzt); glTF nimmt die Öffnungsteile mit, damit Fenster Glas haben.
* Baut alle Mesh-Gruppen (Wände, Decken, Extrusionen, Dächer, Treppen, Stützen, Öffnungsteile,
* Kontext-Meshes) und die Materialtabelle.
*/
function buildScene(project: Project, parts: boolean): MeshScene {
function buildScene(project: Project, opts: MeshOptions = {}): MeshScene {
const groups: MeshGroup[] = [];
const mats = new Materials();
const { walls, slabs } = pickGeometry(project);
@@ -350,37 +380,74 @@ function buildScene(project: Project, parts: boolean): MeshScene {
groups.push(g);
}
if (parts) {
// Öffnungsteile haben keine Bauteil-id (emitOpeningMeshes liefert nur Quader mit Farbe): Glas und
// Rahmenteile je EIN Sammelknoten, die Quader je Material zu einem Teil-Mesh zusammengefasst.
const glazing = newGroup("Verglasung", "glazing", "", -1);
const frames = newGroup("Oeffnungsteile", "frame", "", -1);
const prims = new Map<string, MeshPrim>();
for (const m of emitOpeningMeshes(project, "mittel")) {
const glass = sameRgb(m.color, GLASS_COLOR);
const name = glass ? "Glas" : (OPENING_PART_NAMES.find(([c]) => sameRgb(c, m.color))?.[1] ?? "Oeffnungsteil");
const group = glass ? glazing : frames;
const key = `${glass}|${name}`;
let prim = prims.get(key);
if (!prim) {
// Glas transparent und glatt (BLEND), Rahmen matt.
const mat = glass ? mats.get(name, m.color, 0.35, 0, 0.05) : mats.get(name, m.color, 1, 0, 0.6);
prim = newPrim(group, mat);
prims.set(key, prim);
}
// Modell (x, y, z-hoch) → Welt (x, z, y); danach Wicklung so, dass das Volumen positiv ist.
const pos: number[] = [];
for (let i = 0; i + 2 < m.positions.length; i += 3) pos.push(m.positions[i], m.positions[i + 2], m.positions[i + 1]);
let idx = m.indices;
if (signedVolume(pos, idx) < 0) {
idx = [];
for (let i = 0; i + 2 < m.indices.length; i += 3) idx.push(m.indices[i], m.indices[i + 2], m.indices[i + 1]);
}
const base = prim.positions.length / 3;
for (const p of pos) prim.positions.push(p);
for (const i of idx) prim.indices.push(base + i);
// Dächer, Stützen, Treppen: je Bauteil EIN Aufruf der 3D-Ableitung mit einem Projekt, das nur dieses
// Bauteil enthält — so tragen die Meshes die Bauteil-id (die Ableitungen liefern keine).
const addMeshes = (g: MeshGroup, meshes: RMesh[], name: string, closed = true) => {
for (const m of meshes) {
if (m.indices.length === 0) continue;
appendModelMesh(newPrim(g, mats.get(name, m.color)), m.positions, m.indices, closed);
}
};
for (const roof of project.roofs ?? []) {
const g = newGroup(`Dach_${sanitizeName(roof.id)}`, "roof", roof.id, levelOf(roof.floorId));
addMeshes(g, emitRoofs({ ...project, roofs: [roof] }), "Dach");
groups.push(g);
}
for (const col of project.columns ?? []) {
const g = newGroup(`Stuetze_${sanitizeName(col.id)}`, "column", col.id, levelOf(col.floorId));
addMeshes(g, emitColumns({ ...project, columns: [col] }), componentName(col.componentId, "Stuetze"));
groups.push(g);
}
for (const stair of project.stairs ?? []) {
const one: Project = { ...project, stairs: [stair] };
const g = newGroup(`Treppe_${sanitizeName(stair.id)}`, "stair", stair.id, levelOf(stair.floorId));
for (const s of emitStairs(one)) {
const outline: Vec2[] = s.outline.map(([x, y]) => ({ x, y }));
pushPrism(newPrim(g, mats.get("Treppe", s.color)), outline, s.zBottom, s.zTop);
}
addMeshes(g, emitStairMeshes(one), "Treppe");
addMeshes(g, emitStairRailings(one), "Handlauf");
groups.push(g);
}
// Öffnungsteile: je Öffnung ein Knoten (Name Fenster_<id>/Tuer_<id>) mit Glas und den Rahmenteilen als
// Teil-Meshes je Material. Auch hier die Ableitung nur mit der Wirtswand und dieser Öffnung.
if (opts.openingParts ?? true) {
for (const op of project.openings ?? []) {
const host = project.walls.find((w) => w.id === op.hostWallId);
if (!host) continue;
const parts = emitOpeningMeshes({ ...project, walls: [host], openings: [op] }, "mittel");
if (parts.length === 0) continue;
const g = newGroup(`${op.kind === "window" ? "Fenster" : "Tuer"}_${sanitizeName(op.id)}`, op.kind, op.id, levelOf(host.floorId));
const prims = new Map<string, MeshPrim>();
for (const m of parts) {
const glass = sameRgb(m.color, GLASS_COLOR);
const name = glass ? "Glas" : (OPENING_PART_NAMES.find(([c]) => sameRgb(c, m.color))?.[1] ?? "Oeffnungsteil");
let prim = prims.get(name);
if (!prim) {
// Glas transparent und glatt (BLEND), Rahmen matt.
const mat = glass ? mats.get(name, m.color, 0.35, 0, 0.05) : mats.get(name, m.color, 1, 0, 0.6);
prim = newPrim(g, mat);
prims.set(name, prim);
}
appendModelMesh(prim, m.positions, m.indices, true);
}
groups.push(g);
}
}
// Gelände und importierte Meshes (IFC/DXF): Farbe der Quelle, falls gesetzt.
if (opts.context ?? true) {
for (const obj of project.context ?? []) {
if (obj.type !== "terrainMesh" && obj.type !== "importedMesh") continue;
if (obj.positions.length < 9 || obj.indices.length < 3) continue;
const terrain = obj.type === "terrainMesh";
const rgb: Rgb = !terrain && obj.color ? hexToRgb(obj.color, IMPORTED_RGB) : terrain ? TERRAIN_RGB : IMPORTED_RGB;
const g = newGroup(`${terrain ? "Gelaende" : "Kontext"}_${sanitizeName(obj.id)}`, terrain ? "terrain" : "context", obj.id, -1);
const prim = newPrim(g, mats.get(terrain ? "Gelaende" : obj.name || "Kontext", rgb));
appendModelMesh(prim, obj.positions, obj.indices, false);
groups.push(g);
}
for (const g of [glazing, frames]) if (g.prims.length > 0) groups.push(g);
}
return {
@@ -420,9 +487,9 @@ function encodeScene(scene: MeshScene, byLevel: boolean): [Float64Array, string]
}
/** Ruft eine Rust-Bindung; leeres Ergebnis (kaputter Puffer) wird zum Fehler mit dem Grund. */
function write<T extends string | Uint8Array>(project: Project, parts: boolean, byLevel: boolean, run: (m: ReturnType<typeof fileio>, buf: Float64Array, strings: string) => T): T {
function write<T extends string | Uint8Array>(project: Project, opts: MeshOptions, byLevel: boolean, run: (m: ReturnType<typeof fileio>, buf: Float64Array, strings: string) => T): T {
const m = fileio();
const [buf, strings] = encodeScene(buildScene(project, parts), byLevel);
const [buf, strings] = encodeScene(buildScene(project, opts), byLevel);
const out = run(m, buf, strings);
if (out.length === 0) {
const why = m.export_mesh_check_flat(buf, strings);
@@ -432,41 +499,43 @@ function write<T extends string | Uint8Array>(project: Project, parts: boolean,
}
/**
* Baut einen vollständigen Wavefront-OBJ-String des 3D-Gebäudemodells (Meter, Y-up — siehe Moduldoc).
* Ein `o`-Objekt je Bauteil-Vorkommen (Wand/Decke/Extrusion). Leeres Projekt ⇒ gültige Datei nur mit
* Baut einen vollständigen Wavefront-OBJ-String des 3D-Gebäudemodells (Meter, Y-up rechtshändig:
* Modell (x, y, z-hoch) → (x, z, −y), siehe Moduldoc). Ein `o`-Objekt je Bauteil-Vorkommen (Wand, Decke,
* Extrusion, Dach, Treppe, Stütze, Fenster/Tür, Kontext-Mesh). Leeres Projekt ⇒ gültige Datei nur mit
* Kopf-Kommentaren. Verlangt das geladene Format-Modul (`await loadFileio()`).
*/
export function exportObj(project: Project): string {
return write(project, false, false, (m, b, s) => m.export_mesh_obj_flat(b, s));
export function exportObj(project: Project, opts: MeshOptions = {}): string {
return write(project, opts, false, (m, b, s) => m.export_mesh_obj_flat(b, s));
}
/**
* Baut einen vollständigen ASCII-STL-String (Meter, dieselbe Achsen-Konvention wie {@link exportObj});
* je Dreieck eine Facettennormale. Leeres Projekt ⇒ gültiges leeres `solid`-Gerüst. Verlangt das
* geladene Format-Modul (`await loadFileio()`).
* Baut einen vollständigen ASCII-STL-String (Meter, dieselben Achsen wie {@link exportObj}); je Dreieck
* eine Facettennormale. Leeres Projekt ⇒ gültiges leeres `solid`-Gerüst. Verlangt das geladene
* Format-Modul (`await loadFileio()`).
*/
export function exportStl(project: Project): string {
return write(project, false, false, (m, b, s) => m.export_mesh_stl_flat(b, s));
export function exportStl(project: Project, opts: MeshOptions = {}): string {
return write(project, opts, false, (m, b, s) => m.export_mesh_stl_flat(b, s));
}
/** Optionen des glTF-Exports. */
export interface GltfOptions {
export interface GltfOptions extends MeshOptions {
/** Geschoss als Eltern-Knoten der Bauteile (Standard: ja). */
byLevel?: boolean;
}
/**
* glTF 2.0 binär (GLB) für Blender, Twinmotion, Enscape, Web-Viewer. Ein Knoten je Bauteil (Name
* `Wand_<id>`/`Decke_<id>`/`Extrusion_<id>`, `extras` = Typ + id), PBR-Materialien mit der Farbe der
* Bauteilschicht, Verglasung transparent (`BLEND`), Geschosse als Eltern-Knoten. Meter; die Achsen
* folgen der glTF-Konvention (rechtshändig, Y-up): Modell (x, y, z-hoch) → (x, z, −y), Norden = −Z.
* Verlangt das geladene Format-Modul (`await loadFileio()`).
* `Wand_<id>`, `Decke_<id>`, `Dach_<id>`, `Treppe_<id>`, `Stuetze_<id>`, `Fenster_<id>`, `Tuer_<id>`,
* `Extrusion_<id>`, `Kontext_<id>`, `Gelaende_<id>`; `extras` = Typ + id), PBR-Materialien mit der
* Farbe der Bauteilschicht, Verglasung transparent (`BLEND`), Geschosse als Eltern-Knoten. Meter;
* rechtshändig, Y-up: Modell (x, y, z-hoch) → (x, z, −y), Norden = −Z. Verlangt das geladene
* Format-Modul (`await loadFileio()`).
*/
export function exportGlb(project: Project, opts: GltfOptions = {}): Uint8Array {
return write(project, true, opts.byLevel ?? true, (m, b, s) => m.export_mesh_glb_flat(b, s));
return write(project, opts, opts.byLevel ?? true, (m, b, s) => m.export_mesh_glb_flat(b, s));
}
/** Wie {@link exportGlb}, aber als `.gltf` (JSON, Puffer als Base64-Data-URI eingebettet). */
export function exportGltf(project: Project, opts: GltfOptions = {}): string {
return write(project, true, opts.byLevel ?? true, (m, b, s) => m.export_mesh_gltf_flat(b, s));
return write(project, opts, opts.byLevel ?? true, (m, b, s) => m.export_mesh_gltf_flat(b, s));
}
+164
View File
@@ -0,0 +1,164 @@
// Basismengen für den IFC-Export ([B5], 28.10.): reine Rechnung aus der Geometrie, Werte nachrechenbar.
import { describe, it, expect } from "vitest";
import type { RWall } from "../plan/toWalls3d";
import {
columnQuantities,
flightQuantities,
meshVolume,
openingQuantities,
railingQuantities,
ringArea,
ringPerimeter,
roofQuantities,
slabQuantities,
wallQuantities,
} from "./ifcQuantities";
const byName = (q: { name: string; value: number }[]) => Object.fromEntries(q.map((x) => [x.name, x.value]));
/** Wandband: Quader `len` lang entlang x ab `x0`, Dicke, Höhe ab `base`. */
function band(x0: number, len: number, thickness: number, height: number, base = 0, topDrop?: [number, number]): RWall {
return { start: [x0, 0], end: [x0 + len, 0], thickness, height, baseElevation: base, color: [1, 1, 1], layers: [], wallId: "W", ...(topDrop ? { topDrop } : {}) };
}
describe("Hilfen", () => {
it("Ringfläche (unabhängig vom Umlaufsinn) und Umfang", () => {
const sq = [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 3 }, { x: 0, y: 3 }];
expect(ringArea(sq)).toBe(12);
expect(ringArea([...sq].reverse())).toBe(12);
expect(ringPerimeter(sq)).toBe(14);
expect(ringArea([])).toBe(0);
});
it("Mesh-Volumen eines Würfels, unabhängig von der Wicklung", () => {
const pos = [0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 2, 0, 0, 0, 2, 2, 0, 2, 2, 2, 2, 0, 2, 2];
const idx = [0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 0, 1, 5, 0, 5, 4, 1, 2, 6, 1, 6, 5, 2, 3, 7, 2, 7, 6, 3, 0, 4, 3, 4, 7];
expect(meshVolume(pos, idx)).toBeCloseTo(8, 12);
const rev: number[] = [];
for (let i = 0; i < idx.length; i += 3) rev.push(idx[i], idx[i + 2], idx[i + 1]);
expect(meshVolume(pos, rev)).toBeCloseTo(8, 12);
expect(meshVolume([], [])).toBe(0);
});
});
describe("Wand", () => {
const wall = { start: { x: 0, y: 0 }, end: { x: 5, y: 0 } };
it("eine Schicht: Länge, Dicke, Höhe, Seitenfläche, Volumen; Öffnung wird netto abgezogen", () => {
const q = byName(
wallQuantities(wall, [band(0, 5, 0.3, 2.6)], [{ from: 1, to: 2, zBottom: 0.9, zTop: 2.1 }]),
);
expect(q.Length).toBe(5);
expect(q.Width).toBeCloseTo(0.3, 12);
expect(q.Height).toBeCloseTo(2.6, 12);
expect(q.GrossSideArea).toBeCloseTo(13, 12);
expect(q.NetSideArea).toBeCloseTo(13 - 1.2, 12);
expect(q.GrossVolume).toBeCloseTo(13 * 0.3, 12);
expect(q.NetVolume).toBeCloseTo((13 - 1.2) * 0.3, 12);
});
it("mehrere Schichten: Dicke und Volumen summieren, Öffnung schneidet jede Schicht", () => {
// Aussenschicht 0.2 (Achse −0.15 … ), Dämmung 0.1: Mittellinien bei y = −0.05 und +0.1
const a = { ...band(0, 5, 0.2, 2.6), start: [0, -0.05], end: [5, -0.05] } as RWall;
const b = { ...band(0, 5, 0.1, 2.6), start: [0, 0.1], end: [5, 0.1] } as RWall;
const q = byName(wallQuantities(wall, [a, b], [{ from: 2, to: 3, zBottom: 0, zTop: 2.1 }]));
expect(q.Width).toBeCloseTo(0.3, 12);
expect(q.GrossVolume).toBeCloseTo(5 * 0.3 * 2.6, 12);
expect(q.NetVolume).toBeCloseTo((5 * 2.6 - 1 * 2.1) * 0.3, 12);
});
it("innere Schicht endet unter der Decke: Seitenfläche mit voller Wandhöhe, Volumen je Schicht", () => {
const outer = band(0, 5, 0.2, 2.6);
const inner = band(0.1, 4.8, 0.1, 2.3);
const q = byName(wallQuantities(wall, [outer, inner], []));
expect(q.Height).toBeCloseTo(2.6, 12);
expect(q.GrossSideArea).toBeCloseTo(13, 12);
expect(q.GrossVolume).toBeCloseTo(5 * 0.2 * 2.6 + 4.8 * 0.1 * 2.3, 12);
});
it("Gehrung/Anschluss: kürzeres Band ändert Volumen, nicht die Wandlänge", () => {
const q = byName(wallQuantities(wall, [band(0.1, 4.8, 0.3, 2.6)], []));
expect(q.Length).toBe(5);
expect(q.GrossVolume).toBeCloseTo(4.8 * 0.3 * 2.6, 12);
expect(q.NetVolume).toBeCloseTo(q.GrossVolume, 12);
});
it("schräge Oberkante: Höhe fehlt (nicht konstant), Fläche und Volumen mit mittlerer Höhe", () => {
const q = byName(wallQuantities(wall, [band(0, 5, 0.3, 3, 0, [0, 1])], []));
expect(q.Height).toBeUndefined();
expect(q.GrossSideArea).toBeCloseTo(5 * 2.5, 12);
expect(q.GrossVolume).toBeCloseTo(5 * 0.3 * 2.5, 12);
});
it("Mesh-Wand: Netto-Volumen aus dem Netz, Brutto bleibt der Quader", () => {
const q = byName(wallQuantities(wall, [band(0, 5, 0.3, 2.6)], [{ from: 1, to: 2, zBottom: 0.9, zTop: 2.1 }], 3.5));
expect(q.NetVolume).toBe(3.5);
expect(q.GrossVolume).toBeCloseTo(13 * 0.3, 12);
});
it("Öffnung grösser als die Wand: Netto nie negativ; Öffnung ausserhalb zieht nichts ab", () => {
const q = byName(wallQuantities(wall, [band(0, 5, 0.3, 2.6)], [{ from: -1, to: 6, zBottom: -1, zTop: 5 }, { from: 8, to: 9, zBottom: 0, zTop: 2 }]));
expect(q.NetSideArea).toBe(0);
expect(q.NetVolume).toBeCloseTo(0, 12);
});
it("keine Bänder: keine Mengen", () => {
expect(wallQuantities(wall, [], [])).toEqual([]);
});
});
describe("Decke, Dach, Stütze, Öffnung, Treppe", () => {
it("Decke: Fläche, Umfang, Dicke; Aussparung nur netto", () => {
const outline = [{ x: 0, y: 0 }, { x: 5, y: 0 }, { x: 5, y: 4 }, { x: 0, y: 4 }];
const hole = [{ x: 1, y: 1 }, { x: 2, y: 1 }, { x: 2, y: 2 }, { x: 1, y: 2 }];
const q = byName(slabQuantities(outline, [hole], 0.2));
expect(q.Width).toBeCloseTo(0.2, 12);
expect(q.Perimeter).toBe(18);
expect(q.GrossArea).toBe(20);
expect(q.NetArea).toBe(19);
expect(q.GrossVolume).toBeCloseTo(4, 12);
expect(q.NetVolume).toBeCloseTo(3.8, 12);
});
it("Dach: geneigte Fläche > Grundrissfläche (Satteldach 30°)", () => {
// Zwei Flächen 5 × 2 m Grundriss, 30° geneigt: je 5 × 2/cos(30°).
const h = Math.tan(Math.PI / 6) * 2;
const planes = [
[[0, 0, 0], [5, 0, 0], [5, 2, h], [0, 2, h]],
[[0, 4, 0], [0, 2, h], [5, 2, h], [5, 4, 0]],
] as [number, number, number][][];
const q = byName(roofQuantities(planes));
expect(q.ProjectedArea).toBeCloseTo(20, 9);
expect(q.GrossArea).toBeCloseTo(20 / Math.cos(Math.PI / 6), 9);
expect(q.NetArea).toBe(q.GrossArea);
});
it("Stütze 0.3 × 0.3 × 2.6", () => {
const fp = [{ x: 0, y: 0 }, { x: 0.3, y: 0 }, { x: 0.3, y: 0.3 }, { x: 0, y: 0.3 }];
const q = byName(columnQuantities(fp, 2.6));
expect(q.Length).toBe(2.6);
expect(q.CrossSectionArea).toBeCloseTo(0.09, 12);
expect(q.OuterSurfaceArea).toBeCloseTo(1.2 * 2.6, 12);
expect(q.NetSurfaceArea).toBeCloseTo(1.2 * 2.6 + 0.18, 12);
expect(q.GrossVolume).toBeCloseTo(0.09 * 2.6, 12);
expect(q.NetVolume).toBeCloseTo(q.GrossVolume, 12);
});
it("Fenster/Tür: Breite, Höhe, Umfang, Fläche", () => {
const q = byName(openingQuantities(1.2, 1.5));
expect(q.Width).toBe(1.2);
expect(q.Height).toBe(1.5);
expect(q.Perimeter).toBeCloseTo(5.4, 12);
expect(q.Area).toBeCloseTo(1.8, 12);
});
it("Lauf und Geländer", () => {
expect(byName(flightQuantities(3.4, 1.2))).toEqual({ Length: 3.4, GrossVolume: 1.2, NetVolume: 1.2 });
expect(byName(railingQuantities(5))).toEqual({ Length: 5 });
});
it("nie NaN/negativ: kaputte Eingaben ergeben 0", () => {
const q = openingQuantities(Number.NaN, -1);
for (const x of q) expect(Number.isFinite(x.value) && x.value >= 0).toBe(true);
});
});
+213
View File
@@ -0,0 +1,213 @@
// Basismengen (Qto_*BaseQuantities) für den IFC-Export ([B5], 28.10.): Längen, Flächen und Volumen
// aus derselben Geometrie, die in die Datei geschrieben wird — für Kostenplanung (eBKP-H/BKP) und
// Mengenermittlung. Reine Rechnung auf einfachen Eingaben (Bänder, Ringe, Netze), kein Zugriff auf
// das Projekt; `exportIfc.ts` sammelt und ruft sie auf, Rust schreibt die IfcElementQuantity.
//
// Netto = abzüglich Öffnungen (Wand, Decke). Fehlt einer Menge die Grundlage (z. B. Höhe bei schräger
// Wandoberkante: „nur angeben, wenn konstant“), lassen wir sie weg statt zu raten.
import type { Vec2 } from "../model/types";
import type { RWall } from "../plan/toWalls3d";
/** Eine Menge: Name nach IFC4-Vorlage, Art (Länge/Fläche/Volumen) und Wert (immer endlich und ≥ 0). */
export interface Qty {
name: string;
kind: "length" | "area" | "volume";
value: number;
}
/** Rundungsfehler und kaputte Eingaben (NaN) auf 0, nie negativ. */
const clean = (v: number): number => (Number.isFinite(v) && v > 0 ? v : 0);
const q = (name: string, kind: Qty["kind"], value: number): Qty => ({ name, kind, value: clean(value) });
const len = (name: string, v: number) => q(name, "length", v);
const area = (name: string, v: number) => q(name, "area", v);
const vol = (name: string, v: number) => q(name, "volume", v);
/** Fläche eines Rings (Shoelace, unabhängig vom Umlaufsinn); offener Ring, die Schlusskante gilt als gegeben. */
export function ringArea(pts: readonly Vec2[]): number {
let a = 0;
for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) a += pts[j].x * pts[i].y - pts[i].x * pts[j].y;
return Math.abs(a) / 2;
}
/** Umfang eines geschlossenen Rings. */
export function ringPerimeter(pts: readonly Vec2[]): number {
let p = 0;
for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) p += Math.hypot(pts[i].x - pts[j].x, pts[i].y - pts[j].y);
return p;
}
/** Volumen eines geschlossenen Dreiecks-Netzes (Betrag der Summe der Tetraeder-Volumen zum Ursprung). */
export function meshVolume(positions: readonly number[], indices: readonly number[]): number {
let v = 0;
for (let i = 0; i + 2 < indices.length; i += 3) {
const a = indices[i] * 3;
const b = indices[i + 1] * 3;
const c = indices[i + 2] * 3;
v +=
positions[a] * (positions[b + 1] * positions[c + 2] - positions[b + 2] * positions[c + 1]) -
positions[a + 1] * (positions[b] * positions[c + 2] - positions[b + 2] * positions[c]) +
positions[a + 2] * (positions[b] * positions[c + 1] - positions[b + 1] * positions[c]);
}
return Math.abs(v) / 6;
}
/** Öffnung einer Wand: Achs-Intervall (ab Wandanfang) und absolute Höhen. */
export interface Cutout {
from: number;
to: number;
zBottom: number;
zTop: number;
}
const overlap = (a0: number, a1: number, b0: number, b1: number): number => Math.max(0, Math.min(a1, b1) - Math.max(a0, b0));
/**
* Wand-Basismengen aus den Schicht-Bändern (dieselben wie im 3D) und den Öffnungen.
* • Length: Achslänge; Width: Gesamtdicke quer zur Achse; Height: nur bei konstanter Höhe.
* • GrossSideArea: Achslänge × Wandhöhe (schräge Oberkante: höchste mittlere Bandhöhe);
* NetSideArea: abzüglich der Öffnungsflächen.
* • GrossVolume: Summe der Band-Quader (Gehrungen/Anschlüsse stecken in den Bandlängen);
* NetVolume: abzüglich der Öffnungen je Band — oder `netVolume`, wenn die Wand als Netz mit schon
* ausgestanzten Öffnungen (und Laibungen) geschrieben wird.
*/
export function wallQuantities(
wall: { start: Vec2; end: Vec2 },
bands: readonly RWall[],
cutouts: readonly Cutout[],
netVolume?: number,
): Qty[] {
if (bands.length === 0) return [];
const axisLen = Math.hypot(wall.end.x - wall.start.x, wall.end.y - wall.start.y);
const ux = axisLen > 0 ? (wall.end.x - wall.start.x) / axisLen : 1;
const uy = axisLen > 0 ? (wall.end.y - wall.start.y) / axisLen : 0;
// Quer zur Achse: Ausdehnung aller Bänder entlang der linken Normalen (−uy, ux).
let nLo = Infinity;
let nHi = -Infinity;
let zMin = Infinity;
let zMax = -Infinity;
let sloped = false;
let gross = 0;
let tallest = 0;
for (const b of bands) {
const l = Math.hypot(b.end[0] - b.start[0], b.end[1] - b.start[1]);
const off = -(b.start[0] - wall.start.x) * uy + (b.start[1] - wall.start.y) * ux;
nLo = Math.min(nLo, off - b.thickness / 2);
nHi = Math.max(nHi, off + b.thickness / 2);
zMin = Math.min(zMin, b.baseElevation);
zMax = Math.max(zMax, b.baseElevation + b.height);
const drop = b.topDrop ? (b.topDrop[0] + b.topDrop[1]) / 2 : 0;
if (b.topDrop && (Math.abs(b.topDrop[0]) > 1e-9 || Math.abs(b.topDrop[1]) > 1e-9)) sloped = true;
gross += l * b.thickness * (b.height - drop);
tallest = Math.max(tallest, b.height - drop);
}
// Seitenfläche der Wandebene: innere Schichten enden oft unter der Decke (niedrigere Bänder), die Wand
// selbst reicht über die volle Höhe — bei konstanter Oberkante zählt die Gesamthöhe, bei schräger die
// höchste mittlere Bandhöhe.
const grossSide = axisLen * (sloped ? tallest : zMax - zMin);
let cutSide = 0;
let cutVolume = 0;
for (const c of cutouts) {
cutSide += (c.to - c.from) * overlap(c.zBottom, c.zTop, zMin, zMax);
for (const b of bands) {
const a0 = (b.start[0] - wall.start.x) * ux + (b.start[1] - wall.start.y) * uy;
const a1 = (b.end[0] - wall.start.x) * ux + (b.end[1] - wall.start.y) * uy;
const ox = overlap(Math.min(a0, a1), Math.max(a0, a1), c.from, c.to);
cutVolume += ox * overlap(c.zBottom, c.zTop, b.baseElevation, b.baseElevation + b.height) * b.thickness;
}
}
// Netto aus dem Netz kann den Band-Quader um Rundung/Gehrungsdetails überschreiten: Brutto nie unter Netto.
const net = netVolume ?? Math.max(0, gross - cutVolume);
gross = Math.max(gross, net);
const out: Qty[] = [len("Length", axisLen), len("Width", nHi - nLo)];
if (!sloped && zMax - zMin > 0) out.push(len("Height", zMax - zMin));
out.push(
area("GrossSideArea", grossSide),
area("NetSideArea", Math.max(0, grossSide - cutSide)),
vol("GrossVolume", gross),
vol("NetVolume", net),
);
return out;
}
/** Brutto-Volumen der Löcher in einem Band (für Netz-Wände ohne Netz-Volumen, s. `wallQuantities`). */
export function holeVolume(bands: readonly RWall[]): number {
let v = 0;
for (const b of bands) for (const h of b.holes ?? []) v += (h.to - h.from) * overlap(h.zBottom, h.zTop, b.baseElevation, b.baseElevation + b.height) * b.thickness;
return v;
}
/**
* Platten-Basismengen (Decke, Podest): Dicke, Umfang der Aussenkontur, Flächen und Volumen; Netto
* zieht die Aussparungen ab.
*/
export function slabQuantities(outline: readonly Vec2[], openings: readonly (readonly Vec2[])[], thickness: number): Qty[] {
const gross = ringArea(outline);
const net = Math.max(0, gross - openings.reduce((s, r) => s + ringArea(r), 0));
return [
len("Width", thickness),
len("Perimeter", ringPerimeter(outline)),
area("GrossArea", gross),
area("NetArea", net),
vol("GrossVolume", gross * thickness),
vol("NetVolume", net * thickness),
];
}
type Vec3 = readonly [number, number, number];
/**
* Dach-Basismengen aus den geneigten Dachflächen (Aussenseite): geneigte Fläche (brutto = netto, das
* Modell kennt keine Dachfenster/Aussparungen) und Grundrissprojektion.
*/
export function roofQuantities(planes: readonly (readonly Vec3[])[]): Qty[] {
let sloped = 0;
let projected = 0;
for (const pts of planes) {
// Newell: Vektorfläche des Polygons; Betrag = Fläche, z-Anteil = Projektion auf den Grundriss.
let nx = 0;
let ny = 0;
let nz = 0;
for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) {
const c = pts[j];
const d = pts[i];
nx += (c[1] - d[1]) * (c[2] + d[2]);
ny += (c[2] - d[2]) * (c[0] + d[0]);
nz += (c[0] - d[0]) * (c[1] + d[1]);
}
sloped += Math.hypot(nx, ny, nz) / 2;
projected += Math.abs(nz) / 2;
}
return [area("GrossArea", sloped), area("NetArea", sloped), area("ProjectedArea", projected)];
}
/** Stützen-Basismengen: Länge, Querschnitt, Mantel, Oberfläche und Volumen (keine Aussparungen). */
export function columnQuantities(footprint: readonly Vec2[], length: number): Qty[] {
const cross = ringArea(footprint);
const outer = ringPerimeter(footprint) * length;
return [
len("Length", length),
area("CrossSectionArea", cross),
area("OuterSurfaceArea", outer),
area("NetSurfaceArea", outer + 2 * cross),
vol("GrossVolume", cross * length),
vol("NetVolume", cross * length),
];
}
/** Tür-/Fenster-Basismengen (lichte Öffnung): Breite, Höhe, Umfang, Fläche. */
export function openingQuantities(width: number, height: number): Qty[] {
const w = clean(width);
const h = clean(height);
return [len("Width", w), len("Height", h), len("Perimeter", 2 * (w + h)), area("Area", w * h)];
}
/** Treppenlauf: Lauflänge entlang der Lauflinie und Volumen (keine Aussparungen). */
export function flightQuantities(length: number, volume: number): Qty[] {
return [len("Length", length), vol("GrossVolume", volume), vol("NetVolume", volume)];
}
/** Geländer: Länge. */
export function railingQuantities(length: number): Qty[] {
return [len("Length", length)];
}
+170
View File
@@ -0,0 +1,170 @@
// Treppen im IFC-Export ([B5], 28.10.): statt eines Fussabdruck-Quaders die Teile der Treppe wie im 3D —
// Läufe (IfcStairFlight), Podest (IfcSlab LANDING) und Handlauf/Pfosten (IfcRailing), zusammengefasst
// von der IfcStair (IfcRelAggregates). Quelle sind dieselben Ableitungen wie im 3D-Viewer
// (`emitStairs` Tritt-Prismen und Podest, `emitStairMeshes` glatte Ortbeton-Laufplatte,
// `emitStairRailings`), je Treppe mit einem Ein-Treppen-Projekt aufgerufen (die Ableitungen liefern keine
// ids). Dieses Modul sammelt und rechnet die Basismengen; die Entitäten schreibt Rust (`ifc_export.rs`, STAIR).
//
// Zuordnung der Tritt-Prismen: bei "L" ist das Podest das Prisma mit dem Umriss des Podest-Polygons der
// Treppengeometrie; Tritte bis zur Podest-Oberkante gehören zum ersten, die darüber zum zweiten Lauf.
// Gerade und Wendeltreppen haben einen Lauf (die Wendel-Mitte bleibt Teil davon, wie im 3D).
import type { Project, Stair, Vec2 } from "../model/types";
import { getStairType } from "../model/types";
import { stairVerticalExtent } from "../model/wall";
import { stairGeometry } from "../geometry/stair";
import { emitStairMeshes, emitStairRailings, emitStairs } from "../plan/toWalls3d/stairs";
import type { RSlab } from "../plan/toWalls3d";
import { orientOutward } from "./meshOrient";
import { flightQuantities, meshVolume, railingQuantities, ringArea, slabQuantities, type Qty } from "./ifcQuantities";
/** Ein Prisma (Profil in Welt-XY, Unterkante relativ zum Geschoss, Tiefe). */
export interface StairSolid {
pts: Vec2[];
zRel: number;
depth: number;
}
export interface StairFlightParts {
name: string;
risers: number;
treads: number;
riserHeight: number;
treadLength: number;
/** IfcStairFlightTypeEnum. */
predefined: "STRAIGHT" | "SPIRAL";
quantities: Qty[];
/** Entweder Prismen oder ein Dreiecks-Netz (IFC: x, y, z-hoch, Z relativ zum Geschoss). */
solids?: StairSolid[];
mesh?: { positions: number[]; indices: number[] };
}
export interface StairParts {
flights: StairFlightParts[];
landing: { name: string; pts: Vec2[]; zRel: number; depth: number; quantities: Qty[] } | null;
rail: { name: string; predefined: "HANDRAIL"; mesh: { positions: number[]; indices: number[] }; quantities: Qty[] } | null;
}
const EPS = 1e-6;
/** Gleicher Umriss (gleiche Punktmenge, auch bei anderer Reihenfolge/Startpunkt). */
function sameRing(a: readonly [number, number][], b: readonly Vec2[]): boolean {
if (a.length !== b.length) return false;
return a.every((p) => b.some((q) => Math.abs(p[0] - q.x) < EPS && Math.abs(p[1] - q.y) < EPS));
}
const centroid = (pts: readonly Vec2[]): Vec2 => ({
x: pts.reduce((s, p) => s + p.x, 0) / pts.length,
y: pts.reduce((s, p) => s + p.y, 0) / pts.length,
});
/** Netz (Modell x, y, z-hoch) nach IFC: Z relativ zum Geschoss, Wicklung nach aussen. */
function ifcMesh(positions: readonly number[], indices: readonly number[], base: number): { positions: number[]; indices: number[] } {
const pos = positions.slice();
for (let i = 2; i < pos.length; i += 3) pos[i] -= base;
return { positions: pos, indices: orientOutward(pos, indices) };
}
/**
* Teile einer Treppe für den IFC-Export; `base` = Oberkante des Geschosses, dem die Treppe zugeordnet
* ist (Z-Werte werden relativ dazu geschrieben). Leere Teile (keine Geometrie) ergeben `flights: []`,
* `landing: null`, `rail: null` — der Aufrufer fällt dann auf den Fussabdruck zurück.
*/
export function stairParts(project: Project, stair: Stair, base: number): StairParts {
const one: Project = { ...project, stairs: [stair] };
const { zBottom, zTop } = stairVerticalExtent(project, stair);
const rise = zTop - zBottom;
const geo = stairGeometry(stair, rise);
const slabs = emitStairs(one);
const meshes = emitStairMeshes(one);
const predefined = stair.shape === "spiral" ? "SPIRAL" : "STRAIGHT";
// Podest nur bei "L" (bei der Wendel ist das Polygon die Treppenmitte, Teil des Laufs).
let landingSlab: RSlab | undefined;
if (stair.shape === "L" && geo.landing) landingSlab = slabs.find((s) => sameRing(s.outline, geo.landing as Vec2[]));
const treadSlabs = slabs.filter((s) => s !== landingSlab);
const solidOf = (s: RSlab): StairSolid => ({ pts: s.outline.map(([x, y]) => ({ x, y })), zRel: s.zBottom - base, depth: s.zTop - s.zBottom });
const groups: RSlab[][] = [];
if (landingSlab) {
const top = landingSlab.zTop + EPS;
const lower = treadSlabs.filter((s) => s.zTop <= top);
const upper = treadSlabs.filter((s) => s.zTop > top);
for (const g of [lower, upper]) if (g.length > 0) groups.push(g);
} else if (treadSlabs.length > 0) {
groups.push(treadSlabs);
}
const flights: StairFlightParts[] = [];
groups.forEach((g, k) => {
// Tritte = verschiedene Oberkanten (Setzstufen-Platten und Nasen teilen die Höhe ihres Tritts).
const tops = [...new Set(g.map((s) => Math.round(s.zTop / 1e-4)))];
const treads = tops.length;
// Lauflänge: Weg zwischen erstem und letztem Tritt (Schwerpunkte) plus eine Trittiefe, mit der Steigung.
const lowest = g.reduce((m, s) => (s.zTop < m.zTop ? s : m), g[0]);
const highest = g.reduce((m, s) => (s.zTop > m.zTop ? s : m), g[0]);
const c0 = centroid(solidOf(lowest).pts);
const c1 = centroid(solidOf(highest).pts);
const run = Math.hypot(c1.x - c0.x, c1.y - c0.y) + geo.treadDepth;
const lift = highest.zTop - lowest.zTop + geo.riserHeight;
const solids = g.map(solidOf);
const volume = g.reduce((s, x) => s + ringArea(x.outline.map(([px, py]) => ({ x: px, y: py }))) * (x.zTop - x.zBottom), 0);
flights.push({
name: groups.length > 1 ? `Lauf ${k + 1}` : "Lauf",
risers: treads,
treads,
riserHeight: geo.riserHeight,
treadLength: geo.treadDepth,
predefined,
quantities: flightQuantities(Math.hypot(run, lift), volume),
solids,
});
});
// Glatte Ortbeton-Laufplatte (gerade Betontreppe): ein Lauf als Netz.
if (meshes.length > 0) {
const positions: number[] = [];
const indices: number[] = [];
for (const m of meshes) {
const at = positions.length / 3;
for (const v of m.positions) positions.push(v);
for (const i of m.indices) indices.push(at + i);
}
const mesh = ifcMesh(positions, indices, base);
flights.push({
name: flights.length > 0 ? `Lauf ${flights.length + 1}` : "Lauf",
risers: geo.treads.length,
treads: geo.treads.length,
riserHeight: geo.riserHeight,
treadLength: geo.treadDepth,
predefined,
quantities: flightQuantities(Math.hypot(stair.runLength, rise), meshVolume(mesh.positions, mesh.indices)),
mesh,
});
}
let landing: StairParts["landing"] = null;
if (landingSlab) {
const s = solidOf(landingSlab);
landing = { name: "Podest", pts: s.pts, zRel: s.zRel, depth: s.depth, quantities: slabQuantities(s.pts, [], s.depth) };
}
let rail: StairParts["rail"] = null;
const railMeshes = emitStairRailings(one);
if (railMeshes.length > 0) {
const positions: number[] = [];
const indices: number[] = [];
for (const m of railMeshes) {
const at = positions.length / 3;
for (const v of m.positions) positions.push(v);
for (const i of m.indices) indices.push(at + i);
}
const sides = getStairType(project, stair)?.railing === "beide" ? 2 : 1;
rail = {
name: "Handlauf",
predefined: "HANDRAIL",
mesh: ifcMesh(positions, indices, base),
quantities: railingQuantities(Math.hypot(stair.runLength, rise) * sides),
};
}
return { flights, landing, rail };
}
+94
View File
@@ -0,0 +1,94 @@
// Wicklung von Dreiecks-Netzen nach aussen ausrichten — gemeinsam für Mesh-Export (OBJ/STL/glTF) und
// IFC-Export. Die 3D-Ableitungen (`plan/toWalls3d/*`) liefern keine verlässliche Wicklung, weil render3d
// doppelseitig zeichnet; Dateiformate verlangen sie.
/**
* Richtet ein Dreiecks-Netz (Weltkoordinaten) so aus, dass die Flächennormalen nach AUSSEN zeigen:
* Dreiecke werden über gemeinsame Kanten (Eckpunkte auf 0,01 mm verschweisst) zu Zusammenhangs-
* Komponenten verbunden, jede Komponente zuerst in sich widerspruchsfrei gewickelt (Nachbarn
* durchlaufen eine gemeinsame Kante gegenläufig) und dann nach dem Vorzeichen ihres Volumens
* gedreht. Kanten mit mehr als zwei Dreiecken (Verschneidungen) verbinden nicht. Offene
* Komponenten haben kein sinnvolles Volumen und bleiben, wie sie sind (nach dem Konsistenz-Schritt).
*/
export function orientOutward(pos: readonly number[], idx: readonly number[]): number[] {
const nTri = Math.floor(idx.length / 3);
const nVert = pos.length / 3;
const weld = new Map<string, number>();
const canon = new Array<number>(nVert);
const q = (v: number) => Math.round(v * 1e5);
for (let i = 0; i < nVert; i++) {
const key = `${q(pos[3 * i])},${q(pos[3 * i + 1])},${q(pos[3 * i + 2])}`;
let c = weld.get(key);
if (c === undefined) {
c = weld.size;
weld.set(key, c);
}
canon[i] = c;
}
const N = weld.size + 1;
// Kante (min,max) → [(Dreieck, vorwärts?)…]
const edges = new Map<number, number[]>();
const corner = (t: number, k: number) => canon[idx[3 * t + k]];
for (let t = 0; t < nTri; t++) {
for (let k = 0; k < 3; k++) {
const a = corner(t, k);
const b = corner(t, (k + 1) % 3);
if (a === b) continue;
const key = Math.min(a, b) * N + Math.max(a, b);
const list = edges.get(key);
const entry = t * 2 + (a < b ? 1 : 0);
if (list) list.push(entry);
else edges.set(key, [entry]);
}
}
// Nachbarschaft über Kanten mit genau zwei Dreiecken: Wicklungs-Paritaet (0 = gleich, 1 = gegenläufig noetig).
const adj: number[][] = Array.from({ length: nTri }, () => []);
for (const list of edges.values()) {
if (list.length !== 2) continue;
const [e1, e2] = list;
const t1 = e1 >> 1;
const t2 = e2 >> 1;
if (t1 === t2) continue;
// Gleiche Durchlaufrichtung = Widerspruch ⇒ eines muss gedreht werden.
const parity = (e1 & 1) === (e2 & 1) ? 1 : 0;
adj[t1].push(t2 * 2 + parity);
adj[t2].push(t1 * 2 + parity);
}
const flip = new Array<number>(nTri).fill(-1);
const out = idx.slice();
for (let s = 0; s < nTri; s++) {
if (flip[s] >= 0) continue;
const comp: number[] = [s];
flip[s] = 0;
for (let h = 0; h < comp.length; h++) {
const t = comp[h];
for (const e of adj[t]) {
const u = e >> 1;
if (flip[u] < 0) {
flip[u] = flip[t] ^ (e & 1);
comp.push(u);
}
}
}
// Volumen der Komponente mit den bisherigen Drehungen; Offenheit: Kante mit nur einem Dreieck.
let vol = 0;
for (const t of comp) {
const [a, b, c] = flip[t] ? [idx[3 * t], idx[3 * t + 2], idx[3 * t + 1]] : [idx[3 * t], idx[3 * t + 1], idx[3 * t + 2]];
const A = a * 3;
const B = b * 3;
const C = c * 3;
vol +=
pos[A] * (pos[B + 1] * pos[C + 2] - pos[B + 2] * pos[C + 1]) -
pos[A + 1] * (pos[B] * pos[C + 2] - pos[B + 2] * pos[C]) +
pos[A + 2] * (pos[B] * pos[C + 1] - pos[B + 1] * pos[C]);
}
const turn = vol < 0 ? 1 : 0;
for (const t of comp) {
if (flip[t] ^ turn) {
out[3 * t + 1] = idx[3 * t + 2];
out[3 * t + 2] = idx[3 * t + 1];
}
}
}
return out;
}
+2 -2
View File
@@ -33,8 +33,8 @@ describe("IFC-Import als Bauteile: Rundreise Demo-Haus", () => {
const { project: p, summary, report } = await importInto(emptyProject, sampleProject);
expect(report.parseErrors).toBe(0);
expect(summary).toMatchObject({ walls: 9, openings: 3, ceilings: 1, columns: 0, rooms: 1, floors: 0, wallTypes: 0, ceilingTypes: 0, components: 0, kept: 0 });
// Dach und Treppe bleiben Kontext-Mesh.
expect((p.context ?? []).map((c) => (c as { layer?: string }).layer).sort()).toEqual(["IfcRoof", "IfcStair"]);
// Dach und Treppenlauf (die IfcStair selbst hat keine Darstellung) bleiben Kontext-Mesh.
expect((p.context ?? []).map((c) => (c as { layer?: string }).layer).sort()).toEqual(["IfcRoof", "IfcStairFlight"]);
expect(validateProject(p)).toEqual([]);
const byOrig = new Map<string, Wall>();
+1 -1
View File
@@ -40,7 +40,7 @@ const bytesOf = (s: string) => new TextEncoder().encode(s);
/** Bauteile je IFC-Klasse aus dem Export-Text (Zeilen `#n=IFCWALL(`). */
function exportedCounts(ifc: string): Map<string, number> {
const m = new Map<string, number>();
for (const cls of ["IFCWALL", "IFCSLAB", "IFCROOF", "IFCDOOR", "IFCWINDOW", "IFCSTAIR", "IFCCOLUMN", "IFCBUILDINGELEMENTPROXY"]) {
for (const cls of ["IFCWALL", "IFCSLAB", "IFCROOF", "IFCDOOR", "IFCWINDOW", "IFCSTAIRFLIGHT", "IFCRAILING", "IFCCOLUMN", "IFCBUILDINGELEMENTPROXY"]) {
const n = (ifc.match(new RegExp(`^#\\d+=${cls}\\(`, "gm")) ?? []).length;
if (n) m.set(cls, n);
}