Connection.cpp 49 KB

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