Connection.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Component.h"
  25. #include "Connection.h"
  26. #include "File.h"
  27. #include "FileSystem.h"
  28. #include "Log.h"
  29. #include "MemoryBuffer.h"
  30. #include "NetworkEvents.h"
  31. #include "Protocol.h"
  32. #include "Scene.h"
  33. #include "SceneEvents.h"
  34. #include <kNet.h>
  35. #include "DebugNew.h"
  36. OBJECTTYPESTATIC(Connection);
  37. Connection::Connection(Context* context, bool isClient, kNet::SharedPtr<kNet::MessageConnection> connection) :
  38. Object(context),
  39. connection_(connection),
  40. frameNumber_(0),
  41. isClient_(isClient),
  42. connectPending_(false),
  43. sceneLoaded_(false)
  44. {
  45. }
  46. Connection::~Connection()
  47. {
  48. // Reset owner from the scene, as this connection is about to be destroyed
  49. if (scene_)
  50. scene_->ResetOwner(this);
  51. }
  52. void Connection::SendMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes)
  53. {
  54. // Make sure not to use kNet internal message ID's
  55. if (msgID <= 0x4 || msgID >= 0x3ffffffe)
  56. {
  57. LOGERROR("Can not send message with reserved ID");
  58. return;
  59. }
  60. connection_->SendMessage(msgID, reliable, inOrder, 0, 0, (const char*)data, numBytes);
  61. }
  62. void Connection::SendMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg)
  63. {
  64. SendMessage(msgID, reliable, inOrder, msg.GetData(), msg.GetSize());
  65. }
  66. void Connection::SendMessage(int msgID, unsigned contentID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes)
  67. {
  68. // Make sure not to use kNet internal message ID's
  69. if (msgID <= 0x4 || msgID >= 0x3ffffffe)
  70. {
  71. LOGERROR("Can not send message with reserved ID");
  72. return;
  73. }
  74. connection_->SendMessage(msgID, reliable, inOrder, 0, contentID, (const char*)data, numBytes);
  75. }
  76. void Connection::SendMessage(int msgID, unsigned contentID, bool reliable, bool inOrder, const VectorBuffer& msg)
  77. {
  78. SendMessage(msgID, contentID, reliable, inOrder, msg.GetData(), msg.GetSize());
  79. }
  80. void Connection::SendRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData)
  81. {
  82. msg_.Clear();
  83. msg_.WriteStringHash(eventType);
  84. msg_.WriteVariantMap(eventData);
  85. SendMessage(MSG_REMOTEEVENT, true, inOrder, msg_);
  86. }
  87. void Connection::SendRemoteEvent(Node* receiver, StringHash eventType, bool inOrder, const VariantMap& eventData)
  88. {
  89. if (!receiver)
  90. {
  91. LOGERROR("Null node for remote node event");
  92. return;
  93. }
  94. if (receiver->GetScene() != scene_)
  95. {
  96. LOGERROR("Node is not in the connection's scene, can not send remote node event");
  97. return;
  98. }
  99. if (receiver->GetID() >= FIRST_LOCAL_ID)
  100. {
  101. LOGERROR("Node has a local ID, can not send remote node event");
  102. return;
  103. }
  104. msg_.Clear();
  105. msg_.WriteVLE(receiver->GetID());
  106. msg_.WriteStringHash(eventType);
  107. msg_.WriteVariantMap(eventData);
  108. SendMessage(MSG_REMOTENODEEVENT, true, inOrder, msg_);
  109. }
  110. void Connection::SetScene(Scene* newScene)
  111. {
  112. if (scene_ == newScene)
  113. return;
  114. // Reset the owner reference from the previous scene's nodes
  115. if (scene_)
  116. scene_->ResetOwner(this);
  117. scene_ = newScene;
  118. sceneLoaded_ = false;
  119. UnsubscribeFromEvent(E_ASYNCLOADFINISHED);
  120. if (!scene_)
  121. return;
  122. if (isClient_)
  123. {
  124. sceneState_.Clear();
  125. // When scene is assigned on the server, instruct the client to load it
  126. /// \todo Download package(s) needed for the scene, if they do not exist already on the client
  127. msg_.Clear();
  128. msg_.WriteString(scene_->GetFileName());
  129. SendMessage(MSG_LOADSCENE, true, true, msg_);
  130. }
  131. else
  132. {
  133. // Make sure there is no existing async loading
  134. scene_->StopAsyncLoading();
  135. SubscribeToEvent(scene_, E_ASYNCLOADFINISHED, HANDLER(Connection, HandleAsyncLoadFinished));
  136. }
  137. }
  138. void Connection::SetIdentity(const VariantMap& identity)
  139. {
  140. identity_ = identity;
  141. }
  142. void Connection::SetControls(const Controls& newControls)
  143. {
  144. previousControls_ = controls_;
  145. controls_ = newControls;
  146. }
  147. void Connection::SetConnectPending(bool connectPending)
  148. {
  149. connectPending_ = connectPending;
  150. }
  151. void Connection::Disconnect(int waitMSec)
  152. {
  153. connection_->Disconnect(waitMSec);
  154. }
  155. void Connection::SendServerUpdate()
  156. {
  157. if (!isClient_ || !scene_ || !sceneLoaded_)
  158. return;
  159. const Map<unsigned, Node*>& nodes = scene_->GetAllNodes();
  160. // Check for new or changed nodes
  161. // Start from the root node (scene) so that the scene-wide components get sent first
  162. processedNodes_.Clear();
  163. ProcessNode(scene_);
  164. // Then go through the rest of the nodes
  165. for (Map<unsigned, Node*>::ConstIterator i = nodes.Begin(); i != nodes.End() && i->first_ < FIRST_LOCAL_ID; ++i)
  166. ProcessNode(i->second_);
  167. // Check for removed nodes
  168. for (Map<unsigned, NodeReplicationState>::Iterator i = sceneState_.Begin(); i != sceneState_.End();)
  169. {
  170. Map<unsigned, NodeReplicationState>::Iterator current = i++;
  171. if (current->second_.frameNumber_ != frameNumber_)
  172. {
  173. msg_.Clear();
  174. msg_.WriteVLE(current->first_);
  175. SendMessage(MSG_REMOVENODE, true, true, msg_);
  176. sceneState_.Erase(current);
  177. }
  178. }
  179. ++frameNumber_;
  180. }
  181. void Connection::SendClientUpdate()
  182. {
  183. if (isClient_ || !scene_ || !sceneLoaded_)
  184. return;
  185. msg_.Clear();
  186. msg_.WriteUInt(controls_.buttons_);
  187. msg_.WriteFloat(controls_.yaw_);
  188. msg_.WriteFloat(controls_.pitch_);
  189. msg_.WriteVariantMap(controls_.extraData_);
  190. SendMessage(MSG_CONTROLS, CONTROLS_CONTENT_ID, false, false, msg_);
  191. }
  192. void Connection::ProcessPendingLatestData()
  193. {
  194. if (!scene_)
  195. return;
  196. // Iterate through pending node data and see if we can find the nodes now
  197. for (Map<unsigned, PODVector<unsigned char> >::Iterator i = nodeLatestData_.Begin(); i != nodeLatestData_.End();)
  198. {
  199. Map<unsigned, PODVector<unsigned char> >::Iterator current = i++;
  200. Node* node = scene_->GetNodeByID(current->first_);
  201. if (node)
  202. {
  203. MemoryBuffer msg(current->second_);
  204. msg.ReadVLE(); // Skip the node ID
  205. node->ReadLatestDataUpdate(msg);
  206. nodeLatestData_.Erase(current);
  207. }
  208. }
  209. // Iterate through pending component data and see if we can find the components now
  210. for (Map<unsigned, PODVector<unsigned char> >::Iterator i = componentLatestData_.Begin(); i != componentLatestData_.End();)
  211. {
  212. Map<unsigned, PODVector<unsigned char> >::Iterator current = i++;
  213. Component* component = scene_->GetComponentByID(current->first_);
  214. if (component)
  215. {
  216. MemoryBuffer msg(current->second_);
  217. msg.ReadVLE(); // Skip the component ID
  218. component->ReadLatestDataUpdate(msg);
  219. component->FinishUpdate();
  220. componentLatestData_.Erase(current);
  221. }
  222. }
  223. }
  224. void Connection::ProcessLoadScene(int msgID, MemoryBuffer& msg)
  225. {
  226. if (IsClient())
  227. {
  228. LOGWARNING("Received unexpected LoadScene message from client " + ToString());
  229. return;
  230. }
  231. if (!scene_)
  232. {
  233. LOGERROR("Can not handle LoadScene message without an assigned scene");
  234. return;
  235. }
  236. String fileName = msg.ReadString();
  237. // Make sure there is no existing async loading, and clear previous pending latest data if any
  238. scene_->StopAsyncLoading();
  239. nodeLatestData_.Clear();
  240. componentLatestData_.Clear();
  241. if (fileName.Empty())
  242. {
  243. scene_->Clear();
  244. // If filename is empty, can send the scene loaded reply immediately
  245. VectorBuffer replyMsg;
  246. replyMsg.WriteUInt(scene_->GetChecksum());
  247. SendMessage(MSG_SCENELOADED, true, true, replyMsg);
  248. }
  249. else
  250. {
  251. // Otherwise start the async loading process
  252. String extension = GetExtension(fileName);
  253. SharedPtr<File> file(new File(context_, fileName));
  254. bool success;
  255. if (extension == ".xml")
  256. success = scene_->LoadAsyncXML(file);
  257. else
  258. success = scene_->LoadAsync(file);
  259. if (!success)
  260. {
  261. using namespace NetworkSceneLoadFailed;
  262. VariantMap eventData;
  263. eventData[P_CONNECTION] = (void*)this;
  264. SendEvent(E_NETWORKSCENELOADFAILED, eventData);
  265. }
  266. }
  267. }
  268. void Connection::ProcessSceneChecksumError(int msgID, MemoryBuffer& msg)
  269. {
  270. if (IsClient())
  271. {
  272. LOGWARNING("Received unexpected SceneChecksumError message from client " + ToString());
  273. return;
  274. }
  275. using namespace NetworkSceneLoadFailed;
  276. VariantMap eventData;
  277. eventData[P_CONNECTION] = (void*)this;
  278. SendEvent(E_NETWORKSCENELOADFAILED, eventData);
  279. }
  280. void Connection::ProcessSceneUpdate(int msgID, MemoryBuffer& msg)
  281. {
  282. if (IsClient())
  283. {
  284. LOGWARNING("Received unexpected SceneUpdate message from client " + ToString());
  285. return;
  286. }
  287. if (!scene_)
  288. return;
  289. switch (msgID)
  290. {
  291. case MSG_CREATENODE:
  292. {
  293. unsigned nodeID = msg.ReadVLE();
  294. // In case of the root node (scene), it may already exist. Do not create in that case
  295. Node* node = scene_->GetNodeByID(nodeID);
  296. if (!node)
  297. {
  298. // Add initially to the root level. May be moved later
  299. node = scene_->CreateChild(nodeID, false);
  300. }
  301. // Read initial attributes
  302. node->ReadDeltaUpdate(msg, deltaUpdateBits_);
  303. // Read initial user variables
  304. unsigned numVars = msg.ReadVLE();
  305. VariantMap& vars = node->GetVars();
  306. while (numVars)
  307. {
  308. --numVars;
  309. ShortStringHash key = msg.ReadShortStringHash();
  310. Variant value = msg.ReadVariant();
  311. vars[key] = value;
  312. }
  313. // Read components
  314. unsigned numComponents = msg.ReadVLE();
  315. while (numComponents)
  316. {
  317. --numComponents;
  318. ShortStringHash type = msg.ReadShortStringHash();
  319. unsigned componentID = msg.ReadVLE();
  320. // Check if the component by this ID and type already exists in this node
  321. Component* component = scene_->GetComponentByID(componentID);
  322. if (!component || component->GetType() != type || component->GetNode() != node)
  323. {
  324. if (component)
  325. component->Remove();
  326. component = node->CreateComponent(type, componentID, false);
  327. }
  328. // If was unable to create the component, would desync the message and therefore have to abort
  329. if (!component)
  330. {
  331. LOGERROR("CreateNode message parsing aborted due to unknown component " + type.ToString());
  332. return;
  333. }
  334. // Read initial attributes, then perform finalization
  335. component->ReadDeltaUpdate(msg, deltaUpdateBits_);
  336. component->FinishUpdate();
  337. }
  338. }
  339. break;
  340. case MSG_NODEDELTAUPDATE:
  341. {
  342. unsigned nodeID = msg.ReadVLE();
  343. Node* node = scene_->GetNodeByID(nodeID);
  344. if (node)
  345. {
  346. node->ReadDeltaUpdate(msg, deltaUpdateBits_);
  347. unsigned changedVars = msg.ReadVLE();
  348. VariantMap& vars = node->GetVars();
  349. while (changedVars)
  350. {
  351. --changedVars;
  352. ShortStringHash key = msg.ReadShortStringHash();
  353. Variant value = msg.ReadVariant();
  354. vars[key] = value;
  355. }
  356. }
  357. else
  358. LOGWARNING("NodeDeltaUpdate message received for missing node " + String(nodeID));
  359. }
  360. break;
  361. case MSG_NODELATESTDATA:
  362. {
  363. unsigned nodeID = msg.ReadVLE();
  364. Node* node = scene_->GetNodeByID(nodeID);
  365. if (node)
  366. node->ReadLatestDataUpdate(msg);
  367. else
  368. {
  369. // Latest data messages may be received out-of-order relative to node creation, so cache if necessary
  370. PODVector<unsigned char>& data = nodeLatestData_[nodeID];
  371. data.Resize(msg.GetSize());
  372. memcpy(&data[0], msg.GetData(), msg.GetSize());
  373. }
  374. }
  375. break;
  376. case MSG_REMOVENODE:
  377. {
  378. unsigned nodeID = msg.ReadVLE();
  379. Node* node = scene_->GetNodeByID(nodeID);
  380. if (node)
  381. node->Remove();
  382. else
  383. LOGWARNING("RemoveNode message received for missing node " + String(nodeID));
  384. nodeLatestData_.Erase(nodeID);
  385. }
  386. break;
  387. case MSG_CREATECOMPONENT:
  388. {
  389. unsigned nodeID = msg.ReadVLE();
  390. Node* node = scene_->GetNodeByID(nodeID);
  391. if (node)
  392. {
  393. ShortStringHash type = msg.ReadShortStringHash();
  394. unsigned componentID = msg.ReadVLE();
  395. // Check if the component by this ID and type already exists in this node
  396. Component* component = scene_->GetComponentByID(componentID);
  397. if (!component || component->GetType() != type || component->GetNode() != node)
  398. {
  399. if (component)
  400. component->Remove();
  401. component = node->CreateComponent(type, componentID, false);
  402. }
  403. // If was unable to create the component, would desync the message and therefore have to abort
  404. if (!component)
  405. {
  406. LOGERROR("CreateComponent message parsing aborted due to unknown component " + type.ToString());
  407. return;
  408. }
  409. // Read initial attributes, then perform finalization
  410. component->ReadDeltaUpdate(msg, deltaUpdateBits_);
  411. component->FinishUpdate();
  412. }
  413. else
  414. LOGWARNING("CreateComponent message received for missing node " + String(nodeID));
  415. }
  416. break;
  417. case MSG_COMPONENTDELTAUPDATE:
  418. {
  419. unsigned componentID = msg.ReadVLE();
  420. Component* component = scene_->GetComponentByID(componentID);
  421. if (component)
  422. {
  423. component->ReadDeltaUpdate(msg, deltaUpdateBits_);
  424. component->FinishUpdate();
  425. }
  426. else
  427. LOGWARNING("ComponentDeltaUpdate message received for missing component " + String(componentID));
  428. }
  429. break;
  430. case MSG_COMPONENTLATESTDATA:
  431. {
  432. unsigned componentID = msg.ReadVLE();
  433. Component* component = scene_->GetComponentByID(componentID);
  434. if (component)
  435. {
  436. component->ReadLatestDataUpdate(msg);
  437. component->FinishUpdate();
  438. }
  439. else
  440. {
  441. // Latest data messages may be received out-of-order relative to component creation, so cache if necessary
  442. PODVector<unsigned char>& data = componentLatestData_[componentID];
  443. data.Resize(msg.GetSize());
  444. memcpy(&data[0], msg.GetData(), msg.GetSize());
  445. }
  446. }
  447. break;
  448. case MSG_REMOVECOMPONENT:
  449. {
  450. unsigned componentID = msg.ReadVLE();
  451. Component* component = scene_->GetComponentByID(componentID);
  452. if (component)
  453. component->Remove();
  454. else
  455. LOGWARNING("RemoveComponent message received for missing component " + String(componentID));
  456. componentLatestData_.Erase(componentID);
  457. }
  458. break;
  459. }
  460. }
  461. void Connection::ProcessIdentity(int msgID, MemoryBuffer& msg)
  462. {
  463. if (!IsClient())
  464. {
  465. LOGWARNING("Received unexpected Identity message from server");
  466. return;
  467. }
  468. identity_ = msg.ReadVariantMap();
  469. using namespace ClientIdentity;
  470. VariantMap eventData = identity_;
  471. eventData[P_CONNECTION] = (void*)this;
  472. eventData[P_ALLOW] = true;
  473. SendEvent(E_CLIENTIDENTITY, eventData);
  474. // If connection was denied as a response to the identity event, disconnect now
  475. if (!eventData[P_ALLOW].GetBool())
  476. Disconnect();
  477. }
  478. void Connection::ProcessControls(int msgID, MemoryBuffer& msg)
  479. {
  480. if (!IsClient())
  481. {
  482. LOGWARNING("Received unexpected Controls message from server");
  483. return;
  484. }
  485. Controls newControls;
  486. newControls.buttons_ = msg.ReadUInt();
  487. newControls.yaw_ = msg.ReadFloat();
  488. newControls.pitch_ = msg.ReadFloat();
  489. newControls.extraData_ = msg.ReadVariantMap();
  490. SetControls(newControls);
  491. }
  492. void Connection::ProcessSceneLoaded(int msgID, MemoryBuffer& msg)
  493. {
  494. if (!IsClient())
  495. {
  496. LOGWARNING("Received unexpected SceneLoaded message from server");
  497. return;
  498. }
  499. if (!scene_)
  500. {
  501. LOGWARNING("Received a SceneLoaded message without an assigned scene from client " + ToString());
  502. return;
  503. }
  504. unsigned checksum = msg.ReadUInt();
  505. if (checksum != scene_->GetChecksum())
  506. {
  507. VectorBuffer replyMsg;
  508. SendMessage(MSG_SCENECHECKSUMERROR, true, true, replyMsg);
  509. using namespace NetworkSceneLoadFailed;
  510. VariantMap eventData;
  511. eventData[P_CONNECTION] = (void*)this;
  512. SendEvent(E_NETWORKSCENELOADFAILED, eventData);
  513. }
  514. else
  515. {
  516. sceneLoaded_ = true;
  517. using namespace ClientSceneLoaded;
  518. VariantMap eventData;
  519. eventData[P_CONNECTION] = (void*)this;
  520. SendEvent(E_CLIENTSCENELOADED, eventData);
  521. }
  522. }
  523. void Connection::ProcessRemoteEvent(int msgID, MemoryBuffer& msg)
  524. {
  525. /// \todo Check whether the remote event is allowed based on a black- or whitelist
  526. if (msgID == MSG_REMOTEEVENT)
  527. {
  528. StringHash eventType = msg.ReadStringHash();
  529. VariantMap eventData = msg.ReadVariantMap();
  530. SendEvent(eventType, eventData);
  531. }
  532. else
  533. {
  534. if (!scene_)
  535. {
  536. LOGERROR("Can not receive remote node event without an assigned scene");
  537. return;
  538. }
  539. unsigned nodeID = msg.ReadVLE();
  540. StringHash eventType = msg.ReadStringHash();
  541. VariantMap eventData = msg.ReadVariantMap();
  542. Node* receiver = scene_->GetNodeByID(nodeID);
  543. if (!receiver)
  544. {
  545. LOGWARNING("Missing receiver for remote node event, discarding");
  546. return;
  547. }
  548. SendEvent(receiver, eventType, eventData);
  549. }
  550. }
  551. kNet::MessageConnection* Connection::GetMessageConnection() const
  552. {
  553. return const_cast<kNet::MessageConnection*>(connection_.ptr());
  554. }
  555. Scene* Connection::GetScene() const
  556. {
  557. return scene_;
  558. }
  559. bool Connection::IsConnected() const
  560. {
  561. return connection_->GetConnectionState() == kNet::ConnectionOK;
  562. }
  563. String Connection::GetAddress() const
  564. {
  565. const unsigned char* ip = connection_->RemoteEndPoint().ip;
  566. char str[256];
  567. sprintf(str, "%d.%d.%d.%d", (unsigned)ip[0], (unsigned)ip[1], (unsigned)ip[2], (unsigned)ip[3]);
  568. return String(str);
  569. }
  570. unsigned short Connection::GetPort() const
  571. {
  572. return connection_->RemoteEndPoint().port;
  573. }
  574. String Connection::ToString() const
  575. {
  576. return GetAddress() + ":" + String(GetPort());
  577. }
  578. void Connection::ProcessNode(Node* node)
  579. {
  580. if (!node || processedNodes_.Contains(node))
  581. return;
  582. processedNodes_.Insert(node);
  583. // Process depended upon nodes first
  584. PODVector<Node*> depends;
  585. node->GetDependencyNodes(depends);
  586. for (PODVector<Node*>::ConstIterator i = depends.Begin(); i != depends.End(); ++i)
  587. ProcessNode(*i);
  588. // Check if the client's scene state already has this node
  589. if (sceneState_.Find(node->GetID()) != sceneState_.End())
  590. ProcessExistingNode(node);
  591. else
  592. ProcessNewNode(node);
  593. }
  594. void Connection::ProcessNewNode(Node* node)
  595. {
  596. msg_.Clear();
  597. msg_.WriteVLE(node->GetID());
  598. NodeReplicationState newNodeState;
  599. newNodeState.frameNumber_ = frameNumber_;
  600. // Write node's attributes
  601. node->WriteInitialDeltaUpdate(msg_, deltaUpdateBits_, newNodeState.attributes_);
  602. // Write node's user variables
  603. const VariantMap& vars = node->GetVars();
  604. msg_.WriteVLE(vars.Size());
  605. for (VariantMap::ConstIterator i = vars.Begin(); i != vars.End(); ++i)
  606. {
  607. msg_.WriteShortStringHash(i->first_);
  608. msg_.WriteVariant(i->second_);
  609. newNodeState.vars_[i->first_] = i->second_;
  610. }
  611. // Write node's components
  612. msg_.WriteVLE(node->GetNumNetworkComponents());
  613. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  614. for (unsigned i = 0; i < components.Size(); ++i)
  615. {
  616. Component* component = components[i];
  617. if (component->GetID() >= FIRST_LOCAL_ID)
  618. continue;
  619. msg_.WriteShortStringHash(component->GetType());
  620. msg_.WriteVLE(component->GetID());
  621. ComponentReplicationState newComponentState;
  622. newComponentState.frameNumber_ = frameNumber_;
  623. newComponentState.type_ = component->GetType();
  624. // Write component's attributes
  625. component->WriteInitialDeltaUpdate(msg_, deltaUpdateBits_, newComponentState.attributes_);
  626. newNodeState.components_[component->GetID()] = newComponentState;
  627. }
  628. SendMessage(MSG_CREATENODE, true, true, msg_);
  629. sceneState_[node->GetID()] = newNodeState;
  630. }
  631. void Connection::ProcessExistingNode(Node* node)
  632. {
  633. NodeReplicationState& nodeState = sceneState_[node->GetID()];
  634. nodeState.frameNumber_ = frameNumber_;
  635. // Check if attributes have changed
  636. bool deltaUpdate, latestData;
  637. node->PrepareUpdates(deltaUpdateBits_, nodeState.attributes_, deltaUpdate, latestData);
  638. // Check if user variables have changed. Note: variable removal is not supported
  639. changedVars_.Clear();
  640. const VariantMap& vars = node->GetVars();
  641. for (VariantMap::ConstIterator i = vars.Begin(); i != vars.End(); ++i)
  642. {
  643. VariantMap::Iterator j = nodeState.vars_.Find(i->first_);
  644. if (j == nodeState.vars_.End() || i->second_ != j->second_)
  645. {
  646. j->second_ = i->second_;
  647. changedVars_.Insert(i->first_);
  648. deltaUpdate = true;
  649. }
  650. }
  651. // Send deltaupdate message if necessary
  652. if (deltaUpdate)
  653. {
  654. msg_.Clear();
  655. msg_.WriteVLE(node->GetID());
  656. node->WriteDeltaUpdate(msg_, deltaUpdateBits_, nodeState.attributes_);
  657. // Write changed variables
  658. msg_.WriteVLE(changedVars_.Size());
  659. for (HashSet<ShortStringHash>::ConstIterator i = changedVars_.Begin(); i != changedVars_.End(); ++i)
  660. {
  661. VariantMap::ConstIterator j = vars.Find(*i);
  662. msg_.WriteShortStringHash(j->first_);
  663. msg_.WriteVariant(j->second_);
  664. }
  665. SendMessage(MSG_NODEDELTAUPDATE, true, true, msg_);
  666. }
  667. // Send latestdata message if necessary
  668. if (latestData)
  669. {
  670. // If at least one latest data attribute changes, send all of them
  671. msg_.Clear();
  672. msg_.WriteVLE(node->GetID());
  673. node->WriteLatestDataUpdate(msg_, nodeState.attributes_);
  674. SendMessage(MSG_NODELATESTDATA, node->GetID(), true, false, msg_);
  675. }
  676. // Check for new or changed components
  677. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  678. for (unsigned i = 0; i < components.Size(); ++i)
  679. {
  680. Component* component = components[i];
  681. if (component->GetID() >= FIRST_LOCAL_ID)
  682. continue;
  683. Map<unsigned, ComponentReplicationState>::Iterator j = nodeState.components_.Find(component->GetID());
  684. if (j == nodeState.components_.End())
  685. {
  686. // New component
  687. msg_.Clear();
  688. msg_.WriteVLE(node->GetID());
  689. msg_.WriteShortStringHash(component->GetType());
  690. msg_.WriteVLE(component->GetID());
  691. ComponentReplicationState newComponentState;
  692. newComponentState.frameNumber_ = frameNumber_;
  693. newComponentState.type_ = component->GetType();
  694. // Write component's attributes
  695. component->WriteInitialDeltaUpdate(msg_, deltaUpdateBits_, newComponentState.attributes_);
  696. SendMessage(MSG_CREATECOMPONENT, true, true, msg_);
  697. nodeState.components_[component->GetID()] = newComponentState;
  698. }
  699. else
  700. {
  701. // Existing component
  702. ComponentReplicationState& componentState = j->second_;
  703. componentState.frameNumber_ = frameNumber_;
  704. component->PrepareUpdates(deltaUpdateBits_, componentState.attributes_, deltaUpdate, latestData);
  705. // Send deltaupdate message if necessary
  706. if (deltaUpdate)
  707. {
  708. msg_.Clear();
  709. msg_.WriteVLE(component->GetID());
  710. component->WriteDeltaUpdate(msg_, deltaUpdateBits_, componentState.attributes_);
  711. SendMessage(MSG_COMPONENTDELTAUPDATE, true, true, msg_);
  712. }
  713. // Send latestdata message if necessary
  714. if (latestData)
  715. {
  716. // If at least one latest data attribute changes, send all of them
  717. msg_.Clear();
  718. msg_.WriteVLE(component->GetID());
  719. component->WriteLatestDataUpdate(msg_, componentState.attributes_);
  720. SendMessage(MSG_COMPONENTLATESTDATA, component->GetID(), true, false, msg_);
  721. }
  722. }
  723. }
  724. // Check for removed components
  725. for (Map<unsigned, ComponentReplicationState>::Iterator i = nodeState.components_.Begin(); i != nodeState.components_.End();)
  726. {
  727. Map<unsigned, ComponentReplicationState>::Iterator current = i++;
  728. if (current->second_.frameNumber_ != frameNumber_)
  729. {
  730. msg_.Clear();
  731. msg_.WriteVLE(current->first_);
  732. SendMessage(MSG_REMOVECOMPONENT, true, true, msg_);
  733. nodeState.components_.Erase(current);
  734. }
  735. }
  736. }
  737. void Connection::HandleAsyncLoadFinished(StringHash eventType, VariantMap& eventData)
  738. {
  739. VectorBuffer msg;
  740. msg.WriteUInt(scene_->GetChecksum());
  741. SendMessage(MSG_SCENELOADED, true, true, msg);
  742. }