/*****************************************************************************
 * $Id: mod_pony.cc,v 1.2 2006/11/25 17:29:54 devel Exp $
 * @file
 * @author	Jim E. Brooks  http://www.jimbrooks.org
 * @brief	Top-level of module.
 *//*
 * LEGAL:	COPYRIGHT (C) 2004 JIM E. BROOKS
 *          THIS SOURCE CODE IS RELEASED UNDER THE TERMS
 *          OF THE GNU GENERAL PUBLIC LICENSE (GPL).
 *****************************************************************************/

#define MOD_PONY_CC 1
#include "mod_pony_common.hh"
#include "mod_base_config.hh"
#include "mod_pony_config.hh"
#include "mod_pony_listeners.hh"
#include "mod_pony_gui.hh"
#include "mod_base_craft.hh"
#include "mod_base_combat.hh"
#include "mod_pony_view.hh"
#include "mod_pony_craft.hh"
#include "mod_pony_buildings.hh"
#include "mod_pony_event.hh"
#ifndef NO_PYTHON
#include "mod_pony_python_ifc.hh"
#endif
#include "gfx_random.hh"

extern Runway* gRunway;

// F-14 Tomcat has multiple 3D models for its variable wing sweep.
vector<string> gModelNameF14Vec;
static const int sOtherF14Cnt = 50;		// besides player #1/#2

////////////////////////////////////////////////////////////////////////////////
///////////////////////////////  ModulePony  ///////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

/*****************************************************************************
 * Start module.
 *****************************************************************************/
void
ModulePony::Start( void )
{
	Parent::Start();

	SelfChecks();

	gGui.Init();
	gEng.SetBackgroundRGBA( RGBA(RGB_SKYBLUE, 0.0) );
	gEng.SetFogRGBA( RGBA(0.60, 0.62, 0.67, 1.0) );
	gEng.SetFogDensity( mDefaultFogDensity ); // mDefaultFogDensity set by config
	gEng.EnableFog();
	gGui.UpdateFogDensity();
	gGui.SplashOff();
	gEng.PostRedisplay();
	gEng.SetCurrent( &gEng.mEye );
	gEng.GetCurrent()->ClaimInput();

	// Add primary view.
	gEng.mView.AddViewPrimary( new ViewModulePony( gEng.mView ) );

	// Add radar views.
	gEng.mView.AddView( new ViewRadar( gEng.mView, ViewRadar::eRadar_HORIZON ) );
	gEng.mView.AddView( new ViewRadar( gEng.mView, ViewRadar::eRadar_OVERHEAD ) );

	// Place a pair of craft in center quadrant.
	Position pos1 = gRunway->GetPosition();
	Position pos2 = pos1;
	pos1.z += gRunway->Length() * 0.5 - WORLD(300.0);
	pos2.z -= gRunway->Length() * 0.5 - WORLD(300.0);
	pos1.y  = GROUND_LEVEL + WORLD(5);
	pos2.y  = GROUND_LEVEL + WORLD(5);
	gModelNameF14Vec.push_back( mModelDir + string("f-14tomcat.pal")  );
	mPlayer1Craft = new CraftF14Tomcat( gWorld.GetCenterQuadrant(), pos1, gModelNameF14Vec );
	mPlayer2Craft = new CraftF14Tomcat( gWorld.GetCenterQuadrant(), pos2, gModelNameF14Vec );
	mPlayer2Craft->Rotate( AXIS_Y, 180.0 );	// he's at other end of runway, rotate him
	mCraftDlist.Append( GET_PTR(mPlayer1Craft) );
	mCraftDlist.Append( GET_PTR(mPlayer2Craft) );
	mPlayer1Craft->Save();	// for when Dyna::Reset() is called
	mPlayer2Craft->Save();

	mPlayer1 = mPlayer1Craft;
	mPlayer2 = mPlayer2Craft;
	mPlayer	 = mPlayer1;

	// Load Dyna objects from configuration state.
	// If not loaded, LoadDyna() is a NOP.
	mEyeConfigState.LoadDyna(     gEng.mEye );
	mPlayer1ConfigState.LoadDyna( *mPlayer1Craft );
	mPlayer2ConfigState.LoadDyna( *mPlayer2Craft );

	// Update GUI as config file may have changed state.
	gGui.Update();

#if PUBLIC_RELEASE
	//mCmdarg.mGame = true;
#endif

#if PUBLIC_RELEASE
	*gStreamOut << "Pass -game to run a demo of the experimental dogfight AI. \n";
  //*gStreamOut << "Pass -no-fsaa if aircraft look jagged. \n";
#endif

	if ( mCmdarg.mGame || mCmdarg.mDemo )
	{
		StartTurkeyShoot( sOtherF14Cnt );
	}
	else
	{
#ifndef NO_PYTHON
		// Start Python but not the module code.
		StartPython( false );
#endif
	}
}
void
ModulePony::End( void )
{
	Parent::End();
	StartStopListeners( false );
//	DELETE_NULL( mPlayer1 );		// ~Quadrant() will delete them
//	DELETE_NULL( mPlayer2 );
	mPlayer = NULL;
	CloseConfigFile();
	gGui.Delete();
}

/*****************************************************************************
 * Self-checks.  Causes program exit if any fail.
 *****************************************************************************/
void
ModulePony::SelfChecks( void )
{
	// Self-checks.
	ASSERT( TYPESIG_END < TYPESIG_MAX ); // catch if last typesig value is too big
}

/*****************************************************************************
 * Start the Python components of the module.
 *****************************************************************************/
#ifndef NO_PYTHON
bool
ModulePony::StartPython( bool startGame )
{
	// Create the Python modules which are implemented in C++.
	// The Engine/World Python modules were created prior.
	if ( ! PythonModule() )
	{
		*gStreamError << "ERROR[module]: initializing Python.\n";
		return false;
	}

	// Run the Python module mod_pony.py.
	// In order for "import mod_pony" to succeed, append its path to
	// Python's module search path (sys.path).
	string pycode;
	pycode += string("import sys\n");
	pycode += string("sys.path.append( '") + string(GetPythonDir()) + string("' )\n");
	pycode += string("import mod_pony\n");
	if ( startGame )
	{
		// Start game module (optional).
		pycode += string("module = mod_pony.ModulePony()\n");
		pycode += string("module.StartTurkeyShoot()\n");
	}
	if ( ! gPython.Run( pycode ) )
	{
		*gStreamError << "ERROR[module]: failed to import/run pony Python module. \n";
		return false;
	}

	// Ok.
	return true;
}
#endif // NO_PYTHON

/*****************************************************************************
 * Start rudimentary turkey-shoot game.
 * Implemented in C++ and Python (see mod_pony.py).
 *****************************************************************************/
void
ModulePony::StartTurkeyShoot( int craftCnt )
{
CHECK_TYPESIG( &mCraftDlist, TYPESIG_LIB_DLIST );

	// Make the "killer" Tomcat indestructible as he flies too close to his victims.
	mPlayer1Craft->EnableDetector( false );

	SetPlayer( 1 );
	gEng.SetCurrent( mPlayer1Craft );
	gEng.GetCurrent()->ClaimInput();
	gEng.mEye.SetAnimation( eAnimation_CHASE_PLANE );

#ifndef NO_PYTHON
	// Start Python and the Python module.
	StartPython( true );
#endif
}

/*****************************************************************************
 * Spawn a turket (has a Python counterpart, this C++ code is still used).
 *****************************************************************************/
void
ModulePony::SpawnTurkey( CraftPtrConst pursuer, int i, int craftCnt, bool moreRandom )
{
	// Spawn a turkey near the pursuer.
	Position posCraft = pursuer->GetPosition();
	const fp y = WORLD(2000.0);
	if ( moreRandom )
	{
		posCraft.x += WORLD(700.0) + WORLD(random_f(3000.0)+200.0);
		posCraft.y  = y + WORLD(random_f(300.0));
		posCraft.z += WORLD(700.0) + WORLD(random_f(3000.0)+200.0);
	}
	else
	{
		posCraft.x += (i - (craftCnt/2)) * WORLD(random_f(300.0)+200.0);
		posCraft.y  = y + WORLD(random_f(200.0));
		posCraft.z += WORLD(700.0) + WORLD(random_f(300.0)+200.0);
	}

	Craft* craft = new CraftF14Tomcat( gWorld.GetCenterQuadrant(), posCraft, gModelNameF14Vec );
	craft->Rotate( AXIS_Y, -10.0 );
	mCraftDlist.Append( craft );
	craft->SetAnimation( eAnimation_AUTO_TRANSLATE );
	craft->SetThrottle( 10 );

	static int turkey;
	if ( (++turkey & 7) == 7 )
	{
		craft->SetAnimation( eAnimation_PILOT_PURSUE );
		craft->mPilot->SelectTarget();
	}
}

/*****************************************************************************
 * Module animation routine.
 * Called periodically by a timer (by the engine's Animate()).
 * @return True if redisplay is necessary.
 *****************************************************************************/
int
ModulePony::Animate( void )
{
	return Parent::Animate();
}

/*****************************************************************************
 * Every timer tick.
 * Called periodically by a timer (by the engine's Tick()).
 *****************************************************************************/
void
ModulePony::Tick( void )
{
	Parent::Tick();

	// Call GuiTimerOneSecond() every second.  See gfx_gui.hh.
	static int milsecGuiCountdown = 1000;
	const int milsec = gEng.GetMilsecFrame(); // time between current/previous timer-ticks
	milsecGuiCountdown -= milsec;
	if ( milsecGuiCountdown <= 0 )
	{
		RESET_COUNTDOWN( milsecGuiCountdown, 1000 );
		gGui.TimerOneSecond();
	}

	// Spawn new targets before the "killer" Tomcat kills them all.
	// (Inefficient but currently no alt)
	if ( mCmdarg.mGame )
	{
		int aliveCnt = 0;
		for ( const Dlink<Craft>* dlink = gModule.mCraftDlist.ForStart();
	          gModule.mCraftDlist.ForTest(dlink);
	          gModule.mCraftDlist.ForNext(dlink) )
		{
			Craft* craft = dlink->mObj;
			if ( ! craft->IfDestroyed() ) ++aliveCnt;
		}
		if ( aliveCnt < 10 )
		{
			for ( int i = 0; i < 20; ++i )
			{
				SpawnTurkey( mPlayer1Craft, i, 20, true );
			}
		}
	}
}

/*****************************************************************************
 * Reset scene.
 *****************************************************************************/
void
ModulePony::ResetScene( void )
{
	if ( gModule.IfDemoMode() ) gEng.mEye.SetOrigin( Oy, gModule.DemoModeAltitude() );
}

/*****************************************************************************
 * @return Current Craft object or NULL if Eye is current!
 * This is a dangerous method!  Use Engine::GetCurrent() instead.
 * But this is necessary in a few cases to access Craft-specific methods.
 *****************************************************************************/
CraftPtrConst
ModulePony::GetCurrentCraftOrNULL( void )
{
    if ( gEng.GetCurrent() == &gEng.mEye )
    {
        return NULL;
    }
    else
    {
        // Convert DynaPtr to CraftPtr.
        CraftPtrConst craft = static_cast<Craft*>(GET_PTR(gEng.GetCurrent()));
        return craft;
    }
}
/// @return Current F-14 Tomcat or NULL.
CraftF14Tomcat*
ModulePony::GetCraftF14TomcatOrNULL( void )
{
	CraftPtrConst craft = GetCurrentCraftOrNULL();
    if ( craft != NULL && craft->GetName() == "CraftF14Tomcat" )
		return static_cast<CraftF14Tomcat*>( GET_PTR(craft) );
	else
		return NULL;
}
