//
// GlarePlugin.cpp
//
// Glare 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>
#include "glext.h"

#include "extgl.h"

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

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

using namespace GlarePlugin;


// stuff from GlarePlugin.cpp
extern PBufferC*		g_pPBuffer;
extern void				init_pbuffer();
extern void				release_pbuffer();



static
void
TRACE( const char* szFormat, ...  )
{
	char	szMsg[256];
	va_list	rList;
	va_start( rList, szFormat );
	_vsnprintf( szMsg, 255, szFormat, rList );
	va_end( rList );
	OutputDebugString( szMsg );
}


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;
}





//////////////////////////////////////////////////////////////////////////
//
//  Glare effect class descriptor.
//

GlareDescC::GlareDescC()
{
	// empty
}

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

void*
GlareDescC::create()
{
	return (void*)GlareEffectC::create_new();
}

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

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

ClassIdC
GlareDescC::get_class_id() const
{
	return CLASS_GLARE_EFFECT;
}

const char*
GlareDescC::get_name() const
{
	return "Glare";
}

const char*
GlareDescC::get_desc() const
{
	return "Glare Effect";
}

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

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

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

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

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

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


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

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


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

GlareDescC	g_rGlareDesc;


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

GlareEffectC::GlareEffectC() :
	m_ui32TexId( 0 ),
	m_ui32TexWidth( 0 ),
	m_ui32TexHeight( 0 ),
	m_i32TexCapturedWidth( 0 ),
	m_i32TexCapturedHeight( 0 ),
	m_i32ValidTime( 0 ),
	m_bValidFeedback( false )
{
	init_pbuffer();

	for( int32 i = 0; i < BLUR_TEX_COUNT; i++ )
		m_ui32BlurTexId[i] = 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 );

	// Glare Size
	m_pAttGizmo->add_parameter(	ParamFloatC::create_new( m_pAttGizmo, "Size", 0.2f, ID_ATTRIBUTE_SIZE,
						PARAM_STYLE_EDITBOX | PARAM_STYLE_PERCENT, PARAM_ANIMATABLE, 0, 1.0f, 0.01f ) );

	// Glare Amount
	m_pAttGizmo->add_parameter(	ParamFloatC::create_new( m_pAttGizmo, "Amount", 1.0f, ID_ATTRIBUTE_AMOUNT,
						PARAM_STYLE_EDITBOX | PARAM_STYLE_PERCENT, PARAM_ANIMATABLE, 0, 1.0f, 0.01f ) );

	// Direction
	ParamIntC*	pMode = ParamIntC::create_new( m_pAttGizmo, "Type", 0, ID_ATTRIBUTE_TYPE, PARAM_STYLE_COMBOBOX, PARAM_ANIMATABLE, 0, 3 );
	pMode->add_label( 0, "Bright" );
	pMode->add_label( 1, "Lighten" );
	pMode->add_label( 2, "Darken" );
	pMode->add_label( 3, "Dark" );
	m_pAttGizmo->add_parameter( pMode );

	// Glare feedback
//	m_pAttGizmo->add_parameter(	ParamFloatC::create_new( m_pAttGizmo, "Feedback", 0.0f, ID_ATTRIBUTE_FEEDBACK,
//						PARAM_STYLE_EDITBOX | PARAM_STYLE_PERCENT, PARAM_ANIMATABLE, 0.0f, 1.0f, 0.01f ) );
}

GlareEffectC::GlareEffectC( 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_i32ValidTime( 0 ),
	m_bValidFeedback( false )
{
	// The parameters are not created in the clone constructor.
	init_pbuffer();

	for( int32 i = 0; i < BLUR_TEX_COUNT; i++ )
		m_ui32BlurTexId[i] = 0;
}

GlareEffectC::~GlareEffectC()
{
	release_pbuffer();

	// Return if this is a clone.
	if( get_original() )
		return;

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

	for( int32 i = 0; i < BLUR_TEX_COUNT; i++ ) {
		if( m_ui32BlurTexId[i] ) {
			glDeleteTextures( 1, &m_ui32BlurTexId[i] );
			m_ui32BlurTexId[i] = 0;
		}
	}

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

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

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

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

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

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

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

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

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

GizmoI*
GlareEffectC::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
GlareEffectC::get_class_id()
{
	// Return the class ID. Should be same as in the class descriptor.
	return CLASS_GLARE_EFFECT;
}

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

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

ParamI*
GlareEffectC::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
GlareEffectC::initialize( uint32 ui32Reason, DemoInterfaceC* pInterface )
{
	EffectI::initialize( ui32Reason, pInterface );

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

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

	if( ui32Reason == INIT_DEVICE_CHANGED ) {

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

	}
	else if( ui32Reason == INIT_INITIAL_UPDATE ) {

		init_gl_extension();

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

		check_buffer_size( pViewport->get_width(), pViewport->get_height() );
	}
}


void
GlareEffectC::make_blur_textures()
{
	int32	i;

	if( !g_pPBuffer || !g_pPBuffer->is_initialised() )
		return;

	// if multitexture is not supported, die out
	if( !g_bMultiTexture )
		return;

	if( !g_pPBuffer->begin_draw() ) {
		TRACE( "begin_draw failed\n" );
		return;
	}

	//Setup ortho mode.
	glMatrixMode( GL_PROJECTION );
	glLoadIdentity();
	glOrtho( 0, g_pPBuffer->get_width(), 0, g_pPBuffer->get_height(), -100, 100 );
	glMatrixMode( GL_MODELVIEW );
	glLoadIdentity();

	glEnable( GL_BLEND );
	glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
	glDisable( GL_DEPTH_TEST );
	glDepthMask( GL_FALSE );

	float32	f32A = 0.5f;

	// the texture mix alpha is in color, and the secand mix alpha is in the alpha
	glColor4f( f32A, f32A, f32A, 0.5f );

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

		int32	i32W = (int32)m_ui32TexWidth >> (i + 1);
		int32	i32H = (int32)m_ui32TexHeight >> (i + 1);

//		TRACE( "w: %d  h: %d\n", i32W, i32H );

		float32	f32OX = 1.0f / (float32)i32W;
		float32	f32OY = 1.0f / (float32)i32H;

		uint32	ui32SrcTex;
		if( i > 0 )
			ui32SrcTex = m_ui32BlurTexId[i - 1];
		else
			ui32SrcTex = m_ui32TexId;


		glActiveTextureARB( GL_TEXTURE1_ARB );
		glEnable( GL_TEXTURE_2D );
		glBindTexture( GL_TEXTURE_2D, ui32SrcTex );
		glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT );
		glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB_EXT, GL_INTERPOLATE_EXT );
		glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB_EXT, GL_PREVIOUS_EXT );
		glTexEnvi( GL_TEXTURE_ENV, GL_OPERAND0_RGB_EXT, GL_SRC_COLOR );
		glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE1_RGB_EXT, GL_TEXTURE );
		glTexEnvi( GL_TEXTURE_ENV, GL_OPERAND1_RGB_EXT, GL_SRC_COLOR );
		glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE2_RGB_EXT, GL_PRIMARY_COLOR_EXT );
		glTexEnvi( GL_TEXTURE_ENV, GL_OPERAND2_RGB_EXT, GL_SRC_COLOR );


		glActiveTextureARB( GL_TEXTURE0_ARB );
		glEnable( GL_TEXTURE_2D );
		glBindTexture( GL_TEXTURE_2D, ui32SrcTex );
		glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE );


		glDisable( GL_BLEND );

		glBegin( GL_QUADS );
			glMultiTexCoord2fARB( GL_TEXTURE1_ARB, 0 + f32OX, 0 );
			glMultiTexCoord2fARB( GL_TEXTURE0_ARB, 0 - f32OX, 0 );
			glVertex3f( 0, 0, 10 );
			
			glMultiTexCoord2fARB( GL_TEXTURE1_ARB, 1 + f32OX, 0 );
			glMultiTexCoord2fARB( GL_TEXTURE0_ARB, 1 - f32OX, 0 );
			glVertex3f( (float32)i32W, 0, 10 );
			
			glMultiTexCoord2fARB( GL_TEXTURE1_ARB, 1 + f32OX, 1 );
			glMultiTexCoord2fARB( GL_TEXTURE0_ARB, 1 - f32OX, 1 );
			glVertex3f( (float32)i32W, (float32)i32H, 10 );
			
			glMultiTexCoord2fARB( GL_TEXTURE1_ARB, 0 + f32OX, 1 );
			glMultiTexCoord2fARB( GL_TEXTURE0_ARB, 0 - f32OX, 1 );
			glVertex3f( 0, (float32)i32H, 10 );
		glEnd();


		glEnable( GL_BLEND );

		
		glBegin( GL_QUADS );
			glMultiTexCoord2fARB( GL_TEXTURE1_ARB, 0, 0 + f32OY );
			glMultiTexCoord2fARB( GL_TEXTURE0_ARB, 0, 0 - f32OY );
			glVertex3f( 0, 0, 10 );
			
			glMultiTexCoord2fARB( GL_TEXTURE1_ARB, 1, 0 + f32OY );
			glMultiTexCoord2fARB( GL_TEXTURE0_ARB, 1, 0 - f32OY );
			glVertex3f( (float32)i32W, 0, 10 );
			
			glMultiTexCoord2fARB( GL_TEXTURE1_ARB, 1, 1 + f32OY );
			glMultiTexCoord2fARB( GL_TEXTURE0_ARB, 1, 1 - f32OY );
			glVertex3f( (float32)i32W, (float32)i32H, 10 );
			
			glMultiTexCoord2fARB( GL_TEXTURE1_ARB, 0, 1 + f32OY );
			glMultiTexCoord2fARB( GL_TEXTURE0_ARB, 0, 1 - f32OY );
			glVertex3f( 0, (float32)i32H, 10 );
		glEnd();



		glBindTexture( GL_TEXTURE_2D, m_ui32BlurTexId[i] );

		glCopyTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, 0, 0, i32W, i32H );


	}

	glDisable( GL_BLEND );
	glEnable( GL_DEPTH_TEST );
	glDepthMask( GL_TRUE );


	g_pPBuffer->end_draw();
}

void
GlareEffectC::check_buffer_size( int32 i32Width, int32 i32Height )
{
	int32	i;

	// get image from frame buffer
	int32	i32WidthPow2 = ceil_power2( i32Width );
	int32	i32HeightPow2 = ceil_power2( i32Height );

	// Resize pbfueer on demand
	if( g_pPBuffer ) {
		int32	i32PBufWidth = i32WidthPow2 / 2;
		int32	i32PBufHeight = i32HeightPow2 / 2;
		if( !g_pPBuffer->is_initialised() || i32PBufWidth > g_pPBuffer->get_width() || i32PBufHeight > g_pPBuffer->get_height() ) {
			TRACE( "GLARE: pbuffer->init( %d, %d )\n", i32PBufWidth, i32PBufHeight );
			g_pPBuffer->init( i32PBufWidth, i32PBufHeight, PBUFFER_TEXTURE_NONE );
		}
	}

	// Resize texture

	// If the maximum image size has changed, invalidate texture object if necessary
	if( i32WidthPow2 > (int32)m_ui32TexWidth || i32HeightPow2 > (int32)m_ui32TexHeight ) {
		if( m_ui32TexId )
			glDeleteTextures( 1, &m_ui32TexId );
		m_ui32TexId = 0;

		for( i = 0; i < BLUR_TEX_COUNT; i++ ) {
			if( m_ui32BlurTexId[i] )
				glDeleteTextures( 1, &m_ui32BlurTexId[i] );
			m_ui32BlurTexId[i] = 0;
		}
	}

	if( !m_ui32TexId ) {
		glGenTextures( 1, &m_ui32TexId );
		glBindTexture( GL_TEXTURE_2D, m_ui32TexId );
		m_ui32TexWidth = i32WidthPow2;
		m_ui32TexHeight = i32HeightPow2;
		glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, m_ui32TexWidth, m_ui32TexHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, 0 );
		glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
	}

	for( int32 i = 0; i < BLUR_TEX_COUNT; i++ ) {
		if( !m_ui32BlurTexId[i] ) {
			glGenTextures( 1, &m_ui32BlurTexId[i] );
			glBindTexture( GL_TEXTURE_2D, m_ui32BlurTexId[i] );
			int32	i32BlurTexWidth = (int32)m_ui32TexWidth >> (i + 1);
			int32	i32BlurTexHeight = (int32)m_ui32TexHeight >> (i + 1);
			glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, i32BlurTexWidth, i32BlurTexHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, 0 );
			glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
			glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
			glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
			glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
			glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
		}
	}

}


#define		MAX_PASSES	31

void
GlareEffectC::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;

	float32		f32Width = 25;
	float32		f32Height = 25;
	Vector2C	rMin, rMax;
	Vector2C	rVec;

	// Calcualte vertices of the rectangle.
	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
	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;

	PajaTypes::float32	f32Size = 1.0f;
	PajaTypes::float32	f32Amount = 1.0f;
	PajaTypes::int32	i32Type = 0;
//	PajaTypes::float32	f32Feedback = 0;

	// Get Size
	((ParamFloatC*)m_pAttGizmo->get_parameter_by_id( ID_ATTRIBUTE_SIZE ))->get_val( i32Time, f32Size );

	// Get Amount
	((ParamFloatC*)m_pAttGizmo->get_parameter_by_id( ID_ATTRIBUTE_AMOUNT ))->get_val( i32Time, f32Amount );

	// Get Direction
	((ParamIntC*)m_pAttGizmo->get_parameter_by_id( ID_ATTRIBUTE_TYPE ))->get_val( i32Time, i32Type );

	// Get Feedback
//	((ParamFloatC*)m_pAttGizmo->get_parameter_by_id( ID_ATTRIBUTE_FEEDBACK ))->get_val( i32Time, f32Feedback );


	//
	// draw 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_pixel( m_rBBox );

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

	
	check_buffer_size( i32Width, i32Height );

	// the scale used with size parameter
	Vector2C	rOne( 1, 1 );
	rOne = pViewport->delta_layout_to_client( rOne );


	glBindTexture( GL_TEXTURE_2D, m_ui32TexId );


	// calc where we get our image
	Vector2C	rOffset( 16, 16 );
	BBox2C	rCapture;
	rCapture[0] = pViewport->layout_to_client( m_rBBox[0] - rOffset );
	rCapture[1] = pViewport->layout_to_client( m_rBBox[1] + rOffset );

	int32	i32X, i32Y;

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

	m_i32TexCapturedWidth = (int32)ceil( rCapture.width() );
	m_i32TexCapturedHeight = (int32)ceil( rCapture.height() );

	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;



	glEnable( GL_TEXTURE_2D );
	glDisable( GL_DEPTH_TEST );
	glDepthMask( GL_FALSE );
	glEnable( GL_BLEND );

/*	if( m_bValidFeedback && f32Feedback > 0.01f ) {

		// draw old texture blended
		glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );

		glColor4ub( 255, 255, 255, f32Feedback * 255.0f );

		glBegin( GL_QUADS );

			glTexCoord2f( m_f32LastTexX0, m_f32LastTexY0 );
			glVertex2f( (float32)m_i32LastX, (float32)m_i32LastY );

			glTexCoord2f( m_f32LastTexX1, m_f32LastTexY0 );
			glVertex2f( (float32)(m_i32LastX + m_i32LastWidth), (float32)m_i32LastY );
			
			glTexCoord2f( m_f32LastTexX1, m_f32LastTexY1 );
			glVertex2f( (float32)(m_i32LastX + m_i32LastWidth), (float32)(m_i32LastY + m_i32LastHeight) );
			
			glTexCoord2f( m_f32LastTexX0, m_f32LastTexY1 );
			glVertex2f( (float32)m_i32LastX, (float32)(m_i32LastY + m_i32LastHeight) );

		glEnd();
	}
*/


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

	// make blur textures
	make_blur_textures();

	float32	f32TexX0 = 0;
	float32	f32TexY0 = 0;
	float32	f32TexX1 = m_i32TexCapturedWidth;
	float32	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;

	// draw Glare

	// draw GBlur

	uint32	ui32TexId0 = 0;
	uint32	ui32TexId1 = 0;

	float32	f32LogSize = (float32)(log( f32Size * 20.0f * rOne[0] ) / log( 2.0f ));
	int32	i32Idx0 = (int32)floor( f32LogSize );
	float32	f32A = 1.0f - (f32LogSize - (float32)i32Idx0);
	int32	i32Idx1 = i32Idx0 + 1;

	i32Idx0 = __max( __min( i32Idx0, BLUR_TEX_COUNT ), 0 );
	i32Idx1 = __max( __min( i32Idx1, BLUR_TEX_COUNT ), 0 );

	if( i32Idx0 == 0 )
		ui32TexId0 = m_ui32TexId;
	else if( i32Idx0 <= BLUR_TEX_COUNT )
		ui32TexId0 = m_ui32BlurTexId[i32Idx0 - 1];

	if( i32Idx1 == 0 )
		ui32TexId1 = m_ui32TexId;
	else if( i32Idx1 <= BLUR_TEX_COUNT )
		ui32TexId1 = m_ui32BlurTexId[i32Idx1 - 1];


	// color is the mix between the two textues, and alpha is the destination blend
	glColor4f( f32A, f32A, f32A, f32Amount );


	glActiveTextureARB( GL_TEXTURE1_ARB );
	glEnable( GL_TEXTURE_2D );
	glBindTexture( GL_TEXTURE_2D, ui32TexId1 );
	glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT );
	glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB_EXT, GL_INTERPOLATE_EXT );
	glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB_EXT, GL_PREVIOUS_EXT );
	if( i32Type == GLARE_DARK )
		glTexEnvi( GL_TEXTURE_ENV, GL_OPERAND0_RGB_EXT, GL_ONE_MINUS_SRC_COLOR );
	else
		glTexEnvi( GL_TEXTURE_ENV, GL_OPERAND0_RGB_EXT, GL_SRC_COLOR );
	glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE1_RGB_EXT, GL_TEXTURE );
	if( i32Type == GLARE_DARK )
		glTexEnvi( GL_TEXTURE_ENV, GL_OPERAND1_RGB_EXT, GL_ONE_MINUS_SRC_COLOR );
	else
		glTexEnvi( GL_TEXTURE_ENV, GL_OPERAND1_RGB_EXT, GL_SRC_COLOR );
	glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE2_RGB_EXT, GL_PRIMARY_COLOR_EXT );
	glTexEnvi( GL_TEXTURE_ENV, GL_OPERAND2_RGB_EXT, GL_SRC_COLOR );


	glActiveTextureARB( GL_TEXTURE0_ARB );
	glEnable( GL_TEXTURE_2D );
	glBindTexture( GL_TEXTURE_2D, ui32TexId0 );
	glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE );


	if( i32Type == GLARE_BRIGHT ) {
		glBlendFunc( GL_SRC_ALPHA, GL_ONE );
	}
	else if( i32Type == GLARE_LIGHTEN ) {
		if( g_bBlendEqu )
			glBlendEquation( GL_MAX );
		glBlendFunc( GL_ONE, GL_ONE );
	}
	else if( i32Type == GLARE_DARKEN ) {
		if( g_bBlendEqu )
			glBlendEquation( GL_MIN );
		glBlendFunc( GL_ONE, GL_ONE );
	}
	else if( i32Type == GLARE_DARK ) {
		if( g_bBlendEqu )
			glBlendEquation( GL_FUNC_REVERSE_SUBTRACT_EXT );
		glBlendFunc( GL_SRC_ALPHA, GL_ONE );
	}

	glBegin( GL_QUADS );

		glMultiTexCoord2fARB( GL_TEXTURE1_ARB, f32TexX0, f32TexY0 );
		glMultiTexCoord2fARB( GL_TEXTURE0_ARB, f32TexX0, f32TexY0 );
		glVertex2f( (float32)i32X, (float32)i32Y );

		glMultiTexCoord2fARB( GL_TEXTURE1_ARB, f32TexX1, f32TexY0 );
		glMultiTexCoord2fARB( GL_TEXTURE0_ARB, f32TexX1, f32TexY0 );
		glVertex2f( (float32)(i32X + m_i32TexCapturedWidth), (float32)i32Y );
		
		glMultiTexCoord2fARB( GL_TEXTURE1_ARB, f32TexX1, f32TexY1 );
		glMultiTexCoord2fARB( GL_TEXTURE0_ARB, f32TexX1, f32TexY1 );
		glVertex2f( (float32)(i32X + m_i32TexCapturedWidth), (float32)(i32Y + m_i32TexCapturedHeight) );
		
		glMultiTexCoord2fARB( GL_TEXTURE1_ARB, f32TexX0, f32TexY1 );
		glMultiTexCoord2fARB( GL_TEXTURE0_ARB, f32TexX0, f32TexY1 );
		glVertex2f( (float32)i32X, (float32)(i32Y + m_i32TexCapturedHeight) );

	glEnd();

	if( i32Type == GLARE_LIGHTEN || i32Type == GLARE_DARKEN || i32Type == GLARE_DARK ) {
		if( g_bBlendEqu )
			glBlendEquation( GL_FUNC_ADD );
	}

	glActiveTextureARB( GL_TEXTURE1_ARB );
	glDisable( GL_TEXTURE_2D );

	glActiveTextureARB( GL_TEXTURE0_ARB );

	// blend the original image to adjust amount, when doing min/max blending
	if( i32Type == GLARE_LIGHTEN || i32Type == GLARE_DARKEN ) {

		glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
		glColor4f( 1, 1, 1, 1.0f - f32Amount );

		glBindTexture( GL_TEXTURE_2D, m_ui32TexId );

		glBegin( GL_QUADS );

			glTexCoord2f( f32TexX0, f32TexY0 );
			glVertex2f( (float32)i32X, (float32)i32Y );

			glTexCoord2f( f32TexX1, f32TexY0 );
			glVertex2f( (float32)(i32X + m_i32TexCapturedWidth), (float32)i32Y );
			
			glTexCoord2f( f32TexX1, f32TexY1 );
			glVertex2f( (float32)(i32X + m_i32TexCapturedWidth), (float32)(i32Y + m_i32TexCapturedHeight) );
			
			glTexCoord2f( f32TexX0, f32TexY1 );
			glVertex2f( (float32)i32X, (float32)(i32Y + m_i32TexCapturedHeight) );

		glEnd();
	}

	glDisable( GL_TEXTURE_2D );


	// save for feedback
	m_f32LastTexX0 = f32TexX0;
	m_f32LastTexY0 = f32TexY0;
	m_f32LastTexX1 = f32TexX1;
	m_f32LastTexY1 = f32TexY1;

	m_i32LastX = i32X;
	m_i32LastY = i32Y;
	m_i32LastWidth = m_i32TexCapturedWidth;
	m_i32LastHeight = m_i32TexCapturedHeight;

	// mark that the frame is captured
	m_bValidFeedback = true;

	glEnable( GL_DEPTH_TEST );
	glDisable( GL_BLEND );

	glDepthMask( GL_TRUE );

}

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

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

bool
GlareEffectC::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 GlareEffectChunksE {
	CHUNK_Glare_BASE =			0x1000,
	CHUNK_Glare_TRANSGIZMO =		0x2000,
	CHUNK_Glare_ATTRIBGIZMO =	0x3000,
};

const uint32	Glare_VERSION = 1;

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

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

	// Transform
	pSave->begin_chunk( CHUNK_Glare_TRANSGIZMO, Glare_VERSION );
		ui32Error = m_pTraGizmo->save( pSave );
	pSave->end_chunk();

	// Attribute
	pSave->begin_chunk( CHUNK_Glare_ATTRIBGIZMO, Glare_VERSION );
		ui32Error = m_pAttGizmo->save( pSave );
	pSave->end_chunk();

	return ui32Error;
}

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

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

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

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

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

		default:
			assert( 0 );
		}

		pLoad->close_chunk();

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

	return ui32Error;
}

