pierro/core/math/
margin.rs1use super::{vec2, Axis, Range, Rect, Vec2};
2
3
4#[derive(Clone, Copy)]
5pub struct Margin {
6 pub min: Vec2,
8 pub max: Vec2
10}
11
12impl Margin {
13
14 pub const fn new(left: f32, top: f32, right: f32, bottom: f32) -> Self {
15 Self {
16 min: vec2(left, top),
17 max: vec2(right, bottom)
18 }
19 }
20
21 pub const fn same(margin: f32) -> Self {
22 Self::new(margin, margin, margin, margin)
23 }
24
25 pub const fn horizontal(margin: f32) -> Self {
26 Self::new(margin, 0.0, margin, 0.0)
27 }
28
29 pub const fn vertical(margin: f32) -> Self {
30 Self::new(0.0, margin, 0.0, margin)
31 }
32
33 pub const ZERO: Self = Self::same(0.0);
34
35 pub fn total(&self) -> Vec2 {
36 self.min + self.max
37 }
38
39 pub fn on_axis(&self, axis: Axis) -> (f32, f32) {
40 (self.min.on_axis(axis), self.max.on_axis(axis))
41 }
42
43 pub fn apply_on_axis(&self, space: Range, axis: Axis) -> Range {
44 let (margin_min, margin_max) = self.on_axis(axis);
45 if space.size() > margin_min + margin_max {
46 Range::new(space.min + margin_min, space.max - margin_max)
47 } else {
48 Range::point(space.center())
49 }
50 }
51
52 pub fn apply(&self, rect: Rect) -> Rect {
53 Rect::from_ranges(
54 self.apply_on_axis(rect.x_range(), Axis::X),
55 self.apply_on_axis(rect.y_range(), Axis::Y)
56 )
57 }
58
59}