Connection.cpp 43 KB

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