// ImageGrinder.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "ImageGrinder.h"

#include "MainFrm.h"
#include "ChildFrm.h"
#include "ImageGrinderDoc.h"
#include "ImageGrinderView.h"
#include "ImageCache.h"
#include "TextureLibFrame.h"

#include <Compost\TexturePool.hpp>
#include <DLLPlatform\DLLPlatform.hpp>
#include <Process.h>

unsigned int TNTThreadID=0;
HANDLE HandleTNTThread;
CRITICAL_SECTION TNTCriticalSection;
HANDLE KillTNTEvent;

unsigned int __stdcall TNTThread(void *dat);

/////////////////////////////////////////////////////////////////////////////
// CImageGrinderApp

BEGIN_MESSAGE_MAP(CImageGrinderApp, CWinApp)
	//{{AFX_MSG_MAP(CImageGrinderApp)
	ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
	//}}AFX_MSG_MAP
	// Standard file based document commands
	ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
	ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CImageGrinderApp construction

CImageGrinderApp::CImageGrinderApp()
{
	// TODO: add construction code here,
	// Place all significant initialization in InitInstance
}

/////////////////////////////////////////////////////////////////////////////
// The one and only CImageGrinderApp object

CImageGrinderApp theApp;

/////////////////////////////////////////////////////////////////////////////
// CImageGrinderApp initialization

BOOL CImageGrinderApp::InitInstance()
{
	AfxEnableControlContainer();

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	//  of your final executable, you should remove from the following
	//  the specific initialization routines you do not need.

#ifdef _AFXDLL
	Enable3dControls();			// Call this when using MFC in a shared DLL
#else
	Enable3dControlsStatic();	// Call this when linking to MFC statically
#endif

	// Change the registry key under which our settings are stored.
	// TODO: You should modify this string to be something appropriate
	// such as the name of your company or organization.
	SetRegistryKey(_T("Microsoft\\ArtTools"));

	LoadStdProfileSettings();  // Load standard INI file options (including MRU)

	// Register the application's document templates.  Document templates
	//  serve as the connection between documents, frame windows and views.

	CMultiDocTemplate* pDocTemplate;
	pDocTemplate = new CMultiDocTemplate(
		IDR_IMAGEGTYPE,
		RUNTIME_CLASS(CImageGrinderDoc),
		RUNTIME_CLASS(CChildFrame), // custom MDI child frame
		RUNTIME_CLASS(CImageGrinderView));
	AddDocTemplate(pDocTemplate);


	InitGameOS(NULL, NULL, "StartGOS");
	Stuff::InitializeClasses();
Stuff::ArmorLevel=1;
	CImageCache::InitInstance();
#if defined(USE_TIME_ANALYSIS) && defined(TRACE_ENABLED)
	long TraceLogSize = 1000000;
	Stuff::TraceManager::Instance->CreateTraceLog(TraceLogSize, true);
#endif

	Compost::TexturePool::Instance = new Compost::TexturePool;
	Register_Pointer(Compost::TexturePool::Instance);

char  tdir[MAX_PATH];

	// create main MDI Frame window
	CMainFrame* pMainFrame = new CMainFrame;
	if (!pMainFrame->LoadFrame(IDR_MAINFRAME))
		return FALSE;
	m_pMainWnd = pMainFrame;

	// The main window has been initialized, so show and update it.
	pMainFrame->ShowWindow(m_nCmdShow);
	pMainFrame->UpdateWindow();
	pMainFrame->Init();

GetCurrentDirectory(MAX_PATH,tdir);
OrgDir=tdir;
	OrgDir+="\\";

	CString sloc(OrgDir);
	
	sloc+="ImageGrinder.ICH";
//	CImageCache::Instance->LoadCache(sloc);
#if 1 // jcem
	InitializeCriticalSection( &TNTCriticalSection );
	KillTNTEvent=CreateEvent( NULL, false, false, NULL );
	HandleTNTThread=(HANDLE)_beginthreadex( 0, 1024, TNTThread, (void* )pMainFrame, 0, &TNTThreadID );
#else // original
	_beginthread(TNTThread,1024,(void* )pMainFrame);
#endif

	// Parse command line for standard shell commands, DDE, file open
	CCommandLineInfo cmdInfo;
	ParseCommandLine(cmdInfo);

	// Dispatch commands specified on the command line
	if(cmdInfo.m_nShellCommand!=CCommandLineInfo::FileNew)
		if (!ProcessShellCommand(cmdInfo))
			return FALSE;



	// CG: The following block was inserted by the 'Document Registration' component.
	{
		// Enable DDE Execute open
		EnableShellOpen();
		RegisterShellFileTypes(TRUE);

		m_pMainWnd->DragAcceptFiles();
	}
  return TRUE;
}


/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
		// No message handlers
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

// App command to run the dialog
void CImageGrinderApp::OnAppAbout()
{
	CAboutDlg aboutDlg;
	aboutDlg.DoModal();
}

/////////////////////////////////////////////////////////////////////////////
// CImageGrinderApp message handlers


int CImageGrinderApp::ExitInstance() 
{
	Unregister_Pointer(Compost::TexturePool::Instance);
	delete Compost::TexturePool::Instance;

	// TODO: Add your specialized code here and/or call the base class
/*
	CString sloc=GetProfileString("Settings","TexturePath","c:");
	sloc+="\\";
*/
	CString sloc(OrgDir);
	sloc+="ImageGrinder.ICH";
//	CImageCache::Instance->SaveCache(sloc);
	Stuff::TerminateClasses();
	ExitGameOS();

	return CWinApp::ExitInstance();
}

void InitializeGameEngine()
{
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void DoGameLogic()
{
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void UpdateDisplay()
{
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void TerminateGameEngine()
{
	//
	//-------------------
	// Turn off libraries
	//-------------------
	//
}

void
	DumpScene(const char* name)
{
}

//
// Setup the GameOS structure
//
void __stdcall GetGameOSEnvironment( char* CommandLine )
{
	CommandLine=CommandLine;
	Environment.applicationName			= "TCT";
	Environment.screenWidth				= 640;
	Environment.screenHeight			= 480;
	Environment.fullScreen				= FALSE;
	Environment.bitDepth				= 16;
	Environment.debugLog				= "";			//"DebugLog.txt";
	Environment.spew					= "";			//"GameOS*";

	Environment.UpdateRenderers			= NULL;
	Environment.DoGameLogic				= NULL;
	Environment.InitializeGameEngine	= NULL;
	Environment.TerminateGameEngine		= NULL;

	Environment.Renderer				= 0;
	Environment.FullScreenDevice		= 0;
	
	Environment.AntiAlias				= 0;			// true/false - Enable full screen antialiasing
	
	//
	// Texture infomation
	//
	Environment.Texture_S_256			= 13;
	Environment.Texture_S_128			= 12;
	Environment.Texture_S_64			= 1;
	Environment.Texture_S_32			= 1;
	Environment.Texture_S_16			= 1;
	
	Environment.Texture_K_256			= 1;
	Environment.Texture_K_128			= 1;
	Environment.Texture_K_64			= 1;
	Environment.Texture_K_32			= 1;
	Environment.Texture_K_16			= 1;
	
	Environment.Texture_A_256			= 1;
	Environment.Texture_A_128			= 1;
	Environment.Texture_A_64			= 1;
	Environment.Texture_A_32			= 1;
	Environment.Texture_A_16			= 1;
}


BOOL CImageGrinderApp::OnIdle(LONG lCount) 
{
/*
	BOOL ret,ret2;
	CMainFrame* pMainFrame = (CMainFrame*)m_pMainWnd;
	ret=false;
	if(pMainFrame)
		ret=pMainFrame->OnIdle();
	ret2=CWinApp::OnIdle(lCount);
	return ret || ret2;
*/
	return CWinApp::OnIdle(lCount);
}

unsigned int __stdcall TNTThread(void *dat)
{
CMainFrame* pMainFrame = (CMainFrame*)dat;

	HANDLE	EventHandles[2];
	EventHandles[0]=KillTNTEvent;
	//EventHandles[1]=TNTEvent;

    while( WaitForMultipleObjects( 1, EventHandles, FALSE, 10) == WAIT_TIMEOUT )
		// WAIT_OBJECT_0+1		// Kill event will always be checked first
	{
		//EnterCriticalSection( &TNTCriticalSection );

		if (!pMainFrame->OnIdle())
			break;

		//LeaveCriticalSection( &TNTCriticalSection );
	}

	_endthreadex(0);

	return 0;
}

void DestroyTNTThread()
{
	if( HandleTNTThread )
	{
        SetEvent( KillTNTEvent );
        WaitForSingleObject( HandleTNTThread, INFINITE );
		CloseHandle( HandleTNTThread );
		DeleteCriticalSection( &TNTCriticalSection );
		CloseHandle( KillTNTEvent );
		HandleTNTThread=0;
	}
}
