Connection.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Oorni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Component.h"
  25. #include "Connection.h"
  26. #include "File.h"
  27. #include "FileSystem.h"
  28. #include "Log.h"
  29. #include "MemoryBuffer.h"
  30. #include "Network.h"
  31. #include "NetworkEvents.h"
  32. #include "NetworkPriority.h"
  33. #include "PackageFile.h"
  34. #include "Profiler.h"
  35. #include "Protocol.h"
  36. #include "ResourceCache.h"
  37. #include "Scene.h"
  38. #include "SceneEvents.h"
  39. #include "SmoothedTransform.h"
  40. #include "StringUtils.h"
  41. #include <kNet.h>
  42. #include "DebugNew.h"
  43. namespace Urho3D
  44. {
  45. static const int STATS_INTERVAL_MSEC = 2000;
  46. PackageDownload::PackageDownload() :
  47. totalFragments_(0),
  48. checksum_(0),
  49. initiated_(false)
  50. {
  51. }
  52. PackageUpload::PackageUpload()
  53. {
  54. }
  55. OBJECTTYPESTATIC(Connection);
  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. if (logStatistics_ && statsTimer_.GetMSec(false) > STATS_INTERVAL_MSEC)
  224. {
  225. statsTimer_.Reset();
  226. char statsBuffer[256];
  227. 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(),
  228. (int)connection_->PacketsOutPerSec(), connection_->BytesInPerSec() / 1000.0f, connection_->BytesOutPerSec() / 1000.0f);
  229. LOGINFO(statsBuffer);
  230. }
  231. if (remoteEvents_.Empty())
  232. return;
  233. PROFILE(SendRemoteEvents);
  234. for (Vector<RemoteEvent>::ConstIterator i = remoteEvents_.Begin(); i != remoteEvents_.End(); ++i)
  235. {
  236. msg_.Clear();
  237. if (!i->senderID_)
  238. {
  239. msg_.WriteStringHash(i->eventType_);
  240. msg_.WriteVariantMap(i->eventData_);
  241. SendMessage(MSG_REMOTEEVENT, true, i->inOrder_, msg_);
  242. }
  243. else
  244. {
  245. msg_.WriteNetID(i->senderID_);
  246. msg_.WriteStringHash(i->eventType_);
  247. msg_.WriteVariantMap(i->eventData_);
  248. SendMessage(MSG_REMOTENODEEVENT, true, i->inOrder_, msg_);
  249. }
  250. }
  251. remoteEvents_.Clear();
  252. }
  253. void Connection::SendPackages()
  254. {
  255. while (!uploads_.Empty() && connection_->NumOutboundMessagesPending() < 1000)
  256. {
  257. unsigned char buffer[PACKAGE_FRAGMENT_SIZE];
  258. for (HashMap<StringHash, PackageUpload>::Iterator i = uploads_.Begin(); i != uploads_.End();)
  259. {
  260. HashMap<StringHash, PackageUpload>::Iterator current = i++;
  261. PackageUpload& upload = current->second_;
  262. unsigned fragmentSize = Min((int)(upload.file_->GetSize() - upload.file_->GetPosition()), (int)PACKAGE_FRAGMENT_SIZE);
  263. upload.file_->Read(buffer, fragmentSize);
  264. msg_.Clear();
  265. msg_.WriteStringHash(current->first_);
  266. msg_.WriteUInt(upload.fragment_++);
  267. msg_.Write(buffer, fragmentSize);
  268. SendMessage(MSG_PACKAGEDATA, true, false, msg_);
  269. // Check if upload finished
  270. if (upload.fragment_ == upload.totalFragments_)
  271. uploads_.Erase(current);
  272. }
  273. }
  274. }
  275. void Connection::ProcessPendingLatestData()
  276. {
  277. if (!scene_ || !sceneLoaded_)
  278. return;
  279. // Iterate through pending node data and see if we can find the nodes now
  280. for (HashMap<unsigned, PODVector<unsigned char> >::Iterator i = nodeLatestData_.Begin(); i != nodeLatestData_.End();)
  281. {
  282. HashMap<unsigned, PODVector<unsigned char> >::Iterator current = i++;
  283. Node* node = scene_->GetNode(current->first_);
  284. if (node)
  285. {
  286. MemoryBuffer msg(current->second_);
  287. msg.ReadNetID(); // Skip the node ID
  288. node->ReadLatestDataUpdate(msg);
  289. // ApplyAttributes() is deliberately skipped, as Node has no attributes that require late applying.
  290. // Furthermore it would propagate to components and child nodes, which is not desired in this case
  291. nodeLatestData_.Erase(current);
  292. }
  293. }
  294. // Iterate through pending component data and see if we can find the components now
  295. for (HashMap<unsigned, PODVector<unsigned char> >::Iterator i = componentLatestData_.Begin(); i != componentLatestData_.End();)
  296. {
  297. HashMap<unsigned, PODVector<unsigned char> >::Iterator current = i++;
  298. Component* component = scene_->GetComponent(current->first_);
  299. if (component)
  300. {
  301. MemoryBuffer msg(current->second_);
  302. msg.ReadNetID(); // Skip the component ID
  303. component->ReadLatestDataUpdate(msg);
  304. component->ApplyAttributes();
  305. componentLatestData_.Erase(current);
  306. }
  307. }
  308. }
  309. void Connection::ProcessLoadScene(int msgID, MemoryBuffer& msg)
  310. {
  311. if (IsClient())
  312. {
  313. LOGWARNING("Received unexpected LoadScene message from client " + ToString());
  314. return;
  315. }
  316. if (!scene_)
  317. {
  318. LOGERROR("Can not handle LoadScene message without an assigned scene");
  319. return;
  320. }
  321. // Store the scene file name we need to eventually load
  322. sceneFileName_ = msg.ReadString();
  323. // Clear previous pending latest data and package downloads if any
  324. nodeLatestData_.Clear();
  325. componentLatestData_.Clear();
  326. downloads_.Clear();
  327. // In case we have joined other scenes in this session, remove first all downloaded package files from the resource system
  328. // to prevent resource conflicts
  329. const String& packageCacheDir = GetSubsystem<Network>()->GetPackageCacheDir();
  330. ResourceCache* cache = GetSubsystem<ResourceCache>();
  331. Vector<SharedPtr<PackageFile> > packages = cache->GetPackageFiles();
  332. for (unsigned i = 0; i < packages.Size(); ++i)
  333. {
  334. PackageFile* package = packages[i];
  335. if (!package->GetName().Find(packageCacheDir))
  336. cache->RemovePackageFile(package, true);
  337. }
  338. // Now check which packages we have in the resource cache or in the download cache, and which we need to download
  339. unsigned numPackages = msg.ReadVLE();
  340. packages = cache->GetPackageFiles(); // Refresh resource cache's package list after possible removals
  341. Vector<String> downloadedPackages;
  342. if (!packageCacheDir.Empty())
  343. GetSubsystem<FileSystem>()->ScanDir(downloadedPackages, packageCacheDir, "*.*", SCAN_FILES, false);
  344. for (unsigned i = 0; i < numPackages; ++i)
  345. {
  346. String name = msg.ReadString();
  347. unsigned fileSize = msg.ReadUInt();
  348. unsigned checksum = msg.ReadUInt();
  349. String checksumString = ToStringHex(checksum);
  350. bool found = false;
  351. // Check first the resource cache
  352. for (unsigned j = 0; j < packages.Size(); ++j)
  353. {
  354. PackageFile* package = packages[j];
  355. if (!GetFileNameAndExtension(package->GetName()).Compare(name, false) && package->GetTotalSize() == fileSize &&
  356. package->GetChecksum() == checksum)
  357. {
  358. found = true;
  359. break;
  360. }
  361. }
  362. // Then the download cache
  363. for (unsigned j = 0; j < downloadedPackages.Size(); ++j)
  364. {
  365. const String& fileName = downloadedPackages[j];
  366. if (!fileName.Find(checksumString) && !fileName.Substring(9).Compare(name, false))
  367. {
  368. // Name matches. Check filesize and actual checksum to be sure
  369. SharedPtr<PackageFile> newPackage(new PackageFile(context_, packageCacheDir + fileName));
  370. if (newPackage->GetTotalSize() == fileSize && newPackage->GetChecksum() == checksum)
  371. {
  372. // Add the package to the resource system now, as we will need it to load the scene
  373. cache->AddPackageFile(newPackage, true);
  374. found = true;
  375. break;
  376. }
  377. }
  378. }
  379. // Package not found, need to request a download
  380. if (!found)
  381. {
  382. if (!packageCacheDir.Empty())
  383. RequestPackage(name, fileSize, checksum);
  384. else
  385. {
  386. LOGERROR("Can not download required packages, as package cache directory is not set");
  387. OnSceneLoadFailed();
  388. return;
  389. }
  390. }
  391. }
  392. // If no downloads were queued, can load the scene directly
  393. if (downloads_.Empty())
  394. OnPackagesReady();
  395. }
  396. void Connection::ProcessSceneChecksumError(int msgID, MemoryBuffer& msg)
  397. {
  398. if (IsClient())
  399. {
  400. LOGWARNING("Received unexpected SceneChecksumError message from client " + ToString());
  401. return;
  402. }
  403. LOGERROR("Scene checksum error");
  404. OnSceneLoadFailed();
  405. }
  406. void Connection::ProcessSceneUpdate(int msgID, MemoryBuffer& msg)
  407. {
  408. /// \todo On mobile devices processing this message may potentially cause a crash if it attempts to load new GPU resources
  409. /// while the application is minimized
  410. if (IsClient())
  411. {
  412. LOGWARNING("Received unexpected SceneUpdate message from client " + ToString());
  413. return;
  414. }
  415. if (!scene_)
  416. return;
  417. switch (msgID)
  418. {
  419. case MSG_CREATENODE:
  420. {
  421. unsigned nodeID = msg.ReadNetID();
  422. // In case of the root node (scene), it should already exist. Do not create in that case
  423. Node* node = scene_->GetNode(nodeID);
  424. if (!node)
  425. {
  426. // Add initially to the root level. May be moved as we receive the parent attribute
  427. node = scene_->CreateChild(nodeID, REPLICATED);
  428. // Create smoothed transform component
  429. node->CreateComponent<SmoothedTransform>(LOCAL);
  430. }
  431. // Read initial attributes, then snap the motion smoothing immediately to the end
  432. node->ReadDeltaUpdate(msg);
  433. SmoothedTransform* transform = node->GetComponent<SmoothedTransform>();
  434. if (transform)
  435. transform->Update(1.0f, 0.0f);
  436. // Read initial user variables
  437. unsigned numVars = msg.ReadVLE();
  438. while (numVars)
  439. {
  440. ShortStringHash key = msg.ReadShortStringHash();
  441. node->SetVar(key, msg.ReadVariant());
  442. --numVars;
  443. }
  444. // Read components
  445. unsigned numComponents = msg.ReadVLE();
  446. while (numComponents)
  447. {
  448. --numComponents;
  449. ShortStringHash type = msg.ReadShortStringHash();
  450. unsigned componentID = msg.ReadNetID();
  451. // Check if the component by this ID and type already exists in this node
  452. Component* component = scene_->GetComponent(componentID);
  453. if (!component || component->GetType() != type || component->GetNode() != node)
  454. {
  455. if (component)
  456. component->Remove();
  457. component = node->CreateComponent(type, componentID, REPLICATED);
  458. }
  459. // If was unable to create the component, would desync the message and therefore have to abort
  460. if (!component)
  461. {
  462. LOGERROR("CreateNode message parsing aborted due to unknown component");
  463. return;
  464. }
  465. // Read initial attributes and apply
  466. component->ReadDeltaUpdate(msg);
  467. component->ApplyAttributes();
  468. }
  469. }
  470. break;
  471. case MSG_NODEDELTAUPDATE:
  472. {
  473. unsigned nodeID = msg.ReadNetID();
  474. Node* node = scene_->GetNode(nodeID);
  475. if (node)
  476. {
  477. node->ReadDeltaUpdate(msg);
  478. // ApplyAttributes() is deliberately skipped, as Node has no attributes that require late applying.
  479. // Furthermore it would propagate to components and child nodes, which is not desired in this case
  480. unsigned changedVars = msg.ReadVLE();
  481. while (changedVars)
  482. {
  483. ShortStringHash key = msg.ReadShortStringHash();
  484. node->SetVar(key, msg.ReadVariant());
  485. --changedVars;
  486. }
  487. }
  488. else
  489. LOGWARNING("NodeDeltaUpdate message received for missing node " + String(nodeID));
  490. }
  491. break;
  492. case MSG_NODELATESTDATA:
  493. {
  494. unsigned nodeID = msg.ReadNetID();
  495. Node* node = scene_->GetNode(nodeID);
  496. if (node)
  497. {
  498. node->ReadLatestDataUpdate(msg);
  499. // ApplyAttributes() is deliberately skipped, as Node has no attributes that require late applying.
  500. // Furthermore it would propagate to components and child nodes, which is not desired in this case
  501. }
  502. else
  503. {
  504. // Latest data messages may be received out-of-order relative to node creation, so cache if necessary
  505. PODVector<unsigned char>& data = nodeLatestData_[nodeID];
  506. data.Resize(msg.GetSize());
  507. memcpy(&data[0], msg.GetData(), msg.GetSize());
  508. }
  509. }
  510. break;
  511. case MSG_REMOVENODE:
  512. {
  513. unsigned nodeID = msg.ReadNetID();
  514. Node* node = scene_->GetNode(nodeID);
  515. if (node)
  516. node->Remove();
  517. nodeLatestData_.Erase(nodeID);
  518. }
  519. break;
  520. case MSG_CREATECOMPONENT:
  521. {
  522. unsigned nodeID = msg.ReadNetID();
  523. Node* node = scene_->GetNode(nodeID);
  524. if (node)
  525. {
  526. ShortStringHash type = msg.ReadShortStringHash();
  527. unsigned componentID = msg.ReadNetID();
  528. // Check if the component by this ID and type already exists in this node
  529. Component* component = scene_->GetComponent(componentID);
  530. if (!component || component->GetType() != type || component->GetNode() != node)
  531. {
  532. if (component)
  533. component->Remove();
  534. component = node->CreateComponent(type, componentID, REPLICATED);
  535. }
  536. // If was unable to create the component, would desync the message and therefore have to abort
  537. if (!component)
  538. {
  539. LOGERROR("CreateComponent message parsing aborted due to unknown component");
  540. return;
  541. }
  542. // Read initial attributes and apply
  543. component->ReadDeltaUpdate(msg);
  544. component->ApplyAttributes();
  545. }
  546. else
  547. LOGWARNING("CreateComponent message received for missing node " + String(nodeID));
  548. }
  549. break;
  550. case MSG_COMPONENTDELTAUPDATE:
  551. {
  552. unsigned componentID = msg.ReadNetID();
  553. Component* component = scene_->GetComponent(componentID);
  554. if (component)
  555. {
  556. component->ReadDeltaUpdate(msg);
  557. component->ApplyAttributes();
  558. }
  559. else
  560. LOGWARNING("ComponentDeltaUpdate message received for missing component " + String(componentID));
  561. }
  562. break;
  563. case MSG_COMPONENTLATESTDATA:
  564. {
  565. unsigned componentID = msg.ReadNetID();
  566. Component* component = scene_->GetComponent(componentID);
  567. if (component)
  568. {
  569. component->ReadLatestDataUpdate(msg);
  570. component->ApplyAttributes();
  571. }
  572. else
  573. {
  574. // Latest data messages may be received out-of-order relative to component creation, so cache if necessary
  575. PODVector<unsigned char>& data = componentLatestData_[componentID];
  576. data.Resize(msg.GetSize());
  577. memcpy(&data[0], msg.GetData(), msg.GetSize());
  578. }
  579. }
  580. break;
  581. case MSG_REMOVECOMPONENT:
  582. {
  583. unsigned componentID = msg.ReadNetID();
  584. Component* component = scene_->GetComponent(componentID);
  585. if (component)
  586. component->Remove();
  587. componentLatestData_.Erase(componentID);
  588. }
  589. break;
  590. }
  591. }
  592. void Connection::ProcessPackageDownload(int msgID, MemoryBuffer& msg)
  593. {
  594. switch (msgID)
  595. {
  596. case MSG_REQUESTPACKAGE:
  597. if (!IsClient())
  598. {
  599. LOGWARNING("Received unexpected RequestPackage message from server");
  600. return;
  601. }
  602. else
  603. {
  604. String name = msg.ReadString();
  605. if (!scene_)
  606. {
  607. LOGWARNING("Received a RequestPackage message without an assigned scene from client " + ToString());
  608. return;
  609. }
  610. // The package must be one of those required by the scene
  611. const Vector<SharedPtr<PackageFile> >& packages = scene_->GetRequiredPackageFiles();
  612. for (unsigned i = 0; i < packages.Size(); ++i)
  613. {
  614. PackageFile* package = packages[i];
  615. String packageFullName = package->GetName();
  616. if (!GetFileNameAndExtension(packageFullName).Compare(name, false))
  617. {
  618. StringHash nameHash(name);
  619. // Do not restart upload if already exists
  620. if (uploads_.Contains(nameHash))
  621. {
  622. LOGWARNING("Received a request for package " + name + " already in transfer");
  623. return;
  624. }
  625. // Try to open the file now
  626. SharedPtr<File> file(new File(context_, packageFullName));
  627. if (!file->IsOpen())
  628. {
  629. LOGERROR("Failed to transmit package file " + name);
  630. SendPackageError(name);
  631. return;
  632. }
  633. LOGINFO("Transmitting package file " + name + " to client " + ToString());
  634. uploads_[nameHash].file_ = file;
  635. uploads_[nameHash].fragment_ = 0;
  636. uploads_[nameHash].totalFragments_ = (file->GetSize() + PACKAGE_FRAGMENT_SIZE - 1) / PACKAGE_FRAGMENT_SIZE;
  637. return;
  638. }
  639. }
  640. LOGERROR("Client requested an unexpected package file " + name);
  641. // Send the name hash only to indicate a failed download
  642. SendPackageError(name);
  643. return;
  644. }
  645. break;
  646. case MSG_PACKAGEDATA:
  647. if (IsClient())
  648. {
  649. LOGWARNING("Received unexpected PackageData message from client");
  650. return;
  651. }
  652. else
  653. {
  654. StringHash nameHash = msg.ReadStringHash();
  655. HashMap<StringHash, PackageDownload>::Iterator i = downloads_.Find(nameHash);
  656. // In case of being unable to create the package file into the cache, we will still receive all data from the server.
  657. // Simply disregard it
  658. if (i == downloads_.End())
  659. return;
  660. PackageDownload& download = i->second_;
  661. // If no further data, this is an error reply
  662. if (msg.IsEof())
  663. {
  664. OnPackageDownloadFailed(download.name_);
  665. return;
  666. }
  667. // If file has not yet been opened, try to open now. Prepend the checksum to the filename to allow multiple versions
  668. if (!download.file_)
  669. {
  670. download.file_ = new File(context_, GetSubsystem<Network>()->GetPackageCacheDir() + ToStringHex(download.checksum_) + "_" + download.name_, FILE_WRITE);
  671. if (!download.file_->IsOpen())
  672. {
  673. OnPackageDownloadFailed(download.name_);
  674. return;
  675. }
  676. }
  677. // Write the fragment data to the proper index
  678. unsigned char buffer[PACKAGE_FRAGMENT_SIZE];
  679. unsigned index = msg.ReadUInt();
  680. unsigned fragmentSize = msg.GetSize() - msg.GetPosition();
  681. msg.Read(buffer, fragmentSize);
  682. download.file_->Seek(index * PACKAGE_FRAGMENT_SIZE);
  683. download.file_->Write(buffer, fragmentSize);
  684. download.receivedFragments_.Insert(index);
  685. // Check if all fragments received
  686. if (download.receivedFragments_.Size() == download.totalFragments_)
  687. {
  688. LOGINFO("Package " + download.name_ + " downloaded successfully");
  689. // Instantiate the package and add to the resource system, as we will need it to load the scene
  690. download.file_->Close();
  691. SharedPtr<PackageFile> newPackage(new PackageFile(context_, download.file_->GetName()));
  692. GetSubsystem<ResourceCache>()->AddPackageFile(newPackage, true);
  693. // Then start the next download if there are more
  694. downloads_.Erase(i);
  695. if (downloads_.Empty())
  696. OnPackagesReady();
  697. else
  698. {
  699. PackageDownload& nextDownload = downloads_.Begin()->second_;
  700. LOGINFO("Requesting package " + nextDownload.name_ + " from server");
  701. msg_.Clear();
  702. msg_.WriteString(nextDownload.name_);
  703. SendMessage(MSG_REQUESTPACKAGE, true, true, msg_);
  704. nextDownload.initiated_ = true;
  705. }
  706. }
  707. }
  708. break;
  709. }
  710. }
  711. void Connection::ProcessIdentity(int msgID, MemoryBuffer& msg)
  712. {
  713. if (!IsClient())
  714. {
  715. LOGWARNING("Received unexpected Identity message from server");
  716. return;
  717. }
  718. identity_ = msg.ReadVariantMap();
  719. using namespace ClientIdentity;
  720. VariantMap eventData = identity_;
  721. eventData[P_CONNECTION] = (void*)this;
  722. eventData[P_ALLOW] = true;
  723. SendEvent(E_CLIENTIDENTITY, eventData);
  724. // If connection was denied as a response to the identity event, disconnect now
  725. if (!eventData[P_ALLOW].GetBool())
  726. Disconnect();
  727. }
  728. void Connection::ProcessControls(int msgID, MemoryBuffer& msg)
  729. {
  730. if (!IsClient())
  731. {
  732. LOGWARNING("Received unexpected Controls message from server");
  733. return;
  734. }
  735. Controls newControls;
  736. newControls.buttons_ = msg.ReadUInt();
  737. newControls.yaw_ = msg.ReadFloat();
  738. newControls.pitch_ = msg.ReadFloat();
  739. newControls.extraData_ = msg.ReadVariantMap();
  740. SetControls(newControls);
  741. SetPosition(msg.ReadVector3());
  742. }
  743. void Connection::ProcessSceneLoaded(int msgID, MemoryBuffer& msg)
  744. {
  745. if (!IsClient())
  746. {
  747. LOGWARNING("Received unexpected SceneLoaded message from server");
  748. return;
  749. }
  750. if (!scene_)
  751. {
  752. LOGWARNING("Received a SceneLoaded message without an assigned scene from client " + ToString());
  753. return;
  754. }
  755. unsigned checksum = msg.ReadUInt();
  756. if (checksum != scene_->GetChecksum())
  757. {
  758. LOGINFO("Scene checksum error from client " + ToString());
  759. msg_.Clear();
  760. SendMessage(MSG_SCENECHECKSUMERROR, true, true, msg_);
  761. OnSceneLoadFailed();
  762. }
  763. else
  764. {
  765. sceneLoaded_ = true;
  766. using namespace ClientSceneLoaded;
  767. VariantMap eventData;
  768. eventData[P_CONNECTION] = (void*)this;
  769. SendEvent(E_CLIENTSCENELOADED, eventData);
  770. }
  771. }
  772. void Connection::ProcessRemoteEvent(int msgID, MemoryBuffer& msg)
  773. {
  774. using namespace RemoteEventData;
  775. if (msgID == MSG_REMOTEEVENT)
  776. {
  777. StringHash eventType = msg.ReadStringHash();
  778. if (!GetSubsystem<Network>()->CheckRemoteEvent(eventType))
  779. {
  780. LOGWARNING("Discarding not allowed remote event " + eventType.ToString());
  781. return;
  782. }
  783. VariantMap eventData = msg.ReadVariantMap();
  784. eventData[P_CONNECTION] = (void*)this;
  785. SendEvent(eventType, eventData);
  786. }
  787. else
  788. {
  789. if (!scene_)
  790. {
  791. LOGERROR("Can not receive remote node event without an assigned scene");
  792. return;
  793. }
  794. unsigned nodeID = msg.ReadNetID();
  795. StringHash eventType = msg.ReadStringHash();
  796. if (!GetSubsystem<Network>()->CheckRemoteEvent(eventType))
  797. {
  798. LOGWARNING("Discarding not allowed remote event " + eventType.ToString());
  799. return;
  800. }
  801. VariantMap eventData = msg.ReadVariantMap();
  802. Node* sender = scene_->GetNode(nodeID);
  803. if (!sender)
  804. {
  805. LOGWARNING("Missing sender for remote node event, discarding");
  806. return;
  807. }
  808. eventData[P_CONNECTION] = (void*)this;
  809. sender->SendEvent(eventType, eventData);
  810. }
  811. }
  812. kNet::MessageConnection* Connection::GetMessageConnection() const
  813. {
  814. return const_cast<kNet::MessageConnection*>(connection_.ptr());
  815. }
  816. Scene* Connection::GetScene() const
  817. {
  818. return scene_;
  819. }
  820. bool Connection::IsConnected() const
  821. {
  822. return connection_->GetConnectionState() == kNet::ConnectionOK;
  823. }
  824. String Connection::GetAddress() const
  825. {
  826. const unsigned char* ip = connection_->RemoteEndPoint().ip;
  827. char str[256];
  828. sprintf(str, "%d.%d.%d.%d", (unsigned)ip[0], (unsigned)ip[1], (unsigned)ip[2], (unsigned)ip[3]);
  829. return String(str);
  830. }
  831. unsigned short Connection::GetPort() const
  832. {
  833. return connection_->RemoteEndPoint().port;
  834. }
  835. String Connection::ToString() const
  836. {
  837. return GetAddress() + ":" + String(GetPort());
  838. }
  839. unsigned Connection::GetNumDownloads() const
  840. {
  841. return downloads_.Size();
  842. }
  843. const String& Connection::GetDownloadName() const
  844. {
  845. for (HashMap<StringHash, PackageDownload>::ConstIterator i = downloads_.Begin(); i != downloads_.End(); ++i)
  846. {
  847. if (i->second_.initiated_)
  848. return i->second_.name_;
  849. }
  850. return String::EMPTY;
  851. }
  852. float Connection::GetDownloadProgress() const
  853. {
  854. for (HashMap<StringHash, PackageDownload>::ConstIterator i = downloads_.Begin(); i != downloads_.End(); ++i)
  855. {
  856. if (i->second_.initiated_)
  857. return (float)i->second_.receivedFragments_.Size() / (float)i->second_.totalFragments_;
  858. }
  859. return 1.0f;
  860. }
  861. void Connection::HandleAsyncLoadFinished(StringHash eventType, VariantMap& eventData)
  862. {
  863. sceneLoaded_ = true;
  864. msg_.Clear();
  865. msg_.WriteUInt(scene_->GetChecksum());
  866. SendMessage(MSG_SCENELOADED, true, true, msg_);
  867. }
  868. void Connection::ProcessNode(unsigned nodeID)
  869. {
  870. // Check that we have not already processed this due to dependency recursion
  871. if (!nodesToProcess_.Erase(nodeID))
  872. return;
  873. // Find replication state for the node
  874. HashMap<unsigned, NodeReplicationState>::Iterator i = sceneState_.nodeStates_.Find(nodeID);
  875. if (i != sceneState_.nodeStates_.End())
  876. {
  877. // Replication state found: the node is either be existing or removed
  878. Node* node = i->second_.node_;
  879. if (!node)
  880. {
  881. msg_.Clear();
  882. msg_.WriteNetID(nodeID);
  883. // Note: we will send MSG_REMOVENODE redundantly for each node in the hierarchy, even if removing the root node
  884. // would be enough. However, this may be better due to the client not possibly having updated parenting
  885. // information at the time of receiving this message
  886. SendMessage(MSG_REMOVENODE, true, true, msg_);
  887. sceneState_.nodeStates_.Erase(nodeID);
  888. }
  889. else
  890. ProcessExistingNode(node, i->second_);
  891. }
  892. else
  893. {
  894. // Replication state not found: this is a new node
  895. Node* node = scene_->GetNode(nodeID);
  896. if (node)
  897. ProcessNewNode(node);
  898. else
  899. {
  900. // Did not find the new node (may have been created, then removed immediately): erase from dirty set.
  901. sceneState_.dirtyNodes_.Erase(nodeID);
  902. }
  903. }
  904. }
  905. void Connection::ProcessNewNode(Node* node)
  906. {
  907. // Process depended upon nodes first, if they are dirty
  908. const PODVector<Node*>& dependencyNodes = node->GetDependencyNodes();
  909. for (PODVector<Node*>::ConstIterator i = dependencyNodes.Begin(); i != dependencyNodes.End(); ++i)
  910. {
  911. unsigned nodeID = (*i)->GetID();
  912. if (sceneState_.dirtyNodes_.Contains(nodeID))
  913. ProcessNode(nodeID);
  914. }
  915. msg_.Clear();
  916. msg_.WriteNetID(node->GetID());
  917. NodeReplicationState& nodeState = sceneState_.nodeStates_[node->GetID()];
  918. nodeState.connection_ = this;
  919. nodeState.sceneState_ = &sceneState_;
  920. nodeState.node_ = node;
  921. node->AddReplicationState(&nodeState);
  922. // Write node's attributes
  923. node->WriteInitialDeltaUpdate(msg_);
  924. // Write node's user variables
  925. const VariantMap& vars = node->GetVars();
  926. msg_.WriteVLE(vars.Size());
  927. for (VariantMap::ConstIterator i = vars.Begin(); i != vars.End(); ++i)
  928. {
  929. msg_.WriteShortStringHash(i->first_);
  930. msg_.WriteVariant(i->second_);
  931. }
  932. // Write node's components
  933. msg_.WriteVLE(node->GetNumNetworkComponents());
  934. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  935. for (unsigned i = 0; i < components.Size(); ++i)
  936. {
  937. Component* component = components[i];
  938. // Check if component is not to be replicated
  939. if (component->GetID() >= FIRST_LOCAL_ID)
  940. continue;
  941. ComponentReplicationState& componentState = nodeState.componentStates_[component->GetID()];
  942. componentState.connection_ = this;
  943. componentState.nodeState_ = &nodeState;
  944. componentState.component_ = component;
  945. component->AddReplicationState(&componentState);
  946. msg_.WriteShortStringHash(component->GetType());
  947. msg_.WriteNetID(component->GetID());
  948. component->WriteInitialDeltaUpdate(msg_);
  949. }
  950. SendMessage(MSG_CREATENODE, true, true, msg_);
  951. nodeState.markedDirty_ = false;
  952. sceneState_.dirtyNodes_.Erase(node->GetID());
  953. }
  954. void Connection::ProcessExistingNode(Node* node, NodeReplicationState& nodeState)
  955. {
  956. // Process depended upon nodes first, if they are dirty
  957. const PODVector<Node*>& dependencyNodes = node->GetDependencyNodes();
  958. for (PODVector<Node*>::ConstIterator i = dependencyNodes.Begin(); i != dependencyNodes.End(); ++i)
  959. {
  960. unsigned nodeID = (*i)->GetID();
  961. if (sceneState_.dirtyNodes_.Contains(nodeID))
  962. ProcessNode(nodeID);
  963. }
  964. // Check from the interest management component, if exists, whether should update
  965. /// \todo Searching for the component is a potential CPU hotspot. It should be cached
  966. NetworkPriority* priority = node->GetComponent<NetworkPriority>();
  967. if (priority && (!priority->GetAlwaysUpdateOwner() || node->GetOwner() != this))
  968. {
  969. float distance = (node->GetWorldPosition() - position_).Length();
  970. if (!priority->CheckUpdate(distance, nodeState.priorityAcc_))
  971. return;
  972. }
  973. // Check if attributes have changed
  974. if (nodeState.dirtyAttributes_.Count())
  975. {
  976. const Vector<AttributeInfo>* attributes = node->GetNetworkAttributes();
  977. unsigned numAttributes = attributes->Size();
  978. bool hasLatestData = false;
  979. for (unsigned i = 0; i < numAttributes; ++i)
  980. {
  981. if (nodeState.dirtyAttributes_.IsSet(i) && (attributes->At(i).mode_ & AM_LATESTDATA))
  982. {
  983. hasLatestData = true;
  984. nodeState.dirtyAttributes_.Clear(i);
  985. }
  986. }
  987. // Send latestdata message if necessary
  988. if (hasLatestData)
  989. {
  990. msg_.Clear();
  991. msg_.WriteNetID(node->GetID());
  992. node->WriteLatestDataUpdate(msg_);
  993. SendMessage(MSG_NODELATESTDATA, true, false, msg_, node->GetID());
  994. }
  995. // Send deltaupdate if remaining dirty bits, or vars have changed
  996. if (nodeState.dirtyAttributes_.Count() || nodeState.dirtyVars_.Size())
  997. {
  998. msg_.Clear();
  999. msg_.WriteNetID(node->GetID());
  1000. node->WriteDeltaUpdate(msg_, nodeState.dirtyAttributes_);
  1001. // Write changed variables
  1002. msg_.WriteVLE(nodeState.dirtyVars_.Size());
  1003. const VariantMap& vars = node->GetVars();
  1004. for (HashSet<ShortStringHash>::ConstIterator i = nodeState.dirtyVars_.Begin(); i != nodeState.dirtyVars_.End(); ++i)
  1005. {
  1006. VariantMap::ConstIterator j = vars.Find(*i);
  1007. if (j != vars.End())
  1008. {
  1009. msg_.WriteShortStringHash(j->first_);
  1010. msg_.WriteVariant(j->second_);
  1011. }
  1012. else
  1013. {
  1014. // Variable has been marked dirty, but is removed (which is unsupported): send a dummy variable in place
  1015. LOGWARNING("Sending dummy user variable as original value was removed");
  1016. msg_.WriteShortStringHash(ShortStringHash());
  1017. msg_.WriteVariant(Variant());
  1018. }
  1019. }
  1020. SendMessage(MSG_NODEDELTAUPDATE, true, true, msg_);
  1021. nodeState.dirtyAttributes_.ClearAll();
  1022. nodeState.dirtyVars_.Clear();
  1023. }
  1024. }
  1025. // Check for removed or changed components
  1026. for (HashMap<unsigned, ComponentReplicationState>::Iterator i = nodeState.componentStates_.Begin();
  1027. i != nodeState.componentStates_.End(); )
  1028. {
  1029. HashMap<unsigned, ComponentReplicationState>::Iterator current = i++;
  1030. ComponentReplicationState& componentState = current->second_;
  1031. Component* component = componentState.component_;
  1032. if (!component)
  1033. {
  1034. // Removed component
  1035. msg_.Clear();
  1036. msg_.WriteNetID(current->first_);
  1037. SendMessage(MSG_REMOVECOMPONENT, true, true, msg_);
  1038. nodeState.componentStates_.Erase(current);
  1039. }
  1040. else
  1041. {
  1042. // Existing component. Check if attributes have changed
  1043. if (componentState.dirtyAttributes_.Count())
  1044. {
  1045. const Vector<AttributeInfo>* attributes = component->GetNetworkAttributes();
  1046. unsigned numAttributes = attributes->Size();
  1047. bool hasLatestData = false;
  1048. for (unsigned i = 0; i < numAttributes; ++i)
  1049. {
  1050. if (componentState.dirtyAttributes_.IsSet(i) && (attributes->At(i).mode_ & AM_LATESTDATA))
  1051. {
  1052. hasLatestData = true;
  1053. componentState.dirtyAttributes_.Clear(i);
  1054. }
  1055. }
  1056. // Send latestdata message if necessary
  1057. if (hasLatestData)
  1058. {
  1059. msg_.Clear();
  1060. msg_.WriteNetID(component->GetID());
  1061. component->WriteLatestDataUpdate(msg_);
  1062. SendMessage(MSG_COMPONENTLATESTDATA, true, false, msg_, component->GetID());
  1063. }
  1064. // Send deltaupdate if remaining dirty bits
  1065. if (componentState.dirtyAttributes_.Count())
  1066. {
  1067. msg_.Clear();
  1068. msg_.WriteNetID(component->GetID());
  1069. component->WriteDeltaUpdate(msg_, componentState.dirtyAttributes_);
  1070. SendMessage(MSG_COMPONENTDELTAUPDATE, true, true, msg_);
  1071. componentState.dirtyAttributes_.ClearAll();
  1072. }
  1073. }
  1074. }
  1075. }
  1076. // Check for new components
  1077. if (nodeState.componentStates_.Size() != node->GetNumNetworkComponents())
  1078. {
  1079. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  1080. for (unsigned i = 0; i < components.Size(); ++i)
  1081. {
  1082. Component* component = components[i];
  1083. // Check if component is not to be replicated
  1084. if (component->GetID() >= FIRST_LOCAL_ID)
  1085. continue;
  1086. HashMap<unsigned, ComponentReplicationState>::Iterator j = nodeState.componentStates_.Find(component->GetID());
  1087. if (j == nodeState.componentStates_.End())
  1088. {
  1089. // New component
  1090. ComponentReplicationState& componentState = nodeState.componentStates_[component->GetID()];
  1091. componentState.connection_ = this;
  1092. componentState.nodeState_ = &nodeState;
  1093. componentState.component_ = component;
  1094. component->AddReplicationState(&componentState);
  1095. msg_.Clear();
  1096. msg_.WriteNetID(node->GetID());
  1097. msg_.WriteShortStringHash(component->GetType());
  1098. msg_.WriteNetID(component->GetID());
  1099. component->WriteInitialDeltaUpdate(msg_);
  1100. SendMessage(MSG_CREATECOMPONENT, true, true, msg_);
  1101. }
  1102. }
  1103. }
  1104. nodeState.markedDirty_ = false;
  1105. sceneState_.dirtyNodes_.Erase(node->GetID());
  1106. }
  1107. void Connection::RequestPackage(const String& name, unsigned fileSize, unsigned checksum)
  1108. {
  1109. StringHash nameHash(name);
  1110. if (downloads_.Contains(nameHash))
  1111. return; // Download already exists
  1112. PackageDownload& download = downloads_[nameHash];
  1113. download.name_ = name;
  1114. download.totalFragments_ = (fileSize + PACKAGE_FRAGMENT_SIZE - 1) / PACKAGE_FRAGMENT_SIZE;
  1115. download.checksum_ = checksum;
  1116. // Start download now only if no existing downloads, else wait for the existing ones to finish
  1117. if (downloads_.Size() == 1)
  1118. {
  1119. LOGINFO("Requesting package " + name + " from server");
  1120. msg_.Clear();
  1121. msg_.WriteString(name);
  1122. SendMessage(MSG_REQUESTPACKAGE, true, true, msg_);
  1123. download.initiated_ = true;
  1124. }
  1125. }
  1126. void Connection::SendPackageError(const String& name)
  1127. {
  1128. msg_.Clear();
  1129. msg_.WriteStringHash(StringHash(name));
  1130. SendMessage(MSG_PACKAGEDATA, true, false, msg_);
  1131. }
  1132. void Connection::OnSceneLoadFailed()
  1133. {
  1134. sceneLoaded_ = false;
  1135. using namespace NetworkSceneLoadFailed;
  1136. VariantMap eventData;
  1137. eventData[P_CONNECTION] = (void*)this;
  1138. SendEvent(E_NETWORKSCENELOADFAILED, eventData);
  1139. }
  1140. void Connection::OnPackageDownloadFailed(const String& name)
  1141. {
  1142. LOGERROR("Download of package " + name + " failed");
  1143. // As one package failed, we can not join the scene in any case. Clear the downloads
  1144. downloads_.Clear();
  1145. OnSceneLoadFailed();
  1146. }
  1147. void Connection::OnPackagesReady()
  1148. {
  1149. if (!scene_)
  1150. return;
  1151. if (sceneFileName_.Empty())
  1152. {
  1153. scene_->Clear();
  1154. sceneLoaded_ = true;
  1155. // If filename is empty, can send the scene loaded reply immediately
  1156. msg_.Clear();
  1157. msg_.WriteUInt(scene_->GetChecksum());
  1158. SendMessage(MSG_SCENELOADED, true, true, msg_);
  1159. }
  1160. else
  1161. {
  1162. // Otherwise start the async loading process
  1163. String extension = GetExtension(sceneFileName_);
  1164. SharedPtr<File> file = GetSubsystem<ResourceCache>()->GetFile(sceneFileName_);
  1165. bool success;
  1166. if (extension == ".xml")
  1167. success = scene_->LoadAsyncXML(file);
  1168. else
  1169. success = scene_->LoadAsync(file);
  1170. if (!success)
  1171. OnSceneLoadFailed();
  1172. }
  1173. }
  1174. }