Connection.cpp 51 KB

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