Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 7631 was 7631, checked in by rennerc, 19 years ago

synchronisation should work now

File size: 10.2 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
23#include "state.h"
24
25#include <cassert>
26
27#include "synchronizeable.h"
28
29
30
31/**
32 *  default constructor
33 */
34Synchronizeable::Synchronizeable()
35{
36  this->setClassID(CL_SYNCHRONIZEABLE, "Synchronizeable");
37  this->owner = -1;
38  this->hostID = SharedNetworkData::getInstance()->getHostID();
39  this->setIsServer(this->hostID == 0);
40  this->uniqueID = NET_UID_UNASSIGNED;
41  this->networkStream = NULL;
42  this->bSynchronize = false;
43 
44  if( State::isOnline())
45  {
46    NetworkStream* nd = SharedNetworkData::getInstance()->getDefaultSyncStream();
47    assert(nd != NULL);
48    nd->connectSynchronizeable(*this);
49    this->setUniqueID(SharedNetworkData::getInstance()->getNewUniqueID());
50  }
51
52  /* make sure loadClassId is first synced var because this is read by networkStream */
53  assert( syncVarList.size() == 0 );
54  mLeafClassId = this->registerVarId( new SynchronizeableInt( (int*)&this->getLeafClassID(), (int*)&this->getLeafClassID(), "leafClassId" ) );
55   
56  this->registerVar( new SynchronizeableInt( &this->owner, &this->owner, "owner" ) );
57  this->registerVar( new SynchronizeableString( &this->objectName, &this->objectName, "objectName" ) );
58}
59
60
61
62/**
63 *  default destructor deletes all unneded stuff
64 */
65Synchronizeable::~Synchronizeable()
66{
67  if ( this->networkStream )
68    this->networkStream->disconnectSynchronizeable(*this);
69}
70
71/**
72 * Sets the server flag to a given value
73 * @param isServer: the boolean value which the server flag is to set to
74 */
75void Synchronizeable::setIsServer(bool isServer)
76{
77  if( isServer )
78    this->state = this->state | STATE_SERVER;
79  else
80    this->state = this->state & (~STATE_SERVER);
81}
82
83
84/**
85 * Determines if the server flag is set
86 * @return true, if the server flag is true, false else
87 */
88bool Synchronizeable::isServer()
89{
90  return (this->state & STATE_SERVER) >0;
91}
92
93
94
95int Synchronizeable::getStateDiff( int userId, byte* data, int maxLength, int stateId, int fromStateId, int priorityTH )
96{
97  //make sure this user has his history
98  if ( sentStates.size() <= userId )
99    sentStates.resize( userId+1 );
100
101  //calculate needed memory
102  int neededSize = 0;
103
104  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
105    neededSize += (*it)->getSize();
106
107  if ( !( neededSize <= maxLength ) )
108  {
109    PRINTF(0)( "%d > %d\n", neededSize, maxLength );
110    assert(false);
111  }
112
113  //remove older states from history than fromStateId
114  StateHistory::iterator it = sentStates[userId].begin();
115
116  while ( it != sentStates[userId].end() && (*it)->stateId < fromStateId )
117    it++;
118
119  if ( it != sentStates[userId].begin() )
120  {
121    for ( StateHistory::iterator it2 = sentStates[userId].begin(); it2 != it; it2++ )
122    {
123      if ( (*it2)->data != NULL )
124      {
125        delete (*it2)->data;
126        (*it2)->data = NULL;
127      }
128    }
129    sentStates[userId].erase( sentStates[userId].begin(), it );
130  }
131
132  //find state to create diff from
133  StateHistoryEntry * stateFrom = NULL;
134
135  it = sentStates[userId].begin();
136  while ( it != sentStates[userId].end() && (*it)->stateId != fromStateId )
137    it++;
138
139  if ( it == sentStates[userId].end() )
140  {
141    StateHistoryEntry * initialEntry = new StateHistoryEntry();
142
143    initialEntry->stateId = fromStateId;
144    initialEntry->dataLength = 0;
145    initialEntry->data = NULL;
146
147    stateFrom = initialEntry;
148  }
149  else
150    stateFrom = (*it);
151
152  StateHistoryEntry * stateTo = new StateHistoryEntry();
153
154  stateTo->stateId = stateId;
155  stateTo->dataLength = neededSize;
156  stateTo->data = (byte*)malloc( neededSize );
157
158  std::list<int>::iterator sizeIter = stateFrom->sizeList.begin();
159
160  int i = 0;
161  int n;
162 
163  bool hasPermission;
164
165  // now do the actual synchronization: kick all variables to write into a common buffer
166  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
167  {
168    hasPermission = (
169            this->isServer() && (*it)->checkPermission( PERMISSION_SERVER ) ||
170            this->owner == this->hostID && (*it)->checkPermission( PERMISSION_OWNER ) ||
171            (*it)->checkPermission( PERMISSION_ALL ) 
172                    );
173   
174    if ( ( hasPermission && (*it)->getPriority() >= priorityTH ) || sizeIter == stateFrom->sizeList.end() )
175    {
176      (*it)->debug();
177      n = (*it)->writeToBuf( stateTo->data+i, stateTo->dataLength - i );
178      stateTo->sizeList.push_back( n );
179      i += n;
180    }
181    else if ( ! hasPermission )
182    {
183      for ( int j = 0; j < (*it)->getSize(); j++ )
184      {
185        assert(false);
186        stateTo->data[i] = 0;
187        i++;
188      }
189    }
190    else
191    {
192      for ( int j = 0; j<(*sizeIter); j++ )
193      {
194        assert( i < stateFrom->dataLength );
195        stateTo->data[i] = stateFrom->data[i];
196        i++;
197      }
198      stateTo->sizeList.push_back( (*sizeIter) );
199    }
200
201    if ( sizeIter != stateFrom->sizeList.end() )
202      sizeIter++;
203  }
204
205  sentStates[userId].push_back( stateTo );
206 
207  assert( i == neededSize );
208
209  //write diff to data
210  for ( i = 0; i<neededSize; i++ )
211  {
212    if ( i < stateFrom->dataLength )
213      data[i] = stateTo->data[i] - stateFrom->data[i];
214    else
215      data[i] = stateTo->data[i];
216  }
217
218  return neededSize;
219}
220
221/**
222 * sets a new state out of a diff created on another host
223 * @param userId hostId of user who send me that diff
224 * @param data pointer to diff
225 * @param length length of diff
226 * @param stateId id of current state
227 * @param fromStateId id of the base state id
228 * @return number bytes read
229 * @todo check for permissions
230 */
231int Synchronizeable::setStateDiff( int userId, byte* data, int length, int stateId, int fromStateId )
232{
233  //make sure this user has his history
234  if ( recvStates.size() <= userId )
235    recvStates.resize( userId+1 );
236
237  //create new state
238  StateHistoryEntry * stateTo = new StateHistoryEntry();
239  stateTo->stateId = stateId;
240  stateTo->dataLength = length;
241  stateTo->data = (byte*)malloc( length );
242
243  //remove old states
244  StateHistory::iterator it = recvStates[userId].begin();
245
246  while ( it != recvStates[userId].end() && (*it)->stateId < fromStateId )
247    it++;
248
249  if ( it != recvStates[userId].begin() )
250  {
251    for ( StateHistory::iterator it2 = recvStates[userId].begin(); it2 != it; it2++ )
252    {
253      if ( (*it2)->data != NULL )
254      {
255        delete (*it2)->data;
256        (*it2)->data = NULL;
257      }
258    }
259    recvStates[userId].erase( recvStates[userId].begin(), it );
260  }
261
262  //find state to apply diff to
263  StateHistoryEntry * stateFrom = NULL;
264
265  it = recvStates[userId].begin();
266  while ( it != recvStates[userId].end() && (*it)->stateId != fromStateId )
267    it++;
268
269  if ( it == recvStates[userId].end() )
270  {
271    StateHistoryEntry * initialEntry = new StateHistoryEntry();
272
273    initialEntry->stateId = fromStateId;
274    initialEntry->dataLength = 0;
275    initialEntry->data = NULL;
276
277    stateFrom = initialEntry;
278  }
279  else
280    stateFrom = (*it);
281 
282  //apply diff
283  for ( int i = 0; i<length; i++ )
284  {
285    if ( i < stateFrom->dataLength )
286      stateTo->data[i] = stateFrom->data[i] + data[i];
287    else
288      stateTo->data[i] = data[i];
289   
290  }
291
292  //add state to state history
293  recvStates[userId].push_back( stateTo );
294 
295  int i = 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        (*it)->checkPermission( PERMISSION_ALL ) 
304       )
305    {
306      i += (*it)->readFromBuf( stateTo->data + i, stateTo->dataLength - i );
307      if ( (*it)->getHasChanged() )
308        changes.push_back( (*it)->getVarId() );
309    }
310    else
311    {
312      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 );
313      i += (*it)->getSizeFromBuf( stateTo->data + i, stateTo->dataLength - i );
314    }
315  }
316
317  this->varChangeHandler( changes );
318 
319  return i;
320}
321
322 /**
323 * override this function to be notified on change
324 * of your registred variables.
325 * @param id id's which have changed
326 */
327void Synchronizeable::varChangeHandler( std::list<int> & id )
328{
329}
330
331/**
332 * registers a varable to be synchronized over network
333 * @param var see src/lib/network/synchronizeable_var/ for available classes
334 */
335void Synchronizeable::registerVar( SynchronizeableVar * var )
336{
337  PRINTF(0)("ADDING var: %s (%s)\n", var->getName().c_str(), this->getName() );
338  syncVarList.push_back( var );
339}
340
341/**
342 * registers a varable to be synchronized over network
343 * return value is passed to varChangeHandler on change
344 * @param var see src/lib/network/synchronizeable_var/ for available classes
345 * @return handle passed to varChangeHandler on changes
346 */
347int Synchronizeable::registerVarId( SynchronizeableVar * var )
348{
349  PRINTF(0)("ADDING var: %s (%s)\n", var->getName().c_str(), this->getName() );
350  syncVarList.push_back( var );
351  var->setWatched( true );
352  var->setVarId( syncVarList.size()-1 );
353  return syncVarList.size()-1;
354}
355
356/**
357 * removed user's states from memory
358 * @param userId user to clean
359 */
360void Synchronizeable::cleanUpUser( int userId )
361{
362  for ( UserStateHistory::iterator it = sentStates.begin(); it != sentStates.end(); it++ )
363  {
364    for ( StateHistory::iterator it2 = it->begin(); it2 != it->end(); it++ )
365    {
366      if ( (*it2)->data )
367        delete (*it2)->data;
368      (*it2)->data = NULL;
369     
370      delete *it2;
371    }
372  }
373 
374  sentStates.clear();
375 
376  for ( UserStateHistory::iterator it = recvStates.begin(); it != recvStates.end(); it++ )
377  {
378    for ( StateHistory::iterator it2 = it->begin(); it2 != it->end(); it++ )
379    {
380      if ( (*it2)->data )
381        delete (*it2)->data;
382      (*it2)->data = NULL;
383     
384      delete *it2;
385    }
386  }
387 
388  recvStates.clear();
389}
390
391
392
Note: See TracBrowser for help on using the repository browser.