Connection.cpp 53 KB

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