1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
use super::*;
/// Persistent G-buffer allocation, clearing, and per-pixel update helpers for `RtGBuffer`.
impl RtGBuffer {
/// Allocates a new `RtGBuffer` sized for `width x height` pixels.
///
/// # Arguments
///
/// - `u32` - Viewport width in pixels.
/// - `u32` - Viewport height in pixels.
///
/// # Returns
///
/// - `Self` - Pre-allocated G-buffer.
#[must_use]
pub fn new(width: u32, height: u32) -> Self {
let len: usize = (width as usize).saturating_mul(height as usize);
Self {
width,
height,
albedo: vec![Vec3::zero(); len],
normal: vec![Vec3::zero(); len],
depth: vec![RT_SKY_DEPTH; len],
hit_mask: vec![0; len],
}
}
/// Resizes the G-buffer in place and clears all channels to default miss values.
///
/// # Arguments
///
/// - `&Self` - Mutable G-buffer reference.
/// - `u32` - New viewport width in pixels.
/// - `u32` - New viewport height in pixels.
pub fn resize(&mut self, width: u32, height: u32) {
let len: usize = (width as usize).saturating_mul(height as usize);
self.set_width(width);
self.set_height(height);
self.get_mut_albedo().resize(len, Vec3::zero());
self.get_mut_normal().resize(len, Vec3::zero());
self.get_mut_depth().resize(len, RT_SKY_DEPTH);
self.get_mut_hit_mask().resize(len, 0);
self.clear();
}
/// Resets all G-buffer channels in place with zero heap allocation.
///
/// # Arguments
///
/// - `&Self` - Mutable G-buffer reference.
pub fn clear(&mut self) {
self.get_mut_albedo().fill(Vec3::zero());
self.get_mut_normal().fill(Vec3::zero());
self.get_mut_depth().fill(RT_SKY_DEPTH);
self.get_mut_hit_mask().fill(0);
}
/// Writes primary G-buffer attributes for a single pixel index.
///
/// # Arguments
///
/// - `&Self` - Mutable G-buffer reference.
/// - `usize` - Linear pixel index (`py * width + px`).
/// - `Vec3` - Primary surface albedo.
/// - `Vec3` - Primary world-space shading normal.
/// - `f32` - Primary linear hit distance.
/// - `bool` - Whether the primary ray hit geometry.
pub fn set_pixel(
&mut self,
pixel_index: usize,
albedo: Vec3,
normal: Vec3,
depth: f32,
hit: bool,
) {
if pixel_index >= self.get_depth().len() {
return;
}
self.get_mut_albedo()[pixel_index] = albedo;
self.get_mut_normal()[pixel_index] = normal;
self.get_mut_depth()[pixel_index] = depth;
self.get_mut_hit_mask()[pixel_index] = if hit { 1 } else { 0 };
}
}
/// Progressive temporal accumulation, variance tracking, and motion reset for `TemporalAccumulator`.
impl TemporalAccumulator {
/// Creates a pre-allocated `TemporalAccumulator` for `width x height` pixels.
///
/// # Arguments
///
/// - `u32` - Viewport width in pixels.
/// - `u32` - Viewport height in pixels.
///
/// # Returns
///
/// - `Self` - Pre-allocated temporal accumulator.
#[must_use]
pub fn new(width: u32, height: u32) -> Self {
let len: usize = (width as usize).saturating_mul(height as usize);
Self {
width,
height,
radiance: vec![Vec3::zero(); len],
moment_1: vec![0.0; len],
moment_2: vec![0.0; len],
sample_counts: vec![0; len],
camera_fingerprint: 0,
scene_revision: 0,
max_history_samples: 0,
reset_count: 0,
}
}
/// Resizes all accumulation buffers and resets accumulated samples to zero.
///
/// # Arguments
///
/// - `&Self` - Mutable accumulator reference.
/// - `u32` - New viewport width in pixels.
/// - `u32` - New viewport height in pixels.
pub fn resize(&mut self, width: u32, height: u32) {
let len: usize = (width as usize).saturating_mul(height as usize);
self.set_width(width);
self.set_height(height);
self.get_mut_radiance().resize(len, Vec3::zero());
self.get_mut_moment_1().resize(len, 0.0);
self.get_mut_moment_2().resize(len, 0.0);
self.get_mut_sample_counts().resize(len, 0);
self.reset_accumulation();
}
/// Clears all accumulated radiance, luminance moments, and sample counts in place with zero heap allocation.
///
/// # Arguments
///
/// - `&Self` - Mutable accumulator reference.
pub fn reset_accumulation(&mut self) {
self.get_mut_radiance().fill(Vec3::zero());
self.get_mut_moment_1().fill(0.0);
self.get_mut_moment_2().fill(0.0);
self.get_mut_sample_counts().fill(0);
let next_resets: u64 = self.get_reset_count().saturating_add(1);
self.set_reset_count(next_resets);
}
/// Synchronizes camera and scene fingerprints, automatically resetting accumulation whenever either changes.
///
/// # Arguments
///
/// - `&Self` - Mutable accumulator reference.
/// - `u64` - Current `RtCamera::motion_fingerprint()`.
/// - `u64` - Current `RaytraceScene::get_revision()`.
///
/// # Returns
///
/// - `bool` - `true` when motion or scene mutation triggered an accumulation reset.
pub fn sync_motion(&mut self, camera_fingerprint: u64, scene_revision: u64) -> bool {
if self.get_camera_fingerprint() == camera_fingerprint
&& self.get_scene_revision() == scene_revision
{
return false;
}
self.set_camera_fingerprint(camera_fingerprint);
self.set_scene_revision(scene_revision);
self.reset_accumulation();
true
}
/// Incorporates a new HDR radiance sample at `pixel_index`, updating running mean radiance and luminance moments (`M1`, `M2`).
///
/// # Arguments
///
/// - `&Self` - Mutable accumulator reference.
/// - `usize` - Linear pixel index.
/// - `Vec3` - Sanitized linear HDR RGB sample radiance.
pub fn accumulate_pixel(&mut self, pixel_index: usize, sample_radiance: Vec3) {
if pixel_index >= self.get_sample_counts().len() {
return;
}
let max_hist: u32 = self.get_max_history_samples();
let prev_n: u32 = self.get_sample_counts()[pixel_index];
let next_n: u32 = if max_hist > 0 {
prev_n.saturating_add(1).min(max_hist)
} else {
prev_n.saturating_add(1)
};
let alpha: f32 = 1.0 / (next_n.max(1) as f32);
let luma: f32 = rgb_luminance(sample_radiance);
let Self {
radiance,
moment_1,
moment_2,
sample_counts,
..
} = self;
if prev_n == 0 {
radiance[pixel_index] = sample_radiance;
moment_1[pixel_index] = luma;
moment_2[pixel_index] = luma * luma;
} else {
radiance[pixel_index] = radiance[pixel_index].lerp(sample_radiance, alpha);
moment_1[pixel_index] += alpha * (luma - moment_1[pixel_index]);
moment_2[pixel_index] += alpha * (luma * luma - moment_2[pixel_index]);
}
sample_counts[pixel_index] = next_n;
}
/// Returns the tracked temporal luminance variance `max(0, M2 - M1^2)` for `pixel_index`.
///
/// # Arguments
///
/// - `&Self` - Accumulator reference.
/// - `usize` - Linear pixel index.
///
/// # Returns
///
/// - `f32` - Non-negative temporal variance estimate.
#[must_use]
pub fn pixel_variance(&self, pixel_index: usize) -> f32 {
if pixel_index >= self.get_moment_1().len() {
return 0.0;
}
let m1: f32 = self.get_moment_1()[pixel_index];
let m2: f32 = self.get_moment_2()[pixel_index];
(m2 - m1 * m1).max(0.0)
}
/// Writes per-pixel temporal (or 3x3 spatial fallback at `spp <= 1`) luminance variance into `out_variance` with zero heap allocation.
///
/// # Arguments
///
/// - `&Self` - Accumulator reference.
/// - `&RtGBuffer` - Primary G-buffer used for edge-aware 1-spp spatial variance fallback.
/// - `&mut [f32]` - Pre-allocated output variance slice (`len == width * height`).
pub fn write_variance_into(&self, gbuffer: &RtGBuffer, out_variance: &mut [f32]) {
let w: usize = self.get_width() as usize;
let h: usize = self.get_height() as usize;
let len: usize = w.saturating_mul(h);
if out_variance.len() < len || len == 0 {
return;
}
let m1: &[f32] = self.get_moment_1().as_slice();
let m2: &[f32] = self.get_moment_2().as_slice();
let counts: &[u32] = self.get_sample_counts().as_slice();
let rad: &[Vec3] = self.get_radiance().as_slice();
let hit_mask: &[u8] = gbuffer.get_hit_mask().as_slice();
let wi: isize = w as isize;
let hi: isize = h as isize;
for py in 0..h {
for px in 0..w {
let idx: usize = py * w + px;
if counts[idx] >= 2 {
out_variance[idx] = (m2[idx] - m1[idx] * m1[idx]).max(0.0);
} else {
let center_hit: u8 = hit_mask.get(idx).copied().unwrap_or(0);
let mut sum_l: f32 = 0.0;
let mut sum_l2: f32 = 0.0;
let mut n_valid: f32 = 0.0;
for dy in -1_isize..=1_isize {
let ny: isize = (py as isize) + dy;
if ny < 0 || ny >= hi {
continue;
}
for dx in -1_isize..=1_isize {
let nx: isize = (px as isize) + dx;
if nx < 0 || nx >= wi {
continue;
}
let n_idx: usize = (ny as usize) * w + (nx as usize);
if hit_mask.get(n_idx).copied().unwrap_or(0) != center_hit {
continue;
}
let l: f32 = rgb_luminance(rad[n_idx]);
sum_l += l;
sum_l2 += l * l;
n_valid += 1.0;
}
}
if n_valid > 1.0 {
let mean: f32 = sum_l / n_valid;
out_variance[idx] = (sum_l2 / n_valid - mean * mean).max(0.0);
} else {
out_variance[idx] = 0.0;
}
}
}
}
}
/// Computes the average temporal variance across all accumulated pixels.
///
/// # Arguments
///
/// - `&Self` - Accumulator reference.
///
/// # Returns
///
/// - `f32` - Mean pixel luminance variance.
#[must_use]
pub fn average_variance(&self) -> f32 {
let len: usize = self.get_moment_1().len();
if len == 0 {
return 0.0;
}
let mut sum: f32 = 0.0;
for idx in 0..len {
sum += self.pixel_variance(idx);
}
sum / (len as f32)
}
/// Computes the average accumulated sample count per pixel across the viewport.
///
/// # Arguments
///
/// - `&Self` - Accumulator reference.
///
/// # Returns
///
/// - `f32` - Mean samples per pixel (`spp`).
#[must_use]
pub fn average_samples_per_pixel(&self) -> f32 {
let counts: &[u32] = self.get_sample_counts().as_slice();
if counts.is_empty() {
return 0.0;
}
let mut sum: u64 = 0;
for &c in counts {
sum = sum.saturating_add(c as u64);
}
(sum as f32) / (counts.len() as f32)
}
}
/// Default SVGF edge-stopping configuration constructor for `SvgfConfig`.
impl Default for SvgfConfig {
/// Creates a balanced 4-iteration À-Trous SVGF configuration preserving crisp normals and depth edges.
///
/// # Returns
///
/// - `Self` - Default `SvgfConfig`.
fn default() -> Self {
Self {
iterations: SVGF_DEFAULT_ITERATIONS,
phi_normal: SVGF_DEFAULT_PHI_NORMAL,
phi_depth: SVGF_DEFAULT_PHI_DEPTH,
phi_luma: SVGF_DEFAULT_PHI_LUMA,
variance_floor: 1.0e-4,
demodulate_albedo: false,
}
}
}
/// Zero-allocation multi-pass À-Trous wavelet spatial denoising for `SvgfDenoiser`.
impl SvgfDenoiser {
/// Creates a pre-allocated `SvgfDenoiser` for `width x height` pixels with the specified `config`.
///
/// # Arguments
///
/// - `u32` - Viewport width in pixels.
/// - `u32` - Viewport height in pixels.
/// - `SvgfConfig` - Edge-stopping and iteration parameters.
///
/// # Returns
///
/// - `Self` - Pre-allocated denoiser ready for zero-alloc `denoise()` calls.
#[must_use]
pub fn new(width: u32, height: u32, config: SvgfConfig) -> Self {
let len: usize = (width as usize).saturating_mul(height as usize);
Self {
config,
width,
height,
ping_color: vec![Vec3::zero(); len],
pong_color: vec![Vec3::zero(); len],
ping_variance: vec![0.0; len],
pong_variance: vec![0.0; len],
}
}
/// Resizes internal ping-pong scratch buffers to match `width x height`.
///
/// # Arguments
///
/// - `&Self` - Mutable denoiser reference.
/// - `u32` - New viewport width.
/// - `u32` - New viewport height.
pub fn resize(&mut self, width: u32, height: u32) {
let len: usize = (width as usize).saturating_mul(height as usize);
let Self {
width: w_ref,
height: h_ref,
ping_color,
pong_color,
ping_variance,
pong_variance,
..
} = self;
*w_ref = width;
*h_ref = height;
ping_color.resize(len, Vec3::zero());
pong_color.resize(len, Vec3::zero());
ping_variance.resize(len, 0.0);
pong_variance.resize(len, 0.0);
}
/// Executes multi-pass edge-stopping À-Trous wavelet spatial filtering with zero steady-state heap allocations.
///
/// # Arguments
///
/// - `&Self` - Mutable denoiser owning pre-allocated ping-pong buffers.
/// - `&[Vec3]` - Input noisy or temporally accumulated HDR radiance buffer.
/// - `&[f32]` - Per-pixel luminance variance buffer guiding `phi_luma`.
/// - `&RtGBuffer` - Primary G-buffer supplying world normals, linear depth, albedo, and hit mask.
/// - `&mut [Vec3]` - Destination denoised HDR radiance slice (`len == width * height`).
pub fn denoise(
&mut self,
input_radiance: &[Vec3],
input_variance: &[f32],
gbuffer: &RtGBuffer,
output: &mut [Vec3],
) {
let w: usize = self.get_width() as usize;
let h: usize = self.get_height() as usize;
let len: usize = w.saturating_mul(h);
if len == 0
|| input_radiance.len() < len
|| input_variance.len() < len
|| output.len() < len
|| gbuffer.get_normal().len() < len
|| gbuffer.get_depth().len() < len
|| gbuffer.get_hit_mask().len() < len
{
return;
}
let cfg: SvgfConfig = self.get_config();
let iterations: u32 = cfg.get_iterations().clamp(1, SVGF_MAX_ITERATIONS);
let demod: bool = cfg.get_demodulate_albedo();
let normals: &[Vec3] = gbuffer.get_normal().as_slice();
let depths: &[f32] = gbuffer.get_depth().as_slice();
let albedos: &[Vec3] = gbuffer.get_albedo().as_slice();
let hit_mask: &[u8] = gbuffer.get_hit_mask().as_slice();
let Self {
ping_color,
pong_color,
ping_variance,
pong_variance,
..
} = self;
for idx in 0..len {
let raw: Vec3 = input_radiance[idx];
if demod && hit_mask[idx] != 0 {
let alb: Vec3 = albedos[idx];
ping_color[idx] = Vec3::new(
raw.get_x() / alb.get_x().max(SVGF_ALBEDO_DEMOD_FLOOR),
raw.get_y() / alb.get_y().max(SVGF_ALBEDO_DEMOD_FLOOR),
raw.get_z() / alb.get_z().max(SVGF_ALBEDO_DEMOD_FLOOR),
);
} else {
ping_color[idx] = raw;
}
ping_variance[idx] = input_variance[idx].max(0.0);
}
let wi: isize = w as isize;
let hi: isize = h as isize;
let var_floor: f32 = cfg.get_variance_floor().max(1e-6);
for pass in 0..iterations {
let step: isize = 1_isize << pass;
let step_f: f32 = step as f32;
for py in 0..h {
for px in 0..w {
let p_idx: usize = py * w + px;
let p_color: Vec3 = ping_color[p_idx];
let p_var: f32 = ping_variance[p_idx];
let p_hit: u8 = hit_mask[p_idx];
if p_hit == 0 {
pong_color[p_idx] = p_color;
pong_variance[p_idx] = p_var;
continue;
}
let p_normal: Vec3 = normals[p_idx];
let p_depth: f32 = depths[p_idx];
let p_luma: f32 = rgb_luminance(p_color);
let filtered_var: f32 =
filter_variance_3x3(ping_variance.as_slice(), hit_mask, [w, h], [px, py]);
let luma_sigma: f32 = filtered_var.max(var_floor).sqrt();
let grad_z: f32 = estimate_depth_gradient(depths, hit_mask, [w, h], [px, py]);
let center_k: f32 = SVGF_ATROUS_KERNEL_1D[0] * SVGF_ATROUS_KERNEL_1D[0];
let mut sum_color: Vec3 = p_color.scale(center_k);
let mut sum_var: f32 = p_var * center_k * center_k;
let mut sum_w: f32 = center_k;
for ky in -2_isize..=2_isize {
let qy: isize = (py as isize) + ky * step;
if qy < 0 || qy >= hi {
continue;
}
let wy_k: f32 = SVGF_ATROUS_KERNEL_1D[ky.unsigned_abs()];
for kx in -2_isize..=2_isize {
if kx == 0 && ky == 0 {
continue;
}
let qx: isize = (px as isize) + kx * step;
if qx < 0 || qx >= wi {
continue;
}
let q_idx: usize = (qy as usize) * w + (qx as usize);
if hit_mask[q_idx] != p_hit {
continue;
}
let k_weight: f32 = wy_k * SVGF_ATROUS_KERNEL_1D[kx.unsigned_abs()];
let q_color: Vec3 = ping_color[q_idx];
let q_luma: f32 = rgb_luminance(q_color);
let dist_step: f32 = ((kx * kx + ky * ky) as f32).sqrt() * step_f;
let edge_w: f32 = svgf_edge_stopping_weight(
[p_normal, normals[q_idx]],
[p_depth, depths[q_idx]],
[p_luma, q_luma],
grad_z * dist_step + 0.02,
luma_sigma,
cfg,
);
let total_w: f32 = k_weight * edge_w;
if total_w > 1e-6 {
sum_color = sum_color.add(q_color.scale(total_w));
sum_var += ping_variance[q_idx] * total_w * total_w;
sum_w += total_w;
}
}
}
let inv_w: f32 = 1.0 / sum_w.max(SVGF_EPSILON);
pong_color[p_idx] = sum_color.scale(inv_w);
pong_variance[p_idx] = (sum_var * inv_w * inv_w).max(0.0);
}
}
swap(ping_color, pong_color);
swap(ping_variance, pong_variance);
}
for idx in 0..len {
let filtered: Vec3 = ping_color[idx];
if demod && hit_mask[idx] != 0 {
let alb: Vec3 = albedos[idx];
output[idx] = Vec3::new(
(filtered.get_x() * alb.get_x().max(SVGF_ALBEDO_DEMOD_FLOOR)).max(0.0),
(filtered.get_y() * alb.get_y().max(SVGF_ALBEDO_DEMOD_FLOOR)).max(0.0),
(filtered.get_z() * alb.get_z().max(SVGF_ALBEDO_DEMOD_FLOOR)).max(0.0),
);
} else {
output[idx] = Vec3::new(
filtered.get_x().max(0.0),
filtered.get_y().max(0.0),
filtered.get_z().max(0.0),
);
}
}
}
}