euv-core 0.56.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::*;

/// Sanitizes a floating-point scalar by replacing non-finite values with a fallback.
///
/// # Arguments
///
/// - `f32` - Input scalar to sanitize.
/// - `f32` - Fallback finite value used when input is NaN or infinite.
///
/// # Returns
///
/// - `f32` - Guaranteed finite floating-point value.
pub(crate) fn wake_sanitize_f32(value: f32, fallback: f32) -> f32 {
    if value.is_finite() { value } else { fallback }
}

/// Precomputes the per-cell damping profile combining interior viscosity with a quadratic boundary sponge ramp.
///
/// # Arguments
///
/// - `usize` - Grid width in cells.
/// - `usize` - Grid height in cells.
/// - `f32` - Base interior damping rate.
/// - `usize` - Sponge layer width in cells.
/// - `f32` - Maximum sponge damping strength at the outer edge.
///
/// # Returns
///
/// - `Vec<f32>` - Flat row-major damping table of length `width * height`.
pub(crate) fn compute_wake_damping_profile(
    width: usize,
    height: usize,
    base_damping: f32,
    sponge_width: usize,
    sponge_strength: f32,
) -> Vec<f32> {
    let total: usize = width * height;
    let mut table: Vec<f32> = vec![base_damping; total];
    if sponge_width == 0 || sponge_strength <= 0.0 {
        return table;
    }
    let sponge_span: f32 = sponge_width as f32;
    for row in 0..height {
        let dist_y: usize = row.min(height.saturating_sub(1 + row));
        for col in 0..width {
            let dist_x: usize = col.min(width.saturating_sub(1 + col));
            let edge_dist: usize = dist_x.min(dist_y);
            if edge_dist < sponge_width {
                let ramp: f32 = 1.0 - (edge_dist as f32 / sponge_span);
                let idx: usize = row * width + col;
                table[idx] = base_damping + sponge_strength * ramp * ramp;
            }
        }
    }
    table
}

/// Advances one CFL-stable damped Verlet wave substep with Neumann reflection on solid obstacles.
///
/// # Arguments
///
/// - `WakeSubstepParams` - Bundled grid dimensions and substep time constants.
/// - `&[f32]` - Current height buffer.
/// - `&[f32]` - Previous height buffer.
/// - `&[u8]` - Obstacle solid mask buffer.
/// - `&[f32]` - Precomputed per-cell damping buffer.
/// - `&mut [f32]` - Destination next-step height buffer.
/// - `&mut [f32]` - In-place wake foam buffer.
pub(crate) fn step_wake_substep(
    params: WakeSubstepParams,
    heights_curr: &[f32],
    heights_prev: &[f32],
    obstacle_mask: &[u8],
    cell_damping: &[f32],
    heights_next: &mut [f32],
    foam: &mut [f32],
) {
    let width: usize = params.get_width();
    let height: usize = params.get_height();
    let courant_sq: f32 = params.get_courant_sq();
    let dt_sub: f32 = params.get_dt_sub();
    let foam_retain: f32 = (-params.get_foam_decay_rate() * dt_sub)
        .exp()
        .clamp(0.0, 1.0);
    let inv_dt: f32 = if dt_sub > 1e-6 { 1.0 / dt_sub } else { 0.0 };
    for row in 0..height {
        let row_offset: usize = row * width;
        let row_up: usize = row.saturating_sub(1) * width;
        let row_down: usize = (row + 1).min(height - 1) * width;
        for col in 0..width {
            let idx: usize = row_offset + col;
            if obstacle_mask[idx] != 0 {
                heights_next[idx] = 0.0;
                foam[idx] = 0.0;
                continue;
            }
            let h_center: f32 = heights_curr[idx];
            let left_idx: usize = row_offset + col.saturating_sub(1);
            let right_idx: usize = row_offset + (col + 1).min(width - 1);
            let up_idx: usize = row_up + col;
            let down_idx: usize = row_down + col;
            let h_left: f32 = if obstacle_mask[left_idx] != 0 {
                h_center
            } else {
                heights_curr[left_idx]
            };
            let h_right: f32 = if obstacle_mask[right_idx] != 0 {
                h_center
            } else {
                heights_curr[right_idx]
            };
            let h_up: f32 = if obstacle_mask[up_idx] != 0 {
                h_center
            } else {
                heights_curr[up_idx]
            };
            let h_down: f32 = if obstacle_mask[down_idx] != 0 {
                h_center
            } else {
                heights_curr[down_idx]
            };
            let laplacian: f32 = h_left + h_right + h_up + h_down - 4.0 * h_center;
            let gamma: f32 = 0.5 * cell_damping[idx] * dt_sub;
            let numer: f32 =
                2.0 * h_center - (1.0 - gamma) * heights_prev[idx] + courant_sq * laplacian;
            let raw_next: f32 = numer / (1.0 + gamma);
            let next_h: f32 =
                wake_sanitize_f32(raw_next, 0.0).clamp(-WAKE_HEIGHT_CLAMP_M, WAKE_HEIGHT_CLAMP_M);
            heights_next[idx] = next_h;
            let vert_speed: f32 = (next_h - h_center).abs() * inv_dt;
            let foam_add: f32 = if vert_speed > WAKE_FOAM_VELOCITY_THRESHOLD {
                (vert_speed - WAKE_FOAM_VELOCITY_THRESHOLD) * WAKE_FOAM_GAIN * dt_sub
            } else {
                0.0
            };
            foam[idx] = (foam[idx] * foam_retain + foam_add).clamp(0.0, 1.0);
        }
    }
}

/// Bilinearly samples a flat row-major grid in continuous cell coordinates `(gx, gz)`.
///
/// # Arguments
///
/// - `&[f32]` - Flat row-major field values.
/// - `usize` - Grid width in cells.
/// - `usize` - Grid height in cells.
/// - `f32` - Continuous X cell coordinate.
/// - `f32` - Continuous Z cell coordinate.
///
/// # Returns
///
/// - `f32` - Bilinearly interpolated scalar value.
pub(crate) fn wake_bilinear_sample(
    field: &[f32],
    width: usize,
    height: usize,
    gx: f32,
    gz: f32,
) -> f32 {
    if width == 0 || height == 0 || field.len() < width * height {
        return 0.0;
    }
    let max_x: f32 = (width - 1) as f32;
    let max_z: f32 = (height - 1) as f32;
    let cx: f32 = wake_sanitize_f32(gx, 0.0).clamp(0.0, max_x);
    let cz: f32 = wake_sanitize_f32(gz, 0.0).clamp(0.0, max_z);
    let x0: usize = (cx.floor() as usize).min(width - 1);
    let z0: usize = (cz.floor() as usize).min(height - 1);
    let x1: usize = (x0 + 1).min(width - 1);
    let z1: usize = (z0 + 1).min(height - 1);
    let fx: f32 = cx - x0 as f32;
    let fz: f32 = cz - z0 as f32;
    let v00: f32 = field[z0 * width + x0];
    let v10: f32 = field[z0 * width + x1];
    let v01: f32 = field[z1 * width + x0];
    let v11: f32 = field[z1 * width + x1];
    let top: f32 = v00 + (v10 - v00) * fx;
    let bot: f32 = v01 + (v11 - v01) * fx;
    top + (bot - top) * fz
}

/// Injects a smooth radial cosine impulse into the current heightfield, previous displacement baseline, and optional foam buffer.
///
/// # Arguments
///
/// - `WaveHeightfieldConfig` - Active heightfield configuration.
/// - `WakeImpulseDesc` - Radial splash center, footprint radius, amplitude, and foam intensity.
/// - `&[u8]` - Obstacle mask slice.
/// - `(&mut [f32], &mut [f32])` - Mutable `(heights_curr, heights_prev)` buffers.
/// - `&mut [f32]` - Mutable foam buffer.
pub(crate) fn apply_wake_radial_impulse(
    config: WaveHeightfieldConfig,
    impulse: WakeImpulseDesc,
    obstacle_mask: &[u8],
    heights_pair: (&mut [f32], &mut [f32]),
    foam: &mut [f32],
) {
    let (heights_curr, heights_prev): (&mut [f32], &mut [f32]) = heights_pair;
    let width: usize = config.get_width();
    let height: usize = config.get_height();
    let dx: f32 = config.get_cell_size_m();
    let origin: Vec2 = config.get_origin_xz();
    let world_x: f32 = wake_sanitize_f32(impulse.get_world_x(), origin.get_x());
    let world_z: f32 = wake_sanitize_f32(impulse.get_world_z(), origin.get_y());
    let safe_radius: f32 = wake_sanitize_f32(impulse.get_radius_m(), dx).max(dx * 0.5);
    let safe_amp: f32 = wake_sanitize_f32(impulse.get_amplitude_m(), 0.0)
        .clamp(-WAKE_HEIGHT_CLAMP_M, WAKE_HEIGHT_CLAMP_M);
    let safe_foam: f32 = wake_sanitize_f32(impulse.get_foam_boost(), 0.0).clamp(0.0, 1.0);
    let center_gx: f32 = (world_x - origin.get_x()) / dx;
    let center_gz: f32 = (world_z - origin.get_y()) / dx;
    let cell_radius: f32 = safe_radius / dx;
    let min_col: usize = (center_gx - cell_radius).floor().max(0.0) as usize;
    let max_col: usize = (center_gx + cell_radius).ceil().min((width - 1) as f32) as usize;
    let min_row: usize = (center_gz - cell_radius).floor().max(0.0) as usize;
    let max_row: usize = (center_gz + cell_radius).ceil().min((height - 1) as f32) as usize;
    let inv_r: f32 = 1.0 / safe_radius;
    for row in min_row..=max_row {
        let cell_z: f32 = origin.get_y() + row as f32 * dx;
        let dz: f32 = cell_z - world_z;
        let row_offset: usize = row * width;
        for col in min_col..=max_col {
            let idx: usize = row_offset + col;
            if obstacle_mask[idx] != 0 {
                continue;
            }
            let cell_x: f32 = origin.get_x() + col as f32 * dx;
            let dist_x: f32 = cell_x - world_x;
            let dist: f32 = (dist_x * dist_x + dz * dz).sqrt();
            if dist <= safe_radius {
                let norm_r: f32 = dist * inv_r;
                let kernel: f32 = 0.5 * (1.0 + (PI * norm_r).cos());
                let delta: f32 = safe_amp * kernel;
                let updated: f32 =
                    (heights_curr[idx] + delta).clamp(-WAKE_HEIGHT_CLAMP_M, WAKE_HEIGHT_CLAMP_M);
                heights_curr[idx] = updated;
                heights_prev[idx] =
                    (heights_prev[idx] + delta).clamp(-WAKE_HEIGHT_CLAMP_M, WAKE_HEIGHT_CLAMP_M);
                if safe_foam > 0.0 {
                    foam[idx] = (foam[idx] + safe_foam * kernel).clamp(0.0, 1.0);
                }
            }
        }
    }
}