/* -----------------------------------------------------------------------------
	GSFramework
	Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */


		#include "widget_drawable.h"
		#include "picture/pict.h"

		using namespace GS;
		using namespace GS::S2D;


//------------------------------------------------------------------------------
void				DrawableWidget::Compose(Picture &output, const iRect &clip_rect)
{
	if	(hidden || !dirty || !picture)
		return;

	if	(picture)
			rect.Set(0, 0, picture->GetWidth(), picture->GetHeight());
	else	rect.Set(0, 0, 0, 0);

	iRect out_rect = Widget::FormatOutputRect(rect, clip_rect),
		  blit_rect = out_rect.Intersection(clip_rect);

	if	(blit_rect.GetWidth() > rect.GetWidth())
		blit_rect.ex = blit_rect.sx + rect.GetWidth();
	if	(blit_rect.GetHeight() > rect.GetHeight())
		blit_rect.ey = blit_rect.sy + rect.GetHeight();

	int		src_offsetx = blit_rect.sx - out_rect.sx,
			src_offsety = blit_rect.sy - out_rect.sy;
	uchar	*ptr = picture->GetData() + (src_offsety * picture->GetWidth() + src_offsetx) * 4,
			*pds = output.GetData() + (blit_rect.sy * output.GetWidth() + blit_rect.sx) * 4;

	for	(int y = 0; y < blit_rect.GetHeight(); ++y)
	{
		uchar *psc = ptr, *spt = pds;

		for	(int x = 0; x < blit_rect.GetWidth(); ++x)
		{
			uchar alpha = psc[3];

			uchar a_blend = Picture::AlphaCompositeAlpha(spt[3], alpha);
			spt[0] = Picture::AlphaCompositeColor(spt[0], psc[0], spt[3], alpha, a_blend);
			spt[1] = Picture::AlphaCompositeColor(spt[1], psc[1], spt[3], alpha, a_blend);
			spt[2] = Picture::AlphaCompositeColor(spt[2], psc[2], spt[3], alpha, a_blend);
			spt[3] = a_blend;

			spt += 4;
			psc += 4;
		}

		ptr += picture->GetWidth() * 4;
		pds += output.GetWidth() * 4;
	}
	rect = out_rect;
	dirty = false;
}
DrawableWidget::DrawableWidget(int id) : Widget(id)
{
	type = WidgetTypeDrawable;
	picture = NULL;
}
//------------------------------------------------------------------------------
