Connection.cpp 42 KB

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