Files
LifeProject/LifeCore/math/Rectangle.h
T
2025-05-13 02:46:21 +03:00

127 lines
2.6 KiB
C++

#ifndef Rectangle_h__
#define Rectangle_h__
#include "math/Vector2D.h"
namespace LifeMath
{
template<typename T>
struct Rectangle
{
T x;
T y;
T width;
T height;
Rectangle()
{
x = y = width = height = 0;
}
Rectangle(T _width, T _height)
{
width = _width;
height = _height;
x = y = 0;
}
Rectangle(T _x, T _y, T _width, T _height)
{
width = _width;
height = _height;
x = _x;
y = _y;
}
bool operator ==(const Rectangle<T>& other)
{
return ((x == other.x) && (y == other.y) && (width == other.width) && (height == other.height));
}
bool operator !=(const Rectangle<T>& other)
{
return ((x != other.x) || (y != other.y) || (width != other.width) || (height != other.height));
}
//get rectangle minimum corner coordinate
Vector2D<T> GetMin() const
{
return Vector2D<T>(x, y);
}
//get rectangle maximum corner coordinate
Vector2D<T> GetMax() const
{
return Vector2D<T>(x + (width), y + (height));
}
//get rectangle maximum X
T GetMaxX() const
{
return x + (width);
}
//get rectangle maximum Y
T GetMaxY() const
{
return y + (height);
}
//get rectangle square
T GetSquare() const
{
return width * height;
}
//merge 2 rectangles into 1 bounding rectangle
void Merge(const Rectangle<T>& other)
{
int minX = std::min<T>(x, other.x);
int maxX = std::max<T>(this->GetMaxX(), other.GetMaxX());
int minY = std::min<T>(y, other.y);
int maxY = std::max<T>(this->GetMaxY(), other.GetMaxY());
this->x = minX;
this->y = minY;
this->width = maxX - minX;
this->height = maxY - minY;
}
//crop this rectangle by other rectangle
void Crop(const Rectangle<T>& other)
{
if(this->x < other.x)
{
T diff = other.x - this->x;
this->x += diff;
this->width -= diff;
}
if(this->y < other.y)
{
T diff = other.y - this->y;
this->y += diff;
this->height -= diff;
}
if(this->GetMaxX() > other.GetMaxX())
{
T diff = this->GetMaxX() - other.GetMaxX();
this->width -= diff;
}
if(this->GetMaxY() > other.GetMaxY())
{
T diff = this->GetMaxY() - other.GetMaxY();
this->height -= diff;
}
if(width < 0)
width = 0;
if(height < 0)
height = 0;
}
bool InRect(const T x, const T y)
{
return (x >= this->x && y >= this->y && x <= (this->x + width) && y <=(this->y + height));
}
bool InRect(const Vector2D<T>& point)
{
return InRect(point.X, point.Y);
}
};
typedef Rectangle<int> Rect2i;
typedef Rectangle<float> Rect2f;
typedef Rectangle<double> Rect2d;
}
#endif // Rectangle_h__