github.com/gop9/olt@v0.0.0-20200202132135-d956aad50b08/gio/f32/f32.go (about) 1 // SPDX-License-Identifier: Unlicense OR MIT 2 3 /* 4 Package f32 is a float32 implementation of package image's 5 Point and Rectangle. 6 7 The coordinate space has the origin in the top left 8 corner with the axes extending right and down. 9 */ 10 package f32 11 12 // A Point is a two dimensional point. 13 type Point struct { 14 X, Y float32 15 } 16 17 // A Rectangle contains the points (X, Y) where Min.X <= X < Max.X, 18 // Min.Y <= Y < Max.Y. 19 type Rectangle struct { 20 Min, Max Point 21 } 22 23 // Add return the point p+p2. 24 func (p Point) Add(p2 Point) Point { 25 return Point{X: p.X + p2.X, Y: p.Y + p2.Y} 26 } 27 28 // Sub returns the vector p-p2. 29 func (p Point) Sub(p2 Point) Point { 30 return Point{X: p.X - p2.X, Y: p.Y - p2.Y} 31 } 32 33 // Mul returns p scaled by s. 34 func (p Point) Mul(s float32) Point { 35 return Point{X: p.X * s, Y: p.Y * s} 36 } 37 38 // Size returns r's width and height. 39 func (r Rectangle) Size() Point { 40 return Point{X: r.Dx(), Y: r.Dy()} 41 } 42 43 // Dx returns r's width. 44 func (r Rectangle) Dx() float32 { 45 return r.Max.X - r.Min.X 46 } 47 48 // Dy returns r's Height. 49 func (r Rectangle) Dy() float32 { 50 return r.Max.Y - r.Min.Y 51 } 52 53 // Intersect returns the intersection of r and s. 54 func (r Rectangle) Intersect(s Rectangle) Rectangle { 55 if r.Min.X < s.Min.X { 56 r.Min.X = s.Min.X 57 } 58 if r.Min.Y < s.Min.Y { 59 r.Min.Y = s.Min.Y 60 } 61 if r.Max.X > s.Max.X { 62 r.Max.X = s.Max.X 63 } 64 if r.Max.Y > s.Max.Y { 65 r.Max.Y = s.Max.Y 66 } 67 return r 68 } 69 70 // Union returns the union of r and s. 71 func (r Rectangle) Union(s Rectangle) Rectangle { 72 if r.Min.X > s.Min.X { 73 r.Min.X = s.Min.X 74 } 75 if r.Min.Y > s.Min.Y { 76 r.Min.Y = s.Min.Y 77 } 78 if r.Max.X < s.Max.X { 79 r.Max.X = s.Max.X 80 } 81 if r.Max.Y < s.Max.Y { 82 r.Max.Y = s.Max.Y 83 } 84 return r 85 } 86 87 // Canon returns the canonical version of r, where Min is to 88 // the upper left of Max. 89 func (r Rectangle) Canon() Rectangle { 90 if r.Max.X < r.Min.X { 91 r.Min.X, r.Max.X = r.Max.X, r.Min.X 92 } 93 if r.Max.Y < r.Min.Y { 94 r.Min.Y, r.Max.Y = r.Max.Y, r.Min.Y 95 } 96 return r 97 } 98 99 // Empty reports whether r represents the empty area. 100 func (r Rectangle) Empty() bool { 101 return r.Min.X >= r.Max.X || r.Min.Y >= r.Max.Y 102 } 103 104 // Add offsets r with the vector p. 105 func (r Rectangle) Add(p Point) Rectangle { 106 return Rectangle{ 107 Point{r.Min.X + p.X, r.Min.Y + p.Y}, 108 Point{r.Max.X + p.X, r.Max.Y + p.Y}, 109 } 110 } 111 112 // Sub offsets r with the vector -p. 113 func (r Rectangle) Sub(p Point) Rectangle { 114 return Rectangle{ 115 Point{r.Min.X - p.X, r.Min.Y - p.Y}, 116 Point{r.Max.X - p.X, r.Max.Y - p.Y}, 117 } 118 }