Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/objecthierarchy2/src/network/Synchronisable.cc @ 2662

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