Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/libraries/network/synchronisable/Synchronisable.cc @ 10074

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

merged core6 back to trunk

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