Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/lib/network/network_stream.cc @ 9247

Last change on this file since 9247 was 9246, checked in by patrick, 18 years ago

some network comments

File size: 23.8 KB
RevLine 
[5566]1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11### File Specific:
[9246]12   main-programmer: Christoph Renner rennerc@ee.ethz.ch
13   co-programmer:   Patrick Boenzli  boenzlip@orxonox.ethz.ch
[5566]14*/
15
16
17#define DEBUG_MODULE_NETWORK
18
[5747]19
[5647]20#include "base_object.h"
[5731]21#include "network_protocol.h"
[7954]22#include "udp_socket.h"
23#include "udp_server_socket.h"
[5647]24#include "connection_monitor.h"
25#include "synchronizeable.h"
[6341]26#include "network_game_manager.h"
[6959]27#include "shared_network_data.h"
[7954]28#include "message_manager.h"
29#include "preferences.h"
30#include "zip.h"
[6341]31
[7954]32#include "src/lib/util/loading/resource_manager.h"
33
34#include "network_log.h"
35
[9235]36#include "player_stats.h"
[7954]37
38#include "lib/util/loading/factory.h"
39
[5649]40#include "debug.h"
[6139]41#include "class_list.h"
[6144]42#include <algorithm>
[5647]43
[5566]44/* include your own header */
45#include "network_stream.h"
46
[5595]47/* probably unnecessary */
[5594]48using namespace std;
49
[5595]50
[5747]51#define PACKAGE_SIZE  256
[5647]52
[5747]53
[5800]54NetworkStream::NetworkStream()
[5996]55    : DataStream()
[5647]56{
57  this->init();
[5648]58  /* initialize the references */
[5996]59  this->type = NET_CLIENT;
[5647]60}
61
[6695]62
[9246]63/**
64 * connect to a server as a client
65 *  @param host: host name (address)
66 *  @param port: port number
67 */
[7954]68NetworkStream::NetworkStream( std::string host, int port )
[5996]69{
[6139]70  this->type = NET_CLIENT;
[5996]71  this->init();
[7954]72  this->peers[0].socket = new UdpSocket( host, port );
73  this->peers[0].userId = 0;
74  this->peers[0].isServer = true;
75  this->peers[0].connectionMonitor = new ConnectionMonitor( 0 );
[5996]76}
77
78
[9246]79/**
80 * start as a server
81 *  @param port: at this port
82 */
[7954]83NetworkStream::NetworkStream( int port )
[5647]84{
[6139]85  this->type = NET_SERVER;
[5647]86  this->init();
[7954]87  this->serverSocket = new UdpServerSocket(port);
[5996]88  this->bActive = true;
[5649]89}
90
91
[9246]92/**
93 * generic init functions
94 */
[5647]95void NetworkStream::init()
96{
97  /* set the class id for the base object */
98  this->setClassID(CL_NETWORK_STREAM, "NetworkStream");
[5996]99  this->bActive = false;
[6139]100  this->serverSocket = NULL;
[6341]101  this->networkGameManager = NULL;
[6139]102  myHostId = 0;
[7954]103  currentState = 0;
[9246]104
[7954]105  remainingBytesToWriteToDict = Preferences::getInstance()->getInt( "compression", "writedict", 0 );
[9246]106
[8623]107  assert( Zip::getInstance()->loadDictionary( "testdict" ) >= 0 );
108  this->dictClient = Zip::getInstance()->loadDictionary( "dict2pl_client" );
109  assert( this->dictClient >= 0 );
110  this->dictServer = Zip::getInstance()->loadDictionary( "dict2p_server" );
111  assert( this->dictServer >= 0 );
[5594]112}
113
[5647]114
[9246]115/**
116 * deconstructor
117 */
[5566]118NetworkStream::~NetworkStream()
[5598]119{
[6139]120  if ( this->serverSocket )
121  {
122    serverSocket->close();
123    delete serverSocket;
[8228]124    serverSocket = NULL;
[6139]125  }
[7954]126  for ( PeerList::iterator i = peers.begin(); i!=peers.end(); i++)
[6139]127  {
[7954]128    if ( i->second.socket )
[6139]129    {
[7954]130      i->second.socket->disconnectServer();
131      delete i->second.socket;
132      i->second.socket = NULL;
[6139]133    }
[9246]134
[7954]135    if ( i->second.handshake )
[6139]136    {
[7954]137      delete i->second.handshake;
138      i->second.handshake = NULL;
[6139]139    }
[9246]140
[8623]141    if ( i->second.connectionMonitor )
142    {
143      delete i->second.connectionMonitor;
144      i->second.connectionMonitor = NULL;
145    }
[6139]146  }
[8228]147  for ( SynchronizeableList::const_iterator it = getSyncBegin(); it != getSyncEnd(); it ++ )
148    (*it)->setNetworkStream( NULL );
[5598]149}
150
[5996]151
[9246]152/**
153 * creates a new instance of the network game manager
154 */
[6695]155void NetworkStream::createNetworkGameManager()
156{
157  this->networkGameManager = NetworkGameManager::getInstance();
158  // setUniqueID( maxCon+2 ) because we need one id for every handshake
159  // and one for handshake to reject client maxCon+1
[7954]160  this->networkGameManager->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
161  MessageManager::getInstance()->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
[6695]162}
163
164
[9246]165/**
166 * starts the network handshake
167 */
[6695]168void NetworkStream::startHandshake()
169{
170  Handshake* hs = new Handshake(false);
171  hs->setUniqueID( 0 );
[7954]172  assert( peers[0].handshake == NULL );
173  peers[0].handshake = hs;
[9246]174
[9235]175  hs->setPreferedNickName( Preferences::getInstance()->getString( "multiplayer", "nickname", "Player" ) );
[9246]176
[7954]177//   peers[0].handshake->setSynchronized( true );
[6695]178  //this->connectSynchronizeable(*hs);
[7954]179  //this->connectSynchronizeable(*hs);
180  PRINTF(0)("NetworkStream: Handshake created: %s\n", hs->getName());
[6695]181}
182
183
[9246]184/**
185 * this functions connects a synchronizeable to the networkstream, therefore synchronizeing
186 * it all over the network and creating it on the other platforms (if and only if it is a
187 * server
188 */
[5996]189void NetworkStream::connectSynchronizeable(Synchronizeable& sync)
190{
[6139]191  this->synchronizeables.push_back(&sync);
192  sync.setNetworkStream( this );
193
[7954]194  this->bActive = true;
[5996]195}
196
[6695]197
[9246]198/**
199 * removes the synchronizeable from the list of synchronized entities
200 */
[6139]201void NetworkStream::disconnectSynchronizeable(Synchronizeable& sync)
202{
[6144]203  // removing the Synchronizeable from the List.
204  std::list<Synchronizeable*>::iterator disconnectSynchro = std::find(this->synchronizeables.begin(), this->synchronizeables.end(), &sync);
205  if (disconnectSynchro != this->synchronizeables.end())
206    this->synchronizeables.erase(disconnectSynchro);
[9246]207
[7954]208  oldSynchronizeables[sync.getUniqueID()] = SDL_GetTicks();
[6139]209}
210
211
[9246]212/**
213 * this is called to process data from the network socket to the synchronizeable and vice versa
214 */
[5604]215void NetworkStream::processData()
216{
[8068]217  int tick = SDL_GetTicks();
[9246]218
[7954]219  currentState++;
[9246]220
[6139]221  if ( this->type == NET_SERVER )
[7954]222  {
223    if ( serverSocket )
224      serverSocket->update();
[9246]225
[6139]226    this->updateConnectionList();
[7954]227  }
[6139]228  else
229  {
[9246]230    // check if the connection is ok else terminate and remove
[7954]231    if ( peers[0].socket && ( !peers[0].socket->isOk() || peers[0].connectionMonitor->hasTimedOut() ) )
[6139]232    {
233      PRINTF(1)("lost connection to server\n");
[5741]234
[7954]235      peers[0].socket->disconnectServer();
236      delete peers[0].socket;
237      peers[0].socket = NULL;
[6498]238
[7954]239      if ( peers[0].handshake )
240        delete peers[0].handshake;
241      peers[0].handshake = NULL;
[9246]242
[8623]243      if ( peers[0].connectionMonitor )
244        delete peers[0].connectionMonitor;
245      peers[0].connectionMonitor = NULL;
[6139]246    }
247  }
248
[7954]249  cleanUpOldSyncList();
250  handleHandshakes();
[9246]251
[7954]252  // order of up/downstream is important!!!!
253  // don't change it
[8068]254  handleDownstream( tick );
255  handleUpstream( tick );
[7954]256}
257
[9246]258
259/**
260 * if we are a server update the connection list to accept new connections (clients)
261 * also start the handsake for the new clients
262 */
[7954]263void NetworkStream::updateConnectionList( )
264{
265  //check for new connections
266
267  NetworkSocket* tempNetworkSocket = serverSocket->getNewSocket();
268
[9246]269  // we got new network node
[7954]270  if ( tempNetworkSocket )
[6139]271  {
[7954]272    int clientId;
[9246]273    // if there is a list of free client id slots, take these
274    if ( freeSocketSlots.size() > 0 )
[6139]275    {
[7954]276      clientId = freeSocketSlots.back();
277      freeSocketSlots.pop_back();
278      peers[clientId].socket = tempNetworkSocket;
279      peers[clientId].handshake = new Handshake(true, clientId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID() );
280      peers[clientId].connectionMonitor = new ConnectionMonitor( clientId );
281      peers[clientId].handshake->setUniqueID(clientId);
282      peers[clientId].userId = clientId;
283      peers[clientId].isServer = false;
[9246]284    }
285    else
[7954]286    {
287      clientId = 1;
[9246]288
[7954]289      for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
290        if ( it->first >= clientId )
291          clientId = it->first + 1;
[9246]292
[7954]293      peers[clientId].socket = tempNetworkSocket;
294      peers[clientId].handshake = new Handshake(true, clientId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID());
295      peers[clientId].handshake->setUniqueID(clientId);
296      peers[clientId].connectionMonitor = new ConnectionMonitor( clientId );
297      peers[clientId].userId = clientId;
298      peers[clientId].isServer = false;
[9246]299
[7954]300      PRINTF(0)("num sync: %d\n", synchronizeables.size());
301    }
[6341]302
[9246]303    // check if there are too many clients connected
[7954]304    if ( clientId > MAX_CONNECTIONS )
305    {
306      peers[clientId].handshake->doReject( "too many connections" );
307      PRINTF(0)("Will reject client %d because there are to many connections!\n", clientId);
308    }
309    else
[9246]310    {
311      PRINTF(0)("New Client: %d\n", clientId);
312    }
[6498]313
[7954]314    //this->connectSynchronizeable(*handshakes[clientId]);
315  }
[6341]316
[9246]317
318
[7954]319  //check if connections are ok else remove them
[8228]320  for ( PeerList::iterator it = peers.begin(); it != peers.end(); )
[7954]321  {
[9246]322    if (
[7954]323          it->second.socket &&
[9246]324          (
[7954]325            !it->second.socket->isOk()  ||
326            it->second.connectionMonitor->hasTimedOut()
327          )
328       )
329    {
330      std::string reason = "disconnected";
331      if ( it->second.connectionMonitor->hasTimedOut() )
332        reason = "timeout";
333      PRINTF(0)("Client is gone: %d (%s)\n", it->second.userId, reason.c_str());
334
[9246]335
336      // clean up the network data
[7954]337      it->second.socket->disconnectServer();
338      delete it->second.socket;
339      it->second.socket = NULL;
340
[8623]341      if ( it->second.connectionMonitor )
342        delete it->second.connectionMonitor;
343      it->second.connectionMonitor = NULL;
[9246]344
[7954]345      if ( it->second.handshake )
346        delete it->second.handshake;
347      it->second.handshake = NULL;
[9246]348
[7954]349      for ( SynchronizeableList::iterator it2 = synchronizeables.begin(); it2 != synchronizeables.end(); it2++ )
350      {
351        (*it2)->cleanUpUser( it->second.userId );
[6139]352      }
[7954]353
354      NetworkGameManager::getInstance()->signalLeftPlayer(it->second.userId);
355
356      freeSocketSlots.push_back( it->second.userId );
[9246]357
[8228]358      PeerList::iterator delit = it;
359      it++;
[9246]360
[8228]361      peers.erase( delit );
[9246]362
[8228]363      continue;
[6139]364    }
[9246]365
[8228]366    it++;
[6139]367  }
368
369
[7954]370}
[5800]371
[9246]372
[7954]373void NetworkStream::debug()
374{
375  if( this->isServer())
376    PRINT(0)(" Host ist Server with ID: %i\n", this->myHostId);
377  else
378    PRINT(0)(" Host ist Client with ID: %i\n", this->myHostId);
[6695]379
[7954]380  PRINT(0)(" Got %i connected Synchronizeables, showing active Syncs:\n", this->synchronizeables.size());
[6139]381  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
[5996]382  {
[7954]383    if( (*it)->beSynchronized() == true)
384      PRINT(0)("  Synchronizeable of class: %s::%s, with unique ID: %i, Synchronize: %i\n", (*it)->getClassName(), (*it)->getName(),
385               (*it)->getUniqueID(), (*it)->beSynchronized());
386  }
387  PRINT(0)(" Maximal Connections: %i\n", MAX_CONNECTIONS );
[6959]388
[7954]389}
[6959]390
391
[9246]392/**
393 * @returns the number of synchronizeables registered to this stream
394 */
[7954]395int NetworkStream::getSyncCount()
396{
397  int n = 0;
398  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
399    if( (*it)->beSynchronized() == true)
400      ++n;
[5730]401
[7954]402  //return synchronizeables.size();
403  return n;
404}
[6139]405
[9246]406
[7954]407/**
[9246]408 * check if handshakes completed. if so create the network game manager else remove it again
[7954]409 */
410void NetworkStream::handleHandshakes( )
411{
412  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
413  {
414    if ( it->second.handshake )
415    {
416      if ( it->second.handshake->completed() )
417      {
418        if ( it->second.handshake->ok() )
[6341]419        {
[7954]420          if ( !it->second.handshake->allowDel() )
[6139]421          {
[7954]422            if ( type != NET_SERVER )
[6868]423            {
[7954]424              SharedNetworkData::getInstance()->setHostID( it->second.handshake->getHostId() );
425              myHostId = SharedNetworkData::getInstance()->getHostID();
426
427              this->networkGameManager = NetworkGameManager::getInstance();
428              this->networkGameManager->setUniqueID( it->second.handshake->getNetworkGameManagerId() );
429              MessageManager::getInstance()->setUniqueID( it->second.handshake->getMessageManagerId() );
[6868]430            }
[7954]431
[9246]432
[7954]433            PRINT(0)("handshake finished id=%d\n", it->second.handshake->getNetworkGameManagerId());
434
435            it->second.handshake->del();
[6139]436          }
437          else
438          {
[7954]439            if ( it->second.handshake->canDel() )
[6868]440            {
[7954]441              if ( type == NET_SERVER )
442              {
443                handleNewClient( it->second.userId );
[9246]444
[9235]445                if ( PlayerStats::getStats( it->second.userId ) && it->second.handshake->getPreferedNickName() != "" )
446                {
447                  PlayerStats::getStats( it->second.userId )->setNickName( it->second.handshake->getPreferedNickName() );
448                }
[7954]449              }
[9246]450
[7954]451              PRINT(0)("handshake finished delete it\n");
452              delete it->second.handshake;
453              it->second.handshake = NULL;
[6868]454            }
[6139]455          }
[7954]456
[6139]457        }
458        else
459        {
[7954]460          PRINT(1)("handshake failed!\n");
461          it->second.socket->disconnectServer();
[6139]462        }
[7954]463      }
[6139]464    }
[5996]465  }
[7954]466}
[5741]467
[9246]468
[7954]469/**
470 * handle upstream network traffic
471 */
[8068]472void NetworkStream::handleUpstream( int tick )
[7954]473{
474  int offset;
475  int n;
[9246]476
[8068]477  for ( PeerList::reverse_iterator peer = peers.rbegin(); peer != peers.rend(); peer++ )
[5802]478  {
[9246]479    offset = INTSIZE; // reserve enough space for the packet length
480
481    // continue with the next peer if this peer has no socket assigned (therefore no network)
[7954]482    if ( !peer->second.socket )
483      continue;
[9246]484
485    // header informations: current state
[7954]486    n = Converter::intToByteArray( currentState, buf + offset, UDP_PACKET_SIZE - offset );
487    assert( n == INTSIZE );
488    offset += n;
[9246]489
490    // header informations: last acked state
[7954]491    n = Converter::intToByteArray( peer->second.lastAckedState, buf + offset, UDP_PACKET_SIZE - offset );
492    assert( n == INTSIZE );
493    offset += n;
[9246]494
495    // header informations: last recved state
[7954]496    n = Converter::intToByteArray( peer->second.lastRecvedState, buf + offset, UDP_PACKET_SIZE - offset );
497    assert( n == INTSIZE );
498    offset += n;
[9246]499
500    // now write all synchronizeables in the packet
[7954]501    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
[5810]502    {
[7954]503      int oldOffset = offset;
504      Synchronizeable & sync = **it;
[9246]505
506      // do not include synchronizeables with uninit id and syncs that don't want to be synchronized
[7954]507      if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
508        continue;
[5730]509
[9246]510      // if handshake not finished only sync handshake
[7954]511      if ( peer->second.handshake && sync.getLeafClassID() != CL_HANDSHAKE )
512        continue;
[9246]513
514      // if we are a server and this is not our handshake
[7954]515      if ( isServer() && sync.getLeafClassID() == CL_HANDSHAKE && sync.getUniqueID() != peer->second.userId )
516        continue;
[9246]517
518      /* list of synchronizeables that will never be synchronized over the network: */
519      // do not sync null parent
[7954]520      if ( sync.getLeafClassID() == CL_NULL_PARENT )
521        continue;
[6139]522
[7954]523      assert( offset + INTSIZE <= UDP_PACKET_SIZE );
[9246]524
525      // server fakes uniqueid == 0 for handshake
[7954]526      if ( this->isServer() && sync.getUniqueID() < MAX_CONNECTIONS - 1 )
527        n = Converter::intToByteArray( 0, buf + offset, UDP_PACKET_SIZE - offset );
528      else
529        n = Converter::intToByteArray( sync.getUniqueID(), buf + offset, UDP_PACKET_SIZE - offset );
[9246]530
[7954]531      assert( n == INTSIZE );
532      offset += n;
[9246]533
534      // make space for size
[7954]535      offset += INTSIZE;
[6139]536
[7954]537      n = sync.getStateDiff( peer->second.userId, buf + offset, UDP_PACKET_SIZE-offset, currentState, peer->second.lastAckedState, -1000 );
538      offset += n;
[9246]539
[7954]540      assert( Converter::intToByteArray( n, buf + offset - n - INTSIZE, INTSIZE ) == INTSIZE );
[6341]541
[9246]542      // check if all data bytes == 0 -> remove data and the synchronizeable from the sync process since there is no update
543      // TODO not all synchronizeables like this maybe add Synchronizeable::canRemoveZeroDiff()
544      bool allZero = true;
545      for ( int i = 0; i < n; i++ )
546      {
547         if ( buf[i+oldOffset+2*INTSIZE] != 0 )
548           allZero = false;
549      }
550      // if there is no new data in this synchronizeable reset the data offset to the last state -> dont synchronizes
551      // data that hast not changed
552      if ( allZero )
553      {
554        offset = oldOffset;
555      }
556    } // all synchronizeables written
[6139]557
[9246]558
559
[7954]560    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
561    {
562      Synchronizeable & sync = **it;
[9246]563
[7954]564      if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
565        continue;
[9246]566
[7954]567      sync.handleSentState( peer->second.userId, currentState, peer->second.lastAckedState );
568    }
[9246]569
570
[7954]571    assert( Converter::intToByteArray( offset, buf, INTSIZE ) == INTSIZE );
[9246]572
573    // now compress the data with the zip library
[8623]574    int compLength = 0;
575    if ( this->isServer() )
576      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictServer );
577    else
578      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictClient );
[9246]579
[8623]580    if ( compLength <= 0 )
[7954]581    {
582      PRINTF(1)("compression failed!\n");
583      continue;
584    }
[9246]585
[7954]586    assert( peer->second.socket->writePacket( compBuf, compLength ) );
[9246]587
[7954]588    if ( this->remainingBytesToWriteToDict > 0 )
[8623]589      writeToNewDict( buf, offset, true );
[9246]590
[8068]591    peer->second.connectionMonitor->processUnzippedOutgoingPacket( tick, buf, offset, currentState );
592    peer->second.connectionMonitor->processZippedOutgoingPacket( tick, compBuf, compLength, currentState );
[9246]593
[5810]594  }
[6139]595}
596
[7954]597/**
598 * handle downstream network traffic
599 */
[8068]600void NetworkStream::handleDownstream( int tick )
[6139]601{
[7954]602  int offset = 0;
[9246]603
[7954]604  int length = 0;
605  int packetLength = 0;
606  int compLength = 0;
607  int uniqueId = 0;
608  int state = 0;
609  int ackedState = 0;
610  int fromState = 0;
611  int syncDataLength = 0;
[9246]612
[7954]613  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
[5810]614  {
[9246]615
[7954]616    if ( !peer->second.socket )
617      continue;
[5730]618
[7954]619    while ( 0 < (compLength = peer->second.socket->readPacket( compBuf, UDP_PACKET_SIZE )) )
[6139]620    {
[8068]621      peer->second.connectionMonitor->processZippedIncomingPacket( tick, compBuf, compLength );
[9246]622
[7954]623      packetLength = Zip::getInstance()->unZip( compBuf, compLength, buf, UDP_PACKET_SIZE );
[8623]624
[7954]625      if ( packetLength < 4*INTSIZE )
626      {
627        if ( packetLength != 0 )
628          PRINTF(1)("got too small packet: %d\n", packetLength);
629        continue;
630      }
[9246]631
[7954]632      if ( this->remainingBytesToWriteToDict > 0 )
[8623]633        writeToNewDict( buf, packetLength, false );
[9246]634
[7954]635      assert( Converter::byteArrayToInt( buf, &length ) == INTSIZE );
636      assert( Converter::byteArrayToInt( buf + INTSIZE, &state ) == INTSIZE );
637      assert( Converter::byteArrayToInt( buf + 2*INTSIZE, &fromState ) == INTSIZE );
638      assert( Converter::byteArrayToInt( buf + 3*INTSIZE, &ackedState ) == INTSIZE );
639      //NETPRINTF(n)("ackedstate: %d\n", ackedState);
640      offset = 4*INTSIZE;
[9246]641
[8623]642      peer->second.connectionMonitor->processUnzippedIncomingPacket( tick, buf, packetLength, state, ackedState );
[6139]643
[7954]644      //NETPRINTF(n)("got packet: %d, %d\n", length, packetLength);
[9246]645
[7954]646    //if this is an old state drop it
647      if ( state <= peer->second.lastRecvedState )
648        continue;
[9246]649
[7954]650      if ( packetLength != length )
651      {
652        PRINTF(1)("real packet length (%d) and transmitted packet length (%d) do not match!\n", packetLength, length);
653        peer->second.socket->disconnectServer();
654        continue;
655      }
[9246]656
[7954]657      while ( offset + 2*INTSIZE < length )
658      {
659        assert( offset > 0 );
660        assert( Converter::byteArrayToInt( buf + offset, &uniqueId ) == INTSIZE );
661        offset += INTSIZE;
[9246]662
[7954]663        assert( Converter::byteArrayToInt( buf + offset, &syncDataLength ) == INTSIZE );
664        offset += INTSIZE;
[9246]665
[7954]666        assert( syncDataLength > 0 );
667        assert( syncDataLength < 10000 );
[9246]668
[7954]669        Synchronizeable * sync = NULL;
[9246]670
[7954]671        for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
[9246]672        {
[7954]673        //                                        client thinks his handshake has id 0!!!!!
674          if ( (*it)->getUniqueID() == uniqueId || ( uniqueId == 0 && (*it)->getUniqueID() == peer->second.userId ) )
675          {
676            sync = *it;
677            break;
678          }
679        }
[9246]680
[7954]681        if ( sync == NULL )
682        {
683          PRINTF(0)("could not find sync with id %d. try to create it\n", uniqueId);
684          if ( oldSynchronizeables.find( uniqueId ) != oldSynchronizeables.end() )
685          {
686            offset += syncDataLength;
687            continue;
688          }
[9246]689
[7954]690          if ( !peers[peer->second.userId].isServer )
691          {
692            offset += syncDataLength;
693            continue;
694          }
[9246]695
[7954]696          int leafClassId;
697          if ( INTSIZE > length - offset )
698          {
699            offset += syncDataLength;
700            continue;
701          }
[6139]702
[7954]703          Converter::byteArrayToInt( buf + offset, &leafClassId );
[9246]704
[7954]705          assert( leafClassId != 0 );
[9246]706
[7954]707          BaseObject * b = NULL;
708          /* These are some small exeptions in creation: Not all objects can/should be created via Factory */
709          /* Exception 1: NullParent */
710          if( leafClassId == CL_NULL_PARENT || leafClassId == CL_SYNCHRONIZEABLE || leafClassId == CL_NETWORK_GAME_MANAGER )
711          {
712            PRINTF(1)("Can not create Class with ID %x!\n", (int)leafClassId);
713            offset += syncDataLength;
714            continue;
715          }
716          else
717            b = Factory::fabricate( (ClassID)leafClassId );
[5800]718
[7954]719          if ( !b )
720          {
721            PRINTF(1)("Could not fabricate Object with classID %x\n", leafClassId);
722            offset += syncDataLength;
723            continue;
724          }
[5809]725
[7954]726          if ( b->isA(CL_SYNCHRONIZEABLE) )
727          {
728            sync = dynamic_cast<Synchronizeable*>(b);
729            sync->setUniqueID( uniqueId );
730            sync->setSynchronized(true);
[9246]731
[7954]732            PRINTF(0)("Fabricated %s with id %d\n", sync->getClassName(), sync->getUniqueID());
733          }
734          else
735          {
736            PRINTF(1)("Class with ID %x is not a synchronizeable!\n", (int)leafClassId);
737            delete b;
738            offset += syncDataLength;
739            continue;
740          }
741        }
[6139]742
[9246]743
744        int n = sync->setStateDiff( peer->second.userId, buf+offset, syncDataLength, state, fromState );
[7954]745        offset += n;
746        //NETPRINTF(0)("SSSSSEEEEETTTTT: %s %d\n",sync->getClassName(), n);
[6498]747
[7954]748      }
[9246]749
[7954]750      if ( offset != length )
[6139]751      {
[7954]752        PRINTF(0)("offset (%d) != length (%d)\n", offset, length);
753        peer->second.socket->disconnectServer();
[6139]754      }
[9246]755
756
[7954]757      for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
[6139]758      {
[7954]759        Synchronizeable & sync = **it;
[9246]760
[7954]761        if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
762          continue;
[9246]763
[7954]764        sync.handleRecvState( peer->second.userId, state, fromState );
[6139]765      }
[9246]766
[7954]767      assert( peer->second.lastAckedState <= ackedState );
768      peer->second.lastAckedState = ackedState;
[9246]769
[7954]770      assert( peer->second.lastRecvedState < state );
771      peer->second.lastRecvedState = state;
[8228]772
[6139]773    }
[9246]774
[6139]775  }
[9246]776
[7954]777}
[6139]778
[7954]779/**
780 * is executed when a handshake has finished
781 * @todo create playable for new user
782 */
783void NetworkStream::handleNewClient( int userId )
784{
785  MessageManager::getInstance()->initUser( userId );
[9246]786
[7954]787  networkGameManager->signalNewPlayer( userId );
[5604]788}
[6139]789
[7954]790/**
791 * removes old items from oldSynchronizeables
792 */
793void NetworkStream::cleanUpOldSyncList( )
[6139]794{
[7954]795  int now = SDL_GetTicks();
[9246]796
[7954]797  for ( std::map<int,int>::iterator it = oldSynchronizeables.begin(); it != oldSynchronizeables.end();  )
[6139]798  {
[7954]799    if ( it->second < now - 10*1000 )
800    {
801      std::map<int,int>::iterator delIt = it;
802      it++;
803      oldSynchronizeables.erase( delIt );
804      continue;
805    }
806    it++;
[6139]807  }
[7954]808}
809
810/**
811 * writes data to DATA/dicts/newdict
812 * @param data pointer to data
813 * @param length length
814 */
[8623]815void NetworkStream::writeToNewDict( byte * data, int length, bool upstream )
[7954]816{
817  if ( remainingBytesToWriteToDict <= 0 )
818    return;
[9246]819
[7954]820  if ( length > remainingBytesToWriteToDict )
821    length = remainingBytesToWriteToDict;
[9246]822
[7954]823  std::string fileName = ResourceManager::getInstance()->getDataDir();
824  fileName += "/dicts/newdict";
[9246]825
[8623]826  if ( upstream )
827    fileName += "_upstream";
828  else
829    fileName += "_downstream";
[9246]830
[7954]831  FILE * f = fopen( fileName.c_str(), "a" );
[9246]832
[7954]833  if ( !f )
[6139]834  {
[7954]835    PRINTF(2)("could not open %s\n", fileName.c_str());
836    remainingBytesToWriteToDict = 0;
[6139]837    return;
838  }
[9246]839
[7954]840  if ( fwrite( data, 1, length, f ) != length )
[6341]841  {
[7954]842    PRINTF(2)("could not write to file\n");
843    fclose( f );
[6341]844    return;
845  }
[9246]846
[7954]847  fclose( f );
[9246]848
849  remainingBytesToWriteToDict -= length;
[6139]850}
851
852
[6695]853
854
855
856
Note: See TracBrowser for help on using the repository browser.