Connection.cpp 49 KB

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