[B3] IFC-Import als Mesh: STEP-Leser und Geometrie in Rust (fileio), Kontext-Meshes je Bauteil
- src-tauri/fileio/src/ifc_step.rs: ISO-10303-21-Leser (\X2\/\X4\/\X\/\S\, komplexe Instanzen, Fehlererholung, Grenzen), eigener Code. - src-tauri/fileio/src/ifc_import.rs: IfcExtrudedAreaSolid (Arbitrary/Rechteck/Kreis/I/L/U/T/Derived/ Composite, Löcher, Polyline/IndexedPolyCurve/CompositeCurve/TrimmedCurve), FacetedBrep, Shell-/ FaceBasedSurfaceModel, Triangulated-/PolygonalFaceSet, MappedItem, Block, CSG, Boolean (Union ganz, sonst 1. Operand), Platzierungsketten, Einheiten mit Präfix/Umrechnung, Geschoss, Farbe; Unbekanntes wird gezählt, nie Panic. Bindung import_ifc (Float64Array/Uint32Array + JSON-Bericht). - src/io/ifcImport.ts: Fassade, je Bauteil ein ImportedMesh (Ebene = IFC-Klasse, ab 2000 Bauteilen je Klasse+Geschoss), Rückschub aus LV95 bei Standort-Bezug; App: Menü „IFC importieren …“, Import-Dialog und Drag & Drop für .ifc; CLI import-ifc (Bericht als JSON, --out neues Projekt; Plan zeigt jetzt verschachtelte Ebenen-Codes). - Tests: Rust je Geometrietyp + Unsinn; Rundreise mit exportIfcSpf (Bauteile je Klasse, Volumen je Wand/Decke); Gegencheck mit ifcopenshell (scripts/ifc-import-compare.py), optional DOSSIER_IFC_SAMPLES für die buildingSMART-Beispieldateien. - earcutr (ISC) als Abhängigkeit, NOTICE.
This commit is contained in:
16 files changed
+3228
-7
No files matched your search
+40
-3
@@ -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
@@ -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;
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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([]);
|
||||
});
|
||||
});
|
||||
@@ -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(" · ");
|
||||
}
|
||||
@@ -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: [
|
||||
|
||||
Reference in new issue
Block a user