//
// ImageWarpPlugin.cpp
//
// Imagw Warp Plugin
//
// Copyright (c) 2000 memon/moppi productions
//

//#define WIN32_LEAN_AND_MEAN		// Exclude rarely-used stuff from Windows headers
#include <windows.h>
#include <gl\gl.h>
#include <gl\glu.h>
#include <stdio.h>

// Demopaja headers
#include "DemopajaVersion.h"
#include "PajaTypes.h"
#include "ClassDescC.h"
#include "ImportableI.h"
#include "OpenGLDeviceC.h"
#include "OpenGLViewportC.h"
#include "ImageWarpPlugin.h"
#include "FileIO.h"
#include "AutoGizmoC.h"
#include "ImportableImageI.h"

using namespace PajaTypes;
using namespace PluginClass;
using namespace PajaSystem;
using namespace Edit;
using namespace Composition;
using namespace Import;
using namespace FileIO;

using namespace WarpPlugin;


//////////////////////////////////////////////////////////////////////////
//
//  Blur effect class descriptor.
//

WarpDescC::WarpDescC()
{
	// empty
}

WarpDescC::~WarpDescC()
{
	// empty
}

void*
WarpDescC::create()
{
	return (void*)WarpEffectC::create_new();
}

int32
WarpDescC::get_classtype() const
{
	return CLASS_TYPE_EFFECT;
}

SuperClassIdC
WarpDescC::get_super_class_id() const
{
	return SUPERCLASS_EFFECT;
}

ClassIdC
WarpDescC::get_class_id() const
{
	return CLASS_WARP_EFFECT;
};

const char*
WarpDescC::get_name() const
{
	return "Image Warp";
}

const char*
WarpDescC::get_desc() const
{
	return "Image Warp Effect";
}

const char*
WarpDescC::get_author_name() const
{
	return "Mikko \"memon\" Mononen";
}

const char*
WarpDescC::get_copyright_message() const
{
	return "Copyright (c) 2000 Moppi Productions";
}

const char*
WarpDescC::get_url() const
{
	return "http://moppi.inside.org/demopaja/";
}

const char*
WarpDescC::get_help_filename() const
{
	return "res://ImageWarpHelp.html";
}

uint32
WarpDescC::get_required_device_driver_count() const
{
	return 1;
}

const ClassIdC&
WarpDescC::get_required_device_driver( uint32 ui32Idx )
{
	return PajaSystem::CLASS_OPENGL_DEVICEDRIVER;
}


uint32
WarpDescC::get_ext_count() const
{
	return 0;
}

const char*
WarpDescC::get_ext( uint32 ui32Index ) const
{
	return 0;
}


//////////////////////////////////////////////////////////////////////////
//
// Global descriptors, which will be returned to the Demopaja.
//

WarpDescC	g_rWarpDesc;

#ifndef PAJAPLAYER

//////////////////////////////////////////////////////////////////////////
//
// The DLL
//

BOOL APIENTRY
DllMain( HANDLE hModule, DWORD ulReasonForCall, LPVOID lpReserved )
{
    switch( ulReasonForCall )
	{
		case DLL_PROCESS_ATTACH:
		case DLL_THREAD_ATTACH:
		case DLL_THREAD_DETACH:
		case DLL_PROCESS_DETACH:
			break;
    }
    return TRUE;
}


//
// Returns number of classes inside this plugin DLL.
//

__declspec( dllexport )
int32
get_classdesc_count()
{
	return 1;
}


//
// Returns class descriptors of the plugin classes.
//

__declspec( dllexport )
ClassDescC*
get_classdesc( int32 i )
{
	if( i == 0 )
		return &g_rWarpDesc;
	return 0;
}


//
// Returns the API version this DLL was made with.
//

__declspec( dllexport )
int32
get_api_version()
{
	return DEMOPAJA_VERSION;
}

//
// Returns the DLL name.
//

__declspec( dllexport )
char*
get_dll_name()
{
	return "ImageWarpPlugin.dll - Image Warp Effect plugin (c)2000 memon/moppi productions";
}

#endif



//////////////////////////////////////////////////////////////////////////
//
// The effect
//

WarpEffectC::WarpEffectC() :
	m_ui32TexId( 0 ),
	m_ui32TexWidth( 0 ),
	m_ui32TexHeight( 0 ),
	m_i32TexCapturedWidth( 0 ),
	m_i32TexCapturedHeight( 0 ),
	m_i32TexSize( 0 ),
	m_i32ForceCopy( 0 )
{
	//
	// Create Transform gizmo.
	//
	m_pTraGizmo = AutoGizmoC::create_new( this, "Transform", ID_GIZMO_TRANS );

	m_pTraGizmo->add_parameter(	ParamVector2C::create_new( m_pTraGizmo, "Position", Vector2C(), ID_TRANSFORM_POS,
						PARAM_STYLE_EDITBOX | PARAM_STYLE_ABS_POSITION, PARAM_ANIMATABLE ) );
	
	m_pTraGizmo->add_parameter(	ParamVector2C::create_new( m_pTraGizmo, "Pivot", Vector2C(), ID_TRANSFORM_PIVOT,
						PARAM_STYLE_EDITBOX | PARAM_STYLE_REL_POSITION | PARAM_STYLE_WORLD_SPACE, PARAM_ANIMATABLE ) );
	
	m_pTraGizmo->add_parameter(	ParamVector2C::create_new( m_pTraGizmo, "Scale", Vector2C( 1, 1 ), ID_TRANSFORM_SCALE,
						PARAM_STYLE_EDITBOX | PARAM_STYLE_PERCENT, PARAM_ANIMATABLE, Vector2C(), Vector2C(), 0.01f ) );


	//
	// Create Attributes gizmo.
	//
	m_pAttGizmo = AutoGizmoC::create_new( this, "Attributes", ID_GIZMO_ATTRIB );

	// Color
	m_pAttGizmo->add_parameter(	ParamColorC::create_new( m_pAttGizmo, "Fill Color", ColorC( 1, 1, 1, 1 ), ID_ATTRIBUTE_COLOR,
		PARAM_STYLE_COLORPICKER_RGBA, PARAM_ANIMATABLE ) );

	// Render mode
	ParamIntC*	pRenderMode = ParamIntC::create_new( m_pAttGizmo, "Render mode", 0, ID_ATTRIBUTE_RENDERMODE, PARAM_STYLE_COMBOBOX, PARAM_ANIMATABLE, 0, 2 );
	pRenderMode->add_label( 0, "Normal" );
	pRenderMode->add_label( 1, "Add" );
	pRenderMode->add_label( 2, "Mult" );
	m_pAttGizmo->add_parameter( pRenderMode );

	// Filter mode
	ParamIntC*	pFilterMode = ParamIntC::create_new( m_pAttGizmo, "Filter mode", 0, ID_ATTRIBUTE_FILTERMODE, PARAM_STYLE_COMBOBOX, PARAM_ANIMATABLE, 0, 1 );
	pFilterMode->add_label( 0, "Bilinear" );
	pFilterMode->add_label( 1, "Nearest" );
	m_pAttGizmo->add_parameter( pFilterMode );

	// Warp scale
	m_pAttGizmo->add_parameter(	ParamVector2C::create_new( m_pAttGizmo, "Scale", Vector2C( 1, 1 ), ID_ATTRIBUTE_SCALE,
						PARAM_STYLE_EDITBOX | PARAM_STYLE_PERCENT, PARAM_ANIMATABLE, Vector2C(), Vector2C(), 0.01f ) );

	// Warp offset
	m_pAttGizmo->add_parameter(	ParamVector2C::create_new( m_pAttGizmo, "Offset", Vector2C(), ID_ATTRIBUTE_OFFSET,
						PARAM_STYLE_EDITBOX | PARAM_STYLE_REL_POSITION | PARAM_STYLE_WORLD_SPACE, PARAM_ANIMATABLE ) );

	// Warp rotation
	m_pAttGizmo->add_parameter(	ParamFloatC::create_new( m_pAttGizmo, "Rotation", 0, ID_ATTRIBUTE_ROTATION,
						PARAM_STYLE_EDITBOX | PARAM_STYLE_ANGLE, PARAM_ANIMATABLE, 0, 0, 0.1f ) );
	
	// Warp repeat
	m_pAttGizmo->add_parameter(	ParamIntC::create_new( m_pAttGizmo, "Repeat", 0, ID_ATTRIBUTE_REPEAT, PARAM_STYLE_EDITBOX, PARAM_ANIMATABLE, 1, 100 ) );

	// Additional image	
	m_pAttGizmo->add_parameter( ParamFileC::create_new( m_pAttGizmo, "Image", SUPERCLASS_IMAGE, NULL_CLASSID, ID_ATTRIBUTE_FILE, PARAM_STYLE_FILE, PARAM_ANIMATABLE ) );

}

WarpEffectC::WarpEffectC( EditableI* pOriginal ) :
	EffectI( pOriginal ),
	m_pTraGizmo( 0 ),
	m_pAttGizmo( 0 ),
	m_ui32TexId( 0 ),
	m_ui32TexWidth( 0 ),
	m_ui32TexHeight( 0 ),
	m_i32TexCapturedWidth( 0 ),
	m_i32TexCapturedHeight( 0 ),
	m_i32TexSize( 0 ),
	m_i32ForceCopy( 0 )
{
	// Empty. The parameters are not created in the clone constructor.
}

WarpEffectC::~WarpEffectC()
{
	// Return if this is a clone.
	if( get_original() )
		return;

	if( m_ui32TexId ) {
		glDeleteTextures( 1, &m_ui32TexId );
		m_ui32TexId = 0;
	}

	// Release gizmos.
	m_pTraGizmo->release();
	m_pAttGizmo->release();
}

WarpEffectC*
WarpEffectC::create_new()
{
	return new WarpEffectC;
}

DataBlockI*
WarpEffectC::create()
{
	return new WarpEffectC;
}

DataBlockI*
WarpEffectC::create( EditableI* pOriginal )
{
	return new WarpEffectC( pOriginal );
}

void
WarpEffectC::copy( EditableI* pEditable )
{
	EffectI::copy( pEditable );

	// Make deep copy.
	WarpEffectC*	pEffect = (WarpEffectC*)pEditable;
	m_pTraGizmo->copy( pEffect->m_pTraGizmo );
	m_pAttGizmo->copy( pEffect->m_pAttGizmo );
}

void
WarpEffectC::restore( EditableI* pEditable )
{
	EffectI::restore( pEditable );

	// Make shallow copy.
	WarpEffectC*	pEffect = (WarpEffectC*)pEditable;
	m_pTraGizmo = pEffect->m_pTraGizmo;
	m_pAttGizmo = pEffect->m_pAttGizmo;
}

int32
WarpEffectC::get_gizmo_count()
{
	// Return number of gizmos inside this effect.
	return GIZMO_COUNT;
}

GizmoI*
WarpEffectC::get_gizmo( PajaTypes::int32 i32Index )
{
	// Returns specified gizmo.
	// Since the ID's are zero based, we can use them as indices.
	switch( i32Index ) {
	case ID_GIZMO_TRANS:
		return m_pTraGizmo;
	case ID_GIZMO_ATTRIB:
		return m_pAttGizmo;
	}

	return 0;
}

ClassIdC
WarpEffectC::get_class_id()
{
	// Return the class ID. Should be same as in the class descriptor.
	return CLASS_WARP_EFFECT;
}

const char*
WarpEffectC::get_class_name()
{
	// Return the class name. Should be same as in the class descriptor.
	return "Image Warp";
}

void
WarpEffectC::set_default_file( int32 i32Time, FileHandleC* pHandle )
{
	// empty
}

ParamI*
WarpEffectC::get_default_param( int32 i32Param )
{
	// Return specified default parameter.
	if( i32Param == DEFAULT_PARAM_POSITION )
		return m_pTraGizmo->get_parameter( ID_TRANSFORM_POS );
	else if( i32Param == DEFAULT_PARAM_SCALE )
		return m_pTraGizmo->get_parameter( ID_TRANSFORM_SCALE );
	else if( i32Param == DEFAULT_PARAM_PIVOT )
		return m_pTraGizmo->get_parameter( ID_TRANSFORM_PIVOT );
	return 0;
}

void
WarpEffectC::initialize( uint32 ui32Reason, DemoInterfaceC* pInterface )
{

	EffectI::initialize( ui32Reason, pInterface );

	DeviceContextC* pContext = m_pDemoInterface->get_device_context();
	TimeContextC* pTimeContext = m_pDemoInterface->get_time_context();

	if( ui32Reason == INIT_DEVICE_CHANGED ) {

		OpenGLDeviceC*	pDevice = (OpenGLDeviceC*)pContext->query_interface( CLASS_OPENGL_DEVICEDRIVER );
		if( !pDevice )
			return;

		if( pDevice->get_state() == DEVICE_STATE_SHUTTINGDOWN ) {
			// Delete textures
			if( m_ui32TexId ) {
				glDeleteTextures( 1, &m_ui32TexId );
				m_ui32TexId = 0;
			}
		}

	}
}


inline
uint32
lowest_bit_mask( uint32 v )
{
	return (v & -v);
}

static
uint32
ceil_power2( uint32 ui32Num )
{
	uint32	i = lowest_bit_mask( ui32Num );
	while( i < ui32Num )
		i <<= 1;
	return i;
}


void
WarpEffectC::eval_state( int32 i32Time )
{
	if( !m_pDemoInterface )
		return;

	DeviceContextC* pContext = m_pDemoInterface->get_device_context();
	TimeContextC* pTimeContext = m_pDemoInterface->get_time_context();

	int32		i;
	Matrix2C	rPosMat, rRotMat, rScaleMat, rPivotMat;
	Vector2C	rScale;
	Vector2C	rPos;
	Vector2C	rPivot;

	// Get parameters which affect the transformation.
	((ParamVector2C*)m_pTraGizmo->get_parameter( ID_TRANSFORM_POS ))->get_val( i32Time, rPos );
	((ParamVector2C*)m_pTraGizmo->get_parameter( ID_TRANSFORM_PIVOT ))->get_val( i32Time, rPivot );
	((ParamVector2C*)m_pTraGizmo->get_parameter( ID_TRANSFORM_SCALE ))->get_val( i32Time, rScale );

	// Calculate transformation matrix.
	rPivotMat.set_trans( rPivot );
	rPosMat.set_trans( rPos );
	rScaleMat.set_scale( rScale ) ;
	m_rTM = rPivotMat * rScaleMat * rPosMat;


	// Calculate bounding box vertices

	// Initial values
	float32		f32Width = 25;
	float32		f32Height = 25;

	// If image is used, get the initial dimension from it.
	ImportableImageI*	pImpImage = 0;
	FileHandleC*		pImageHandle;
	int32				i32FileTime;
	((ParamFileC*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_FILE ))->get_file( i32Time, pImageHandle, i32FileTime );
	if( pImageHandle )
		pImpImage = (ImportableImageI*)pImageHandle->get_importable();
	
	if( pImpImage ) {
		pImpImage->eval_state( i32FileTime );
		f32Width = pImpImage->get_width() * 0.5f;
		f32Height = pImpImage->get_height() * 0.5f;
	}

	// Calcualte vertices of the bounding box.
	Vector2C	rMin, rMax;
	Vector2C	rVec;

	m_rVertices[0][0] = -f32Width;		// top-left
	m_rVertices[0][1] = -f32Height;

	m_rVertices[1][0] =  f32Width;		// top-right
	m_rVertices[1][1] = -f32Height;

	m_rVertices[2][0] =  f32Width;		// bottom-right
	m_rVertices[2][1] =  f32Height;

	m_rVertices[3][0] = -f32Width;		// bottom-left
	m_rVertices[3][1] =  f32Height;

	// Calculate bounding box from vertices
	for( i = 0; i < 4; i++ ) {
		rVec = m_rTM * m_rVertices[i];
		m_rVertices[i] = rVec;

		if( !i )
			rMin = rMax = rVec;
		else {
			if( rVec[0] < rMin[0] ) rMin[0] = rVec[0];
			if( rVec[1] < rMin[1] ) rMin[1] = rVec[1];
			if( rVec[0] > rMax[0] ) rMax[0] = rVec[0];
			if( rVec[1] > rMax[1] ) rMax[1] = rVec[1];
		}
	}

	// Store bounding box.
	m_rBBox[0] = rMin;
	m_rBBox[1] = rMax;

	// Get fill color.
	((ParamColorC*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_COLOR ))->get_val( i32Time, m_rFillColor );

	// Get rendermode
	((ParamIntC*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_RENDERMODE ))->get_val( i32Time, m_i32RenderMode );

	// Get filtermode
	((ParamIntC*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_FILTERMODE ))->get_val( i32Time, m_i32FilterMode );

	// Get warp scale
	((ParamVector2C*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_SCALE ))->get_val( i32Time, m_rWarpScale );

	// Get warp offset
	((ParamVector2C*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_OFFSET ))->get_val( i32Time, m_rWarpOffset );

	// Get warp rotation
	((ParamFloatC*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_ROTATION ))->get_val( i32Time, m_f32WarpRotation );

	// Get warp repeat count
	((ParamIntC*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_REPEAT ))->get_val( i32Time, m_i32RepeatCount );


	//
	// render effect
	//

	// Get the OpenGL device.
	OpenGLDeviceC*	pDevice = (OpenGLDeviceC*)pContext->query_interface( CLASS_OPENGL_DEVICEDRIVER );
	if( !pDevice )
		return;

	// Get the OpenGL viewport.
	OpenGLViewportC*	pViewport = (OpenGLViewportC*)pDevice->query_interface( GRAPHICSDEVICE_VIEWPORT_INTERFACE );
	if( !pViewport )
		return;

	// Set orthographic projection.
//	pViewport->set_ortho( m_rBBox, m_rBBox[0][0], m_rBBox[1][0], m_rBBox[1][1], m_rBBox[0][1] );
	pViewport->set_ortho_pixel( m_rBBox );

	// get image from frame buffer
	int32	i32Width = pViewport->get_width();
	int32	i32Height = pViewport->get_height();

	// orverride projection matrix to exact pixel mapping.
//	glMatrixMode( GL_PROJECTION );
//	glLoadIdentity();
//	glOrtho( 0, i32Width, 0, i32Height, -1, 1 );

	glMatrixMode( GL_MODELVIEW );


	int32		i32X, i32Y;
	float32		f32TexX0, f32TexY0, f32TexX1, f32TexY1;
	Vector2C	rVerts[4];
	Vector2C	rPVerts[4];
	Vector2C	rCenter;
	bool		bHasImage = false;

	// If an image is provided, use it instead of capturing the screen.
	if( pImpImage ) {

		//
		// Use image
		//
		glEnable( GL_TEXTURE_2D );

		pImpImage->bind_texture( pDevice, 0, IMAGE_CLAMP | IMAGE_LINEAR );

		m_i32TexCapturedWidth = m_ui32TexWidth = pImpImage->get_width();
		m_i32TexCapturedHeight = m_ui32TexHeight = pImpImage->get_height();

		// calculate texture coordinates and polygon vertices
		BBox2C	rCapture;
		rCapture[0] = pViewport->layout_to_client( m_rBBox[0] );
		rCapture[1] = pViewport->layout_to_client( m_rBBox[1] );

		i32X = (int32)floor( rCapture[0][0] );
		i32Y = (int32)floor( rCapture[0][1] );

		f32TexX0 = 0;
		f32TexY0 = 0;
		f32TexX1 = 1;
		f32TexY1 = 1;

		rVerts[0] = Vector2C( rCapture[0][0], rCapture[0][1] );
		rVerts[1] = Vector2C( rCapture[1][0], rCapture[0][1] );
		rVerts[2] = Vector2C( rCapture[1][0], rCapture[1][1] );
		rVerts[3] = Vector2C( rCapture[0][0], rCapture[1][1] );

		rCenter = rCapture.center();

		bHasImage = true;
	}
	else {

		//
		// Capture warped area from color buffer.
		//

		glEnable( GL_TEXTURE_2D );

		// If the maximum image size has changed, invalidate texture object
		if( ceil_power2( i32Width ) != m_ui32TexWidth || ceil_power2( i32Height ) != m_ui32TexHeight ) {
			glDeleteTextures( 1, &m_ui32TexId );
			m_ui32TexId = 0;
		}

		// If there's no texture object, create new.
		if( !m_ui32TexId ) {
			glGenTextures( 1, &m_ui32TexId );
			glBindTexture( GL_TEXTURE_2D, m_ui32TexId );

			// Calculate the texture size based on the viewport size.
			m_ui32TexWidth = ceil_power2( i32Width );
			m_ui32TexHeight = ceil_power2( i32Height );

			glCopyTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, 0, 0, m_ui32TexWidth, m_ui32TexHeight, 0 );
//			glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB8, m_ui32TexWidth, m_ui32TexHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, 0 );
//			glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, m_ui32TexWidth, m_ui32TexHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0 );
		}
		else 
			glBindTexture( GL_TEXTURE_2D, m_ui32TexId );


		glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );

		if( m_i32FilterMode == FILTERMODE_LINEAR ) {
			glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
			glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
		}
		else {
			glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
			glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
		}

		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );


		// Map the effect bounding box from layout coordinates to pixel coordinates.
		BBox2C	rCapture;
		rCapture[0] = pViewport->layout_to_client( m_rBBox[0] );
		rCapture[1] = pViewport->layout_to_client( m_rBBox[1] );

		// calculate starting position
		i32X = (int32)floor( rCapture[0][0] );
		i32Y = (int32)floor( rCapture[0][1] );

		// calculate capturing size
		m_i32TexCapturedWidth = (int32)ceil( rCapture.width() );
		m_i32TexCapturedHeight = (int32)ceil( rCapture.height() );

		// Clip the capture position and size to current viewport
		if( i32X >= i32Width )
			return;
		if( i32X < 0 ) {
			m_i32TexCapturedWidth += i32X;
			i32X = 0;
		}
		if( (i32X + m_i32TexCapturedWidth) >= i32Width )
			m_i32TexCapturedWidth -= (i32X + m_i32TexCapturedWidth) - i32Width;
		if( m_i32TexCapturedWidth < 0 )
			return;

		if( i32Y >= i32Height )
			return;
		if( i32Y < 0 ) {
			m_i32TexCapturedHeight += i32Y;
			i32Y = 0;
		}
		if( (i32Y + m_i32TexCapturedHeight) >= i32Height )
			m_i32TexCapturedHeight -= (i32Y + m_i32TexCapturedHeight) - i32Height;
		if( m_i32TexCapturedHeight < 0 )
			return;


//		int32	i32W = ceil_power2( m_i32TexCapturedWidth );
//		int32	i32H = ceil_power2( m_i32TexCapturedHeight );

		// Copy the preivously calculated are from color buffer to texture.

		glCopyTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, i32X, i32Y, m_i32TexCapturedWidth, m_i32TexCapturedHeight );

//		uint8*	pBuffer = new uint8[m_ui32TexWidth * m_ui32TexHeight * 4];
//		glReadPixels( i32X, i32Y, i32W, i32H, GL_RGBA, GL_UNSIGNED_BYTE, pBuffer );
//		glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, i32W, i32H, GL_RGBA, GL_UNSIGNED_BYTE, pBuffer );
//		delete [] pBuffer;

		// calculate texture coordinates and polygon vertices
		f32TexX0 = 0;
		f32TexY0 = 0;
		f32TexX1 = m_i32TexCapturedWidth;
		f32TexY1 = m_i32TexCapturedHeight;

		float32	f32InvTexWidth = 1.0f/ (float32)(m_ui32TexWidth);
		float32	f32InvTexHeight = 1.0f/ (float32)(m_ui32TexHeight);

		f32TexX0 *= f32InvTexWidth;
		f32TexY0 *= f32InvTexHeight;
		f32TexX1 *= f32InvTexWidth;
		f32TexY1 *= f32InvTexHeight;

		rVerts[0] = Vector2C( (float32)i32X, (float32)i32Y );
		rVerts[1] = Vector2C( (float32)(i32X + m_i32TexCapturedWidth), (float32)i32Y );
		rVerts[2] = Vector2C( (float32)(i32X + m_i32TexCapturedWidth), (float32)(i32Y + m_i32TexCapturedHeight) );
		rVerts[3] = Vector2C( (float32)i32X, (float32)(i32Y + m_i32TexCapturedHeight) );

		rCenter = rCapture.center();
	}

	// set rendering states
	glDisable( GL_DEPTH_TEST );
	glDepthMask( GL_FALSE );
	glEnable( GL_BLEND );


	//
	// Draw warp
	//


	// draw initial image
	if( bHasImage ) {
		glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
		glColor4ub( 255, 255, 255, 255 );

		glBegin( GL_QUADS );

		glTexCoord2f( f32TexX0, f32TexY0 );
		glVertex2f( rVerts[0][0], rVerts[0][1] );

		glTexCoord2f( f32TexX1, f32TexY0 );
		glVertex2f( rVerts[1][0], rVerts[1][1] );
		
		glTexCoord2f( f32TexX1, f32TexY1 );
		glVertex2f( rVerts[2][0], rVerts[2][1] );
		
		glTexCoord2f( f32TexX0, f32TexY1 );
		glVertex2f( rVerts[3][0], rVerts[3][1] );

		glEnd();
	}


	if( m_i32RenderMode == RENDERMODE_NORMAL )
		glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );	// Normal
	else if( m_i32RenderMode == RENDERMODE_ADD )
		glBlendFunc( GL_SRC_ALPHA, GL_ONE );					// Additive
	else
		glBlendFunc( GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA );	// Multiply

	if( m_i32RenderMode == RENDERMODE_MULT ) // mult
		glColor4f( m_rFillColor[0] * m_rFillColor[3], m_rFillColor[1] * m_rFillColor[3], m_rFillColor[2] * m_rFillColor[3], m_rFillColor[3] );
	else
		glColor4fv( m_rFillColor );


	Vector2C	rWarpOffset = pViewport->delta_layout_to_client( m_rWarpOffset );	// convert from layto to pixel values.

	Vector2C	rFxScale = m_rWarpScale;
	Vector2C	rFxOffset = rWarpOffset;
	float32		f32FxRot = m_f32WarpRotation;

	for( i = 0; i < m_i32RepeatCount; i++ ) {

		Matrix2C	rRotMat;
		rRotMat.set_rot( f32FxRot / 180.0f * M_PI );

		for( uint32 j = 0; j < 4; j++ ) {
			rPVerts[j] = rVerts[j] - rCenter;
			rPVerts[j][0] *= rFxScale[0];
			rPVerts[j][1] *= rFxScale[1];
			rPVerts[j] *= rRotMat;
			rPVerts[j] += rCenter + rFxOffset;
		}

		glBegin( GL_QUADS );

		glTexCoord2f( f32TexX0, f32TexY0 );
		glVertex2f( rPVerts[0][0], rPVerts[0][1] );

		glTexCoord2f( f32TexX1, f32TexY0 );
		glVertex2f( rPVerts[1][0], rPVerts[1][1] );
		
		glTexCoord2f( f32TexX1, f32TexY1 );
		glVertex2f( rPVerts[2][0], rPVerts[2][1] );
		
		glTexCoord2f( f32TexX0, f32TexY1 );
		glVertex2f( rPVerts[3][0], rPVerts[3][1] );

		glEnd();

		// Accumulate scale, offset, and rotation
		rFxScale[0] *= m_rWarpScale[0];
		rFxScale[1] *= m_rWarpScale[1];
		rFxOffset += rWarpOffset;
		f32FxRot += m_f32WarpRotation;
	}


	glDepthMask( GL_TRUE );
}

BBox2C
WarpEffectC::get_bbox()
{
	// Return the bounding box.
	return m_rBBox;
}

const Matrix2C&
WarpEffectC::get_transform_matrix() const
{
	// Return the trnasformation matrix.
	return m_rTM;
}

bool
WarpEffectC::hit_test( const Vector2C& rPoint )
{
	// Point in polygon test.
	// from c.g.a FAQ
	int		i, j;
	bool	bInside = false;

	for( i = 0, j = 4 - 1; i < 4; j = i++ ) {
		if( ( ((m_rVertices[i][1] <= rPoint[1]) && (rPoint[1] < m_rVertices[j][1])) ||
			((m_rVertices[j][1] <= rPoint[1]) && (rPoint[1] < m_rVertices[i][1])) ) &&
			(rPoint[0] < (m_rVertices[j][0] - m_rVertices[i][0]) * (rPoint[1] - m_rVertices[i][1]) / (m_rVertices[j][1] - m_rVertices[i][1]) + m_rVertices[i][0]) )

			bInside = !bInside;
	}

	return bInside;
}


enum WarpEffectChunksE {
	CHUNK_WARP_BASE =			0x1000,
	CHUNK_WARP_TRANSGIZMO =		0x2000,
	CHUNK_WARP_ATTRIBGIZMO =	0x3000,
};

const uint32	WARP_VERSION = 1;

uint32
WarpEffectC::save( SaveC* pSave )
{
	uint32	ui32Error = IO_OK;

	// EffectI base class
	pSave->begin_chunk( CHUNK_WARP_BASE, WARP_VERSION );
		ui32Error = EffectI::save( pSave );
	pSave->end_chunk();

	// Transform
	pSave->begin_chunk( CHUNK_WARP_TRANSGIZMO, WARP_VERSION );
		ui32Error = m_pTraGizmo->save( pSave );
	pSave->end_chunk();

	// Attribute
	pSave->begin_chunk( CHUNK_WARP_ATTRIBGIZMO, WARP_VERSION );
		ui32Error = m_pAttGizmo->save( pSave );
	pSave->end_chunk();

	return ui32Error;
}

uint32
WarpEffectC::load( LoadC* pLoad )
{
	uint32	ui32Error = IO_OK;

	while( (ui32Error = pLoad->open_chunk()) == IO_OK ) {

		switch( pLoad->get_chunk_id() ) {
		case CHUNK_WARP_BASE:
			// EffectI base class
			if( pLoad->get_chunk_version() == WARP_VERSION )
				ui32Error = EffectI::load( pLoad );
			break;

		case CHUNK_WARP_TRANSGIZMO:
			// Transform
			if( pLoad->get_chunk_version() == WARP_VERSION )
				ui32Error = m_pTraGizmo->load( pLoad );
			break;

		case CHUNK_WARP_ATTRIBGIZMO:
			// Attribute
			if( pLoad->get_chunk_version() == WARP_VERSION )
				ui32Error = m_pAttGizmo->load( pLoad );
			break;

		default:
			assert( 0 );
		}

		pLoad->close_chunk();

		if( ui32Error != IO_OK && ui32Error != IO_END )
			return ui32Error;
	}

	return ui32Error;
}
