[211] Rendering mit Blender/Cycles: Export-Paket, Skript, Dialog, CLI
Paket model.glb + scene.json + textures (renderer-neutral, doc/RENDER-SZENE.md): Kamera der 3D-Ansicht, Sonne aus dem Sonnenstand, PBR-Materialtabelle mit Glas und ambientCG-Karten (Box-Projektion ohne UVs). scripts/blender/render_dossier.py (Cycles, Himmel mit Sonne, Denoiser, GPU/Metal wenn vorhanden). Dialog "Rendering mit Blender" (Befehl rendering, Menue Ansicht, Pfad in den Einstellungen), Fortschritt, Abbrechen, Speichern; Tauri blender.rs + Capabilities, Electron electron-blender.cjs, Browser: ZIP. CLI: render --out bild.png [--view --when --samples --size --cpu --blender]. Nicht in der Tauri-App/auf dem Mac geprueft.
This commit is contained in:
30 files changed
+2595
-8
No files matched your search
@@ -0,0 +1,234 @@
|
||||
// [211] Rendering mit Blender: Szenen-JSON (Kamera, Sonne aus dem Sonnenstand, Materialzuordnung), Paket und
|
||||
// Prozess-Ablauf gegen einen gemockten Gastgeber. Blender selbst läuft hier nicht.
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import "../engine/fileioWasm.setup";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { buildComplexSampleProject } from "../model/sampleProjectComplex";
|
||||
import type { Project } from "../model/types";
|
||||
import { projectLatLon, sunPosition } from "../analysis/sun";
|
||||
import {
|
||||
BlenderMissingError,
|
||||
RenderCancelled,
|
||||
blenderArgs,
|
||||
buildRenderPackage,
|
||||
defaultRenderTime,
|
||||
glbMaterials,
|
||||
paperPixels,
|
||||
parseBlenderLine,
|
||||
renderSun,
|
||||
runBlenderRender,
|
||||
type BlenderHost,
|
||||
type RenderOptions,
|
||||
} from "./blenderRender";
|
||||
import { exportGlb } from "./exportMesh";
|
||||
|
||||
const when = new Date(Date.UTC(2026, 5, 21, 10, 0, 0));
|
||||
const opts = (over: Partial<RenderOptions> = {}): RenderOptions => ({ width: 640, height: 360, samples: 16, when, camera: { preset: "iso" }, ...over });
|
||||
|
||||
describe("Sonne und Kamera in scene.json", () => {
|
||||
it("Sonne = Sonnenstand des Projekts am gewählten Zeitpunkt", () => {
|
||||
const { lat, lon } = projectLatLon(sampleProject);
|
||||
const s = sunPosition(lat, lon, when);
|
||||
const r = renderSun(sampleProject, when);
|
||||
expect(r.azimuth).toBeCloseTo(s.azimuth, 9);
|
||||
expect(r.elevation).toBeCloseTo(s.elevation, 9);
|
||||
expect(r.when).toBe("2026-06-21T10:00:00.000Z");
|
||||
// Mittsommer, Vormittag in Zürich: Sonne im Südosten und hoch.
|
||||
expect(r.azimuth).toBeGreaterThan(90);
|
||||
expect(r.azimuth).toBeLessThan(180);
|
||||
expect(r.elevation).toBeGreaterThan(40);
|
||||
});
|
||||
|
||||
it("Vorbelegung der Zeit aus der Sonnenstudie, sonst Mittsommer", () => {
|
||||
const p: Project = { ...sampleProject, sunStudy: { when: "2026-12-21T11:00:00Z", show: true } };
|
||||
expect(defaultRenderTime(p).toISOString()).toBe("2026-12-21T11:00:00.000Z");
|
||||
expect(defaultRenderTime({ ...sampleProject, sunStudy: undefined }).getUTCMonth()).toBe(5);
|
||||
expect(defaultRenderTime({ ...sampleProject, sunStudy: { when: "kaputt", show: true } }).getUTCMonth()).toBe(5);
|
||||
});
|
||||
|
||||
it("A-Formate bei 300 dpi", () => {
|
||||
expect(paperPixels("a4", "landscape", 300)).toEqual({ width: 3508, height: 2480 });
|
||||
expect(paperPixels("a3", "portrait", 300)).toEqual({ width: 3508, height: 4961 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Materialien aus dem GLB", () => {
|
||||
it("Farbe sRGB, Rauheit, Glas = Alpha-Blend mit Deckkraft < 1", () => {
|
||||
const mats = glbMaterials(exportGlb(buildComplexSampleProject()));
|
||||
expect(mats.length).toBeGreaterThan(2);
|
||||
const glass = mats.filter((m) => m.glass);
|
||||
expect(glass.length).toBeGreaterThan(0);
|
||||
for (const g of glass) expect(g.opacity).toBeLessThan(1);
|
||||
for (const m of mats.filter((m) => !m.glass)) {
|
||||
expect(m.opacity).toBe(1);
|
||||
expect(m.color.every((c) => c >= 0 && c <= 1)).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Paket", () => {
|
||||
it("GLB, scene.json und Materialtabelle; Kamera der Ansicht wird übernommen", async () => {
|
||||
const camera = { kind: "perspective" as const, position: [10, -12, 8] as [number, number, number], direction: [-0.5, 0.7, -0.5] as [number, number, number], up: [0, 0, 1] as [number, number, number], fovDeg: 50, orthoHeight: 0 };
|
||||
const pkg = await buildRenderPackage(sampleProject, opts({ camera, samples: 64 }));
|
||||
expect(pkg.files.map((f) => f.path)).toEqual(["model.glb", "scene.json"]);
|
||||
const json = JSON.parse(new TextDecoder().decode(pkg.files[1].bytes));
|
||||
expect(json.camera).toEqual(camera);
|
||||
expect(json.resolution).toEqual({ width: 640, height: 360 });
|
||||
expect(json.samples).toBe(64);
|
||||
expect(json.denoise).toBe(true);
|
||||
expect(json.model).toBe("model.glb");
|
||||
expect(json.sun.azimuth).toBeCloseTo(renderSun(sampleProject, when).azimuth, 9);
|
||||
expect(json.materials.length).toBeGreaterThan(0);
|
||||
const glb = pkg.files[0].bytes;
|
||||
expect(new DataView(glb.buffer, glb.byteOffset).getUint32(0, true)).toBe(0x46546c67);
|
||||
});
|
||||
|
||||
it("Texturen aus dem Material-System: nach Bauteilname zugeordnet, einmal gespeichert, fehlende gemeldet", async () => {
|
||||
// Bauteil, das im GLB vorkommt: dessen Name steht in der Materialtabelle.
|
||||
const names = new Set(glbMaterials(exportGlb(sampleProject)).map((m) => m.name));
|
||||
const comp = sampleProject.components.find((c) => names.has(c.name));
|
||||
expect(comp).toBeDefined();
|
||||
const withMat: Project = {
|
||||
...sampleProject,
|
||||
components: sampleProject.components.map((c) =>
|
||||
c.id === comp!.id ? { ...c, material: { color: "/assets/materials/Concrete048/color.jpg", normal: "/assets/materials/Concrete048/normal.jpg", roughness: "https://example.test/gibt-es-nicht.png", sizeM: 2 } } : c,
|
||||
),
|
||||
};
|
||||
const loaded: string[] = [];
|
||||
const pkg = await buildRenderPackage(withMat, opts(), async (url) => {
|
||||
loaded.push(url);
|
||||
return url.includes("example.test") ? null : new Uint8Array([1, 2, 3]);
|
||||
});
|
||||
const used = pkg.scene.materials.filter((m) => m.name === comp!.name && m.textures);
|
||||
expect(used.length).toBeGreaterThan(0);
|
||||
expect(used[0].textures).toEqual({ color: "textures/0_color.jpg", normal: "textures/1_normal.jpg" });
|
||||
expect(used[0].sizeM).toBe(2);
|
||||
expect(pkg.files.map((f) => f.path)).toContain("textures/0_color.jpg");
|
||||
expect(pkg.missingTextures).toEqual(["https://example.test/gibt-es-nicht.png"]);
|
||||
});
|
||||
|
||||
it("Glas bekommt keine Textur", async () => {
|
||||
const pkg = await buildRenderPackage(buildComplexSampleProject(), opts(), async () => new Uint8Array([1]));
|
||||
for (const m of pkg.scene.materials.filter((m) => m.glass)) expect(m.textures).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Blender-Ausgabe", () => {
|
||||
it("liest Cycles-Fortschritt und die Marken des Skripts", () => {
|
||||
expect(parseBlenderLine("Fra:1 Mem:34.12M (Peak 40M) | Time:00:02.10 | Remaining:00:10.5 | Mem:2M | Scene, ViewLayer | Sample 16/128")).toEqual({ kind: "sample", done: 16, total: 128 });
|
||||
expect(parseBlenderLine("DOSSIER_STAGE render")).toEqual({ kind: "stage", stage: "render" });
|
||||
expect(parseBlenderLine("DOSSIER_DONE /tmp/x/render.png")).toEqual({ kind: "done", path: "/tmp/x/render.png" });
|
||||
expect(parseBlenderLine("DOSSIER_ERROR kaputt")).toEqual({ kind: "error", message: "kaputt" });
|
||||
expect(parseBlenderLine("Blender 4.2.0")).toBeNull();
|
||||
});
|
||||
|
||||
it("Kommandozeile", () => {
|
||||
expect(blenderArgs("/a/s.py", "/a/scene.json")).toEqual(["-b", "--python-exit-code", "1", "--python", "/a/s.py", "--", "/a/scene.json"]);
|
||||
});
|
||||
});
|
||||
|
||||
/** Gemockter Gastgeber: Blender gibt eine feste Ausgabe und schreibt (oder nicht) das Bild. */
|
||||
function fakeHost(lines: string[], o: { code?: number; png?: boolean; exe?: string | null; hang?: boolean } = {}) {
|
||||
const written: { path: string; bytes: Uint8Array }[] = [];
|
||||
const calls: { exe: string; args: string[] }[] = [];
|
||||
let cancelled = false;
|
||||
const host: BlenderHost = {
|
||||
find: async (custom) => (o.exe === undefined ? (custom ?? "/usr/bin/blender") : o.exe),
|
||||
prepare: async (files) => {
|
||||
written.push(...files);
|
||||
return "/tmp/job";
|
||||
},
|
||||
spawn: (exe, args, onLine) => {
|
||||
calls.push({ exe, args });
|
||||
let end!: (c: number) => void;
|
||||
const done = new Promise<number>((r) => (end = r));
|
||||
const cancel = () => {
|
||||
cancelled = true;
|
||||
end(-1);
|
||||
};
|
||||
if (!o.hang) {
|
||||
queueMicrotask(() => {
|
||||
for (const l of lines) onLine(l);
|
||||
end(o.code ?? 0);
|
||||
});
|
||||
}
|
||||
return { done, cancel };
|
||||
},
|
||||
readFile: async () => {
|
||||
if (o.png === false) throw new Error("fehlt");
|
||||
return new Uint8Array([137, 80, 78, 71]);
|
||||
},
|
||||
join: (d, r) => `${d}/${r}`,
|
||||
};
|
||||
return { host, written, calls, wasCancelled: () => cancelled };
|
||||
}
|
||||
|
||||
describe("Prozess-Fassade (gemockt)", () => {
|
||||
it("startet Blender mit dem Skript, meldet Fortschritt und liefert das Bild", async () => {
|
||||
const pkg = await buildRenderPackage(sampleProject, opts());
|
||||
const f = fakeHost(["DOSSIER_STAGE import", "DOSSIER_STAGE render", "Fra:1 | Sample 8/16", "Fra:1 | Sample 16/16", "DOSSIER_DONE /tmp/job/render.png"]);
|
||||
const seen: string[] = [];
|
||||
const res = await runBlenderRender(f.host, pkg, {
|
||||
script: "print('x')",
|
||||
blenderPath: "/opt/Blender",
|
||||
onProgress: (e) => seen.push(`${e.stage}:${Math.round(e.fraction * 100)}`),
|
||||
});
|
||||
expect(f.calls[0].exe).toBe("/opt/Blender");
|
||||
expect(f.calls[0].args).toEqual(blenderArgs("/tmp/job/render_dossier.py", "/tmp/job/scene.json"));
|
||||
expect(new TextDecoder().decode(f.written.find((w) => w.path === "render_dossier.py")!.bytes)).toBe("print('x')");
|
||||
expect(seen).toContain("render:50");
|
||||
expect(seen.at(-1)).toBe("done:100");
|
||||
expect(Array.from(res.png)).toEqual([137, 80, 78, 71]);
|
||||
expect(res.path).toBe("/tmp/job/render.png");
|
||||
});
|
||||
|
||||
it("ohne Blender: BlenderMissingError, nichts wird geschrieben", async () => {
|
||||
const pkg = await buildRenderPackage(sampleProject, opts());
|
||||
const f = fakeHost([], { exe: null });
|
||||
await expect(runBlenderRender(f.host, pkg, { script: "" })).rejects.toBeInstanceOf(BlenderMissingError);
|
||||
expect(f.written).toEqual([]);
|
||||
});
|
||||
|
||||
it("Fehler des Skripts kommt mit seinem Text", async () => {
|
||||
const pkg = await buildRenderPackage(sampleProject, opts());
|
||||
const f = fakeHost(["DOSSIER_ERROR Das Modell enthaelt keine Koerper"], { code: 1 });
|
||||
await expect(runBlenderRender(f.host, pkg, { script: "" })).rejects.toThrow("Das Modell enthaelt keine Koerper");
|
||||
});
|
||||
|
||||
it("Abbrechen beendet den Prozess", async () => {
|
||||
const pkg = await buildRenderPackage(sampleProject, opts());
|
||||
const f = fakeHost([], { hang: true });
|
||||
const ac = new AbortController();
|
||||
const p = runBlenderRender(f.host, pkg, { script: "", signal: ac.signal });
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
ac.abort();
|
||||
await expect(p).rejects.toBeInstanceOf(RenderCancelled);
|
||||
expect(f.wasCancelled()).toBe(true);
|
||||
});
|
||||
|
||||
it("Exit 0 ohne Bild ist ein Fehler", async () => {
|
||||
const pkg = await buildRenderPackage(sampleProject, opts());
|
||||
const f = fakeHost([], { png: false });
|
||||
await expect(runBlenderRender(f.host, pkg, { script: "" })).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Blender-Skript", () => {
|
||||
const path = join(process.cwd(), "scripts", "blender", "render_dossier.py");
|
||||
const script = readFileSync(path, "utf8");
|
||||
|
||||
it("enthält die Schritte: glTF-Import, Himmel mit Sonne, Cycles mit Entrauscher, PNG", () => {
|
||||
for (const marker of ["import_scene.gltf", "ShaderNodeTexSky", "sun_rotation", "OPENIMAGEDENOISE", "METAL", "render.render(write_still=True)", "DOSSIER_DONE"]) {
|
||||
expect(script).toContain(marker);
|
||||
}
|
||||
});
|
||||
|
||||
it("ist gültiges Python", () => {
|
||||
const r = spawnSync("python3", ["-c", "import ast,sys; ast.parse(open(sys.argv[1]).read())", path]);
|
||||
if (r.error) return; // kein Python: übersprungen
|
||||
expect(r.status, String(r.stderr)).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,390 @@
|
||||
// Rendering mit Blender/Cycles ([211]): Export-Paket für ein installiertes Blender (eigener Prozess, GPL —
|
||||
// nichts davon ist in Dossier eingebunden).
|
||||
//
|
||||
// Paket (ein Ordner): `model.glb` (Export [201]: Normalen, PBR-Materialien, Glas als Alpha-Blend), `scene.json`
|
||||
// (Kamera, Sonne, Bildgrösse, Samples, Materialtabelle) und `textures/…` (Bildkarten aus dem Material-System).
|
||||
// Das Python-Skript `scripts/blender/render_dossier.py` liest `scene.json`. Dieses Modul baut nur das Paket;
|
||||
// den Prozess starten die Gastgeber (`src/native/blender.ts`: Tauri/Electron, `src/cli/main.ts`: Node).
|
||||
//
|
||||
// UV-Koordinaten: das GLB hat keine. Texturen legt das Skript per Box-Projektion über Objektkoordinaten
|
||||
// (Kachelgrösse `sizeM` des Materials in Metern), das ersetzt UVs ohne den Rust-Exporter anzufassen.
|
||||
// Materialzuordnung: der glTF-Materialname ist der Bauteilname (`Component.name`); dessen `material` (ambientCG-
|
||||
// Karten) kommt als Textur-Eintrag in die Materialtabelle. Verglasung (Deckkraft < 1) bekommt `glass: true`.
|
||||
//
|
||||
// Das Format ist renderer-neutral und in `doc/RENDER-SZENE.md` beschrieben (Blender-Skript = ein Leser davon;
|
||||
// später auch Cycles-Standalone, [215]).
|
||||
//
|
||||
// Achsen in `scene.json`: Modell-Koordinaten (x Ost, y Nord, z oben, Meter) — Blenders glTF-Import dreht das
|
||||
// Y-oben-GLB genau dorthin zurück, Kamera und Sonne brauchen im Skript keine Umrechnung.
|
||||
|
||||
import type { ComponentMaterial, LayoutOrientation, LayoutPaperFormat, Project } from "../model/types";
|
||||
import { projectLatLon, sunPosition } from "../analysis/sun";
|
||||
import { sheetSizeMm } from "../model/layoutModel";
|
||||
import { exportGlb } from "./exportMesh";
|
||||
|
||||
/** Kamera in Modell-Koordinaten (gleiche Form wie `ViewCamera` der 3D-Ansicht, `viewport/cameraBridge.ts`). */
|
||||
export interface RenderCamera {
|
||||
kind: "perspective" | "orthogonal";
|
||||
position: [number, number, number];
|
||||
/** Blickrichtung, normiert. */
|
||||
direction: [number, number, number];
|
||||
up: [number, number, number];
|
||||
/** Vertikaler Öffnungswinkel in Grad (perspektivisch). */
|
||||
fovDeg: number;
|
||||
/** Sichthöhe in Metern (orthografisch). */
|
||||
orthoHeight: number;
|
||||
}
|
||||
|
||||
/** Voreingestellte Blickrichtungen; das Skript rahmt das Modell selbst ein (Ortho ausser `perspective`). */
|
||||
export const RENDER_VIEW_PRESETS = ["iso", "perspective", "front", "back", "left", "right", "side", "top"] as const;
|
||||
export type RenderViewPreset = (typeof RENDER_VIEW_PRESETS)[number];
|
||||
|
||||
export type RenderCameraSpec = { preset: RenderViewPreset } | RenderCamera;
|
||||
|
||||
/** Vorgaben für Bildgrössen im Dialog. */
|
||||
export interface RenderSizePreset {
|
||||
id: string;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export const RENDER_SIZE_PRESETS: RenderSizePreset[] = [
|
||||
{ id: "hd", width: 1920, height: 1080 },
|
||||
{ id: "uhd", width: 3840, height: 2160 },
|
||||
{ id: "square", width: 2400, height: 2400 },
|
||||
];
|
||||
|
||||
/** Qualitätsstufen = Samples je Pixel (Cycles, mit Denoiser). */
|
||||
export const RENDER_QUALITY_PRESETS = [
|
||||
{ id: "draft", samples: 32 },
|
||||
{ id: "normal", samples: 128 },
|
||||
{ id: "high", samples: 512 },
|
||||
{ id: "final", samples: 1536 },
|
||||
] as const;
|
||||
|
||||
/** Grösse eines Papierformats in Pixeln bei `dpi` (z. B. A3 quer bei 300 dpi = 4961 × 3508). */
|
||||
export function paperPixels(paper: LayoutPaperFormat, orientation: LayoutOrientation, dpi: number): { width: number; height: number } {
|
||||
const { w, h } = sheetSizeMm(paper, orientation);
|
||||
return { width: Math.max(1, Math.round((w / 25.4) * dpi)), height: Math.max(1, Math.round((h / 25.4) * dpi)) };
|
||||
}
|
||||
|
||||
export interface RenderOptions {
|
||||
width: number;
|
||||
height: number;
|
||||
samples: number;
|
||||
/** Zeitpunkt der Sonne (Datum, UTC-basiert wie `SunStudy.when`). */
|
||||
when: Date;
|
||||
/** Kamera der aktiven 3D-Ansicht oder eine Voreinstellung. */
|
||||
camera: RenderCameraSpec;
|
||||
/** Entrauschen (Standard: an). */
|
||||
denoise?: boolean;
|
||||
/** `cpu` erzwingt die CPU, sonst GPU wenn vorhanden. */
|
||||
device?: "auto" | "cpu";
|
||||
}
|
||||
|
||||
/** Eintrag der Materialtabelle in `scene.json`. */
|
||||
export interface RenderMaterial {
|
||||
/** glTF-Materialname (= Bauteilname). */
|
||||
name: string;
|
||||
/** Basisfarbe sRGB 0..1. */
|
||||
color: [number, number, number];
|
||||
opacity: number;
|
||||
roughness: number;
|
||||
metallic: number;
|
||||
/** Verglasung: der Leser ersetzt Alpha durch Transmission. */
|
||||
glass: boolean;
|
||||
/** Transmission 0..1 (Glas 1, sonst 0), Brechungsindex. Renderer-neutral: jeder Leser setzt sie in sein PBR-Material. */
|
||||
transmission: number;
|
||||
ior: number;
|
||||
/** Dateien relativ zu `scene.json`, nach Karte. */
|
||||
textures?: Partial<Record<TextureKind, string>>;
|
||||
/** Kantenlänge einer Texturkachel in Metern. */
|
||||
sizeM?: number;
|
||||
}
|
||||
|
||||
export type TextureKind = "color" | "normal" | "roughness" | "metalness";
|
||||
const TEXTURE_KINDS: TextureKind[] = ["color", "normal", "roughness", "metalness"];
|
||||
|
||||
export interface RenderScene {
|
||||
version: 1;
|
||||
/** Name des Projekts (für Dateinamen und Metadaten). */
|
||||
project: string;
|
||||
model: string;
|
||||
output: string;
|
||||
resolution: { width: number; height: number };
|
||||
samples: number;
|
||||
denoise: boolean;
|
||||
device: "auto" | "cpu";
|
||||
camera: RenderCameraSpec;
|
||||
sun: { azimuth: number; elevation: number; when: string; lat: number; lon: number };
|
||||
materials: RenderMaterial[];
|
||||
}
|
||||
|
||||
/** Sonnenstand aus Ort (`geoAnchor`) und Zeit — dieselbe Rechnung wie Lageplan und 3D-Schatten. */
|
||||
export function renderSun(project: Project, when: Date): RenderScene["sun"] {
|
||||
const { lat, lon } = projectLatLon(project);
|
||||
const s = sunPosition(lat, lon, when);
|
||||
return { azimuth: s.azimuth, elevation: s.elevation, when: when.toISOString(), lat, lon };
|
||||
}
|
||||
|
||||
/** Vorbelegung des Dialogs: Zeit der Sonnenstudie, sonst Mittsommer 14 Uhr (UTC+2 ≈ 12:00 UTC). */
|
||||
export function defaultRenderTime(project: Project): Date {
|
||||
const w = project.sunStudy ? new Date(project.sunStudy.when) : null;
|
||||
return w && Number.isFinite(w.getTime()) ? w : new Date(Date.UTC(2026, 5, 21, 12, 0, 0));
|
||||
}
|
||||
|
||||
/** JSON-Chunk eines GLB. */
|
||||
function glbJson(glb: Uint8Array): { materials?: GltfMaterial[] } {
|
||||
const dv = new DataView(glb.buffer, glb.byteOffset, glb.byteLength);
|
||||
if (glb.byteLength < 20 || dv.getUint32(0, true) !== 0x46546c67) throw new Error("Kein GLB");
|
||||
const len = dv.getUint32(12, true);
|
||||
return JSON.parse(new TextDecoder().decode(glb.subarray(20, 20 + len)));
|
||||
}
|
||||
|
||||
interface GltfMaterial {
|
||||
name?: string;
|
||||
alphaMode?: string;
|
||||
pbrMetallicRoughness?: { baseColorFactor?: number[]; metallicFactor?: number; roughnessFactor?: number };
|
||||
}
|
||||
|
||||
const linearToSrgb = (c: number): number => {
|
||||
const x = Math.min(1, Math.max(0, c));
|
||||
return x <= 0.0031308 ? x * 12.92 : 1.055 * Math.pow(x, 1 / 2.4) - 0.055;
|
||||
};
|
||||
|
||||
/** Materialien eines GLB (glTF speichert die Farbe linear, hier sRGB). */
|
||||
export function glbMaterials(glb: Uint8Array): RenderMaterial[] {
|
||||
const out: RenderMaterial[] = [];
|
||||
for (const m of glbJson(glb).materials ?? []) {
|
||||
const p = m.pbrMetallicRoughness ?? {};
|
||||
const f = p.baseColorFactor ?? [1, 1, 1, 1];
|
||||
const opacity = f[3] ?? 1;
|
||||
out.push({
|
||||
name: m.name ?? "",
|
||||
color: [linearToSrgb(f[0] ?? 1), linearToSrgb(f[1] ?? 1), linearToSrgb(f[2] ?? 1)],
|
||||
opacity,
|
||||
roughness: p.roughnessFactor ?? 0.9,
|
||||
metallic: p.metallicFactor ?? 0,
|
||||
glass: m.alphaMode === "BLEND" && opacity < 1,
|
||||
transmission: m.alphaMode === "BLEND" && opacity < 1 ? 1 : 0,
|
||||
ior: m.alphaMode === "BLEND" && opacity < 1 ? 1.45 : 1.5,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Liest Bilddateien (URL aus dem Material-System → Bytes) oder liefert null, wenn nicht erreichbar. */
|
||||
export type TextureLoader = (url: string) => Promise<Uint8Array | null>;
|
||||
|
||||
export interface RenderPackage {
|
||||
scene: RenderScene;
|
||||
/** Dateien des Pakets (relative Pfade), `scene.json` und `model.glb` eingeschlossen. */
|
||||
files: { path: string; bytes: Uint8Array }[];
|
||||
/** URLs, die sich nicht laden liessen (Hinweis an den Nutzer; Rendering läuft mit Grundfarbe). */
|
||||
missingTextures: string[];
|
||||
}
|
||||
|
||||
function extensionOf(url: string): string {
|
||||
const m = /\.([a-z0-9]{2,4})(?:[?#].*)?$/i.exec(url);
|
||||
return m ? m[1].toLowerCase() : "jpg";
|
||||
}
|
||||
|
||||
/** Bauteil-Materialkarten nach glTF-Materialname (erste Komponente gleichen Namens mit Farbkarte gewinnt). */
|
||||
function componentMaterials(project: Project): Map<string, ComponentMaterial> {
|
||||
const byName = new Map<string, ComponentMaterial>();
|
||||
for (const c of project.components ?? []) {
|
||||
if (c.material?.color && !byName.has(c.name)) byName.set(c.name, c.material);
|
||||
}
|
||||
return byName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Baut das Export-Paket für Blender: GLB, Materialtabelle (mit Texturen, soweit `loadTexture` sie liefert),
|
||||
* Kamera, Sonne. Verlangt das geladene Format-Modul (`await loadFileio()`) und den Kern.
|
||||
*/
|
||||
export async function buildRenderPackage(project: Project, opts: RenderOptions, loadTexture?: TextureLoader): Promise<RenderPackage> {
|
||||
const glb = exportGlb(project);
|
||||
const files: RenderPackage["files"] = [{ path: "model.glb", bytes: glb }];
|
||||
const materials = glbMaterials(glb);
|
||||
const comp = componentMaterials(project);
|
||||
const missing: string[] = [];
|
||||
const stored = new Map<string, string>();
|
||||
|
||||
for (const mat of materials) {
|
||||
const cm = comp.get(mat.name);
|
||||
if (!cm || mat.glass || !loadTexture) continue;
|
||||
const textures: Partial<Record<TextureKind, string>> = {};
|
||||
for (const kind of TEXTURE_KINDS) {
|
||||
const url = cm[kind];
|
||||
if (!url) continue;
|
||||
let path = stored.get(url);
|
||||
if (!path) {
|
||||
const bytes = await loadTexture(url).catch(() => null);
|
||||
if (!bytes || bytes.length === 0) {
|
||||
if (!missing.includes(url)) missing.push(url);
|
||||
continue;
|
||||
}
|
||||
path = `textures/${stored.size}_${kind}.${extensionOf(url)}`;
|
||||
stored.set(url, path);
|
||||
files.push({ path, bytes });
|
||||
}
|
||||
textures[kind] = path;
|
||||
}
|
||||
if (textures.color) {
|
||||
mat.textures = textures;
|
||||
mat.sizeM = cm.sizeM && cm.sizeM > 0 ? cm.sizeM : 1;
|
||||
}
|
||||
}
|
||||
|
||||
const scene: RenderScene = {
|
||||
version: 1,
|
||||
project: project.name || "projekt",
|
||||
model: "model.glb",
|
||||
output: "render.png",
|
||||
resolution: { width: Math.round(opts.width), height: Math.round(opts.height) },
|
||||
samples: Math.max(1, Math.round(opts.samples)),
|
||||
denoise: opts.denoise ?? true,
|
||||
device: opts.device ?? "auto",
|
||||
camera: opts.camera,
|
||||
sun: renderSun(project, opts.when),
|
||||
materials,
|
||||
};
|
||||
files.push({ path: "scene.json", bytes: new TextEncoder().encode(JSON.stringify(scene, null, 2)) });
|
||||
return { scene, files, missingTextures: missing };
|
||||
}
|
||||
|
||||
// ── Blender-Ausgabe lesen ───────────────────────────────────────────────────
|
||||
|
||||
export type BlenderEvent =
|
||||
| { kind: "sample"; done: number; total: number }
|
||||
| { kind: "stage"; stage: string }
|
||||
| { kind: "done"; path: string }
|
||||
| { kind: "error"; message: string }
|
||||
| { kind: "note"; message: string };
|
||||
|
||||
/** Eine Ausgabezeile von Blender: Cycles meldet `… | Sample 16/128`, das Skript die `DOSSIER_*`-Marken. */
|
||||
export function parseBlenderLine(line: string): BlenderEvent | null {
|
||||
const s = /\bSample\s+(\d+)\s*\/\s*(\d+)/.exec(line);
|
||||
if (s) return { kind: "sample", done: Number(s[1]), total: Number(s[2]) };
|
||||
const m = /^DOSSIER_(STAGE|DONE|ERROR|NOTE)\s+(.*)$/.exec(line.trim());
|
||||
if (!m) return null;
|
||||
const text = m[2].trim();
|
||||
switch (m[1]) {
|
||||
case "STAGE":
|
||||
return { kind: "stage", stage: text };
|
||||
case "DONE":
|
||||
return { kind: "done", path: text };
|
||||
case "ERROR":
|
||||
return { kind: "error", message: text };
|
||||
default:
|
||||
return { kind: "note", message: text };
|
||||
}
|
||||
}
|
||||
|
||||
/** Kommandozeile von Blender für das Skript (Hintergrund, Fehler im Skript = Exit-Code 1). */
|
||||
export function blenderArgs(scriptPath: string, scenePath: string): string[] {
|
||||
return ["-b", "--python-exit-code", "1", "--python", scriptPath, "--", scenePath];
|
||||
}
|
||||
|
||||
/** Aufruf-Gastgeber (Tauri, Electron, Node): alles, was nur ein Prozess/Dateisystem kann. */
|
||||
export interface BlenderHost {
|
||||
/** Pfad der Blender-Programmdatei (eigene Angabe zuerst, dann übliche Orte), oder null. */
|
||||
find(custom?: string): Promise<string | null>;
|
||||
/** Legt einen neuen Arbeitsordner an, schreibt die Dateien hinein, gibt den Ordner zurück. */
|
||||
prepare(files: { path: string; bytes: Uint8Array }[]): Promise<string>;
|
||||
/** Startet Blender; `onLine` für jede Ausgabezeile (stdout und stderr). */
|
||||
spawn(exe: string, args: string[], onLine: (line: string) => void): { done: Promise<number>; cancel(): void };
|
||||
readFile(path: string): Promise<Uint8Array>;
|
||||
/** Pfad zu `dir/rel`. */
|
||||
join(dir: string, rel: string): string;
|
||||
}
|
||||
|
||||
export class BlenderMissingError extends Error {
|
||||
constructor() {
|
||||
super("Blender nicht gefunden");
|
||||
this.name = "BlenderMissingError";
|
||||
}
|
||||
}
|
||||
|
||||
export class RenderCancelled extends Error {
|
||||
constructor() {
|
||||
super("Rendering abgebrochen");
|
||||
this.name = "RenderCancelled";
|
||||
}
|
||||
}
|
||||
|
||||
export interface RenderRunOptions {
|
||||
/** Eigener Blender-Pfad (Einstellungen). */
|
||||
blenderPath?: string;
|
||||
/** Text des Python-Skripts (`scripts/blender/render_dossier.py`). */
|
||||
script: string;
|
||||
/** Fortschritt 0..1 (Samples) und Phase. */
|
||||
onProgress?: (e: { fraction: number; stage: string; done: number; total: number }) => void;
|
||||
/** Rohausgabe von Blender (für Fehlermeldungen/Protokoll). */
|
||||
onLine?: (line: string) => void;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface RenderResult {
|
||||
png: Uint8Array;
|
||||
dir: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Packt das Paket aus, startet Blender, meldet den Fortschritt und liest das Bild. Wirft
|
||||
* {@link BlenderMissingError}, {@link RenderCancelled} oder einen Fehler mit der Meldung des Skripts.
|
||||
*/
|
||||
export async function runBlenderRender(host: BlenderHost, pkg: RenderPackage, opts: RenderRunOptions): Promise<RenderResult> {
|
||||
const exe = await host.find(opts.blenderPath);
|
||||
if (!exe) throw new BlenderMissingError();
|
||||
const dir = await host.prepare([...pkg.files, { path: "render_dossier.py", bytes: new TextEncoder().encode(opts.script) }]);
|
||||
const scenePath = host.join(dir, "scene.json");
|
||||
let stage = "import";
|
||||
let error = "";
|
||||
let lastLines: string[] = [];
|
||||
const total = pkg.scene.samples;
|
||||
const job = host.spawn(exe, blenderArgs(host.join(dir, "render_dossier.py"), scenePath), (line) => {
|
||||
opts.onLine?.(line);
|
||||
lastLines.push(line);
|
||||
if (lastLines.length > 12) lastLines = lastLines.slice(-12);
|
||||
const ev = parseBlenderLine(line);
|
||||
if (!ev) return;
|
||||
if (ev.kind === "stage") {
|
||||
stage = ev.stage;
|
||||
opts.onProgress?.({ fraction: 0, stage, done: 0, total });
|
||||
} else if (ev.kind === "sample") {
|
||||
opts.onProgress?.({ fraction: ev.total > 0 ? Math.min(1, ev.done / ev.total) : 0, stage: "render", done: ev.done, total: ev.total });
|
||||
} else if (ev.kind === "error") {
|
||||
error = ev.message;
|
||||
}
|
||||
});
|
||||
const onAbort = () => job.cancel();
|
||||
opts.signal?.addEventListener("abort", onAbort);
|
||||
if (opts.signal?.aborted) job.cancel();
|
||||
let code: number;
|
||||
try {
|
||||
code = await job.done;
|
||||
} finally {
|
||||
opts.signal?.removeEventListener("abort", onAbort);
|
||||
}
|
||||
if (opts.signal?.aborted) throw new RenderCancelled();
|
||||
if (code !== 0) throw new Error(error || `Blender beendet mit Code ${code}: ${lastLines.slice(-3).join(" | ")}`);
|
||||
const path = host.join(dir, pkg.scene.output);
|
||||
const png = await host.readFile(path).catch(() => null);
|
||||
if (!png || png.length === 0) throw new Error(error || "Blender hat kein Bild geschrieben");
|
||||
opts.onProgress?.({ fraction: 1, stage: "done", done: total, total });
|
||||
return { png, dir, path };
|
||||
}
|
||||
|
||||
/** Übliche Blender-Orte, in Suchreihenfolge (macOS-App, Linux-Pakete). `blender` im PATH prüft der Gastgeber zuerst. */
|
||||
export const BLENDER_CANDIDATES = [
|
||||
"/Applications/Blender.app/Contents/MacOS/Blender",
|
||||
"/usr/bin/blender",
|
||||
"/usr/local/bin/blender",
|
||||
"/snap/bin/blender",
|
||||
"/var/lib/flatpak/exports/bin/org.blender.Blender",
|
||||
];
|
||||
|
||||
/** Download-Seite für den Hinweis ohne Blender. */
|
||||
export const BLENDER_DOWNLOAD_URL = "https://www.blender.org/download/";
|
||||
Reference in new issue
Block a user