Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/proxy/src/lib/network/synchronizeable.cc @ 9474

Last change on this file since 9474 was 9474, checked in by patrick, 19 years ago

the hybrid mode should work now in a very closed setup

File size: 18.0 KB
RevLine 
[5523]1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
[5547]11
[5523]12### File Specific:
[9406]13   main-programmer: Christoph Renner (rennerc@ee.ethz.ch)
14   co-programmer: Patrick Boenzli (patrick@orxonox.ethz.ch)
[5547]15*/
[5523]16
[6139]17#define DEBUG_MODULE_NETWORK
18
[6695]19#include "shared_network_data.h"
20#include "network_stream.h"
[5547]21#include "netdefs.h"
[7954]22#include "network_log.h"
[8068]23#include "network_game_manager.h"
[5529]24
[6695]25#include "state.h"
[5996]26
[6753]27#include <cassert>
[6695]28
29#include "synchronizeable.h"
30
[9406]31#include "converter.h"
[6695]32
33
[9406]34
[5547]35/**
[5807]36 *  default constructor
[5547]37 */
[5996]38Synchronizeable::Synchronizeable()
[5997]39{
[6341]40  this->setClassID(CL_SYNCHRONIZEABLE, "Synchronizeable");
[8068]41  this->owner = 0;
[9406]42//   this->setIsServer(SharedNetworkData::getInstance()->getHostID() == 0);
[6695]43  this->uniqueID = NET_UID_UNASSIGNED;
[6145]44  this->networkStream = NULL;
[6695]45  this->bSynchronize = false;
[9406]46
[6695]47  if( State::isOnline())
48  {
49    NetworkStream* nd = SharedNetworkData::getInstance()->getDefaultSyncStream();
50    assert(nd != NULL);
51    nd->connectSynchronizeable(*this);
52    this->setUniqueID(SharedNetworkData::getInstance()->getNewUniqueID());
53  }
[7954]54
55  /* make sure loadClassId is first synced var because this is read by networkStream */
56  assert( syncVarList.size() == 0 );
57  mLeafClassId = this->registerVarId( new SynchronizeableInt( (int*)&this->getLeafClassID(), (int*)&this->getLeafClassID(), "leafClassId" ) );
[9406]58
[7954]59  this->registerVar( new SynchronizeableInt( &this->owner, &this->owner, "owner" ) );
60  this->registerVar( new SynchronizeableString( &this->objectName, &this->objectName, "objectName" ) );
[5997]61}
62
[5523]63
[5996]64
[5547]65/**
[5807]66 *  default destructor deletes all unneded stuff
[5547]67 */
68Synchronizeable::~Synchronizeable()
[6139]69{
70  if ( this->networkStream )
[9110]71  {
[6139]72    this->networkStream->disconnectSynchronizeable(*this);
[9406]73
[9474]74    // remove the message manager only by the server
75    if ( (SharedNetworkData::getInstance()->isMasterServer() )
[9406]76           && this->beSynchronized() && this->getUniqueID() > 0 && !this->isA( CL_MESSAGE_MANAGER ) )
[9110]77      NetworkGameManager::getInstance()->removeSynchronizeable( this->getUniqueID() );
78  }
[9406]79
[8623]80  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
81  {
82    delete *it;
83  }
84  syncVarList.clear();
[9406]85
[8623]86  for ( UserStateHistory::iterator it = recvStates.begin(); it != recvStates.end(); it++ )
87  {
88    for ( StateHistory::iterator it2 = it->begin(); it2 != it->end(); it2++ )
89    {
90      if ( (*it2)->data )
91      {
92        delete [] (*it2)->data;
93        (*it2)->data = NULL;
94      }
95      delete *it2;
96    }
97
98  }
[9406]99
[8623]100  for ( UserStateHistory::iterator it = sentStates.begin(); it != sentStates.end(); it++ )
101  {
102    for ( StateHistory::iterator it2 = it->begin(); it2 != it->end(); it2++ )
103    {
104      if ( (*it2)->data )
105      {
106        delete [] (*it2)->data;
107        (*it2)->data = NULL;
108      }
109      delete *it2;
110    }
111  }
[6139]112}
[5523]113
114
[6695]115
[5547]116/**
[9406]117 * creates a diff image from two states
118 * @param userId: the userid of the user where the image will be sent to
119 * @param data: the binary data array to write to
120 * @param maxLength: maximal length of the data written (length of available space in the array)
121 * @param stateId: the state id that this diff will represent
122 * @param priorityTH: the priority threshold: all syncs below this threshold won't be synchronized
123 *
124 * @todo check for permissions
[5547]125 */
[7954]126int Synchronizeable::getStateDiff( int userId, byte* data, int maxLength, int stateId, int fromStateId, int priorityTH )
127{
128  //make sure this user has his history
129  if ( sentStates.size() <= userId )
130    sentStates.resize( userId+1 );
[5547]131
[7954]132  //calculate needed memory
133  int neededSize = 0;
[5997]134
[7954]135  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
[8147]136  {
137    //PRINTF(0)("SIZE = %d %s\n", (*it)->getSize(), (*it)->getName().c_str());
[7954]138    neededSize += (*it)->getSize();
[8147]139  }
[5997]140
[7954]141  if ( !( neededSize <= maxLength ) )
142  {
143    PRINTF(0)( "%d > %d\n", neededSize, maxLength );
144    assert(false);
145  }
146
147  //remove older states from history than fromStateId
148  StateHistory::iterator it = sentStates[userId].begin();
149
150  while ( it != sentStates[userId].end() && (*it)->stateId < fromStateId )
151    it++;
152
153  if ( it != sentStates[userId].begin() )
154  {
155    for ( StateHistory::iterator it2 = sentStates[userId].begin(); it2 != it; it2++ )
156    {
157      if ( (*it2)->data != NULL )
158      {
159        delete [] (*it2)->data;
160        (*it2)->data = NULL;
161      }
[9406]162
[8623]163      delete *it2;
[7954]164    }
165    sentStates[userId].erase( sentStates[userId].begin(), it );
166  }
167
168  //find state to create diff from
169  StateHistoryEntry * stateFrom = NULL;
170
171  it = sentStates[userId].begin();
172  while ( it != sentStates[userId].end() && (*it)->stateId != fromStateId )
173    it++;
174
175  if ( it == sentStates[userId].end() )
176  {
177    StateHistoryEntry * initialEntry = new StateHistoryEntry();
178
179    initialEntry->stateId = fromStateId;
180    initialEntry->dataLength = 0;
181    initialEntry->data = NULL;
182
183    stateFrom = initialEntry;
[9406]184
[8623]185    sentStates[userId].push_back( stateFrom );
[7954]186  }
187  else
188    stateFrom = (*it);
189
[8623]190  StateHistoryEntry * stateTo = new StateHistoryEntry;
[7954]191
[8623]192  sentStates[userId].push_back( stateTo );
[9406]193
[7954]194  stateTo->stateId = stateId;
195  stateTo->dataLength = neededSize;
196  stateTo->data = new byte[ neededSize ];
197
198  std::list<int>::iterator sizeIter = stateFrom->sizeList.begin();
199
200  int i = 0;
201  int n;
[9406]202
203  bool hasPermission = false;
[8623]204  bool sizeChanged = false;
[7954]205
206  // now do the actual synchronization: kick all variables to write into a common buffer
207  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
208  {
[9406]209    // DATA PERMISSIONS
210    // check if this synchronizeable has the permissions to write the data
211
212    // first check MASTER_SERVER permissions
213    if( SharedNetworkData::getInstance()->isMasterServer() && (*it)->checkPermission( PERMISSION_MASTER_SERVER ))
214      hasPermission = true;
215    // now check PROXY_SERVER permissions
[9458]216    else if( SharedNetworkData::getInstance()->isProxyServerActive() && (*it)->checkPermission( PERMISSION_PROXY_SERVER ))
[9406]217      hasPermission = true;
218    // now check OWNER permissions
219    else if( this->owner == SharedNetworkData::getInstance()->getHostID() && (*it)->checkPermission( PERMISSION_OWNER ))
220      hasPermission = true;
221    // now check ALL permissions
222    else if( (*it)->checkPermission( PERMISSION_ALL ))
223      hasPermission = true;
224    // SPECIAL: get write permissions if i am master server and i am able to overwrite the client stuff
225    else if( SharedNetworkData::getInstance()->isMasterServer() && this->owner != userId && (*it)->checkPermission( PERMISSION_OWNER ))
226      hasPermission = true;
227    // SPECIAL: get write permissions if i am proxy server and i am able to overwrite the client stuff
[9469]228//     else if( SharedNetworkData::getInstance()->isProxyServerActive()  && this->owner != userId && (*it)->checkPermission( PERMISSION_OWNER ))
229//       hasPermission = true;
[9406]230    else
231      hasPermission = false;
232
233
234    if ( sizeIter == stateFrom->sizeList.end() || *sizeIter != (*it)->getSize() )
[8623]235      sizeChanged = true;
[9406]236
[8623]237    if ( ( hasPermission && (*it)->getPriority() >= priorityTH ) || sizeChanged )
[7954]238    {
239      n = (*it)->writeToBuf( stateTo->data+i, stateTo->dataLength - i );
240      //NETPRINTF(0)("getvar %s %d\n", (*it)->getName().c_str(), n);
[9406]241      //PRINTF(0)("getvar %s %d\n", (*it)->getName().c_str(), n);
[7954]242      stateTo->sizeList.push_back( n );
[9406]243      // this is only for very hardcore debug sessions
244      // (*it)->debug();
[7954]245      i += n;
246    }
247    else
248    {
249      for ( int j = 0; j<(*sizeIter); j++ )
250      {
251        assert( i < stateFrom->dataLength );
252        stateTo->data[i] = stateFrom->data[i];
253        i++;
254      }
255      //NETPRINTF(0)("getvar %s %d\n", (*it)->getName().c_str(), *sizeIter);
256      stateTo->sizeList.push_back( (*sizeIter) );
257    }
258
259    if ( sizeIter != stateFrom->sizeList.end() )
260      sizeIter++;
261  }
262
[8147]263  if ( i != neededSize )
264  {
[9406]265    PRINTF(0)("strange error: (%s) %d != %d\n", this->getClassCName(), i, neededSize);
[8147]266    assert(false);
267  }
[7954]268
269  //write diff to data
270  for ( i = 0; i<neededSize; i++ )
271  {
272    if ( i < stateFrom->dataLength )
273      data[i] = stateTo->data[i] - stateFrom->data[i];
274    else
275      data[i] = stateTo->data[i];
276  }
277
278  return neededSize;
279}
280
[5997]281/**
[7954]282 * sets a new state out of a diff created on another host
283 * @param userId hostId of user who send me that diff
284 * @param data pointer to diff
285 * @param length length of diff
286 * @param stateId id of current state
287 * @param fromStateId id of the base state id
288 * @return number bytes read
[9406]289 *
[7954]290 * @todo check for permissions
[5997]291 */
[7954]292int Synchronizeable::setStateDiff( int userId, byte* data, int length, int stateId, int fromStateId )
[5997]293{
[7954]294  //make sure this user has his history
295  if ( recvStates.size() <= userId )
296    recvStates.resize( userId+1 );
297
298  //create new state
299  StateHistoryEntry * stateTo = new StateHistoryEntry();
300  stateTo->stateId = stateId;
301  stateTo->dataLength = length;
302  stateTo->data = new byte[ length ];
303
304
305  //find state to apply diff to
306  StateHistoryEntry * stateFrom = NULL;
307
[9406]308  // search the state from wich the diff is made of
[7954]309  StateHistory::iterator it = recvStates[userId].begin();
310  while ( it != recvStates[userId].end() && (*it)->stateId != fromStateId )
311    it++;
312
[9406]313  // if this is the first state to receive
[7954]314  if ( it == recvStates[userId].end() )
315  {
316    StateHistoryEntry * initialEntry = new StateHistoryEntry();
317
318    initialEntry->stateId = fromStateId;
319    initialEntry->dataLength = 0;
320    initialEntry->data = NULL;
321
322    stateFrom = initialEntry;
[9406]323
[8623]324    recvStates[userId].push_back( stateFrom );
[7954]325  }
[5997]326  else
[7954]327    stateFrom = (*it);
[9406]328
329
330  // apply diff
[7954]331  for ( int i = 0; i<length; i++ )
332  {
333    if ( i < stateFrom->dataLength )
334      stateTo->data[i] = stateFrom->data[i] + data[i];
335    else
336      stateTo->data[i] = data[i];
337  }
[9406]338
[7954]339  //add state to state history
340  recvStates[userId].push_back( stateTo );
[9406]341
[7954]342  int i = 0;
343  int n = 0;
344  std::list<int> changes;
[9406]345  bool hasPermission = false;
346
347  // extract the new state for every client
[7954]348  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
349  {
[9406]350    // DATA PERMISSIONS
351    // check if this synchronizeable has the permissions to write the data
352
353    // first check MASTER_SERVER permissions
354    if(  this->networkStream->isUserMasterServer( userId ) && (*it)->checkPermission( PERMISSION_MASTER_SERVER ))
355      hasPermission = true;
356    // now check PROXY_SERVER permissions
[9458]357    else if( this->networkStream->isUserProxyServerActive( userId )  && (*it)->checkPermission( PERMISSION_PROXY_SERVER ))
[9406]358      hasPermission = true;
359    // now check OWNER permissions
360    else if( this->owner == userId && (*it)->checkPermission( PERMISSION_OWNER ))
361      hasPermission = true;
362    // now check ALL permissions
363    else if( (*it)->checkPermission( PERMISSION_ALL ))
364      hasPermission = true;
365    // SPECIAL: get write permissions if im sending to a master server that does not own this sync
366    else if( this->networkStream->isUserMasterServer( userId ) && this->owner != SharedNetworkData::getInstance()->getHostID() && (*it)->checkPermission( PERMISSION_OWNER ))
367      hasPermission = true;
368    // SPECIAL: get write permissions if im sending to a proxy server that does not own this sync
[9469]369//     else if( this->networkStream->isUserProxyServerActive( userId )  && this->owner != SharedNetworkData::getInstance()->getHostID() && (*it)->checkPermission( PERMISSION_OWNER ))
370//       hasPermission = true;
[9406]371    else
372      hasPermission = false;
373
374
375
376    // if it has the permission to write do it
377    if( hasPermission)
[7954]378    {
379      n = (*it)->readFromBuf( stateTo->data + i, stateTo->dataLength - i );
380      i += n;
[9406]381      //NETPRINTF(0)("%s::setvar %s %d\n", getClassCName(), (*it)->getName().c_str(), n);
382      //PRINTF(0)("%s::setvar %s %d\n", getClassCName(), (*it)->getName().c_str(), n);
[7954]383      //(*it)->debug();
384      if ( (*it)->getHasChanged() )
385      {
386        changes.push_back( (*it)->getVarId() );
387      }
388    }
389    else
390    {
[9406]391//      PRINTF(0)("DONT SET VAR BECAUSE OF PERMISSION: %s %d %d %d %d %d %d\n", (*it)->getName().c_str(), (*it)->checkPermission( PERMISSION_MASTER_SERVER ), (*it)->checkPermission( PERMISSION_OWNER ), (*it)->checkPermission( PERMISSION_ALL ), networkStream->isUserServer( userId ), this->owner, userId );
[7954]392      n = (*it)->getSizeFromBuf( stateTo->data + i, stateTo->dataLength - i );
[9406]393      //NETPRINTF(0)("%s::setvar %s %d\n", getClassCName(), (*it)->getName().c_str(), n);
[7954]394      //(*it)->debug();
395      i += n;
396    }
397  }
398
399  this->varChangeHandler( changes );
[9406]400
[7954]401  return i;
[5997]402}
403
[7954]404 /**
405 * override this function to be notified on change
406 * of your registred variables.
407 * @param id id's which have changed
408 */
409void Synchronizeable::varChangeHandler( std::list<int> & id )
410{
411}
[6695]412
[5997]413/**
[7954]414 * registers a varable to be synchronized over network
415 * @param var see src/lib/network/synchronizeable_var/ for available classes
[5997]416 */
[7954]417void Synchronizeable::registerVar( SynchronizeableVar * var )
[5997]418{
[7954]419  syncVarList.push_back( var );
[5997]420}
421
422/**
[7954]423 * registers a varable to be synchronized over network
424 * return value is passed to varChangeHandler on change
425 * @param var see src/lib/network/synchronizeable_var/ for available classes
426 * @return handle passed to varChangeHandler on changes
[5997]427 */
[7954]428int Synchronizeable::registerVarId( SynchronizeableVar * var )
[5997]429{
[7954]430  syncVarList.push_back( var );
431  var->setWatched( true );
432  var->setVarId( syncVarList.size()-1 );
433  return syncVarList.size()-1;
[5997]434}
435
436/**
[7954]437 * removed user's states from memory
438 * @param userId user to clean
[5997]439 */
[7954]440void Synchronizeable::cleanUpUser( int userId )
[5997]441{
[8228]442  if ( recvStates.size() > userId )
[7954]443  {
[8228]444    for ( std::list<StateHistoryEntry*>::iterator it = recvStates[userId].begin(); it != recvStates[userId].end(); it++ )
[7954]445    {
[8228]446      if ( (*it)->data )
[8623]447      {
[8228]448        delete [] (*it)->data;
[8623]449        (*it)->data = NULL;
450      }
[9406]451
[8228]452      delete *it;
[7954]453    }
[8228]454    recvStates[userId].clear();
[7954]455  }
[9406]456
[8228]457  if ( sentStates.size() > userId )
[7954]458  {
[9406]459
[8228]460    for ( std::list<StateHistoryEntry*>::iterator it = sentStates[userId].begin(); it != sentStates[userId].end(); it++ )
[7954]461    {
[8228]462      if ( (*it)->data )
[8623]463      {
[8228]464        delete [] (*it)->data;
[8623]465        (*it)->data = NULL;
466      }
[9406]467
[8228]468      delete *it;
[7954]469    }
[8228]470    sentStates[userId].clear();
[7954]471  }
[5997]472}
[6139]473
[6341]474/**
[7954]475 * this function is called after recieving a state.
[9406]476 * @param userId
477 * @param stateId
478 * @param fromStateId
[6341]479 */
[7954]480void Synchronizeable::handleRecvState( int userId, int stateId, int fromStateId )
[6341]481{
[7954]482   //make sure this user has his history
483  if ( recvStates.size() <= userId )
484    recvStates.resize( userId+1 );
[9406]485
[7954]486  //remove old states
487  StateHistory::iterator it = recvStates[userId].begin();
488
489#if 0
490  while ( it != recvStates[userId].end() && (*it)->stateId < fromStateId )
491    it++;
492
493  if ( it != recvStates[userId].begin() )
494  {
495    for ( StateHistory::iterator it2 = recvStates[userId].begin(); it2 != it; it2++ )
496    {
497      if ( (*it2)->data != NULL )
498      {
499        delete [] (*it2)->data;
500        (*it2)->data = NULL;
501      }
502    }
503    recvStates[userId].erase( recvStates[userId].begin(), it );
504  }
505#endif
506
507  for ( it = recvStates[userId].begin(); it != recvStates[userId].end();  )
508  {
509    if ( (*it)->stateId < fromStateId )
510    {
511      StateHistory::iterator delIt = it;
512      it ++;
[9406]513
[7954]514      if ( (*delIt)->data )
[8623]515      {
[7954]516        delete [] (*delIt)->data;
[8623]517        (*delIt)->data = NULL;
518      }
519      delete *delIt;
[7954]520      recvStates[userId].erase( delIt );
[9406]521
[7954]522      continue;
523    }
524    it++;
525  }
[9406]526
[7954]527  StateHistory::iterator fromState = recvStates[userId].end();
528  StateHistory::iterator toState = recvStates[userId].end();
[9406]529
[7954]530  for ( it = recvStates[userId].begin(); it != recvStates[userId].end(); it++ )
531  {
532    if ( (*it)->stateId == stateId )
533      toState = it;
534    if ( (*it)->stateId == fromStateId )
535      fromState = it;
[9406]536
[7954]537    if ( fromState != recvStates[userId].end() && toState != recvStates[userId].end() )
538      break;
539  }
[9406]540
[7954]541  // setStateDiff was not called and i know fromStateId
542  if ( fromState != recvStates[userId].end() && toState == recvStates[userId].end() )
543  {
544    StateHistoryEntry * entry = new StateHistoryEntry;
[9406]545
[7954]546    entry->dataLength = (*fromState)->dataLength;
547    if ( entry->dataLength > 0 )
548    {
549      entry->data = new byte[entry->dataLength];
[9406]550
[7954]551      assert( (*fromState)->data );
552      memcpy( entry->data, (*fromState)->data, entry->dataLength );
553    }
554    else
555      entry->data = NULL;
[9406]556
[7954]557    entry->sizeList = (*fromState)->sizeList;
558    entry->stateId = stateId;
[9406]559
[7954]560    recvStates[userId].push_back(entry);
561  }
[6341]562}
[6139]563
[6341]564/**
[7954]565 * this function is called after sending a state
[9406]566 * @param userId
567 * @param stateId
568 * @param fromStateId
[6341]569 */
[7954]570void Synchronizeable::handleSentState( int userId, int stateId, int fromStateId )
[6341]571{
[7954]572   //make sure this user has his history
573  if ( sentStates.size() <= userId )
574    sentStates.resize( userId+1 );
575
576   //remove old states
577  StateHistory::iterator it = sentStates[userId].begin();
578
579  for ( it = sentStates[userId].begin(); it != sentStates[userId].end();  )
580  {
581    if ( (*it)->stateId < fromStateId )
582    {
583      StateHistory::iterator delIt = it;
584      it ++;
[9406]585
[7954]586      if ( (*delIt)->data )
[8623]587      {
[7954]588        delete [] (*delIt)->data;
[8623]589        (*delIt)->data = NULL;
590      }
591      delete *delIt;
[7954]592      sentStates[userId].erase( delIt );
[9406]593
[7954]594      continue;
595    }
596    it++;
597  }
598
[9406]599
[7954]600  StateHistory::iterator fromState = sentStates[userId].end();
601  StateHistory::iterator toState = sentStates[userId].end();
[9406]602
[7954]603  for ( it = sentStates[userId].begin(); it != sentStates[userId].end(); it++ )
604  {
605    if ( (*it)->stateId == stateId )
606      toState = it;
607    if ( (*it)->stateId == fromStateId )
608      fromState = it;
[9406]609
[7954]610    if ( fromState != sentStates[userId].end() && toState != sentStates[userId].end() )
611      break;
612  }
613
[9406]614
[7954]615  // getStateDiff was not called and i know fromStateId
616  if ( fromState != sentStates[userId].end() && toState == sentStates[userId].end() )
617  {
618    StateHistoryEntry * entry = new StateHistoryEntry;
[9406]619
[7954]620    entry->dataLength = (*fromState)->dataLength;
621    if ( entry->dataLength > 0 )
622    {
623      entry->data = new byte[entry->dataLength];
[9406]624
[7954]625      assert( (*fromState)->data );
626      memcpy( entry->data, (*fromState)->data, entry->dataLength );
627    }
628    else
629      entry->data = NULL;
[9406]630
[7954]631    entry->sizeList = (*fromState)->sizeList;
632    entry->stateId = stateId;
[9406]633
[7954]634    sentStates[userId].push_back(entry);
635  }
[9406]636
[6341]637}
[6139]638
[6341]639
640
Note: See TracBrowser for help on using the repository browser.