[C11] Mesh-Export vollständig: Dächer, Treppen, Stützen, Gelände/Kontext, Knoten je Öffnung; OBJ/STL rechtshändig

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
This commit is contained in:
Claude committed 2026-10-28 14:31:41 +00:00
1 parent 62975760ed
commit 7fb376a05e
7 files changed
+493 -98

No files matched your search

+4 -4
View File
@@ -43,13 +43,13 @@ describe("glTF-Export", () => {
expect(report.issues.numErrors).toBe(0);
});
it("Rundreise: ein Knoten je Bauteil, Dreiecke wie im OBJ (plus Öffnungsteile)", () => {
it("Rundreise: ein Knoten je Bauteil, Dreiecke und Objekte wie im OBJ", () => {
const g = glbJson(exportGlb(sampleProject));
const obj = exportObj(sampleProject);
const objGroups = obj.split("\n").filter((l) => l.startsWith("o "));
const objFaces = obj.split("\n").filter((l) => l.startsWith("f ")).length;
const parts = g.nodes.filter((n) => n.mesh !== undefined);
const element = parts.filter((n) => ["wall", "slab", "extrusion"].includes(n.extras?.type ?? ""));
const element = parts;
expect(element.length).toBe(objGroups.length);
for (const n of element) expect(objGroups).toContain(`o ${n.name}`);
const elementTris = element.reduce(
@@ -57,7 +57,7 @@ describe("glTF-Export", () => {
0,
);
expect(elementTris).toBe(objFaces);
expect(triangles(g)).toBeGreaterThanOrEqual(objFaces);
expect(triangles(g)).toBe(objFaces);
});
it("Geschosse sind Eltern-Knoten der Bauteile; ohne byLevel liegen alle an der Wurzel", () => {
@@ -77,7 +77,7 @@ describe("glTF-Export", () => {
const glass = g.materials.find((m) => m.name === "Glas");
expect(glass?.alphaMode).toBe("BLEND");
expect(glass!.pbrMetallicRoughness.baseColorFactor[3]).toBeLessThan(1);
expect(g.nodes.some((n) => n.extras?.type === "glazing")).toBe(true);
expect(g.nodes.some((n) => n.extras?.type === "window")).toBe(true);
// Wandmaterial trägt den Namen der Komponente.
const names = sampleProject.components.map((c) => c.name);
expect(g.materials.some((m) => names.includes(m.name))).toBe(true);
+214
View File
@@ -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<string, number> {
const verts: number[][] = [];
const out = new Map<string, number>();
let cur = "";
for (const l of obj.split("\n")) {
if (l.startsWith("v ")) verts.push(l.slice(2).trim().split(/\s+/).map(Number));
else if (l.startsWith("o ")) {
cur = l.slice(2).trim();
out.set(cur, 0);
} else if (l.startsWith("f ")) {
const [a, b, c] = l.slice(2).trim().split(/\s+/).map((i) => verts[Number(i) - 1]);
const v =
a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0]);
out.set(cur, (out.get(cur) ?? 0) + v / 6);
}
}
return out;
}
describe("orientOutward", () => {
it("dreht einen innen gewickelten Würfel nach aussen und gleicht gemischte Wicklung an", () => {
const pos = CUBE_POS;
const mixed = CUBE_IDX.slice();
// ein Dreieck umdrehen ⇒ widersprüchliche Wicklung
[mixed[1], mixed[2]] = [mixed[2], mixed[1]];
const inward: number[] = [];
for (let i = 0; i < CUBE_IDX.length; i += 3) inward.push(CUBE_IDX[i], CUBE_IDX[i + 2], CUBE_IDX[i + 1]);
const vol = (idx: number[]) => {
let v = 0;
for (let i = 0; i < idx.length; i += 3) {
const [a, b, c] = [idx[i] * 3, idx[i + 1] * 3, idx[i + 2] * 3];
v +=
pos[a] * (pos[b + 1] * pos[c + 2] - pos[b + 2] * pos[c + 1]) -
pos[a + 1] * (pos[b] * pos[c + 2] - pos[b + 2] * pos[c]) +
pos[a + 2] * (pos[b] * pos[c + 1] - pos[b + 1] * pos[c]);
}
return v / 6;
};
expect(vol(CUBE_IDX)).toBeCloseTo(8, 9);
expect(vol(orientOutward(pos, inward))).toBeCloseTo(8, 9);
expect(vol(orientOutward(pos, mixed))).toBeCloseTo(8, 9);
});
});
describe("Mesh-Export vollständig", () => {
const project = withContext(sampleProject);
it("Achsen rechtshändig: Norden (Modell +y) liegt bei −Z, Höhe bei Y, Ost bei +X — OBJ, STL und glTF", () => {
const obj = exportObj(sampleProject);
const zs = obj.split("\n").filter((l) => l.startsWith("v ")).map((l) => Number(l.split(" ")[3]));
const ys = obj.split("\n").filter((l) => l.startsWith("v ")).map((l) => Number(l.split(" ")[2]));
// Das Beispielhaus liegt bei y = 0 … 4 (Norden), Höhe bis über das Dach.
expect(Math.max(...zs)).toBeLessThan(0.7);
expect(Math.min(...zs)).toBeLessThan(-3.9);
expect(Math.min(...ys)).toBeGreaterThan(-0.5);
expect(Math.max(...ys)).toBeGreaterThan(4);
// STL: gleiche Spanne
const stlZ = exportStl(sampleProject)
.split("\n")
.filter((l) => l.startsWith("vertex "))
.map((l) => Number(l.split(" ")[3]));
expect(Math.min(...stlZ)).toBeCloseTo(Math.min(...zs), 6);
// glTF: Positionen min/max aller Knoten
const g = glbJson(exportGlb(sampleProject));
const minZ = Math.min(...g.accessors.filter((a) => a.min).map((a) => a.min![2]));
expect(minZ).toBeCloseTo(Math.min(...zs), 4);
});
it("alle Bauteile haben ein positives Volumen (Wicklung nach aussen) in OBJ", () => {
const vols = objVolumes(exportObj(project));
expect(vols.size).toBeGreaterThan(10);
for (const [name, v] of vols) {
// Offene Flächen (Gelände) haben kein Volumen.
if (name.startsWith("Gelaende_")) continue;
expect(v, name).toBeGreaterThan(0);
}
expect(vols.get("Kontext_IM1")).toBeCloseTo(8, 6);
});
it("Dächer, Treppen, Stützen, Kontext und Gelände sind Knoten mit Bauteil-id", () => {
const g = glbJson(exportGlb(project));
const by = (type: string) => g.nodes.filter((n) => n.extras?.type === type).map((n) => n.extras!.id);
expect(by("roof")).toEqual((project.roofs ?? []).map((r) => r.id));
expect(by("stair")).toEqual((project.stairs ?? []).map((s) => s.id));
expect(by("column")).toEqual(["C1"]);
expect(by("context")).toEqual(["IM1"]);
expect(by("terrain")).toEqual(["TM1"]);
for (const n of g.nodes.filter((x) => x.extras && x.extras.type !== "level")) expect(nodeTris(g, n)).toBeGreaterThan(0);
});
it("importiertes Mesh trägt seine Farbe (linear umgerechnet), Gelände die Grundfarbe", () => {
const g = glbJson(exportGlb(project));
const node = g.nodes.find((n) => n.extras?.id === "IM1")!;
const mat = g.meshes[node.mesh!].primitives[0].material;
const c = g.materials[mat].pbrMetallicRoughness.baseColorFactor;
expect(c[0]).toBeCloseTo(1, 6);
expect(c[1]).toBeCloseTo(0, 6);
expect(c[2]).toBeCloseTo(0, 6);
});
it("je Öffnung ein Knoten (Fenster_/Tuer_) mit Glas bzw. Rahmen; kein Sammelknoten mehr", () => {
const g = glbJson(exportGlb(project));
const ops = project.openings ?? [];
expect(ops.length).toBeGreaterThan(2);
for (const op of ops) {
const n = g.nodes.find((x) => x.extras?.id === op.id);
expect(n, op.id).toBeDefined();
expect(n!.extras!.type).toBe(op.kind);
expect(n!.name).toBe(`${op.kind === "window" ? "Fenster" : "Tuer"}_${op.id}`);
}
expect(g.nodes.some((n) => n.extras?.type === "glazing" || n.extras?.type === "frame")).toBe(false);
});
it("Dreieckszahl je Bauteilart = Summe der 3D-Ableitungen (Dach, Treppe, Stütze, Öffnungsteile)", () => {
const g = glbJson(exportGlb(project));
const tris = (type: string) => g.nodes.filter((n) => n.extras?.type === type).reduce((s, n) => s + nodeTris(g, n), 0);
const meshTris = (ms: { indices: number[] }[]) => ms.reduce((s, m) => s + m.indices.length / 3, 0);
expect(tris("roof")).toBe(meshTris(emitRoofs(project)));
expect(tris("column")).toBe(meshTris(emitColumns(project)));
expect(tris("window") + tris("door")).toBe(meshTris(emitOpeningMeshes(project, "mittel")));
const stairMeshes = meshTris(emitStairMeshes(project)) + meshTris(emitStairRailings(project));
// Stufen-Prismen: jede Stufe wird zu einem Prisma (2 Kappen + Mantel) — mindestens die Mesh-Dreiecke.
expect(emitStairs(project).length).toBeGreaterThan(0);
expect(tris("stair")).toBeGreaterThanOrEqual(stairMeshes + emitStairs(project).length * 12);
// OBJ und glTF enthalten dieselben Dreiecke
const faces = exportObj(project).split("\n").filter((l) => l.startsWith("f ")).length;
const all = g.nodes.reduce((s, n) => s + nodeTris(g, n), 0);
expect(all).toBe(faces);
});
it("openingParts:false / context:false lassen die Teile weg", () => {
const g = glbJson(exportGlb(project, { openingParts: false, context: false }));
expect(g.nodes.some((n) => n.extras?.type === "window" || n.extras?.type === "door")).toBe(false);
expect(g.nodes.some((n) => n.extras?.type === "context" || n.extras?.type === "terrain")).toBe(false);
expect(g.nodes.some((n) => n.extras?.type === "roof")).toBe(true);
});
it("GLB und .gltf bestehen den Khronos-Validator ohne Fehler", async () => {
const r1 = await validator.validateBytes(exportGlb(project), { maxIssues: 50 });
expect(r1.issues.messages.filter((m) => m.severity === 0)).toEqual([]);
const r2 = await validator.validateString(exportGltf(project), { maxIssues: 50 });
expect(r2.issues.numErrors).toBe(0);
});
});
+7 -4
View File
@@ -9,6 +9,9 @@ import "../engine/fileioWasm.setup";
import { exportObj, exportStl } from "./exportMesh";
import type { Project, Wall, Ceiling, ExtrudedSolid, Opening } from "../model/types";
/** Nur die Wand (ohne Rahmen/Glas der Öffnung): die Tests zählen die Dreiecke des ausgeschnittenen Wandkörpers. */
const WALL_ONLY = { openingParts: false };
/** Gemeinsame Ressourcen-Basis (Komponente/Wandtyp/Deckentyp/Geschoss/Ebene). */
function baseProject(): Project {
return {
@@ -262,14 +265,14 @@ describe("exportStl — ASCII-STL-Export", () => {
// (= Rust-Zerlegung `extrude_layer_segment_with_holes`): 8 solide Langseiten-
// Teilrechtecke (3×3-Gitter minus Loch) × 2 Seiten × 2 Dreiecke = 32,
// + Deckel/Boden/2 Stirnkappen = 8, + 4 Laibungen × 2 = 8 → 48 Dreiecke.
const stl = exportStl(projectWithOpening("window"));
const stl = exportStl(projectWithOpening("window"), WALL_ONLY);
const facetCount = stl.split("\n").filter((l) => l.startsWith("facet normal")).length;
expect(facetCount).toBe(48);
// Die volle Box hätte NUR Ecken bei y∈{0,2.6}, x∈{0,5}. Der Ausschnitt
// führt echte Vertices an den Loch-Rändern ein — Beweis, dass das Loch
// wirklich in der Fläche steckt (nicht bloss eine übergelegte Scheibe).
const verts = parseObjVertices(exportObj(projectWithOpening("window")));
const verts = parseObjVertices(exportObj(projectWithOpening("window"), WALL_ONLY));
const near = (a: number, b: number) => Math.abs(a - b) < 1e-6;
expect(verts.some((v) => near(v[1], 0.9))).toBe(true); // Brüstungs-OK
expect(verts.some((v) => near(v[1], 2.4))).toBe(true); // Sturz-UK
@@ -283,10 +286,10 @@ describe("exportStl — ASCII-STL-Export", () => {
// Tür [x 2..3] × [y 0..2.1]: Boden bekommt die Lücke [2,3] (statt einer
// unteren Laibung) → 5 Langseiten-Teilrechtecke × 2 × 2 = 20, Deckel(1)=2,
// Boden(2 Streifen)=4, 2 Stirnkappen=4, 3 Laibungen (links/rechts/oben)=6 → 36.
const stl = exportStl(projectWithOpening("door"));
const stl = exportStl(projectWithOpening("door"), WALL_ONLY);
const facetCount = stl.split("\n").filter((l) => l.startsWith("facet normal")).length;
expect(facetCount).toBe(36);
const verts = parseObjVertices(exportObj(projectWithOpening("door")));
const verts = parseObjVertices(exportObj(projectWithOpening("door"), WALL_ONLY));
const near = (a: number, b: number) => Math.abs(a - b) < 1e-6;
// Sturz-UK bei y=2.1 vorhanden, aber KEIN Brüstungsvertex (Tür sitzt am Boden).
expect(verts.some((v) => near(v[1], 2.1))).toBe(true);
+230 -71
View File
@@ -30,10 +30,18 @@
// gunsten der pure-Modul-Architektur — ehrlich dokumentiert, kein
// Stillschweigen.
//
// ACHSEN-KONVENTION: identisch zur bestehenden 3D-Pick-/Highlight-Geometrie
// (siehe `selectionHighlightLines` in toWalls3d.ts): Modell (x, y) → Welt
// (x, Höhe, y), Y-UP, rechtshändig. Ein Weltvertex (vx,vy,vz) entspricht also
// (Modell-x, Meter-Höhe, Modell-y) — exakt wie im 3D-Viewer.
// ACHSEN-KONVENTION (intern, Weg zum Schreiber): Modell (x, y, z-hoch) → Welt (x, z, y) wie die
// Pick-/Highlight-Geometrie in toWalls3d.ts (`selectionHighlightLines`). Das ist eine Spiegelung
// des Modells; der Rust-Schreiber stellt für ALLE Formate (OBJ, STL, glTF) die Rechtshändigkeit
// her: Gesamtabbildung Modell (x, y, z-hoch) → Datei (x, z, −y), Norden = −Z.
//
// WEITERE BAUTEILE ([C11], 28.10.): Dächer, Treppen (Tritte, Laufplatte, Handlauf), Stützen,
// Öffnungsteile (je Öffnung ein Knoten), Gelände und importierte Kontext-Meshes. Quelle sind
// dieselben `emit*`-Ableitungen wie im 3D-Viewer (`projectToModel3d`). Diese liefern keine
// Bauteil-ids; deshalb wird jede Ableitung je Bauteil mit einem Projekt aufgerufen, das nur dieses
// Bauteil enthält (reines Lesen, `src/plan` bleibt unverändert). Die Ableitungen schreiben keine
// verlässliche Wicklung (render3d zeichnet doppelseitig): {@link orientOutward} richtet jedes
// geschlossene Teil nach aussen aus.
import type { Project, Vec2 } from "../model/types";
import { getFloor } from "../model/types";
@@ -42,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<string, number>();
const canon = new Array<number>(nVert);
const q = (v: number) => Math.round(v * 1e5);
for (let i = 0; i < nVert; i++) {
const key = `${q(pos[3 * i])},${q(pos[3 * i + 1])},${q(pos[3 * i + 2])}`;
let c = weld.get(key);
if (c === undefined) {
c = weld.size;
weld.set(key, c);
}
canon[i] = c;
}
const N = weld.size + 1;
// Kante (min,max) → [(Dreieck, vorwärts?)…]
const edges = new Map<number, number[]>();
const corner = (t: number, k: number) => canon[idx[3 * t + k]];
for (let t = 0; t < nTri; t++) {
for (let k = 0; k < 3; k++) {
const a = corner(t, k);
const b = corner(t, (k + 1) % 3);
if (a === b) continue;
const key = Math.min(a, b) * N + Math.max(a, b);
const list = edges.get(key);
const entry = t * 2 + (a < b ? 1 : 0);
if (list) list.push(entry);
else edges.set(key, [entry]);
}
}
// Nachbarschaft über Kanten mit genau zwei Dreiecken: Wicklungs-Paritaet (0 = gleich, 1 = gegenläufig noetig).
const adj: number[][] = Array.from({ length: nTri }, () => []);
for (const list of edges.values()) {
if (list.length !== 2) continue;
const [e1, e2] = list;
const t1 = e1 >> 1;
const t2 = e2 >> 1;
if (t1 === t2) continue;
// Gleiche Durchlaufrichtung = Widerspruch ⇒ eines muss gedreht werden.
const parity = (e1 & 1) === (e2 & 1) ? 1 : 0;
adj[t1].push(t2 * 2 + parity);
adj[t2].push(t1 * 2 + parity);
}
const flip = new Array<number>(nTri).fill(-1);
const out = idx.slice();
for (let s = 0; s < nTri; s++) {
if (flip[s] >= 0) continue;
const comp: number[] = [s];
flip[s] = 0;
for (let h = 0; h < comp.length; h++) {
const t = comp[h];
for (const e of adj[t]) {
const u = e >> 1;
if (flip[u] < 0) {
flip[u] = flip[t] ^ (e & 1);
comp.push(u);
}
}
}
// Volumen der Komponente mit den bisherigen Drehungen; Offenheit: Kante mit nur einem Dreieck.
let vol = 0;
for (const t of comp) {
const [a, b, c] = flip[t] ? [idx[3 * t], idx[3 * t + 2], idx[3 * t + 1]] : [idx[3 * t], idx[3 * t + 1], idx[3 * t + 2]];
const A = a * 3;
const B = b * 3;
const C = c * 3;
vol +=
pos[A] * (pos[B + 1] * pos[C + 2] - pos[B + 2] * pos[C + 1]) -
pos[A + 1] * (pos[B] * pos[C + 2] - pos[B + 2] * pos[C]) +
pos[A + 2] * (pos[B] * pos[C + 1] - pos[B + 1] * pos[C]);
}
const turn = vol < 0 ? 1 : 0;
for (const t of comp) {
if (flip[t] ^ turn) {
out[3 * t + 1] = idx[3 * t + 2];
out[3 * t + 2] = idx[3 * t + 1];
}
}
}
return out;
}
/**
* 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<string, MeshPrim>();
for (const m of emitOpeningMeshes(project, "mittel")) {
const glass = sameRgb(m.color, GLASS_COLOR);
const name = glass ? "Glas" : (OPENING_PART_NAMES.find(([c]) => sameRgb(c, m.color))?.[1] ?? "Oeffnungsteil");
const group = glass ? glazing : frames;
const key = `${glass}|${name}`;
let prim = prims.get(key);
if (!prim) {
// Glas transparent und glatt (BLEND), Rahmen matt.
const mat = glass ? mats.get(name, m.color, 0.35, 0, 0.05) : mats.get(name, m.color, 1, 0, 0.6);
prim = newPrim(group, mat);
prims.set(key, prim);
}
// Modell (x, y, z-hoch) → Welt (x, z, y); danach Wicklung so, dass das Volumen positiv ist.
const pos: number[] = [];
for (let i = 0; i + 2 < m.positions.length; i += 3) pos.push(m.positions[i], m.positions[i + 2], m.positions[i + 1]);
let idx = m.indices;
if (signedVolume(pos, idx) < 0) {
idx = [];
for (let i = 0; i + 2 < m.indices.length; i += 3) idx.push(m.indices[i], m.indices[i + 2], m.indices[i + 1]);
}
const base = prim.positions.length / 3;
for (const p of pos) prim.positions.push(p);
for (const i of idx) prim.indices.push(base + i);
// Dächer, Stützen, Treppen: je Bauteil EIN Aufruf der 3D-Ableitung mit einem Projekt, das nur dieses
// Bauteil enthält — so tragen die Meshes die Bauteil-id (die Ableitungen liefern keine).
const addMeshes = (g: MeshGroup, meshes: RMesh[], name: string, closed = true) => {
for (const m of meshes) {
if (m.indices.length === 0) continue;
appendModelMesh(newPrim(g, mats.get(name, m.color)), m.positions, m.indices, closed);
}
};
for (const roof of project.roofs ?? []) {
const g = newGroup(`Dach_${sanitizeName(roof.id)}`, "roof", roof.id, levelOf(roof.floorId));
addMeshes(g, emitRoofs({ ...project, roofs: [roof] }), "Dach");
groups.push(g);
}
for (const col of project.columns ?? []) {
const g = newGroup(`Stuetze_${sanitizeName(col.id)}`, "column", col.id, levelOf(col.floorId));
addMeshes(g, emitColumns({ ...project, columns: [col] }), componentName(col.componentId, "Stuetze"));
groups.push(g);
}
for (const stair of project.stairs ?? []) {
const one: Project = { ...project, stairs: [stair] };
const g = newGroup(`Treppe_${sanitizeName(stair.id)}`, "stair", stair.id, levelOf(stair.floorId));
for (const s of emitStairs(one)) {
const outline: Vec2[] = s.outline.map(([x, y]) => ({ x, y }));
pushPrism(newPrim(g, mats.get("Treppe", s.color)), outline, s.zBottom, s.zTop);
}
addMeshes(g, emitStairMeshes(one), "Treppe");
addMeshes(g, emitStairRailings(one), "Handlauf");
groups.push(g);
}
// Öffnungsteile: je Öffnung ein Knoten (Name Fenster_<id>/Tuer_<id>) mit Glas und den Rahmenteilen als
// Teil-Meshes je Material. Auch hier die Ableitung nur mit der Wirtswand und dieser Öffnung.
if (opts.openingParts ?? true) {
for (const op of project.openings ?? []) {
const host = project.walls.find((w) => w.id === op.hostWallId);
if (!host) continue;
const parts = emitOpeningMeshes({ ...project, walls: [host], openings: [op] }, "mittel");
if (parts.length === 0) continue;
const g = newGroup(`${op.kind === "window" ? "Fenster" : "Tuer"}_${sanitizeName(op.id)}`, op.kind, op.id, levelOf(host.floorId));
const prims = new Map<string, MeshPrim>();
for (const m of parts) {
const glass = sameRgb(m.color, GLASS_COLOR);
const name = glass ? "Glas" : (OPENING_PART_NAMES.find(([c]) => sameRgb(c, m.color))?.[1] ?? "Oeffnungsteil");
let prim = prims.get(name);
if (!prim) {
// Glas transparent und glatt (BLEND), Rahmen matt.
const mat = glass ? mats.get(name, m.color, 0.35, 0, 0.05) : mats.get(name, m.color, 1, 0, 0.6);
prim = newPrim(g, mat);
prims.set(name, prim);
}
appendModelMesh(prim, m.positions, m.indices, true);
}
groups.push(g);
}
}
// Gelände und importierte Meshes (IFC/DXF): Farbe der Quelle, falls gesetzt.
if (opts.context ?? true) {
for (const obj of project.context ?? []) {
if (obj.type !== "terrainMesh" && obj.type !== "importedMesh") continue;
if (obj.positions.length < 9 || obj.indices.length < 3) continue;
const terrain = obj.type === "terrainMesh";
const rgb: Rgb = !terrain && obj.color ? hexToRgb(obj.color, IMPORTED_RGB) : terrain ? TERRAIN_RGB : IMPORTED_RGB;
const g = newGroup(`${terrain ? "Gelaende" : "Kontext"}_${sanitizeName(obj.id)}`, terrain ? "terrain" : "context", obj.id, -1);
const prim = newPrim(g, mats.get(terrain ? "Gelaende" : obj.name || "Kontext", rgb));
appendModelMesh(prim, obj.positions, obj.indices, false);
groups.push(g);
}
for (const g of [glazing, frames]) if (g.prims.length > 0) groups.push(g);
}
return {
@@ -420,9 +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<T extends string | Uint8Array>(project: Project, parts: boolean, byLevel: boolean, run: (m: ReturnType<typeof fileio>, buf: Float64Array, strings: string) => T): T {
function write<T extends string | Uint8Array>(project: Project, opts: MeshOptions, byLevel: boolean, run: (m: ReturnType<typeof fileio>, buf: Float64Array, strings: string) => T): T {
const m = fileio();
const [buf, strings] = encodeScene(buildScene(project, parts), byLevel);
const [buf, strings] = encodeScene(buildScene(project, opts), byLevel);
const out = run(m, buf, strings);
if (out.length === 0) {
const why = m.export_mesh_check_flat(buf, strings);
@@ -432,41 +589,43 @@ function write<T extends string | Uint8Array>(project: Project, parts: boolean,
}
/**
* Baut einen vollständigen Wavefront-OBJ-String des 3D-Gebäudemodells (Meter, Y-up — siehe Moduldoc).
* Ein `o`-Objekt je Bauteil-Vorkommen (Wand/Decke/Extrusion). Leeres Projekt ⇒ gültige Datei nur mit
* Baut einen vollständigen Wavefront-OBJ-String des 3D-Gebäudemodells (Meter, Y-up rechtshändig:
* Modell (x, y, z-hoch) → (x, z, −y), siehe Moduldoc). Ein `o`-Objekt je Bauteil-Vorkommen (Wand, Decke,
* Extrusion, Dach, Treppe, Stütze, Fenster/Tür, Kontext-Mesh). Leeres Projekt ⇒ gültige Datei nur mit
* Kopf-Kommentaren. Verlangt das geladene Format-Modul (`await loadFileio()`).
*/
export function exportObj(project: Project): string {
return write(project, false, false, (m, b, s) => m.export_mesh_obj_flat(b, s));
export function exportObj(project: Project, opts: MeshOptions = {}): string {
return write(project, opts, false, (m, b, s) => m.export_mesh_obj_flat(b, s));
}
/**
* Baut einen vollständigen ASCII-STL-String (Meter, dieselbe Achsen-Konvention wie {@link exportObj});
* je Dreieck eine Facettennormale. Leeres Projekt ⇒ gültiges leeres `solid`-Gerüst. Verlangt das
* geladene Format-Modul (`await loadFileio()`).
* Baut einen vollständigen ASCII-STL-String (Meter, dieselben Achsen wie {@link exportObj}); je Dreieck
* eine Facettennormale. Leeres Projekt ⇒ gültiges leeres `solid`-Gerüst. Verlangt das geladene
* Format-Modul (`await loadFileio()`).
*/
export function exportStl(project: Project): string {
return write(project, false, false, (m, b, s) => m.export_mesh_stl_flat(b, s));
export function exportStl(project: Project, opts: MeshOptions = {}): string {
return write(project, opts, false, (m, b, s) => m.export_mesh_stl_flat(b, s));
}
/** Optionen des glTF-Exports. */
export interface GltfOptions {
export interface GltfOptions extends MeshOptions {
/** Geschoss als Eltern-Knoten der Bauteile (Standard: ja). */
byLevel?: boolean;
}
/**
* glTF 2.0 binär (GLB) für Blender, Twinmotion, Enscape, Web-Viewer. Ein Knoten je Bauteil (Name
* `Wand_<id>`/`Decke_<id>`/`Extrusion_<id>`, `extras` = Typ + id), PBR-Materialien mit der Farbe der
* Bauteilschicht, Verglasung transparent (`BLEND`), Geschosse als Eltern-Knoten. Meter; die Achsen
* folgen der glTF-Konvention (rechtshändig, Y-up): Modell (x, y, z-hoch) → (x, z, −y), Norden = −Z.
* Verlangt das geladene Format-Modul (`await loadFileio()`).
* `Wand_<id>`, `Decke_<id>`, `Dach_<id>`, `Treppe_<id>`, `Stuetze_<id>`, `Fenster_<id>`, `Tuer_<id>`,
* `Extrusion_<id>`, `Kontext_<id>`, `Gelaende_<id>`; `extras` = Typ + id), PBR-Materialien mit der
* Farbe der Bauteilschicht, Verglasung transparent (`BLEND`), Geschosse als Eltern-Knoten. Meter;
* rechtshändig, Y-up: Modell (x, y, z-hoch) → (x, z, −y), Norden = −Z. Verlangt das geladene
* Format-Modul (`await loadFileio()`).
*/
export function exportGlb(project: Project, opts: GltfOptions = {}): Uint8Array {
return write(project, true, opts.byLevel ?? true, (m, b, s) => m.export_mesh_glb_flat(b, s));
return write(project, opts, opts.byLevel ?? true, (m, b, s) => m.export_mesh_glb_flat(b, s));
}
/** Wie {@link exportGlb}, aber als `.gltf` (JSON, Puffer als Base64-Data-URI eingebettet). */
export function exportGltf(project: Project, opts: GltfOptions = {}): string {
return write(project, true, opts.byLevel ?? true, (m, b, s) => m.export_mesh_gltf_flat(b, s));
return write(project, opts, opts.byLevel ?? true, (m, b, s) => m.export_mesh_gltf_flat(b, s));
}