[215] Cycles: Szene aus dem Kern, CLI render --engine cycles, Tonwert, Doku und Bilder
This commit is contained in:
22 files changed
+2183
-53
No files matched your search
@@ -0,0 +1,62 @@
|
||||
// [215] Test-Hilfe: kleines OpenEXR (B, G, R als Float, ZIP oder unkomprimiert) in der Form, die `cycles` schreibt.
|
||||
import { deflateSync } from "node:zlib";
|
||||
|
||||
/** Kleines OpenEXR (B, G, R als Float, wie das Programm; ZIP oder unkomprimiert) für die Tests. */
|
||||
export function makeExr(width: number, height: number, rgb: Float32Array, zip: boolean): Uint8Array {
|
||||
const enc = new TextEncoder();
|
||||
const parts: number[] = [0x76, 0x2f, 0x31, 0x01, 2, 0, 0, 0];
|
||||
const str = (s: string) => parts.push(...enc.encode(s), 0);
|
||||
const i32 = (v: number) => parts.push(v & 255, (v >> 8) & 255, (v >> 16) & 255, (v >>> 24) & 255);
|
||||
const attr = (name: string, type: string, body: number[]) => {
|
||||
str(name);
|
||||
str(type);
|
||||
i32(body.length);
|
||||
parts.push(...body);
|
||||
};
|
||||
const chBody: number[] = [];
|
||||
for (const n of ["B", "G", "R"]) chBody.push(...enc.encode(n), 0, 2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0);
|
||||
chBody.push(0);
|
||||
attr("channels", "chlist", chBody);
|
||||
attr("compression", "compression", [zip ? 3 : 0]);
|
||||
const le = (v: number) => [v & 255, (v >> 8) & 255, (v >> 16) & 255, (v >>> 24) & 255];
|
||||
attr("dataWindow", "box2i", [...le(0), ...le(0), ...le(width - 1), ...le(height - 1)]);
|
||||
attr("displayWindow", "box2i", [...le(0), ...le(0), ...le(width - 1), ...le(height - 1)]);
|
||||
parts.push(0);
|
||||
const rows = zip ? 16 : 1;
|
||||
const blocks = Math.ceil(height / rows);
|
||||
const data: Uint8Array[] = [];
|
||||
for (let b = 0; b < blocks; b++) {
|
||||
const lines = Math.min(rows, height - b * rows);
|
||||
const raw = new Uint8Array(lines * width * 12);
|
||||
const dv = new DataView(raw.buffer);
|
||||
let q = 0;
|
||||
for (let l = 0; l < lines; l++) {
|
||||
for (const slot of [2, 1, 0]) for (let x = 0; x < width; x++, q += 4) dv.setFloat32(q, rgb[((b * rows + l) * width + x) * 3 + slot], true);
|
||||
}
|
||||
let body = raw;
|
||||
if (zip) {
|
||||
const half = (raw.length + 1) >> 1;
|
||||
const re = new Uint8Array(raw.length);
|
||||
for (let i = 0, k = 0; i < raw.length; i += 2, k++) re[k] = raw[i];
|
||||
for (let i = 1, k = half; i < raw.length; i += 2, k++) re[k] = raw[i];
|
||||
const delta = new Uint8Array(raw.length);
|
||||
delta[0] = re[0];
|
||||
for (let i = 1; i < re.length; i++) delta[i] = (re[i] - re[i - 1] + 128 + 256) & 255;
|
||||
body = new Uint8Array(deflateSync(delta));
|
||||
}
|
||||
const head = new Uint8Array(8);
|
||||
new DataView(head.buffer).setInt32(0, b * rows, true);
|
||||
new DataView(head.buffer).setInt32(4, body.length, true);
|
||||
data.push(head, body);
|
||||
}
|
||||
const tableStart = parts.length;
|
||||
let off = tableStart + blocks * 8;
|
||||
const table = new Uint8Array(blocks * 8);
|
||||
const tv = new DataView(table.buffer);
|
||||
for (let b = 0; b < blocks; b++) {
|
||||
tv.setBigUint64(b * 8, BigInt(off), true);
|
||||
off += data[b * 2].length + data[b * 2 + 1].length;
|
||||
}
|
||||
return Uint8Array.from([...parts, ...table, ...data.flatMap((d) => [...d])]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
// [215] Cycles: Szene aus dem Kern, Zeilen des Programms, EXR lesen, PNG schreiben, Ablauf mit Ersatz-Host. Ein echter
|
||||
// Lauf steht in `cyclesRender.integration.test.ts` (nur mit `DOSSIER_CYCLES`).
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { deflateSync, inflateSync } from "node:zlib";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { makeExr } from "./cyclesExr.testutil";
|
||||
import {
|
||||
buildCyclesPackage,
|
||||
cyclesArgs,
|
||||
cyclesSceneInfo,
|
||||
encodePng,
|
||||
exrToPng,
|
||||
parseCyclesLine,
|
||||
readExr,
|
||||
runCyclesRender,
|
||||
CyclesMissingError,
|
||||
type CyclesHost,
|
||||
} from "./cyclesRender";
|
||||
|
||||
const codec = {
|
||||
inflate: (d: Uint8Array) => new Uint8Array(inflateSync(d)),
|
||||
deflate: (d: Uint8Array) => new Uint8Array(deflateSync(d)),
|
||||
};
|
||||
|
||||
describe("parseCyclesLine", () => {
|
||||
it("Fortschritt, Phasen, Fehler", () => {
|
||||
expect(parseCyclesLine("Progress 06.25 Sample 1/16")).toEqual({ kind: "sample", done: 1, total: 16 });
|
||||
expect(parseCyclesLine("Progress 00.00 Loading render kernels (may take a few minutes the first time)")).toEqual({ kind: "stage", stage: "kernels" });
|
||||
expect(parseCyclesLine("Writing image /tmp/x/render.exr")).toEqual({ kind: "stage", stage: "write" });
|
||||
expect(parseCyclesLine("Finished Rendering.")).toEqual({ kind: "done" });
|
||||
expect(parseCyclesLine("00:00.00 | ERROR: Unknown input socket name \"vector\" on \"alb\"")).toEqual({ kind: "error", message: "Unknown input socket name \"vector\" on \"alb\"" });
|
||||
expect(parseCyclesLine("Progress 00.00 Updating Meshes")).toEqual({ kind: "stage", stage: "scene" });
|
||||
expect(parseCyclesLine("irgendwas")).toBeNull();
|
||||
});
|
||||
|
||||
it("Kommandozeile", () => {
|
||||
expect(cyclesArgs({ width: 640, height: 360, samples: 8 }, "/t/scene.xml", "/t/render.exr", { device: "CPU", threads: 2 })).toEqual([
|
||||
"--background", "--samples", "8", "--width", "640", "--height", "360", "--output", "/t/render.exr", "--device", "CPU", "--threads", "2", "/t/scene.xml",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("EXR und PNG", () => {
|
||||
const rgb = new Float32Array(20 * 18 * 3).map((_, i) => (i % 7) * 0.5 + (i % 3) * 0.125);
|
||||
|
||||
it.each([false, true])("EXR lesen (ZIP: %s) gibt die Pixel zurück", (zip) => {
|
||||
const img = readExr(makeExr(20, 18, rgb, zip), codec.inflate);
|
||||
expect([img.width, img.height]).toEqual([20, 18]);
|
||||
expect(Array.from(img.rgb)).toEqual(Array.from(rgb));
|
||||
});
|
||||
|
||||
it("EXR mit anderer Kompression/Unsinn wirft statt zu raten", () => {
|
||||
expect(() => readExr(new Uint8Array(40), codec.inflate)).toThrow("Kein OpenEXR");
|
||||
const exr = makeExr(4, 4, new Float32Array(48), false);
|
||||
// Kompression PIZ (4) eintragen: Position des Wertes hinter dem Attribut `compression`.
|
||||
const at = new TextDecoder("latin1").decode(exr).indexOf("compression\0compression\0") + "compression\0compression\0".length + 4;
|
||||
exr[at] = 4;
|
||||
expect(() => readExr(exr, codec.inflate)).toThrow("Kompression 4");
|
||||
});
|
||||
|
||||
it("PNG: Kopf, Prüfsummen, Rückweg über zlib", () => {
|
||||
const px = new Uint8Array(5 * 3 * 3).map((_, i) => (i * 7) & 255);
|
||||
const png = encodePng(5, 3, px, codec.deflate);
|
||||
expect(Array.from(png.subarray(0, 8))).toEqual([137, 80, 78, 71, 13, 10, 26, 10]);
|
||||
const dv = new DataView(png.buffer, png.byteOffset);
|
||||
expect([dv.getUint32(16), dv.getUint32(20), png[24], png[25]]).toEqual([5, 3, 8, 2]);
|
||||
// IDAT entpacken: je Zeile Filter 0 + RGB.
|
||||
const len = dv.getUint32(33);
|
||||
expect(new TextDecoder().decode(png.subarray(37, 41))).toBe("IDAT");
|
||||
const raw = inflateSync(png.subarray(41, 41 + len));
|
||||
expect(raw.length).toBe((5 * 3 + 1) * 3);
|
||||
expect(raw[0]).toBe(0);
|
||||
expect(Array.from(raw.subarray(1, 16))).toEqual(Array.from(px.subarray(0, 15)));
|
||||
// CRC des IDAT-Chunks prüfen (Standardverfahren, zlib.crc32 ab Node 22 nicht nötig: eigene Tabelle).
|
||||
let c = 0xffffffff;
|
||||
for (const b of png.subarray(37, 41 + len)) {
|
||||
c ^= b;
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
}
|
||||
expect((c ^ 0xffffffff) >>> 0).toBe(dv.getUint32(41 + len));
|
||||
});
|
||||
|
||||
it("Tonwert im Kern: Szenenwerte → sichtbares Bild (Weiss besonnt unter 255, Schwarz 0)", () => {
|
||||
const img = { width: 2, height: 1, rgb: new Float32Array([0, 0, 0, 1.2, 1.2, 1.2]) };
|
||||
const png = exrToPng(img, "filmic", 0, codec.deflate);
|
||||
const raw = inflateSync(png.subarray(41, 41 + new DataView(png.buffer, png.byteOffset).getUint32(33)));
|
||||
expect(Array.from(raw.subarray(1, 4))).toEqual([0, 0, 0]);
|
||||
expect(raw[4]).toBeGreaterThan(215);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Szene aus dem Kern", () => {
|
||||
it("Beispielprojekt: XML mit Netzen, Glas, Kamera, Sonne; Optionen kommen an", () => {
|
||||
const info = cyclesSceneInfo(sampleProject, { width: 640, height: 360, samples: 8, camera: { preset: "iso" }, whenMs: Date.UTC(2026, 5, 21, 12, 0, 0) });
|
||||
expect(info.meshes).toBeGreaterThan(5);
|
||||
expect([info.width, info.height, info.samples]).toEqual([640, 360, 8]);
|
||||
expect(info.xml).toContain("<cycles>");
|
||||
expect(info.xml).toContain("camera_type=\"orthograph\"");
|
||||
expect(info.sunElevation).toBeGreaterThan(60);
|
||||
});
|
||||
|
||||
it("Bildkarten: geladene kommen als Dateien neben die XML, fehlende fallen auf Einfarbig zurück", async () => {
|
||||
const p = { ...sampleProject, components: sampleProject.components.map((c) => ({ ...c, material: { color: "/assets/materials/Bricks104/color.jpg", sizeM: 2 } })) };
|
||||
const base = { width: 320, height: 180, samples: 4 };
|
||||
const ok = await buildCyclesPackage(p, base, async () => new Uint8Array([1, 2, 3]));
|
||||
expect(ok.files.map((f) => f.path)).toContain("scene.xml");
|
||||
expect(ok.files.some((f) => f.path.startsWith("textures/0_color."))).toBe(true);
|
||||
expect(ok.info.xml).toContain("image_texture");
|
||||
const none = await buildCyclesPackage(p, base, async () => null);
|
||||
expect(none.files.map((f) => f.path)).toEqual(["scene.xml"]);
|
||||
expect(none.missingTextures.length).toBeGreaterThan(0);
|
||||
expect(none.info.xml).not.toContain("filename=");
|
||||
// Ohne Lader (Browser ohne Bilder): nie eine Datei erwähnen, die fehlt.
|
||||
const noLoader = await buildCyclesPackage(p, base);
|
||||
expect(noLoader.info.xml).not.toContain("filename=");
|
||||
});
|
||||
});
|
||||
|
||||
describe("runCyclesRender", () => {
|
||||
/** Ersatz-Gastgeber: schreibt ein EXR, meldet Zeilen wie Cycles. */
|
||||
function fakeHost(exr: Uint8Array | null, code = 0, lines: string[] = ["Progress 50.00 Sample 4/8", "Progress 100.00 Sample 8/8", "Finished Rendering."]) {
|
||||
const written = new Map<string, Uint8Array>();
|
||||
const calls: string[][] = [];
|
||||
const host: CyclesHost = {
|
||||
find: async (custom) => (custom === "fehlt" ? null : "/fake/cycles"),
|
||||
prepare: async (files) => {
|
||||
for (const f of files) written.set(f.path, f.bytes);
|
||||
return "/work";
|
||||
},
|
||||
spawn: (_exe, args, onLine) => {
|
||||
calls.push(args);
|
||||
for (const l of lines) onLine(l);
|
||||
if (exr) written.set("render.exr", exr);
|
||||
return { done: Promise.resolve(code), cancel: () => {} };
|
||||
},
|
||||
readFile: async (path) => {
|
||||
const b = written.get(path.replace("/work/", ""));
|
||||
if (!b) throw new Error("fehlt");
|
||||
return b;
|
||||
},
|
||||
join: (d, r) => `${d}/${r}`,
|
||||
};
|
||||
return { host, calls, written };
|
||||
}
|
||||
|
||||
it("Ablauf: Paket auspacken, Programm starten, Fortschritt melden, PNG liefern", async () => {
|
||||
const pkg = await buildCyclesPackage(sampleProject, { width: 4, height: 2, samples: 8 });
|
||||
const exr = makeExr(4, 2, new Float32Array(24).fill(0.3), true);
|
||||
const { host, calls, written } = fakeHost(exr);
|
||||
const seen: number[] = [];
|
||||
const res = await runCyclesRender(host, pkg, { codec, device: "CPU", onProgress: (e) => seen.push(e.fraction) });
|
||||
expect(written.has("scene.xml")).toBe(true);
|
||||
expect(calls[0]).toContain("--device");
|
||||
expect(calls[0].slice(-1)[0]).toBe("/work/scene.xml");
|
||||
expect(seen).toContain(0.5);
|
||||
expect(seen.at(-1)).toBe(1);
|
||||
expect([res.width, res.height]).toEqual([4, 2]);
|
||||
expect(Array.from(res.png.subarray(1, 4))).toEqual([80, 78, 71]);
|
||||
});
|
||||
|
||||
it("Fehler: Programm fehlt, Exit-Code ≠ 0, kein Bild", async () => {
|
||||
const pkg = await buildCyclesPackage(sampleProject, { width: 4, height: 2, samples: 8 });
|
||||
await expect(runCyclesRender(fakeHost(null).host, pkg, { codec, cyclesPath: "fehlt" })).rejects.toBeInstanceOf(CyclesMissingError);
|
||||
await expect(runCyclesRender(fakeHost(null, 3, ["00:00.00 | ERROR: kaputt"]).host, pkg, { codec })).rejects.toThrow(/Code 3.*kaputt/);
|
||||
await expect(runCyclesRender(fakeHost(null).host, pkg, { codec })).rejects.toThrow("kein Bild");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,403 @@
|
||||
// [215] Rendering mit dem mitgelieferten Cycles-Programm (Standalone, Apache-2.0; Plan: `doc/CYCLES.md`).
|
||||
//
|
||||
// Die Szene schreibt der Rust-Kern (`src-tauri/core/src/cycles_scene.rs`, Abfrage `cyclesScene`): Cycles-XML mit allen
|
||||
// 3D-Netzen des Modells (gleiche Quelle wie glTF-Export und 3D-Anzeige), Materialien, Kamera, Sonne und Himmel. Dieses Modul
|
||||
// reicht die Optionen weiter, lädt die Bildkarten (der Kern liest keine Dateien), startet das Programm über einen Gastgeber
|
||||
// (Node-CLI heute; Tauri/Electron später wie `BlenderHost`), liest den Fortschritt und macht aus dem linearen EXR ein PNG:
|
||||
// EXR lesen (Zeilenblöcke, unkomprimiert/ZIP, Half/Float) → Tonwert im Kern (`cycles_post.rs`) → PNG.
|
||||
//
|
||||
// Das Programm hat keine Tonwert-Abbildung und keine Farbverwaltung (ohne OCIO gebaut): `<film exposure>` der Szene belichtet,
|
||||
// der Tonwert (Filmic-artig, `filmic`, oder `standard`) liegt hier. Zlib (EXR-ZIP, PNG) kommt vom Gastgeber (`Codec`).
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import { documentFor } from "../core/document";
|
||||
import { core } from "../engine/coreWasm";
|
||||
import type { RenderCamera, RenderViewPreset, TextureLoader } from "./blenderRender";
|
||||
|
||||
/** Optionen der Szene (JSON an den Kern, camelCase; `cyclesScene` in `cycles_scene.rs`). */
|
||||
export interface CyclesSceneOptions {
|
||||
width: number;
|
||||
height: number;
|
||||
samples: number;
|
||||
denoise?: boolean;
|
||||
/** Zeitpunkt der Sonne (Unix-ms); fehlt er, gilt der 21.6.2026 12:00 UTC. */
|
||||
whenMs?: number;
|
||||
/** Fester Sonnenstand statt Zeit/Ort. */
|
||||
sun?: { azimuth: number; elevation: number };
|
||||
sunIntensity?: number;
|
||||
/** Belichtung in EV; fehlt sie, belichtet der Kern automatisch nach Sonnenhöhe. */
|
||||
exposureEv?: number;
|
||||
/** Voreinstellung (rahmt das Gebäude ein) oder explizit (gespeicherte/aktuelle Kamera). */
|
||||
camera?: { preset: RenderViewPreset } | RenderCamera;
|
||||
/** [227] Gelände ohne Baugrube (Standard: ja). */
|
||||
backfilled?: boolean;
|
||||
/** Gelände und Kontext (Standard: ja). */
|
||||
context?: boolean;
|
||||
/** Bodenplatte (Standard: ja). */
|
||||
ground?: boolean;
|
||||
/** Bild-URLs, die geladen werden können (`undefined` = alle). */
|
||||
textures?: string[];
|
||||
}
|
||||
|
||||
/** Antwort des Kerns. */
|
||||
export interface CyclesSceneInfo {
|
||||
xml: string;
|
||||
textures: { path: string; url: string }[];
|
||||
meshes: number;
|
||||
triangles: number;
|
||||
width: number;
|
||||
height: number;
|
||||
samples: number;
|
||||
sunAzimuth: number;
|
||||
sunElevation: number;
|
||||
exposure: number;
|
||||
notes: string[];
|
||||
}
|
||||
|
||||
/** Szene mit geladenen Bildkarten: Dateien relativ zu `scene.xml`. */
|
||||
export interface CyclesPackage {
|
||||
info: CyclesSceneInfo;
|
||||
/** `scene.xml` und `textures/…`. */
|
||||
files: { path: string; bytes: Uint8Array }[];
|
||||
missingTextures: string[];
|
||||
}
|
||||
|
||||
/** Szene aus dem Kern (ohne Bilddateien). */
|
||||
export function cyclesSceneInfo(project: Project, opts: CyclesSceneOptions): CyclesSceneInfo {
|
||||
return documentFor(project).query<CyclesSceneInfo>("cyclesScene", [], JSON.stringify(opts));
|
||||
}
|
||||
|
||||
/**
|
||||
* Baut das Paket: Szene aus dem Kern, Bildkarten über `loadTexture` (nicht ladbare fallen im zweiten Durchgang auf den
|
||||
* Ersatzlook des Kerns zurück, damit die XML keine fehlenden Dateien nennt).
|
||||
*/
|
||||
export async function buildCyclesPackage(project: Project, opts: CyclesSceneOptions, loadTexture?: TextureLoader): Promise<CyclesPackage> {
|
||||
let info = cyclesSceneInfo(project, opts.textures || !loadTexture ? opts : { ...opts, textures: undefined });
|
||||
const bytes = new Map<string, Uint8Array>();
|
||||
const missing: string[] = [];
|
||||
if (loadTexture) {
|
||||
for (const t of info.textures) {
|
||||
if (bytes.has(t.url) || missing.includes(t.url)) continue;
|
||||
const b = await loadTexture(t.url).catch(() => null);
|
||||
if (b && b.length > 0) bytes.set(t.url, b);
|
||||
else missing.push(t.url);
|
||||
}
|
||||
if (missing.length > 0) info = cyclesSceneInfo(project, { ...opts, textures: [...bytes.keys()] });
|
||||
} else if (info.textures.length > 0) {
|
||||
info = cyclesSceneInfo(project, { ...opts, textures: [] });
|
||||
}
|
||||
const files: CyclesPackage["files"] = [{ path: "scene.xml", bytes: new TextEncoder().encode(info.xml) }];
|
||||
for (const t of info.textures) {
|
||||
const b = bytes.get(t.url);
|
||||
if (b) files.push({ path: t.path, bytes: b });
|
||||
}
|
||||
return { info, files, missingTextures: missing };
|
||||
}
|
||||
|
||||
// ── Programm starten, Ausgabe lesen ─────────────────────────────────────────
|
||||
|
||||
export type CyclesEvent =
|
||||
| { kind: "sample"; done: number; total: number }
|
||||
| { kind: "stage"; stage: "scene" | "kernels" | "write" }
|
||||
| { kind: "done" }
|
||||
| { kind: "error"; message: string };
|
||||
|
||||
/**
|
||||
* Eine Ausgabezeile von `cycles` (Fortschritt mit Wagenrücklauf: `Progress 06.25 Sample 1/16`, dazu
|
||||
* `Updating …`, `Loading render kernels …`, `Writing image …`, `Finished Rendering.`, Fehler `… | ERROR: …`).
|
||||
*/
|
||||
export function parseCyclesLine(line: string): CyclesEvent | 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 e = /\bERROR:\s*(.*)$/.exec(line);
|
||||
if (e) return { kind: "error", message: e[1].trim() };
|
||||
if (/Loading (render|denoising) kernels/.test(line)) return { kind: "stage", stage: "kernels" };
|
||||
if (/Writing image/.test(line)) return { kind: "stage", stage: "write" };
|
||||
if (/Finished Rendering/.test(line)) return { kind: "done" };
|
||||
if (/Updating /.test(line)) return { kind: "stage", stage: "scene" };
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Aufruf-Gastgeber (Node, später Tauri/Electron): Prozess und Dateisystem. */
|
||||
export interface CyclesHost {
|
||||
/** Pfad des Programms (eigene Angabe, `DOSSIER_CYCLES`, neben der App), oder null. */
|
||||
find(custom?: string): Promise<string | null>;
|
||||
/** Neuer Arbeitsordner, Dateien hinein, Ordner zurück. */
|
||||
prepare(files: { path: string; bytes: Uint8Array }[]): Promise<string>;
|
||||
/** Startet das Programm; `onLine` je Ausgabezeile (stdout und stderr, Wagenrücklauf trennt). */
|
||||
spawn(exe: string, args: string[], onLine: (line: string) => void): { done: Promise<number>; cancel(): void };
|
||||
readFile(path: string): Promise<Uint8Array>;
|
||||
join(dir: string, rel: string): string;
|
||||
}
|
||||
|
||||
export class CyclesMissingError extends Error {
|
||||
constructor() {
|
||||
super("Cycles nicht gefunden");
|
||||
this.name = "CyclesMissingError";
|
||||
}
|
||||
}
|
||||
|
||||
export class CyclesCancelled extends Error {
|
||||
constructor() {
|
||||
super("Rendering abgebrochen");
|
||||
this.name = "CyclesCancelled";
|
||||
}
|
||||
}
|
||||
|
||||
/** Zlib des Gastgebers (Node: `zlib`; Browser: Kompressions-Ströme). */
|
||||
export interface Codec {
|
||||
inflate(data: Uint8Array): Uint8Array;
|
||||
deflate(data: Uint8Array): Uint8Array;
|
||||
}
|
||||
|
||||
export interface CyclesRunOptions {
|
||||
/** Eigener Programmpfad. */
|
||||
cyclesPath?: string;
|
||||
/** `CPU` erzwingt die CPU (`--device CPU`); sonst Wahl des Programms. */
|
||||
device?: string;
|
||||
threads?: number;
|
||||
/** Tonwert: `filmic` (Standard) oder `standard`; Zusatzbelichtung in EV. */
|
||||
look?: "filmic" | "standard";
|
||||
extraEv?: number;
|
||||
codec: Codec;
|
||||
onProgress?: (e: { fraction: number; stage: string; done: number; total: number }) => void;
|
||||
onLine?: (line: string) => void;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface CyclesResult {
|
||||
png: Uint8Array;
|
||||
/** Rohes lineares Bild des Programms (EXR). */
|
||||
exr: Uint8Array;
|
||||
width: number;
|
||||
height: number;
|
||||
dir: string;
|
||||
/** Wandzeit von Programmstart bis Ende (ms). */
|
||||
millis: number;
|
||||
/** Fehler-/Warnzeilen des Programms (leer = sauber). */
|
||||
messages: string[];
|
||||
}
|
||||
|
||||
/** Kommandozeile für `cycles`. */
|
||||
export function cyclesArgs(info: Pick<CyclesSceneInfo, "width" | "height" | "samples">, scenePath: string, outPath: string, o: Pick<CyclesRunOptions, "device" | "threads"> = {}): string[] {
|
||||
const a = ["--background", "--samples", String(info.samples), "--width", String(info.width), "--height", String(info.height), "--output", outPath];
|
||||
if (o.device) a.push("--device", o.device);
|
||||
if (o.threads && o.threads > 0) a.push("--threads", String(Math.round(o.threads)));
|
||||
a.push(scenePath);
|
||||
return a;
|
||||
}
|
||||
|
||||
/** Paket auspacken, `cycles` laufen lassen, Fortschritt melden, EXR → Tonwert → PNG. */
|
||||
export async function runCyclesRender(host: CyclesHost, pkg: CyclesPackage, opts: CyclesRunOptions): Promise<CyclesResult> {
|
||||
const exe = await host.find(opts.cyclesPath);
|
||||
if (!exe) throw new CyclesMissingError();
|
||||
const dir = await host.prepare(pkg.files);
|
||||
const out = host.join(dir, "render.exr");
|
||||
const total = pkg.info.samples;
|
||||
const messages: string[] = [];
|
||||
const t0 = Date.now();
|
||||
let stage = "scene";
|
||||
const job = host.spawn(exe, cyclesArgs(pkg.info, host.join(dir, "scene.xml"), out, opts), (line) => {
|
||||
opts.onLine?.(line);
|
||||
const ev = parseCyclesLine(line);
|
||||
if (!ev) return;
|
||||
if (ev.kind === "error") messages.push(ev.message);
|
||||
else 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 });
|
||||
}
|
||||
});
|
||||
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 CyclesCancelled();
|
||||
const millis = Date.now() - t0;
|
||||
if (code !== 0) throw new Error(`Cycles beendet mit Code ${code}${messages.length ? `: ${messages.slice(-3).join(" | ")}` : ""}`);
|
||||
const exr = await host.readFile(out).catch(() => null);
|
||||
if (!exr || exr.length === 0) throw new Error(messages.length ? `Cycles hat kein Bild geschrieben: ${messages.slice(-3).join(" | ")}` : "Cycles hat kein Bild geschrieben");
|
||||
const img = readExr(exr, opts.codec.inflate);
|
||||
const png = exrToPng(img, opts.look ?? "filmic", opts.extraEv ?? 0, opts.codec.deflate);
|
||||
opts.onProgress?.({ fraction: 1, stage: "done", done: total, total });
|
||||
return { png, exr, width: img.width, height: img.height, dir, millis, messages };
|
||||
}
|
||||
|
||||
// ── EXR lesen ───────────────────────────────────────────────────────────────
|
||||
|
||||
export interface ExrImage {
|
||||
width: number;
|
||||
height: number;
|
||||
/** RGB, zeilenweise von oben, linear. */
|
||||
rgb: Float32Array;
|
||||
}
|
||||
|
||||
/** Half → Float (IEEE 754 binary16). */
|
||||
function halfToFloat(h: number): number {
|
||||
const s = (h & 0x8000) !== 0 ? -1 : 1;
|
||||
const e = (h >> 10) & 0x1f;
|
||||
const f = h & 0x3ff;
|
||||
if (e === 0) return s * f * 2 ** -24;
|
||||
if (e === 31) return f === 0 ? s * Infinity : NaN;
|
||||
return s * (1 + f / 1024) * 2 ** (e - 15);
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenEXR (einteilig, Zeilenblöcke) lesen: Kompression keine/ZIPS/ZIP, Kanäle R, G, B (Half, Float oder UInt32). Anderes (PIZ,
|
||||
* Kacheln, mehrteilig) wirft einen Fehler; das Programm schreibt sein EXR mit ZIP und Float.
|
||||
*/
|
||||
export function readExr(bytes: Uint8Array, inflate: (d: Uint8Array) => Uint8Array): ExrImage {
|
||||
const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
if (bytes.length < 16 || dv.getUint32(0, true) !== 0x01312f76) throw new Error("Kein OpenEXR-Bild");
|
||||
const flags = dv.getUint32(4, true);
|
||||
if (flags & 0x1a00) throw new Error("OpenEXR: Kacheln/mehrteilig/lange Namen werden nicht gelesen");
|
||||
let pos = 8;
|
||||
const text = new TextDecoder();
|
||||
const cstr = (): string => {
|
||||
const start = pos;
|
||||
while (pos < bytes.length && bytes[pos] !== 0) pos++;
|
||||
const s = text.decode(bytes.subarray(start, pos));
|
||||
pos++;
|
||||
return s;
|
||||
};
|
||||
let channels: { name: string; type: number }[] = [];
|
||||
let win: [number, number, number, number] = [0, 0, -1, -1];
|
||||
let compression = 0;
|
||||
for (;;) {
|
||||
const name = cstr();
|
||||
if (name === "") break;
|
||||
cstr();
|
||||
const size = dv.getInt32(pos, true);
|
||||
pos += 4;
|
||||
const end = pos + size;
|
||||
if (name === "channels") {
|
||||
let p = pos;
|
||||
channels = [];
|
||||
while (p < end && bytes[p] !== 0) {
|
||||
let q = p;
|
||||
while (bytes[q] !== 0) q++;
|
||||
const chName = text.decode(bytes.subarray(p, q));
|
||||
p = q + 1;
|
||||
channels.push({ name: chName, type: dv.getInt32(p, true) });
|
||||
p += 16;
|
||||
}
|
||||
} else if (name === "dataWindow") {
|
||||
win = [dv.getInt32(pos, true), dv.getInt32(pos + 4, true), dv.getInt32(pos + 8, true), dv.getInt32(pos + 12, true)];
|
||||
} else if (name === "compression") {
|
||||
compression = bytes[pos];
|
||||
}
|
||||
pos = end;
|
||||
}
|
||||
const width = win[2] - win[0] + 1;
|
||||
const height = win[3] - win[1] + 1;
|
||||
if (!(width > 0 && height > 0) || width * height > 2 ** 28) throw new Error("OpenEXR: ungültige Bildgrösse");
|
||||
if (compression !== 0 && compression !== 2 && compression !== 3) throw new Error(`OpenEXR: Kompression ${compression} wird nicht gelesen (erwartet: keine, ZIPS, ZIP)`);
|
||||
const rows = compression === 3 ? 16 : 1;
|
||||
const blocks = Math.ceil(height / rows);
|
||||
const idx = (n: string) => channels.findIndex((c) => c.name === n);
|
||||
const [ri, gi, bi] = [idx("R"), idx("G"), idx("B")];
|
||||
if (ri < 0 || gi < 0 || bi < 0) throw new Error("OpenEXR: Kanäle R, G, B fehlen");
|
||||
const size = (t: number) => (t === 1 ? 2 : 4);
|
||||
const rowBytes = channels.reduce((n, c) => n + width * size(c.type), 0);
|
||||
const out = new Float32Array(width * height * 3);
|
||||
const table = pos;
|
||||
for (let b = 0; b < blocks; b++) {
|
||||
const off = Number(dv.getBigUint64(table + b * 8, true));
|
||||
const y0 = dv.getInt32(off, true) - win[1];
|
||||
const n = dv.getInt32(off + 4, true);
|
||||
let raw = bytes.subarray(off + 8, off + 8 + n);
|
||||
const lines = Math.min(rows, height - y0);
|
||||
const want = rowBytes * lines;
|
||||
if (compression !== 0 && n < want) {
|
||||
const d = inflate(raw);
|
||||
// Vorhersage rückgängig machen, Hälften wieder verschränken.
|
||||
const t = new Uint8Array(d.length);
|
||||
t[0] = d[0];
|
||||
for (let i = 1; i < d.length; i++) t[i] = (t[i - 1] + d[i] - 128) & 255;
|
||||
const half = (d.length + 1) >> 1;
|
||||
const un = new Uint8Array(d.length);
|
||||
for (let i = 0, k = 0; k < half; i += 2, k++) un[i] = t[k];
|
||||
for (let i = 1, k = half; k < d.length; i += 2, k++) un[i] = t[k];
|
||||
raw = un;
|
||||
}
|
||||
if (raw.length < want) throw new Error("OpenEXR: Zeilenblock zu kurz");
|
||||
const rv = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
|
||||
let q = 0;
|
||||
for (let l = 0; l < lines; l++) {
|
||||
const y = y0 + l;
|
||||
for (let ci = 0; ci < channels.length; ci++) {
|
||||
const c = channels[ci];
|
||||
const slot = ci === ri ? 0 : ci === gi ? 1 : ci === bi ? 2 : -1;
|
||||
const sz = size(c.type);
|
||||
if (slot >= 0) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
const o = q + x * sz;
|
||||
out[(y * width + x) * 3 + slot] = c.type === 1 ? halfToFloat(rv.getUint16(o, true)) : c.type === 2 ? rv.getFloat32(o, true) : rv.getUint32(o, true);
|
||||
}
|
||||
}
|
||||
q += width * sz;
|
||||
}
|
||||
}
|
||||
}
|
||||
return { width, height, rgb: out };
|
||||
}
|
||||
|
||||
// ── PNG schreiben ───────────────────────────────────────────────────────────
|
||||
|
||||
let crcTable: Uint32Array | null = null;
|
||||
function crc32(parts: Uint8Array[]): number {
|
||||
if (!crcTable) {
|
||||
crcTable = new Uint32Array(256);
|
||||
for (let n = 0; n < 256; n++) {
|
||||
let c = n;
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
crcTable[n] = c >>> 0;
|
||||
}
|
||||
}
|
||||
let c = 0xffffffff;
|
||||
for (const p of parts) for (let i = 0; i < p.length; i++) c = crcTable[(c ^ p[i]) & 255] ^ (c >>> 8);
|
||||
return (c ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
/** PNG (RGB, 8 Bit) aus einem RGB-Puffer; `deflate` = Zlib des Gastgebers. */
|
||||
export function encodePng(width: number, height: number, rgb: Uint8Array, deflate: (d: Uint8Array) => Uint8Array): Uint8Array {
|
||||
const raw = new Uint8Array((width * 3 + 1) * height);
|
||||
for (let y = 0; y < height; y++) raw.set(rgb.subarray(y * width * 3, (y + 1) * width * 3), y * (width * 3 + 1) + 1);
|
||||
const idat = deflate(raw);
|
||||
const chunk = (type: string, data: Uint8Array): Uint8Array => {
|
||||
const t = new TextEncoder().encode(type);
|
||||
const out = new Uint8Array(12 + data.length);
|
||||
const dv = new DataView(out.buffer);
|
||||
dv.setUint32(0, data.length);
|
||||
out.set(t, 4);
|
||||
out.set(data, 8);
|
||||
dv.setUint32(8 + data.length, crc32([t, data]));
|
||||
return out;
|
||||
};
|
||||
const head = new Uint8Array(13);
|
||||
const hv = new DataView(head.buffer);
|
||||
hv.setUint32(0, width);
|
||||
hv.setUint32(4, height);
|
||||
head.set([8, 2, 0, 0, 0], 8);
|
||||
const parts = [new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", head), chunk("IDAT", idat), chunk("IEND", new Uint8Array(0))];
|
||||
const png = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
||||
let o = 0;
|
||||
for (const p of parts) {
|
||||
png.set(p, o);
|
||||
o += p.length;
|
||||
}
|
||||
return png;
|
||||
}
|
||||
|
||||
/** Lineares Bild → Tonwert (Kern) → PNG. */
|
||||
export function exrToPng(img: ExrImage, look: "filmic" | "standard", extraEv: number, deflate: (d: Uint8Array) => Uint8Array): Uint8Array {
|
||||
const rgb8 = core().cycles_tonemap(img.rgb, 3, extraEv, look);
|
||||
if (rgb8.length !== img.width * img.height * 3) throw new Error("Tonwert-Abbildung fehlgeschlagen");
|
||||
return encodePng(img.width, img.height, rgb8, deflate);
|
||||
}
|
||||
Reference in new issue
Block a user