Connection.cpp 43 KB

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