Add clamp() member function to constrain Offsets and Coords to a bounding box
authorMartin Read <martin@blackswordsonics.com>
Tue, 18 Feb 2014 22:41:21 +0000 (22:41 +0000)
committerMartin Read <martin@blackswordsonics.com>
Tue, 18 Feb 2014 22:41:21 +0000 (22:41 +0000)
* coord.hh: Added Offset::clamp() and Coord::clamp() member functions which
  constrain the x and y values to fit inside a specified bounding box.

coord.hh

index 7f06491..e8c07a6 100644 (file)
--- a/coord.hh
+++ b/coord.hh
@@ -63,6 +63,11 @@ public:
     bool operator <=(Offset const& right) const { return (y < right.y) || ((y == right.y) && (x <= right.x)); }
     bool operator >(Offset const& right) const { return (y > right.y) || ((y == right.y) && (x > right.x)); }
     bool operator >=(Offset const& right) const { return (y > right.y) || ((y == right.y) && (x >= right.x)); }
+    void clamp(int ymin, int xmin, int ymax, int xmax)
+    {
+        y = std::min(ymax, std::max(ymin, y));
+        x = std::min(xmax, std::max(xmin, x));
+    }
 };
 
 /*! \brief A two-dimensional point
@@ -93,6 +98,11 @@ public:
     bool operator <=(Coord const& right) const { return (y < right.y) || ((y == right.y) && (x <= right.x)); }
     bool operator >(Coord const& right) const { return (y > right.y) || ((y == right.y) && (x > right.x)); }
     bool operator >=(Coord const& right) const { return (y > right.y) || ((y == right.y) && (x >= right.x)); }
+    void clamp(int ymin, int xmin, int ymax, int xmax)
+    {
+        y = std::min(ymax, std::max(ymin, y));
+        x = std::min(xmax, std::max(xmin, x));
+    }
 };
 
 extern Coord const Nowhere;