geometry.rs

  1use bytemuck::{Pod, Zeroable};
  2use core::fmt::Debug;
  3use derive_more::{Add, AddAssign, Div, Mul, Sub, SubAssign};
  4use refineable::Refineable;
  5use std::ops::{Add, AddAssign, Div, Mul, MulAssign, Sub, SubAssign};
  6
  7#[derive(Refineable, Default, Add, AddAssign, Sub, SubAssign, Copy, Debug, PartialEq, Eq, Hash)]
  8#[refineable(debug)]
  9#[repr(C)]
 10pub struct Point<T: Clone + Debug> {
 11    pub x: T,
 12    pub y: T,
 13}
 14
 15pub fn point<T: Clone + Debug>(x: T, y: T) -> Point<T> {
 16    Point { x, y }
 17}
 18
 19impl<T: Clone + Debug> Point<T> {
 20    pub fn new(x: T, y: T) -> Self {
 21        Self { x, y }
 22    }
 23
 24    pub fn map<U: Clone + Debug, F: Fn(T) -> U>(&self, f: F) -> Point<U> {
 25        Point {
 26            x: f(self.x.clone()),
 27            y: f(self.y.clone()),
 28        }
 29    }
 30}
 31
 32impl<T, Rhs> Mul<Rhs> for Point<T>
 33where
 34    T: Mul<Rhs, Output = Rhs> + Clone + Debug,
 35    Rhs: Clone + Debug,
 36{
 37    type Output = Point<Rhs>;
 38
 39    fn mul(self, rhs: Rhs) -> Self::Output {
 40        Point {
 41            x: self.x * rhs.clone(),
 42            y: self.y * rhs,
 43        }
 44    }
 45}
 46
 47impl<T: Clone + Debug + Mul<S, Output = T>, S: Clone> MulAssign<S> for Point<T> {
 48    fn mul_assign(&mut self, rhs: S) {
 49        self.x = self.x.clone() * rhs.clone();
 50        self.y = self.y.clone() * rhs;
 51    }
 52}
 53
 54impl<T: Clone + Debug + Sub<Output = T>> SubAssign<Size<T>> for Point<T> {
 55    fn sub_assign(&mut self, rhs: Size<T>) {
 56        self.x = self.x.clone() - rhs.width;
 57        self.y = self.y.clone() - rhs.height;
 58    }
 59}
 60
 61impl<T: Clone + Debug + Add<Output = T> + Copy> AddAssign<T> for Point<T> {
 62    fn add_assign(&mut self, rhs: T) {
 63        self.x = self.x.clone() + rhs;
 64        self.y = self.y.clone() + rhs;
 65    }
 66}
 67
 68impl<T: Clone + Debug + Div<S, Output = T>, S: Clone> Div<S> for Point<T> {
 69    type Output = Self;
 70
 71    fn div(self, rhs: S) -> Self::Output {
 72        Self {
 73            x: self.x / rhs.clone(),
 74            y: self.y / rhs,
 75        }
 76    }
 77}
 78
 79impl<T: Clone + Debug + std::cmp::PartialOrd> Point<T> {
 80    pub fn max(&self, other: &Self) -> Self {
 81        Point {
 82            x: if self.x >= other.x {
 83                self.x.clone()
 84            } else {
 85                other.x.clone()
 86            },
 87            y: if self.y >= other.y {
 88                self.y.clone()
 89            } else {
 90                other.y.clone()
 91            },
 92        }
 93    }
 94}
 95
 96impl<T: Clone + Debug> Clone for Point<T> {
 97    fn clone(&self) -> Self {
 98        Self {
 99            x: self.x.clone(),
100            y: self.y.clone(),
101        }
102    }
103}
104
105unsafe impl<T: Clone + Debug + Zeroable + Pod> Zeroable for Point<T> {}
106unsafe impl<T: Clone + Debug + Zeroable + Pod> Pod for Point<T> {}
107
108#[derive(Refineable, Default, Clone, Copy, Debug, PartialEq, Div)]
109#[refineable(debug)]
110#[repr(C)]
111pub struct Size<T: Clone + Debug> {
112    pub width: T,
113    pub height: T,
114}
115
116unsafe impl<T: Clone + Debug + Zeroable + Pod> Zeroable for Size<T> {}
117unsafe impl<T: Clone + Debug + Zeroable + Pod> Pod for Size<T> {}
118
119pub fn size<T: Clone + Debug>(width: T, height: T) -> Size<T> {
120    Size { width, height }
121}
122
123impl<T: Clone + Debug> Size<T> {
124    pub fn map<U: Clone + Debug, F: Fn(T) -> U>(&self, f: F) -> Size<U> {
125        Size {
126            width: f(self.width.clone()),
127            height: f(self.height.clone()),
128        }
129    }
130}
131
132impl<T, Rhs> Mul<Rhs> for Size<T>
133where
134    T: Mul<Rhs, Output = Rhs> + Debug + Clone,
135    Rhs: Debug + Clone,
136{
137    type Output = Size<Rhs>;
138
139    fn mul(self, rhs: Rhs) -> Self::Output {
140        Size {
141            width: self.width * rhs.clone(),
142            height: self.height * rhs,
143        }
144    }
145}
146
147impl<T: Clone + Debug + Mul<S, Output = T>, S: Clone> MulAssign<S> for Size<T> {
148    fn mul_assign(&mut self, rhs: S) {
149        self.width = self.width.clone() * rhs.clone();
150        self.height = self.height.clone() * rhs;
151    }
152}
153
154impl From<Size<Option<Pixels>>> for Size<Option<f32>> {
155    fn from(val: Size<Option<Pixels>>) -> Self {
156        Size {
157            width: val.width.map(|p| p.0 as f32),
158            height: val.height.map(|p| p.0 as f32),
159        }
160    }
161}
162
163impl Size<Length> {
164    pub fn full() -> Self {
165        Self {
166            width: relative(1.).into(),
167            height: relative(1.).into(),
168        }
169    }
170}
171
172impl Size<DefiniteLength> {
173    pub fn zero() -> Self {
174        Self {
175            width: px(0.).into(),
176            height: px(0.).into(),
177        }
178    }
179}
180
181impl Size<Length> {
182    pub fn auto() -> Self {
183        Self {
184            width: Length::Auto,
185            height: Length::Auto,
186        }
187    }
188}
189
190#[derive(Refineable, Clone, Default, Debug, PartialEq)]
191#[refineable(debug)]
192#[repr(C)]
193pub struct Bounds<T: Clone + Debug> {
194    pub origin: Point<T>,
195    pub size: Size<T>,
196}
197
198unsafe impl<T: Clone + Debug + Zeroable + Pod> Zeroable for Bounds<T> {}
199unsafe impl<T: Clone + Debug + Zeroable + Pod> Pod for Bounds<T> {}
200
201// Bounds<f32> * Pixels = Bounds<Pixels>
202impl<T, Rhs> Mul<Rhs> for Bounds<T>
203where
204    T: Mul<Rhs, Output = Rhs> + Clone + Debug,
205    Rhs: Clone + Debug,
206{
207    type Output = Bounds<Rhs>;
208
209    fn mul(self, rhs: Rhs) -> Self::Output {
210        Bounds {
211            origin: self.origin * rhs.clone(),
212            size: self.size * rhs,
213        }
214    }
215}
216
217impl<T: Clone + Debug + Mul<S, Output = T>, S: Clone> MulAssign<S> for Bounds<T> {
218    fn mul_assign(&mut self, rhs: S) {
219        self.origin *= rhs.clone();
220        self.size *= rhs;
221    }
222}
223
224impl<T: Clone + Debug + Div<S, Output = T>, S: Clone> Div<S> for Bounds<T>
225where
226    Size<T>: Div<S, Output = Size<T>>,
227{
228    type Output = Self;
229
230    fn div(self, rhs: S) -> Self {
231        Self {
232            origin: self.origin / rhs.clone(),
233            size: self.size / rhs,
234        }
235    }
236}
237
238impl<T: Clone + Debug + Add<T, Output = T>> Bounds<T> {
239    pub fn upper_right(&self) -> Point<T> {
240        Point {
241            x: self.origin.x.clone() + self.size.width.clone(),
242            y: self.origin.y.clone(),
243        }
244    }
245
246    pub fn lower_right(&self) -> Point<T> {
247        Point {
248            x: self.origin.x.clone() + self.size.width.clone(),
249            y: self.origin.y.clone() + self.size.height.clone(),
250        }
251    }
252}
253
254impl<T: Clone + Debug + PartialOrd + Add<T, Output = T>> Bounds<T> {
255    pub fn contains_point(&self, point: Point<T>) -> bool {
256        point.x >= self.origin.x
257            && point.x <= self.origin.x.clone() + self.size.width.clone()
258            && point.y >= self.origin.y
259            && point.y <= self.origin.y.clone() + self.size.height.clone()
260    }
261
262    pub fn map<U: Clone + Debug, F: Fn(T) -> U>(&self, f: F) -> Bounds<U> {
263        Bounds {
264            origin: self.origin.map(&f),
265            size: self.size.map(f),
266        }
267    }
268}
269
270impl<T: Clone + Debug + Copy> Copy for Bounds<T> {}
271
272#[derive(Refineable, Clone, Default, Debug)]
273#[refineable(debug)]
274#[repr(C)]
275pub struct Edges<T: Clone + Debug> {
276    pub top: T,
277    pub right: T,
278    pub bottom: T,
279    pub left: T,
280}
281
282impl<T: Clone + Debug + Mul<Output = T>> Mul for Edges<T> {
283    type Output = Self;
284
285    fn mul(self, rhs: Self) -> Self::Output {
286        Self {
287            top: self.top.clone() * rhs.top,
288            right: self.right.clone() * rhs.right,
289            bottom: self.bottom.clone() * rhs.bottom,
290            left: self.left.clone() * rhs.left,
291        }
292    }
293}
294
295impl<T: Clone + Debug + Mul<S, Output = T>, S: Clone> MulAssign<S> for Edges<T> {
296    fn mul_assign(&mut self, rhs: S) {
297        self.top = self.top.clone() * rhs.clone();
298        self.right = self.right.clone() * rhs.clone();
299        self.bottom = self.bottom.clone() * rhs.clone();
300        self.left = self.left.clone() * rhs.clone();
301    }
302}
303
304impl<T: Clone + Debug + Copy> Copy for Edges<T> {}
305
306unsafe impl<T: Clone + Debug + Zeroable + Pod> Zeroable for Edges<T> {}
307
308unsafe impl<T: Clone + Debug + Zeroable + Pod> Pod for Edges<T> {}
309
310impl Edges<Length> {
311    pub fn auto() -> Self {
312        Self {
313            top: Length::Auto,
314            right: Length::Auto,
315            bottom: Length::Auto,
316            left: Length::Auto,
317        }
318    }
319
320    pub fn zero() -> Self {
321        Self {
322            top: px(0.).into(),
323            right: px(0.).into(),
324            bottom: px(0.).into(),
325            left: px(0.).into(),
326        }
327    }
328}
329
330impl Edges<DefiniteLength> {
331    pub fn zero() -> Self {
332        Self {
333            top: px(0.).into(),
334            right: px(0.).into(),
335            bottom: px(0.).into(),
336            left: px(0.).into(),
337        }
338    }
339}
340
341impl Edges<AbsoluteLength> {
342    pub fn zero() -> Self {
343        Self {
344            top: px(0.).into(),
345            right: px(0.).into(),
346            bottom: px(0.).into(),
347            left: px(0.).into(),
348        }
349    }
350
351    pub fn to_pixels(&self, rem_size: Pixels) -> Edges<Pixels> {
352        Edges {
353            top: self.top.to_pixels(rem_size),
354            right: self.right.to_pixels(rem_size),
355            bottom: self.bottom.to_pixels(rem_size),
356            left: self.left.to_pixels(rem_size),
357        }
358    }
359}
360
361impl Edges<Pixels> {
362    pub fn is_empty(&self) -> bool {
363        self.top == px(0.) && self.right == px(0.) && self.bottom == px(0.) && self.left == px(0.)
364    }
365}
366
367#[derive(Refineable, Clone, Default, Debug)]
368#[refineable(debug)]
369#[repr(C)]
370pub struct Corners<T: Clone + Debug> {
371    pub top_left: T,
372    pub top_right: T,
373    pub bottom_right: T,
374    pub bottom_left: T,
375}
376
377impl<T: Clone + Debug + Mul<Output = T>> Mul for Corners<T> {
378    type Output = Self;
379
380    fn mul(self, rhs: Self) -> Self::Output {
381        Self {
382            top_left: self.top_left.clone() * rhs.top_left,
383            top_right: self.top_right.clone() * rhs.top_right,
384            bottom_right: self.bottom_right.clone() * rhs.bottom_right,
385            bottom_left: self.bottom_left.clone() * rhs.bottom_left,
386        }
387    }
388}
389
390impl<T: Clone + Debug + Mul<S, Output = T>, S: Clone> MulAssign<S> for Corners<T> {
391    fn mul_assign(&mut self, rhs: S) {
392        self.top_left = self.top_left.clone() * rhs.clone();
393        self.top_right = self.top_right.clone() * rhs.clone();
394        self.bottom_right = self.bottom_right.clone() * rhs.clone();
395        self.bottom_left = self.bottom_left.clone() * rhs;
396    }
397}
398
399impl<T: Clone + Debug + Copy> Copy for Corners<T> {}
400
401unsafe impl<T: Clone + Debug + Zeroable + Pod> Zeroable for Corners<T> {}
402
403unsafe impl<T: Clone + Debug + Zeroable + Pod> Pod for Corners<T> {}
404
405#[derive(Clone, Copy, Default, Add, AddAssign, Sub, SubAssign, Div, PartialEq, PartialOrd)]
406#[repr(transparent)]
407pub struct Pixels(pub(crate) f32);
408
409impl Mul<f32> for Pixels {
410    type Output = Pixels;
411
412    fn mul(self, other: f32) -> Pixels {
413        Pixels(self.0 * other)
414    }
415}
416
417impl Mul<Pixels> for f32 {
418    type Output = Pixels;
419
420    fn mul(self, rhs: Pixels) -> Self::Output {
421        Pixels(self * rhs.0)
422    }
423}
424
425impl Pixels {
426    pub fn round(&self) -> Self {
427        Self(self.0.round())
428    }
429
430    pub fn to_device_pixels(&self, scale: f32) -> DevicePixels {
431        DevicePixels((self.0 * scale).ceil() as u32)
432    }
433}
434
435impl Mul<Pixels> for Pixels {
436    type Output = Pixels;
437
438    fn mul(self, rhs: Pixels) -> Self::Output {
439        Pixels(self.0 * rhs.0)
440    }
441}
442
443impl Eq for Pixels {}
444
445impl Ord for Pixels {
446    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
447        self.0.partial_cmp(&other.0).unwrap()
448    }
449}
450
451impl std::hash::Hash for Pixels {
452    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
453        self.0.to_bits().hash(state);
454    }
455}
456
457impl From<f64> for Pixels {
458    fn from(val: f64) -> Self {
459        Pixels(val as f32)
460    }
461}
462
463impl From<f32> for Pixels {
464    fn from(val: f32) -> Self {
465        Pixels(val)
466    }
467}
468
469unsafe impl bytemuck::Pod for Pixels {}
470unsafe impl bytemuck::Zeroable for Pixels {}
471
472impl Debug for Pixels {
473    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
474        write!(f, "{} px", self.0)
475    }
476}
477
478impl From<Pixels> for f32 {
479    fn from(pixels: Pixels) -> Self {
480        pixels.0
481    }
482}
483
484impl From<&Pixels> for f32 {
485    fn from(pixels: &Pixels) -> Self {
486        pixels.0
487    }
488}
489
490impl From<Pixels> for f64 {
491    fn from(pixels: Pixels) -> Self {
492        pixels.0 as f64
493    }
494}
495
496#[derive(
497    Clone, Copy, Debug, Default, Add, AddAssign, Sub, SubAssign, Div, PartialEq, PartialOrd,
498)]
499#[repr(transparent)]
500pub struct DevicePixels(pub(crate) u32);
501
502unsafe impl bytemuck::Pod for DevicePixels {}
503unsafe impl bytemuck::Zeroable for DevicePixels {}
504
505impl From<DevicePixels> for u32 {
506    fn from(device_pixels: DevicePixels) -> Self {
507        device_pixels.0
508    }
509}
510
511impl From<u32> for DevicePixels {
512    fn from(val: u32) -> Self {
513        DevicePixels(val)
514    }
515}
516
517#[derive(Clone, Copy, Default, Add, Sub, Mul, Div)]
518pub struct Rems(f32);
519
520impl Mul<Pixels> for Rems {
521    type Output = Pixels;
522
523    fn mul(self, other: Pixels) -> Pixels {
524        Pixels(self.0 * other.0)
525    }
526}
527
528impl Debug for Rems {
529    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
530        write!(f, "{} rem", self.0)
531    }
532}
533
534#[derive(Clone, Copy, Debug)]
535pub enum AbsoluteLength {
536    Pixels(Pixels),
537    Rems(Rems),
538}
539
540impl From<Pixels> for AbsoluteLength {
541    fn from(pixels: Pixels) -> Self {
542        AbsoluteLength::Pixels(pixels)
543    }
544}
545
546impl From<Rems> for AbsoluteLength {
547    fn from(rems: Rems) -> Self {
548        AbsoluteLength::Rems(rems)
549    }
550}
551
552impl AbsoluteLength {
553    pub fn to_pixels(&self, rem_size: Pixels) -> Pixels {
554        match self {
555            AbsoluteLength::Pixels(pixels) => *pixels,
556            AbsoluteLength::Rems(rems) => *rems * rem_size,
557        }
558    }
559}
560
561impl Default for AbsoluteLength {
562    fn default() -> Self {
563        px(0.).into()
564    }
565}
566
567/// A non-auto length that can be defined in pixels, rems, or percent of parent.
568#[derive(Clone, Copy)]
569pub enum DefiniteLength {
570    Absolute(AbsoluteLength),
571    /// A fraction of the parent's size between 0 and 1.
572    Fraction(f32),
573}
574
575impl DefiniteLength {
576    pub fn to_pixels(&self, base_size: AbsoluteLength, rem_size: Pixels) -> Pixels {
577        match self {
578            DefiniteLength::Absolute(size) => size.to_pixels(rem_size),
579            DefiniteLength::Fraction(fraction) => match base_size {
580                AbsoluteLength::Pixels(px) => px * *fraction,
581                AbsoluteLength::Rems(rems) => rems * rem_size * *fraction,
582            },
583        }
584    }
585}
586
587impl Debug for DefiniteLength {
588    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
589        match self {
590            DefiniteLength::Absolute(length) => Debug::fmt(length, f),
591            DefiniteLength::Fraction(fract) => write!(f, "{}%", (fract * 100.0) as i32),
592        }
593    }
594}
595
596impl From<Pixels> for DefiniteLength {
597    fn from(pixels: Pixels) -> Self {
598        Self::Absolute(pixels.into())
599    }
600}
601
602impl From<Rems> for DefiniteLength {
603    fn from(rems: Rems) -> Self {
604        Self::Absolute(rems.into())
605    }
606}
607
608impl From<AbsoluteLength> for DefiniteLength {
609    fn from(length: AbsoluteLength) -> Self {
610        Self::Absolute(length)
611    }
612}
613
614impl Default for DefiniteLength {
615    fn default() -> Self {
616        Self::Absolute(AbsoluteLength::default())
617    }
618}
619
620/// A length that can be defined in pixels, rems, percent of parent, or auto.
621#[derive(Clone, Copy)]
622pub enum Length {
623    Definite(DefiniteLength),
624    Auto,
625}
626
627impl Debug for Length {
628    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
629        match self {
630            Length::Definite(definite_length) => write!(f, "{:?}", definite_length),
631            Length::Auto => write!(f, "auto"),
632        }
633    }
634}
635
636pub fn relative(fraction: f32) -> DefiniteLength {
637    DefiniteLength::Fraction(fraction).into()
638}
639
640/// Returns the Golden Ratio, i.e. `~(1.0 + sqrt(5.0)) / 2.0`.
641pub fn phi() -> DefiniteLength {
642    relative(1.61803398875)
643}
644
645pub fn rems(rems: f32) -> Rems {
646    Rems(rems)
647}
648
649pub fn px(pixels: f32) -> Pixels {
650    Pixels(pixels)
651}
652
653pub fn auto() -> Length {
654    Length::Auto
655}
656
657impl From<Pixels> for Length {
658    fn from(pixels: Pixels) -> Self {
659        Self::Definite(pixels.into())
660    }
661}
662
663impl From<Rems> for Length {
664    fn from(rems: Rems) -> Self {
665        Self::Definite(rems.into())
666    }
667}
668
669impl From<DefiniteLength> for Length {
670    fn from(length: DefiniteLength) -> Self {
671        Self::Definite(length)
672    }
673}
674
675impl From<AbsoluteLength> for Length {
676    fn from(length: AbsoluteLength) -> Self {
677        Self::Definite(length.into())
678    }
679}
680
681impl Default for Length {
682    fn default() -> Self {
683        Self::Definite(DefiniteLength::default())
684    }
685}
686
687impl From<()> for Length {
688    fn from(_: ()) -> Self {
689        Self::Definite(DefiniteLength::default())
690    }
691}