/*
	Twilight Prophecy 3D/Multimedia SDK
	A multi-platform development system for virtual reality and multimedia.

	Copyright (C) 1997-2001 by Twilight 3D Finland Oy Ltd.

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

	Please read the file LICENSE.TXT for additional details.


	source: 
		surface implementation

	revision history:
		Jan/24/2001 - Jukka Liimatta - initial revision/renaissance build
*/
#include <prcore/prcore.hpp>
using namespace prcore;



Surface::Surface()
: width(0), height(0), pitch(0), image(NULL)
{
}


Surface::Surface(int width_, int height_, int pitch_, const PixelFormat& format_, void* image_)
: width(width_), height(height_), pitch(pitch_), format(format_), image((uint8*)image_)
{
}


Surface::~Surface()
{
}


Surface Surface::GetSurface(const Rect& rect) const
{
	// clip
	Rect q;
	if ( !q.Intersect(GetRect(),rect) )
		return *this;
		
	Surface surface;
	surface.width = q.width;
	surface.height = q.height;
	surface.pitch = pitch;
	surface.format = format;
	surface.image = image + q.y * pitch + q.x * format.GetBytes();
	
	return surface;
}


void Surface::Blit(int x, int y, const Surface& source)
{
	// assert
	assert( image && source.image );

	// clip
	Rect rect;
	if ( !rect.Intersect(
		Rect(0,0,width,height),
		Rect(x,y,source.width,source.height) ))
		return;

	int sx = rect.x - x;
	int sy = rect.y - y;

	// setup blit surfaces
	int bpp1 = format.GetBytes();
	int bpp2 = source.format.GetBytes();
	uint8* image1 = image + rect.y * pitch + rect.x * bpp1;
	uint8* image2 = source.image + sy * source.pitch + sx * bpp2;

	Surface s1(rect.width,rect.height,pitch,format,image1);
	Surface s2(rect.width,rect.height,source.pitch,source.format,image2);

	// blit
	s1.Blit(s2,BLIT_COPY);
}


int Surface::GetWidth() const
{
	return width;
}


int Surface::GetHeight() const
{
	return height;
}


int Surface::GetPitch() const
{
	return pitch;
}


const PixelFormat& Surface::GetFormat() const
{
	return format;
}


uint8* Surface::GetImage() const
{
	return image;
}


Rect Surface::GetRect() const
{
	return Rect(0,0,width,height);
}
