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::*;

/// Encodes a linear display channel in `[0.0, 1.0]` to an 8-bit IEC 61966-2-1 sRGB byte.
///
/// # Arguments
///
/// - `f32` - Linear display color channel.
///
/// # Returns
///
/// - `u8` - Quantized sRGB byte in `0..=255`.
#[must_use]
pub fn linear_to_srgb_u8(linear: f32) -> u8 {
    let clamped: f32 = if linear.is_finite() {
        linear.clamp(0.0, 1.0)
    } else {
        0.0
    };
    let encoded: f32 = if clamped <= 0.003_130_8 {
        clamped * 12.92
    } else {
        1.055 * clamped.powf(1.0 / 2.4) - 0.055
    };
    (encoded.clamp(0.0, 1.0) * 255.0 + 0.5) as u8
}

/// Applies exposure scaling, display tone mapping (`AgX`, `ACES`, or `Linear`), and sRGB encoding to a single HDR pixel.
///
/// # Arguments
///
/// - `Vec3` - Linear scene-referred HDR RGB radiance.
/// - `RtTonemapMode` - Selected tone-mapping operator.
/// - `f32` - Positive linear exposure multiplier.
///
/// # Returns
///
/// - `[u8; 4]` - Encoded opaque sRGB `[R, G, B, 255]` pixel.
#[must_use]
pub fn tonemap_pixel(hdr: Vec3, mode: RtTonemapMode, exposure: f32) -> [u8; 4] {
    let exp_scale: f32 = exposure.max(0.0);
    let exposed: Vec3 = Vec3::new(
        if hdr.get_x().is_finite() {
            (hdr.get_x() * exp_scale).max(0.0)
        } else {
            0.0
        },
        if hdr.get_y().is_finite() {
            (hdr.get_y() * exp_scale).max(0.0)
        } else {
            0.0
        },
        if hdr.get_z().is_finite() {
            (hdr.get_z() * exp_scale).max(0.0)
        } else {
            0.0
        },
    );
    let mapped: Vec3 = match mode {
        RtTonemapMode::Agx => agx_tonemap(exposed),
        RtTonemapMode::Aces => aces_filmic_tonemap(exposed),
        RtTonemapMode::Linear => Vec3::new(
            exposed.get_x().clamp(0.0, 1.0),
            exposed.get_y().clamp(0.0, 1.0),
            exposed.get_z().clamp(0.0, 1.0),
        ),
    };
    [
        linear_to_srgb_u8(mapped.get_x()),
        linear_to_srgb_u8(mapped.get_y()),
        linear_to_srgb_u8(mapped.get_z()),
        255,
    ]
}

/// Tone-maps an entire linear HDR RGB buffer into a pre-allocated sRGB RGBA8 slice with zero heap allocation.
///
/// # Arguments
///
/// - `&[Vec3]` - Input linear HDR pixels.
/// - `RtTonemapMode` - Tone-mapping operator.
/// - `f32` - Linear exposure multiplier.
/// - `&mut [u8]` - Destination RGBA8 byte slice (`len >= hdr.len() * 4`).
pub fn tonemap_hdr_to_rgba8(
    hdr: &[Vec3],
    mode: RtTonemapMode,
    exposure: f32,
    out_rgba8: &mut [u8],
) {
    let count: usize = hdr.len().min(out_rgba8.len() / 4);
    #[cfg(not(target_arch = "wasm32"))]
    if count >= 8192 {
        let view: RgbaRowMutView = RgbaRowMutView {
            ptr: out_rgba8.as_mut_ptr(),
        };
        global_engine_worker_pool().parallel_for_chunks(
            count,
            4096,
            |start_idx: usize, end_idx: usize, _: usize| {
                let byte_offset: usize = start_idx * 4;
                let byte_len: usize = (end_idx - start_idx) * 4;
                // SAFETY: Workers claim strictly disjoint pixel ranges `[start_idx..end_idx)` within `count`.
                let dst: &mut [u8] =
                    unsafe { from_raw_parts_mut(view.ptr().add(byte_offset), byte_len) };
                for (local_i, &px) in hdr[start_idx..end_idx].iter().enumerate() {
                    let rgba: [u8; 4] = tonemap_pixel(px, mode, exposure);
                    let base: usize = local_i * 4;
                    dst[base] = rgba[0];
                    dst[base + 1] = rgba[1];
                    dst[base + 2] = rgba[2];
                    dst[base + 3] = rgba[3];
                }
            },
        );
        return;
    }
    for (idx, &px) in hdr.iter().take(count).enumerate() {
        let rgba: [u8; 4] = tonemap_pixel(px, mode, exposure);
        let base: usize = idx * 4;
        out_rgba8[base] = rgba[0];
        out_rgba8[base + 1] = rgba[1];
        out_rgba8[base + 2] = rgba[2];
        out_rgba8[base + 3] = rgba[3];
    }
}

/// Traces one full frame pass over all pixels into `accumulator` and `gbuffer`, parallelizing scanlines on native targets.
///
/// # Arguments
///
/// - `&RaytraceConfig` - Active session configuration.
/// - `&RaytraceScene` - Scene to ray-trace.
/// - `u32` - Active full-frame sample pass index (`0, 1, 2, ...`).
/// - `&mut TemporalAccumulator` - Persistent radiance and moment accumulator.
/// - `&mut RtGBuffer` - Primary G-buffer updated on first pass or unhit slots.
///
/// # Returns
///
/// - `RtRayCounter` - Aggregated primary, shadow, and bounce ray counts cast during the pass.
#[must_use]
pub(crate) fn trace_full_pass_parallel(
    cfg: &RaytraceConfig,
    scene: &RaytraceScene,
    current_pass: u32,
    accumulator: &mut TemporalAccumulator,
    gbuffer: &mut RtGBuffer,
) -> RtRayCounter {
    let width: u32 = cfg.get_width().max(1);
    let height: u32 = cfg.get_height().max(1);
    let camera: RtCamera = scene.get_camera();
    let base_seed: u32 = cfg.get_seed();
    let resolution: [u32; 2] = [width, height];
    let jitter: [f32; 2] = r2_subpixel_jitter(current_pass);
    let max_hist: u32 = accumulator.get_max_history_samples();
    #[cfg(not(target_arch = "wasm32"))]
    if height >= 16 && (width as usize).saturating_mul(height as usize) >= 4096 {
        let w_usize: usize = width as usize;
        let view: RtPassMutView = RtPassMutView {
            radiance: accumulator.get_mut_radiance().as_mut_ptr(),
            moment_1: accumulator.get_mut_moment_1().as_mut_ptr(),
            moment_2: accumulator.get_mut_moment_2().as_mut_ptr(),
            sample_counts: accumulator.get_mut_sample_counts().as_mut_ptr(),
            albedo: gbuffer.get_mut_albedo().as_mut_ptr(),
            normal: gbuffer.get_mut_normal().as_mut_ptr(),
            depth: gbuffer.get_mut_depth().as_mut_ptr(),
            hit_mask: gbuffer.get_mut_hit_mask().as_mut_ptr(),
        };
        let prim_total: AtomicU64 = AtomicU64::new(0);
        let shad_total: AtomicU64 = AtomicU64::new(0);
        let bnc_total: AtomicU64 = AtomicU64::new(0);
        global_engine_worker_pool().parallel_for_chunks(
            height as usize,
            4,
            |y_start: usize, y_end: usize, _: usize| {
                let offset: usize = y_start * w_usize;
                let band_len: usize = (y_end - y_start) * w_usize;
                let (rad_ptr, m1_ptr, m2_ptr, cnt_ptr): (*mut Vec3, *mut f32, *mut f32, *mut u32) =
                    view.accum_ptrs();
                let (alb_ptr, norm_ptr, depth_ptr, hit_ptr): (
                    *mut Vec3,
                    *mut Vec3,
                    *mut f32,
                    *mut u8,
                ) = view.gbuffer_ptrs();
                // SAFETY: Each worker receives a strictly disjoint row band `[y_start..y_end)`.
                let (rad_band, m1_band, m2_band, cnt_band): (
                    &mut [Vec3],
                    &mut [f32],
                    &mut [f32],
                    &mut [u32],
                ) = unsafe {
                    (
                        from_raw_parts_mut(rad_ptr.add(offset), band_len),
                        from_raw_parts_mut(m1_ptr.add(offset), band_len),
                        from_raw_parts_mut(m2_ptr.add(offset), band_len),
                        from_raw_parts_mut(cnt_ptr.add(offset), band_len),
                    )
                };
                // SAFETY: Each worker receives a strictly disjoint row band `[y_start..y_end)`.
                let (alb_band, norm_band, depth_band, hit_band): (
                    &mut [Vec3],
                    &mut [Vec3],
                    &mut [f32],
                    &mut [u8],
                ) = unsafe {
                    (
                        from_raw_parts_mut(alb_ptr.add(offset), band_len),
                        from_raw_parts_mut(norm_ptr.add(offset), band_len),
                        from_raw_parts_mut(depth_ptr.add(offset), band_len),
                        from_raw_parts_mut(hit_ptr.add(offset), band_len),
                    )
                };
                let mut local_counter: RtRayCounter = RtRayCounter::default();
                for py in y_start..y_end {
                    let local_row: usize = (py - y_start) * w_usize;
                    let global_row: usize = py * w_usize;
                    for px in 0..w_usize {
                        let pixel_idx: usize = global_row + px;
                        let local_idx: usize = local_row + px;
                        let mut rng: RtRng =
                            RtRng::from_pixel_sample(pixel_idx as u32, current_pass, base_seed);
                        let lens_xi: [f32; 2] = rng.next_f32_pair();
                        let ray: Ray3D = camera.generate_ray(
                            [px as u32, py as u32],
                            resolution,
                            jitter,
                            lens_xi,
                        );
                        let sample_out: RtSampleOutput =
                            dispatch_integrator_ray(cfg, scene, &ray, &mut rng, &mut local_counter);
                        let sample_rad: Vec3 = sample_out.get_radiance();
                        let prev_n: u32 = cnt_band[local_idx];
                        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_rad);
                        if prev_n == 0 {
                            rad_band[local_idx] = sample_rad;
                            m1_band[local_idx] = luma;
                            m2_band[local_idx] = luma * luma;
                        } else {
                            rad_band[local_idx] = rad_band[local_idx].lerp(sample_rad, alpha);
                            m1_band[local_idx] += alpha * (luma - m1_band[local_idx]);
                            m2_band[local_idx] += alpha * (luma * luma - m2_band[local_idx]);
                        }
                        cnt_band[local_idx] = next_n;
                        if current_pass == 0 || hit_band[local_idx] == 0 {
                            alb_band[local_idx] = sample_out.get_albedo();
                            norm_band[local_idx] = sample_out.get_normal();
                            depth_band[local_idx] = sample_out.get_depth();
                            hit_band[local_idx] = u8::from(sample_out.get_hit());
                        }
                    }
                }
                let _: u64 =
                    prim_total.fetch_add(local_counter.get_primary_rays(), Ordering::Relaxed);
                let _: u64 =
                    shad_total.fetch_add(local_counter.get_shadow_rays(), Ordering::Relaxed);
                let _: u64 =
                    bnc_total.fetch_add(local_counter.get_bounce_rays(), Ordering::Relaxed);
            },
        );
        let mut total_counter: RtRayCounter = RtRayCounter::default();
        total_counter.add_primary(prim_total.load(Ordering::Relaxed));
        total_counter.add_shadow(shad_total.load(Ordering::Relaxed));
        total_counter.add_bounce(bnc_total.load(Ordering::Relaxed));
        return total_counter;
    }
    let _: u32 = max_hist;
    let mut serial_counter: RtRayCounter = RtRayCounter::default();
    for py in 0..height {
        let row_offset: usize = (py as usize) * (width as usize);
        for px in 0..width {
            let pixel_idx: usize = row_offset + (px as usize);
            let mut rng: RtRng =
                RtRng::from_pixel_sample(pixel_idx as u32, current_pass, base_seed);
            let lens_xi: [f32; 2] = rng.next_f32_pair();
            let ray: Ray3D = camera.generate_ray([px, py], resolution, jitter, lens_xi);
            let sample_out: RtSampleOutput =
                dispatch_integrator_ray(cfg, scene, &ray, &mut rng, &mut serial_counter);
            accumulator.accumulate_pixel(pixel_idx, sample_out.get_radiance());
            if current_pass == 0 || gbuffer.get_hit_mask()[pixel_idx] == 0 {
                gbuffer.set_pixel(
                    pixel_idx,
                    sample_out.get_albedo(),
                    sample_out.get_normal(),
                    sample_out.get_depth(),
                    sample_out.get_hit(),
                );
            }
        }
    }
    serial_counter
}

/// Dispatches a primary ray to the integrator selected by `config`.
///
/// # Arguments
///
/// - `&RaytraceConfig` - Active session configuration.
/// - `&RaytraceScene` - Scene to trace.
/// - `&Ray3D` - Primary camera ray.
/// - `&mut RtRng` - Deterministic per-pixel RNG.
/// - `&mut RtRayCounter` - Step ray telemetry counter.
///
/// # Returns
///
/// - `RtSampleOutput` - Traced radiance and primary G-buffer record.
#[must_use]
pub(crate) fn dispatch_integrator_ray(
    config: &RaytraceConfig,
    scene: &RaytraceScene,
    ray: &Ray3D,
    rng: &mut RtRng,
    counter: &mut RtRayCounter,
) -> RtSampleOutput {
    match config.get_integrator() {
        RtIntegratorMode::Whitted => config.get_whitted().trace_ray(scene, ray, rng, counter),
        RtIntegratorMode::PathTrace => config.get_path_trace().trace_ray(scene, ray, rng, counter),
        RtIntegratorMode::Rtao => config.get_rtao().trace_ray(scene, ray, rng, counter),
        RtIntegratorMode::HybridPreview => config
            .get_hybrid_preview()
            .trace_ray(scene, ray, rng, counter),
    }
}

/// Captures a cross-platform `RtTimer` start timestamp for wall-clock step telemetry.
///
/// # Returns
///
/// - `RtTimer` - Started timer token.
#[must_use]
pub(crate) fn rt_now() -> RtTimer {
    #[cfg(not(target_arch = "wasm32"))]
    {
        RtTimer {
            start: Instant::now(),
        }
    }
    #[cfg(target_arch = "wasm32")]
    {
        RtTimer { start: 0 }
    }
}

/// Computes elapsed wall-clock milliseconds since `timer` was created (`0.0` on `wasm32`).
///
/// # Arguments
///
/// - `RtTimer` - Previously captured timer token.
///
/// # Returns
///
/// - `f32` - Elapsed duration in milliseconds.
#[must_use]
pub(crate) fn rt_elapsed_ms(timer: RtTimer) -> f32 {
    #[cfg(not(target_arch = "wasm32"))]
    {
        let RtTimer { start } = timer;
        start.elapsed().as_secs_f32() * 1000.0
    }
    #[cfg(target_arch = "wasm32")]
    {
        let RtTimer { start } = timer;
        start as f32
    }
}