Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 2006 was 1990, checked in by scheusso, 16 years ago
  • some adjustments in client handling (we use unsigned int as id now everywhere)
  • fixed a problem with clientinformation
  • Property svn:eol-style set to native
File size: 15.1 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 <iostream>
45#include <assert.h>
46
47#include "core/CoreIncludes.h"
48#include "core/BaseObject.h"
49// #include "core/Identifier.h"
50
51namespace network
52{
53
54
55  std::map<unsigned int, Synchronisable *> Synchronisable::objectMap_;
56  std::queue<unsigned int> Synchronisable::deletedObjects_;
57
58  int Synchronisable::state_=0x1; // detemines wheter we are server (default) or client
59
60  /**
61  * Constructor:
62  * Initializes all Variables and sets the right objectID
63  */
64  Synchronisable::Synchronisable(){
65    RegisterRootObject(Synchronisable);
66    static uint32_t idCounter=0;
67    objectFrequency_=1;
68    objectMode_=0x1; // by default do not send data to server
69    objectID=idCounter++;
70    classID = (unsigned int)-1;
71    syncList = new std::list<synchronisableVariable *>;
72  }
73
74  /**
75   * Destructor:
76   * Delete all callback objects and remove objectID from the objectMap_
77   */
78  Synchronisable::~Synchronisable(){
79    // delete callback function objects
80    if(!orxonox::Identifier::isCreatingHierarchy()){
81      for(std::list<synchronisableVariable *>::iterator it = syncList->begin(); it!=syncList->end(); it++)
82        delete (*it)->callback;
83      if (this->objectMode_ != 0x0)
84        deletedObjects_.push(objectID);
85//       COUT(3) << "destruct synchronisable +++" << objectID << " | " << classID << std::endl;
86//       COUT(3) << " bump ---" << objectID << " | " << &objectMap_ << std::endl;
87//       assert(objectMap_[objectID]->objectID==objectID);
88//       objectMap_.erase(objectID);
89    }
90  }
91
92  /**
93   * This function gets called after all neccessary data has been passed to the object
94   * Overload this function and recall the create function of the parent class
95   * @return true/false
96   */
97  bool Synchronisable::create(){
98    this->classID = this->getIdentifier()->getNetworkID();
99//     COUT(4) << "creating synchronisable: setting classid from " << this->getIdentifier()->getName() << " to: " << classID << std::endl;
100
101//     COUT(3) << "construct synchronisable +++" << objectID << " | " << classID << std::endl;
102//     objectMap_[objectID]=this;
103//     assert(objectMap_[objectID]==this);
104//     assert(objectMap_[objectID]->objectID==objectID);
105    return true;
106  }
107
108
109  /**
110   * This function sets the internal mode for synchronisation
111   * @param b true if this object is located on a client or on a server
112   */
113  void Synchronisable::setClient(bool b){
114    if(b) // client
115      state_=0x2;
116    else  // server
117      state_=0x1;
118  }
119
120  /**
121   * This function fabricated a new synchrnisable (and children of it), sets calls updateData and create
122   * After calling this function the mem pointer will be increased by the size of the needed data
123   * @param mem pointer to where the appropriate data is located
124   * @param mode defines the mode, how the data should be loaded
125   * @return pointer to the newly created synchronisable
126   */
127  Synchronisable *Synchronisable::fabricate(uint8_t*& mem, int mode)
128  {
129    synchronisableHeader *header = (synchronisableHeader *)mem;
130
131    COUT(3) << "fabricating object with id: " << header->objectID << std::endl;
132
133    orxonox::Identifier* id = ClassByID(header->classID);
134    assert(id);
135    orxonox::BaseObject *bo = id->fabricate();
136    Synchronisable *no = dynamic_cast<Synchronisable *>(bo);
137    assert(no);
138    no->objectID=header->objectID;
139    no->classID=header->classID;
140    COUT(3) << "fabricate objectID: " << no->objectID << " classID: " << no->classID << std::endl;
141          // update data and create object/entity...
142    bool b = no->updateData(mem, mode, true);
143    assert(b);
144    b = no->create();
145    assert(b);
146    return no;
147  }
148
149
150  /**
151   * Finds and deletes the Synchronisable with the appropriate objectID
152   * @param objectID objectID of the Synchronisable
153   * @return true/false
154   */
155  bool Synchronisable::deleteObject(unsigned int objectID){
156//     assert(getSynchronisable(objectID));
157    if(!getSynchronisable(objectID))
158      return false;
159    assert(getSynchronisable(objectID)->objectID==objectID);
160//     delete objectMap_[objectID];
161    Synchronisable *s = getSynchronisable(objectID);
162    if(s)
163      delete s;
164    else
165      return false;
166    return true;
167  }
168
169  /**
170   * This function looks up the objectID in the objectMap_ and returns a pointer to the right Synchronisable
171   * @param objectID objectID of the Synchronisable
172   * @return pointer to the Synchronisable with the objectID
173   */
174  Synchronisable* Synchronisable::getSynchronisable(unsigned int objectID){
175    orxonox::ObjectList<Synchronisable>::iterator it;
176    for(it = orxonox::ObjectList<Synchronisable>::begin(); it; ++it){
177      if( it->getObjectID()==objectID )
178           return *it;
179    }
180    return NULL;
181
182//     std::map<unsigned int, Synchronisable *>::iterator i = objectMap_.find(objectID);
183//     if(i==objectMap_.end())
184//       return NULL;
185//     assert(i->second->objectID==objectID);
186//     return (*i).second;
187  }
188
189
190  /**
191  * This function is used to register a variable to be synchronized
192  * also counts the total datasize needed to save the variables
193  * @param var pointer to the variable
194  * @param size size of the datatype the variable consists of
195  * @param t the type of the variable (network::DATA or network::STRING
196  * @param mode same as in getData
197  * @param cb callback object that should get called, if the value of the variable changes
198  */
199  void Synchronisable::registerVar(void *var, int size, variableType t, int mode, NetworkCallbackBase *cb){
200    // create temporary synch.Var struct
201    synchronisableVariable *temp = new synchronisableVariable;
202    temp->size = size;
203    temp->var = var;
204    temp->mode = mode;
205    temp->type = t;
206    temp->callback = cb;
207    COUT(5) << "Syncronisable::registering var with size: " << temp->size << " and type: " << temp->type << std::endl;
208    //std::cout << "push temp to syncList (at the bottom) " << datasize << std::endl;
209    COUT(5) << "Syncronisable::objectID: " << objectID << " this: " << this << " name: " << this->getIdentifier()->getName() << " networkID: " << this->getIdentifier()->getNetworkID() << std::endl;
210    syncList->push_back(temp);
211#ifndef NDEBUG
212    std::list<synchronisableVariable *>::iterator it = syncList->begin();
213    while(it!=syncList->end()){
214      assert(*it!=var);
215      it++;
216    }
217#endif
218  }
219
220  /**
221   * This function takes all SynchronisableVariables out of the Synchronisable and saves them together with the size, objectID and classID to the given memory
222   * takes a pointer to already allocated memory (must have at least getSize bytes length)
223   * structure of the bitstream:
224   * |totalsize,objectID,classID,var1,var2,string1_length,string1,var3,...|
225   * length of varx: size saved int syncvarlist
226   * @param mem pointer to allocated memory with enough size
227   * @param id gamestateid of the gamestate to be saved (important for priorities)
228   * @param mode defines the direction in which the data will be send/received
229   *             0x1: server->client
230   *             0x2: client->server (not recommended)
231   *             0x3: bidirectional
232   * @return true: if !doSync or if everything was successfully saved
233   */
234  bool Synchronisable::getData(uint8_t*& mem, unsigned int id, int mode){
235    //if this tick is we dont synchronise, then abort now
236    if(!doSync(id))
237      return true;
238    //std::cout << "inside getData" << std::endl;
239    unsigned int tempsize = 0;
240    if(mode==0x0)
241      mode=state_;
242    if(classID==0)
243      COUT(3) << "classid 0 " << this->getIdentifier()->getName() << std::endl;
244
245    if (this->classID == (unsigned int)-1)
246        this->classID = this->getIdentifier()->getNetworkID();
247
248    assert(this->classID==this->getIdentifier()->getNetworkID());
249//     this->classID=this->getIdentifier()->getNetworkID(); // TODO: correct this
250    std::list<synchronisableVariable *>::iterator i;
251    unsigned int size;
252    size=getSize(id, mode);
253
254    // start copy header
255    synchronisableHeader *header = (synchronisableHeader *)mem;
256    header->size = size;
257    header->objectID = this->objectID;
258    header->classID = this->classID;
259    header->dataAvailable = true;
260    tempsize+=sizeof(synchronisableHeader);
261    mem+=sizeof(synchronisableHeader);
262    // end copy header
263
264
265    COUT(5) << "Synchronisable getting data from objectID: " << objectID << " classID: " << classID << " length: " << size << std::endl;
266    // copy to location
267    for(i=syncList->begin(); i!=syncList->end(); ++i){
268      if( ((*i)->mode & mode) == 0 ){
269        COUT(5) << "not getting data: " << std::endl;
270        continue;  // this variable should only be received
271      }
272      switch((*i)->type){
273        case DATA:
274          memcpy( (void *)(mem), (void*)((*i)->var), (*i)->size);
275          mem+=(*i)->size;
276          tempsize+=(*i)->size;
277          break;
278        case STRING:
279          memcpy( (void *)(mem), (void *)&((*i)->size), sizeof(int) );
280          mem+=sizeof(int);
281          const char *data = ( ( *(std::string *) (*i)->var).c_str());
282          memcpy( mem, (void*)data, (*i)->size);
283          COUT(5) << "synchronisable: char: " << (const char *)(mem) << " data: " << data << " string: " << *(std::string *)((*i)->var) << std::endl;
284          mem+=(*i)->size;
285          tempsize+=(*i)->size + 4;
286          break;
287      }
288    }
289    assert(tempsize==size);
290    return true;
291  }
292
293
294  /**
295   * This function takes a bytestream and loads the data into the registered variables
296   * @param mem pointer to the bytestream
297   * @param mode same as in getData
298   * @return true/false
299   */
300  bool Synchronisable::updateData(uint8_t*& mem, int mode, bool forceCallback){
301    if(mode==0x0)
302      mode=state_;
303    std::list<synchronisableVariable *>::iterator i;
304    if(syncList->empty()){
305      COUT(4) << "Synchronisable::updateData syncList is empty" << std::endl;
306      return false;
307    }
308
309    uint8_t *data=mem;
310    // start extract header
311    synchronisableHeader *syncHeader = (synchronisableHeader *)mem;
312    assert(syncHeader->objectID==this->objectID);
313    if(syncHeader->dataAvailable==false){
314      mem+=syncHeader->size;
315      return true;
316    }
317
318    mem+=sizeof(synchronisableHeader);
319    // stop extract header
320    assert(this->objectID==syncHeader->objectID);
321//    assert(this->classID==syncHeader->classID); //TODO: fix this!!! maybe a problem with the identifier ?
322
323    COUT(5) << "Synchronisable: objectID " << syncHeader->objectID << ", classID " << syncHeader->classID << " size: " << syncHeader->size << " synchronising data" << std::endl;
324    for(i=syncList->begin(); i!=syncList->end() && mem <= data+syncHeader->size; i++){
325      if( ((*i)->mode ^ mode) == 0 ){
326        COUT(5) << "synchronisable: not updating variable " << std::endl;
327        continue;  // this variable should only be set
328      }
329      COUT(5) << "Synchronisable: element size: " << (*i)->size << " type: " << (*i)->type << std::endl;
330      bool callback=false;
331      switch((*i)->type){
332        case DATA:
333          if((*i)->callback) // check whether this variable changed (but only if callback was set)
334            if(strncmp((char *)(*i)->var, (char *)mem, (*i)->size)!=0)
335              callback=true;
336          memcpy((void*)(*i)->var, mem, (*i)->size);
337          mem+=(*i)->size;
338          break;
339        case STRING:
340          (*i)->size = *(uint32_t *)mem;
341          COUT(5) << "string size: " << (*i)->size << std::endl;
342          mem+=sizeof(int);
343          if((*i)->callback) // check whether this string changed
344            if( *(std::string *)((*i)->var) != std::string((char *)mem) )
345              callback=true;
346          *((std::string *)((*i)->var)) = std::string((const char*)mem);
347          COUT(5) << "synchronisable: char: " << (const char*)mem << " string: " << std::string((const char*)mem) << std::endl;
348          mem += (*i)->size;
349          break;
350      }
351      // call the callback function, if defined
352      if((callback || forceCallback) && (*i)->callback)
353        (*i)->callback->call();
354    }
355    return true;
356  }
357
358  /**
359  * This function returns the total amount of bytes needed by getData to save the whole content of the variables
360  * @param id id of the gamestate
361  * @param mode same as getData
362  * @return amount of bytes
363  */
364  uint32_t Synchronisable::getSize(unsigned int id, int mode){
365    if(!doSync(id))
366      return 0;
367    int tsize=sizeof(synchronisableHeader);
368    if(mode==0x0)
369      mode=state_;
370    std::list<synchronisableVariable *>::iterator i;
371    for(i=syncList->begin(); i!=syncList->end(); i++){
372      if( ((*i)->mode & mode) == 0 )
373        continue;  // this variable should only be received, so dont add its size to the send-size
374      switch((*i)->type){
375      case DATA:
376        tsize+=(*i)->size;
377        break;
378      case STRING:
379        tsize+=sizeof(int);
380        (*i)->size=((std::string *)(*i)->var)->length()+1;
381        COUT(5) << "String size: " << (*i)->size << std::endl;
382        tsize+=(*i)->size;
383        break;
384      }
385    }
386    return tsize;
387  }
388
389  /**
390   * This function determines, wheter the object should be saved to the bytestream (according to its syncmode/direction)
391   * @param id gamestate id
392   * @return true/false
393   */
394  bool Synchronisable::doSync(unsigned int id){
395    return ( (objectMode_&state_)!=0 );
396  }
397
398  bool Synchronisable::doSelection(unsigned int id){
399    return ( id==0 || id%objectFrequency_==objectID%objectFrequency_ ) && ((objectMode_&state_)!=0);
400  }
401
402  /**
403   * This function looks at the header located in the bytestream and checks wheter objectID and classID match with the Synchronisables ones
404   * @param mem pointer to the bytestream
405   */
406  bool Synchronisable::isMyData(uint8_t* mem)
407  {
408    synchronisableHeader *header = (synchronisableHeader *)mem;
409    assert(header->objectID==this->objectID);
410    return header->dataAvailable;
411  }
412
413  /**
414   * This function sets the synchronisation mode of the object
415   * If set to 0x1 variables will only be synchronised to the client
416   * If set to 0x2 variables will only be synchronised to the server
417   * If set to 0x3 variables will be synchronised bidirectionally (only if set so in registerVar)
418   * @param mode same as in registerVar
419   */
420  void Synchronisable::setObjectMode(int mode){
421    assert(mode==0x0 || mode==0x1 || mode==0x2 || mode==0x3);
422    objectMode_=mode;
423  }
424
425
426}
Note: See TracBrowser for help on using the repository browser.