[C12][B3] 3D-Modell importieren: Fassade, Worker, Dialog (Einheit/Achse/Platzierung), Menue, Drag & Drop, CLI import-mesh

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-28 16:15:00 +00:00
1 parent c978c39dba
commit a395f050d6
15 files changed
+1221 -4

No files matched your search

+66
View File
@@ -0,0 +1,66 @@
// dossier-cli import-mesh und convert mit Mesh-Eingabe: Rundreise über echte Dateien (glb, gltf, obj+mtl, stl).
import { beforeAll, describe, expect, it } from "vitest";
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { run } from "./main";
import { parseProjectFile, sampleProject, serializeProject } from "../core";
import type { Project } from "../core";
const dir = mkdtempSync(join(tmpdir(), "dossier-import-mesh-"));
const p = (name: string) => join(dir, name);
const obp = p("demo.obp");
/** Projektdatei lesen; schlägt der Test fehl, wenn sie ungültig ist. */
function load(path: string): Project {
const r = parseProjectFile(readFileSync(path, "utf8"));
if (!r.ok) throw new Error(r.error);
return r.project;
}
beforeAll(() => {
process.env.DOSSIER_WASM_DIR = join(process.cwd(), "src", "engine");
writeFileSync(obp, serializeProject(sampleProject));
});
describe("dossier-cli: Mesh-Import", () => {
it("convert: glb/gltf/obj/stl → obp mit Kontext-Meshes", async () => {
for (const ext of ["glb", "gltf", "obj", "stl"]) {
expect(await run(["convert", obp, p(`m.${ext}`)]), ext).toBe(0);
const out = p(`von-${ext}.obp`);
expect(await run(["convert", p(`m.${ext}`), out]), ext).toBe(0);
const project = load(out);
const ctx = project.context ?? [];
expect(ctx.length, ext).toBeGreaterThan(0);
expect(ctx.every((c) => c.type === "importedMesh" && c.indices.length > 0), ext).toBe(true);
}
}, 120_000);
it("import-mesh: glTF mit Farbe, --out schreibt das Projekt", async () => {
const out = p("import.obp");
expect(await run([obp, "import-mesh", p("m.glb"), "--out", out, "--placement", "original"])).toBe(0);
const project = load(out);
const before = sampleProject.context?.length ?? 0;
expect((project.context ?? []).length).toBeGreaterThan(before);
// Wände des Beispielprojekts haben Farben aus ihren Bauteilen.
expect((project.context ?? []).some((c) => c.type === "importedMesh" && typeof c.color === "string")).toBe(true);
}, 120_000);
it("import-mesh: OBJ mit MTL aus dem Verzeichnis, Einheit und Achse", async () => {
writeFileSync(p("z.obj"), "mtllib z.mtl\no Kiste\nusemtl rot\nv 0 0 0\nv 1000 0 0\nv 0 1000 0\nv 0 0 2000\nf 1 3 2\nf 1 2 4\nf 2 3 4\nf 3 1 4\n");
writeFileSync(p("z.mtl"), "newmtl rot\nKd 1 0 0\n");
const out = p("z.obp");
expect(await run([obp, "import-mesh", p("z.obj"), "--unit", "mm", "--up", "z", "--placement", "original", "--out", out])).toBe(0);
const project = load(out);
const m = (project.context ?? []).find((c) => c.name === "Kiste");
if (m?.type !== "importedMesh") throw new Error("Kiste fehlt");
expect(m.color).toBe("#ff0000");
expect(Math.max(...m.positions.filter((_, i) => i % 3 === 2))).toBeCloseTo(2, 9);
}, 60_000);
it("ungültige Optionen und kaputte Dateien: Exit-Code ≠ 0", async () => {
expect(await run([obp, "import-mesh", p("z.obj"), "--unit", "km"]).catch(() => 1)).not.toBe(0);
writeFileSync(p("kaputt.glb"), "kein glb");
expect(await run([obp, "import-mesh", p("kaputt.glb")]).catch(() => 1)).not.toBe(0);
}, 60_000);
});
+79 -3
View File
@@ -17,6 +17,8 @@
// dossier-cli <projekt.obp> import-ifc <datei.ifc> [--out neu.obp] [--group product|class] [--elements]
// IFC als Kontext-Meshes ([B3]), mit --elements als echte
// Bauteile ([B4]); Bericht als JSON auf stdout
// dossier-cli <projekt.obp> import-mesh <datei.obj|stl|gltf|glb|ply> [--out neu.obp] [--unit mm|cm|m|inch|foot] [--up z|y|auto]
// [--placement center|original] 3D-Modell als Kontext-Meshes; Bericht als JSON
// dossier-cli <projekt.obp> model3d [--out modell.json] 3D-Modell fürs Headless-Rendern (render_png)
// dossier-cli pointcloud-info <datei.las|laz|e57|ply|xyz|pts> [--voxel 0.05] [--max 2000000]
// Punktwolke lesen ([B9]) und Bericht als JSON (ohne Projekt)
@@ -46,6 +48,10 @@ import {
readIfcElements,
ifcElementsToProject,
ifcToImportedMeshes,
readMesh,
meshObjectsToImportedMeshes,
isMeshFile,
MESH_UNITS,
projectGeoOrigin,
ensureContextCategories,
projectToWorldCoords,
@@ -270,8 +276,8 @@ export async function run(argv: string[]): Promise<number> {
if (file === "pdf-info") return runPdfInfo(args, command);
if (!file || (!command && args.cmds.length === 0)) {
process.stderr.write(
"Aufruf: dossier-cli <projekt.obp> <info|validate|migrate|plan|section|elevation|dxf|dwg|ifc|import-ifc|step|obj|stl|glb|gltf|schedule|kennzahlen|sun|model3d> [Optionen]\n" +
" dossier-cli convert <eingabe.dxf|dwg|ifc|pdf|obp> <ausgabe.obp|dxf|dwg|ifc|obj|stl|glb|gltf|step> [--cmd \"befehl …\"]…\n" +
"Aufruf: dossier-cli <projekt.obp> <info|validate|migrate|plan|section|elevation|dxf|dwg|ifc|import-ifc|import-mesh|step|obj|stl|glb|gltf|schedule|kennzahlen|sun|model3d> [Optionen]\n" +
" dossier-cli convert <eingabe.dxf|dwg|ifc|pdf|obj|stl|gltf|glb|ply|obp> <ausgabe.obp|dxf|dwg|ifc|obj|stl|glb|gltf|step> [--cmd \"befehl …\"]…\n" +
" dossier-cli <projekt.obp> --cmd \"befehl …\" [--cmd …] ({last} = zuletzt geschriebene Datei)\n" +
" dossier-cli pointcloud-info <datei> [--voxel 0.05] [--max 2000000]\n" +
" dossier-cli bcf-info <datei.bcfzip>\n" +
@@ -331,6 +337,7 @@ async function importAny(path: string, args: Args): Promise<Project> {
const fileName = path.split(/[\\/]/).pop() ?? path;
const base: Project = { ...emptyProject, name: fileName.replace(/\.[^.]+$/, "") };
if (ext === "ifc") return (await ifcInto(base, bytes, fileName, args)).next;
if (isMeshFile(fileName)) return (await meshInto(base, bytes, path, args)).next;
if (ext === "dxf" || ext === "dwg" || ext === "pdf") {
await loadFileio();
let parsed;
@@ -363,7 +370,7 @@ async function importAny(path: string, args: Args): Promise<Project> {
];
return applyOps(base, diffToOps(base, { ...base, layers, drawings2d: drawings, context: [...parsed.meshes] }));
}
return fail(`Eingabeformat nicht unterstützt: .${ext} (obp, dxf, dwg, ifc, pdf)`);
return fail(`Eingabeformat nicht unterstützt: .${ext} (obp, dxf, dwg, ifc, pdf, obj, stl, gltf, glb, ply)`);
}
/** `convert <eingabe> <ausgabe>`: Eingabe nach Endung lesen, Ausgabe nach Endung schreiben, dann `--cmd` ausführen. */
@@ -430,6 +437,60 @@ async function ifcInto(project: Project, bytes: Uint8Array, fileName: string, ar
return { next, report: { ...report, byClass, triangles, contextObjects: meshes.length } };
}
/** Begleitdateien eines Mesh-Modells aus demselben Verzeichnis: `.mtl` (OBJ `mtllib`), externe `.bin` (glTF). */
function meshSidecars(path: string, bytes: Uint8Array): { name: string; bytes: Uint8Array }[] {
const names: string[] = [];
const ext = extOf(path);
if (ext === "obj") {
for (const m of new TextDecoder().decode(bytes.subarray(0, Math.min(bytes.length, 1 << 20))).matchAll(/^mtllib[ \t]+(.+)$/gm)) {
names.push(...m[1].trim().split(/\s+/));
}
} else if (ext === "gltf") {
try {
const j = JSON.parse(new TextDecoder().decode(bytes)) as { buffers?: { uri?: string }[] };
for (const b of j.buffers ?? []) if (b.uri && !b.uri.startsWith("data:")) names.push(decodeURIComponent(b.uri));
} catch {
/* kaputtes JSON meldet der Leser */
}
}
const out: { name: string; bytes: Uint8Array }[] = [];
for (const n of names) {
try {
out.push({ name: n, bytes: new Uint8Array(readFileSync(join(dirname(path), n))) });
} catch {
/* fehlende Datei meldet der Leser (MTL: Hinweis, glTF: Fehler) */
}
}
return out;
}
/** 3D-Modell (OBJ/STL/glTF/GLB/PLY) als Kontext-Meshes in ein Projekt übernehmen; `report` = Bericht für `import-mesh`. */
async function meshInto(project: Project, bytes: Uint8Array, path: string, args: Args): Promise<{ next: Project; report: unknown }> {
const fileName = path.split(/[\\/]/).pop() ?? path;
const unit = args.flags.get("unit") ?? "m";
if (!(MESH_UNITS as readonly string[]).includes(unit)) return fail(`--unit: ${MESH_UNITS.join("|")}`);
const up = args.flags.get("up") ?? "auto";
if (up !== "auto" && up !== "z" && up !== "y") return fail("--up: z|y|auto");
const placement = args.flags.get("placement") ?? "original";
if (placement !== "center" && placement !== "original") return fail("--placement: center|original");
let read;
try {
read = await readMesh(bytes, fileName, { unit: unit as (typeof MESH_UNITS)[number], up, files: meshSidecars(path, bytes) });
} catch (e) {
return fail(`${path}: ${e instanceof Error ? e.message : String(e)}`);
}
const meshes = meshObjectsToImportedMeshes(read.objects, fileName, { placement, geoOrigin: projectGeoOrigin(project) });
const next = applyOps(
project,
diffToOps(project, {
...project,
context: [...(project.context ?? []), ...meshes],
layers: ensureContextCategories(project.layers, meshes.flatMap((m) => (m.categoryCode ? [m.categoryCode] : []))),
}),
);
return { next, report: { ...read.report, contextObjects: meshes.length } };
}
/** Führt EINEN Befehl gegen ein geladenes Projekt aus (Rückgabe = Exit-Code). */
async function execute(project: Project, file: string, command: string, rest: string[], args: Args): Promise<number> {
const scale = Number(args.flags.get("scale") ?? 100);
@@ -582,6 +643,21 @@ async function execute(project: Project, file: string, command: string, rest: st
if (target) out(args, serializeProject(r.next), target);
return 0;
}
case "import-mesh": {
const src = rest[0];
if (!src) fail("import-mesh: Modelldatei 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 r = await meshInto(project, bytes, src, args);
process.stdout.write(JSON.stringify(r.report, null, 2) + "\n");
const target = args.flags.get("out");
if (target) out(args, serializeProject(r.next), target);
return 0;
}
case "mcp":
await serveStdio(file);
return 0;