Connection.cpp 53 KB

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