ConnectionManager.cpp 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441
  1. /*
  2. ** Command & Conquer Generals Zero Hour(tm)
  3. ** Copyright 2025 Electronic Arts Inc.
  4. **
  5. ** This program is free software: you can redistribute it and/or modify
  6. ** it under the terms of the GNU General Public License as published by
  7. ** the Free Software Foundation, either version 3 of the License, or
  8. ** (at your option) any later version.
  9. **
  10. ** This program is distributed in the hope that it will be useful,
  11. ** but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ** GNU General Public License for more details.
  14. **
  15. ** You should have received a copy of the GNU General Public License
  16. ** along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. ////////////////////////////////////////////////////////////////////////////////
  19. // //
  20. // (c) 2001-2003 Electronic Arts Inc. //
  21. // //
  22. ////////////////////////////////////////////////////////////////////////////////
  23. #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine
  24. #include "Compression.h"
  25. #include "strtok_r.h"
  26. #include "Common/AudioEventRTS.h"
  27. #include "Common/CRCDebug.h"
  28. #include "Common/Debug.h"
  29. #include "Common/File.h"
  30. #include "Common/GameAudio.h"
  31. #include "Common/LocalFileSystem.h"
  32. #include "Common/Player.h"
  33. #include "Common/PlayerList.h"
  34. #include "Common/RandomValue.h"
  35. #include "Common/Recorder.h"
  36. #include "GameClient/Diplomacy.h"
  37. #include "GameClient/GameText.h"
  38. #include "GameClient/MessageBox.h"
  39. #include "GameNetwork/ConnectionManager.h"
  40. #include "GameNetwork/LANAPICallbacks.h"
  41. #include "GameNetwork/NAT.h"
  42. #include "GameNetwork/NetCommandWrapperList.h"
  43. #include "GameNetwork/NetworkUtil.h"
  44. #include "GameLogic/GameLogic.h"
  45. #include "GameLogic/ScriptActions.h"
  46. #include "GameLogic/ScriptEngine.h"
  47. #include "GameLogic/VictoryConditions.h"
  48. #include "GameClient/DisconnectMenu.h"
  49. #include "GameClient/InGameUI.h"
  50. #ifdef _INTERNAL
  51. // for occasional debugging...
  52. //#pragma optimize("", off)
  53. //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes")
  54. #endif
  55. /**
  56. * Le destructor.
  57. */
  58. ConnectionManager::~ConnectionManager(void)
  59. {
  60. if (m_localUser != NULL) {
  61. m_localUser->deleteInstance();
  62. m_localUser = NULL;
  63. }
  64. // m_transport = NULL; // Network will delete transports; we just forget them
  65. if (m_transport != NULL) {
  66. delete m_transport;
  67. m_transport = NULL;
  68. }
  69. for (Int i = 0; i < MAX_SLOTS; ++i) {
  70. if (m_frameData[i] != NULL) {
  71. m_frameData[i]->deleteInstance();
  72. m_frameData[i] = NULL;
  73. }
  74. }
  75. for (i = 0; i < NUM_CONNECTIONS; ++i) {
  76. if (m_connections[i] != NULL) {
  77. m_connections[i]->deleteInstance();
  78. m_connections[i] = NULL;
  79. }
  80. }
  81. if (TheDisconnectMenu != NULL) {
  82. // This is done here since TheDisconnectMenu should only be there if we are in a network game.
  83. delete TheDisconnectMenu;
  84. TheDisconnectMenu = NULL;
  85. }
  86. if (m_disconnectManager != NULL) {
  87. delete m_disconnectManager;
  88. m_disconnectManager = NULL;
  89. }
  90. if (m_pendingCommands != NULL) {
  91. m_pendingCommands->deleteInstance();
  92. m_pendingCommands = NULL;
  93. }
  94. if (m_relayedCommands != NULL) {
  95. m_relayedCommands->deleteInstance();
  96. m_relayedCommands = NULL;
  97. }
  98. if (m_netCommandWrapperList != NULL) {
  99. m_netCommandWrapperList->deleteInstance();
  100. m_netCommandWrapperList = NULL;
  101. }
  102. s_fileCommandMap.clear();
  103. s_fileRecipientMaskMap.clear();
  104. for (i = 0; i < MAX_SLOTS; ++i) {
  105. s_fileProgressMap[i].clear();
  106. }
  107. }
  108. /**
  109. * Le constructor
  110. */
  111. ConnectionManager::ConnectionManager(void)
  112. {
  113. for (Int i = 0; i < MAX_SLOTS; ++i) {
  114. m_frameData[i] = NULL;
  115. }
  116. m_transport = NULL;
  117. m_disconnectManager = NULL;
  118. m_pendingCommands = NULL;
  119. m_relayedCommands = NULL;
  120. m_localAddr = 0;
  121. m_localPort = 0;
  122. m_netCommandWrapperList = NULL;
  123. m_localUser = NULL;
  124. m_localUser = newInstance(User);
  125. }
  126. /**
  127. * Initialize the connection manager and any subsystems.
  128. */
  129. void ConnectionManager::init()
  130. {
  131. // if (m_transport == NULL) {
  132. // m_transport = new Transport;
  133. // }
  134. // m_transport->reset();
  135. for (UnsignedInt i = 0; i < NUM_CONNECTIONS; ++i) {
  136. m_connections[i] = NULL;
  137. }
  138. if (m_pendingCommands == NULL) {
  139. m_pendingCommands = newInstance(NetCommandList);
  140. m_pendingCommands->init();
  141. }
  142. m_pendingCommands->reset();
  143. if (m_relayedCommands == NULL) {
  144. m_relayedCommands = newInstance(NetCommandList);
  145. m_relayedCommands->init();
  146. }
  147. m_relayedCommands->reset();
  148. m_localSlot = -1;
  149. #ifdef MEMORYPOOL_DEBUG
  150. TheMemoryPoolFactory->debugSetInitFillerIndex(m_localSlot);
  151. #endif
  152. m_packetRouterSlot = 0; /// @todo The LAN/WOL interface should be telling us who the packet router is based on machine specs passed around through game options.
  153. for (i = 0; i < MAX_SLOTS; ++i) {
  154. m_packetRouterFallback[i] = -1;
  155. }
  156. for (i = 0; i < MAX_SLOTS; ++i) {
  157. if (m_frameData[i] != NULL) {
  158. m_frameData[i]->deleteInstance();
  159. m_frameData[i] = NULL;
  160. }
  161. }
  162. // m_averageFps = 30; // since 30 fps is the desired rate, we'll start off at that.
  163. // m_averageLatency = (Real)0.2; // 200ms seems like a good starting point.
  164. for (i = 0; i < MAX_SLOTS; ++i) {
  165. m_fpsAverages[i] = -1;
  166. }
  167. for (i = 0; i < MAX_SLOTS; ++i) {
  168. m_latencyAverages[i] = 0.0; // using zero since all floating point standards should be able to specify 0.0 accurately.
  169. }
  170. m_smallestPacketArrivalCushion = -1;
  171. m_frameMetrics.init();
  172. TheDisconnectMenu = NEW DisconnectMenu;
  173. TheDisconnectMenu->init();
  174. m_disconnectManager = NEW DisconnectManager;
  175. m_disconnectManager->init();
  176. TheDisconnectMenu->attachDisconnectManager(m_disconnectManager);
  177. TheDisconnectMenu->hideScreen();
  178. m_netCommandWrapperList = newInstance(NetCommandWrapperList);
  179. m_netCommandWrapperList->init();
  180. s_fileCommandMap.clear();
  181. s_fileRecipientMaskMap.clear();
  182. for (i = 0; i < MAX_SLOTS; ++i) {
  183. s_fileProgressMap[i].clear();
  184. }
  185. }
  186. /**
  187. * Reset the connection manager and any subsystems.
  188. */
  189. void ConnectionManager::reset()
  190. {
  191. // if (m_transport == NULL) {
  192. // m_transport = new Transport;
  193. // }
  194. // m_transport->reset();
  195. if (m_transport != NULL) {
  196. delete m_transport;
  197. m_transport = NULL;
  198. }
  199. for (Int i = 0; i < NUM_CONNECTIONS; ++i) {
  200. if (m_connections[i] != NULL) {
  201. m_connections[i]->deleteInstance();
  202. m_connections[i] = NULL;
  203. }
  204. }
  205. for (i=0; i<MAX_SLOTS; ++i)
  206. {
  207. if (m_frameData[i] != NULL) {
  208. m_frameData[i]->deleteInstance();
  209. m_frameData[i] = NULL;
  210. }
  211. }
  212. if (m_pendingCommands == NULL) {
  213. m_pendingCommands = newInstance(NetCommandList);
  214. m_pendingCommands->init();
  215. }
  216. m_pendingCommands->reset();
  217. if (m_relayedCommands == NULL) {
  218. m_relayedCommands = newInstance(NetCommandList);
  219. m_relayedCommands->init();
  220. }
  221. m_relayedCommands->reset();
  222. if (m_netCommandWrapperList == NULL) {
  223. m_netCommandWrapperList = newInstance(NetCommandWrapperList);
  224. m_netCommandWrapperList->init();
  225. }
  226. m_netCommandWrapperList->reset();
  227. m_localSlot = -1;
  228. #ifdef MEMORYPOOL_DEBUG
  229. TheMemoryPoolFactory->debugSetInitFillerIndex(m_localSlot);
  230. #endif
  231. m_packetRouterSlot = -1;
  232. for (i = 0; i < TheGlobalData->m_networkFPSHistoryLength; ++i) {
  233. m_fpsAverages[i] = -1;
  234. }
  235. for (i = 0; i < TheGlobalData->m_networkLatencyHistoryLength; ++i) {
  236. m_latencyAverages[i] = 0.0;
  237. }
  238. for (i = 0; i < MAX_SLOTS; ++i) {
  239. m_packetRouterFallback[i] = -1;
  240. }
  241. m_frameMetrics.reset();
  242. }
  243. UnsignedInt ConnectionManager::getPingFrame()
  244. {
  245. return (m_disconnectManager)?m_disconnectManager->getPingFrame():0;
  246. }
  247. Int ConnectionManager::getPingsSent()
  248. {
  249. return (m_disconnectManager)?m_disconnectManager->getPingsSent():0;
  250. }
  251. Int ConnectionManager::getPingsRecieved()
  252. {
  253. return (m_disconnectManager)?m_disconnectManager->getPingsRecieved():0;
  254. }
  255. Bool ConnectionManager::isPlayerConnected( Int playerID )
  256. {
  257. return ( playerID == m_localSlot || (m_connections[playerID] && !m_connections[playerID]->isQuitting()) );
  258. }
  259. void ConnectionManager::attachTransport(Transport *transport) {
  260. if (m_transport != NULL) {
  261. delete m_transport;
  262. m_transport = NULL;
  263. }
  264. m_transport = transport;
  265. }
  266. /**
  267. * zero out the command counts for the given frames. Presently this is used for
  268. * the start of a game since there won't be any commands for the first few frames due to runahead.
  269. */
  270. void ConnectionManager::zeroFrames(UnsignedInt startingFrame, UnsignedInt numFrames) {
  271. for (Int i = 0; i < MAX_SLOTS; ++i) {
  272. if (m_frameData[i] != NULL) {
  273. // DEBUG_LOG(("Calling zeroFrames on player %d, starting frame %d, numFrames %d\n", i, startingFrame, numFrames));
  274. m_frameData[i]->zeroFrames(startingFrame, numFrames);
  275. }
  276. }
  277. }
  278. /**
  279. * Destroy any game messages that are left over due to the run ahead.
  280. */
  281. void ConnectionManager::destroyGameMessages() {
  282. for (Int i = 0; i < MAX_SLOTS; ++i) {
  283. // Need to destroy these game messages because when the game ends, there are
  284. // still some game messages left over because of the run ahead aspect of
  285. // network play.
  286. if (m_frameData[i] != NULL) {
  287. m_frameData[i]->destroyGameMessages();
  288. }
  289. }
  290. }
  291. /**
  292. * ConnectionManager::doRelay()
  293. * Queries the transport for commands that need to be relayed to another client.
  294. * Get those commands and relay them to the appropriate Connection(s). We make the
  295. * assumption that a command will only be relayed once.
  296. */
  297. void ConnectionManager::doRelay() {
  298. static Int numPackets = 0;
  299. static Int numCommands = 0;
  300. NetPacket *packet = NULL;
  301. for (Int i = 0; i < MAX_MESSAGES; ++i) {
  302. if (m_transport->m_inBuffer[i].length != 0) {
  303. // This transport buffer has yet to be processed.
  304. // make a NetPacket out of this data so it can be broken up into individual commands.
  305. packet = newInstance(NetPacket)(&(m_transport->m_inBuffer[i]));
  306. //DEBUG_LOG(("ConnectionManager::doRelay() - got a packet with %d commands\n", packet->getNumCommands()));
  307. //LOGBUFFER( packet->getData(), packet->getLength() );
  308. // Get the command list from the packet.
  309. NetCommandList *cmdList = packet->getCommandList();
  310. NetCommandRef *cmd = cmdList->getFirstMessage();
  311. // Iterate through the commands in this packet and send them to the proper connections.
  312. while (cmd != NULL) {
  313. //DEBUG_LOG(("ConnectionManager::doRelay() - Looking at a command of type %s\n",
  314. //GetAsciiNetCommandType(cmd->getCommand()->getNetCommandType()).str()));
  315. if (CommandRequiresAck(cmd->getCommand())) {
  316. ackCommand(cmd, m_localSlot);
  317. }
  318. if (!processNetCommand(cmd)) {
  319. sendRemoteCommand(cmd);
  320. }
  321. cmd = cmd->getNext();
  322. ++numCommands;
  323. }
  324. ++numPackets;
  325. // Delete this packet since we won't be needing it anymore.
  326. packet->deleteInstance();
  327. packet = NULL;
  328. cmdList->deleteInstance();
  329. cmdList = NULL;
  330. // signal that this has been processed.
  331. m_transport->m_inBuffer[i].length = 0;
  332. }
  333. }
  334. NetCommandList *cmdList = m_netCommandWrapperList->getReadyCommands();
  335. NetCommandRef *cmd = cmdList->getFirstMessage();
  336. while (cmd != NULL) {
  337. if (CommandRequiresAck(cmd->getCommand())) {
  338. ackCommand(cmd, m_localSlot);
  339. }
  340. if (!processNetCommand(cmd)) {
  341. sendRemoteCommand(cmd);
  342. }
  343. cmd = cmd->getNext();
  344. ++numCommands;
  345. }
  346. ++numPackets;
  347. // Delete this packet since we won't be needing it anymore.
  348. packet->deleteInstance();
  349. packet = NULL;
  350. cmdList->deleteInstance();
  351. cmdList = NULL;
  352. }
  353. /**
  354. * This is where the non-synchronized network commands should be processed.
  355. * Return TRUE if the command should not be relayed. Return FALSE if it should be relayed.
  356. */
  357. Bool ConnectionManager::processNetCommand(NetCommandRef *ref) {
  358. NetCommandMsg *msg = ref->getCommand();
  359. if ((msg->getNetCommandType() == NETCOMMANDTYPE_ACKSTAGE1) ||
  360. (msg->getNetCommandType() == NETCOMMANDTYPE_ACKSTAGE2) ||
  361. (msg->getNetCommandType() == NETCOMMANDTYPE_ACKBOTH)) {
  362. processAck(msg);
  363. return FALSE;
  364. }
  365. if ((m_connections[msg->getPlayerID()] == NULL) && (msg->getPlayerID() != m_localSlot)) {
  366. // if this is from a player that is no longer in the game, then ignore them.
  367. return TRUE;
  368. }
  369. if (msg->getNetCommandType() == NETCOMMANDTYPE_WRAPPER) {
  370. processWrapper(ref); // need to send the NetCommandRef since we have to construct the relay for the wrapped command.
  371. return FALSE;
  372. }
  373. if ((msg->getPlayerID() >= 0) && (msg->getPlayerID() < MAX_SLOTS) && (msg->getPlayerID() != m_localSlot)) {
  374. if (m_connections[msg->getPlayerID()] == NULL) {
  375. return TRUE;
  376. }
  377. }
  378. // Don't allow an out of date command to be sent through.
  379. // Its unnecessary traffic and it could cause problems.
  380. //
  381. // This was a fix for a command count bug where a command would be
  382. // executed, then a command for that old frame would be added to the
  383. // FrameData for that frame + 256, and would screw up the command count.
  384. if (IsCommandSynchronized(msg->getNetCommandType())) {
  385. if (ref->getCommand()->getExecutionFrame() < TheGameLogic->getFrame()) {
  386. return TRUE;
  387. }
  388. }
  389. if (msg->getNetCommandType() == NETCOMMANDTYPE_FRAMEINFO) {
  390. processFrameInfo((NetFrameCommandMsg *)msg);
  391. // need to set the relay so we don't send it to ourselves.
  392. UnsignedByte relay = ref->getRelay();
  393. relay = relay & (0xff ^ (1 << m_localSlot));
  394. ref->setRelay(relay);
  395. return FALSE;
  396. }
  397. if (msg->getNetCommandType() == NETCOMMANDTYPE_PROGRESS)
  398. {
  399. //DEBUG_LOG(("ConnectionManager::processNetCommand - got a progress net command from player %d\n", msg->getPlayerID()));
  400. processProgress((NetProgressCommandMsg *) msg);
  401. // need to set the relay so we don't send it to ourselves.
  402. UnsignedByte relay = ref->getRelay();
  403. relay = relay & (0xff ^ (1 << m_localSlot));
  404. ref->setRelay(relay);
  405. return FALSE;
  406. }
  407. if (msg->getNetCommandType() == NETCOMMANDTYPE_TIMEOUTSTART)
  408. {
  409. DEBUG_LOG(("ConnectionManager::processNetCommand - got a TimeOut GameStart net command from player %d\n", msg->getPlayerID()));
  410. processTimeOutGameStart(msg);
  411. return FALSE;
  412. }
  413. if (msg->getNetCommandType() == NETCOMMANDTYPE_RUNAHEADMETRICS) {
  414. processRunAheadMetrics((NetRunAheadMetricsCommandMsg *)msg);
  415. return TRUE;
  416. }
  417. if (msg->getNetCommandType() == NETCOMMANDTYPE_KEEPALIVE) {
  418. return TRUE;
  419. }
  420. if ((msg->getNetCommandType() > NETCOMMANDTYPE_DISCONNECTSTART) && (msg->getNetCommandType() < NETCOMMANDTYPE_DISCONNECTEND)) {
  421. m_disconnectManager->processDisconnectCommand(ref, this);
  422. return TRUE;
  423. }
  424. if (msg->getNetCommandType() == NETCOMMANDTYPE_DISCONNECTCHAT) {
  425. processDisconnectChat((NetDisconnectChatCommandMsg *)msg);
  426. }
  427. if (msg->getNetCommandType() == NETCOMMANDTYPE_LOADCOMPLETE)
  428. {
  429. DEBUG_LOG(("ConnectionManager::processNetCommand - got a Load Complete net command from player %d\n", msg->getPlayerID()));
  430. processLoadComplete(msg);
  431. return FALSE;
  432. }
  433. if (msg->getNetCommandType() == NETCOMMANDTYPE_CHAT) {
  434. processChat((NetChatCommandMsg *)msg);
  435. return FALSE;
  436. }
  437. if (msg->getNetCommandType() == NETCOMMANDTYPE_FILE) {
  438. processFile((NetFileCommandMsg *)msg);
  439. return FALSE;
  440. }
  441. if (msg->getNetCommandType() == NETCOMMANDTYPE_FILEANNOUNCE) {
  442. processFileAnnounce((NetFileAnnounceCommandMsg *)msg);
  443. return FALSE;
  444. }
  445. if (msg->getNetCommandType() == NETCOMMANDTYPE_FILEPROGRESS) {
  446. processFileProgress((NetFileProgressCommandMsg *)msg);
  447. return FALSE;
  448. }
  449. if (msg->getNetCommandType() == NETCOMMANDTYPE_FRAMERESENDREQUEST) {
  450. processFrameResendRequest((NetFrameResendRequestCommandMsg *)msg);
  451. return TRUE;
  452. }
  453. return FALSE;
  454. }
  455. void ConnectionManager::processFrameResendRequest(NetFrameResendRequestCommandMsg *msg) {
  456. // first make sure this is a valid slot
  457. Int playerID = msg->getPlayerID();
  458. if ((playerID < 0) || (playerID >= MAX_SLOTS)) {
  459. return;
  460. }
  461. // make sure this player is still in our game.
  462. if ((m_connections[playerID] == NULL) || (m_connections[playerID]->isQuitting() == TRUE)) {
  463. return;
  464. }
  465. sendFrameDataToPlayer(playerID, msg->getFrameToResend());
  466. }
  467. /**
  468. * We have received a wrapper for a command too big to fit in a packet.
  469. */
  470. void ConnectionManager::processWrapper(NetCommandRef *ref)
  471. {
  472. NetWrapperCommandMsg *wrapperMsg = (NetWrapperCommandMsg *)(ref->getCommand());
  473. UnsignedShort commandID = wrapperMsg->getWrappedCommandID();
  474. DEBUG_LOG(("ConnectionManager::processWrapper() - wrapped commandID is %d, commandID is %d\n",
  475. commandID, wrapperMsg->getID()));
  476. Int origProgress = 0;
  477. FileCommandMap::iterator fcIt = s_fileCommandMap.find(commandID);
  478. if (fcIt != s_fileCommandMap.end())
  479. {
  480. origProgress = s_fileProgressMap[m_localSlot][commandID];
  481. }
  482. DEBUG_LOG(("ConnectionManager::processWrapper() - origProgress[%d] == %d for command %d\n",
  483. m_localSlot, origProgress, commandID));
  484. m_netCommandWrapperList->processWrapper(ref);
  485. if (fcIt != s_fileCommandMap.end())
  486. {
  487. Int newProgress = m_netCommandWrapperList->getPercentComplete(commandID);
  488. DEBUG_LOG(("ConnectionManager::processWrapper() - newProgress[%d] == %d for command %d\n",
  489. m_localSlot, newProgress, commandID));
  490. if (newProgress > origProgress && newProgress < 100)
  491. {
  492. DEBUG_LOG(("ConnectionManager::processWrapper() - sending a NetFileProgressCommandMsg\n"));
  493. s_fileProgressMap[m_localSlot][commandID] = newProgress;
  494. Int progressMask = 0xff ^ (1 << m_localSlot);
  495. NetFileProgressCommandMsg *msg = newInstance(NetFileProgressCommandMsg);
  496. msg->setPlayerID(m_localSlot);
  497. msg->setID(0);
  498. if (DoesCommandRequireACommandID(msg->getNetCommandType()))
  499. {
  500. msg->setID(GenerateNextCommandID());
  501. }
  502. msg->setFileID(commandID);
  503. msg->setProgress(newProgress);
  504. sendLocalCommand(msg, progressMask);
  505. processFileProgress(msg);
  506. msg->detach();
  507. }
  508. }
  509. }
  510. /**
  511. * A client has sent us their run ahead metrics, lets store them away for future calculations.
  512. */
  513. void ConnectionManager::processRunAheadMetrics(NetRunAheadMetricsCommandMsg *msg)
  514. {
  515. UnsignedInt player = msg->getPlayerID();
  516. if ((player >= 0) && (player < MAX_SLOTS) && (isPlayerConnected(player))) {
  517. m_latencyAverages[player] = msg->getAverageLatency();
  518. m_fpsAverages[player] = msg->getAverageFps();
  519. //DEBUG_LOG(("ConnectionManager::processRunAheadMetrics - player %d, fps = %d, latency = %f\n", player, msg->getAverageFps(), msg->getAverageLatency()));
  520. if (m_fpsAverages[player] > 100) {
  521. // limit the reported frame rate average to 100. This is done because if a
  522. // user alt-tab's out of the game their frame rate climbs to in the neighborhood of
  523. // 300, that was deemed "ugly" by the powers that be.
  524. m_fpsAverages[player] = 100;
  525. }
  526. }
  527. }
  528. void ConnectionManager::processDisconnectChat(NetDisconnectChatCommandMsg *msg)
  529. {
  530. UnicodeString unitext;
  531. UnicodeString name;
  532. UnsignedByte playerID = msg->getPlayerID();
  533. if (playerID == m_localSlot) {
  534. name = m_localUser->GetName();
  535. } else if (isPlayerConnected(playerID)) {
  536. name = m_connections[playerID]->getUser()->GetName();
  537. }
  538. unitext.format(L"[%ls] %ls", name.str(), msg->getText().str());
  539. // DEBUG_LOG(("ConnectionManager::processDisconnectChat - got message from player %d, message is %ls\n", playerID, unitext.str()));
  540. TheDisconnectMenu->showChat(unitext); // <-- need to implement this
  541. }
  542. void ConnectionManager::processChat(NetChatCommandMsg *msg)
  543. {
  544. UnicodeString unitext;
  545. UnicodeString name;
  546. UnsignedByte playerID = msg->getPlayerID();
  547. //DEBUG_LOG(("processChat(): playerID = %d\n", playerID));
  548. if (playerID == m_localSlot) {
  549. name = m_localUser->GetName();
  550. //DEBUG_LOG(("connection is NULL, using %ls\n", name.str()));
  551. } else if (((m_connections[playerID] != NULL) && (m_connections[playerID]->isQuitting() == FALSE))) {
  552. name = m_connections[playerID]->getUser()->GetName();
  553. //DEBUG_LOG(("connection is non-NULL, using %ls\n", name.str()));
  554. }
  555. unitext.format(L"[%ls] %ls", name.str(), msg->getText().str());
  556. // DEBUG_LOG(("ConnectionManager::processChat - got message from player %d (mask %8.8X), message is %ls\n", playerID, msg->getPlayerMask(), unitext.str()));
  557. AsciiString playerName;
  558. playerName.format("player%d", msg->getPlayerID());
  559. const Player *player = ThePlayerList->findPlayerWithNameKey( TheNameKeyGenerator->nameToKey( playerName ) );
  560. if (!player)
  561. {
  562. TheInGameUI->message(UnicodeString(L"%ls"), unitext.str());
  563. return;
  564. }
  565. Bool fromObserver = !player->isPlayerActive();
  566. Bool amIObserver = !ThePlayerList->getLocalPlayer()->isPlayerActive();
  567. Bool canSeeChat = amIObserver || !fromObserver && !TheGameInfo->getConstSlot(playerID)->isMuted();
  568. if ( ((1<<m_localSlot) & msg->getPlayerMask() ) && canSeeChat )
  569. {
  570. RGBColor rgb;
  571. rgb.setFromInt(player->getPlayerColor());
  572. TheInGameUI->messageColor(&rgb, UnicodeString(L"%ls"), unitext.str());
  573. // feedback for received chat messages in-game
  574. AudioEventRTS audioEvent("GUICommunicatorIncoming");
  575. TheAudio->addAudioEvent(&audioEvent);
  576. }
  577. }
  578. void ConnectionManager::processFile(NetFileCommandMsg *msg)
  579. {
  580. #ifdef _INTERNAL
  581. UnicodeString log;
  582. log.format(L"Saw file transfer: '%hs' of %d bytes from %d", msg->getPortableFilename().str(), msg->getFileLength(), msg->getPlayerID());
  583. DEBUG_LOG(("%ls\n", log.str()));
  584. #endif
  585. if (TheFileSystem->doesFileExist(msg->getRealFilename().str()))
  586. {
  587. DEBUG_LOG(("File exists already!\n"));
  588. //return;
  589. }
  590. UnsignedByte *buf = msg->getFileData();
  591. Int len = msg->getFileLength();
  592. // uncompress Targas
  593. #ifdef COMPRESS_TARGAS
  594. Bool deleteBuf = FALSE;
  595. if (msg->getFilename().endsWith(".tga") && CompressionManager::isDataCompressed(buf, len))
  596. {
  597. Int uncompLen = CompressionManager::getUncompressedSize(buf, len);
  598. UnsignedByte *uncompBuffer = NEW UnsignedByte[uncompLen];
  599. Int actualLen = CompressionManager::decompressData(buf, len, uncompBuffer, uncompLen);
  600. if (actualLen == uncompLen)
  601. {
  602. DEBUG_LOG(("Uncompressed Targa after map transfer\n"));
  603. deleteBuf = TRUE;
  604. buf = uncompBuffer;
  605. len = uncompLen;
  606. }
  607. else
  608. {
  609. DEBUG_LOG(("Failed to uncompress Targa after map transfer\n"));
  610. delete[] uncompBuffer; // failed to decompress, so just use the source
  611. }
  612. }
  613. #endif // COMPRESS_TARGAS
  614. File *fp = TheFileSystem->openFile(msg->getRealFilename().str(), File::CREATE | File::BINARY | File::WRITE);
  615. if (fp)
  616. {
  617. fp->write(buf, len);
  618. fp->close();
  619. fp = NULL;
  620. DEBUG_LOG(("Wrote %d bytes to file %s!\n",len,msg->getRealFilename().str()));
  621. }
  622. else
  623. {
  624. DEBUG_LOG(("Cannot open file!\n"));
  625. }
  626. DEBUG_LOG(("ConnectionManager::processFile() - sending a NetFileProgressCommandMsg\n"));
  627. Int commandID = msg->getID();
  628. Int newProgress = 100;
  629. s_fileProgressMap[m_localSlot][commandID] = newProgress;
  630. Int progressMask = 0xff ^ (1 << m_localSlot);
  631. NetFileProgressCommandMsg *progressMsg = newInstance(NetFileProgressCommandMsg);
  632. progressMsg->setPlayerID(m_localSlot);
  633. progressMsg->setID(0);
  634. if (DoesCommandRequireACommandID(progressMsg->getNetCommandType()))
  635. {
  636. progressMsg->setID(GenerateNextCommandID());
  637. }
  638. progressMsg->setFileID(commandID);
  639. progressMsg->setProgress(newProgress);
  640. sendLocalCommand(progressMsg, progressMask);
  641. processFileProgress(progressMsg);
  642. progressMsg->detach();
  643. #ifdef COMPRESS_TARGAS
  644. if (deleteBuf)
  645. {
  646. delete[] buf;
  647. buf = NULL;
  648. }
  649. #endif // COMPRESS_TARGAS
  650. }
  651. void ConnectionManager::processFileAnnounce(NetFileAnnounceCommandMsg *msg)
  652. {
  653. DEBUG_LOG(("ConnectionManager::processFileAnnounce() - expecting '%s' (%s) in command %d\n", msg->getPortableFilename().str(), msg->getRealFilename().str(), msg->getFileID()));
  654. s_fileCommandMap[msg->getFileID()] = msg->getRealFilename();
  655. s_fileRecipientMaskMap[msg->getFileID()] = msg->getPlayerMask();
  656. for (Int i=0; i<MAX_SLOTS; ++i)
  657. {
  658. if ( (1<<i) & msg->getPlayerMask() )
  659. {
  660. s_fileProgressMap[i][msg->getFileID()] = 0;
  661. }
  662. else
  663. {
  664. s_fileProgressMap[i][msg->getFileID()] = 100; // they don't need to get it, so they're already done.
  665. }
  666. }
  667. }
  668. void ConnectionManager::processFileProgress(NetFileProgressCommandMsg *msg)
  669. {
  670. DEBUG_LOG(("ConnectionManager::processFileProgress() - command %d is at %d%%\n",
  671. msg->getFileID(), msg->getProgress()));
  672. Int oldProgress = s_fileProgressMap[msg->getPlayerID()][msg->getFileID()];
  673. s_fileProgressMap[msg->getPlayerID()][msg->getFileID()] = max(oldProgress, msg->getProgress());
  674. }
  675. void ConnectionManager::processProgress( NetProgressCommandMsg *msg )
  676. {
  677. TheGameLogic->processProgress(msg->getPlayerID(), msg->getPercentage());
  678. }
  679. void ConnectionManager::processLoadComplete( NetCommandMsg *msg )
  680. {
  681. TheGameLogic->processProgressComplete(msg->getPlayerID());
  682. }
  683. void ConnectionManager::processTimeOutGameStart( NetCommandMsg *msg )
  684. {
  685. TheGameLogic->timeOutGameStart();
  686. }
  687. /**
  688. * Another client has sent us the command count for a new frame.
  689. */
  690. void ConnectionManager::processFrameInfo(NetFrameCommandMsg *msg) {
  691. //stupid frame info, why don't you process yourself?
  692. UnsignedInt playerID = msg->getPlayerID();
  693. if ((playerID >= 0) && (playerID < MAX_SLOTS)) {
  694. if (m_frameData[playerID] != NULL) {
  695. // DEBUG_LOG(("ConnectionManager::processFrameInfo - player %d, frame %d, command count %d, received on frame %d\n", playerID, msg->getExecutionFrame(), msg->getCommandCount(), TheGameLogic->getFrame()));
  696. m_frameData[playerID]->setFrameCommandCount(msg->getExecutionFrame(), msg->getCommandCount());
  697. }
  698. }
  699. }
  700. /**
  701. * We just got a stage 1 ack from someone. So we should remove it from the connection that sent it so
  702. * it doesn't keep resending it.
  703. */
  704. void ConnectionManager::processAckStage1(NetCommandMsg *msg) {
  705. #if defined(_DEBUG) || defined(_INTERNAL)
  706. Bool doDebug = (msg->getNetCommandType() == NETCOMMANDTYPE_DISCONNECTFRAME) ? TRUE : FALSE;
  707. #endif
  708. UnsignedByte playerID = msg->getPlayerID();
  709. NetCommandRef *ref = NULL;
  710. #if defined(_DEBUG) || defined(_INTERNAL)
  711. if (doDebug == TRUE) {
  712. DEBUG_LOG(("ConnectionManager::processAck - processing ack for command %d from player %d\n", ((NetAckStage1CommandMsg *)msg)->getCommandID(), playerID));
  713. }
  714. #endif
  715. if ((playerID >= 0) && (playerID < NUM_CONNECTIONS)) {
  716. if (m_connections[playerID] != NULL) {
  717. ref = m_connections[playerID]->processAck(msg);
  718. }
  719. } else {
  720. DEBUG_ASSERTCRASH((playerID >= 0) && (playerID < NUM_CONNECTIONS), ("ConnectionManager::processAck - %d is an invalid player number"));
  721. }
  722. if (ref != NULL) {
  723. if (ref->getCommand()->getNetCommandType() == NETCOMMANDTYPE_FRAMEINFO) {
  724. m_frameMetrics.processLatencyResponse(((NetFrameCommandMsg *)(ref->getCommand()))->getExecutionFrame());
  725. }
  726. ref->deleteInstance();
  727. ref = NULL;
  728. }
  729. }
  730. /**
  731. * We just got a stage 2 ack from someone. So remove it from the pending commands list so it doesn't
  732. * get sent in the case of a new packet router.
  733. */
  734. void ConnectionManager::processAckStage2(NetCommandMsg *msg) {
  735. UnsignedShort commandID = 0;
  736. UnsignedByte playerID = 0;
  737. if (msg->getNetCommandType() == NETCOMMANDTYPE_ACKSTAGE2) {
  738. commandID = ((NetAckStage2CommandMsg *)msg)->getCommandID();
  739. playerID = ((NetAckStage2CommandMsg *)msg)->getOriginalPlayerID();
  740. } else if (msg->getNetCommandType() == NETCOMMANDTYPE_ACKBOTH) {
  741. commandID = ((NetAckBothCommandMsg *)msg)->getCommandID();
  742. playerID = ((NetAckBothCommandMsg *)msg)->getOriginalPlayerID();
  743. } else {
  744. return;
  745. }
  746. NetCommandRef *ref = m_pendingCommands->findMessage(commandID, playerID);
  747. if (ref != NULL) {
  748. //DEBUG_LOG(("ConnectionManager::processAckStage2 - removing command %d from the pending commands list.\n", commandID));
  749. DEBUG_ASSERTCRASH((m_localSlot == playerID), ("Found a command in the pending commands list that wasn't originated by the local player"));
  750. m_pendingCommands->removeMessage(ref);
  751. ref->deleteInstance();
  752. ref = NULL;
  753. } else {
  754. //DEBUG_LOG(("ConnectionManager::processAckStage2 - Couldn't find command %d from player %d in the pending commands list.\n", commandID, playerID));
  755. }
  756. ref = m_relayedCommands->findMessage(commandID, playerID);
  757. if (ref != NULL) {
  758. //DEBUG_LOG(("ConnectionManager::processAckStage2 - found command ID %d from player %d in the relayed commands list.\n", commandID, playerID));
  759. UnsignedByte relay = ref->getRelay();
  760. //DEBUG_LOG(("ConnectionManager::processAckStage2 - relay was %d and is now ", relay));
  761. relay = relay & ~(1 << msg->getPlayerID());
  762. //DEBUG_LOG(("%d\n", relay));
  763. if (relay == 0) {
  764. //DEBUG_LOG(("ConnectionManager::processAckStage2 - relay is 0, removing command from the relayed commands list.\n"));
  765. m_relayedCommands->removeMessage(ref);
  766. NetAckStage2CommandMsg *ackmsg = newInstance(NetAckStage2CommandMsg)(ref->getCommand());
  767. sendLocalCommand(ackmsg, 1 << ackmsg->getOriginalPlayerID());
  768. ref->deleteInstance();
  769. ref = NULL;
  770. ackmsg->detach();
  771. ackmsg = NULL;
  772. } else {
  773. ref->setRelay(relay);
  774. }
  775. }
  776. }
  777. /**
  778. * We just got a "both" ack from someone. So process it as both a stage 1 and stage 2 ack.
  779. */
  780. void ConnectionManager::processAck(NetCommandMsg *msg) {
  781. if ((msg->getNetCommandType() == NETCOMMANDTYPE_ACKSTAGE1) || (msg->getNetCommandType() == NETCOMMANDTYPE_ACKBOTH)) {
  782. processAckStage1(msg);
  783. }
  784. if ((msg->getNetCommandType() == NETCOMMANDTYPE_ACKSTAGE2) || (msg->getNetCommandType() == NETCOMMANDTYPE_ACKBOTH)) {
  785. processAckStage2(msg);
  786. }
  787. }
  788. /**
  789. * A player has just left our game. Delete their connection and frame data manager.
  790. * return codes are:
  791. * PLAYERLEAVECODE_UNKNOWN - player didn't have a valid slot number.
  792. * PLAYERLEAVECODE_CLIENT - someone in the game that wasn't us or the packet router.
  793. * PLAYERLEAVECODE_LOCAL - We are leaving the game, we could also be the packet router.
  794. * PLAYERLEAVECODE_PACKETROUTER - The packet router left the game.
  795. *
  796. * If we are leaving and are also the packet router, it will return the PLAYERLEAVECODE_LOCAL return code.
  797. */
  798. PlayerLeaveCode ConnectionManager::processPlayerLeave(NetPlayerLeaveCommandMsg *msg) {
  799. UnsignedByte playerID = msg->getLeavingPlayerID();
  800. if ((playerID != m_localSlot) && (m_connections[playerID] != NULL)) {
  801. DEBUG_LOG(("ConnectionManager::processPlayerLeave() - setQuitting() on player %d on frame %d\n", playerID, TheGameLogic->getFrame()));
  802. m_connections[playerID]->setQuitting();
  803. }
  804. DEBUG_ASSERTCRASH(m_frameData[playerID]->getIsQuitting() == FALSE, ("Player %d is already quitting", playerID));
  805. if ((playerID != m_localSlot) && (m_frameData[playerID] != NULL) && (m_frameData[playerID]->getIsQuitting() == FALSE)) {
  806. DEBUG_LOG(("ConnectionManager::processPlayerLeave - setQuitFrame on player %d for frame %d\n", playerID, TheGameLogic->getFrame()+1));
  807. m_frameData[playerID]->setQuitFrame(TheGameLogic->getFrame() + FRAMES_TO_KEEP + 1);
  808. }
  809. if (playerID == m_localSlot)
  810. {
  811. // we're leaving, so mark our connections and frame datas to go away.
  812. for (Int i=0; i<MAX_SLOTS; ++i)
  813. {
  814. if (m_connections[i])
  815. {
  816. m_connections[i]->clearCommandsExceptFrom(m_localSlot);
  817. m_connections[i]->setQuitting();
  818. }
  819. }
  820. }
  821. PlayerLeaveCode code = disconnectPlayer(playerID);
  822. DEBUG_LOG(("ConnectionManager::processPlayerLeave() - just disconnected player %d with ret code %d\n", playerID, code));
  823. if (code == PLAYERLEAVECODE_PACKETROUTER)
  824. resendPendingCommands();
  825. PopulateInGameDiplomacyPopup();
  826. return code;
  827. }
  828. UnsignedInt ConnectionManager::getPacketRouterFallbackSlot(Int packetRouterNumber) {
  829. if ((packetRouterNumber >= 0) && (packetRouterNumber < MAX_SLOTS)) {
  830. return m_packetRouterFallback[packetRouterNumber];
  831. }
  832. return MAX_SLOTS;
  833. }
  834. UnsignedInt ConnectionManager::getPacketRouterSlot() {
  835. return m_packetRouterSlot;
  836. }
  837. Bool ConnectionManager::areAllQueuesEmpty(void) {
  838. Bool retval = TRUE;
  839. for (Int i = 0; (i < MAX_SLOTS) && retval; ++i) {
  840. if (m_connections[i] != NULL) {
  841. if (m_connections[i]->isQueueEmpty() == FALSE) {
  842. //DEBUG_LOG(("ConnectionManager::areAllQueuesEmpty() - m_connections[%d] is not empty\n", i));
  843. //m_connections[i]->debugPrintCommands();
  844. retval = FALSE;
  845. }
  846. }
  847. }
  848. return retval;
  849. }
  850. Bool ConnectionManager::canILeave() {
  851. return areAllQueuesEmpty();
  852. }
  853. /**
  854. * The local player is leaving. Tell the local player as well as the other players
  855. * to remove this player at the specified frame.
  856. */
  857. void ConnectionManager::handleLocalPlayerLeaving(UnsignedInt frame) {
  858. NetPlayerLeaveCommandMsg *msg = newInstance(NetPlayerLeaveCommandMsg);
  859. msg->setLeavingPlayerID(m_localSlot);
  860. msg->setExecutionFrame(frame);
  861. if (DoesCommandRequireACommandID(msg->getNetCommandType())) {
  862. msg->setID(GenerateNextCommandID());
  863. }
  864. msg->setPlayerID(m_localSlot);
  865. DEBUG_LOG(("ConnectionManager::handleLocalPlayerLeaving - Local player leaving on frame %d\n", frame));
  866. DEBUG_ASSERTCRASH(m_packetRouterSlot >= 0, ("ConnectionManager::handleLocalPlayerLeaving, packet router is %d, illegal value.", m_packetRouterSlot));
  867. sendLocalCommand(msg);
  868. msg->detach();
  869. }
  870. /**
  871. * We just got a message that needs to be ack'd, so ack it!
  872. */
  873. void ConnectionManager::ackCommand(NetCommandRef *ref, UnsignedInt localSlot) {
  874. NetCommandMsg *msg = ref->getCommand();
  875. NetCommandMsg *ackmsg;
  876. UnsignedShort commandID;
  877. UnsignedByte originalPlayerID;
  878. UnsignedByte sendRelay = 0;
  879. // Make send relay a bitmask for the connections that the relay will actually be sent to. This is
  880. // necessary to determine whether or not we have to wait to send a stage 2 ack.
  881. for (Int i = 0; i < MAX_SLOTS; ++i) {
  882. if (((m_connections[i] != NULL) && (m_connections[i]->isQuitting() == FALSE))) {
  883. sendRelay = sendRelay | (1 << i);
  884. }
  885. }
  886. #if defined(_DEBUG) || defined(_INTERNAL)
  887. Bool doDebug = (msg->getNetCommandType() == NETCOMMANDTYPE_DISCONNECTFRAME) ? TRUE : FALSE;
  888. #endif
  889. sendRelay = sendRelay & ref->getRelay();
  890. if (sendRelay == 0) {
  891. NetAckBothCommandMsg *bothmsg = newInstance(NetAckBothCommandMsg)(ref->getCommand());
  892. ackmsg = bothmsg;
  893. commandID = bothmsg->getCommandID();
  894. originalPlayerID = bothmsg->getOriginalPlayerID();
  895. #if defined(_DEBUG) || defined(_INTERNAL)
  896. if (doDebug) {
  897. DEBUG_LOG(("ConnectionManager::ackCommand - doing ack both for command %d from player %d\n", bothmsg->getCommandID(), bothmsg->getOriginalPlayerID()));
  898. }
  899. #endif
  900. } else {
  901. NetAckStage1CommandMsg *stage1msg = newInstance(NetAckStage1CommandMsg)(ref->getCommand());
  902. ackmsg = stage1msg;
  903. commandID = stage1msg->getCommandID();
  904. originalPlayerID = stage1msg->getOriginalPlayerID();
  905. #if defined(_DEBUG) || defined(_INTERNAL)
  906. if (doDebug) {
  907. DEBUG_LOG(("ConnectionManager::ackCommand - doing ack stage 1 for command %d from player %d\n", stage1msg->getCommandID(), stage1msg->getOriginalPlayerID()));
  908. }
  909. #endif
  910. }
  911. ackmsg->setPlayerID(localSlot); // Tell the player who this ack is coming from.
  912. if (CommandRequiresDirectSend(msg) && CommandRequiresAck(msg)) {
  913. // Send this ack directly back to the sending player, don't go through the packet router.
  914. if ((msg->getPlayerID() >= 0) && (msg->getPlayerID() < MAX_SLOTS)) {
  915. if (m_connections[msg->getPlayerID()] != NULL) {
  916. m_connections[msg->getPlayerID()]->sendNetCommandMsg(ackmsg, 1 << msg->getPlayerID());
  917. }
  918. }
  919. } else {
  920. // The local connection may be the packet router, in that case, the connection would be NULL. So do something about it!
  921. if ((m_packetRouterSlot >= 0) && (m_packetRouterSlot < MAX_SLOTS)) {
  922. if (m_connections[m_packetRouterSlot] != NULL) {
  923. // DEBUG_LOG(("ConnectionManager::ackCommand - acking command %d from player %d to packet router.\n", commandID, m_packetRouterSlot));
  924. m_connections[m_packetRouterSlot]->sendNetCommandMsg(ackmsg, 1 << m_packetRouterSlot);
  925. } else if (m_localSlot == m_packetRouterSlot) {
  926. // we are the packet router, send the ack to the player that sent the command.
  927. if ((msg->getPlayerID() >= 0) && (msg->getPlayerID() < MAX_SLOTS)) {
  928. if (m_connections[msg->getPlayerID()] != NULL) {
  929. // DEBUG_LOG(("ConnectionManager::ackCommand - acking command %d from player %d directly to player.\n", commandID, msg->getPlayerID()));
  930. m_connections[msg->getPlayerID()]->sendNetCommandMsg(ackmsg, 1 << msg->getPlayerID());
  931. } else {
  932. // DEBUG_ASSERTCRASH(m_connections[msg->getPlayerID()] != NULL, ("Connection to player is NULL"));
  933. }
  934. } else {
  935. DEBUG_ASSERTCRASH((msg->getPlayerID() >= 0) && (msg->getPlayerID() < MAX_SLOTS), ("Command sent by an invalid player ID."));
  936. }
  937. } else {
  938. DEBUG_ASSERTCRASH(m_connections[m_packetRouterSlot] != NULL, ("Connection to packet router is NULL"));
  939. }
  940. } else {
  941. DEBUG_ASSERTCRASH((m_packetRouterSlot >= 0) && (m_packetRouterSlot < MAX_SLOTS), ("I don't know who the packet router is."));
  942. }
  943. }
  944. ackmsg->detach();
  945. }
  946. /**
  947. * This is where we relay a command from one client to others (including ourselves).
  948. * This should only be done by the current packet router.
  949. */
  950. void ConnectionManager::sendRemoteCommand(NetCommandRef *msg) {
  951. UnsignedByte actualRelay = 0;
  952. if (msg->getCommand() == NULL) {
  953. return;
  954. }
  955. DEBUG_LOG(("ConnectionManager::sendRemoteCommand - sending net command %d of type %s from player %d, relay is 0x%x\n",
  956. msg->getCommand()->getID(), GetAsciiNetCommandType(msg->getCommand()->getNetCommandType()).str(), msg->getCommand()->getPlayerID(), msg->getRelay()));
  957. UnsignedByte relay = msg->getRelay();
  958. if ((relay & (1 << m_localSlot)) && (m_frameData[msg->getCommand()->getPlayerID()] != NULL)) {
  959. if (IsCommandSynchronized(msg->getCommand()->getNetCommandType())) {
  960. DEBUG_LOG(("ConnectionManager::sendRemoteCommand - adding net command of type %s to player %d for frame %d\n", GetAsciiNetCommandType(msg->getCommand()->getNetCommandType()).str(), msg->getCommand()->getPlayerID(), msg->getCommand()->getExecutionFrame()));
  961. m_frameData[msg->getCommand()->getPlayerID()]->addNetCommandMsg(msg->getCommand());
  962. }
  963. }
  964. for (Int i = 0; i < MAX_SLOTS; ++i) {
  965. if ((relay & (1 << i)) && ((m_connections[i] != NULL) && (m_connections[i]->isQuitting() == FALSE))) {
  966. DEBUG_LOG(("ConnectionManager::sendRemoteCommand - relaying command %d to player %d\n", msg->getCommand()->getID(), i));
  967. m_connections[i]->sendNetCommandMsg(msg->getCommand(), 1 << i);
  968. actualRelay = actualRelay | (1 << i);
  969. }
  970. }
  971. if ((actualRelay != 0) && (CommandRequiresAck(msg->getCommand()) == TRUE)) {
  972. NetCommandRef *ref = m_relayedCommands->addMessage(msg->getCommand());
  973. if (ref != NULL) {
  974. ref->setRelay(actualRelay);
  975. //DEBUG_LOG(("ConnectionManager::sendRemoteCommand - command %d added to relayed commands with relay %d\n", msg->getCommand()->getID(), ref->getRelay()));
  976. }
  977. }
  978. // Do some metrics to find the minimum packet arrival cushion.
  979. if (IsCommandSynchronized(msg->getCommand()->getNetCommandType())) {
  980. // DEBUG_LOG(("ConnectionManager::sendRemoteCommand - about to call allCommandsReady\n"));
  981. if (allCommandsReady(msg->getCommand()->getExecutionFrame(), TRUE)) {
  982. UnsignedInt cushion = msg->getCommand()->getExecutionFrame() - TheGameLogic->getFrame();
  983. if ((cushion < m_smallestPacketArrivalCushion) || (m_smallestPacketArrivalCushion == -1)) {
  984. m_smallestPacketArrivalCushion = cushion;
  985. }
  986. m_frameMetrics.addCushion(cushion);
  987. // DEBUG_LOG(("Adding %d to cushion for frame %d\n", cushion, msg->getCommand()->getExecutionFrame()));
  988. }
  989. }
  990. }
  991. /**
  992. * ConnectionManager::update
  993. * Update the connections. Tell them to do the receive and send. Also relay
  994. * commands to their final destinations as necessary.
  995. */
  996. void ConnectionManager::update(Bool isInGame) {
  997. //
  998. // 1. do this
  999. // 2. do that
  1000. // 3. do something else
  1001. // 4. blow something up
  1002. // 5. bust some cap
  1003. //
  1004. if ((m_localAddr == 0) || (m_localPort == 0)) {
  1005. // we don't have a local address or port yet, this is bad.
  1006. DEBUG_ASSERTCRASH((m_localAddr != 0) && (m_localPort != 0), ("ConnectionManager doesn't have a local address."));
  1007. return;
  1008. }
  1009. m_transport->doRecv();
  1010. if (isInGame) {
  1011. m_disconnectManager->update(this);
  1012. }
  1013. // take the packets from the transport, break them up into commands, and give them to the appropriate connections.
  1014. doRelay();
  1015. // send any necessary keep-alive packets.
  1016. doKeepAlive();
  1017. for (Int i = 0; i < NUM_CONNECTIONS; ++i) {
  1018. if (m_connections[i] != NULL) {
  1019. /*
  1020. if (m_connections[i]->isQueueEmpty() == FALSE) {
  1021. // DEBUG_LOG(("ConnectionManager::update - calling doSend on connection %d\n", i));
  1022. }
  1023. */
  1024. m_connections[i]->doSend();
  1025. if (m_connections[i]->isQuitting() && m_connections[i]->isQueueEmpty())
  1026. {
  1027. DEBUG_LOG(("ConnectionManager::update - deleting connection for slot %d\n", i));
  1028. m_connections[i]->deleteInstance();
  1029. m_connections[i] = NULL;
  1030. }
  1031. }
  1032. if ((m_frameData[i] != NULL) && (m_frameData[i]->getIsQuitting() == TRUE)) {
  1033. if (m_frameData[i]->getQuitFrame() == TheGameLogic->getFrame()) {
  1034. DEBUG_LOG(("ConnectionManager::update - deleting frame data for slot %d on quitting frame %d\n", i, m_frameData[i]->getQuitFrame()));
  1035. m_frameData[i]->deleteInstance();
  1036. m_frameData[i] = NULL;
  1037. }
  1038. }
  1039. }
  1040. m_transport->doSend();
  1041. }
  1042. void ConnectionManager::updateRunAhead(Int oldRunAhead, Int frameRate, Bool didSelfSlug, Int nextExecutionFrame) {
  1043. static time_t lasttimesent = 0;
  1044. time_t curTime = timeGetTime();
  1045. if ((lasttimesent == 0) || ((curTime - lasttimesent) > TheGlobalData->m_networkRunAheadMetricsTime)) {
  1046. if (m_localSlot == m_packetRouterSlot) {
  1047. // We are the packet router, time to compute a new run ahead for this game.
  1048. m_latencyAverages[m_localSlot] = m_frameMetrics.getAverageLatency();
  1049. // since we are now using the display frame rate rather than the logic frame rate to get our average FPS,
  1050. // it doesn't make sense to send the desired logic frame rate if we "slugged" ourself.
  1051. // if (didSelfSlug) {
  1052. // m_fpsAverages[m_localSlot] = frameRate;
  1053. // } else {
  1054. m_fpsAverages[m_localSlot] = m_frameMetrics.getAverageFPS();
  1055. // }
  1056. if (didSelfSlug) {
  1057. //DEBUG_LOG(("ConnectionManager::updateRunAhead - local player run ahead metrics, fps = %d, actual fps = %d, latency = %f, didSelfSlug = true\n", m_fpsAverages[m_localSlot], m_frameMetrics.getAverageFPS(), m_latencyAverages[m_localSlot]));
  1058. } else {
  1059. //DEBUG_LOG(("ConnectionManager::updateRunAhead - local player run ahead metrics, fps = %d, latency = %f, didSelfSlug = false\n", m_fpsAverages[m_localSlot], m_latencyAverages[m_localSlot]));
  1060. }
  1061. Int minFps;
  1062. Int minFpsPlayer;
  1063. getMinimumFps(minFps, minFpsPlayer);
  1064. DEBUG_LOG(("ConnectionManager::updateRunAhead - max latency = %f, min fps = %d, min fps player = %d old FPS = %d\n", getMaximumLatency(), minFps, minFpsPlayer, frameRate));
  1065. if ((minFps >= ((frameRate * 9) / 10)) && (minFps < frameRate)) {
  1066. // if the minimum fps is within 10% of the desired framerate, then keep the current minimum fps.
  1067. minFps = frameRate;
  1068. }
  1069. if (minFps < 5) {
  1070. minFps = 5; // Absolutely do not run below 5 fps.
  1071. }
  1072. if (minFps > TheGlobalData->m_framesPerSecondLimit) {
  1073. minFps = TheGlobalData->m_framesPerSecondLimit; // Cap to 30 FPS.
  1074. }
  1075. DEBUG_LOG(("ConnectionManager::updateRunAhead - minFps after adjustment is %d\n", minFps));
  1076. Int newRunAhead = (Int)((getMaximumLatency() / 2.0) * (Real)minFps);
  1077. newRunAhead += (newRunAhead * TheGlobalData->m_networkRunAheadSlack) / 100; // Add in 10% of slack to the run ahead in case of network hiccups.
  1078. if (newRunAhead < MIN_RUNAHEAD) {
  1079. newRunAhead = MIN_RUNAHEAD; // make sure its at least MIN_RUNAHEAD.
  1080. }
  1081. if (newRunAhead > (MAX_FRAMES_AHEAD / 2)) {
  1082. newRunAhead = MAX_FRAMES_AHEAD / 2; // dont let run ahead get out of hand.
  1083. }
  1084. NetRunAheadCommandMsg *msg = newInstance(NetRunAheadCommandMsg);
  1085. msg->setPlayerID(m_localSlot);
  1086. if (DoesCommandRequireACommandID(msg->getNetCommandType())) {
  1087. msg->setID(GenerateNextCommandID());
  1088. }
  1089. // needs to be set to the greater of getExecutionFrame and TheGameLogic->getFrame() + oldRunAhead
  1090. // This prevents the case of...
  1091. // run ahead starts at 30
  1092. // run ahead changes to 10 at frame 31 (the command was created on frame 1)
  1093. // run ahead changes to 10 at frame 56 (the command was created on frame 46)
  1094. // notice that 56 is within the previous run ahead of 30 which has triggered
  1095. // the frame command count being set for frames 1 through 60 since run ahead
  1096. // didn't change for the first time till frame 31. This creates an extra command
  1097. // for frame 56 that isn't accounted for in the frame command count that is sent
  1098. // out in the NetFrameCommandMsg. sheesh.
  1099. if (nextExecutionFrame > (TheGameLogic->getFrame() + oldRunAhead)) {
  1100. msg->setExecutionFrame(nextExecutionFrame);
  1101. } else {
  1102. msg->setExecutionFrame(TheGameLogic->getFrame() + oldRunAhead);
  1103. }
  1104. msg->setRunAhead(newRunAhead);
  1105. msg->setFrameRate(minFps);
  1106. //DEBUG_LOG(("ConnectionManager::updateRunAhead - new run ahead = %d, new frame rate = %d, execution frame %d\n", newRunAhead, minFps, msg->getExecutionFrame()));
  1107. sendLocalCommand(msg, 0xff ^ (1 << minFpsPlayer)); // Send the packet to everyone but the lowest FPS player.
  1108. NetRunAheadCommandMsg *msg2 = newInstance(NetRunAheadCommandMsg);
  1109. msg2->setPlayerID(m_localSlot);
  1110. if (DoesCommandRequireACommandID(msg2->getNetCommandType())) {
  1111. /*
  1112. * Ok there needs to be a big friggin comment about this change...
  1113. * What happens is that the two run ahead commands get sent to different players
  1114. * using different command ID's. So player 1 has the run ahead command as command x
  1115. * and player 2 has the command as command x+1. This is all good except when it comes
  1116. * to players being disconnected. With the new disconnect scheme player 1 could potentially
  1117. * send his run ahead command to player 2 (or the other way around) to let player 2 catch
  1118. * up to him. So if player 2 has his run ahead command as x+1 and now he gets player 1's
  1119. * command list with the run ahead command listed as command x, he won't see them as being
  1120. * the same command and will now think he has two different run ahead commands for that frame
  1121. * and thus his command list will have an extra command and he will never be able to recover.
  1122. * So to fix this we have to use the same command ID for both run ahead commands. That way
  1123. * when the commands are copied places for the disconnect screen they will be seen as the
  1124. * same command, and all will be good.
  1125. */
  1126. // msg2->setID(GenerateNextCommandID());
  1127. msg2->setID(msg->getID());
  1128. }
  1129. if (nextExecutionFrame > (TheGameLogic->getFrame() + oldRunAhead)) {
  1130. msg2->setExecutionFrame(nextExecutionFrame);
  1131. } else {
  1132. msg2->setExecutionFrame(TheGameLogic->getFrame() + oldRunAhead);
  1133. }
  1134. // Let the player with the slowest FPS run a little faster than the other computers...
  1135. // just in case they are able to. Then we might be able to run the game faster which would be good.
  1136. Int newMinFps = (minFps * 11) / 10;
  1137. if (newMinFps == minFps) {
  1138. newMinFps = minFps + 1;
  1139. }
  1140. if (newMinFps > 30) {
  1141. newMinFps = 30; // Cap FPS to 30.
  1142. }
  1143. msg2->setRunAhead(newRunAhead);
  1144. msg2->setFrameRate(newMinFps);
  1145. sendLocalCommand(msg2, 1 << minFpsPlayer);
  1146. msg->detach();
  1147. msg2->detach();
  1148. } else {
  1149. // We are not the packet router, send our metrics info to the packet router.
  1150. NetRunAheadMetricsCommandMsg *msg = newInstance(NetRunAheadMetricsCommandMsg);
  1151. msg->setPlayerID(m_localSlot);
  1152. if (DoesCommandRequireACommandID(msg->getNetCommandType())) {
  1153. msg->setID(GenerateNextCommandID());
  1154. }
  1155. msg->setAverageLatency(m_frameMetrics.getAverageLatency());
  1156. // see above for explanation.
  1157. // if (didSelfSlug) {
  1158. // msg->setAverageFps(frameRate);
  1159. // } else {
  1160. msg->setAverageFps(m_frameMetrics.getAverageFPS());
  1161. // }
  1162. if (didSelfSlug) {
  1163. //DEBUG_LOG(("ConnectionManager::updateRunAhead - average latency = %f, average fps = %d, actual fps = %d, didSelfSlug = true\n", m_frameMetrics.getAverageLatency(), m_frameMetrics.getAverageFPS(), m_frameMetrics.getAverageFPS()));
  1164. } else {
  1165. //DEBUG_LOG(("ConnectionManager::updateRunAhead - average latency = %f, average fps = %d, didSelfSlug = false\n", m_frameMetrics.getAverageLatency(), m_frameMetrics.getAverageFPS()));
  1166. }
  1167. m_connections[m_packetRouterSlot]->sendNetCommandMsg(msg, 1 << m_packetRouterSlot);
  1168. msg->detach();
  1169. }
  1170. lasttimesent = curTime;
  1171. }
  1172. }
  1173. Real ConnectionManager::getMaximumLatency() {
  1174. // This works for 2 player games because the latency for the packet router is always 0.
  1175. Real lat1 = 0.0;
  1176. Real lat2 = 0.0;
  1177. for (Int i = 0; i < MAX_SLOTS; ++i) {
  1178. if (isPlayerConnected(i)) {
  1179. if (m_latencyAverages[i] != 0.0) {
  1180. if (m_latencyAverages[i] > lat1) {
  1181. lat2 = lat1;
  1182. lat1 = m_latencyAverages[i];
  1183. } else if (m_latencyAverages[i] > lat2) {
  1184. lat2 = m_latencyAverages[i];
  1185. }
  1186. }
  1187. }
  1188. }
  1189. return (lat1 + lat2);
  1190. }
  1191. void ConnectionManager::getMinimumFps(Int &minFps, Int &minFpsPlayer) {
  1192. minFps = -1;
  1193. minFpsPlayer = -1;
  1194. // DEBUG_LOG(("ConnectionManager::getMinimumFps -"));
  1195. for (Int i = 0; i < MAX_SLOTS; ++i) {
  1196. if ((m_connections[i] != NULL) || (i == m_localSlot)) {
  1197. // DEBUG_LOG((" %d: %d,", i, m_fpsAverages[i]));
  1198. if (m_fpsAverages[i] != -1) {
  1199. if ((minFps == -1) || (m_fpsAverages[i] < minFps)) {
  1200. minFps = m_fpsAverages[i];
  1201. minFpsPlayer = i;
  1202. }
  1203. }
  1204. }
  1205. }
  1206. // DEBUG_LOG(("\n"));
  1207. }
  1208. UnsignedInt ConnectionManager::getMinimumCushion() {
  1209. return m_frameMetrics.getMinimumCushion();
  1210. }
  1211. /**
  1212. * The commands for the given frame are all ready, time to send out our command count for that frame.
  1213. */
  1214. void ConnectionManager::processFrameTick(UnsignedInt frame) {
  1215. if ((m_frameData[m_localSlot] == NULL) || (m_frameData[m_localSlot]->getIsQuitting() == TRUE)) {
  1216. // if the local frame data stuff is NULL, we must be leaving the game.
  1217. return;
  1218. }
  1219. UnsignedShort commandCount = m_frameData[m_localSlot]->getCommandCount(frame);
  1220. NetFrameCommandMsg *msg = newInstance(NetFrameCommandMsg);
  1221. msg->setExecutionFrame(frame);
  1222. msg->setCommandCount(commandCount);
  1223. if (DoesCommandRequireACommandID(msg->getNetCommandType())) {
  1224. msg->setID(GenerateNextCommandID());
  1225. }
  1226. msg->setPlayerID(m_localSlot);
  1227. m_frameMetrics.doPerFrameMetrics(frame);
  1228. DEBUG_LOG(("ConnectionManager::processFrameTick - sending frame info for frame %d, ID %d, command count %d\n", frame, msg->getID(), commandCount));
  1229. sendLocalCommand(msg, 0xff & ~(1 << m_localSlot));
  1230. msg->detach();
  1231. }
  1232. /**
  1233. * Set the local address.
  1234. */
  1235. void ConnectionManager::setLocalAddress(UnsignedInt ip, UnsignedInt port) {
  1236. DEBUG_LOG(("ConnectionManager::setLocalAddress() - local address is %X:%d\n", ip, port));
  1237. m_localAddr = ip;
  1238. m_localPort = port;
  1239. }
  1240. /**
  1241. * Initialize the transport object
  1242. */
  1243. void ConnectionManager::initTransport() {
  1244. DEBUG_ASSERTCRASH((m_transport == NULL), ("m_transport already exists when trying to init it."));
  1245. DEBUG_LOG(("ConnectionManager::initTransport - Initializing Transport\n"));
  1246. if (m_transport != NULL) {
  1247. delete m_transport;
  1248. m_transport = NULL;
  1249. }
  1250. m_transport = new Transport;
  1251. m_transport->reset();
  1252. m_transport->init(m_localAddr, m_localPort);
  1253. }
  1254. /**
  1255. * This is where the commands from the local client are sent to the other clients in
  1256. * the game. This is also where the local commands are put into the frame data for
  1257. * future execution.
  1258. */
  1259. void ConnectionManager::sendLocalGameMessage(GameMessage *msg, UnsignedInt frame) {
  1260. UnsignedShort currentID = 0;
  1261. if (DoesCommandRequireACommandID(NETCOMMANDTYPE_GAMECOMMAND)) {
  1262. currentID = GenerateNextCommandID();
  1263. }
  1264. NetCommandMsg *netmsg = newInstance(NetGameCommandMsg)(msg);
  1265. netmsg->setExecutionFrame(frame);
  1266. netmsg->setPlayerID(m_localSlot);
  1267. netmsg->setID(currentID);
  1268. sendLocalCommand(netmsg);
  1269. netmsg->detach();
  1270. }
  1271. /**
  1272. * This is a NetCommandMsg that originated on the local computer. Send this to everyone specified
  1273. * in the relay field. Commands sent in this way go through the packet router.
  1274. */
  1275. void ConnectionManager::sendLocalCommand(NetCommandMsg *msg, UnsignedByte relay /* = 0xff by default*/) {
  1276. if (CommandRequiresDirectSend(msg) || (m_packetRouterSlot < 0) || (m_packetRouterSlot >= MAX_SLOTS) || (m_connections[m_packetRouterSlot] == NULL)) {
  1277. sendLocalCommandDirect(msg, relay);
  1278. return;
  1279. }
  1280. msg->attach();
  1281. DEBUG_LOG(("ConnectionManager::sendLocalCommand - sending net command %d of type %s\n", msg->getID(),
  1282. GetAsciiNetCommandType(msg->getNetCommandType()).str()));
  1283. if (relay & (1 << m_localSlot)) {
  1284. DEBUG_LOG(("ConnectionManager::sendLocalCommand - adding net command of type %s to player %d for frame %d\n", GetAsciiNetCommandType(msg->getNetCommandType()).str(), msg->getPlayerID(), msg->getExecutionFrame()));
  1285. m_frameData[m_localSlot]->addNetCommandMsg(msg);
  1286. }
  1287. // Send the packet to everyone else
  1288. if (m_localSlot == m_packetRouterSlot) {
  1289. // I am the packet router, I need to send this packet to everyone individually.
  1290. for (Int i = 0; i < MAX_SLOTS; ++i) {
  1291. // Send it to all open connections.
  1292. if (((m_connections[i] != NULL) && (m_connections[i]->isQuitting() == FALSE)) && (relay & (1 << i))) {
  1293. // Set the relay mask to only go to this player so he knows not to relay it to anyone else.
  1294. UnsignedByte temprelay = 1 << i;
  1295. m_connections[i]->sendNetCommandMsg(msg, temprelay); // This will create a new copy of netmsg for this connection.
  1296. }
  1297. }
  1298. } else {
  1299. // Send the command to everyone else via the packet router.
  1300. UnsignedByte temprelay = relay & ~(1 << m_localSlot); // Tell the packet router to relay the message to everyone but myself.
  1301. // Hopefully the packet router is smart enough to not send it
  1302. // to slots that are not in the game.
  1303. m_connections[m_packetRouterSlot]->sendNetCommandMsg(msg, temprelay); // This will create a new copy of netmsg for this connection.
  1304. if (CommandRequiresAck(msg)) {
  1305. NetCommandRef *ref = m_pendingCommands->addMessage(msg);
  1306. //DEBUG_LOG(("ConnectionManager::sendLocalCommand - added command %d to pending commands list.\n", msg->getID()));
  1307. if (ref != NULL) {
  1308. ref->setRelay(temprelay);
  1309. }
  1310. }
  1311. }
  1312. msg->detach(); // detach from the command msg.
  1313. }
  1314. /**
  1315. * This is a NetCommandMsg that originated on the local computer. Send this to everyone specified
  1316. * in the relay field. Commands sent in this way do not go through the packet router.
  1317. */
  1318. void ConnectionManager::sendLocalCommandDirect(NetCommandMsg *msg, UnsignedByte relay) {
  1319. msg->attach();
  1320. if (((relay & (1 << m_localSlot)) != 0) && (m_frameData[m_localSlot] != NULL)) {
  1321. if (IsCommandSynchronized(msg->getNetCommandType()) == TRUE) {
  1322. DEBUG_LOG(("ConnectionManager::sendLocalCommandDirect - adding net command of type %s to player %d for frame %d\n", GetAsciiNetCommandType(msg->getNetCommandType()).str(), msg->getPlayerID(), msg->getExecutionFrame()));
  1323. m_frameData[m_localSlot]->addNetCommandMsg(msg);
  1324. }
  1325. }
  1326. for (Int i = 0; i < MAX_SLOTS; ++i) {
  1327. if ((relay & (1 << i)) != 0) {
  1328. if ((m_connections[i] != NULL) && (m_connections[i]->isQuitting() == FALSE)) {
  1329. UnsignedByte temprelay = 1 << i;
  1330. m_connections[i]->sendNetCommandMsg(msg, temprelay);
  1331. DEBUG_LOG(("ConnectionManager::sendLocalCommandDirect - Sending direct command %d of type %s to player %d\n", msg->getID(), GetAsciiNetCommandType(msg->getNetCommandType()).str(), i));
  1332. }
  1333. }
  1334. }
  1335. msg->detach();
  1336. }
  1337. Int commandsReadyDebugSpewage = 0;
  1338. /**
  1339. * Returns true if all the commands for the given frame are ready to be executed.
  1340. */
  1341. Bool ConnectionManager::allCommandsReady(UnsignedInt frame, Bool justTesting /* = FALSE */) {
  1342. Bool retval = TRUE;
  1343. FrameDataReturnType frameRetVal;
  1344. // retval = FALSE; // ****for testing purposes only!!!!!!****
  1345. for (Int i = 0; (i < MAX_SLOTS) && retval; ++i) {
  1346. if ((m_frameData[i] != NULL) && (m_frameData[i]->getIsQuitting() == FALSE)) {
  1347. /*
  1348. if (!(m_frameData[i]->allCommandsReady(frame, (frame != commandsReadyDebugSpewage) && (justTesting == FALSE)))) {
  1349. if ((frame != commandsReadyDebugSpewage) && (justTesting == FALSE)) {
  1350. DEBUG_LOG(("ConnectionManager::allCommandsReady, frame %d player %d not ready.\n", frame, i));
  1351. commandsReadyDebugSpewage = frame;
  1352. }
  1353. retval = FALSE;
  1354. } else {
  1355. // DEBUG_LOG(("ConnectionManager::allCommandsReady, frame %d player %d is ready.\n", frame, i));
  1356. }
  1357. */
  1358. frameRetVal = m_frameData[i]->allCommandsReady(frame, (frame != commandsReadyDebugSpewage) && (justTesting == FALSE));
  1359. if (frameRetVal == FRAMEDATA_NOTREADY) {
  1360. retval = FALSE;
  1361. } else if (frameRetVal == FRAMEDATA_RESEND) {
  1362. requestFrameDataResend(i, frame);
  1363. retval = FALSE;
  1364. }
  1365. }
  1366. }
  1367. if (frameRetVal == FRAMEDATA_RESEND) {
  1368. // this frame's data is really screwed up, we need to clean it out so it can be resent to us.
  1369. for (i = 0; i < MAX_SLOTS; ++i) {
  1370. if ((m_frameData[i] != NULL) && (i != m_localSlot)) {
  1371. m_frameData[i]->resetFrame(frame, FALSE);
  1372. }
  1373. }
  1374. }
  1375. if ((retval == TRUE) && (justTesting == FALSE)) {
  1376. m_disconnectManager->allCommandsReady(TheGameLogic->getFrame(), this);
  1377. retval = m_disconnectManager->allowedToContinue(); // allow the disconnect manager to keep us on this frame
  1378. // in case we are waiting for a new packet router or something.
  1379. }
  1380. return retval;
  1381. }
  1382. void ConnectionManager::handleAllCommandsReady(void)
  1383. {
  1384. m_disconnectManager->allCommandsReady(TheGameLogic->getFrame(), this, FALSE);
  1385. }
  1386. /**
  1387. * Only call this after making sure that all the commands are there for this frame.
  1388. * After calling this the commands for this frame will be removed from the connection.
  1389. *
  1390. * BGC - To account for the case where the host disconnects without sending the
  1391. * same commands to all players, we now have to keep around the last 'run ahead'
  1392. * frames so we can potentially send those commands to the other players in the
  1393. * game so they can catch up.
  1394. */
  1395. NetCommandList *ConnectionManager::getFrameCommandList(UnsignedInt frame)
  1396. {
  1397. NetCommandList *retlist = newInstance(NetCommandList);
  1398. retlist->init();
  1399. for (Int i = 0; i < MAX_SLOTS; ++i) {
  1400. if (m_frameData[i] != NULL) {
  1401. retlist->appendList(m_frameData[i]->getFrameCommandList(frame));
  1402. if (frame > FRAMES_TO_KEEP) {
  1403. m_frameData[i]->resetFrame(frame - FRAMES_TO_KEEP); // After getting the commands for that frame from this
  1404. // FrameDataManager object, we need to tell it that we're
  1405. // done with the messages for that frame.
  1406. DEBUG_LOG(("getFrameCommandList - called reset frame on player %d for frame %d\n", i, frame - FRAMES_TO_KEEP));
  1407. }
  1408. }
  1409. }
  1410. return retlist; // retlist deallocated by calling function.
  1411. }
  1412. void ConnectionManager::setFrameGrouping(time_t frameGrouping) {
  1413. // Since we are the packet router, we should send more packets per second since we
  1414. // may become the latency bottleneck for sending packets from one player to the next.
  1415. // This is probably ok since the packet router should have the fastest connection of all
  1416. // the players in the game.
  1417. if (m_localSlot == m_packetRouterSlot) {
  1418. frameGrouping = frameGrouping / 2;
  1419. }
  1420. for (Int i = 0; i < MAX_SLOTS; ++i) {
  1421. if (m_connections[i] != NULL) {
  1422. m_connections[i]->setFrameGrouping(frameGrouping);
  1423. }
  1424. }
  1425. }
  1426. /*
  1427. void ConnectionManager::determineRouterFallbackPlan() {
  1428. memset(m_packetRouterFallback, 0, sizeof(m_packetRouterFallback));
  1429. Int curnum = 1;
  1430. for (Int i = 0; i < MAX_SLOTS; ++i) {
  1431. if (m_connections[i] != NULL) {
  1432. m_packetRouterFallback[i] = curnum;
  1433. if (curnum == 1) {
  1434. m_packetRouterSlot = i;
  1435. }
  1436. ++curnum;
  1437. }
  1438. }
  1439. }
  1440. */
  1441. void ConnectionManager::doKeepAlive() {
  1442. static Int nextIndex = 0;
  1443. static time_t startTime = 0;
  1444. time_t curTime = timeGetTime();
  1445. if (startTime == 0) {
  1446. startTime = curTime;
  1447. return;
  1448. }
  1449. time_t numSeconds = (curTime - startTime) / 1000;
  1450. while ((nextIndex <= numSeconds) && (nextIndex < MAX_SLOTS)) {
  1451. // DEBUG_LOG(("ConnectionManager::doKeepAlive - trying to send keep alive message to player %d\n", nextIndex));
  1452. if (m_connections[nextIndex] != NULL) {
  1453. NetKeepAliveCommandMsg *msg = newInstance(NetKeepAliveCommandMsg);
  1454. msg->setPlayerID(m_localSlot);
  1455. if (DoesCommandRequireACommandID(msg->getNetCommandType()) == TRUE) {
  1456. msg->setID(GenerateNextCommandID());
  1457. }
  1458. // DEBUG_LOG(("ConnectionManager::doKeepAlive - sending keep alive message to player %d\n", nextIndex));
  1459. sendLocalCommandDirect(msg, 1 << nextIndex);
  1460. msg->detach();
  1461. }
  1462. ++nextIndex;
  1463. }
  1464. if (nextIndex == MAX_SLOTS) {
  1465. nextIndex = 0;
  1466. startTime = curTime;
  1467. }
  1468. }
  1469. PlayerLeaveCode ConnectionManager::disconnectPlayer(Int slot) {
  1470. // Need to do the deletion of the slot's connection and frame data here.
  1471. PlayerLeaveCode retval = PLAYERLEAVECODE_CLIENT;
  1472. DEBUG_LOG(("ConnectionManager::disconnectPlayer - disconnecting slot %d on frame %d\n", slot, TheGameLogic->getFrame()));
  1473. if ((slot < 0) || (slot >= MAX_SLOTS)) {
  1474. return PLAYERLEAVECODE_UNKNOWN;
  1475. }
  1476. if (TheGameInfo)
  1477. {
  1478. GameSlot *gSlot = TheGameInfo->getSlot( slot );
  1479. if (gSlot && !gSlot->lastFrameInGame())
  1480. {
  1481. DEBUG_LOG(("ConnectionManager::disconnectPlayer(%d) - slot is last in the game on frame %d\n",
  1482. slot, TheGameLogic->getFrame()));
  1483. gSlot->setLastFrameInGame(TheGameLogic->getFrame());
  1484. }
  1485. }
  1486. UnicodeString unicodeName;
  1487. unicodeName = getPlayerName(slot);
  1488. if (unicodeName.getLength() > 0 && m_connections[slot]) {
  1489. TheInGameUI->message("Network:PlayerLeftGame", unicodeName.str());
  1490. // People are boneheads. Also play a sound
  1491. static AudioEventRTS leftGameSound("GUIMessageReceived");
  1492. TheAudio->addAudioEvent(&leftGameSound);
  1493. }
  1494. if ((m_frameData[slot] != NULL) && (m_frameData[slot]->getIsQuitting() == FALSE)) {
  1495. DEBUG_LOG(("ConnectionManager::disconnectPlayer - deleting player %d frame data\n", slot));
  1496. m_frameData[slot]->deleteInstance();
  1497. m_frameData[slot] = NULL;
  1498. }
  1499. if (m_connections[slot] != NULL && !m_connections[slot]->isQuitting()) {
  1500. DEBUG_LOG(("ConnectionManager::disconnectPlayer - deleting player %d connection\n", slot));
  1501. m_connections[slot]->deleteInstance();
  1502. m_connections[slot] = NULL;
  1503. }
  1504. // if (playerID == m_localSlot) {
  1505. // TheMessageStream->appendMessage(GameMessage::MSG_CLEAR_GAME_DATA);
  1506. // }
  1507. if (slot == m_packetRouterSlot) {
  1508. Int index = 0;
  1509. while ((index < (MAX_SLOTS-1)) && (m_packetRouterFallback[index] != m_packetRouterSlot)) {
  1510. ++index;
  1511. }
  1512. ++index;
  1513. m_packetRouterSlot = m_packetRouterFallback[index];
  1514. DEBUG_LOG(("Packet router left. New packet router is slot %d\n", m_packetRouterSlot));
  1515. retval = PLAYERLEAVECODE_PACKETROUTER;
  1516. }
  1517. if (m_localSlot == slot) {
  1518. DEBUG_LOG(("Disconnecting self\n"));
  1519. retval = PLAYERLEAVECODE_LOCAL;
  1520. }
  1521. // Take the player out of the fallback plan
  1522. Int fallbackindex = 0;
  1523. while ((fallbackindex < MAX_SLOTS) && (m_packetRouterFallback[fallbackindex] != slot)) {
  1524. ++fallbackindex;
  1525. }
  1526. for (Int i = fallbackindex; i < MAX_SLOTS-1; ++i) {
  1527. m_packetRouterFallback[i] = m_packetRouterFallback[i+1];
  1528. }
  1529. m_packetRouterFallback[MAX_SLOTS-1] = -1;
  1530. return retval;
  1531. }
  1532. void ConnectionManager::quitGame() {
  1533. // Need to do the NetDisconnectPlayerCommandMsg creation and sending here.
  1534. NetDisconnectPlayerCommandMsg *disconnectMsg = newInstance(NetDisconnectPlayerCommandMsg);
  1535. disconnectMsg->setDisconnectSlot(m_localSlot);
  1536. disconnectMsg->setPlayerID(m_localSlot);
  1537. if (DoesCommandRequireACommandID(disconnectMsg->getNetCommandType())) {
  1538. disconnectMsg->setID(GenerateNextCommandID());
  1539. }
  1540. //DEBUG_LOG(("ConnectionManager::disconnectLocalPlayer - about to send disconnect command\n"));
  1541. sendLocalCommandDirect(disconnectMsg, 0xff ^ (1 << m_localSlot));
  1542. //DEBUG_LOG(("ConnectionManager::disconnectLocalPlayer - about to flush connections\n"));
  1543. flushConnections(); // need to do this so our packet actually gets sent before the connections are deleted.
  1544. //DEBUG_LOG(("ConnectionManager::disconnectLocalPlayer - done flushing connections\n"));
  1545. disconnectMsg->detach();
  1546. disconnectLocalPlayer();
  1547. }
  1548. void ConnectionManager::disconnectLocalPlayer() {
  1549. // kill the frame data and the connections for all the other players.
  1550. DEBUG_LOG(("ConnectionManager::disconnectLocalPlayer()\n"));
  1551. for (Int i = 0; i < MAX_SLOTS; ++i) {
  1552. if (i != m_localSlot) {
  1553. disconnectPlayer(i);
  1554. }
  1555. }
  1556. }
  1557. /**
  1558. * Takes all the commands that are ready to send and sends them right now.
  1559. */
  1560. void ConnectionManager::flushConnections() {
  1561. for (Int i = 0; i < MAX_SLOTS; ++i) {
  1562. if (m_connections[i] != NULL) {
  1563. // DEBUG_LOG(("ConnectionManager::flushConnections - flushing connection to player %d\n", i));
  1564. /*
  1565. if (m_connections[i]->isQueueEmpty()) {
  1566. // DEBUG_LOG(("ConnectionManager::flushConnections - connection queue empty\n"));
  1567. }
  1568. */
  1569. m_connections[i]->doSend();
  1570. }
  1571. }
  1572. if (m_transport != NULL) {
  1573. m_transport->doSend();
  1574. }
  1575. }
  1576. void ConnectionManager::resendPendingCommands() {
  1577. //DEBUG_LOG(("ConnectionManager::resendPendingCommands()\n"));
  1578. if (m_pendingCommands == NULL) {
  1579. return;
  1580. }
  1581. NetCommandRef *ref = m_pendingCommands->getFirstMessage();
  1582. while (ref != NULL) {
  1583. //DEBUG_LOG(("ConnectionManager::resendPendingCommands - resending command %d\n", ref->getCommand()->getID()));
  1584. sendLocalCommand(ref->getCommand(), ref->getRelay());
  1585. ref = ref->getNext();
  1586. }
  1587. }
  1588. UnsignedInt ConnectionManager::getLocalPlayerID() {
  1589. return m_localSlot;
  1590. }
  1591. UnicodeString ConnectionManager::getPlayerName(Int playerNum) {
  1592. UnicodeString retval;
  1593. if( playerNum == m_localSlot ) {
  1594. retval = m_localUser->GetName();
  1595. } else if (((m_connections[playerNum] != NULL) && (m_connections[playerNum]->isQuitting() == FALSE))) {
  1596. retval = m_connections[playerNum]->getUser()->GetName();
  1597. }
  1598. return retval;
  1599. }
  1600. /**
  1601. * Take a user list and make connections and frame data manager objects for each of the players.
  1602. * For now, this is also how we'll determine the packet router fallback plan.
  1603. */
  1604. void ConnectionManager::parseUserList(const GameInfo *game)
  1605. {
  1606. if (!game)
  1607. return;
  1608. Int i;
  1609. Int numUsers = 0;
  1610. m_localSlot = -1;
  1611. DEBUG_LOG(("Local slot is %d\n", game->getLocalSlotNum()));
  1612. for (i=0; i<MAX_SLOTS; ++i)
  1613. {
  1614. const GameSlot *slot = game->getConstSlot(i); // badness, but since we cast right back to const, we should be ok
  1615. if (slot->isHuman())
  1616. {
  1617. if (game->getLocalSlotNum() == i)
  1618. {
  1619. m_localSlot = i;
  1620. m_localUser->setName(slot->getName());
  1621. }
  1622. if (m_localSlot != i)
  1623. {
  1624. m_connections[i] = newInstance(Connection)();
  1625. m_connections[i]->init();
  1626. m_connections[i]->attachTransport(m_transport);
  1627. // UnsignedShort port = (TheNAT)?TheNAT->getSlotPort(i):8088;
  1628. UnsignedShort port = slot->getPort();
  1629. m_connections[i]->setUser(newInstance(User)(slot->getName(), slot->getIP(), port));
  1630. m_frameData[i] = newInstance(FrameDataManager)(FALSE);
  1631. DEBUG_LOG(("Remote user is at %X:%d\n", slot->getIP(), slot->getPort()));
  1632. }
  1633. else
  1634. {
  1635. DEBUG_LOG(("Local user is %d (%X:%d)\n", m_localSlot, slot->getIP(), slot->getPort()));
  1636. m_frameData[i] = newInstance(FrameDataManager)(TRUE);
  1637. }
  1638. m_frameData[i]->init();
  1639. m_frameData[i]->reset();
  1640. m_packetRouterFallback[numUsers] = i;
  1641. ++numUsers;
  1642. }
  1643. }
  1644. #ifdef MEMORYPOOL_DEBUG
  1645. TheMemoryPoolFactory->debugSetInitFillerIndex(m_localSlot);
  1646. #endif
  1647. /*
  1648. if ( numUsers < 2 || m_localSlot == -1 )
  1649. {
  1650. DEBUG_CRASH(("FAILED parseUserList - network game won't work as expected\n"));
  1651. return;
  1652. }
  1653. char * list = strdup(buf);
  1654. char *listPtr = list;
  1655. if (!list)
  1656. return;
  1657. User users[MAX_SLOTS];
  1658. int localUser = -1;
  1659. int i;
  1660. for (i=0; i<MAX_SLOTS; i++)
  1661. {
  1662. users[i].setName("");
  1663. }
  1664. char *userStr, *nameStr, *addrStr, *portStr;
  1665. AsciiString addrAsciiStr;
  1666. char *listPos;
  1667. DEBUG_LOG(("ConnectionManager::parseUserList - looking for local user at %d.%d.%d.%d:%d\n",
  1668. (m_localAddr >> 24) & 0xff,
  1669. (m_localAddr >> 16) & 0xff,
  1670. (m_localAddr >> 8) & 0xff,
  1671. m_localAddr & 0xff,
  1672. m_localPort));
  1673. int numUsers = 0;
  1674. while ( (userStr=strtok_r(listPtr, ",", &listPos)) != NULL )
  1675. {
  1676. listPtr = NULL;
  1677. char *pos = NULL;
  1678. nameStr = strtok_r(userStr, "@", &pos);
  1679. addrStr = strtok_r(NULL, "@:", &pos);
  1680. portStr = strtok_r(NULL, ": ", &pos);
  1681. if (!portStr || numUsers >= MAX_SLOTS)
  1682. {
  1683. DEBUG_LOG(("ConnectionManager::parseUserList - (numUsers = %d) FAILED parseUserList with list [%s]\n", numUsers, buf));
  1684. return;
  1685. }
  1686. addrAsciiStr = addrStr;
  1687. UnsignedInt addr = ResolveIP(addrAsciiStr);
  1688. UnsignedInt port = atoi(portStr);
  1689. // if ((m_localAddr != addr) || (m_localPort != port)) {
  1690. if (loginName.compare(nameStr) != 0) {
  1691. m_connections[numUsers] = newInstance(Connection)();
  1692. m_connections[numUsers]->init();
  1693. m_connections[numUsers]->attachTransport(m_transport);
  1694. m_connections[numUsers]->setUser(newInstance(User)(nameStr, addr, port));
  1695. m_frameData[numUsers] = newInstance(FrameDataManager)(FALSE);
  1696. DEBUG_LOG(("ConnectionManager::parseUserList - User %d is %s\n", numUsers, nameStr));
  1697. } else {
  1698. m_localSlot = numUsers;
  1699. m_localUser.setName(nameStr);
  1700. DEBUG_LOG(("ConnectionManager::parseUserList - User %d is %s\n", numUsers, nameStr));
  1701. DEBUG_LOG(("Local user is %d\n", m_localSlot));
  1702. m_frameData[numUsers] = newInstance(FrameDataManager)(TRUE);
  1703. }
  1704. m_frameData[numUsers]->init();
  1705. m_frameData[numUsers]->reset();
  1706. m_packetRouterFallback[numUsers] = numUsers;
  1707. numUsers++;
  1708. }
  1709. if (numUsers < 2 || m_localSlot == -1)
  1710. {
  1711. DEBUG_LOG(("ConnectionManager::parseUserList - FAILED (local user = %d, num players = %d) with list [%s]\n", m_localSlot, numUsers, buf));
  1712. return;
  1713. }
  1714. if (list != NULL) {
  1715. free(list); // from the strdup above.
  1716. list = NULL;
  1717. }
  1718. */
  1719. }
  1720. /**
  1721. * Return the number of incoming bytes per second averaged over 30 sec.
  1722. */
  1723. Real ConnectionManager::getIncomingBytesPerSecond( void )
  1724. {
  1725. if (m_transport)
  1726. return m_transport->getIncomingBytesPerSecond();
  1727. else
  1728. return 0.0;
  1729. }
  1730. /**
  1731. * Return the number of incoming packets per second averaged over the last 30 sec.
  1732. */
  1733. Real ConnectionManager::getIncomingPacketsPerSecond( void )
  1734. {
  1735. if (m_transport)
  1736. return m_transport->getIncomingPacketsPerSecond();
  1737. else
  1738. return 0.0;
  1739. }
  1740. /**
  1741. * Return the number of outgoing bytes per second averaged over the last 30 sec.
  1742. */
  1743. Real ConnectionManager::getOutgoingBytesPerSecond( void )
  1744. {
  1745. if (m_transport)
  1746. return m_transport->getOutgoingBytesPerSecond();
  1747. else
  1748. return 0.0;
  1749. }
  1750. /**
  1751. * Return the number of outgoing packets per second averaged over the last 30 sec.
  1752. */
  1753. Real ConnectionManager::getOutgoingPacketsPerSecond( void )
  1754. {
  1755. if (m_transport) {
  1756. return m_transport->getOutgoingPacketsPerSecond();
  1757. } else {
  1758. return 0.0;
  1759. }
  1760. }
  1761. /**
  1762. * Return the number of bytes not from generals clients received per second averaged over the last 30 sec.
  1763. */
  1764. Real ConnectionManager::getUnknownBytesPerSecond( void )
  1765. {
  1766. if (m_transport)
  1767. return m_transport->getUnknownBytesPerSecond();
  1768. else
  1769. return 0.0;
  1770. }
  1771. /**
  1772. * Return the number ov packets not from generals clients received per second averaged over the last 30 sec.
  1773. */
  1774. Real ConnectionManager::getUnknownPacketsPerSecond( void )
  1775. {
  1776. if (m_transport)
  1777. return m_transport->getUnknownPacketsPerSecond();
  1778. else
  1779. return 0.0;
  1780. }
  1781. /**
  1782. * Return the smallest packet arrival cushion since this was last called.
  1783. */
  1784. UnsignedInt ConnectionManager::getPacketArrivalCushion() {
  1785. UnsignedInt retval = m_smallestPacketArrivalCushion;
  1786. m_smallestPacketArrivalCushion = -1;
  1787. return retval;
  1788. }
  1789. void ConnectionManager::sendChat(UnicodeString text, Int playerMask, UnsignedInt executionFrame)
  1790. {
  1791. NetChatCommandMsg *msg = newInstance(NetChatCommandMsg);
  1792. msg->setText(text);
  1793. msg->setPlayerMask(playerMask);
  1794. msg->setPlayerID(m_localSlot);
  1795. msg->setID(0);
  1796. msg->setExecutionFrame(executionFrame);
  1797. if (DoesCommandRequireACommandID(msg->getNetCommandType()))
  1798. {
  1799. msg->setID(GenerateNextCommandID());
  1800. }
  1801. DEBUG_LOG(("Chat message has ID of %d, mask of %8.8X, text of %ls\n", msg->getID(), msg->getPlayerMask(), msg->getText().str()));
  1802. sendLocalCommand(msg, 0xff ^ (1 << m_localSlot));
  1803. processChat(msg);
  1804. msg->detach();
  1805. }
  1806. void ConnectionManager::sendDisconnectChat(UnicodeString text) {
  1807. NetDisconnectChatCommandMsg *msg = newInstance(NetDisconnectChatCommandMsg);
  1808. msg->setPlayerID(m_localSlot);
  1809. if (DoesCommandRequireACommandID(msg->getNetCommandType())) {
  1810. msg->setID(GenerateNextCommandID());
  1811. }
  1812. msg->setText(text);
  1813. sendLocalCommandDirect(msg, 0xff ^ (1 << m_localSlot));
  1814. processDisconnectChat(msg);
  1815. }
  1816. UnsignedShort ConnectionManager::sendFileAnnounce(AsciiString path, UnsignedByte playerMask)
  1817. {
  1818. File *theFile = TheLocalFileSystem->openFile(path.str());
  1819. if (!theFile || !theFile->size())
  1820. {
  1821. UnicodeString log;
  1822. log.format(L"Not sending file '%hs' to %X\n", path.str(), playerMask);
  1823. DEBUG_LOG(("%ls\n", log.str()));
  1824. if (TheLAN)
  1825. TheLAN->OnChat(UnicodeString(L"sendFile"), 0, log, LANAPI::LANCHAT_SYSTEM);
  1826. return 0;
  1827. }
  1828. theFile->close();
  1829. Int announceMask = 0xff ^ (1 << m_localSlot);
  1830. NetFileAnnounceCommandMsg *announceMsg = newInstance(NetFileAnnounceCommandMsg);
  1831. announceMsg->setPlayerID(m_localSlot);
  1832. if (DoesCommandRequireACommandID(announceMsg->getNetCommandType()) == TRUE) {
  1833. announceMsg->setID(GenerateNextCommandID());
  1834. }
  1835. announceMsg->setRealFilename(path);
  1836. announceMsg->setPlayerMask(playerMask);
  1837. UnsignedShort fileID = GenerateNextCommandID();
  1838. announceMsg->setFileID(fileID);
  1839. DEBUG_LOG(("ConnectionManager::sendFileAnnounce() - creating announce message with ID of %d from %d to mask %X for '%s' going to %X as command %d\n",
  1840. announceMsg->getID(), announceMsg->getPlayerID(), announceMask, announceMsg->getRealFilename().str(),
  1841. announceMsg->getPlayerMask(), announceMsg->getFileID()));
  1842. processFileAnnounce(announceMsg); // set up things for the host
  1843. DEBUG_LOG(("Sending file announce to %X\n", announceMask));
  1844. sendLocalCommand(announceMsg, announceMask);
  1845. announceMsg->detach();
  1846. return fileID;
  1847. }
  1848. void ConnectionManager::sendFile(AsciiString path, UnsignedByte playerMask, UnsignedShort commandID)
  1849. {
  1850. File *theFile = TheLocalFileSystem->openFile(path.str());
  1851. if (!theFile || !theFile->size())
  1852. {
  1853. UnicodeString log;
  1854. log.format(L"Not sending file '%hs' to %X\n", path.str(), playerMask);
  1855. DEBUG_LOG(("%ls\n", log.str()));
  1856. if (TheLAN)
  1857. TheLAN->OnChat(UnicodeString(L"sendFile"), 0, log, LANAPI::LANCHAT_SYSTEM);
  1858. return;
  1859. }
  1860. Int len = theFile->size();
  1861. char *buf = theFile->readEntireAndClose();
  1862. // compress Targas
  1863. #ifdef COMPRESS_TARGAS
  1864. char *compressedBuf = NULL;
  1865. Int compressedLen = path.endsWith(".tga")?CompressionManager::getMaxCompressedSize(len, CompressionManager::getPreferredCompression()):0;
  1866. Int compressedSize = 0;
  1867. if (compressedLen)
  1868. compressedSize = CompressionManager::compressData(CompressionManager::getPreferredCompression(),
  1869. buf, len, compressedBuf, compressedLen);
  1870. if (compressedBuf && !compressedSize)
  1871. {
  1872. delete[] compressedBuf;
  1873. compressedBuf = NULL;
  1874. }
  1875. #endif // COMPRESS_TARGAS
  1876. NetFileCommandMsg *fileMsg = newInstance(NetFileCommandMsg);
  1877. fileMsg->setPlayerID(m_localSlot);
  1878. fileMsg->setID(commandID);
  1879. fileMsg->setRealFilename(path);
  1880. #ifdef COMPRESS_TARGAS
  1881. if (compressedBuf)
  1882. {
  1883. DEBUG_LOG(("Compressed '%s' from %d to %d (%g%%) before transfer\n", path.str(), len, compressedSize,
  1884. (Real)compressedSize/(Real)len*100.0f));
  1885. fileMsg->setFileData((unsigned char *)compressedBuf, compressedSize);
  1886. }
  1887. else
  1888. #endif // COMPRESS_TARGAS
  1889. {
  1890. fileMsg->setFileData((unsigned char *)buf, len);
  1891. }
  1892. DEBUG_LOG(("ConnectionManager::sendFile() - creating file message with ID of %d for '%s' going to %X from %d, size of %d\n",
  1893. fileMsg->getID(), fileMsg->getRealFilename().str(), playerMask, fileMsg->getPlayerID(), fileMsg->getFileLength()));
  1894. delete[] buf;
  1895. buf = NULL;
  1896. #ifdef COMPRESS_TARGAS
  1897. if (compressedBuf)
  1898. {
  1899. delete[] compressedBuf;
  1900. compressedBuf = NULL;
  1901. }
  1902. #endif // COMPRESS_TARGAS
  1903. DEBUG_LOG(("Sending file: '%s', len %d, to %X\n", path.str(), len, playerMask));
  1904. sendLocalCommand(fileMsg, playerMask);
  1905. fileMsg->detach();
  1906. }
  1907. Int ConnectionManager::getFileTransferProgress(Int playerID, AsciiString path)
  1908. {
  1909. FileCommandMap::iterator commandIt = s_fileCommandMap.begin();
  1910. while (commandIt != s_fileCommandMap.end())
  1911. {
  1912. //DEBUG_LOG(("ConnectionManager::getFileTransferProgress(%s): looking at existing transfer of '%s'\n",
  1913. // path.str(), commandIt->second.str()));
  1914. if (commandIt->second == path)
  1915. {
  1916. return s_fileProgressMap[playerID][commandIt->first];
  1917. }
  1918. ++commandIt;
  1919. }
  1920. //DEBUG_LOG(("Falling back to 0, since we couldn't find the map\n"));
  1921. DEBUG_LOG(("ConnectionManager::getFileTransferProgress: path %s not found\n",path.str()));
  1922. return 0;
  1923. }
  1924. void ConnectionManager::voteForPlayerDisconnect(Int slot) {
  1925. if (m_disconnectManager != NULL) {
  1926. m_disconnectManager->voteForPlayerDisconnect(slot, this);
  1927. }
  1928. }
  1929. Int ConnectionManager::getNumPlayers()
  1930. {
  1931. Int retval = 0;
  1932. for (Int i = 0; i < MAX_SLOTS; ++i)
  1933. {
  1934. if (isPlayerConnected(i)) {
  1935. ++retval;
  1936. }
  1937. }
  1938. return retval;
  1939. }
  1940. void ConnectionManager::updateLoadProgress( Int progress )
  1941. {
  1942. NetProgressCommandMsg *msg = newInstance(NetProgressCommandMsg);
  1943. msg->setPercentage( progress );
  1944. msg->setPlayerID( m_localSlot );
  1945. if (DoesCommandRequireACommandID(msg->getNetCommandType()) == TRUE) {
  1946. msg->setID(GenerateNextCommandID());
  1947. }
  1948. processProgress(msg);
  1949. sendLocalCommand(msg, 0xff ^ (1 << m_localSlot));
  1950. msg->detach();
  1951. }
  1952. void ConnectionManager::loadProgressComplete()
  1953. {
  1954. NetCommandMsg *msg = newInstance(NetCommandMsg);
  1955. msg->setPlayerID( m_localSlot );
  1956. if (DoesCommandRequireACommandID(msg->getNetCommandType()) == TRUE) {
  1957. msg->setID(GenerateNextCommandID());
  1958. }
  1959. msg->setNetCommandType(NETCOMMANDTYPE_LOADCOMPLETE);
  1960. processLoadComplete(msg);
  1961. sendLocalCommand(msg, 0xff ^ (1 << m_localSlot));
  1962. msg->detach();
  1963. }
  1964. void ConnectionManager::sendTimeOutGameStart()
  1965. {
  1966. NetCommandMsg *msg = newInstance(NetCommandMsg);
  1967. msg->setPlayerID( m_localSlot );
  1968. msg->setNetCommandType(NETCOMMANDTYPE_TIMEOUTSTART);
  1969. if (DoesCommandRequireACommandID(msg->getNetCommandType()) == TRUE) {
  1970. msg->setID(GenerateNextCommandID());
  1971. }
  1972. processTimeOutGameStart(msg);
  1973. sendLocalCommand(msg, 0xff ^ (1 << m_localSlot));
  1974. msg->detach();
  1975. }
  1976. Bool ConnectionManager::isPacketRouter( void )
  1977. {
  1978. return m_localSlot == m_packetRouterSlot;
  1979. }
  1980. Int ConnectionManager::getAverageFPS( void )
  1981. {
  1982. return m_frameMetrics.getAverageFPS();
  1983. }
  1984. Int ConnectionManager::getSlotAverageFPS(Int slot) {
  1985. if ((slot < 0) || (slot >= MAX_SLOTS)) {
  1986. return -1;
  1987. }
  1988. if ((m_packetRouterSlot != m_localSlot) && (slot == m_localSlot)) {
  1989. // our framerate data isn't valid for other players unless we are the
  1990. // packet router, so don't fake someone out.
  1991. return -1;
  1992. }
  1993. return m_fpsAverages[slot];
  1994. }
  1995. #if defined(_DEBUG) || defined(_INTERNAL)
  1996. void ConnectionManager::debugPrintConnectionCommands() {
  1997. DEBUG_LOG(("ConnectionManager::debugPrintConnectionCommands - begin commands\n"));
  1998. for (Int i = 0; i < MAX_SLOTS; ++i) {
  1999. if (m_connections[i] != NULL) {
  2000. DEBUG_LOG(("ConnectionManager::debugPrintConnectionCommands - commands for connection %d\n", i));
  2001. m_connections[i]->debugPrintCommands();
  2002. }
  2003. }
  2004. DEBUG_LOG(("ConnectionManager::debugPrintConnectionCommands - end commands\n"));
  2005. }
  2006. #endif
  2007. void ConnectionManager::notifyOthersOfCurrentFrame(Int frame) {
  2008. NetDisconnectFrameCommandMsg *msg = newInstance(NetDisconnectFrameCommandMsg);
  2009. msg->setPlayerID(m_localSlot);
  2010. msg->setDisconnectFrame(frame);
  2011. if (DoesCommandRequireACommandID(msg->getNetCommandType())) {
  2012. msg->setID(GenerateNextCommandID());
  2013. }
  2014. DEBUG_LOG(("ConnectionManager::notifyOthersOfCurrentFrame - sending disconnect frame of %d, command ID = %d\n", frame, msg->getID()));
  2015. sendLocalCommandDirect(msg, 0xff ^ (1 << m_localSlot));
  2016. NetCommandRef *ref = NEW_NETCOMMANDREF(msg);
  2017. ref->setRelay(1 << m_localSlot);
  2018. m_disconnectManager->processDisconnectCommand(ref, this);
  2019. ref->deleteInstance();
  2020. msg->detach();
  2021. DEBUG_LOG(("ConnectionManager::notifyOthersOfCurrentFrame - start screen on debug stuff\n"));
  2022. #if defined(_DEBUG) || defined(_INTERNAL)
  2023. debugPrintConnectionCommands();
  2024. #endif
  2025. }
  2026. void ConnectionManager::notifyOthersOfNewFrame(UnsignedInt frame) {
  2027. NetDisconnectScreenOffCommandMsg *msg = newInstance(NetDisconnectScreenOffCommandMsg);
  2028. msg->setPlayerID(m_localSlot);
  2029. msg->setNewFrame(frame);
  2030. if (DoesCommandRequireACommandID(msg->getNetCommandType())) {
  2031. msg->setID(GenerateNextCommandID());
  2032. }
  2033. sendLocalCommandDirect(msg, 0xff ^ (1 << m_localSlot));
  2034. NetCommandRef *ref = NEW_NETCOMMANDREF(msg);
  2035. ref->setRelay(1 << m_localSlot);
  2036. m_disconnectManager->processDisconnectCommand(ref, this);
  2037. ref->deleteInstance();
  2038. msg->detach();
  2039. }
  2040. void ConnectionManager::sendFrameDataToPlayer(UnsignedInt playerID, UnsignedInt startingFrame) {
  2041. DEBUG_LOG(("ConnectionManager::sendFrameDataToPlayer - sending frame data to player %d starting with frame %d\n", playerID, startingFrame));
  2042. for (UnsignedInt frame = startingFrame; frame < TheGameLogic->getFrame(); ++frame) {
  2043. sendSingleFrameToPlayer(playerID, frame);
  2044. }
  2045. DEBUG_LOG(("ConnectionManager::sendFrameDataToPlayer - done sending commands to player %d\n", playerID));
  2046. }
  2047. void ConnectionManager::sendSingleFrameToPlayer(UnsignedInt playerID, UnsignedInt frame) {
  2048. if ((TheGameLogic->getFrame() - FRAMES_TO_KEEP) > frame) {
  2049. DEBUG_LOG(("ConnectionManager::sendSingleFrameToPlayer - player %d requested frame %d when we are on frame %d, this is too far in the past.\n", playerID, frame, TheGameLogic->getFrame()));
  2050. return;
  2051. }
  2052. UnsignedByte relay = 1 << playerID;
  2053. DEBUG_LOG(("ConnectionManager::sendFrameDataToPlayer - sending data for frame %d\n", frame));
  2054. for (Int i = 0; i < MAX_SLOTS; ++i) {
  2055. if ((m_frameData[i] != NULL) && (i != playerID)) { // no need to send his own commands to him.
  2056. NetCommandList *list = m_frameData[i]->getFrameCommandList(frame);
  2057. if (list != NULL) {
  2058. NetCommandRef *ref = list->getFirstMessage();
  2059. while (ref != NULL) {
  2060. DEBUG_LOG(("ConnectionManager::sendFrameDataToPlayer - sending command %d from player %d to player %d using relay 0x%x\n", ref->getCommand()->getID(), i, playerID, relay));
  2061. sendLocalCommandDirect(ref->getCommand(), relay);
  2062. ref = ref->getNext();
  2063. }
  2064. }
  2065. UnsignedInt frameCommandCount = m_frameData[i]->getFrameCommandCount(frame);
  2066. NetFrameCommandMsg *msg = newInstance(NetFrameCommandMsg);
  2067. msg->setExecutionFrame(frame);
  2068. msg->setCommandCount(frameCommandCount);
  2069. if (DoesCommandRequireACommandID(msg->getNetCommandType())) {
  2070. msg->setID(GenerateNextCommandID());
  2071. }
  2072. msg->setPlayerID(i);
  2073. DEBUG_LOG(("ConnectionManager::sendFrameDataToPlayer - sending frame info from player %d to player %d for frame %d with command count %d and ID %d and relay %d\n", i, playerID, msg->getExecutionFrame(), msg->getCommandCount(), msg->getID(), relay));
  2074. sendLocalCommandDirect(msg, relay);
  2075. msg->detach();
  2076. }
  2077. }
  2078. }
  2079. UnsignedInt ConnectionManager::getNextPacketRouterSlot(UnsignedInt playerID) {
  2080. Int index = 0;
  2081. while ((index < (MAX_SLOTS-1)) && (m_packetRouterFallback[index] != playerID)) {
  2082. ++index;
  2083. }
  2084. ++index;
  2085. return m_packetRouterFallback[index];
  2086. }
  2087. void ConnectionManager::requestFrameDataResend(Int playerID, UnsignedInt frame) {
  2088. NetFrameResendRequestCommandMsg *msg = newInstance(NetFrameResendRequestCommandMsg);
  2089. msg->setPlayerID(m_localSlot);
  2090. msg->setFrameToResend(frame);
  2091. if (DoesCommandRequireACommandID(msg->getNetCommandType())) {
  2092. msg->setID(GenerateNextCommandID());
  2093. }
  2094. if (isPlayerConnected(playerID) == FALSE) {
  2095. playerID = 0;
  2096. while ((playerID < MAX_SLOTS) && (isPlayerConnected(playerID) == FALSE)) {
  2097. ++playerID;
  2098. }
  2099. }
  2100. if (playerID < MAX_SLOTS) {
  2101. sendLocalCommandDirect(msg, 1 << playerID);
  2102. }
  2103. msg->detach();
  2104. }