//
// DX9DayLightPlugin.cpp
//
// DX9DayLight Plugin
//
// Copyright (c) 2000-2004 memon/moppi productions
//

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <d3d9.h>
#include <d3dx9math.h>

// Demopaja headers
#include "DemopajaVersion.h"
#include "PajaTypes.h"
#include "ClassDescC.h"
#include "ImportableI.h"
#include "DX9DeviceC.h"
#include "Dx9ViewportC.h"
#include "FileIO.h"
#include "AutoGizmoC.h"
#include "Vector2C.h"
#include "BBox2C.h"
#include "EffectMaskI.h"
#include "DX9MeshPlugin.h"
#include "DX9DayLightPlugin.h"

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

using namespace DX9DayLightPlugin;


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

//////////////////////////////////////////////////////////////////////////
//
//  DX9DayLight effect class descriptor.
//

DX9DayLightDescC::DX9DayLightDescC()
{
	// empty
}

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

void*
DX9DayLightDescC::create()
{
	return (void*)DX9DayLightEffectC::create_new();
}

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

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

ClassIdC
DX9DayLightDescC::get_class_id() const
{
	return CLASS_DX9DAYLIGHT_EFFECT;
};

const char*
DX9DayLightDescC::get_name() const
{
	return CLASS_DX9DAYLIGHT_EFFECT_NAME;
}

const char*
DX9DayLightDescC::get_desc() const
{
	return CLASS_DX9DAYLIGHT_EFFECT_DESC;
}

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

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

const char*
DX9DayLightDescC::get_url() const
{
	return "http://www.demopaja.org/";
}

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

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

const ClassIdC&
DX9DayLightDescC::get_required_device_driver( uint32 ui32Idx )
{
	return PajaSystem::CLASS_DX9_DEVICEDRIVER;
}


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

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


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

DX9DayLightDescC			g_rDX9DayLightDesc;

#ifndef DEMOPAJAPLAYER

//////////////////////////////////////////////////////////////////////////
//
// 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_rDX9DayLightDesc;
	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 "DX9DayLightPlugin.dll - Image Plugin (c)2000-2004 memon/moppi productions";
}

#endif



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

DX9DayLightEffectC::DX9DayLightEffectC() :
	m_pPrimaryLight( 0 ),
	m_pFill1Light( 0 ),
	m_pFill2Light( 0 )
{
	//
	// Create Attributes gizmo.
	//

	m_pAttGizmo = AutoGizmoC::create_new( this, "Attributes", ID_GIZMO_ATTRIB );

	m_pAttGizmo->add_parameter( ParamIntC::create_new( m_pAttGizmo, "Primary Light", 0, ID_ATTRIBUTE_PRIMARY_LIGHT,
		PARAM_STYLE_COMBOBOX, PARAM_ANIMATABLE, 0, 1 ) );

	m_pAttGizmo->add_parameter( ParamIntC::create_new( m_pAttGizmo, "Fill Light 1", 0, ID_ATTRIBUTE_FILL_LIGHT_1,
		PARAM_STYLE_COMBOBOX, PARAM_ANIMATABLE, 0, 1 ) );

	m_pAttGizmo->add_parameter( ParamIntC::create_new( m_pAttGizmo, "Fill Light 2", 0, ID_ATTRIBUTE_FILL_LIGHT_2,
		PARAM_STYLE_COMBOBOX, PARAM_ANIMATABLE, 0, 1 ) );

	m_pAttGizmo->add_parameter( ParamFileC::create_new( m_pAttGizmo, "Scene", NULL_SUPERCLASS, CLASS_DX9ASE_IMPORT, ID_ATTRIBUTE_FILE ) );

	//
	// Create Time gizmo.
	//
	m_pTimeGizmo = AutoGizmoC::create_new( this, "Timing", ID_GIZMO_TIME );
	
	m_pTimeGizmo->add_parameter( ParamFloatC::create_new( m_pTimeGizmo, "Frame", 0, ID_TIME_FRAME,
						PARAM_STYLE_EDITBOX, PARAM_ANIMATABLE, 0, 0, 1.0f ) );
}

DX9DayLightEffectC::DX9DayLightEffectC( EditableI* pOriginal ) :
	EffectI( pOriginal ),
	m_pAttGizmo( 0 ),
	m_pTimeGizmo( 0 ),
	m_pPrimaryLight( 0 ),
	m_pFill1Light( 0 ),
	m_pFill2Light( 0 )
{
	// Empty. The parameters are not created in the clone constructor.
}

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

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

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

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

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

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

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

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

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

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

GizmoI*
DX9DayLightEffectC::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_ATTRIB:
		return m_pAttGizmo;
	case ID_GIZMO_TIME:
		return m_pTimeGizmo;
	}

	return 0;
}

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

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

void
DX9DayLightEffectC::set_default_file( int32 i32Time, FileHandleC* pHandle )
{
	// Sets the default file.

	// Get the file parameter.
	ParamFileC*	pParam = (ParamFileC*)m_pAttGizmo->get_parameter( ID_ATTRIBUTE_FILE );

	// Begin Undo block.
	UndoC*	pOldUndo = pParam->begin_editing( get_undo() );
		// Set the file.
		pParam->set_file( i32Time, pHandle );
	// End undo block.
	pParam->end_editing( pOldUndo );
}

ParamI*
DX9DayLightEffectC::get_default_param( int32 i32Param )
{
	return 0;
}

uint32
DX9DayLightEffectC::update_notify( EditableI* pCaller )
{
	ParamI*	pParam = 0;
	GizmoI*	pGizmo = 0;
	if( pCaller->get_base_class_id() == BASECLASS_PARAMETER )
		pParam = (ParamI*)pCaller;
	if( pParam )
		pGizmo = pParam->get_parent();

	if( pParam && pGizmo && pGizmo->get_id() == ID_GIZMO_ATTRIB )
	{
		if( pParam->get_id() == ID_ATTRIBUTE_FILE )
		{
			// The file has changed. Change Time.
			ParamFileC*		pFile = (ParamFileC*)m_pAttGizmo->get_parameter_by_id( ID_ATTRIBUTE_FILE );
			ParamFloatC*	pFrame = (ParamFloatC*)m_pTimeGizmo->get_parameter_by_id( ID_TIME_FRAME );
			ParamIntC*		pPrimaryLight = (ParamIntC*)m_pAttGizmo->get_parameter_by_id( ID_ATTRIBUTE_PRIMARY_LIGHT );
			ParamIntC*		pFillLight1 = (ParamIntC*)m_pAttGizmo->get_parameter_by_id( ID_ATTRIBUTE_FILL_LIGHT_1 );
			ParamIntC*		pFillLight2 = (ParamIntC*)m_pAttGizmo->get_parameter_by_id( ID_ATTRIBUTE_FILL_LIGHT_2 );

			UndoC*		pOldUndo;
			UndoC*		pUndo = pFile->get_undo();

			FileHandleC*		pHandle = 0;
			DX9ASEImportC*	pImp = 0;

			pHandle = pFile->get_file( 0 );
			if( pHandle )
				pImp = (DX9ASEImportC*)pHandle->get_importable();

			if( pImp )
			{
				int32	i32FPS, i32TicksPerFrame, i32FirstFrame, i32LastFrame;
				pImp->get_time_parameters( i32FPS, i32TicksPerFrame, i32FirstFrame, i32LastFrame );

				// Update primary labels.
				pOldUndo = pPrimaryLight->begin_editing( pUndo );
				pPrimaryLight->clear_labels();
				pPrimaryLight->add_label( 0, "<none>" );
				for( uint32 i = 0; i < pImp->get_light_count(); i++ ) {
					LightC*	pLight = pImp->get_light( i );
					if( !pLight )
						continue;
					pPrimaryLight->add_label( i + 1, pLight->get_name() );
				}
				pPrimaryLight->set_min_max( 0, pImp->get_light_count() );
				pPrimaryLight->end_editing( pOldUndo );

				// Update fill 1 labels.
				pOldUndo = pPrimaryLight->begin_editing( pUndo );
				pFillLight1->clear_labels();
				pFillLight1->add_label( 0, "<none>" );
				for( uint32 i = 0; i < pImp->get_light_count(); i++ ) {
					LightC*	pLight = pImp->get_light( i );
					if( !pLight )
						continue;
					pFillLight1->add_label( i + 1, pLight->get_name() );
				}
				pFillLight1->set_min_max( 0, pImp->get_light_count() );
				pFillLight1->end_editing( pOldUndo );

				// Update fill 2 labels.
				pOldUndo = pPrimaryLight->begin_editing( pUndo );
				pFillLight2->clear_labels();
				pFillLight2->add_label( 0, "<none>" );
				for( uint32 i = 0; i < pImp->get_light_count(); i++ ) {
					LightC*	pLight = pImp->get_light( i );
					if( !pLight )
						continue;
					pFillLight2->add_label( i + 1, pLight->get_name() );
				}
				pFillLight2->set_min_max( 0, pImp->get_light_count() );
				pFillLight2->end_editing( pOldUndo );
			}
		}
	}

	m_pPrimaryLight = 0;
	m_pFill1Light = 0;
	m_pFill2Light = 0;

	// Relay update
	return EffectI::update_notify( pCaller );
}

void
DX9DayLightEffectC::initialize( uint32 ui32Reason, PajaSystem::DemoInterfaceC* pInterface )
{
	EffectI::initialize( ui32Reason, pInterface );
}


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

	// Requires multitexturing and bledn equation.
	DeviceContextC* pContext = m_pDemoInterface->get_device_context();
	TimeContextC* pTimeContext = m_pDemoInterface->get_time_context();


	// Calculate transformation matrix.
	m_rTM.set_identity();
	m_rBBox[0] = Vector2C( 0, 0 );
	m_rBBox[1] = Vector2C( 0, 0 );



	//
	// Calculate current frame.
	//
	DX9ASEImportC*	pImp = 0;
	FileHandleC*		pHandle;
	int32						i32FileTime;

	((ParamFileC*)m_pAttGizmo->get_parameter_by_id( ID_ATTRIBUTE_FILE ))->get_file( i32Time, pHandle, i32FileTime );

	if( pHandle )
		pImp = (DX9ASEImportC*)pHandle->get_importable();
	
	if( pImp )
	{
		// If "Frame" parameter is animated, use it instead of FPS setting.
		ParamFloatC*	pParamFrame = (ParamFloatC*)m_pTimeGizmo->get_parameter_by_id( ID_TIME_FRAME );
		ControllerC*	pCont = pParamFrame->get_controller();
		if( pCont && pCont->get_key_count() ) {
			float32	f32Frame;
			pParamFrame->get_val( i32Time, f32Frame );

			float32	f32StartFrame = pImp->get_start_label();
			float32	f32EndFrame = pImp->get_end_label();

			if( (f32EndFrame - f32StartFrame) >= 0 ) {
				i32FileTime = (int32)(((f32Frame - f32StartFrame) / (f32EndFrame - f32StartFrame)) * pImp->get_duration());
			}
		}

		pImp->eval_state( i32FileTime );
	
		// get camera
		int32	i32PrimaryLight = 0;
		int32	i32Fill1Light = 0;
		int32	i32Fill2Light = 0;
		((ParamIntC*)m_pAttGizmo->get_parameter_by_id( ID_ATTRIBUTE_PRIMARY_LIGHT ))->get_val( i32Time, i32PrimaryLight );
		((ParamIntC*)m_pAttGizmo->get_parameter_by_id( ID_ATTRIBUTE_FILL_LIGHT_1 ))->get_val( i32Time, i32Fill1Light );
		((ParamIntC*)m_pAttGizmo->get_parameter_by_id( ID_ATTRIBUTE_FILL_LIGHT_2 ))->get_val( i32Time, i32Fill2Light );

		m_pPrimaryLight = 0;
		m_pFill1Light = 0;
		m_pFill2Light = 0;

		if( i32PrimaryLight != 0 )
			m_pPrimaryLight = pImp->get_light( i32PrimaryLight - 1 );
		if( i32Fill1Light != 0 )
			m_pFill1Light = pImp->get_light( i32Fill1Light - 1 );
		if( i32Fill2Light != 0 )
			m_pFill2Light = pImp->get_light( i32Fill2Light - 1 );

		int32	i32Frame = pImp->get_current_frame();

		if( m_pPrimaryLight )
			m_pPrimaryLight->eval_state( i32Frame );
		if( m_pFill1Light )
			m_pFill1Light->eval_state( i32Frame );
		if( m_pFill2Light )
			m_pFill2Light->eval_state( i32Frame );
	}
}

LightC*
DX9DayLightEffectC::get_primary_light()
{
	return m_pPrimaryLight;
}

LightC*
DX9DayLightEffectC::get_fill_light_1()
{
	return m_pFill1Light;
}

LightC*
DX9DayLightEffectC::get_fill_light_2()
{
	return m_pFill2Light;
}

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

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

bool
DX9DayLightEffectC::hit_test( const Vector2C& rPoint )
{
	return false;
}


enum DX9DayLightEffectChunksE {
	CHUNK_IMAGE_BASE =				0x10,
	CHUNK_IMAGE_ATTRIBGIZMO =	0x30,
	CHUNK_IMAGE_TIMEGIZMO =	0x40,
};

const uint32	IMAGE_VERSION = 1;

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

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

	// Attribute
	pSave->begin_chunk( CHUNK_IMAGE_ATTRIBGIZMO, IMAGE_VERSION );
		ui32Error = m_pAttGizmo->save( pSave );
	pSave->end_chunk();

	// Time
	pSave->begin_chunk( CHUNK_IMAGE_TIMEGIZMO, IMAGE_VERSION );
		ui32Error = m_pTimeGizmo->save( pSave );
	pSave->end_chunk();

	return ui32Error;
}

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

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

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

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

		case CHUNK_IMAGE_TIMEGIZMO:
			// Attribute
			if( pLoad->get_chunk_version() == IMAGE_VERSION )
				ui32Error = m_pTimeGizmo->load( pLoad );
			break;

		default:
			assert( 0 );
		}

		pLoad->close_chunk();

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

	return ui32Error;
}
