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

/// Converts a correlated blackbody color temperature in Kelvin (`1000..=40000 K`) to normalized linear RGB.
///
/// # Arguments
///
/// - `f32` - Color temperature in Kelvin (e.g., `1900.0` candle, `3200.0` tungsten, `6500.0` daylight, `10000.0` blue sky).
///
/// # Returns
///
/// - `Vec3` - Normalized linear RGB color in `[0.0, 1.0]`.
#[must_use]
pub fn kelvin_to_linear_rgb(kelvin: f32) -> Vec3 {
    let clamped_k: f32 = if kelvin.is_finite() {
        kelvin.clamp(KELVIN_MIN, KELVIN_MAX)
    } else {
        6_500.0
    };
    let temp: f32 = clamped_k * 0.01;
    let red_srgb: f32 = if temp <= 66.0 {
        1.0
    } else {
        let r_val: f32 = 329.698_73 * (temp - 60.0).max(0.01).powf(-0.133_204_76);
        (r_val / 255.0).clamp(0.0, 1.0)
    };
    let green_srgb: f32 = if temp <= 66.0 {
        let g_val: f32 = 99.470_8 * temp.max(1.0).ln() - 161.119_57;
        (g_val / 255.0).clamp(0.0, 1.0)
    } else {
        let g_val: f32 = 288.122_16 * (temp - 60.0).max(0.01).powf(-0.075_514_85);
        (g_val / 255.0).clamp(0.0, 1.0)
    };
    let blue_srgb: f32 = if temp >= 66.0 {
        1.0
    } else if temp <= 19.0 {
        0.0
    } else {
        let b_val: f32 = 138.517_73 * (temp - 10.0).max(0.01).ln() - 305.044_8;
        (b_val / 255.0).clamp(0.0, 1.0)
    };
    let to_linear: fn(f32) -> f32 = |ch: f32| -> f32 {
        let c: f32 = ch.clamp(0.0, 1.0);
        if c <= 0.040_45 {
            c / 12.92
        } else {
            ((c + 0.055) / 1.055).powf(2.4)
        }
    };
    Vec3::new(
        to_linear(red_srgb),
        to_linear(green_srgb),
        to_linear(blue_srgb),
    )
}

/// Evaluates physically based inverse-square attenuation `1 / (d^2 + r^2)` multiplied by Lagarde smooth range windowing.
///
/// # Arguments
///
/// - `f32` - Squared distance `d^2` from shading point to emitter in square meters.
/// - `f32` - Physical emitter source radius `r` in meters.
/// - `f32` - Maximum cutoff range in meters (`<= 0.0` disables range windowing).
///
/// # Returns
///
/// - `f32` - Non-negative finite attenuation factor (`0.0` at or beyond `range`).
#[must_use]
pub fn lagarde_attenuation(distance_sq: f32, source_radius: f32, range: f32) -> f32 {
    if !distance_sq.is_finite() {
        return 0.0;
    }
    let safe_d2: f32 = distance_sq.max(0.0);
    let safe_r: f32 = if source_radius.is_finite() {
        source_radius.max(MIN_SOURCE_RADIUS)
    } else {
        MIN_SOURCE_RADIUS
    };
    let inv_sq: f32 = 1.0 / (safe_d2 + safe_r * safe_r);
    if !range.is_finite() || range <= 0.0 {
        return inv_sq;
    }
    let ratio_sq: f32 = safe_d2 / (range * range).max(1.0e-4);
    let win: f32 = (1.0 - ratio_sq * ratio_sq).clamp(0.0, 1.0);
    inv_sq * win * win
}

/// Tests exact intersection between a 3D sphere `(center, radius)` and an `AxisAlignedBox3D`.
///
/// # Arguments
///
/// - `Vec3` - Sphere center position.
/// - `f32` - Sphere radius (`>= 0.0`).
/// - `AxisAlignedBox3D` - Axis-aligned bounding box.
///
/// # Returns
///
/// - `bool` - `true` when the sphere intersects or touches the bounding box.
#[must_use]
pub fn sphere_intersects_aabb(center: Vec3, radius: f32, bounds: AxisAlignedBox3D) -> bool {
    if !radius.is_finite() || radius < 0.0 {
        return false;
    }
    let mn: Vec3 = bounds.get_min();
    let mx: Vec3 = bounds.get_max();
    let cx: f32 = center.get_x().clamp(mn.get_x(), mx.get_x());
    let cy: f32 = center.get_y().clamp(mn.get_y(), mx.get_y());
    let cz: f32 = center.get_z().clamp(mn.get_z(), mx.get_z());
    let dx: f32 = center.get_x() - cx;
    let dy: f32 = center.get_y() - cy;
    let dz: f32 = center.get_z() - cz;
    (dx * dx + dy * dy + dz * dz) <= (radius * radius)
}

/// Evaluates an energy-conserving Cook-Torrance GGX specular + Lambertian diffuse BRDF for a single punctual light direction.
///
/// # Arguments
///
/// - `Vec3` - Unit surface normal.
/// - `Vec3` - Unit view direction pointing toward camera.
/// - `Vec3` - Unit light direction pointing toward emitter.
/// - `&PbrMaterial` - Metallic-roughness PBR material.
///
/// # Returns
///
/// - `Vec3` - Reflected RGB BRDF value multiplied by `max(N·L, 0)`.
#[must_use]
pub fn evaluate_cook_torrance_brdf(
    normal: Vec3,
    view_dir: Vec3,
    light_dir: Vec3,
    material: &PbrMaterial,
) -> Vec3 {
    let unit_n: Vec3 = normal.normalize();
    let unit_v: Vec3 = view_dir.normalize();
    let unit_l: Vec3 = light_dir.normalize();
    let n_dot_l: f32 = unit_n.dot(unit_l).max(0.0);
    if n_dot_l <= 0.0 {
        return Vec3::zero();
    }
    let n_dot_v: f32 = unit_n.dot(unit_v).max(1.0e-4);
    let half_vec: Vec3 = unit_v.add(unit_l).normalize();
    let n_dot_h: f32 = unit_n.dot(half_vec).max(0.0);
    let v_dot_h: f32 = unit_v.dot(half_vec).clamp(0.0, 1.0);
    let rough: f32 = material.get_roughness().clamp(0.04, 1.0);
    let alpha: f32 = rough * rough;
    let alpha2: f32 = alpha * alpha;
    let denom_d: f32 = n_dot_h * n_dot_h * (alpha2 - 1.0) + 1.0;
    let ndf: f32 = alpha2 / (PI * denom_d * denom_d).max(1.0e-6);
    let vis_v: f32 = n_dot_l * (alpha2 + (1.0 - alpha2) * n_dot_v * n_dot_v).sqrt();
    let vis_l: f32 = n_dot_v * (alpha2 + (1.0 - alpha2) * n_dot_l * n_dot_l).sqrt();
    let vis: f32 = 0.5 / (vis_v + vis_l).max(1.0e-5);
    let base_col: Vec3 = Vec3::new(
        material.get_base_color().get_x().clamp(0.0, 1.0),
        material.get_base_color().get_y().clamp(0.0, 1.0),
        material.get_base_color().get_z().clamp(0.0, 1.0),
    );
    let metallic: f32 = material.get_metallic().clamp(0.0, 1.0);
    let f0: Vec3 = Vec3::splat(0.04).lerp(base_col, metallic);
    let om_vh: f32 = 1.0 - v_dot_h;
    let pow5: f32 = om_vh * om_vh * om_vh * om_vh * om_vh;
    let fresnel: Vec3 = f0.add(Vec3::splat(1.0).sub(f0).scale(pow5));
    let kd: Vec3 = Vec3::splat(1.0).sub(fresnel).scale(1.0 - metallic);
    let diffuse: Vec3 = base_col.mul(kd).scale(1.0 / PI);
    let specular: Vec3 = fresnel.scale((ndf * vis).min(256.0));
    diffuse.add(specular).scale(n_dot_l)
}

/// Builds a right-handed column-major orthographic projection matrix matching `Mat4`.
///
/// # Arguments
///
/// - `f32` - Left plane coordinate.
/// - `f32` - Right plane coordinate.
/// - `f32` - Bottom plane coordinate.
/// - `f32` - Top plane coordinate.
/// - `f32` - Near plane distance.
/// - `f32` - Far plane distance.
///
/// # Returns
///
/// - `Mat4` - Column-major orthographic projection matrix.
#[must_use]
pub fn build_ortho_matrix(
    left: f32,
    right: f32,
    bottom: f32,
    top: f32,
    near: f32,
    far: f32,
) -> Mat4 {
    let inv_rl: f32 = 1.0 / (right - left).abs().max(1.0e-4) * (right - left).signum();
    let inv_tb: f32 = 1.0 / (top - bottom).abs().max(1.0e-4) * (top - bottom).signum();
    let inv_fn: f32 = 1.0 / (far - near).abs().max(1.0e-4) * (far - near).signum();
    let mut matrix: Mat4 = Mat4::identity();
    matrix.set_elements([
        2.0 * inv_rl,
        0.0,
        0.0,
        0.0,
        0.0,
        2.0 * inv_tb,
        0.0,
        0.0,
        0.0,
        0.0,
        -2.0 * inv_fn,
        0.0,
        -(right + left) * inv_rl,
        -(top + bottom) * inv_tb,
        -(far + near) * inv_fn,
        1.0,
    ]);
    matrix
}

/// Constructs a right-handed orthonormal basis `(right, up, forward)` around `direction` using `up_hint`.
///
/// # Arguments
///
/// - `Vec3` - Primary forward direction vector.
/// - `Vec3` - Preferred up reference vector.
///
/// # Returns
///
/// - `(Vec3, Vec3, Vec3)` - Orthonormal basis `(right, up, forward)` satisfying `right × up = forward`.
#[must_use]
pub fn light_orthonormal_basis(direction: Vec3, up_hint: Vec3) -> (Vec3, Vec3, Vec3) {
    let fwd: Vec3 = direction.normalize();
    let hint_unit: Vec3 = up_hint.normalize();
    let ref_up: Vec3 = if fwd.dot(hint_unit).abs() > 0.98 {
        if fwd.get_z().abs() < 0.9 {
            Vec3::new(0.0, 0.0, 1.0)
        } else {
            Vec3::new(1.0, 0.0, 0.0)
        }
    } else {
        hint_unit
    };
    let right: Vec3 = ref_up.cross(fwd).normalize();
    let up: Vec3 = fwd.cross(right).normalize();
    (right, up, fwd)
}