emath/
lib.rs

1//! Opinionated 2D math library for building GUIs.
2//!
3//! Includes vectors, positions, rectangles etc.
4//!
5//! Conventions (unless otherwise specified):
6//!
7//! * All angles are in radians
8//! * X+ is right and Y+ is down.
9//! * (0,0) is left top.
10//! * Dimension order is always `x y`
11//!
12//! ## Integrating with other math libraries.
13//! `emath` does not strive to become a general purpose or all-powerful math library.
14//!
15//! For that, use something else ([`glam`](https://docs.rs/glam), [`nalgebra`](https://docs.rs/nalgebra), …)
16//! and enable the `mint` feature flag in `emath` to enable implicit conversion to/from `emath`.
17//!
18//! ## Feature flags
19#![cfg_attr(feature = "document-features", doc = document_features::document_features!())]
20//!
21
22#![allow(clippy::float_cmp)]
23
24use std::ops::{Add, Div, Mul, RangeInclusive, Sub};
25
26// ----------------------------------------------------------------------------
27
28pub mod align;
29pub mod easing;
30mod history;
31mod numeric;
32mod ordered_float;
33mod pos2;
34mod range;
35mod rect;
36mod rect_transform;
37mod rot2;
38pub mod smart_aim;
39mod ts_transform;
40mod vec2;
41mod vec2b;
42
43pub use self::{
44    align::{Align, Align2},
45    history::History,
46    numeric::*,
47    ordered_float::*,
48    pos2::*,
49    range::Rangef,
50    rect::*,
51    rect_transform::*,
52    rot2::*,
53    ts_transform::*,
54    vec2::*,
55    vec2b::*,
56};
57
58// ----------------------------------------------------------------------------
59
60/// Helper trait to implement [`lerp`] and [`remap`].
61pub trait One {
62    const ONE: Self;
63}
64
65impl One for f32 {
66    const ONE: Self = 1.0;
67}
68
69impl One for f64 {
70    const ONE: Self = 1.0;
71}
72
73/// Helper trait to implement [`lerp`] and [`remap`].
74pub trait Real:
75    Copy
76    + PartialEq
77    + PartialOrd
78    + One
79    + Add<Self, Output = Self>
80    + Sub<Self, Output = Self>
81    + Mul<Self, Output = Self>
82    + Div<Self, Output = Self>
83{
84}
85
86impl Real for f32 {}
87
88impl Real for f64 {}
89
90// ----------------------------------------------------------------------------
91
92/// Linear interpolation.
93///
94/// ```
95/// # use emath::lerp;
96/// assert_eq!(lerp(1.0..=5.0, 0.0), 1.0);
97/// assert_eq!(lerp(1.0..=5.0, 0.5), 3.0);
98/// assert_eq!(lerp(1.0..=5.0, 1.0), 5.0);
99/// assert_eq!(lerp(1.0..=5.0, 2.0), 9.0);
100/// ```
101#[inline(always)]
102pub fn lerp<R, T>(range: impl Into<RangeInclusive<R>>, t: T) -> R
103where
104    T: Real + Mul<R, Output = R>,
105    R: Copy + Add<R, Output = R>,
106{
107    let range = range.into();
108    (T::ONE - t) * *range.start() + t * *range.end()
109}
110
111/// Where in the range is this value? Returns 0-1 if within the range.
112///
113/// Returns <0 if before and >1 if after.
114///
115/// Returns `None` if the input range is zero-width.
116///
117/// ```
118/// # use emath::inverse_lerp;
119/// assert_eq!(inverse_lerp(1.0..=5.0, 1.0), Some(0.0));
120/// assert_eq!(inverse_lerp(1.0..=5.0, 3.0), Some(0.5));
121/// assert_eq!(inverse_lerp(1.0..=5.0, 5.0), Some(1.0));
122/// assert_eq!(inverse_lerp(1.0..=5.0, 9.0), Some(2.0));
123/// assert_eq!(inverse_lerp(1.0..=1.0, 3.0), None);
124/// ```
125#[inline]
126pub fn inverse_lerp<R>(range: RangeInclusive<R>, value: R) -> Option<R>
127where
128    R: Copy + PartialEq + Sub<R, Output = R> + Div<R, Output = R>,
129{
130    let min = *range.start();
131    let max = *range.end();
132    if min == max {
133        None
134    } else {
135        Some((value - min) / (max - min))
136    }
137}
138
139/// Linearly remap a value from one range to another,
140/// so that when `x == from.start()` returns `to.start()`
141/// and when `x == from.end()` returns `to.end()`.
142pub fn remap<T>(x: T, from: impl Into<RangeInclusive<T>>, to: impl Into<RangeInclusive<T>>) -> T
143where
144    T: Real,
145{
146    let from = from.into();
147    let to = to.into();
148    debug_assert!(from.start() != from.end());
149    let t = (x - *from.start()) / (*from.end() - *from.start());
150    lerp(to, t)
151}
152
153/// Like [`remap`], but also clamps the value so that the returned value is always in the `to` range.
154pub fn remap_clamp<T>(
155    x: T,
156    from: impl Into<RangeInclusive<T>>,
157    to: impl Into<RangeInclusive<T>>,
158) -> T
159where
160    T: Real,
161{
162    let from = from.into();
163    let to = to.into();
164    if from.end() < from.start() {
165        return remap_clamp(x, *from.end()..=*from.start(), *to.end()..=*to.start());
166    }
167    if x <= *from.start() {
168        *to.start()
169    } else if *from.end() <= x {
170        *to.end()
171    } else {
172        debug_assert!(from.start() != from.end());
173        let t = (x - *from.start()) / (*from.end() - *from.start());
174        // Ensure no numerical inaccuracies sneak in:
175        if T::ONE <= t {
176            *to.end()
177        } else {
178            lerp(to, t)
179        }
180    }
181}
182
183/// Round a value to the given number of decimal places.
184pub fn round_to_decimals(value: f64, decimal_places: usize) -> f64 {
185    // This is a stupid way of doing this, but stupid works.
186    format!("{value:.decimal_places$}").parse().unwrap_or(value)
187}
188
189pub fn format_with_minimum_decimals(value: f64, decimals: usize) -> String {
190    format_with_decimals_in_range(value, decimals..=6)
191}
192
193/// Use as few decimals as possible to show the value accurately, but within the given range.
194///
195/// Decimals are counted after the decimal point.
196pub fn format_with_decimals_in_range(value: f64, decimal_range: RangeInclusive<usize>) -> String {
197    let min_decimals = *decimal_range.start();
198    let max_decimals = *decimal_range.end();
199    debug_assert!(min_decimals <= max_decimals);
200    debug_assert!(max_decimals < 100);
201    let max_decimals = max_decimals.min(16);
202    let min_decimals = min_decimals.min(max_decimals);
203
204    if min_decimals < max_decimals {
205        // Ugly/slow way of doing this. TODO(emilk): clean up precision.
206        for decimals in min_decimals..max_decimals {
207            let text = format!("{value:.decimals$}");
208            let epsilon = 16.0 * f32::EPSILON; // margin large enough to handle most peoples round-tripping needs
209            if almost_equal(text.parse::<f32>().unwrap(), value as f32, epsilon) {
210                // Enough precision to show the value accurately - good!
211                return text;
212            }
213        }
214        // The value has more precision than we expected.
215        // Probably the value was set not by the slider, but from outside.
216        // In any case: show the full value
217    }
218    format!("{value:.max_decimals$}")
219}
220
221/// Return true when arguments are the same within some rounding error.
222///
223/// For instance `almost_equal(x, x.to_degrees().to_radians(), f32::EPSILON)` should hold true for all x.
224/// The `epsilon`  can be `f32::EPSILON` to handle simple transforms (like degrees -> radians)
225/// but should be higher to handle more complex transformations.
226pub fn almost_equal(a: f32, b: f32, epsilon: f32) -> bool {
227    if a == b {
228        true // handle infinites
229    } else {
230        let abs_max = a.abs().max(b.abs());
231        abs_max <= epsilon || ((a - b).abs() / abs_max) <= epsilon
232    }
233}
234
235#[allow(clippy::approx_constant)]
236#[test]
237fn test_format() {
238    assert_eq!(format_with_minimum_decimals(1_234_567.0, 0), "1234567");
239    assert_eq!(format_with_minimum_decimals(1_234_567.0, 1), "1234567.0");
240    assert_eq!(format_with_minimum_decimals(3.14, 2), "3.14");
241    assert_eq!(format_with_minimum_decimals(3.14, 3), "3.140");
242    assert_eq!(
243        format_with_minimum_decimals(std::f64::consts::PI, 2),
244        "3.14159"
245    );
246}
247
248#[test]
249fn test_almost_equal() {
250    for &x in &[
251        0.0_f32,
252        f32::MIN_POSITIVE,
253        1e-20,
254        1e-10,
255        f32::EPSILON,
256        0.1,
257        0.99,
258        1.0,
259        1.001,
260        1e10,
261        f32::MAX / 100.0,
262        // f32::MAX, // overflows in rad<->deg test
263        f32::INFINITY,
264    ] {
265        for &x in &[-x, x] {
266            for roundtrip in &[
267                |x: f32| x.to_degrees().to_radians(),
268                |x: f32| x.to_radians().to_degrees(),
269            ] {
270                let epsilon = f32::EPSILON;
271                assert!(
272                    almost_equal(x, roundtrip(x), epsilon),
273                    "{} vs {}",
274                    x,
275                    roundtrip(x)
276                );
277            }
278        }
279    }
280}
281
282#[test]
283fn test_remap() {
284    assert_eq!(remap_clamp(1.0, 0.0..=1.0, 0.0..=16.0), 16.0);
285    assert_eq!(remap_clamp(1.0, 1.0..=0.0, 16.0..=0.0), 16.0);
286    assert_eq!(remap_clamp(0.5, 1.0..=0.0, 16.0..=0.0), 8.0);
287}
288
289// ----------------------------------------------------------------------------
290
291/// Extends `f32`, [`Vec2`] etc with `at_least` and `at_most` as aliases for `max` and `min`.
292pub trait NumExt {
293    /// More readable version of `self.max(lower_limit)`
294    #[must_use]
295    fn at_least(self, lower_limit: Self) -> Self;
296
297    /// More readable version of `self.min(upper_limit)`
298    #[must_use]
299    fn at_most(self, upper_limit: Self) -> Self;
300}
301
302macro_rules! impl_num_ext {
303    ($t: ty) => {
304        impl NumExt for $t {
305            #[inline(always)]
306            fn at_least(self, lower_limit: Self) -> Self {
307                self.max(lower_limit)
308            }
309
310            #[inline(always)]
311            fn at_most(self, upper_limit: Self) -> Self {
312                self.min(upper_limit)
313            }
314        }
315    };
316}
317
318impl_num_ext!(u8);
319impl_num_ext!(u16);
320impl_num_ext!(u32);
321impl_num_ext!(u64);
322impl_num_ext!(u128);
323impl_num_ext!(usize);
324impl_num_ext!(i8);
325impl_num_ext!(i16);
326impl_num_ext!(i32);
327impl_num_ext!(i64);
328impl_num_ext!(i128);
329impl_num_ext!(isize);
330impl_num_ext!(f32);
331impl_num_ext!(f64);
332impl_num_ext!(Vec2);
333impl_num_ext!(Pos2);
334
335// ----------------------------------------------------------------------------
336
337/// Wrap angle to `[-PI, PI]` range.
338pub fn normalized_angle(mut angle: f32) -> f32 {
339    use std::f32::consts::{PI, TAU};
340    angle %= TAU;
341    if angle > PI {
342        angle -= TAU;
343    } else if angle < -PI {
344        angle += TAU;
345    }
346    angle
347}
348
349#[test]
350fn test_normalized_angle() {
351    macro_rules! almost_eq {
352        ($left: expr, $right: expr) => {
353            let left = $left;
354            let right = $right;
355            assert!((left - right).abs() < 1e-6, "{} != {}", left, right);
356        };
357    }
358
359    use std::f32::consts::TAU;
360    almost_eq!(normalized_angle(-3.0 * TAU), 0.0);
361    almost_eq!(normalized_angle(-2.3 * TAU), -0.3 * TAU);
362    almost_eq!(normalized_angle(-TAU), 0.0);
363    almost_eq!(normalized_angle(0.0), 0.0);
364    almost_eq!(normalized_angle(TAU), 0.0);
365    almost_eq!(normalized_angle(2.7 * TAU), -0.3 * TAU);
366}
367
368// ----------------------------------------------------------------------------
369
370/// Calculate a lerp-factor for exponential smoothing using a time step.
371///
372/// * `exponential_smooth_factor(0.90, 1.0, dt)`: reach 90% in 1.0 seconds
373/// * `exponential_smooth_factor(0.50, 0.2, dt)`: reach 50% in 0.2 seconds
374///
375/// Example:
376/// ```
377/// # use emath::{lerp, exponential_smooth_factor};
378/// # let (mut smoothed_value, target_value, dt) = (0.0_f32, 1.0_f32, 0.01_f32);
379/// let t = exponential_smooth_factor(0.90, 0.2, dt); // reach 90% in 0.2 seconds
380/// smoothed_value = lerp(smoothed_value..=target_value, t);
381/// ```
382pub fn exponential_smooth_factor(
383    reach_this_fraction: f32,
384    in_this_many_seconds: f32,
385    dt: f32,
386) -> f32 {
387    1.0 - (1.0 - reach_this_fraction).powf(dt / in_this_many_seconds)
388}
389
390/// If you have a value animating over time,
391/// how much towards its target do you need to move it this frame?
392///
393/// You only need to store the start time and target value in order to animate using this function.
394///
395/// ``` rs
396/// struct Animation {
397///     current_value: f32,
398///
399///     animation_time_span: (f64, f64),
400///     target_value: f32,
401/// }
402///
403/// impl Animation {
404///     fn update(&mut self, now: f64, dt: f32) {
405///         let t = interpolation_factor(self.animation_time_span, now, dt, ease_in_ease_out);
406///         self.current_value = emath::lerp(self.current_value..=self.target_value, t);
407///     }
408/// }
409/// ```
410pub fn interpolation_factor(
411    (start_time, end_time): (f64, f64),
412    current_time: f64,
413    dt: f32,
414    easing: impl Fn(f32) -> f32,
415) -> f32 {
416    let animation_duration = (end_time - start_time) as f32;
417    let prev_time = current_time - dt as f64;
418    let prev_t = easing((prev_time - start_time) as f32 / animation_duration);
419    let end_t = easing((current_time - start_time) as f32 / animation_duration);
420    if end_t < 1.0 {
421        (end_t - prev_t) / (1.0 - prev_t)
422    } else {
423        1.0
424    }
425}
426
427/// Ease in, ease out.
428///
429/// `f(0) = 0, f'(0) = 0, f(1) = 1, f'(1) = 0`.
430#[inline]
431pub fn ease_in_ease_out(t: f32) -> f32 {
432    let t = t.clamp(0.0, 1.0);
433    (3.0 * t * t - 2.0 * t * t * t).clamp(0.0, 1.0)
434}