2
0

Connection.cpp 52 KB

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