Index: code/branches/PresentationFS18/src/libraries/network/GamestateManager.cc
===================================================================
--- code/branches/PresentationFS18/src/libraries/network/GamestateManager.cc	(revision 12012)
+++ code/branches/PresentationFS18/src/libraries/network/GamestateManager.cc	(revision 12020)
@@ -43,5 +43,4 @@
 #include <cassert>
 #include <queue>
-// #include <boost/thread/mutex.hpp>
 
 #include "packet/Acknowledgement.h"
@@ -55,5 +54,4 @@
 #include "util/Clock.h"
 #include "util/OrxAssert.h"
-// #include "TrafficControl.h"
 
 namespace orxonox
@@ -62,28 +60,31 @@
   currentGamestate_(nullptr), id_(0)
   {
-//     trafficControl_ = new TrafficControl();
-//     threadMutex_ = new boost::mutex();
-//     threadPool_ = new ThreadPool();
   }
 
   GamestateManager::~GamestateManager()
   {
-    if( this->currentGamestate_ )
-        delete this->currentGamestate_;
-    for( const auto& mapEntry : gamestateQueue )
-      delete mapEntry.second;
-    for( const auto& mapEntryPeer : peerMap_ )
-    {
-      for( const auto& mapEntryGamestate : mapEntryPeer.second.gamestates )
-        delete mapEntryGamestate.second;
-    }
-//     this->trafficControl_->destroy();
-//     delete this->threadMutex_;
-//     delete this->threadPool_;
-  }
-
-  bool GamestateManager::update(){
-//     cleanup();
-    return getSnapshot();
+    if(this->currentGamestate_)
+    {
+      delete this->currentGamestate_;
+      this->currentGamestate_ = nullptr;
+    }
+
+    for(const auto& gsPair : this->gamestateQueue)
+    {
+      delete gsPair.second;
+    }
+
+    for(const auto& peerPair : this->peerMap_)
+    {
+      for(const auto& gsPair : peerPair.second.gamestates)
+      {
+        delete gsPair.second;
+      }
+    }
+  }
+
+  bool GamestateManager::update()
+  {
+    return this->getSnapshot();
   }
 
@@ -91,37 +92,54 @@
   {
     assert(gs);
-    std::map<unsigned int, packet::Gamestate*>::iterator it = gamestateQueue.find(clientID);
-    if(it!=gamestateQueue.end())
+    // Search the queue for a gamestate for the client
+    std::map<unsigned int, packet::Gamestate*>::iterator it = this->gamestateQueue.find(clientID);
+    if(it != this->gamestateQueue.end())
     {
       // delete obsolete gamestate
       delete it->second;
     }
-    gamestateQueue[clientID] = gs;
+    // update the client's gamestate
+    this->gamestateQueue[clientID] = gs;
+
     return true;
   }
 
+  /**
+   * Process the queued gamestates.
+   */
   bool GamestateManager::processGamestates()
   {
-    if( this->gamestateQueue.empty() )
+    // Queue is empty, nothing to do
+    if(this->gamestateQueue.empty())
+    {
         return true;
+    }
+
     // now push only the most recent gamestates we received (ignore obsolete ones)
-    for(const auto& mapEntry : gamestateQueue)
-    {
-      OrxVerify(processGamestate(mapEntry.second), "ERROR: could not process Gamestate");
-      sendAck( mapEntry.second->getID(), mapEntry.second->getPeerID() );
-      delete mapEntry.second;
+    for(const auto& gsPair : this->gamestateQueue)
+    {
+      OrxVerify(this->processGamestate(gsPair.second), "ERROR: could not process Gamestate");
+      this->sendAck(gsPair.second->getID(), gsPair.second->getPeerID());
+      delete gsPair.second;
     }
     // now clear the queue
-    gamestateQueue.clear();
+    this->gamestateQueue.clear();
+
     //and call all queued callbacks
     NetworkCallbackManager::callCallbacks();
+
     return true;
   }
   
+  /**
+   * Send Acknowledgement packet.
+   * @param gamestateId The gamestate ID we want to acknowledge
+   * @param peerID The ID of the peer we want to send the Acknowledgement to
+   */
   bool GamestateManager::sendAck(unsigned int gamestateID, uint32_t peerID)
   {
-    assert( gamestateID != ACKID_NACK );
+    assert(gamestateID != ACKID_NACK);
     packet::Acknowledgement *ack = new packet::Acknowledgement(gamestateID, peerID);
-    if( !this->sendPacket(ack))
+    if(!this->sendPacket(ack))
     {
       orxout(internal_warning, context::network) << "could not ack gamestate: " << gamestateID << endl;
@@ -135,21 +153,36 @@
   }
 
-
-  bool GamestateManager::getSnapshot(){
-    if ( currentGamestate_ != nullptr )
-      delete currentGamestate_;
+  /**
+   * Update the current gamestate.
+   */
+  bool GamestateManager::getSnapshot()
+  {
+    // Delete current gamestate
+    if (this->currentGamestate_)
+    {
+      delete this->currentGamestate_;
+      this->currentGamestate_ = nullptr;
+    }
+
     uint8_t gsMode;
-    if( GameMode::isMaster() )
+    if(GameMode::isMaster())
+    {
       gsMode = packet::GAMESTATE_MODE_SERVER;
-    else
+    }
+    else
+    {
       gsMode = packet::GAMESTATE_MODE_CLIENT;
+    }
+
     uint32_t newID;
-    if( GameMode::isMaster() )
-      newID = ++id_;
-    else
-    {
-      assert(peerMap_.size()!=0);
-      newID = peerMap_[NETWORK_PEER_ID_SERVER].lastReceivedGamestateID;
-      if( newID == GAMESTATEID_INITIAL )
+    if(GameMode::isMaster())
+    {
+      newID = ++this->id_;
+    }
+    else
+    {
+      assert(this->peerMap_.size() != 0);
+      newID = this->peerMap_[NETWORK_PEER_ID_SERVER].lastReceivedGamestateID;
+      if(newID == GAMESTATEID_INITIAL)
       {
         return false;
@@ -157,24 +190,31 @@
     }
     
-    currentGamestate_ = new packet::Gamestate();
-    
-    if(!currentGamestate_->collectData(newID, gsMode))
-    { //we have no data to send
-      delete currentGamestate_;
-      currentGamestate_=nullptr;
+    // Create a new gamestate
+    this->currentGamestate_ = new packet::Gamestate();
+    if(!this->currentGamestate_->collectData(newID, gsMode))
+    {
+      // we have no data to send
+      delete this->currentGamestate_;
+      this->currentGamestate_ = nullptr;
       return false;
     }
+
     return true;
   }
 
+  /**
+   * Return a vector with the gamestates of all peers.
+   */
   std::vector<packet::Gamestate*> GamestateManager::getGamestates()
   {
-    if(!currentGamestate_)
+    // Current gamestate is empty
+    if(!this->currentGamestate_){
       return std::vector<packet::Gamestate*>();
+    }
+
     std::vector<packet::Gamestate*> peerGamestates;
-    
-    for( const auto& mapEntry : peerMap_ )
-    {
-      if( !mapEntry.second.isSynched )
+    for(const auto& mapEntry : this->peerMap_)
+    {
+      if(!mapEntry.second.isSynched)
       {
         orxout(verbose_more, context::network) << "Server: not sending gamestate" << endl;
@@ -198,16 +238,10 @@
       peerGamestates.push_back(nullptr);  // insert an empty gamestate* to be changed
       finishGamestate( peerID, peerGamestates.back(), baseGamestate, currentGamestate_ );
-      if( peerGamestates.back()==nullptr )
+      if(peerGamestates.back() == nullptr)
+      {
         // nothing to send to remove pointer from vector
         peerGamestates.pop_back();
-      //FunctorMember<GamestateManager>* functor =
-//       ExecutorMember<GamestateManager>* executor = createExecutor( createFunctor(&GamestateManager::finishGamestate, this) );
-//       executor->setDefaultValues( cid, &clientGamestates.back(), client, currentGamestate_ );
-//       (*static_cast<Executor*>(executor))();
-//       this->threadPool_->passFunction( executor, true );
-//       (*functor)( cid, &(clientGamestates.back()), client, currentGamestate_ );
-    }
-
-//     threadPool_->synchronise();
+      }
+    }
 
     return peerGamestates;
@@ -215,19 +249,14 @@
 
 
-  void GamestateManager::finishGamestate( unsigned int peerID, packet::Gamestate*& destgamestate, packet::Gamestate* base, packet::Gamestate* gamestate ) {
-    //why are we searching the same client's gamestate id as we searched in
-    //Server::sendGameState?
+  void GamestateManager::finishGamestate(unsigned int peerID, packet::Gamestate*& destgamestate, packet::Gamestate* base, packet::Gamestate* gamestate)
+  {
     // save the (undiffed) gamestate in the clients gamestate map
-    //chose wheather the next gamestate is the first or not
-
-//     packet::Gamestate *gs = gamestate->doSelection(clientID, 20000);
-//       packet::Gamestate* gs = new packet::Gamestate(*gamestate);
-//     packet::Gamestate* gs = gamestate;
+    // choose whether the next gamestate is the first or not
+
+    // Create a copy of the gamestate
     packet::Gamestate *gs = new packet::Gamestate(*gamestate); //this is neccessary because the gamestate are being kept (to diff them later on) for each client seperately
-//     packet::Gamestate *gs = new packet::Gamestate();
-//     gs->collectData( id_, 0x1 );
-//     this->threadMutex_->lock();
-    peerMap_[peerID].gamestates[gamestate->getID()]=gs;
-//     this->threadMutex_->unlock();
+    this->peerMap_[peerID].gamestates[gamestate->getID()] = gs;
+
+    // Start the clock
     Clock clock;
     clock.capture();
@@ -236,5 +265,5 @@
     {
       packet::Gamestate *diffed1 = gs->diffVariables(base);
-      if( diffed1->getDataSize() == 0 )
+      if(diffed1->getDataSize() == 0)
       {
         delete diffed1;
@@ -249,13 +278,9 @@
     }
 
-
-//     OrxVerify(gs->compressData(), "");
+    // Stop the clock
     clock.capture();
     orxout(verbose_more, context::network) << "diff and compress time: " << clock.getDeltaTime() << endl;
-//     orxout(verbose_more, context::network) << "sending gamestate with id " << gs->getID();
-//     if(gamestate->isDiffed())
-//       orxout(verbose_more, context::network) << " and baseid " << gs->getBaseID() << endl;
-//     else
-//       orxout(verbose_more, context::network) << endl;
+
+
     gs->setPeerID(peerID);
     destgamestate = gs;
@@ -263,33 +288,30 @@
 
 
+  /**
+   * Acknowledge a received gamestate.
+   * @param gamestateID The ID of the gamestate to be acknowledged
+   * @param peerID The ID of the peer to send the Acknowledgement to
+   */
   bool GamestateManager::ackGamestate(unsigned int gamestateID, unsigned int peerID)
   {
-//     ClientInformation *temp = ClientInformation::findClient(peerID);
-//     assert(temp);
+    // Search for the peer in the peer map
     std::map<uint32_t, peerInfo>::iterator it = this->peerMap_.find(peerID);
-    assert(it!=this->peerMap_.end());
+    assert(it != this->peerMap_.end());
+
     unsigned int curid = it->second.lastAckedGamestateID;
 
     assert(gamestateID != ACKID_NACK);
-//     if(gamestateID == ACKID_NACK){
-//       it->second.lastAckedGamestateID = GAMESTATEID_INITIAL;
-// //       temp->setGamestateID(GAMESTATEID_INITIAL);
-//       // now delete all saved gamestates for this client
-//       std::map<uint32_t, packet::Gamestate*>::iterator it2;
-//       for(it2 = it->second.gamestates.begin(); it2!=it->second.gamestates.end(); ++it2 ){
-//         delete it2->second;
-//       }
-//       it->second.gamestates.clear();
-//       return true;
-//     }
-
-//    assert(curid==GAMESTATEID_INITIAL || curid<=gamestateID); // this line is commented out because acknowledgements are unreliable and may arrive in distorted order
-    if( gamestateID <= curid && curid != GAMESTATEID_INITIAL )
+
+    // The gamestate has already been acknowledged, nothing to do
+    if(gamestateID <= curid && curid != GAMESTATEID_INITIAL)
+    {
         return true;
-orxout(verbose, context::network) << "acking gamestate " << gamestateID << " for peerID: " << peerID << " curid: " << curid << endl;
+    }
+
+    orxout(verbose, context::network) << "acking gamestate " << gamestateID << " for peerID: " << peerID << " curid: " << curid << endl;
     std::map<uint32_t, packet::Gamestate*>::iterator it2;
-    for( it2=it->second.gamestates.begin(); it2!=it->second.gamestates.end(); )
-    {
-      if( it2->second->getID() < gamestateID )
+    for (it2 = it->second.gamestates.begin(); it2 != it->second.gamestates.end();)
+    {
+      if(it2->second->getID() < gamestateID)
       {
         delete it2->second;
@@ -297,64 +319,77 @@
       }
       else
+      {
         ++it2;
+      }
     }
     
-//     std::map<unsigned int, packet::Gamestate*>::iterator it;
-//     for(it = gamestateMap_[peerID].begin(); it!=gamestateMap_[peerID].end() && it->first<gamestateID; ){
-//       delete it->second;
-//       gamestateMap_[peerID].erase(it++);
-//     }
+    // update the last acked gamestate
     it->second.lastAckedGamestateID = gamestateID;
-//     temp->setGamestateID(gamestateID);
-//     TrafficControl::processAck(peerID, gamestateID);
+
     return true;
   }
   
+  /**
+   * Return the ID of the last received gamestate for a certain peer
+   * @param peerID The ID of the peer\
+   */
   uint32_t GamestateManager::getLastReceivedGamestateID(unsigned int peerID)
   {
-    assert( this->peerMap_.find(peerID)!=this->peerMap_.end() );
-    if( this->peerMap_.find(peerID) != this->peerMap_.end() )
+    if(this->peerMap_.find(peerID) != this->peerMap_.end())
+    {
       return this->peerMap_[peerID].lastReceivedGamestateID;
-    else
+    }
+    else
+    {
       return GAMESTATEID_INITIAL;
+    }
   }
   
-  
+  /**
+   * Add a peer to the game.
+   * @param peerID The ID of the peer to add.
+   */
   void GamestateManager::addPeer(uint32_t peerID)
   {
-    assert(peerMap_.find(peerID)==peerMap_.end());
-    peerMap_[peerID].peerID = peerID;
-    peerMap_[peerID].lastReceivedGamestateID = GAMESTATEID_INITIAL;
-    peerMap_[peerID].lastAckedGamestateID = GAMESTATEID_INITIAL;
-    if( GameMode::isMaster() )
-      peerMap_[peerID].isSynched = false;
-    else
-      peerMap_[peerID].isSynched = true;
-  }
-
+    // Ensure that the peer doesn't already exist.
+    assert(this->peerMap_.find(peerID) == this->peerMap_.end());
+
+    // Create the peerInfo struct for the peer
+    this->peerMap_[peerID].peerID = peerID;
+    this->peerMap_[peerID].lastReceivedGamestateID = GAMESTATEID_INITIAL;
+    this->peerMap_[peerID].lastAckedGamestateID = GAMESTATEID_INITIAL;
+    if(GameMode::isMaster())
+    {
+      this->peerMap_[peerID].isSynched = false;
+    }
+    else
+    {
+      this->peerMap_[peerID].isSynched = true;
+    }
+  }
+
+  /**
+   * Remove a peer from the game.
+   * @param peerID The ID of the peer to be removed
+   */
   void GamestateManager::removePeer(uint32_t peerID)
   {
-    assert(peerMap_.find(peerID)!=peerMap_.end());
-    for( const auto& mapEntry : peerMap_[peerID].gamestates )
+    // Make sure that the peer exists
+    assert(this->peerMap_.find(peerID) != this->peerMap_.end());
+
+    for (const auto& mapEntry : this->peerMap_[peerID].gamestates)
     {
       delete mapEntry.second;
     }
-    peerMap_.erase(peerMap_.find(peerID));
-  }
-
-
-//   void GamestateManager::removeClient(ClientInformation* client){
-//     assert(client);
-//     std::map<unsigned int, std::map<unsigned int, packet::Gamestate*>>::iterator clientMap = gamestateMap_.find(client->getID());
-//     // first delete all remained gamestates
-//     std::map<unsigned int, packet::Gamestate*>::iterator it;
-//     for(it=clientMap->second.begin(); it!=clientMap->second.end(); it++)
-//       delete it->second;
-//     // now delete the clients gamestatemap
-//     gamestateMap_.erase(clientMap);
-//   }
-
+    this->peerMap_.erase(this->peerMap_.find(peerID));
+  }
+
+  /**
+   * Process an incoming Gamestate packet.
+   * @param gs Pointer to the incoming Gamestate packet
+   */
   bool GamestateManager::processGamestate(packet::Gamestate *gs)
   {
+    // Decompress if necessary
     if(gs->isCompressed())
     {
@@ -362,10 +397,16 @@
     }
     assert(!gs->isDiffed());
+
     uint8_t gsMode;
-    if( GameMode::isMaster() )
+    if(GameMode::isMaster())
+    {
       gsMode = packet::GAMESTATE_MODE_SERVER;
-    else
+    }
+    else
+    {
       gsMode = packet::GAMESTATE_MODE_CLIENT;
-    if( gs->spreadData(gsMode) )
+    }
+
+    if(gs->spreadData(gsMode))
     {
       this->peerMap_[gs->getPeerID()].lastReceivedGamestateID = gs->getID();
@@ -373,5 +414,7 @@
     }
     else
+    {
       return false;
+    }
   }
 
