//-----------------------------------------------------------------------------
// Torque Game Engine 
// Copyright (C) GarageGames.com, Inc.
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Server mission loading
//-----------------------------------------------------------------------------

// On every mission load except the first, there is a pause after
// the initial mission info is downloaded to the client.
$MissionLoadPause = 0;
$WalkableBorder = 19;

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

function onLoadDone()
{
   if ($MissionLoaded == true)
   {
      stopGameLoad();
      if ($LoadMapEarly == true)
      {
         slgAIInitMapBasedSystems($WalkableBorder);
      }
      metrics("fps");
      return;
   }
   
   schedule(100, 0, onLoadDone);
}

function loadMission(%missionName, %isFirstMission, %ignoreWaiting) 
{
   slgDisableQuitScreen();
   
   $AI_MONITORJOB = true;
   $AI_MONITORHOME = true;
   $AI_MONITORHUNGER = true;
   
   $MissionLoaded = false;
   $GameMenuLoaded = false;
   $DisableQuitScenario = false;
   $DisableReloadScenario = false;
   $LastProduceCount = 0;
   for (%index = 0; %index < 7; %index++)
   {
      $ProduceBadges[%index] = 0;
   }
   onLoadDone();
   
   TaskRunner.haltTasks(true);
   $SaveManager.clear();
   slgDestroyAISystem();
   slgAIInitPathingGrids();
   slgBuildAISystem();
   slgClearTimerFireMessages();
   slgAIInvalidateRegions();
   startMissionLoad();
   alertSvrClearDatabase();
   slgResetDisasterManager();
   
   // clear the hud objects
   BuildHud1.visible = false;
   BuildHud2.visible = false;
   BuildHud3.visible = false;
   BuildingHud.visible = false;
   CharacterHud.visible = false;
   PopUpHud.visible = false;
   PortraitHud.visible = false;
   
   // stop ambient sounds
   tsStopAmbientSound();
   tsPopAllAmbientSounds();
   
   // clear the terrain textures
   clearTerrainTextures();

   // clear all of the mission objects
   if (isObject(MissionGroup) == true)
   {
      %count = MissionGroup.getCount();
      for (%index = 0; %index < %count; %index++)
      {
         %object = MissionGroup.getObject(%index);
         RemoveObject(%object);
      }
   }
   
   // clear all of the remaining objects that need to be cleaned up
   if (isObject(MissionCleanup) == true)
   {
      %count = MissionCleanup.getCount();
      for (%index = 0; %index < %count; %index++)
      {
         %object = MissionCleanup.getObject(%index);
         RemoveObject(%object);
      }
   }
   
   ResetGrids();
   slgStartWaiting();
   $MissionWaiting = !%ignoreWaiting;
   
   endMission();
   echo("*** LOADING MISSION: " @ %missionName);
   echo("*** Stage 1 load");

   // increment the mission sequence (used for ghost sequencing)
   $missionSequence++;
   $missionRunning = false;
   $Server::MissionFile = %missionName;

   // Extract mission info from the mission file,
   // including the display name and stuff to send
   // to the client.
   buildLoadInfo( %missionName );

   // Download mission info to the clients
   %count = ClientGroup.getCount();
   for( %cl = 0; %cl < %count; %cl++ ) {
      %client = ClientGroup.getObject( %cl );
      if (!%client.isAIControlled())
         sendLoadInfoToClient(%client);
   }

   // if this isn't the first mission, allow some time for the server
   // to transmit information to the clients:
   if (%isFirstMission || $Server::ServerType $= "SinglePlayer")
   {
      loadMissionStage2();
   }
   else
   {
      // no pausing between missions
      loadMissionStage2();
      //schedule($MissionLoadPause, ServerGroup, loadMissionStage2);
   }
}

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

function loadMissionStage2() 
{
   // Create the mission group off the ServerGroup
   echo("*** Stage 2 load");
   $instantGroup = ServerGroup;

   // Make sure the mission exists
   %missionfile = $Server::MissionFile;
   %compileFile = %missionfile @ ".dso";
   %bMissionExists = slgFileExists(%missionfile);
   %bCompileExists = slgFileExists(%compileFile);
   if(!%bMissionExists && !%bCompileExists) {
      %bMissionExists = isFile(%missionfile);
      %bCompileExists = isFile(%compileFile);
      if(!%bMissionExists && !%bCompileExists) {
         error("Could not find mission " @ %missionfile);
         return;
      }
   }

   // Calculate the mission CRC.  The CRC is used by the clients
   // to caching mission lighting.
   if(%bMissionExists) {
      $missionCRC = getFileCRC(%missionfile);
   }
   else {
      $missionCRC = getFileCRC(%compileFile);
   }

   // Exec the mission, objects are added to the ServerGroup
   exec(%missionfile);
   
   // If there was a problem with the load, let's try another mission
   if( !isObject(MissionGroup) ) {
      error( "No 'MissionGroup' found in mission \"" @ $missionName @ "\"." );
      schedule( 3000, ServerGroup, CycleMissions );
      return;
   }

   // Mission cleanup group
   new SimGroup( MissionCleanup );
   $instantGroup = MissionCleanup;
   
   // set up the resources
   if ($CreateResources == true)
   {
     CreateResources();
     $CreateResources = false;
   }
   
   // Construct MOD paths
   pathOnMissionLoadDone();

   // Mission loading done...
   echo("*** Mission loaded");
   
   // Start all the clients in the mission
   $missionRunning = true;
   for( %clientIndex = 0; %clientIndex < ClientGroup.getCount(); %clientIndex++ )
      ClientGroup.getObject(%clientIndex).loadMission();

   // Go ahead and launch the game
   onMissionLoaded();
   purgeResources();
}


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

function endMission()
{
   UnloadPortraitCameras();
   
   if (!isObject( MissionGroup ))
      return;

   echo("*** ENDING MISSION");
   
   // Inform the game code we're done.
   onMissionEnded();

   // Inform the clients
   for( %clientIndex = 0; %clientIndex < ClientGroup.getCount(); %clientIndex++ ) {
      // clear ghosts and paths from all clients
      %cl = ClientGroup.getObject( %clientIndex );
      %cl.endMission();
      %cl.resetGhosting();
      %cl.clearPaths();
   }

   // delete the mission objects
   MissionGroup.delete();
   MissionCleanup.delete();

   $ServerGroup.delete();
   $ServerGroup = new SimGroup(ServerGroup);
}


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

function resetMission()
{
   echo("*** MISSION RESET");

   // Remove any temporary mission objects
   MissionCleanup.delete();
   $instantGroup = ServerGroup;
   new SimGroup( MissionCleanup );
   $instantGroup = MissionCleanup;

   //
   onMissionReset();
}
