Connection.cpp 52 KB

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