euv_core/game/engine3d/raytrace/denoiser/
impl.rs1use super::*;
2
3#[cfg(not(target_arch = "wasm32"))]
4unsafe impl Sync for VarianceRowMutView {}
6
7#[cfg(not(target_arch = "wasm32"))]
8impl VarianceRowMutView {
9 #[must_use]
15 pub(crate) fn ptr(&self) -> *mut f32 {
16 let Self { var_ptr } = *self;
17 var_ptr
18 }
19}
20
21#[cfg(not(target_arch = "wasm32"))]
22unsafe impl Sync for SvgfRowMutView {}
24
25#[cfg(not(target_arch = "wasm32"))]
26impl SvgfRowMutView {
27 #[must_use]
33 pub(crate) fn ptrs(&self) -> (*mut Vec3, *mut f32) {
34 let Self { color_ptr, var_ptr } = *self;
35 (color_ptr, var_ptr)
36 }
37}
38
39impl RtGBuffer {
41 #[must_use]
52 pub fn new(width: u32, height: u32) -> Self {
53 let len: usize = (width as usize).saturating_mul(height as usize);
54 Self {
55 width,
56 height,
57 albedo: vec![Vec3::zero(); len],
58 normal: vec![Vec3::zero(); len],
59 depth: vec![RT_SKY_DEPTH; len],
60 hit_mask: vec![0; len],
61 }
62 }
63
64 pub fn resize(&mut self, width: u32, height: u32) {
72 let len: usize = (width as usize).saturating_mul(height as usize);
73 self.set_width(width);
74 self.set_height(height);
75 self.get_mut_albedo().resize(len, Vec3::zero());
76 self.get_mut_normal().resize(len, Vec3::zero());
77 self.get_mut_depth().resize(len, RT_SKY_DEPTH);
78 self.get_mut_hit_mask().resize(len, 0);
79 self.clear();
80 }
81
82 pub fn clear(&mut self) {
88 self.get_mut_albedo().fill(Vec3::zero());
89 self.get_mut_normal().fill(Vec3::zero());
90 self.get_mut_depth().fill(RT_SKY_DEPTH);
91 self.get_mut_hit_mask().fill(0);
92 }
93
94 pub fn set_pixel(
105 &mut self,
106 pixel_index: usize,
107 albedo: Vec3,
108 normal: Vec3,
109 depth: f32,
110 hit: bool,
111 ) {
112 if pixel_index >= self.get_depth().len() {
113 return;
114 }
115 self.get_mut_albedo()[pixel_index] = albedo;
116 self.get_mut_normal()[pixel_index] = normal;
117 self.get_mut_depth()[pixel_index] = depth;
118 self.get_mut_hit_mask()[pixel_index] = if hit { 1 } else { 0 };
119 }
120}
121
122impl TemporalAccumulator {
124 #[must_use]
135 pub fn new(width: u32, height: u32) -> Self {
136 let len: usize = (width as usize).saturating_mul(height as usize);
137 Self {
138 width,
139 height,
140 radiance: vec![Vec3::zero(); len],
141 moment_1: vec![0.0; len],
142 moment_2: vec![0.0; len],
143 sample_counts: vec![0; len],
144 camera_fingerprint: 0,
145 scene_revision: 0,
146 max_history_samples: 0,
147 reset_count: 0,
148 }
149 }
150
151 pub fn resize(&mut self, width: u32, height: u32) {
159 let len: usize = (width as usize).saturating_mul(height as usize);
160 self.set_width(width);
161 self.set_height(height);
162 self.get_mut_radiance().resize(len, Vec3::zero());
163 self.get_mut_moment_1().resize(len, 0.0);
164 self.get_mut_moment_2().resize(len, 0.0);
165 self.get_mut_sample_counts().resize(len, 0);
166 self.reset_accumulation();
167 }
168
169 pub fn reset_accumulation(&mut self) {
175 self.get_mut_radiance().fill(Vec3::zero());
176 self.get_mut_moment_1().fill(0.0);
177 self.get_mut_moment_2().fill(0.0);
178 self.get_mut_sample_counts().fill(0);
179 let next_resets: u64 = self.get_reset_count().saturating_add(1);
180 self.set_reset_count(next_resets);
181 }
182
183 pub fn sync_motion(&mut self, camera_fingerprint: u64, scene_revision: u64) -> bool {
195 if self.get_camera_fingerprint() == camera_fingerprint
196 && self.get_scene_revision() == scene_revision
197 {
198 return false;
199 }
200 self.set_camera_fingerprint(camera_fingerprint);
201 self.set_scene_revision(scene_revision);
202 self.reset_accumulation();
203 true
204 }
205
206 pub fn accumulate_pixel(&mut self, pixel_index: usize, sample_radiance: Vec3) {
214 if pixel_index >= self.get_sample_counts().len() {
215 return;
216 }
217 let max_hist: u32 = self.get_max_history_samples();
218 let prev_n: u32 = self.get_sample_counts()[pixel_index];
219 let next_n: u32 = if max_hist > 0 {
220 prev_n.saturating_add(1).min(max_hist)
221 } else {
222 prev_n.saturating_add(1)
223 };
224 let alpha: f32 = 1.0 / (next_n.max(1) as f32);
225 let luma: f32 = rgb_luminance(sample_radiance);
226 let Self {
227 radiance,
228 moment_1,
229 moment_2,
230 sample_counts,
231 ..
232 } = self;
233 if prev_n == 0 {
234 radiance[pixel_index] = sample_radiance;
235 moment_1[pixel_index] = luma;
236 moment_2[pixel_index] = luma * luma;
237 } else {
238 radiance[pixel_index] = radiance[pixel_index].lerp(sample_radiance, alpha);
239 moment_1[pixel_index] += alpha * (luma - moment_1[pixel_index]);
240 moment_2[pixel_index] += alpha * (luma * luma - moment_2[pixel_index]);
241 }
242 sample_counts[pixel_index] = next_n;
243 }
244
245 #[must_use]
256 pub fn pixel_variance(&self, pixel_index: usize) -> f32 {
257 if pixel_index >= self.get_moment_1().len() {
258 return 0.0;
259 }
260 let m1: f32 = self.get_moment_1()[pixel_index];
261 let m2: f32 = self.get_moment_2()[pixel_index];
262 (m2 - m1 * m1).max(0.0)
263 }
264
265 pub fn write_variance_into(&self, gbuffer: &RtGBuffer, out_variance: &mut [f32]) {
273 let w: usize = self.get_width() as usize;
274 let h: usize = self.get_height() as usize;
275 let len: usize = w.saturating_mul(h);
276 if out_variance.len() < len || len == 0 {
277 return;
278 }
279 #[cfg(not(target_arch = "wasm32"))]
280 if h >= 16 && len >= 4096 {
281 let view: VarianceRowMutView = VarianceRowMutView {
282 var_ptr: out_variance.as_mut_ptr(),
283 };
284 global_engine_worker_pool().parallel_for_chunks(
285 h,
286 8,
287 |y0: usize, y1: usize, _: usize| {
288 let offset: usize = y0 * w;
289 let slice_len: usize = (y1 - y0) * w;
290 let row_out: &mut [f32] =
292 unsafe { from_raw_parts_mut(view.ptr().add(offset), slice_len) };
293 eval_variance_row_band(self, gbuffer, y0, y1, row_out);
294 },
295 );
296 return;
297 }
298 eval_variance_row_band(self, gbuffer, 0, h, &mut out_variance[..len]);
299 }
300
301 #[must_use]
311 pub fn average_variance(&self) -> f32 {
312 let len: usize = self.get_moment_1().len();
313 if len == 0 {
314 return 0.0;
315 }
316 let mut sum: f32 = 0.0;
317 for idx in 0..len {
318 sum += self.pixel_variance(idx);
319 }
320 sum / (len as f32)
321 }
322
323 #[must_use]
333 pub fn average_samples_per_pixel(&self) -> f32 {
334 let counts: &[u32] = self.get_sample_counts().as_slice();
335 if counts.is_empty() {
336 return 0.0;
337 }
338 let mut sum: u64 = 0;
339 for &c in counts {
340 sum = sum.saturating_add(c as u64);
341 }
342 (sum as f32) / (counts.len() as f32)
343 }
344}
345
346impl Default for SvgfConfig {
348 fn default() -> Self {
354 Self {
355 iterations: SVGF_DEFAULT_ITERATIONS,
356 phi_normal: SVGF_DEFAULT_PHI_NORMAL,
357 phi_depth: SVGF_DEFAULT_PHI_DEPTH,
358 phi_luma: SVGF_DEFAULT_PHI_LUMA,
359 variance_floor: 1.0e-4,
360 demodulate_albedo: false,
361 }
362 }
363}
364
365impl SvgfDenoiser {
367 #[must_use]
379 pub fn new(width: u32, height: u32, config: SvgfConfig) -> Self {
380 let len: usize = (width as usize).saturating_mul(height as usize);
381 Self {
382 config,
383 width,
384 height,
385 ping_color: vec![Vec3::zero(); len],
386 pong_color: vec![Vec3::zero(); len],
387 ping_variance: vec![0.0; len],
388 pong_variance: vec![0.0; len],
389 }
390 }
391
392 pub fn resize(&mut self, width: u32, height: u32) {
400 let len: usize = (width as usize).saturating_mul(height as usize);
401 let Self {
402 width: w_ref,
403 height: h_ref,
404 ping_color,
405 pong_color,
406 ping_variance,
407 pong_variance,
408 ..
409 } = self;
410 *w_ref = width;
411 *h_ref = height;
412 ping_color.resize(len, Vec3::zero());
413 pong_color.resize(len, Vec3::zero());
414 ping_variance.resize(len, 0.0);
415 pong_variance.resize(len, 0.0);
416 }
417
418 pub fn denoise(
428 &mut self,
429 input_radiance: &[Vec3],
430 input_variance: &[f32],
431 gbuffer: &RtGBuffer,
432 output: &mut [Vec3],
433 ) {
434 let w: usize = self.get_width() as usize;
435 let h: usize = self.get_height() as usize;
436 let len: usize = w.saturating_mul(h);
437 if len == 0
438 || input_radiance.len() < len
439 || input_variance.len() < len
440 || output.len() < len
441 || gbuffer.get_normal().len() < len
442 || gbuffer.get_depth().len() < len
443 || gbuffer.get_hit_mask().len() < len
444 {
445 return;
446 }
447 let cfg: SvgfConfig = self.get_config();
448 let iterations: u32 = cfg.get_iterations().clamp(1, SVGF_MAX_ITERATIONS);
449 let demod: bool = cfg.get_demodulate_albedo();
450 let albedos: &[Vec3] = gbuffer.get_albedo().as_slice();
451 let hit_mask: &[u8] = gbuffer.get_hit_mask().as_slice();
452 let Self {
453 ping_color,
454 pong_color,
455 ping_variance,
456 pong_variance,
457 ..
458 } = self;
459 for idx in 0..len {
460 let raw: Vec3 = input_radiance[idx];
461 if demod && hit_mask[idx] != 0 {
462 let alb: Vec3 = albedos[idx];
463 ping_color[idx] = Vec3::new(
464 raw.get_x() / alb.get_x().max(SVGF_ALBEDO_DEMOD_FLOOR),
465 raw.get_y() / alb.get_y().max(SVGF_ALBEDO_DEMOD_FLOOR),
466 raw.get_z() / alb.get_z().max(SVGF_ALBEDO_DEMOD_FLOOR),
467 );
468 } else {
469 ping_color[idx] = raw;
470 }
471 ping_variance[idx] = input_variance[idx].max(0.0);
472 }
473 for pass in 0..iterations {
474 let step: isize = 1_isize << pass;
475 let src_color: &[Vec3] = ping_color.as_slice();
476 let src_var: &[f32] = ping_variance.as_slice();
477 #[cfg(not(target_arch = "wasm32"))]
478 if h >= 16 && len >= 4096 {
479 let row_view: SvgfRowMutView = SvgfRowMutView {
480 color_ptr: pong_color.as_mut_ptr(),
481 var_ptr: pong_variance.as_mut_ptr(),
482 };
483 global_engine_worker_pool().parallel_for_chunks(
484 h,
485 8,
486 |y0: usize, y1: usize, _: usize| {
487 let offset: usize = y0 * w;
488 let slice_len: usize = (y1 - y0) * w;
489 let (c_ptr, v_ptr): (*mut Vec3, *mut f32) = row_view.ptrs();
490 let (dst_c, dst_v): (&mut [Vec3], &mut [f32]) = unsafe {
492 (
493 from_raw_parts_mut(c_ptr.add(offset), slice_len),
494 from_raw_parts_mut(v_ptr.add(offset), slice_len),
495 )
496 };
497 eval_atrous_row_band(
498 cfg,
499 gbuffer,
500 (src_color, src_var),
501 step,
502 (y0, y1),
503 (dst_c, dst_v),
504 );
505 },
506 );
507 } else {
508 eval_atrous_row_band(
509 cfg,
510 gbuffer,
511 (src_color, src_var),
512 step,
513 (0, h),
514 (&mut pong_color[..len], &mut pong_variance[..len]),
515 );
516 }
517 #[cfg(target_arch = "wasm32")]
518 {
519 eval_atrous_row_band(
520 cfg,
521 gbuffer,
522 (src_color, src_var),
523 step,
524 (0, h),
525 (&mut pong_color[..len], &mut pong_variance[..len]),
526 );
527 }
528 swap(ping_color, pong_color);
529 swap(ping_variance, pong_variance);
530 }
531 for idx in 0..len {
532 let filtered: Vec3 = ping_color[idx];
533 if demod && hit_mask[idx] != 0 {
534 let alb: Vec3 = albedos[idx];
535 output[idx] = Vec3::new(
536 (filtered.get_x() * alb.get_x().max(SVGF_ALBEDO_DEMOD_FLOOR)).max(0.0),
537 (filtered.get_y() * alb.get_y().max(SVGF_ALBEDO_DEMOD_FLOOR)).max(0.0),
538 (filtered.get_z() * alb.get_z().max(SVGF_ALBEDO_DEMOD_FLOOR)).max(0.0),
539 );
540 } else {
541 output[idx] = Vec3::new(
542 filtered.get_x().max(0.0),
543 filtered.get_y().max(0.0),
544 filtered.get_z().max(0.0),
545 );
546 }
547 }
548 }
549}