From 7fb376a05e9de19d83e3b7cb561b2425ff2b4d91 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 14:31:41 +0000 Subject: [PATCH] =?UTF-8?q?[C11]=20Mesh-Export=20vollst=C3=A4ndig:=20D?= =?UTF-8?q?=C3=A4cher,=20Treppen,=20St=C3=BCtzen,=20Gel=C3=A4nde/Kontext,?= =?UTF-8?q?=20Knoten=20je=20=C3=96ffnung;=20OBJ/STL=20rechtsh=C3=A4ndig?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Quelle sind dieselben emit*-Ableitungen wie im 3D, je Bauteil mit einem Ein-Bauteil-Projekt aufgerufen (ids), Wicklung nach aussen ausgerichtet. Fenster/Tür-Teile je Öffnung ein Knoten mit Öffnungs-id, auch in OBJ/STL. OBJ/STL-Achsen wie glTF: (x, y, z-hoch) -> (x, z, -y). Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67 --- README.md | 2 +- TODO.md | 19 +- src-tauri/fileio/src/mesh_export.rs | 36 +-- src/export/exportGltf.test.ts | 8 +- src/export/exportMesh.complete.test.ts | 214 ++++++++++++++++++ src/export/exportMesh.test.ts | 11 +- src/export/exportMesh.ts | 301 +++++++++++++++++++------ 7 files changed, 493 insertions(+), 98 deletions(-) create mode 100644 src/export/exportMesh.complete.test.ts diff --git a/README.md b/README.md index 72d1cbed..c9594d5c 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/TODO.md b/TODO.md index 4f4ebea9..8d43855f 100644 --- a/TODO.md +++ b/TODO.md @@ -581,11 +581,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_`), Treppen (`Treppe_`: Tritt-Prismen, + Ortbeton-Laufplatte, Handlauf), Stützen (`Stuetze_`), Gelände (`Gelaende_`) und importierte IFC/DXF-Meshes + (`Kontext_`, mit `color`, falls gesetzt) in OBJ, STL und glTF; Verglasung/Rahmen je Öffnung ein Knoten + (`Fenster_`/`Tuer_`, `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 diff --git a/src-tauri/fileio/src/mesh_export.rs b/src-tauri/fileio/src/mesh_export.rs index 830b3799..147ba6f7 100644 --- a/src-tauri/fileio/src/mesh_export.rs +++ b/src-tauri/fileio/src/mesh_export.rs @@ -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"); } diff --git a/src/export/exportGltf.test.ts b/src/export/exportGltf.test.ts index 8e739a42..a93ec5e3 100644 --- a/src/export/exportGltf.test.ts +++ b/src/export/exportGltf.test.ts @@ -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); diff --git a/src/export/exportMesh.complete.test.ts b/src/export/exportMesh.complete.test.ts new file mode 100644 index 00000000..9c7db853 --- /dev/null +++ b/src/export/exportMesh.complete.test.ts @@ -0,0 +1,214 @@ +// 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, orientOutward } from "./exportMesh"; +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 { + const verts: number[][] = []; + const out = new Map(); + 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); + }); +}); diff --git a/src/export/exportMesh.test.ts b/src/export/exportMesh.test.ts index 9fc5ccba..fb2559b7 100644 --- a/src/export/exportMesh.test.ts +++ b/src/export/exportMesh.test.ts @@ -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); diff --git a/src/export/exportMesh.ts b/src/export/exportMesh.ts index 1696e134..39681d61 100644 --- a/src/export/exportMesh.ts +++ b/src/export/exportMesh.ts @@ -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,6 +50,11 @@ 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"; /** @@ -57,10 +70,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 +244,121 @@ function pushPrism( } } +/** + * 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(); + const canon = new Array(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(); + 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(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; +} + +/** + * 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 +406,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 +470,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(); - 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_/Tuer_) 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(); + 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 +577,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(project: Project, parts: boolean, byLevel: boolean, run: (m: ReturnType, buf: Float64Array, strings: string) => T): T { +function write(project: Project, opts: MeshOptions, byLevel: boolean, run: (m: ReturnType, 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 +589,43 @@ function write(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_`/`Decke_`/`Extrusion_`, `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_`, `Decke_`, `Dach_`, `Treppe_`, `Stuetze_`, `Fenster_`, `Tuer_`, + * `Extrusion_`, `Kontext_`, `Gelaende_`; `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)); }