Connection.cpp 42 KB

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