// RWWrapper.cpp : implementation file
//

#include "stdafx.h"

// renderware stuff

#include "rwcore.h"		// renderware core
#include "rt2d.h"
#include "rtcharse.h"
#include "rtpng.h"		// PNG tool
#include "rpworld.h"	// renderware world plugin
#include "rplodatm.h"
#include "rpmorph.h"	// renderware morph plugin
#include "rpskin.h"		// renderware skin plugin
#include "rphanim.h"
#include "rpmatfx.h"
#include "rpspline.h"

#include "PGLWad.h"
#include "RWWrapper.h"
#include "tga.h"		// targa image loader

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// RWWrapper

IMPLEMENT_DYNCREATE(RWWrapper, CObject)

RWWrapper::RWWrapper()
{
}

RWWrapper::~RWWrapper()
{
}

// --------------------------------
// initialize the renderware engine
// --------------------------------

bool RWWrapper::initialize()
{

	// initialize engine

    RwEngineOpenParams openParams;

    RwEngineInit(NULL, 0);

	// attach plug-ins

    if (!RpWorldPluginAttach())
    {
        return false;
    }

	if (!RpHAnimPluginAttach())
	{
		return false;
	}

	if (!RpSkinPluginAttach())
	{
		return false;
	}

	if (!RpMorphPluginAttach())
	{
		return false;
	}

	if (!RpSplinePluginAttach())
	{
		return false;
	}

	openParams.displayID = NULL;

    if (!RwEngineOpen(&openParams))
    {
        RwEngineTerm();
        return false;
    }

    RwEngineSetSubSystem(0);

    if (!RwEngineStart())
    {
        RwEngineClose();
        RwEngineTerm();
    
        return false;
    }

    // register inmage format

    if (!RwImageRegisterImageFormat((const char*)(RWSTRING("bmp")), RwImageReadBMP, (RwImageCallBackWrite)NULL))
    {
		return false;
    
    }

    if (!RwImageRegisterImageFormat((const char*)(RWSTRING("tga")), ImageReadTGA, (RwImageCallBackWrite)NULL))
    {
		return false;
	}

    if (!RwImageRegisterImageFormat((const char*)(RWSTRING("png")), RwImageReadPNG, (RwImageCallBackWrite)NULL))
    {
		return false;
    }

	// engine started Ok

    return true;

}

bool RWWrapper::close()
{
	// shut down renderware	
	
    RwEngineStop();
    RwEngineClose();
    RwEngineTerm();

	return true;

}

bool RWWrapper::DetermineTXDname(KGString & imagePath)
{
	WIN32_FIND_DATA fd;

	HANDLE hFind = ::FindFirstFile((imagePath.getAsChar()),&fd);

	if (hFind != INVALID_HANDLE_VALUE)
	{	
		do
		{
			if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			{
				KGString name = fd.cFileName;

				if (name != "." && name != "..")
				{

					imagePath = name;

					break;
				
				}
			}
			
		} while (::FindNextFile(hFind,&fd));
	}

	::FindClose(hFind);



	return true;
}

bool RWWrapper::addDirectoryToDictionary(KGString & imagePath)
{
	RwTexture * texture = NULL;
	
 	KSizedString<255> foundFile;
	KGString textPNGs = ".png";
	KGString textPNGc = ".PNG";

	KGString textBMPs = ".bmp";
	KGString textBMPc = ".BMP";

	KGString textTGAs = ".tga";
	KGString textTGAc = ".TGA";

	WIN32_FIND_DATA fd;

	HANDLE hFind = ::FindFirstFile((imagePath.getAsChar()),&fd);

	if (hFind != INVALID_HANDLE_VALUE)
	{	
		do
		{
			foundFile = fd.cFileName;

			int posPeriod;

			// PNGs

			posPeriod = foundFile.hasSubString(textPNGs);

			if (posPeriod == -1)
			{
				posPeriod = foundFile.hasSubString(textPNGc);
			}

			// Targas

			if (posPeriod == -1)
			{
				posPeriod = foundFile.hasSubString(textTGAs);
			}
			if (posPeriod == -1)
			{
				posPeriod = foundFile.hasSubString(textTGAc);
			}

			// BMPs

			if (posPeriod == -1)
			{
				posPeriod = foundFile.hasSubString(textBMPs);
			}
			if (posPeriod == -1)
			{
				posPeriod = foundFile.hasSubString(textBMPc);
			}

			//

			if (posPeriod != -1)
			{
				
				
				texture = RwTextureRead(foundFile.getAsChar(),NULL);				   

				if( texture != NULL)
				{
					foundFile.setCharAt( posPeriod, 0 );
					RwTextureSetName(texture, foundFile.getAsChar());
					RwTexDictionaryAddTexture(m_TextureDictionary, texture);
				}
			}

		} while (::FindNextFile(hFind,&fd));
	}

	::FindClose(hFind);

	return true;
}

// create texture dictionary

bool RWWrapper::createTextureDictionary(KString & level)
{
 	KSizedString<255> imagePath;
 	KGString imagePathG = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

	// create dictionary

	RwTexDictionary * defaultTextDict;
	defaultTextDict = RwTexDictionaryGetCurrent(); 
	RwBool deletedDict = RwTexDictionaryDestroy(defaultTextDict); 
	defaultTextDict = RwTexDictionaryGetCurrent(); 

	m_TextureDictionary = RwTexDictionaryCreate();

	RwTexDictionary * createdTextDict;
	createdTextDict = RwTexDictionarySetCurrent(m_TextureDictionary);


	// do directory

	// load and add textures to dictionary
	// enumerate through files in directory

	imagePath = "*.*";
	imagePathG = "*.*";

	DetermineTXDname(imagePathG);
	KGString dictName = imagePathG;
	imagePath = imagePathG;
	imagePath += "/";
	
	imagePathG += "\\*.*";
	
	RwImageSetPath(imagePath.getAsChar());

	addDirectoryToDictionary(imagePathG);

	// save off dictionary

	// there is a problem with just loading textures and adding them
	// to the dictionary.  When a dff is loaded and processed it's does
	// some addational processing to the texture if it needs an alpha mask,
	// needs to be resized for various reasons, etc.

	saveTextureDictionary(dictName);

	return true;
}

// create texture dictionary from dff

bool RWWrapper::createTextureDictionaryFromDff(KString & level)
{
 	KSizedString<255> imagePath;
 	KGString imagePathG = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

    RwStream *stream;
    RpClump *clump = (RpClump *)NULL;

	char * path = "sully.dff";

	// create dictionary

//	RwTexDictionary * defaultTextDict;
//	defaultTextDict = RwTexDictionaryGetCurrent(); 
//	RwBool deletedDict = RwTexDictionaryDestroy(defaultTextDict); 
//	defaultTextDict = RwTexDictionaryGetCurrent(); 
//
//	m_TextureDictionary = RwTexDictionaryCreate();
//
//	RwTexDictionary * createdTextDict;
//	createdTextDict = RwTexDictionarySetCurrent(m_TextureDictionary);

	// load and add textures to dictionary
	// enumerate through files in directory

	imagePath = "*.*";
	imagePathG = "*.*";

	DetermineTXDname(imagePathG);
	KGString dictName = imagePathG;

    /*
     * Open a stream connected to the disk file...
     */
    stream = RwStreamOpen(rwSTREAMFILENAME, rwSTREAMREAD, path);
    if( stream )
    {
        /*
         * Find a clump chunk in the stream...
         */
        if( !RwStreamFindChunk(stream, rwID_CLUMP, 
                               (RwUInt32 *)NULL, (RwUInt32 *)NULL) )
        {
            RwStreamClose(stream, NULL);
            return (RpClump *)NULL;
        }

        /*
         * Read the clump chunk...
         */
        clump = RpClumpStreamRead(stream);

        RwStreamClose(stream, NULL);
    }

	saveTextureDictionary(dictName);

    return true;
}

bool RWWrapper::saveTextureDictionary(KString& level)
{
 	KSizedString<255> path;

 	path  = level;
 	path += "_ps2.txd";

    //
	
	RwStream * DictStream = NULL;

    DictStream = RwStreamOpen(rwSTREAMFILENAME, rwSTREAMWRITE, path.getAsChar());

	if (DictStream)
	{
		RwTexDictionaryStreamWrite(RwTexDictionaryGetCurrent(), DictStream);
		RwStreamClose(DictStream, NULL);
	}

	return true;
}

// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------

//BEGIN_MESSAGE_MAP(RWWrapper, CCmdTarget)
	//{{AFX_MSG_MAP(RWWrapper)
		// NOTE - the ClassWizard will add and remove mapping macros here.
	//}}AFX_MSG_MAP
//END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// RWWrapper message handlers
