PageRenderTime 43ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/Core/Dependencies/Engine/MultiplayerOnline/RakNet/NetManager.cpp

https://bitbucket.org/barakianc/nvidia-physx-and-apex-in-gge
C++ | 1059 lines | 562 code | 184 blank | 313 comment | 118 complexity | 1f1f481e29db113099270cdfffaace05 MD5 | raw file
  1. #include "StdAfx.h"
  2. #include "NetManager.h"
  3. using namespace std;
  4. static const int DEFAULT_SERVER_MILLISECONDS_BETWEEN_UPDATES=250;
  5. namespace GamePipeGame
  6. {
  7. NetTopology topology;
  8. extern ofstream outputLog;
  9. /// ~NetManager - Constructor
  10. NetManager::NetManager(CustomPacketHandler pCustomPacketHandler /*= 0*/) :
  11. managerStatus(INACTIVE), subsystem(RAKNET), topology(CLIENT),
  12. maxConnections(1), sleepInterval(100),
  13. localPort(0), remoteHost("127.0.0.1"), remotePort(60000), password(""),
  14. isNetworkIDAuthority(false),
  15. networkInterface(NULL),
  16. rakPacket(NULL),
  17. globalLog(NULL),
  18. m_pCustomPacketHandler(pCustomPacketHandler)
  19. {
  20. //networkInterface = RakNetworkFactory::GetRakPeerInterface();
  21. //raknet 4.0b8
  22. networkInterface = RakNet::RakPeerInterface::GetInstance();
  23. }
  24. /// ~NetManager - Destructor
  25. NetManager::~NetManager()
  26. {
  27. networkInterface->Shutdown(0, 0, HIGH_PRIORITY);
  28. managerStatus = DESTROYING;
  29. }
  30. /// GetStatus - Gets the current NetManager status
  31. NetManagerStatus NetManager::GetStatus() { return managerStatus; }
  32. /// GetTopology - Gets the current network topology value (CLIENT, SERVER, PEER)
  33. NetTopology NetManager::GetTopology() { return topology; }
  34. /// SetTopology - Sets a new network topology value (CLIENT, SERVER, PEER)
  35. int
  36. NetManager::SetTopology(NetTopology newTopology)
  37. {
  38. topology = newTopology;
  39. return NETMANAGER_SUCCESS;
  40. }
  41. /// CreateNetworkIDManager - Attaches a NetworkIDManager object to the RakPeerInterface
  42. ///
  43. /// Parameters: newAuthority - a flag indicating whether this NetworkIDManager is the ID Authority (usually, a server)
  44. int
  45. NetManager::CreateNetworkIDManager(bool newAuthority)
  46. {
  47. isNetworkIDAuthority = newAuthority;
  48. if(subsystem == RAKNET)
  49. {
  50. //networkInterface->SetNetworkIDManager(&networkIDManager);
  51. //raknet 4.0b8
  52. replicaManager.SetNetworkIDManager(&networkIDManager);
  53. replicaManager.SetAutoSerializeInterval(DEFAULT_SERVER_MILLISECONDS_BETWEEN_UPDATES);
  54. //networkIDManager.SetIsNetworkIDAuthority(newAuthority);
  55. }
  56. return NETMANAGER_SUCCESS;
  57. }
  58. /// SetLocalSocketPort - Sets a new port number for local binding
  59. int
  60. NetManager::SetLocalSocketPort(unsigned short newLocalPort)
  61. {
  62. localPort = newLocalPort;
  63. return NETMANAGER_SUCCESS;
  64. }
  65. /// SetMaxConnections - Sets the maximum number of connections for this RakPeerInterface
  66. int
  67. NetManager::SetMaxConnections(int newMaxConnections)
  68. {
  69. maxConnections = newMaxConnections;
  70. return NETMANAGER_SUCCESS;
  71. }
  72. /// SetSleepInterval - Sets a new sleep interval for polling
  73. int
  74. NetManager::SetSleepInterval(int newSleepIntervalMS)
  75. {
  76. sleepInterval = newSleepIntervalMS;
  77. return NETMANAGER_SUCCESS;
  78. }
  79. /// SetRemoteHost - Sets a new remote port host name
  80. int
  81. NetManager::SetRemoteHost(const char *newRemoteHost)
  82. {
  83. remoteHost.clear();
  84. remoteHost.assign(newRemoteHost);
  85. return NETMANAGER_SUCCESS;
  86. }
  87. /// SetRemotePort - Sets a new remote port number
  88. int
  89. NetManager::SetRemotePort(unsigned short newRemotePort)
  90. {
  91. remotePort = newRemotePort;
  92. return NETMANAGER_SUCCESS;
  93. }
  94. /// SetPasswordOptions - Sets a new password string
  95. int
  96. NetManager::SetPasswordOptions(const char *newPassword, int length)
  97. {
  98. password.clear();
  99. password.assign(newPassword, length);
  100. return NETMANAGER_SUCCESS;
  101. }
  102. /// EnableRakNetPlugin - Attaches a specific plug-in to the RakPeerInterface
  103. ///
  104. /// Parameters: pluginName - a string containing the name of the plug-in to attach
  105. ///
  106. /// Returns:
  107. /// NETMANAGER_FAILURE, if the subsystem value is not set to RAKNET
  108. /// NETMANAGER_SUCCESS, otherwise.
  109. int
  110. NetManager::EnableRakNetPlugin(const char *pluginName)
  111. {
  112. if(subsystem != RAKNET) return NETMANAGER_FAILURE;
  113. if(!strcmp(pluginName, "ReplicaManager3"))
  114. networkInterface->AttachPlugin(&replicaManager);
  115. return NETMANAGER_SUCCESS;
  116. }
  117. /// Initialize - Sets the initial properties of the RakPeerInterface.
  118. ///
  119. /// Returns:
  120. /// NETMANAGER_FAILURE, if the call to RakPeerInterface->Startup returns a failure.
  121. /// NETMANAGER_SUCCESS, otherwise.
  122. int
  123. NetManager::Initialize()
  124. {
  125. //bool startupResult = false;
  126. //raknet 4.0b8
  127. RakNet::StartupResult startupResult;
  128. managerStatus = INITIALIZING;
  129. if(subsystem == RAKNET)
  130. {
  131. connectionSD.port = localPort;
  132. //startupResult = networkInterface->Startup(maxConnections, sleepInterval, &connectionSD, 1);
  133. //raknet 4.0b8
  134. startupResult = networkInterface->Startup(maxConnections, &connectionSD, 1);
  135. //if(startupResult) networkInterface->SetMaximumIncomingConnections(maxConnections);
  136. //raknet 4.0b8
  137. if(startupResult==RakNet::RAKNET_STARTED)networkInterface->SetMaximumIncomingConnections(maxConnections);
  138. }
  139. //return ((startupResult)? NETMANAGER_SUCCESS : NETMANAGER_FAILURE);
  140. //raknet 4.0b8
  141. if(startupResult==RakNet::RAKNET_STARTED)
  142. {
  143. return NETMANAGER_SUCCESS;
  144. }
  145. else
  146. {
  147. return NETMANAGER_FAILURE;
  148. }
  149. }
  150. /// Connect - Connects the network interface to a remote host and port using previously set values.
  151. ///
  152. /// Returns:
  153. /// NETMANAGER_FAILURE, if this is a server OR if RakPeerInterface->Connect returns a failure.
  154. /// NETMANAGER_SUCCESS, otherwise.
  155. int
  156. NetManager::Connect()
  157. {
  158. if(topology == SERVER) return NETMANAGER_FAILURE; // should not call Connect() for servers
  159. //bool connectInitResult = false;
  160. //raknet 4.0b8
  161. RakNet::ConnectionAttemptResult connectInitResult;
  162. if(subsystem == RAKNET)
  163. {
  164. connectInitResult = networkInterface->Connect(remoteHost.c_str(), remotePort, password.c_str(), password.length(), 0);
  165. }
  166. //return ((connectInitResult)? NETMANAGER_SUCCESS : NETMANAGER_FAILURE);
  167. //raknet 4.0b8
  168. if(connectInitResult==RakNet::CONNECTION_ATTEMPT_STARTED)
  169. {
  170. return NETMANAGER_SUCCESS;
  171. }
  172. else
  173. {
  174. return NETMANAGER_FAILURE;
  175. }
  176. }
  177. /// Disconnect - Disconnects the network interface from a remote host and port using previously set values.
  178. ///
  179. /// Returns:
  180. /// NETMANAGER_FAILURE, if this is a server.
  181. /// NETMANAGER_SUCCESS, otherwise.
  182. int
  183. NetManager::Disconnect()
  184. {
  185. if(topology == SERVER) return NETMANAGER_FAILURE; // should not call Disconnect() for servers
  186. managerStatus = STOPPING;
  187. if(subsystem == RAKNET)
  188. {
  189. std::vector<Ogre::String> destructionList;
  190. DestroyMyObjects(destructionList);
  191. AddLogMessage("Disconnecting from server.");
  192. //SystemAddress disconnectSystem(remoteHost.c_str(), remotePort);
  193. //raknet 4.0b8
  194. RakNet::SystemAddress disconnectSystem(remoteHost.c_str(), remotePort);
  195. networkInterface->CloseConnection(disconnectSystem, true);
  196. AddLogMessage("Shutting down the network connection.");
  197. networkInterface->Shutdown(0);
  198. //raknet 4.0b8
  199. RakNet::RakPeerInterface::DestroyInstance(networkInterface);
  200. managerStatus = INACTIVE;
  201. }
  202. return NETMANAGER_SUCCESS;
  203. }
  204. /// Shutdown - Calls Disconnect if client, Shutdown if server
  205. ///
  206. /// Returns:
  207. /// NETMANAGER_SUCCESS, if Disconnect() succeeds for a client or after Shutdown is called for a server
  208. /// NETMANAGER_SUCCESS, otherwise.
  209. int
  210. NetManager::NetShutdown()
  211. {
  212. if(NotStarted()) return NETMANAGER_FAILURE;
  213. if(subsystem == RAKNET)
  214. {
  215. if(topology == CLIENT)
  216. {
  217. return NetManager::Disconnect();
  218. }
  219. else
  220. {
  221. managerStatus = INACTIVE;
  222. networkInterface->Shutdown(0);
  223. //raknet 4.0b8
  224. RakNet::RakPeerInterface::DestroyInstance(networkInterface);
  225. return NETMANAGER_SUCCESS;
  226. }
  227. }
  228. return NETMANAGER_FAILURE;
  229. }
  230. /// NotStarted - Checks to see if the NetManager is in the INACTIVE state
  231. ///
  232. /// Returns: True, if managerStatus is INACTIVE. False, otherwise.
  233. bool NetManager::NotStarted() { return managerStatus == INACTIVE; }
  234. /// AddObject - Adds a BasicReplica to the replica manager.
  235. ///
  236. /// Parameters: replica - a BasicReplica pointer to use for addtion to the replica manager
  237. ///
  238. /// Returns:
  239. /// NETMANAGER_FAILURE, if the replica pointer is NULL.
  240. /// NETMANAGER_SUCCESS, otherwise.
  241. int
  242. //NetManager::AddObject(BasicReplica *replica)
  243. //raknet 4.0b8
  244. NetManager::AddObject(GameObjectReplica *replica)
  245. {
  246. if(replica == NULL) return NETMANAGER_FAILURE;
  247. if(subsystem == RAKNET)
  248. {
  249. replicaManager.Reference(replica);
  250. }
  251. return NETMANAGER_SUCCESS;
  252. }
  253. /// AddObject - Adds a BasicReplica to the replica manager with adding the GUID of client who requested the obect creation.
  254. ///
  255. /// Parameters: replica - a BasicReplica pointer to use for addtion to the replica manager
  256. /// guid - RakNetGUID of client
  257. ///
  258. /// Returns:
  259. /// NETMANAGER_FAILURE, if the replica pointer is NULL.
  260. /// NETMANAGER_SUCCESS, otherwise.
  261. int
  262. //NetManager::AddObject(BasicReplica *replica, RakNet::RakNetGUID)
  263. //raknet 4.0b8
  264. NetManager::AddObject(GameObjectReplica *replica, RakNet::RakNetGUID guid)
  265. {
  266. if(replica == NULL) return NETMANAGER_FAILURE;
  267. if(subsystem == RAKNET)
  268. {
  269. replicaManager.Reference(replica);
  270. listGUID.push_back(guid);
  271. listNetworkID.push_back(replica->GetNetworkID());
  272. }
  273. return NETMANAGER_SUCCESS;
  274. }
  275. /// DestroyObjectByPtr - Destroys an object given a pointer
  276. ///
  277. /// Parameters: replica - a BasicReplica pointer to use for destruction
  278. ///
  279. /// Returns:
  280. /// NETMANAGER_FAILURE, if the replica pointer is NULL.
  281. /// NETMANAGER_SUCCESS, otherwise.
  282. int
  283. //NetManager::DestroyObjectByPtr(BasicReplica *replica)
  284. //raknet 4.0b8
  285. NetManager::DestroyObjectByPtr(GameObjectReplica *replica)
  286. {
  287. if(replica == NULL) return NETMANAGER_FAILURE;
  288. if(subsystem == RAKNET)
  289. {
  290. //
  291. replica->BroadcastDestruction();
  292. }
  293. return NETMANAGER_SUCCESS;
  294. }
  295. /// DestroyObjectByName - Destroys an object given a specific name
  296. ///
  297. /// Not implemented.
  298. ///
  299. /// Parameters: name - a reference to an Ogre string containing the name of the entity to destroy
  300. int
  301. NetManager::DestroyObjectByName(Ogre::String name)
  302. {
  303. if(subsystem == RAKNET)
  304. {
  305. }
  306. return NETMANAGER_FAILURE;
  307. }
  308. /// DestroyObjectByGUID - Destroys an object given a specific GUID
  309. ///
  310. /// Not implemented.
  311. ///
  312. /// Parameters: guid - a GamePipeNetObjectGUID (typedef'd to some other value) to search for for destruction
  313. int
  314. NetManager::DestroyObjectByGUID(GamePipeNetObjectGUID guid)
  315. {
  316. if(subsystem == RAKNET)
  317. {
  318. }
  319. return NETMANAGER_FAILURE;
  320. }
  321. /// DestroyMyObjects - Destroys all shared objects that were created by the replica manager in this NetManager instance.
  322. ///
  323. /// This function destroys only objects that have been allocated a network ID.
  324. ///
  325. /// Parameters:
  326. /// destroyedEntityNames - a vector of Ogre strings containing the names of all successfully destroyed entities
  327. ///
  328. /// Returns:
  329. /// NETMANAGER_SUCCESS
  330. int
  331. NetManager::DestroyMyObjects(std::vector<Ogre::String> &destroyedEntityNames)
  332. {
  333. if(subsystem == RAKNET)
  334. {
  335. destroyedEntityNames.clear();
  336. DataStructures::List<RakNet::Replica3*> myReplicaList, replicaDestructionList;
  337. //DataStructures::Multilist<ML_STACK, RakNet::Replica3 *> myReplicaList, replicaDestructionList;
  338. replicaManager.GetReplicasCreatedByMe(myReplicaList);
  339. for(unsigned index = 0; index < myReplicaList.Size(); index++)
  340. {
  341. //BasicReplica *replica = static_cast<BasicReplica *>(myReplicaList[index]);
  342. //raknet 4.0b8
  343. GameObjectReplica *replica = static_cast<GameObjectReplica *>(myReplicaList[index]);
  344. Ogre::String entityName = replica->GetEntityName();
  345. // Only delete objects that have already been assigned a network ID, as these objects have been completely
  346. // set up in the replica manager. Deleting objects with IDs of 65535 (UNASSIGNED) leads to "orphaned" objects.
  347. //if(replica->GetNetworkID().localSystemAddress != 65535)
  348. //raknet 4.0b8
  349. if(replica->GetNetworkID() != 65535)
  350. {
  351. destroyedEntityNames.push_back(entityName); // Add to the list of entities to handle later
  352. replicaDestructionList.Push(replica, _FILE_AND_LINE_); // Add to the local destruction stack
  353. //cout << "[NetManager/DestroyMyObjects] Queuing replica for destruction, ID = " << replica->GetNetworkID().localSystemAddress << endl;
  354. //raknet 4.0b8
  355. cout << "[NetManager/DestroyMyObjects] Queuing replica for destruction, ID = " << replica->GetNetworkID() << endl;
  356. }
  357. else
  358. {
  359. cout << "[NetManager/DestroyMyObjects] Cannot destroy object (" << entityName << ") yet as it has a network ID of zero" << endl;
  360. }
  361. }
  362. //replicaManager.BroadcastDestructionList(replicaDestructionList, UNASSIGNED_SYSTEM_ADDRESS);
  363. //raknet 4.0b8
  364. replicaManager.BroadcastDestructionList(replicaDestructionList, RakNet::UNASSIGNED_SYSTEM_ADDRESS);
  365. //replicaDestructionList.;
  366. }
  367. return NETMANAGER_SUCCESS;
  368. }
  369. /// DestroyAllObjects - Destroys all shared objects.
  370. ///
  371. /// This function destroys only objects that have been allocated a network ID.
  372. ///
  373. /// Parameters:
  374. /// destroyedEntityNames - a vector of Ogre strings containing the names of all successfully destroyed entities
  375. ///
  376. /// Returns:
  377. /// NETMANAGER_FAILURE, if the function is called by a NetManager that is not a server.
  378. /// NETMANAGER_SUCCESS, otherwise.
  379. int
  380. NetManager::DestroyAllObjects(std::vector<Ogre::String> &destroyedEntityNames)
  381. {
  382. if(topology != SERVER) return NETMANAGER_FAILURE; // Only the server can attempt to delete all objects in the manager
  383. if(subsystem == RAKNET)
  384. {
  385. destroyedEntityNames.clear();
  386. DataStructures::List<RakNet::Replica3*> allReplicaList, replicaDestructionList;
  387. //DataStructures::Multilist<ML_STACK, RakNet::Replica3 *> allReplicaList, replicaDestructionList;
  388. replicaManager.GetReplicasCreatedByMe(allReplicaList);
  389. // Remove the objects I created:
  390. // Remove the objects from the scene (associated entity and scene nodes)
  391. // Remove the objects from the entity map
  392. for(unsigned index = 0; index < allReplicaList.Size(); index++)
  393. {
  394. //BasicReplica *replica = static_cast<BasicReplica *>(allReplicaList[index]);
  395. //raknet 4.0b8
  396. GameObjectReplica *replica = static_cast<GameObjectReplica *>(allReplicaList[index]);
  397. Ogre::String entityName = replica->GetEntityName();
  398. //if(replica->GetNetworkID().localSystemAddress != 0)
  399. //raknet 4.0b8
  400. if(replica->GetNetworkID() != 0)
  401. {
  402. destroyedEntityNames.push_back(entityName);
  403. replicaDestructionList.Push(replica, _FILE_AND_LINE_);
  404. }
  405. else
  406. {
  407. cout << "[NetManager/DestroyAllObjects] Cannot destroy object (" << entityName << ") yet as it has a network ID of zero" << endl;
  408. }
  409. }
  410. //replicaManager.BroadcastDestructionList(replicaDestructionList, UNASSIGNED_SYSTEM_ADDRESS);
  411. //raknet 4.0b8
  412. replicaManager.BroadcastDestructionList(replicaDestructionList, RakNet::UNASSIGNED_SYSTEM_ADDRESS);
  413. //replicaDestructionList.ClearPointers();
  414. }
  415. return NETMANAGER_SUCCESS;
  416. }
  417. /// QueryByObjectName - Returns a pointer to a replica whose object name matches the supplied Ogre String.
  418. ///
  419. /// This function returns only the first matching replica in the replica manager. Object names do not have to be unique.
  420. ///
  421. /// Parameters: name - a reference to an Ogre string containing the object name to search for
  422. /// Returns: a BasicReplica pointer matching the object name. NULL if the object name is not found in the replica manager.
  423. //BasicReplica *
  424. //raknet 4.0b8
  425. GameObjectReplica *
  426. NetManager::QueryByObjectName(Ogre::String &name)
  427. {
  428. if(subsystem == RAKNET)
  429. {
  430. DataStructures::List<RakNet::Replica3*> fullReplicaList;
  431. //DataStructures::Multilist<ML_STACK, RakNet::Replica3 *> fullReplicaList;
  432. replicaManager.GetReferencedReplicaList(fullReplicaList);
  433. for(unsigned index = 0; index < replicaManager.GetReplicaCount(); index++)
  434. {
  435. //BasicReplica *replica = static_cast<BasicReplica *>(replicaManager.GetReplicaAtIndex(index));
  436. //raknet 4.0b8
  437. GameObjectReplica *replica = static_cast<GameObjectReplica *>(replicaManager.GetReplicaAtIndex(index));
  438. if(!name.compare(replica->GetObjectName()))
  439. return replica;
  440. }
  441. }
  442. return NULL;
  443. }
  444. /// QueryByEntityName - Returns a pointer to a replica whose entity name matches the supplied Ogre String.
  445. ///
  446. /// This function returns only the first matching replica in the replica manager. Entity names should generally be unique.
  447. ///
  448. /// Parameters: name - a reference to an Ogre string containing the entity name to search for
  449. ///
  450. /// Returns: a BasicReplica pointer matching the entity name. NULL if the entity name is not found in the replica manager.
  451. //BasicReplica *
  452. //raknet 4.0b8
  453. GameObjectReplica *
  454. NetManager::QueryByEntityName(Ogre::String &name)
  455. {
  456. if(subsystem == RAKNET)
  457. {
  458. DataStructures::List<RakNet::Replica3*> fullReplicaList;
  459. // DataStructures::Multilist<ML_STACK, RakNet::Replica3 *> fullReplicaList;
  460. replicaManager.GetReferencedReplicaList(fullReplicaList);
  461. for(unsigned index = 0; index < replicaManager.GetReplicaCount(); index++)
  462. {
  463. //BasicReplica *replica = static_cast<BasicReplica *>(replicaManager.GetReplicaAtIndex(index));
  464. //raknet 4.0b8
  465. GameObjectReplica *replica = static_cast<GameObjectReplica *>(replicaManager.GetReplicaAtIndex(index));
  466. if(!name.compare(replica->GetEntityName()))
  467. return replica;
  468. }
  469. }
  470. return NULL;
  471. }
  472. /// QueryAllObjects - Returns a list of BasicReplica pointers containing all objects in the replica manager.
  473. ///
  474. /// Not implemented.
  475. ///
  476. /// Parameters: objectList - a reference to a std::vector of BasicReplica pointers
  477. int
  478. //NetManager::QueryAllObjects(std::vector<BasicReplica *> &objectList)
  479. //raknet 4.0b8
  480. NetManager::QueryAllObjects(std::vector<GameObjectReplica *> &objectList)
  481. {
  482. return NETMANAGER_FAILURE;
  483. }
  484. //BasicReplica *
  485. //raknet 4.03
  486. int NetManager::QueryObjectsByGUID(std::vector<GameObjectReplica *> &objectList,RakNet::RakNetGUID guid)
  487. {
  488. if(subsystem == RAKNET)
  489. {
  490. DataStructures::List<RakNet::Replica3*> fullReplicaList;
  491. // DataStructures::Multilist<ML_STACK, RakNet::Replica3 *> fullReplicaList;
  492. replicaManager.GetReferencedReplicaList(fullReplicaList);
  493. vector<RakNet::NetworkID> listByGuid;
  494. for(int listIndex = 0;listIndex<(int)listGUID.size();listIndex++)
  495. {
  496. if(listGUID[listIndex]==guid)
  497. {
  498. listByGuid.push_back(listNetworkID[listIndex]);
  499. }
  500. }
  501. for(unsigned index = 0; index < replicaManager.GetReplicaCount(); index++)
  502. {
  503. GameObjectReplica *replica = static_cast<GameObjectReplica *>(replicaManager.GetReplicaAtIndex(index));
  504. for(int listIndex = 0;listIndex<(int)listByGuid.size();listIndex++)
  505. {
  506. if(listByGuid[listIndex]==replica->GetNetworkID())
  507. {
  508. //listByGuid.push_back(listNetworkID[listIndex]);
  509. objectList.push_back(replica);
  510. break;
  511. }
  512. }
  513. }
  514. }
  515. return NETMANAGER_SUCCESS;
  516. }
  517. /// SelectNextObject - Iterates through the replicas in the replica manager, returning a reference to the next replica.
  518. ///
  519. /// Only servers are allowed to iterate through the entire known replica list, clients and peers can only iterate
  520. /// through objects they own.
  521. ///
  522. /// Parameters:
  523. /// currentEntityPtr - a pointer to the current object selected
  524. /// forward - whether to return the next object forward or backward in the list from the replica manager. Default value is true.
  525. ///
  526. /// Returns: a BasicReplica pointer to the next object to be selected. NULL is returned if currentEntityPtr is the
  527. /// last object in the replica list.
  528. //BasicReplica *
  529. //raknet 4.0b8
  530. GameObjectReplica *
  531. //NetManager::SelectNextObject(BasicReplica *currentEntityPtr, bool forward)
  532. //raknet 4.0b8
  533. NetManager::SelectNextObject(GameObjectReplica *currentEntityPtr, bool forward)
  534. {
  535. if(subsystem == RAKNET)
  536. {
  537. DataStructures::List<RakNet::Replica3*> replicaList;
  538. //DataStructures::Multilist<ML_STACK, RakNet::Replica3 *> replicaList;
  539. if(topology == SERVER)
  540. replicaManager.GetReferencedReplicaList(replicaList); // Only the server can select all objects
  541. else
  542. replicaManager.GetReplicasCreatedByMe(replicaList); // Clients and peers can only select objects they won
  543. // If there's no selectable entities to select, just return null
  544. if(replicaList.Size() == 0)
  545. {
  546. AddLogMessage("No entities to select.");
  547. return NULL;
  548. }
  549. // If nothing was selected before, just return the first object
  550. if(currentEntityPtr == NULL && replicaList.Size() > 0)
  551. {
  552. //BasicReplica *replica = static_cast<BasicReplica *>(replicaList[0]);
  553. //raknet 4.0b8
  554. GameObjectReplica *replica = static_cast<GameObjectReplica *>(replicaList[0]);
  555. AddLogMessage("Selected entity: " + replica->GetEntityName());
  556. return replica;
  557. }
  558. // Otherwise, find the current object and then return the next one on the stack.
  559. // If the current object was the last one on the list, return null (deselect object)
  560. //DataStructures::DefaultIndexType i = 0;
  561. for(unsigned i = 0; i < replicaList.Size(); i++)
  562. {
  563. //BasicReplica *replica = static_cast<BasicReplica *>(replicaList[i]);
  564. //raknet 4.0b8
  565. GameObjectReplica *replica = static_cast<GameObjectReplica *>(replicaList[i]);
  566. if(currentEntityPtr == replica)
  567. {
  568. //BasicReplica *replicaToReturn = (i+1 < replicaList.GetSize())? static_cast<BasicReplica *>(replicaList[i+1]) : NULL;
  569. //
  570. GameObjectReplica *replicaToReturn = (i+1 < replicaList.Size())? static_cast<GameObjectReplica *>(replicaList[i+1]) : NULL;
  571. if(replicaToReturn != NULL)
  572. AddLogMessage("Selected entity: " + replicaToReturn->GetEntityName());
  573. else
  574. AddLogMessage("Reset selection.");
  575. return replicaToReturn;
  576. }
  577. }
  578. }
  579. return NULL;
  580. }
  581. /// ProcessMessages - Processes incoming messages through the RakPeerInterface.
  582. ///
  583. /// This function can be edited to handle custom ID types (the first byte of rakPacket->data)
  584. ///
  585. /// Returns:
  586. /// NETMANAGER_FAILURE, if the NetManager is not started (ie., in INACTIVE state)
  587. /// NETMANAGER_SUCCESS, otherwise.
  588. int
  589. NetManager::ProcessMessages()
  590. {
  591. if(NotStarted()) return NETMANAGER_FAILURE;
  592. if(subsystem == RAKNET)
  593. {
  594. for (rakPacket = networkInterface->Receive(); rakPacket; networkInterface->DeallocatePacket(rakPacket), rakPacket = networkInterface->Receive())
  595. {
  596. switch (rakPacket->data[0])
  597. {
  598. case ID_CONNECTION_ATTEMPT_FAILED:
  599. {
  600. AddLogMessage("ID_CONNECTION_ATTEMPT_FAILED\n");
  601. networkInterface->Shutdown(0);
  602. managerStatus = INACTIVE;
  603. if(outputLog.is_open()) outputLog << "[NetManager] ID_CONNECTION_ATTEMPT_FAILED" << endl;
  604. break;
  605. }
  606. case ID_NO_FREE_INCOMING_CONNECTIONS:
  607. {
  608. AddLogMessage("ID_NO_FREE_INCOMING_CONNECTIONS\n");
  609. networkInterface->Shutdown(0);
  610. managerStatus = INACTIVE;
  611. if(outputLog.is_open()) outputLog << "[NetManager] ID_NO_FREE_INCOMING_CONNECTION" << endl;
  612. break;
  613. }
  614. case ID_CONNECTION_REQUEST_ACCEPTED:
  615. {
  616. AddLogMessage("ID_CONNECTION_REQUEST_ACCEPTED\n");
  617. managerStatus = RUNNING;
  618. if(outputLog.is_open()) outputLog << "[NetManager] ID_CONNECTION_REQUEST_ACCEPTED" << endl;
  619. break;
  620. }
  621. case ID_NEW_INCOMING_CONNECTION:
  622. {
  623. std::string buffer = "ID_NEW_INCOMING_CONNECTION from ";
  624. buffer.append(rakPacket->systemAddress.ToString());
  625. AddLogMessage(buffer);
  626. if(outputLog.is_open()) outputLog << "[NetManager] ID_NEW_INCOMING_CONNECTION" << endl;
  627. break;
  628. }
  629. case ID_DISCONNECTION_NOTIFICATION:
  630. {
  631. AddLogMessage("ID_DISCONNECTION_NOTIFICATION\n");
  632. if(outputLog.is_open()) outputLog << "[NetManager] ID_DISCONNECTION_NOTIFICATION" << endl;
  633. break;
  634. }
  635. case ID_CONNECTION_LOST:
  636. {
  637. AddLogMessage("ID_CONNECTION_LOST\n");
  638. if(outputLog.is_open()) outputLog << "[NetManager] ID_CONNECTION_LOST" << endl;
  639. break;
  640. }
  641. case ID_ADVERTISE_SYSTEM:
  642. {
  643. //Edited: Originally, rakPacket->systemAddress.port
  644. //Dustin Farris: RakNet 4.033 rakPacket->systemAddress.GetPort() changed from rakPacket->systemAddress.port
  645. networkInterface->Connect(rakPacket->systemAddress.ToString(false), rakPacket->systemAddress.GetPort(),0,0);
  646. if(outputLog.is_open()) outputLog << "[NetManager] ID_ADVERTISE_SYSTEM" << endl;
  647. break;
  648. }
  649. default:
  650. {
  651. break;
  652. }
  653. } // end of switch(rakPacket->data[0])
  654. // if we have a custom packet handler, pass the message on
  655. // in case the application wants to do something special
  656. // in response to the packet we just received
  657. if (m_pCustomPacketHandler)
  658. (*m_pCustomPacketHandler)(rakPacket);
  659. } // end of for(rakPacket = networkInterface->Receive();...
  660. } // end of if(subsystem == RAKNET)
  661. return NETMANAGER_SUCCESS;
  662. }
  663. /// SendPacket - Sends data to a connection.
  664. ///
  665. /// Parameters:
  666. /// messageType - an ID value representing the message type. Taken from the enum DefaultMessageIDTypes or user-defined.
  667. /// message - the data to be sent
  668. /// messageLength - the length of the data to send
  669. /// messagePriority - the message priority value, taken from enum PacketPriority
  670. /// messageReliability - the message reliability value, taken from enum PacketReliability
  671. /// channel - the ordering channel. Default value is 0
  672. /// destination - the destination system information (IP, port). Default value is UNASSIGNED_SYSTEM_ADDRESS (RakNet value reserved for unknown system)
  673. /// broadcast - whether to broadcast the message to all connected systems. When this is true, destination refers to which system to skip.
  674. ///
  675. /// Returns:
  676. /// NETMANAGER_FAILURE, if the call to RakPeerInterface->Send() returns false (send failure) or the system isn't connected.
  677. /// NETMANAGER_SUCCESS, otherwise.
  678. int
  679. //NetManager::SendPacket(int messageType, const char *message, int messageLength, int messagePriority, int messageReliability, int channel, SystemAddress destination, bool broadcast)
  680. //raknet 4.0b8
  681. NetManager::SendPacket(int messageType, const char *message, int messageLength, int messagePriority, int messageReliability, int channel, RakNet::SystemAddress destination, bool broadcast)
  682. {
  683. if(NotStarted()) return NETMANAGER_FAILURE;
  684. //bool sendResult = false;
  685. //raknet 4.0b8
  686. uint32_t sendResult;
  687. if(subsystem == RAKNET)
  688. {
  689. RakNet::BitStream messageOut;
  690. messageOut.Write((unsigned char)messageType);
  691. messageOut.Write(message, messageLength);
  692. sendResult = networkInterface->Send(&messageOut, static_cast<PacketPriority>(messagePriority), static_cast<PacketReliability>(messageReliability),
  693. (char)channel, destination, broadcast);
  694. }
  695. //return( (sendResult)? NETMANAGER_SUCCESS : NETMANAGER_FAILURE );
  696. //RakNet 4.0b8
  697. if(sendResult==0)
  698. {
  699. return NETMANAGER_FAILURE;
  700. }
  701. else
  702. {
  703. return NETMANAGER_SUCCESS;
  704. }
  705. }
  706. /// SendPacket - Sends data saved in a BitStream to a connection.
  707. ///
  708. /// This function assumes that the data--including the messageType ID--has been previously written to a BitStream object.
  709. ///
  710. /// Parameters:
  711. /// message - the data previously written to the BitStream
  712. /// messagePriority - the message priority value, taken from enum PacketPriority
  713. /// messageReliability - the message reliability value, taken from enum PacketReliability
  714. /// channel - the ordering channel. Default value is 0
  715. /// destination - the destination system information (IP, port). Default value is UNASSIGNED_SYSTEM_ADDRESS (RakNet value reserved for unknown system)
  716. /// broadcast - whether to broadcast the message to all connected systems. When this is true, destination refers to which system to skip.
  717. ///
  718. /// Returns:
  719. /// NETMANAGER_FAILURE, if the call to RakPeerInterface->Send() returns false (send failure) or the system isn't connected.
  720. /// NETMANAGER_SUCCESS, otherwise.
  721. int
  722. //NetManager::SendPacket(RakNet::BitStream &message, int messagePriority, int messageReliability, int channel, SystemAddress destination, bool broadcast)
  723. // raknet 4.0b8
  724. NetManager::SendPacket(RakNet::BitStream &message, int messagePriority, int messageReliability, int channel, RakNet::SystemAddress destination, bool broadcast)
  725. {
  726. if(NotStarted()) return NETMANAGER_FAILURE;
  727. //bool sendResult = false;
  728. //raknet 4.0b8
  729. uint32_t sendResult;
  730. if(subsystem == RAKNET)
  731. {
  732. sendResult = networkInterface->Send(&message, static_cast<PacketPriority>(messagePriority), static_cast<PacketReliability>(messageReliability),
  733. (char)channel, destination, broadcast);
  734. }
  735. //return( (sendResult)? NETMANAGER_SUCCESS : NETMANAGER_FAILURE );
  736. //raknet 4.0b8
  737. if(sendResult==0)
  738. {
  739. return NETMANAGER_FAILURE;
  740. }
  741. else
  742. {
  743. return NETMANAGER_SUCCESS;
  744. }
  745. }
  746. /// UpdateNetworkObjectsInScene - Updates the local replicas with Ogre information and sets scene data.
  747. ///
  748. /// This function assumes that the replica will create needed Ogre entities and scene nodes.
  749. ///
  750. /// Returns:
  751. /// NETMANAGER_FAILURE, if the pointer to the Ogre scene manager is NULL.
  752. /// NETMANAGER_SUCCESS, otherwise.
  753. int
  754. NetManager::UpdateNetworkObjectsInScene(Ogre::SceneManager *pSceneManager, EntityMapType &entityMap)
  755. {
  756. if(pSceneManager == NULL) return NETMANAGER_FAILURE;
  757. if(subsystem == RAKNET)
  758. {
  759. DataStructures::List<RakNet::Replica3*> fullReplicaList;
  760. // DataStructures::Multilist<ML_STACK, RakNet::Replica3 *> fullReplicaList;
  761. replicaManager.GetReferencedReplicaList(fullReplicaList);
  762. // For each replica in the replica manager
  763. // Determine the entity name (replica.entityName)
  764. // Determine the scene node name (replica.entityName + ".SN")
  765. // If the entity does not exist in the scene
  766. // Create a new scene node and assign it the determined scene node name
  767. // Create a new entity and assign it the determined entity name
  768. // Attach the new entity to the new scene node
  769. // Get a reference to the entity and its scene node
  770. for(unsigned index = 0; index < replicaManager.GetReplicaCount(); index++)
  771. {
  772. //BasicReplica *replica = static_cast<BasicReplica *>(replicaManager.GetReplicaAtIndex(index));
  773. //raknet 4.0b8
  774. GameObjectReplica *replica = static_cast<GameObjectReplica *>(replicaManager.GetReplicaAtIndex(index));
  775. if(replica != NULL)
  776. {
  777. Ogre::String objectName = replica->GetObjectName();
  778. Ogre::String entityName = replica->GetEntityName();
  779. // If the entity name isn't set and this is a server or a peer, set the entity name now
  780. // This case only appears to happen for server instances when objects are created before
  781. // any client has ever connected.
  782. //
  783. // The problem doesn't appear to occur if objects are created after all clients have
  784. // been disconnected.
  785. //
  786. // We cannot do this for objects that are not NetworkIDAuthorities because the name
  787. // contains the unique shared network object value, which is invalid for non-authorities.
  788. if(entityName.empty())
  789. {
  790. //if(networkIDManager.IsNetworkIDAuthority())
  791. //raknet 4.0b8
  792. if(topology==SERVER)
  793. {
  794. // Entity base name format: "objectName.guid"
  795. Ogre::String newEntityName = objectName + ".";
  796. //newEntityName.append(Ogre::StringConverter::toString((int)(replica->GetNetworkID().localSystemAddress)));
  797. //ranket 4.0b8
  798. newEntityName.append(Ogre::StringConverter::toString((int)(replica->GetNetworkID())));
  799. replica->SetEntityName(newEntityName.c_str());
  800. entityName = replica->GetEntityName();
  801. }
  802. else
  803. {
  804. // If the entity name isn't set and this is a client, skip this object because we don't yet have
  805. // a valid network ID to construct an entity name and the object shouldn't be rendered
  806. continue;
  807. }
  808. }
  809. Ogre::String derivedSceneNodeName = entityName + ".SN"; // Scene node name format: "objectName.guid.SN"
  810. Ogre::SceneNode *node;
  811. Ogre::Entity *entity;
  812. if(!pSceneManager->hasEntity(entityName))
  813. {
  814. node = pSceneManager->getRootSceneNode()->createChildSceneNode(derivedSceneNodeName);
  815. entity = pSceneManager->createEntity(entityName, replica->GetMeshName());
  816. node->attachObject(entity);
  817. }
  818. else
  819. {
  820. node = pSceneManager->getSceneNode(derivedSceneNodeName);
  821. entity = pSceneManager->getEntity(entityName);
  822. }
  823. // Originally I wanted to be able to change the mesh of an object if that value was
  824. // changed, but it appears you would have to destroy and then recreate the entity
  825. // with the new mesh, so I'm excluding that functionality for now.
  826. // Update the scene with the information in the replica
  827. node->setScale(replica->GetScale());
  828. node->setOrientation(replica->GetOrientation());
  829. //node->setPosition(replica->UpdateRenderPosition(replica->GetCreatingSystemGUID() == networkIDManager.GetGuid()));
  830. //raknet 4.0b8
  831. node->setPosition(replica->UpdateRenderPosition(replica->GetCreatingSystemGUID() == networkInterface->GetMyGUID()));
  832. // Update the entity name indicating that this entity was seen in the replica manager
  833. entityMap[entityName] = true;
  834. } // end of if(replica != NULL)
  835. } // end of for(DataStructures::DefaultIndexType index = 0;...
  836. } // end of if(subsystem == RAKNET)
  837. return NETMANAGER_SUCCESS;
  838. }
  839. /// SetMessageLog - Sets a pointer to a LogMessage deque, used for on-screen feedback
  840. ///
  841. /// Returns:
  842. /// NETMANAGER_FAILURE, if the pointer to the LogMessage deque is NULL.
  843. /// NETMANAGER_SUCCESS, otherwise.
  844. int
  845. NetManager::SetMessageLog(std::deque<LogMessage *> *newLog)
  846. {
  847. if(newLog == NULL) return NETMANAGER_FAILURE;
  848. globalLog = newLog;
  849. return NETMANAGER_SUCCESS;
  850. }
  851. /// AddLogMessage - Adds a new message to the LogMessage deque
  852. ///
  853. /// Returns:
  854. /// NETMANAGER_FAILURE, if the pointer to the LogMessage deque is NULL.
  855. /// NETMANAGER_SUCCESS, otherwise.
  856. int
  857. NetManager::AddLogMessage(std::string newMessage, int priority)
  858. {
  859. if(globalLog == NULL) return NETMANAGER_FAILURE;
  860. if(!globalLog->empty())
  861. globalLog->front()->messageAge += 1;
  862. globalLog->push_back(new LogMessage(newMessage, priority));
  863. return NETMANAGER_SUCCESS;
  864. }
  865. // LogMessage class stuff
  866. LogMessage::LogMessage() : messageAge(0), messagePriority(0), messageText("")
  867. {
  868. }
  869. LogMessage::LogMessage(std::string newMessage, int newPriority) : messageAge(0), messagePriority(newPriority), messageText(newMessage)
  870. {
  871. }
  872. LogMessage::~LogMessage()
  873. {
  874. }
  875. }