Connection.cpp 54 KB

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