Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/lod/src/network/Synchronisable.cc @ 2274

Last change on this file since 2274 was 1907, checked in by scheusso, 16 years ago

merged network branch back to trunk

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