Connection.cpp 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Profiler.h"
  24. #include "../IO/File.h"
  25. #include "../IO/FileSystem.h"
  26. #include "../IO/Log.h"
  27. #include "../IO/MemoryBuffer.h"
  28. #include "../IO/PackageFile.h"
  29. #include "../Network/Connection.h"
  30. #include "../Network/Network.h"
  31. #include "../Network/NetworkEvents.h"
  32. #include "../Network/NetworkPriority.h"
  33. #include "../Network/Protocol.h"
  34. #include "../Resource/ResourceCache.h"
  35. #include "../Scene/Scene.h"
  36. #include "../Scene/SceneEvents.h"
  37. #include "../Scene/SmoothedTransform.h"
  38. #include <kNet/include/kNet.h>
  39. #include "../DebugNew.h"
  40. namespace Atomic
  41. {
  42. static const int STATS_INTERVAL_MSEC = 2000;
  43. PackageDownload::PackageDownload() :
  44. totalFragments_(0),
  45. checksum_(0),
  46. initiated_(false)
  47. {
  48. }
  49. PackageUpload::PackageUpload() :
  50. fragment_(0),
  51. totalFragments_(0)
  52. {
  53. }
  54. Connection::Connection(Context* context) : Object(context)
  55. {
  56. }
  57. Connection::Connection(Context* context, bool isClient, kNet::SharedPtr<kNet::MessageConnection> connection) :
  58. Object(context),
  59. timeStamp_(0),
  60. connection_(connection),
  61. sendMode_(OPSM_NONE),
  62. isClient_(isClient),
  63. connectPending_(false),
  64. sceneLoaded_(false),
  65. logStatistics_(false)
  66. {
  67. sceneState_.connection_ = this;
  68. // Store address and port now for accurate logging (kNet may already have destroyed the socket on disconnection,
  69. // in which case we would log a zero address:port on disconnect)
  70. kNet::EndPoint endPoint = connection_->RemoteEndPoint();
  71. ///\todo Not IPv6-capable.
  72. address_ = Atomic::ToString("%d.%d.%d.%d", endPoint.ip[0], endPoint.ip[1], endPoint.ip[2], endPoint.ip[3]);
  73. port_ = endPoint.port;
  74. }
  75. Connection::~Connection()
  76. {
  77. // Reset scene (remove possible owner references), as this connection is about to be destroyed
  78. SetScene(0);
  79. }
  80. void Connection::SendMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg, unsigned contentID)
  81. {
  82. SendMessage(msgID, reliable, inOrder, msg.GetData(), msg.GetSize(), contentID);
  83. }
  84. void Connection::SendMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes,
  85. unsigned contentID)
  86. {
  87. // Make sure not to use kNet internal message ID's
  88. if (msgID <= 0x4 || msgID >= 0x3ffffffe)
  89. {
  90. LOGERROR("Can not send message with reserved ID");
  91. return;
  92. }
  93. if (numBytes && !data)
  94. {
  95. LOGERROR("Null pointer supplied for network message data");
  96. return;
  97. }
  98. kNet::NetworkMessage* msg = connection_->StartNewMessage((unsigned long)msgID, numBytes);
  99. if (!msg)
  100. {
  101. LOGERROR("Can not start new network message");
  102. return;
  103. }
  104. msg->reliable = reliable;
  105. msg->inOrder = inOrder;
  106. msg->priority = 0;
  107. msg->contentID = contentID;
  108. if (numBytes)
  109. memcpy(msg->data, data, numBytes);
  110. connection_->EndAndQueueMessage(msg);
  111. }
  112. void Connection::SendRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData)
  113. {
  114. RemoteEvent queuedEvent;
  115. queuedEvent.senderID_ = 0;
  116. queuedEvent.eventType_ = eventType;
  117. queuedEvent.eventData_ = eventData;
  118. queuedEvent.inOrder_ = inOrder;
  119. remoteEvents_.Push(queuedEvent);
  120. }
  121. void Connection::SendRemoteEvent(Node* node, StringHash eventType, bool inOrder, const VariantMap& eventData)
  122. {
  123. if (!node)
  124. {
  125. LOGERROR("Null sender node for remote node event");
  126. return;
  127. }
  128. if (node->GetScene() != scene_)
  129. {
  130. LOGERROR("Sender node is not in the connection's scene, can not send remote node event");
  131. return;
  132. }
  133. if (node->GetID() >= FIRST_LOCAL_ID)
  134. {
  135. LOGERROR("Sender node has a local ID, can not send remote node event");
  136. return;
  137. }
  138. RemoteEvent queuedEvent;
  139. queuedEvent.senderID_ = node->GetID();
  140. queuedEvent.eventType_ = eventType;
  141. queuedEvent.eventData_ = eventData;
  142. queuedEvent.inOrder_ = inOrder;
  143. remoteEvents_.Push(queuedEvent);
  144. }
  145. void Connection::SetScene(Scene* newScene)
  146. {
  147. if (scene_)
  148. {
  149. // Remove replication states and owner references from the previous scene
  150. scene_->CleanupConnection(this);
  151. }
  152. scene_ = newScene;
  153. sceneLoaded_ = false;
  154. UnsubscribeFromEvent(E_ASYNCLOADFINISHED);
  155. if (!scene_)
  156. return;
  157. if (isClient_)
  158. {
  159. sceneState_.Clear();
  160. // When scene is assigned on the server, instruct the client to load it. This may require downloading packages
  161. const Vector<SharedPtr<PackageFile> >& packages = scene_->GetRequiredPackageFiles();
  162. unsigned numPackages = packages.Size();
  163. msg_.Clear();
  164. msg_.WriteString(scene_->GetFileName());
  165. msg_.WriteVLE(numPackages);
  166. for (unsigned i = 0; i < numPackages; ++i)
  167. {
  168. PackageFile* package = packages[i];
  169. msg_.WriteString(GetFileNameAndExtension(package->GetName()));
  170. msg_.WriteUInt(package->GetTotalSize());
  171. msg_.WriteUInt(package->GetChecksum());
  172. }
  173. SendMessage(MSG_LOADSCENE, true, true, msg_);
  174. }
  175. else
  176. {
  177. // Make sure there is no existing async loading
  178. scene_->StopAsyncLoading();
  179. SubscribeToEvent(scene_, E_ASYNCLOADFINISHED, HANDLER(Connection, HandleAsyncLoadFinished));
  180. }
  181. SubscribeToEvent(scene_, E_COMPONENTREMOVED, HANDLER(Connection, HandleComponentRemoved));
  182. }
  183. void Connection::SetIdentity(const VariantMap& identity)
  184. {
  185. identity_ = identity;
  186. }
  187. void Connection::SetControls(const Controls& newControls)
  188. {
  189. controls_ = newControls;
  190. }
  191. void Connection::SetPosition(const Vector3& position)
  192. {
  193. position_ = position;
  194. if (sendMode_ == OPSM_NONE)
  195. sendMode_ = OPSM_POSITION;
  196. }
  197. void Connection::SetRotation(const Quaternion& rotation)
  198. {
  199. rotation_ = rotation;
  200. if (sendMode_ != OPSM_POSITION_ROTATION)
  201. sendMode_ = OPSM_POSITION_ROTATION;
  202. }
  203. void Connection::SetConnectPending(bool connectPending)
  204. {
  205. connectPending_ = connectPending;
  206. }
  207. void Connection::SetLogStatistics(bool enable)
  208. {
  209. logStatistics_ = enable;
  210. }
  211. void Connection::Disconnect(int waitMSec)
  212. {
  213. connection_->Disconnect(waitMSec);
  214. }
  215. void Connection::SendServerUpdate()
  216. {
  217. if (!scene_ || !sceneLoaded_)
  218. return;
  219. // Always check the root node (scene) first so that the scene-wide components get sent first,
  220. // and all other replicated nodes get added to the dirty set for sending the initial state
  221. unsigned sceneID = scene_->GetID();
  222. nodesToProcess_.Insert(sceneID);
  223. ProcessNode(sceneID);
  224. // Then go through all dirtied nodes
  225. nodesToProcess_.Insert(sceneState_.dirtyNodes_);
  226. nodesToProcess_.Erase(sceneID); // Do not process the root node twice
  227. while (nodesToProcess_.Size())
  228. {
  229. unsigned nodeID = nodesToProcess_.Front();
  230. ProcessNode(nodeID);
  231. }
  232. }
  233. void Connection::SendClientUpdate()
  234. {
  235. if (!scene_ || !sceneLoaded_)
  236. return;
  237. msg_.Clear();
  238. msg_.WriteUInt(controls_.buttons_);
  239. msg_.WriteFloat(controls_.yaw_);
  240. msg_.WriteFloat(controls_.pitch_);
  241. msg_.WriteVariantMap(controls_.extraData_);
  242. msg_.WriteUByte(timeStamp_);
  243. if (sendMode_ >= OPSM_POSITION)
  244. msg_.WriteVector3(position_);
  245. if (sendMode_ >= OPSM_POSITION_ROTATION)
  246. msg_.WritePackedQuaternion(rotation_);
  247. SendMessage(MSG_CONTROLS, false, false, msg_, CONTROLS_CONTENT_ID);
  248. ++timeStamp_;
  249. }
  250. void Connection::SendRemoteEvents()
  251. {
  252. #ifdef ATOMIC_LOGGING
  253. if (logStatistics_ && statsTimer_.GetMSec(false) > STATS_INTERVAL_MSEC)
  254. {
  255. statsTimer_.Reset();
  256. char statsBuffer[256];
  257. sprintf(statsBuffer, "RTT %.3f ms Pkt in %d Pkt out %d Data in %.3f KB/s Data out %.3f KB/s", connection_->RoundTripTime(),
  258. (int)connection_->PacketsInPerSec(),
  259. (int)connection_->PacketsOutPerSec(), connection_->BytesInPerSec() / 1000.0f, connection_->BytesOutPerSec() / 1000.0f);
  260. LOGINFO(statsBuffer);
  261. }
  262. #endif
  263. if (remoteEvents_.Empty())
  264. return;
  265. PROFILE(SendRemoteEvents);
  266. for (Vector<RemoteEvent>::ConstIterator i = remoteEvents_.Begin(); i != remoteEvents_.End(); ++i)
  267. {
  268. msg_.Clear();
  269. if (!i->senderID_)
  270. {
  271. msg_.WriteStringHash(i->eventType_);
  272. msg_.WriteVariantMap(i->eventData_);
  273. SendMessage(MSG_REMOTEEVENT, true, i->inOrder_, msg_);
  274. }
  275. else
  276. {
  277. msg_.WriteNetID(i->senderID_);
  278. msg_.WriteStringHash(i->eventType_);
  279. msg_.WriteVariantMap(i->eventData_);
  280. SendMessage(MSG_REMOTENODEEVENT, true, i->inOrder_, msg_);
  281. }
  282. }
  283. remoteEvents_.Clear();
  284. }
  285. void Connection::SendPackages()
  286. {
  287. while (!uploads_.Empty() && connection_->NumOutboundMessagesPending() < 1000)
  288. {
  289. unsigned char buffer[PACKAGE_FRAGMENT_SIZE];
  290. for (HashMap<StringHash, PackageUpload>::Iterator i = uploads_.Begin(); i != uploads_.End();)
  291. {
  292. HashMap<StringHash, PackageUpload>::Iterator current = i++;
  293. PackageUpload& upload = current->second_;
  294. unsigned fragmentSize =
  295. (unsigned)Min((int)(upload.file_->GetSize() - upload.file_->GetPosition()), (int)PACKAGE_FRAGMENT_SIZE);
  296. upload.file_->Read(buffer, fragmentSize);
  297. msg_.Clear();
  298. msg_.WriteStringHash(current->first_);
  299. msg_.WriteUInt(upload.fragment_++);
  300. msg_.Write(buffer, fragmentSize);
  301. SendMessage(MSG_PACKAGEDATA, true, false, msg_);
  302. // Check if upload finished
  303. if (upload.fragment_ == upload.totalFragments_)
  304. uploads_.Erase(current);
  305. }
  306. }
  307. }
  308. void Connection::ProcessPendingLatestData()
  309. {
  310. if (!scene_ || !sceneLoaded_)
  311. return;
  312. // Iterate through pending node data and see if we can find the nodes now
  313. for (HashMap<unsigned, PODVector<unsigned char> >::Iterator i = nodeLatestData_.Begin(); i != nodeLatestData_.End();)
  314. {
  315. HashMap<unsigned, PODVector<unsigned char> >::Iterator current = i++;
  316. Node* node = scene_->GetNode(current->first_);
  317. if (node)
  318. {
  319. MemoryBuffer msg(current->second_);
  320. msg.ReadNetID(); // Skip the node ID
  321. node->ReadLatestDataUpdate(msg);
  322. // ApplyAttributes() is deliberately skipped, as Node has no attributes that require late applying.
  323. // Furthermore it would propagate to components and child nodes, which is not desired in this case
  324. nodeLatestData_.Erase(current);
  325. }
  326. }
  327. // Iterate through pending component data and see if we can find the components now
  328. for (HashMap<unsigned, PODVector<unsigned char> >::Iterator i = componentLatestData_.Begin(); i != componentLatestData_.End();)
  329. {
  330. HashMap<unsigned, PODVector<unsigned char> >::Iterator current = i++;
  331. Component* component = scene_->GetComponent(current->first_);
  332. if (component)
  333. {
  334. MemoryBuffer msg(current->second_);
  335. msg.ReadNetID(); // Skip the component ID
  336. if (component->ReadLatestDataUpdate(msg))
  337. component->ApplyAttributes();
  338. componentLatestData_.Erase(current);
  339. }
  340. }
  341. }
  342. bool Connection::ProcessMessage(int msgID, MemoryBuffer& msg)
  343. {
  344. bool processed = true;
  345. switch (msgID)
  346. {
  347. case MSG_IDENTITY:
  348. ProcessIdentity(msgID, msg);
  349. break;
  350. case MSG_CONTROLS:
  351. ProcessControls(msgID, msg);
  352. break;
  353. case MSG_SCENELOADED:
  354. ProcessSceneLoaded(msgID, msg);
  355. break;
  356. case MSG_REQUESTPACKAGE:
  357. case MSG_PACKAGEDATA:
  358. ProcessPackageDownload(msgID, msg);
  359. break;
  360. case MSG_LOADSCENE:
  361. ProcessLoadScene(msgID, msg);
  362. break;
  363. case MSG_SCENECHECKSUMERROR:
  364. ProcessSceneChecksumError(msgID, msg);
  365. break;
  366. case MSG_CREATENODE:
  367. case MSG_NODEDELTAUPDATE:
  368. case MSG_NODELATESTDATA:
  369. case MSG_REMOVENODE:
  370. case MSG_CREATECOMPONENT:
  371. case MSG_COMPONENTDELTAUPDATE:
  372. case MSG_COMPONENTLATESTDATA:
  373. case MSG_REMOVECOMPONENT:
  374. ProcessSceneUpdate(msgID, msg);
  375. break;
  376. case MSG_REMOTEEVENT:
  377. case MSG_REMOTENODEEVENT:
  378. ProcessRemoteEvent(msgID, msg);
  379. break;
  380. case MSG_PACKAGEINFO:
  381. ProcessPackageInfo(msgID, msg);
  382. break;
  383. case MSG_STRING:
  384. ProcessStringMessage(msgID, msg);
  385. break;
  386. default:
  387. processed = false;
  388. break;
  389. }
  390. return processed;
  391. }
  392. void Connection::ProcessLoadScene(int msgID, MemoryBuffer& msg)
  393. {
  394. if (IsClient())
  395. {
  396. LOGWARNING("Received unexpected LoadScene message from client " + ToString());
  397. return;
  398. }
  399. if (!scene_)
  400. {
  401. LOGERROR("Can not handle LoadScene message without an assigned scene");
  402. return;
  403. }
  404. // Store the scene file name we need to eventually load
  405. sceneFileName_ = msg.ReadString();
  406. // Clear previous pending latest data and package downloads if any
  407. nodeLatestData_.Clear();
  408. componentLatestData_.Clear();
  409. downloads_.Clear();
  410. // In case we have joined other scenes in this session, remove first all downloaded package files from the resource system
  411. // to prevent resource conflicts
  412. ResourceCache* cache = GetSubsystem<ResourceCache>();
  413. const String& packageCacheDir = GetSubsystem<Network>()->GetPackageCacheDir();
  414. Vector<SharedPtr<PackageFile> > packages = cache->GetPackageFiles();
  415. for (unsigned i = 0; i < packages.Size(); ++i)
  416. {
  417. PackageFile* package = packages[i];
  418. if (!package->GetName().Find(packageCacheDir))
  419. cache->RemovePackageFile(package, true);
  420. }
  421. // Now check which packages we have in the resource cache or in the download cache, and which we need to download
  422. unsigned numPackages = msg.ReadVLE();
  423. if (!RequestNeededPackages(numPackages, msg))
  424. {
  425. OnSceneLoadFailed();
  426. return;
  427. }
  428. // If no downloads were queued, can load the scene directly
  429. if (downloads_.Empty())
  430. OnPackagesReady();
  431. }
  432. void Connection::ProcessSceneChecksumError(int msgID, MemoryBuffer& msg)
  433. {
  434. if (IsClient())
  435. {
  436. LOGWARNING("Received unexpected SceneChecksumError message from client " + ToString());
  437. return;
  438. }
  439. LOGERROR("Scene checksum error");
  440. OnSceneLoadFailed();
  441. }
  442. void Connection::ProcessSceneUpdate(int msgID, MemoryBuffer& msg)
  443. {
  444. /// \todo On mobile devices processing this message may potentially cause a crash if it attempts to load new GPU resources
  445. /// while the application is minimized
  446. if (IsClient())
  447. {
  448. LOGWARNING("Received unexpected SceneUpdate message from client " + ToString());
  449. return;
  450. }
  451. if (!scene_)
  452. return;
  453. switch (msgID)
  454. {
  455. case MSG_CREATENODE:
  456. {
  457. unsigned nodeID = msg.ReadNetID();
  458. // In case of the root node (scene), it should already exist. Do not create in that case
  459. Node* node = scene_->GetNode(nodeID);
  460. if (!node)
  461. {
  462. // Add initially to the root level. May be moved as we receive the parent attribute
  463. node = scene_->CreateChild(nodeID, REPLICATED);
  464. // Create smoothed transform component
  465. node->CreateComponent<SmoothedTransform>(LOCAL);
  466. }
  467. // Read initial attributes, then snap the motion smoothing immediately to the end
  468. node->ReadDeltaUpdate(msg);
  469. SmoothedTransform* transform = node->GetComponent<SmoothedTransform>();
  470. if (transform)
  471. transform->Update(1.0f, 0.0f);
  472. // Read initial user variables
  473. unsigned numVars = msg.ReadVLE();
  474. while (numVars)
  475. {
  476. StringHash key = msg.ReadStringHash();
  477. node->SetVar(key, msg.ReadVariant());
  478. --numVars;
  479. }
  480. // Read components
  481. unsigned numComponents = msg.ReadVLE();
  482. while (numComponents)
  483. {
  484. --numComponents;
  485. StringHash type = msg.ReadStringHash();
  486. unsigned componentID = msg.ReadNetID();
  487. // Check if the component by this ID and type already exists in this node
  488. Component* component = scene_->GetComponent(componentID);
  489. if (!component || component->GetType() != type || component->GetNode() != node)
  490. {
  491. if (component)
  492. component->Remove();
  493. component = node->CreateComponent(type, REPLICATED, componentID);
  494. }
  495. // If was unable to create the component, would desync the message and therefore have to abort
  496. if (!component)
  497. {
  498. LOGERROR("CreateNode message parsing aborted due to unknown component");
  499. return;
  500. }
  501. // Read initial attributes and apply
  502. component->ReadDeltaUpdate(msg);
  503. component->ApplyAttributes();
  504. }
  505. }
  506. break;
  507. case MSG_NODEDELTAUPDATE:
  508. {
  509. unsigned nodeID = msg.ReadNetID();
  510. Node* node = scene_->GetNode(nodeID);
  511. if (node)
  512. {
  513. node->ReadDeltaUpdate(msg);
  514. // ApplyAttributes() is deliberately skipped, as Node has no attributes that require late applying.
  515. // Furthermore it would propagate to components and child nodes, which is not desired in this case
  516. unsigned changedVars = msg.ReadVLE();
  517. while (changedVars)
  518. {
  519. StringHash key = msg.ReadStringHash();
  520. node->SetVar(key, msg.ReadVariant());
  521. --changedVars;
  522. }
  523. }
  524. else
  525. LOGWARNING("NodeDeltaUpdate message received for missing node " + String(nodeID));
  526. }
  527. break;
  528. case MSG_NODELATESTDATA:
  529. {
  530. unsigned nodeID = msg.ReadNetID();
  531. Node* node = scene_->GetNode(nodeID);
  532. if (node)
  533. {
  534. node->ReadLatestDataUpdate(msg);
  535. // ApplyAttributes() is deliberately skipped, as Node has no attributes that require late applying.
  536. // Furthermore it would propagate to components and child nodes, which is not desired in this case
  537. }
  538. else
  539. {
  540. // Latest data messages may be received out-of-order relative to node creation, so cache if necessary
  541. PODVector<unsigned char>& data = nodeLatestData_[nodeID];
  542. data.Resize(msg.GetSize());
  543. memcpy(&data[0], msg.GetData(), msg.GetSize());
  544. }
  545. }
  546. break;
  547. case MSG_REMOVENODE:
  548. {
  549. unsigned nodeID = msg.ReadNetID();
  550. Node* node = scene_->GetNode(nodeID);
  551. if (node)
  552. node->Remove();
  553. nodeLatestData_.Erase(nodeID);
  554. }
  555. break;
  556. case MSG_CREATECOMPONENT:
  557. {
  558. unsigned nodeID = msg.ReadNetID();
  559. Node* node = scene_->GetNode(nodeID);
  560. if (node)
  561. {
  562. StringHash type = msg.ReadStringHash();
  563. unsigned componentID = msg.ReadNetID();
  564. // Check if the component by this ID and type already exists in this node
  565. Component* component = scene_->GetComponent(componentID);
  566. if (!component || component->GetType() != type || component->GetNode() != node)
  567. {
  568. if (component)
  569. component->Remove();
  570. component = node->CreateComponent(type, REPLICATED, componentID);
  571. }
  572. // If was unable to create the component, would desync the message and therefore have to abort
  573. if (!component)
  574. {
  575. LOGERROR("CreateComponent message parsing aborted due to unknown component");
  576. return;
  577. }
  578. // Read initial attributes and apply
  579. component->ReadDeltaUpdate(msg);
  580. component->ApplyAttributes();
  581. }
  582. else
  583. LOGWARNING("CreateComponent message received for missing node " + String(nodeID));
  584. }
  585. break;
  586. case MSG_COMPONENTDELTAUPDATE:
  587. {
  588. unsigned componentID = msg.ReadNetID();
  589. Component* component = scene_->GetComponent(componentID);
  590. if (component)
  591. {
  592. component->ReadDeltaUpdate(msg);
  593. component->ApplyAttributes();
  594. }
  595. else
  596. LOGWARNING("ComponentDeltaUpdate message received for missing component " + String(componentID));
  597. }
  598. break;
  599. case MSG_COMPONENTLATESTDATA:
  600. {
  601. unsigned componentID = msg.ReadNetID();
  602. Component* component = scene_->GetComponent(componentID);
  603. if (component)
  604. {
  605. if (component->ReadLatestDataUpdate(msg))
  606. component->ApplyAttributes();
  607. }
  608. else
  609. {
  610. // Latest data messages may be received out-of-order relative to component creation, so cache if necessary
  611. PODVector<unsigned char>& data = componentLatestData_[componentID];
  612. data.Resize(msg.GetSize());
  613. memcpy(&data[0], msg.GetData(), msg.GetSize());
  614. }
  615. }
  616. break;
  617. case MSG_REMOVECOMPONENT:
  618. {
  619. unsigned componentID = msg.ReadNetID();
  620. Component* component = scene_->GetComponent(componentID);
  621. if (component)
  622. component->Remove();
  623. componentLatestData_.Erase(componentID);
  624. }
  625. break;
  626. default: break;
  627. }
  628. }
  629. void Connection::ProcessPackageDownload(int msgID, MemoryBuffer& msg)
  630. {
  631. switch (msgID)
  632. {
  633. case MSG_REQUESTPACKAGE:
  634. if (!IsClient())
  635. {
  636. LOGWARNING("Received unexpected RequestPackage message from server");
  637. return;
  638. }
  639. else
  640. {
  641. String name = msg.ReadString();
  642. if (!scene_)
  643. {
  644. LOGWARNING("Received a RequestPackage message without an assigned scene from client " + ToString());
  645. return;
  646. }
  647. // The package must be one of those required by the scene
  648. const Vector<SharedPtr<PackageFile> >& packages = scene_->GetRequiredPackageFiles();
  649. for (unsigned i = 0; i < packages.Size(); ++i)
  650. {
  651. PackageFile* package = packages[i];
  652. String packageFullName = package->GetName();
  653. if (!GetFileNameAndExtension(packageFullName).Compare(name, false))
  654. {
  655. StringHash nameHash(name);
  656. // Do not restart upload if already exists
  657. if (uploads_.Contains(nameHash))
  658. {
  659. LOGWARNING("Received a request for package " + name + " already in transfer");
  660. return;
  661. }
  662. // Try to open the file now
  663. SharedPtr<File> file(new File(context_, packageFullName));
  664. if (!file->IsOpen())
  665. {
  666. LOGERROR("Failed to transmit package file " + name);
  667. SendPackageError(name);
  668. return;
  669. }
  670. LOGINFO("Transmitting package file " + name + " to client " + ToString());
  671. uploads_[nameHash].file_ = file;
  672. uploads_[nameHash].fragment_ = 0;
  673. uploads_[nameHash].totalFragments_ = (file->GetSize() + PACKAGE_FRAGMENT_SIZE - 1) / PACKAGE_FRAGMENT_SIZE;
  674. return;
  675. }
  676. }
  677. LOGERROR("Client requested an unexpected package file " + name);
  678. // Send the name hash only to indicate a failed download
  679. SendPackageError(name);
  680. return;
  681. }
  682. break;
  683. case MSG_PACKAGEDATA:
  684. if (IsClient())
  685. {
  686. LOGWARNING("Received unexpected PackageData message from client");
  687. return;
  688. }
  689. else
  690. {
  691. StringHash nameHash = msg.ReadStringHash();
  692. HashMap<StringHash, PackageDownload>::Iterator i = downloads_.Find(nameHash);
  693. // In case of being unable to create the package file into the cache, we will still receive all data from the server.
  694. // Simply disregard it
  695. if (i == downloads_.End())
  696. return;
  697. PackageDownload& download = i->second_;
  698. // If no further data, this is an error reply
  699. if (msg.IsEof())
  700. {
  701. OnPackageDownloadFailed(download.name_);
  702. return;
  703. }
  704. // If file has not yet been opened, try to open now. Prepend the checksum to the filename to allow multiple versions
  705. if (!download.file_)
  706. {
  707. download.file_ = new File(context_,
  708. GetSubsystem<Network>()->GetPackageCacheDir() + ToStringHex(download.checksum_) + "_" + download.name_,
  709. FILE_WRITE);
  710. if (!download.file_->IsOpen())
  711. {
  712. OnPackageDownloadFailed(download.name_);
  713. return;
  714. }
  715. }
  716. // Write the fragment data to the proper index
  717. unsigned char buffer[PACKAGE_FRAGMENT_SIZE];
  718. unsigned index = msg.ReadUInt();
  719. unsigned fragmentSize = msg.GetSize() - msg.GetPosition();
  720. msg.Read(buffer, fragmentSize);
  721. download.file_->Seek(index * PACKAGE_FRAGMENT_SIZE);
  722. download.file_->Write(buffer, fragmentSize);
  723. download.receivedFragments_.Insert(index);
  724. // Check if all fragments received
  725. if (download.receivedFragments_.Size() == download.totalFragments_)
  726. {
  727. LOGINFO("Package " + download.name_ + " downloaded successfully");
  728. // Instantiate the package and add to the resource system, as we will need it to load the scene
  729. download.file_->Close();
  730. GetSubsystem<ResourceCache>()->AddPackageFile(download.file_->GetName(), 0);
  731. // Then start the next download if there are more
  732. downloads_.Erase(i);
  733. if (downloads_.Empty())
  734. OnPackagesReady();
  735. else
  736. {
  737. PackageDownload& nextDownload = downloads_.Begin()->second_;
  738. LOGINFO("Requesting package " + nextDownload.name_ + " from server");
  739. msg_.Clear();
  740. msg_.WriteString(nextDownload.name_);
  741. SendMessage(MSG_REQUESTPACKAGE, true, true, msg_);
  742. nextDownload.initiated_ = true;
  743. }
  744. }
  745. }
  746. break;
  747. default: break;
  748. }
  749. }
  750. void Connection::ProcessIdentity(int msgID, MemoryBuffer& msg)
  751. {
  752. if (!IsClient())
  753. {
  754. LOGWARNING("Received unexpected Identity message from server");
  755. return;
  756. }
  757. identity_ = msg.ReadVariantMap();
  758. using namespace ClientIdentity;
  759. VariantMap eventData = identity_;
  760. eventData[P_CONNECTION] = this;
  761. eventData[P_ALLOW] = true;
  762. SendEvent(E_CLIENTIDENTITY, eventData);
  763. // If connection was denied as a response to the identity event, disconnect now
  764. if (!eventData[P_ALLOW].GetBool())
  765. Disconnect();
  766. }
  767. void Connection::ProcessControls(int msgID, MemoryBuffer& msg)
  768. {
  769. if (!IsClient())
  770. {
  771. LOGWARNING("Received unexpected Controls message from server");
  772. return;
  773. }
  774. Controls newControls;
  775. newControls.buttons_ = msg.ReadUInt();
  776. newControls.yaw_ = msg.ReadFloat();
  777. newControls.pitch_ = msg.ReadFloat();
  778. newControls.extraData_ = msg.ReadVariantMap();
  779. SetControls(newControls);
  780. timeStamp_ = msg.ReadUByte();
  781. // Client may or may not send observer position & rotation for interest management
  782. if (!msg.IsEof())
  783. position_ = msg.ReadVector3();
  784. if (!msg.IsEof())
  785. rotation_ = msg.ReadPackedQuaternion();
  786. }
  787. void Connection::ProcessSceneLoaded(int msgID, MemoryBuffer& msg)
  788. {
  789. if (!IsClient())
  790. {
  791. LOGWARNING("Received unexpected SceneLoaded message from server");
  792. return;
  793. }
  794. if (!scene_)
  795. {
  796. LOGWARNING("Received a SceneLoaded message without an assigned scene from client " + ToString());
  797. return;
  798. }
  799. unsigned checksum = msg.ReadUInt();
  800. if (checksum != scene_->GetChecksum())
  801. {
  802. LOGINFO("Scene checksum error from client " + ToString());
  803. msg_.Clear();
  804. SendMessage(MSG_SCENECHECKSUMERROR, true, true, msg_);
  805. OnSceneLoadFailed();
  806. }
  807. else
  808. {
  809. sceneLoaded_ = true;
  810. using namespace ClientSceneLoaded;
  811. VariantMap& eventData = GetEventDataMap();
  812. eventData[P_CONNECTION] = this;
  813. SendEvent(E_CLIENTSCENELOADED, eventData);
  814. }
  815. }
  816. void Connection::ProcessRemoteEvent(int msgID, MemoryBuffer& msg)
  817. {
  818. using namespace RemoteEventData;
  819. if (msgID == MSG_REMOTEEVENT)
  820. {
  821. StringHash eventType = msg.ReadStringHash();
  822. if (!GetSubsystem<Network>()->CheckRemoteEvent(eventType))
  823. {
  824. LOGWARNING("Discarding not allowed remote event " + eventType.ToString());
  825. return;
  826. }
  827. VariantMap eventData = msg.ReadVariantMap();
  828. eventData[P_CONNECTION] = this;
  829. SendEvent(eventType, eventData);
  830. }
  831. else
  832. {
  833. if (!scene_)
  834. {
  835. LOGERROR("Can not receive remote node event without an assigned scene");
  836. return;
  837. }
  838. unsigned nodeID = msg.ReadNetID();
  839. StringHash eventType = msg.ReadStringHash();
  840. if (!GetSubsystem<Network>()->CheckRemoteEvent(eventType))
  841. {
  842. LOGWARNING("Discarding not allowed remote event " + eventType.ToString());
  843. return;
  844. }
  845. VariantMap eventData = msg.ReadVariantMap();
  846. Node* sender = scene_->GetNode(nodeID);
  847. if (!sender)
  848. {
  849. LOGWARNING("Missing sender for remote node event, discarding");
  850. return;
  851. }
  852. eventData[P_CONNECTION] = this;
  853. sender->SendEvent(eventType, eventData);
  854. }
  855. }
  856. kNet::MessageConnection* Connection::GetMessageConnection() const
  857. {
  858. return const_cast<kNet::MessageConnection*>(connection_.ptr());
  859. }
  860. Scene* Connection::GetScene() const
  861. {
  862. return scene_;
  863. }
  864. bool Connection::IsConnected() const
  865. {
  866. return connection_->GetConnectionState() == kNet::ConnectionOK;
  867. }
  868. float Connection::GetRoundTripTime() const
  869. {
  870. return connection_->RoundTripTime();
  871. }
  872. float Connection::GetLastHeardTime() const
  873. {
  874. return connection_->LastHeardTime();
  875. }
  876. float Connection::GetBytesInPerSec() const
  877. {
  878. return connection_->BytesInPerSec();
  879. }
  880. float Connection::GetBytesOutPerSec() const
  881. {
  882. return connection_->BytesOutPerSec();
  883. }
  884. float Connection::GetPacketsInPerSec() const
  885. {
  886. return connection_->PacketsInPerSec();
  887. }
  888. float Connection::GetPacketsOutPerSec() const
  889. {
  890. return connection_->PacketsOutPerSec();
  891. }
  892. String Connection::ToString() const
  893. {
  894. return GetAddress() + ":" + String(GetPort());
  895. }
  896. unsigned Connection::GetNumDownloads() const
  897. {
  898. return downloads_.Size();
  899. }
  900. const String& Connection::GetDownloadName() const
  901. {
  902. for (HashMap<StringHash, PackageDownload>::ConstIterator i = downloads_.Begin(); i != downloads_.End(); ++i)
  903. {
  904. if (i->second_.initiated_)
  905. return i->second_.name_;
  906. }
  907. return String::EMPTY;
  908. }
  909. float Connection::GetDownloadProgress() const
  910. {
  911. for (HashMap<StringHash, PackageDownload>::ConstIterator i = downloads_.Begin(); i != downloads_.End(); ++i)
  912. {
  913. if (i->second_.initiated_)
  914. return (float)i->second_.receivedFragments_.Size() / (float)i->second_.totalFragments_;
  915. }
  916. return 1.0f;
  917. }
  918. void Connection::SendPackageToClient(PackageFile* package)
  919. {
  920. if (!scene_)
  921. return;
  922. if (!IsClient())
  923. {
  924. LOGERROR("SendPackageToClient can be called on the server only");
  925. return;
  926. }
  927. if (!package)
  928. {
  929. LOGERROR("Null package specified for SendPackageToClient");
  930. return;
  931. }
  932. msg_.Clear();
  933. String filename = GetFileNameAndExtension(package->GetName());
  934. msg_.WriteString(filename);
  935. msg_.WriteUInt(package->GetTotalSize());
  936. msg_.WriteUInt(package->GetChecksum());
  937. SendMessage(MSG_PACKAGEINFO, true, true, msg_);
  938. }
  939. void Connection::ConfigureNetworkSimulator(int latencyMs, float packetLoss)
  940. {
  941. if (connection_)
  942. {
  943. kNet::NetworkSimulator& simulator = connection_->NetworkSendSimulator();
  944. simulator.enabled = latencyMs > 0 || packetLoss > 0.0f;
  945. simulator.constantPacketSendDelay = (float)latencyMs;
  946. simulator.packetLossRate = packetLoss;
  947. }
  948. }
  949. void Connection::HandleAsyncLoadFinished(StringHash eventType, VariantMap& eventData)
  950. {
  951. sceneLoaded_ = true;
  952. msg_.Clear();
  953. msg_.WriteUInt(scene_->GetChecksum());
  954. SendMessage(MSG_SCENELOADED, true, true, msg_);
  955. }
  956. void Connection::HandleComponentRemoved(StringHash eventType, VariantMap& eventData)
  957. {
  958. using namespace ComponentRemoved;
  959. Component* comp = static_cast<Component*>(eventData[P_COMPONENT].GetPtr());
  960. Node* node = static_cast<Node*>(eventData[P_NODE].GetPtr());
  961. unsigned nodeId = node->GetID();
  962. unsigned compId = comp->GetID();
  963. if (sceneState_.nodeStates_.Contains(node->GetID()))
  964. {
  965. NodeReplicationState& nodeState = sceneState_.nodeStates_[node->GetID()];
  966. if (nodeState.componentStates_.Contains(comp->GetID()))
  967. {
  968. ComponentReplicationState& compState = nodeState.componentStates_[comp->GetID()];
  969. compState.component_ = NULL;
  970. }
  971. }
  972. }
  973. void Connection::ProcessNode(unsigned nodeID)
  974. {
  975. // Check that we have not already processed this due to dependency recursion
  976. if (!nodesToProcess_.Erase(nodeID))
  977. return;
  978. // Find replication state for the node
  979. HashMap<unsigned, NodeReplicationState>::Iterator i = sceneState_.nodeStates_.Find(nodeID);
  980. if (i != sceneState_.nodeStates_.End())
  981. {
  982. // Replication state found: the node is either be existing or removed
  983. Node* node = i->second_.node_;
  984. if (!node)
  985. {
  986. msg_.Clear();
  987. msg_.WriteNetID(nodeID);
  988. // Note: we will send MSG_REMOVENODE redundantly for each node in the hierarchy, even if removing the root node
  989. // would be enough. However, this may be better due to the client not possibly having updated parenting
  990. // information at the time of receiving this message
  991. SendMessage(MSG_REMOVENODE, true, true, msg_);
  992. sceneState_.nodeStates_.Erase(nodeID);
  993. }
  994. else
  995. ProcessExistingNode(node, i->second_);
  996. }
  997. else
  998. {
  999. // Replication state not found: this is a new node
  1000. Node* node = scene_->GetNode(nodeID);
  1001. if (node)
  1002. ProcessNewNode(node);
  1003. else
  1004. {
  1005. // Did not find the new node (may have been created, then removed immediately): erase from dirty set.
  1006. sceneState_.dirtyNodes_.Erase(nodeID);
  1007. }
  1008. }
  1009. }
  1010. void Connection::ProcessNewNode(Node* node)
  1011. {
  1012. // Process depended upon nodes first, if they are dirty
  1013. const PODVector<Node*>& dependencyNodes = node->GetDependencyNodes();
  1014. for (PODVector<Node*>::ConstIterator i = dependencyNodes.Begin(); i != dependencyNodes.End(); ++i)
  1015. {
  1016. unsigned nodeID = (*i)->GetID();
  1017. if (sceneState_.dirtyNodes_.Contains(nodeID))
  1018. ProcessNode(nodeID);
  1019. }
  1020. msg_.Clear();
  1021. msg_.WriteNetID(node->GetID());
  1022. NodeReplicationState& nodeState = sceneState_.nodeStates_[node->GetID()];
  1023. nodeState.connection_ = this;
  1024. nodeState.sceneState_ = &sceneState_;
  1025. nodeState.node_ = node;
  1026. node->AddReplicationState(&nodeState);
  1027. // Write node's attributes
  1028. node->WriteInitialDeltaUpdate(msg_, timeStamp_);
  1029. // Write node's user variables
  1030. const VariantMap& vars = node->GetVars();
  1031. msg_.WriteVLE(vars.Size());
  1032. for (VariantMap::ConstIterator i = vars.Begin(); i != vars.End(); ++i)
  1033. {
  1034. msg_.WriteStringHash(i->first_);
  1035. msg_.WriteVariant(i->second_);
  1036. }
  1037. // Write node's components
  1038. msg_.WriteVLE(node->GetNumNetworkComponents());
  1039. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  1040. for (unsigned i = 0; i < components.Size(); ++i)
  1041. {
  1042. Component* component = components[i];
  1043. // Check if component is not to be replicated
  1044. if (component->GetID() >= FIRST_LOCAL_ID)
  1045. continue;
  1046. ComponentReplicationState& componentState = nodeState.componentStates_[component->GetID()];
  1047. componentState.connection_ = this;
  1048. componentState.nodeState_ = &nodeState;
  1049. componentState.component_ = component;
  1050. component->AddReplicationState(&componentState);
  1051. msg_.WriteStringHash(component->GetType());
  1052. msg_.WriteNetID(component->GetID());
  1053. component->WriteInitialDeltaUpdate(msg_, timeStamp_);
  1054. }
  1055. SendMessage(MSG_CREATENODE, true, true, msg_);
  1056. nodeState.markedDirty_ = false;
  1057. sceneState_.dirtyNodes_.Erase(node->GetID());
  1058. }
  1059. void Connection::ProcessExistingNode(Node* node, NodeReplicationState& nodeState)
  1060. {
  1061. // Process depended upon nodes first, if they are dirty
  1062. const PODVector<Node*>& dependencyNodes = node->GetDependencyNodes();
  1063. for (PODVector<Node*>::ConstIterator i = dependencyNodes.Begin(); i != dependencyNodes.End(); ++i)
  1064. {
  1065. unsigned nodeID = (*i)->GetID();
  1066. if (sceneState_.dirtyNodes_.Contains(nodeID))
  1067. ProcessNode(nodeID);
  1068. }
  1069. // Check from the interest management component, if exists, whether should update
  1070. /// \todo Searching for the component is a potential CPU hotspot. It should be cached
  1071. NetworkPriority* priority = node->GetComponent<NetworkPriority>();
  1072. if (priority && (!priority->GetAlwaysUpdateOwner() || node->GetOwner() != this))
  1073. {
  1074. float distance = (node->GetWorldPosition() - position_).Length();
  1075. if (!priority->CheckUpdate(distance, nodeState.priorityAcc_))
  1076. return;
  1077. }
  1078. // Check if attributes have changed
  1079. if (nodeState.dirtyAttributes_.Count() || nodeState.dirtyVars_.Size())
  1080. {
  1081. const Vector<AttributeInfo>* attributes = node->GetNetworkAttributes();
  1082. unsigned numAttributes = attributes->Size();
  1083. bool hasLatestData = false;
  1084. for (unsigned i = 0; i < numAttributes; ++i)
  1085. {
  1086. if (nodeState.dirtyAttributes_.IsSet(i) && (attributes->At(i).mode_ & AM_LATESTDATA))
  1087. {
  1088. hasLatestData = true;
  1089. nodeState.dirtyAttributes_.Clear(i);
  1090. }
  1091. }
  1092. // Send latestdata message if necessary
  1093. if (hasLatestData)
  1094. {
  1095. msg_.Clear();
  1096. msg_.WriteNetID(node->GetID());
  1097. node->WriteLatestDataUpdate(msg_, timeStamp_);
  1098. SendMessage(MSG_NODELATESTDATA, true, false, msg_, node->GetID());
  1099. }
  1100. // Send deltaupdate if remaining dirty bits, or vars have changed
  1101. if (nodeState.dirtyAttributes_.Count() || nodeState.dirtyVars_.Size())
  1102. {
  1103. msg_.Clear();
  1104. msg_.WriteNetID(node->GetID());
  1105. node->WriteDeltaUpdate(msg_, nodeState.dirtyAttributes_, timeStamp_);
  1106. // Write changed variables
  1107. msg_.WriteVLE(nodeState.dirtyVars_.Size());
  1108. const VariantMap& vars = node->GetVars();
  1109. for (HashSet<StringHash>::ConstIterator i = nodeState.dirtyVars_.Begin(); i != nodeState.dirtyVars_.End(); ++i)
  1110. {
  1111. VariantMap::ConstIterator j = vars.Find(*i);
  1112. if (j != vars.End())
  1113. {
  1114. msg_.WriteStringHash(j->first_);
  1115. msg_.WriteVariant(j->second_);
  1116. }
  1117. else
  1118. {
  1119. // Variable has been marked dirty, but is removed (which is unsupported): send a dummy variable in place
  1120. LOGWARNING("Sending dummy user variable as original value was removed");
  1121. msg_.WriteStringHash(StringHash());
  1122. msg_.WriteVariant(Variant::EMPTY);
  1123. }
  1124. }
  1125. SendMessage(MSG_NODEDELTAUPDATE, true, true, msg_);
  1126. nodeState.dirtyAttributes_.ClearAll();
  1127. nodeState.dirtyVars_.Clear();
  1128. }
  1129. }
  1130. // Check for removed or changed components
  1131. for (HashMap<unsigned, ComponentReplicationState>::Iterator i = nodeState.componentStates_.Begin();
  1132. i != nodeState.componentStates_.End();)
  1133. {
  1134. HashMap<unsigned, ComponentReplicationState>::Iterator current = i++;
  1135. ComponentReplicationState& componentState = current->second_;
  1136. Component* component = componentState.component_;
  1137. if (!component)
  1138. {
  1139. // Removed component
  1140. msg_.Clear();
  1141. msg_.WriteNetID(current->first_);
  1142. SendMessage(MSG_REMOVECOMPONENT, true, true, msg_);
  1143. nodeState.componentStates_.Erase(current);
  1144. }
  1145. else
  1146. {
  1147. // Existing component. Check if attributes have changed
  1148. if (componentState.dirtyAttributes_.Count())
  1149. {
  1150. const Vector<AttributeInfo>* attributes = component->GetNetworkAttributes();
  1151. unsigned numAttributes = attributes->Size();
  1152. bool hasLatestData = false;
  1153. for (unsigned i = 0; i < numAttributes; ++i)
  1154. {
  1155. if (componentState.dirtyAttributes_.IsSet(i) && (attributes->At(i).mode_ & AM_LATESTDATA))
  1156. {
  1157. hasLatestData = true;
  1158. componentState.dirtyAttributes_.Clear(i);
  1159. }
  1160. }
  1161. // Send latestdata message if necessary
  1162. if (hasLatestData)
  1163. {
  1164. msg_.Clear();
  1165. msg_.WriteNetID(component->GetID());
  1166. component->WriteLatestDataUpdate(msg_, timeStamp_);
  1167. SendMessage(MSG_COMPONENTLATESTDATA, true, false, msg_, component->GetID());
  1168. }
  1169. // Send deltaupdate if remaining dirty bits
  1170. if (componentState.dirtyAttributes_.Count())
  1171. {
  1172. msg_.Clear();
  1173. msg_.WriteNetID(component->GetID());
  1174. component->WriteDeltaUpdate(msg_, componentState.dirtyAttributes_, timeStamp_);
  1175. SendMessage(MSG_COMPONENTDELTAUPDATE, true, true, msg_);
  1176. componentState.dirtyAttributes_.ClearAll();
  1177. }
  1178. }
  1179. }
  1180. }
  1181. // Check for new components
  1182. if (nodeState.componentStates_.Size() != node->GetNumNetworkComponents())
  1183. {
  1184. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  1185. for (unsigned i = 0; i < components.Size(); ++i)
  1186. {
  1187. Component* component = components[i];
  1188. // Check if component is not to be replicated
  1189. if (component->GetID() >= FIRST_LOCAL_ID)
  1190. continue;
  1191. HashMap<unsigned, ComponentReplicationState>::Iterator j = nodeState.componentStates_.Find(component->GetID());
  1192. if (j == nodeState.componentStates_.End())
  1193. {
  1194. // New component
  1195. ComponentReplicationState& componentState = nodeState.componentStates_[component->GetID()];
  1196. componentState.connection_ = this;
  1197. componentState.nodeState_ = &nodeState;
  1198. componentState.component_ = component;
  1199. component->AddReplicationState(&componentState);
  1200. msg_.Clear();
  1201. msg_.WriteNetID(node->GetID());
  1202. msg_.WriteStringHash(component->GetType());
  1203. msg_.WriteNetID(component->GetID());
  1204. component->WriteInitialDeltaUpdate(msg_, timeStamp_);
  1205. SendMessage(MSG_CREATECOMPONENT, true, true, msg_);
  1206. }
  1207. }
  1208. }
  1209. nodeState.markedDirty_ = false;
  1210. sceneState_.dirtyNodes_.Erase(node->GetID());
  1211. }
  1212. bool Connection::RequestNeededPackages(unsigned numPackages, MemoryBuffer& msg)
  1213. {
  1214. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1215. const String& packageCacheDir = GetSubsystem<Network>()->GetPackageCacheDir();
  1216. Vector<SharedPtr<PackageFile> > packages = cache->GetPackageFiles();
  1217. Vector<String> downloadedPackages;
  1218. bool packagesScanned = false;
  1219. for (unsigned i = 0; i < numPackages; ++i)
  1220. {
  1221. String name = msg.ReadString();
  1222. unsigned fileSize = msg.ReadUInt();
  1223. unsigned checksum = msg.ReadUInt();
  1224. String checksumString = ToStringHex(checksum);
  1225. bool found = false;
  1226. // Check first the resource cache
  1227. for (unsigned j = 0; j < packages.Size(); ++j)
  1228. {
  1229. PackageFile* package = packages[j];
  1230. if (!GetFileNameAndExtension(package->GetName()).Compare(name, false) && package->GetTotalSize() == fileSize &&
  1231. package->GetChecksum() == checksum)
  1232. {
  1233. found = true;
  1234. break;
  1235. }
  1236. }
  1237. if (found)
  1238. continue;
  1239. if (!packagesScanned)
  1240. {
  1241. if (packageCacheDir.Empty())
  1242. {
  1243. LOGERROR("Can not check/download required packages, as package cache directory is not set");
  1244. return false;
  1245. }
  1246. GetSubsystem<FileSystem>()->ScanDir(downloadedPackages, packageCacheDir, "*.*", SCAN_FILES, false);
  1247. packagesScanned = true;
  1248. }
  1249. // Then the download cache
  1250. for (unsigned j = 0; j < downloadedPackages.Size(); ++j)
  1251. {
  1252. const String& fileName = downloadedPackages[j];
  1253. // In download cache, package file name format is checksum_packagename
  1254. if (!fileName.Find(checksumString) && !fileName.Substring(9).Compare(name, false))
  1255. {
  1256. // Name matches. Check file size and actual checksum to be sure
  1257. SharedPtr<PackageFile> newPackage(new PackageFile(context_, packageCacheDir + fileName));
  1258. if (newPackage->GetTotalSize() == fileSize && newPackage->GetChecksum() == checksum)
  1259. {
  1260. // Add the package to the resource system now, as we will need it to load the scene
  1261. cache->AddPackageFile(newPackage, 0);
  1262. found = true;
  1263. break;
  1264. }
  1265. }
  1266. }
  1267. // Package not found, need to request a download
  1268. if (!found)
  1269. RequestPackage(name, fileSize, checksum);
  1270. }
  1271. return true;
  1272. }
  1273. void Connection::RequestPackage(const String& name, unsigned fileSize, unsigned checksum)
  1274. {
  1275. StringHash nameHash(name);
  1276. if (downloads_.Contains(nameHash))
  1277. return; // Download already exists
  1278. PackageDownload& download = downloads_[nameHash];
  1279. download.name_ = name;
  1280. download.totalFragments_ = (fileSize + PACKAGE_FRAGMENT_SIZE - 1) / PACKAGE_FRAGMENT_SIZE;
  1281. download.checksum_ = checksum;
  1282. // Start download now only if no existing downloads, else wait for the existing ones to finish
  1283. if (downloads_.Size() == 1)
  1284. {
  1285. LOGINFO("Requesting package " + name + " from server");
  1286. msg_.Clear();
  1287. msg_.WriteString(name);
  1288. SendMessage(MSG_REQUESTPACKAGE, true, true, msg_);
  1289. download.initiated_ = true;
  1290. }
  1291. }
  1292. void Connection::SendPackageError(const String& name)
  1293. {
  1294. msg_.Clear();
  1295. msg_.WriteStringHash(name);
  1296. SendMessage(MSG_PACKAGEDATA, true, false, msg_);
  1297. }
  1298. void Connection::OnSceneLoadFailed()
  1299. {
  1300. sceneLoaded_ = false;
  1301. using namespace NetworkSceneLoadFailed;
  1302. VariantMap& eventData = GetEventDataMap();
  1303. eventData[P_CONNECTION] = this;
  1304. SendEvent(E_NETWORKSCENELOADFAILED, eventData);
  1305. }
  1306. void Connection::OnPackageDownloadFailed(const String& name)
  1307. {
  1308. LOGERROR("Download of package " + name + " failed");
  1309. // As one package failed, we can not join the scene in any case. Clear the downloads
  1310. downloads_.Clear();
  1311. OnSceneLoadFailed();
  1312. }
  1313. void Connection::OnPackagesReady()
  1314. {
  1315. if (!scene_)
  1316. return;
  1317. // If sceneLoaded_ is true, we may have received additional package downloads while already joined in a scene.
  1318. // In that case the scene should not be loaded.
  1319. if (sceneLoaded_)
  1320. return;
  1321. if (sceneFileName_.Empty())
  1322. {
  1323. // If the scene filename is empty, just clear the scene of all existing replicated content, and send the loaded reply
  1324. scene_->Clear(true, false);
  1325. sceneLoaded_ = true;
  1326. msg_.Clear();
  1327. msg_.WriteUInt(scene_->GetChecksum());
  1328. SendMessage(MSG_SCENELOADED, true, true, msg_);
  1329. }
  1330. else
  1331. {
  1332. // Otherwise start the async loading process
  1333. String extension = GetExtension(sceneFileName_);
  1334. SharedPtr<File> file = GetSubsystem<ResourceCache>()->GetFile(sceneFileName_);
  1335. bool success;
  1336. if (extension == ".xml")
  1337. success = scene_->LoadAsyncXML(file);
  1338. else
  1339. success = scene_->LoadAsync(file);
  1340. if (!success)
  1341. OnSceneLoadFailed();
  1342. }
  1343. }
  1344. void Connection::ProcessPackageInfo(int msgID, MemoryBuffer& msg)
  1345. {
  1346. if (!scene_)
  1347. return;
  1348. if (IsClient())
  1349. {
  1350. LOGWARNING("Received unexpected packages info message from client");
  1351. return;
  1352. }
  1353. RequestNeededPackages(1, msg);
  1354. }
  1355. // Expose control methods for current controls
  1356. void Connection::SetControlButtons(unsigned buttons, bool down)
  1357. {
  1358. controls_.Set(buttons,down);
  1359. }
  1360. /// Check if a button is held down.
  1361. bool Connection::IsControlButtonDown(unsigned button) const
  1362. {
  1363. return (controls_.IsDown(button));
  1364. }
  1365. void Connection::SetControlDataInt(const String &key, int value) {
  1366. controls_.extraData_[key] = value;
  1367. }
  1368. int Connection::GetControlDataInt(const String &key) {
  1369. return controls_.extraData_[key].GetInt();
  1370. }
  1371. void Connection::SendStringMessage(const String& message)
  1372. {
  1373. // Send the identity map now
  1374. VectorBuffer msg;
  1375. msg.WriteString(message);
  1376. SendMessage(MSG_STRING, true, true, msg);
  1377. }
  1378. void Connection::ProcessStringMessage(int msgID, MemoryBuffer &msg) {
  1379. using namespace NetworkMessage;
  1380. VariantMap &eventData = GetEventDataMap();
  1381. eventData[P_MESSAGEID] = (int) msgID;
  1382. eventData[P_CONNECTION] = this;
  1383. eventData[P_DATA] = msg.ReadString();
  1384. SendEvent(E_NETWORKSTRINGMESSAGE, eventData);
  1385. }
  1386. }