github.com/searKing/golang/go@v1.2.74/exp/image/point.go (about) 1 // Copyright 2023 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package image 6 7 import ( 8 "fmt" 9 "image" 10 11 "github.com/searKing/golang/go/exp/constraints" 12 ) 13 14 // A Point is an X, Y coordinate pair. The axes increase right and down. 15 type Point[E constraints.Number] struct { 16 X, Y E 17 } 18 19 // String returns a string representation of p like "(3,4)". 20 func (p Point[E]) String() string { 21 return fmt.Sprintf("(%v,%v)", p.X, p.Y) 22 } 23 24 // Add returns the vector p+q. 25 func (p Point[E]) Add(q Point[E]) Point[E] { 26 return Point[E]{p.X + q.X, p.Y + q.Y} 27 } 28 29 // Sub returns the vector p-q. 30 func (p Point[E]) Sub(q Point[E]) Point[E] { 31 return Point[E]{p.X - q.X, p.Y - q.Y} 32 } 33 34 // Mul returns the vector p*k. 35 func (p Point[E]) Mul(k E) Point[E] { 36 return Point[E]{p.X * k, p.Y * k} 37 } 38 39 // Div returns the vector p/k. 40 func (p Point[E]) Div(k E) Point[E] { 41 return Point[E]{p.X / k, p.Y / k} 42 } 43 44 // In reports whether p is in r. 45 func (p Point[E]) In(r Rectangle[E]) bool { 46 return r.Min.X <= p.X && p.X < r.Max.X && 47 r.Min.Y <= p.Y && p.Y < r.Max.Y 48 } 49 50 // Mod returns the point q in r such that p.X-q.X is a multiple of r's width 51 // and p.Y-q.Y is a multiple of r's height. 52 func (p Point[E]) Mod(r image.Rectangle) image.Point { 53 p2 := p.RoundPoint() 54 return p2.Mod(r) 55 } 56 57 // Eq reports whether p and q are equal. 58 func (p Point[E]) Eq(q Point[E]) bool { 59 return p == q 60 } 61 62 func (p Point[E]) RoundPoint() image.Point { 63 return image.Pt(round(p.X), round(p.Y)) 64 } 65 66 // Pt is shorthand for Point[E]{X, Y}. 67 func Pt[E constraints.Number](X, Y E) Point[E] { 68 return Point[E]{X, Y} 69 } 70 71 func FromPtInt[E constraints.Number](q image.Point) Point[E] { 72 return Point[E]{E(q.X), E(q.Y)} 73 }