Merge [B3] IFC-Import als Mesh: STEP-Leser und Geometrie in Rust (fileio)

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-28 10:49:38 +00:00
commit db01fd83a5
16 files changed
+3228 -7

No files matched your search

+3
View File
@@ -8,3 +8,6 @@ acadrust (https://github.com/hakanaktt/acadrust), MPL-2.0
i_overlay (https://github.com/iShape-Rust/iOverlay), MIT OR Apache-2.0
Abhängigkeit von src-tauri/core (Polygon-Booleans).
earcutr (https://github.com/frewsxcv/earcutr), ISC License — Rust-Port von mapbox/earcut (ISC)
Abhängigkeit von src-tauri/fileio (IFC-Import: Dreieckszerlegung von Profilen und Flächen), unverändert.
+10 -2
View File
@@ -280,7 +280,7 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
- ○ **[65] Explosionsaxonometrie.** · S–M
- ○ **[66] Präsentationspläne mit einem Klick.** · M
- ○ **[67] Skizzenstil.** · M
- ○ **[25] IFC-Import** → [B3]/[B4]. · L
- ◐ **[25] IFC-Import** → [B3] ✅ (Mesh), [B4] ○. · L
- ◐ **[26] Dächer über beliebige Grundrisse.** `geometry/roofSkeleton.ts` (Walm/Sattel/Mansarde/
Krüppelwalm auf L/T/U, Kehlen, Giebel); Port nach Rust läuft [K2]. Offen: Innenhöfe, schiefwinklige
Grundrisse → [B2]. · M
@@ -307,7 +307,15 @@ Ganzes nicht WASM-tauglich (rayon, tempfile, SystemTime) — nur einzelne Module
- ○ **[B2] Straight Skeleton** (für [26]), jetzt nach `dossier-core` statt `kernel2d`. `skeleton.rs`
(709 Z., 8 Tests inkl. Fuzz): Innenhöfe, schiefwinklige Grundrisse, Giebel auf beliebiger Kante,
Neigung je Kante, Arbeitsbudget. · S (Kernel) + M (Einbau)
- ○ **[B3] IFC-Import als Mesh** (erste Stufe von [25]). `step.rs` + Leseteil von `import.rs`. · M
- ✅ **[B3] IFC-Import als Mesh** (erste Stufe von [25]). (28.10.) Eigener Code in `src-tauri/fileio`
(`ifc_step.rs` STEP-Leser inkl. `\X2\`/`\X4\`, `ifc_import.rs` Geometrie), Fassade `io/ifcImport.ts`:
je IfcProduct ein Kontext-Mesh (Ebene = IFC-Klasse; > 2000 Bauteile je Klasse+Geschoss), Menü „IFC
importieren …", Import-Dialog und Drag & Drop (`.ifc`), CLI `import-ifc`. Extrusion (Arbitrary/
Rechteck/Kreis/I/L/U/T, Löcher, Bögen), FacetedBrep, Tri-/PolygonalFaceSet, MappedItem, mm/Fuss,
IFC2x3/4/4.3. Rundreise und alle buildingSMART-Simple-Scene-Dateien gegen ifcopenshell gleich (Volumen je
Bauteil). Offen: Öffnungen abziehen und Boolesche Körper (nur 1. Operand) → [B4]; IfcAdvancedBrep,
Revolved/SweptDisk; Farbe/GlobalId gelesen, aber `ImportedMesh` hat kein Feld dafür (GlobalId steht im
Namen); Laden im Worker; nur Linux-Container/vitest, nicht in der Tauri-App geprüft. · M
- ○ **[B4] IFC-Import zu echten Bauteilen** (zweite Stufe von [25]). · L · nach [B3].
- ◐ **[B5] IFC-Export nachziehen** (`exportIfc.ts`). Stand 27.10.:
- ✅ Nicht-ASCII nach ISO 10303-21 (`\X2\`/`\X4\`).
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Gegencheck für den IFC-Import ([B3]): Dreiecke und Volumen je Bauteil aus ifcopenshell.geom.
Aufruf: python3 scripts/ifc-import-compare.py datei.ifc
Ausgabe (stdout, JSON): {"<GlobalId>": {"class": "IfcWall", "triangles": 12, "volume": 1.5}, …}
Volumen in m³ (Weltkoordinaten, Einheiten der Datei umgerechnet). Ausgelassen wie im Import:
IfcOpeningElement, IfcSpace, IfcAnnotation, IfcGrid, IfcVirtualElement, IfcSpatialZone und Bauteile ohne Körper.
Braucht `pip install ifcopenshell` (getestet mit 0.8/0.9).
"""
import json
import sys
import ifcopenshell
import ifcopenshell.geom
import ifcopenshell.util.shape
SKIP = {"IfcOpeningElement", "IfcOpeningStandardCase", "IfcSpace", "IfcAnnotation", "IfcGrid", "IfcVirtualElement", "IfcSpatialZone"}
def main(path: str) -> int:
model = ifcopenshell.open(path)
settings = ifcopenshell.geom.settings()
settings.set("use-world-coords", True)
# Öffnungen nicht abziehen — der Mesh-Import [B3] tut es auch nicht.
settings.set("disable-opening-subtractions", True)
out = {}
for product in model.by_type("IfcProduct"):
if product.is_a() in SKIP or product.Representation is None:
continue
try:
shape = ifcopenshell.geom.create_shape(settings, product)
except Exception: # noqa: BLE001 — ohne Körper: auslassen
continue
geom = shape.geometry
out[product.GlobalId] = {
"class": product.is_a(),
"triangles": len(geom.faces) // 3,
"volume": ifcopenshell.util.shape.get_volume(geom),
}
json.dump(out, sys.stdout)
return 0
if __name__ == "__main__":
if len(sys.argv) != 2:
print(__doc__)
sys.exit(2)
sys.exit(main(sys.argv[1]))
+35
View File
@@ -38,6 +38,12 @@ version = "1.0.103"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3"
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "bitflags"
version = "2.13.0"
@@ -112,12 +118,23 @@ version = "0.1.0"
dependencies = [
"acadrust",
"console_error_panic_hook",
"earcutr",
"getrandom",
"serde",
"serde_json",
"wasm-bindgen",
]
[[package]]
name = "earcutr"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "afc28d89ac6cb489f679fcf51aaa62b4667bb0fb73a30f1d4d23949069707c07"
dependencies = [
"itertools",
"num-traits",
]
[[package]]
name = "either"
version = "1.19.0"
@@ -209,6 +226,15 @@ dependencies = [
"hashbrown",
]
[[package]]
name = "itertools"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "1.0.18"
@@ -273,6 +299,15 @@ dependencies = [
"minimal-lexical",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "oem_cp"
version = "2.1.2"
+3
View File
@@ -40,3 +40,6 @@ serde_json = { version = "1", optional = true }
# WASM-Bindings — nur im Feature "web" aktiv.
wasm-bindgen = { version = "0.2", optional = true }
console_error_panic_hook = { version = "0.1", optional = true }
# IFC-Import ([B3]): Dreieckszerlegung von Profilen und Flächen mit Löchern (ISC, Port von mapbox/earcut).
earcutr = "0.5"
File diff suppressed because it is too large. Load diff
+617
View File
@@ -0,0 +1,617 @@
// STEP-Klartext-Leser (ISO 10303-21) für IFC ([B3]): zerlegt eine `.ifc`-Datei in Instanzen
// `#id = TYP(argumente);`. Kennt keine Schemata (IFC2x3, IFC4, IFC4.3 laufen gleich durch);
// die Bedeutung der Argumente liest `ifc_import.rs`.
//
// Eigener Code (nichts aus BIMCraft `step.rs` übernommen).
//
// Robustheit: kaputte Instanzen werden übersprungen und gezählt (Lesen geht beim nächsten `;`
// weiter), Verschachtelung und Dateigrösse sind begrenzt, nie Panic.
//
// Zeichenketten nach ISO 10303-21 §6.4.3: `''` → `'`, `\\` → `\`, `\S\c` (ISO 8859 obere Hälfte),
// `\X\hh` (ISO 8859-1), `\X2\hhhh…\X0\` (UTF-16), `\X4\hhhhhhhh…\X0\` (UTF-32), `\P?\` (Codeseite,
// ignoriert). Rohe Nicht-ASCII-Bytes (in der Praxis UTF-8 oder Latin-1) werden toleriert.
use std::collections::HashMap;
/// Obergrenze der Dateigrösse (Bytes) — darüber wird gar nicht erst gelesen.
pub const MAX_FILE_BYTES: usize = 400 * 1024 * 1024;
/// Obergrenze der Instanzen.
pub const MAX_ENTITIES: usize = 20_000_000;
/// Obergrenze der Listen-Verschachtelung (schützt den Stack).
const MAX_DEPTH: usize = 64;
/// Ein Argument einer Instanz.
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
/// `$` — nicht gesetzt.
Null,
/// `*` — abgeleitet (redeklariert).
Derived,
Int(i64),
Real(f64),
Str(String),
/// `.ENUM.` (ohne Punkte, gross).
Enum(String),
/// `#123`
Ref(u64),
/// `"…"` (Binärwert, Inhalt unbeachtet).
Binary,
List(Vec<Value>),
/// Typisierter Wert `IFCLABEL('x')`, `IFCLENGTHMEASURE(1.)`.
Typed(String, Vec<Value>),
}
impl Value {
pub fn as_ref_id(&self) -> Option<u64> {
match self {
Value::Ref(r) => Some(*r),
_ => None,
}
}
/// Zahl (auch ganzzahlig oder typisiert wie `IFCREAL(1.)`); nur endliche Werte.
pub fn as_f64(&self) -> Option<f64> {
let v = match self {
Value::Real(r) => *r,
Value::Int(i) => *i as f64,
Value::Typed(_, a) if a.len() == 1 => return a[0].as_f64(),
_ => return None,
};
v.is_finite().then_some(v)
}
pub fn as_i64(&self) -> Option<i64> {
match self {
Value::Int(i) => Some(*i),
Value::Typed(_, a) if a.len() == 1 => a[0].as_i64(),
_ => None,
}
}
pub fn as_str(&self) -> Option<&str> {
match self {
Value::Str(s) => Some(s),
Value::Typed(_, a) if a.len() == 1 => a[0].as_str(),
_ => None,
}
}
pub fn as_enum(&self) -> Option<&str> {
match self {
Value::Enum(s) => Some(s),
_ => None,
}
}
pub fn as_list(&self) -> Option<&[Value]> {
match self {
Value::List(l) => Some(l),
_ => None,
}
}
pub fn is_null(&self) -> bool {
matches!(self, Value::Null | Value::Derived)
}
}
/// Eine Instanz `#id = TYP(args)`; komplexe Instanzen `#id = (A(..) B(..))` tragen den Typ
/// `""` und je Teil ein `Value::Typed` in `args`.
#[derive(Debug, Clone)]
pub struct Entity {
pub ty: String,
pub args: Vec<Value>,
}
impl Entity {
pub fn arg(&self, i: usize) -> Option<&Value> {
self.args.get(i)
}
}
/// Inhalt einer STEP-Datei.
#[derive(Debug, Default)]
pub struct StepFile {
/// Erstes Schema aus `FILE_SCHEMA` (gross, z. B. `IFC2X3`, `IFC4`, `IFC4X3_ADD2`).
pub schema: String,
pub entities: HashMap<u64, Entity>,
/// Übersprungene, unlesbare Anweisungen.
pub errors: usize,
}
impl StepFile {
pub fn get(&self, id: u64) -> Option<&Entity> {
self.entities.get(&id)
}
}
struct Lexer<'a> {
b: &'a [u8],
i: usize,
}
impl<'a> Lexer<'a> {
fn peek(&self) -> Option<u8> {
self.b.get(self.i).copied()
}
/// Überspringt Leerraum und `/* … */`-Kommentare.
fn ws(&mut self) {
loop {
while let Some(c) = self.peek() {
if c.is_ascii_whitespace() {
self.i += 1;
} else {
break;
}
}
if self.b.get(self.i) == Some(&b'/') && self.b.get(self.i + 1) == Some(&b'*') {
match find(self.b, self.i + 2, b"*/") {
Some(end) => self.i = end + 2,
None => self.i = self.b.len(),
}
} else {
return;
}
}
}
fn eat(&mut self, c: u8) -> bool {
self.ws();
if self.peek() == Some(c) {
self.i += 1;
true
} else {
false
}
}
/// Schlüsselwort (`IFCWALL`, `FILE_SCHEMA`, `END-ISO-10303-21`), gross gemacht.
fn keyword(&mut self) -> Option<String> {
self.ws();
let start = self.i;
while let Some(c) = self.peek() {
if c.is_ascii_alphanumeric() || c == b'_' || c == b'-' {
self.i += 1;
} else {
break;
}
}
if self.i == start {
return None;
}
Some(String::from_utf8_lossy(&self.b[start..self.i]).to_ascii_uppercase())
}
fn integer(&mut self) -> Option<u64> {
let start = self.i;
while let Some(c) = self.peek() {
if c.is_ascii_digit() {
self.i += 1;
} else {
break;
}
}
std::str::from_utf8(&self.b[start..self.i]).ok()?.parse().ok()
}
/// Springt hinter das nächste `;` ausserhalb von Zeichenketten (Fehlererholung).
fn skip_statement(&mut self) {
while let Some(c) = self.peek() {
self.i += 1;
match c {
b';' => return,
b'\'' => {
// Zeichenkette bis zum schliessenden Hochkomma (`''` = Hochkomma).
while let Some(d) = self.peek() {
self.i += 1;
if d == b'\'' {
if self.peek() == Some(b'\'') {
self.i += 1;
} else {
break;
}
}
}
}
b'/' if self.peek() == Some(b'*') => {
self.i = find(self.b, self.i + 1, b"*/").map_or(self.b.len(), |e| e + 2);
}
_ => {}
}
}
}
/// Argumentliste nach der öffnenden Klammer bis zur schliessenden.
fn args(&mut self, depth: usize) -> Option<Vec<Value>> {
if depth > MAX_DEPTH {
return None;
}
let mut out = Vec::new();
if self.eat(b')') {
return Some(out);
}
loop {
out.push(self.value(depth)?);
if self.eat(b',') {
continue;
}
if self.eat(b')') {
return Some(out);
}
return None;
}
}
fn value(&mut self, depth: usize) -> Option<Value> {
self.ws();
let c = self.peek()?;
match c {
b'$' => {
self.i += 1;
Some(Value::Null)
}
b'*' => {
self.i += 1;
Some(Value::Derived)
}
b'#' => {
self.i += 1;
self.integer().map(Value::Ref)
}
b'\'' => self.string().map(Value::Str),
b'"' => {
self.i += 1;
let end = self.b[self.i..].iter().position(|&d| d == b'"')?;
self.i += end + 1;
Some(Value::Binary)
}
b'.' if self.b.get(self.i + 1).is_some_and(|d| d.is_ascii_alphabetic() || *d == b'_') => {
self.i += 1;
let start = self.i;
while let Some(d) = self.peek() {
if d == b'.' {
break;
}
if !(d.is_ascii_alphanumeric() || d == b'_') {
return None;
}
self.i += 1;
}
let s = String::from_utf8_lossy(&self.b[start..self.i]).to_ascii_uppercase();
self.i += 1; // schliessender Punkt
Some(Value::Enum(s))
}
b'(' => {
self.i += 1;
self.args(depth + 1).map(Value::List)
}
b'+' | b'-' | b'.' | b'0'..=b'9' => self.number(),
c if c.is_ascii_alphabetic() => {
let name = self.keyword()?;
if !self.eat(b'(') {
return None;
}
let a = self.args(depth + 1)?;
Some(Value::Typed(name, a))
}
_ => None,
}
}
fn number(&mut self) -> Option<Value> {
let start = self.i;
let mut real = false;
while let Some(c) = self.peek() {
match c {
b'0'..=b'9' | b'+' | b'-' => {}
b'.' | b'E' | b'e' => real = true,
_ => break,
}
self.i += 1;
}
let s = std::str::from_utf8(&self.b[start..self.i]).ok()?;
if !real {
if let Ok(i) = s.parse::<i64>() {
return Some(Value::Int(i));
}
}
// `1.` und `1.E-5` sind gültiges STEP; Rust liest beides, zur Sicherheit „1.0“-Form.
let fixed;
let t = if let Some(p) = s.find('.') {
let after = s.as_bytes().get(p + 1);
if after.is_none_or(|c| !c.is_ascii_digit()) {
fixed = format!("{}0{}", &s[..=p], &s[p + 1..]);
&fixed
} else {
s
}
} else {
s
};
let v: f64 = t.parse().ok()?;
Some(Value::Real(v))
}
/// Zeichenkette ab dem öffnenden Hochkomma, dekodiert.
fn string(&mut self) -> Option<String> {
self.i += 1;
let mut raw: Vec<u8> = Vec::new();
loop {
let c = self.peek()?;
self.i += 1;
if c == b'\'' {
if self.peek() == Some(b'\'') {
self.i += 1;
raw.push(b'\'');
} else {
break;
}
} else {
raw.push(c);
}
}
Some(decode_string(&raw))
}
}
fn find(hay: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
if from >= hay.len() {
return None;
}
hay[from..].windows(needle.len()).position(|w| w == needle).map(|p| p + from)
}
fn hex_val(c: u8) -> Option<u32> {
(c as char).to_digit(16)
}
/// Dekodiert die Steuersequenzen einer STEP-Zeichenkette (Inhalt ohne Hochkommas, `''` bereits
/// aufgelöst).
pub fn decode_string(raw: &[u8]) -> String {
let mut out = String::with_capacity(raw.len());
let mut i = 0;
// Rohe Nicht-ASCII-Bytes: als UTF-8 lesen, wenn gültig, sonst Latin-1.
let push_raw = |out: &mut String, bytes: &[u8]| match std::str::from_utf8(bytes) {
Ok(s) => out.push_str(s),
Err(_) => out.extend(bytes.iter().map(|&b| b as char)),
};
let mut plain_start = 0;
while i < raw.len() {
if raw[i] != b'\\' {
i += 1;
continue;
}
push_raw(&mut out, &raw[plain_start..i]);
let rest = &raw[i..];
if rest.starts_with(b"\\\\") {
out.push('\\');
i += 2;
} else if rest.starts_with(b"\\S\\") && rest.len() >= 4 {
out.push(char::from_u32(rest[3] as u32 + 128).unwrap_or('?'));
i += 4;
} else if rest.starts_with(b"\\P") && rest.len() >= 4 && rest[3] == b'\\' {
i += 4;
} else if rest.starts_with(b"\\X\\") && rest.len() >= 5 {
match (hex_val(rest[3]), hex_val(rest[4])) {
(Some(h), Some(l)) => out.push(char::from_u32(h * 16 + l).unwrap_or('?')),
_ => out.push('?'),
}
i += 5;
} else if rest.starts_with(b"\\X2\\") || rest.starts_with(b"\\X4\\") {
let width = if rest[2] == b'2' { 4 } else { 8 };
let body_start = i + 4;
let end = find(raw, body_start, b"\\X0\\").unwrap_or(raw.len());
let body = &raw[body_start..end];
let mut units: Vec<u32> = Vec::new();
for chunk in body.chunks(width) {
if chunk.len() < width {
break;
}
let mut v = 0u32;
let mut ok = true;
for &c in chunk {
match hex_val(c) {
Some(h) => v = v.wrapping_mul(16).wrapping_add(h),
None => ok = false,
}
}
if ok {
units.push(v);
}
}
if width == 4 {
let u16s: Vec<u16> = units.iter().map(|&u| u as u16).collect();
out.push_str(&String::from_utf16_lossy(&u16s));
} else {
out.extend(units.iter().map(|&u| char::from_u32(u).unwrap_or('\u{FFFD}')));
}
i = (end + 4).min(raw.len());
} else {
// Unbekannte Sequenz: Backslash wörtlich behalten.
out.push('\\');
i += 1;
}
plain_start = i;
}
push_raw(&mut out, &raw[plain_start.min(raw.len())..]);
out
}
/// Liest eine STEP-Datei. Fehler nur bei grundsätzlich unbrauchbarer Eingabe (zu gross, kein
/// STEP); einzelne kaputte Instanzen zählen in `errors`.
pub fn parse(bytes: &[u8]) -> Result<StepFile, String> {
if bytes.len() > MAX_FILE_BYTES {
return Err(format!("Datei zu gross ({} MB, höchstens {} MB)", bytes.len() >> 20, MAX_FILE_BYTES >> 20));
}
let head = &bytes[..bytes.len().min(4096)];
if find(head, 0, b"ISO-10303-21").is_none() {
return Err("keine STEP-Datei (ISO-10303-21 fehlt)".into());
}
let mut lx = Lexer { b: bytes, i: 0 };
let mut file = StepFile::default();
loop {
lx.ws();
let Some(c) = lx.peek() else { break };
if c == b'#' {
lx.i += 1;
let start = lx.i;
let parsed = (|| {
let id = lx.integer()?;
if !lx.eat(b'=') {
return None;
}
lx.ws();
let ent = if lx.peek() == Some(b'(') {
// Komplexe Instanz: Folge von TYP(args) in Klammern.
lx.i += 1;
let mut parts = Vec::new();
loop {
if lx.eat(b')') {
break;
}
let name = lx.keyword()?;
if !lx.eat(b'(') {
return None;
}
parts.push(Value::Typed(name, lx.args(1)?));
}
Entity { ty: String::new(), args: parts }
} else {
let ty = lx.keyword()?;
if !lx.eat(b'(') {
return None;
}
Entity { ty, args: lx.args(1)? }
};
if !lx.eat(b';') {
return None;
}
Some((id, ent))
})();
match parsed {
Some((id, ent)) => {
if file.entities.len() >= MAX_ENTITIES {
return Err(format!("zu viele Instanzen (höchstens {MAX_ENTITIES})"));
}
file.entities.insert(id, ent);
}
None => {
file.errors += 1;
lx.i = start;
lx.skip_statement();
}
}
continue;
}
// Kopf- und Abschnitts-Anweisungen.
let Some(kw) = lx.keyword() else {
lx.i += 1;
file.errors += 1;
lx.skip_statement();
continue;
};
match kw.as_str() {
"END-ISO-10303-21" => break,
"FILE_SCHEMA" => {
if lx.eat(b'(') {
if let Some(a) = lx.args(1) {
if let Some(Value::List(l)) = a.first() {
if let Some(s) = l.first().and_then(|v| v.as_str()) {
file.schema = s.trim().to_ascii_uppercase();
}
}
}
}
lx.skip_statement();
}
_ => lx.skip_statement(),
}
}
Ok(file)
}
#[cfg(test)]
mod tests {
use super::*;
const MINI: &str = "ISO-10303-21;\nHEADER;\nFILE_DESCRIPTION(('ViewDefinition [CoordinationView]'),'2;1');\n\
FILE_NAME('a.ifc','2024-01-01T00:00:00',(''),(''),'x','y','');\nFILE_SCHEMA(('IFC4'));\nENDSEC;\nDATA;\n\
#1=IFCCARTESIANPOINT((0.,1.5,-2.E-1));\n/* Kommentar; mit Semikolon */\n\
#2 = IFCWALL('2O2Fr$t4X7Zf8NOew3FLOH',$,'K\\X2\\00FC\\X0\\che',*,.T.,#1,(#1,#3),IFCLABEL('it''s'));\n\
#3=IFCDIRECTION((1,0,0));\n#4=(IFCA(1)IFCB('x'));\nENDSEC;\nEND-ISO-10303-21;\n";
#[test]
fn parses_header_and_instances() {
let f = parse(MINI.as_bytes()).unwrap();
assert_eq!(f.schema, "IFC4");
assert_eq!(f.errors, 0);
let p = f.get(1).unwrap();
assert_eq!(p.ty, "IFCCARTESIANPOINT");
let c: Vec<f64> = p.args[0].as_list().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
assert_eq!(c, vec![0.0, 1.5, -0.2]);
let w = f.get(2).unwrap();
assert_eq!(w.ty, "IFCWALL");
assert_eq!(w.args[2].as_str(), Some("Küche"));
assert_eq!(w.args[3], Value::Derived);
assert_eq!(w.args[4], Value::Enum("T".into()));
assert_eq!(w.args[5], Value::Ref(1));
assert_eq!(w.args[7].as_str(), Some("it's"));
assert_eq!(f.get(3).unwrap().args[0].as_list().unwrap()[0], Value::Int(1));
let cx = f.get(4).unwrap();
assert_eq!(cx.ty, "");
assert_eq!(cx.args.len(), 2);
}
#[test]
fn decodes_escapes() {
assert_eq!(decode_string(b"\\X2\\00E400F6\\X0\\"), "äö");
assert_eq!(decode_string(b"\\X4\\0001F600\\X0\\x"), "😀x");
assert_eq!(decode_string(b"a\\\\b"), "a\\b");
assert_eq!(decode_string(b"\\S\\d"), "ä"); // 'd' = 0x64, +128 = 0xE4
assert_eq!(decode_string(b"\\X\\E9t\\X\\E9"), "été");
assert_eq!(decode_string(b"\\PA\\Z"), "Z");
assert_eq!(decode_string("Grüezi".as_bytes()), "Grüezi");
assert_eq!(decode_string(&[0x47, 0xFC]), "Gü"); // Latin-1 roh
// Kaputt: nie Panic.
assert_eq!(decode_string(b"\\X2\\00E"), "");
let _ = decode_string(b"\\X\\Z");
let _ = decode_string(b"\\");
}
#[test]
fn recovers_from_broken_instances() {
let s = "ISO-10303-21;\nDATA;\n#1=IFCFOO(1,,2);\n#2=IFCBAR('a;b');\n#3=IFCBAZ((1,2);\n#4=IFCOK(.X.);\nENDSEC;\n";
let f = parse(s.as_bytes()).unwrap();
assert!(f.get(1).is_none());
assert_eq!(f.get(2).unwrap().args[0].as_str(), Some("a;b"));
assert!(f.get(4).is_some());
assert!(f.errors >= 2);
}
#[test]
fn rejects_nonsense_without_panic() {
assert!(parse(b"").is_err());
assert!(parse(b"hello world").is_err());
for s in [
"ISO-10303-21;#",
"ISO-10303-21;#1=",
"ISO-10303-21;#1=X(",
"ISO-10303-21;#1=X('unterminated",
"ISO-10303-21;#1=X(\"bin",
"ISO-10303-21;#1=X(.E",
"ISO-10303-21;/* offen",
"ISO-10303-21;#99999999999999999999999=X();",
"ISO-10303-21;#1=X(-);#2=X(1.2.3E);#3=X(+.E);",
] {
let _ = parse(s.as_bytes());
}
// Tiefe Verschachtelung: Abbruch statt Stack-Überlauf.
let deep = format!("ISO-10303-21;#1=X({}{});", "(".repeat(10_000), ")".repeat(10_000));
let f = parse(deep.as_bytes()).unwrap();
assert!(f.get(1).is_none());
// Zufallsbytes.
let mut x: u32 = 12345;
let mut buf = b"ISO-10303-21;DATA;".to_vec();
for _ in 0..20_000 {
x = x.wrapping_mul(1103515245).wrapping_add(12345);
let alphabet = b"#=(),;'$*.ABC0123456789\\X2 \n/*";
buf.push(alphabet[(x >> 16) as usize % alphabet.len()]);
}
let _ = parse(&buf);
}
}
+2
View File
@@ -16,6 +16,8 @@ pub mod import;
pub mod split;
#[cfg(feature = "web")]
mod web_import;
pub mod ifc_step;
pub mod ifc_import;
use std::collections::HashMap;
use std::io::Cursor;
+40 -3
View File
@@ -54,6 +54,8 @@ import { RecoverAutosaveDialog } from "./ui/RecoverAutosaveDialog";
import { Toast } from "./ui/Toast";
import { isTauriRuntime, PROJECT_TEMPLATE_EXT } from "./native/projectFile";
import { stepTextToImportedMeshes } from "./io/stepImport";
import { formatIfcReport, ifcBytesToImportedMeshes } from "./io/ifcImport";
import { projectGeoOrigin } from "./model/geoRebase";
import { applyClashMarkers, runClashCheck } from "./analysis/clash";
import { checkForUpdate } from "./update/checkForUpdate";
import type { PlanViewHandle } from "./views/plan/PlanView";
@@ -547,6 +549,8 @@ export default function App() {
const dxfInputRef = useRef<HTMLInputElement>(null);
// Verstecktes Datei-Input für den STEP-Import (Menü Datei, STEP importieren).
const stepInputRef = useRef<HTMLInputElement>(null);
// Verstecktes Datei-Input für den IFC-Import ([B3], Menü Datei, IFC importieren).
const ifcInputRef = useRef<HTMLInputElement>(null);
// Verstecktes Datei-Input für „Bild einfügen" (Werkzeug „image", s. tools.ts-
// Kommentar) — akzeptiert auch PDF (jede Seite wird gerastert, s. pdfImport.ts);
@@ -1694,6 +1698,26 @@ export default function App() {
setRoomStamp,
} = useProjectActions(setProject, notify, planViewRef);
// IFC-Import ([B3]): Bauteile als Kontext-Meshes (Format-Modul, `io/ifcImport.ts`), Bericht als Toast.
const importIfcFile = (f: File) => {
void f
.arrayBuffer()
.then((buf) => ifcBytesToImportedMeshes(new Uint8Array(buf), f.name, { geoOrigin: projectGeoOrigin(project) }))
.then(({ meshes, report }) => {
if (meshes.length) addContextObjectsAndFit(meshes);
const warn = meshes.length === 0 || report.truncated || report.productsWithoutGeometry > 0;
notify(formatIfcReport(report, t), warn ? "warning" : "info");
})
.catch((err) =>
notify(`${t("ifc.import.failed")}: ${err instanceof Error ? err.message : String(err)}`, "error"),
);
};
/** Datei aus Import-Dialog oder Drag & Drop: IFC direkt, sonst DXF/DWG-Dialog. */
const openImportForAnyFile = (f: File) => {
if (/\.ifc$/i.test(f.name)) importIfcFile(f);
else openImportForFile(f);
};
// 2D-Griff-Editieren (Eckpunkt-/Kanten-Griffe + Feld-Controller) der aktuellen
// Auswahl — siehe state/useGripEditing.ts.
// Schnitt-/Ansichts-Blatt: geschnittene (bzw. in der Ansicht sichtbare)
@@ -2391,6 +2415,7 @@ export default function App() {
onExportStl,
onExportStep,
onImportStep: () => stepInputRef.current?.click(),
onImportIfc: () => ifcInputRef.current?.click(),
onClashCheck: () => {
const p0 = project;
runClashCheck(p0)
@@ -3080,7 +3105,7 @@ export default function App() {
// App-weites Drag & Drop einer DXF/DWG-Datei — siehe state/useImportHandling.ts.
const { onAppDragEnter, onAppDragOver, onAppDragLeave, onAppDrop } = useFileDropImport(
setDropActive,
openImportForFile,
openImportForAnyFile,
);
// Host-Context für die Panels — siehe state/usePanelHostBase.ts.
@@ -3256,11 +3281,11 @@ export default function App() {
<input
ref={dxfInputRef}
type="file"
accept=".dxf,.dwg,text/plain"
accept=".dxf,.dwg,.ifc,text/plain"
style={{ display: "none" }}
onChange={(e) => {
const f = e.target.files?.[0];
if (f) openImportForFile(f);
if (f) openImportForAnyFile(f);
e.target.value = "";
}}
/>
@@ -3283,6 +3308,18 @@ export default function App() {
);
}}
/>
{/* Verstecktes IFC-Datei-Input (Menü Datei, IFC importieren). */}
<input
ref={ifcInputRef}
type="file"
accept=".ifc"
style={{ display: "none" }}
onChange={(e) => {
const f = e.target.files?.[0];
e.target.value = "";
if (f) importIfcFile(f);
}}
/>
{/* Verstecktes Bild/PDF-Datei-Input (Werkzeug „image"). */}
<input
ref={imageInputRef}
+47 -2
View File
@@ -9,6 +9,8 @@
// dossier-cli <projekt.obp> section <Name> [--out schnitt.svg] (braucht render3d-WASM)
// dossier-cli <projekt.obp> elevation <Name> [--out ansicht.svg]
// dossier-cli <projekt.obp> dxf|dwg|ifc|step|obj|stl|schedule|kennzahlen|sun [--level EG] [--out datei]
// dossier-cli <projekt.obp> import-ifc <datei.ifc> [--out neu.obp] [--group product|class]
// IFC als Kontext-Meshes ([B3]); Bericht als JSON auf stdout
// dossier-cli <projekt.obp> model3d [--out modell.json] 3D-Modell fürs Headless-Rendern (render_png)
// dossier-cli <projekt.obp> mcp MCP-Server (stdio): project_info, query, render_svg, apply_ops, validate
// dossier-cli <projekt.obp> bench [--runs 10] Zeitprofil der Ableitungen (ms je Aufruf)
@@ -22,6 +24,10 @@ import {
buildPlanDxf,
buildPlanDwg,
loadFileio,
readIfc,
ifcToImportedMeshes,
projectGeoOrigin,
ensureContextCategories,
projectToWorldCoords,
computeSection,
exportIfcSpf,
@@ -124,7 +130,7 @@ export async function run(argv: string[]): Promise<number> {
const [file, command, ...rest] = args.positional;
if (!file || !command) {
process.stderr.write(
"Aufruf: dossier-cli <projekt.obp> <info|validate|migrate|plan|section|elevation|dxf|dwg|ifc|step|obj|stl|schedule|kennzahlen|sun> [Optionen]\n",
"Aufruf: dossier-cli <projekt.obp> <info|validate|migrate|plan|section|elevation|dxf|dwg|ifc|import-ifc|step|obj|stl|schedule|kennzahlen|sun> [Optionen]\n",
);
return 2;
}
@@ -136,7 +142,15 @@ export async function run(argv: string[]): Promise<number> {
await initCore();
const project = loadProject(file);
const scale = Number(args.flags.get("scale") ?? 100);
const allCodes = new Set(project.layers.map((l) => l.code));
// Alle Ebenen-Codes inkl. verschachtelter (z. B. „10 Situation" unter „05 Kontext").
const allCodes = new Set<string>();
const collectCodes = (ls: Project["layers"]): void => {
for (const l of ls) {
allCodes.add(l.code);
if (l.children) collectCodes(l.children);
}
};
collectCodes(project.layers);
switch (command) {
case "info": {
@@ -245,6 +259,37 @@ export async function run(argv: string[]): Promise<number> {
out(args, r.text, `${project.name || "projekt"}.stp`);
return 0;
}
case "import-ifc": {
const src = rest[0];
if (!src) fail("import-ifc: IFC-Datei fehlt");
let bytes: Uint8Array;
try {
bytes = new Uint8Array(readFileSync(src));
} catch (e) {
fail(`Datei nicht lesbar: ${src} (${e instanceof Error ? e.message : String(e)})`);
}
const { products, report } = await readIfc(bytes);
const group = args.flags.get("group");
const meshes = ifcToImportedMeshes(products, src.split(/[\\/]/).pop() ?? src, {
geoOrigin: projectGeoOrigin(project),
group: group === "product" || group === "class" ? group : "auto",
});
const byClass: Record<string, number> = {};
for (const p of products) byClass[p.ifcClass] = (byClass[p.ifcClass] ?? 0) + 1;
const triangles = products.reduce((s, p) => s + p.indices.length / 3, 0);
process.stdout.write(JSON.stringify({ ...report, byClass, triangles, contextObjects: meshes.length }, null, 2) + "\n");
const target = args.flags.get("out");
if (target) {
const next = applyOps(project, diffToOps(project, {
...project,
context: [...(project.context ?? []), ...meshes],
// Wie in der App (siteSlice): fehlende Kontext-Kategorie als Ebene ergänzen.
layers: ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : []))),
}));
out(args, serializeProject(next), target);
}
return 0;
}
case "mcp":
await serveStdio(file);
return 0;
+3
View File
@@ -6,6 +6,9 @@ export { exportIfcSpf } from "../export/exportIfc";
export { buildPlanDxf } from "../export/exportDxf";
export { buildPlanDwg } from "../export/exportDxf";
export { loadFileio } from "../engine/fileioWasm";
export { readIfc, ifcToImportedMeshes } from "../io/ifcImport";
export { projectGeoOrigin } from "../model/geoRebase";
export { ensureContextCategories } from "../model/contextCategories";
export { projectToWorldCoords } from "../model/geoRebase";
export { exportScheduleCsv } from "../export/exportSchedule";
export { exportObj, exportStl } from "../export/exportMesh";
+7
View File
@@ -1755,6 +1755,13 @@ export const de = {
"step.import.failed": "STEP-Import fehlgeschlagen",
"step.import.done": "STEP importiert: {n} Körper",
"menu.native.importStep": "STEP importieren …",
"menu.native.importIfc": "IFC importieren …",
"ifc.import.failed": "IFC-Import fehlgeschlagen",
"ifc.import.done": "{schema} importiert: {n} Bauteile als Kontext-Meshes",
"ifc.import.skipped": "{n} Bauteile ohne lesbare Geometrie, übersprungen: {list}",
"ifc.import.voids": "{n} Öffnungen nicht abgezogen",
"ifc.import.booleans": "{n} Boolesche Körper vereinfacht (nur erster Operand)",
"ifc.import.truncated": "abgebrochen: zu viele Dreiecke",
"recover.title": "Ungesicherte Arbeit gefunden",
"recover.message": "Von „{name}“ gibt es eine automatische Sicherung vom {when}, die nicht gespeichert wurde.",
"recover.unsaved": "unbenanntes Projekt",
+7
View File
@@ -1716,6 +1716,13 @@ export const en: Record<TranslationKey, string> = {
"step.import.failed": "STEP import failed",
"step.import.done": "STEP imported: {n} solids",
"menu.native.importStep": "Import STEP …",
"menu.native.importIfc": "Import IFC …",
"ifc.import.failed": "IFC import failed",
"ifc.import.done": "{schema} imported: {n} elements as context meshes",
"ifc.import.skipped": "{n} elements without readable geometry, skipped: {list}",
"ifc.import.voids": "{n} openings not subtracted",
"ifc.import.booleans": "{n} boolean solids simplified (first operand only)",
"ifc.import.truncated": "aborted: too many triangles",
"recover.title": "Unsaved work found",
"recover.message": "There is an automatic backup of “{name}” from {when} that was never saved.",
"recover.unsaved": "untitled project",
+220
View File
@@ -0,0 +1,220 @@
// IFC-Import ([B3]): Rundreise mit dem eigenen IFC-Export und Gegencheck mit ifcopenshell.
//
// Toleranzen: Wände/Dächer sind im Export Dreiecksnetze (IfcTriangulatedFaceSet) und Decken
// Extrusionen von Polygonen — beides ohne Tessellierung, das Volumen muss bis auf die
// Zahlenformatierung des Exports (R(), ~1e-9 m) stimmen: relativ 1e-6. Gegen ifcopenshell gilt
// dasselbe für ebene Geometrie; Kreise/Bögen werden von beiden Seiten verschieden fein zerlegt
// (hier Sehnenfehler ≤ 2 mm) → dort relativ 3 %.
import "../engine/fileioWasm.setup";
import { describe, expect, it } from "vitest";
import { spawnSync } from "node:child_process";
import { existsSync, mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { exportIfcSpf } from "../export/exportIfc";
import { sampleProject } from "../model/sampleProject";
import { ceilingVerticalExtent } from "../model/wall";
import { polygonArea } from "../geometry/roomArea";
import { pickGeometry } from "../plan/toWalls3d";
import { wallCutMeshes } from "../plan/wallMeshCut";
import { formatIfcReport, ifcToImportedMeshes, readIfc, type IfcProduct } from "./ifcImport";
function volume(pos: ArrayLike<number>, idx: ArrayLike<number>): number {
let v = 0;
for (let i = 0; i + 2 < 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 + 2] * pos[c] - pos[b] * pos[c + 2]) +
pos[a + 2] * (pos[b] * pos[c + 1] - pos[b + 1] * pos[c])) /
6;
}
return v;
}
const vol = (p: IfcProduct) => volume(p.positions, p.indices);
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"]) {
const n = (ifc.match(new RegExp(`^#\\d+=${cls}\\(`, "gm")) ?? []).length;
if (n) m.set(cls, n);
}
return m;
}
const relClose = (a: number, b: number, rel: number) => Math.abs(a - b) <= rel * Math.max(Math.abs(a), Math.abs(b), 1e-9);
describe("IFC-Import: Rundreise mit dem eigenen Export", () => {
const ifc = exportIfcSpf(sampleProject);
it("gleiche Bauteilzahl je Klasse, Räume ausgelassen", async () => {
const { products, report } = await readIfc(bytesOf(ifc));
expect(report.schema).toBe("IFC4");
expect(report.parseErrors).toBe(0);
expect(report.productsWithoutGeometry).toBe(0);
expect(report.skippedItems).toEqual({});
const got = new Map<string, number>();
for (const p of products) got.set(p.ifcClass.toUpperCase(), (got.get(p.ifcClass.toUpperCase()) ?? 0) + 1);
expect(got).toEqual(exportedCounts(ifc));
const spaces = (ifc.match(/^#\d+=IFCSPACE\(/gm) ?? []).length;
expect(report.skippedProducts.IfcSpace ?? 0).toBe(spaces);
// Alle Körper geschlossen und aussen orientiert.
for (const p of products) expect(vol(p), `${p.ifcClass} ${p.name}`).toBeGreaterThan(0);
// Geschoss und GlobalId gesetzt.
for (const p of products) {
expect(p.globalId).toMatch(/^[0-9A-Za-z_$]{22}$/);
expect(p.storey).toBeTruthy();
}
});
it("Volumen je Wand = Volumen der Wand-Netze, je Decke = Fläche × Dicke", async () => {
const { products } = await readIfc(bytesOf(ifc));
// Wände: dieselben Ausschnitt-Netze wie der Export (Bänder je Wand).
const bands = pickGeometry(sampleProject).walls;
const byWall = new Map<string, number>();
wallCutMeshes(bands).forEach((m, i) => {
byWall.set(bands[i].wallId, (byWall.get(bands[i].wallId) ?? 0) + Math.abs(volume(m.positions, m.indices)));
});
const wallsExpected = [...byWall.values()].sort((a, b) => a - b);
const wallsGot = products.filter((p) => p.ifcClass === "IfcWall").map(vol).sort((a, b) => a - b);
expect(wallsGot.length).toBe(wallsExpected.length);
wallsGot.forEach((v, i) => expect(relClose(v, wallsExpected[i], 1e-6), `${v} ≠ ${wallsExpected[i]}`).toBe(true));
const slabsExpected = (sampleProject.ceilings ?? [])
.filter((c) => c.outline.length >= 3)
.map((c) => {
const { zBottom, zTop } = ceilingVerticalExtent(sampleProject, c);
return Math.abs(polygonArea(c.outline)) * Math.max(zTop - zBottom, 0.001);
})
.sort((a, b) => a - b);
const slabsGot = products.filter((p) => p.ifcClass === "IfcSlab").map(vol).sort((a, b) => a - b);
expect(slabsGot.length).toBe(slabsExpected.length);
slabsGot.forEach((v, i) => expect(relClose(v, slabsExpected[i], 1e-6), `${v} ≠ ${slabsExpected[i]}`).toBe(true));
});
it("Kontext-Meshes: je Bauteil, Klasse als Ebene; Rückschub auf den Modell-Nullpunkt bei Georeferenz", async () => {
const { products, report } = await readIfc(bytesOf(ifc));
const meshes = ifcToImportedMeshes(products, "haus.ifc");
expect(meshes.length).toBe(products.length);
expect(new Set(meshes.map((m) => m.id)).size).toBe(meshes.length);
expect(meshes.every((m) => m.type === "importedMesh" && m.positions.length >= 9 && m.indices.length >= 3)).toBe(true);
expect(meshes.find((m) => m.layer === "IfcWall")).toBeTruthy();
const grouped = ifcToImportedMeshes(products, "haus.ifc", { group: "class" });
expect(grouped.length).toBeLessThan(meshes.length);
expect(grouped.reduce((s, m) => s + m.indices.length, 0)).toBe(meshes.reduce((s, m) => s + m.indices.length, 0));
// Datei in LV95 (Export mit Standort-Bezug) → zurück auf die lokalen Koordinaten.
const origin = { e: 2_600_000, n: 1_200_000 };
const shifted = products.map((p) => {
const pos = new Float64Array(p.positions);
for (let i = 0; i < pos.length; i += 3) {
pos[i] += origin.e;
pos[i + 1] += origin.n;
}
return { ...p, positions: pos };
});
const back = ifcToImportedMeshes(shifted, "haus.ifc", { geoOrigin: origin });
expect(back[0].positions[0]).toBeCloseTo(meshes[0].positions[0], 6);
// Ohne Bezug in der Datei (lokal) bleibt alles, auch wenn das Projekt einen hat.
const local = ifcToImportedMeshes(products, "haus.ifc", { geoOrigin: origin });
expect(local[0].positions[0]).toBeCloseTo(meshes[0].positions[0], 9);
const text = formatIfcReport(report, (k, v) => `${k}${JSON.stringify(v ?? {})}`);
expect(text).toContain("ifc.import.done");
});
it("Unsinn ergibt einen Fehler, keinen Absturz des Moduls", async () => {
await expect(readIfc(new Uint8Array())).rejects.toBeTruthy();
await expect(readIfc(bytesOf("kein IFC"))).rejects.toBeTruthy();
const broken = ifc.slice(0, Math.floor(ifc.length / 2));
const r = await readIfc(bytesOf(broken));
expect(r.products.length).toBeGreaterThanOrEqual(0);
// Modul lebt noch.
expect((await readIfc(bytesOf(ifc))).products.length).toBeGreaterThan(0);
});
});
// ── Gegencheck mit ifcopenshell (ohne Python/ifcopenshell übersprungen) ─────────────────────────
const hasIfcOpenShell = spawnSync("python3", ["-c", "import ifcopenshell, ifcopenshell.geom, ifcopenshell.util.shape"]).status === 0;
interface OsProduct {
class: string;
triangles: number;
volume: number;
}
function ifcopenshellProducts(file: string): Record<string, OsProduct> {
const r = spawnSync("python3", ["scripts/ifc-import-compare.py", file], { encoding: "utf8", timeout: 120_000, maxBuffer: 64 << 20 });
if (r.status !== 0) throw new Error(r.stderr);
return JSON.parse(r.stdout) as Record<string, OsProduct>;
}
/** Vergleich je GlobalId; liefert Abweichungen als Text (leer = gleich). */
async function compare(file: string, rel: (p: IfcProduct) => number): Promise<string[]> {
const ref = ifcopenshellProducts(file);
const { products, report } = await readIfc(new Uint8Array(readFileSync(file)));
// ifcopenshell 0.9 liefert bei manchen Dateien in mm (z. B. buildingSMART
// „wall-with-opening-and-window.ifc", IfcSIUnit MILLI) die Geometrie unskaliert in Dateieinheiten,
// obwohl `convert-back-units` aus ist; unser Import rechnet dort richtig in m (Rust-Test mit mm).
const s3 = report.lengthScale ** 3;
const problems: string[] = [];
const ours = new Map(products.map((p) => [p.globalId, p]));
for (const [gid, o] of Object.entries(ref)) {
const p = ours.get(gid);
if (!p) {
problems.push(`${o.class} ${gid}: fehlt im Import`);
continue;
}
if (p.ifcClass !== o.class) problems.push(`${gid}: Klasse ${p.ifcClass} ≠ ${o.class}`);
const v = Math.abs(vol(p));
const refV = Math.abs(o.volume);
if (!relClose(v, refV, rel(p)) && !(s3 !== 1 && relClose(v, refV * s3, rel(p)))) problems.push(`${o.class} ${gid}: Volumen ${v} ≠ ${o.volume}`);
}
for (const p of products) if (!(p.globalId in ref)) problems.push(`${p.ifcClass} ${p.globalId}: nur im Import`);
return problems;
}
describe.skipIf(!hasIfcOpenShell)("IFC-Import gegen ifcopenshell", { timeout: 120_000 }, () => {
it("Demo-Haus: gleiche Bauteile, gleiches Volumen je Bauteil", async () => {
const dir = mkdtempSync(join(tmpdir(), "dossier-ifcimp-"));
const file = join(dir, "demo-haus.ifc");
writeFileSync(file, exportIfcSpf(sampleProject));
const problems = await compare(file, () => 1e-6);
expect(problems).toEqual([]);
});
it("mit runder Stütze (Kreis-Profil): Volumen bis auf Tessellierung", async () => {
const col = {
id: "S2", type: "column" as const, floorId: "eg", categoryCode: "50", position: { x: 1, y: 1 },
profile: { kind: "round" as const, radius: 0.15 }, rotation: 0, height: 2.5,
};
const dir = mkdtempSync(join(tmpdir(), "dossier-ifcimp-"));
const file = join(dir, "stuetze.ifc");
writeFileSync(file, exportIfcSpf({ ...sampleProject, columns: [col] }));
const problems = await compare(file, (p) => (p.ifcClass === "IfcColumn" ? 0.03 : 1e-6));
expect(problems).toEqual([]);
});
// Freie Beispieldateien (z. B. github.com/buildingSMART/Sample-Test-Files, nicht im Repo, Lizenz
// ungeklärt): DOSSIER_IFC_SAMPLES=<Verzeichnis> setzen.
const samples = process.env.DOSSIER_IFC_SAMPLES;
it.skipIf(!samples || !existsSync(samples))("Beispieldateien aus DOSSIER_IFC_SAMPLES", async () => {
const files: string[] = [];
const walk = (d: string) => {
for (const n of readdirSync(d)) {
const p = join(d, n);
if (statSync(p).isDirectory()) walk(p);
else if (/\.ifc$/i.test(n)) files.push(p);
}
};
walk(samples!);
const all: string[] = [];
for (const f of files) {
// Gekrümmte Geometrie wird verschieden fein zerlegt → 3 %.
for (const p of await compare(f, () => 0.03)) all.push(`${f}: ${p}`);
}
expect(all).toEqual([]);
});
});
+193
View File
@@ -0,0 +1,193 @@
// IFC-Import als Mesh ([B3]): dünne Fassade über `import_ifc` im Format-Modul (`src-tauri/fileio`,
// `ifc_import.rs`). Jedes IFC-Bauteil mit Körper wird zu einem `ImportedMesh` der Kontext-Schicht
// (wie der STEP-Import, `stepImport.ts`); echte Bauteile (Wand, Decke …) kommen mit [B4].
//
// Gruppierung: je Bauteil ein Mesh (anwählbar, Name/Geschoss/GlobalId bleiben erhalten, im
// Kontext-Panel nach IFC-Klasse gruppiert über `layer`). Bei sehr vielen Bauteilen (> `MAX_SINGLE`)
// werden Bauteile gleicher Klasse und gleichen Geschosses zusammengelegt, damit Projektdatei und
// Kontext-Panel handhabbar bleiben.
//
// Koordinaten: Meter, Z = Höhe, unverändert aus der Datei — ausser die Datei liegt in
// Landeskoordinaten und das Projekt hat einen Standort-Bezug: dann wird auf den Modell-Nullpunkt
// zurückgeschoben (Gegenstück zu `projectToWorldCoords` beim Export).
import { loadFileio } from "../engine/fileioWasm";
import { GENERIC_IMPORT_CATEGORY } from "../model/contextCategories";
import type { ImportedMesh } from "../model/types";
/** Ein gelesenes IFC-Bauteil. */
export interface IfcProduct {
globalId: string;
/** IFC-Klasse, z. B. `IfcWall`. */
ifcClass: string;
name: string | null;
storey: string | null;
/** RGBA 0..1 aus IfcStyledItem/Material, falls vorhanden. */
color: [number, number, number, number] | null;
/** x,y,z in Metern (Z = Höhe). */
positions: Float64Array;
indices: Uint32Array;
}
/** Bericht des Imports: was gelesen, was übersprungen wurde. */
export interface IfcImportReport {
schema: string;
lengthScale: number;
products: number;
/** Übersprungene Geometrie je IFC-Typ (z. B. `IFCSWEPTDISKSOLID`). */
skippedItems: Record<string, number>;
/** Bewusst ausgelassene Bauteile je Klasse (Öffnungen, Räume …). */
skippedProducts: Record<string, number>;
productsWithoutGeometry: number;
simplifiedBooleans: number;
voidsIgnored: number;
parseErrors: number;
truncated: boolean;
}
interface RawProduct {
globalId: string;
ifcClass: string;
name: string | null;
storey: string | null;
color: [number, number, number, number] | null;
positionCount: number;
indexCount: number;
}
/** Liest IFC-Bytes. Wirft bei unlesbarer Datei (Meldung aus Rust). */
export async function readIfc(bytes: Uint8Array): Promise<{ products: IfcProduct[]; report: IfcImportReport }> {
const m = await loadFileio();
const r = m.import_ifc(bytes);
try {
const meta = JSON.parse(r.meta) as Omit<IfcImportReport, "products"> & { products: RawProduct[] };
const pos = r.positions();
const idx = r.indices();
let po = 0;
let io = 0;
const products: IfcProduct[] = [];
for (const p of meta.products) {
products.push({
globalId: p.globalId,
ifcClass: p.ifcClass,
name: p.name,
storey: p.storey,
color: p.color,
positions: pos.subarray(po, po + p.positionCount),
indices: idx.subarray(io, io + p.indexCount),
});
po += p.positionCount;
io += p.indexCount;
}
return { products, report: { ...meta, products: products.length } };
} finally {
r.free();
}
}
/** Ab so vielen Bauteilen wird je Klasse + Geschoss zusammengelegt. */
export const MAX_SINGLE = 2000;
export interface IfcToMeshesOptions {
/** LV95-Ursprung des Projekts (`projectGeoOrigin`), sonst null. */
geoOrigin?: { e: number; n: number } | null;
/** "product" = je Bauteil, "class" = je Klasse + Geschoss, "auto" (Standard) nach `MAX_SINGLE`. */
group?: "product" | "class" | "auto";
}
let counter = 0;
/** Verschiebung, falls die Datei in Landeskoordinaten liegt und das Projekt einen Bezug hat. */
function geoShift(products: IfcProduct[], origin: { e: number; n: number } | null | undefined): [number, number] {
if (!origin) return [0, 0];
let sx = 0;
let sy = 0;
let n = 0;
for (const p of products) {
for (let i = 0; i + 2 < p.positions.length; i += 3 * 64) {
sx += p.positions[i];
sy += p.positions[i + 1];
n++;
}
}
if (n === 0) return [0, 0];
const cx = sx / n;
const cy = sy / n;
const nearOrigin = Math.hypot(cx - origin.e, cy - origin.n) < Math.hypot(cx, cy);
return nearOrigin ? [-origin.e, -origin.n] : [0, 0];
}
/** Bauteile → Kontext-Meshes (Kategorie „Situation" wie STEP; `layer` = IFC-Klasse). */
export function ifcToImportedMeshes(products: IfcProduct[], fileName: string, opts: IfcToMeshesOptions = {}): ImportedMesh[] {
const base = fileName.replace(/\.[^.]+$/, "") || "IFC";
const [dx, dy] = geoShift(products, opts.geoOrigin);
const stamp = Date.now().toString(36);
const group = opts.group ?? "auto";
const perProduct = group === "product" || (group === "auto" && products.length <= MAX_SINGLE);
const toArrays = (parts: IfcProduct[]): { positions: number[]; indices: number[] } => {
const positions: number[] = [];
const indices: number[] = [];
for (const p of parts) {
const off = positions.length / 3;
for (let i = 0; i + 2 < p.positions.length; i += 3) {
positions.push(p.positions[i] + dx, p.positions[i + 1] + dy, p.positions[i + 2]);
}
for (let i = 0; i < p.indices.length; i++) indices.push(p.indices[i] + off);
}
return { positions, indices };
};
if (perProduct) {
return products.map((p) => ({
id: `imported-ifc-${stamp}-${counter++}`,
type: "importedMesh" as const,
name: [p.storey, p.name || p.ifcClass].filter(Boolean).join(": ") + (p.globalId ? ` [${p.globalId}]` : ""),
layer: p.ifcClass,
categoryCode: GENERIC_IMPORT_CATEGORY.code,
...toArrays([p]),
}));
}
const groups = new Map<string, IfcProduct[]>();
for (const p of products) {
const key = `${p.ifcClass}\u0000${p.storey ?? ""}`;
const g = groups.get(key);
if (g) g.push(p);
else groups.set(key, [p]);
}
return [...groups.values()].map((parts) => ({
id: `imported-ifc-${stamp}-${counter++}`,
type: "importedMesh" as const,
name: `${base}: ${[parts[0].storey, parts[0].ifcClass].filter(Boolean).join(" ")} (${parts.length})`,
layer: parts[0].ifcClass,
categoryCode: GENERIC_IMPORT_CATEGORY.code,
...toArrays(parts),
}));
}
/** Datei-Bytes → Kontext-Meshes + Bericht. */
export async function ifcBytesToImportedMeshes(
bytes: Uint8Array,
fileName: string,
opts: IfcToMeshesOptions = {},
): Promise<{ meshes: ImportedMesh[]; report: IfcImportReport }> {
const { products, report } = await readIfc(bytes);
return { meshes: ifcToImportedMeshes(products, fileName, opts), report };
}
/** Bericht als kurzer Text; `tr` übersetzt (Kern kennt kein i18n, die Hülle reicht `t` herein). */
export function formatIfcReport(
r: IfcImportReport,
tr: (key: "ifc.import.done" | "ifc.import.skipped" | "ifc.import.voids" | "ifc.import.booleans" | "ifc.import.truncated", vars?: Record<string, string | number>) => string,
): string {
const parts = [tr("ifc.import.done", { n: r.products, schema: r.schema || "IFC" })];
const skipped = Object.entries(r.skippedItems)
.map(([k, v]) => `${k} ×${v}`)
.join(", ");
const without = r.productsWithoutGeometry;
if (skipped || without) parts.push(tr("ifc.import.skipped", { n: without, list: skipped || "–" }));
if (r.voidsIgnored) parts.push(tr("ifc.import.voids", { n: r.voidsIgnored }));
if (r.simplifiedBooleans) parts.push(tr("ifc.import.booleans", { n: r.simplifiedBooleans }));
if (r.truncated) parts.push(tr("ifc.import.truncated"));
return parts.join(" · ");
}
+5
View File
@@ -34,6 +34,7 @@ export interface NativeAppMenuHandlers {
onExportStl: () => void;
onExportStep: () => void;
onImportStep: () => void;
onImportIfc: () => void;
onClashCheck: () => void;
onKennzahlen: () => void;
@@ -174,6 +175,10 @@ export function useNativeAppMenu(
text: t("menu.native.importStep"),
action: () => handlersRef.current.onImportStep(),
}),
await MenuItem.new({
text: t("menu.native.importIfc"),
action: () => handlersRef.current.onImportIfc(),
}),
await Submenu.new({
text: t("menu.native.export"),
items: [