Connection.cpp 47 KB

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