Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/network/src/lib/network/network_game_manager.cc @ 6483

Last change on this file since 6483 was 6483, checked in by rennerc, 18 years ago

base_object.cc: fixed bug with sync

File size: 19.0 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: Benjamin Wuest
13   co-programmer: ...
14*/
15
16
17/* this is for debug output. It just says, that all calls to PRINT() belong to the DEBUG_MODULE_NETWORK module
18   For more information refere to https://www.orxonox.net/cgi-bin/trac.cgi/wiki/DebugOutput
19*/
20#define DEBUG_MODULE_NETWORK
21
22#include "factory.h"
23#include "network_stream.h"
24#include "converter.h"
25
26#include "p_node.h"
27#include "state.h"
28#include "game_world.h"
29#include "world_entity.h"
30#include "network_manager.h"
31
32
33/* include your own header */
34#include "network_game_manager.h"
35
36
37/* using namespace std is default, this needs to be here */
38using namespace std;
39
40NetworkGameManager* NetworkGameManager::singletonRef = NULL;
41
42/*!
43 * Standard constructor
44 */
45NetworkGameManager::NetworkGameManager()
46{
47  PRINTF(0)("START\n");
48
49  /* set the class id for the base object */
50  this->setClassID(CL_NETWORK_GAME_MANAGER, "NetworkGameManager");
51
52  allOutBuffer.length = 0;
53
54  allOutBuffer.maxLength = 10*1024;
55
56  allOutBuffer.buffer = new byte[10*1024];
57
58  newUniqueID = MAX_CONNECTIONS + 2;
59
60  hasRequestedWorld = false;
61}
62
63/*!
64 * Standard destructor
65 */
66NetworkGameManager::~NetworkGameManager()
67{
68  for ( int i = 0; i<outBuffer.size(); i++)
69  {
70    if ( outBuffer[i].buffer )
71      delete outBuffer[i].buffer;
72  }
73
74  if ( allOutBuffer.buffer )
75    delete allOutBuffer.buffer;
76}
77
78
79int NetworkGameManager::writeBytes(const byte* data, int length, int sender)
80{
81  int i = 0;
82  byte b;
83
84  while ( i<length )
85  {
86    b = data[i++];
87
88    if ( isServer() )
89    {
90      if ( b == REQUEST_CREATE )
91      {
92        if ( !handleRequestCreate( i, data, length, sender ) )
93          return i;
94        continue;
95      }
96      if ( b == REQUEST_REMOVE )
97      {
98        if ( !handleRequestRemove( i, data, length, sender ) )
99          return i;
100        continue;
101      }
102    }
103    else
104    {
105      if ( b == CREATE_ENTITY )
106      {
107        if ( !handleCreateEntity( i, data, length, sender ) )
108          return i;
109        continue;
110      }
111      if ( b == REMOVE_ENTITY )
112      {
113        if ( !handleRemoveEntity( i, data, length, sender ) )
114          return i;
115        continue;
116      }
117      if ( b == CREATE_ENTITY_LIST )
118      {
119        if ( !handleCreateEntityList( i, data, length, sender ) )
120          return i;
121        continue;
122      }
123      if ( b == REMOVE_ENTITY_LIST )
124      {
125        if ( !handleRemoveEntityList( i, data, length, sender ) )
126          return i;
127        continue;
128      }
129      if ( b == YOU_ARE_ENTITY )
130      {
131        if ( !handleYouAreEntity( i, data, length, sender ) )
132          return i;
133        continue;
134      }
135    }
136
137    if ( b == REQUEST_SYNC )
138    {
139      if ( !handleRequestSync( i, data, length, sender ) )
140        return i;
141      continue;
142    }
143
144    if ( b == REQUEST_ENTITY_LIST )
145    {
146      sendEntityList( sender );
147      continue;
148    }
149
150    //if we get her something with data is wrong
151    PRINTF(1)("Data is not in the right format! i=%d\n", i);
152    return i;
153  }
154
155  return i;
156}
157
158int NetworkGameManager::readBytes(byte* data, int maxLength, int * reciever)
159{
160  if ( !isServer() && !hasRequestedWorld )
161  {
162    SYNCHELP_WRITE_BEGIN();
163    byte b = REQUEST_ENTITY_LIST;
164    SYNCHELP_WRITE_BYTE( b );
165    hasRequestedWorld = true;
166    return SYNCHELP_WRITE_N;
167  }
168  for ( int i = 0; i<outBuffer.size(); i++ )
169  {
170    *reciever = i;
171    if ( outBuffer[i].length>0 )
172    {
173      int nbytes = outBuffer[i].length;
174      outBuffer[i].length = 0;
175
176      if ( nbytes > maxLength )
177      {
178        PRINTF(1)("OutBuffer.length (%d) > (%d) networkStreamBuffer.maxLength\n", nbytes, maxLength);
179        return 0;
180      }
181
182      memcpy(data, outBuffer[i].buffer, nbytes);
183      return nbytes;
184    }
185  }
186
187  *reciever = 0;
188  int nbytes = allOutBuffer.length;
189  allOutBuffer.length = 0;
190
191  if ( nbytes <=0 )
192    return 0;
193
194  if ( nbytes > maxLength )
195  {
196    PRINTF(1)("OutBuffer.length (%d) > (%d) networkStreamBuffer.length\n", nbytes, maxLength);
197    return 0;
198  }
199
200  memcpy( data, allOutBuffer.buffer, nbytes );
201  return nbytes;
202}
203
204void NetworkGameManager::writeDebug() const
205{
206}
207
208void NetworkGameManager::readDebug() const
209{
210}
211
212
213/*!
214 * Checks whether this is connected to a server or a client
215 * and afterwards creates the needed entity
216 * @param classID: The ID of the class of which an entity should be created
217 */
218void NetworkGameManager::createEntity( ClassID classID, int owner )
219{
220  if ( this->isServer() )
221  {
222    if ( newUniqueID < 0 )
223    {
224      PRINTF(1)("Cannot create entity! There are no more uniqueIDs left!\n");
225      return;
226    }
227
228    this->executeCreateEntity( classID, newUniqueID++, owner );
229  }
230  else
231  {
232    this->requestCreateEntity( classID );
233  }
234}
235
236
237/*!
238 * Checks whether this is connected to a server or a client
239 * and afterwards creates the needed entity
240 * @param classID: The ID of the class of which an entity should be created
241 */
242BaseObject* NetworkGameManager::createEntity(const TiXmlElement* element)
243{
244  if ( this->isServer() )
245  {
246    if ( newUniqueID < 0 )
247    {
248      PRINTF(1)("Cannot create entity! There are no more uniqueIDs left!\n");
249      return NULL;
250    }
251    newUniqueID++;
252
253    BaseObject * b = Factory::fabricate( element );
254
255    if ( !b )
256    {
257      PRINTF(1)("Could not fabricate Object with className %s\n", element->Value() );
258      return NULL;
259    }
260
261
262    if ( b->isA(CL_SYNCHRONIZEABLE) )
263    {
264      Synchronizeable * s = dynamic_cast<Synchronizeable*>(b);
265      s->setUniqueID( newUniqueID );
266      s->setOwner( 0 );
267      this->networkStream->connectSynchronizeable( *s );
268      return b;
269    }
270    else
271    {
272      PRINTF(1)("Class %s is not a synchronizeable!\n", b->getClassName() );
273      delete b;
274    }
275
276  }
277  else
278  {
279    PRINTF(1)("This node is not a server and cannot create id %x\n", element->Value());
280  }
281  return NULL;
282}
283
284
285/*!
286 * Checks whether this is connected to a server or a client
287 * and afterwards removes the specified entity
288 * @param uniqueID: The ID of the entity object which should be removed
289 */
290void NetworkGameManager::removeEntity(int uniqueID)
291{
292  if ( this->isServer() )
293  {
294    this->executeRemoveEntity( uniqueID );
295  }
296  else
297  {
298    this->requestRemoveEntity( uniqueID );
299  }
300}
301
302
303
304/*!
305 * Creates the needed entity on the server if possible
306 * @param classID: The ID of the class of which an entity should be created
307 */
308void NetworkGameManager::requestCreateEntity(ClassID classID)
309{
310  if ( !writeToClientBuffer( allOutBuffer, (byte)REQUEST_CREATE ) )
311    return;
312  if ( !writeToClientBuffer( allOutBuffer, (int)classID ) )
313    return;
314}
315
316/*!
317 * Removes the specified entity on the server
318 * @param uniqueID: The ID of the entity object which should be removed
319 */
320void NetworkGameManager::requestRemoveEntity(int uniqueID)
321{
322  if ( !writeToClientBuffer( allOutBuffer, (byte)REQUEST_REMOVE ) )
323    return;
324  if ( !writeToClientBuffer( allOutBuffer, uniqueID ) )
325    return;
326}
327
328/*!
329 * Creates the needed entity if possible
330 * This function is called if this is a server
331 * @param classID: The ID of the class of which an entity should be created
332 */
333void NetworkGameManager::executeCreateEntity(ClassID classID, int uniqueID, int owner)
334{
335  if ( !writeToClientBuffer( allOutBuffer, (byte)CREATE_ENTITY ) )
336    return;
337  if ( !writeToClientBuffer( allOutBuffer, (int)classID ) )
338    return;
339  if ( !writeToClientBuffer( allOutBuffer, uniqueID ) )
340    return;
341  if ( !writeToClientBuffer( allOutBuffer, owner ) )
342    return;
343
344  doCreateEntity( classID, uniqueID, owner );
345}
346
347/*!
348 * Removes the specified entity
349 * This function is called if this is a server
350 * @param uniqueID: The ID of the entity object which should be removed
351 */
352void NetworkGameManager::executeRemoveEntity(int uniqueID)
353{
354  if ( !writeToClientBuffer( allOutBuffer, (byte)REMOVE_ENTITY ) )
355    return;
356  if ( !writeToClientBuffer( allOutBuffer, uniqueID ) )
357    return;
358
359  doRemoveEntity(uniqueID);
360}
361
362/*!
363 * Checks whether it is possible to create an entity of a given class
364 * @return: true if the entity can be created, false otherwise
365 */
366bool NetworkGameManager::canCreateEntity(ClassID classID)
367{
368  return true;
369}
370
371/*!
372 * Sends the Entities to the new connected client
373 * @param userID: The ID of the user
374 */
375void NetworkGameManager::sendEntityList( int userID )
376{
377  if ( !isServer() )
378    return;
379
380  if ( userID >= outBuffer.size() )
381    resizeBufferVector( userID );
382
383  SynchronizeableList::const_iterator it, e;
384
385  it = this->networkStream->getSyncBegin();
386  e = this->networkStream->getSyncEnd();
387
388  if ( !writeToClientBuffer( outBuffer[userID], (byte)CREATE_ENTITY_LIST ) )
389    return;
390
391  // -2 because you must not send network_game_manager and handshake
392  if ( !writeToClientBuffer( outBuffer[userID], networkStream->getSyncCount() ) )
393    return;
394
395  //PRINTF(0)("SendEntityList: n = %d\n", networkStream->getSyncCount()-2 );
396
397  int n = 0;
398
399  while ( it != e )
400  {
401
402    if ( !writeToClientBuffer( outBuffer[userID], (int)((*it)->getLeafClassID()) ) )
403      return;
404
405    if ( !writeToClientBuffer( outBuffer[userID], (int)((*it)->getUniqueID()) ) )
406      return;
407
408    if ( !writeToClientBuffer( outBuffer[userID], (int)((*it)->getOwner()) ) )
409      return;
410
411    it++;
412  }
413
414
415}
416
417/**
418 * Creates a buffer for user n
419 * @param n The ID of the user
420 */
421void NetworkGameManager::resizeBufferVector( int n )
422{
423  for ( int i = outBuffer.size(); i<=n; i++)
424  {
425    clientBuffer outBuf;
426
427    outBuf.length = 0;
428
429    outBuf.maxLength = 5*1024;
430
431    outBuf.buffer = new byte[5*1014];
432
433    outBuffer.push_back(outBuf);
434  }
435}
436
437/**
438 * Creates the entity on this host
439 * @param classID: ClassID of the entity to create
440 * @param uniqueID: Unique ID to assign to the synchronizeable
441 * @param owner: owner of this synchronizealbe
442 */
443BaseObject* NetworkGameManager::doCreateEntity( ClassID classID, int uniqueID, int owner )
444{
445  BaseObject * b = Factory::fabricate( classID );
446
447  if ( !b )
448  {
449    PRINTF(1)("Could not fabricate Object with classID %x\n", classID);
450    return NULL;
451  }
452
453  if ( b->isA(CL_SYNCHRONIZEABLE) )
454  {
455    Synchronizeable * s = dynamic_cast<Synchronizeable*>(b);
456    s->setUniqueID( uniqueID );
457    s->setOwner( owner );
458    this->networkStream->connectSynchronizeable( *s );
459    if ( !isServer() )
460      s->setIsOutOfSync( true );
461    PRINTF(0)("Fabricated %s with id %d\n", s->getClassName(), s->getUniqueID());
462
463    //HACK: hack to prevent collision
464    if ( b->isA(CL_WORLD_ENTITY) )
465    {
466      if ( NetworkManager::getInstance()->getHostID()!=0 )
467      {
468        static Vector pos = Vector(1000.0, 1000.0, 1000.0);
469        PNode *p = dynamic_cast<PNode*>(b);
470        p->setRelCoor(pos);
471        p->updateNode(0);
472        pos += Vector(1000.0, 1000.0, 1000.0);
473      }
474    }
475
476    return b;
477  }
478  else
479  {
480    PRINTF(1)("Class with ID %x is not a synchronizeable!", (int)classID);
481    delete b;
482  }
483  return NULL;
484}
485
486/**
487 * Removes a entity on this host
488 * @param uniqueID: unique ID assigned with the entity to remove
489 */
490void NetworkGameManager::doRemoveEntity( int uniqueID )
491{
492  SynchronizeableList::const_iterator it,e;
493  it = this->networkStream->getSyncBegin();
494  e = this->networkStream->getSyncEnd();
495
496  while ( it != e )
497  {
498    if ( (*it)->getUniqueID() == uniqueID )
499    {
500      delete *it;
501      break;
502    }
503    it++;
504  }
505}
506
507/**
508 * Tell the synchronizeable that a user's synchronizeable is out of sync
509 * @param uniqueID: unique ID assigned with the entity which is out of sync
510 * @param userID: user ID who's synchronizeable is out of sync
511 */
512void NetworkGameManager::doRequestSync( int uniqueID, int userID )
513{
514  SynchronizeableList::const_iterator it,e;
515  it = this->networkStream->getSyncBegin();
516  e = this->networkStream->getSyncEnd();
517
518  while ( it != e )
519  {
520    if ( (*it)->getUniqueID() == uniqueID )
521    {
522      (*it)->requestSync( userID );
523      break;
524    }
525    it++;
526  }
527}
528
529/**
530 * Copies length bytes to the clientBuffer with error checking
531 * @param clientBuffer: the clientBuffer to write to
532 * @param data: buffer to the data
533 * @param length: length of data
534 * @return false on error true else
535 */
536bool NetworkGameManager::writeToClientBuffer( clientBuffer &cb, byte * data, int length )
537{
538  if ( length > cb.maxLength-cb.length )
539  {
540    PRINTF(1)("No space left in clientBuffer\n");
541    return false;
542  }
543
544  memcpy( cb.buffer+cb.length, data, length );
545  return true;
546}
547
548/**
549 * Reads data from clientBuffer with error checking
550 * @param clientBuffer: the clientBuffer to read from
551 * @param data: pointer to the buffer
552 * @param length:
553 * @return
554 */
555bool NetworkGameManager::readFromClientBuffer( clientBuffer &cb, byte * data, int length )
556{
557  if ( cb.length < length )
558  {
559    PRINTF(0)("There is not enough data in clientBuffer\n");
560    return 0;
561  }
562
563  memcpy( data, cb.buffer+cb.length-length, length );
564  return true;
565}
566
567/**
568 * Tells this client that he has to control this entity
569 * @param uniqueID: the entity's uniqeID
570 */
571void NetworkGameManager::doYouAre( int uniqueID )
572{
573  //TODO: what has to be done
574}
575
576/**
577 * Tells a remote client that he has to control this entity
578 * @param uniqueID: the entity's uniqeID
579 * @param userID: the users ID
580 */
581void NetworkGameManager::sendYouAre( int uniqueID, int userID )
582{
583  if ( !isServer() )
584    return;
585
586  if ( userID != 0 )
587  {
588    if ( !writeToClientBuffer( outBuffer[userID], (byte)YOU_ARE_ENTITY ) )
589      return;
590
591    if ( !writeToClientBuffer( outBuffer[userID], uniqueID ) )
592      return;
593  }
594  else
595  {
596    doYouAre(uniqueID);
597  }
598}
599
600bool NetworkGameManager::handleRequestCreate( int & i, const byte * data, int length, int sender )
601{
602  if ( INTSIZE > length-i )
603  {
604    PRINTF(1)("Cannot read classID from buffer! Not enough data left!\n");
605    return false;
606  }
607  int classID;
608  i += Converter::byteArrayToInt( &data[i], &classID );
609
610  createEntity( (ClassID)classID );
611
612  return true;
613}
614
615bool NetworkGameManager::handleRequestRemove( int & i, const byte * data, int length, int sender )
616{
617  if ( INTSIZE > length-i )
618  {
619    PRINTF(1)("Cannot read uniqueID from buffer! Not enough data left!\n");
620    return false;
621  }
622  int uniqueID;
623  i += Converter::byteArrayToInt( &data[i], &uniqueID );
624
625  removeEntity( uniqueID );
626
627  return true;
628}
629
630bool NetworkGameManager::handleCreateEntity( int & i, const byte * data, int length, int sender )
631{
632  if ( INTSIZE > length-i )
633  {
634    PRINTF(1)("Cannot read classID from buffer! Not enough data left!\n");
635    return false;
636  }
637  int classID;
638  i += Converter::byteArrayToInt( &data[i], &classID );
639
640  if ( INTSIZE > length-i )
641  {
642    PRINTF(1)("Cannot read uniqueID from buffer! Not enough data left!\n");
643    return false;
644  }
645  int uniqueID;
646  i += Converter::byteArrayToInt( &data[i], &uniqueID );
647
648  if ( INTSIZE > length-i )
649  {
650    PRINTF(1)("Cannot read owner from buffer! Not enough data left!\n");
651    return false;
652  }
653  int owner;
654  i += Converter::byteArrayToInt( &data[i], &owner );
655
656  doCreateEntity( (ClassID)classID, uniqueID, owner );
657
658  return true;
659}
660
661bool NetworkGameManager::handleRemoveEntity( int & i, const byte * data, int length, int sender )
662{
663  if ( INTSIZE > length-i )
664  {
665    PRINTF(1)("Cannot read uniqueID from buffer! Not enough data left!\n");
666    return false;
667  }
668  int uniqueID;
669  i += Converter::byteArrayToInt( &data[i], &uniqueID );
670
671  doRemoveEntity( uniqueID );
672
673  return true;
674}
675
676bool NetworkGameManager::handleCreateEntityList( int & i, const byte * data, int length, int sender )
677{
678  if ( INTSIZE > length-i )
679  {
680    PRINTF(1)("Cannot read n from buffer! Not enough data left!\n");
681    return false;
682  }
683
684  PRINTF(0)("HandleCreateEntityList:  data[i..i+3] = %d %d %d %d\n", data[i], data[i+1], data[i+2], data[i+3]);
685
686  int n;
687  i += Converter::byteArrayToInt( &data[i], &n );
688
689
690  PRINTF(0)("HandleCreateEntityList: n = %d\n", n);
691
692  int classID, uniqueID, owner;
693
694  for ( int j = 0; j<n; j++ )
695  {
696
697    if ( INTSIZE > length-i )
698    {
699      PRINTF(1)("Cannot read classID from buffer! Not enough data left!\n");
700      return false;
701    }
702    i += Converter::byteArrayToInt( &data[i], &classID );
703
704    if ( INTSIZE > length-i )
705    {
706      PRINTF(1)("Cannot read uniqueID from buffer! Not enough data left!\n");
707      return false;
708    }
709    i += Converter::byteArrayToInt( &data[i], &uniqueID );
710
711    if ( INTSIZE > length-i )
712    {
713      PRINTF(1)("Cannot read owner from buffer! Not enough data left!\n");
714      return false;
715    }
716    i += Converter::byteArrayToInt( &data[i], &owner );
717
718    if ( classID != CL_NETWORK_GAME_MANAGER && classID != CL_HANDSHAKE )
719    {
720      BaseObject* b = doCreateEntity( (ClassID)classID, uniqueID, owner );
721
722      /*if ( b != NULL )
723      {
724        if ( b->isA(CL_WORLD_ENTITY) )
725        {
726          int n = dynamic_cast<WorldEntity*>(b)->writeState( data, length, sender );
727
728          i += n;
729        }
730    }*/
731    }
732
733  }
734
735  return true;
736}
737
738bool NetworkGameManager::handleRemoveEntityList( int & i, const byte * data, int length, int sender )
739{
740  if ( INTSIZE > length-i )
741  {
742    PRINTF(1)("Cannot read n from buffer! Not enough data left!\n");
743    return false;
744  }
745  int n;
746  i += Converter::byteArrayToInt( &data[i], &n );
747
748  int uniqueID;
749
750  for ( int j = 0; j<n; j++ )
751  {
752
753    if ( INTSIZE > length-i )
754    {
755      PRINTF(1)("Cannot read uniqueID from buffer! Not enough data left!\n");
756      return false;
757    }
758    i += Converter::byteArrayToInt( &data[i], &uniqueID );
759
760    doRemoveEntity( uniqueID );
761  }
762
763  return true;
764}
765
766bool NetworkGameManager::handleYouAreEntity( int & i, const byte * data, int length, int sender )
767{
768  if ( INTSIZE > length-i )
769  {
770    PRINTF(1)("Cannot read uniqueID from buffer! Not enough data left!\n");
771    return false;
772  }
773
774  int uniqueID;
775  i += Converter::byteArrayToInt( &data[i], &uniqueID );
776
777  doYouAre( uniqueID );
778
779  return true;
780}
781
782bool NetworkGameManager::handleRequestSync( int & i, const byte * data, int length, int sender )
783{
784  if ( INTSIZE > length-i )
785  {
786    PRINTF(1)("Cannot read uniqueID from buffer! Not enough data left!\n");
787    return false;
788  }
789  int uniqueID;
790  i += Converter::byteArrayToInt( &data[i], &uniqueID );
791
792  doRequestSync( uniqueID, sender );
793
794  return true;
795}
796
797bool NetworkGameManager::writeToClientBuffer( clientBuffer & cb, byte b )
798{
799  if ( cb.maxLength-cb.length < 1 )
800  {
801    PRINTF(1)("Cannot write to clientBuffer! Not enough space for 1 byte\n");
802    return false;
803  }
804
805  cb.buffer[cb.length++] = b;
806
807  return true;
808}
809
810bool NetworkGameManager::writeToClientBuffer( clientBuffer & cb, int i )
811{
812  int n = Converter::intToByteArray( i, cb.buffer+cb.length, cb.maxLength-cb.length );
813  cb.length += n;
814
815  if ( n <= 0 )
816  {
817    PRINTF(1)("Cannot write to clientBuffer! Not enough space for 1 int\n");
818    return false;
819  }
820
821  return true;
822}
823
824void NetworkGameManager::sync( int uniqueID, int owner )
825{
826  if ( owner==this->getHostID() )
827    return;
828
829  if ( !isServer() )
830    executeRequestSync( uniqueID, 0 );
831  else
832    executeRequestSync( uniqueID, owner );
833}
834
835void NetworkGameManager::executeRequestSync( int uniqueID, int user )
836{
837  if ( user >= outBuffer.size() )
838    resizeBufferVector( user );
839
840  if ( !writeToClientBuffer( outBuffer[user], (byte)REQUEST_SYNC ) )
841    return;
842  if ( !writeToClientBuffer( outBuffer[user], uniqueID ) )
843    return;
844}
845
Note: See TracBrowser for help on using the repository browser.