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
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// 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
43#include <cstring>
44#include <string>
45#include <iostream>
46#include <assert.h>
47
48#include "core/CoreIncludes.h"
49#include "core/BaseObject.h"
50// #include "core/Identifier.h"
51
52#include "Host.h"
53namespace orxonox
54{
55
56
57  std::map<unsigned int, Synchronisable *> Synchronisable::objectMap_;
58  std::queue<unsigned int> Synchronisable::deletedObjects_;
59
60  uint8_t Synchronisable::state_=0x1; // detemines wheter we are server (default) or client
61
62  /**
63  * Constructor:
64  * Initializes all Variables and sets the right objectID
65  */
66  Synchronisable::Synchronisable(BaseObject* creator){
67    RegisterRootObject(Synchronisable);
68    static uint32_t idCounter=0;
69    objectFrequency_=1;
70    objectMode_=0x1; // by default do not send data to server
71    objectID=idCounter++;
72    classID = (unsigned int)-1;
73    syncList = new std::list<synchronisableVariable *>;
74
75    this->creatorID = OBJECTID_UNKNOWN;
76
77    searchcreatorID:
78    if (creator)
79    {
80        Synchronisable* synchronisable_creator = dynamic_cast<Synchronisable*>(creator);
81        if (synchronisable_creator && synchronisable_creator->objectMode_)
82        {
83            this->creatorID = synchronisable_creator->getObjectID();
84        }
85        else if (creator != creator->getCreator())
86        {
87            creator = creator->getCreator();
88            goto searchcreatorID;
89        }
90    }
91  }
92
93  /**
94   * Destructor:
95   * Delete all callback objects and remove objectID from the objectMap_
96   */
97  Synchronisable::~Synchronisable(){
98    // delete callback function objects
99    if(!Identifier::isCreatingHierarchy()){
100      for(std::list<synchronisableVariable *>::iterator it = syncList->begin(); it!=syncList->end(); it++)
101        delete (*it)->callback;
102      if (this->objectMode_ != 0x0 && (Host::running() && Host::isServer()))
103        deletedObjects_.push(objectID);
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    }
109  }
110
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   */
116  bool Synchronisable::create(){
117    this->classID = this->getIdentifier()->getNetworkID();
118//     COUT(4) << "creating synchronisable: setting classid from " << this->getIdentifier()->getName() << " to: " << classID << std::endl;
119
120//     COUT(3) << "construct synchronisable +++" << objectID << " | " << classID << std::endl;
121//     objectMap_[objectID]=this;
122//     assert(objectMap_[objectID]==this);
123//     assert(objectMap_[objectID]->objectID==objectID);
124    return true;
125  }
126
127
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   */
132  void Synchronisable::setClient(bool b){
133    if(b) // client
134      state_=0x2;
135    else  // server
136      state_=0x1;
137  }
138
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   */
146  Synchronisable *Synchronisable::fabricate(uint8_t*& mem, uint8_t mode)
147  {
148    synchronisableHeader *header = (synchronisableHeader *)mem;
149
150    if(!header->dataAvailable)
151    {
152      mem += header->size;
153      return 0;
154    }
155   
156    COUT(4) << "fabricating object with id: " << header->objectID << std::endl;
157
158    Identifier* id = ClassByID(header->classID);
159    assert(id);
160    BaseObject* creator = 0;
161    if (header->creatorID != OBJECTID_UNKNOWN)
162    {
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
170        creator = dynamic_cast<BaseObject*>(synchronisable_creator);
171    }
172    BaseObject *bo = id->fabricate(creator);
173    assert(bo);
174    Synchronisable *no = dynamic_cast<Synchronisable *>(bo);
175    assert(no);
176    no->objectID=header->objectID;
177    no->creatorID=header->creatorID; //TODO: remove this
178    no->classID=header->classID;
179    COUT(4) << "fabricate objectID: " << no->objectID << " classID: " << no->classID << std::endl;
180          // update data and create object/entity...
181    bool b = no->updateData(mem, mode, true);
182    assert(b);
183    if (b)
184    {
185        b = no->create();
186        assert(b);
187    }
188    return no;
189  }
190
191
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))
200      return false;
201    assert(getSynchronisable(objectID)->objectID==objectID);
202//     delete objectMap_[objectID];
203    Synchronisable *s = getSynchronisable(objectID);
204    if(s)
205      delete s;
206    else
207      return false;
208    return true;
209  }
210
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){
217    ObjectList<Synchronisable>::iterator it;
218    for(it = ObjectList<Synchronisable>::begin(); it; ++it){
219      if( it->getObjectID()==objectID )
220           return *it;
221    }
222    return NULL;
223
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
231
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
237  * @param t the type of the variable (DATA or STRING
238  * @param mode same as in getData
239  * @param cb callback object that should get called, if the value of the variable changes
240  */
241  void Synchronisable::registerVar(void *var, int size, variableType t, uint8_t mode, NetworkCallbackBase *cb){
242    assert( mode==direction::toclient || mode==direction::toserver || mode==direction::serverMaster || mode==direction::clientMaster);
243    // create temporary synch.Var struct
244    synchronisableVariable *temp = new synchronisableVariable;
245    temp->size = size;
246    temp->var = var;
247    temp->mode = mode;
248    temp->type = t;
249    temp->callback = cb;
250    if( ( mode & direction::bidirectional ) )
251    {
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      }
261      temp->varReference = 0;
262    }
263    COUT(5) << "Syncronisable::registering var with size: " << temp->size << " and type: " << temp->type << std::endl;
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);
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
274  }
275
276  /**
277   * This function takes all SynchronisableVariables out of the Synchronisable and saves them together with the size, objectID and classID to the given memory
278   * takes a pointer to already allocated memory (must have at least getSize bytes length)
279   * structure of the bitstream:
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
288   * @return true: if !doSync or if everything was successfully saved
289   */
290  bool Synchronisable::getData(uint8_t*& mem, unsigned int id, uint8_t mode){
291    if(mode==0x0)
292      mode=state_;
293    //if this tick is we dont synchronise, then abort now
294    if(!doSync(id, mode))
295      return true;
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;
300
301    if (this->classID == (unsigned int)-1)
302        this->classID = this->getIdentifier()->getNetworkID();
303
304    assert(this->classID==this->getIdentifier()->getNetworkID());
305//     this->classID=this->getIdentifier()->getNetworkID(); // TODO: correct this
306    std::list<synchronisableVariable *>::iterator i;
307    unsigned int size;
308    size=getSize(id, mode);
309
310    // start copy header
311    synchronisableHeader *header = (synchronisableHeader *)mem;
312    header->size = size;
313    header->objectID = this->objectID;
314    header->creatorID = this->creatorID;
315    header->classID = this->classID;
316    header->dataAvailable = true;
317    tempsize += sizeof(synchronisableHeader);
318    mem += sizeof(synchronisableHeader);
319    // end copy header
320
321
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      }
329     
330      // =========== start bidirectional stuff =============
331      // if the variable gets synchronised bidirectional, then add the reference to the bytestream
332      if( ( (*i)->mode & direction::bidirectional ) == direction::bidirectional )
333      {
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
355        *(uint8_t*)mem = (*i)->varReference;
356        mem += sizeof( (*i)->varReference );
357        tempsize += sizeof( (*i)->varReference );
358      }
359      // ================== end bidirectional stuff
360       
361      switch((*i)->type){
362        case DATA:
363          memcpy( (void *)(mem), (void*)((*i)->var), (*i)->size);
364          mem += (*i)->size;
365          tempsize += (*i)->size;
366          break;
367        case STRING:
368          memcpy( (void *)(mem), (void *)&((*i)->size), sizeof(size_t) );
369          mem += sizeof(size_t);
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;
373          mem += (*i)->size;
374          tempsize += (*i)->size + sizeof(size_t);
375          break;
376      }
377    }
378    assert(tempsize==size);
379    return true;
380  }
381
382
383  /**
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
387   * @return true/false
388   */
389  bool Synchronisable::updateData(uint8_t*& mem, uint8_t mode, bool forceCallback){
390    if(mode==0x0)
391      mode=state_;
392    std::list<synchronisableVariable *>::iterator i;
393    //assert(objectMode_!=0x0);
394    //assert( (mode ^ objectMode_) != 0);
395    if(syncList->empty()){
396      COUT(4) << "Synchronisable::updateData syncList is empty" << std::endl;
397      return false;
398    }
399
400    uint8_t *data=mem;
401    // start extract header
402    synchronisableHeader *syncHeader = (synchronisableHeader *)mem;
403    assert(syncHeader->objectID==this->objectID);
404    assert(syncHeader->creatorID==this->creatorID);
405    assert(this->classID==syncHeader->classID); //TODO: fix this!!! maybe a problem with the identifier ?
406    if(syncHeader->dataAvailable==false){
407      mem += syncHeader->size;
408      return true;
409    }
410
411    mem += sizeof(synchronisableHeader);
412    // stop extract header
413
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++){
416      if( ((*i)->mode ^ mode) == 0 ){
417        COUT(5) << "synchronisable: not updating variable " << std::endl;
418        // if we have a forcecallback then do the callback
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;
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 )
435            {
436              mem += sizeof((*i)->varReference) + (*i)->size;
437            }
438            else //STRING
439            {
440              mem += sizeof(size_t) + *(size_t *)mem;
441            }
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;
462          }
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:
471          if((*i)->callback) // check whether this variable changed (but only if callback was set)
472          {
473            if(memcmp((*i)->var, mem, (*i)->size) != 0)
474              callback=true;
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;
484          break;
485        case STRING:
486          (*i)->size = *(size_t *)mem;
487          mem += sizeof(size_t);
488         
489          if( (*i)->callback) // check whether this string changed
490            if( *static_cast<std::string*>((*i)->var) != std::string((char *)mem) )
491              callback=true;
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         
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
505      if((callback || forceCallback) && (*i)->callback)
506        (*i)->callback->call();
507    }
508    assert(mem == data+syncHeader->size);
509    return true;
510  }
511
512  /**
513  * This function returns the total amount of bytes needed by getData to save the whole content of the variables
514  * @param id id of the gamestate
515  * @param mode same as getData
516  * @return amount of bytes
517  */
518  uint32_t Synchronisable::getSize(unsigned int id, uint8_t mode){
519    int tsize=sizeof(synchronisableHeader);
520    if(mode==0x0)
521      mode=state_;
522    if(!doSync(id, mode))
523      return 0;
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      }
539      if( ( (*i)->mode & direction::bidirectional ) == direction::bidirectional )
540      {
541        tsize+=sizeof( (*i)->varReference );
542      }
543    }
544    return tsize;
545  }
546
547  /**
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
551   */
552  bool Synchronisable::doSync(unsigned int id, uint8_t mode){
553    if(mode==0x0)
554      mode=state_;
555    return ( (objectMode_&mode)!=0 && (!syncList->empty() ) );
556  }
557
558  bool Synchronisable::doSelection(unsigned int id){
559    return true; //TODO: change this
560    //return ( id==0 || id%objectFrequency_==objectID%objectFrequency_ ) && ((objectMode_&state_)!=0);
561  }
562
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)
568  {
569    synchronisableHeader *header = (synchronisableHeader *)mem;
570    assert(header->objectID==this->objectID);
571    return header->dataAvailable;
572  }
573
574  /**
575   * This function sets the synchronisation mode of the object
576   * If set to 0x0 variables will not be synchronised at all
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   */
582  void Synchronisable::setObjectMode(uint8_t mode){
583    assert(mode==0x0 || mode==0x1 || mode==0x2 || mode==0x3);
584    objectMode_=mode;
585  }
586
587
588}
Note: See TracBrowser for help on using the repository browser.