euv-core 0.57.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
use super::*;

/// Computes the combined SVGF edge-stopping weight across normal, linear depth, and luminance variance.
///
/// # Arguments
///
/// - `[Vec3; 2]` - Pair of unit world-space normals `[normal_p, normal_q]`.
/// - `[f32; 2]` - Pair of linear depths `[depth_p, depth_q]`.
/// - `[f32; 2]` - Pair of pixel luminances `[luma_p, luma_q]`.
/// - `f32` - Effective depth tolerance scale for the current à-trous step.
/// - `f32` - Filtered local standard deviation `sqrt(variance)` at pixel `p`.
/// - `SvgfConfig` - Edge-stopping tuning parameters.
///
/// # Returns
///
/// - `f32` - Non-negative edge-stopping weight in `[0.0, 1.0]`.
#[must_use]
pub fn svgf_edge_stopping_weight(
    normals: [Vec3; 2],
    depths: [f32; 2],
    luminances: [f32; 2],
    depth_scale: f32,
    luma_sigma: f32,
    config: SvgfConfig,
) -> f32 {
    let n_dot: f32 = normals[0].dot(normals[1]).clamp(0.0, 1.0);
    let w_normal: f32 = n_dot.powf(config.get_phi_normal().max(0.0));
    if w_normal <= 1e-6 {
        return 0.0;
    }
    let depth_diff: f32 = (depths[0] - depths[1]).abs();
    let depth_den: f32 = config.get_phi_depth().max(1e-4) * depth_scale.max(0.01) + SVGF_EPSILON;
    let w_depth: f32 = (-depth_diff / depth_den).exp();
    let luma_diff: f32 = (luminances[0] - luminances[1]).abs();
    let luma_den: f32 = config.get_phi_luma().max(1e-4) * luma_sigma.max(1e-3) + SVGF_EPSILON;
    let w_luma: f32 = (-luma_diff / luma_den).exp();
    (w_normal * w_depth * w_luma).clamp(0.0, 1.0)
}

/// Computes the scalar population luminance variance across an HDR RGB image buffer.
///
/// # Arguments
///
/// - `&[Vec3]` - Linear HDR RGB pixel slice.
///
/// # Returns
///
/// - `f32` - Non-negative luminance variance across all pixels.
#[must_use]
pub fn compute_image_luminance_variance(pixels: &[Vec3]) -> f32 {
    if pixels.is_empty() {
        return 0.0;
    }
    let inv_n: f32 = 1.0 / (pixels.len() as f32);
    let mut sum_l: f32 = 0.0;
    let mut sum_l2: f32 = 0.0;
    for &px in pixels {
        let l: f32 = rgb_luminance(px);
        sum_l += l;
        sum_l2 += l * l;
    }
    let mean: f32 = sum_l * inv_n;
    (sum_l2 * inv_n - mean * mean).max(0.0)
}

/// Evaluates the 3x3 Gaussian-smoothed luminance variance around `(px, py)` respecting geometry hit masks.
///
/// # Arguments
///
/// - `&[f32]` - Current variance buffer.
/// - `&[u8]` - Geometry hit mask (`1` = hit, `0` = sky).
/// - `[usize; 2]` - Image dimensions `[width, height]`.
/// - `[usize; 2]` - Center pixel coordinates `[px, py]`.
///
/// # Returns
///
/// - `f32` - Smoothed non-negative luminance variance.
#[must_use]
pub(crate) fn filter_variance_3x3(
    variance: &[f32],
    hit_mask: &[u8],
    dims: [usize; 2],
    coord: [usize; 2],
) -> f32 {
    let w: isize = dims[0] as isize;
    let h: isize = dims[1] as isize;
    let cx: isize = coord[0] as isize;
    let cy: isize = coord[1] as isize;
    let center_idx: usize = coord[1] * dims[0] + coord[0];
    let center_hit: u8 = hit_mask[center_idx];
    let mut sum: f32 = 0.0;
    let mut w_sum: f32 = 0.0;
    for dy in -1_isize..=1_isize {
        let ny: isize = cy + dy;
        if ny < 0 || ny >= h {
            continue;
        }
        for dx in -1_isize..=1_isize {
            let nx: isize = cx + dx;
            if nx < 0 || nx >= w {
                continue;
            }
            let n_idx: usize = (ny as usize) * dims[0] + (nx as usize);
            if hit_mask[n_idx] != center_hit {
                continue;
            }
            let k_idx: usize = (dx.unsigned_abs() + dy.unsigned_abs()).min(2);
            let k_w: f32 = SVGF_VARIANCE_KERNEL_3X3[k_idx];
            sum += variance[n_idx].max(0.0) * k_w;
            w_sum += k_w;
        }
    }
    if w_sum > SVGF_EPSILON {
        (sum / w_sum).max(0.0)
    } else {
        variance[center_idx].max(0.0)
    }
}

/// Estimates the local linear depth gradient magnitude at `(px, py)` for slope-aware depth edge-stopping.
///
/// # Arguments
///
/// - `&[f32]` - Linear depth buffer.
/// - `&[u8]` - Geometry hit mask.
/// - `[usize; 2]` - Image dimensions `[width, height]`.
/// - `[usize; 2]` - Center pixel coordinates `[px, py]`.
///
/// # Returns
///
/// - `f32` - Estimated positive depth gradient per pixel.
#[must_use]
pub(crate) fn estimate_depth_gradient(
    depths: &[f32],
    hit_mask: &[u8],
    dims: [usize; 2],
    coord: [usize; 2],
) -> f32 {
    let w: usize = dims[0];
    let h: usize = dims[1];
    let px: usize = coord[0];
    let py: usize = coord[1];
    let idx: usize = py * w + px;
    let z: f32 = depths[idx];
    let mask: u8 = hit_mask[idx];
    let mut gx: f32 = 0.0;
    let mut has_gx: bool = false;
    if px > 0 && hit_mask[idx - 1] == mask {
        gx = (z - depths[idx - 1]).abs();
        has_gx = true;
    }
    if px + 1 < w && hit_mask[idx + 1] == mask {
        let right_diff: f32 = (depths[idx + 1] - z).abs();
        gx = if has_gx {
            gx.min(right_diff)
        } else {
            right_diff
        };
    }
    let mut gy: f32 = 0.0;
    let mut has_gy: bool = false;
    if py > 0 && hit_mask[idx - w] == mask {
        gy = (z - depths[idx - w]).abs();
        has_gy = true;
    }
    if py + 1 < h && hit_mask[idx + w] == mask {
        let down_diff: f32 = (depths[idx + w] - z).abs();
        gy = if has_gy { gy.min(down_diff) } else { down_diff };
    }
    (gx + gy).max(0.015)
}

/// Computes luminance variance for a contiguous row band `[y_start..y_end)` into `out_slice`.
///
/// # Arguments
///
/// - `&TemporalAccumulator` - Source temporal luminance moments and sample counts.
/// - `&RtGBuffer` - Primary geometry hit mask for 1-spp spatial variance fallback.
/// - `usize` - Inclusive start row index.
/// - `usize` - Exclusive end row index.
/// - `&mut [f32]` - Destination variance slice sized `(y_end - y_start) * width`.
pub(crate) fn eval_variance_row_band(
    accum: &TemporalAccumulator,
    gbuffer: &RtGBuffer,
    y_start: usize,
    y_end: usize,
    out_slice: &mut [f32],
) {
    let w: usize = accum.get_width() as usize;
    let h: usize = accum.get_height() as usize;
    let m1: &[f32] = accum.get_moment_1().as_slice();
    let m2: &[f32] = accum.get_moment_2().as_slice();
    let counts: &[u32] = accum.get_sample_counts().as_slice();
    let rad: &[Vec3] = accum.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 y_start..y_end {
        let row_local: usize = (py - y_start) * w;
        for px in 0..w {
            let idx: usize = py * w + px;
            if counts[idx] >= 2 {
                out_slice[row_local + px] = (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_slice[row_local + px] = (sum_l2 / n_valid - mean * mean).max(0.0);
                } else {
                    out_slice[row_local + px] = 0.0;
                }
            }
        }
    }
}

/// Evaluates one À-Trous SVGF wavelet pass over a contiguous row band `[rows.0..rows.1)`.
///
/// # Arguments
///
/// - `SvgfConfig` - Edge-stopping and variance floor configuration.
/// - `&RtGBuffer` - Primary G-buffer supplying world normals, depths, and hit mask.
/// - `(&[Vec3], &[f32])` - Source `(ping_color, ping_variance)` full-frame slices.
/// - `isize` - Current À-Trous step stride (`1, 2, 4, 8, 16`).
/// - `(usize, usize)` - Contiguous `(y_start, y_end)` row band.
/// - `(&mut [Vec3], &mut [f32])` - Disjoint destination `(dst_color, dst_variance)` slices for the row band.
pub(crate) fn eval_atrous_row_band(
    cfg: SvgfConfig,
    gbuffer: &RtGBuffer,
    src: (&[Vec3], &[f32]),
    step: isize,
    rows: (usize, usize),
    dst: (&mut [Vec3], &mut [f32]),
) {
    let w: usize = gbuffer.get_width() as usize;
    let h: usize = gbuffer.get_height() as usize;
    let wi: isize = w as isize;
    let hi: isize = h as isize;
    let step_f: f32 = step as f32;
    let var_floor: f32 = cfg.get_variance_floor().max(1e-6);
    let normals: &[Vec3] = gbuffer.get_normal().as_slice();
    let depths: &[f32] = gbuffer.get_depth().as_slice();
    let hit_mask: &[u8] = gbuffer.get_hit_mask().as_slice();
    let (src_color, src_var): (&[Vec3], &[f32]) = src;
    let (y_start, y_end): (usize, usize) = rows;
    let (dst_color, dst_var): (&mut [Vec3], &mut [f32]) = dst;
    for py in y_start..y_end {
        let row_local: usize = (py - y_start) * w;
        for px in 0..w {
            let p_idx: usize = py * w + px;
            let out_idx: usize = row_local + px;
            let p_color: Vec3 = src_color[p_idx];
            let p_var: f32 = src_var[p_idx];
            let p_hit: u8 = hit_mask[p_idx];
            if p_hit == 0 {
                dst_color[out_idx] = p_color;
                dst_var[out_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(src_var, 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 = src_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 += src_var[q_idx] * total_w * total_w;
                        sum_w += total_w;
                    }
                }
            }
            let inv_w: f32 = 1.0 / sum_w.max(SVGF_EPSILON);
            dst_color[out_idx] = sum_color.scale(inv_w);
            dst_var[out_idx] = (sum_var * inv_w * inv_w).max(0.0);
        }
    }
}