Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/bsp_model/src/lib/network/synchronizeable.cc @ 8538

Last change on this file since 8538 was 8228, checked in by patrick, 18 years ago

trunk: merged the network branche back to trunk with command: svn merge branches/network trunk -r8150:HEAD

File size: 15.0 KB
Line 
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
11
12### File Specific:
13   main-programmer: Silvan Nellen
14   co-programmer: Benjamin Wuest
15*/
16
17#define DEBUG_MODULE_NETWORK
18
19#include "shared_network_data.h"
20#include "network_stream.h"
21#include "netdefs.h"
22#include "network_log.h"
23#include "network_game_manager.h"
24
25#include "state.h"
26
27#include <cassert>
28
29#include "synchronizeable.h"
30
31
32
33/**
34 *  default constructor
35 */
36Synchronizeable::Synchronizeable()
37{
38  this->setClassID(CL_SYNCHRONIZEABLE, "Synchronizeable");
39  this->owner = 0;
40  this->hostID = SharedNetworkData::getInstance()->getHostID();
41  this->setIsServer(this->hostID == 0);
42  this->uniqueID = NET_UID_UNASSIGNED;
43  this->networkStream = NULL;
44  this->bSynchronize = false;
45 
46  if( State::isOnline())
47  {
48    NetworkStream* nd = SharedNetworkData::getInstance()->getDefaultSyncStream();
49    assert(nd != NULL);
50    nd->connectSynchronizeable(*this);
51    this->setUniqueID(SharedNetworkData::getInstance()->getNewUniqueID());
52  }
53
54  /* make sure loadClassId is first synced var because this is read by networkStream */
55  assert( syncVarList.size() == 0 );
56  mLeafClassId = this->registerVarId( new SynchronizeableInt( (int*)&this->getLeafClassID(), (int*)&this->getLeafClassID(), "leafClassId" ) );
57   
58  this->registerVar( new SynchronizeableInt( &this->owner, &this->owner, "owner" ) );
59  this->registerVar( new SynchronizeableString( &this->objectName, &this->objectName, "objectName" ) );
60}
61
62
63
64/**
65 *  default destructor deletes all unneded stuff
66 */
67Synchronizeable::~Synchronizeable()
68{
69  if ( this->networkStream )
70    this->networkStream->disconnectSynchronizeable(*this);
71 
72  if ( this->isServer() && this->beSynchronized() && this->getUniqueID() > 0 )
73    NetworkGameManager::getInstance()->removeSynchronizeable( this->getUniqueID() );
74}
75
76/**
77 * Sets the server flag to a given value
78 * @param isServer: the boolean value which the server flag is to set to
79 */
80void Synchronizeable::setIsServer(bool isServer)
81{
82  if( isServer )
83    this->state = this->state | STATE_SERVER;
84  else
85    this->state = this->state & (~STATE_SERVER);
86}
87
88
89/**
90 * Determines if the server flag is set
91 * @return true, if the server flag is true, false else
92 */
93bool Synchronizeable::isServer()
94{
95  return (this->state & STATE_SERVER) >0;
96}
97
98
99
100int Synchronizeable::getStateDiff( int userId, byte* data, int maxLength, int stateId, int fromStateId, int priorityTH )
101{
102  //make sure this user has his history
103  if ( sentStates.size() <= userId )
104    sentStates.resize( userId+1 );
105
106  //calculate needed memory
107  int neededSize = 0;
108
109  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
110  {
111    //PRINTF(0)("SIZE = %d %s\n", (*it)->getSize(), (*it)->getName().c_str());
112    neededSize += (*it)->getSize();
113  }
114
115  if ( !( neededSize <= maxLength ) )
116  {
117    PRINTF(0)( "%d > %d\n", neededSize, maxLength );
118    assert(false);
119  }
120
121  //remove older states from history than fromStateId
122  StateHistory::iterator it = sentStates[userId].begin();
123
124  while ( it != sentStates[userId].end() && (*it)->stateId < fromStateId )
125    it++;
126
127  if ( it != sentStates[userId].begin() )
128  {
129    for ( StateHistory::iterator it2 = sentStates[userId].begin(); it2 != it; it2++ )
130    {
131      if ( (*it2)->data != NULL )
132      {
133        delete [] (*it2)->data;
134        (*it2)->data = NULL;
135      }
136    }
137    sentStates[userId].erase( sentStates[userId].begin(), it );
138  }
139
140  //find state to create diff from
141  StateHistoryEntry * stateFrom = NULL;
142
143  it = sentStates[userId].begin();
144  while ( it != sentStates[userId].end() && (*it)->stateId != fromStateId )
145    it++;
146 
147//  if ( getLeafClassID() == CL_SPACE_SHIP )
148//  {
149//    PRINTF(0)("getStateDiff:SpaceShip from: %d stateId: %d\n", (it == sentStates[userId].end())?-1:fromStateId, stateId);
150//  }
151
152  if ( it == sentStates[userId].end() )
153  {
154    StateHistoryEntry * initialEntry = new StateHistoryEntry();
155
156    initialEntry->stateId = fromStateId;
157    initialEntry->dataLength = 0;
158    initialEntry->data = NULL;
159
160    stateFrom = initialEntry;
161  }
162  else
163    stateFrom = (*it);
164
165  StateHistoryEntry * stateTo = new StateHistoryEntry();
166
167  stateTo->stateId = stateId;
168  stateTo->dataLength = neededSize;
169  stateTo->data = new byte[ neededSize ];
170
171  std::list<int>::iterator sizeIter = stateFrom->sizeList.begin();
172
173  int i = 0;
174  int n;
175 
176  bool hasPermission;
177
178  // now do the actual synchronization: kick all variables to write into a common buffer
179  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
180  {
181    hasPermission = (
182            this->isServer() && (*it)->checkPermission( PERMISSION_SERVER ) ||
183            this->owner == this->hostID && (*it)->checkPermission( PERMISSION_OWNER ) ||
184            this->isServer() && this->owner != userId && (*it)->checkPermission( PERMISSION_OWNER ) ||
185            (*it)->checkPermission( PERMISSION_ALL ) 
186                    );
187   
188    if ( ( sizeIter != stateFrom->sizeList.end() && *sizeIter != (*it)->getSize() ) || ( hasPermission && (*it)->getPriority() >= priorityTH ) || sizeIter == stateFrom->sizeList.end() )
189    {
190      n = (*it)->writeToBuf( stateTo->data+i, stateTo->dataLength - i );
191      //NETPRINTF(0)("getvar %s %d\n", (*it)->getName().c_str(), n);
192      stateTo->sizeList.push_back( n );
193      //(*it)->debug();
194      i += n;
195    }
196    else
197    {
198      for ( int j = 0; j<(*sizeIter); j++ )
199      {
200        assert( i < stateFrom->dataLength );
201        stateTo->data[i] = stateFrom->data[i];
202        i++;
203      }
204      //NETPRINTF(0)("getvar %s %d\n", (*it)->getName().c_str(), *sizeIter);
205      stateTo->sizeList.push_back( (*sizeIter) );
206    }
207
208    if ( sizeIter != stateFrom->sizeList.end() )
209      sizeIter++;
210  }
211
212  sentStates[userId].push_back( stateTo );
213 
214  if ( i != neededSize )
215  {
216    PRINTF(0)("strange error: (%s) %d != %d\n", this->getClassName(), i, neededSize);
217    assert(false);
218  }
219
220  //write diff to data
221  for ( i = 0; i<neededSize; i++ )
222  {
223    if ( i < stateFrom->dataLength )
224      data[i] = stateTo->data[i] - stateFrom->data[i];
225    else
226      data[i] = stateTo->data[i];
227  }
228
229  return neededSize;
230}
231
232/**
233 * sets a new state out of a diff created on another host
234 * @param userId hostId of user who send me that diff
235 * @param data pointer to diff
236 * @param length length of diff
237 * @param stateId id of current state
238 * @param fromStateId id of the base state id
239 * @return number bytes read
240 * @todo check for permissions
241 */
242int Synchronizeable::setStateDiff( int userId, byte* data, int length, int stateId, int fromStateId )
243{
244  //make sure this user has his history
245  if ( recvStates.size() <= userId )
246    recvStates.resize( userId+1 );
247
248  //create new state
249  StateHistoryEntry * stateTo = new StateHistoryEntry();
250  stateTo->stateId = stateId;
251  stateTo->dataLength = length;
252  stateTo->data = new byte[ length ];
253
254
255  //find state to apply diff to
256  StateHistoryEntry * stateFrom = NULL;
257
258  StateHistory::iterator it = recvStates[userId].begin();
259  while ( it != recvStates[userId].end() && (*it)->stateId != fromStateId )
260    it++;
261
262 
263//  if ( getLeafClassID() == CL_SPACE_SHIP )
264//  {
265//    PRINTF(0)("setStateDiff:SpaceShip from: %d stateId: %d\n", (it == recvStates[userId].end())?-1:fromStateId, stateId);
266//  }
267
268  if ( it == recvStates[userId].end() )
269  {
270    StateHistoryEntry * initialEntry = new StateHistoryEntry();
271
272    initialEntry->stateId = fromStateId;
273    initialEntry->dataLength = 0;
274    initialEntry->data = NULL;
275
276    stateFrom = initialEntry;
277  }
278  else
279    stateFrom = (*it);
280 
281  //apply diff
282  for ( int i = 0; i<length; i++ )
283  {
284    if ( i < stateFrom->dataLength )
285      stateTo->data[i] = stateFrom->data[i] + data[i];
286    else
287      stateTo->data[i] = data[i];
288   
289  }
290 
291  //add state to state history
292  recvStates[userId].push_back( stateTo );
293 
294  int i = 0;
295  int n = 0;
296  std::list<int> changes;
297 
298  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
299  {
300    if (
301        (*it)->checkPermission( PERMISSION_SERVER ) && networkStream->isUserServer( userId ) ||
302        (*it)->checkPermission( PERMISSION_OWNER ) && this->owner == userId ||
303        networkStream->isUserServer( userId ) && this->owner != getHostID() && (*it)->checkPermission( PERMISSION_OWNER ) ||
304        (*it)->checkPermission( PERMISSION_ALL ) 
305       )
306    {
307      n = (*it)->readFromBuf( stateTo->data + i, stateTo->dataLength - i );
308      i += n;
309      //NETPRINTF(0)("%s::setvar %s %d\n", getClassName(), (*it)->getName().c_str(), n);
310      //(*it)->debug();
311      if ( (*it)->getHasChanged() )
312      {
313        changes.push_back( (*it)->getVarId() );
314      }
315    }
316    else
317    {
318//      PRINTF(0)("DONT SET VAR BECAUSE OF PERMISSION: %s %d %d %d %d %d %d\n", (*it)->getName().c_str(), (*it)->checkPermission( PERMISSION_SERVER ), (*it)->checkPermission( PERMISSION_OWNER ), (*it)->checkPermission( PERMISSION_ALL ), networkStream->isUserServer( userId ), this->owner, userId );
319      n = (*it)->getSizeFromBuf( stateTo->data + i, stateTo->dataLength - i );
320      //NETPRINTF(0)("%s::setvar %s %d\n", getClassName(), (*it)->getName().c_str(), n);
321      //(*it)->debug();
322      i += n;
323    }
324  }
325
326  this->varChangeHandler( changes );
327 
328  return i;
329}
330
331 /**
332 * override this function to be notified on change
333 * of your registred variables.
334 * @param id id's which have changed
335 */
336void Synchronizeable::varChangeHandler( std::list<int> & id )
337{
338}
339
340/**
341 * registers a varable to be synchronized over network
342 * @param var see src/lib/network/synchronizeable_var/ for available classes
343 */
344void Synchronizeable::registerVar( SynchronizeableVar * var )
345{
346  //PRINTF(0)("ADDING VAR: %s\n", var->getName().c_str());
347  syncVarList.push_back( var );
348}
349
350/**
351 * registers a varable to be synchronized over network
352 * return value is passed to varChangeHandler on change
353 * @param var see src/lib/network/synchronizeable_var/ for available classes
354 * @return handle passed to varChangeHandler on changes
355 */
356int Synchronizeable::registerVarId( SynchronizeableVar * var )
357{
358  //PRINTF(0)("ADDING VAR: %s\n", var->getName().c_str());
359  syncVarList.push_back( var );
360  var->setWatched( true );
361  var->setVarId( syncVarList.size()-1 );
362  return syncVarList.size()-1;
363}
364
365/**
366 * removed user's states from memory
367 * @param userId user to clean
368 */
369void Synchronizeable::cleanUpUser( int userId )
370{
371  if ( recvStates.size() > userId )
372  {
373    for ( std::list<StateHistoryEntry*>::iterator it = recvStates[userId].begin(); it != recvStates[userId].end(); it++ )
374    {
375      if ( (*it)->data )
376        delete [] (*it)->data;
377      (*it)->data = NULL;
378   
379      delete *it;
380    }
381    recvStates[userId].clear();
382  }
383 
384  if ( sentStates.size() > userId )
385  {
386   
387    for ( std::list<StateHistoryEntry*>::iterator it = sentStates[userId].begin(); it != sentStates[userId].end(); it++ )
388    {
389      if ( (*it)->data )
390        delete [] (*it)->data;
391      (*it)->data = NULL;
392   
393      delete *it;
394    }
395    sentStates[userId].clear();
396  }
397}
398
399/**
400 * this function is called after recieving a state.
401 * @param userId
402 * @param stateId
403 * @param fromStateId
404 */
405void Synchronizeable::handleRecvState( int userId, int stateId, int fromStateId )
406{
407   //make sure this user has his history
408  if ( recvStates.size() <= userId )
409    recvStates.resize( userId+1 );
410 
411  //remove old states
412  StateHistory::iterator it = recvStates[userId].begin();
413
414#if 0
415  while ( it != recvStates[userId].end() && (*it)->stateId < fromStateId )
416    it++;
417
418  if ( it != recvStates[userId].begin() )
419  {
420    for ( StateHistory::iterator it2 = recvStates[userId].begin(); it2 != it; it2++ )
421    {
422      if ( (*it2)->data != NULL )
423      {
424        delete [] (*it2)->data;
425        (*it2)->data = NULL;
426      }
427    }
428    recvStates[userId].erase( recvStates[userId].begin(), it );
429  }
430#endif
431
432  for ( it = recvStates[userId].begin(); it != recvStates[userId].end();  )
433  {
434    if ( (*it)->stateId < fromStateId )
435    {
436      StateHistory::iterator delIt = it;
437      it ++;
438     
439      if ( (*delIt)->data )
440        delete [] (*delIt)->data;
441      recvStates[userId].erase( delIt );
442     
443      continue;
444    }
445    it++;
446  }
447 
448  StateHistory::iterator fromState = recvStates[userId].end();
449  StateHistory::iterator toState = recvStates[userId].end();
450 
451  for ( it = recvStates[userId].begin(); it != recvStates[userId].end(); it++ )
452  {
453    if ( (*it)->stateId == stateId )
454      toState = it;
455    if ( (*it)->stateId == fromStateId )
456      fromState = it;
457   
458    if ( fromState != recvStates[userId].end() && toState != recvStates[userId].end() )
459      break;
460  }
461 
462  // setStateDiff was not called and i know fromStateId
463  if ( fromState != recvStates[userId].end() && toState == recvStates[userId].end() )
464  {
465    StateHistoryEntry * entry = new StateHistoryEntry;
466   
467    entry->dataLength = (*fromState)->dataLength;
468    if ( entry->dataLength > 0 )
469    {
470      entry->data = new byte[entry->dataLength];
471         
472      assert( (*fromState)->data );
473      memcpy( entry->data, (*fromState)->data, entry->dataLength );
474    }
475    else
476      entry->data = NULL;
477   
478    entry->sizeList = (*fromState)->sizeList;
479    entry->stateId = stateId;
480   
481    recvStates[userId].push_back(entry);
482  }
483}
484
485/**
486 * this function is called after sending a state
487 * @param userId
488 * @param stateId
489 * @param fromStateId
490 */
491void Synchronizeable::handleSentState( int userId, int stateId, int fromStateId )
492{
493   //make sure this user has his history
494  if ( sentStates.size() <= userId )
495    sentStates.resize( userId+1 );
496
497   //remove old states
498  StateHistory::iterator it = sentStates[userId].begin();
499
500  for ( it = sentStates[userId].begin(); it != sentStates[userId].end();  )
501  {
502    if ( (*it)->stateId < fromStateId )
503    {
504      StateHistory::iterator delIt = it;
505      it ++;
506     
507      if ( (*delIt)->data )
508        delete [] (*delIt)->data;
509      sentStates[userId].erase( delIt );
510     
511      continue;
512    }
513    it++;
514  }
515
516 
517  StateHistory::iterator fromState = sentStates[userId].end();
518  StateHistory::iterator toState = sentStates[userId].end();
519 
520  for ( it = sentStates[userId].begin(); it != sentStates[userId].end(); it++ )
521  {
522    if ( (*it)->stateId == stateId )
523      toState = it;
524    if ( (*it)->stateId == fromStateId )
525      fromState = it;
526   
527    if ( fromState != sentStates[userId].end() && toState != sentStates[userId].end() )
528      break;
529  }
530
531 
532  // getStateDiff was not called and i know fromStateId
533  if ( fromState != sentStates[userId].end() && toState == sentStates[userId].end() )
534  {
535    StateHistoryEntry * entry = new StateHistoryEntry;
536   
537    entry->dataLength = (*fromState)->dataLength;
538    if ( entry->dataLength > 0 )
539    {
540      entry->data = new byte[entry->dataLength];
541     
542      assert( (*fromState)->data );
543      memcpy( entry->data, (*fromState)->data, entry->dataLength );
544    }
545    else
546      entry->data = NULL;
547   
548    entry->sizeList = (*fromState)->sizeList;
549    entry->stateId = stateId;
550   
551    sentStates[userId].push_back(entry);
552  }
553 
554}
555
556
557
Note: See TracBrowser for help on using the repository browser.