Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 6450 was 6450, checked in by scheusso, 14 years ago

further traffic reduction:

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