types.rs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. use std::cmp::{min, max};
  2. #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
  3. pub struct Size {
  4. pub width: usize,
  5. pub height: usize,
  6. }
  7. impl specs::Component for Size {
  8. type Storage = specs::VecStorage<Self>;
  9. }
  10. impl From<[usize; 2]> for Size {
  11. fn from([width, height]: [usize; 2]) -> Size {
  12. Size { width, height }
  13. }
  14. }
  15. #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
  16. pub struct Coord {
  17. pub x: usize,
  18. pub y: usize,
  19. }
  20. impl specs::Component for Coord {
  21. type Storage = specs::VecStorage<Coord>;
  22. }
  23. impl From<[usize; 2]> for Coord {
  24. fn from([x, y]: [usize; 2]) -> Coord {
  25. Coord { x, y }
  26. }
  27. }
  28. #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
  29. pub struct Rect {
  30. pub origin: Coord,
  31. pub size: Size,
  32. }
  33. impl Rect {
  34. pub fn new(origin: Coord, size: Size) -> Rect{
  35. Rect { origin, size }
  36. }
  37. pub fn from_points(p1: Coord, p2: Coord) -> Rect {
  38. let origin = Coord {
  39. x: min(p1.x, p2.x),
  40. y: min(p1.y, p2.y),
  41. };
  42. let size = Size {
  43. width: max(p1.x, p2.x) - origin.x,
  44. height: max(p1.y, p2.y) - origin.y,
  45. };
  46. Rect { origin, size }
  47. }
  48. pub fn area(&self) -> usize {
  49. self.size.width * self.size.height
  50. }
  51. pub fn width(&self) -> usize {
  52. self.size.width
  53. }
  54. pub fn height(&self) -> usize {
  55. self.size.height
  56. }
  57. pub fn x(&self) -> usize {
  58. self.origin.x
  59. }
  60. pub fn y(&self) -> usize {
  61. self.origin.y
  62. }
  63. pub fn contains(&self, pt: impl Into<Coord>) -> bool {
  64. let pt = pt.into();
  65. pt.x >= self.origin.x &&
  66. pt.y >= self.origin.y &&
  67. pt.x < self.origin.x + self.size.width &&
  68. pt.y < self.origin.y + self.size.height
  69. }
  70. }