clairlune_scene/math.rs
1//! Small math helpers.
2//!
3//! Basic IEEE operations (`+ - * /`, `sqrt`, `floor`, `round`, `min`, `max`) give
4//! identical results on every platform. Transcendental functions (`pow`, `exp`,
5//! `sin`) do not when they come from the platform's C library, so they must go
6//! through `libm`, which is pure Rust and identical everywhere.
7
8pub use core::f64::consts::TAU;
9
10#[inline]
11pub fn clamp01(x: f64) -> f64 {
12 x.clamp(0.0, 1.0)
13}
14
15#[inline]
16pub fn lerp(a: f64, b: f64, t: f64) -> f64 {
17 a + (b - a) * t
18}
19
20/// Hermite smoothstep between `e0` and `e1`.
21#[inline]
22pub fn smoothstep(e0: f64, e1: f64, x: f64) -> f64 {
23 let t = clamp01((x - e0) / (e1 - e0));
24 t * t * (3.0 - 2.0 * t)
25}
26
27/// `x^y` via libm (deterministic across platforms).
28#[inline]
29pub fn pow(x: f64, y: f64) -> f64 {
30 libm::pow(x, y)
31}
32
33/// `sin(x)` via libm (deterministic across platforms).
34#[inline]
35pub fn sin(x: f64) -> f64 {
36 libm::sin(x)
37}
38
39/// Per-mille integer to a fraction.
40#[inline]
41pub fn pm(v: u32) -> f64 {
42 f64::from(v) / 1000.0
43}