Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/network/src/network/GameStateManager.cc @ 1516

Last change on this file since 1516 was 1516, checked in by scheusso, 16 years ago

removed crc testing and changes debug output

  • Property svn:eol-style set to native
File size: 18.7 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Oliver Scheuss, (C) 2007
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29//
30// C++ Implementation: GameStateManager
31//
32// Description:
33//
34//
35// Author:  Oliver Scheuss, (C) 2007
36//
37// Copyright: See COPYING file that comes with this distribution
38//
39//
40
41#include "GameStateManager.h"
42
43#include <utility>
44#include <iostream>
45#include <zlib.h>
46
47#include "core/CoreIncludes.h"
48#include "core/BaseObject.h"
49#include "ClientInformation.h"
50#include "Synchronisable.h"
51
52namespace network
53{
54  GameStateManager::GameStateManager(ClientInformation *head) {
55    id_=0;
56    head_=head;
57  }
58
59  GameStateManager::~GameStateManager() {
60  }
61
62  void GameStateManager::update(){
63    cleanup();
64    reference = getSnapshot();
65    COUT(4) << "inserting gamestate: " << reference << std::endl;
66    gameStateMap.insert(std::pair<int, GameState*>(id_, reference));
67    gameStateUsed[id_]=0;
68    printGameStates();
69    return;
70  }
71 
72  void GameStateManager::addGameState(GameStateCompressed *gs, int clientID){
73    if(!gs)
74      return;
75    std::map<int, GameStateCompressed*>::iterator it = gameStateQueue.find(clientID);
76    if(it!=gameStateQueue.end()){
77      // delete obsolete gamestate
78      delete[] it->second->data;
79      delete it->second;
80    }
81    gameStateQueue[clientID] = gs;
82    return;
83  }
84 
85  void GameStateManager::processGameStates(){
86    std::map<int, GameStateCompressed*>::iterator it;
87    // now push only the most recent gamestates we received (ignore obsolete ones)
88    for(it = gameStateQueue.begin(); it!=gameStateQueue.end(); it++){
89      pushGameState(it->second, it->first);
90    }
91    // now clear the queue
92    gameStateQueue.clear();
93  }
94 
95 
96  /**
97   * this function is used to keep the memory usage low
98   * it tries to delete all the unused gamestates
99   *
100   *
101   */
102  void GameStateManager::cleanup(){
103    std::map<int,int>::iterator it = gameStateUsed.begin();
104    while(it!=gameStateUsed.end()){
105      if((id_-(*it).first)<KEEP_GAMESTATES)
106        break;
107      if( (*it).second <= 0 ){
108        COUT(5) << "GameStateManager: deleting gamestate with id: " << (*it).first << ", uses: " << (*it).second << std::endl;
109        std::map<int, GameState *>::iterator tempit = gameStateMap.find((*it).first);
110        if( tempit != gameStateMap.end() ){
111          GameState *temp = tempit->second;
112          if(temp){
113            delete[] gameStateMap[(*it).first]->data;
114            delete gameStateMap[(*it).first];
115            gameStateMap.erase((*it).first);
116          }
117        }
118        gameStateUsed.erase(it++);
119        continue;
120      }/*else if(id_-it->first<=KEEP_GAMESTATES){  //as soon as we got a used gamestate break here because we could use newer gamestates in future but only if we do not exceed KEEP_GAMESTATES # of gamestates in cache
121        COUT(4) << "breaking " << std::endl;
122        break;
123      }*/
124      it++;
125    }
126  }
127
128  GameStateCompressed *GameStateManager::popGameState(int clientID) {
129    //why are we searching the same client's gamestate id as we searched in
130    //Server::sendGameState?
131    int gID = head_->findClient(clientID)->getGamestateID();
132    COUT(4) << "G.St.Man: popgamestate: sending gstate_id: " << id_ << " diffed from: " << gID << std::endl;
133//     COUT(3) << "gamestatemap: " << &gameStateMap << std::endl;
134    //chose wheather the next gamestate is the first or not
135    if(gID != GAMESTATEID_INITIAL){
136      // TODO something with the gamestatemap is wrong
137      GameState *client=NULL;
138      std::map<int, GameState*>::iterator it = gameStateMap.find(gID);
139      if(it!=gameStateMap.end())
140        client = it->second;
141      GameState *server = reference;
142      //COUT(4) << "client: " << client << " server: " << server << " gamestatemap: " << &gameStateMap << " size: " << server->size << std::endl;
143      COUT(4) << "client: " << (client!=0 ? client->id : (int)client) << " server: " << server->id << " gamestatemap: " << &gameStateMap << " size: " << server->size << std::endl;
144      if(client)
145        return encode(client, server);
146      else
147        return encode(server);
148    } else {
149      COUT(4) << "we got a GAMESTATEID_INITIAL for clientID: " << clientID << std::endl;
150      GameState *server = reference;
151//       ackGameState(clientID, reference->id);
152      return encode(server);
153      // return an undiffed gamestate and set appropriate flags
154    }
155  }
156 
157  bool GameStateManager::pushGameState( GameStateCompressed *gs, int clientID ){
158    GameState *ugs = decompress(gs);
159    delete[] gs->data;
160    delete gs;
161    bool result = loadPartialSnapshot(ugs, clientID);
162    delete[] ugs->data;
163    delete ugs;
164    return result;
165  }
166
167  /**
168  * This function goes through the whole list of synchronisables and
169  * saves all the synchronisables to a flat "list".
170  * @return struct of type gamestate containing the size of the whole gamestate and a pointer linking to the flat list
171  */
172  GameState *GameStateManager::getSnapshot()
173  {
174    //std::cout << "begin getSnapshot" << std::endl;
175    //the size of the gamestate
176    int totalsize=0;
177    int memsize=0;
178    //the size of one specific synchronisable
179    int tempsize=0;
180    // get the start of the Synchronisable list
181    orxonox::Iterator<Synchronisable> it;
182    // struct for return value of Synchronisable::getData()
183    syncData sync;
184
185    GameState *retval=new GameState; //return value
186    retval->id=++id_;
187    COUT(4) << "G.ST.Man: producing gamestate with id: " << retval->id << std::endl;
188    // offset of memory functions
189    int offset=0, size=0;
190    // get total size of gamestate
191    for(it = orxonox::ObjectList<Synchronisable>::start(); it; ++it){
192      size+=it->getSize(); // size of the actual data of the synchronisable
193      size+=3*sizeof(int); // size of datasize, classID and objectID
194    }
195    //retval->data = (unsigned char*)malloc(size);
196    if(size==0)
197      return NULL;
198    retval->data = new unsigned char[size];
199    if(!retval->data){
200      COUT(2) << "GameStateManager: could not allocate memory" << std::endl;
201      return NULL;
202    }
203    memsize=size;
204    // go through all Synchronisables
205    for(it = orxonox::ObjectList<Synchronisable>::start(); it; ++it){
206      //get size of the synchronisable
207      tempsize=it->getSize();
208      // add place for data and 3 ints (length,classid,objectid)
209      totalsize+=tempsize+3*sizeof(int);
210      // allocate+tempsize additional space
211      if(totalsize > size){
212        COUT(3) << "G.St.Man: need additional memory" << std::endl;
213//         if(tempsize < 1000){
214//           retval->data = (unsigned char *)realloc((void *)retval->data, totalsize+1000);
215//           memsize+=1000;
216//         } else {
217//           retval->data = (unsigned char *)realloc((void *)retval->data, totalsize+1000);
218//           memsize+=tempsize+1000;
219//         }
220//         COUT(5) << "G.St.Man: additional space allocation finished" << std::endl;
221      }
222
223      // run Synchronisable::getData with offset and additional place for 3 ints in between (for ids and length)
224      sync=it->getData((retval->data)+offset+3*sizeof(int));
225      memcpy(retval->data+offset, (void *)&(sync.length), sizeof(int));
226      memcpy(retval->data+offset+sizeof(int), (void *)&(sync.objectID), sizeof(int));
227      memcpy(retval->data+offset+2*sizeof(int), (void *)&(sync.classID), sizeof(int));
228      // increase data pointer
229      offset+=tempsize+3*sizeof(int);
230    }
231    retval->size=totalsize;
232    //#### bugfix
233    retval->diffed = false;
234    retval->complete = true;
235    //std::cout << "end snapShot" << std::endl;
236    COUT(5) << "G.ST.Man: Gamestate size: " << totalsize << std::endl;
237    COUT(5) << "G.ST.Man: 'estimated' Gamestate size: " << size << std::endl;
238    return retval;
239  }
240
241  bool GameStateManager::loadPartialSnapshot(GameState *state, int clientID){
242    if(!state)
243      return false;
244    unsigned char *data=state->data;
245    COUT(4) << "loadSnapshot: loading gs: " << state->id << std::endl;
246    // get the start of the Synchronisable list
247    orxonox::Iterator<Synchronisable> it=orxonox::ObjectList<Synchronisable>::start();
248    syncData sync;
249    /*ClientInformation *client = head_->findClient(clientID);
250    if(client)
251      if(client->getPartialGamestateID()>state->id){
252        COUT(3) << "we received an obsolete partial gamestate" << std::endl;
253        return false;
254      }
255    else;*/
256        //what should we do now ??
257    // loop as long as we have some data ;)
258    while(data < state->data+state->size){
259      // prepare the syncData struct
260      sync.length = *(int *)data;
261      data+=sizeof(int);
262      sync.objectID = *(int*)data;
263      data+=sizeof(int);
264      sync.classID = *(int*)data;
265      if(sync.classID == 0) // TODO: remove this
266        COUT(3) << "received a classid 0" << std::endl;
267      data+=sizeof(int);
268      sync.data = data;
269      data+=sync.length;
270      COUT(5) << "objectID: " << sync.objectID << " classID: " << sync.classID << std::endl;
271      while(it && it->objectID!=sync.objectID)
272        ++it;
273
274
275      if(!it){
276        // the objectaber ich glaub die  does not exist yet
277        COUT(4) << "loadsnapshot: creating new object " << std::endl;
278        //COUT(4) << "loadSnapshot:\tclassid: " << sync.classID << ", name: " << ID((unsigned int) sync.classID)->getName() << std::endl;
279        orxonox::Identifier* id = ID((unsigned int)sync.classID);
280        if(!id){
281          COUT(4) << "We could not identify a new object; classid: " << sync.classID << std::endl;
282          continue;
283        }
284        Synchronisable *no = dynamic_cast<Synchronisable *>(id->fabricate());
285        COUT(4) << "loadpartialsnapshot (generating new object): classid: " << sync.classID << " objectID: " << sync.objectID << " length: " << sync.length << std::endl;
286        no->objectID=sync.objectID;
287        no->classID=sync.classID;
288        it=orxonox::ObjectList<Synchronisable>::end();
289        // update data and create object/entity...
290        if( !no->updateData(sync) )
291          COUT(1) << "We couldn't update the object: " << sync.objectID << std::endl;
292        if( !no->create() )
293          COUT(1) << "We couldn't manifest (create() ) the object: " << sync.objectID << std::endl;
294      }else{
295        // we have our object
296        COUT(4) << "loadpartialsnapshot: we found the appropriate object" << std::endl;
297        if(checkAccess(clientID, sync.objectID)){
298          if(! it->updateData(sync))
299            COUT(1) << "We couldn't update objectID: " \
300              << sync.objectID << "; classID: " << sync.classID << std::endl;
301        }else
302          COUT(4) << "loadPartialSnapshot: no access to change objectID: " << sync.objectID << std::endl;
303      }
304      ++it;
305    }
306    //client->setPartialGamestateID(state->id);
307    return true;
308  }
309 
310 
311  //##### ADDED FOR TESTING PURPOSE #####
312  GameStateCompressed* GameStateManager::testCompress( GameState* g ) {
313    return compress_( g );
314  }
315
316  GameState* GameStateManager::testDiff( GameState* a, GameState* b ) {
317    return diff( a, b );
318  }
319  //##### END TESTING PURPOSE #####
320
321  GameStateCompressed *GameStateManager::encode(GameState *a, GameState *b) {
322    COUT(5) << "G.St.Man: this will be a DIFFED gamestate" << std::endl;
323    GameState *r = diff(a,b);
324    GameStateCompressed *c = compress_(r);
325    delete[] r->data;
326    delete r;
327    return c;
328  }
329
330  GameStateCompressed *GameStateManager::encode(GameState *a) {
331    COUT(5) << "G.St.Man: encoding gamestate (compress)" << std::endl;
332    a->base_id=GAMESTATEID_INITIAL;
333    return compress_(a);
334    /*GameStateCompressed *g = new GameStateCompressed;
335    g->base_id = a->base_id;
336    g->id = a->id;
337    g->diffed = a->diffed;
338    g->data = a->data;
339    g->normsize = a->size;
340    g->compsize = a->size;
341    return g;*/
342  }
343
344  GameState *GameStateManager::diff(GameState *alt, GameState *neu) {
345    unsigned char *ap = alt->data, *bp = neu->data;
346    int of=0; // pointers offset
347    int dest_length=0;
348    /*if(alt->size>neu->size)
349      dest_length=alt->size;
350    else*/
351      dest_length=neu->size;
352    if(dest_length==0)
353      return NULL;
354    //unsigned char *dp = (unsigned char *)malloc(dest_length*sizeof(unsigned char));
355    unsigned char *dp = new unsigned char[dest_length*sizeof(unsigned char)];
356    while(of<alt->size && of<neu->size){
357      *(dp+of)=*(ap+of)^*(bp+of); // do the xor
358      ++of;
359    }
360    if(alt->size!=neu->size){ // do we have to fill up ?
361      unsigned char n=0;
362      if(alt->size<neu->size){
363        while(of<dest_length){
364          *(dp+of)=n^*(bp+of);
365          of++;
366        }
367      } /*else{
368        while(of<dest_length){
369          *(dp+of)=*(ap+of)^n;
370          of++;
371        }
372      }*/
373    }
374
375    GameState *r = new GameState;
376    r->id = neu->id;
377    r->size = dest_length;
378    r->diffed = true;
379    r->base_id = alt->id;
380    r->data = dp;
381    r->complete = true;
382    return r;
383  }
384
385  GameStateCompressed *GameStateManager::compress_(GameState *a) {
386    //COUT(4) << "G.St.Man: compressing gamestate" << std::endl;
387
388    //COUT(4) << "G.St.Man: a: id: " << a->id << " base_id: " << a->base_id << " size: " << a->size << " diffed: " << a->diffed << std::endl;
389    int size = a->size;
390
391    uLongf buffer = (uLongf)((a->size + 12)*1.01)+1;
392    //COUT(4) << "size: " << size << ", buffer: " << buffer << std::endl;
393    //unsigned char* dest = (unsigned char*)malloc( buffer );
394    if(buffer==0)
395      return NULL;
396    unsigned char *dest = new unsigned char[buffer];
397    //COUT(4) << "dest: " << dest << std::endl;
398    int retval;
399    //std::cout << "before ziped " << buffer << std::endl;
400    retval = compress( dest, &buffer, a->data, (uLong)size );
401    //COUT(4) << "bloablabla aft3er compress" << std::endl;
402    //std::cout << "after ziped " << buffer << std::endl;
403
404    switch ( retval ) {
405      case Z_OK: COUT(5) << "G.St.Man: compress: successfully compressed" << std::endl; break;
406      case Z_MEM_ERROR: COUT(1) << "G.St.Man: compress: not enough memory available in gamestate.compress" << std::endl; 
407      return NULL;
408      case Z_BUF_ERROR: COUT(2) << "G.St.Man: compress: not enough memory available in the buffer in gamestate.compress" << std::endl;
409      return NULL;
410      case Z_DATA_ERROR: COUT(2) << "G.St.Man: compress: data corrupted in gamestate.compress" << std::endl;
411      return NULL;
412    }
413
414    GameStateCompressed *compressedGamestate = new GameStateCompressed;
415    compressedGamestate->compsize = buffer;
416//     std::cout << "compressedGamestate.compsize = buffer; " << buffer << std::endl;
417    compressedGamestate->normsize = size;
418//     std::cout << "compressedGamestate.normsize = size; " << size << std::endl;
419    compressedGamestate->id = a->id;
420    compressedGamestate->data = dest;
421    compressedGamestate->diffed = a->diffed;
422    compressedGamestate->complete = a->complete;
423    compressedGamestate->base_id = a->base_id;
424    //COUT(5) << "G.St.Man: saved compressed data in GameStateCompressed:" << std::endl;
425    return compressedGamestate;
426  }
427 
428  GameState *GameStateManager::decompress(GameStateCompressed *a) {
429    //COUT(4) << "GameStateClient: uncompressing gamestate. id: " << a->id << ", baseid: " << a->base_id << ", normsize: " << a->normsize << ", compsize: " << a->compsize << std::endl;
430    int normsize = a->normsize;
431    int compsize = a->compsize;
432    int bufsize;
433    if(normsize < compsize)
434      bufsize = compsize;
435    else
436      bufsize = normsize;
437//     unsigned char* dest = (unsigned char*)malloc( bufsize );
438    if(bufsize==0)
439      return NULL;
440    unsigned char *dest = new unsigned char[bufsize];
441    int retval;
442    uLongf length=normsize;
443    //std::cout << "gamestateclient" << std::endl;
444    //std::cout << "normsize " << a.normsize << " compsize " << a.compsize << " " << bufsize << std::endl;
445    retval = uncompress( dest, &length, a->data, (uLong)compsize );
446    //std::cout << "length " << length << std::endl;
447    switch ( retval ) {
448      case Z_OK: COUT(5) << "successfully decompressed" << std::endl; break;
449      case Z_MEM_ERROR: COUT(1) << "not enough memory available" << std::endl; return NULL;
450      case Z_BUF_ERROR: COUT(2) << "not enough memory available in the buffer" << std::endl; return NULL;
451      case Z_DATA_ERROR: COUT(2) << "data corrupted (zlib)" << std::endl; return NULL;
452    }
453
454    GameState *gamestate = new GameState;
455    gamestate->id = a->id;
456    gamestate->size = normsize;
457    gamestate->data = dest;
458    gamestate->base_id = a->base_id;
459    gamestate->diffed = a->diffed;
460    gamestate->complete = a->complete;
461
462
463    return gamestate;
464  }
465 
466
467  void GameStateManager::ackGameState(int clientID, int gamestateID) {
468    ClientInformation *temp = head_->findClient(clientID);
469    if(temp==0)
470      return;
471    int curid = temp->getGamestateID();
472   
473    if(gamestateID == GAMESTATEID_INITIAL){
474      temp->setGameStateID(GAMESTATEID_INITIAL);
475      if(curid!=GAMESTATEID_INITIAL)
476        --(gameStateUsed.find(curid)->second);
477      return;
478    }
479    if(curid > gamestateID)
480      // the network packets got messed up
481      return;
482    COUT(4) << "acking gamestate " << gamestateID << " for clientid: " << clientID << " curid: " << curid << std::endl;
483    // decrease usage of gamestate and save it
484//     deleteUnusedGameState(curid);
485    //increase gamestateused
486    if(curid!=GAMESTATEID_INITIAL)
487      --(gameStateUsed.find(curid)->second);
488    ++(gameStateUsed.find(gamestateID)->second);
489    temp->setGameStateID(gamestateID);
490    /*
491    GameState *old = clientGameState[clientID];
492    deleteUnusedGameState(old);
493    clientGameState[clientID]=idGameState[gamestateID];*/
494  }
495
496  bool GameStateManager::printGameStates() {
497    std::map<int, GameState*>::iterator it;
498    COUT(4) << "gamestates: ";
499    for(it = gameStateMap.begin(); it!=gameStateMap.end(); it++){
500      COUT(4) << (*it).first << ":" << (*it).second << " | ";
501    }
502    COUT(4) << std::endl;
503    return true;
504  }
505 
506  bool GameStateManager::checkAccess(int clientID, int objectID){
507    // currently we only check, wheter the object is the clients spaceship
508//     return head_->findClient(objectID)->getShipID()==objectID;
509    return true; // TODO: change this
510  }
511 
512  void GameStateManager::removeClient(ClientInformation* client){
513    if(!client)
514      return;
515    if(client->getGamestateID()>=0)
516      gameStateUsed[client->getGamestateID()]--;
517    head_->removeClient(client->getID());
518  }
519
520}
Note: See TracBrowser for help on using the repository browser.