Connection.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777
  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. unsigned nodeID = msg.ReadNetID();
  588. // In case of the root node (scene), it should already exist. Do not create in that case
  589. Node* node = scene_->GetNode(nodeID);
  590. if (!node)
  591. {
  592. // Add initially to the root level. May be moved as we receive the parent attribute
  593. node = scene_->CreateChild(nodeID, REPLICATED);
  594. // Create smoothed transform component
  595. node->CreateComponent<SmoothedTransform>(LOCAL);
  596. }
  597. // Read initial attributes, then snap the motion smoothing immediately to the end
  598. node->ReadDeltaUpdate(msg);
  599. auto* transform = node->GetComponent<SmoothedTransform>();
  600. if (transform)
  601. transform->Update(1.0f, 0.0f);
  602. // Read initial user variables
  603. unsigned numVars = msg.ReadVLE();
  604. while (numVars)
  605. {
  606. StringHash key = msg.ReadStringHash();
  607. node->SetVar(key, msg.ReadVariant());
  608. --numVars;
  609. }
  610. // Read components
  611. unsigned numComponents = msg.ReadVLE();
  612. while (numComponents)
  613. {
  614. --numComponents;
  615. StringHash type = msg.ReadStringHash();
  616. unsigned componentID = msg.ReadNetID();
  617. // Check if the component by this ID and type already exists in this node
  618. Component* component = scene_->GetComponent(componentID);
  619. if (!component || component->GetType() != type || component->GetNode() != node)
  620. {
  621. if (component)
  622. component->Remove();
  623. component = node->CreateComponent(type, REPLICATED, componentID);
  624. }
  625. // If was unable to create the component, would desync the message and therefore have to abort
  626. if (!component)
  627. {
  628. URHO3D_LOGERROR("CreateNode message parsing aborted due to unknown component");
  629. return;
  630. }
  631. // Read initial attributes and apply
  632. component->ReadDeltaUpdate(msg);
  633. component->ApplyAttributes();
  634. }
  635. }
  636. break;
  637. case MSG_NODEDELTAUPDATE:
  638. {
  639. unsigned nodeID = msg.ReadNetID();
  640. Node* node = scene_->GetNode(nodeID);
  641. if (node)
  642. {
  643. node->ReadDeltaUpdate(msg);
  644. // ApplyAttributes() is deliberately skipped, as Node has no attributes that require late applying.
  645. // Furthermore it would propagate to components and child nodes, which is not desired in this case
  646. unsigned changedVars = msg.ReadVLE();
  647. while (changedVars)
  648. {
  649. StringHash key = msg.ReadStringHash();
  650. node->SetVar(key, msg.ReadVariant());
  651. --changedVars;
  652. }
  653. }
  654. else
  655. URHO3D_LOGWARNING("NodeDeltaUpdate message received for missing node " + String(nodeID));
  656. }
  657. break;
  658. case MSG_NODELATESTDATA:
  659. {
  660. unsigned nodeID = msg.ReadNetID();
  661. Node* node = scene_->GetNode(nodeID);
  662. if (node)
  663. {
  664. node->ReadLatestDataUpdate(msg);
  665. // ApplyAttributes() is deliberately skipped, as Node has no attributes that require late applying.
  666. // Furthermore it would propagate to components and child nodes, which is not desired in this case
  667. }
  668. else
  669. {
  670. // Latest data messages may be received out-of-order relative to node creation, so cache if necessary
  671. PODVector<unsigned char>& data = nodeLatestData_[nodeID];
  672. data.Resize(msg.GetSize());
  673. memcpy(&data[0], msg.GetData(), msg.GetSize());
  674. }
  675. }
  676. break;
  677. case MSG_REMOVENODE:
  678. {
  679. unsigned nodeID = msg.ReadNetID();
  680. Node* node = scene_->GetNode(nodeID);
  681. if (node)
  682. node->Remove();
  683. nodeLatestData_.Erase(nodeID);
  684. }
  685. break;
  686. case MSG_CREATECOMPONENT:
  687. {
  688. unsigned nodeID = msg.ReadNetID();
  689. Node* node = scene_->GetNode(nodeID);
  690. if (node)
  691. {
  692. StringHash type = msg.ReadStringHash();
  693. unsigned componentID = msg.ReadNetID();
  694. // Check if the component by this ID and type already exists in this node
  695. Component* component = scene_->GetComponent(componentID);
  696. if (!component || component->GetType() != type || component->GetNode() != node)
  697. {
  698. if (component)
  699. component->Remove();
  700. component = node->CreateComponent(type, REPLICATED, componentID);
  701. }
  702. // If was unable to create the component, would desync the message and therefore have to abort
  703. if (!component)
  704. {
  705. URHO3D_LOGERROR("CreateComponent message parsing aborted due to unknown component");
  706. return;
  707. }
  708. // Read initial attributes and apply
  709. component->ReadDeltaUpdate(msg);
  710. component->ApplyAttributes();
  711. }
  712. else
  713. URHO3D_LOGWARNING("CreateComponent message received for missing node " + String(nodeID));
  714. }
  715. break;
  716. case MSG_COMPONENTDELTAUPDATE:
  717. {
  718. unsigned componentID = msg.ReadNetID();
  719. Component* component = scene_->GetComponent(componentID);
  720. if (component)
  721. {
  722. component->ReadDeltaUpdate(msg);
  723. component->ApplyAttributes();
  724. }
  725. else
  726. URHO3D_LOGWARNING("ComponentDeltaUpdate message received for missing component " + String(componentID));
  727. }
  728. break;
  729. case MSG_COMPONENTLATESTDATA:
  730. {
  731. unsigned componentID = msg.ReadNetID();
  732. Component* component = scene_->GetComponent(componentID);
  733. if (component)
  734. {
  735. if (component->ReadLatestDataUpdate(msg))
  736. component->ApplyAttributes();
  737. }
  738. else
  739. {
  740. // Latest data messages may be received out-of-order relative to component creation, so cache if necessary
  741. PODVector<unsigned char>& data = componentLatestData_[componentID];
  742. data.Resize(msg.GetSize());
  743. memcpy(&data[0], msg.GetData(), msg.GetSize());
  744. }
  745. }
  746. break;
  747. case MSG_REMOVECOMPONENT:
  748. {
  749. unsigned componentID = msg.ReadNetID();
  750. Component* component = scene_->GetComponent(componentID);
  751. if (component)
  752. component->Remove();
  753. componentLatestData_.Erase(componentID);
  754. }
  755. break;
  756. default: break;
  757. }
  758. }
  759. void Connection::ProcessPackageDownload(int msgID, MemoryBuffer& msg)
  760. {
  761. switch (msgID)
  762. {
  763. case MSG_REQUESTPACKAGE:
  764. if (!IsClient())
  765. {
  766. URHO3D_LOGWARNING("Received unexpected RequestPackage message from server");
  767. return;
  768. }
  769. else
  770. {
  771. String name = msg.ReadString();
  772. if (!scene_)
  773. {
  774. URHO3D_LOGWARNING("Received a RequestPackage message without an assigned scene from client " + ToString());
  775. return;
  776. }
  777. // The package must be one of those required by the scene
  778. const Vector<SharedPtr<PackageFile> >& packages = scene_->GetRequiredPackageFiles();
  779. for (unsigned i = 0; i < packages.Size(); ++i)
  780. {
  781. PackageFile* package = packages[i];
  782. const String& packageFullName = package->GetName();
  783. if (!GetFileNameAndExtension(packageFullName).Compare(name, false))
  784. {
  785. StringHash nameHash(name);
  786. // Do not restart upload if already exists
  787. if (uploads_.Contains(nameHash))
  788. {
  789. URHO3D_LOGWARNING("Received a request for package " + name + " already in transfer");
  790. return;
  791. }
  792. // Try to open the file now
  793. SharedPtr<File> file(new File(context_, packageFullName));
  794. if (!file->IsOpen())
  795. {
  796. URHO3D_LOGERROR("Failed to transmit package file " + name);
  797. SendPackageError(name);
  798. return;
  799. }
  800. URHO3D_LOGINFO("Transmitting package file " + name + " to client " + ToString());
  801. uploads_[nameHash].file_ = file;
  802. uploads_[nameHash].fragment_ = 0;
  803. uploads_[nameHash].totalFragments_ = (file->GetSize() + PACKAGE_FRAGMENT_SIZE - 1) / PACKAGE_FRAGMENT_SIZE;
  804. return;
  805. }
  806. }
  807. URHO3D_LOGERROR("Client requested an unexpected package file " + name);
  808. // Send the name hash only to indicate a failed download
  809. SendPackageError(name);
  810. return;
  811. }
  812. break;
  813. case MSG_PACKAGEDATA:
  814. if (IsClient())
  815. {
  816. URHO3D_LOGWARNING("Received unexpected PackageData message from client");
  817. return;
  818. }
  819. else
  820. {
  821. StringHash nameHash = msg.ReadStringHash();
  822. HashMap<StringHash, PackageDownload>::Iterator i = downloads_.Find(nameHash);
  823. // In case of being unable to create the package file into the cache, we will still receive all data from the server.
  824. // Simply disregard it
  825. if (i == downloads_.End())
  826. return;
  827. PackageDownload& download = i->second_;
  828. // If no further data, this is an error reply
  829. if (msg.IsEof())
  830. {
  831. OnPackageDownloadFailed(download.name_);
  832. return;
  833. }
  834. // If file has not yet been opened, try to open now. Prepend the checksum to the filename to allow multiple versions
  835. if (!download.file_)
  836. {
  837. download.file_ = new File(context_,
  838. GetSubsystem<Network>()->GetPackageCacheDir() + ToStringHex(download.checksum_) + "_" + download.name_,
  839. FILE_WRITE);
  840. if (!download.file_->IsOpen())
  841. {
  842. OnPackageDownloadFailed(download.name_);
  843. return;
  844. }
  845. }
  846. // Write the fragment data to the proper index
  847. unsigned char buffer[PACKAGE_FRAGMENT_SIZE];
  848. unsigned index = msg.ReadUInt();
  849. unsigned fragmentSize = msg.GetSize() - msg.GetPosition();
  850. msg.Read(buffer, fragmentSize);
  851. download.file_->Seek(index * PACKAGE_FRAGMENT_SIZE);
  852. download.file_->Write(buffer, fragmentSize);
  853. download.receivedFragments_.Insert(index);
  854. // Check if all fragments received
  855. if (download.receivedFragments_.Size() == download.totalFragments_)
  856. {
  857. URHO3D_LOGINFO("Package " + download.name_ + " downloaded successfully");
  858. // Instantiate the package and add to the resource system, as we will need it to load the scene
  859. download.file_->Close();
  860. GetSubsystem<ResourceCache>()->AddPackageFile(download.file_->GetName(), 0);
  861. // Then start the next download if there are more
  862. downloads_.Erase(i);
  863. if (downloads_.Empty())
  864. OnPackagesReady();
  865. else
  866. {
  867. PackageDownload& nextDownload = downloads_.Begin()->second_;
  868. URHO3D_LOGINFO("Requesting package " + nextDownload.name_ + " from server");
  869. msg_.Clear();
  870. msg_.WriteString(nextDownload.name_);
  871. SendMessage(MSG_REQUESTPACKAGE, true, true, msg_);
  872. nextDownload.initiated_ = true;
  873. }
  874. }
  875. }
  876. break;
  877. default: break;
  878. }
  879. }
  880. void Connection::ProcessIdentity(int msgID, MemoryBuffer& msg)
  881. {
  882. if (!IsClient())
  883. {
  884. URHO3D_LOGWARNING("Received unexpected Identity message from server");
  885. return;
  886. }
  887. identity_ = msg.ReadVariantMap();
  888. using namespace ClientIdentity;
  889. VariantMap eventData = identity_;
  890. eventData[P_CONNECTION] = this;
  891. eventData[P_ALLOW] = true;
  892. SendEvent(E_CLIENTIDENTITY, eventData);
  893. // If connection was denied as a response to the identity event, disconnect now
  894. if (!eventData[P_ALLOW].GetBool())
  895. Disconnect();
  896. }
  897. void Connection::ProcessControls(int msgID, MemoryBuffer& msg)
  898. {
  899. if (!IsClient())
  900. {
  901. URHO3D_LOGWARNING("Received unexpected Controls message from server");
  902. return;
  903. }
  904. Controls newControls;
  905. newControls.buttons_ = msg.ReadUInt();
  906. newControls.yaw_ = msg.ReadFloat();
  907. newControls.pitch_ = msg.ReadFloat();
  908. newControls.extraData_ = msg.ReadVariantMap();
  909. SetControls(newControls);
  910. timeStamp_ = msg.ReadUByte();
  911. // Client may or may not send observer position & rotation for interest management
  912. if (!msg.IsEof())
  913. position_ = msg.ReadVector3();
  914. if (!msg.IsEof())
  915. rotation_ = msg.ReadPackedQuaternion();
  916. }
  917. void Connection::ProcessSceneLoaded(int msgID, MemoryBuffer& msg)
  918. {
  919. if (!IsClient())
  920. {
  921. URHO3D_LOGWARNING("Received unexpected SceneLoaded message from server");
  922. return;
  923. }
  924. if (!scene_)
  925. {
  926. URHO3D_LOGWARNING("Received a SceneLoaded message without an assigned scene from client " + ToString());
  927. return;
  928. }
  929. unsigned checksum = msg.ReadUInt();
  930. if (checksum != scene_->GetChecksum())
  931. {
  932. URHO3D_LOGINFO("Scene checksum error from client " + ToString());
  933. msg_.Clear();
  934. SendMessage(MSG_SCENECHECKSUMERROR, true, true, msg_);
  935. OnSceneLoadFailed();
  936. }
  937. else
  938. {
  939. sceneLoaded_ = true;
  940. using namespace ClientSceneLoaded;
  941. VariantMap& eventData = GetEventDataMap();
  942. eventData[P_CONNECTION] = this;
  943. SendEvent(E_CLIENTSCENELOADED, eventData);
  944. }
  945. }
  946. void Connection::ProcessRemoteEvent(int msgID, MemoryBuffer& msg)
  947. {
  948. using namespace RemoteEventData;
  949. if (msgID == MSG_REMOTEEVENT)
  950. {
  951. StringHash eventType = msg.ReadStringHash();
  952. if (!GetSubsystem<Network>()->CheckRemoteEvent(eventType))
  953. {
  954. URHO3D_LOGWARNING("Discarding not allowed remote event " + eventType.ToString());
  955. return;
  956. }
  957. VariantMap eventData = msg.ReadVariantMap();
  958. eventData[P_CONNECTION] = this;
  959. SendEvent(eventType, eventData);
  960. }
  961. else
  962. {
  963. if (!scene_)
  964. {
  965. URHO3D_LOGERROR("Can not receive remote node event without an assigned scene");
  966. return;
  967. }
  968. unsigned nodeID = msg.ReadNetID();
  969. StringHash eventType = msg.ReadStringHash();
  970. if (!GetSubsystem<Network>()->CheckRemoteEvent(eventType))
  971. {
  972. URHO3D_LOGWARNING("Discarding not allowed remote event " + eventType.ToString());
  973. return;
  974. }
  975. VariantMap eventData = msg.ReadVariantMap();
  976. Node* sender = scene_->GetNode(nodeID);
  977. if (!sender)
  978. {
  979. URHO3D_LOGWARNING("Missing sender for remote node event, discarding");
  980. return;
  981. }
  982. eventData[P_CONNECTION] = this;
  983. sender->SendEvent(eventType, eventData);
  984. }
  985. }
  986. Scene* Connection::GetScene() const
  987. {
  988. return scene_;
  989. }
  990. bool Connection::IsConnected() const
  991. {
  992. #ifndef __EMSCRIPTEN__
  993. return peer_ && peer_->IsActive();
  994. #else
  995. if (ws_.GetWS())
  996. return true;
  997. #endif
  998. }
  999. float Connection::GetRoundTripTime() const
  1000. {
  1001. #ifndef __EMSCRIPTEN__
  1002. if (peer_)
  1003. {
  1004. SLNet::RakNetStatistics stats{};
  1005. if (peer_->GetStatistics(address_->systemAddress, &stats))
  1006. return (float)peer_->GetAveragePing(*address_);
  1007. }
  1008. #endif
  1009. return 0.0f;
  1010. }
  1011. unsigned Connection::GetLastHeardTime() const
  1012. {
  1013. return const_cast<Timer&>(lastHeardTimer_).GetMSec(false);
  1014. }
  1015. float Connection::GetBytesInPerSec() const
  1016. {
  1017. #ifndef __EMSCRIPTEN__
  1018. if (peer_)
  1019. {
  1020. SLNet::RakNetStatistics stats{};
  1021. if (peer_->GetStatistics(address_->systemAddress, &stats))
  1022. return (float)stats.valueOverLastSecond[SLNet::ACTUAL_BYTES_RECEIVED];
  1023. }
  1024. #endif
  1025. return 0.0f;
  1026. }
  1027. float Connection::GetBytesOutPerSec() const
  1028. {
  1029. #ifndef __EMSCRIPTEN__
  1030. if (peer_)
  1031. {
  1032. SLNet::RakNetStatistics stats{};
  1033. if (peer_->GetStatistics(address_->systemAddress, &stats))
  1034. return (float)stats.valueOverLastSecond[SLNet::ACTUAL_BYTES_SENT];
  1035. }
  1036. #endif
  1037. return 0.0f;
  1038. }
  1039. int Connection::GetPacketsInPerSec() const
  1040. {
  1041. return packetCounter_.x_;
  1042. }
  1043. int Connection::GetPacketsOutPerSec() const
  1044. {
  1045. return packetCounter_.y_;
  1046. }
  1047. String Connection::ToString() const
  1048. {
  1049. if (peer_)
  1050. return GetAddress() + ":" + String(GetPort());
  1051. #ifdef URHO3D_WEBSOCKETS
  1052. if (ws_.GetWS())
  1053. return "WS connection";
  1054. #endif
  1055. return String::EMPTY;
  1056. }
  1057. unsigned Connection::GetNumDownloads() const
  1058. {
  1059. return downloads_.Size();
  1060. }
  1061. const String& Connection::GetDownloadName() const
  1062. {
  1063. for (HashMap<StringHash, PackageDownload>::ConstIterator i = downloads_.Begin(); i != downloads_.End(); ++i)
  1064. {
  1065. if (i->second_.initiated_)
  1066. return i->second_.name_;
  1067. }
  1068. return String::EMPTY;
  1069. }
  1070. float Connection::GetDownloadProgress() const
  1071. {
  1072. for (HashMap<StringHash, PackageDownload>::ConstIterator i = downloads_.Begin(); i != downloads_.End(); ++i)
  1073. {
  1074. if (i->second_.initiated_)
  1075. return (float)i->second_.receivedFragments_.Size() / (float)i->second_.totalFragments_;
  1076. }
  1077. return 1.0f;
  1078. }
  1079. void Connection::SendPackageToClient(PackageFile* package)
  1080. {
  1081. if (!scene_)
  1082. return;
  1083. if (!IsClient())
  1084. {
  1085. URHO3D_LOGERROR("SendPackageToClient can be called on the server only");
  1086. return;
  1087. }
  1088. if (!package)
  1089. {
  1090. URHO3D_LOGERROR("Null package specified for SendPackageToClient");
  1091. return;
  1092. }
  1093. msg_.Clear();
  1094. String filename = GetFileNameAndExtension(package->GetName());
  1095. msg_.WriteString(filename);
  1096. msg_.WriteUInt(package->GetTotalSize());
  1097. msg_.WriteUInt(package->GetChecksum());
  1098. SendMessage(MSG_PACKAGEINFO, true, true, msg_);
  1099. }
  1100. void Connection::ConfigureNetworkSimulator(int latencyMs, float packetLoss)
  1101. {
  1102. #ifndef __EMSCRIPTEN__
  1103. if (peer_)
  1104. peer_->ApplyNetworkSimulator(packetLoss, latencyMs, 0);
  1105. #endif
  1106. }
  1107. void Connection::SetPacketSizeLimit(int limit)
  1108. {
  1109. packedMessageLimit_ = limit;
  1110. }
  1111. void Connection::HandleAsyncLoadFinished(StringHash eventType, VariantMap& eventData)
  1112. {
  1113. sceneLoaded_ = true;
  1114. // Clear all replicated nodes
  1115. scene_->Clear(true, false);
  1116. msg_.Clear();
  1117. msg_.WriteUInt(scene_->GetChecksum());
  1118. SendMessage(MSG_SCENELOADED, true, true, msg_);
  1119. }
  1120. void Connection::ProcessNode(unsigned nodeID)
  1121. {
  1122. // Check that we have not already processed this due to dependency recursion
  1123. if (!nodesToProcess_.Erase(nodeID))
  1124. return;
  1125. // Find replication state for the node
  1126. HashMap<unsigned, NodeReplicationState>::Iterator i = sceneState_.nodeStates_.Find(nodeID);
  1127. if (i != sceneState_.nodeStates_.End())
  1128. {
  1129. // Replication state found: the node is either be existing or removed
  1130. Node* node = i->second_.node_;
  1131. if (!node)
  1132. {
  1133. msg_.Clear();
  1134. msg_.WriteNetID(nodeID);
  1135. // Note: we will send MSG_REMOVENODE redundantly for each node in the hierarchy, even if removing the root node
  1136. // would be enough. However, this may be better due to the client not possibly having updated parenting
  1137. // information at the time of receiving this message
  1138. SendMessage(MSG_REMOVENODE, true, true, msg_);
  1139. sceneState_.nodeStates_.Erase(nodeID);
  1140. }
  1141. else
  1142. ProcessExistingNode(node, i->second_);
  1143. }
  1144. else
  1145. {
  1146. // Replication state not found: this is a new node
  1147. Node* node = scene_->GetNode(nodeID);
  1148. if (node)
  1149. ProcessNewNode(node);
  1150. else
  1151. {
  1152. // Did not find the new node (may have been created, then removed immediately): erase from dirty set.
  1153. sceneState_.dirtyNodes_.Erase(nodeID);
  1154. }
  1155. }
  1156. }
  1157. void Connection::ProcessNewNode(Node* node)
  1158. {
  1159. // Process depended upon nodes first, if they are dirty
  1160. const PODVector<Node*>& dependencyNodes = node->GetDependencyNodes();
  1161. for (PODVector<Node*>::ConstIterator i = dependencyNodes.Begin(); i != dependencyNodes.End(); ++i)
  1162. {
  1163. unsigned nodeID = (*i)->GetID();
  1164. if (sceneState_.dirtyNodes_.Contains(nodeID))
  1165. ProcessNode(nodeID);
  1166. }
  1167. msg_.Clear();
  1168. msg_.WriteNetID(node->GetID());
  1169. NodeReplicationState& nodeState = sceneState_.nodeStates_[node->GetID()];
  1170. nodeState.connection_ = this;
  1171. nodeState.sceneState_ = &sceneState_;
  1172. nodeState.node_ = node;
  1173. node->AddReplicationState(&nodeState);
  1174. // Write node's attributes
  1175. node->WriteInitialDeltaUpdate(msg_, timeStamp_);
  1176. // Write node's user variables
  1177. const VariantMap& vars = node->GetVars();
  1178. msg_.WriteVLE(vars.Size());
  1179. for (VariantMap::ConstIterator i = vars.Begin(); i != vars.End(); ++i)
  1180. {
  1181. msg_.WriteStringHash(i->first_);
  1182. msg_.WriteVariant(i->second_);
  1183. }
  1184. // Write node's components
  1185. msg_.WriteVLE(node->GetNumNetworkComponents());
  1186. URHO3D_LOGINFOF("Sending MSG_CREATE [%d] node with %d network components", node->GetID(), node->GetNumNetworkComponents());
  1187. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  1188. for (unsigned i = 0; i < components.Size(); ++i)
  1189. {
  1190. Component* component = components[i];
  1191. // Check if component is not to be replicated
  1192. if (!component->IsReplicated())
  1193. continue;
  1194. ComponentReplicationState& componentState = nodeState.componentStates_[component->GetID()];
  1195. componentState.connection_ = this;
  1196. componentState.nodeState_ = &nodeState;
  1197. componentState.component_ = component;
  1198. component->AddReplicationState(&componentState);
  1199. msg_.WriteStringHash(component->GetType());
  1200. msg_.WriteNetID(component->GetID());
  1201. component->WriteInitialDeltaUpdate(msg_, timeStamp_);
  1202. }
  1203. SendMessage(MSG_CREATENODE, true, true, msg_);
  1204. nodeState.markedDirty_ = false;
  1205. sceneState_.dirtyNodes_.Erase(node->GetID());
  1206. }
  1207. void Connection::ProcessExistingNode(Node* node, NodeReplicationState& nodeState)
  1208. {
  1209. // Process depended upon nodes first, if they are dirty
  1210. const PODVector<Node*>& dependencyNodes = node->GetDependencyNodes();
  1211. for (PODVector<Node*>::ConstIterator i = dependencyNodes.Begin(); i != dependencyNodes.End(); ++i)
  1212. {
  1213. unsigned nodeID = (*i)->GetID();
  1214. if (sceneState_.dirtyNodes_.Contains(nodeID))
  1215. ProcessNode(nodeID);
  1216. }
  1217. // Check from the interest management component, if exists, whether should update
  1218. /// \todo Searching for the component is a potential CPU hotspot. It should be cached
  1219. auto* priority = node->GetComponent<NetworkPriority>();
  1220. if (priority && (!priority->GetAlwaysUpdateOwner() || node->GetOwner() != this))
  1221. {
  1222. float distance = (node->GetWorldPosition() - position_).Length();
  1223. if (!priority->CheckUpdate(distance, nodeState.priorityAcc_))
  1224. return;
  1225. }
  1226. // Check if attributes have changed
  1227. if (nodeState.dirtyAttributes_.Count() || nodeState.dirtyVars_.Size())
  1228. {
  1229. const Vector<AttributeInfo>* attributes = node->GetNetworkAttributes();
  1230. unsigned numAttributes = attributes->Size();
  1231. bool hasLatestData = false;
  1232. for (unsigned i = 0; i < numAttributes; ++i)
  1233. {
  1234. if (nodeState.dirtyAttributes_.IsSet(i) && (attributes->At(i).mode_ & AM_LATESTDATA))
  1235. {
  1236. hasLatestData = true;
  1237. nodeState.dirtyAttributes_.Clear(i);
  1238. }
  1239. }
  1240. // Send latestdata message if necessary
  1241. if (hasLatestData)
  1242. {
  1243. msg_.Clear();
  1244. msg_.WriteNetID(node->GetID());
  1245. node->WriteLatestDataUpdate(msg_, timeStamp_);
  1246. SendMessage(MSG_NODELATESTDATA, true, false, msg_, node->GetID());
  1247. }
  1248. // Send deltaupdate if remaining dirty bits, or vars have changed
  1249. if (nodeState.dirtyAttributes_.Count() || nodeState.dirtyVars_.Size())
  1250. {
  1251. msg_.Clear();
  1252. msg_.WriteNetID(node->GetID());
  1253. node->WriteDeltaUpdate(msg_, nodeState.dirtyAttributes_, timeStamp_);
  1254. // Write changed variables
  1255. msg_.WriteVLE(nodeState.dirtyVars_.Size());
  1256. const VariantMap& vars = node->GetVars();
  1257. for (HashSet<StringHash>::ConstIterator i = nodeState.dirtyVars_.Begin(); i != nodeState.dirtyVars_.End(); ++i)
  1258. {
  1259. VariantMap::ConstIterator j = vars.Find(*i);
  1260. if (j != vars.End())
  1261. {
  1262. msg_.WriteStringHash(j->first_);
  1263. msg_.WriteVariant(j->second_);
  1264. }
  1265. else
  1266. {
  1267. // Variable has been marked dirty, but is removed (which is unsupported): send a dummy variable in place
  1268. URHO3D_LOGWARNING("Sending dummy user variable as original value was removed");
  1269. msg_.WriteStringHash(StringHash());
  1270. msg_.WriteVariant(Variant::EMPTY);
  1271. }
  1272. }
  1273. SendMessage(MSG_NODEDELTAUPDATE, true, true, msg_);
  1274. nodeState.dirtyAttributes_.ClearAll();
  1275. nodeState.dirtyVars_.Clear();
  1276. }
  1277. }
  1278. // Check for removed or changed components
  1279. for (HashMap<unsigned, ComponentReplicationState>::Iterator i = nodeState.componentStates_.Begin();
  1280. i != nodeState.componentStates_.End();)
  1281. {
  1282. HashMap<unsigned, ComponentReplicationState>::Iterator current = i++;
  1283. ComponentReplicationState& componentState = current->second_;
  1284. Component* component = componentState.component_;
  1285. if (!component)
  1286. {
  1287. // Removed component
  1288. msg_.Clear();
  1289. msg_.WriteNetID(current->first_);
  1290. SendMessage(MSG_REMOVECOMPONENT, true, true, msg_);
  1291. nodeState.componentStates_.Erase(current);
  1292. }
  1293. else
  1294. {
  1295. // Existing component. Check if attributes have changed
  1296. if (componentState.dirtyAttributes_.Count())
  1297. {
  1298. const Vector<AttributeInfo>* attributes = component->GetNetworkAttributes();
  1299. unsigned numAttributes = attributes->Size();
  1300. bool hasLatestData = false;
  1301. for (unsigned i = 0; i < numAttributes; ++i)
  1302. {
  1303. if (componentState.dirtyAttributes_.IsSet(i) && (attributes->At(i).mode_ & AM_LATESTDATA))
  1304. {
  1305. hasLatestData = true;
  1306. componentState.dirtyAttributes_.Clear(i);
  1307. }
  1308. }
  1309. // Send latestdata message if necessary
  1310. if (hasLatestData)
  1311. {
  1312. msg_.Clear();
  1313. msg_.WriteNetID(component->GetID());
  1314. component->WriteLatestDataUpdate(msg_, timeStamp_);
  1315. SendMessage(MSG_COMPONENTLATESTDATA, true, false, msg_, component->GetID());
  1316. }
  1317. // Send deltaupdate if remaining dirty bits
  1318. if (componentState.dirtyAttributes_.Count())
  1319. {
  1320. msg_.Clear();
  1321. msg_.WriteNetID(component->GetID());
  1322. component->WriteDeltaUpdate(msg_, componentState.dirtyAttributes_, timeStamp_);
  1323. SendMessage(MSG_COMPONENTDELTAUPDATE, true, true, msg_);
  1324. componentState.dirtyAttributes_.ClearAll();
  1325. }
  1326. }
  1327. }
  1328. }
  1329. // Check for new components
  1330. if (nodeState.componentStates_.Size() != node->GetNumNetworkComponents())
  1331. {
  1332. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  1333. for (unsigned i = 0; i < components.Size(); ++i)
  1334. {
  1335. Component* component = components[i];
  1336. // Check if component is not to be replicated
  1337. if (!component->IsReplicated())
  1338. continue;
  1339. HashMap<unsigned, ComponentReplicationState>::Iterator j = nodeState.componentStates_.Find(component->GetID());
  1340. if (j == nodeState.componentStates_.End())
  1341. {
  1342. // New component
  1343. ComponentReplicationState& componentState = nodeState.componentStates_[component->GetID()];
  1344. componentState.connection_ = this;
  1345. componentState.nodeState_ = &nodeState;
  1346. componentState.component_ = component;
  1347. component->AddReplicationState(&componentState);
  1348. msg_.Clear();
  1349. msg_.WriteNetID(node->GetID());
  1350. msg_.WriteStringHash(component->GetType());
  1351. msg_.WriteNetID(component->GetID());
  1352. component->WriteInitialDeltaUpdate(msg_, timeStamp_);
  1353. SendMessage(MSG_CREATECOMPONENT, true, true, msg_);
  1354. }
  1355. }
  1356. }
  1357. nodeState.markedDirty_ = false;
  1358. sceneState_.dirtyNodes_.Erase(node->GetID());
  1359. }
  1360. bool Connection::RequestNeededPackages(unsigned numPackages, MemoryBuffer& msg)
  1361. {
  1362. auto* cache = GetSubsystem<ResourceCache>();
  1363. const String& packageCacheDir = GetSubsystem<Network>()->GetPackageCacheDir();
  1364. Vector<SharedPtr<PackageFile> > packages = cache->GetPackageFiles();
  1365. Vector<String> downloadedPackages;
  1366. bool packagesScanned = false;
  1367. for (unsigned i = 0; i < numPackages; ++i)
  1368. {
  1369. String name = msg.ReadString();
  1370. unsigned fileSize = msg.ReadUInt();
  1371. unsigned checksum = msg.ReadUInt();
  1372. String checksumString = ToStringHex(checksum);
  1373. bool found = false;
  1374. // Check first the resource cache
  1375. for (unsigned j = 0; j < packages.Size(); ++j)
  1376. {
  1377. PackageFile* package = packages[j];
  1378. if (!GetFileNameAndExtension(package->GetName()).Compare(name, false) && package->GetTotalSize() == fileSize &&
  1379. package->GetChecksum() == checksum)
  1380. {
  1381. found = true;
  1382. break;
  1383. }
  1384. }
  1385. if (found)
  1386. continue;
  1387. if (!packagesScanned)
  1388. {
  1389. if (packageCacheDir.Empty())
  1390. {
  1391. URHO3D_LOGERROR("Can not check/download required packages, as package cache directory is not set");
  1392. return false;
  1393. }
  1394. GetSubsystem<FileSystem>()->ScanDir(downloadedPackages, packageCacheDir, "*.*", SCAN_FILES, false);
  1395. packagesScanned = true;
  1396. }
  1397. // Then the download cache
  1398. for (unsigned j = 0; j < downloadedPackages.Size(); ++j)
  1399. {
  1400. const String& fileName = downloadedPackages[j];
  1401. // In download cache, package file name format is checksum_packagename
  1402. if (!fileName.Find(checksumString) && !fileName.Substring(9).Compare(name, false))
  1403. {
  1404. // Name matches. Check file size and actual checksum to be sure
  1405. SharedPtr<PackageFile> newPackage(new PackageFile(context_, packageCacheDir + fileName));
  1406. if (newPackage->GetTotalSize() == fileSize && newPackage->GetChecksum() == checksum)
  1407. {
  1408. // Add the package to the resource system now, as we will need it to load the scene
  1409. cache->AddPackageFile(newPackage, 0);
  1410. found = true;
  1411. break;
  1412. }
  1413. }
  1414. }
  1415. // Package not found, need to request a download
  1416. if (!found)
  1417. RequestPackage(name, fileSize, checksum);
  1418. }
  1419. return true;
  1420. }
  1421. void Connection::RequestPackage(const String& name, unsigned fileSize, unsigned checksum)
  1422. {
  1423. StringHash nameHash(name);
  1424. if (downloads_.Contains(nameHash))
  1425. return; // Download already exists
  1426. PackageDownload& download = downloads_[nameHash];
  1427. download.name_ = name;
  1428. download.totalFragments_ = (fileSize + PACKAGE_FRAGMENT_SIZE - 1) / PACKAGE_FRAGMENT_SIZE;
  1429. download.checksum_ = checksum;
  1430. // Start download now only if no existing downloads, else wait for the existing ones to finish
  1431. if (downloads_.Size() == 1)
  1432. {
  1433. URHO3D_LOGINFO("Requesting package " + name + " from server");
  1434. msg_.Clear();
  1435. msg_.WriteString(name);
  1436. SendMessage(MSG_REQUESTPACKAGE, true, true, msg_);
  1437. download.initiated_ = true;
  1438. }
  1439. }
  1440. void Connection::SendPackageError(const String& name)
  1441. {
  1442. msg_.Clear();
  1443. msg_.WriteStringHash(name);
  1444. SendMessage(MSG_PACKAGEDATA, true, false, msg_);
  1445. }
  1446. void Connection::OnSceneLoadFailed()
  1447. {
  1448. sceneLoaded_ = false;
  1449. using namespace NetworkSceneLoadFailed;
  1450. URHO3D_LOGERRORF("Failed to load scene");
  1451. VariantMap& eventData = GetEventDataMap();
  1452. eventData[P_CONNECTION] = this;
  1453. SendEvent(E_NETWORKSCENELOADFAILED, eventData);
  1454. }
  1455. void Connection::OnPackageDownloadFailed(const String& name)
  1456. {
  1457. URHO3D_LOGERROR("Download of package " + name + " failed");
  1458. // As one package failed, we can not join the scene in any case. Clear the downloads
  1459. downloads_.Clear();
  1460. OnSceneLoadFailed();
  1461. }
  1462. void Connection::OnPackagesReady()
  1463. {
  1464. if (!scene_)
  1465. return;
  1466. // If sceneLoaded_ is true, we may have received additional package downloads while already joined in a scene.
  1467. // In that case the scene should not be loaded.
  1468. if (sceneLoaded_)
  1469. return;
  1470. if (sceneFileName_.Empty())
  1471. {
  1472. // If the scene filename is empty, just clear the scene of all existing replicated content, and send the loaded reply
  1473. scene_->Clear(true, false);
  1474. sceneLoaded_ = true;
  1475. msg_.Clear();
  1476. msg_.WriteUInt(scene_->GetChecksum());
  1477. SendMessage(MSG_SCENELOADED, true, true, msg_);
  1478. }
  1479. else
  1480. {
  1481. // Otherwise start the async loading process
  1482. String extension = GetExtension(sceneFileName_);
  1483. SharedPtr<File> file = GetSubsystem<ResourceCache>()->GetFile(sceneFileName_);
  1484. bool success;
  1485. if (extension == ".xml")
  1486. success = scene_->LoadAsyncXML(file);
  1487. else
  1488. success = scene_->LoadAsync(file);
  1489. if (!success)
  1490. OnSceneLoadFailed();
  1491. }
  1492. }
  1493. void Connection::ProcessPackageInfo(int msgID, MemoryBuffer& msg)
  1494. {
  1495. if (!scene_)
  1496. return;
  1497. if (IsClient())
  1498. {
  1499. URHO3D_LOGWARNING("Received unexpected packages info message from client");
  1500. return;
  1501. }
  1502. RequestNeededPackages(1, msg);
  1503. }
  1504. void Connection::ProcessUnknownMessage(int msgID, MemoryBuffer& msg)
  1505. {
  1506. // If message was not handled internally, forward as an event
  1507. using namespace NetworkMessage;
  1508. VariantMap& eventData = GetEventDataMap();
  1509. eventData[P_CONNECTION] = this;
  1510. eventData[P_MESSAGEID] = (int)msgID;
  1511. eventData[P_DATA].SetBuffer(msg.GetData(), msg.GetSize());
  1512. SendEvent(E_NETWORKMESSAGE, eventData);
  1513. }
  1514. String Connection::GetAddress() const {
  1515. #ifndef __EMSCRIPTEN__
  1516. return String(address_->ToString(false /*write port*/));
  1517. #else
  1518. return String::EMPTY;
  1519. #endif
  1520. }
  1521. void Connection::SetAddressOrGUID(const SLNet::AddressOrGUID& addr)
  1522. {
  1523. #ifndef __EMSCRIPTEN__
  1524. delete address_;
  1525. address_ = nullptr;
  1526. address_ = new SLNet::AddressOrGUID(addr);
  1527. #endif
  1528. }
  1529. }