1#![cfg_attr(feature = "document-features", doc = document_features::document_features!())]
20#![allow(clippy::float_cmp)]
23
24use std::ops::{Add, Div, Mul, RangeInclusive, Sub};
25
26pub mod align;
29pub mod easing;
30mod gui_rounding;
31mod history;
32mod numeric;
33mod ordered_float;
34mod pos2;
35mod range;
36mod rect;
37mod rect_align;
38mod rect_transform;
39mod rot2;
40pub mod smart_aim;
41mod ts_transform;
42mod vec2;
43mod vec2b;
44
45pub use self::{
46 align::{Align, Align2},
47 gui_rounding::{GUI_ROUNDING, GuiRounding},
48 history::History,
49 numeric::*,
50 ordered_float::*,
51 pos2::*,
52 range::Rangef,
53 rect::*,
54 rect_align::RectAlign,
55 rect_transform::*,
56 rot2::*,
57 ts_transform::*,
58 vec2::*,
59 vec2b::*,
60};
61
62pub trait One {
66 const ONE: Self;
67}
68
69impl One for f32 {
70 const ONE: Self = 1.0;
71}
72
73impl One for f64 {
74 const ONE: Self = 1.0;
75}
76
77pub trait Real:
79 Copy
80 + PartialEq
81 + PartialOrd
82 + One
83 + Add<Self, Output = Self>
84 + Sub<Self, Output = Self>
85 + Mul<Self, Output = Self>
86 + Div<Self, Output = Self>
87{
88}
89
90impl Real for f32 {}
91
92impl Real for f64 {}
93
94#[inline(always)]
106pub fn lerp<R, T>(range: impl Into<RangeInclusive<R>>, t: T) -> R
107where
108 T: Real + Mul<R, Output = R>,
109 R: Copy + Add<R, Output = R>,
110{
111 let range = range.into();
112 (T::ONE - t) * *range.start() + t * *range.end()
113}
114
115#[inline]
130pub fn inverse_lerp<R>(range: RangeInclusive<R>, value: R) -> Option<R>
131where
132 R: Copy + PartialEq + Sub<R, Output = R> + Div<R, Output = R>,
133{
134 let min = *range.start();
135 let max = *range.end();
136 if min == max {
137 None
138 } else {
139 Some((value - min) / (max - min))
140 }
141}
142
143pub fn remap<T>(x: T, from: impl Into<RangeInclusive<T>>, to: impl Into<RangeInclusive<T>>) -> T
147where
148 T: Real,
149{
150 let from = from.into();
151 let to = to.into();
152 debug_assert!(
153 from.start() != from.end(),
154 "from.start() and from.end() should not be equal"
155 );
156 let t = (x - *from.start()) / (*from.end() - *from.start());
157 lerp(to, t)
158}
159
160pub fn remap_clamp<T>(
162 x: T,
163 from: impl Into<RangeInclusive<T>>,
164 to: impl Into<RangeInclusive<T>>,
165) -> T
166where
167 T: Real,
168{
169 let from = from.into();
170 let to = to.into();
171 if from.end() < from.start() {
172 return remap_clamp(x, *from.end()..=*from.start(), *to.end()..=*to.start());
173 }
174 if x <= *from.start() {
175 *to.start()
176 } else if *from.end() <= x {
177 *to.end()
178 } else {
179 debug_assert!(
180 from.start() != from.end(),
181 "from.start() and from.end() should not be equal"
182 );
183 let t = (x - *from.start()) / (*from.end() - *from.start());
184 if T::ONE <= t { *to.end() } else { lerp(to, t) }
186 }
187}
188
189pub fn round_to_decimals(value: f64, decimal_places: usize) -> f64 {
191 format!("{value:.decimal_places$}").parse().unwrap_or(value)
193}
194
195pub fn format_with_minimum_decimals(value: f64, decimals: usize) -> String {
196 format_with_decimals_in_range(value, decimals..=6)
197}
198
199pub fn format_with_decimals_in_range(value: f64, decimal_range: RangeInclusive<usize>) -> String {
203 let min_decimals = *decimal_range.start();
204 let max_decimals = *decimal_range.end();
205 debug_assert!(
206 min_decimals <= max_decimals,
207 "min_decimals should be <= max_decimals, but got min_decimals: {min_decimals}, max_decimals: {max_decimals}"
208 );
209 debug_assert!(
210 max_decimals < 100,
211 "max_decimals should be < 100, but got {max_decimals}"
212 );
213 let max_decimals = max_decimals.min(16);
214 let min_decimals = min_decimals.min(max_decimals);
215
216 if min_decimals < max_decimals {
217 for decimals in min_decimals..max_decimals {
219 let text = format!("{value:.decimals$}");
220 let epsilon = 16.0 * f32::EPSILON; if almost_equal(text.parse::<f32>().unwrap(), value as f32, epsilon) {
222 return text;
224 }
225 }
226 }
230 format!("{value:.max_decimals$}")
231}
232
233pub fn almost_equal(a: f32, b: f32, epsilon: f32) -> bool {
239 if a == b {
240 true } else {
242 let abs_max = a.abs().max(b.abs());
243 abs_max <= epsilon || ((a - b).abs() / abs_max) <= epsilon
244 }
245}
246
247#[expect(clippy::approx_constant)]
248#[test]
249fn test_format() {
250 assert_eq!(format_with_minimum_decimals(1_234_567.0, 0), "1234567");
251 assert_eq!(format_with_minimum_decimals(1_234_567.0, 1), "1234567.0");
252 assert_eq!(format_with_minimum_decimals(3.14, 2), "3.14");
253 assert_eq!(format_with_minimum_decimals(3.14, 3), "3.140");
254 assert_eq!(
255 format_with_minimum_decimals(std::f64::consts::PI, 2),
256 "3.14159"
257 );
258}
259
260#[test]
261fn test_almost_equal() {
262 for &x in &[
263 0.0_f32,
264 f32::MIN_POSITIVE,
265 1e-20,
266 1e-10,
267 f32::EPSILON,
268 0.1,
269 0.99,
270 1.0,
271 1.001,
272 1e10,
273 f32::MAX / 100.0,
274 f32::INFINITY,
276 ] {
277 for &x in &[-x, x] {
278 for roundtrip in &[
279 |x: f32| x.to_degrees().to_radians(),
280 |x: f32| x.to_radians().to_degrees(),
281 ] {
282 let epsilon = f32::EPSILON;
283 assert!(
284 almost_equal(x, roundtrip(x), epsilon),
285 "{} vs {}",
286 x,
287 roundtrip(x)
288 );
289 }
290 }
291 }
292}
293
294#[test]
295fn test_remap() {
296 assert_eq!(remap_clamp(1.0, 0.0..=1.0, 0.0..=16.0), 16.0);
297 assert_eq!(remap_clamp(1.0, 1.0..=0.0, 16.0..=0.0), 16.0);
298 assert_eq!(remap_clamp(0.5, 1.0..=0.0, 16.0..=0.0), 8.0);
299}
300
301pub trait NumExt {
305 #[must_use]
307 fn at_least(self, lower_limit: Self) -> Self;
308
309 #[must_use]
311 fn at_most(self, upper_limit: Self) -> Self;
312}
313
314macro_rules! impl_num_ext {
315 ($t: ty) => {
316 impl NumExt for $t {
317 #[inline(always)]
318 fn at_least(self, lower_limit: Self) -> Self {
319 self.max(lower_limit)
320 }
321
322 #[inline(always)]
323 fn at_most(self, upper_limit: Self) -> Self {
324 self.min(upper_limit)
325 }
326 }
327 };
328}
329
330impl_num_ext!(u8);
331impl_num_ext!(u16);
332impl_num_ext!(u32);
333impl_num_ext!(u64);
334impl_num_ext!(u128);
335impl_num_ext!(usize);
336impl_num_ext!(i8);
337impl_num_ext!(i16);
338impl_num_ext!(i32);
339impl_num_ext!(i64);
340impl_num_ext!(i128);
341impl_num_ext!(isize);
342impl_num_ext!(f32);
343impl_num_ext!(f64);
344impl_num_ext!(Vec2);
345impl_num_ext!(Pos2);
346
347pub fn normalized_angle(mut angle: f32) -> f32 {
351 use std::f32::consts::{PI, TAU};
352 angle %= TAU;
353 if angle > PI {
354 angle -= TAU;
355 } else if angle < -PI {
356 angle += TAU;
357 }
358 angle
359}
360
361#[test]
362fn test_normalized_angle() {
363 macro_rules! almost_eq {
364 ($left: expr, $right: expr) => {
365 let left = $left;
366 let right = $right;
367 assert!((left - right).abs() < 1e-6, "{} != {}", left, right);
368 };
369 }
370
371 use std::f32::consts::TAU;
372 almost_eq!(normalized_angle(-3.0 * TAU), 0.0);
373 almost_eq!(normalized_angle(-2.3 * TAU), -0.3 * TAU);
374 almost_eq!(normalized_angle(-TAU), 0.0);
375 almost_eq!(normalized_angle(0.0), 0.0);
376 almost_eq!(normalized_angle(TAU), 0.0);
377 almost_eq!(normalized_angle(2.7 * TAU), -0.3 * TAU);
378}
379
380pub fn exponential_smooth_factor(
395 reach_this_fraction: f32,
396 in_this_many_seconds: f32,
397 dt: f32,
398) -> f32 {
399 1.0 - (1.0 - reach_this_fraction).powf(dt / in_this_many_seconds)
400}
401
402pub fn interpolation_factor(
423 (start_time, end_time): (f64, f64),
424 current_time: f64,
425 dt: f32,
426 easing: impl Fn(f32) -> f32,
427) -> f32 {
428 let animation_duration = (end_time - start_time) as f32;
429 let prev_time = current_time - dt as f64;
430 let prev_t = easing((prev_time - start_time) as f32 / animation_duration);
431 let end_t = easing((current_time - start_time) as f32 / animation_duration);
432 if end_t < 1.0 {
433 (end_t - prev_t) / (1.0 - prev_t)
434 } else {
435 1.0
436 }
437}
438
439#[inline]
443pub fn ease_in_ease_out(t: f32) -> f32 {
444 let t = t.clamp(0.0, 1.0);
445 (3.0 * t * t - 2.0 * t * t * t).clamp(0.0, 1.0)
446}