diff --git a/TODO.md b/TODO.md index e56f4579..9760ee9a 100644 --- a/TODO.md +++ b/TODO.md @@ -846,6 +846,7 @@ Kennwort, anonym) als PDF; Austausch mit Fachplanern über DXF/IFC. Standalone (EXR → Belichtung/Tonwert/sRGB macht Dossier); ohne OCIO nur „auto“/Non-Color als Farbraum. **Empfehlung:** Cycles einbauen, Pathtracer [212] bleibt Vorschau; Aufwand **12–16 Tage** (Bauskripte/CI 2, Mac/Metal/Signieren 3 (Mac), XML-Schreiber im Kern 4–5, Job/Dialog/CLI 1–2, Tonwert/PNG 1–2, Feinschliff 1–2). Mac-Skript `scripts/cycles/build-macos.sh` nur Entwurf (nichts ausgeführt). **Offen:** gesamter Mac-Weg (Metal, Kernel-Übersetzung beim ersten Start, Zeiten), älterer Linux-Unterbau für AppImage, kleinerer Embree/OIDN, grosse Modelle, Tonwert-Look gegen den Blender-Leser (AgX), Sonnen-Drehsinn prüfen. + **Stand 17.11. (Teil 1: Szene + CLI):** Kern schreibt die Cycles-XML-Szene (`cycles_scene.rs`, Abfrage `cyclesScene`; gleiche Netze wie glTF/3D, Materialien, Glas, Box-Texturen, Kamera, Sonne/Nishita, Belichtung), Tonwert im Kern (`cycles_post.rs`), TS `src/export/cyclesRender.ts` (EXR lesen, PNG), CLI `render --engine cycles` (`--engine blender` bleibt Standard). Tests: Rust 18, vitest (Ersatz-`cycles`, EXR/PNG), Integrationstest nur mit `DOSSIER_CYCLES`. Echte Läufe `:beispiel`, `:musterhaus-komplex`, `:wettbewerb` (1280×720, 64 Samples: 44–249 s auf ausgelasteten 4 vCPU) angesehen, Bilder in `doc/review-215/`; Details `doc/CYCLES.md` Abschnitt 10. **Offen:** Dialog/Sidecar/Mac (Teil 2), Normalenkarten, Mac/Metal ungeprüft, Standard-Engine der CLI auf Cycles umstellen sobald das Programm ausgeliefert wird. ### Nicht in 1.0 (bewusst später) Ausführungsplanung 1:50/1:20-Details, [42] Varianten, [11] Bibliothek per GUID, [88] Web-Link, [G7] Booleans-Ausbau, diff --git a/doc/ARCHITEKTUR.md b/doc/ARCHITEKTUR.md index b8a8cc50..9fb1f0d9 100644 --- a/doc/ARCHITEKTUR.md +++ b/doc/ARCHITEKTUR.md @@ -643,7 +643,8 @@ Import-Liste und keine „Kontext-Schicht", die Sichtbarkeit oder Darstellung st (läuft nur, wenn ifcopenshell installiert ist). Andere Formate laufen nach demselben Muster: der Kern sammelt einen flachen Puffer (`mesh_data.rs` für -OBJ/STL/glTF, `plan/dxf.rs` für DXF/DWG), `fileio` schreibt die Datei. +OBJ/STL/glTF, `plan/dxf.rs` für DXF/DWG), `fileio` schreibt die Datei. Die Cycles-Szene für Endbilder ([215]) schreibt der Kern selbst +(`cycles_scene.rs`, gleiche Dreiecke wie `mesh_data.rs`; Abfrage `cyclesScene`), Gastgeber/Prozess in `src/export/cyclesRender.ts`, Plan in `doc/CYCLES.md`. Was bei Speichern, Export und Import jedes Formats mitreist und was verloren geht (mit Belegen im Code): `doc/DATEIFORMATE.md` ([C9]). diff --git a/doc/CYCLES.md b/doc/CYCLES.md index d22a68da..8135c59d 100644 --- a/doc/CYCLES.md +++ b/doc/CYCLES.md @@ -186,3 +186,35 @@ Summe **12–16 Tage**, davon **≈ 5 Tage Mac-abhängig**. Verkleinern der Ausl - Tonwert-Look gegen den Blender-Leser (AgX) und Sonnen-Drehsinn gegen `render_dossier.py`. - Hosts im Cloud-Container: gesperrt war `github.com` (alle Pfade, auch `codeload`, `api.github.com`, Release-Downloads; `raw.githubusercontent.com` und `pypi.org` gingen); gebraucht wurden nur `projects.blender.org` (Quellen, OIDN-LFS) und `archive.ubuntu.com` (OIIO-/libtiff-Quellen, apt). + +## 10. Umsetzung Teil 1: Szene aus dem Kern, CLI (17.11.) + +**Wo:** `src-tauri/core/src/cycles_scene.rs` (Szene), `cycles_post.rs` (Tonwert), Abfrage `cyclesScene` (`queries.rs`), Bindung `cycles_tonemap` (`web/cycles.rs`); +TS: `src/export/cyclesRender.ts` (Optionen, Bildkarten laden, Prozess, EXR lesen, PNG schreiben), CLI `src/cli/main.ts` +(`render --engine cycles`; `--engine blender` = Blender-Weg [211], bleibt Standard bis der Sidecar ausgeliefert wird). + +**Netze:** dieselbe Sammlung wie glTF/OBJ/STL und 3D-Anzeige (`mesh_data::collect_scene`: Wände mit Öffnungen, Decken, Dächer, Stützen, Treppen, Bäume, Fenster/Türen mit Glas, freie Körper, +Gelände, Kontext); Baugrube ausgeblendet wie [227] (`--excavation` lässt sie). Welt (x, Höhe, y) → Modell (x Ost, y Nord, z oben), Wicklung vertauscht. Ecken nach Knickwinkel 30° geteilt, +`interpolation="smooth"` (Cycles mittelt selbst, scharfe Kanten bleiben). Ein `` je Teil-Netz, gleiche Shader in einem ``. Kein `N`, keine UVs. + +**Materialien:** Principled BSDF, Farbe sRGB → linear, Albedo ≤ 0.8; Ersatzlooks ohne Bildkarte wie im Blender-Leser; Dachschichten je Baustoff. Glas: Transmission 1, IOR 1.5, für Schattenstrahlen +durchsichtig (`light_path is_shadow_ray` → `mix_closure` mit `transparent_bsdf`). Bildkarten: `texture_coordinate object → mapping (1/sizeM) → image_texture projection="box"`, Farbkarte × 0.8 (`vector_math`), +Rauheit/Metall `colorspace="Non-Color"`, Farbkarte Farbraum „auto“. Dateien `textures/_.` neben `scene.xml`; der Kern liefert `{path, url}`, der Gastgeber lädt die Bytes +(nicht ladbare Karten → Ersatzlook, die XML nennt nie eine fehlende Datei). + +**Kamera (im Spike falsch beschrieben):** Typ heisst `camera_type="perspective|orthograph"` — ein `type="…"` wird STILL ignoriert (immer Perspektive); `` gilt nicht, die Grösse +kommt per `--width/--height`. Matrix 16 Zahlen spaltenweise: rechts (= Blick × oben), oben, Blickrichtung, Ort. Orthogonal: Sichtebene ±1 hoch → halbe Sichthöhe als Skalierung der Spalten rechts/oben +(Test: 10-m-Höhe stimmt). `fov` (Bogenmass) gilt für die kürzere Bildkante. Voreinstellungen rahmen das Gebäude ein (Mass wie `make_camera` im Blender-Leser). + +**Sonne:** `sun_rotation` = Kompass-Azimut (0 = Nord, 90° = Ost) — mit Schattenwurf geprüft (Sonne Ost → Schatten nach Westen); `sun_elevation` Bogenmass, unter dem Horizont 1°. +Belichtung `` = 2^EV, automatisch nach Sonnenhöhe (Tabelle des Blender-Lesers), `--exposure EV` übersteuert. Hintergrundlicht `use_mis`, Bodenplatte, 8 Abpraller, OIDN. + +**Tonwert (`cycles_post.rs`):** EXR (Float, ZIP; `readExr` kennt keine/ZIPS/ZIP, Half/Float) → Kern `cycles_tonemap` → PNG. Look `filmic`: Helligkeit durch die ACES-Näherung (Narkowicz), +Farbton erhalten, Lichter entsättigt, sRGB-Übertragung; `standard` = nur begrenzen + sRGB. Einfacher als AgX (AgX bleibt in sehr hellen Flächen farbiger). + +**CLI:** `render --engine cycles --out bild.png [--cycles pfad|$DOSSIER_CYCLES] [--samples 64] [--size 1280x720] [--view|--camera] [--when] [--exposure EV] [--look] [--no-denoise] [--cpu] [--exr roh.exr] +[--no-context] [--excavation] [--verbose]`; Programm nicht gefunden = Exit 3. + +**Messwerte** (Linux-Container, 4 vCPU, durch andere Agenten ausgelastet, 1280×720, 64 Samples, OIDN, CPU; Wandzeit streut stark): `:beispiel` Iso 139 s · `:musterhaus-komplex` Südost-Perspektive 249 s, +Iso 96 s · `:wettbewerb` Iso 48 s, Perspektive 44 s. Bilder: `doc/review-215/`. Angesehen: Normalen stimmen, Fenster spiegeln/durchsichtig, Schatten zur erwarteten Seite. +**Nicht geprüft:** Mac/Metal, Tauri/Electron-Einbindung, Texturen im echten Lauf nur über `:musterhaus-komplex` (Wiese), Normalenkarten (unbenutzt). diff --git a/doc/review-215/musterhaus-komplex-iso.png b/doc/review-215/musterhaus-komplex-iso.png new file mode 100644 index 00000000..4336d9a1 Binary files /dev/null and b/doc/review-215/musterhaus-komplex-iso.png differ diff --git a/doc/review-215/musterhaus-komplex-suedost.png b/doc/review-215/musterhaus-komplex-suedost.png new file mode 100644 index 00000000..449b8e5a Binary files /dev/null and b/doc/review-215/musterhaus-komplex-suedost.png differ diff --git a/doc/review-215/wettbewerb-perspektive.png b/doc/review-215/wettbewerb-perspektive.png new file mode 100644 index 00000000..aeaf0ab0 Binary files /dev/null and b/doc/review-215/wettbewerb-perspektive.png differ diff --git a/src-tauri/core/src/README.md b/src-tauri/core/src/README.md index f6e1c296..fe3b3726 100644 --- a/src-tauri/core/src/README.md +++ b/src-tauri/core/src/README.md @@ -110,7 +110,9 @@ Neues Modul: `.rs` und `mod` in `lib.rs`, Bindungen in `web/.rs` u | `import_ifc.rs`, `import_context.rs` | IFC zu Bauteilen bzw. Kontext-Netzen (gelesen hat vorher `fileio`) | | `import_drawing.rs`, `import_terrain.rs`, `geo_mesh.rs` | DXF/DWG-Zeichnungen ins Projekt (`import_terrain`: Höhenlinien erkennen, [143]); swissBUILDINGS3D-Netze | | `ifc_data.rs`, `ifc_quantities.rs`, `ifc_stairs.rs` | IFC-Export-Sammler, Basismengen, Treppen | -| `mesh_data.rs` | Sammler für OBJ, STL, glTF | +| `mesh_data.rs` | Sammler für OBJ, STL, glTF (und die Cycles-Szene) | +| `cycles_scene.rs` | [215] Cycles-XML-Szene aus dem Projekt (Netze, Materialien, Kamera, Sonne); Abfrage `cyclesScene` | +| `cycles_post.rs` | [215] Tonwert linear → sRGB 8 Bit für das Cycles-Bild | | `export_schedule.rs`, `opening_schedule.rs` | Bauteilliste, Fenster- und Türliste | ## Tests diff --git a/src-tauri/core/src/cycles_post.rs b/src-tauri/core/src/cycles_post.rs new file mode 100644 index 00000000..4058b509 --- /dev/null +++ b/src-tauri/core/src/cycles_post.rs @@ -0,0 +1,128 @@ +//! [215] Nachbearbeitung des Cycles-Bildes: lineares Licht (EXR, Fliesskomma) → Tonwert → sRGB, 8 Bit. +//! +//! Das Standalone-Programm `cycles` hat weder Tonwert-Abbildung noch Farbverwaltung (ohne OCIO gebaut, s. `doc/CYCLES.md`): +//! ein PNG von ihm wäre lineares Licht in 8 Bit. Dossier rechnet darum selbst. Die Belichtung steckt schon in der Szene +//! (``, `cycles_scene.rs`); hier gibt es nur einen optionalen Zusatz in EV. +//! +//! Look `filmic` (Standard; ein einfacher Verlauf in der Art von Filmic/AgX, ohne Tabellen): +//! 1. Helligkeit L = 0.2126 R + 0.7152 G + 0.0722 B; Kurve `aces(x) = x(2.51x + 0.03) / (x(2.43x + 0.59) + 0.14)` +//! (Narkowicz-Näherung von ACES: weicher Fuss, flache Schulter, 0.18 → 0.27, Weiss läuft aus). +//! 2. Farbton erhalten: Pixel · aces(L)/L; Lichter entsättigen: je heller, desto mehr Anteil der Kurve je Kanal +//! (Mischung t = L/(1+L)) — sehr helle Farben laufen zu Weiss statt zu knalligem Gelb/Cyan. +//! 3. Begrenzen auf 0…1, sRGB-Übertragungsfunktion, auf 8 Bit runden. +//! Look `standard`: nur begrenzen und sRGB (für Vergleiche und Kontrollen). +//! Unterschied zu AgX in Blender: AgX bleibt auch bei sehr hellen Flächen farbiger und hat mehr Kontrastspielraum; für +//! Architekturbilder (Weiss besonnt ≈ 1.2 nach der Belichtung) genügt der einfache Verlauf. Nicht endliche Werte werden 0. + +use crate::jsnum; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Look { + Filmic, + Standard, +} + +impl Look { + pub fn parse(s: &str) -> Look { + if s.eq_ignore_ascii_case("standard") { + Look::Standard + } else { + Look::Filmic + } + } +} + +fn aces(x: f64) -> f64 { + (x * (2.51 * x + 0.03) / (x * (2.43 * x + 0.59) + 0.14)).clamp(0.0, 1.0) +} + +/// Lineares sRGB → Anzeigewert (Übertragungsfunktion). +fn oetf(x: f64) -> f64 { + let x = x.clamp(0.0, 1.0); + if x <= 0.003_130_8 { + x * 12.92 + } else { + 1.055 * jsnum::pow(x, 1.0 / 2.4) - 0.055 + } +} + +/// Ein Pixel: lineares RGB (Szenenwerte) → 8 Bit sRGB. +pub fn tonemap_pixel(rgb: [f64; 3], ev: f64, look: Look) -> [u8; 3] { + let gain = if ev.is_finite() && ev != 0.0 { jsnum::pow(2.0, ev.clamp(-16.0, 16.0)) } else { 1.0 }; + let c = rgb.map(|v| if v.is_finite() { v.max(0.0) * gain } else { 0.0 }); + let out = match look { + Look::Standard => c, + Look::Filmic => { + let l = 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; + let ratio = if l > 1e-9 { aces(l) / l } else { 0.0 }; + let t = l / (1.0 + l); + [0, 1, 2].map(|k| (c[k] * ratio * (1.0 - t) + aces(c[k]) * t).clamp(0.0, 1.0)) + } + }; + out.map(|v| (oetf(v) * 255.0 + 0.5).floor().clamp(0.0, 255.0) as u8) +} + +/// Pixelpuffer (RGB oder RGBA, Fliesskomma, zeilenweise von oben) → RGB 8 Bit. Ein Puffer mit anderer Kanalzahl oder +/// unvollständigen Pixeln ergibt einen leeren Puffer (nie Panic). +pub fn tonemap(data: &[f32], channels: usize, ev: f64, look: Look) -> Vec { + if !(channels == 3 || channels == 4) || data.is_empty() || data.len() % channels != 0 { + return Vec::new(); + } + let mut out = Vec::with_capacity(data.len() / channels * 3); + for px in data.chunks_exact(channels) { + out.extend_from_slice(&tonemap_pixel([f64::from(px[0]), f64::from(px[1]), f64::from(px[2])], ev, look)); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn schwarz_bleibt_schwarz_weiss_laeuft_aus() { + assert_eq!(tonemap_pixel([0.0; 3], 0.0, Look::Filmic), [0, 0, 0]); + let hi = tonemap_pixel([50.0; 3], 0.0, Look::Filmic); + assert_eq!(hi, [255, 255, 255]); + // Weisser Putz nach der Belichtung (≈ 1.2) liegt unter Weiss, Mittelgrau (0.27) in der Mitte. + let putz = tonemap_pixel([1.2; 3], 0.0, Look::Filmic)[0]; + let grau = tonemap_pixel([0.27; 3], 0.0, Look::Filmic)[0]; + assert!((220..=255).contains(&putz), "{putz}"); + assert!((110..=170).contains(&grau), "{grau}"); + } + + #[test] + fn monoton_und_farbton_erhalten() { + let mut last = 0; + for i in 0..200 { + let v = tonemap_pixel([f64::from(i) * 0.02; 3], 0.0, Look::Filmic)[1]; + assert!(v >= last, "bei {i}"); + last = v; + } + // Rotstich bleibt rot (mittlere Helligkeit), sehr helles Rot läuft Richtung Weiss. + let rot = tonemap_pixel([0.6, 0.1, 0.1], 0.0, Look::Filmic); + assert!(rot[0] > rot[1] + 60 && rot[1] == rot[2], "{rot:?}"); + let hell = tonemap_pixel([30.0, 3.0, 3.0], 0.0, Look::Filmic); + assert!(hell[1] > rot[1], "Lichter entsättigen: {hell:?}"); + } + + #[test] + fn zusatzbelichtung_in_ev() { + let a = tonemap_pixel([0.2; 3], 0.0, Look::Standard)[0]; + let b = tonemap_pixel([0.1; 3], 1.0, Look::Standard)[0]; + assert_eq!(a, b, "ein Blendenwert mehr = doppelt so hell"); + // sRGB-Punkte: 0.2140411 linear = 0.5 → 128. + assert!((127..=128).contains(&tonemap_pixel([0.2140411; 3], 0.0, Look::Standard)[0])); + } + + #[test] + fn kaputte_eingaben_ohne_panik() { + assert!(tonemap(&[], 3, 0.0, Look::Filmic).is_empty()); + assert!(tonemap(&[1.0, 1.0], 3, 0.0, Look::Filmic).is_empty()); + assert!(tonemap(&[1.0; 6], 2, 0.0, Look::Filmic).is_empty()); + let o = tonemap(&[f32::NAN, f32::INFINITY, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0], 4, f64::NAN, Look::Filmic); + assert_eq!(o.len(), 6); + assert_eq!(&o[..3], &[0, 0, 0]); + assert_eq!(tonemap(&[0.5; 8], 4, 0.0, Look::Filmic).len(), 6, "RGBA → RGB"); + } +} diff --git a/src-tauri/core/src/cycles_scene.rs b/src-tauri/core/src/cycles_scene.rs new file mode 100644 index 00000000..a64ef8b6 --- /dev/null +++ b/src-tauri/core/src/cycles_scene.rs @@ -0,0 +1,1085 @@ +//! [215] Cycles-Szene aus dem Projekt: schreibt die Cycles-XML-Szene für das mitgelieferte `cycles`-Programm +//! (Standalone, Apache-2.0; Plan und Messwerte: `doc/CYCLES.md`). +//! +//! Dreiecks-Quelle ist dieselbe wie bei glTF/OBJ/STL und der 3D-Anzeige (`mesh_data::collect_scene`: Wände mit +//! Öffnungen, Decken, Dächer, Stützen, Treppen, Bäume, Fenster/Türen mit Glas, freie Körper, Gelände, Kontext; +//! Baugrube wie [227] ausblendbar). Aus den Welt-Achsen der Sammlung (x, Höhe, y) werden Modell-Achsen +//! (x Ost, y Nord, z oben) mit umgekehrter Wicklung; Cycles bekommt die Netze unverändert in Metern. +//! +//! Was das Programm braucht und wie Dossier es liefert: +//! • Netze: `` je Teil-Netz, Ecken nach Knickwinkel (30°) geteilt (`smooth_corner_normals`), +//! Schattierung `smooth` — Cycles mittelt die Normalen je Ecke selbst, scharfe Kanten bleiben kantig. +//! • Materialien: Principled BSDF aus den Dossier-Materialien (Farbe sRGB → linear, Albedo höchstens 0.8, Rauheit, +//! Metall); Glas = Transmission 1 (IOR 1.5), für Schattenstrahlen durchsichtig; Bildkarten (`Component.material`, +//! Gelände: gewählte oder Wiese `Grass005`) als Box-Projektion über Objektkoordinaten, Kachel `sizeM` +//! (Farbkarte: Farbraum „auto“ = sRGB bei 8 Bit; Rauheit/Metall `Non-Color`). Ohne Bildkarte Ersatzlooks nach +//! Verwendung und Baustoffname wie im Blender-Leser (`scripts/blender/render_dossier.py`). +//! • Kamera: `` 16 Zahlen SPALTENWEISE (rechts, oben, Blickrichtung, Ort); die Cycles-Kamera blickt +//! entlang +Z, oben = +Y, rechts = Blick × oben. Orthogonal: `camera_type="orthograph"`, die Sichthöhe steckt als +//! Skalierung (halbe Höhe) in den Spalten rechts/oben. `fov` ist der Bildwinkel der kürzeren Bildkante. +//! • Himmel: Nishita (`multiple_scattering`) mit Sonne aus Datum/Ort (`sun::sun_position`) oder Azimut/Höhe; Cycles +//! zählt die Sonnen-Rotation wie der Kompass (0 = Nord +Y, 90° = Ost +X). Hintergrundlicht mit `use_mis`. +//! • Belichtung: `` als Faktor, automatisch nach Sonnenhöhe (`SUNLIT_WHITE` aus dem Blender-Leser); +//! das Programm schreibt lineares Licht (EXR), Tonwert: `cycles_post.rs`. +//! Rückgabe: XML-Text und die Liste der Bilddateien (relativer Pfad ↔ URL des Material-Systems); die Gastgeber laden +//! die Bytes (Rust im WASM liest keine Dateien) und legen sie neben die XML. + +use crate::jsnum; +use crate::mesh_data::{collect_scene, MeshOptions, Prim, SceneData}; +use crate::model::*; +use crate::style::hex_to_rgb; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::fmt::Write as _; + +/// Albedo-Obergrenze (linear): kein Baustoff reflektiert 100 Prozent (wie `ALBEDO_MAX` im Blender-Leser). +const ALBEDO_MAX: f64 = 0.80; +/// Knickwinkel der geteilten Ecken (wie glTF-Export und 3D-Anzeige). +const CREASE_DEG: f32 = 30.0; +/// Gemessene Strahldichte einer weissen besonnten Fläche im Nishita-Himmel nach Sonnenhöhe (Grad → Wert), wie im Blender-Leser. +const SUNLIT_WHITE: [(f64, f64); 11] = [(1.0, 0.65), (3.0, 1.5), (6.0, 3.3), (10.0, 6.4), (15.0, 10.9), (20.0, 14.9), (30.0, 23.7), (45.0, 34.9), (60.0, 43.5), (70.0, 47.5), (90.0, 50.8)]; +/// Gewünschte Helligkeit einer weissen besonnten Fläche nach der Belichtung. +const SUNLIT_TARGET: f64 = 1.5; +/// Mittag, 21. Juni 2026, 12:00 UTC (Vorgabe der Sonne ohne Zeitangabe). +const DEFAULT_WHEN_MS: f64 = 1_782_043_200_000.0; +const GRASS: [&str; 3] = ["/assets/materials/Grass005/color.jpg", "/assets/materials/Grass005/normal.jpg", "/assets/materials/Grass005/roughness.jpg"]; +const GRASS_SIZE_M: f64 = 4.0; + +/// Sonne mit festem Azimut (Grad von Nord im Uhrzeigersinn) und Höhe. +#[derive(Debug, Clone, Copy, Deserialize)] +pub struct SunIn { + pub azimuth: f64, + pub elevation: f64, +} + +/// Kamera: Voreinstellung (`iso`, `perspective`, `front`, `back`, `left`, `right`, `side`, `top`; rahmt das Gebäude ein) +/// oder explizit in Modell-Koordinaten (Form wie `RenderCamera` in `doc/RENDER-SZENE.md`). +#[derive(Debug, Clone, Deserialize)] +#[serde(untagged)] +pub enum CameraSpec { + Preset { preset: String }, + Explicit { + #[serde(default)] + kind: String, + position: [f64; 3], + direction: [f64; 3], + #[serde(default = "up_z")] + up: [f64; 3], + #[serde(default, rename = "fovDeg")] + fov_deg: Option, + #[serde(default, rename = "orthoHeight")] + ortho_height: Option, + }, +} + +fn up_z() -> [f64; 3] { + [0.0, 0.0, 1.0] +} + +/// Optionen der Szene (JSON, camelCase). +#[derive(Debug, Clone, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct CyclesOptions { + pub width: f64, + pub height: f64, + pub samples: f64, + pub denoise: bool, + /// Zeitpunkt der Sonne (Unix-ms); ohne Angabe und ohne `sun` der 21.6.2026 12:00 UTC. + pub when_ms: Option, + /// Fester Sonnenstand (übersteuert Zeit und Ort). + pub sun: Option, + /// Sonnenstärke (Vorgabe 1). + pub sun_intensity: f64, + /// Belichtung in EV (Vorgabe: automatisch nach Sonnenhöhe). + pub exposure_ev: Option, + pub camera: Option, + /// [227] Gelände ohne Baugrube (hinterfüllt); Vorgabe an (für Bilder). + pub backfilled: bool, + /// Gelände und Kontext mitnehmen. + pub context: bool, + /// Bodenplatte unter dem Modell (der Himmel unter dem Horizont ist dunkel). + pub ground: bool, + /// Bild-URLs, die der Gastgeber laden kann; `None` = alle. Fehlende Karten fallen auf den Ersatzlook zurück. + pub textures: Option>, +} + +impl Default for CyclesOptions { + fn default() -> Self { + CyclesOptions { + width: 1920.0, + height: 1080.0, + samples: 128.0, + denoise: true, + when_ms: None, + sun: None, + sun_intensity: 1.0, + exposure_ev: None, + camera: None, + backfilled: true, + context: true, + ground: true, + textures: None, + } + } +} + +/// Eine Bilddatei der Szene: relativer Pfad neben der XML, URL im Material-System. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct TextureRef { + pub path: String, + pub url: String, +} + +/// Ergebnis: XML-Text, Bilddateien, Kennzahlen. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CyclesScene { + pub xml: String, + pub textures: Vec, + /// Anzahl der Netze des Modells (ohne Boden) und ihrer Dreiecke. + pub meshes: usize, + pub triangles: usize, + pub width: u32, + pub height: u32, + pub samples: u32, + pub sun_azimuth: f64, + pub sun_elevation: f64, + /// Belichtungsfaktor in `` (2^EV). + pub exposure: f64, + pub notes: Vec, +} + +// ── Farben, Materialien ───────────────────────────────────────────────────── + +fn srgb_to_linear(c: f64) -> f64 { + if c <= 0.04045 { + c / 12.92 + } else { + jsnum::pow((c + 0.055) / 1.055, 2.4) + } +} + +fn lin(rgb: [f64; 3]) -> [f64; 3] { + [srgb_to_linear(rgb[0]), srgb_to_linear(rgb[1]), srgb_to_linear(rgb[2])] +} + +fn clamp_albedo(c: [f64; 3]) -> [f64; 3] { + [c[0].min(ALBEDO_MAX), c[1].min(ALBEDO_MAX), c[2].min(ALBEDO_MAX)] +} + +#[derive(Clone, Copy, PartialEq, Debug)] +enum Role { + Terrain, + Context, + Roof, + Opening, + Building, +} + +fn role_of(kind: &str) -> Role { + match kind { + "terrain" => Role::Terrain, + "context" => Role::Context, + "roof" => Role::Roof, + "window" | "door" | "" => Role::Opening, + _ => Role::Building, + } +} + +/// Bildkarten eines Materials (URLs) und Kachelgrösse. +#[derive(Debug, Clone, PartialEq)] +struct Tex { + color: String, + rough: Option, + metal: Option, + size_m: f64, +} + +/// Aufgelöstes Aussehen einer Fläche. +#[derive(Debug, Clone, PartialEq)] +struct Look { + label: String, + /// Linear, Albedo begrenzt (bei Glas leicht getönt). + color: [f64; 3], + rough: f64, + metal: f64, + glass: bool, + tex: Option, +} + +/// Ersatzlooks ohne Bildkarte: (Schlüsselwörter im Baustoffnamen, Farbe sRGB, Rauheit, Metall). +type LookRow = (&'static [&'static str], [f64; 3], f64, f64); +const ROOF_LOOKS: [LookRow; 7] = [ + (&["ziegel", "biber", "dachstein"], [0.56, 0.25, 0.16], 0.7, 0.0), + (&["schindel"], [0.40, 0.28, 0.18], 0.85, 0.0), + (&["blech", "zink", "titan", "kupfer", "alu", "stehfalz"], [0.55, 0.57, 0.58], 0.35, 1.0), + (&["kies"], [0.46, 0.44, 0.41], 0.95, 0.0), + (&["schiefer", "faserzement", "eternit"], [0.22, 0.23, 0.25], 0.8, 0.0), + (&["begr", "substrat", "gras"], [0.30, 0.42, 0.18], 0.95, 0.0), + (&["bitumen", "abdicht", "folie"], [0.10, 0.10, 0.10], 0.7, 0.0), +]; +const ROOF_DEFAULT: ([f64; 3], f64, f64) = ([0.34, 0.30, 0.28], 0.75, 0.0); +const BUILDING_LOOKS: [LookRow; 6] = [ + (&["backstein", "ziegel"], [0.60, 0.31, 0.22], 0.8, 0.0), + (&["beton"], [0.52, 0.52, 0.50], 0.85, 0.0), + (&["holz", "parkett", "lattung", "schalung", "bsp", "brettsperr"], [0.56, 0.40, 0.24], 0.65, 0.0), + (&["stahl", "metall", "alu"], [0.55, 0.57, 0.58], 0.4, 1.0), + (&["naturstein", "marmor", "granit"], [0.62, 0.60, 0.57], 0.5, 0.0), + (&["keramik", "fliese", "platte"], [0.75, 0.74, 0.72], 0.3, 0.0), +]; +const GRASS_SRGB: [f64; 3] = [0.33, 0.45, 0.18]; +const CONTEXT_SRGB: [f64; 3] = [0.78, 0.78, 0.77]; + +fn pick_look(table: &[LookRow], text: &str) -> Option<([f64; 3], f64, f64)> { + table.iter().find(|(words, ..)| words.iter().any(|w| text.contains(w))).map(|(_, c, r, m)| (*c, *r, *m)) +} + +/// Weiss = vom Modell nicht gesetzt (der Look kommt aus Bildkarte oder Namen). +fn is_unset(c: [f64; 3]) -> bool { + c.iter().all(|v| *v >= 0.97) +} + +/// Aussehen ohne Bildkarte: Farbe/Rauheit/Metall nach Verwendung, Baustoffname und gesetzter Farbe. +fn flat_look(role: Role, text: &str, rgb: [f64; 3], rough: f64, metal: f64) -> ([f64; 3], f64, f64) { + let mut hit: Option<([f64; 3], f64, f64)> = None; + match role { + Role::Terrain => hit = Some((GRASS_SRGB, 0.95, 0.0)), + Role::Context => hit = Some((CONTEXT_SRGB, 0.9, 0.0)), + Role::Roof => { + hit = pick_look(&ROOF_LOOKS, text); + if hit.is_none() && is_unset(rgb) { + hit = Some(ROOF_DEFAULT); + } + } + _ => { + if is_unset(rgb) { + hit = pick_look(&BUILDING_LOOKS, text); + } + } + } + let (c, r, m) = hit.unwrap_or((rgb, rough, metal)); + (clamp_albedo(lin(c)), r, m) +} + +/// Dachschicht, deren Baustoff die Farbe des Teilnetzes trägt (wie `splitRoofMaterials` in TS): die Schicht des +/// Dachtyps (aussen → innen), Rückfall die äusserste. Dächer mit eigener Farbe oder ohne Typ bleiben „Dach“. +fn roof_layer<'a>(p: &'a Project, roof_id: &str, mat_srgb: [f64; 3]) -> Option<&'a Component> { + let roof = p.roofs.as_deref()?.iter().find(|r| r.id == roof_id)?; + if roof.color.as_deref().is_some_and(|c| !c.is_empty()) { + return None; + } + let tid = roof.roof_type_id.as_deref()?; + let ty = p.roof_types.as_deref()?.iter().find(|t| t.id == tid)?; + let comps: Vec<&Component> = ty.layers.iter().filter_map(|l| p.component(&l.component_id)).collect(); + let want = lin(mat_srgb); + let close = |c: &Component| { + let have = lin(hex_to_rgb(&c.color, [f64::NAN; 3])); + have.iter().all(|v| v.is_finite()) && (have[0] - want[0]).abs() + (have[1] - want[1]).abs() + (have[2] - want[2]).abs() < 0.02 + }; + comps.iter().copied().find(|c| close(c)).or_else(|| comps.first().copied()) +} + +/// Erster Gelände-Körper mit Bauteil-Bildkarten, sonst die Wiese. +fn terrain_material(p: &Project) -> ComponentMaterial { + for o in p.context.as_deref().unwrap_or(&[]) { + if let ContextObject::TerrainMesh(t) = o { + if let Some(m) = t.component_id.as_deref().and_then(|id| p.component(id)).and_then(|c| c.material.as_ref()) { + if m.color.as_deref().is_some_and(|c| !c.is_empty()) { + return m.clone(); + } + } + } + } + ComponentMaterial { library_id: Some("Grass005".into()), color: Some(GRASS[0].into()), normal: Some(GRASS[1].into()), roughness: Some(GRASS[2].into()), size_m: Some(GRASS_SIZE_M), ..Default::default() } +} + +/// Ordner der Bilddateien neben der XML. +struct Textures { + list: Vec, + by_url: HashMap, +} + +impl Textures { + fn path_for(&mut self, url: &str, kind: &str) -> String { + if let Some(p) = self.by_url.get(url) { + return p.clone(); + } + let path = format!("textures/{}_{kind}.{}", self.by_url.len(), extension_of(url)); + self.by_url.insert(url.to_string(), path.clone()); + self.list.push(TextureRef { path: path.clone(), url: url.to_string() }); + path + } +} + +fn extension_of(url: &str) -> String { + let base = url.split(['?', '#']).next().unwrap_or(""); + match base.rsplit_once('.') { + Some((_, e)) if (2..=4).contains(&e.len()) && e.bytes().all(|b| b.is_ascii_alphanumeric()) => e.to_ascii_lowercase(), + _ => "jpg".into(), + } +} + +// ── Zahlen und XML ────────────────────────────────────────────────────────── + +/// Zahl mit höchstens `digits` Nachkommastellen, ohne überflüssige Nullen; nicht endlich → 0. +fn fmt(v: f64, digits: usize) -> String { + if !v.is_finite() { + return "0".into(); + } + let mut s = format!("{v:.digits$}"); + if s.contains('.') { + while s.ends_with('0') { + s.pop(); + } + if s.ends_with('.') { + s.pop(); + } + } + if s == "-0" { + s = "0".into(); + } + s +} + +fn rgb_attr(c: [f64; 3]) -> String { + format!("{} {} {}", fmt(c[0], 5), fmt(c[1], 5), fmt(c[2], 5)) +} + +/// Name für das XML: Buchstaben, Ziffern, `_`/`-`; sonst `_`. +fn xml_name(s: &str) -> String { + let n: String = s.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c } else { '_' }).collect(); + if n.is_empty() { + "x".into() + } else { + n + } +} + +fn xml_escape(s: &str) -> String { + s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) +} + +/// `` für ein Aussehen. Dateipfade der Bildkarten über `tex`. +fn shader_xml(name: &str, look: &Look, tex: &mut Textures) -> String { + let mut s = String::new(); + let _ = write!(s, ""); + if look.glass { + let _ = write!( + s, + "\ + \ + \ + ", + rgb_attr(look.color) + ); + } else if let Some(t) = &look.tex { + let inv = 1.0 / t.size_m; + let _ = write!( + s, + "\ + \ + \ + \ + \ + \ + ", + fmt(inv, 6), + xml_escape(&tex.path_for(&t.color, "color")), + fmt(ALBEDO_MAX, 3), + fmt(look.rough, 4), + fmt(look.metal, 4) + ); + for (url, id, socket) in [(&t.rough, "trough", "roughness"), (&t.metal, "tmetal", "metallic")] { + if let Some(u) = url { + let _ = write!( + s, + "\ + ", + xml_escape(&tex.path_for(u, socket)) + ); + } + } + s.push_str(""); + } else { + let _ = write!( + s, + "", + rgb_attr(look.color), + fmt(look.rough, 4), + fmt(look.metal, 4) + ); + } + s.push_str(""); + s +} + +// ── Netze ─────────────────────────────────────────────────────────────────── + +/// Ein Netz in Modell-Achsen mit geteilten Ecken. +struct MeshOut { + p: Vec, + verts: Vec, +} + +/// Teil-Netz (Welt-Achsen x, Höhe, y; nach aussen gewickelt) → Modell-Achsen (x, y, z) mit vertauschter Wicklung, Ecken je Lage und +/// Normale geteilt (Knickwinkel). Dreiecke mit ungültigen Indizes/Ecken und entartete fallen weg. +fn mesh_out(prim: &Prim) -> Option<(MeshOut, Vec<[f64; 3]>)> { + let model: Vec<[f64; 3]> = prim.positions.chunks_exact(3).map(|c| [c[0], c[2], c[1]]).collect(); + let nv = model.len(); + let ok = |v: f64| v >= 0.0 && v < nv as f64 && v.fract() == 0.0 && model[v as usize].iter().all(|x| x.is_finite()); + let mut idx: Vec = Vec::with_capacity(prim.indices.len()); + for t in prim.indices.chunks_exact(3) { + if ok(t[0]) && ok(t[1]) && ok(t[2]) { + idx.extend_from_slice(&[t[0] as u32, t[2] as u32, t[1] as u32]); + } + } + if idx.is_empty() { + return None; + } + let world = |i: usize| -> [f32; 3] { [model[i][0] as f32, model[i][1] as f32, model[i][2] as f32] }; + let normals = dossier_hatch::mesh_normals::smooth_corner_normals(&idx, nv, &world, CREASE_DEG); + let key = |v: f64| jsnum::round(v * 1e4) as i64; + let nkey = |v: f32| jsnum::round(f64::from(v) * 1e3) as i32; + let mut weld: HashMap<([i64; 3], [i32; 3]), u32> = HashMap::new(); + let mut out = MeshOut { p: Vec::new(), verts: Vec::new() }; + let mut used: Vec<[f64; 3]> = Vec::new(); + for (t, n) in idx.chunks_exact(3).zip(&normals) { + let Some(n) = n else { continue }; + for k in 0..3 { + let v = model[t[k] as usize]; + let id = *weld.entry(([key(v[0]), key(v[1]), key(v[2])], [nkey(n[k][0]), nkey(n[k][1]), nkey(n[k][2])])).or_insert_with(|| { + out.p.extend_from_slice(&v); + used.push(v); + (used.len() - 1) as u32 + }); + out.verts.push(id); + } + } + (!out.verts.is_empty()).then_some((out, used)) +} + +// ── Kamera, Sonne ─────────────────────────────────────────────────────────── + +fn norm3(v: [f64; 3]) -> Option<[f64; 3]> { + let l = v[0].hypot(v[1]).hypot(v[2]); + (l.is_finite() && l > 1e-12).then(|| [v[0] / l, v[1] / l, v[2] / l]) +} + +fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} + +/// Aufgelöste Kamera: Ort, Blickrichtung, oben, Art, vertikaler Bildwinkel (Grad) bzw. Sichthöhe (m). +struct Cam { + pos: [f64; 3], + dir: [f64; 3], + up: [f64; 3], + ortho: bool, + fov_deg: f64, + ortho_height: f64, +} + +/// Blickrichtungen der Voreinstellungen (vom Auge zum Modell, x Ost, y Nord, z oben) und ob orthogonal. +fn preset(name: &str) -> ([f64; 3], bool) { + match name { + "perspective" => ([1.0, 1.0, -0.55], false), + "front" => ([0.0, 1.0, 0.0], true), + "back" => ([0.0, -1.0, 0.0], true), + "side" | "right" => ([-1.0, 0.0, 0.0], true), + "left" => ([1.0, 0.0, 0.0], true), + "top" => ([0.0, 0.0, -1.0], true), + _ => ([1.0, 1.0, -0.8], true), + } +} + +/// Kamera rahmt das Gebäude ein (Mitte der Hülle, Radius = halbe Diagonale, mind. 1 m); wie `make_camera` im Blender-Leser. +fn framed_camera(name: &str, lo: [f64; 3], hi: [f64; 3], aspect: f64) -> Cam { + let (d, ortho) = preset(name); + let dir = norm3(d).unwrap_or([0.0, 1.0, 0.0]); + let up = if name == "top" { [0.0, 1.0, 0.0] } else { [0.0, 0.0, 1.0] }; + let center = [(lo[0] + hi[0]) / 2.0, (lo[1] + hi[1]) / 2.0, (lo[2] + hi[2]) / 2.0]; + let radius = ((hi[0] - lo[0]).hypot(hi[1] - lo[1]).hypot(hi[2] - lo[2]) / 2.0).max(1.0); + let fov = 50.0_f64; + let (dist, ortho_height) = if ortho { + (radius * 3.0, 2.2 * radius * (1.0_f64).max(1.0 / aspect)) + } else { + let half = (fov.to_radians() / 2.0).min(jsnum::atan(jsnum::tan(fov.to_radians() / 2.0) * aspect)); + (radius * 1.15 / jsnum::sin(half), 0.0) + }; + Cam { pos: [center[0] - dir[0] * dist, center[1] - dir[1] * dist, center[2] - dir[2] * dist], dir, up, ortho, fov_deg: fov, ortho_height } +} + +/// Matrix und Kamera-Element des XML. `None` bei unbrauchbarer Kamera (Richtung null, nicht endlich). +fn camera_xml(c: &Cam, width: f64, height: f64) -> Option { + let dir = norm3(c.dir)?; + let mut right = cross(dir, c.up); + if norm3(right).is_none() { + right = cross(dir, [0.0, 1.0, 0.0]); + } + let right = norm3(right)?; + let up = norm3(cross(right, dir))?; + if !c.pos.iter().all(|v| v.is_finite()) { + return None; + } + let aspect = width / height; + let (sx, sy, attrs) = if c.ortho { + let h = if c.ortho_height.is_finite() && c.ortho_height > 0.0 { c.ortho_height } else { 10.0 }; + // Die Sichtebene der Cycles-Kamera ist 2 hoch (Querformat) bzw. 2 breit (Hochformat): Spalten rechts/oben skalieren. + let s = h / 2.0; + (s, s, "camera_type=\"orthograph\"".to_string()) + } else { + let fv = c.fov_deg.clamp(5.0, 120.0).to_radians(); + // Cycles: `fov` gilt für die kürzere Bildkante. + let f = if aspect >= 1.0 { fv } else { 2.0 * jsnum::atan(jsnum::tan(fv / 2.0) * aspect) }; + (1.0, 1.0, format!("camera_type=\"perspective\" fov=\"{}\"", fmt(f, 8))) + }; + let col = |v: [f64; 3], s: f64| format!("{} {} {} 0", fmt(v[0] * s, 8), fmt(v[1] * s, 8), fmt(v[2] * s, 8)); + Some(format!( + "\n\n", + fmt(width, 0), + fmt(height, 0), + col(right, sx), + col(up, sy), + col(dir, 1.0), + fmt(c.pos[0], 5), + fmt(c.pos[1], 5), + fmt(c.pos[2], 5) + )) +} + +/// Belichtungsfaktor wie eine Kamera mit Automatik: besonnte weisse Fläche → `SUNLIT_TARGET`; geometrische +/// Interpolation der Tabelle (ohne `ln`/`exp`, plattformgleich). Begrenzt auf 2^-8 … 2^3. +fn auto_exposure(elevation: f64, strength: f64) -> f64 { + let e = if elevation.is_finite() { elevation.max(1.0) } else { 40.0 }; + let mut value = SUNLIT_WHITE[SUNLIT_WHITE.len() - 1].1; + for w in SUNLIT_WHITE.windows(2) { + let ((e0, v0), (e1, v1)) = (w[0], w[1]); + if e <= e1 { + let f = ((e - e0) / (e1 - e0)).max(0.0); + value = v0 * jsnum::pow(v1 / v0, f); + break; + } + } + let s = if strength.is_finite() { strength.max(1e-3) } else { 1.0 }; + (SUNLIT_TARGET / (value * s)).clamp(jsnum::pow(2.0, -8.0), 8.0) +} + +// ── Szene ─────────────────────────────────────────────────────────────────── + +/// Schreibt die Cycles-Szene. Fehler nur bei unbrauchbaren Optionen (Bildgrösse, Kamera); ein leeres Projekt ergibt eine +/// gültige Szene ohne Netze (`meshes == 0`). +pub fn cycles_scene(p: &Project, o: &CyclesOptions) -> Result { + let dim = |v: f64, what: &str| -> Result { + if v.is_finite() && (1.0..=32768.0).contains(&v) { + Ok(v.round() as u32) + } else { + Err(format!("cyclesScene: {what} ausserhalb 1…32768")) + } + }; + let (width, height) = (dim(o.width, "Breite")?, dim(o.height, "Höhe")?); + if !(o.samples.is_finite() && o.samples >= 1.0) { + return Err("cyclesScene: Samples ≥ 1".into()); + } + let samples = o.samples.min(1e6).round() as u32; + let mut notes: Vec = Vec::new(); + + let SceneData { groups, mats, .. } = collect_scene(p, &MeshOptions { opening_parts: true, context: o.context, by_level: false, backfilled: o.backfilled })?; + + let comp_mat: HashMap<&str, &ComponentMaterial> = { + let mut m = HashMap::new(); + for c in &p.components { + if let Some(cm) = c.material.as_ref().filter(|m| m.color.as_deref().is_some_and(|u| !u.is_empty())) { + m.entry(c.name.as_str()).or_insert(cm); + } + } + m + }; + let terrain_mat = terrain_material(p); + let avail = |u: &str| o.textures.as_ref().map_or(true, |l| l.iter().any(|x| x == u)); + let mut missing: Vec = Vec::new(); + + let mut tex = Textures { list: Vec::new(), by_url: HashMap::new() }; + let mut shader_ids: HashMap = HashMap::new(); + let mut shaders: Vec = Vec::new(); + let mut by_shader: Vec> = Vec::new(); + let (mut meshes, mut triangles) = (0usize, 0usize); + let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]); + let (mut lo_all, mut hi_all) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]); + let mut terrain_lo_z = f64::INFINITY; + + for g in &groups { + let role = role_of(g.kind); + for prim in &g.prims { + let Some(m) = (prim.material >= 0.0 && prim.material.fract() == 0.0).then(|| mats.list.get(prim.material as usize)).flatten() else { continue }; + let Some((mesh, used)) = mesh_out(prim) else { continue }; + + // Aussehen: Glas, Bildkarte, sonst Ersatzlook. + let srgb = [m.rgba[0], m.rgba[1], m.rgba[2]]; + let mut comp_name = m.name.clone(); + let mut label = m.name.clone(); + if role == Role::Roof && m.name == "Dach" { + if let Some(c) = roof_layer(p, &g.id, srgb) { + comp_name = c.name.clone(); + label = format!("Dach: {}", c.name); + } + } + let look = if m.rgba[3] < 1.0 { + let c = lin(srgb); + Look { label, color: [0.90 + 0.10 * c[0], 0.94 + 0.06 * c[1], 0.95 + 0.05 * c[2]], rough: 0.0, metal: 0.0, glass: true, tex: None } + } else { + let cm = if role == Role::Terrain { Some(&terrain_mat) } else { comp_mat.get(comp_name.as_str()).copied() }; + let mut t: Option = None; + if let Some(cm) = cm { + match cm.color.as_deref().filter(|u| !u.is_empty()) { + Some(u) if avail(u) => { + let ok = |u: &Option, missing: &mut Vec| u.as_deref().filter(|u| !u.is_empty()).and_then(|u| if avail(u) { Some(u.to_string()) } else { missing.push(u.to_string()); None }); + t = Some(Tex { + color: u.to_string(), + rough: ok(&cm.roughness, &mut missing), + metal: ok(&cm.metalness, &mut missing), + size_m: cm.size_m.filter(|s| s.is_finite() && *s > 0.0).unwrap_or(1.0), + }); + } + Some(u) => missing.push(u.to_string()), + None => {} + } + } + let (color, rough, metal) = flat_look(role, &comp_name.to_lowercase(), srgb, m.roughness, m.metallic); + Look { label, color, rough, metal, glass: false, tex: t } + }; + let key = format!("{look:?}"); + let sid = match shader_ids.get(&key) { + Some(&i) => i, + None => { + let i = shaders.len(); + shaders.push(shader_xml(&format!("m{i}_{}", xml_name(&look.label)), &look, &mut tex)); + by_shader.push(Vec::new()); + shader_ids.insert(key, i); + i + } + }; + + let mut s = String::with_capacity(mesh.p.len() * 8 + mesh.verts.len() * 7 + 64); + s.push_str(" 0 { + s.push(' '); + } + s.push_str(&fmt(*v, 4)); + } + let _ = write!(s, "\" nverts=\"{}\" verts=\"", vec!["3"; mesh.verts.len() / 3].join(" ")); + for (i, v) in mesh.verts.iter().enumerate() { + if i > 0 { + s.push(' '); + } + let _ = write!(s, "{v}"); + } + s.push_str("\" />"); + by_shader[sid].push(s); + meshes += 1; + triangles += mesh.verts.len() / 3; + for v in &used { + for k in 0..3 { + lo_all[k] = lo_all[k].min(v[k]); + hi_all[k] = hi_all[k].max(v[k]); + if !matches!(role, Role::Context | Role::Terrain) { + lo[k] = lo[k].min(v[k]); + hi[k] = hi[k].max(v[k]); + } + } + if role == Role::Terrain { + terrain_lo_z = terrain_lo_z.min(v[2]); + } + } + } + } + if meshes == 0 { + notes.push("Keine Geometrie im Modell".into()); + lo_all = [0.0; 3]; + hi_all = [0.0; 3]; + } + // Hülle fürs Einrahmen: das Gebäude; gibt es nur Kontext/Gelände, dieses. + let (blo, bhi) = if lo[0].is_finite() { (lo, hi) } else { (lo_all, hi_all) }; + if !missing.is_empty() { + missing.sort(); + missing.dedup(); + notes.push(format!("{} Bildkarten nicht verfügbar (Material einfarbig): {}", missing.len(), missing.join(", "))); + } + + // Sonne. + let (azimuth, elevation) = match (&o.sun, o.when_ms) { + (Some(s), _) if s.azimuth.is_finite() && s.elevation.is_finite() => (s.azimuth, s.elevation), + (_, when) => { + let (lat, lon) = crate::plan::extras::project_lat_lon(p); + let t = when.filter(|t| t.is_finite()).unwrap_or(DEFAULT_WHEN_MS); + let s = crate::sun::sun_position(lat, lon, t); + (s.azimuth, s.elevation) + } + }; + let strength = if o.sun_intensity.is_finite() && o.sun_intensity > 0.0 { o.sun_intensity } else { 1.0 }; + let exposure = match o.exposure_ev { + Some(ev) if ev.is_finite() => jsnum::pow(2.0, ev.clamp(-12.0, 8.0)), + _ => auto_exposure(elevation, strength), + }; + // Unter dem Horizont gibt es keine Sonne; knapp darüber rendern (Dämmerung) statt schwarz. + let sun_el = elevation.max(1.0).min(90.0).to_radians(); + let sun_rot = (((azimuth % 360.0) + 360.0) % 360.0).to_radians(); + + // Kamera. + let aspect = f64::from(width) / f64::from(height); + let cam = match &o.camera { + Some(CameraSpec::Explicit { kind, position, direction, up, fov_deg, ortho_height }) => { + Cam { pos: *position, dir: *direction, up: *up, ortho: kind == "orthogonal", fov_deg: fov_deg.filter(|f| f.is_finite() && *f > 0.0).unwrap_or(50.0), ortho_height: ortho_height.unwrap_or(10.0) } + } + Some(CameraSpec::Preset { preset }) => framed_camera(preset, blo, bhi, aspect), + None => framed_camera("iso", blo, bhi, aspect), + }; + let cam_xml = camera_xml(&cam, f64::from(width), f64::from(height)).ok_or("cyclesScene: Kamera unbrauchbar (Blickrichtung null oder nicht endlich)")?; + + // Boden: knapp unter dem Gelände (sonst dem tiefsten Punkt), gross genug bis zum Horizont. + let ground = o.ground.then(|| { + let z = if terrain_lo_z.is_finite() { terrain_lo_z } else { lo_all[2] } - 0.02; + let (cx, cy) = ((lo_all[0] + hi_all[0]) / 2.0, (lo_all[1] + hi_all[1]) / 2.0); + let h = ((hi_all[0] - lo_all[0]).hypot(hi_all[1] - lo_all[1]).hypot(hi_all[2] - lo_all[2])).max(10.0) * 30.0; + format!( + "", + fmt(cx - h, 2), fmt(cy - h, 2), fmt(z, 4), fmt(cx + h, 2), fmt(cy - h, 2), fmt(z, 4), fmt(cx + h, 2), fmt(cy + h, 2), fmt(z, 4), fmt(cx - h, 2), fmt(cy + h, 2), fmt(z, 4) + ) + }); + + let mut xml = String::new(); + let _ = writeln!(xml, ""); + let _ = writeln!(xml, ""); + let _ = writeln!(xml, "", fmt(exposure, 6)); + let _ = writeln!( + xml, + "", + o.denoise + ); + xml.push_str(&cam_xml); + let _ = writeln!( + xml, + "\n \n \n \n \n", + fmt(strength, 4), + fmt(sun_el, 8), + fmt(sun_rot, 8) + ); + for s in &shaders { + let _ = writeln!(xml, "{s}"); + } + if ground.is_some() { + let _ = writeln!( + xml, + "", + rgb_attr(lin([0.40, 0.46, 0.28])) + ); + } + let _ = writeln!(xml, ""); + for (i, list) in by_shader.iter().enumerate() { + if list.is_empty() { + continue; + } + let name = shaders[i].split('"').nth(1).unwrap_or("x").to_string(); + let _ = writeln!(xml, "{}", list.join("")); + } + if let Some(g) = &ground { + let _ = writeln!(xml, "{g}"); + } + xml.push_str("\n"); + + Ok(CyclesScene { xml, textures: tex.list, meshes, triangles, width, height, samples, sun_azimuth: azimuth, sun_elevation: elevation, exposure, notes }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample() -> Project { + serde_json::from_str(include_str!("../tests/fixtures/sample_project.json")).unwrap() + } + + fn opts(json: &str) -> CyclesOptions { + serde_json::from_str(json).unwrap() + } + + /// Prüft die Verschachtelung (Stapel der Element-Namen), Kommentare und Anführungszeichen der Attribute. + fn well_formed(xml: &str) { + let mut stack: Vec = Vec::new(); + let mut rest = xml; + let mut roots = 0; + while let Some(i) = rest.find('<') { + rest = &rest[i..]; + if let Some(r) = rest.strip_prefix("").expect("Kommentar offen") + 3..]; + continue; + } + // Ende des Tags: erstes `>` ausserhalb von Anführungszeichen. + let (mut q, mut end) = (false, None); + for (k, c) in rest.char_indices() { + match c { + '"' => q = !q, + '>' if !q => { + end = Some(k); + break; + } + _ => {} + } + } + let end = end.expect("Tag offen"); + let tag = &rest[1..end]; + rest = &rest[end + 1..]; + if let Some(name) = tag.strip_prefix('/') { + assert_eq!(stack.pop().as_deref(), Some(name.trim()), "Schliess-Tag {name}"); + } else { + let name = tag.split(|c: char| c.is_whitespace() || c == '/').next().unwrap().to_string(); + assert!(!name.is_empty()); + if stack.is_empty() { + roots += 1; + } + if !tag.ends_with('/') { + stack.push(name); + } + } + } + assert!(stack.is_empty() && roots == 1, "offene Elemente {stack:?}, Wurzeln {roots}"); + } + + /// Zählt ` usize { + xml.matches(&format!("<{tag} ")).count() + xml.matches(&format!("<{tag}>")).count() + } + + /// Das Beispielprojekt ergibt eine wohlgeformte XML-Szene: Zähler und Verschachtelung stimmen, alle Indizes zeigen auf Ecken. + #[test] + fn beispiel_ist_wohlgeformt() { + let s = cycles_scene(&sample(), &opts("{}")).unwrap(); + assert!(s.meshes > 5 && s.triangles > 50, "{} Netze, {} Dreiecke", s.meshes, s.triangles); + let x = &s.xml; + assert!(x.starts_with("") && x.trim_end().ends_with("")); + well_formed(x); + // Netzanzahl = Teil-Netze (Modell + ein Boden). + assert_eq!(count(x, "mesh"), s.meshes + 1); + // Jedes Netz: nverts × 3 = verts, alle Indizes < Ecken. + let mut tris = 0; + for m in x.split(" = vs.split_whitespace().map(|v| v.parse().unwrap()).collect(); + assert_eq!(nv.split_whitespace().map(|v| v.parse::().unwrap()).sum::(), ids.len()); + assert!(ids.iter().all(|i| *i < np / 3)); + tris += faces; + } + assert_eq!(tris, s.triangles + 1, "Flächen (Boden: 1 Viereck)"); + // Jeder Shader, den ein nennt, ist definiert. + for st in x.split("")), "Shader {name}"); + } + } + // Verbindungen nur zu Knoten desselben Shaders (grob): jede `from`-Knoten-Id kommt als name vor. + assert!(x.contains("transmission_weight=\"1\""), "Glas der Fenster"); + assert!(x.contains("is_shadow_ray")); + assert!(x.contains("interpolation=\"smooth\"")); + assert!(x.contains("use_denoise=\"true\"")); + } + + #[test] + fn leeres_projekt_ohne_panik() { + let p = Project { id: "leer".into(), ..Default::default() }; + let s = cycles_scene(&p, &opts("{}")).unwrap(); + assert_eq!(s.meshes, 0); + assert!(s.notes.iter().any(|n| n.contains("Keine Geometrie"))); + assert!(s.xml.contains(" = m.split_whitespace().map(|x| x.parse().unwrap()).collect(); + assert_eq!(v, vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 2.0, 3.0, 1.0]); + // Bildwinkel 60° vertikal bei 16:9 → `fov` = 60° im Bogenmass. + assert!(s.xml.contains("camera_type=\"perspective\" fov=\"1.047197"), "{}", s.xml.split(" = m.split_whitespace().map(|x| x.parse().unwrap()).collect(); + assert_eq!((v[0], v[6], v[9]), (6.0, 6.0, 1.0), "rechts = 6·X, oben = 6·Z, vorn = Y"); + } + + #[test] + fn voreinstellung_rahmt_das_gebaeude() { + let s = cycles_scene(&sample(), &opts("{\"camera\":{\"preset\":\"front\"}}")).unwrap(); + let m = s.xml.split(" = m.split_whitespace().map(|x| x.parse().unwrap()).collect(); + // Blick nach Norden: Ort südlich des Hauses (y < 0), Blickrichtung +Y. + assert!(v[13] < -5.0, "y = {}", v[13]); + assert_eq!((v[8], v[9], v[10]), (0.0, 1.0, 0.0)); + } + + /// Sonne: fester Azimut/Höhe → Nishita-Rotation = Kompass, Höhe im Bogenmass; Datum/Ort: Mittsommer Zürich. + #[test] + fn sonnenrichtung() { + let s = cycles_scene(&sample(), &opts("{\"sun\":{\"azimuth\":90,\"elevation\":30}}")).unwrap(); + assert!(s.xml.contains(&format!("sun_rotation=\"{}\"", fmt(90.0_f64.to_radians(), 8)))); + assert!(s.xml.contains(&format!("sun_elevation=\"{}\"", fmt(30.0_f64.to_radians(), 8)))); + // 21.6.2026 12:00 UTC in Zürich: ~65° hoch, nahe Süd (kurz nach dem Sonnenhöchststand also Azimut ≥ 180). + let z = cycles_scene(&Project { id: "z".into(), ..Default::default() }, &opts("{\"whenMs\":1782043200000}")).unwrap(); + assert!((z.sun_elevation - 65.0).abs() < 2.0, "{}", z.sun_elevation); + assert!((175.0..205.0).contains(&z.sun_azimuth), "{}", z.sun_azimuth); + // Winter morgens um 8 Uhr UTC: tiefe Sonne im Südosten. + let w = cycles_scene(&Project { id: "z".into(), ..Default::default() }, &opts("{\"whenMs\":1766390400000}")).unwrap(); + assert!(w.sun_elevation < 10.0 && (100.0..160.0).contains(&w.sun_azimuth), "{} {}", w.sun_elevation, w.sun_azimuth); + // Tiefe Sonne → hellere Belichtung (Faktor grösser). + assert!(w.exposure > z.exposure * 4.0); + } + + #[test] + fn belichtung_nach_tabelle() { + // Tabellenpunkte treffen ihren Wert: 60° → 1.5/43.5. + assert!((auto_exposure(60.0, 1.0) - SUNLIT_TARGET / 43.5).abs() < 1e-9); + assert!((auto_exposure(10.0, 1.0) - SUNLIT_TARGET / 6.4).abs() < 1e-9); + // Überschreiben in EV. + let s = cycles_scene(&sample(), &opts("{\"exposureEv\":-3}")).unwrap(); + assert!((s.exposure - 0.125).abs() < 1e-12); + } + + /// Material: Glas der Fenster, Bildkarte der Bauteile mit Material, Ersatzlooks; fehlende Karten fallen zurück. + #[test] + fn materialien_und_texturen() { + let mut p = sample(); + for c in p.components.iter_mut() { + c.material = Some(ComponentMaterial { color: Some("/assets/materials/Bricks104/color.jpg".into()), roughness: Some("/assets/materials/Bricks104/roughness.jpg".into()), size_m: Some(2.0), ..Default::default() }); + } + let s = cycles_scene(&p, &opts("{}")).unwrap(); + assert!(s.xml.contains("projection=\"box\"") && s.xml.contains(" c[2] && (r - 0.7).abs() < 1e-12 && m == 0.0, "{c:?}"); + let (c, _, m) = flat_look(Role::Building, "stahl", [1.0, 1.0, 1.0], 0.9, 0.0); + assert!(m == 1.0 && c[0] < 0.4); + assert!((srgb_to_linear(0.5) - 0.2140411).abs() < 1e-6); + } + + /// Hartes Ende bleibt kantig: ein Würfel hat 24 Ecken (3 je Ecke), eine glatte Fläche teilt ihre Ecken. + #[test] + fn ecken_nach_knickwinkel_geteilt() { + // Würfel als 8 Ecken / 12 Dreiecke in Welt-Achsen (x, Höhe, y). + let pos: Vec = vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0]; + let quads = [[0, 3, 2, 1], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]; + let mut idx: Vec = Vec::new(); + for q in quads { + for t in [[q[0], q[1], q[2]], [q[0], q[2], q[3]]] { + idx.extend(t.iter().map(|v| *v as f64)); + } + } + let prim = Prim { material: 0.0, positions: pos, indices: idx }; + let (m, _) = mesh_out(&prim).unwrap(); + assert_eq!(m.p.len() / 3, 24, "scharfe Kanten: 4 Ecken je Seite"); + assert_eq!(m.verts.len(), 36); + // Ebene Fläche aus zwei Dreiecken: 4 Ecken (Diagonale geteilt). + let flat = Prim { material: 0.0, positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0], indices: vec![0.0, 1.0, 2.0, 0.0, 2.0, 3.0] }; + assert_eq!(mesh_out(&flat).unwrap().0.p.len() / 3, 4); + // Kaputte Indizes/NaN: weg statt Panic. + let bad = Prim { material: 0.0, positions: vec![f64::NAN; 9], indices: vec![0.0, 1.0, 2.0, 9.0, 9.0, 9.0] }; + assert!(mesh_out(&bad).is_none()); + } + + /// Modell-Achsen: ein Dreieck, das in Welt-Achsen nach oben (+Höhe) zeigt, zeigt im Modell nach +z (Wicklung vertauscht). + #[test] + fn wicklung_zeigt_nach_aussen() { + // Welt (x, Höhe, y): Dreieck in der Ebene Höhe = 0, nach aussen (oben) gewickelt: Normale (0,1,0) in Welt-Rechtssystem. + let prim = Prim { material: 0.0, positions: vec![0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0], indices: vec![0.0, 1.0, 2.0] }; + let (m, _) = mesh_out(&prim).unwrap(); + let q = |i: usize| [m.p[3 * i], m.p[3 * i + 1], m.p[3 * i + 2]]; + let (a, b, c) = (q(m.verts[0] as usize), q(m.verts[1] as usize), q(m.verts[2] as usize)); + let n = cross([b[0] - a[0], b[1] - a[1], b[2] - a[2]], [c[0] - a[0], c[1] - a[1], c[2] - a[2]]); + assert!(n[2] > 0.0, "Modell-Normale {n:?}"); + } + + #[test] + fn baugrube_ausgeblendet_wie_227() { + let mut p = sample(); + let t = TerrainMesh { id: "g".into(), positions: vec![-50.0, -50.0, 0.0, 50.0, -50.0, 0.0, 50.0, 50.0, 0.0, -50.0, 50.0, 0.0], indices: vec![0.0, 1.0, 2.0, 0.0, 2.0, 3.0], ..Default::default() }; + let pit = Excavation { + id: "bg".into(), + outline: vec![Vec2 { x: -5.0, y: -5.0 }, Vec2 { x: 5.0, y: -5.0 }, Vec2 { x: 5.0, y: 5.0 }, Vec2 { x: -5.0, y: 5.0 }], + bottom: -3.0, + slope: Some(45.0), + ..Default::default() + }; + p.context = Some(vec![ContextObject::TerrainMesh(t), ContextObject::Excavation(pit)]); + let with = cycles_scene(&p, &opts("{\"backfilled\":false}")).unwrap(); + let back = cycles_scene(&p, &opts("{\"backfilled\":true}")).unwrap(); + assert!(with.triangles > back.triangles); + let none = cycles_scene(&p, &opts("{\"context\":false}")).unwrap(); + assert!(none.triangles < back.triangles); + } + + #[test] + fn dachschicht_nach_farbe() { + let mut p = sample(); + p.components.push(Component { id: "ziegel".into(), name: "Tonziegel".into(), color: "#8f402a".into(), ..Default::default() }); + p.roof_types = Some(vec![RoofType { id: "rt".into(), name: "Ziegeldach".into(), layers: vec![Layer { component_id: "ziegel".into(), thickness: 0.05, ..Default::default() }], ..Default::default() }]); + if let Some(r) = p.roofs.as_mut().and_then(|r| r.first_mut()) { + r.roof_type_id = Some("rt".into()); + r.color = None; + } + let s = cycles_scene(&p, &opts("{}")).unwrap(); + assert!(s.xml.contains("Dach__Tonziegel") || s.xml.contains("Dach_"), "{}", s.xml.lines().filter(|l| l.starts_with(">().join("\n")); + } +} diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index a9cedf0d..894f29b1 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -90,6 +90,8 @@ pub mod ifc_quantities; pub mod ifc_stairs; pub mod ifc_data; pub mod mesh_data; +pub mod cycles_scene; +pub mod cycles_post; pub mod solid_bool; pub mod solid_mesh; pub mod dormer; diff --git a/src-tauri/core/src/mesh_data.rs b/src-tauri/core/src/mesh_data.rs index 2a918b39..f8517fe5 100644 --- a/src-tauri/core/src/mesh_data.rs +++ b/src-tauri/core/src/mesh_data.rs @@ -48,19 +48,19 @@ impl Default for MeshOptions { } /// Teil-Netz mit EINEM Material, lokale Indizes. -struct Prim { - material: f64, - positions: Vec, - indices: Vec, +pub(crate) struct Prim { + pub(crate) material: f64, + pub(crate) positions: Vec, + pub(crate) indices: Vec, } /// Ein Bauteil-Vorkommen mit ≥ 1 Teil-Netz. -struct Group { - name: String, - kind: &'static str, - id: String, - level: f64, - prims: Vec, +pub(crate) struct Group { + pub(crate) name: String, + pub(crate) kind: &'static str, + pub(crate) id: String, + pub(crate) level: f64, + pub(crate) prims: Vec, } impl Group { @@ -74,17 +74,17 @@ impl Group { } /// Material der Szene: Farbe sRGB 0..1, Alpha < 1 = transparent (Glas). -struct Material { - name: String, - rgba: [f64; 4], - metallic: f64, - roughness: f64, +pub(crate) struct Material { + pub(crate) name: String, + pub(crate) rgba: [f64; 4], + pub(crate) metallic: f64, + pub(crate) roughness: f64, } /// Materialtabelle: gleiche Farbe + Name = ein Material (Schlüssel wie in TS als Text). #[derive(Default)] -struct Materials { - list: Vec, +pub(crate) struct Materials { + pub(crate) list: Vec, by_key: HashMap, } @@ -338,8 +338,47 @@ fn same_rgb(a: &Rgb, b: &Rgb) -> bool { a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9) } +/// Gesammelte Szene: Bauteil-Gruppen mit Teil-Netzen, Materialtabelle, Geschosse (gemeinsame Quelle von +/// glTF/OBJ/STL und der Cycles-Szene [215], `cycles_scene.rs`). +pub(crate) struct SceneData { + pub(crate) groups: Vec, + pub(crate) mats: Materials, + pub(crate) levels: Vec<(String, String)>, +} + /// Die Szene als flacher Puffer (s. Modulkopf). pub fn mesh_export_data(src: &Project, opt: &MeshOptions) -> Result { + let SceneData { groups, mats, levels } = collect_scene(src, opt)?; + // Flacher Puffer (Gegenstück zu `mesh_export.rs`). + let mut f = Flat::new(FLAT_VERSION); + f.num(if opt.by_level { 1.0 } else { 0.0 }); + f.num(mats.list.len() as f64); + for m in &mats.list { + let n = f.str(&m.name); + f.nums(&[n, m.rgba[0], m.rgba[1], m.rgba[2], m.rgba[3], m.metallic, m.roughness]); + } + f.num(levels.len() as f64); + for (id, name) in &levels { + let (a, b) = (f.str(id), f.str(name)); + f.nums(&[a, b]); + } + let groups: Vec<&Group> = groups.iter().filter(|g| g.prims.iter().any(|p| !p.indices.is_empty())).collect(); + f.num(groups.len() as f64); + for g in groups { + let (name, kind, id) = (f.str(&g.name), f.str(g.kind), f.str(&g.id)); + f.nums(&[name, kind, id, g.level, g.prims.len() as f64]); + for pr in &g.prims { + f.nums(&[pr.material, (pr.positions.len() / 3) as f64]); + f.nums(&pr.positions); + f.num((pr.indices.len() / 3) as f64); + f.nums(&pr.indices); + } + } + Ok(f) +} + +/// Sammelt die Szene aus dem Projekt (Dreiecke in Welt-Achsen (x, Höhe, y), nach aussen gewickelt). +pub(crate) fn collect_scene(src: &Project, opt: &MeshOptions) -> Result { let mut p = src.clone(); let mut groups: Vec = Vec::new(); let mut mats = Materials::default(); @@ -533,32 +572,7 @@ pub fn mesh_export_data(src: &Project, opt: &MeshOptions) -> Result = groups.iter().filter(|g| g.prims.iter().any(|p| !p.indices.is_empty())).collect(); - f.num(groups.len() as f64); - for g in groups { - let (name, kind, id) = (f.str(&g.name), f.str(g.kind), f.str(&g.id)); - f.nums(&[name, kind, id, g.level, g.prims.len() as f64]); - for pr in &g.prims { - f.nums(&[pr.material, (pr.positions.len() / 3) as f64]); - f.nums(&pr.positions); - f.num((pr.indices.len() / 3) as f64); - f.nums(&pr.indices); - } - } - Ok(f) + Ok(SceneData { groups, mats, levels }) } #[cfg(test)] diff --git a/src-tauri/core/src/plan/extras.rs b/src-tauri/core/src/plan/extras.rs index 4999a14f..3df649cf 100644 --- a/src-tauri/core/src/plan/extras.rs +++ b/src-tauri/core/src/plan/extras.rs @@ -82,7 +82,7 @@ fn ring_pts(r: &[[f64; 2]]) -> Vec { } /// Breite/Länge des Projekts aus `geoAnchor` (LV95), sonst Zürich. -fn project_lat_lon(p: &Project) -> (f64, f64) { +pub(crate) fn project_lat_lon(p: &Project) -> (f64, f64) { match &p.geo_anchor { Some(a) => crate::geo_rebase::lv95_to_wgs84(a.lv95.e, a.lv95.n), None => (47.3769, 8.5417), diff --git a/src-tauri/core/src/queries.rs b/src-tauri/core/src/queries.rs index 6c38a6dd..13e4d300 100644 --- a/src-tauri/core/src/queries.rs +++ b/src-tauri/core/src/queries.rs @@ -91,6 +91,11 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result json(&site_rules::check_project(p)), + // [215] Cycles-Szene (XML + Bilddateien) aus dem Projekt; Text = `CyclesOptions` als JSON (camelCase). + ("cyclesScene", _) => { + let o: crate::cycles_scene::CyclesOptions = if text.trim().is_empty() { Default::default() } else { serde_json::from_str(text).map_err(|e| format!("cyclesScene: {e}"))? }; + json(&crate::cycles_scene::cycles_scene(p, &o)?) + } ("dormerStatus", _) => json(&crate::dormer::status(p)), ("excavationQuantities", _) => json(&crate::excavation::quantities(p)), ("buildingFootprint", _) => json(&site_rules::building_footprint(p)), diff --git a/src-tauri/core/src/web/cycles.rs b/src-tauri/core/src/web/cycles.rs new file mode 100644 index 00000000..22e69cbb --- /dev/null +++ b/src-tauri/core/src/web/cycles.rs @@ -0,0 +1,11 @@ +//! Bindung der Cycles-Nachbearbeitung ([215], `crate::cycles_post`): lineares Fliesskomma-Bild → sRGB 8 Bit. + +use crate::cycles_post::{tonemap, Look}; +use wasm_bindgen::prelude::wasm_bindgen; + +/// `data`: RGB oder RGBA (`channels` 3/4), zeilenweise von oben, lineares Licht; `ev`: Zusatzbelichtung in Blenden; +/// `look`: "filmic" (Standard) oder "standard". Ergebnis: RGB 8 Bit; leer bei kaputtem Puffer. +#[wasm_bindgen] +pub fn cycles_tonemap(data: &[f32], channels: u32, ev: f64, look: &str) -> Vec { + tonemap(data, channels as usize, ev, Look::parse(look)) +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index 694f2fa1..c11383e0 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -52,6 +52,7 @@ pub mod furniture_lib; pub mod solid_bool; pub mod line_pattern; pub mod fonts; +pub mod cycles; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src/cli/main.ts b/src/cli/main.ts index 1da96f40..a54a2fd9 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -38,6 +38,9 @@ // ins Geschoss); Bericht als JSON. Z. B. convert plan.dxf p.obp --cmd "erkennen --out e.obp" // dossier-cli render --out bild.png [--view iso|perspective|front|back|left|right|top] [--when 2026-06-21T10:00Z] // [--camera Name|id] [--samples 128] [--size 1920x1080] [--cpu] [--excavation] [--blender pfad] [--keep] [211] [227] (--excavation: Baugrube im Bild lassen) Rendering mit Blender/Cycles +// dossier-cli render --engine cycles [--cycles pfad|$DOSSIER_CYCLES] --out bild.png [--view …|--camera …] [--when …] [--samples 64] [--size 1280x720] +// [--exposure EV] [--look filmic|standard] [--no-denoise] [--cpu|--device CPU] [--exr roh.exr] [--no-context] [--excavation] [--keep] [--verbose] +// [215] Rendering mit dem mitgelieferten Cycles (Szene aus dem Kern, Tonwert in Dossier); `--engine blender` (Standard) = Blender-Weg [211] // dossier-cli blend --out x.blend [--view …] [--camera …] [--when …] [--samples 128] [--size 1920x1080] [--cpu] [--excavation] [--blender pfad] [--keep] [228] Szene als .blend (Collections nach Bauteil, Bilder eingepackt, Kamera «Dossier-Kamera»), ohne zu rendern // dossier-cli model3d [--explode 3] [--hide …] [--grey …] [--out modell.json] 3D-Modell fürs Headless-Rendern (render_png) // dossier-cli pointcloud-info [--voxel 0.05] [--max 2000000] @@ -56,8 +59,9 @@ // // WASM-Pakete (src/engine/pkg*) werden aus DOSSIER_WASM_DIR bzw. `/src/engine` gelesen. -import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs"; import { spawn } from "node:child_process"; +import { deflateSync, inflateSync } from "node:zlib"; import { tmpdir } from "node:os"; import { basename, dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; @@ -169,8 +173,11 @@ import { RENDER_VIEW_PRESETS, findRenderCamera, projectRenderCameras, + buildCyclesPackage, + runCyclesRender, + CyclesMissingError, } from "../core"; -import type { BlenderHost, Filter3d, Project, RenderMode, RenderPackage, RenderViewPreset, TextureLoader, ViewTemplate } from "../core"; +import type { BlenderHost, CyclesHost, Filter3d, Project, RenderMode, RenderPackage, RenderViewPreset, TextureLoader, ViewTemplate } from "../core"; import { serveStdio } from "./mcp"; import { startBridge } from "./mcpBridge"; @@ -803,8 +810,8 @@ function nodeBlenderHost(keep: boolean): BlenderHost { }; } -/** Optionen von `render` und `blend` ([211] [228]): Kamera, Zeit, Grösse, Samples → Paket (bei ungültigen Optionen beendet `fail()` den Prozess). */ -async function buildCliPackage(project: Project, args: Args, mode: RenderMode): Promise { +/** Gemeinsame Optionen von `render` (Blender und Cycles) und `blend`: Kamera, Zeit, Grösse, Samples (bei ungültigen Optionen beendet `fail()` den Prozess). */ +function cliRenderParams(project: Project, args: Args, defaultSamples = 128, defaultSize = "1920x1080") { const view = (args.flags.get("view") ?? "iso") as RenderViewPreset; if (!(RENDER_VIEW_PRESETS as readonly string[]).includes(view)) return fail(`--view: ${RENDER_VIEW_PRESETS.join("|")}`); // [213] `--camera `: gespeicherte Kamera (Standpunkt, Ziel, Bildwinkel; Sonnenzeit der Kamera, falls `--when` fehlt). @@ -814,15 +821,21 @@ async function buildCliPackage(project: Project, args: Args, mode: RenderMode): const whenText = args.flags.get("when"); const when = whenText ? new Date(whenText) : (choice?.sunWhen ?? defaultRenderTime(project)); if (Number.isNaN(when.getTime())) return fail("--when: ungültiges Datum"); - const samples = Number(args.flags.get("samples") ?? 128); + const samples = Number(args.flags.get("samples") ?? defaultSamples); if (!Number.isFinite(samples) || samples < 1) return fail("--samples: Zahl ≥ 1"); - const sizeText = args.flags.get("size") ?? "1920x1080"; + const sizeText = args.flags.get("size") ?? defaultSize; const m = /^(\d+)x(\d+)$/i.exec(sizeText); if (!m) return fail("--size: BreitexHöhe in Pixeln, z. B. 1920x1080"); + return { view, choice, when, samples, width: Number(m[1]), height: Number(m[2]) }; +} + +/** Optionen von `render` und `blend` ([211] [228]): Kamera, Zeit, Grösse, Samples → Paket. */ +async function buildCliPackage(project: Project, args: Args, mode: RenderMode): Promise { + const { view, choice, when, samples, width, height } = cliRenderParams(project, args); await loadFileio(); const pkg = await buildRenderPackage( project, - { mode, width: Number(m[1]), height: Number(m[2]), samples, when, camera: choice ? choice.camera : { preset: view }, device: args.flags.has("cpu") ? "cpu" : "auto", backfilled: !args.flags.has("excavation") }, + { mode, width, height, samples, when, camera: choice ? choice.camera : { preset: view }, device: args.flags.has("cpu") ? "cpu" : "auto", backfilled: !args.flags.has("excavation") }, localTextureLoader(), ); if (pkg.missingTextures.length > 0) process.stderr.write(`Hinweis: ${pkg.missingTextures.length} Bildkarten nicht lesbar (Material erscheint einfarbig)\n`); @@ -841,6 +854,9 @@ function blenderFailure(e: unknown): number { /** `dossier-cli … render`: Paket bauen, Blender starten, Bild nach `--out`. Rückgabe = Exit-Code. */ async function runRender(project: Project, args: Args): Promise { + const engine = args.flags.get("engine") ?? "blender"; + if (engine === "cycles") return runCyclesRenderCli(project, args); + if (engine !== "blender") return fail("--engine: cycles|blender"); const pkg = await buildCliPackage(project, args, "render"); const target = args.flags.get("out") ?? `${exportProjectName(project) || "projekt"}.png`; try { @@ -861,6 +877,85 @@ async function runRender(project: Project, args: Args): Promise { } } +/** [215] Zlib des Node-Gastgebers für EXR (ZIP) und PNG. */ +const nodeCodec = { + inflate: (d: Uint8Array): Uint8Array => new Uint8Array(inflateSync(d)), + deflate: (d: Uint8Array): Uint8Array => new Uint8Array(deflateSync(d, { level: 6 })), +}; + +/** [215] Cycles als Kindprozess (Node): Programm aus `--cycles`, `DOSSIER_CYCLES`, neben der CLI (`cycles`, `cycles/cycles`) oder im PATH. */ +function nodeCyclesHost(keep: boolean): CyclesHost { + const exeName = process.platform === "win32" ? "cycles.exe" : "cycles"; + const isFile = (p: string) => existsSync(p) && statSync(p).isFile(); + return { + ...nodeBlenderHost(keep), + async find(custom) { + const given = custom?.trim() || process.env.DOSSIER_CYCLES?.trim(); + if (given) { + if (isFile(given)) return given; + const inner = join(given, exeName); + return isFile(inner) ? inner : null; + } + const here = dirname(fileURLToPath(import.meta.url)); + for (const c of [join(here, exeName), join(here, "cycles", exeName), join(here, "..", "cycles", exeName)]) if (isFile(c)) return c; + for (const d of (process.env.PATH ?? "").split(process.platform === "win32" ? ";" : ":")) { + if (d && isFile(join(d, exeName))) return join(d, exeName); + } + return null; + }, + }; +} + +/** `dossier-cli … render --engine cycles` [215]: Szene aus dem Kern, `cycles` starten, EXR → Tonwert → PNG. Rückgabe = Exit-Code (3 = Cycles fehlt). */ +async function runCyclesRenderCli(project: Project, args: Args): Promise { + const { view, choice, when, samples, width, height } = cliRenderParams(project, args, 64, "1280x720"); + const evText = args.flags.get("exposure"); + const exposureEv = evText === undefined ? undefined : Number(evText); + if (exposureEv !== undefined && !Number.isFinite(exposureEv)) return fail("--exposure: Zahl (EV)"); + const look = args.flags.get("look") ?? "filmic"; + if (look !== "filmic" && look !== "standard") return fail("--look: filmic|standard"); + const pkg = await buildCyclesPackage( + project, + { width, height, samples, denoise: !args.flags.has("no-denoise"), whenMs: when.getTime(), camera: choice ? choice.camera : { preset: view }, backfilled: !args.flags.has("excavation"), context: !args.flags.has("no-context"), exposureEv }, + localTextureLoader(), + ); + if (pkg.info.meshes === 0) return fail("render: Das Modell enthält keine 3D-Geometrie"); + if (pkg.missingTextures.length > 0) process.stderr.write(`Hinweis: ${pkg.missingTextures.length} Bildkarten nicht lesbar (Material erscheint einfarbig)\n`); + const target = args.flags.get("out") ?? `${exportProjectName(project) || "projekt"}.png`; + process.stderr.write(`Szene: ${pkg.info.meshes} Netze, ${pkg.info.triangles} Dreiecke, Sonne ${pkg.info.sunAzimuth.toFixed(0)}° / ${pkg.info.sunElevation.toFixed(0)}° hoch, Belichtung ×${pkg.info.exposure.toPrecision(3)}\n`); + let lastShown = 0; + try { + const res = await runCyclesRender(nodeCyclesHost(args.flags.has("keep")), pkg, { + cyclesPath: args.flags.get("cycles"), + device: args.flags.has("cpu") ? "CPU" : args.flags.get("device"), + look, + codec: nodeCodec, + onLine: args.flags.has("verbose") ? (l) => process.stderr.write(` ${l}\n`) : undefined, + onProgress: (e) => { + // Cycles meldet jeden Stand mehrfach; je Achtel und am Ende genau einmal anzeigen. + if (e.stage === "render" && e.done > lastShown && e.total > 0 && (e.done === e.total || e.done % Math.max(1, Math.floor(e.total / 8)) === 0)) { + lastShown = e.done; + process.stderr.write(`Sample ${e.done}/${e.total}\n`); + } + }, + }); + writeFileSync(target, res.png); + const exrTarget = args.flags.get("exr"); + if (exrTarget) writeFileSync(exrTarget, res.exr); + lastOutput = target; + process.stderr.write(`geschrieben: ${target} (${res.png.length} Bytes, ${res.width}x${res.height}, ${samples} Samples, Cycles ${(res.millis / 1000).toFixed(1)} s)\n`); + for (const n of pkg.info.notes) process.stderr.write(`Hinweis: ${n}\n`); + return 0; + } catch (e) { + if (e instanceof CyclesMissingError) { + process.stderr.write("Cycles nicht gefunden: --cycles angeben, DOSSIER_CYCLES setzen oder das Programm neben die CLI legen.\n"); + return 3; + } + process.stderr.write(`dossier-cli: ${e instanceof Error ? e.message : String(e)}\n`); + return 1; + } +} + /** [228] `dossier-cli … blend`: Szene wie fürs Rendering aufbauen und als .blend nach `--out` speichern (nicht rendern). */ async function runBlend(project: Project, args: Args): Promise { const pkg = await buildCliPackage(project, args, "save"); diff --git a/src/cli/render.test.ts b/src/cli/render.test.ts index fdf66722..c83ccab6 100644 --- a/src/cli/render.test.ts +++ b/src/cli/render.test.ts @@ -9,6 +9,7 @@ import { spawnSync } from "node:child_process"; import { run } from "./main"; import { serializeProject } from "../core"; import { sampleProject } from "../model/sampleProject"; +import { makeExr } from "../export/cyclesExr.testutil"; const dir = mkdtempSync(join(tmpdir(), "dossier-cli-render-")); const file = join(dir, "demo.obp"); @@ -187,3 +188,119 @@ print("PROBE " + json.dumps({ expect(info.persp).toEqual(["CAMERA"]); }, 300_000); }); + +// [215] `render --engine cycles`: Szene aus dem Kern, Ersatz-`cycles` (Shell-Skript) schreibt ein EXR; die CLI macht daraus das PNG. +describe("dossier-cli render --engine cycles", () => { + const fakeCycles = join(dir, "cycles-fake"); + const fakeExr = join(dir, "fake.exr"); + beforeAll(() => { + writeFileSync(fakeExr, makeExr(8, 4, new Float32Array(8 * 4 * 3).fill(0.4), true)); + writeFileSync( + fakeCycles, + `#!/bin/sh +echo "args: $@" > "${dir}/fake-cycles-args.txt" +out="" +prev="" +for a in "$@"; do + [ "$prev" = "--output" ] && out="$a" + prev="$a" + scene="$a" +done +cp "$scene" "${dir}/fake-cycles-scene.xml" +printf 'Progress 50.00 Sample 4/8\\rProgress 100.00 Sample 8/8\\n' +cp "${fakeExr}" "$out" +echo "Finished Rendering." +`, + ); + chmodSync(fakeCycles, 0o755); + }); + const quiet = async (f: () => Promise): Promise<{ result: T; err: string }> => { + const err = vi.spyOn(process.stderr, "write").mockImplementation(() => true); + try { + const result = await f(); + return { result, err: err.mock.calls.map((c) => String(c[0])).join("") }; + } finally { + err.mockRestore(); + } + }; + + it("schreibt Szene, startet cycles mit Grösse/Samples und macht ein PNG", async () => { + const png = join(dir, "cy.png"); + const { result, err } = await quiet(() => run([":musterhaus-komplex", "render", "--engine", "cycles", "--cycles", fakeCycles, "--out", png, "--camera", "Südost", "--samples", "8", "--size", "8x4"])); + expect(result).toBe(0); + expect(Array.from(readFileSync(png).subarray(1, 4))).toEqual([80, 78, 71]); + expect(err).toContain("geschrieben:"); + const args = readFileSync(join(dir, "fake-cycles-args.txt"), "utf8"); + expect(args).toMatch(/--background --samples 8 --width 8 --height 4 --output .*render\.exr .*scene\.xml/); + const xml = readFileSync(join(dir, "fake-cycles-scene.xml"), "utf8"); + expect(xml).toContain(""); + expect(xml).toContain("camera_type=\"perspective\""); + expect(xml).toMatch(/ { + const png = join(dir, "cy2.png"); + const old = process.env.DOSSIER_CYCLES; + try { + process.env.DOSSIER_CYCLES = fakeCycles; + expect((await quiet(() => run([file, "render", "--engine", "cycles", "--out", png, "--samples", "8", "--size", "8x4"]))).result).toBe(0); + expect(existsSync(png)).toBe(true); + process.env.DOSSIER_CYCLES = join(dir, "gibt-es-nicht"); + const r = await quiet(() => run([file, "render", "--engine", "cycles", "--out", join(dir, "cy3.png")])); + expect(r.result).toBe(3); + expect(r.err).toContain("Cycles nicht gefunden"); + } finally { + if (old === undefined) delete process.env.DOSSIER_CYCLES; + else process.env.DOSSIER_CYCLES = old; + } + }, 120_000); + + it("--engine blender bleibt der Standardweg; unbekannte Engine/Look beenden mit Fehler", async () => { + const exit = vi.spyOn(process, "exit").mockImplementation((() => { + throw new Error("exit"); + }) as never); + try { + await quiet(async () => { + await expect(run([file, "render", "--engine", "unity", "--out", join(dir, "u.png")])).rejects.toThrow("exit"); + await expect(run([file, "render", "--engine", "cycles", "--look", "grell", "--cycles", fakeCycles, "--out", join(dir, "u.png")])).rejects.toThrow("exit"); + }); + } finally { + exit.mockRestore(); + } + expect((await quiet(() => run([file, "render", "--engine", "blender", "--out", join(dir, "b.png"), "--blender", fake, "--size", "320x180", "--samples", "8"]))).result).toBe(0); + }, 120_000); +}); + +// Echter Lauf mit dem gebauten Cycles (nur wenn `DOSSIER_CYCLES` auf das Programm zeigt): `:beispiel` klein mit 8 Samples. +const realCycles = process.env.DOSSIER_CYCLES; +describe.skipIf(!realCycles || !existsSync(realCycles))("dossier-cli render --engine cycles mit echtem Cycles", () => { + it(":beispiel 320x180, 8 Samples → PNG mit Himmel, Haus und Boden", async () => { + const png = join(dir, "echt.png"); + const err = vi.spyOn(process.stderr, "write").mockImplementation(() => true); + try { + expect(await run([":beispiel", "render", "--engine", "cycles", "--out", png, "--samples", "8", "--size", "320x180", "--cpu"])).toBe(0); + } finally { + err.mockRestore(); + } + const bytes = readFileSync(png); + expect(Array.from(bytes.subarray(1, 4))).toEqual([80, 78, 71]); + const dv = new DataView(bytes.buffer, bytes.byteOffset); + expect([dv.getUint32(16), dv.getUint32(20)]).toEqual([320, 180]); + const { inflateSync } = await import("node:zlib"); + const raw = inflateSync(bytes.subarray(41, 41 + dv.getUint32(33))); + // Nicht einfarbig und nicht schwarz: Mittelwert hell genug, Streuung vorhanden. + let sum = 0; + let min = 255; + let max = 0; + for (let i = 0; i < raw.length; i++) { + if (i % (320 * 3 + 1) === 0) continue; + sum += raw[i]; + min = Math.min(min, raw[i]); + max = Math.max(max, raw[i]); + } + expect(sum / (raw.length - 180)).toBeGreaterThan(40); + expect(max - min).toBeGreaterThan(80); + }, 240_000); +}); diff --git a/src/core/document.ts b/src/core/document.ts index c61f9d1b..84887261 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -188,6 +188,7 @@ export type QueryName = | "ivhb" | "siteProof" | "siteCheck" + | "cyclesScene" | "excavationQuantities" | "dormerStatus" | "buildingFootprint" diff --git a/src/core/extra.ts b/src/core/extra.ts index 71ae79d4..552ca37b 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -113,6 +113,9 @@ export { BlenderMissingError, RenderCancelled, RENDER_SIZE_PRESETS, RENDER_QUALITY_PRESETS, RENDER_VIEW_PRESETS, BLENDER_CANDIDATES, BLENDER_DOWNLOAD_URL, } from "../export/blenderRender"; export type { BlenderHost, RenderPackage, RenderOptions, RenderScene, RenderCamera, RenderCameraSpec, RenderViewPreset, RenderMaterial, RenderRole, RenderCameraChoice, TextureLoader, BlenderEvent, RenderResult, RenderRunOptions, RenderMode, BlendResult } from "../export/blenderRender"; +// [215] Rendering mit dem mitgelieferten Cycles: Szene aus dem Kern (cyclesScene), Prozess-Ablauf, EXR/PNG +export { buildCyclesPackage, cyclesSceneInfo, runCyclesRender, parseCyclesLine, cyclesArgs, readExr, encodePng, exrToPng, CyclesMissingError, CyclesCancelled } from "../export/cyclesRender"; +export type { CyclesHost, CyclesPackage, CyclesSceneInfo, CyclesSceneOptions, CyclesRunOptions, CyclesResult, CyclesEvent, Codec, ExrImage } from "../export/cyclesRender"; // [209] Kostenschätzung grob (Kern kosten.rs): Rechnung, Beispielwerte, Bericht (CSV/PDF wie der Flächen-Nachweis) export { computeCostEstimate, defaultCostEstimate, formatChf } from "../analysis/costEstimate"; export type { CostResult, CostRow, CostQuantities, CostEstimate, CostGroup, CostMethod, CostBasis } from "../analysis/costEstimate"; diff --git a/src/export/cyclesExr.testutil.ts b/src/export/cyclesExr.testutil.ts new file mode 100644 index 00000000..1d8b2feb --- /dev/null +++ b/src/export/cyclesExr.testutil.ts @@ -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])]); +} + diff --git a/src/export/cyclesRender.test.ts b/src/export/cyclesRender.test.ts new file mode 100644 index 00000000..f10f95d4 --- /dev/null +++ b/src/export/cyclesRender.test.ts @@ -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(""); + 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(); + 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"); + }); +}); diff --git a/src/export/cyclesRender.ts b/src/export/cyclesRender.ts new file mode 100644 index 00000000..389fd26d --- /dev/null +++ b/src/export/cyclesRender.ts @@ -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): `` 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("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 { + let info = cyclesSceneInfo(project, opts.textures || !loadTexture ? opts : { ...opts, textures: undefined }); + const bytes = new Map(); + 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; + /** Neuer Arbeitsordner, Dateien hinein, Ordner zurück. */ + prepare(files: { path: string; bytes: Uint8Array }[]): Promise; + /** Startet das Programm; `onLine` je Ausgabezeile (stdout und stderr, Wagenrücklauf trennt). */ + spawn(exe: string, args: string[], onLine: (line: string) => void): { done: Promise; cancel(): void }; + readFile(path: string): Promise; + 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, scenePath: string, outPath: string, o: Pick = {}): 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 { + 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); +}