Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/network2/src/libraries/network/synchronisable/Synchronisable.cc @ 6455

Last change on this file since 6455 was 6455, checked in by scheusso, 15 years ago

unregisterVariable reintroduced
some style changes

  • Property svn:eol-style set to native
File size: 14.4 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#include "Synchronisable.h"
32
33#include <cstdlib>
34#include "core/CoreIncludes.h"
35#include "core/GameMode.h"
36#include "core/BaseObject.h"
37#include "network/Host.h"
38
39namespace orxonox
40{
41
42  std::map<uint32_t, Synchronisable *> Synchronisable::objectMap_;
43  std::queue<uint32_t> Synchronisable::deletedObjects_;
44
45  uint8_t Synchronisable::state_=0x1; // detemines wheter we are server (default) or client
46
47  /**
48  * Constructor:
49  * Initializes all Variables and sets the right objectID_
50  */
51  Synchronisable::Synchronisable(BaseObject* creator )
52  {
53    RegisterRootObject(Synchronisable);
54    static uint32_t idCounter=0;
55    objectMode_=0x1; // by default do not send data to server
56    if ( GameMode::isMaster() || ( Host::running() && Host::isServer() ) )
57    {
58      this->setObjectID( idCounter++ );
59    }
60    else
61    {
62      objectID_=OBJECTID_UNKNOWN;
63    }
64    classID_ = static_cast<uint32_t>(-1);
65
66    // set dataSize to 0
67    this->dataSize_ = 0;
68    // set standard priority
69    this->setPriority( Priority::Normal );
70
71    // get creator id
72    if( creator )
73      this->creatorID_ = creator->getSceneID();
74    else
75      this->creatorID_ = OBJECTID_UNKNOWN;
76  }
77
78  /**
79   * Destructor:
80   * Delete all callback objects and remove objectID_ from the objectMap_
81   */
82  Synchronisable::~Synchronisable()
83  {
84    // delete callback function objects
85    if(!Identifier::isCreatingHierarchy()){
86      // remove object from the static objectMap
87      if (this->objectMode_ != 0x0 && (Host::running() && Host::isServer()))
88        deletedObjects_.push(objectID_);
89    }
90    // delete all Synchronisable Variables from syncList_ ( which are also in stringList_ )
91    for(std::vector<SynchronisableVariableBase*>::iterator it = syncList_.begin(); it!=syncList_.end(); it++)
92      delete (*it);
93    syncList_.clear();
94    stringList_.clear();
95    std::map<uint32_t, Synchronisable*>::iterator it;
96    it = objectMap_.find(objectID_);
97    if (it != objectMap_.end())
98      objectMap_.erase(it);
99
100  }
101
102
103  /**
104   * This function sets the internal mode for synchronisation
105   * @param b true if this object is located on a client or on a server
106   */
107  void Synchronisable::setClient(bool b)
108  {
109    if(b) // client
110      state_=0x2;
111    else  // server
112      state_=0x1;
113  }
114
115  /**
116   * This function fabricated a new synchrnisable (and children of it), sets calls updateData and create
117   * After calling this function the mem pointer will be increased by the size of the needed data
118   * @param mem pointer to where the appropriate data is located
119   * @param mode defines the mode, how the data should be loaded
120   * @return pointer to the newly created synchronisable
121   */
122  Synchronisable *Synchronisable::fabricate(uint8_t*& mem, uint8_t mode)
123  {
124    SynchronisableHeader header(mem);
125    assert( !header.isDiffed() );
126
127    COUT(4) << "fabricating object with id: " << header.getObjectID() << std::endl;
128
129    Identifier* id = ClassByID(header.getClassID());
130    if (!id)
131    {
132        for(int i = 0; i<160; i++)
133            COUT(0) << "classid: " << i << " identifier: " << ClassByID(i) << endl;
134        COUT(0) << "Assertion failed: id" << std::endl;
135        COUT(0) << "Possible reason for this error: Client received a synchronizable object whose class has no factory." << std::endl;
136        abort();
137    }
138    assert(id);
139    BaseObject* creator = 0;
140    if (header.getCreatorID() != OBJECTID_UNKNOWN)
141    {
142      Synchronisable* synchronisable_creator = Synchronisable::getSynchronisable(header.getCreatorID());
143      if (!synchronisable_creator)
144      {
145        mem += header.getDataSize()+SynchronisableHeader::getSize(); //.TODO: this suckz.... remove size from header
146        assert(0); // TODO: uncomment this if we have a clean objecthierarchy (with destruction of children of objects) ^^
147        return 0;
148      }
149      else
150        creator = orxonox_cast<BaseObject*>(synchronisable_creator);
151    }
152    assert(getSynchronisable(header.getObjectID())==0);   //make sure no object with this id exists
153    BaseObject *bo = id->fabricate(creator);
154    assert(bo);
155    Synchronisable *no = orxonox_cast<Synchronisable*>(bo);
156    assert(no);
157    assert( Synchronisable::objectMap_.find(header.getObjectID()) == Synchronisable::objectMap_.end() );
158    no->setObjectID(header.getObjectID());
159    //no->creatorID=header.getCreatorID(); //TODO: remove this
160    no->setClassID(header.getClassID());
161    assert(no->creatorID_ == header.getCreatorID());
162    //assert(no->classID_ == header.getClassID());
163    COUT(4) << "fabricate objectID_: " << no->objectID_ << " classID_: " << no->classID_ << std::endl;
164          // update data and create object/entity...
165    bool b = no->updateData(mem, mode, true);
166    assert(b);
167    if (b)
168    {
169//        b = no->create();
170        assert(b);
171    }
172    return no;
173  }
174
175
176  /**
177   * Finds and deletes the Synchronisable with the appropriate objectID_
178   * @param objectID_ objectID_ of the Synchronisable
179   * @return true/false
180   */
181  bool Synchronisable::deleteObject(uint32_t objectID_)
182  {
183    if(!getSynchronisable(objectID_))
184      return false;
185    assert(getSynchronisable(objectID_)->objectID_==objectID_);
186    Synchronisable *s = getSynchronisable(objectID_);
187    if(s)
188      s->destroy(); // or delete?
189    else
190      return false;
191    return true;
192  }
193
194  /**
195   * This function looks up the objectID_ in the objectMap_ and returns a pointer to the right Synchronisable
196   * @param objectID_ objectID_ of the Synchronisable
197   * @return pointer to the Synchronisable with the objectID_
198   */
199  Synchronisable* Synchronisable::getSynchronisable(uint32_t objectID_)
200  {
201    std::map<uint32_t, Synchronisable*>::iterator it1;
202    it1 = objectMap_.find(objectID_);
203    if (it1 != objectMap_.end())
204      return it1->second;
205    // if the objects not in the map it should'nt exist at all anymore
206    return NULL;
207  }
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 !doSync or if everything was successfully saved
223   */
224  uint32_t Synchronisable::getData(uint8_t*& mem, std::vector<uint32_t>& sizes, int32_t id, uint8_t mode)
225  {
226    unsigned int test = 0;
227    if(mode==0x0)
228      mode=state_;
229    //if this tick is we dont synchronise, then abort now
230    if(!doSync(id, mode))
231      return 0;
232    uint32_t tempsize = 0;
233#ifndef NDEBUG
234    uint8_t* oldmem = mem;
235    if (this->classID_==0)
236      COUT(3) << "classid 0 " << this->getIdentifier()->getName() << std::endl;
237#endif
238
239    if (this->classID_ == static_cast<uint32_t>(-1))
240        this->classID_ = this->getIdentifier()->getNetworkID();
241
242    assert(ClassByID(this->classID_));
243    assert(this->classID_==this->getIdentifier()->getNetworkID());
244    assert(this->objectID_!=OBJECTID_UNKNOWN);
245    std::vector<SynchronisableVariableBase*>::iterator i;
246
247    // start copy header
248    SynchronisableHeader header(mem);
249    mem += SynchronisableHeader::getSize();
250    // end copy header
251
252    CCOUT(5) << "getting data from objectID_: " << objectID_ << ", classID_: " << classID_ << std::endl;
253//     COUT(4) << "objectid: " << this->objectID_ << ":";
254    // copy to location
255    for(i=syncList_.begin(); i!=syncList_.end(); ++i)
256    {
257      uint32_t varsize = (*i)->getData( mem, mode );
258//       COUT(4) << " " << varsize;
259      tempsize += varsize;
260      sizes.push_back(varsize);
261      ++test;
262      //tempsize += (*i)->getSize( mode );
263    }
264//     COUT(4) << endl;
265
266    header.setObjectID( this->objectID_ );
267    header.setCreatorID( this->creatorID_ );
268    header.setClassID( this->classID_ );
269    header.setDataSize( tempsize );
270    assert( tempsize == mem-oldmem-SynchronisableHeader::getSize() );
271    assert( test == this->getNrOfVariables() );
272    header.setDiffed(false);
273    tempsize += SynchronisableHeader::getSize();
274
275#ifndef NDEBUG
276    uint32_t size;
277    size=getSize(id, mode);
278    assert(tempsize==size);
279#endif
280    return tempsize;
281  }
282
283
284  /**
285   * This function takes a bytestream and loads the data into the registered variables
286   * @param mem pointer to the bytestream
287   * @param mode same as in getData
288   * @return true/false
289   */
290  bool Synchronisable::updateData(uint8_t*& mem, uint8_t mode, bool forceCallback)
291  {
292    if(mode==0x0)
293      mode=state_;
294    if(syncList_.empty())
295    {
296      assert(0);
297      COUT(2) << "Synchronisable::updateData syncList_ is empty" << std::endl;
298      return false;
299    }
300
301    uint8_t* data=mem;
302    // start extract header
303    SynchronisableHeaderLight syncHeaderLight(mem);
304    assert(syncHeaderLight.getObjectID()==this->getObjectID());
305
306    //COUT(5) << "Synchronisable: objectID_ " << syncHeader.getObjectID() << ", classID_ " << syncHeader.getClassID() << " size: " << syncHeader.getDataSize() << " synchronising data" << std::endl;
307    if( !syncHeaderLight.isDiffed() )
308    {
309      SynchronisableHeader syncHeader2(mem);
310      assert( this->getClassID() == syncHeader2.getClassID() );
311      assert( this->getCreatorID() == syncHeader2.getCreatorID() );
312      mem += SynchronisableHeader::getSize();
313      std::vector<SynchronisableVariableBase *>::iterator i;
314      for(i=syncList_.begin(); i!=syncList_.end(); i++)
315      {
316        assert( mem <= data+syncHeader2.getDataSize()+SynchronisableHeader::getSize() ); // always make sure we don't exceed the datasize in our stream
317        (*i)->putData( mem, mode, forceCallback );
318      }
319      assert(mem == data+syncHeaderLight.getDataSize()+SynchronisableHeader::getSize() );
320    }
321    else
322    {
323      mem += SynchronisableHeaderLight::getSize();
324//       COUT(0) << "objectID: " << this->objectID_ << endl;
325      while( mem < data+syncHeaderLight.getDataSize()+SynchronisableHeaderLight::getSize() )
326      {
327        VariableID varID = *(VariableID*)mem;
328//         COUT(0) << "varID: " << varID << endl;
329        assert( varID < syncList_.size() );
330        mem += sizeof(VariableID);
331        syncList_[varID]->putData( mem, mode, forceCallback );
332      }
333      assert(mem == data+syncHeaderLight.getDataSize()+SynchronisableHeaderLight::getSize() );
334    }
335    return true;
336  }
337
338  /**
339  * This function returns the total amount of bytes needed by getData to save the whole content of the variables
340  * @param id id of the gamestate
341  * @param mode same as getData
342  * @return amount of bytes
343  */
344  uint32_t Synchronisable::getSize(int32_t id, uint8_t mode)
345  {
346    uint32_t tsize=SynchronisableHeader::getSize();
347    if (mode==0x0)
348      mode=state_;
349    if (!doSync(id, mode))
350      return 0;
351    assert( mode==state_ );
352    tsize += this->dataSize_;
353    std::vector<SynchronisableVariableBase*>::iterator i;
354    for(i=stringList_.begin(); i!=stringList_.end(); ++i)
355    {
356      tsize += (*i)->getSize( mode );
357    }
358    return tsize;
359  }
360
361  /**
362   * This function determines, wheter the object should be saved to the bytestream (according to its syncmode/direction)
363   * @param id gamestate id
364   * @return true/false
365   */
366  bool Synchronisable::doSync(int32_t id, uint8_t mode)
367  {
368    if(mode==0x0)
369      mode=state_;
370    return ( (this->objectMode_ & mode)!=0 && (!syncList_.empty() ) );
371  }
372
373  /**
374   * This function sets the synchronisation mode of the object
375   * If set to 0x0 variables will not be synchronised at all
376   * If set to 0x1 variables will only be synchronised to the client
377   * If set to 0x2 variables will only be synchronised to the server
378   * If set to 0x3 variables will be synchronised bidirectionally (only if set so in registerVar)
379   * @param mode same as in registerVar
380   */
381  void Synchronisable::setSyncMode(uint8_t mode)
382  {
383    assert(mode==0x0 || mode==0x1 || mode==0x2 || mode==0x3);
384    this->objectMode_=mode;
385  }
386
387  template <> void Synchronisable::registerVariable( std::string& variable, uint8_t mode, NetworkCallbackBase *cb, bool bidirectional)
388  {
389    SynchronisableVariableBase* sv;
390    if (bidirectional)
391      sv = new SynchronisableVariableBidirectional<std::string>(variable, mode, cb);
392    else
393      sv = new SynchronisableVariable<std::string>(variable, mode, cb);
394    syncList_.push_back(sv);
395    stringList_.push_back(sv);
396  }
397
398template <> void Synchronisable::unregisterVariable( std::string& variable )
399  {
400    bool unregistered_nonexistent_variable = true;
401    std::vector<SynchronisableVariableBase*>::iterator it = syncList_.begin();
402    while(it!=syncList_.end())
403    {
404      if( ((*it)->getReference()) == &variable )
405      {
406        delete (*it);
407        syncList_.erase(it);
408        unregistered_nonexistent_variable = false;
409        break;
410      }
411      else
412        ++it;
413    }
414    assert(unregistered_nonexistent_variable == false);
415   
416    it = stringList_.begin();
417    while(it!=stringList_.end())
418    {
419      if( ((*it)->getReference()) == &variable )
420      {
421        delete (*it);
422        stringList_.erase(it);
423        return;
424      }
425      else
426        ++it;
427    }
428    unregistered_nonexistent_variable = true;
429    assert(unregistered_nonexistent_variable == false); //if we reach this point something went wrong:
430    // the variable has not been registered before
431  }
432
433
434}
Note: See TracBrowser for help on using the repository browser.