Implement Point::Wrap

This commit is contained in:
Dmitry Marakasov 2015-01-20 02:38:16 +03:00
parent ecf9731750
commit fa7ba94957
3 changed files with 63 additions and 0 deletions

View File

@ -128,4 +128,24 @@ Point& Point::Clamp(const Rect& rect) {
return *this;
}
Point Point::GetWrapped(const Rect& rect) const {
Point p = *this;
p.Wrap(rect);
return p;
}
Point& Point::Wrap(const Rect& rect) {
if (x < rect.x)
x = rect.x + rect.w - 1 - (rect.x - x + rect.w - 1) % rect.w;
else if (x >= rect.x + rect.w)
x = rect.x + (x - rect.x - rect.w) % rect.w;
if (y < rect.y)
y = rect.y + rect.h - 1 - (rect.y - y + rect.h - 1) % rect.h;
else if (y >= rect.y + rect.h)
y = rect.y + (y - rect.y - rect.h) % rect.h;
return *this;
}
}

View File

@ -253,6 +253,26 @@ public:
///
////////////////////////////////////////////////////////////
Point& Clamp(const Rect& rect);
////////////////////////////////////////////////////////////
/// \brief Get a point wrapped within a specified rect
///
/// \param[in] rect Rectangle to wrap with
///
/// \returns Wrapped point
///
////////////////////////////////////////////////////////////
Point GetWrapped(const Rect& rect) const;
////////////////////////////////////////////////////////////
/// \brief Wrap point coordinates within a spedified rect
///
/// \param[in] rect Rectangle to wrap with
///
/// \returns Reference to self
///
////////////////////////////////////////////////////////////
Point& Wrap(const Rect& rect);
};
}

View File

@ -310,4 +310,27 @@ BEGIN_TEST()
EXPECT_TRUE(Point(10, 10).GetClamped(rect) == Point(3, 5));
EXPECT_TRUE(Point(10, 10).Clamp(rect) == Point(3, 5));
}
{
// wrap
Rect rect(10, 20, 30, 40);
EXPECT_TRUE(Point(10, 20).GetWrapped(rect) == Point(10, 20));
EXPECT_TRUE(Point(39, 59).GetWrapped(rect) == Point(39, 59));
EXPECT_TRUE(Point(9, 20).GetWrapped(rect) == Point(39, 20));
EXPECT_TRUE(Point(40, 20).GetWrapped(rect) == Point(10, 20));
EXPECT_TRUE(Point(10, 19).GetWrapped(rect) == Point(10, 59));
EXPECT_TRUE(Point(10, 60).GetWrapped(rect) == Point(10, 20));
EXPECT_TRUE(Point(-50, -60).GetWrapped(rect) == Point(10, 20));
EXPECT_TRUE(Point(-20, -20).GetWrapped(rect) == Point(10, 20));
EXPECT_TRUE(Point(10, 20).GetWrapped(rect) == Point(10, 20));
EXPECT_TRUE(Point(40, 60).GetWrapped(rect) == Point(10, 20));
EXPECT_TRUE(Point(70, 100).GetWrapped(rect) == Point(10, 20));
EXPECT_TRUE(Point(100, 140).GetWrapped(rect) == Point(10, 20));
EXPECT_TRUE(Point(-19, -19).GetWrapped(rect) == Point(11, 21));
EXPECT_TRUE(Point(-21, -21).GetWrapped(rect) == Point(39, 59));
}
END_TEST()