[212] Pathtracer Etappe 5 (Teil 1): kein Panic im Browser bei grossen Puffern, Fenster als Lichtportale (NEE mit MIS), Raumlicht bei Nacht, Belichtungsautomatik und -regler, Refit des Baums, Zeitstempel
- Puffer ohne mappedAtCreation, Grösse gegen die Gerätegrenzen geprüft (zu gross: nur Himmel, Hinweis im Viewport); e2e release10 [212] wieder aktiv, Test mit künstlich kleinen Grenzen - pt_lights.rs: Lichtliste (Glasflächen als Portale, Leuchten, Deckenuntersichten als Raumlicht), Auswahl nach Gewicht, Power-Heuristik gegen die BRDF; Test: Erwartungswert gleich, Varianz kleiner - exposure.rs: Histogramm-Automatik (40.–95. Perzentil), sanft nachgeführt; Regler EV, Auto, Raumlicht im Viewport - Bvh::refit bei gleicher Topologie, Dreiecke je Klumpen zwischengespeichert - render_png: --eye/--fov, --portals, --room-light, --exposure, --auto-exposure, --timing
This commit is contained in:
15 files changed
+1754
-141
No files matched your search
@@ -365,6 +365,10 @@ Kennwort, anonym) als PDF; Austausch mit Fachplanern über DXF/IFC.
|
||||
Normalenkarten, Gelände-Material im Modell (`TerrainMesh` hat kein Material-Feld; render3d nimmt `materialIndex` am
|
||||
Gelände schon an), Wiesen-Bildkarte `Grass005` fürs Gelände (heute prozedural), Mipmaps (ferne Karten flimmern nur ohne
|
||||
Akkumulation), Innenlicht bei Kamera im Haus, Mond, BVH-Teil-Update, OIDN.
|
||||
**Stand 13.11. (Etappe 5, Innenräume und Tempo; in Arbeit):** Absturz im Browser behoben (Chromium/SwiftShader: Panic in wgpu
|
||||
`create_buffer` beim ersten Bild — Puffer mit `mappedAtCreation` wirft im Browser synchron): der Pathtracer legt alle Puffer ohne
|
||||
`mappedAtCreation` an und prüft sie gegen `max_buffer_size`/`max_storage_buffer_binding_size`; zu gross = nur Himmel und Hinweis im
|
||||
Viewport. e2e `release10` [212] läuft wieder (mit altem render3d-WASM rot, mit neuem grün), Test mit künstlich kleinen Grenzen.
|
||||
**Stand 13.11. (Etappe 4, Oberflächen):** (1) Normalen- und Rauigkeitskarten (`ComponentMaterial.normal`/`.roughness`,
|
||||
OpenGL-Konvention wie `normal.jpg`/`…_NormalGL`): `pathtraceMaterials` gibt sie je Ebene mit (`normal`, `rough`), der
|
||||
Viewer dekodiert sie neben den Farbkarten (`materialTextures.ts`, `web::set_material_detail_textures`), render3d packt sie
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// derselbe Ablauf wie die Mac-Abnahme-Checkliste `doc/RELEASE-1.0.md`, so weit er im Browser geht.
|
||||
// Ein durchgehender Test (leeres Projekt → Kataster → Baurecht → Volumen → Raumprogramm → Pläne →
|
||||
// Flächen/Kennzahlen → Kostenschätzung → Abgabe-PDF → DXF/IFC), jeder Schritt ein `test.step` mit Prüfung des Ergebnisses.
|
||||
// Schritte, die noch fehlen, stehen als eigene `test.fixme` mit TODO-ID unten (derzeit nur [212] Pathtracer-Zähler) — nicht
|
||||
// Schritte, die noch fehlen, stehen als eigene `test.fixme` mit TODO-ID unten (derzeit keine; [212] Pathtracer-Zähler läuft seit 13.11. wieder) — nicht
|
||||
// weglassen, damit sichtbar bleibt, was für 1.0 fehlt. [207] [208] [211] sind seit 13.11. echte Tests (eigene `test`-Blöcke unten).
|
||||
// Netzabrufe (swisstopo/geo.admin) gibt es offline nicht: Grundstück und Nachbarbauten kommen aus der
|
||||
// Kataster-Fixture (`fixtures/kataster.dxf`, LV95).
|
||||
@@ -483,11 +483,11 @@ test("[211] Rendering-Dialog im Browser erzeugt das Export-Paket (model.glb + sc
|
||||
|
||||
// [212] Pathtracing-Stil der 3D-Ansicht: Zähler „Pathtracing: N Samples" zählt hoch. Das Canvas-Bild ist headless nicht lesbar —
|
||||
// geprüft werden nur Zähler und Konsole (Fixture meldet unerwartete Fehler).
|
||||
// Stand 13.11.: im Playwright-Chromium (WebGPU über SwiftShader, Adapter „google/swiftshader") initialisiert der 3D-Viewport,
|
||||
// aber der Pathtracer-Stil bricht beim ersten Bild mit einem Panic in wgpu `create_buffer` ab (webgpu.rs:2331, wohl ein Puffer über
|
||||
// den SwiftShader-Limits) — der Zähler erscheint nie. Darum nur mit DOSSIER_PATHTRACE=1 aktiv, sonst `fixme`.
|
||||
// Bis 13.11. brach der Stil im Playwright-Chromium (WebGPU über SwiftShader) beim ersten Bild mit einem Panic in wgpu
|
||||
// `create_buffer` ab (Puffer mit `mappedAtCreation`, webgpu.rs:2331). Seit [212] Etappe 5 legt der Pathtracer seine Puffer ohne
|
||||
// `mappedAtCreation` an und prüft sie gegen die Gerätegrenzen (zu gross: Hinweis statt Absturz) — der Test läuft wieder immer.
|
||||
// Auf dem Mac (Metal) wird der Stil von Hand geprüft (`doc/RELEASE-1.0.md`, 13.1).
|
||||
const pathtraceTest = process.env.DOSSIER_PATHTRACE ? test : test.fixme;
|
||||
const pathtraceTest = test;
|
||||
pathtraceTest("[212] Pathtracer-Stil: Sample-Zähler zählt hoch", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await startNewProject(page);
|
||||
|
||||
@@ -3,6 +3,13 @@
|
||||
// Dient Referenzbildern und der Prüfung des 3D ohne Nutzer-App.
|
||||
//
|
||||
// cargo run --release --features png --bin render_png -- modell.json aus.png [--view iso] [--style shaded] [--size 1200x800] [--target x,y,z] [--dist 12] [--sun 135,30]
|
||||
// [--eye x,y,z --target x,y,z [--fov 50]]
|
||||
// [--portals off] [--room-light off] [--exposure EV] [--auto-exposure off] [--timing] [--pt-bounces N] [--pt-notex]
|
||||
//
|
||||
// [212] Etappe 5: `--portals off` ohne Fenster-Portale (Vergleich), `--room-light off` ohne Raumlicht bei Nacht,
|
||||
// `--exposure EV` Belichtungskorrektur, `--auto-exposure off` feste Belichtung des Himmels (sonst Automatik wie im
|
||||
// Viewport, hier sofort eingestellt); `--timing` misst je Abschnitt (GPU-Zeitstempel, wenn das Gerät sie kann, sonst nur
|
||||
// Wanduhr) und meldet Baum-Aufbau, Lichtliste und Belichtung; `--pt-bounces N` / `--pt-notex` nur zur Messung.
|
||||
// [--points wolke.txt] [--point-size 3] [--point-color rgb|intensity|class|height]
|
||||
// [--style pathtrace --samples 64 [--denoise off] [--pt-goal 1024]] [--textures public] [--test-texture]
|
||||
//
|
||||
@@ -329,7 +336,8 @@ pub(crate) fn new_device() -> (wgpu::Device, wgpu::Queue) {
|
||||
.expect("kein GPU-Adapter");
|
||||
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
|
||||
label: Some("render_png.device"),
|
||||
required_features: wgpu::Features::empty(),
|
||||
// [212] Etappe 5: Zeitstempel für `--timing`, wenn der Adapter sie kann.
|
||||
required_features: adapter.features() & wgpu::Features::TIMESTAMP_QUERY,
|
||||
required_limits: wgpu::Limits::default(),
|
||||
experimental_features: wgpu::ExperimentalFeatures::disabled(),
|
||||
memory_hints: wgpu::MemoryHints::Performance,
|
||||
@@ -436,6 +444,12 @@ fn main() {
|
||||
}
|
||||
renderer.set_pathtrace_materials(&model.pt_materials);
|
||||
renderer.set_pathtrace_denoise(flag("--denoise", "on") != "off");
|
||||
renderer.set_pathtrace_portals(flag("--portals", "on") != "off");
|
||||
renderer.set_pathtrace_room_light(flag("--room-light", "on") != "off");
|
||||
renderer.set_pathtrace_exposure(flag("--exposure", "0").parse().unwrap_or(0.0), flag("--auto-exposure", "on") != "off");
|
||||
renderer.set_pathtrace_debug(flag("--pt-bounces", "0").parse().unwrap_or(0), args.iter().any(|a| a == "--pt-notex"));
|
||||
let timing = args.iter().any(|a| a == "--timing");
|
||||
renderer.set_pathtrace_timing(timing);
|
||||
let tex_dir = flag("--textures", "");
|
||||
let test_tex = args.iter().any(|a| a == "--test-texture");
|
||||
if (!tex_dir.is_empty() || test_tex) && !model.pt_materials.is_empty() {
|
||||
@@ -479,7 +493,16 @@ fn main() {
|
||||
.map(|v| [v[0], v[1], v[2]])
|
||||
.unwrap_or(target);
|
||||
let dist = flag("--dist", "").parse::<f32>().unwrap_or(dist);
|
||||
let camera = preset_camera(preset(&flag("--view", "iso")), target, dist);
|
||||
let mut camera = preset_camera(preset(&flag("--view", "iso")), target, dist);
|
||||
// [212] Etappe 5: freier Augpunkt (world x, Höhe, y wie `bounds`) mit `--target` als Blickziel, z. B. eine
|
||||
// Innenansicht; `--fov` = vertikaler Bildwinkel in Grad (Standard 50).
|
||||
let eye = flag("--eye", "").split(',').map(|v| v.trim().parse::<f32>()).collect::<Result<Vec<_>, _>>().ok().filter(|v| v.len() == 3);
|
||||
if let Some(e) = eye {
|
||||
camera = render3d::types::Camera { eye: [e[0], e[1], e[2]], target, ..render3d::types::Camera::default() };
|
||||
}
|
||||
if let Some(fov) = flag("--fov", "").parse::<f32>().ok().filter(|f| f.is_finite() && *f > 1.0 && *f < 170.0) {
|
||||
camera.fov_y = fov.to_radians();
|
||||
}
|
||||
|
||||
let tex = target_texture(&device, format, w, h);
|
||||
let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
@@ -500,6 +523,33 @@ fn main() {
|
||||
let _ = device.poll(wgpu::PollType::wait_indefinitely());
|
||||
let dt = t1.elapsed().as_secs_f64();
|
||||
let n = renderer.pathtrace_samples().saturating_sub(1).max(1);
|
||||
if timing {
|
||||
let (b, lights) = renderer.pathtrace_build();
|
||||
eprintln!(
|
||||
"Baum: {} Dreiecke aus {} Klumpen, {} in {:.1} ms; Lichter: {} Portale, {} Leuchten, {} Deckenlichter",
|
||||
b.tris,
|
||||
b.chunks_read,
|
||||
if b.refit { "Refit" } else { "Neubau" },
|
||||
b.ms,
|
||||
lights[0],
|
||||
lights[1],
|
||||
lights[2]
|
||||
);
|
||||
if let Some(t) = renderer.pathtrace_timings(&device) {
|
||||
eprintln!(
|
||||
"GPU-Zeit: Samples {:.1} ms ({:.2} ms je Sample), Entrauscher {:.2} ms, Belichtung + Anzeige {:.2} ms",
|
||||
t.samples_ms,
|
||||
t.samples_ms / (samples.saturating_sub(1).max(1)) as f64,
|
||||
t.denoise_ms,
|
||||
t.display_ms
|
||||
);
|
||||
} else {
|
||||
eprintln!("GPU-Zeit: keine Zeitstempel (Gerät ohne TIMESTAMP_QUERY)");
|
||||
}
|
||||
if let Some(e) = renderer.pathtrace_exposure(&device, &queue) {
|
||||
eprintln!("Belichtung: {:.3} (Ziel {:.3}, Mittel log2 {:.2})", e[0], e[2], e[3]);
|
||||
}
|
||||
}
|
||||
eprintln!(
|
||||
"pathtrace: {} Dreiecke, Aufbau + 1. Sample {:.2} s, {} Samples in {:.2} s = {:.2} Samples/s ({:.2} Mio. Pfade/s bei {}x{})",
|
||||
renderer.pathtrace_tri_count(),
|
||||
|
||||
+125
-21
@@ -109,6 +109,11 @@ pub fn classify_material(color: [f32; 3]) -> (u32, f32) {
|
||||
/// Höchste Albedo (energieerhaltend, wie der Blender-Leser [211]: ≤ 0.8).
|
||||
const MAX_ALBEDO: f32 = 0.8;
|
||||
|
||||
/// Grundfarbe linear (0..1) aus `GpuTri::mat` (wie `unpack_albedo` im Shader).
|
||||
pub fn unpack_linear(mat: u32) -> [f32; 3] {
|
||||
[(mat & 0xFF) as f32 / 255.0, ((mat >> 8) & 0xFF) as f32 / 255.0, ((mat >> 16) & 0xFF) as f32 / 255.0]
|
||||
}
|
||||
|
||||
fn pack_mat(color: [f32; 3], kind: u32) -> u32 {
|
||||
let mut out = kind << 24;
|
||||
for (k, c) in color.iter().enumerate() {
|
||||
@@ -159,8 +164,19 @@ pub struct Bvh {
|
||||
pub tris: Vec<GpuTri>,
|
||||
/// Texturdaten je Dreieck (gleiche Reihenfolge wie `tris`).
|
||||
pub tex: Vec<GpuTriTex>,
|
||||
/// [212] Etappe 5: Lichtliste (Portale, Leuchten, Raumlicht; `pt_lights.rs`).
|
||||
pub lights: crate::pt_lights::LightList,
|
||||
/// Platz im Baum je Eingabe-Dreieck (`NO_SLOT` = verworfen) — für `refit`.
|
||||
slots: Vec<u32>,
|
||||
/// SAH-Kosten nach dem Bau (Vergleich nach `refit`).
|
||||
sah_built: f32,
|
||||
}
|
||||
|
||||
/// Eingabe-Dreieck ohne Platz im Baum (nicht endlich, entartet oder Doppelseite).
|
||||
const NO_SLOT: u32 = u32::MAX;
|
||||
/// Nach einem `refit` darf der Baum höchstens so viel teurer sein (SAH) als frisch gebaut, sonst Neubau.
|
||||
pub const REFIT_MAX_COST: f32 = 1.3;
|
||||
|
||||
fn sub(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
|
||||
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
|
||||
}
|
||||
@@ -208,6 +224,31 @@ fn tri_key(v: &[[f32; 3]; 3]) -> [[i64; 3]; 3] {
|
||||
k
|
||||
}
|
||||
|
||||
/// Welche Eingabe-Dreiecke in den Baum kommen: endlich, nicht entartet, je Doppelseite das erste.
|
||||
fn kept_inputs(input: &[PtTri]) -> Vec<bool> {
|
||||
let mut seen: HashSet<[[i64; 3]; 3]> = HashSet::with_capacity(input.len());
|
||||
input
|
||||
.iter()
|
||||
.map(|t| {
|
||||
if !t.v.iter().flatten().all(|c| c.is_finite() && c.abs() < 1e7) {
|
||||
return false;
|
||||
}
|
||||
let n = cross(sub(t.v[1], t.v[0]), sub(t.v[2], t.v[0]));
|
||||
dot(n, n) > 1e-18 && seen.insert(tri_key(&t.v))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// GPU-Dreieck und Texturdaten eines Eingabe-Dreiecks (Material aus Tabelle und Vertexfarbe).
|
||||
fn gpu_tri(t: &PtTri, table: &PtMaterialTable) -> (GpuTri, GpuTriTex) {
|
||||
let (m, color) = table.resolve(t.layer, t.color);
|
||||
let tx = table.tex_for(t.layer, &m);
|
||||
(
|
||||
GpuTri { v0: t.v[0], mat: pack_mat(color, m.kind), e1: sub(t.v[1], t.v[0]), rough: m.rough, e2: sub(t.v[2], t.v[0]), metal: m.metal },
|
||||
GpuTriTex { uv0: t.uv[0], uv1: t.uv[1], uv2: t.uv[2], tex: (tx.layer & 0xFFFF) | ((tx.proc & 0xFF) << 16) | ((tx.detail as u32) << 24), scale: tx.scale },
|
||||
)
|
||||
}
|
||||
|
||||
impl Bvh {
|
||||
pub fn tri_count(&self) -> usize {
|
||||
self.tris.len()
|
||||
@@ -221,22 +262,10 @@ impl Bvh {
|
||||
/// Baut den Baum (Binned-SAH). Ungültige Dreiecke fallen weg (s. Moduldoc); leer → leerer Baum. Material je
|
||||
/// Dreieck aus `table` (Ebene) und Vertexfarbe aufgelöst.
|
||||
pub fn build_with(input: &[PtTri], table: &PtMaterialTable) -> Bvh {
|
||||
let mut seen: HashSet<[[i64; 3]; 3]> = HashSet::with_capacity(input.len());
|
||||
let mut tris: Vec<PtTri> = Vec::with_capacity(input.len());
|
||||
for t in input {
|
||||
if !t.v.iter().flatten().all(|c| c.is_finite() && c.abs() < 1e7) {
|
||||
continue;
|
||||
}
|
||||
let n = cross(sub(t.v[1], t.v[0]), sub(t.v[2], t.v[0]));
|
||||
if !(dot(n, n) > 1e-18) {
|
||||
continue;
|
||||
}
|
||||
if seen.insert(tri_key(&t.v)) {
|
||||
tris.push(*t);
|
||||
}
|
||||
}
|
||||
let keep = kept_inputs(input);
|
||||
let tris: Vec<PtTri> = input.iter().zip(&keep).filter(|(_, k)| **k).map(|(t, _)| *t).collect();
|
||||
if tris.is_empty() {
|
||||
return Bvh::default();
|
||||
return Bvh { slots: vec![NO_SLOT; input.len()], ..Bvh::default() };
|
||||
}
|
||||
let bounds: Vec<Aabb> = tris
|
||||
.iter()
|
||||
@@ -360,13 +389,88 @@ impl Bvh {
|
||||
let mut gpu_tris = Vec::with_capacity(order.len());
|
||||
let mut gpu_tex = Vec::with_capacity(order.len());
|
||||
for &i in &order {
|
||||
let t = &tris[i as usize];
|
||||
let (m, color) = table.resolve(t.layer, t.color);
|
||||
let tx = table.tex_for(t.layer, &m);
|
||||
gpu_tris.push(GpuTri { v0: t.v[0], mat: pack_mat(color, m.kind), e1: sub(t.v[1], t.v[0]), rough: m.rough, e2: sub(t.v[2], t.v[0]), metal: m.metal });
|
||||
gpu_tex.push(GpuTriTex { uv0: t.uv[0], uv1: t.uv[1], uv2: t.uv[2], tex: (tx.layer & 0xFFFF) | ((tx.proc & 0xFF) << 16) | ((tx.detail as u32) << 24), scale: tx.scale });
|
||||
let (g, x) = gpu_tri(&tris[i as usize], table);
|
||||
gpu_tris.push(g);
|
||||
gpu_tex.push(x);
|
||||
}
|
||||
Bvh { nodes, tris: gpu_tris, tex: gpu_tex }
|
||||
// Platz je Eingabe: k-tes behaltene Dreieck liegt an der Stelle, an der `order` es nennt.
|
||||
let mut slot_of_kept = vec![0u32; tris.len()];
|
||||
for (slot, &k) in order.iter().enumerate() {
|
||||
slot_of_kept[k as usize] = slot as u32;
|
||||
}
|
||||
let mut slots = Vec::with_capacity(input.len());
|
||||
let mut k = 0usize;
|
||||
for &kept in &keep {
|
||||
if kept {
|
||||
slots.push(slot_of_kept[k]);
|
||||
k += 1;
|
||||
} else {
|
||||
slots.push(NO_SLOT);
|
||||
}
|
||||
}
|
||||
let mut bvh = Bvh { nodes, tris: gpu_tris, tex: gpu_tex, lights: Default::default(), slots, sah_built: 0.0 };
|
||||
bvh.sah_built = bvh.sah_cost();
|
||||
bvh.lights = crate::pt_lights::build_lights(&mut bvh);
|
||||
bvh
|
||||
}
|
||||
|
||||
/// [212] Etappe 5, Teil-Update: dieselben Eingabe-Dreiecke an neuer Lage (gleiche Zahl, gleiche verworfene — z. B. ein
|
||||
/// verschobenes Objekt) bekommen die alte Baumstruktur mit neu gerechneten Hüllen (Refit, von den Blättern zur
|
||||
/// Wurzel), Material und UV neu aufgelöst, Lichtliste neu. `false` (Baum unverändert) = Neubau nötig: andere Topologie
|
||||
/// oder der Baum wäre um mehr als `REFIT_MAX_COST` teurer als frisch gebaut.
|
||||
pub fn refit(&mut self, input: &[PtTri], table: &PtMaterialTable) -> bool {
|
||||
if input.len() != self.slots.len() || self.tris.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let keep = kept_inputs(input);
|
||||
if keep.iter().zip(&self.slots).any(|(k, s)| *k != (*s != NO_SLOT)) {
|
||||
return false;
|
||||
}
|
||||
let (old_nodes, old_tris, old_tex) = (self.nodes.clone(), self.tris.clone(), self.tex.clone());
|
||||
for (t, &s) in input.iter().zip(&self.slots) {
|
||||
if s != NO_SLOT {
|
||||
let (g, x) = gpu_tri(t, table);
|
||||
self.tris[s as usize] = g;
|
||||
self.tex[s as usize] = x;
|
||||
}
|
||||
}
|
||||
// Kinder liegen immer hinter dem Elternknoten (Bau-Reihenfolge): rückwärts sind sie fertig, bevor er dran ist.
|
||||
for ni in (0..self.nodes.len()).rev() {
|
||||
let n = self.nodes[ni];
|
||||
let mut b = Aabb::EMPTY;
|
||||
if n.count > 0 {
|
||||
for t in &self.tris[n.left_first as usize..(n.left_first + n.count) as usize] {
|
||||
b.grow_p(t.v0);
|
||||
b.grow_p([t.v0[0] + t.e1[0], t.v0[1] + t.e1[1], t.v0[2] + t.e1[2]]);
|
||||
b.grow_p([t.v0[0] + t.e2[0], t.v0[1] + t.e2[1], t.v0[2] + t.e2[2]]);
|
||||
}
|
||||
} else {
|
||||
for c in [n.left_first as usize, n.left_first as usize + 1] {
|
||||
b.grow(&Aabb { min: self.nodes[c].min, max: self.nodes[c].max });
|
||||
}
|
||||
}
|
||||
self.nodes[ni].min = b.min;
|
||||
self.nodes[ni].max = b.max;
|
||||
}
|
||||
if self.sah_cost() > self.sah_built * REFIT_MAX_COST {
|
||||
self.nodes = old_nodes;
|
||||
self.tris = old_tris;
|
||||
self.tex = old_tex;
|
||||
return false;
|
||||
}
|
||||
self.lights = crate::pt_lights::build_lights(self);
|
||||
true
|
||||
}
|
||||
|
||||
/// SAH-Kosten des Baums relativ zur Wurzel (Knoten 1, Dreieckstest 1): Σ Fläche(Knoten)/Fläche(Wurzel) · (innen:
|
||||
/// `TRAVERSAL_COST`, Blatt: Zahl der Dreiecke). Mass der Baumgüte (Refit-Grenze, Tests).
|
||||
pub fn sah_cost(&self) -> f32 {
|
||||
let Some(root) = self.nodes.first() else { return 0.0 };
|
||||
let ra = Aabb { min: root.min, max: root.max }.area().max(1e-12);
|
||||
self.nodes
|
||||
.iter()
|
||||
.map(|n| Aabb { min: n.min, max: n.max }.area() / ra * if n.count > 0 { n.count as f32 } else { TRAVERSAL_COST })
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Strahl gegen ein Dreieck (Möller–Trumbore); `t` im offenen Intervall (`tmin`, `tmax`).
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
// [212] Etappe 5: Belichtungsautomatik des Pathtracers für den Wechsel Aussen ↔ Innen. GPU-frei: Referenz auf der CPU
|
||||
// (Tests) und die WGSL-Quelle des Compute-Passes, den `gpu_pathtrace.rs` vor jeder Anzeige rechnet.
|
||||
//
|
||||
// Messung: 64 × 64 gleichmässig verteilte Pixel des Mittelbildes (Akkumulation / Zahl), Luminanz in ein Histogramm von
|
||||
// 64 Fächern über log2 ∈ [−14, 6]; gemittelt wird log2 zwischen dem 40. und 95. Perzentil (die dunkelsten Ecken und die
|
||||
// hellsten Spitzen — Sonnenflecken, Himmel im Fenster — bestimmen die Belichtung nicht allein, wie das Histogramm-
|
||||
// Verfahren gängiger Engines). Ziel: `KEY / 2^Mittel`, begrenzt auf [¼, 32] (Nacht [¼, 4]) × Belichtung des Himmels.
|
||||
// Nachgeführt wird im log-Raum: neu = 2^mix(log2 alt, log2 Ziel, Rate) je Bild (Viewport sanft, Export/headless sofort).
|
||||
// Der Belichtungsregler (EV) multipliziert danach.
|
||||
|
||||
/// Fächer des Histogramms, Bereich in log2(Luminanz).
|
||||
pub const HIST_BINS: usize = 64;
|
||||
pub const LOG_MIN: f32 = -14.0;
|
||||
pub const LOG_MAX: f32 = 6.0;
|
||||
/// Messraster (GRID × GRID Pixel).
|
||||
pub const GRID: u32 = 64;
|
||||
/// Perzentile des gemittelten Bereichs.
|
||||
pub const PCT_LO: f32 = 0.4;
|
||||
pub const PCT_HI: f32 = 0.95;
|
||||
/// Ziel-Helligkeit: so gewählt, dass die Aussenansicht des Musterhauses am Tag etwa die feste Belichtung
|
||||
/// (`pathtrace::DEFAULT_EXPOSURE`) bekommt.
|
||||
pub const KEY: f32 = 0.12;
|
||||
|
||||
/// Fach einer Luminanz (≤ 0 und NaN ins unterste).
|
||||
pub fn bin_of(lum: f32) -> usize {
|
||||
if !(lum > 0.0) {
|
||||
return 0;
|
||||
}
|
||||
let x = (lum.log2() - LOG_MIN) / (LOG_MAX - LOG_MIN) * HIST_BINS as f32;
|
||||
(x.floor().max(0.0) as usize).min(HIST_BINS - 1)
|
||||
}
|
||||
|
||||
/// log2 der Fach-Mitte.
|
||||
pub fn bin_center(b: usize) -> f32 {
|
||||
LOG_MIN + (b as f32 + 0.5) * (LOG_MAX - LOG_MIN) / HIST_BINS as f32
|
||||
}
|
||||
|
||||
/// Index des Messpixels Nr. s (0 ≤ s < GRID²) im Bild w × h (wie der Shader).
|
||||
pub fn grid_pixel(s: u32, w: u32, h: u32) -> usize {
|
||||
let (w, h) = (w.max(1), h.max(1));
|
||||
let (gx, gy) = (s % GRID, s / GRID);
|
||||
let x = (((gx as f32 + 0.5) * w as f32 / GRID as f32) as u32).min(w - 1);
|
||||
let y = (((gy as f32 + 0.5) * h as f32 / GRID as f32) as u32).min(h - 1);
|
||||
(y * w + x) as usize
|
||||
}
|
||||
|
||||
/// Mittel von log2 zwischen den Perzentilen `PCT_LO`…`PCT_HI` (Fach-Mitten).
|
||||
pub fn mean_log2(hist: &[u32; HIST_BINS]) -> f32 {
|
||||
let total: f32 = hist.iter().map(|&n| n as f32).sum();
|
||||
let (lo, hi) = (PCT_LO * total, PCT_HI * total);
|
||||
let (mut acc, mut sum, mut cnt) = (0.0f32, 0.0f32, 0.0f32);
|
||||
for (b, &n) in hist.iter().enumerate() {
|
||||
let (a0, a1) = (acc, acc + n as f32);
|
||||
let take = (a1.min(hi) - a0.max(lo)).max(0.0);
|
||||
sum += take * bin_center(b);
|
||||
cnt += take;
|
||||
acc = a1;
|
||||
}
|
||||
sum / cnt.max(1.0)
|
||||
}
|
||||
|
||||
/// Ziel-Belichtung zum gemittelten log2, begrenzt auf [lo, hi].
|
||||
pub fn target(mean_log2: f32, lo: f32, hi: f32) -> f32 {
|
||||
(KEY * (-mean_log2).exp2()).clamp(lo.min(hi), hi.max(lo))
|
||||
}
|
||||
|
||||
/// Nachführung im log-Raum (Rate 0…1; ohne gültigen Vorwert sofort das Ziel).
|
||||
pub fn adapt(prev: Option<f32>, target: f32, rate: f32) -> f32 {
|
||||
match prev.filter(|p| p.is_finite() && *p > 0.0) {
|
||||
Some(p) if rate < 1.0 => (p.log2() + (target.log2() - p.log2()) * rate.clamp(0.0, 1.0)).exp2(),
|
||||
_ => target,
|
||||
}
|
||||
}
|
||||
|
||||
/// Referenz der Messung über die Akkumulation (`[rgb Summe, Zahl]` je Pixel): (Ziel, Mittel log2).
|
||||
pub fn measure(accum: &[[f32; 4]], w: u32, h: u32, lo: f32, hi: f32) -> (f32, f32) {
|
||||
let mut hist = [0u32; HIST_BINS];
|
||||
for s in 0..GRID * GRID {
|
||||
let a = accum.get(grid_pixel(s, w, h)).copied().unwrap_or([0.0; 4]);
|
||||
let n = a[3].max(1.0);
|
||||
let lum = (0.2126 * a[0] + 0.7152 * a[1] + 0.0722 * a[2]) / n;
|
||||
hist[bin_of(lum)] += 1;
|
||||
}
|
||||
let m = mean_log2(&hist);
|
||||
(target(m, lo, hi), m)
|
||||
}
|
||||
|
||||
/// Compute-Pass der Automatik: eine Arbeitsgruppe, Histogramm im gemeinsamen Speicher, Ergebnis in `expo[0]`
|
||||
/// (x = Belichtung, y = 1 gültig, z = Ziel, w = Mittel log2). Parameter wie der Pfad (`P.expo`: y = Rate, z/w = Grenzen).
|
||||
pub const EXPOSE_WGSL: &str = concat!(
|
||||
crate::pathtrace::wgsl_params!(),
|
||||
r#"
|
||||
@group(0) @binding(0) var<uniform> P: Params;
|
||||
@group(0) @binding(1) var<storage, read> accum: array<vec4<f32>>;
|
||||
@group(0) @binding(2) var<storage, read_write> expo: array<vec4<f32>>;
|
||||
|
||||
const BINS: u32 = 64u;
|
||||
const LOG_MIN: f32 = -14.0;
|
||||
const LOG_MAX: f32 = 6.0;
|
||||
const GRID: u32 = 64u;
|
||||
const PCT_LO: f32 = 0.4;
|
||||
const PCT_HI: f32 = 0.95;
|
||||
const KEY: f32 = 0.12;
|
||||
|
||||
var<workgroup> hist: array<atomic<u32>, 64>;
|
||||
|
||||
fn bin_of(lum: f32) -> u32 {
|
||||
if (!(lum > 0.0)) { return 0u; }
|
||||
let x = (log2(lum) - LOG_MIN) / (LOG_MAX - LOG_MIN) * f32(BINS);
|
||||
return min(u32(max(floor(x), 0.0)), BINS - 1u);
|
||||
}
|
||||
|
||||
@compute @workgroup_size(256, 1, 1)
|
||||
fn expose(@builtin(local_invocation_index) li: u32) {
|
||||
if (li < BINS) { atomicStore(&hist[li], 0u); }
|
||||
workgroupBarrier();
|
||||
let w = max(P.dims.x, 1u);
|
||||
let h = max(P.dims.y, 1u);
|
||||
for (var k = 0u; k < GRID * GRID / 256u; k = k + 1u) {
|
||||
let s = li + k * 256u;
|
||||
let x = min(u32((f32(s % GRID) + 0.5) * f32(w) / f32(GRID)), w - 1u);
|
||||
let y = min(u32((f32(s / GRID) + 0.5) * f32(h) / f32(GRID)), h - 1u);
|
||||
let a = accum[y * w + x];
|
||||
let lum = dot(a.rgb, vec3<f32>(0.2126, 0.7152, 0.0722)) / max(a.w, 1.0);
|
||||
atomicAdd(&hist[bin_of(lum)], 1u);
|
||||
}
|
||||
workgroupBarrier();
|
||||
if (li == 0u) {
|
||||
let total = f32(GRID * GRID);
|
||||
let lo = PCT_LO * total;
|
||||
let hi = PCT_HI * total;
|
||||
var acc = 0.0;
|
||||
var sum = 0.0;
|
||||
var cnt = 0.0;
|
||||
for (var b = 0u; b < BINS; b = b + 1u) {
|
||||
let n = f32(atomicLoad(&hist[b]));
|
||||
let a1 = acc + n;
|
||||
let take = max(min(a1, hi) - max(acc, lo), 0.0);
|
||||
sum = sum + take * (LOG_MIN + (f32(b) + 0.5) * (LOG_MAX - LOG_MIN) / f32(BINS));
|
||||
cnt = cnt + take;
|
||||
acc = a1;
|
||||
}
|
||||
let m = sum / max(cnt, 1.0);
|
||||
let tgt = clamp(KEY * exp2(-m), min(P.expo.z, P.expo.w), max(P.expo.z, P.expo.w));
|
||||
let prev = expo[0];
|
||||
var e = tgt;
|
||||
if (prev.y > 0.5 && prev.x > 0.0 && P.expo.y < 1.0) {
|
||||
e = exp2(mix(log2(prev.x), log2(tgt), clamp(P.expo.y, 0.0, 1.0)));
|
||||
}
|
||||
expo[0] = vec4<f32>(e, 1.0, tgt, m);
|
||||
}
|
||||
}
|
||||
"#
|
||||
);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn wgsl_valide_und_metal() {
|
||||
let module = naga::front::wgsl::parse_str(EXPOSE_WGSL).unwrap_or_else(|e| panic!("{}", e.emit_to_string(EXPOSE_WGSL)));
|
||||
use naga::valid::{Capabilities, ValidationFlags, Validator};
|
||||
let info = Validator::new(ValidationFlags::all(), Capabilities::empty()).validate(&module).expect("valide");
|
||||
let opts = naga::back::msl::Options { lang_version: (2, 1), ..Default::default() };
|
||||
naga::back::msl::write_string(&module, &info, &opts, &naga::back::msl::PipelineOptions::default()).expect("MSL");
|
||||
assert!(EXPOSE_WGSL.contains(&format!("const KEY: f32 = {KEY:?};")), "KEY gleich in Rust und WGSL");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn faecher_und_perzentile() {
|
||||
assert_eq!(bin_of(0.0), 0);
|
||||
assert_eq!(bin_of(f32::NAN), 0);
|
||||
assert_eq!(bin_of(1e9), HIST_BINS - 1);
|
||||
let b = bin_of(1.0);
|
||||
assert!(bin_center(b) <= 0.2 && bin_center(b) >= -0.2, "{}", bin_center(b));
|
||||
// Alles gleich hell: Mittel = dieses Fach.
|
||||
let mut h = [0u32; HIST_BINS];
|
||||
h[b] = 100;
|
||||
assert!((mean_log2(&h) - bin_center(b)).abs() < 1e-6);
|
||||
// Wenige sehr helle Pixel (Sonnenflecken, ≤ 5 %) verschieben die Messung nicht.
|
||||
h[HIST_BINS - 1] = 5;
|
||||
assert!((mean_log2(&h) - bin_center(b)).abs() < 1e-6);
|
||||
// Leer: kein NaN.
|
||||
assert!(mean_log2(&[0; HIST_BINS]).is_finite());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn innen_heller_als_aussen_und_sanft() {
|
||||
let (w, h) = (80u32, 50u32);
|
||||
let img = |l: f32| vec![[l, l, l, 1.0]; (w * h) as usize];
|
||||
let (out, _) = measure(&img(0.4), w, h, 0.2, 27.0);
|
||||
let (inn, _) = measure(&img(0.01), w, h, 0.2, 27.0);
|
||||
assert!(inn > out * 20.0, "{inn} vs {out}");
|
||||
// Grenzen halten.
|
||||
assert_eq!(measure(&img(1e-6), w, h, 0.2, 27.0).0, 27.0);
|
||||
assert_eq!(measure(&img(100.0), w, h, 0.2, 27.0).0, 0.2);
|
||||
// Mittelbild = Summe / Zahl: 4 Samples mit Summe 1.6 wie 1 Sample mit 0.4.
|
||||
let four = vec![[1.6, 1.6, 1.6, 4.0]; (w * h) as usize];
|
||||
assert_eq!(measure(&four, w, h, 0.2, 27.0), measure(&img(0.4), w, h, 0.2, 27.0));
|
||||
// Nachführung: monoton, im log-Raum, ohne Vorwert sofort.
|
||||
assert_eq!(adapt(None, 8.0, 0.15), 8.0);
|
||||
assert_eq!(adapt(Some(1.0), 8.0, 1.0), 8.0);
|
||||
let mut e = 1.0;
|
||||
for _ in 0..40 {
|
||||
let n = adapt(Some(e), 8.0, AUTO_RATE_TEST);
|
||||
assert!(n > e && n <= 8.0);
|
||||
e = n;
|
||||
}
|
||||
assert!((e - 8.0).abs() < 0.05, "{e}");
|
||||
assert!((adapt(Some(1.0), 4.0, 0.5) - 2.0).abs() < 1e-6, "halber Weg im log-Raum");
|
||||
// Kaputter Puffer / leeres Bild: endlich.
|
||||
assert!(measure(&[], 0, 0, 0.2, 27.0).0.is_finite());
|
||||
}
|
||||
|
||||
const AUTO_RATE_TEST: f32 = crate::pathtrace::AUTO_EXPOSURE_RATE;
|
||||
}
|
||||
@@ -616,6 +616,30 @@ pub struct Renderer {
|
||||
pt_max_pixels: u64,
|
||||
/// [212] Etappe 4: Detail-Ebenen (Normale/Rauigkeit) parallel zum Material-Array; None = keine (Platzhalter).
|
||||
pt_detail: Option<wgpu::Texture>,
|
||||
/// [212] Etappe 5, Teil-Update: Dreiecke je Klumpen (nur geänderte Klumpen neu gelesen), der zuletzt gebaute Baum
|
||||
/// (Refit statt Neubau bei gleicher Topologie, `Bvh::refit`), Stand des letzten Aufbaus.
|
||||
pt_chunk_tris: Vec<Option<Vec<crate::bvh::PtTri>>>,
|
||||
pt_bvh: crate::bvh::Bvh,
|
||||
pt_build: PtBuildStats,
|
||||
/// Nur die Bildkarten neu binden (kein Baum).
|
||||
pt_tex_dirty: bool,
|
||||
/// Etappe 5: Portale, Raumlicht, Belichtung (EV, Automatik), Abpraller, Messschalter; Zeitstempel.
|
||||
pt_options: crate::pathtrace::PtOptions,
|
||||
pt_auto_exposure: bool,
|
||||
pt_timing: bool,
|
||||
}
|
||||
|
||||
/// [212] Etappe 5: Stand des letzten Baum-Aufbaus des Pathtracers (Messung, `render_png --timing`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct PtBuildStats {
|
||||
/// Dreiecke im Baum.
|
||||
pub tris: u32,
|
||||
/// Neu gelesene Klumpen.
|
||||
pub chunks_read: u32,
|
||||
/// Refit statt Neubau.
|
||||
pub refit: bool,
|
||||
/// Zeit (ms) für Lesen + Baum + Lichtliste (0 im Browser: keine Uhr in WASM).
|
||||
pub ms: f64,
|
||||
}
|
||||
|
||||
/// [180]/[214] GPU-Puffer eines Klumpens der Geisterschicht (Formate wie `set_ghost`).
|
||||
@@ -1529,6 +1553,13 @@ impl Renderer {
|
||||
pt_night: false,
|
||||
pt_max_pixels: crate::pathtrace::MAX_PIXELS,
|
||||
pt_detail: None,
|
||||
pt_chunk_tris: Vec::new(),
|
||||
pt_bvh: crate::bvh::Bvh::default(),
|
||||
pt_build: PtBuildStats::default(),
|
||||
pt_tex_dirty: true,
|
||||
pt_options: crate::pathtrace::PtOptions::default(),
|
||||
pt_auto_exposure: true,
|
||||
pt_timing: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1620,6 +1651,16 @@ impl Renderer {
|
||||
let ch = self.scene.apply(upd);
|
||||
self.shadow_dirty = true;
|
||||
self.pt_dirty = true;
|
||||
// [212] Etappe 5: nur geänderte Klumpen neu lesen.
|
||||
if ch.reset {
|
||||
self.pt_chunk_tris.clear();
|
||||
}
|
||||
self.pt_chunk_tris.resize_with(self.scene.chunk_count(), || None);
|
||||
for &c in &ch.dirty_chunks {
|
||||
if let Some(slot) = self.pt_chunk_tris.get_mut(c) {
|
||||
*slot = None;
|
||||
}
|
||||
}
|
||||
// Silhouette-Cache verwerfen (neues Modell) — wird bei Bedarf neu gebaut.
|
||||
self.silhouette = None;
|
||||
self.silhouette_key = None;
|
||||
@@ -2150,6 +2191,7 @@ impl Renderer {
|
||||
// Textur-Bindung neu (`render_pathtrace`).
|
||||
self.pt_materials.set_texture_means(rgba, bytes_per_layer, material_layers as usize);
|
||||
self.pt_dirty = true;
|
||||
self.pt_tex_dirty = true;
|
||||
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor {
|
||||
dimension: Some(wgpu::TextureViewDimension::D2Array),
|
||||
@@ -2745,12 +2787,38 @@ impl Renderer {
|
||||
let pt = self.pathtracer.get_or_insert_with(|| crate::gpu_pathtrace::PathTracer::new(device, self.color_format));
|
||||
pt.max_samples = self.pt_max_samples;
|
||||
if self.pt_dirty {
|
||||
let mut tris = Vec::new();
|
||||
for c in 0..self.scene.chunk_count() {
|
||||
let d = self.scene.chunk_data(c);
|
||||
crate::bvh::tris_from_mesh(&d.mesh.verts, &d.mesh.indices, &d.layers, &mut tris);
|
||||
// [212] Etappe 5, Teil-Update: nur Klumpen ohne Zwischenstand neu lesen; gleiche Topologie (Zahl und Lage der
|
||||
// Dreiecke je Eingabe gleich, etwa ein verschobenes Objekt oder neue Materialien) = Refit des alten Baums,
|
||||
// sonst Neubau.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let t0 = std::time::Instant::now();
|
||||
let n = self.scene.chunk_count();
|
||||
self.pt_chunk_tris.resize_with(n, || None);
|
||||
let mut read = 0u32;
|
||||
for c in 0..n {
|
||||
if self.pt_chunk_tris[c].is_none() {
|
||||
let d = self.scene.chunk_data(c);
|
||||
let mut tris = Vec::new();
|
||||
crate::bvh::tris_from_mesh(&d.mesh.verts, &d.mesh.indices, &d.layers, &mut tris);
|
||||
self.pt_chunk_tris[c] = Some(tris);
|
||||
read += 1;
|
||||
}
|
||||
}
|
||||
pt.set_bvh(device, &crate::bvh::Bvh::build_with(&tris, &self.pt_materials));
|
||||
let tris: Vec<crate::bvh::PtTri> = self.pt_chunk_tris.iter().flatten().flatten().copied().collect();
|
||||
let refit = self.pt_bvh.refit(&tris, &self.pt_materials);
|
||||
if !refit {
|
||||
self.pt_bvh = crate::bvh::Bvh::build_with(&tris, &self.pt_materials);
|
||||
}
|
||||
pt.set_bvh(device, queue, &self.pt_bvh);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let ms = t0.elapsed().as_secs_f64() * 1e3;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let ms = 0.0;
|
||||
self.pt_build = PtBuildStats { tris: self.pt_bvh.tri_count() as u32, chunks_read: read, refit, ms };
|
||||
self.pt_dirty = false;
|
||||
self.pt_tex_dirty = true;
|
||||
}
|
||||
if self.pt_tex_dirty {
|
||||
// [212] Etappe 3: dasselbe Textur-Array wie der Stil „textured“ (Ebene = Material-Ebene).
|
||||
let view = self.texture.create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() });
|
||||
// Etappe 4: Detail-Ebenen; ohne Karten ein leerer Platzhalter (der Shader liest ihn nicht, `GpuTriTex` Bit 24).
|
||||
@@ -2763,17 +2831,76 @@ impl Renderer {
|
||||
}
|
||||
};
|
||||
let dview = detail.create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() });
|
||||
pt.set_textures(device, &view, &dview, &self.texture_sampler, &self.pt_materials.inv_means());
|
||||
self.pt_dirty = false;
|
||||
pt.set_textures(device, queue, &view, &dview, &self.texture_sampler, &self.pt_materials.inv_means());
|
||||
self.pt_tex_dirty = false;
|
||||
}
|
||||
pt.denoise = self.pt_denoise;
|
||||
pt.max_pixels = self.pt_max_pixels;
|
||||
pt.options = self.pt_options;
|
||||
pt.auto_exposure = self.pt_auto_exposure;
|
||||
pt.set_timing(device, queue, self.pt_timing);
|
||||
let night = self.pt_night && self.sun.is_none();
|
||||
let sun = self.sun.or(Some([self.base_light[0], self.base_light[1], self.base_light[2]]));
|
||||
pt.render(device, queue, target, camera, sun, night, viewport, self.pt_batch);
|
||||
self.frame_stats = FrameStats::default();
|
||||
}
|
||||
|
||||
/// [212] Etappe 5: Belichtungskorrektur in Blenden (EV, −10…10) und Belichtungsautomatik (Standard an). Wirkt nur
|
||||
/// auf die Anzeige; die Summe läuft weiter.
|
||||
pub fn set_pathtrace_exposure(&mut self, ev: f32, auto: bool) {
|
||||
self.pt_options.ev = if ev.is_finite() { ev.clamp(-10.0, 10.0) } else { 0.0 };
|
||||
self.pt_auto_exposure = auto;
|
||||
}
|
||||
|
||||
/// [212] Etappe 5: Raumlicht bei Nacht an den Deckenuntersichten (Standard an; nur ohne Leuchten im Modell).
|
||||
pub fn set_pathtrace_room_light(&mut self, on: bool) {
|
||||
self.pt_options.room_light = on;
|
||||
}
|
||||
|
||||
/// [212] Etappe 5: Fenster als Lichtportale des Himmels (Standard an; aus = wie Etappe 4, für Vergleiche).
|
||||
pub fn set_pathtrace_portals(&mut self, on: bool) {
|
||||
self.pt_options.portals = on;
|
||||
}
|
||||
|
||||
/// [212] Etappe 5, Messung: Abpraller je Pfad (1…16, 0 = Standard) und Bildkarten aus.
|
||||
pub fn set_pathtrace_debug(&mut self, bounces: u32, no_tex: bool) {
|
||||
self.pt_options.bounces = if bounces == 0 { crate::pathtrace::MAX_BOUNCES } else { bounces.min(16) };
|
||||
self.pt_options.no_tex = no_tex;
|
||||
}
|
||||
|
||||
/// [212] Etappe 5, Messung: Zeitstempel je Abschnitt (nur mit `TIMESTAMP_QUERY`; headless).
|
||||
pub fn set_pathtrace_timing(&mut self, on: bool) {
|
||||
self.pt_timing = on;
|
||||
}
|
||||
|
||||
/// [212] Zeitstempel des letzten Bildes (wartet auf die GPU).
|
||||
pub fn pathtrace_timings(&self, device: &wgpu::Device) -> Option<crate::gpu_pathtrace::PtTimings> {
|
||||
self.pathtracer.as_ref()?.read_timings(device)
|
||||
}
|
||||
|
||||
/// [212] Belichtung der Automatik (aktuell, gültig, Ziel, Mittel log2; wartet auf die GPU).
|
||||
pub fn pathtrace_exposure(&self, device: &wgpu::Device, queue: &wgpu::Queue) -> Option<[f32; 4]> {
|
||||
Some(self.pathtracer.as_ref()?.read_exposure(device, queue))
|
||||
}
|
||||
|
||||
/// [212] Etappe 5: Szene zu gross für die Puffergrenzen des Geräts (der Pathtracer zeigt nur den Himmel; der
|
||||
/// Viewport meldet es statt abzustürzen).
|
||||
pub fn pathtrace_scene_too_big(&self) -> bool {
|
||||
self.pathtracer.as_ref().is_some_and(|p| p.scene_too_big())
|
||||
}
|
||||
|
||||
/// Test: Puffergrenze des Pathtracers künstlich verkleinern (legt ihn bei Bedarf an).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn pathtrace_limit_for_test(&mut self, device: &wgpu::Device, bytes: u64) {
|
||||
let pt = self.pathtracer.get_or_insert_with(|| crate::gpu_pathtrace::PathTracer::new(device, self.color_format));
|
||||
pt.limit_for_test(bytes);
|
||||
}
|
||||
|
||||
/// [212] Stand des letzten Baum-Aufbaus und Zahl der Lichter je Art (Portale, Leuchten, Raumlicht).
|
||||
pub fn pathtrace_build(&self) -> (PtBuildStats, [u32; 3]) {
|
||||
(self.pt_build, self.pathtracer.as_ref().map_or([0; 3], |p| p.light_counts()))
|
||||
}
|
||||
|
||||
/// [212] Samples je `render` im Stil `Pathtrace` (Standard 1; headless mehr auf einmal). 0 → 1.
|
||||
pub fn set_pathtrace_batch(&mut self, n: u32) {
|
||||
self.pt_batch = n.clamp(1, 1 << 16);
|
||||
@@ -2804,6 +2931,7 @@ impl Renderer {
|
||||
(0..layer_count.min(4096) as usize).map(|i| crate::pt_texture::pack_detail(layer(normal, i).as_deref(), layer(rough, i).as_deref(), px)).collect();
|
||||
self.pt_materials.set_detail(&layers);
|
||||
self.pt_dirty = true;
|
||||
self.pt_tex_dirty = true;
|
||||
if !layers.iter().any(|d| d.present) {
|
||||
self.pt_detail = None;
|
||||
return;
|
||||
@@ -3109,6 +3237,7 @@ mod shadow_gpu_tests {
|
||||
r.render(&device, &queue, &view, &cam, (32, 24));
|
||||
assert_eq!(r.pathtrace_samples(), 2);
|
||||
r.set_pathtrace_denoise(false);
|
||||
r.set_pathtrace_exposure(0.0, false);
|
||||
r.render(&device, &queue, &view, &cam, (32, 24));
|
||||
assert_eq!(r.pathtrace_samples(), 4, "Schalter beginnt nicht von vorn");
|
||||
// Nacht nur ohne Sonne: Sonne unter dem Horizont = Nachthimmel, Summe von vorn.
|
||||
@@ -3192,6 +3321,7 @@ mod shadow_gpu_tests {
|
||||
let mut r = Renderer::new(&device, format);
|
||||
r.set_render_style(RenderStyle::Pathtrace);
|
||||
r.set_pathtrace_denoise(false);
|
||||
r.set_pathtrace_exposure(0.0, false);
|
||||
r.set_sun(crate::shadow::sun_dir_world(180.0, 70.0), true);
|
||||
r.upload_model(&device, &[], &[], &[plate(MeshKind::Imported, Some(1))]);
|
||||
r.set_pathtrace_batch(6);
|
||||
@@ -3255,6 +3385,7 @@ mod shadow_gpu_tests {
|
||||
let mut r = Renderer::new(&device, format);
|
||||
r.set_render_style(RenderStyle::Pathtrace);
|
||||
r.set_pathtrace_denoise(false);
|
||||
r.set_pathtrace_exposure(0.0, false);
|
||||
let sun = crate::shadow::sun_dir_world(180.0, 35.0).unwrap();
|
||||
r.set_sun(Some(sun), true);
|
||||
r.upload_model(&device, &[], &[], &[plate]);
|
||||
|
||||
@@ -17,12 +17,19 @@
|
||||
//
|
||||
// Etappe 4: zweites Textur-Array mit den Detail-Ebenen (Normale/Rauigkeit, `pt_texture.rs`) in derselben Gruppe
|
||||
// (binding 3); beide Arrays mit Mip-Stufen, der Shader wählt die Stufe nach Strahlkegel.
|
||||
//
|
||||
// Etappe 5: Lichtliste (`pt_lights.rs`, binding 7: Portale, Leuchten, Raumlicht) mit dem Baum hochgeladen;
|
||||
// Belichtungsautomatik (`exposure.rs`) als kleiner Compute-Pass vor der Anzeige, Ergebnis in einem 16-Byte-Puffer, den
|
||||
// die Anzeige liest (Viewport sanft nachgeführt, Stapel > 1 sofort); Zeitstempel je Abschnitt (Samples, Entrauscher,
|
||||
// Belichtung + Anzeige), wenn das Gerät `TIMESTAMP_QUERY` kann und `timing` an ist (Messung, `render_png --timing`).
|
||||
|
||||
#[cfg(test)]
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
use crate::bvh::{Bvh, GpuNode, GpuTri, GpuTriTex};
|
||||
use crate::denoise::{blend_weight, DN_WGSL, ITERATIONS, SIGMA_L, SIGMA_N, SIGMA_Z};
|
||||
use crate::pathtrace::{build_params, internal_size, night_sky, sky_for_sun, PtParams, MAX_PIXELS, PT_DISPLAY_WGSL, PT_WGSL};
|
||||
use crate::exposure::EXPOSE_WGSL;
|
||||
use crate::pathtrace::{build_params_with, internal_size, night_sky, sky_for_sun, PtOptions, PtParams, AUTO_EXPOSURE_RATE, MAX_PIXELS, PT_DISPLAY_WGSL, PT_WGSL};
|
||||
use crate::types::{Camera, Projection};
|
||||
|
||||
/// Standard-Obergrenze der Samples je Pixel (danach steht das Bild).
|
||||
@@ -44,6 +51,24 @@ struct Frame {
|
||||
filt: [wgpu::Buffer; 2],
|
||||
}
|
||||
|
||||
/// Zeitstempel der Abschnitte eines `render` (GPU, ms): Samples, Entrauscher, Belichtung + Anzeige.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct PtTimings {
|
||||
pub samples_ms: f64,
|
||||
pub denoise_ms: f64,
|
||||
pub display_ms: f64,
|
||||
}
|
||||
|
||||
struct Timing {
|
||||
set: wgpu::QuerySet,
|
||||
resolve: wgpu::Buffer,
|
||||
read: wgpu::Buffer,
|
||||
period_ns: f32,
|
||||
}
|
||||
|
||||
/// Zeitstempel-Plätze: Samples (Anfang, Ende), Entrauscher, Belichtung + Anzeige.
|
||||
const TS_COUNT: u32 = 6;
|
||||
|
||||
pub struct PathTracer {
|
||||
compute: wgpu::ComputePipeline,
|
||||
compute_layout: wgpu::BindGroupLayout,
|
||||
@@ -58,6 +83,15 @@ pub struct PathTracer {
|
||||
nodes: wgpu::Buffer,
|
||||
tris: wgpu::Buffer,
|
||||
tri_tex: wgpu::Buffer,
|
||||
/// Etappe 5: Lichtliste (Dreiecks-Indizes) und Zahl je Art.
|
||||
lights: wgpu::Buffer,
|
||||
light_counts: [u32; 3],
|
||||
expose: wgpu::ComputePipeline,
|
||||
expose_layout: wgpu::BindGroupLayout,
|
||||
expose_bind: Option<wgpu::BindGroup>,
|
||||
/// Belichtung der Automatik (x aktuell, y gültig, z Ziel, w Mittel log2).
|
||||
expo: wgpu::Buffer,
|
||||
timing: Option<Timing>,
|
||||
tex_layout: wgpu::BindGroupLayout,
|
||||
/// Bildkarten (group 1); None bis `set_textures` (dann zeichnet er nicht).
|
||||
tex_bind: Option<wgpu::BindGroup>,
|
||||
@@ -79,8 +113,16 @@ pub struct PathTracer {
|
||||
pub denoise: bool,
|
||||
/// Höchstzahl Pixel je Sample (grössere Ansichten rechnen verkleinert).
|
||||
pub max_pixels: u64,
|
||||
/// Etappe 5: Fenster als Lichtportale, Raumlicht bei Nacht, Belichtungskorrektur (EV), Automatik, Abpraller,
|
||||
/// Bildkarten aus (Messung). Ändern beginnt die Summe von vorn (ausser EV/Automatik: nur Anzeige).
|
||||
pub options: PtOptions,
|
||||
/// Belichtungsautomatik an (Rate je Bild `AUTO_EXPOSURE_RATE`, Stapel > 1 sofort).
|
||||
pub auto_exposure: bool,
|
||||
srgb_encode: bool,
|
||||
/// Grösster Speicher-Puffer (kleinere von Puffer- und Bindungsgrenze des Geräts).
|
||||
max_binding: u64,
|
||||
/// Letzte Szene überschritt die Grenzen (leer gezeigt).
|
||||
too_big: bool,
|
||||
}
|
||||
|
||||
fn storage_entry(binding: u32, read_only: bool, vis: wgpu::ShaderStages) -> wgpu::BindGroupLayoutEntry {
|
||||
@@ -116,6 +158,7 @@ impl PathTracer {
|
||||
storage_entry(4, false, cs),
|
||||
storage_entry(5, false, cs),
|
||||
storage_entry(6, true, cs),
|
||||
storage_entry(7, true, cs),
|
||||
],
|
||||
});
|
||||
let tex_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
@@ -147,7 +190,11 @@ impl PathTracer {
|
||||
});
|
||||
let display_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("pathtrace.display.layout"),
|
||||
entries: &[uniform_entry(fs, psize), storage_entry(1, true, fs), storage_entry(2, true, fs), storage_entry(3, true, fs)],
|
||||
entries: &[uniform_entry(fs, psize), storage_entry(1, true, fs), storage_entry(2, true, fs), storage_entry(3, true, fs), storage_entry(4, true, fs)],
|
||||
});
|
||||
let expose_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("pathtrace.expose.layout"),
|
||||
entries: &[uniform_entry(cs, psize), storage_entry(1, true, cs), storage_entry(2, false, cs)],
|
||||
});
|
||||
let dn_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("pathtrace.denoise.layout"),
|
||||
@@ -163,6 +210,8 @@ impl PathTracer {
|
||||
let cmod = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pathtrace.wgsl"), source: wgpu::ShaderSource::Wgsl(PT_WGSL.into()) });
|
||||
let dmod = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pathtrace.display.wgsl"), source: wgpu::ShaderSource::Wgsl(PT_DISPLAY_WGSL.into()) });
|
||||
let nmod = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pathtrace.denoise.wgsl"), source: wgpu::ShaderSource::Wgsl(DN_WGSL.into()) });
|
||||
let emod = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pathtrace.expose.wgsl"), source: wgpu::ShaderSource::Wgsl(EXPOSE_WGSL.into()) });
|
||||
let elayout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("pathtrace.expose.pl"), bind_group_layouts: &[Some(&expose_layout)], immediate_size: 0 });
|
||||
let clayout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("pathtrace.compute.pl"), bind_group_layouts: &[Some(&compute_layout), Some(&tex_layout)], immediate_size: 0 });
|
||||
let dlayout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("pathtrace.display.pl"), bind_group_layouts: &[Some(&display_layout)], immediate_size: 0 });
|
||||
let nlayout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("pathtrace.denoise.pl"), bind_group_layouts: &[Some(&dn_layout)], immediate_size: 0 });
|
||||
@@ -179,6 +228,14 @@ impl PathTracer {
|
||||
let compute = compute_pipe("pathtrace.compute", &clayout, &cmod, "main");
|
||||
let dn_prep = compute_pipe("pathtrace.denoise.prep", &nlayout, &nmod, "prep");
|
||||
let dn_atrous = compute_pipe("pathtrace.denoise.atrous", &nlayout, &nmod, "atrous");
|
||||
let expose = compute_pipe("pathtrace.expose", &elayout, &emod, "expose");
|
||||
let expo = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("pathtrace.expo"),
|
||||
size: 16,
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let lights = Self::light_buffer(device, None, &[]);
|
||||
let display = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("pathtrace.display"),
|
||||
layout: Some(&dlayout),
|
||||
@@ -211,7 +268,7 @@ impl PathTracer {
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let (nodes, tris, tri_tex) = Self::scene_buffers(device, &Bvh::default());
|
||||
let (nodes, tris, tri_tex) = Self::scene_buffers(device, None, &Bvh::default());
|
||||
Self {
|
||||
compute,
|
||||
compute_layout,
|
||||
@@ -225,6 +282,13 @@ impl PathTracer {
|
||||
nodes,
|
||||
tris,
|
||||
tri_tex,
|
||||
lights,
|
||||
light_counts: [0; 3],
|
||||
expose,
|
||||
expose_layout,
|
||||
expose_bind: None,
|
||||
expo,
|
||||
timing: None,
|
||||
tex_layout,
|
||||
tex_bind: None,
|
||||
tri_count: 0,
|
||||
@@ -240,33 +304,123 @@ impl PathTracer {
|
||||
max_samples: DEFAULT_MAX_SAMPLES,
|
||||
denoise: true,
|
||||
max_pixels: MAX_PIXELS,
|
||||
options: PtOptions::default(),
|
||||
auto_exposure: true,
|
||||
srgb_encode: !color_format.is_srgb(),
|
||||
max_binding: device.limits().max_storage_buffer_binding_size,
|
||||
max_binding: device.limits().max_storage_buffer_binding_size.min(device.limits().max_buffer_size),
|
||||
too_big: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Speicher-Puffer mit Inhalt, OHNE `mapped_at_creation` (Etappe 5): im Browser wirft `createBuffer` mit
|
||||
/// `mappedAtCreation` synchron, wenn der Puffer nicht angelegt werden kann (Grenze, Speicher), und wgpu macht daraus
|
||||
/// einen Panic, der das ganze WASM-Modul lahmlegt (SwiftShader, Musterhaus komplex). Leer angelegt und per
|
||||
/// `write_buffer` gefüllt landen Fehler höchstens als Validierungsmeldung; die Grösse prüft `fits` vorher.
|
||||
/// Ohne `queue` (beim Anlegen) bleibt er genullt.
|
||||
fn storage_with(device: &wgpu::Device, queue: Option<&wgpu::Queue>, label: &str, bytes: &[u8]) -> wgpu::Buffer {
|
||||
let size = (bytes.len() as u64).max(16).next_multiple_of(wgpu::COPY_BUFFER_ALIGNMENT);
|
||||
let buf = device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
|
||||
if let Some(q) = queue {
|
||||
if !bytes.is_empty() {
|
||||
let mut data = bytes.to_vec();
|
||||
data.resize(bytes.len().next_multiple_of(wgpu::COPY_BUFFER_ALIGNMENT as usize), 0);
|
||||
q.write_buffer(&buf, 0, &data);
|
||||
}
|
||||
}
|
||||
buf
|
||||
}
|
||||
|
||||
/// Passt ein Speicher-Puffer dieser Grösse in die Grenzen des Geräts (Puffer- und Bindungsgrösse)?
|
||||
pub fn fits(&self, bytes: u64) -> bool {
|
||||
bytes <= self.max_binding
|
||||
}
|
||||
|
||||
/// Szene war zu gross für das Gerät (Pathtracer zeigt nur den Himmel; der Viewport meldet es).
|
||||
pub fn scene_too_big(&self) -> bool {
|
||||
self.too_big
|
||||
}
|
||||
|
||||
/// Test: Grenzen des Geräts künstlich verkleinern (Puffer = Bindung = `bytes`).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn limit_for_test(&mut self, bytes: u64) {
|
||||
self.max_binding = bytes;
|
||||
}
|
||||
|
||||
/// Puffer für Baum, Dreiecke und Texturdaten; leer = je ein Platzhalter-Eintrag (Bindungen dürfen nicht leer sein).
|
||||
/// Texturdaten in anderer Länge als die Dreiecke (kein Fall des Baums) werden mit „ohne Textur“ aufgefüllt.
|
||||
fn scene_buffers(device: &wgpu::Device, bvh: &Bvh) -> (wgpu::Buffer, wgpu::Buffer, wgpu::Buffer) {
|
||||
fn scene_buffers(device: &wgpu::Device, queue: Option<&wgpu::Queue>, bvh: &Bvh) -> (wgpu::Buffer, wgpu::Buffer, wgpu::Buffer) {
|
||||
let node0 = [GpuNode::default()];
|
||||
let tri0 = [GpuTri::default()];
|
||||
let nodes: &[GpuNode] = if bvh.nodes.is_empty() { &node0 } else { &bvh.nodes };
|
||||
let tris: &[GpuTri] = if bvh.tris.is_empty() { &tri0 } else { &bvh.tris };
|
||||
let mut tex: Vec<GpuTriTex> = bvh.tex.iter().copied().take(tris.len()).collect();
|
||||
tex.resize(tris.len(), GpuTriTex { scale: 1.0, ..GpuTriTex::default() });
|
||||
let n = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("pathtrace.nodes"), contents: bytemuck::cast_slice(nodes), usage: wgpu::BufferUsages::STORAGE });
|
||||
let t = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("pathtrace.tris"), contents: bytemuck::cast_slice(tris), usage: wgpu::BufferUsages::STORAGE });
|
||||
let x = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("pathtrace.tri_tex"), contents: bytemuck::cast_slice(&tex), usage: wgpu::BufferUsages::STORAGE });
|
||||
let n = Self::storage_with(device, queue, "pathtrace.nodes", bytemuck::cast_slice(nodes));
|
||||
let t = Self::storage_with(device, queue, "pathtrace.tris", bytemuck::cast_slice(tris));
|
||||
let x = Self::storage_with(device, queue, "pathtrace.tri_tex", bytemuck::cast_slice(&tex));
|
||||
(n, t, x)
|
||||
}
|
||||
|
||||
/// Lichtliste als Puffer (leer = ein Platzhalter-Eintrag, die Zahlen im Parameter-Block sind dann 0).
|
||||
fn light_buffer(device: &wgpu::Device, queue: Option<&wgpu::Queue>, idx: &[u32]) -> wgpu::Buffer {
|
||||
Self::storage_with(device, queue, "pathtrace.lights", bytemuck::cast_slice(idx))
|
||||
}
|
||||
|
||||
/// Zeitstempel je Abschnitt an/aus (nur wenn das Gerät `TIMESTAMP_QUERY` kann; sonst bleibt es aus). Rückgabe: an?
|
||||
pub fn set_timing(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, on: bool) -> bool {
|
||||
if !on || !device.features().contains(wgpu::Features::TIMESTAMP_QUERY) {
|
||||
self.timing = None;
|
||||
return false;
|
||||
}
|
||||
if self.timing.is_none() {
|
||||
let size = TS_COUNT as u64 * 8;
|
||||
self.timing = Some(Timing {
|
||||
set: device.create_query_set(&wgpu::QuerySetDescriptor { label: Some("pathtrace.timestamps"), ty: wgpu::QueryType::Timestamp, count: TS_COUNT }),
|
||||
resolve: device.create_buffer(&wgpu::BufferDescriptor { label: None, size, usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false }),
|
||||
read: device.create_buffer(&wgpu::BufferDescriptor { label: None, size, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false }),
|
||||
period_ns: queue.get_timestamp_period(),
|
||||
});
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Zeitstempel des letzten `render` lesen (wartet auf die GPU; nur für Messungen). None ohne `set_timing`.
|
||||
pub fn read_timings(&self, device: &wgpu::Device) -> Option<PtTimings> {
|
||||
let t = self.timing.as_ref()?;
|
||||
let slice = t.read.slice(..);
|
||||
slice.map_async(wgpu::MapMode::Read, |_| {});
|
||||
let _ = device.poll(wgpu::PollType::wait_indefinitely());
|
||||
let ts: Vec<u64> = bytemuck::cast_slice::<u8, u64>(&slice.get_mapped_range()).to_vec();
|
||||
t.read.unmap();
|
||||
let ms = |a: usize| if ts[a + 1] > ts[a] { (ts[a + 1] - ts[a]) as f64 * t.period_ns as f64 / 1e6 } else { 0.0 };
|
||||
Some(PtTimings { samples_ms: ms(0), denoise_ms: ms(2), display_ms: ms(4) })
|
||||
}
|
||||
|
||||
/// Belichtung der Automatik lesen (wartet auf die GPU; Tests, Messung): (aktuell, gültig, Ziel, Mittel log2).
|
||||
pub fn read_exposure(&self, device: &wgpu::Device, queue: &wgpu::Queue) -> [f32; 4] {
|
||||
let read = device.create_buffer(&wgpu::BufferDescriptor { label: None, size: 16, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false });
|
||||
let mut enc = device.create_command_encoder(&Default::default());
|
||||
enc.copy_buffer_to_buffer(&self.expo, 0, &read, 0, 16);
|
||||
queue.submit([enc.finish()]);
|
||||
read.slice(..).map_async(wgpu::MapMode::Read, |_| {});
|
||||
let _ = device.poll(wgpu::PollType::wait_indefinitely());
|
||||
let v = bytemuck::cast_slice::<u8, f32>(&read.slice(..).get_mapped_range()).to_vec();
|
||||
[v[0], v[1], v[2], v[3]]
|
||||
}
|
||||
|
||||
/// Zahl der Lichter je Art (Portale, Leuchten, Raumlicht).
|
||||
pub fn light_counts(&self) -> [u32; 3] {
|
||||
self.light_counts
|
||||
}
|
||||
|
||||
/// Bildkarten für den Pfad: Textur-Array (D2Array, wie `Renderer::set_material_textures`), Detail-Array (Normale/
|
||||
/// Rauigkeit, gleiche Ebenen-Nummern; Etappe 4), Sampler mit Wiederholung und je Ebene der Kehrwert der mittleren
|
||||
/// Kartenfarbe (`PtMaterialTable::inv_means`, Index = Ebene). Die Summe beginnt von vorn.
|
||||
pub fn set_textures(&mut self, device: &wgpu::Device, view: &wgpu::TextureView, detail: &wgpu::TextureView, sampler: &wgpu::Sampler, inv_means: &[[f32; 4]]) {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn set_textures(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, view: &wgpu::TextureView, detail: &wgpu::TextureView, sampler: &wgpu::Sampler, inv_means: &[[f32; 4]]) {
|
||||
let one = [[1.0f32; 4]];
|
||||
let inv: &[[f32; 4]] = if inv_means.is_empty() { &one } else { inv_means };
|
||||
let buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("pathtrace.layer_inv"), contents: bytemuck::cast_slice(inv), usage: wgpu::BufferUsages::STORAGE });
|
||||
let inv: &[[f32; 4]] = if inv_means.is_empty() || !self.fits((inv_means.len() * 16) as u64) { &one } else { inv_means };
|
||||
let buf = Self::storage_with(device, Some(queue), "pathtrace.layer_inv", bytemuck::cast_slice(inv));
|
||||
self.tex_bind = Some(device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("pathtrace.textures.bind"),
|
||||
layout: &self.tex_layout,
|
||||
@@ -281,18 +435,27 @@ impl PathTracer {
|
||||
self.key = None;
|
||||
}
|
||||
|
||||
/// Neue Szene hochladen; die Summe beginnt von vorn. Zu grosse Szenen (über dem Bindungs-Limit des Geräts)
|
||||
/// werden leer gezeigt statt die Validierung scheitern zu lassen.
|
||||
pub fn set_bvh(&mut self, device: &wgpu::Device, bvh: &Bvh) {
|
||||
let too_big = (bvh.tris.len() * std::mem::size_of::<GpuTri>()) as u64 > self.max_binding
|
||||
|| (bvh.nodes.len() * std::mem::size_of::<GpuNode>()) as u64 > self.max_binding;
|
||||
/// Neue Szene hochladen; die Summe beginnt von vorn. Zu grosse Szenen (ein Puffer über der Puffer- oder
|
||||
/// Bindungsgrenze des Geräts) werden leer gezeigt (`scene_too_big`) statt die Validierung scheitern zu lassen
|
||||
/// oder — im Browser — einen Panic auszulösen.
|
||||
pub fn set_bvh(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, bvh: &Bvh) {
|
||||
let sizes = [
|
||||
bvh.tris.len() * std::mem::size_of::<GpuTri>(),
|
||||
bvh.nodes.len() * std::mem::size_of::<GpuNode>(),
|
||||
bvh.tris.len() * std::mem::size_of::<GpuTriTex>(),
|
||||
bvh.lights.idx.len() * 4,
|
||||
];
|
||||
let too_big = sizes.iter().any(|&b| !self.fits(b as u64));
|
||||
self.too_big = too_big;
|
||||
let empty = Bvh::default();
|
||||
let use_bvh = if too_big { &empty } else { bvh };
|
||||
let (n, t, x) = Self::scene_buffers(device, use_bvh);
|
||||
let (n, t, x) = Self::scene_buffers(device, Some(queue), use_bvh);
|
||||
self.nodes = n;
|
||||
self.tris = t;
|
||||
self.tri_tex = x;
|
||||
self.tri_count = use_bvh.tris.len() as u32;
|
||||
self.lights = Self::light_buffer(device, Some(queue), &use_bvh.lights.idx);
|
||||
self.light_counts = if use_bvh.lights.idx.is_empty() { [0; 3] } else { use_bvh.lights.counts };
|
||||
self.scene_gen = self.scene_gen.wrapping_add(1);
|
||||
self.compute_bind = None;
|
||||
self.key = None;
|
||||
@@ -342,6 +505,7 @@ impl PathTracer {
|
||||
self.internal = size;
|
||||
self.compute_bind = None;
|
||||
self.display_bind = None;
|
||||
self.expose_bind = None;
|
||||
self.dn_binds.clear();
|
||||
self.key = None;
|
||||
}
|
||||
@@ -360,6 +524,8 @@ impl PathTracer {
|
||||
}
|
||||
k.push(night as u32);
|
||||
k.push(self.scene_gen);
|
||||
let o = &self.options;
|
||||
k.extend([o.portals as u32, o.room_light as u32, o.bounces, o.no_tex as u32]);
|
||||
k
|
||||
}
|
||||
|
||||
@@ -378,6 +544,18 @@ impl PathTracer {
|
||||
wgpu::BindGroupEntry { binding: 4, resource: fb.aux_a.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 5, resource: fb.aux_b.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 6, resource: self.tri_tex.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 7, resource: self.lights.as_entire_binding() },
|
||||
],
|
||||
}));
|
||||
}
|
||||
if self.expose_bind.is_none() {
|
||||
self.expose_bind = Some(device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("pathtrace.expose.bind"),
|
||||
layout: &self.expose_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry { binding: 0, resource: self.params.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 1, resource: fb.accum.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 2, resource: self.expo.as_entire_binding() },
|
||||
],
|
||||
}));
|
||||
}
|
||||
@@ -392,6 +570,7 @@ impl PathTracer {
|
||||
wgpu::BindGroupEntry { binding: 1, resource: fb.accum.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 2, resource: fb.filt[last].as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 3, resource: fb.aux_a.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 4, resource: self.expo.as_entire_binding() },
|
||||
],
|
||||
}));
|
||||
}
|
||||
@@ -424,8 +603,14 @@ impl PathTracer {
|
||||
queue.write_buffer(buf, 0, bytemuck::bytes_of(&p));
|
||||
}
|
||||
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pathtrace.denoise") });
|
||||
let last = self.dn_binds.len().saturating_sub(1);
|
||||
for (pass, bind) in self.dn_binds.iter().enumerate() {
|
||||
let mut cp = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("pathtrace.denoise.pass"), timestamp_writes: None });
|
||||
let ts = self.timing.as_ref().filter(|_| pass == 0 || pass == last).map(|t| wgpu::ComputePassTimestampWrites {
|
||||
query_set: &t.set,
|
||||
beginning_of_pass_write_index: (pass == 0).then_some(2),
|
||||
end_of_pass_write_index: (pass == last).then_some(3),
|
||||
});
|
||||
let mut cp = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("pathtrace.denoise.pass"), timestamp_writes: ts });
|
||||
cp.set_pipeline(if pass == 0 { &self.dn_prep } else { &self.dn_atrous });
|
||||
cp.set_bind_group(0, bind, &[]);
|
||||
cp.dispatch_workgroups(w.div_ceil(8), h.div_ceil(8), 1);
|
||||
@@ -461,18 +646,29 @@ impl PathTracer {
|
||||
self.ensure_binds(device);
|
||||
let internal = self.internal;
|
||||
let (tri_count, srgb) = (self.tri_count, self.srgb_encode);
|
||||
let params = |frame: u32, dn: f32| build_params(camera, &sky, internal, (w, h), frame, tri_count, srgb, dn);
|
||||
// Belichtung: Automatik im Viewport sanft (je Bild), bei mehreren Samples auf einmal (Export, headless) sofort.
|
||||
let opt = PtOptions {
|
||||
light_counts: self.light_counts,
|
||||
auto_exposure: if !self.auto_exposure { 0.0 } else if batch > 1 { 1.0 } else { AUTO_EXPOSURE_RATE },
|
||||
..self.options
|
||||
};
|
||||
let params = |frame: u32, dn: f32| build_params_with(camera, &sky, internal, (w, h), frame, tri_count, srgb, dn, &opt);
|
||||
if params(0, 0.0).is_none() || self.tex_bind.is_none() {
|
||||
return;
|
||||
}
|
||||
// Samples: je eines mit eigenem Parameter-Block (Schreiben + Abschicken in Reihenfolge).
|
||||
let n = batch.max(1).min(self.max_samples.saturating_sub(self.frame));
|
||||
for _ in 0..n {
|
||||
for s in 0..n {
|
||||
let Some(p) = params(self.frame, 0.0) else { return };
|
||||
queue.write_buffer(&self.params, 0, bytemuck::bytes_of(&p));
|
||||
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pathtrace.sample") });
|
||||
{
|
||||
let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("pathtrace.compute"), timestamp_writes: None });
|
||||
let ts = self.timing.as_ref().filter(|_| s == 0 || s + 1 == n).map(|t| wgpu::ComputePassTimestampWrites {
|
||||
query_set: &t.set,
|
||||
beginning_of_pass_write_index: (s == 0).then_some(0),
|
||||
end_of_pass_write_index: (s + 1 == n).then_some(1),
|
||||
});
|
||||
let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("pathtrace.compute"), timestamp_writes: ts });
|
||||
pass.set_pipeline(&self.compute);
|
||||
pass.set_bind_group(0, self.compute_bind.as_ref(), &[]);
|
||||
pass.set_bind_group(1, self.tex_bind.as_ref(), &[]);
|
||||
@@ -489,7 +685,20 @@ impl PathTracer {
|
||||
let Some(p) = params(self.frame, dn) else { return };
|
||||
queue.write_buffer(&self.params, 0, bytemuck::bytes_of(&p));
|
||||
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pathtrace.display") });
|
||||
// Belichtungsautomatik (eine Arbeitsgruppe) vor der Anzeige.
|
||||
if self.auto_exposure && self.frame > 0 {
|
||||
let ts = self.timing.as_ref().map(|t| wgpu::ComputePassTimestampWrites { query_set: &t.set, beginning_of_pass_write_index: Some(4), end_of_pass_write_index: None });
|
||||
let mut cp = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("pathtrace.expose"), timestamp_writes: ts });
|
||||
cp.set_pipeline(&self.expose);
|
||||
cp.set_bind_group(0, self.expose_bind.as_ref(), &[]);
|
||||
cp.dispatch_workgroups(1, 1, 1);
|
||||
}
|
||||
{
|
||||
let ts = self.timing.as_ref().map(|t| wgpu::RenderPassTimestampWrites {
|
||||
query_set: &t.set,
|
||||
beginning_of_pass_write_index: (!self.auto_exposure || self.frame == 0).then_some(4),
|
||||
end_of_pass_write_index: Some(5),
|
||||
});
|
||||
let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("pathtrace.display.pass"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
@@ -499,7 +708,7 @@ impl PathTracer {
|
||||
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store },
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
timestamp_writes: None,
|
||||
timestamp_writes: ts,
|
||||
occlusion_query_set: None,
|
||||
multiview_mask: None,
|
||||
});
|
||||
@@ -507,6 +716,10 @@ impl PathTracer {
|
||||
pass.set_bind_group(0, self.display_bind.as_ref(), &[]);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
if let Some(t) = &self.timing {
|
||||
enc.resolve_query_set(&t.set, 0..TS_COUNT, &t.resolve, 0);
|
||||
enc.copy_buffer_to_buffer(&t.resolve, 0, &t.read, 0, TS_COUNT as u64 * 8);
|
||||
}
|
||||
queue.submit([enc.finish()]);
|
||||
}
|
||||
|
||||
@@ -535,3 +748,191 @@ impl PathTracer {
|
||||
bytemuck::cast_slice::<u8, [f32; 4]>(&data).to_vec()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl PathTracer {
|
||||
/// Test: Akkumulation und Hilfspuffer A (Albedo, Luminanz²) der laufenden Summe zurücklesen.
|
||||
pub(crate) fn read_sums(&self, device: &wgpu::Device, queue: &wgpu::Queue) -> (Vec<[f32; 4]>, Vec<[f32; 4]>) {
|
||||
let fb = self.frame_bufs.as_ref().unwrap();
|
||||
let size = self.internal.0 as u64 * self.internal.1 as u64 * 16;
|
||||
let read = |b: &wgpu::Buffer| {
|
||||
let r = device.create_buffer(&wgpu::BufferDescriptor { label: None, size, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false });
|
||||
let mut enc = device.create_command_encoder(&Default::default());
|
||||
enc.copy_buffer_to_buffer(b, 0, &r, 0, size);
|
||||
queue.submit([enc.finish()]);
|
||||
r.slice(..).map_async(wgpu::MapMode::Read, |_| {});
|
||||
let _ = device.poll(wgpu::PollType::wait_indefinitely());
|
||||
let v = bytemuck::cast_slice::<u8, [f32; 4]>(&r.slice(..).get_mapped_range()).to_vec();
|
||||
v
|
||||
};
|
||||
(read(&fb.accum), read(&fb.aux_a))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::types::Camera;
|
||||
|
||||
fn device() -> Option<(wgpu::Device, wgpu::Queue)> {
|
||||
let instance = wgpu::Instance::default();
|
||||
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?;
|
||||
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).ok()
|
||||
}
|
||||
|
||||
/// Pathtracer mit 1×1-Platzhalter-Texturen (keine Bildkarten).
|
||||
fn tracer(device: &wgpu::Device, queue: &wgpu::Queue) -> PathTracer {
|
||||
let mut pt = PathTracer::new(device, wgpu::TextureFormat::Rgba8UnormSrgb);
|
||||
let tex = |fmt| {
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: None,
|
||||
size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: fmt,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
})
|
||||
};
|
||||
let a = tex(wgpu::TextureFormat::Rgba8UnormSrgb);
|
||||
let b = tex(wgpu::TextureFormat::Rgba8Unorm);
|
||||
let view = |t: &wgpu::Texture| t.create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() });
|
||||
let sampler = device.create_sampler(&Default::default());
|
||||
pt.set_textures(device, queue, &view(&a), &view(&b), &sampler, &[]);
|
||||
pt.denoise = false;
|
||||
pt
|
||||
}
|
||||
|
||||
fn target(device: &wgpu::Device, w: u32, h: u32) -> wgpu::TextureView {
|
||||
device
|
||||
.create_texture(&wgpu::TextureDescriptor {
|
||||
label: None,
|
||||
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8UnormSrgb,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
view_formats: &[],
|
||||
})
|
||||
.create_view(&Default::default())
|
||||
}
|
||||
|
||||
/// Mittel und mittlere Varianz je Pixel (aus Summe und Luminanz²-Summe) der Luminanz über das Bild.
|
||||
fn stats(acc: &[[f32; 4]], aux: &[[f32; 4]]) -> (f64, f64) {
|
||||
let (mut mean, mut var) = (0.0f64, 0.0f64);
|
||||
for (a, x) in acc.iter().zip(aux) {
|
||||
let n = a[3].max(1.0) as f64;
|
||||
let m = (0.2126 * a[0] + 0.7152 * a[1] + 0.0722 * a[2]) as f64 / n;
|
||||
mean += m;
|
||||
var += (x[3] as f64 / n - m * m).max(0.0);
|
||||
}
|
||||
(mean / acc.len() as f64, var / acc.len() as f64)
|
||||
}
|
||||
|
||||
const CAM: Camera = Camera {
|
||||
eye: [3.6, 1.5, 3.7],
|
||||
target: [1.0, 0.6, 0.5],
|
||||
up: [0.0, 1.0, 0.0],
|
||||
projection: crate::types::Projection::Perspective,
|
||||
fov_y: 1.0,
|
||||
ortho_half_height: 5.0,
|
||||
near: 0.05,
|
||||
far: 1000.0,
|
||||
};
|
||||
|
||||
/// [212] Etappe 5: Fenster als Lichtportale — im geschlossenen Raum mit einem Fenster (bedeckter Himmel, keine Sonne)
|
||||
/// bleibt der Erwartungswert gleich wie ohne Portale (MIS erwartungstreu), die Varianz je Pixel sinkt deutlich.
|
||||
#[test]
|
||||
fn portal_nee_erwartungswert_gleich_varianz_kleiner() {
|
||||
let Some((device, queue)) = device() else {
|
||||
eprintln!("kein GPU-Adapter: Test übersprungen");
|
||||
return;
|
||||
};
|
||||
let bvh = Bvh::build(&crate::pt_lights::tests::room());
|
||||
assert_eq!(bvh.lights.counts[0], 2);
|
||||
let (w, h) = (48u32, 32u32);
|
||||
let view = target(&device, w, h);
|
||||
let run = |portals: bool, spp: u32| {
|
||||
let mut pt = tracer(&device, &queue);
|
||||
pt.set_bvh(&device, &queue, &bvh);
|
||||
pt.options.portals = portals;
|
||||
// Viele Abpraller: die Abschneidung des Pfades (die NEE der letzten Ecke reicht ein Segment weiter) fällt
|
||||
// nicht ins Gewicht.
|
||||
pt.options.bounces = 16;
|
||||
pt.max_samples = spp;
|
||||
pt.render(&device, &queue, &view, &CAM, None, false, (w, h), spp);
|
||||
let (acc, aux) = pt.read_sums(&device, &queue);
|
||||
assert_eq!(pt.samples(), spp);
|
||||
stats(&acc, &aux)
|
||||
};
|
||||
let (m_off, v_off) = run(false, 1024);
|
||||
let (m_on, v_on) = run(true, 1024);
|
||||
eprintln!("ohne Portale: Mittel {m_off:.5}, Varianz {v_off:.6}; mit: Mittel {m_on:.5}, Varianz {v_on:.6}");
|
||||
assert!(m_off > 0.0 && m_on > 0.0);
|
||||
assert!((m_on - m_off).abs() / m_off < 0.01, "Erwartungswert: {m_on} vs {m_off}");
|
||||
assert!(v_on < v_off * 0.5, "Varianz: {v_on} vs {v_off}");
|
||||
}
|
||||
|
||||
/// [212] Etappe 5: Belichtungsautomatik auf der GPU wie die CPU-Referenz (`exposure::measure`), Stapel > 1 stellt
|
||||
/// sofort ein; Innenraum bekommt mehr Belichtung als der Himmel allein.
|
||||
#[test]
|
||||
fn belichtung_wie_referenz() {
|
||||
let Some((device, queue)) = device() else {
|
||||
eprintln!("kein GPU-Adapter: Test übersprungen");
|
||||
return;
|
||||
};
|
||||
let bvh = Bvh::build(&crate::pt_lights::tests::room());
|
||||
let (w, h) = (48u32, 32u32);
|
||||
let view = target(&device, w, h);
|
||||
let mut pt = tracer(&device, &queue);
|
||||
pt.set_bvh(&device, &queue, &bvh);
|
||||
pt.max_samples = 8;
|
||||
pt.render(&device, &queue, &view, &CAM, None, false, (w, h), 8);
|
||||
let e = pt.read_exposure(&device, &queue);
|
||||
let (acc, _) = pt.read_sums(&device, &queue);
|
||||
let sky = sky_for_sun(None);
|
||||
let lo = sky.exposure * crate::pathtrace::AUTO_EXPOSURE_MIN;
|
||||
let hi = sky.exposure * crate::pathtrace::AUTO_EXPOSURE_MAX_DAY;
|
||||
let (tgt, m) = crate::exposure::measure(&acc, w, h, lo, hi);
|
||||
assert_eq!(e[1], 1.0, "gültig");
|
||||
assert!((e[3] - m).abs() < 1e-3, "Mittel log2 {} vs {m}", e[3]);
|
||||
assert!((e[2] - tgt).abs() / tgt < 1e-3 && (e[0] - tgt).abs() / tgt < 1e-3, "{e:?} vs {tgt}");
|
||||
assert!(e[0] > sky.exposure, "Innenraum heller belichtet: {}", e[0]);
|
||||
// Viewport (Stapel 1): sanft, nur ein Teil des Weges zu einem neuen Ziel.
|
||||
let far = Camera { eye: [3.6, 1.5, 3.7], target: [2.0, 1.4, -1.0], ..CAM };
|
||||
pt.max_samples = 16;
|
||||
pt.render(&device, &queue, &view, &far, None, false, (w, h), 1);
|
||||
let e2 = pt.read_exposure(&device, &queue);
|
||||
assert!((e2[0] - e2[2]).abs() > 1e-4 || (e2[2] - e[0]).abs() < 1e-4, "{e2:?}");
|
||||
}
|
||||
|
||||
/// Browser-Befund (SwiftShader): zu grosse Puffer dürfen den Pathtracer nicht abstürzen lassen. Mit künstlich
|
||||
/// kleinen Grenzen bleibt die Szene leer (gemeldet), die Summe rechnet verkleinert — ohne Validierungsfehler
|
||||
/// (die native wgpu-Schicht würde darauf mit Panic reagieren).
|
||||
#[test]
|
||||
fn kleine_grenzen_ohne_panic() {
|
||||
let Some((device, queue)) = device() else {
|
||||
eprintln!("kein GPU-Adapter: Test übersprungen");
|
||||
return;
|
||||
};
|
||||
let bvh = Bvh::build(&crate::pt_lights::tests::room());
|
||||
let mut pt = tracer(&device, &queue);
|
||||
pt.limit_for_test(1024);
|
||||
pt.set_bvh(&device, &queue, &bvh);
|
||||
assert!(pt.scene_too_big());
|
||||
assert_eq!(pt.tri_count(), 0);
|
||||
let view = target(&device, 64, 48);
|
||||
pt.render(&device, &queue, &view, &CAM, None, false, (64, 48), 2);
|
||||
let (iw, ih) = pt.internal_size();
|
||||
assert!((iw as u64 * ih as u64 * 16) <= 1024, "{iw}x{ih}");
|
||||
assert_eq!(pt.samples(), 2);
|
||||
// Grenze wieder gross: Szene da, Meldung weg.
|
||||
pt.limit_for_test(1 << 26);
|
||||
pt.set_bvh(&device, &queue, &bvh);
|
||||
assert!(!pt.scene_too_big() && pt.tri_count() > 0);
|
||||
pt.render(&device, &queue, &view, &CAM, None, false, (64, 48), 1);
|
||||
let _ = device.poll(wgpu::PollType::wait_indefinitely());
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
pub mod bvh;
|
||||
pub mod denoise;
|
||||
pub mod edges;
|
||||
pub mod exposure;
|
||||
pub mod ghost;
|
||||
pub mod grid;
|
||||
pub mod math;
|
||||
@@ -24,6 +25,7 @@ pub mod mesh;
|
||||
pub mod pathtrace;
|
||||
pub mod pattern_lines;
|
||||
pub mod points;
|
||||
pub mod pt_lights;
|
||||
pub mod pt_material;
|
||||
pub mod pt_texture;
|
||||
pub(crate) mod openings;
|
||||
|
||||
@@ -42,7 +42,7 @@ const SUN_IRRADIANCE: f32 = 3.0;
|
||||
/// Belichtung vor dem Tonemapping.
|
||||
pub const DEFAULT_EXPOSURE: f32 = 0.85;
|
||||
|
||||
/// Parameter-Block, 192 Byte, 1:1 zum WGSL-`Params` (nur `vec4`, std140-sicher).
|
||||
/// Parameter-Block, 240 Byte, 1:1 zum WGSL-`Params` (nur `vec4`, std140-sicher).
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
#[cfg_attr(feature = "render", derive(bytemuck::Pod, bytemuck::Zeroable))]
|
||||
@@ -67,11 +67,59 @@ pub struct PtParams {
|
||||
pub dims: [u32; 4],
|
||||
/// Dreiecke, Breite, Höhe (Anzeige), 1 = sRGB im Shader kodieren.
|
||||
pub info: [u32; 4],
|
||||
/// Entrauscher in der Anzeige: x = Mischgewicht (0 = roh, 1 = gefiltert, `denoise::blend_weight`); y = Innenlicht
|
||||
/// hinter Glas (`Sky::room_light`).
|
||||
/// Entrauscher in der Anzeige: x = Mischgewicht (0 = roh, 1 = gefiltert, `denoise::blend_weight`); y = Strahldichte
|
||||
/// des Raumlichts (`Sky::room_light`, nur wenn eingeschaltet).
|
||||
pub dn: [f32; 4],
|
||||
/// [212] Etappe 5: Lichtliste (`pt_lights.rs`): Zahl der Portale, Leuchten, Deckenlichter; w = Schalter
|
||||
/// (`F_PORTALS` | `F_EMITTERS` | `F_ROOM` | `F_NO_TEX`).
|
||||
pub lights: [u32; 4],
|
||||
/// Leistung für die Lichtwahl: x = Himmel durch Portale, y = Raumlicht; z, w frei.
|
||||
pub light_pow: [f32; 4],
|
||||
/// Belichtung (Etappe 5): x = Faktor 2^EV, y = Nachführung der Automatik je Bild (0 = aus, 1 = sofort), z/w = Grenzen
|
||||
/// der Automatik.
|
||||
pub expo: [f32; 4],
|
||||
}
|
||||
|
||||
/// Schalter in `PtParams::lights.w`.
|
||||
pub const F_PORTALS: u32 = 1;
|
||||
pub const F_EMITTERS: u32 = 2;
|
||||
pub const F_ROOM: u32 = 4;
|
||||
/// Messung: Bildkarten aus (Kosten der Texturen, `render_png --pt-notex`).
|
||||
pub const F_NO_TEX: u32 = 16;
|
||||
|
||||
/// Einstellungen des Pathtracers jenseits von Kamera und Himmel (Etappe 5).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct PtOptions {
|
||||
/// Zahl der Lichter je Art (`LightList::counts`).
|
||||
pub light_counts: [u32; 3],
|
||||
/// Fenster als Lichtportale (NEE auf den Himmel).
|
||||
pub portals: bool,
|
||||
/// Raumlicht bei Nacht (nur ohne Leuchten im Modell).
|
||||
pub room_light: bool,
|
||||
/// Belichtungskorrektur in Blenden (EV).
|
||||
pub ev: f32,
|
||||
/// Nachführung der Belichtungsautomatik je Bild (0 = aus, 1 = sofort).
|
||||
pub auto_exposure: f32,
|
||||
/// Abpraller je Pfad.
|
||||
pub bounces: u32,
|
||||
/// Messung: Bildkarten aus.
|
||||
pub no_tex: bool,
|
||||
}
|
||||
|
||||
impl Default for PtOptions {
|
||||
fn default() -> Self {
|
||||
PtOptions { light_counts: [0; 3], portals: true, room_light: true, ev: 0.0, auto_exposure: 0.0, bounces: MAX_BOUNCES, no_tex: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// Grenzen der Belichtungsautomatik relativ zur Belichtung des Himmels: Tag bis 32× heller (Innenraum), Nacht bis 4×
|
||||
/// (der dunkle Himmel soll dunkel bleiben), nie unter ¼.
|
||||
pub const AUTO_EXPOSURE_MIN: f32 = 0.25;
|
||||
pub const AUTO_EXPOSURE_MAX_DAY: f32 = 32.0;
|
||||
pub const AUTO_EXPOSURE_MAX_NIGHT: f32 = 4.0;
|
||||
/// Nachführung der Automatik je Bild im Viewport (sanft: ≈ 15 Bilder bis zum Ziel).
|
||||
pub const AUTO_EXPOSURE_RATE: f32 = 0.15;
|
||||
|
||||
/// Himmel und Sonne aus der Richtung ZUR Sonne (world, Y oben).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Sky {
|
||||
@@ -181,14 +229,39 @@ pub fn camera_basis(cam: &Camera, aspect: f32) -> Option<([f32; 4], [f32; 4], [f
|
||||
))
|
||||
}
|
||||
|
||||
/// Füllt den Parameter-Block. None bei unbrauchbarer Kamera (dann zeichnet der Pathtracer nicht). `denoise` =
|
||||
/// Mischgewicht des Entrauschers in der Anzeige.
|
||||
/// Füllt den Parameter-Block mit den Standard-Optionen (ohne Lichtliste, Belichtung fest). None bei unbrauchbarer
|
||||
/// Kamera (dann zeichnet der Pathtracer nicht). `denoise` = Mischgewicht des Entrauschers in der Anzeige.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn build_params(cam: &Camera, sky: &Sky, internal: (u32, u32), display: (u32, u32), frame: u32, tri_count: u32, srgb_encode: bool, denoise: f32) -> Option<PtParams> {
|
||||
build_params_with(cam, sky, internal, display, frame, tri_count, srgb_encode, denoise, &PtOptions::default())
|
||||
}
|
||||
|
||||
fn lum(c: [f32; 3]) -> f32 {
|
||||
0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]
|
||||
}
|
||||
|
||||
/// Wie `build_params`, mit Lichtliste, Raumlicht, Belichtung und Abprallern aus `opt` (Etappe 5).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn build_params_with(cam: &Camera, sky: &Sky, internal: (u32, u32), display: (u32, u32), frame: u32, tri_count: u32, srgb_encode: bool, denoise: f32, opt: &PtOptions) -> Option<PtParams> {
|
||||
let aspect = display.0 as f32 / display.1.max(1) as f32;
|
||||
let (cam_pos, cam_fwd, cam_right, cam_up) = camera_basis(cam, aspect)?;
|
||||
let cos_r = SUN_ANGULAR_RADIUS_DEG.to_radians().cos();
|
||||
let v4 = |c: [f32; 3], w: f32| [c[0], c[1], c[2], w];
|
||||
// Nacht = Himmel ohne Sonne mit Raumlicht-Stärke (`night_sky`); Portale nur am Tag (der Nachthimmel ist dunkel),
|
||||
// Raumlicht nur bei Nacht, eingeschaltet und ohne Leuchten im Modell.
|
||||
let night = sky.room_light > 0.0;
|
||||
let room_on = night && opt.room_light && opt.light_counts[1] == 0 && opt.light_counts[2] > 0;
|
||||
let room = if room_on { sky.room_light.max(0.0) } else { 0.0 };
|
||||
let mut flags = F_EMITTERS;
|
||||
if opt.portals && !night && opt.light_counts[0] > 0 {
|
||||
flags |= F_PORTALS;
|
||||
}
|
||||
if room_on {
|
||||
flags |= F_ROOM;
|
||||
}
|
||||
if opt.no_tex {
|
||||
flags |= F_NO_TEX;
|
||||
}
|
||||
Some(PtParams {
|
||||
cam_pos,
|
||||
cam_fwd,
|
||||
@@ -199,12 +272,23 @@ pub fn build_params(cam: &Camera, sky: &Sky, internal: (u32, u32), display: (u32
|
||||
sky_zenith: v4(sky.zenith, 0.0),
|
||||
sky_horizon: v4(sky.horizon, 0.0),
|
||||
ground: v4(sky.ground, sky.exposure),
|
||||
dims: [internal.0, internal.1, frame, MAX_BOUNCES],
|
||||
dims: [internal.0, internal.1, frame, opt.bounces.clamp(1, 16)],
|
||||
info: [tri_count, display.0, display.1, srgb_encode as u32],
|
||||
dn: [if denoise.is_finite() { denoise.clamp(0.0, 1.0) } else { 0.0 }, sky.room_light.max(0.0), 0.0, 0.0],
|
||||
dn: [if denoise.is_finite() { denoise.clamp(0.0, 1.0) } else { 0.0 }, room, 0.0, 0.0],
|
||||
lights: [opt.light_counts[0], opt.light_counts[1], opt.light_counts[2], flags],
|
||||
light_pow: [0.5 * (lum(sky.zenith) + lum(sky.horizon)), room * lum(ROOM_RGB), 0.0, 0.0],
|
||||
expo: [
|
||||
if opt.ev.is_finite() { 2f32.powf(opt.ev.clamp(-10.0, 10.0)) } else { 1.0 },
|
||||
if opt.auto_exposure.is_finite() { opt.auto_exposure.clamp(0.0, 1.0) } else { 0.0 },
|
||||
sky.exposure * AUTO_EXPOSURE_MIN,
|
||||
sky.exposure * if night { AUTO_EXPOSURE_MAX_NIGHT } else { AUTO_EXPOSURE_MAX_DAY },
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
/// Farbe des Raumlichts (warmweiss ≈ 2700 K; 1:1 `ROOM_RGB` im Shader).
|
||||
pub const ROOM_RGB: [f32; 3] = [1.0, 0.72, 0.42];
|
||||
|
||||
/// Höchstzahl Pixel, die je Sample verfolgt werden (grössere Ansichten rechnen verkleinert und werden in der
|
||||
/// Anzeige bilinear hochgezogen — Retina-Ansichten wären sonst zu langsam für die Vorschau).
|
||||
pub const MAX_PIXELS: u64 = 1_200_000;
|
||||
@@ -220,8 +304,10 @@ pub fn internal_size(w: u32, h: u32, max_pixels: u64) -> (u32, u32) {
|
||||
(((w as f64 * s).floor() as u32).max(1), ((h as f64 * s).floor() as u32).max(1))
|
||||
}
|
||||
|
||||
/// Compute-Shader der Pfadverfolgung: ein Sample je Pixel, aufaddiert in `accum` (rgb Summe, w Zahl).
|
||||
pub const PT_WGSL: &str = r#"
|
||||
/// WGSL-`Params` (1:1 `PtParams`), gemeinsam für Pfad, Anzeige und Belichtung.
|
||||
macro_rules! wgsl_params {
|
||||
() => {
|
||||
r#"
|
||||
struct Params {
|
||||
cam_pos: vec4<f32>,
|
||||
cam_fwd: vec4<f32>,
|
||||
@@ -235,7 +321,17 @@ struct Params {
|
||||
dims: vec4<u32>,
|
||||
info: vec4<u32>,
|
||||
dn: vec4<f32>,
|
||||
lights: vec4<u32>,
|
||||
light_pow: vec4<f32>,
|
||||
expo: vec4<f32>,
|
||||
};
|
||||
"#
|
||||
};
|
||||
}
|
||||
pub(crate) use wgsl_params;
|
||||
|
||||
/// Compute-Shader der Pfadverfolgung: ein Sample je Pixel, aufaddiert in `accum` (rgb Summe, w Zahl).
|
||||
pub const PT_WGSL: &str = concat!(wgsl_params!(), r#"
|
||||
struct Node { bmin: vec3<f32>, left_first: u32, bmax: vec3<f32>, count: u32 };
|
||||
struct Tri { v0: vec3<f32>, mat: u32, e1: vec3<f32>, rough: f32, e2: vec3<f32>, metal: f32 };
|
||||
// Texturdaten je Dreieck (parallel zu `tris`, `bvh::GpuTriTex`): UV der Ecken (m), Ebene | Prozedur << 16, 1/Kachel.
|
||||
@@ -256,6 +352,8 @@ struct TriTex { uv0: vec2<f32>, uv1: vec2<f32>, uv2: vec2<f32>, tex: u32, scale:
|
||||
@group(1) @binding(1) var mat_samp: sampler;
|
||||
@group(1) @binding(2) var<storage, read> layer_inv: array<vec4<f32>>;
|
||||
@group(1) @binding(3) var det_tex: texture_2d_array<f32>;
|
||||
// Etappe 5: Lichtliste (Dreiecks-Indizes; Bereiche Portale | Leuchten | Raumlicht, Zahlen in `P.lights`).
|
||||
@group(0) @binding(7) var<storage, read> light_idx: array<u32>;
|
||||
|
||||
const NONE: u32 = 0xffffffffu;
|
||||
const MISS: f32 = 1e30;
|
||||
@@ -272,20 +370,41 @@ const MAX_GLASS: u32 = 8u;
|
||||
const GLASS_SHADOW_T: f32 = 0.9;
|
||||
// Strahldichte einer Leuchte je Einheit Grundfarbe.
|
||||
const EMISSION: f32 = 1.0;
|
||||
// Farbe des Innenlichts bei Nacht (warmweiss, ≈ 2700 K).
|
||||
// Farbe des Raumlichts bei Nacht (warmweiss, ≈ 2700 K; `pathtrace::ROOM_RGB`).
|
||||
const ROOM_RGB: vec3<f32> = vec3<f32>(1.0, 0.72, 0.42);
|
||||
// Bildkarten bis zu diesem Abpraller (0 = Blickstrahl, 1 = erster Abpraller), danach Grundfarbe = Kartenmittel.
|
||||
const TEX_BOUNCES: u32 = 2u;
|
||||
// Kegelöffnung nach einem diffusen Abpraller (`pt_texture::DIFFUSE_SPREAD`).
|
||||
const DIFFUSE_SPREAD: f32 = 0.3;
|
||||
// Etappe 5 (`pt_lights.rs`): Arten der Lichtliste, Bit „gelistet“ in `TriTex.tex`, Schalter in `P.lights.w`.
|
||||
const L_PORTAL: u32 = 0u;
|
||||
const L_EMIT: u32 = 1u;
|
||||
const L_CEIL: u32 = 2u;
|
||||
const LISTED: u32 = 0x2000000u;
|
||||
const F_NO_TEX: u32 = 16u;
|
||||
const LUM: vec3<f32> = vec3<f32>(0.2126, 0.7152, 0.0722);
|
||||
// Strahlverfolgung: nächster Treffer; Sonne (beliebiger Treffer, Glas × GLASS_SHADOW_T); Strecke bis tmax (Glas wie
|
||||
// im Pfad durchlässig, `sh_rgb`); Portal (bis ins Unendliche, dazu die Licht-Dichte der gekreuzten Portale `sh_pdf`).
|
||||
const MODE_CLOSEST: u32 = 0u;
|
||||
const MODE_SUN: u32 = 1u;
|
||||
const MODE_SEG: u32 = 2u;
|
||||
const MODE_PORTAL: u32 = 3u;
|
||||
|
||||
var<private> rng: u32;
|
||||
// Erster Treffer des Blickstrahls (für den Entrauscher): Albedo, Normale (zur Kamera), Tiefe; Himmel = (1, 0, 0).
|
||||
var<private> g_albedo: vec3<f32>;
|
||||
var<private> g_normal: vec3<f32>;
|
||||
var<private> g_depth: f32;
|
||||
// Durchlass der zuletzt verfolgten Schattenstrahlen durch Glas (`trace` mit `shadow`).
|
||||
// Durchlass der zuletzt verfolgten Schattenstrahlen durch Glas (`trace` im Modus Sonne).
|
||||
var<private> sh_tr: f32;
|
||||
// Modus Strecke/Portal: Durchlass (wie der Pfad durch Glas) und Summe der Portal-Dichten (ohne 1/W).
|
||||
var<private> sh_rgb: vec3<f32>;
|
||||
var<private> sh_pdf: f32;
|
||||
// Empfänger der Lichtwahl (Punkt, geometrische Normale) für `sh_pdf`.
|
||||
var<private> rc_p: vec3<f32>;
|
||||
var<private> rc_n: vec3<f32>;
|
||||
// Summe der Auswahlgewichte W der letzten Lichtwahl (`nee_lights`; 0 = keine).
|
||||
var<private> nee_w: f32;
|
||||
|
||||
fn pcg(v: u32) -> u32 {
|
||||
let s = v * 747796405u + 2891336453u;
|
||||
@@ -326,20 +445,37 @@ fn tri_hit(tr: Tri, o: vec3<f32>, d: vec3<f32>, tmax: f32) -> f32 {
|
||||
return -1.0;
|
||||
}
|
||||
|
||||
// Nächster Treffer; `shadow` = beliebiger Treffer (Glas durchsichtig), Abbruch beim ersten.
|
||||
fn trace(o: vec3<f32>, d: vec3<f32>, shadow: bool) -> Hit {
|
||||
// Durchlass einer Glasfläche (dünne Scheibe: Fresnel beider Grenzflächen, leichte Tönung) — derselbe Faktor im Pfad
|
||||
// und in den Schattenstrahlen der Lichtwahl (sonst wichen die beiden MIS-Wege voneinander ab).
|
||||
fn glass_t(tr: Tri, d: vec3<f32>) -> vec3<f32> {
|
||||
let nn = normalize(cross(tr.e1, tr.e2));
|
||||
let f = fresnel(vec3<f32>(0.04), abs(dot(d, nn))).x;
|
||||
let rt = 2.0 * f / (1.0 + f);
|
||||
let a = unpack_albedo(tr.mat);
|
||||
let tint = a / max(max(a.x, max(a.y, a.z)), 1e-3);
|
||||
return (1.0 - rt) * mix(vec3<f32>(1.0), tint, 0.15);
|
||||
}
|
||||
|
||||
// Strahl (o, d) bis `tmax` im Modus `mode` (s. MODE_*). Ausser MODE_CLOSEST endet er am ersten undurchsichtigen
|
||||
// Treffer (Rückgabe mit `tri` ≠ NONE = verdeckt); Glas hält ihn nicht auf (jedes Dreieck nur einmal im Baum).
|
||||
fn trace(o: vec3<f32>, d: vec3<f32>, mode: u32, tmax: f32) -> Hit {
|
||||
var h: Hit;
|
||||
h.t = MISS;
|
||||
h.t = tmax;
|
||||
h.tri = NONE;
|
||||
sh_tr = 1.0;
|
||||
if (P.info.x == 0u) { return h; }
|
||||
sh_rgb = vec3<f32>(1.0);
|
||||
sh_pdf = 0.0;
|
||||
if (P.info.x == 0u) { h.t = MISS; return h; }
|
||||
let shadow = mode != MODE_CLOSEST;
|
||||
let inv = vec3<f32>(
|
||||
select(select(1e30, -1e30, d.x < 0.0), 1.0 / d.x, abs(d.x) > 1e-20),
|
||||
select(select(1e30, -1e30, d.y < 0.0), 1.0 / d.y, abs(d.y) > 1e-20),
|
||||
select(select(1e30, -1e30, d.z < 0.0), 1.0 / d.z, abs(d.z) > 1e-20));
|
||||
let root = nodes[0];
|
||||
if (box_hit(root.bmin, root.bmax, o, inv, h.t) >= MISS) { return h; }
|
||||
var stack: array<u32, 64>;
|
||||
if (box_hit(root.bmin, root.bmax, o, inv, h.t) >= MISS) { h.t = MISS; return h; }
|
||||
// Stapel mit Eintrittsabstand: ein zurückgestellter Knoten hinter dem inzwischen gefundenen Treffer wird
|
||||
// übersprungen, ohne ihn zu laden (Etappe 5).
|
||||
var stack: array<vec2<u32>, 64>;
|
||||
var sp: u32 = 0u;
|
||||
var ni: u32 = 0u;
|
||||
loop {
|
||||
@@ -348,8 +484,18 @@ fn trace(o: vec3<f32>, d: vec3<f32>, shadow: bool) -> Hit {
|
||||
for (var i = n.left_first; i < n.left_first + n.count; i = i + 1u) {
|
||||
let tr = tris[i];
|
||||
if (shadow && (tr.mat >> 24u) == MAT_GLASS) {
|
||||
// Glas dämpft den Schattenstrahl, hält ihn aber nicht auf (jedes Dreieck nur einmal im Baum).
|
||||
if (tri_hit(tr, o, d, MISS) > 0.0) { sh_tr = sh_tr * GLASS_SHADOW_T; }
|
||||
// Glas dämpft den Schattenstrahl, hält ihn aber nicht auf.
|
||||
let tg = tri_hit(tr, o, d, h.t);
|
||||
if (tg > 0.0) {
|
||||
if (mode == MODE_SUN) {
|
||||
sh_tr = sh_tr * GLASS_SHADOW_T;
|
||||
} else {
|
||||
sh_rgb = sh_rgb * glass_t(tr, d);
|
||||
if (mode == MODE_PORTAL && (tri_tex[i].tex & LISTED) != 0u) {
|
||||
sh_pdf = sh_pdf + portal_pdf(tr, o + d * tg, d);
|
||||
}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let t = tri_hit(tr, o, d, h.t);
|
||||
@@ -359,33 +505,41 @@ fn trace(o: vec3<f32>, d: vec3<f32>, shadow: bool) -> Hit {
|
||||
if (shadow) { return h; }
|
||||
}
|
||||
}
|
||||
} else {
|
||||
var c0 = n.left_first;
|
||||
var c1 = c0 + 1u;
|
||||
let n0 = nodes[c0];
|
||||
let n1 = nodes[c1];
|
||||
var t0 = box_hit(n0.bmin, n0.bmax, o, inv, h.t);
|
||||
var t1 = box_hit(n1.bmin, n1.bmax, o, inv, h.t);
|
||||
if (t1 < t0) {
|
||||
let tt = t0; t0 = t1; t1 = tt;
|
||||
let cc = c0; c0 = c1; c1 = cc;
|
||||
}
|
||||
if (t0 < MISS) {
|
||||
ni = c0;
|
||||
if (t1 < MISS && sp < 64u) {
|
||||
stack[sp] = vec2<u32>(c1, bitcast<u32>(t1));
|
||||
sp = sp + 1u;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// Nächsten zurückgestellten Knoten holen, der noch vor dem Treffer beginnt.
|
||||
var found = false;
|
||||
loop {
|
||||
if (sp == 0u) { break; }
|
||||
sp = sp - 1u;
|
||||
ni = stack[sp];
|
||||
continue;
|
||||
}
|
||||
var c0 = n.left_first;
|
||||
var c1 = c0 + 1u;
|
||||
let n0 = nodes[c0];
|
||||
let n1 = nodes[c1];
|
||||
var t0 = box_hit(n0.bmin, n0.bmax, o, inv, h.t);
|
||||
var t1 = box_hit(n1.bmin, n1.bmax, o, inv, h.t);
|
||||
if (t1 < t0) {
|
||||
let tt = t0; t0 = t1; t1 = tt;
|
||||
let cc = c0; c0 = c1; c1 = cc;
|
||||
}
|
||||
if (t0 >= MISS) {
|
||||
if (sp == 0u) { break; }
|
||||
sp = sp - 1u;
|
||||
ni = stack[sp];
|
||||
continue;
|
||||
}
|
||||
ni = c0;
|
||||
if (t1 < MISS && sp < 64u) {
|
||||
stack[sp] = c1;
|
||||
sp = sp + 1u;
|
||||
let e = stack[sp];
|
||||
if (bitcast<f32>(e.y) <= h.t) {
|
||||
ni = e.x;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) { break; }
|
||||
}
|
||||
if (h.tri == NONE) { h.t = MISS; }
|
||||
return h;
|
||||
}
|
||||
|
||||
@@ -609,6 +763,134 @@ fn brdf(kind: u32, albedo: vec3<f32>, rough: f32, metal: f32, n: vec3<f32>, wo:
|
||||
return diffuse;
|
||||
}
|
||||
|
||||
// Dichte der BRDF-Wahl (Raumwinkel) für die Richtung wi — dieselbe Mischung wie die Richtungswahl in `radiance`
|
||||
// (glänzend: Spiegel-Lobe mit `p_spec`, sonst Kosinus).
|
||||
fn bsdf_pdf(kind: u32, rough: f32, ns: vec3<f32>, wo: vec3<f32>, wi: vec3<f32>, p_spec: f32) -> f32 {
|
||||
let pd = max(dot(ns, wi), 0.0) / PI;
|
||||
if (kind != MAT_GLOSSY) { return pd; }
|
||||
let a = max(rough * rough, 0.002);
|
||||
let h = normalize(wo + wi);
|
||||
let noh = max(dot(ns, h), 1e-4);
|
||||
let voh = max(dot(wo, h), 1e-4);
|
||||
return p_spec * ggx_d(noh, a) * noh / (4.0 * voh) + (1.0 - p_spec) * pd;
|
||||
}
|
||||
|
||||
// Auswahlgewicht eines Lichts für den Empfänger p (geometrische Normale n), 1:1 `pt_lights::light_weight`.
|
||||
fn lweight(tr: Tri, k: u32, p: vec3<f32>, n: vec3<f32>) -> f32 {
|
||||
let v1 = tr.v0 + tr.e1;
|
||||
let v2 = tr.v0 + tr.e2;
|
||||
let front = max(dot(tr.v0 - p, n), max(dot(v1 - p, n), dot(v2 - p, n)));
|
||||
if (!(front > 0.0)) { return 0.0; }
|
||||
let cr = cross(tr.e1, tr.e2);
|
||||
let len = length(cr);
|
||||
if (!(len > 1e-12)) { return 0.0; }
|
||||
let area = 0.5 * len;
|
||||
let nl = cr / len;
|
||||
var power = P.light_pow.x;
|
||||
if (k == L_CEIL) {
|
||||
let nd = select(nl, -nl, nl.y > 0.0);
|
||||
if (!(dot(p - tr.v0, nd) > 0.0)) { return 0.0; }
|
||||
power = P.light_pow.y;
|
||||
} else if (k == L_EMIT) {
|
||||
power = max(dot(unpack_albedo(tr.mat) * EMISSION, LUM), 1e-4);
|
||||
}
|
||||
let dv = tr.v0 + (tr.e1 + tr.e2) * (1.0 / 3.0) - p;
|
||||
let d2 = max(dot(dv, dv), 1e-12);
|
||||
let d = sqrt(d2);
|
||||
let cl = abs(dot(nl, dv)) / d;
|
||||
let crr = max(dot(n, dv) / d, 0.0);
|
||||
return power * area * max(cl, 0.1) / max(d2, area) * (0.25 + crr);
|
||||
}
|
||||
|
||||
fn light_on(k: u32) -> bool {
|
||||
return (P.lights.w & (1u << k)) != 0u;
|
||||
}
|
||||
|
||||
// Licht-Dichte (ohne 1/W) eines gekreuzten Portals für den Empfänger `rc_p`/`rc_n`: w · d² / (cos · A).
|
||||
fn portal_pdf(tr: Tri, y: vec3<f32>, d: vec3<f32>) -> f32 {
|
||||
let cr = cross(tr.e1, tr.e2);
|
||||
let len = length(cr);
|
||||
if (!(len > 1e-12)) { return 0.0; }
|
||||
let cl = abs(dot(cr, d)) / len;
|
||||
if (cl < 1e-4) { return 0.0; }
|
||||
let dd = y - rc_p;
|
||||
return lweight(tr, L_PORTAL, rc_p, rc_n) * dot(dd, dd) / (cl * 0.5 * len);
|
||||
}
|
||||
|
||||
// Next-Event-Estimation auf die Lichtliste (Etappe 5, `pt_lights.rs`): ein Licht nach Gewicht wählen (ein Durchgang,
|
||||
// Reservoir mit einer Zufallszahl), Punkt gleichverteilt darauf, Schattenstrahl; Portale bringen den Himmel dahinter,
|
||||
// Leuchten ihre Farbe (beide mit Power-Heuristik gegen die BRDF), das Raumlicht ist nur hierüber sichtbar. Rückgabe ohne
|
||||
// Pfad-Durchsatz; setzt `nee_w` (Summe der Gewichte) für die MIS des nächsten BRDF-Strahls. `last` = letzte Ecke des
|
||||
// Pfades (kein BRDF-Strahl mehr): volles Gewicht für die Lichtwahl.
|
||||
fn nee_lights(p: vec3<f32>, n: vec3<f32>, ns: vec3<f32>, wo: vec3<f32>, kind: u32, albedo: vec3<f32>, rough: f32, metal: f32, p_spec: f32, eps: f32, last: bool) -> vec3<f32> {
|
||||
nee_w = 0.0;
|
||||
if ((P.lights.w & 7u) == 0u) { return vec3<f32>(0.0); }
|
||||
var u = rnd();
|
||||
var wsum = 0.0;
|
||||
var pick = NONE;
|
||||
var pw = 0.0;
|
||||
var pk = 0u;
|
||||
var start = 0u;
|
||||
for (var k = 0u; k < 3u; k = k + 1u) {
|
||||
let cnt = P.lights[k];
|
||||
if (light_on(k)) {
|
||||
for (var i = start; i < start + cnt; i = i + 1u) {
|
||||
let w = lweight(tris[light_idx[i]], k, p, n);
|
||||
if (w > 0.0) {
|
||||
wsum = wsum + w;
|
||||
let pr = w / wsum;
|
||||
if (u < pr) {
|
||||
pick = i;
|
||||
pw = w;
|
||||
pk = k;
|
||||
u = u / pr;
|
||||
} else {
|
||||
u = (u - pr) / max(1.0 - pr, 1e-7);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
start = start + cnt;
|
||||
}
|
||||
nee_w = wsum;
|
||||
if (pick == NONE) { return vec3<f32>(0.0); }
|
||||
let tr = tris[light_idx[pick]];
|
||||
let r1 = rnd();
|
||||
let r2 = rnd();
|
||||
let sq = sqrt(r1);
|
||||
let y = tr.v0 + tr.e1 * (sq * (1.0 - r2)) + tr.e2 * (sq * r2);
|
||||
let dv = y - p;
|
||||
let dist = length(dv);
|
||||
if (!(dist > 1e-5)) { return vec3<f32>(0.0); }
|
||||
let wi = dv / dist;
|
||||
let ndl = dot(ns, wi);
|
||||
if (ndl <= 0.0 || dot(n, wi) <= 0.0) { return vec3<f32>(0.0); }
|
||||
let cr = cross(tr.e1, tr.e2);
|
||||
let len = length(cr);
|
||||
let nl = cr / len;
|
||||
let cl = abs(dot(nl, wi));
|
||||
if (cl < 1e-4) { return vec3<f32>(0.0); }
|
||||
let own = pw * dist * dist / (cl * 0.5 * len);
|
||||
let f = brdf(kind, albedo, rough, metal, ns, wo, wi) * ndl;
|
||||
let o = p + n * eps;
|
||||
rc_p = p;
|
||||
rc_n = n;
|
||||
if (pk == L_PORTAL) {
|
||||
if (trace(o, wi, MODE_PORTAL, MISS).tri != NONE) { return vec3<f32>(0.0); }
|
||||
let pl = max(sh_pdf, own) / wsum;
|
||||
let pb = select(bsdf_pdf(kind, rough, ns, wo, wi, p_spec), 0.0, last);
|
||||
return f * sky(wi, false, false) * sh_rgb * (pl / (pl * pl + pb * pb));
|
||||
}
|
||||
if (pk == L_CEIL && dot(select(nl, -nl, nl.y > 0.0), wi) >= 0.0) { return vec3<f32>(0.0); }
|
||||
if (trace(o, wi, MODE_SEG, max(dist - max(dist * 1e-3, 4.0 * eps), 0.0)).tri != NONE) { return vec3<f32>(0.0); }
|
||||
let pl = own / wsum;
|
||||
if (pk == L_EMIT) {
|
||||
let pb = select(bsdf_pdf(kind, rough, ns, wo, wi, p_spec), 0.0, last);
|
||||
return f * unpack_albedo(tr.mat) * EMISSION * sh_rgb * (pl / (pl * pl + pb * pb));
|
||||
}
|
||||
return f * ROOM_RGB * P.dn.y * sh_rgb / pl;
|
||||
}
|
||||
|
||||
// Himmel; `primary` = Blickstrahl: unter dem Horizont Dunst statt Boden (heller Hintergrund wie die übrigen Stile).
|
||||
fn sky(d: vec3<f32>, with_sun: bool, primary: bool) -> vec3<f32> {
|
||||
let s = P.sun_dir.xyz;
|
||||
@@ -630,20 +912,20 @@ fn sky(d: vec3<f32>, with_sun: bool, primary: bool) -> vec3<f32> {
|
||||
// getroffene Fläche mit Sonnenlicht (ein Schattenstrahl) und gleichmässigem Himmelslicht — statt Schwarz, wenn die
|
||||
// Spiegelung auf Boden oder Nachbarbau fällt (Blick von oben auf eine Fassade).
|
||||
fn reflected(o: vec3<f32>, d: vec3<f32>, cw: f32, cs: f32) -> vec3<f32> {
|
||||
let h = trace(o, d, false);
|
||||
let h = trace(o, d, MODE_CLOSEST, MISS);
|
||||
if (h.tri == NONE) { return sky(d, false, false); }
|
||||
let tr = tris[h.tri];
|
||||
if ((tr.mat >> 24u) == MAT_GLASS) { return sky(d, false, false); }
|
||||
var n = normalize(cross(tr.e1, tr.e2));
|
||||
if (dot(n, d) > 0.0) { n = -n; }
|
||||
let albedo = surface(h.tri, tr, o, d, n, cw + cs * h.t, true).albedo;
|
||||
let albedo = surface(h.tri, tr, o, d, n, cw + cs * h.t, (P.lights.w & F_NO_TEX) == 0u).albedo;
|
||||
if ((tr.mat >> 24u) == MAT_EMISSIVE) { return albedo * EMISSION; }
|
||||
let p = o + d * h.t;
|
||||
let eps = 1e-4 * max(1.0, max(abs(p.x), max(abs(p.y), abs(p.z))));
|
||||
var c = albedo * (0.5 * (P.sky_zenith.rgb + P.sky_horizon.rgb)) * (0.5 + 0.5 * max(n.y, 0.0));
|
||||
if (P.sun_irr.w > 0.5) {
|
||||
let ndl = dot(n, P.sun_dir.xyz);
|
||||
if (ndl > 0.0 && trace(p + n * eps, P.sun_dir.xyz, true).tri == NONE) {
|
||||
if (ndl > 0.0 && trace(p + n * eps, P.sun_dir.xyz, MODE_SUN, MISS).tri == NONE) {
|
||||
c = c + albedo * (1.0 / PI) * P.sun_irr.rgb * ndl * sh_tr;
|
||||
}
|
||||
}
|
||||
@@ -663,14 +945,24 @@ fn radiance(o_in: vec3<f32>, d_in: vec3<f32>, cw0: f32, cs0: f32) -> vec3<f32> {
|
||||
var b = 0u;
|
||||
var glass_n = 0u;
|
||||
var albedo_set = false;
|
||||
// MIS-Zustand der letzten Ecke mit Lichtwahl (Etappe 5): W, Punkt, Normale, BRDF-Dichte der gewählten Richtung,
|
||||
// gesammelte Portal-Dichte der seither gekreuzten Scheiben.
|
||||
var mis_w = 0.0;
|
||||
var mis_p = vec3<f32>(0.0);
|
||||
var mis_n = vec3<f32>(0.0);
|
||||
var mis_pb = 0.0;
|
||||
var mis_pl = 0.0;
|
||||
g_albedo = vec3<f32>(1.0);
|
||||
g_normal = vec3<f32>(0.0);
|
||||
g_depth = 0.0;
|
||||
loop {
|
||||
if (b >= P.dims.w) { break; }
|
||||
let h = trace(o, d, false);
|
||||
let h = trace(o, d, MODE_CLOSEST, MISS);
|
||||
if (h.tri == NONE) {
|
||||
l = l + tp * sky(d, specular, b == 0u);
|
||||
// Himmel durch Portale: BRDF-Anteil der Power-Heuristik gegen die Lichtwahl der letzten Ecke.
|
||||
var wgt = 1.0;
|
||||
if (mis_w > 0.0 && mis_pl > 0.0) { wgt = mis_pb * mis_pb / (mis_pb * mis_pb + mis_pl * mis_pl); }
|
||||
l = l + tp * sky(d, specular, b == 0u) * wgt;
|
||||
break;
|
||||
}
|
||||
let tr = tris[h.tri];
|
||||
@@ -678,7 +970,7 @@ fn radiance(o_in: vec3<f32>, d_in: vec3<f32>, cw0: f32, cs0: f32) -> vec3<f32> {
|
||||
var n = normalize(cross(tr.e1, tr.e2));
|
||||
if (dot(n, d) > 0.0) { n = -n; }
|
||||
let w = cw + cs * h.t;
|
||||
let sf = surface(h.tri, tr, o, d, n, w, b < TEX_BOUNCES);
|
||||
let sf = surface(h.tri, tr, o, d, n, w, b < TEX_BOUNCES && (P.lights.w & F_NO_TEX) == 0u);
|
||||
let albedo = sf.albedo;
|
||||
let ns = sf.n;
|
||||
let p = o + d * h.t;
|
||||
@@ -694,11 +986,23 @@ fn radiance(o_in: vec3<f32>, d_in: vec3<f32>, cw0: f32, cs0: f32) -> vec3<f32> {
|
||||
albedo_set = true;
|
||||
g_albedo = albedo;
|
||||
}
|
||||
let listed = (tri_tex[h.tri].tex & LISTED) != 0u;
|
||||
if (kind == MAT_EMISSIVE) {
|
||||
l = l + tp * albedo * EMISSION;
|
||||
var wgt = 1.0;
|
||||
if (mis_w > 0.0 && listed && light_on(L_EMIT)) {
|
||||
let cr = cross(tr.e1, tr.e2);
|
||||
let pl = lweight(tr, L_EMIT, mis_p, mis_n) / mis_w * dot(p - mis_p, p - mis_p) / max(abs(dot(cr, d)) * 0.5, 1e-12);
|
||||
wgt = mis_pb * mis_pb / (mis_pb * mis_pb + pl * pl);
|
||||
}
|
||||
l = l + tp * albedo * EMISSION * wgt;
|
||||
break;
|
||||
}
|
||||
if (kind == MAT_GLASS) {
|
||||
if (mis_w > 0.0 && listed && light_on(L_PORTAL)) {
|
||||
rc_p = mis_p;
|
||||
rc_n = mis_n;
|
||||
mis_pl = mis_pl + portal_pdf(tr, p, d) / mis_w;
|
||||
}
|
||||
// Dünne Scheibe: Spiegelung mit Fresnel (beide Grenzflächen) fest als Anteil statt Zufallswahl (kein
|
||||
// Salz-und-Pfeffer-Rauschen), ausgewertet ohne weiteren Pfad (`reflected`); der Rest geht leicht getönt
|
||||
// durch. Durchgänge zählen nicht als Abpraller und nicht für Russian Roulette.
|
||||
@@ -706,8 +1010,7 @@ fn radiance(o_in: vec3<f32>, d_in: vec3<f32>, cw0: f32, cs0: f32) -> vec3<f32> {
|
||||
let rt = 2.0 * f / (1.0 + f);
|
||||
let rd = reflect(d, n);
|
||||
l = l + tp * rt * reflected(p + n * eps, rd, w, cs);
|
||||
let tint = albedo / max(max(albedo.x, max(albedo.y, albedo.z)), 1e-3);
|
||||
tp = tp * (1.0 - rt) * mix(vec3<f32>(1.0), tint, 0.15);
|
||||
tp = tp * glass_t(tr, d);
|
||||
o = p - n * eps;
|
||||
cw = w;
|
||||
glass_n = glass_n + 1u;
|
||||
@@ -720,23 +1023,21 @@ fn radiance(o_in: vec3<f32>, d_in: vec3<f32>, cw0: f32, cs0: f32) -> vec3<f32> {
|
||||
let ls = cone_dir(P.sun_dir.xyz, P.sun_dir.w);
|
||||
let ndl = dot(ns, ls);
|
||||
if (ndl > 0.0 && dot(n, ls) > 0.0) {
|
||||
let sh = trace(p + n * eps, ls, true);
|
||||
let sh = trace(p + n * eps, ls, MODE_SUN, MISS);
|
||||
if (sh.tri == NONE) {
|
||||
l = l + tp * brdf(kind, albedo, sf.rough, tr.metal, ns, wo, ls) * P.sun_irr.rgb * ndl * sh_tr;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Nacht: warmes Innenlicht auf Flächen, die der Pfad durch Glas erreicht hat (erleuchtete Räume, Licht, das
|
||||
// aus den Fenstern auf Boden und Fassade fällt).
|
||||
if (P.dn.y > 0.0 && glass_n > 0u) {
|
||||
l = l + tp * albedo * ROOM_RGB * P.dn.y;
|
||||
}
|
||||
// Nächste Richtung. Glänzend: Spiegel-Lobe mit Wahrscheinlichkeit nach Fresnel (Metall: immer) wählen, sonst
|
||||
// diffus (Gewicht / Wahl).
|
||||
let nov0 = max(dot(ns, wo), 1e-4);
|
||||
let f0 = spec_f0(albedo, tr.metal);
|
||||
let p_d = clamp(fresnel(vec3<f32>(0.04), nov0).x * 4.0, 0.1, 0.9);
|
||||
let p_spec = select(0.0, clamp(mix(p_d, 1.0, tr.metal), 0.1, 1.0), kind == MAT_GLOSSY);
|
||||
// Etappe 5: Lichtwahl (Fenster als Portale des Himmels, Leuchten, Raumlicht bei Nacht).
|
||||
l = l + tp * nee_lights(p, n, ns, wo, kind, albedo, sf.rough, tr.metal, p_spec, eps, b + 1u >= P.dims.w);
|
||||
let w_lights = nee_w;
|
||||
if (kind == MAT_GLOSSY && rnd() < p_spec) {
|
||||
let a = max(sf.rough * sf.rough, 0.002);
|
||||
let r1 = rnd();
|
||||
@@ -763,6 +1064,11 @@ fn radiance(o_in: vec3<f32>, d_in: vec3<f32>, cw0: f32, cs0: f32) -> vec3<f32> {
|
||||
if (kind == MAT_GLOSSY) { tp = tp * (1.0 - 0.04) * (1.0 - tr.metal); }
|
||||
cs = max(cs, DIFFUSE_SPREAD);
|
||||
}
|
||||
mis_w = w_lights;
|
||||
mis_p = p;
|
||||
mis_n = n;
|
||||
mis_pb = bsdf_pdf(kind, sf.rough, ns, wo, d, p_spec);
|
||||
mis_pl = 0.0;
|
||||
cw = w;
|
||||
o = p + n * eps;
|
||||
specular = false;
|
||||
@@ -817,30 +1123,18 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
||||
aux_a[idx] = pa + vec4<f32>(g_albedo, lu * lu);
|
||||
aux_b[idx] = pb + vec4<f32>(g_normal, g_depth);
|
||||
}
|
||||
"#;
|
||||
"#);
|
||||
|
||||
/// Anzeige: Vollbild-Dreieck, liest die Akkumulation (bilinear auf die Anzeigegrösse), Mittel, Belichtung,
|
||||
/// ACES (Narkowicz 2015) und — bei Ziel ohne sRGB-Format (WebGPU-Canvas) — sRGB-Kodierung.
|
||||
pub const PT_DISPLAY_WGSL: &str = r#"
|
||||
struct Params {
|
||||
cam_pos: vec4<f32>,
|
||||
cam_fwd: vec4<f32>,
|
||||
cam_right: vec4<f32>,
|
||||
cam_up: vec4<f32>,
|
||||
sun_dir: vec4<f32>,
|
||||
sun_irr: vec4<f32>,
|
||||
sky_zenith: vec4<f32>,
|
||||
sky_horizon: vec4<f32>,
|
||||
ground: vec4<f32>,
|
||||
dims: vec4<u32>,
|
||||
info: vec4<u32>,
|
||||
dn: vec4<f32>,
|
||||
};
|
||||
pub const PT_DISPLAY_WGSL: &str = concat!(wgsl_params!(), r#"
|
||||
@group(0) @binding(0) var<uniform> P: Params;
|
||||
@group(0) @binding(1) var<storage, read> accum: array<vec4<f32>>;
|
||||
// Entrauscher ([212] Etappe 2): gefiltertes Licht (`denoise.rs`) und Albedo-Summe; Mischgewicht `P.dn.x`.
|
||||
@group(0) @binding(2) var<storage, read> filt: array<vec4<f32>>;
|
||||
@group(0) @binding(3) var<storage, read> aux_a: array<vec4<f32>>;
|
||||
// Etappe 5: Belichtung der Automatik (`exposure.rs`): x = aktuell, y = gültig.
|
||||
@group(0) @binding(4) var<storage, read> expo: array<vec4<f32>>;
|
||||
|
||||
@vertex
|
||||
fn vs_main(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {
|
||||
@@ -884,11 +1178,14 @@ fn fs_main(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let tx = fx - floor(fx);
|
||||
let ty = fy - floor(fy);
|
||||
let c = mix(mix(texel(x0, y0), texel(x0 + 1, y0), tx), mix(texel(x0, y0 + 1), texel(x0 + 1, y0 + 1), tx), ty);
|
||||
var m = aces(c * P.ground.w);
|
||||
// Belichtung: Automatik (nachgeführt, `exposure.rs`) oder die des Himmels, dazu die Korrektur 2^EV.
|
||||
var e = P.ground.w;
|
||||
if (P.expo.y > 0.0 && expo[0].y > 0.5) { e = expo[0].x; }
|
||||
var m = aces(c * (e * P.expo.x));
|
||||
if (P.info.w == 1u) { m = to_srgb(m); }
|
||||
return vec4<f32>(m, 1.0);
|
||||
}
|
||||
"#;
|
||||
"#);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -932,7 +1229,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn parameter_block_passt_zum_shader() {
|
||||
assert_eq!(std::mem::size_of::<PtParams>(), 192);
|
||||
assert_eq!(std::mem::size_of::<PtParams>(), 240);
|
||||
assert_eq!(std::mem::size_of::<crate::bvh::GpuNode>(), 32);
|
||||
assert_eq!(std::mem::size_of::<crate::bvh::GpuTri>(), 48);
|
||||
assert_eq!(std::mem::size_of::<crate::bvh::GpuTriTex>(), 32);
|
||||
@@ -958,7 +1255,21 @@ mod tests {
|
||||
// Innenlicht hinter Glas nur bei Nacht, im Parameter-Block dn.y.
|
||||
assert!(n.room_light > 0.0 && high.room_light == 0.0);
|
||||
let p = build_params(&Camera::default(), &n, (4, 4), (4, 4), 0, 1, false, 0.5).unwrap();
|
||||
assert_eq!(p.dn, [0.5, 0.0, 0.0, 0.0], "ohne Deckenlichter kein Raumlicht");
|
||||
// Etappe 5: Raumlicht nur mit Deckenlichtern, ohne Leuchten, eingeschaltet; Portale nur am Tag.
|
||||
let opt = |counts: [u32; 3], room: bool| PtOptions { light_counts: counts, room_light: room, ..PtOptions::default() };
|
||||
let p = build_params_with(&Camera::default(), &n, (4, 4), (4, 4), 0, 1, false, 0.5, &opt([3, 0, 2], true)).unwrap();
|
||||
assert_eq!(p.dn, [0.5, ROOM_LIGHT, 0.0, 0.0]);
|
||||
assert_eq!(p.lights, [3, 0, 2, F_EMITTERS | F_ROOM]);
|
||||
let off = build_params_with(&Camera::default(), &n, (4, 4), (4, 4), 0, 1, false, 0.5, &opt([3, 0, 2], false)).unwrap();
|
||||
assert_eq!((off.dn[1], off.lights[3]), (0.0, F_EMITTERS));
|
||||
let lamps = build_params_with(&Camera::default(), &n, (4, 4), (4, 4), 0, 1, false, 0.5, &opt([3, 1, 2], true)).unwrap();
|
||||
assert_eq!(lamps.lights[3], F_EMITTERS, "Leuchten im Modell: kein Raumlicht");
|
||||
let day = build_params_with(&Camera::default(), &high, (4, 4), (4, 4), 0, 1, false, 0.5, &opt([3, 0, 2], true)).unwrap();
|
||||
assert_eq!(day.lights[3], F_EMITTERS | F_PORTALS);
|
||||
assert!(day.light_pow[0] > 0.0 && day.expo[0] == 1.0 && day.expo[3] > day.expo[2]);
|
||||
let ev = build_params_with(&Camera::default(), &high, (4, 4), (4, 4), 0, 1, false, 0.5, &PtOptions { ev: 1.0, ..PtOptions::default() }).unwrap();
|
||||
assert_eq!(ev.expo[0], 2.0);
|
||||
assert!(n.zenith.iter().zip(&low.zenith).all(|(a, b)| a < b));
|
||||
// Keine/kaputte Sonne: bedeckt, ohne Sonne.
|
||||
for d in [None, Some([f32::NAN, 1.0, 0.0]), Some([0.0, -1.0, 0.0]), Some([0.0; 3])] {
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
// [212] Etappe 5: Lichtliste des Pathtracers für Next-Event-Estimation (NEE) auf Flächenlichter — Fensterscheiben als
|
||||
// Lichtportale des Himmels (wie das „Portal“ in Cycles), Leuchten (`MAT_EMISSIVE`) und bei Nacht ein einfaches Raumlicht
|
||||
// an den Deckenuntersichten jedes Geschosses. GPU-frei: die Liste entsteht auf der CPU aus dem gebauten Baum (`bvh.rs`),
|
||||
// die Auswahlgewichte hier sind 1:1 die des Shaders (`pathtrace::PT_WGSL`, `lweight`) und dienen den Tests als Referenz.
|
||||
//
|
||||
// Verfahren je Pfad-Ecke p (Normale n): ein Licht k wird mit Wahrscheinlichkeit w_k(p) / W(p) gewählt (w = geschätzter
|
||||
// Beitrag: Leistung · Raumwinkel · Empfänger-Kosinus, `light_weight`), darauf ein Punkt gleichverteilt auf dem Dreieck.
|
||||
// Die Dichte der Richtung ist für Leuchten P_k · d² / (cos θ_k · A_k); für Portale die Summe dieses Ausdrucks über ALLE
|
||||
// gelisteten Scheiben, die der Strahl auf dem Weg in den Himmel kreuzt (eine Scheibe hat zwei Flächen, Fenster liegen
|
||||
// hintereinander) — der Schattenstrahl zählt sie unterwegs. Mit der Dichte der BRDF-Wahl kombiniert die Power-Heuristik
|
||||
// (Veach 1997) beide Wege: trifft ein BRDF-Pfad durch Portale den Himmel oder trifft er eine Leuchte, rechnet der Shader
|
||||
// dieselbe Licht-Dichte vom letzten Punkt aus nach. Erwartungswert unverändert (Test `portal_nee_*`), Varianz im Raum viel
|
||||
// kleiner. Ein Licht, das nicht in der Liste steht (Obergrenzen unten), hat die Licht-Dichte 0 und wird wie bisher nur
|
||||
// über die BRDF gefunden — die Kombination bleibt erwartungstreu.
|
||||
//
|
||||
// Raumlicht (`LIGHT_CEILING`): nach unten gerichtete, waagrechte bis mässig geneigte Flächen (|n.y| ≥ 0.7) mit 1.8 … 6 m
|
||||
// freiem Raum darunter (Deckenuntersichten, Dachschrägen über Räumen; nicht die verdeckten Schichten im Deckenpaket, nicht
|
||||
// Tischplatten, nicht das Gelände) strahlen nur nach unten. Es ist ein reines NEE-Licht: für Blick- und BRDF-Strahlen
|
||||
// unsichtbar (die Decke selbst bleibt eine gewöhnliche Fläche), daher ohne MIS. Nur bei Nacht und nur, wenn das Modell
|
||||
// keine Leuchten kennt (`gpu_pathtrace`), abschaltbar.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::bvh::{Bvh, GpuTri, MAT_EMISSIVE, MAT_GLASS};
|
||||
|
||||
/// Art eines Lichts in der Liste (Reihenfolge der Bereiche im Index-Puffer).
|
||||
pub const LIGHT_PORTAL: u32 = 0;
|
||||
pub const LIGHT_EMITTER: u32 = 1;
|
||||
pub const LIGHT_CEILING: u32 = 2;
|
||||
|
||||
/// Obergrenzen je Art (der Shader läuft je Pfad-Ecke einmal über die eingeschalteten Bereiche).
|
||||
pub const MAX_PORTALS: usize = 256;
|
||||
pub const MAX_EMITTERS: usize = 128;
|
||||
pub const MAX_CEILINGS: usize = 256;
|
||||
/// Kleinere Glasflächen (Stirnseiten der Scheiben) sind keine Portale.
|
||||
pub const MIN_PORTAL_AREA: f32 = 0.01;
|
||||
/// Freier Raum unter einer Deckenuntersicht (m), damit sie Raumlicht wird.
|
||||
pub const CEILING_MIN_DROP: f32 = 1.8;
|
||||
pub const CEILING_MAX_DROP: f32 = 6.0;
|
||||
/// Bit in `GpuTriTex::tex`: Dreieck steht in der Lichtliste (Portal oder Leuchte; MIS im Shader).
|
||||
pub const LISTED_BIT: u32 = 1 << 25;
|
||||
|
||||
/// Lichtliste: Dreiecks-Indizes in den Baum (`Bvh::tris`), Bereiche [Portale | Leuchten | Decken].
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct LightList {
|
||||
pub idx: Vec<u32>,
|
||||
pub counts: [u32; 3],
|
||||
}
|
||||
|
||||
impl LightList {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.idx.is_empty()
|
||||
}
|
||||
/// Index-Bereich einer Art in `idx`.
|
||||
pub fn range(&self, kind: u32) -> std::ops::Range<usize> {
|
||||
let c = self.counts.map(|c| c as usize);
|
||||
match kind {
|
||||
LIGHT_PORTAL => 0..c[0],
|
||||
LIGHT_EMITTER => c[0]..c[0] + c[1],
|
||||
_ => c[0] + c[1]..c[0] + c[1] + c[2],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sub(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
|
||||
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
|
||||
}
|
||||
fn add(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
|
||||
[a[0] + b[0], a[1] + b[1], a[2] + b[2]]
|
||||
}
|
||||
fn scale(a: [f32; 3], s: f32) -> [f32; 3] {
|
||||
[a[0] * s, a[1] * s, a[2] * s]
|
||||
}
|
||||
fn cross(a: [f32; 3], b: [f32; 3]) -> [f32; 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]]
|
||||
}
|
||||
fn dot(a: [f32; 3], b: [f32; 3]) -> f32 {
|
||||
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
|
||||
}
|
||||
|
||||
/// Fläche und Einheitsnormale (Windung des Baums) eines Dreiecks; None bei entartetem.
|
||||
pub fn tri_area_normal(t: &GpuTri) -> Option<(f32, [f32; 3])> {
|
||||
let c = cross(t.e1, t.e2);
|
||||
let len = dot(c, c).sqrt();
|
||||
(len.is_finite() && len > 1e-12).then(|| (0.5 * len, scale(c, 1.0 / len)))
|
||||
}
|
||||
|
||||
/// Auswahlgewicht eines Lichts für den Empfänger p mit (geometrischer) Normale n — 1:1 `lweight` im Shader. 0 nur, wenn
|
||||
/// das Licht sicher nichts beiträgt (alle Ecken hinter der Empfängerfläche; Raumlicht: p nicht unter der Decke), sonst
|
||||
/// > 0 (MIS bleibt erwartungstreu). `power` = Leistung je Strahldichte-Einheit der Art (Himmel, Leuchtfarbe, Raumlicht).
|
||||
pub fn light_weight(t: &GpuTri, kind: u32, power: f32, p: [f32; 3], n: [f32; 3]) -> f32 {
|
||||
let v1 = add(t.v0, t.e1);
|
||||
let v2 = add(t.v0, t.e2);
|
||||
let front = dot(sub(t.v0, p), n).max(dot(sub(v1, p), n)).max(dot(sub(v2, p), n));
|
||||
if !(front > 0.0) {
|
||||
return 0.0;
|
||||
}
|
||||
let Some((area, nl)) = tri_area_normal(t) else { return 0.0 };
|
||||
if kind == LIGHT_CEILING {
|
||||
let nd = if nl[1] > 0.0 { scale(nl, -1.0) } else { nl };
|
||||
if !(dot(sub(p, t.v0), nd) > 0.0) {
|
||||
return 0.0;
|
||||
}
|
||||
}
|
||||
let c = add(t.v0, scale(add(t.e1, t.e2), 1.0 / 3.0));
|
||||
let dv = sub(c, p);
|
||||
let d2 = dot(dv, dv).max(1e-12);
|
||||
let d = d2.sqrt();
|
||||
let cl = dot(nl, dv).abs() / d;
|
||||
let cr = (dot(n, dv) / d).max(0.0);
|
||||
power * area * cl.max(0.1) / d2.max(area) * (0.25 + cr)
|
||||
}
|
||||
|
||||
/// Punkt auf dem Dreieck aus zwei Zufallszahlen (gleichverteilt, wie der Shader).
|
||||
pub fn sample_point(t: &GpuTri, r1: f32, r2: f32) -> [f32; 3] {
|
||||
let s = r1.max(0.0).sqrt();
|
||||
add(t.v0, add(scale(t.e1, s * (1.0 - r2)), scale(t.e2, s * r2)))
|
||||
}
|
||||
|
||||
/// Dichte (Raumwinkel) der Richtung zu einem Punkt im Abstand `dist` auf Licht `t` bei Wahl-Wahrscheinlichkeit `pick`.
|
||||
pub fn solid_angle_pdf(t: &GpuTri, pick: f32, dist: f32, dir: [f32; 3]) -> f32 {
|
||||
let Some((area, nl)) = tri_area_normal(t) else { return 0.0 };
|
||||
let cl = dot(nl, dir).abs();
|
||||
if cl < 1e-6 {
|
||||
return 0.0;
|
||||
}
|
||||
pick * dist * dist / (cl * area)
|
||||
}
|
||||
|
||||
/// Schlüssel einer Glasfläche unabhängig von der Seite der Scheibe: Ebenen-Richtung und der in die Ebene projizierte
|
||||
/// Umriss (1 cm Raster). Vorder- und Rückseite einer Scheibe (Abstand Millimeter) haben denselben Schlüssel.
|
||||
fn pane_key(t: &GpuTri, nl: [f32; 3]) -> Option<[i64; 8]> {
|
||||
let mut n = nl;
|
||||
let first = n.iter().copied().find(|c| c.abs() > 1e-3).unwrap_or(1.0);
|
||||
if first < 0.0 {
|
||||
n = scale(n, -1.0);
|
||||
}
|
||||
let a = if n[0].abs() < 0.9 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] };
|
||||
let u = cross(n, a);
|
||||
let ul = dot(u, u).sqrt();
|
||||
if !(ul > 1e-9) {
|
||||
return None;
|
||||
}
|
||||
let u = scale(u, 1.0 / ul);
|
||||
let v = cross(n, u);
|
||||
let q = |x: f32| (x as f64 * 100.0).round() as i64;
|
||||
let mut pts = [t.v0, add(t.v0, t.e1), add(t.v0, t.e2)].map(|p| [q(dot(p, u)), q(dot(p, v))]);
|
||||
pts.sort();
|
||||
let nq = n.map(|c| (c as f64 * 100.0).round() as i64);
|
||||
Some([nq[0], nq[1], pts[0][0], pts[0][1], pts[1][0], pts[1][1], pts[2][0] * 1_000_003 + pts[2][1], nq[2]])
|
||||
}
|
||||
|
||||
/// Freier Fall unter einem Punkt (m) bis zur nächsten Fläche; None = nichts darunter.
|
||||
fn drop_below(bvh: &Bvh, q: [f32; 3]) -> Option<f32> {
|
||||
bvh.intersect([q[0], q[1] - 1e-3, q[2]], [0.0, -1.0, 0.0], CEILING_MAX_DROP * 2.0).map(|(t, _)| t + 1e-3)
|
||||
}
|
||||
|
||||
/// Raumlicht-Kandidat: Untersicht mit Platz darunter (s. Moduldoc).
|
||||
fn is_ceiling(bvh: &Bvh, t: &GpuTri, nl: [f32; 3]) -> bool {
|
||||
if nl[1].abs() < 0.7 {
|
||||
return false;
|
||||
}
|
||||
let c = add(t.v0, scale(add(t.e1, t.e2), 1.0 / 3.0));
|
||||
let probes = [c, scale(add(c, t.v0), 0.5), scale(add(c, add(t.v0, t.e1)), 0.5), scale(add(c, add(t.v0, t.e2)), 0.5)];
|
||||
probes.iter().any(|q| drop_below(bvh, *q).is_some_and(|d| (CEILING_MIN_DROP..=CEILING_MAX_DROP).contains(&d)))
|
||||
}
|
||||
|
||||
/// Lichtliste aus dem Baum: Glasflächen ≥ `MIN_PORTAL_AREA` (je Scheibe eine Seite), Leuchten, Deckenuntersichten
|
||||
/// (s. Moduldoc), je Art die grössten bis zur Obergrenze. Setzt `LISTED_BIT` in `bvh.tex` für Portale und Leuchten.
|
||||
pub fn build_lights(bvh: &mut Bvh) -> LightList {
|
||||
let mut portals: Vec<(f32, u32)> = Vec::new();
|
||||
let mut emitters: Vec<(f32, u32)> = Vec::new();
|
||||
let mut ceilings: Vec<(f32, u32)> = Vec::new();
|
||||
let mut panes: HashSet<[i64; 8]> = HashSet::new();
|
||||
for (i, t) in bvh.tris.iter().enumerate() {
|
||||
let Some((area, nl)) = tri_area_normal(t) else { continue };
|
||||
match t.mat >> 24 {
|
||||
MAT_GLASS => {
|
||||
if area >= MIN_PORTAL_AREA && pane_key(t, nl).is_some_and(|k| panes.insert(k)) {
|
||||
portals.push((area, i as u32));
|
||||
}
|
||||
}
|
||||
MAT_EMISSIVE => {
|
||||
let c = crate::bvh::unpack_linear(t.mat);
|
||||
emitters.push((area * (0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]).max(1e-4), i as u32));
|
||||
}
|
||||
_ => {
|
||||
if is_ceiling(bvh, t, nl) {
|
||||
ceilings.push((area, i as u32));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = LightList::default();
|
||||
for (k, (mut list, cap)) in [(portals, MAX_PORTALS), (emitters, MAX_EMITTERS), (ceilings, MAX_CEILINGS)].into_iter().enumerate() {
|
||||
// Grösste zuerst (stabil nach Index bei gleicher Grösse), dann in Baum-Reihenfolge (Speicherzugriff).
|
||||
list.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1)));
|
||||
list.truncate(cap);
|
||||
let mut idx: Vec<u32> = list.into_iter().map(|(_, i)| i).collect();
|
||||
idx.sort_unstable();
|
||||
out.counts[k] = idx.len() as u32;
|
||||
if k != LIGHT_CEILING as usize {
|
||||
for &i in &idx {
|
||||
bvh.tex[i as usize].tex |= LISTED_BIT;
|
||||
}
|
||||
}
|
||||
out.idx.extend(idx);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use crate::bvh::{PtTri, GLASS_RGB, NO_UV};
|
||||
|
||||
/// Rechteck (zwei Dreiecke) aus Ecke und zwei Kanten.
|
||||
pub(crate) fn quad(o: [f32; 3], a: [f32; 3], b: [f32; 3], color: [f32; 3]) -> [PtTri; 2] {
|
||||
let p1 = add(o, a);
|
||||
let p2 = add(add(o, a), b);
|
||||
let p3 = add(o, b);
|
||||
[PtTri { v: [o, p1, p2], color, layer: -1, uv: NO_UV }, PtTri { v: [o, p2, p3], color, layer: -1, uv: NO_UV }]
|
||||
}
|
||||
|
||||
/// Geschlossener Raum 4 × 2.6 × 4 m (Boden y = 0) mit einem Fenster 1.6 × 1.2 m in der Wand z = 0 (Glas als
|
||||
/// Scheibe aus zwei Flächen 8 mm auseinander), darüber eine Decke als eigene Schicht (Untersicht in 2.6 m) und eine
|
||||
/// verdeckte zweite Schicht darüber.
|
||||
pub(crate) fn room() -> Vec<PtTri> {
|
||||
let w = [0.85, 0.85, 0.83];
|
||||
let mut t = Vec::new();
|
||||
t.extend(quad([0.0, 0.0, 0.0], [4.0, 0.0, 0.0], [0.0, 0.0, 4.0], w)); // Boden
|
||||
t.extend(quad([0.0, 2.6, 0.0], [4.0, 0.0, 0.0], [0.0, 0.0, 4.0], w)); // Decke (Untersicht)
|
||||
t.extend(quad([0.0, 2.8, 0.0], [4.0, 0.0, 0.0], [0.0, 0.0, 4.0], w)); // verdeckte Schicht
|
||||
t.extend(quad([0.0, 0.0, 4.0], [4.0, 0.0, 0.0], [0.0, 2.6, 0.0], w)); // Rückwand
|
||||
t.extend(quad([0.0, 0.0, 0.0], [0.0, 0.0, 4.0], [0.0, 2.6, 0.0], w)); // links
|
||||
t.extend(quad([4.0, 0.0, 0.0], [0.0, 0.0, 4.0], [0.0, 2.6, 0.0], w)); // rechts
|
||||
// Wand z = 0 mit Öffnung x 1.2..2.8, y 0.8..2.0.
|
||||
t.extend(quad([0.0, 0.0, 0.0], [1.2, 0.0, 0.0], [0.0, 2.6, 0.0], w));
|
||||
t.extend(quad([2.8, 0.0, 0.0], [1.2, 0.0, 0.0], [0.0, 2.6, 0.0], w));
|
||||
t.extend(quad([1.2, 0.0, 0.0], [1.6, 0.0, 0.0], [0.0, 0.8, 0.0], w));
|
||||
t.extend(quad([1.2, 2.0, 0.0], [1.6, 0.0, 0.0], [0.0, 0.6, 0.0], w));
|
||||
t.extend(quad([1.2, 0.8, 0.0], [1.6, 0.0, 0.0], [0.0, 1.2, 0.0], GLASS_RGB));
|
||||
t.extend(quad([1.2, 0.8, -0.008], [1.6, 0.0, 0.0], [0.0, 1.2, 0.0], GLASS_RGB));
|
||||
// Stirnseite der Scheibe (zu klein für ein Portal).
|
||||
t.extend(quad([1.2, 0.8, -0.008], [1.6, 0.0, 0.0], [0.0, 0.0, 0.008], GLASS_RGB));
|
||||
t
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn liste_portale_und_decke() {
|
||||
let mut bvh = Bvh::build(&room());
|
||||
let lights = build_lights(&mut bvh);
|
||||
// Eine Seite der Scheibe (2 Dreiecke), keine Stirnseite; Decke: nur die Untersicht in 2.6 m (2 Dreiecke).
|
||||
assert_eq!(lights.counts, [2, 0, 2], "{lights:?}");
|
||||
for i in lights.range(LIGHT_PORTAL) {
|
||||
let t = &bvh.tris[lights.idx[i] as usize];
|
||||
assert_eq!(t.mat >> 24, MAT_GLASS);
|
||||
assert!(bvh.tex[lights.idx[i] as usize].tex & LISTED_BIT != 0);
|
||||
}
|
||||
for i in lights.range(LIGHT_CEILING) {
|
||||
let t = &bvh.tris[lights.idx[i] as usize];
|
||||
assert!((t.v0[1] - 2.6).abs() < 1e-6, "Untersicht, nicht die verdeckte Schicht");
|
||||
assert!(bvh.tex[lights.idx[i] as usize].tex & LISTED_BIT == 0, "Raumlicht ohne MIS");
|
||||
}
|
||||
// Leere Szene: leere Liste.
|
||||
let mut e = Bvh::default();
|
||||
assert!(build_lights(&mut e).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gewichte_null_nur_ohne_beitrag() {
|
||||
let mut bvh = Bvh::build(&room());
|
||||
let lights = build_lights(&mut bvh);
|
||||
let portal = bvh.tris[lights.idx[0] as usize];
|
||||
let ceil = bvh.tris[lights.idx[lights.range(LIGHT_CEILING).start] as usize];
|
||||
let floor_p = [2.0, 0.0, 2.0];
|
||||
let up = [0.0, 1.0, 0.0];
|
||||
assert!(light_weight(&portal, LIGHT_PORTAL, 1.0, floor_p, up) > 0.0);
|
||||
assert!(light_weight(&ceil, LIGHT_CEILING, 1.0, floor_p, up) > 0.0);
|
||||
// Hinter der Empfängerfläche: 0.
|
||||
assert_eq!(light_weight(&portal, LIGHT_PORTAL, 1.0, floor_p, [0.0, -1.0, 0.0]), 0.0);
|
||||
// Über der Decke: kein Raumlicht.
|
||||
assert_eq!(light_weight(&ceil, LIGHT_CEILING, 1.0, [2.0, 3.0, 2.0], [0.0, -1.0, 0.0]), 0.0);
|
||||
// Näher = schwerer.
|
||||
let near = light_weight(&portal, LIGHT_PORTAL, 1.0, [2.0, 1.0, 0.5], [0.0, 0.0, -1.0]);
|
||||
let far = light_weight(&portal, LIGHT_PORTAL, 1.0, [2.0, 1.0, 3.5], [0.0, 0.0, -1.0]);
|
||||
assert!(near > far && far > 0.0);
|
||||
// Entartet / NaN: 0, kein Panic.
|
||||
let bad = GpuTri { v0: [f32::NAN; 3], ..portal };
|
||||
assert_eq!(light_weight(&bad, LIGHT_PORTAL, 1.0, floor_p, up), 0.0);
|
||||
assert_eq!(light_weight(&GpuTri::default(), LIGHT_PORTAL, 1.0, floor_p, up), 0.0);
|
||||
}
|
||||
}
|
||||
@@ -463,6 +463,22 @@ impl WebModelRenderer {
|
||||
self.renderer.pathtrace_done()
|
||||
}
|
||||
|
||||
/// [212] Etappe 5: Modell zu gross für die Puffergrenzen des Geräts — der Pathtracer zeigt nur den Himmel, der
|
||||
/// Viewport meldet es (statt eines Panics, der das WASM-Modul lahmlegt).
|
||||
pub fn pathtrace_too_big(&self) -> bool {
|
||||
self.renderer.pathtrace_scene_too_big()
|
||||
}
|
||||
|
||||
/// [212] Etappe 5: Belichtungskorrektur in Blenden (EV) und Belichtungsautomatik des Pathtracers.
|
||||
pub fn set_pathtrace_exposure(&mut self, ev: f64, auto: bool) {
|
||||
self.renderer.set_pathtrace_exposure(ev as f32, auto);
|
||||
}
|
||||
|
||||
/// [212] Etappe 5: Raumlicht bei Nacht (Deckenuntersichten; nur ohne Leuchten im Modell).
|
||||
pub fn set_pathtrace_room_light(&mut self, on: bool) {
|
||||
self.renderer.set_pathtrace_room_light(on);
|
||||
}
|
||||
|
||||
/// [212] Etappe 3: Promise, das sich erfüllt, wenn die GPU alle bis jetzt abgeschickte Arbeit erledigt hat. Der
|
||||
/// Bild-Export rechnet viele Samples in Häppchen und wartet dazwischen hierauf (Fortschritt, Abbruch, Hauptthread
|
||||
/// frei), statt alles auf einmal einzureihen.
|
||||
|
||||
@@ -102,6 +102,12 @@ export const de = {
|
||||
"display.style.pathtrace": "Pathtracing (Vorschau)",
|
||||
"viewport.pathtrace.status": "Pathtracing: {samples} Samples · {rate}/s",
|
||||
"viewport.pathtrace.done": "Pathtracing: {samples} Samples (fertig)",
|
||||
"viewport.pathtrace.tooBig": "Pathtracing: Modell zu gross für diese Grafikkarte – nur Himmel",
|
||||
"viewport.pathtrace.exposure": "Belichtung",
|
||||
"viewport.pathtrace.exposureHint": "Belichtungskorrektur in Blenden (Doppelklick: 0)",
|
||||
"viewport.pathtrace.autoExposure": "Auto",
|
||||
"viewport.pathtrace.roomLight": "Raumlicht",
|
||||
"viewport.pathtrace.roomLightHint": "Bei Nacht fällt Licht von den Decken der Räume, wenn das Modell keine Leuchten hat",
|
||||
|
||||
"topbar.referenceLinesGroup": "Referenzlinien",
|
||||
"topbar.referenceLines": "Referenzlinien",
|
||||
|
||||
@@ -100,6 +100,12 @@ export const en: Record<TranslationKey, string> = {
|
||||
"display.style.hidden": "Hidden line",
|
||||
"display.style.pathtrace": "Path tracing (preview)",
|
||||
"viewport.pathtrace.status": "Path tracing: {samples} samples · {rate}/s",
|
||||
"viewport.pathtrace.tooBig": "Path tracing: model too large for this graphics card – sky only",
|
||||
"viewport.pathtrace.exposure": "Exposure",
|
||||
"viewport.pathtrace.exposureHint": "Exposure compensation in stops (double-click: 0)",
|
||||
"viewport.pathtrace.autoExposure": "Auto",
|
||||
"viewport.pathtrace.roomLight": "Room light",
|
||||
"viewport.pathtrace.roomLightHint": "At night light falls from the room ceilings when the model has no light fixtures",
|
||||
"viewport.pathtrace.done": "Path tracing: {samples} samples (done)",
|
||||
|
||||
"topbar.referenceLinesGroup": "Reference lines",
|
||||
|
||||
@@ -655,6 +655,7 @@ export function Wasm3DViewport({
|
||||
updateModel,
|
||||
setRenderStyle,
|
||||
pathtraceStatus,
|
||||
setPathtraceLook,
|
||||
setSun,
|
||||
applyViewPreset,
|
||||
viewFit,
|
||||
@@ -836,7 +837,16 @@ export function Wasm3DViewport({
|
||||
// [212] Pathtracing (Vorschau): progressiv — solange der Stil aktiv und das Bild nicht fertig ist, je Animationsbild
|
||||
// ein Sample dazurechnen (der Renderer beginnt bei Kamera-/Modell-/Sonnenänderung selbst von vorn). Zähler und
|
||||
// Samples/s unten links; die Rate ist über ~1 s gemittelt.
|
||||
const [ptStatus, setPtStatus] = useState<{ samples: number; rate: number; done: boolean } | null>(null);
|
||||
const [ptStatus, setPtStatus] = useState<{ samples: number; rate: number; done: boolean; tooBig: boolean } | null>(null);
|
||||
// [212] Etappe 5: Belichtung (Korrektur in Blenden, Automatik) und Raumlicht bei Nacht — Ansichtszustand, kein Op.
|
||||
const [ptEv, setPtEv] = useState(0);
|
||||
const [ptAuto, setPtAuto] = useState(true);
|
||||
const [ptRoom, setPtRoom] = useState(true);
|
||||
useEffect(() => {
|
||||
if (!ready) return;
|
||||
setPathtraceLook(ptEv, ptAuto, ptRoom);
|
||||
redrawRef.current();
|
||||
}, [ready, ptEv, ptAuto, ptRoom, setPathtraceLook]);
|
||||
useEffect(() => {
|
||||
if (!ready || renderMode !== "pathtrace") {
|
||||
setPtStatus(null);
|
||||
@@ -855,10 +865,10 @@ export function Wasm3DViewport({
|
||||
if (now - last.t >= 1000) {
|
||||
last = { t: now, samples: cur.samples, rate: ((cur.samples - last.samples) * 1000) / (now - last.t) };
|
||||
}
|
||||
const key = `${cur.samples}|${cur.done}|${last.rate.toFixed(1)}`;
|
||||
const key = `${cur.samples}|${cur.done}|${last.rate.toFixed(1)}|${cur.tooBig}`;
|
||||
if (key !== shown) {
|
||||
shown = key;
|
||||
setPtStatus({ samples: cur.samples, rate: last.rate, done: cur.done });
|
||||
setPtStatus({ samples: cur.samples, rate: last.rate, done: cur.done, tooBig: cur.tooBig });
|
||||
}
|
||||
}
|
||||
raf = requestAnimationFrame(tick);
|
||||
@@ -1880,9 +1890,53 @@ export function Wasm3DViewport({
|
||||
pointerEvents: "none",
|
||||
}}
|
||||
>
|
||||
{ptStatus.done
|
||||
? t("viewport.pathtrace.done", { samples: ptStatus.samples })
|
||||
: t("viewport.pathtrace.status", { samples: ptStatus.samples, rate: ptStatus.rate.toFixed(1) })}
|
||||
{ptStatus.tooBig
|
||||
? t("viewport.pathtrace.tooBig")
|
||||
: ptStatus.done
|
||||
? t("viewport.pathtrace.done", { samples: ptStatus.samples })
|
||||
: t("viewport.pathtrace.status", { samples: ptStatus.samples, rate: ptStatus.rate.toFixed(1) })}
|
||||
</div>
|
||||
)}
|
||||
{ptStatus && (
|
||||
<div
|
||||
data-testid="pathtrace-look"
|
||||
style={{
|
||||
position: "absolute",
|
||||
left: 10,
|
||||
bottom: 38,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 8,
|
||||
padding: "3px 8px",
|
||||
borderRadius: 6,
|
||||
background: "rgba(20,20,24,0.65)",
|
||||
color: "#f2f2f2",
|
||||
fontSize: 12,
|
||||
}}
|
||||
>
|
||||
<label title={t("viewport.pathtrace.exposureHint")} style={{ display: "flex", alignItems: "center", gap: 4 }}>
|
||||
{t("viewport.pathtrace.exposure")}
|
||||
<input
|
||||
type="range"
|
||||
min={-3}
|
||||
max={3}
|
||||
step={0.25}
|
||||
value={ptEv}
|
||||
data-testid="pathtrace-ev"
|
||||
onChange={(e) => setPtEv(Number(e.target.value))}
|
||||
onDoubleClick={() => setPtEv(0)}
|
||||
style={{ width: 90 }}
|
||||
/>
|
||||
<span style={{ minWidth: 34 }}>{`${ptEv > 0 ? "+" : ""}${ptEv.toFixed(2)}`}</span>
|
||||
</label>
|
||||
<label style={{ display: "flex", alignItems: "center", gap: 3 }}>
|
||||
<input type="checkbox" checked={ptAuto} data-testid="pathtrace-auto" onChange={(e) => setPtAuto(e.target.checked)} />
|
||||
{t("viewport.pathtrace.autoExposure")}
|
||||
</label>
|
||||
<label title={t("viewport.pathtrace.roomLightHint")} style={{ display: "flex", alignItems: "center", gap: 3 }}>
|
||||
<input type="checkbox" checked={ptRoom} data-testid="pathtrace-room" onChange={(e) => setPtRoom(e.target.checked)} />
|
||||
{t("viewport.pathtrace.roomLight")}
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
{/* [213] Begehen (WASD) und Kamera aus der aktuellen Ansicht anlegen. */}
|
||||
|
||||
@@ -58,6 +58,11 @@ interface WebModelRendererLike {
|
||||
* Optional — ältere WASM-Builds. */
|
||||
pathtrace_samples?(): number;
|
||||
pathtrace_done?(): boolean;
|
||||
/** [212] Etappe 5: Modell zu gross für die Puffergrenzen des Geräts (Pathtracer zeigt nur den Himmel). */
|
||||
pathtrace_too_big?(): boolean;
|
||||
/** [212] Etappe 5: Belichtungskorrektur (EV) und Belichtungsautomatik; Raumlicht bei Nacht. */
|
||||
set_pathtrace_exposure?(ev: number, auto: boolean): void;
|
||||
set_pathtrace_room_light?(on: boolean): void;
|
||||
set_view_preset(preset: string): void;
|
||||
/** [223] Hintergrundfarbe (0..1) für den Bild-Export mit transparentem Hintergrund. Optional — ältere WASM-Builds. */
|
||||
set_clear_color?(r: number, g: number, b: number): void;
|
||||
@@ -518,16 +523,28 @@ export function useWasm3dRenderer(
|
||||
}, []);
|
||||
|
||||
/** [212] Stand des Pathtracers: Samples je Pixel und ob das Bild fertig ist; null ohne Renderer/alter Build. */
|
||||
const pathtraceStatus = useCallback((): { samples: number; done: boolean } | null => {
|
||||
const pathtraceStatus = useCallback((): { samples: number; done: boolean; tooBig: boolean } | null => {
|
||||
const r = rendererRef.current;
|
||||
if (!r?.pathtrace_samples) return null;
|
||||
try {
|
||||
return { samples: r.pathtrace_samples(), done: r.pathtrace_done?.() ?? false };
|
||||
return { samples: r.pathtrace_samples(), done: r.pathtrace_done?.() ?? false, tooBig: r.pathtrace_too_big?.() ?? false };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
/** [212] Etappe 5: Belichtung (EV, Automatik) und Raumlicht des Pathtracers; wirkt beim nächsten `render`. */
|
||||
const setPathtraceLook = useCallback((ev: number, autoExposure: boolean, roomLight: boolean) => {
|
||||
const r = rendererRef.current;
|
||||
if (!r) return;
|
||||
try {
|
||||
r.set_pathtrace_exposure?.(ev, autoExposure);
|
||||
r.set_pathtrace_room_light?.(roomLight);
|
||||
} catch (e) {
|
||||
console.warn("render3d Pathtracing-Einstellung fehlgeschlagen:", e);
|
||||
}
|
||||
}, []);
|
||||
|
||||
/** Sonne + Schatten im 3D setzen ([64], s. `sun3d.ts`). Wirkt erst beim nächsten `render`. */
|
||||
const setSun = useCallback((active: boolean, azimuthDeg: number, elevationDeg: number) => {
|
||||
const r = rendererRef.current;
|
||||
@@ -835,6 +852,7 @@ export function useWasm3dRenderer(
|
||||
updateModel,
|
||||
setRenderStyle,
|
||||
pathtraceStatus,
|
||||
setPathtraceLook,
|
||||
setSun,
|
||||
applyViewPreset,
|
||||
viewFit,
|
||||
|
||||
Reference in new issue
Block a user