Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 2150 was 2144, checked in by scheusso, 16 years ago

small change in synchronisable and baseobject (check when changing activity)

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