Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

redirection flag added, proxy settings as a way to get/save the server settings

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