#include "munga.h"
#pragma hdrstop

#include "rect2d.h"

//
//------------------------------------------------------------------------
// Creators
//------------------------------------------------------------------------
//
Rectangle2D::Rectangle2D()
{
	MakeEmpty();				// uninitialized rectangles should be "empty"
}

Rectangle2D::Rectangle2D(
		Vector2DOf<int> bl,
		Vector2DOf<int> tr
	)
{
	bottomLeft = bl;
	topRight = tr;
}

Rectangle2D::Rectangle2D(
		int x1, int y1, int x2, int y2
	)
{
	bottomLeft.x = x1;
	bottomLeft.y = y1;
	topRight.x = x2;
	topRight.y = y2;
}

//
//------------------------------------------------------------------------
// Union (returns bounding rectangle)
//------------------------------------------------------------------------
//
void
	Rectangle2D::Union(
			const Rectangle2D& r1,
			const Rectangle2D& r2
		)
{
	Check(this);
	Check(&r1);
	Check(&r2);

	if (r1.IsEmpty())
	{
		if (r2.IsEmpty())
		{
			MakeEmpty();
		}
		else
		{
			bottomLeft = r2.bottomLeft;
			topRight = r2.topRight;
		}
	}
	else
	{
		if (r2.IsEmpty())
		{
			bottomLeft = r1.bottomLeft;
			topRight = r1.topRight;
		}
		else
		{
			bottomLeft.x = Min(r1.bottomLeft.x, r2.bottomLeft.x);
			bottomLeft.y = Min(r1.bottomLeft.y, r2.bottomLeft.y);
			topRight.x = Max(r1.topRight.x, r2.topRight.x);
			topRight.y = Max(r1.topRight.y, r2.topRight.y);
		}
	}
}

//
//------------------------------------------------------------------------
// Intersection (returns overlapping section)
//------------------------------------------------------------------------
//
void
	Rectangle2D::Intersection(
		const Rectangle2D& r1,
		const Rectangle2D& r2
		)
{
	Check(this);
	Check(&r1);
	Check(&r2);

	if (r1.IsEmpty())
	{
		MakeEmpty();
	}
	else
	{
		if (r2.IsEmpty())
		{
			MakeEmpty();
		}
		else
		{
			bottomLeft.x = Max(r1.bottomLeft.x, r2.bottomLeft.x);
			bottomLeft.y = Max(r1.bottomLeft.y, r2.bottomLeft.y);
			topRight.x = Min(r1.topRight.x, r2.topRight.x);
			topRight.y = Min(r1.topRight.y, r2.topRight.y);
		}
	}
}

//
//------------------------------------------------------------------------
// Output stream operator
//------------------------------------------------------------------------
//
std::ostream& operator<<(std::ostream& Stream, const Rectangle2D& r)
{
	Check(&r);
	return Stream << '(' << r.bottomLeft << ',' << r.topRight << ')';
}

//
//------------------------------------------------------------------------
// TestInstance
//------------------------------------------------------------------------
//
Logical
	Rectangle2D::TestInstance() const
{
	return True;
}

#if defined(TEST_CLASS)
#	include "rect2d.tcp"
#endif
