Connection.cpp 30 KB

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