euv-core 0.48.3

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

/// Default 60Hz integer-nanosecond fixed-timestep `FrameClock` with 8-substep safety cap.
impl Default for FrameClock {
    /// Creates a `FrameClock` configured for 60Hz (`16_666_667 ns`) fixed simulation steps.
    ///
    /// # Returns
    ///
    /// - `Self` - Default 60Hz game clock.
    fn default() -> Self {
        Self::from_fixed_step_ns(CLOCK_DEFAULT_FIXED_STEP_NS, CLOCK_DEFAULT_MAX_SUBSTEPS)
    }
}

/// Nanosecond fixed-step accumulation, VSync hysteresis snapping, and dt-invariant FPS telemetry for `FrameClock`.
impl FrameClock {
    /// Constructs a `FrameClock` from a fixed timestep in seconds and substep cap.
    ///
    /// # Arguments
    ///
    /// - `f32` - Fixed simulation timestep in seconds (e.g. `1.0 / 60.0`).
    /// - `u32` - Upper cap on fixed substeps executed per rendered frame.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured integer-nanosecond frame clock.
    #[must_use]
    pub fn new(fixed_dt: f32, max_substeps: u32) -> Self {
        let safe_dt: f32 = if fixed_dt.is_finite() {
            fixed_dt.max(0.000_1)
        } else {
            1.0 / 60.0
        };
        let step_ns: u64 = ((safe_dt as f64) * CLOCK_NS_PER_SEC_F64)
            .round()
            .max(CLOCK_MIN_FIXED_STEP_NS as f64) as u64;
        Self::from_fixed_step_ns(step_ns, max_substeps)
    }

    /// Constructs a `FrameClock` directly from an exact integer-nanosecond simulation period.
    ///
    /// # Arguments
    ///
    /// - `u64` - Fixed simulation step duration in nanoseconds (`16_666_667` for 60Hz, `8_333_333` for 120Hz).
    /// - `u32` - Upper cap on fixed substeps executed per rendered frame.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured integer-nanosecond frame clock.
    #[must_use]
    pub fn from_fixed_step_ns(fixed_step_ns: u64, max_substeps: u32) -> Self {
        let safe_ns: u64 = fixed_step_ns.max(CLOCK_MIN_FIXED_STEP_NS);
        Self {
            fixed_dt: ((safe_ns as f64) / CLOCK_NS_PER_SEC_F64) as f32,
            fixed_step_ns: safe_ns,
            max_substeps: max_substeps.max(1),
            accumulator_ns: 0,
            accumulator: 0.0,
            delta_ns: 0,
            delta_secs: 0.0,
            elapsed_ns: 0,
            elapsed_secs: 0.0,
            alpha: 0.0,
            fps: 0.0,
            frame_count: 0,
            fixed_step_count: 0,
        }
    }

    /// Constructs a `FrameClock` for an integer simulation frequency in Hertz (e.g. `60` or `120`).
    ///
    /// # Arguments
    ///
    /// - `u32` - Simulation tick frequency in Hertz (`1..=1000`).
    /// - `u32` - Upper cap on fixed substeps executed per rendered frame.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured integer-nanosecond frame clock.
    #[must_use]
    pub fn for_sim_hz(sim_hz: u32, max_substeps: u32) -> Self {
        let clamped_hz: u64 = (sim_hz.clamp(1, 1000)) as u64;
        let step_ns: u64 = (CLOCK_NS_PER_SEC + clamped_hz / 2) / clamped_hz;
        Self::from_fixed_step_ns(step_ns, max_substeps)
    }

    /// Returns the ±0.5% VSync-boundary hysteresis snap window in nanoseconds (`±83_333 ns` at 60Hz).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Frame clock reference.
    ///
    /// # Returns
    ///
    /// - `u64` - Hysteresis tolerance window in nanoseconds.
    #[must_use]
    pub fn hysteresis_window_ns(&self) -> u64 {
        let safe_fixed_ns: u64 = self.get_fixed_step_ns().max(CLOCK_MIN_FIXED_STEP_NS);
        (safe_fixed_ns / CLOCK_HYSTERESIS_DIVISOR).max(1)
    }

    /// Advances the clock by `raw_dt_ns` nanoseconds using ±0.5% VSync-boundary hysteresis snapping and dt-invariant FPS smoothing.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable frame clock.
    /// - `u64` - Unclamped elapsed nanoseconds since the previous frame.
    ///
    /// # Returns
    ///
    /// - `u32` - Number of fixed-timestep simulation updates to execute this frame.
    pub fn tick_ns(&mut self, raw_dt_ns: u64) -> u32 {
        let mut safe_fixed_ns: u64 = self.get_fixed_step_ns().max(CLOCK_MIN_FIXED_STEP_NS);
        let expected_dt_f32: f32 = ((safe_fixed_ns as f64) / CLOCK_NS_PER_SEC_F64) as f32;
        if (self.get_fixed_dt() - expected_dt_f32).abs() > 1e-5 && self.get_fixed_dt().is_finite() {
            let safe_dt: f32 = self.get_fixed_dt().max(0.000_1);
            safe_fixed_ns = ((safe_dt as f64) * CLOCK_NS_PER_SEC_F64)
                .round()
                .max(CLOCK_MIN_FIXED_STEP_NS as f64) as u64;
            self.set_fixed_step_ns(safe_fixed_ns);
        }
        let dt_ns: u64 = raw_dt_ns.min(CLOCK_MAX_FRAME_DT_NS);
        let dt_secs: f32 = ((dt_ns as f64) / CLOCK_NS_PER_SEC_F64) as f32;
        self.set_delta_ns(dt_ns);
        self.set_delta_secs(dt_secs);
        let next_elapsed_ns: u64 = self.get_elapsed_ns().saturating_add(dt_ns);
        self.set_elapsed_ns(next_elapsed_ns);
        self.set_elapsed_secs((next_elapsed_ns as f64) / CLOCK_NS_PER_SEC_F64);
        self.set_frame_count(self.get_frame_count().saturating_add(1));
        if dt_ns > 0 {
            let inst_fps: f32 = (CLOCK_NS_PER_SEC_F64 / (dt_ns as f64)) as f32;
            let prev_fps: f32 = self.get_fps();
            let smoothed: f32 = if prev_fps <= 0.0 {
                inst_fps
            } else {
                let ema_alpha: f32 =
                    (1.0 - (-dt_secs / CLOCK_FPS_EMA_TAU_SECS).exp()).clamp(0.0, 1.0);
                prev_fps + (inst_fps - prev_fps) * ema_alpha
            };
            self.set_fps(smoothed);
        }
        let snap_window_ns: u64 = (safe_fixed_ns / CLOCK_HYSTERESIS_DIVISOR).max(1);
        let mut acc_ns: u64 = self.get_accumulator_ns().saturating_add(dt_ns);
        let rem_before: u64 = acc_ns % safe_fixed_ns;
        if rem_before > 0 && safe_fixed_ns - rem_before <= snap_window_ns {
            acc_ns = acc_ns.saturating_add(safe_fixed_ns - rem_before);
        }
        let max_steps: u32 = self.get_max_substeps().max(1);
        let mut steps: u32 = 0;
        while acc_ns >= safe_fixed_ns && steps < max_steps {
            acc_ns -= safe_fixed_ns;
            steps += 1;
        }
        if (steps == max_steps && acc_ns >= safe_fixed_ns)
            || (steps > 0 && acc_ns <= snap_window_ns)
        {
            acc_ns = 0;
        }
        self.set_accumulator_ns(acc_ns);
        self.set_accumulator(((acc_ns as f64) / CLOCK_NS_PER_SEC_F64) as f32);
        self.set_alpha(((acc_ns as f64) / (safe_fixed_ns as f64)).clamp(0.0, 1.0) as f32);
        self.set_fixed_step_count(self.get_fixed_step_count().saturating_add(steps as u64));
        steps
    }

    /// Advances the clock by `raw_dt_secs` seconds (converted to integer nanoseconds) and returns how many fixed simulation steps to execute.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable frame clock.
    /// - `f32` - Unclamped elapsed seconds since the previous frame.
    ///
    /// # Returns
    ///
    /// - `u32` - Number of fixed-timestep updates to run this frame.
    pub fn tick(&mut self, raw_dt_secs: f32) -> u32 {
        let dt_ns: u64 = if raw_dt_secs.is_finite() && raw_dt_secs > 0.0 {
            ((raw_dt_secs.clamp(0.0, 0.25) as f64) * CLOCK_NS_PER_SEC_F64).round() as u64
        } else {
            0
        };
        self.tick_ns(dt_ns)
    }
}

/// Default 60Hz fixed simulation / 60Hz presentation `FixedTimestep3DSession`.
impl Default for FixedTimestep3DSession {
    /// Creates a `FixedTimestep3DSession` with 60Hz fixed simulation, 8 max substeps, and 60Hz presentation cadence.
    ///
    /// # Returns
    ///
    /// - `Self` - Default decoupled 3D simulation session.
    fn default() -> Self {
        Self::new(60, CLOCK_DEFAULT_MAX_SUBSTEPS, 60.0)
    }
}

/// Decoupled fixed-timestep simulation stepping and render interpolation helpers for `FixedTimestep3DSession`.
impl FixedTimestep3DSession {
    /// Constructs a `FixedTimestep3DSession` with explicit fixed simulation frequency, substep cap, and presentation cadence.
    ///
    /// # Arguments
    ///
    /// - `u32` - Fixed simulation frequency in Hertz (`1..=1000`).
    /// - `u32` - Maximum fixed substeps allowed per presentation frame to prevent spiral-of-death stalls.
    /// - `f32` - Display presentation cadence in Hertz (e.g. `60.0`, `120.0`, `144.0`, `240.0`).
    ///
    /// # Returns
    ///
    /// - `Self` - Configured decoupled 3D simulation session.
    #[must_use]
    pub fn new(sim_hz: u32, max_substeps: u32, present_hz: f32) -> Self {
        let safe_present_hz: f32 = if present_hz.is_finite() {
            present_hz.clamp(1.0, 1000.0)
        } else {
            60.0
        };
        Self {
            clock: FrameClock::for_sim_hz(sim_hz, max_substeps),
            present_hz: safe_present_hz,
            sim_steps_total: 0,
            present_frames_total: 0,
            interpolated_only_frames: 0,
            clamped_stall_frames: 0,
            last_alpha: 0.0,
            last_steps: 0,
        }
    }

    /// Updates the display presentation cadence in Hertz without altering the fixed simulation timestep or accumulator.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable simulation session.
    /// - `f32` - New presentation cadence in Hertz (`1.0..=1000.0`).
    pub fn set_present_cadence_hz(&mut self, present_hz: f32) {
        if present_hz.is_finite() {
            self.set_present_hz(present_hz.clamp(1.0, 1000.0));
        }
    }

    /// Advances the decoupled loop by `present_dt_ns` nanoseconds, executing only the required fixed simulation steps and returning render interpolation `alpha`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable simulation session.
    /// - `u64` - Elapsed presentation interval in integer nanoseconds.
    /// - `F` - Fixed-timestep simulation callback invoked once per fixed substep with `fixed_dt_secs`.
    ///
    /// # Returns
    ///
    /// - `SimPresentFrame` - Per-present step count, interpolation alpha, and clamp flags.
    pub fn advance_present_ns<F>(&mut self, present_dt_ns: u64, mut step_sim: F) -> SimPresentFrame
    where
        F: FnMut(f32),
    {
        let fixed_ns: u64 = self
            .get_clock()
            .get_fixed_step_ns()
            .max(CLOCK_MIN_FIXED_STEP_NS);
        let max_substeps: u32 = self.get_clock().get_max_substeps().max(1);
        let pre_acc_ns: u64 = self.get_clock().get_accumulator_ns();
        let clamped_dt_ns: u64 = present_dt_ns.min(CLOCK_MAX_FRAME_DT_NS);
        let uncapped_steps: u64 = pre_acc_ns.saturating_add(clamped_dt_ns) / fixed_ns;
        let hit_clamp: bool =
            present_dt_ns > CLOCK_MAX_FRAME_DT_NS || uncapped_steps > (max_substeps as u64);
        let steps: u32 = self.get_mut_clock().tick_ns(present_dt_ns);
        let fixed_dt: f32 = self.get_clock().get_fixed_dt();
        let alpha: f32 = self.get_clock().get_alpha();
        let present_dt_secs: f32 = self.get_clock().get_delta_secs();
        for _ in 0..steps {
            step_sim(fixed_dt);
        }
        let interpolated_only: bool = steps == 0;
        self.set_sim_steps_total(self.get_sim_steps_total().saturating_add(steps as u64));
        self.set_present_frames_total(self.get_present_frames_total().saturating_add(1));
        if interpolated_only {
            self.set_interpolated_only_frames(
                self.get_interpolated_only_frames().saturating_add(1),
            );
        }
        if hit_clamp {
            self.set_clamped_stall_frames(self.get_clamped_stall_frames().saturating_add(1));
        }
        self.set_last_alpha(alpha);
        self.set_last_steps(steps);
        SimPresentFrame::new(
            steps,
            alpha,
            fixed_dt,
            present_dt_secs,
            interpolated_only,
            hit_clamp,
        )
    }

    /// Advances the decoupled loop by `present_dt_secs` seconds (converted to integer nanoseconds) and returns render interpolation metadata.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable simulation session.
    /// - `f32` - Elapsed presentation interval in seconds.
    /// - `F` - Fixed-timestep simulation callback invoked once per fixed substep with `fixed_dt_secs`.
    ///
    /// # Returns
    ///
    /// - `SimPresentFrame` - Per-present step count, interpolation alpha, and clamp flags.
    pub fn advance_present<F>(&mut self, present_dt_secs: f32, step_sim: F) -> SimPresentFrame
    where
        F: FnMut(f32),
    {
        let dt_ns: u64 = if present_dt_secs.is_finite() && present_dt_secs > 0.0 {
            ((present_dt_secs.min(1.0) as f64) * CLOCK_NS_PER_SEC_F64).round() as u64
        } else {
            0
        };
        self.advance_present_ns(dt_ns, step_sim)
    }

    /// Linearly interpolates between `prev` and `next` simulation scalar values using `alpha` clamped to `[0.0, 1.0]`.
    ///
    /// # Arguments
    ///
    /// - `f32` - Previous fixed simulation scalar value.
    /// - `f32` - Latest fixed simulation scalar value.
    /// - `f32` - Render interpolation factor in `[0.0, 1.0]`.
    ///
    /// # Returns
    ///
    /// - `f32` - Smoothly interpolated render scalar value.
    #[must_use]
    pub fn interpolate_scalar(prev: f32, next: f32, alpha: f32) -> f32 {
        let t: f32 = if alpha.is_finite() {
            alpha.clamp(0.0, 1.0)
        } else {
            1.0
        };
        prev + (next - prev) * t
    }
}