Connection.cpp 45 KB

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