Connection.cpp 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790
  1. //
  2. // Copyright (c) 2008-2020 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Profiler.h"
  24. #include "../IO/File.h"
  25. #include "../IO/FileSystem.h"
  26. #include "../IO/Log.h"
  27. #include "../IO/MemoryBuffer.h"
  28. #include "../IO/PackageFile.h"
  29. #include "../Network/Connection.h"
  30. #include "../Network/Network.h"
  31. #include "../Network/NetworkEvents.h"
  32. #include "../Network/NetworkPriority.h"
  33. #include "../Network/Protocol.h"
  34. #include "../Resource/ResourceCache.h"
  35. #include "../Scene/Scene.h"
  36. #include "../Scene/SceneEvents.h"
  37. #include "../Scene/SmoothedTransform.h"
  38. #ifndef __EMSCRIPTEN__
  39. #include <SLikeNet/MessageIdentifiers.h>
  40. #include <SLikeNet/peerinterface.h>
  41. #include <SLikeNet/statistics.h>
  42. #endif
  43. #ifdef URHO3D_WEBSOCKETS
  44. #include "WS/WSPacket.h"
  45. #include "WS/WSHandler.h"
  46. #include "WS/WSConnection.h"
  47. #include "WS/WSClient.h"
  48. #include "WS/WSServer.h"
  49. #endif
  50. #ifdef SendMessage
  51. #undef SendMessage
  52. #endif
  53. #include "../DebugNew.h"
  54. #include <cstdio>
  55. namespace Urho3D
  56. {
  57. static const int STATS_INTERVAL_MSEC = 2000;
  58. PackageDownload::PackageDownload() :
  59. totalFragments_(0),
  60. checksum_(0),
  61. initiated_(false)
  62. {
  63. }
  64. PackageUpload::PackageUpload() :
  65. fragment_(0),
  66. totalFragments_(0)
  67. {
  68. }
  69. Connection::Connection(Context* context, bool isClient, const SLNet::AddressOrGUID& address, SLNet::RakPeerInterface* peer) :
  70. Object(context),
  71. timeStamp_(0),
  72. peer_(peer),
  73. sendMode_(OPSM_NONE),
  74. isClient_(isClient),
  75. connectPending_(false),
  76. sceneLoaded_(false),
  77. logStatistics_(false),
  78. address_(nullptr),
  79. ws_(nullptr),
  80. wsHandler_(nullptr),
  81. packedMessageLimit_(1024)
  82. {
  83. sceneState_.connection_ = this;
  84. #ifndef __EMSCRIPTEN__
  85. port_ = address.systemAddress.GetPort();
  86. #endif
  87. SetAddressOrGUID(address);
  88. }
  89. Connection::Connection(Context* context, bool isClient, const WSConnection& ws, WSHandler* wsHandler):
  90. Object(context),
  91. timeStamp_(0),
  92. sendMode_(OPSM_NONE),
  93. isClient_(isClient),
  94. connectPending_(false),
  95. sceneLoaded_(false),
  96. logStatistics_(false),
  97. address_(nullptr),
  98. packedMessageLimit_(1024),
  99. peer_(nullptr),
  100. ws_(ws),
  101. wsHandler_(wsHandler)
  102. {
  103. sceneState_.connection_ = this;
  104. }
  105. void Connection::SetWS(const WSConnection& ws)
  106. {
  107. #ifdef URHO3D_WEBSOCKETS
  108. ws_ = ws;
  109. #endif
  110. }
  111. void Connection::SetWSHandler(WSHandler* wsHandler)
  112. {
  113. #ifdef URHO3D_WEBSOCKETS
  114. wsHandler_ = wsHandler;
  115. #endif
  116. }
  117. Connection::~Connection()
  118. {
  119. // Reset scene (remove possible owner references), as this connection is about to be destroyed
  120. SetScene(nullptr);
  121. delete address_;
  122. address_ = nullptr;
  123. }
  124. PacketType Connection::GetPacketType(bool reliable, bool inOrder)
  125. {
  126. if (reliable && inOrder)
  127. return PT_RELIABLE_ORDERED;
  128. if (reliable && !inOrder)
  129. return PT_RELIABLE_UNORDERED;
  130. if (!reliable && inOrder)
  131. return PT_UNRELIABLE_ORDERED;
  132. return PT_UNRELIABLE_UNORDERED;
  133. }
  134. void Connection::SendMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg, unsigned contentID)
  135. {
  136. SendMessage(msgID, reliable, inOrder, msg.GetData(), msg.GetSize(), contentID);
  137. }
  138. void Connection::SendMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes,
  139. unsigned contentID)
  140. {
  141. if (numBytes && !data)
  142. {
  143. URHO3D_LOGERROR("Null pointer supplied for network message data");
  144. return;
  145. }
  146. PacketType type = GetPacketType(reliable, inOrder);
  147. VectorBuffer& buffer = outgoingBuffer_[type];
  148. if (buffer.GetSize() + numBytes >= packedMessageLimit_)
  149. SendBuffer(type);
  150. if (buffer.GetSize() == 0)
  151. {
  152. #ifndef __EMSCRIPTEN__
  153. buffer.WriteUByte((unsigned char)DefaultMessageIDTypes::ID_USER_PACKET_ENUM);
  154. #else
  155. buffer.WriteUByte((unsigned char)URHO3D_MESSAGE);
  156. #endif
  157. buffer.WriteUInt((unsigned int)MSG_PACKED_MESSAGE);
  158. }
  159. buffer.WriteUInt((unsigned int) msgID);
  160. buffer.WriteUInt(numBytes);
  161. buffer.Write(data, numBytes);
  162. }
  163. void Connection::SendRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData)
  164. {
  165. RemoteEvent queuedEvent;
  166. queuedEvent.senderID_ = 0;
  167. queuedEvent.eventType_ = eventType;
  168. queuedEvent.eventData_ = eventData;
  169. queuedEvent.inOrder_ = inOrder;
  170. remoteEvents_.Push(queuedEvent);
  171. }
  172. void Connection::SendRemoteEvent(Node* node, StringHash eventType, bool inOrder, const VariantMap& eventData)
  173. {
  174. if (!node)
  175. {
  176. URHO3D_LOGERROR("Null sender node for remote node event");
  177. return;
  178. }
  179. if (node->GetScene() != scene_)
  180. {
  181. URHO3D_LOGERROR("Sender node is not in the connection's scene, can not send remote node event");
  182. return;
  183. }
  184. if (!node->IsReplicated())
  185. {
  186. URHO3D_LOGERROR("Sender node has a local ID, can not send remote node event");
  187. return;
  188. }
  189. RemoteEvent queuedEvent;
  190. queuedEvent.senderID_ = node->GetID();
  191. queuedEvent.eventType_ = eventType;
  192. queuedEvent.eventData_ = eventData;
  193. queuedEvent.inOrder_ = inOrder;
  194. remoteEvents_.Push(queuedEvent);
  195. }
  196. void Connection::SetScene(Scene* newScene)
  197. {
  198. if (scene_)
  199. {
  200. // Remove replication states and owner references from the previous scene
  201. scene_->CleanupConnection(this);
  202. }
  203. scene_ = newScene;
  204. sceneLoaded_ = false;
  205. UnsubscribeFromEvent(E_ASYNCLOADFINISHED);
  206. if (!scene_)
  207. return;
  208. if (isClient_)
  209. {
  210. sceneState_.Clear();
  211. // When scene is assigned on the server, instruct the client to load it. This may require downloading packages
  212. const Vector<SharedPtr<PackageFile> >& packages = scene_->GetRequiredPackageFiles();
  213. unsigned numPackages = packages.Size();
  214. msg_.Clear();
  215. msg_.WriteString(scene_->GetFileName());
  216. msg_.WriteVLE(numPackages);
  217. for (unsigned i = 0; i < numPackages; ++i)
  218. {
  219. PackageFile* package = packages[i];
  220. msg_.WriteString(GetFileNameAndExtension(package->GetName()));
  221. msg_.WriteUInt(package->GetTotalSize());
  222. msg_.WriteUInt(package->GetChecksum());
  223. }
  224. SendMessage(MSG_LOADSCENE, true, true, msg_);
  225. }
  226. else
  227. {
  228. // Make sure there is no existing async loading
  229. scene_->StopAsyncLoading();
  230. SubscribeToEvent(scene_, E_ASYNCLOADFINISHED, URHO3D_HANDLER(Connection, HandleAsyncLoadFinished));
  231. }
  232. }
  233. void Connection::SetIdentity(const VariantMap& identity)
  234. {
  235. identity_ = identity;
  236. }
  237. void Connection::SetControls(const Controls& newControls)
  238. {
  239. controls_ = newControls;
  240. }
  241. void Connection::SetPosition(const Vector3& position)
  242. {
  243. position_ = position;
  244. if (sendMode_ == OPSM_NONE)
  245. sendMode_ = OPSM_POSITION;
  246. }
  247. void Connection::SetRotation(const Quaternion& rotation)
  248. {
  249. rotation_ = rotation;
  250. if (sendMode_ != OPSM_POSITION_ROTATION)
  251. sendMode_ = OPSM_POSITION_ROTATION;
  252. }
  253. void Connection::SetConnectPending(bool connectPending)
  254. {
  255. connectPending_ = connectPending;
  256. }
  257. void Connection::SetLogStatistics(bool enable)
  258. {
  259. logStatistics_ = enable;
  260. }
  261. void Connection::Disconnect(int waitMSec)
  262. {
  263. #ifndef __EMSCRIPTEN__
  264. if (peer_)
  265. peer_->CloseConnection(*address_, true);
  266. #endif
  267. #ifdef URHO3D_WEBSOCKETS
  268. if (!isClient_ && wsHandler_)
  269. static_cast<WSClient*>(wsHandler_)->Disconnect();
  270. #ifndef __EMSCRIPTEN__
  271. if (isClient_ && wsHandler_)
  272. static_cast<WSServer*>(wsHandler_)->MarkForDisconnect(ws_);
  273. #endif
  274. #endif
  275. }
  276. void Connection::SendServerUpdate()
  277. {
  278. if (!scene_ || !sceneLoaded_)
  279. return;
  280. // Always check the root node (scene) first so that the scene-wide components get sent first,
  281. // and all other replicated nodes get added to the dirty set for sending the initial state
  282. unsigned sceneID = scene_->GetID();
  283. nodesToProcess_.Insert(sceneID);
  284. ProcessNode(sceneID);
  285. // Then go through all dirtied nodes
  286. nodesToProcess_.Insert(sceneState_.dirtyNodes_);
  287. nodesToProcess_.Erase(sceneID); // Do not process the root node twice
  288. while (nodesToProcess_.Size())
  289. {
  290. unsigned nodeID = nodesToProcess_.Front();
  291. ProcessNode(nodeID);
  292. }
  293. }
  294. void Connection::SendClientUpdate()
  295. {
  296. if (!scene_ || !sceneLoaded_)
  297. return;
  298. msg_.Clear();
  299. msg_.WriteUInt(controls_.buttons_);
  300. msg_.WriteFloat(controls_.yaw_);
  301. msg_.WriteFloat(controls_.pitch_);
  302. msg_.WriteVariantMap(controls_.extraData_);
  303. msg_.WriteUByte(timeStamp_);
  304. if (sendMode_ >= OPSM_POSITION)
  305. msg_.WriteVector3(position_);
  306. if (sendMode_ >= OPSM_POSITION_ROTATION)
  307. msg_.WritePackedQuaternion(rotation_);
  308. SendMessage(MSG_CONTROLS, false, false, msg_, CONTROLS_CONTENT_ID);
  309. ++timeStamp_;
  310. }
  311. void Connection::SendRemoteEvents()
  312. {
  313. #ifdef URHO3D_LOGGING
  314. if (logStatistics_ && statsTimer_.GetMSec(false) > STATS_INTERVAL_MSEC)
  315. {
  316. statsTimer_.Reset();
  317. char statsBuffer[256];
  318. sprintf(statsBuffer, "RTT %.3f ms Pkt in %i Pkt out %i Data in %.3f KB/s Data out %.3f KB/s, Last heard %u", GetRoundTripTime(),
  319. GetPacketsInPerSec(),
  320. GetPacketsOutPerSec(),
  321. GetBytesInPerSec(),
  322. GetBytesOutPerSec(),
  323. GetLastHeardTime());
  324. URHO3D_LOGINFO(statsBuffer);
  325. }
  326. #endif
  327. if (packetCounterTimer_.GetMSec(false) > 1000)
  328. {
  329. packetCounterTimer_.Reset();
  330. packetCounter_ = tempPacketCounter_;
  331. tempPacketCounter_ = IntVector2::ZERO;
  332. }
  333. if (remoteEvents_.Empty())
  334. return;
  335. URHO3D_PROFILE(SendRemoteEvents);
  336. for (Vector<RemoteEvent>::ConstIterator i = remoteEvents_.Begin(); i != remoteEvents_.End(); ++i)
  337. {
  338. msg_.Clear();
  339. if (!i->senderID_)
  340. {
  341. msg_.WriteStringHash(i->eventType_);
  342. msg_.WriteVariantMap(i->eventData_);
  343. SendMessage(MSG_REMOTEEVENT, true, i->inOrder_, msg_);
  344. }
  345. else
  346. {
  347. msg_.WriteNetID(i->senderID_);
  348. msg_.WriteStringHash(i->eventType_);
  349. msg_.WriteVariantMap(i->eventData_);
  350. SendMessage(MSG_REMOTENODEEVENT, true, i->inOrder_, msg_);
  351. }
  352. }
  353. remoteEvents_.Clear();
  354. }
  355. void Connection::SendPackages()
  356. {
  357. while (!uploads_.Empty())
  358. {
  359. unsigned char buffer[PACKAGE_FRAGMENT_SIZE];
  360. for (HashMap<StringHash, PackageUpload>::Iterator i = uploads_.Begin(); i != uploads_.End();)
  361. {
  362. HashMap<StringHash, PackageUpload>::Iterator current = i++;
  363. PackageUpload& upload = current->second_;
  364. auto fragmentSize =
  365. (unsigned)Min((int)(upload.file_->GetSize() - upload.file_->GetPosition()), (int)PACKAGE_FRAGMENT_SIZE);
  366. upload.file_->Read(buffer, fragmentSize);
  367. msg_.Clear();
  368. msg_.WriteStringHash(current->first_);
  369. msg_.WriteUInt(upload.fragment_++);
  370. msg_.Write(buffer, fragmentSize);
  371. SendMessage(MSG_PACKAGEDATA, true, false, msg_);
  372. // Check if upload finished
  373. if (upload.fragment_ == upload.totalFragments_)
  374. uploads_.Erase(current);
  375. }
  376. }
  377. }
  378. void Connection::SendBuffer(PacketType type)
  379. {
  380. VectorBuffer& buffer = outgoingBuffer_[type];
  381. if (buffer.GetSize() == 0)
  382. return;
  383. bool sentOut = false;
  384. #ifndef __EMSCRIPTEN__
  385. PacketReliability reliability = PacketReliability::UNRELIABLE;
  386. if (type == PT_UNRELIABLE_ORDERED)
  387. reliability = PacketReliability::UNRELIABLE_SEQUENCED;
  388. if (type == PT_RELIABLE_ORDERED)
  389. reliability = PacketReliability::RELIABLE_ORDERED;
  390. if (type == PT_RELIABLE_UNORDERED)
  391. reliability = PacketReliability::RELIABLE;
  392. if (peer_)
  393. {
  394. peer_->Send((const char *) buffer.GetData(), (int) buffer.GetSize(), HIGH_PRIORITY, reliability, (char) 0, *address_, false);
  395. tempPacketCounter_.y_++;
  396. sentOut = true;
  397. }
  398. #endif
  399. #ifdef URHO3D_WEBSOCKETS
  400. if (wsHandler_)
  401. {
  402. wsHandler_->AddOutgoingPacket(WSPacket(ws_, buffer));
  403. tempPacketCounter_.y_++;
  404. sentOut = true;
  405. }
  406. #endif
  407. if (!sentOut)
  408. URHO3D_LOGERRORF("Message has not yet been sent out");
  409. else
  410. buffer.Clear();
  411. }
  412. void Connection::SendAllBuffers()
  413. {
  414. SendBuffer(PT_RELIABLE_ORDERED);
  415. SendBuffer(PT_RELIABLE_UNORDERED);
  416. SendBuffer(PT_UNRELIABLE_ORDERED);
  417. SendBuffer(PT_UNRELIABLE_UNORDERED);
  418. }
  419. void Connection::ProcessPendingLatestData()
  420. {
  421. if (!scene_ || !sceneLoaded_)
  422. return;
  423. // Iterate through pending node data and see if we can find the nodes now
  424. for (HashMap<unsigned, PODVector<unsigned char> >::Iterator i = nodeLatestData_.Begin(); i != nodeLatestData_.End();)
  425. {
  426. HashMap<unsigned, PODVector<unsigned char> >::Iterator current = i++;
  427. Node* node = scene_->GetNode(current->first_);
  428. if (node)
  429. {
  430. MemoryBuffer msg(current->second_);
  431. msg.ReadNetID(); // Skip the node ID
  432. node->ReadLatestDataUpdate(msg);
  433. // ApplyAttributes() is deliberately skipped, as Node has no attributes that require late applying.
  434. // Furthermore it would propagate to components and child nodes, which is not desired in this case
  435. nodeLatestData_.Erase(current);
  436. }
  437. }
  438. // Iterate through pending component data and see if we can find the components now
  439. for (HashMap<unsigned, PODVector<unsigned char> >::Iterator i = componentLatestData_.Begin(); i != componentLatestData_.End();)
  440. {
  441. HashMap<unsigned, PODVector<unsigned char> >::Iterator current = i++;
  442. Component* component = scene_->GetComponent(current->first_);
  443. if (component)
  444. {
  445. MemoryBuffer msg(current->second_);
  446. msg.ReadNetID(); // Skip the component ID
  447. if (component->ReadLatestDataUpdate(msg))
  448. component->ApplyAttributes();
  449. componentLatestData_.Erase(current);
  450. }
  451. }
  452. }
  453. bool Connection::ProcessMessage(int msgID, MemoryBuffer& buffer)
  454. {
  455. tempPacketCounter_.x_++;
  456. if (buffer.GetSize() == 0)
  457. return false;
  458. if (msgID != MSG_PACKED_MESSAGE)
  459. {
  460. ProcessUnknownMessage(msgID, buffer);
  461. return true;
  462. }
  463. while (!buffer.IsEof()) {
  464. msgID = buffer.ReadUInt();
  465. unsigned int packetSize = buffer.ReadUInt();
  466. MemoryBuffer msg(buffer.GetData() + buffer.GetPosition(), packetSize);
  467. buffer.Seek(buffer.GetPosition() + packetSize);
  468. switch (msgID)
  469. {
  470. case MSG_IDENTITY:
  471. ProcessIdentity(msgID, msg);
  472. break;
  473. case MSG_CONTROLS:
  474. ProcessControls(msgID, msg);
  475. break;
  476. case MSG_SCENELOADED:
  477. ProcessSceneLoaded(msgID, msg);
  478. break;
  479. case MSG_REQUESTPACKAGE:
  480. case MSG_PACKAGEDATA:
  481. ProcessPackageDownload(msgID, msg);
  482. break;
  483. case MSG_LOADSCENE:
  484. ProcessLoadScene(msgID, msg);
  485. break;
  486. case MSG_SCENECHECKSUMERROR:
  487. ProcessSceneChecksumError(msgID, msg);
  488. break;
  489. case MSG_CREATENODE:
  490. case MSG_NODEDELTAUPDATE:
  491. case MSG_NODELATESTDATA:
  492. case MSG_REMOVENODE:
  493. case MSG_CREATECOMPONENT:
  494. case MSG_COMPONENTDELTAUPDATE:
  495. case MSG_COMPONENTLATESTDATA:
  496. case MSG_REMOVECOMPONENT:
  497. ProcessSceneUpdate(msgID, msg);
  498. break;
  499. case MSG_REMOTEEVENT:
  500. case MSG_REMOTENODEEVENT:
  501. ProcessRemoteEvent(msgID, msg);
  502. break;
  503. case MSG_PACKAGEINFO:
  504. ProcessPackageInfo(msgID, msg);
  505. break;
  506. default:
  507. ProcessUnknownMessage(msgID, msg);
  508. break;
  509. }
  510. }
  511. return true;
  512. }
  513. void Connection::Ban()
  514. {
  515. #ifndef __EMSCRIPTEN__
  516. if (peer_)
  517. {
  518. peer_->AddToBanList(address_->ToString(false), 0);
  519. }
  520. #endif
  521. }
  522. void Connection::ProcessLoadScene(int msgID, MemoryBuffer& msg)
  523. {
  524. if (IsClient())
  525. {
  526. URHO3D_LOGWARNING("Received unexpected LoadScene message from client " + ToString());
  527. return;
  528. }
  529. if (!scene_)
  530. {
  531. URHO3D_LOGERROR("Can not handle LoadScene message without an assigned scene");
  532. return;
  533. }
  534. // Store the scene file name we need to eventually load
  535. sceneFileName_ = msg.ReadString();
  536. // Clear previous pending latest data and package downloads if any
  537. nodeLatestData_.Clear();
  538. componentLatestData_.Clear();
  539. downloads_.Clear();
  540. // In case we have joined other scenes in this session, remove first all downloaded package files from the resource system
  541. // to prevent resource conflicts
  542. auto* cache = GetSubsystem<ResourceCache>();
  543. const String& packageCacheDir = GetSubsystem<Network>()->GetPackageCacheDir();
  544. Vector<SharedPtr<PackageFile> > packages = cache->GetPackageFiles();
  545. for (unsigned i = 0; i < packages.Size(); ++i)
  546. {
  547. PackageFile* package = packages[i];
  548. if (!package->GetName().Find(packageCacheDir))
  549. cache->RemovePackageFile(package, true);
  550. }
  551. // Now check which packages we have in the resource cache or in the download cache, and which we need to download
  552. unsigned numPackages = msg.ReadVLE();
  553. if (!RequestNeededPackages(numPackages, msg))
  554. {
  555. OnSceneLoadFailed();
  556. return;
  557. }
  558. // If no downloads were queued, can load the scene directly
  559. if (downloads_.Empty())
  560. OnPackagesReady();
  561. }
  562. void Connection::ProcessSceneChecksumError(int msgID, MemoryBuffer& msg)
  563. {
  564. if (IsClient())
  565. {
  566. URHO3D_LOGWARNING("Received unexpected SceneChecksumError message from client " + ToString());
  567. return;
  568. }
  569. URHO3D_LOGERROR("Scene checksum error");
  570. OnSceneLoadFailed();
  571. }
  572. void Connection::ProcessSceneUpdate(int msgID, MemoryBuffer& msg)
  573. {
  574. /// \todo On mobile devices processing this message may potentially cause a crash if it attempts to load new GPU resources
  575. /// while the application is minimized
  576. if (IsClient())
  577. {
  578. URHO3D_LOGWARNING("Received unexpected SceneUpdate message from client " + ToString());
  579. return;
  580. }
  581. if (!scene_)
  582. return;
  583. switch (msgID)
  584. {
  585. case MSG_CREATENODE:
  586. {
  587. URHO3D_LOGINFOF("MSG_CREATENODE received with size %d", msg.GetSize());
  588. unsigned nodeID = msg.ReadNetID();
  589. // In case of the root node (scene), it should already exist. Do not create in that case
  590. Node* node = scene_->GetNode(nodeID);
  591. if (!node)
  592. {
  593. URHO3D_LOGINFOF("CREATE NODE 1: %d", nodeID);
  594. // Add initially to the root level. May be moved as we receive the parent attribute
  595. node = scene_->CreateChild(nodeID, REPLICATED);
  596. // Create smoothed transform component
  597. node->CreateComponent<SmoothedTransform>(LOCAL);
  598. }
  599. URHO3D_LOGINFOF("CREATE NODE 2: %d", nodeID);
  600. // Read initial attributes, then snap the motion smoothing immediately to the end
  601. node->ReadDeltaUpdate(msg);
  602. auto* transform = node->GetComponent<SmoothedTransform>();
  603. if (transform)
  604. transform->Update(1.0f, 0.0f);
  605. // Read initial user variables
  606. unsigned numVars = msg.ReadVLE();
  607. URHO3D_LOGINFOF("CREATE NODE 3");
  608. while (numVars)
  609. {
  610. StringHash key = msg.ReadStringHash();
  611. node->SetVar(key, msg.ReadVariant());
  612. --numVars;
  613. }
  614. URHO3D_LOGINFOF("CREATE NODE 4");
  615. // Read components
  616. unsigned numComponents = msg.ReadVLE();
  617. URHO3D_LOGINFOF("NUm components %d", numComponents);
  618. while (numComponents)
  619. {
  620. URHO3D_LOGINFOF("CREATE NODE 5");
  621. --numComponents;
  622. StringHash type = msg.ReadStringHash();
  623. unsigned componentID = msg.ReadNetID();
  624. // Check if the component by this ID and type already exists in this node
  625. Component* component = scene_->GetComponent(componentID);
  626. if (!component || component->GetType() != type || component->GetNode() != node)
  627. {
  628. if (component)
  629. component->Remove();
  630. component = node->CreateComponent(type, REPLICATED, componentID);
  631. URHO3D_LOGINFOF("CREATE NODE 6");
  632. }
  633. // If was unable to create the component, would desync the message and therefore have to abort
  634. if (!component)
  635. {
  636. URHO3D_LOGERROR("CreateNode message parsing aborted due to unknown component");
  637. return;
  638. }
  639. // Read initial attributes and apply
  640. component->ReadDeltaUpdate(msg);
  641. component->ApplyAttributes();
  642. URHO3D_LOGINFOF("CREATE NODE 7");
  643. }
  644. }
  645. break;
  646. case MSG_NODEDELTAUPDATE:
  647. {
  648. unsigned nodeID = msg.ReadNetID();
  649. Node* node = scene_->GetNode(nodeID);
  650. if (node)
  651. {
  652. node->ReadDeltaUpdate(msg);
  653. // ApplyAttributes() is deliberately skipped, as Node has no attributes that require late applying.
  654. // Furthermore it would propagate to components and child nodes, which is not desired in this case
  655. unsigned changedVars = msg.ReadVLE();
  656. while (changedVars)
  657. {
  658. StringHash key = msg.ReadStringHash();
  659. node->SetVar(key, msg.ReadVariant());
  660. --changedVars;
  661. }
  662. }
  663. else
  664. URHO3D_LOGWARNING("NodeDeltaUpdate message received for missing node " + String(nodeID));
  665. }
  666. break;
  667. case MSG_NODELATESTDATA:
  668. {
  669. unsigned nodeID = msg.ReadNetID();
  670. Node* node = scene_->GetNode(nodeID);
  671. if (node)
  672. {
  673. node->ReadLatestDataUpdate(msg);
  674. // ApplyAttributes() is deliberately skipped, as Node has no attributes that require late applying.
  675. // Furthermore it would propagate to components and child nodes, which is not desired in this case
  676. }
  677. else
  678. {
  679. // Latest data messages may be received out-of-order relative to node creation, so cache if necessary
  680. PODVector<unsigned char>& data = nodeLatestData_[nodeID];
  681. data.Resize(msg.GetSize());
  682. memcpy(&data[0], msg.GetData(), msg.GetSize());
  683. }
  684. }
  685. break;
  686. case MSG_REMOVENODE:
  687. {
  688. unsigned nodeID = msg.ReadNetID();
  689. Node* node = scene_->GetNode(nodeID);
  690. if (node)
  691. node->Remove();
  692. nodeLatestData_.Erase(nodeID);
  693. }
  694. break;
  695. case MSG_CREATECOMPONENT:
  696. {
  697. unsigned nodeID = msg.ReadNetID();
  698. Node* node = scene_->GetNode(nodeID);
  699. if (node)
  700. {
  701. StringHash type = msg.ReadStringHash();
  702. unsigned componentID = msg.ReadNetID();
  703. // Check if the component by this ID and type already exists in this node
  704. Component* component = scene_->GetComponent(componentID);
  705. if (!component || component->GetType() != type || component->GetNode() != node)
  706. {
  707. if (component)
  708. component->Remove();
  709. component = node->CreateComponent(type, REPLICATED, componentID);
  710. }
  711. // If was unable to create the component, would desync the message and therefore have to abort
  712. if (!component)
  713. {
  714. URHO3D_LOGERROR("CreateComponent message parsing aborted due to unknown component");
  715. return;
  716. }
  717. // Read initial attributes and apply
  718. component->ReadDeltaUpdate(msg);
  719. component->ApplyAttributes();
  720. }
  721. else
  722. URHO3D_LOGWARNING("CreateComponent message received for missing node " + String(nodeID));
  723. }
  724. break;
  725. case MSG_COMPONENTDELTAUPDATE:
  726. {
  727. unsigned componentID = msg.ReadNetID();
  728. Component* component = scene_->GetComponent(componentID);
  729. if (component)
  730. {
  731. component->ReadDeltaUpdate(msg);
  732. component->ApplyAttributes();
  733. }
  734. else
  735. URHO3D_LOGWARNING("ComponentDeltaUpdate message received for missing component " + String(componentID));
  736. }
  737. break;
  738. case MSG_COMPONENTLATESTDATA:
  739. {
  740. unsigned componentID = msg.ReadNetID();
  741. Component* component = scene_->GetComponent(componentID);
  742. if (component)
  743. {
  744. if (component->ReadLatestDataUpdate(msg))
  745. component->ApplyAttributes();
  746. }
  747. else
  748. {
  749. // Latest data messages may be received out-of-order relative to component creation, so cache if necessary
  750. PODVector<unsigned char>& data = componentLatestData_[componentID];
  751. data.Resize(msg.GetSize());
  752. memcpy(&data[0], msg.GetData(), msg.GetSize());
  753. }
  754. }
  755. break;
  756. case MSG_REMOVECOMPONENT:
  757. {
  758. unsigned componentID = msg.ReadNetID();
  759. Component* component = scene_->GetComponent(componentID);
  760. if (component)
  761. component->Remove();
  762. componentLatestData_.Erase(componentID);
  763. }
  764. break;
  765. default: break;
  766. }
  767. }
  768. void Connection::ProcessPackageDownload(int msgID, MemoryBuffer& msg)
  769. {
  770. switch (msgID)
  771. {
  772. case MSG_REQUESTPACKAGE:
  773. if (!IsClient())
  774. {
  775. URHO3D_LOGWARNING("Received unexpected RequestPackage message from server");
  776. return;
  777. }
  778. else
  779. {
  780. String name = msg.ReadString();
  781. if (!scene_)
  782. {
  783. URHO3D_LOGWARNING("Received a RequestPackage message without an assigned scene from client " + ToString());
  784. return;
  785. }
  786. // The package must be one of those required by the scene
  787. const Vector<SharedPtr<PackageFile> >& packages = scene_->GetRequiredPackageFiles();
  788. for (unsigned i = 0; i < packages.Size(); ++i)
  789. {
  790. PackageFile* package = packages[i];
  791. const String& packageFullName = package->GetName();
  792. if (!GetFileNameAndExtension(packageFullName).Compare(name, false))
  793. {
  794. StringHash nameHash(name);
  795. // Do not restart upload if already exists
  796. if (uploads_.Contains(nameHash))
  797. {
  798. URHO3D_LOGWARNING("Received a request for package " + name + " already in transfer");
  799. return;
  800. }
  801. // Try to open the file now
  802. SharedPtr<File> file(new File(context_, packageFullName));
  803. if (!file->IsOpen())
  804. {
  805. URHO3D_LOGERROR("Failed to transmit package file " + name);
  806. SendPackageError(name);
  807. return;
  808. }
  809. URHO3D_LOGINFO("Transmitting package file " + name + " to client " + ToString());
  810. uploads_[nameHash].file_ = file;
  811. uploads_[nameHash].fragment_ = 0;
  812. uploads_[nameHash].totalFragments_ = (file->GetSize() + PACKAGE_FRAGMENT_SIZE - 1) / PACKAGE_FRAGMENT_SIZE;
  813. return;
  814. }
  815. }
  816. URHO3D_LOGERROR("Client requested an unexpected package file " + name);
  817. // Send the name hash only to indicate a failed download
  818. SendPackageError(name);
  819. return;
  820. }
  821. break;
  822. case MSG_PACKAGEDATA:
  823. if (IsClient())
  824. {
  825. URHO3D_LOGWARNING("Received unexpected PackageData message from client");
  826. return;
  827. }
  828. else
  829. {
  830. StringHash nameHash = msg.ReadStringHash();
  831. HashMap<StringHash, PackageDownload>::Iterator i = downloads_.Find(nameHash);
  832. // In case of being unable to create the package file into the cache, we will still receive all data from the server.
  833. // Simply disregard it
  834. if (i == downloads_.End())
  835. return;
  836. PackageDownload& download = i->second_;
  837. // If no further data, this is an error reply
  838. if (msg.IsEof())
  839. {
  840. OnPackageDownloadFailed(download.name_);
  841. return;
  842. }
  843. // If file has not yet been opened, try to open now. Prepend the checksum to the filename to allow multiple versions
  844. if (!download.file_)
  845. {
  846. download.file_ = new File(context_,
  847. GetSubsystem<Network>()->GetPackageCacheDir() + ToStringHex(download.checksum_) + "_" + download.name_,
  848. FILE_WRITE);
  849. if (!download.file_->IsOpen())
  850. {
  851. OnPackageDownloadFailed(download.name_);
  852. return;
  853. }
  854. }
  855. // Write the fragment data to the proper index
  856. unsigned char buffer[PACKAGE_FRAGMENT_SIZE];
  857. unsigned index = msg.ReadUInt();
  858. unsigned fragmentSize = msg.GetSize() - msg.GetPosition();
  859. msg.Read(buffer, fragmentSize);
  860. download.file_->Seek(index * PACKAGE_FRAGMENT_SIZE);
  861. download.file_->Write(buffer, fragmentSize);
  862. download.receivedFragments_.Insert(index);
  863. // Check if all fragments received
  864. if (download.receivedFragments_.Size() == download.totalFragments_)
  865. {
  866. URHO3D_LOGINFO("Package " + download.name_ + " downloaded successfully");
  867. // Instantiate the package and add to the resource system, as we will need it to load the scene
  868. download.file_->Close();
  869. GetSubsystem<ResourceCache>()->AddPackageFile(download.file_->GetName(), 0);
  870. // Then start the next download if there are more
  871. downloads_.Erase(i);
  872. if (downloads_.Empty())
  873. OnPackagesReady();
  874. else
  875. {
  876. PackageDownload& nextDownload = downloads_.Begin()->second_;
  877. URHO3D_LOGINFO("Requesting package " + nextDownload.name_ + " from server");
  878. msg_.Clear();
  879. msg_.WriteString(nextDownload.name_);
  880. SendMessage(MSG_REQUESTPACKAGE, true, true, msg_);
  881. nextDownload.initiated_ = true;
  882. }
  883. }
  884. }
  885. break;
  886. default: break;
  887. }
  888. }
  889. void Connection::ProcessIdentity(int msgID, MemoryBuffer& msg)
  890. {
  891. if (!IsClient())
  892. {
  893. URHO3D_LOGWARNING("Received unexpected Identity message from server");
  894. return;
  895. }
  896. identity_ = msg.ReadVariantMap();
  897. using namespace ClientIdentity;
  898. VariantMap eventData = identity_;
  899. eventData[P_CONNECTION] = this;
  900. eventData[P_ALLOW] = true;
  901. SendEvent(E_CLIENTIDENTITY, eventData);
  902. // If connection was denied as a response to the identity event, disconnect now
  903. if (!eventData[P_ALLOW].GetBool())
  904. Disconnect();
  905. }
  906. void Connection::ProcessControls(int msgID, MemoryBuffer& msg)
  907. {
  908. if (!IsClient())
  909. {
  910. URHO3D_LOGWARNING("Received unexpected Controls message from server");
  911. return;
  912. }
  913. Controls newControls;
  914. newControls.buttons_ = msg.ReadUInt();
  915. newControls.yaw_ = msg.ReadFloat();
  916. newControls.pitch_ = msg.ReadFloat();
  917. newControls.extraData_ = msg.ReadVariantMap();
  918. SetControls(newControls);
  919. timeStamp_ = msg.ReadUByte();
  920. // Client may or may not send observer position & rotation for interest management
  921. if (!msg.IsEof())
  922. position_ = msg.ReadVector3();
  923. if (!msg.IsEof())
  924. rotation_ = msg.ReadPackedQuaternion();
  925. }
  926. void Connection::ProcessSceneLoaded(int msgID, MemoryBuffer& msg)
  927. {
  928. if (!IsClient())
  929. {
  930. URHO3D_LOGWARNING("Received unexpected SceneLoaded message from server");
  931. return;
  932. }
  933. if (!scene_)
  934. {
  935. URHO3D_LOGWARNING("Received a SceneLoaded message without an assigned scene from client " + ToString());
  936. return;
  937. }
  938. unsigned checksum = msg.ReadUInt();
  939. if (checksum != scene_->GetChecksum())
  940. {
  941. URHO3D_LOGINFO("Scene checksum error from client " + ToString());
  942. msg_.Clear();
  943. SendMessage(MSG_SCENECHECKSUMERROR, true, true, msg_);
  944. OnSceneLoadFailed();
  945. }
  946. else
  947. {
  948. sceneLoaded_ = true;
  949. using namespace ClientSceneLoaded;
  950. VariantMap& eventData = GetEventDataMap();
  951. eventData[P_CONNECTION] = this;
  952. SendEvent(E_CLIENTSCENELOADED, eventData);
  953. }
  954. }
  955. void Connection::ProcessRemoteEvent(int msgID, MemoryBuffer& msg)
  956. {
  957. using namespace RemoteEventData;
  958. if (msgID == MSG_REMOTEEVENT)
  959. {
  960. StringHash eventType = msg.ReadStringHash();
  961. if (!GetSubsystem<Network>()->CheckRemoteEvent(eventType))
  962. {
  963. URHO3D_LOGWARNING("Discarding not allowed remote event " + eventType.ToString());
  964. return;
  965. }
  966. VariantMap eventData = msg.ReadVariantMap();
  967. eventData[P_CONNECTION] = this;
  968. SendEvent(eventType, eventData);
  969. }
  970. else
  971. {
  972. if (!scene_)
  973. {
  974. URHO3D_LOGERROR("Can not receive remote node event without an assigned scene");
  975. return;
  976. }
  977. unsigned nodeID = msg.ReadNetID();
  978. StringHash eventType = msg.ReadStringHash();
  979. if (!GetSubsystem<Network>()->CheckRemoteEvent(eventType))
  980. {
  981. URHO3D_LOGWARNING("Discarding not allowed remote event " + eventType.ToString());
  982. return;
  983. }
  984. VariantMap eventData = msg.ReadVariantMap();
  985. Node* sender = scene_->GetNode(nodeID);
  986. if (!sender)
  987. {
  988. URHO3D_LOGWARNING("Missing sender for remote node event, discarding");
  989. return;
  990. }
  991. eventData[P_CONNECTION] = this;
  992. sender->SendEvent(eventType, eventData);
  993. }
  994. }
  995. Scene* Connection::GetScene() const
  996. {
  997. return scene_;
  998. }
  999. bool Connection::IsConnected() const
  1000. {
  1001. #ifndef __EMSCRIPTEN__
  1002. return peer_ && peer_->IsActive();
  1003. #else
  1004. if (ws_.GetWS())
  1005. return true;
  1006. #endif
  1007. }
  1008. float Connection::GetRoundTripTime() const
  1009. {
  1010. #ifndef __EMSCRIPTEN__
  1011. if (peer_)
  1012. {
  1013. SLNet::RakNetStatistics stats{};
  1014. if (peer_->GetStatistics(address_->systemAddress, &stats))
  1015. return (float)peer_->GetAveragePing(*address_);
  1016. }
  1017. #endif
  1018. return 0.0f;
  1019. }
  1020. unsigned Connection::GetLastHeardTime() const
  1021. {
  1022. return const_cast<Timer&>(lastHeardTimer_).GetMSec(false);
  1023. }
  1024. float Connection::GetBytesInPerSec() const
  1025. {
  1026. #ifndef __EMSCRIPTEN__
  1027. if (peer_)
  1028. {
  1029. SLNet::RakNetStatistics stats{};
  1030. if (peer_->GetStatistics(address_->systemAddress, &stats))
  1031. return (float)stats.valueOverLastSecond[SLNet::ACTUAL_BYTES_RECEIVED];
  1032. }
  1033. #endif
  1034. return 0.0f;
  1035. }
  1036. float Connection::GetBytesOutPerSec() const
  1037. {
  1038. #ifndef __EMSCRIPTEN__
  1039. if (peer_)
  1040. {
  1041. SLNet::RakNetStatistics stats{};
  1042. if (peer_->GetStatistics(address_->systemAddress, &stats))
  1043. return (float)stats.valueOverLastSecond[SLNet::ACTUAL_BYTES_SENT];
  1044. }
  1045. #endif
  1046. return 0.0f;
  1047. }
  1048. int Connection::GetPacketsInPerSec() const
  1049. {
  1050. return packetCounter_.x_;
  1051. }
  1052. int Connection::GetPacketsOutPerSec() const
  1053. {
  1054. return packetCounter_.y_;
  1055. }
  1056. String Connection::ToString() const
  1057. {
  1058. if (peer_)
  1059. return GetAddress() + ":" + String(GetPort());
  1060. #ifdef URHO3D_WEBSOCKETS
  1061. if (ws_.GetWS())
  1062. return "WS connection";
  1063. #endif
  1064. return String::EMPTY;
  1065. }
  1066. unsigned Connection::GetNumDownloads() const
  1067. {
  1068. return downloads_.Size();
  1069. }
  1070. const String& Connection::GetDownloadName() const
  1071. {
  1072. for (HashMap<StringHash, PackageDownload>::ConstIterator i = downloads_.Begin(); i != downloads_.End(); ++i)
  1073. {
  1074. if (i->second_.initiated_)
  1075. return i->second_.name_;
  1076. }
  1077. return String::EMPTY;
  1078. }
  1079. float Connection::GetDownloadProgress() const
  1080. {
  1081. for (HashMap<StringHash, PackageDownload>::ConstIterator i = downloads_.Begin(); i != downloads_.End(); ++i)
  1082. {
  1083. if (i->second_.initiated_)
  1084. return (float)i->second_.receivedFragments_.Size() / (float)i->second_.totalFragments_;
  1085. }
  1086. return 1.0f;
  1087. }
  1088. void Connection::SendPackageToClient(PackageFile* package)
  1089. {
  1090. if (!scene_)
  1091. return;
  1092. if (!IsClient())
  1093. {
  1094. URHO3D_LOGERROR("SendPackageToClient can be called on the server only");
  1095. return;
  1096. }
  1097. if (!package)
  1098. {
  1099. URHO3D_LOGERROR("Null package specified for SendPackageToClient");
  1100. return;
  1101. }
  1102. msg_.Clear();
  1103. String filename = GetFileNameAndExtension(package->GetName());
  1104. msg_.WriteString(filename);
  1105. msg_.WriteUInt(package->GetTotalSize());
  1106. msg_.WriteUInt(package->GetChecksum());
  1107. SendMessage(MSG_PACKAGEINFO, true, true, msg_);
  1108. }
  1109. void Connection::ConfigureNetworkSimulator(int latencyMs, float packetLoss)
  1110. {
  1111. #ifndef __EMSCRIPTEN__
  1112. if (peer_)
  1113. peer_->ApplyNetworkSimulator(packetLoss, latencyMs, 0);
  1114. #endif
  1115. }
  1116. void Connection::SetPacketSizeLimit(int limit)
  1117. {
  1118. packedMessageLimit_ = limit;
  1119. }
  1120. void Connection::HandleAsyncLoadFinished(StringHash eventType, VariantMap& eventData)
  1121. {
  1122. sceneLoaded_ = true;
  1123. // Clear all replicated nodes
  1124. scene_->Clear(true, false);
  1125. msg_.Clear();
  1126. msg_.WriteUInt(scene_->GetChecksum());
  1127. SendMessage(MSG_SCENELOADED, true, true, msg_);
  1128. }
  1129. void Connection::ProcessNode(unsigned nodeID)
  1130. {
  1131. // Check that we have not already processed this due to dependency recursion
  1132. if (!nodesToProcess_.Erase(nodeID))
  1133. return;
  1134. // Find replication state for the node
  1135. HashMap<unsigned, NodeReplicationState>::Iterator i = sceneState_.nodeStates_.Find(nodeID);
  1136. if (i != sceneState_.nodeStates_.End())
  1137. {
  1138. // Replication state found: the node is either be existing or removed
  1139. Node* node = i->second_.node_;
  1140. if (!node)
  1141. {
  1142. msg_.Clear();
  1143. msg_.WriteNetID(nodeID);
  1144. // Note: we will send MSG_REMOVENODE redundantly for each node in the hierarchy, even if removing the root node
  1145. // would be enough. However, this may be better due to the client not possibly having updated parenting
  1146. // information at the time of receiving this message
  1147. SendMessage(MSG_REMOVENODE, true, true, msg_);
  1148. sceneState_.nodeStates_.Erase(nodeID);
  1149. }
  1150. else
  1151. ProcessExistingNode(node, i->second_);
  1152. }
  1153. else
  1154. {
  1155. // Replication state not found: this is a new node
  1156. Node* node = scene_->GetNode(nodeID);
  1157. if (node)
  1158. ProcessNewNode(node);
  1159. else
  1160. {
  1161. // Did not find the new node (may have been created, then removed immediately): erase from dirty set.
  1162. sceneState_.dirtyNodes_.Erase(nodeID);
  1163. }
  1164. }
  1165. }
  1166. void Connection::ProcessNewNode(Node* node)
  1167. {
  1168. // Process depended upon nodes first, if they are dirty
  1169. const PODVector<Node*>& dependencyNodes = node->GetDependencyNodes();
  1170. for (PODVector<Node*>::ConstIterator i = dependencyNodes.Begin(); i != dependencyNodes.End(); ++i)
  1171. {
  1172. unsigned nodeID = (*i)->GetID();
  1173. if (sceneState_.dirtyNodes_.Contains(nodeID))
  1174. ProcessNode(nodeID);
  1175. }
  1176. msg_.Clear();
  1177. msg_.WriteNetID(node->GetID());
  1178. NodeReplicationState& nodeState = sceneState_.nodeStates_[node->GetID()];
  1179. nodeState.connection_ = this;
  1180. nodeState.sceneState_ = &sceneState_;
  1181. nodeState.node_ = node;
  1182. node->AddReplicationState(&nodeState);
  1183. // Write node's attributes
  1184. node->WriteInitialDeltaUpdate(msg_, timeStamp_);
  1185. // Write node's user variables
  1186. const VariantMap& vars = node->GetVars();
  1187. msg_.WriteVLE(vars.Size());
  1188. for (VariantMap::ConstIterator i = vars.Begin(); i != vars.End(); ++i)
  1189. {
  1190. msg_.WriteStringHash(i->first_);
  1191. msg_.WriteVariant(i->second_);
  1192. }
  1193. // Write node's components
  1194. msg_.WriteVLE(node->GetNumNetworkComponents());
  1195. URHO3D_LOGINFOF("Sending MSG_CREATE [%d] node with %d network components", node->GetID(), node->GetNumNetworkComponents());
  1196. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  1197. for (unsigned i = 0; i < components.Size(); ++i)
  1198. {
  1199. Component* component = components[i];
  1200. // Check if component is not to be replicated
  1201. if (!component->IsReplicated())
  1202. continue;
  1203. ComponentReplicationState& componentState = nodeState.componentStates_[component->GetID()];
  1204. componentState.connection_ = this;
  1205. componentState.nodeState_ = &nodeState;
  1206. componentState.component_ = component;
  1207. component->AddReplicationState(&componentState);
  1208. msg_.WriteStringHash(component->GetType());
  1209. msg_.WriteNetID(component->GetID());
  1210. component->WriteInitialDeltaUpdate(msg_, timeStamp_);
  1211. }
  1212. URHO3D_LOGINFOF("MSG_CREATENODE sending with size %d", msg_.GetSize());
  1213. SendMessage(MSG_CREATENODE, true, true, msg_);
  1214. // auto test = MemoryBuffer(msg_.GetData(), msg_.GetSize());
  1215. // ProcessSceneUpdate(MSG_CREATENODE, test);
  1216. nodeState.markedDirty_ = false;
  1217. sceneState_.dirtyNodes_.Erase(node->GetID());
  1218. }
  1219. void Connection::ProcessExistingNode(Node* node, NodeReplicationState& nodeState)
  1220. {
  1221. // Process depended upon nodes first, if they are dirty
  1222. const PODVector<Node*>& dependencyNodes = node->GetDependencyNodes();
  1223. for (PODVector<Node*>::ConstIterator i = dependencyNodes.Begin(); i != dependencyNodes.End(); ++i)
  1224. {
  1225. unsigned nodeID = (*i)->GetID();
  1226. if (sceneState_.dirtyNodes_.Contains(nodeID))
  1227. ProcessNode(nodeID);
  1228. }
  1229. // Check from the interest management component, if exists, whether should update
  1230. /// \todo Searching for the component is a potential CPU hotspot. It should be cached
  1231. auto* priority = node->GetComponent<NetworkPriority>();
  1232. if (priority && (!priority->GetAlwaysUpdateOwner() || node->GetOwner() != this))
  1233. {
  1234. float distance = (node->GetWorldPosition() - position_).Length();
  1235. if (!priority->CheckUpdate(distance, nodeState.priorityAcc_))
  1236. return;
  1237. }
  1238. // Check if attributes have changed
  1239. if (nodeState.dirtyAttributes_.Count() || nodeState.dirtyVars_.Size())
  1240. {
  1241. const Vector<AttributeInfo>* attributes = node->GetNetworkAttributes();
  1242. unsigned numAttributes = attributes->Size();
  1243. bool hasLatestData = false;
  1244. for (unsigned i = 0; i < numAttributes; ++i)
  1245. {
  1246. if (nodeState.dirtyAttributes_.IsSet(i) && (attributes->At(i).mode_ & AM_LATESTDATA))
  1247. {
  1248. hasLatestData = true;
  1249. nodeState.dirtyAttributes_.Clear(i);
  1250. }
  1251. }
  1252. // Send latestdata message if necessary
  1253. if (hasLatestData)
  1254. {
  1255. msg_.Clear();
  1256. msg_.WriteNetID(node->GetID());
  1257. node->WriteLatestDataUpdate(msg_, timeStamp_);
  1258. SendMessage(MSG_NODELATESTDATA, true, false, msg_, node->GetID());
  1259. }
  1260. // Send deltaupdate if remaining dirty bits, or vars have changed
  1261. if (nodeState.dirtyAttributes_.Count() || nodeState.dirtyVars_.Size())
  1262. {
  1263. msg_.Clear();
  1264. msg_.WriteNetID(node->GetID());
  1265. node->WriteDeltaUpdate(msg_, nodeState.dirtyAttributes_, timeStamp_);
  1266. // Write changed variables
  1267. msg_.WriteVLE(nodeState.dirtyVars_.Size());
  1268. const VariantMap& vars = node->GetVars();
  1269. for (HashSet<StringHash>::ConstIterator i = nodeState.dirtyVars_.Begin(); i != nodeState.dirtyVars_.End(); ++i)
  1270. {
  1271. VariantMap::ConstIterator j = vars.Find(*i);
  1272. if (j != vars.End())
  1273. {
  1274. msg_.WriteStringHash(j->first_);
  1275. msg_.WriteVariant(j->second_);
  1276. }
  1277. else
  1278. {
  1279. // Variable has been marked dirty, but is removed (which is unsupported): send a dummy variable in place
  1280. URHO3D_LOGWARNING("Sending dummy user variable as original value was removed");
  1281. msg_.WriteStringHash(StringHash());
  1282. msg_.WriteVariant(Variant::EMPTY);
  1283. }
  1284. }
  1285. SendMessage(MSG_NODEDELTAUPDATE, true, true, msg_);
  1286. nodeState.dirtyAttributes_.ClearAll();
  1287. nodeState.dirtyVars_.Clear();
  1288. }
  1289. }
  1290. // Check for removed or changed components
  1291. for (HashMap<unsigned, ComponentReplicationState>::Iterator i = nodeState.componentStates_.Begin();
  1292. i != nodeState.componentStates_.End();)
  1293. {
  1294. HashMap<unsigned, ComponentReplicationState>::Iterator current = i++;
  1295. ComponentReplicationState& componentState = current->second_;
  1296. Component* component = componentState.component_;
  1297. if (!component)
  1298. {
  1299. // Removed component
  1300. msg_.Clear();
  1301. msg_.WriteNetID(current->first_);
  1302. SendMessage(MSG_REMOVECOMPONENT, true, true, msg_);
  1303. nodeState.componentStates_.Erase(current);
  1304. }
  1305. else
  1306. {
  1307. // Existing component. Check if attributes have changed
  1308. if (componentState.dirtyAttributes_.Count())
  1309. {
  1310. const Vector<AttributeInfo>* attributes = component->GetNetworkAttributes();
  1311. unsigned numAttributes = attributes->Size();
  1312. bool hasLatestData = false;
  1313. for (unsigned i = 0; i < numAttributes; ++i)
  1314. {
  1315. if (componentState.dirtyAttributes_.IsSet(i) && (attributes->At(i).mode_ & AM_LATESTDATA))
  1316. {
  1317. hasLatestData = true;
  1318. componentState.dirtyAttributes_.Clear(i);
  1319. }
  1320. }
  1321. // Send latestdata message if necessary
  1322. if (hasLatestData)
  1323. {
  1324. msg_.Clear();
  1325. msg_.WriteNetID(component->GetID());
  1326. component->WriteLatestDataUpdate(msg_, timeStamp_);
  1327. SendMessage(MSG_COMPONENTLATESTDATA, true, false, msg_, component->GetID());
  1328. }
  1329. // Send deltaupdate if remaining dirty bits
  1330. if (componentState.dirtyAttributes_.Count())
  1331. {
  1332. msg_.Clear();
  1333. msg_.WriteNetID(component->GetID());
  1334. component->WriteDeltaUpdate(msg_, componentState.dirtyAttributes_, timeStamp_);
  1335. SendMessage(MSG_COMPONENTDELTAUPDATE, true, true, msg_);
  1336. componentState.dirtyAttributes_.ClearAll();
  1337. }
  1338. }
  1339. }
  1340. }
  1341. // Check for new components
  1342. if (nodeState.componentStates_.Size() != node->GetNumNetworkComponents())
  1343. {
  1344. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  1345. for (unsigned i = 0; i < components.Size(); ++i)
  1346. {
  1347. Component* component = components[i];
  1348. // Check if component is not to be replicated
  1349. if (!component->IsReplicated())
  1350. continue;
  1351. HashMap<unsigned, ComponentReplicationState>::Iterator j = nodeState.componentStates_.Find(component->GetID());
  1352. if (j == nodeState.componentStates_.End())
  1353. {
  1354. // New component
  1355. ComponentReplicationState& componentState = nodeState.componentStates_[component->GetID()];
  1356. componentState.connection_ = this;
  1357. componentState.nodeState_ = &nodeState;
  1358. componentState.component_ = component;
  1359. component->AddReplicationState(&componentState);
  1360. msg_.Clear();
  1361. msg_.WriteNetID(node->GetID());
  1362. msg_.WriteStringHash(component->GetType());
  1363. msg_.WriteNetID(component->GetID());
  1364. component->WriteInitialDeltaUpdate(msg_, timeStamp_);
  1365. SendMessage(MSG_CREATECOMPONENT, true, true, msg_);
  1366. }
  1367. }
  1368. }
  1369. nodeState.markedDirty_ = false;
  1370. sceneState_.dirtyNodes_.Erase(node->GetID());
  1371. }
  1372. bool Connection::RequestNeededPackages(unsigned numPackages, MemoryBuffer& msg)
  1373. {
  1374. auto* cache = GetSubsystem<ResourceCache>();
  1375. const String& packageCacheDir = GetSubsystem<Network>()->GetPackageCacheDir();
  1376. Vector<SharedPtr<PackageFile> > packages = cache->GetPackageFiles();
  1377. Vector<String> downloadedPackages;
  1378. bool packagesScanned = false;
  1379. for (unsigned i = 0; i < numPackages; ++i)
  1380. {
  1381. String name = msg.ReadString();
  1382. unsigned fileSize = msg.ReadUInt();
  1383. unsigned checksum = msg.ReadUInt();
  1384. String checksumString = ToStringHex(checksum);
  1385. bool found = false;
  1386. // Check first the resource cache
  1387. for (unsigned j = 0; j < packages.Size(); ++j)
  1388. {
  1389. PackageFile* package = packages[j];
  1390. if (!GetFileNameAndExtension(package->GetName()).Compare(name, false) && package->GetTotalSize() == fileSize &&
  1391. package->GetChecksum() == checksum)
  1392. {
  1393. found = true;
  1394. break;
  1395. }
  1396. }
  1397. if (found)
  1398. continue;
  1399. if (!packagesScanned)
  1400. {
  1401. if (packageCacheDir.Empty())
  1402. {
  1403. URHO3D_LOGERROR("Can not check/download required packages, as package cache directory is not set");
  1404. return false;
  1405. }
  1406. GetSubsystem<FileSystem>()->ScanDir(downloadedPackages, packageCacheDir, "*.*", SCAN_FILES, false);
  1407. packagesScanned = true;
  1408. }
  1409. // Then the download cache
  1410. for (unsigned j = 0; j < downloadedPackages.Size(); ++j)
  1411. {
  1412. const String& fileName = downloadedPackages[j];
  1413. // In download cache, package file name format is checksum_packagename
  1414. if (!fileName.Find(checksumString) && !fileName.Substring(9).Compare(name, false))
  1415. {
  1416. // Name matches. Check file size and actual checksum to be sure
  1417. SharedPtr<PackageFile> newPackage(new PackageFile(context_, packageCacheDir + fileName));
  1418. if (newPackage->GetTotalSize() == fileSize && newPackage->GetChecksum() == checksum)
  1419. {
  1420. // Add the package to the resource system now, as we will need it to load the scene
  1421. cache->AddPackageFile(newPackage, 0);
  1422. found = true;
  1423. break;
  1424. }
  1425. }
  1426. }
  1427. // Package not found, need to request a download
  1428. if (!found)
  1429. RequestPackage(name, fileSize, checksum);
  1430. }
  1431. return true;
  1432. }
  1433. void Connection::RequestPackage(const String& name, unsigned fileSize, unsigned checksum)
  1434. {
  1435. StringHash nameHash(name);
  1436. if (downloads_.Contains(nameHash))
  1437. return; // Download already exists
  1438. PackageDownload& download = downloads_[nameHash];
  1439. download.name_ = name;
  1440. download.totalFragments_ = (fileSize + PACKAGE_FRAGMENT_SIZE - 1) / PACKAGE_FRAGMENT_SIZE;
  1441. download.checksum_ = checksum;
  1442. // Start download now only if no existing downloads, else wait for the existing ones to finish
  1443. if (downloads_.Size() == 1)
  1444. {
  1445. URHO3D_LOGINFO("Requesting package " + name + " from server");
  1446. msg_.Clear();
  1447. msg_.WriteString(name);
  1448. SendMessage(MSG_REQUESTPACKAGE, true, true, msg_);
  1449. download.initiated_ = true;
  1450. }
  1451. }
  1452. void Connection::SendPackageError(const String& name)
  1453. {
  1454. msg_.Clear();
  1455. msg_.WriteStringHash(name);
  1456. SendMessage(MSG_PACKAGEDATA, true, false, msg_);
  1457. }
  1458. void Connection::OnSceneLoadFailed()
  1459. {
  1460. sceneLoaded_ = false;
  1461. using namespace NetworkSceneLoadFailed;
  1462. URHO3D_LOGERRORF("Failed to load scene");
  1463. VariantMap& eventData = GetEventDataMap();
  1464. eventData[P_CONNECTION] = this;
  1465. SendEvent(E_NETWORKSCENELOADFAILED, eventData);
  1466. }
  1467. void Connection::OnPackageDownloadFailed(const String& name)
  1468. {
  1469. URHO3D_LOGERROR("Download of package " + name + " failed");
  1470. // As one package failed, we can not join the scene in any case. Clear the downloads
  1471. downloads_.Clear();
  1472. OnSceneLoadFailed();
  1473. }
  1474. void Connection::OnPackagesReady()
  1475. {
  1476. if (!scene_)
  1477. return;
  1478. // If sceneLoaded_ is true, we may have received additional package downloads while already joined in a scene.
  1479. // In that case the scene should not be loaded.
  1480. if (sceneLoaded_)
  1481. return;
  1482. if (sceneFileName_.Empty())
  1483. {
  1484. // If the scene filename is empty, just clear the scene of all existing replicated content, and send the loaded reply
  1485. scene_->Clear(true, false);
  1486. sceneLoaded_ = true;
  1487. msg_.Clear();
  1488. msg_.WriteUInt(scene_->GetChecksum());
  1489. SendMessage(MSG_SCENELOADED, true, true, msg_);
  1490. }
  1491. else
  1492. {
  1493. // Otherwise start the async loading process
  1494. String extension = GetExtension(sceneFileName_);
  1495. SharedPtr<File> file = GetSubsystem<ResourceCache>()->GetFile(sceneFileName_);
  1496. bool success;
  1497. if (extension == ".xml")
  1498. success = scene_->LoadAsyncXML(file);
  1499. else
  1500. success = scene_->LoadAsync(file);
  1501. if (!success)
  1502. OnSceneLoadFailed();
  1503. }
  1504. }
  1505. void Connection::ProcessPackageInfo(int msgID, MemoryBuffer& msg)
  1506. {
  1507. if (!scene_)
  1508. return;
  1509. if (IsClient())
  1510. {
  1511. URHO3D_LOGWARNING("Received unexpected packages info message from client");
  1512. return;
  1513. }
  1514. RequestNeededPackages(1, msg);
  1515. }
  1516. void Connection::ProcessUnknownMessage(int msgID, MemoryBuffer& msg)
  1517. {
  1518. // If message was not handled internally, forward as an event
  1519. using namespace NetworkMessage;
  1520. VariantMap& eventData = GetEventDataMap();
  1521. eventData[P_CONNECTION] = this;
  1522. eventData[P_MESSAGEID] = (int)msgID;
  1523. eventData[P_DATA].SetBuffer(msg.GetData(), msg.GetSize());
  1524. SendEvent(E_NETWORKMESSAGE, eventData);
  1525. }
  1526. String Connection::GetAddress() const {
  1527. #ifndef __EMSCRIPTEN__
  1528. return String(address_->ToString(false /*write port*/));
  1529. #else
  1530. return String::EMPTY;
  1531. #endif
  1532. }
  1533. void Connection::SetAddressOrGUID(const SLNet::AddressOrGUID& addr)
  1534. {
  1535. #ifndef __EMSCRIPTEN__
  1536. delete address_;
  1537. address_ = nullptr;
  1538. address_ = new SLNet::AddressOrGUID(addr);
  1539. #endif
  1540. }
  1541. }