Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/network/src/network/Synchronisable.cc @ 1834

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

Fix in Projectiles (network fix)
different improvements in synchronisable and gamestates

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