bb.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package tamias
  2. import "fmt"
  3. // Bounding box type
  4. type BB struct {
  5. L, T, B, R Float
  6. }
  7. //BBMake returns a new bounds box with the given left, top, right, and bottom
  8. //coordinates in that respective order.
  9. func BBMake(l, t, r, b Float) (BB) {
  10. return BB{L: l, B: b, R: r, T: t}
  11. }
  12. func (a BB) Intersects(b BB) bool {
  13. return (a.L<=b.R && b.L<=a.R && a.B<=b.T && b.B<=a.T)
  14. }
  15. func (bb BB) Contains(other BB) bool {
  16. return (bb.L < other.L && bb.R > other.R && bb.B < other.B && bb.T > other.T)
  17. }
  18. func (bb BB) ContainsVect(v Vect) bool {
  19. return (bb.L < v.X && bb.R > v.X && bb.B < v.Y && bb.T > v.Y)
  20. }
  21. func (am BB) Merge(bm BB) (BB) {
  22. l := am.L.Min(bm.L)
  23. b := am.B.Min(bm.B)
  24. r := am.R.Max(bm.R)
  25. t := am.T.Max(bm.T)
  26. return BBMake(l, t, r, b)
  27. }
  28. func (bb BB) Expand(v Vect) (BB) {
  29. l := bb.L.Min(v.X)
  30. b := bb.B.Min(v.Y)
  31. r := bb.R.Max(v.X)
  32. t := bb.T.Max(v.Y)
  33. return BBMake(l, t, r, b)
  34. }
  35. func (bb BB) Grow(by Float) (BB) {
  36. l := bb.L - by
  37. b := bb.B - by
  38. r := bb.R + by
  39. t := bb.T + by
  40. return BBMake(l, t, r, b)
  41. }
  42. // clamps the vector to lie within the bbox
  43. func (bb BB) ClampVect(v Vect) (Vect) {
  44. x := bb.L.Max(v.X).Min(bb.R)
  45. y := bb.B.Max(v.Y).Min(bb.T)
  46. return V(x, y)
  47. }
  48. // wrap a vector to a bbox
  49. func (bb BB) WrapVect(v Vect) (Vect) {
  50. ix := (bb.T - bb.L).Abs();
  51. modx := (v.X - bb.L).Mod(ix);
  52. x := modx
  53. if (modx <= 0.0) {
  54. x = modx + ix
  55. }
  56. iy := (bb.T - bb.B).Abs();
  57. mody := (v.Y - bb.B).Mod(iy);
  58. y := mody
  59. if (mody <= 0.0) {
  60. y = mody + iy
  61. }
  62. return V(x + bb.L, y + bb.B);
  63. }
  64. func (bb BB) String() (string) {
  65. return fmt.Sprintf("[%.3f,%.3f|%.3f,%.3f]", bb.L, bb.T, bb.B, bb.R)
  66. }
  67. /*
  68. func (bb * BB) String() string {
  69. var str string
  70. fmt.Sprintf(str, "BB [%f %f %f %f]", bb.L, bb.T, bb.R, bb.B)
  71. return str
  72. }
  73. */