Connection.cpp 52 KB

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