Connection.cpp 52 KB

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