bevyengine/bevy · error · AspectRatioError

AspectRatio error: width or height is NaN

Error message

AspectRatio error: width or height is NaN

What it means

The same AspectRatio constructors reject NaN width or height (aspect_ratio.rs:40). NaN typically arises from 0.0/0.0-style computations and would silently corrupt the stored ratio, so it is rejected up front.

Source

Thrown at crates/bevy_math/src/aspect_ratio.rs:101

    type Error = AspectRatioError;

    #[inline]
    fn try_from(value: Vec2) -> Result<Self, Self::Error> {
        Self::try_new(value.x, value.y)
    }
}

/// An Error type for when [`AspectRatio`](`super::AspectRatio`) is provided invalid width or height values
#[derive(Error, Debug, PartialEq, Eq, Clone, Copy)]
pub enum AspectRatioError {
    /// Error due to width or height having zero as a value.
    #[error("AspectRatio error: width or height is zero")]
    Zero,
    /// Error due towidth or height being infinite.
    #[error("AspectRatio error: width or height is infinite")]
    Infinite,
    /// Error due to width or height being Not a Number (NaN).
    #[error("AspectRatio error: width or height is NaN")]
    NaN,
}

View on GitHub (pinned to 396ca72708)

Solutions

  1. Trace and fix the upstream 0/0 or otherwise invalid computation.
  2. Check is_nan() at data boundaries (parse, deserialize) and reject or default early.
  3. Add unit tests for size math with degenerate inputs.

Example fix

// before
let ar = AspectRatio::try_new(w / total, h / total)?; // NaN when total == 0.0

// after
if total == 0.0 {
    return; // no measurable size yet
}
let ar = AspectRatio::try_new(w / total, h / total)?;
Defensive patterns

Strategy: validation

Validate before calling

fn valid_float_dimensions(w: f32, h: f32) -> bool {
    w.is_finite() && h.is_finite() && w != 0.0 && h != 0.0 && !w.is_nan() && !h.is_nan()
}

Try / catch

match AspectRatio::try_new(w, h) {
    Ok(ar) => { /* use ar */ }
    Err(AspectRatioError::NaN) => { /* trace the 0/0 source, skip this frame */ }
    Err(e) => warn!("bad aspect ratio inputs: {e}"),
}

Prevention

When it happens

Trigger: Passing dimensions produced by 0.0/0.0 math, uninitialized f32 values, or config/serde input that deserialized NaN.

Common situations: Degenerate transforms feeding size computations; parsing user config with bad numbers; arithmetic on uninitialized memory patterns after refactors.

Related errors


AI-assisted analysis of bevyengine/bevy@396ca72708 (2026-08-20). Data as JSON: /api/errors/d2a578fde9305f64. Report an issue: GitHub.