1pub type V3 = [f32; 3];
24
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub enum SdfKind {
29 Sphere,
31 Box,
33 Capsule,
35 Plane,
38}
39
40impl SdfKind {
41 pub fn bits(self) -> f32 {
43 match self {
44 SdfKind::Sphere => 0.0,
45 SdfKind::Box => 1.0,
46 SdfKind::Capsule => 2.0,
47 SdfKind::Plane => 3.0,
48 }
49 }
50}
51
52#[derive(Clone, Copy, Debug, PartialEq)]
59pub struct SdfPrim {
60 pub kind: SdfKind,
61 pub pos: V3,
62 pub ext: V3,
63 pub radius: f32,
64 pub bound_c: V3,
65 pub bound_r: f32,
66 pub emis: V3,
67}
68
69pub const BOUND_OPEN: f32 = 2.0e30;
73
74pub const DIST_START: f32 = 1.0e30;
77
78pub const NORMAL_H: f32 = 1.0e-3;
81
82pub const TAU: f32 = std::f32::consts::TAU;
85const NORMAL_EPS: f32 = 1.0e-8;
86
87fn add(a: V3, b: V3) -> V3 {
88 [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
89}
90fn sub(a: V3, b: V3) -> V3 {
91 [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
92}
93fn scale(a: V3, s: f32) -> V3 {
94 [a[0] * s, a[1] * s, a[2] * s]
95}
96fn dot(a: V3, b: V3) -> f32 {
97 (a[0] * b[0] + a[1] * b[1]) + a[2] * b[2]
98}
99fn cross(a: V3, b: V3) -> V3 {
100 [
101 a[1] * b[2] - a[2] * b[1],
102 a[2] * b[0] - a[0] * b[2],
103 a[0] * b[1] - a[1] * b[0],
104 ]
105}
106fn len(v: V3) -> f32 {
107 dot(v, v).sqrt()
108}
109fn norm(v: V3) -> V3 {
112 let l = len(v);
113 if l == 0.0 {
114 [0.0; 3]
115 } else {
116 [v[0] / l, v[1] / l, v[2] / l]
117 }
118}
119
120impl SdfPrim {
121 pub fn sphere(c: V3, r: f32, emis: V3) -> Self {
123 Self {
124 kind: SdfKind::Sphere,
125 pos: c,
126 ext: [0.0; 3],
127 radius: r,
128 bound_c: c,
129 bound_r: r,
130 emis,
131 }
132 }
133 pub fn axis_box(c: V3, h: V3, emis: V3) -> Self {
135 Self {
136 kind: SdfKind::Box,
137 pos: c,
138 ext: h,
139 radius: 0.0,
140 bound_c: c,
141 bound_r: len(h),
142 emis,
143 }
144 }
145 pub fn capsule(a: V3, b: V3, r: f32, emis: V3) -> Self {
147 let mid = scale(add(a, b), 0.5);
148 Self {
149 kind: SdfKind::Capsule,
150 pos: a,
151 ext: b,
152 radius: r,
153 bound_c: mid,
154 bound_r: len(sub(b, a)) * 0.5 + r,
155 emis,
156 }
157 }
158 pub fn plane(p: V3, n: V3, emis: V3) -> Self {
161 Self {
162 kind: SdfKind::Plane,
163 pos: p,
164 ext: n,
165 radius: 0.0,
166 bound_c: [0.0; 3],
167 bound_r: BOUND_OPEN,
168 emis,
169 }
170 }
171
172 pub fn dist(&self, p: V3) -> f32 {
175 match self.kind {
176 SdfKind::Sphere => len(sub(p, self.pos)) - self.radius,
177 SdfKind::Box => {
178 let q = sub(p, self.pos);
179 let a = [
180 (q[0]).abs() - self.ext[0],
181 (q[1]).abs() - self.ext[1],
182 (q[2]).abs() - self.ext[2],
183 ];
184 let mx = a[0].max(a[1].max(a[2])).min(0.0);
185 len([a[0].max(0.0), a[1].max(0.0), a[2].max(0.0)]) + mx
186 }
187 SdfKind::Capsule => {
188 let pa = sub(p, self.pos);
189 let ba = sub(self.ext, self.pos);
190 let h = (dot(pa, ba) / dot(ba, ba)).clamp(0.0, 1.0);
191 len(sub(pa, scale(ba, h))) - self.radius
192 }
193 SdfKind::Plane => dot(sub(p, self.pos), self.ext),
194 }
195 }
196}
197
198#[derive(Clone, Debug, Default)]
200pub struct SdfScene {
201 pub prims: Vec<SdfPrim>,
202}
203
204#[derive(Clone, Copy, Debug, PartialEq)]
207pub struct Hit {
208 pub t: f32,
209 pub prim: u32,
210 pub pos: V3,
211 pub n: V3,
212 pub emis: V3,
213}
214
215#[derive(Clone, Copy, Debug, PartialEq)]
217pub struct TraceCfg {
218 pub eps_hit: f32,
220 pub eps_step: f32,
222 pub tmax: f32,
224 pub max_steps: u32,
226}
227
228impl Default for TraceCfg {
229 fn default() -> Self {
230 Self {
231 eps_hit: 1.0e-4,
232 eps_step: 1.0e-5,
233 tmax: 100.0,
234 max_steps: 128,
235 }
236 }
237}
238
239#[derive(Clone, Copy, Debug, PartialEq)]
241pub struct SdfRay {
242 pub ro: V3,
243 pub rd: V3,
244 pub tmin: f32,
245}
246
247impl SdfScene {
248 pub fn new() -> Self {
249 Self::default()
250 }
251 pub fn from_prims(prims: Vec<SdfPrim>) -> Self {
252 Self { prims }
253 }
254 pub fn add(&mut self, p: SdfPrim) -> u32 {
255 self.prims.push(p);
256 (self.prims.len() - 1) as u32
257 }
258
259 pub fn dist(&self, p: V3) -> (f32, u32) {
265 let mut best = DIST_START;
266 let mut idx = 0u32;
267 for (i, pr) in self.prims.iter().enumerate() {
268 let dc = len(sub(p, pr.bound_c));
269 if dc - pr.bound_r > best {
270 continue;
271 }
272 let d = pr.dist(p);
273 if d < best {
274 best = d;
275 idx = i as u32 + 1;
276 }
277 }
278 (best, idx)
279 }
280
281 pub fn normal(&self, p: V3) -> V3 {
284 let h = [NORMAL_H, 0.0, 0.0];
285 let v = [[0.0, NORMAL_H, 0.0], [0.0, 0.0, NORMAL_H]];
286 let gx = self.dist(add(p, h)).0 - self.dist(sub(p, h)).0;
287 let gy = self.dist(add(p, v[0])).0 - self.dist(sub(p, v[0])).0;
288 let gz = self.dist(add(p, v[1])).0 - self.dist(sub(p, v[1])).0;
289 let g = [gx, gy, gz];
290 let l = len(g);
291 if l < NORMAL_EPS {
292 [0.0, 1.0, 0.0]
293 } else {
294 [g[0] / l, g[1] / l, g[2] / l]
295 }
296 }
297}
298
299pub fn trace(scene: &SdfScene, ray: &SdfRay, cfg: &TraceCfg) -> Option<Hit> {
305 let mut t = ray.tmin;
306 for _ in 0..cfg.max_steps {
307 let p = add(ray.ro, scale(ray.rd, t));
308 let (d, idx) = scene.dist(p);
309 if d < cfg.eps_hit {
310 let t2 = t - d;
311 let pos = add(ray.ro, scale(ray.rd, t2));
312 return Some(Hit {
313 t: t2,
314 prim: idx.saturating_sub(1),
315 pos,
316 n: scene.normal(pos),
317 emis: scene.prims[idx.saturating_sub(1) as usize].emis,
318 });
319 }
320 t += d.max(cfg.eps_step);
321 if t > cfg.tmax {
322 break;
323 }
324 }
325 None
326}
327
328#[derive(Clone, Copy, Debug, PartialEq)]
332pub struct GatherPoint {
333 pub pos: V3,
334 pub n: V3,
335 pub self_prim: u32,
336}
337
338#[derive(Clone, Copy, Debug, PartialEq)]
341pub struct GatherCfg {
342 pub trace: TraceCfg,
343 pub n_dirs: u32,
344 pub ambient: V3,
345}
346
347impl Default for GatherCfg {
348 fn default() -> Self {
349 Self {
350 trace: TraceCfg::default(),
351 n_dirs: 64,
352 ambient: [0.0, 0.0, 0.0],
353 }
354 }
355}
356
357pub fn radical2(i: u32) -> f32 {
361 let mut x = i.wrapping_add(1);
362 x = x.rotate_left(16);
363 x = ((x & 0x00ff_00ff) << 8) | ((x >> 8) & 0x00ff_00ff);
364 x = ((x & 0x0f0f_0f0f) << 4) | ((x >> 4) & 0x0f0f_0f0f);
365 x = ((x & 0x3333_3333) << 2) | ((x >> 2) & 0x3333_3333);
366 x = ((x & 0x5555_5555) << 1) | ((x >> 1) & 0x5555_5555);
367 x as f32 / 4294967296.0
368}
369
370pub fn radical3(i: u32) -> f32 {
373 let mut n = i.wrapping_add(1);
374 let mut inv = 1.0 / 3.0;
375 let mut r = 0.0;
376 loop {
377 r += (n % 3) as f32 * inv;
378 n /= 3;
379 if n == 0 {
380 break;
381 }
382 inv /= 3.0;
383 }
384 r
385}
386
387pub fn hemi_dir(n: V3, i: u32) -> V3 {
391 let up = if n[1].abs() >= 0.99 {
392 [1.0, 0.0, 0.0]
393 } else {
394 [0.0, 1.0, 0.0]
395 };
396 let tv = norm(cross(up, n));
397 let bv = cross(n, tv);
398 let z = radical2(i);
399 let phi = TAU * radical3(i);
400 let s = (1.0 - z * z).max(0.0).sqrt();
401 let d1 = add(scale(tv, s * phi.cos()), scale(bv, s * phi.sin()));
402 norm(add(d1, scale(n, z)))
403}
404
405pub fn gather(scene: &SdfScene, cfg: &GatherCfg, points: &[GatherPoint]) -> Vec<V3> {
411 let nd = cfg.n_dirs.max(1) as f32;
412 points
413 .iter()
414 .map(|pt| {
415 let mut acc = [0.0f32; 3];
416 for d in 0..cfg.n_dirs {
417 let dir = hemi_dir(pt.n, d);
418 let mut t = 0.0;
419 let mut col = cfg.ambient;
420 for _ in 0..cfg.trace.max_steps {
421 let q = add(pt.pos, scale(dir, t));
422 let (dd, idx) = scene.dist(q);
423 if dd < cfg.trace.eps_hit {
424 if idx != 0 && pt.self_prim != u32::MAX && idx == pt.self_prim + 1 {
425 col = [0.0; 3];
426 } else if idx != 0 {
427 col = scene.prims[(idx - 1) as usize].emis;
428 }
429 break;
430 }
431 t += dd.max(cfg.trace.eps_step);
432 if t > cfg.trace.tmax {
433 break;
434 }
435 }
436 acc = add(acc, col);
437 }
438 [acc[0] / nd, acc[1] / nd, acc[2] / nd]
439 })
440 .collect()
441}
442
443#[cfg(test)]
444mod tests {
445 use super::*;
446
447 const BLACK: V3 = [0.0; 3];
448 const WHITE: V3 = [1.0; 3];
449
450 #[test]
451 fn kugel_abstand_exakt() {
452 let s = SdfScene::from_prims(vec![SdfPrim::sphere([0.0; 3], 1.0, BLACK)]);
453 assert_eq!(s.dist([0.0, 0.0, 2.0]).0, 1.0);
454 assert_eq!(s.dist([0.0, 0.0, 0.0]).0, -1.0);
455 let (d, idx) = s.dist([0.0, 0.0, 1.5]);
456 assert!((d - 0.5).abs() < 1e-6);
457 assert_eq!(idx, 1);
458 }
459
460 #[test]
461 fn quader_abstand_exakt() {
462 let s = SdfScene::from_prims(vec![SdfPrim::axis_box([0.0; 3], [1.0; 3], BLACK)]);
463 assert_eq!(s.dist([2.0, 0.0, 0.0]).0, 1.0);
465 let ecke = [2.0, 2.0, 2.0];
467 let d = s.dist(ecke).0;
468 assert!((d - 3.0f32.sqrt()).abs() < 1e-5);
469 assert_eq!(s.dist([0.0; 3]).0, -1.0);
471 }
472
473 #[test]
474 fn kapsel_abstand_exakt() {
475 let s = SdfScene::from_prims(vec![SdfPrim::capsule(
476 [0.0, -1.0, 0.0],
477 [0.0, 1.0, 0.0],
478 0.5,
479 BLACK,
480 )]);
481 assert!((s.dist([2.0, 0.0, 0.0]).0 - 1.5).abs() < 1e-6);
483 assert!((s.dist([0.0, 3.0, 0.0]).0 - 1.5).abs() < 1e-6);
485 assert!((s.dist([0.0, 0.0, 0.0]).0 + 0.5).abs() < 1e-6);
487 }
488
489 #[test]
490 fn ebene_abstand_und_normalenrichtung() {
491 let ground = SdfPrim::plane([0.0; 3], [0.0, 1.0, 0.0], BLACK);
492 let s = SdfScene::from_prims(vec![ground]);
493 assert_eq!(s.dist([7.0, 2.5, -3.0]).0, 2.5);
494 assert_eq!(s.dist([7.0, -2.5, -3.0]).0, -2.5);
495 let n = s.normal([7.0, 0.05, -3.0]);
497 assert!((n[1] - 1.0).abs() < 1e-5 && n[0].abs() < 1e-5);
498 }
499
500 #[test]
501 fn suche_treffer_analytische_kugel() {
502 let s = SdfScene::from_prims(vec![SdfPrim::sphere([0.0; 3], 1.0, WHITE)]);
503 let hit = trace(
504 &s,
505 &SdfRay {
506 ro: [0.0, 0.0, -5.0],
507 rd: [0.0, 0.0, 1.0],
508 tmin: 0.0,
509 },
510 &TraceCfg::default(),
511 )
512 .expect("Kugel liegt auf dem Weg");
513 assert!((hit.t - 4.0).abs() < 2e-3, "t = {}", hit.t);
514 assert!((hit.pos[2] + 1.0).abs() < 2e-3);
515 assert!((hit.n[2] + 1.0).abs() < 1e-2, "n = {:?}", hit.n);
516 assert_eq!(hit.emis, WHITE);
517 assert_eq!(hit.prim, 0);
518 }
519
520 #[test]
521 fn suche_verfehlt_und_trifft_den_naeheren() {
522 let s = SdfScene::from_prims(vec![
523 SdfPrim::sphere([3.0, 0.0, 5.0], 1.0, BLACK),
524 SdfPrim::sphere([-3.0, 0.0, 5.0], 1.0, BLACK),
525 ]);
526 let miss = trace(
528 &s,
529 &SdfRay {
530 ro: [0.0, 9.0, -5.0],
531 rd: [0.0, 0.0, 1.0],
532 tmin: 0.0,
533 },
534 &TraceCfg {
535 tmax: 30.0,
536 ..Default::default()
537 },
538 );
539 assert!(miss.is_none());
540 let hit = trace(
542 &s,
543 &SdfRay {
544 ro: [2.4, 0.0, -5.0],
545 rd: [0.0, 0.0, 1.0],
546 tmin: 0.0,
547 },
548 &TraceCfg::default(),
549 )
550 .expect("rechte Kugel trifft");
551 assert_eq!(hit.prim, 0);
552 }
553
554 #[test]
555 fn fruehausleitung_veraendert_das_minimum_nicht() {
556 let s = SdfScene::from_prims(vec![
558 SdfPrim::sphere([0.0, 0.0, 0.0], 1.5, BLACK),
559 SdfPrim::axis_box([4.0, 1.0, -2.0], [1.0, 2.0, 1.0], BLACK),
560 SdfPrim::capsule([-3.0, 0.0, 2.0], [-1.0, 3.0, 4.0], 0.4, BLACK),
561 SdfPrim::plane([0.0, -2.0, 0.0], [0.0, 1.0, 0.0], BLACK),
562 SdfPrim::sphere([6.0, 6.0, 6.0], 0.8, BLACK),
563 ]);
564 let probe = [
565 [0.0, 0.0, 0.0],
566 [3.5, 1.2, -2.5],
567 [-2.2, 1.5, 3.1],
568 [0.0, -3.5, 0.0],
569 [7.0, 6.5, 5.0],
570 [-9.0, 2.0, 8.0],
571 ];
572 for p in probe {
573 let (d, idx) = s.dist(p);
574 let mut naive = DIST_START;
575 let mut nidx = 0u32;
576 for (i, pr) in s.prims.iter().enumerate() {
577 let dd = pr.dist(p);
578 if dd < naive {
579 naive = dd;
580 nidx = i as u32 + 1;
581 }
582 }
583 assert_eq!((d, idx), (naive, nidx), "Probe {p:?}");
584 }
585 }
586
587 #[test]
588 fn sammel_lauf_schatten_und_ambient() {
589 let ground = SdfPrim::plane([0.0; 3], [0.0, 1.0, 0.0], BLACK);
592 let ceiling = SdfPrim::plane([0.0, 6.0, 0.0], [0.0, -1.0, 0.0], WHITE);
593 let ball = SdfPrim::sphere([0.0, 2.2, 0.0], 1.6, BLACK);
594 let s = SdfScene::from_prims(vec![ground, ceiling, ball]);
595 let cfg = GatherCfg {
596 trace: TraceCfg {
597 tmax: 30.0,
598 ..Default::default()
599 },
600 n_dirs: 64,
601 ambient: BLACK,
602 };
603 let pts = [
604 GatherPoint {
606 pos: [0.0, 0.02, 0.0],
607 n: [0.0, 1.0, 0.0],
608 self_prim: 0,
609 },
610 GatherPoint {
611 pos: [12.0, 0.02, 0.0],
612 n: [0.0, 1.0, 0.0],
613 self_prim: 0,
614 },
615 ];
616 let gi = gather(&s, &cfg, &pts);
617 assert!(
618 gi[0][0] < gi[1][0],
619 "Schattierung fehlt: {:?} vs {:?}",
620 gi[0],
621 gi[1]
622 );
623 assert!(
624 gi[1][0] > 0.0,
625 "freie Stelle ohne Einstrahlung: {:?}",
626 gi[1]
627 );
628 assert_eq!(gi, gather(&s, &cfg, &pts));
630 }
631
632 #[test]
633 fn sammel_lauf_leere_haelfte_ist_ambient() {
634 let ground = SdfPrim::plane([0.0; 3], [0.0, 1.0, 0.0], BLACK);
636 let s = SdfScene::from_prims(vec![ground]);
637 let cfg = GatherCfg {
638 trace: TraceCfg {
639 tmax: 5.0,
640 ..Default::default()
641 },
642 n_dirs: 32,
643 ambient: [0.2, 0.3, 0.4],
644 };
645 let pts = [GatherPoint {
646 pos: [1.0, 0.02, -2.0],
647 n: [0.0, 1.0, 0.0],
648 self_prim: 0,
649 }];
650 let gi = gather(&s, &cfg, &pts);
651 for (k, (got, want)) in gi[0].into_iter().zip(cfg.ambient).enumerate() {
652 assert!((got - want).abs() < 1e-6, "Kanal {k}");
653 }
654 }
655
656 #[test]
657 fn selbsttreffer_bleibt_schwarz() {
658 let ball = SdfPrim::sphere([0.0; 3], 1.0, WHITE);
661 let wall = SdfPrim::plane([0.0, 4.0, 0.0], [0.0, -1.0, 0.0], WHITE);
662 let s = SdfScene::from_prims(vec![ball, wall]);
663 let cfg = GatherCfg {
664 trace: TraceCfg {
665 tmax: 40.0,
666 ..Default::default()
667 },
668 n_dirs: 64,
669 ambient: BLACK,
670 };
671 let pts = [GatherPoint {
672 pos: [0.0, 1.02, 0.0],
673 n: [0.0, 1.0, 0.0],
674 self_prim: 0,
675 }];
676 let gi = gather(&s, &cfg, &pts);
677 assert!(gi[0][0] > 0.05 && gi[0][0] < 0.95, "gi = {:?}", gi[0]);
680 }
681
682 #[test]
683 fn richtungsraster_gleichverteilt_und_dicht() {
684 let n = [0.3f32, -0.6, 0.74];
687 let n = norm(n);
688 for i in 0..96 {
689 let d = hemi_dir(n, i);
690 assert!(dot(d, n) > 0.0, "Richtung {i} unter der Fläche");
691 assert!((len(d) - 1.0).abs() < 1e-5);
692 }
693 assert_eq!(radical2(0), 0.5);
695 assert_eq!(radical2(1), 0.25);
696 assert!(radical2(3) > 0.0 && radical2(64) < 1.0);
697 assert_eq!(radical3(0), 1.0 / 3.0);
698 }
699}