Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/core6/src/libraries/network/synchronisable/Synchronisable.cc @ 9629

Last change on this file since 9629 was 9629, checked in by landauf, 11 years ago

BaseObject now requires a Context instead of a creator (BaseObject*) in its constructor.
Namespace, Level, and Scene inherit from Context

  • Property svn:eol-style set to native
File size: 16.6 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 *      Dumeni Manatschal, (C) 2007
24 *      Oliver Scheuss, (C) 2007
25 *   Co-authors:
26 *      ...
27 *
28 */
29
30
31#include "Synchronisable.h"
32
33#include <cstdlib>
34#include "core/CoreIncludes.h"
35#include "core/GameMode.h"
36#include "core/BaseObject.h"
37#include "network/Host.h"
38
39namespace orxonox
40{
41
42  std::map<uint32_t, Synchronisable *> Synchronisable::objectMap_;
43  std::queue<uint32_t> Synchronisable::deletedObjects_;
44
45  uint8_t Synchronisable::state_=0x1; // detemines wheter we are server (default) or client
46
47  /**
48  * Constructor:
49  * Initializes all Variables and sets the right objectID_
50  */
51  Synchronisable::Synchronisable(Context* context)
52  {
53    RegisterRootObject(Synchronisable);
54    static uint32_t idCounter=0;
55    objectMode_=0x1; // by default do not send data to server
56    if ( GameMode::isMaster()/* || ( Host::running() && Host::isServer() )*/ )
57    {
58      this->setObjectID( idCounter++ );
59    }
60    else
61    {
62      objectID_=OBJECTID_UNKNOWN;
63    }
64    classID_ = static_cast<uint32_t>(-1);
65
66    // set dataSize to 0
67    this->dataSize_ = 0;
68    // set standard priority
69    this->setPriority( Priority::Normal );
70
71    // get context id
72    this->contextID_ = this->findContextID(context);
73  }
74
75  /**
76   * Destructor:
77   * Delete all callback objects and remove objectID_ from the objectMap_
78   */
79  Synchronisable::~Synchronisable()
80  {
81    // delete callback function objects
82    if(!IdentifierManager::isCreatingHierarchy()){
83      // remove object from the static objectMap
84      if (this->objectMode_ != 0x0 && (Host::running() && Host::isServer()))
85        deletedObjects_.push(objectID_);
86    }
87    // delete all Synchronisable Variables from syncList_ ( which are also in stringList_ )
88    for(std::vector<SynchronisableVariableBase*>::iterator it = syncList_.begin(); it!=syncList_.end(); it++)
89      delete (*it);
90    syncList_.clear();
91    stringList_.clear();
92    std::map<uint32_t, Synchronisable*>::iterator it2;
93    it2 = objectMap_.find(objectID_);
94    if (it2 != objectMap_.end())
95      objectMap_.erase(it2);
96
97  }
98
99  /**
100   * @brief Returns the id of the context.
101   * If the context is not Synchronisable, it moves on to its parent, recursively.
102   */
103  uint32_t Synchronisable::findContextID(Context* context)
104  {
105      if (context == NULL)
106          return OBJECTID_UNKNOWN;
107
108      Synchronisable* synchronisableContext = orxonox_cast<Synchronisable*>(context);
109      if (synchronisableContext != NULL)
110          return synchronisableContext->getObjectID();
111      else
112          return this->findContextID(context->getParentContext());
113  }
114
115  /**
116   * This function sets the internal mode for synchronisation
117   * @param b true if this object is located on a client or on a server
118   */
119  void Synchronisable::setClient(bool b)
120  {
121    if(b) // client
122      state_=0x2;
123    else  // server
124      state_=0x1;
125  }
126
127  /**
128   * This function fabricated a new synchrnisable (and children of it), sets calls updateData and create
129   * After calling this function the mem pointer will be increased by the size of the needed data
130   * @param mem pointer to where the appropriate data is located
131   * @param mode defines the mode, how the data should be loaded
132   * @return pointer to the newly created synchronisable
133   */
134  Synchronisable *Synchronisable::fabricate(uint8_t*& mem, uint8_t mode)
135  {
136    SynchronisableHeader header(mem);
137    if( header.isDiffed() )
138    {
139      mem += header.getDataSize() + header.getSize();
140      return 0;
141    }
142//     assert( !header.isDiffed() );
143
144    orxout(verbose, context::network) << "fabricating object with id: " << header.getObjectID() << endl;
145
146    Identifier* id = ClassByID(header.getClassID());
147    if (!id)
148    {
149        for(int i = 0; i<160; i++)
150            orxout(user_error, context::network) << "classid: " << i << " identifier: " << ClassByID(i) << endl;
151        orxout(user_error, context::network) << "Assertion failed: id" << endl;
152        orxout(user_error, context::network) << "Possible reason for this error: Client received a synchronizable object whose class has no factory." << endl;
153        abort();
154    }
155    assert(id);
156    Context* context = 0;
157    if (header.getContextID() != OBJECTID_UNKNOWN)
158    {
159      Synchronisable* synchronisable_context = Synchronisable::getSynchronisable(header.getContextID());
160      if (!synchronisable_context)
161      {
162        mem += header.getDataSize()+SynchronisableHeader::getSize(); //.TODO: this suckz.... remove size from header
163        assert(0); // TODO: uncomment this if we have a clean objecthierarchy (with destruction of children of objects) ^^
164        return 0;
165      }
166      else
167        context = orxonox_cast<Context*>(synchronisable_context);
168    }
169    assert(getSynchronisable(header.getObjectID())==0);   //make sure no object with this id exists
170    BaseObject *bo = orxonox_cast<BaseObject*>(id->fabricate(context));
171    assert(bo);
172    Synchronisable *no = orxonox_cast<Synchronisable*>(bo);
173    assert(no);
174    assert( Synchronisable::objectMap_.find(header.getObjectID()) == Synchronisable::objectMap_.end() );
175    no->setObjectID(header.getObjectID());
176    //no->contextID=header.getContextID(); //TODO: remove this
177    no->setClassID(header.getClassID());
178    assert(no->contextID_ == header.getContextID());
179    if( context )
180    {
181      BaseObject* boContext = orxonox_cast<BaseObject*>(context);
182      if (boContext)
183          bo->setLevel(boContext->getLevel()); // Note: this ensures that the level is known on the client for child objects of the scene (and the scene itself)
184    }
185    //assert(no->classID_ == header.getClassID());
186    orxout(verbose, context::network) << "fabricate objectID_: " << no->objectID_ << " classID_: " << no->classID_ << endl;
187          // update data and create object/entity...
188    bool b = no->updateData(mem, mode, true);
189    assert(b);
190    if (b)
191    {
192//        b = no->create();
193        assert(b);
194    }
195    return no;
196  }
197
198
199  /**
200   * Finds and deletes the Synchronisable with the appropriate objectID_
201   * @param objectID_ objectID_ of the Synchronisable
202   * @return true/false
203   */
204  bool Synchronisable::deleteObject(uint32_t objectID_)
205  {
206    if(!getSynchronisable(objectID_))
207      return false;
208    assert(getSynchronisable(objectID_)->objectID_==objectID_);
209    Synchronisable *s = getSynchronisable(objectID_);
210    if(s)
211      s->destroy(); // or delete?
212    else
213      return false;
214    return true;
215  }
216
217  /**
218   * This function looks up the objectID_ in the objectMap_ and returns a pointer to the right Synchronisable
219   * @param objectID_ objectID_ of the Synchronisable
220   * @return pointer to the Synchronisable with the objectID_
221   */
222  Synchronisable* Synchronisable::getSynchronisable(uint32_t objectID_)
223  {
224    std::map<uint32_t, Synchronisable*>::iterator it1;
225    it1 = objectMap_.find(objectID_);
226    if (it1 != objectMap_.end())
227      return it1->second;
228    // if the objects not in the map it should'nt exist at all anymore
229    return NULL;
230  }
231
232
233  /**
234   * This function takes all SynchronisableVariables out of the Synchronisable and saves them together with the size, objectID_ and classID_ to the given memory
235   * takes a pointer to already allocated memory (must have at least getSize bytes length)
236   * structure of the bitstream:
237   * |totalsize,objectID_,classID_,var1,var2,string1_length,string1,var3,...|
238   * length of varx: size saved int syncvarlist
239   * @param mem pointer to allocated memory with enough size
240   * @param sizes vector containing sizes of all objects in gamestate (to be appended)
241   * @param id gamestateid of the gamestate to be saved (important for priorities)
242   * @param mode defines the direction in which the data will be send/received
243   *             0x1: server->client
244   *             0x2: client->server
245   *             0x3: bidirectional
246   * @return true: if !doSync or if everything was successfully saved
247   */
248  uint32_t Synchronisable::getData(uint8_t*& mem, std::vector<uint32_t>& sizes, int32_t id, uint8_t mode)
249  {
250    unsigned int test = 0;
251    if(mode==0x0)
252      mode=state_;
253    //if this tick is we dont synchronise, then abort now
254    if(!doSync(/*id,*/ mode))
255      return 0;
256    uint32_t tempsize = 0;
257#ifndef NDEBUG
258    uint8_t* oldmem = mem;
259    if (this->classID_==0)
260      orxout(internal_info, context::network) << "classid 0 " << this->getIdentifier()->getName() << endl;
261#endif
262
263    if (this->classID_ == static_cast<uint32_t>(-1))
264        this->classID_ = this->getIdentifier()->getNetworkID();
265
266    assert(ClassByID(this->classID_));
267    assert(this->classID_==this->getIdentifier()->getNetworkID());
268    assert(this->objectID_!=OBJECTID_UNKNOWN);
269    std::vector<SynchronisableVariableBase*>::iterator i;
270
271    // start copy header
272    SynchronisableHeader header(mem);
273    mem += SynchronisableHeader::getSize();
274    // end copy header
275
276    orxout(verbose_more, context::network) << "getting data from objectID_: " << objectID_ << ", classID_: " << classID_ << endl;
277//     orxout(verbose, context::network) << "objectid: " << this->objectID_ << ":";
278    // copy to location
279    for(i=syncList_.begin(); i!=syncList_.end(); ++i)
280    {
281      uint32_t varsize = (*i)->getData( mem, mode );
282//       orxout(verbose, context::network) << " " << varsize;
283      tempsize += varsize;
284      sizes.push_back(varsize);
285      ++test;
286      //tempsize += (*i)->getSize( mode );
287    }
288    assert(tempsize!=0);  // if this happens an empty object (with no variables) would be transmitted
289//     orxout(verbose, context::network) << endl;
290
291    header.setObjectID( this->objectID_ );
292    header.setContextID( this->contextID_ );
293    header.setClassID( this->classID_ );
294    header.setDataSize( tempsize );
295    assert( tempsize == mem-oldmem-SynchronisableHeader::getSize() );
296    assert( test == this->getNrOfVariables() );
297    header.setDiffed(false);
298    tempsize += SynchronisableHeader::getSize();
299
300#ifndef NDEBUG
301    uint32_t size;
302    size=getSize(id, mode);
303    assert(tempsize==size);
304#endif
305    return tempsize;
306  }
307
308
309  /**
310   * This function takes a bytestream and loads the data into the registered variables
311   * @param mem pointer to the bytestream
312   * @param mode same as in getData
313   * @param forceCallback this makes updateData call each callback
314   * @return true/false
315   */
316  bool Synchronisable::updateData(uint8_t*& mem, uint8_t mode, bool forceCallback)
317  {
318    if(mode==0x0)
319      mode=state_;
320   
321    if(syncList_.empty())
322    {
323      orxout(internal_warning, context::network) << "Synchronisable::updateData syncList_ is empty" << endl;
324      assert(0);
325      return false;
326    }
327
328    uint8_t* data=mem;
329    // start extract header
330    SynchronisableHeaderLight syncHeaderLight(mem);
331    assert(syncHeaderLight.getObjectID()==this->getObjectID());
332   
333    if( !this->doReceive(mode) )
334    {
335      uint32_t headerSize;
336      if( syncHeaderLight.isDiffed() )
337        headerSize = SynchronisableHeaderLight::getSize();
338      else
339        headerSize = SynchronisableHeader::getSize();
340      mem += syncHeaderLight.getDataSize() + headerSize;
341      return true;
342    }
343
344    //orxout(verbose_more, context::network) << "Synchronisable: objectID_ " << syncHeader.getObjectID() << ", classID_ " << syncHeader.getClassID() << " size: " << syncHeader.getDataSize() << " synchronising data" << endl;
345    if( !syncHeaderLight.isDiffed() )
346    {
347      SynchronisableHeader syncHeader2(mem);
348      assert( this->getClassID() == syncHeader2.getClassID() );
349      assert( this->getContextID() == syncHeader2.getContextID() );
350      mem += SynchronisableHeader::getSize();
351      std::vector<SynchronisableVariableBase *>::iterator i;
352      for(i=syncList_.begin(); i!=syncList_.end(); ++i)
353      {
354        assert( mem <= data+syncHeader2.getDataSize()+SynchronisableHeader::getSize() ); // always make sure we don't exceed the datasize in our stream
355        (*i)->putData( mem, mode, forceCallback );
356      }
357      assert(mem == data+syncHeaderLight.getDataSize()+SynchronisableHeader::getSize() );
358    }
359    else
360    {
361      mem += SynchronisableHeaderLight::getSize();
362//       orxout(debug_output, context::network) << "objectID: " << this->objectID_ << endl;
363      while( mem < data+syncHeaderLight.getDataSize()+SynchronisableHeaderLight::getSize() )
364      {
365        VariableID varID = *(VariableID*)mem;
366//         orxout(debug_output, context::network) << "varID: " << varID << endl;
367        assert( varID < syncList_.size() );
368        mem += sizeof(VariableID);
369        syncList_[varID]->putData( mem, mode, forceCallback );
370      }
371      assert(mem == data+syncHeaderLight.getDataSize()+SynchronisableHeaderLight::getSize() );
372    }
373    return true;
374  }
375
376  /**
377  * This function returns the total amount of bytes needed by getData to save the whole content of the variables
378  * @param id id of the gamestate
379  * @param mode same as getData
380  * @return amount of bytes
381  */
382  uint32_t Synchronisable::getSize(int32_t id, uint8_t mode)
383  {
384    uint32_t tsize=SynchronisableHeader::getSize();
385    if (mode==0x0)
386      mode=state_;
387    if (!doSync(/*id, */mode))
388      return 0;
389    assert( mode==state_ );
390    tsize += this->dataSize_;
391    std::vector<SynchronisableVariableBase*>::iterator i;
392    for(i=stringList_.begin(); i!=stringList_.end(); ++i)
393    {
394      tsize += (*i)->getSize( mode );
395    }
396    return tsize;
397  }
398
399  /**
400   * This function determines, wheter the object should be saved to the bytestream (according to its syncmode/direction)
401   * @param mode Synchronisation mode (toclient, toserver or bidirectional)
402   * @return true/false
403   */
404  bool Synchronisable::doSync(/*int32_t id,*/ uint8_t mode)
405  {
406//     if(mode==0x0)
407//       mode=state_;
408    assert(mode!=0x0);
409    return ( (this->objectMode_ & mode)!=0 && (!syncList_.empty() ) );
410  }
411 
412  /**
413   * This function determines, wheter the object should accept data from the bytestream (according to its syncmode/direction)
414   * @param mode Synchronisation mode (toclient, toserver or bidirectional)
415   * @return true/false
416   */
417  bool Synchronisable::doReceive( uint8_t mode)
418  {
419    //return mode != this->objectMode_ || this->objectMode_ == ObjectDirection::Bidirectional;
420    return true;
421  }
422
423  /**
424   * This function sets the synchronisation mode of the object
425   * If set to 0x0 variables will not be synchronised at all
426   * If set to 0x1 variables will only be synchronised to the client
427   * If set to 0x2 variables will only be synchronised to the server
428   * If set to 0x3 variables will be synchronised bidirectionally (only if set so in registerVar)
429   * @param mode same as in registerVar
430   */
431  void Synchronisable::setSyncMode(uint8_t mode)
432  {
433    assert(mode==0x0 || mode==0x1 || mode==0x2 || mode==0x3);
434    this->objectMode_=mode;
435  }
436
437  template <> void Synchronisable::registerVariable( std::string& variable, uint8_t mode, NetworkCallbackBase *cb, bool bidirectional)
438  {
439    SynchronisableVariableBase* sv;
440    if (bidirectional)
441      sv = new SynchronisableVariableBidirectional<std::string>(variable, mode, cb);
442    else
443      sv = new SynchronisableVariable<std::string>(variable, mode, cb);
444    syncList_.push_back(sv);
445    stringList_.push_back(sv);
446  }
447
448template <> void Synchronisable::unregisterVariable( std::string& variable )
449  {
450    bool unregistered_nonexistent_variable = true;
451    std::vector<SynchronisableVariableBase*>::iterator it = syncList_.begin();
452    while(it!=syncList_.end())
453    {
454      if( ((*it)->getReference()) == &variable )
455      {
456        delete (*it);
457        syncList_.erase(it);
458        unregistered_nonexistent_variable = false;
459        break;
460      }
461      else
462        ++it;
463    }
464    assert(unregistered_nonexistent_variable == false);
465   
466    it = stringList_.begin();
467    while(it!=stringList_.end())
468    {
469      if( ((*it)->getReference()) == &variable )
470      {
471        delete (*it);
472        stringList_.erase(it);
473        return;
474      }
475      else
476        ++it;
477    }
478    unregistered_nonexistent_variable = true;
479    assert(unregistered_nonexistent_variable == false); //if we reach this point something went wrong:
480    // the variable has not been registered before
481  }
482
483
484}
Note: See TracBrowser for help on using the repository browser.