1use crate::sdf::{SdfRay, SdfScene, TraceCfg, V3};
31
32pub const PT_OFF: f32 = 2.0e-3;
36
37pub fn hash32(mut x: u32) -> u32 {
40 x ^= x >> 16;
41 x = x.wrapping_mul(0x7feb_352d);
42 x ^= x >> 15;
43 x = x.wrapping_mul(0x846c_a68b);
44 x ^= x >> 16;
45 x
46}
47
48pub fn unif(x: u32) -> f32 {
51 (x >> 8) as f32 * (1.0 / 16777216.0)
52}
53
54fn next(s: &mut u32) -> f32 {
56 *s = hash32(*s);
57 unif(*s)
58}
59
60pub fn seed_pass(seed: u32, pass: u32, pix: u32) -> u32 {
63 hash32(seed ^ pass.wrapping_mul(0x9E37_79B9) ^ pix.wrapping_mul(0x85EB_CA77))
64}
65
66fn add(a: V3, b: V3) -> V3 {
67 [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
68}
69fn sub(a: V3, b: V3) -> V3 {
70 [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
71}
72fn scale(a: V3, s: f32) -> V3 {
73 [a[0] * s, a[1] * s, a[2] * s]
74}
75fn mul3(a: V3, b: V3) -> V3 {
76 [a[0] * b[0], a[1] * b[1], a[2] * b[2]]
77}
78fn dot(a: V3, b: V3) -> f32 {
79 (a[0] * b[0] + a[1] * b[1]) + a[2] * b[2]
80}
81fn cross(a: V3, b: V3) -> V3 {
82 [
83 a[1] * b[2] - a[2] * b[1],
84 a[2] * b[0] - a[0] * b[2],
85 a[0] * b[1] - a[1] * b[0],
86 ]
87}
88fn norm(v: V3) -> V3 {
91 let l = dot(v, v).sqrt();
92 if l == 0.0 {
93 [0.0; 3]
94 } else {
95 [v[0] / l, v[1] / l, v[2] / l]
96 }
97}
98
99fn basis_t(n: V3) -> V3 {
104 let (ax, ay, az) = (n[0].abs(), n[1].abs(), n[2].abs());
105 let e = if ax <= ay && ax <= az {
106 [1.0, 0.0, 0.0]
107 } else if ay <= az {
108 [0.0, 1.0, 0.0]
109 } else {
110 [0.0, 0.0, 1.0]
111 };
112 norm(cross(e, n))
113}
114
115pub fn cos_dir(n: V3, s: &mut u32) -> V3 {
123 let (x, y) = {
124 let mut x = 0.0f32;
125 let mut y = 0.0f32;
126 for _ in 0..64 {
127 x = 2.0 * next(s) - 1.0;
128 y = 2.0 * next(s) - 1.0;
129 if x * x + y * y <= 1.0 {
130 break;
131 }
132 }
133 (x, y)
134 };
135 let z = (1.0 - x * x - y * y).max(0.0).sqrt();
136 let t = basis_t(n);
137 let b = cross(n, t);
138 add(add(scale(t, x), scale(b, y)), scale(n, z))
139}
140
141#[derive(Clone, Copy, Debug, PartialEq)]
145pub struct PtCam {
146 pub pos: V3,
147 pub fwd: V3,
148 pub right: V3,
149 pub up: V3,
150 pub pxscale: f32,
151}
152
153impl PtCam {
154 pub fn look_at(pos: V3, ziel: V3, hint: V3, hoehe: f32, vfov: f32) -> Self {
157 let fwd = norm(sub(ziel, pos));
158 let mut right = norm(cross(fwd, hint));
159 if right == [0.0; 3] {
160 right = [1.0, 0.0, 0.0];
161 }
162 let up = cross(right, fwd);
163 Self {
164 pos,
165 fwd,
166 right,
167 up,
168 pxscale: (vfov * 0.5).tan() * 2.0 / hoehe,
169 }
170 }
171}
172
173#[derive(Clone, Copy, Debug, PartialEq)]
175pub struct PtCfg {
176 pub max_depth: u32,
178 pub eps_hit: f32,
179 pub eps_step: f32,
180 pub tmax: f32,
181 pub max_steps: u32,
182 pub sky: V3,
184 pub seed: u32,
186}
187
188impl Default for PtCfg {
189 fn default() -> Self {
190 Self {
191 max_depth: 4,
192 eps_hit: 2.0e-4,
193 eps_step: 1.0e-4,
194 tmax: 60.0,
195 max_steps: 128,
196 sky: [0.2, 0.35, 0.6],
197 seed: 7,
198 }
199 }
200}
201
202pub struct PtScene<'a> {
205 pub sdf: &'a SdfScene,
206 pub albedo: &'a [V3],
207 pub cfg: PtCfg,
208}
209
210impl<'a> PtScene<'a> {
211 pub fn radiance(&self, ro: V3, rd: V3, s: &mut u32) -> V3 {
218 let tcfg = TraceCfg {
219 eps_hit: self.cfg.eps_hit,
220 eps_step: self.cfg.eps_step,
221 tmax: self.cfg.tmax,
222 max_steps: self.cfg.max_steps,
223 };
224 let mut acc = [0.0; 3];
225 let mut thr = [1.0; 3];
226 let (mut o, mut d) = (ro, rd);
227 for _ in 0..self.cfg.max_depth {
228 match crate::sdf::trace(
229 self.sdf,
230 &SdfRay {
231 ro: o,
232 rd: d,
233 tmin: 0.0,
234 },
235 &tcfg,
236 ) {
237 Some(h) => {
238 if h.emis[0] > 0.0 || h.emis[1] > 0.0 || h.emis[2] > 0.0 {
239 acc = add(acc, mul3(thr, h.emis));
240 return acc;
241 }
242 thr = mul3(thr, self.albedo[h.prim as usize]);
243 o = add(h.pos, scale(h.n, PT_OFF));
244 d = cos_dir(h.n, s);
245 }
246 None => {
247 acc = add(acc, mul3(thr, self.cfg.sky));
248 return acc;
249 }
250 }
251 }
252 acc
253 }
254
255 pub fn primary(&self, cam: &PtCam, w: u32, h: u32, x: u32, y: u32, s: &mut u32) -> (V3, V3) {
257 let fx = (x as f32 + next(s)) - (w as f32) * 0.5;
258 let fy = (y as f32 + next(s)) - (h as f32) * 0.5;
259 let rd = norm(add(add(cam.fwd, scale(cam.right, fx * cam.pxscale)), {
260 scale(cam.up, fy * cam.pxscale)
261 }));
262 (cam.pos, rd)
263 }
264}
265
266#[derive(Clone, Debug)]
270pub struct PtAccum {
271 pub w: u32,
272 pub h: u32,
273 pub n: u32,
274 pub rgb: Vec<f32>,
275}
276
277impl PtAccum {
278 pub fn new(w: u32, h: u32) -> Self {
279 Self {
280 w,
281 h,
282 n: 0,
283 rgb: vec![0.0; (w * h) as usize * 3],
284 }
285 }
286
287 pub fn pass(&mut self, sc: &PtScene, cam: &PtCam) {
290 self.n += 1;
291 let nf = self.n as f32;
292 for i in 0..(self.w * self.h) as usize {
293 let (x, y) = ((i as u32) % self.w, (i as u32) / self.w);
294 let mut s = seed_pass(sc.cfg.seed, self.n, i as u32);
295 let (ro, rd) = sc.primary(cam, self.w, self.h, x, y, &mut s);
296 let rad = sc.radiance(ro, rd, &mut s);
297 let b = i * 3;
298 for (slot, r) in self.rgb[b..b + 3].iter_mut().zip(rad) {
299 *slot += (r - *slot) / nf;
300 }
301 }
302 }
303
304 pub fn rmse_vs(&self, other: &[f32]) -> f32 {
306 let mut sum = 0.0;
307 for (a, b) in self.rgb.iter().zip(other.iter()) {
308 let d = a - b;
309 sum += d * d;
310 }
311 (sum / self.rgb.len() as f32).sqrt()
312 }
313}
314
315#[cfg(test)]
318mod tests {
319 use super::*;
320 use crate::sdf::SdfPrim;
321
322 fn halle() -> (SdfScene, Vec<V3>) {
323 let black = [0.0; 3];
325 let sdf = SdfScene::from_prims(vec![
326 SdfPrim::plane([0.0; 3], [0.0, 1.0, 0.0], black),
327 SdfPrim::sphere([0.0, 6.0, 0.0], 2.0, [6.0, 4.5, 3.0]),
328 SdfPrim::sphere([1.4, 0.8, 0.0], 0.8, black),
329 SdfPrim::sphere([-1.6, 0.6, -0.8], 0.6, black),
330 ]);
331 let albedo = vec![[0.6, 0.6, 0.62], black, [0.8, 0.25, 0.15], [0.2, 0.4, 0.8]];
332 (sdf, albedo)
333 }
334
335 #[test]
336 fn strom_ist_deterministisch_und_normiert() {
337 let mut s = seed_pass(42, 1, 0);
338 let mut sum = 0.0f32;
339 let mut min = 1.0f32;
340 let mut max = 0.0f32;
341 for _ in 0..4096 {
342 let u = next(&mut s);
343 assert!((0.0..1.0).contains(&u), "Wert {u} außerhalb [0,1)");
344 sum += u;
345 min = min.min(u);
346 max = max.max(u);
347 }
348 let mean = sum / 4096.0;
350 assert!((mean - 0.5).abs() < 0.02, "Mittel {mean}");
351 assert!(min < 0.02 && max > 0.98, "Spanne [{min},{max}]");
352 let mut s2 = seed_pass(42, 1, 0);
354 assert_eq!(next(&mut s2).to_bits(), {
355 let mut s = seed_pass(42, 1, 0);
356 next(&mut s).to_bits()
357 });
358 }
359
360 #[test]
361 fn cos_dir_trefft_hemisphaere_und_mittelt_zweidrittel_hoehe() {
362 let n = [0.0, 1.0, 0.0];
363 let mut s = seed_pass(9, 3, 11);
364 let mut zy = 0.0;
365 for _ in 0..4096 {
366 let d = cos_dir(n, &mut s);
367 assert!(dot(d, n) >= 0.0, "unter der Fläche");
368 let l = dot(d, d).sqrt();
369 assert!((l - 1.0).abs() < 1e-5, "nicht normiert: {l}");
370 zy += d[1];
371 }
372 assert!((zy / 4096.0 - 2.0 / 3.0).abs() < 0.03, "Höhenmittel {zy}");
374 }
375
376 #[test]
377 fn progressiv_konvergiert_gegen_den_langlauf() {
378 let (sdf, albedo) = halle();
379 let sc = PtScene {
380 sdf: &sdf,
381 albedo: &albedo,
382 cfg: PtCfg {
383 max_depth: 3,
384 tmax: 40.0,
385 max_steps: 64,
386 ..Default::default()
387 },
388 };
389 let cam = PtCam::look_at([0.0, 1.6, 4.0], [0.0, 1.2, 0.0], [0.0, 1.0, 0.0], 24.0, 1.4);
390 let (w, h) = (12, 12);
391 let mut ref_acc = PtAccum::new(w, h);
392 for _ in 0..512 {
393 ref_acc.pass(&sc, &cam);
394 }
395 let mut fast = PtAccum::new(w, h);
396 let mut err_prev = f32::INFINITY;
397 for probe in [8, 32, 128] {
398 while fast.n < probe {
399 fast.pass(&sc, &cam);
400 }
401 let err = fast.rmse_vs(&ref_acc.rgb);
402 assert!(err < err_prev, "Konvergenz gestört: {err} nach {probe}");
403 err_prev = err;
404 }
405 assert!(
407 ref_acc
408 .rgb
409 .iter()
410 .max_by(|a, b| a.total_cmp(b))
411 .copied()
412 .unwrap()
413 > 0.5,
414 "Bild ohne Licht"
415 );
416 }
417}