Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/netp3/src/network/packet/Gamestate.cc @ 3045

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

some cleaning up

  • Property svn:eol-style set to native
File size: 15.8 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 *      Oliver Scheuss
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29#include "Gamestate.h"
30#include <enet/enet.h>
31#include <zlib.h>
32#include <cassert>
33#include "../GamestateHandler.h"
34#include "../synchronisable/Synchronisable.h"
35#include "../TrafficControl.h"
36#include "core/GameMode.h"
37#include "core/CoreIncludes.h"
38#include "core/Iterator.h"
39
40
41
42
43namespace orxonox {
44
45namespace packet {
46
47#define GAMESTATE_START(data) (data + GamestateHeader::getSize())
48
49#define PACKET_FLAG_GAMESTATE  ENET_PACKET_FLAG_RELIABLE
50
51
52Gamestate::Gamestate()
53{
54  flags_ = flags_ | PACKET_FLAG_GAMESTATE;
55  header_ = 0;
56}
57
58Gamestate::Gamestate(uint8_t *data, unsigned int clientID):
59    Packet(data, clientID)
60{
61  flags_ = flags_ | PACKET_FLAG_GAMESTATE;
62  header_ = new GamestateHeader(data_);
63}
64
65Gamestate::Gamestate(uint8_t *data)
66{
67  flags_ = flags_ | PACKET_FLAG_GAMESTATE;
68  data_=data;
69  header_ = new GamestateHeader(data_);
70}
71
72Gamestate::Gamestate(const Gamestate& g) :
73    Packet( *(Packet*)&g )
74{
75  flags_ = flags_ | PACKET_FLAG_GAMESTATE;
76  header_ = new GamestateHeader(data_);
77}
78
79
80Gamestate::~Gamestate()
81{
82}
83
84bool Gamestate::collectData(int id, uint8_t mode)
85{
86  assert(this->header_==0); // make sure the header didn't exist before
87  uint32_t tempsize=0, currentsize=0;
88  assert(data_==0);
89  uint32_t size = calcGamestateSize(id, mode);
90
91  COUT(4) << "G.ST.Man: producing gamestate with id: " << id << std::endl;
92  if(size==0)
93    return false;
94  data_ = new uint8_t[size + GamestateHeader::getSize()];
95  if(!data_){
96    COUT(2) << "GameStateManager: could not allocate memory" << std::endl;
97    return false;
98  }
99 
100  // create the header object
101  header_ = new GamestateHeader(data_);
102
103  //start collect data synchronisable by synchronisable
104  uint8_t *mem=data_;
105  mem += GamestateHeader::getSize();
106  ObjectList<Synchronisable>::iterator it;
107  for(it = ObjectList<Synchronisable>::begin(); it; ++it){
108   
109//     tempsize=it->getSize(id, mode);
110
111    tempsize = it->getData(mem, id, mode);
112    if ( tempsize != 0 )
113      dataVector_.push_back( obj(it->getObjectID(), it->getCreatorID(), tempsize, mem-data_) );
114   
115#ifndef NDEBUG
116    if(currentsize+tempsize > size){
117      assert(0); // if we don't use multithreading this part shouldn't be neccessary
118      // start allocate additional memory
119      COUT(3) << "G.St.Man: need additional memory" << std::endl;
120      ObjectList<Synchronisable>::iterator temp = it;
121      uint32_t addsize=tempsize;
122      while(++temp)
123        addsize+=temp->getSize(id, mode);
124      data_ = (uint8_t *)realloc(data_, GamestateHeader::getSize() + currentsize + addsize);
125      if(!data_)
126        return false;
127      size = currentsize+addsize;
128    }// stop allocate additional memory
129#endif
130//     if(!it->getData(mem, id, mode))
131//       return false; // mem pointer gets automatically increased because of call by reference
132    // increase size counter by size of current synchronisable
133    currentsize+=tempsize;
134  }
135
136
137  //start write gamestate header
138  header_->setDataSize( currentsize );
139  header_->setID( id );
140  header_->setDiffed( false );
141  header_->setComplete( true );
142  header_->setCompressed( false );
143  //stop write gamestate header
144
145  COUT(5) << "G.ST.Man: Gamestate size: " << currentsize << std::endl;
146  COUT(5) << "G.ST.Man: 'estimated' (and corrected) Gamestate size: " << size << std::endl;
147  return true;
148}
149
150bool Gamestate::spreadData(uint8_t mode)
151{
152  COUT(4) << "processing gamestate with id " << header_->getID() << endl;
153  assert(data_);
154  assert(!header_->isCompressed());
155  assert(!header_->isDiffed());
156  uint8_t *mem=data_+GamestateHeader::getSize();
157  Synchronisable *s;
158
159  // update the data of the objects we received
160  while(mem < data_+GamestateHeader::getSize()+header_->getDataSize()){
161    SynchronisableHeader objectheader(mem);
162
163    s = Synchronisable::getSynchronisable( objectheader.getObjectID() );
164    if(!s)
165    {
166      if (!GameMode::isMaster())
167      {
168        Synchronisable::fabricate(mem, mode);
169      }
170      else
171      {
172        mem += objectheader.getDataSize();
173      }
174    }
175    else
176    {
177      bool b = s->updateData(mem, mode);
178      assert(b);
179    }
180  }
181   // In debug mode, check first, whether there are no duplicate objectIDs
182#ifndef NDEBUG
183  if(this->getID()%1000==0){
184    std::vector<uint32_t> v1;
185    ObjectList<Synchronisable>::iterator it;
186    for (it = ObjectList<Synchronisable>::begin(); it != ObjectList<Synchronisable>::end(); ++it) {
187      if (it->getObjectID() == OBJECTID_UNKNOWN) {
188        if (it->objectMode_ != 0x0) {
189          COUT(0) << "Found object with OBJECTID_UNKNOWN on the client with objectMode != 0x0!" << std::endl;
190          COUT(0) << "Possible reason for this error: Client created a synchronized object without the Server's approval." << std::endl;
191          COUT(0) << "Objects class: " << it->getIdentifier()->getName() << std::endl;
192          assert(false);
193        }
194      }
195      else {
196        std::vector<uint32_t>::iterator it2;
197        for (it2 = v1.begin(); it2 != v1.end(); ++it2) {
198          if (it->getObjectID() == *it2) {
199            COUT(0) << "Found duplicate objectIDs on the client!" << std::endl
200                    << "Are you sure you don't create a Sychnronisable objcect with 'new' \
201                        that doesn't have objectMode = 0x0?" << std::endl;
202            assert(false);
203          }
204        }
205        v1.push_back(it->getObjectID());
206      }
207    }
208  }
209#endif
210
211  return true;
212}
213
214uint32_t Gamestate::getSize() const
215{
216  assert(data_);
217  if(header_->isCompressed())
218    return header_->getCompSize()+GamestateHeader::getSize();
219  else
220  {
221    return header_->getDataSize()+GamestateHeader::getSize();
222  }
223}
224
225bool Gamestate::operator==(packet::Gamestate gs){
226  uint8_t *d1 = data_+GamestateHeader::getSize();
227  uint8_t *d2 = gs.data_+GamestateHeader::getSize();
228  assert(!isCompressed());
229  assert(!gs.isCompressed());
230  while(d1<data_+header_->getDataSize())
231  {
232    if(*d1!=*d2)
233      return false;
234    d1++;
235    d2++;
236  }
237  return true;
238}
239
240bool Gamestate::process()
241{
242  return GamestateHandler::addGamestate(this, getClientID());
243}
244
245
246
247bool Gamestate::compressData()
248{
249  assert(data_);
250  assert(!header_->isCompressed());
251  uLongf buffer = (uLongf)(((header_->getDataSize() + 12)*1.01)+1);
252  if(buffer==0)
253    return false;
254
255  uint8_t *ndata = new uint8_t[buffer+GamestateHeader::getSize()];
256  uint8_t *dest = ndata + GamestateHeader::getSize();
257  uint8_t *source = data_ + GamestateHeader::getSize();
258  int retval;
259  retval = compress( dest, &buffer, source, (uLong)(header_->getDataSize()) );
260  switch ( retval ) {
261    case Z_OK: COUT(5) << "G.St.Man: compress: successfully compressed" << std::endl; break;
262    case Z_MEM_ERROR: COUT(1) << "G.St.Man: compress: not enough memory available in gamestate.compress" << std::endl; return false;
263    case Z_BUF_ERROR: COUT(2) << "G.St.Man: compress: not enough memory available in the buffer in gamestate.compress" << std::endl; return false;
264    case Z_DATA_ERROR: COUT(2) << "G.St.Man: compress: data corrupted in gamestate.compress" << std::endl; return false;
265  }
266
267  //copy and modify header
268  GamestateHeader *temp = header_;
269  header_ = new GamestateHeader(ndata, temp);
270  delete temp;
271  //delete old data
272  delete[] data_;
273  //save new data
274  data_ = ndata;
275  header_->setCompSize( buffer );
276  header_->setCompressed( true );
277  COUT(5) << "gamestate compress datasize: " << header_->getDataSize() << " compsize: " << header_->getCompSize() << std::endl;
278  return true;
279}
280bool Gamestate::decompressData()
281{
282  assert(data_);
283  assert(header_->isCompressed());
284  COUT(4) << "GameStateClient: uncompressing gamestate. id: " << header_->getID() << ", baseid: " << header_->getBaseID() << ", datasize: " << header_->getDataSize() << ", compsize: " << header_->getCompSize() << std::endl;
285  uint32_t datasize = header_->getDataSize();
286  uint32_t compsize = header_->getCompSize();
287  uint32_t bufsize;
288  bufsize = datasize;
289  assert(bufsize!=0);
290  uint8_t *ndata = new uint8_t[bufsize + GamestateHeader::getSize()];
291  uint8_t *dest = ndata + GamestateHeader::getSize();
292  uint8_t *source = data_ + GamestateHeader::getSize();
293  int retval;
294  uLongf length=bufsize;
295  retval = uncompress( dest, &length, source, (uLong)compsize );
296  switch ( retval ) {
297    case Z_OK: COUT(5) << "successfully decompressed" << std::endl; break;
298    case Z_MEM_ERROR: COUT(1) << "not enough memory available" << std::endl; return false;
299    case Z_BUF_ERROR: COUT(2) << "not enough memory available in the buffer" << std::endl; return false;
300    case Z_DATA_ERROR: COUT(2) << "data corrupted (zlib)" << std::endl; return false;
301  }
302
303  //copy over the header
304  GamestateHeader *temp = header_;
305  header_ = new GamestateHeader( data_, header_ );
306  delete temp;
307
308  if (this->bDataENetAllocated_){
309    // Memory was allocated by ENet. --> We let it be since enet_packet_destroy will
310    // deallocated it anyway. So data and packet stay together.
311    this->bDataENetAllocated_ = false;
312  }
313  else{
314    // We allocated the memory in the first place (unlikely). So we destroy the old data
315    // and overwrite it with the new decompressed data.
316    delete[] this->data_;
317  }
318
319  //set new pointers
320  data_ = ndata;
321  header_->setCompressed( false );
322  assert(header_->getDataSize()==datasize);
323  assert(header_->getCompSize()==compsize);
324  return true;
325}
326
327Gamestate *Gamestate::diff(Gamestate *base)
328{
329  assert(data_);
330  assert(!header_->isCompressed());
331  assert(!header_->isDiffed());
332  GamestateHeader diffHeader(base->data_);
333  uint8_t *basep = GAMESTATE_START(base->data_), *gs = GAMESTATE_START(this->data_);
334  uint32_t of=0; // pointers offset
335  uint32_t dest_length=0;
336  dest_length=header_->getDataSize();
337  if(dest_length==0)
338    return NULL;
339  uint8_t *ndata = new uint8_t[dest_length*sizeof(uint8_t)+GamestateHeader::getSize()];
340  uint8_t *dest = ndata + GamestateHeader::getSize();
341 
342 
343  // LOOP-UNROLLED DIFFING
344  uint32_t *dest32 = (uint32_t*)dest, *base32 = (uint32_t*)basep, *gs32 = (uint32_t*)gs;
345  // diff in 4-byte steps
346  while( of < (uint32_t)(header_->getDataSize())/4 ){
347    if( of < (uint32_t)(diffHeader.getDataSize())/4 )
348    {
349      *(dest32+of)=*(base32+of) ^ *(gs32+of); // do the xor
350      ++of;
351    } else
352    {
353      *(dest32+of)=*(gs32+of); // same as 0 ^ *(gs32+of)
354      ++of;
355    }
356  }
357  uint32_t base_rest = 0;
358  // fill the base_rest first with 0 and then with the remaining bytes in base32
359  switch( diffHeader.getDataSize()%sizeof(uint32_t) )
360  {
361    case 3:
362      *((uint8_t*)(&base_rest)+2) = *((uint8_t*)(base32+of-1)+2); // save the last byte to the buffer
363    case 2:
364      *((uint16_t*)(&base_rest)) = *((uint16_t*)(base32+of-1)); // xor 2 bytes at once (either 2nd and 3rd last or the 2 last bytes)
365      break;
366    case 1:
367      *((uint8_t*)(&base_rest)) = *((uint8_t*)(base32+of-1)); // xor the last byte
368    case 0:
369      break; // leave 0
370  }
371  // now diff the rest and save it to dest32 in 2- and 1-byte steps
372  switch( header_->getDataSize()%sizeof(uint32_t) )
373  {
374    case 3:
375      *((uint8_t*)(dest32+of)+2) = *((uint8_t*)&base_rest+2) ^ *((uint8_t*)(gs32+of-1)+2); // save the last byte to the buffer
376    case 2:
377      *((uint16_t*)(dest32+of)) = *((uint16_t*)&base_rest) ^ *((uint16_t*)(gs32+of-1)); // xor 2 bytes at once (either 2nd and 3rd last or the 2 last bytes)
378      break;
379    case 1:
380      *((uint8_t*)(dest32+of)) = *((uint8_t*)&base_rest) ^ *((uint8_t*)(gs32+of-1)); // xor the last byte
381    case 0:
382      break;
383  }
384
385  Gamestate *g = new Gamestate(ndata, getClientID());
386  *(g->header_) = *header_;
387  g->header_->setDiffed( true );
388  g->header_->setBaseID( base->getID() );
389  g->flags_=flags_;
390  g->packetDirection_ = packetDirection_;
391  return g;
392}
393
394Gamestate* Gamestate::doSelection(unsigned int clientID, unsigned int targetSize){
395  assert(data_);
396  std::vector<obj>::iterator it;
397
398  // allocate memory for new data
399  uint8_t *gdata = new uint8_t[header_->getDataSize()+GamestateHeader::getSize()];
400  // create a gamestate out of it
401  Gamestate *gs = new Gamestate(gdata);
402  uint8_t *newdata = gdata + GamestateHeader::getSize();
403  uint8_t *origdata = GAMESTATE_START(data_);
404
405  //copy the GamestateHeader
406  assert(gs->header_);
407  *(gs->header_) = *header_;
408
409  uint32_t objectOffset;
410  unsigned int objectsize, destsize=0;
411  // TODO: Why is this variable not used?
412  //Synchronisable *object;
413
414  //call TrafficControl
415  TrafficControl::getInstance()->processObjectList( clientID, header_->getID(), dataVector_ );
416
417  //copy in the zeros
418  for(it=dataVector_.begin(); it!=dataVector_.end();){
419    SynchronisableHeader oldobjectheader(origdata);
420    SynchronisableHeader newobjectheader(newdata);
421    if ( (*it).objSize == 0 )
422    {
423      ++it;
424      continue;
425    }
426    objectsize = oldobjectheader.getDataSize();
427    objectOffset=SynchronisableHeader::getSize(); //skip the size and the availableData variables in the objectheader
428    if ( (*it).objID == oldobjectheader.getObjectID() ){
429      memcpy(newdata, origdata, objectsize);
430      assert(newobjectheader.isDataAvailable()==true);
431      ++it;
432    }else{
433      newobjectheader = oldobjectheader;
434      newobjectheader.setDataAvailable(false);
435      memset(newdata+objectOffset, 0, objectsize-objectOffset);
436    }
437    newdata += objectsize;
438    origdata += objectsize;
439    destsize += objectsize;
440  }
441#ifndef NDEBUG
442  uint32_t origsize = destsize;
443  while ( origsize < header_->getDataSize() )
444  {
445    SynchronisableHeader oldobjectheader(origdata);
446    objectsize = oldobjectheader.getDataSize();
447    origdata += objectsize;
448    origsize += objectsize;
449  }
450  assert(origsize==header_->getDataSize());
451  assert(destsize!=0);
452#endif
453  gs->header_->setDataSize( destsize );
454  return gs;
455}
456
457
458Gamestate *Gamestate::undiff(Gamestate *base)
459{
460  assert(this && base);assert(data_);
461  assert(header_->isDiffed());
462  assert(!header_->isCompressed() && !base->header_->isCompressed());
463  uint8_t *basep = GAMESTATE_START(base->data_);
464  uint8_t *gs = GAMESTATE_START(this->data_);
465  uint32_t of=0; // pointers offset
466  uint32_t dest_length=0;
467  dest_length=header_->getDataSize();
468  if(dest_length==0)
469    return NULL;
470  uint8_t *ndata = new uint8_t[dest_length*sizeof(uint8_t)+GamestateHeader::getSize()];
471  uint8_t *dest = ndata + GamestateHeader::getSize();
472  while(of < base->header_->getDataSize() && of < header_->getDataSize()){
473    *(dest+of)=*(basep+of)^*(gs+of); // do the xor
474    ++of;
475  }
476  if(base->header_->getDataSize()!=header_->getDataSize()){
477    uint8_t n=0;
478    if(base->header_->getDataSize() < header_->getDataSize()){
479      while(of < dest_length){
480        *(dest+of)=n^*(gs+of);
481        of++;
482      }
483    }
484  }
485  Gamestate *g = new Gamestate(ndata, getClientID());
486  assert(g->header_);
487  *(g->header_) = *header_;
488  g->header_->setDiffed( false );
489  g->flags_=flags_;
490  g->packetDirection_ = packetDirection_;
491  assert(!g->isDiffed());
492  assert(!g->isCompressed());
493  return g;
494}
495
496
497uint32_t Gamestate::calcGamestateSize(int32_t id, uint8_t mode)
498{
499  uint32_t size=0;
500    // get the start of the Synchronisable list
501  ObjectList<Synchronisable>::iterator it;
502    // get total size of gamestate
503  for(it = ObjectList<Synchronisable>::begin(); it; ++it)
504    size+=it->getSize(id, mode); // size of the actual data of the synchronisable
505  return size;
506}
507
508} //namespace packet
509} //namespace orxonox
Note: See TracBrowser for help on using the repository browser.