Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/objecthierarchy/src/network/Synchronisable.cc @ 2132

Last change on this file since 2132 was 2132, checked in by scheusso, 17 years ago

bidirectional synchronisation works now:
register variables with mode direction::serverMaster or direction::clientMaster
clientMaster: both sides may change the variable but the client is master
serverMaster: both sides may change the variable but the server is master

  • Property svn:eol-style set to native
File size: 20.9 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// C++ Implementation: synchronisable
32//
33// Description:
34//
35//
36// Author:  Dumeni, Oliver Scheuss, (C) 2007
37//
38// Copyright: See COPYING file that comes with this distribution
39//
40
41#include "Synchronisable.h"
42
[1837]43#include <cstring>
[2011]44#include <string>
[1505]45#include <iostream>
[1735]46#include <assert.h>
[1505]47
48#include "core/CoreIncludes.h"
[1735]49#include "core/BaseObject.h"
[1534]50// #include "core/Identifier.h"
[1505]51
[2132]52#include "Host.h"
[2112]53namespace orxonox
[1505]54{
[1639]55
[1940]56
[1907]57  std::map<unsigned int, Synchronisable *> Synchronisable::objectMap_;
58  std::queue<unsigned int> Synchronisable::deletedObjects_;
[1639]59
[2132]60  uint8_t Synchronisable::state_=0x1; // detemines wheter we are server (default) or client
[1639]61
[1505]62  /**
63  * Constructor:
[1907]64  * Initializes all Variables and sets the right objectID
[1505]65  */
[2112]66  Synchronisable::Synchronisable(BaseObject* creator){
[1505]67    RegisterRootObject(Synchronisable);
[1907]68    static uint32_t idCounter=0;
[1751]69    objectFrequency_=1;
[1907]70    objectMode_=0x1; // by default do not send data to server
[1505]71    objectID=idCounter++;
[1940]72    classID = (unsigned int)-1;
[1505]73    syncList = new std::list<synchronisableVariable *>;
[2034]74
75    this->creatorID = OBJECTID_UNKNOWN;
76
77    searchcreatorID:
78    if (creator)
79    {
[2041]80        Synchronisable* synchronisable_creator = dynamic_cast<Synchronisable*>(creator);
81        if (synchronisable_creator && synchronisable_creator->objectMode_)
[2034]82        {
83            this->creatorID = synchronisable_creator->getObjectID();
84        }
85        else if (creator != creator->getCreator())
86        {
87            creator = creator->getCreator();
88            goto searchcreatorID;
89        }
90    }
[1505]91  }
92
[1907]93  /**
[1940]94   * Destructor:
[1907]95   * Delete all callback objects and remove objectID from the objectMap_
96   */
[1505]97  Synchronisable::~Synchronisable(){
[1534]98    // delete callback function objects
[2112]99    if(!Identifier::isCreatingHierarchy()){
[1534]100      for(std::list<synchronisableVariable *>::iterator it = syncList->begin(); it!=syncList->end(); it++)
101        delete (*it)->callback;
[2132]102      if (this->objectMode_ != 0x0 && (Host::running() && Host::isServer()))
[1989]103        deletedObjects_.push(objectID);
[1907]104//       COUT(3) << "destruct synchronisable +++" << objectID << " | " << classID << std::endl;
105//       COUT(3) << " bump ---" << objectID << " | " << &objectMap_ << std::endl;
106//       assert(objectMap_[objectID]->objectID==objectID);
107//       objectMap_.erase(objectID);
108    }
[1505]109  }
[1639]110
[1907]111  /**
112   * This function gets called after all neccessary data has been passed to the object
113   * Overload this function and recall the create function of the parent class
114   * @return true/false
115   */
[1505]116  bool Synchronisable::create(){
117    this->classID = this->getIdentifier()->getNetworkID();
[1907]118//     COUT(4) << "creating synchronisable: setting classid from " << this->getIdentifier()->getName() << " to: " << classID << std::endl;
[1940]119
[1907]120//     COUT(3) << "construct synchronisable +++" << objectID << " | " << classID << std::endl;
121//     objectMap_[objectID]=this;
122//     assert(objectMap_[objectID]==this);
123//     assert(objectMap_[objectID]->objectID==objectID);
[1505]124    return true;
125  }
[1639]126
[1856]127
[1907]128  /**
129   * This function sets the internal mode for synchronisation
130   * @param b true if this object is located on a client or on a server
131   */
[1505]132  void Synchronisable::setClient(bool b){
133    if(b) // client
134      state_=0x2;
135    else  // server
136      state_=0x1;
137  }
[1856]138
[1907]139  /**
140   * This function fabricated a new synchrnisable (and children of it), sets calls updateData and create
141   * After calling this function the mem pointer will be increased by the size of the needed data
142   * @param mem pointer to where the appropriate data is located
143   * @param mode defines the mode, how the data should be loaded
144   * @return pointer to the newly created synchronisable
145   */
[2132]146  Synchronisable *Synchronisable::fabricate(uint8_t*& mem, uint8_t mode)
[1735]147  {
[1907]148    synchronisableHeader *header = (synchronisableHeader *)mem;
[1856]149
[2062]150    if(!header->dataAvailable)
151    {
152      mem += header->size;
153      return 0;
154    }
155   
[2041]156    COUT(4) << "fabricating object with id: " << header->objectID << std::endl;
[1856]157
[2112]158    Identifier* id = ClassByID(header->classID);
[1907]159    assert(id);
[2112]160    BaseObject* creator = 0;
[2034]161    if (header->creatorID != OBJECTID_UNKNOWN)
162    {
[2035]163      Synchronisable* synchronisable_creator = Synchronisable::getSynchronisable(header->creatorID);
164      if (!synchronisable_creator)
165      {
166        mem += header->size; //.TODO: this suckz.... remove size from header
167        return 0;
168      }
169      else
[2112]170        creator = dynamic_cast<BaseObject*>(synchronisable_creator);
[2034]171    }
[2112]172    BaseObject *bo = id->fabricate(creator);
[2034]173    assert(bo);
[1735]174    Synchronisable *no = dynamic_cast<Synchronisable *>(bo);
175    assert(no);
[1907]176    no->objectID=header->objectID;
[2033]177    no->creatorID=header->creatorID; //TODO: remove this
[1907]178    no->classID=header->classID;
[2041]179    COUT(4) << "fabricate objectID: " << no->objectID << " classID: " << no->classID << std::endl;
[1735]180          // update data and create object/entity...
[1945]181    bool b = no->updateData(mem, mode, true);
[2035]182    assert(b);
[2031]183    if (b)
184    {
185        b = no->create();
186        assert(b);
187    }
[1907]188    return no;
189  }
190
[1940]191
[1907]192  /**
193   * Finds and deletes the Synchronisable with the appropriate objectID
194   * @param objectID objectID of the Synchronisable
195   * @return true/false
196   */
197  bool Synchronisable::deleteObject(unsigned int objectID){
198//     assert(getSynchronisable(objectID));
199    if(!getSynchronisable(objectID))
[1735]200      return false;
[1907]201    assert(getSynchronisable(objectID)->objectID==objectID);
202//     delete objectMap_[objectID];
203    Synchronisable *s = getSynchronisable(objectID);
204    if(s)
205      delete s;
206    else
[1735]207      return false;
208    return true;
209  }
[1940]210
[1907]211  /**
212   * This function looks up the objectID in the objectMap_ and returns a pointer to the right Synchronisable
213   * @param objectID objectID of the Synchronisable
214   * @return pointer to the Synchronisable with the objectID
215   */
216  Synchronisable* Synchronisable::getSynchronisable(unsigned int objectID){
[2112]217    ObjectList<Synchronisable>::iterator it;
218    for(it = ObjectList<Synchronisable>::begin(); it; ++it){
[1907]219      if( it->getObjectID()==objectID )
220           return *it;
221    }
222    return NULL;
[1505]223
[1907]224//     std::map<unsigned int, Synchronisable *>::iterator i = objectMap_.find(objectID);
225//     if(i==objectMap_.end())
226//       return NULL;
227//     assert(i->second->objectID==objectID);
228//     return (*i).second;
229  }
230
[1940]231
[1505]232  /**
233  * This function is used to register a variable to be synchronized
234  * also counts the total datasize needed to save the variables
235  * @param var pointer to the variable
236  * @param size size of the datatype the variable consists of
[2112]237  * @param t the type of the variable (DATA or STRING
[1907]238  * @param mode same as in getData
239  * @param cb callback object that should get called, if the value of the variable changes
[1505]240  */
[2132]241  void Synchronisable::registerVar(void *var, int size, variableType t, uint8_t mode, NetworkCallbackBase *cb){
[2011]242    assert( mode==direction::toclient || mode==direction::toserver || mode==direction::serverMaster || mode==direction::clientMaster);
[1505]243    // create temporary synch.Var struct
244    synchronisableVariable *temp = new synchronisableVariable;
245    temp->size = size;
246    temp->var = var;
[1639]247    temp->mode = mode;
[1505]248    temp->type = t;
[1534]249    temp->callback = cb;
[2011]250    if( ( mode & direction::bidirectional ) )
251    {
[2132]252      if(t!=STRING)
253      {
254        temp->varBuffer = new uint8_t[size];
255        memcpy(temp->varBuffer, temp->var, size); //now fill the buffer for the first time
256      }
257      else
258      {
259        temp->varBuffer=new std::string( *static_cast<std::string*>(var) );
260      }
[2011]261      temp->varReference = 0;
262    }
[1639]263    COUT(5) << "Syncronisable::registering var with size: " << temp->size << " and type: " << temp->type << std::endl;
[1505]264    //std::cout << "push temp to syncList (at the bottom) " << datasize << std::endl;
265    COUT(5) << "Syncronisable::objectID: " << objectID << " this: " << this << " name: " << this->getIdentifier()->getName() << " networkID: " << this->getIdentifier()->getNetworkID() << std::endl;
266    syncList->push_back(temp);
[1907]267#ifndef NDEBUG
268    std::list<synchronisableVariable *>::iterator it = syncList->begin();
269    while(it!=syncList->end()){
270      assert(*it!=var);
271      it++;
272    }
273#endif
[1505]274  }
[1856]275
[1735]276  /**
[1907]277   * This function takes all SynchronisableVariables out of the Synchronisable and saves them together with the size, objectID and classID to the given memory
[1735]278   * takes a pointer to already allocated memory (must have at least getSize bytes length)
[1751]279   * structure of the bitstream:
[1907]280   * |totalsize,objectID,classID,var1,var2,string1_length,string1,var3,...|
281   * length of varx: size saved int syncvarlist
282   * @param mem pointer to allocated memory with enough size
283   * @param id gamestateid of the gamestate to be saved (important for priorities)
284   * @param mode defines the direction in which the data will be send/received
285   *             0x1: server->client
286   *             0x2: client->server (not recommended)
287   *             0x3: bidirectional
[1990]288   * @return true: if !doSync or if everything was successfully saved
[1735]289   */
[2132]290  bool Synchronisable::getData(uint8_t*& mem, unsigned int id, uint8_t mode){
291    if(mode==0x0)
292      mode=state_;
[1907]293    //if this tick is we dont synchronise, then abort now
[2132]294    if(!doSync(id, mode))
[1907]295      return true;
[1735]296    //std::cout << "inside getData" << std::endl;
297    unsigned int tempsize = 0;
298    if(classID==0)
299      COUT(3) << "classid 0 " << this->getIdentifier()->getName() << std::endl;
[1940]300
301    if (this->classID == (unsigned int)-1)
302        this->classID = this->getIdentifier()->getNetworkID();
303
[1907]304    assert(this->classID==this->getIdentifier()->getNetworkID());
305//     this->classID=this->getIdentifier()->getNetworkID(); // TODO: correct this
[1735]306    std::list<synchronisableVariable *>::iterator i;
307    unsigned int size;
[1907]308    size=getSize(id, mode);
[1856]309
[1735]310    // start copy header
[1907]311    synchronisableHeader *header = (synchronisableHeader *)mem;
312    header->size = size;
313    header->objectID = this->objectID;
[2028]314    header->creatorID = this->creatorID;
[1907]315    header->classID = this->classID;
316    header->dataAvailable = true;
[2132]317    tempsize += sizeof(synchronisableHeader);
318    mem += sizeof(synchronisableHeader);
[1735]319    // end copy header
[1856]320
321
[1735]322    COUT(5) << "Synchronisable getting data from objectID: " << objectID << " classID: " << classID << " length: " << size << std::endl;
323    // copy to location
324    for(i=syncList->begin(); i!=syncList->end(); ++i){
325      if( ((*i)->mode & mode) == 0 ){
326        COUT(5) << "not getting data: " << std::endl;
327        continue;  // this variable should only be received
328      }
[2132]329     
330      // =========== start bidirectional stuff =============
[2011]331      // if the variable gets synchronised bidirectional, then add the reference to the bytestream
[2062]332      if( ( (*i)->mode & direction::bidirectional ) == direction::bidirectional )
[2011]333      {
[2132]334        if( ( ((*i)->mode == direction::serverMaster) && (mode == 0x1) ) || \
335            ( ((*i)->mode == direction::clientMaster) && (mode == 0x2) ) )
336        {
337          // MASTER
338          if((*i)->type==DATA){
339            if( memcmp((*i)->var,(*i)->varBuffer,(*i)->size) != 0 ) //check whether the variable changed during the last tick
340            {
341              ((*i)->varReference)++;   //the variable changed so increase the refnr
342              memcpy((*i)->varBuffer, (*i)->var, (*i)->size); //set the buffer to the new value
343            }
344          }
345          else //STRING
346          {
347            if( *static_cast<std::string*>((*i)->var) != *static_cast<std::string*>((*i)->varBuffer) ) //the string changed
348            {
349              ((*i)->varReference)++;   //the variable changed
350              *static_cast<std::string*>((*i)->varBuffer) = *static_cast<std::string*>((*i)->var);  //now set the buffer to the new value
351            }
352          }
353        }
354        // copy the reference number to the stream
[2011]355        *(uint8_t*)mem = (*i)->varReference;
356        mem += sizeof( (*i)->varReference );
[2062]357        tempsize += sizeof( (*i)->varReference );
[2011]358      }
[2132]359      // ================== end bidirectional stuff
360       
[1735]361      switch((*i)->type){
362        case DATA:
363          memcpy( (void *)(mem), (void*)((*i)->var), (*i)->size);
[2132]364          mem += (*i)->size;
365          tempsize += (*i)->size;
[1735]366          break;
367        case STRING:
[2011]368          memcpy( (void *)(mem), (void *)&((*i)->size), sizeof(size_t) );
[2132]369          mem += sizeof(size_t);
[1735]370          const char *data = ( ( *(std::string *) (*i)->var).c_str());
371          memcpy( mem, (void*)data, (*i)->size);
372          COUT(5) << "synchronisable: char: " << (const char *)(mem) << " data: " << data << " string: " << *(std::string *)((*i)->var) << std::endl;
[2132]373          mem += (*i)->size;
374          tempsize += (*i)->size + sizeof(size_t);
[1735]375          break;
376      }
377    }
378    assert(tempsize==size);
379    return true;
380  }
[1505]381
[1856]382
[1505]383  /**
[1907]384   * This function takes a bytestream and loads the data into the registered variables
385   * @param mem pointer to the bytestream
386   * @param mode same as in getData
[1735]387   * @return true/false
388   */
[2132]389  bool Synchronisable::updateData(uint8_t*& mem, uint8_t mode, bool forceCallback){
[1735]390    if(mode==0x0)
391      mode=state_;
392    std::list<synchronisableVariable *>::iterator i;
[2132]393    //assert(objectMode_!=0x0);
394    //assert( (mode ^ objectMode_) != 0);
[1735]395    if(syncList->empty()){
396      COUT(4) << "Synchronisable::updateData syncList is empty" << std::endl;
397      return false;
398    }
[1856]399
[1907]400    uint8_t *data=mem;
[1735]401    // start extract header
[1907]402    synchronisableHeader *syncHeader = (synchronisableHeader *)mem;
403    assert(syncHeader->objectID==this->objectID);
[2132]404    assert(syncHeader->creatorID==this->creatorID);
405    assert(this->classID==syncHeader->classID); //TODO: fix this!!! maybe a problem with the identifier ?
[1907]406    if(syncHeader->dataAvailable==false){
[2132]407      mem += syncHeader->size;
[1751]408      return true;
[1907]409    }
[1856]410
[2132]411    mem += sizeof(synchronisableHeader);
[1907]412    // stop extract header
[1940]413
[1907]414    COUT(5) << "Synchronisable: objectID " << syncHeader->objectID << ", classID " << syncHeader->classID << " size: " << syncHeader->size << " synchronising data" << std::endl;
415    for(i=syncList->begin(); i!=syncList->end() && mem <= data+syncHeader->size; i++){
[1735]416      if( ((*i)->mode ^ mode) == 0 ){
417        COUT(5) << "synchronisable: not updating variable " << std::endl;
[2132]418        // if we have a forcecallback then do the callback
[1735]419        continue;  // this variable should only be set
420      }
421      COUT(5) << "Synchronisable: element size: " << (*i)->size << " type: " << (*i)->type << std::endl;
422      bool callback=false;
[2132]423      bool master=false;
424     
425      if( ( (*i)->mode & direction::bidirectional ) == direction::bidirectional )
426      {
427        uint8_t refNr = *(uint8_t *)mem;
428        if( ( ((*i)->mode == direction::serverMaster) && (mode == 0x1) ) || \
429            ( ((*i)->mode == direction::clientMaster) && (mode == 0x2) ) )
430        { // MASTER
431          master=true;
432          if( refNr != (*i)->varReference || ( memcmp((*i)->var, (*i)->varBuffer, (*i)->size) != 0 ) )
433          { // DISCARD data
434            if( (*i)->type == DATA )
[2011]435            {
[2132]436              mem += sizeof((*i)->varReference) + (*i)->size;
[2011]437            }
[2132]438            else //STRING
[2011]439            {
[2132]440              mem += sizeof(size_t) + *(size_t *)mem;
[2011]441            }
[2132]442            if( forceCallback && (*i)->callback)
443              (*i)->callback->call();
444            continue;
445          }//otherwise everything is ok and we update the value
446        }
447        else // SLAVE
448        {
449          if( (*i)->varReference == refNr ){
450            //discard data because it's outdated or not different to what we've got
451            if( (*i)->type == DATA )
452            {
453              mem += sizeof((*i)->varReference) + (*i)->size;
454            }
455            else //STRING
456            {
457              mem += sizeof(size_t) + *(size_t *)mem;
458            }
459            if( forceCallback && (*i)->callback)
460              (*i)->callback->call();
461            continue;
[2011]462          }
[2132]463          else
464            (*i)->varReference = refNr; //copy the reference value for this variable
465        }
466        mem += sizeof((*i)->varReference);
467      }
468     
469      switch((*i)->type){
470        case DATA:
[1735]471          if((*i)->callback) // check whether this variable changed (but only if callback was set)
[2132]472          {
473            if(memcmp((*i)->var, mem, (*i)->size) != 0)
[1735]474              callback=true;
[2132]475          }
476          if( master )
477          {
478            if( callback || memcmp((*i)->var, mem, (*i)->size) != 0 )
479              //value changed, so set the buffer to the new value
480              memcpy((*i)->varBuffer, mem, (*i)->size);
481          }
482          memcpy((*i)->var, mem, (*i)->size);
483          mem += (*i)->size;
[1735]484          break;
485        case STRING:
[2011]486          (*i)->size = *(size_t *)mem;
487          mem += sizeof(size_t);
[2132]488         
489          if( (*i)->callback) // check whether this string changed
490            if( *static_cast<std::string*>((*i)->var) != std::string((char *)mem) )
[1735]491              callback=true;
[2132]492          if( master )
493          {
494            if( callback || *static_cast<std::string*>((*i)->var) != std::string((char *)mem) )
495              //string changed. set the buffer to the new one
496              *static_cast<std::string*>((*i)->varBuffer)=*static_cast<std::string*>( (void*)(mem+sizeof(size_t)) );
497          }
498         
[1735]499          *((std::string *)((*i)->var)) = std::string((const char*)mem);
500          COUT(5) << "synchronisable: char: " << (const char*)mem << " string: " << std::string((const char*)mem) << std::endl;
501          mem += (*i)->size;
502          break;
503      }
504      // call the callback function, if defined
[1945]505      if((callback || forceCallback) && (*i)->callback)
[1735]506        (*i)->callback->call();
507    }
[2132]508    assert(mem == data+syncHeader->size);
[1735]509    return true;
510  }
[1505]511
512  /**
513  * This function returns the total amount of bytes needed by getData to save the whole content of the variables
[1907]514  * @param id id of the gamestate
515  * @param mode same as getData
[1505]516  * @return amount of bytes
517  */
[2132]518  uint32_t Synchronisable::getSize(unsigned int id, uint8_t mode){
[1907]519    int tsize=sizeof(synchronisableHeader);
[1505]520    if(mode==0x0)
521      mode=state_;
[2132]522    if(!doSync(id, mode))
523      return 0;
[1505]524    std::list<synchronisableVariable *>::iterator i;
525    for(i=syncList->begin(); i!=syncList->end(); i++){
526      if( ((*i)->mode & mode) == 0 )
527        continue;  // this variable should only be received, so dont add its size to the send-size
528      switch((*i)->type){
529      case DATA:
530        tsize+=(*i)->size;
531        break;
532      case STRING:
533        tsize+=sizeof(int);
534        (*i)->size=((std::string *)(*i)->var)->length()+1;
535        COUT(5) << "String size: " << (*i)->size << std::endl;
536        tsize+=(*i)->size;
537        break;
538      }
[2062]539      if( ( (*i)->mode & direction::bidirectional ) == direction::bidirectional )
[2011]540      {
541        tsize+=sizeof( (*i)->varReference );
542      }
[1505]543    }
544    return tsize;
545  }
[1639]546
[1735]547  /**
[1907]548   * This function determines, wheter the object should be saved to the bytestream (according to its syncmode/direction)
549   * @param id gamestate id
550   * @return true/false
[1735]551   */
[2132]552  bool Synchronisable::doSync(unsigned int id, uint8_t mode){
553    if(mode==0x0)
554      mode=state_;
555    return ( (objectMode_&mode)!=0 && (!syncList->empty() ) );
[1735]556  }
[1856]557
[1907]558  bool Synchronisable::doSelection(unsigned int id){
[2132]559    return true; //TODO: change this
560    //return ( id==0 || id%objectFrequency_==objectID%objectFrequency_ ) && ((objectMode_&state_)!=0);
[1751]561  }
[1856]562
[1907]563  /**
564   * This function looks at the header located in the bytestream and checks wheter objectID and classID match with the Synchronisables ones
565   * @param mem pointer to the bytestream
566   */
567  bool Synchronisable::isMyData(uint8_t* mem)
[1735]568  {
[1907]569    synchronisableHeader *header = (synchronisableHeader *)mem;
570    assert(header->objectID==this->objectID);
571    return header->dataAvailable;
[1735]572  }
[1856]573
[1907]574  /**
575   * This function sets the synchronisation mode of the object
[2132]576   * If set to 0x0 variables will not be synchronised at all
[1907]577   * If set to 0x1 variables will only be synchronised to the client
578   * If set to 0x2 variables will only be synchronised to the server
579   * If set to 0x3 variables will be synchronised bidirectionally (only if set so in registerVar)
580   * @param mode same as in registerVar
581   */
[2132]582  void Synchronisable::setObjectMode(uint8_t mode){
[1989]583    assert(mode==0x0 || mode==0x1 || mode==0x2 || mode==0x3);
[1751]584    objectMode_=mode;
[1505]585  }
586
[1639]587
[1505]588}
Note: See TracBrowser for help on using the repository browser.