Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/proxy/src/lib/network/network_stream.cc @ 9271

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

node type now saved

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