scene_replication_interface.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. /**************************************************************************/
  2. /* scene_replication_interface.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "scene_replication_interface.h"
  31. #include "scene_multiplayer.h"
  32. #include "core/debugger/engine_debugger.h"
  33. #include "core/io/marshalls.h"
  34. #include "scene/main/node.h"
  35. #include "scene/scene_string_names.h"
  36. #define MAKE_ROOM(m_amount) \
  37. if (packet_cache.size() < m_amount) \
  38. packet_cache.resize(m_amount);
  39. #ifdef DEBUG_ENABLED
  40. _FORCE_INLINE_ void SceneReplicationInterface::_profile_node_data(const String &p_what, ObjectID p_id, int p_size) {
  41. if (EngineDebugger::is_profiling("multiplayer:replication")) {
  42. Array values;
  43. values.push_back(p_what);
  44. values.push_back(p_id);
  45. values.push_back(p_size);
  46. EngineDebugger::profiler_add_frame_data("multiplayer:replication", values);
  47. }
  48. }
  49. #endif
  50. SceneReplicationInterface::TrackedNode &SceneReplicationInterface::_track(const ObjectID &p_id) {
  51. if (!tracked_nodes.has(p_id)) {
  52. tracked_nodes[p_id] = TrackedNode(p_id);
  53. Node *node = get_id_as<Node>(p_id);
  54. node->connect(SceneStringNames::get_singleton()->tree_exited, callable_mp(this, &SceneReplicationInterface::_untrack).bind(p_id), Node::CONNECT_ONE_SHOT);
  55. }
  56. return tracked_nodes[p_id];
  57. }
  58. void SceneReplicationInterface::_untrack(const ObjectID &p_id) {
  59. if (!tracked_nodes.has(p_id)) {
  60. return;
  61. }
  62. uint32_t net_id = tracked_nodes[p_id].net_id;
  63. uint32_t peer = tracked_nodes[p_id].remote_peer;
  64. tracked_nodes.erase(p_id);
  65. // If it was spawned by a remote, remove it from the received nodes.
  66. if (peer && peers_info.has(peer)) {
  67. peers_info[peer].recv_nodes.erase(net_id);
  68. }
  69. // If we spawned or synced it, we need to remove it from any peer it was sent to.
  70. if (net_id || peer == 0) {
  71. for (KeyValue<int, PeerInfo> &E : peers_info) {
  72. E.value.spawn_nodes.erase(p_id);
  73. }
  74. }
  75. }
  76. void SceneReplicationInterface::_free_remotes(const PeerInfo &p_info) {
  77. for (const KeyValue<uint32_t, ObjectID> &E : p_info.recv_nodes) {
  78. Node *node = tracked_nodes.has(E.value) ? get_id_as<Node>(E.value) : nullptr;
  79. ERR_CONTINUE(!node);
  80. node->queue_free();
  81. }
  82. }
  83. void SceneReplicationInterface::on_peer_change(int p_id, bool p_connected) {
  84. if (p_connected) {
  85. peers_info[p_id] = PeerInfo();
  86. for (const ObjectID &oid : spawned_nodes) {
  87. _update_spawn_visibility(p_id, oid);
  88. }
  89. for (const ObjectID &oid : sync_nodes) {
  90. _update_sync_visibility(p_id, get_id_as<MultiplayerSynchronizer>(oid));
  91. }
  92. } else {
  93. ERR_FAIL_COND(!peers_info.has(p_id));
  94. _free_remotes(peers_info[p_id]);
  95. peers_info.erase(p_id);
  96. }
  97. }
  98. void SceneReplicationInterface::on_reset() {
  99. for (const KeyValue<int, PeerInfo> &E : peers_info) {
  100. _free_remotes(E.value);
  101. }
  102. peers_info.clear();
  103. // Tracked nodes are cleared on deletion, here we only reset the ids so they can be later re-assigned.
  104. for (KeyValue<ObjectID, TrackedNode> &E : tracked_nodes) {
  105. TrackedNode &tobj = E.value;
  106. tobj.net_id = 0;
  107. tobj.remote_peer = 0;
  108. }
  109. for (const ObjectID &oid : sync_nodes) {
  110. MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(oid);
  111. ERR_CONTINUE(!sync);
  112. sync->reset();
  113. }
  114. last_net_id = 0;
  115. }
  116. void SceneReplicationInterface::on_network_process() {
  117. // Prevent endless stalling in case of unforeseen spawn errors.
  118. if (spawn_queue.size()) {
  119. ERR_PRINT("An error happened during last spawn, this usually means the 'ready' signal was not emitted by the spawned node.");
  120. for (const ObjectID &oid : spawn_queue) {
  121. Node *node = get_id_as<Node>(oid);
  122. ERR_CONTINUE(!node);
  123. if (node->is_connected(SceneStringNames::get_singleton()->ready, callable_mp(this, &SceneReplicationInterface::_node_ready))) {
  124. node->disconnect(SceneStringNames::get_singleton()->ready, callable_mp(this, &SceneReplicationInterface::_node_ready));
  125. }
  126. }
  127. spawn_queue.clear();
  128. }
  129. // Process timed syncs.
  130. uint64_t msec = OS::get_singleton()->get_ticks_msec();
  131. for (KeyValue<int, PeerInfo> &E : peers_info) {
  132. const HashSet<ObjectID> to_sync = E.value.sync_nodes;
  133. if (to_sync.is_empty()) {
  134. continue; // Nothing to sync
  135. }
  136. uint16_t sync_net_time = ++E.value.last_sent_sync;
  137. _send_sync(E.key, to_sync, sync_net_time, msec);
  138. }
  139. }
  140. Error SceneReplicationInterface::on_spawn(Object *p_obj, Variant p_config) {
  141. Node *node = Object::cast_to<Node>(p_obj);
  142. ERR_FAIL_COND_V(!node || p_config.get_type() != Variant::OBJECT, ERR_INVALID_PARAMETER);
  143. MultiplayerSpawner *spawner = Object::cast_to<MultiplayerSpawner>(p_config.get_validated_object());
  144. ERR_FAIL_COND_V(!spawner, ERR_INVALID_PARAMETER);
  145. // Track node.
  146. const ObjectID oid = node->get_instance_id();
  147. TrackedNode &tobj = _track(oid);
  148. // Spawn state needs to be callected after "ready", but the spawn order follows "enter_tree".
  149. ERR_FAIL_COND_V(tobj.spawner != ObjectID(), ERR_ALREADY_IN_USE);
  150. tobj.spawner = spawner->get_instance_id();
  151. spawn_queue.insert(oid);
  152. node->connect(SceneStringNames::get_singleton()->ready, callable_mp(this, &SceneReplicationInterface::_node_ready).bind(oid), Node::CONNECT_ONE_SHOT);
  153. return OK;
  154. }
  155. void SceneReplicationInterface::_node_ready(const ObjectID &p_oid) {
  156. ERR_FAIL_COND(!spawn_queue.has(p_oid)); // Bug.
  157. // If we are a nested spawn, we need to wait until the parent is ready.
  158. if (p_oid != *(spawn_queue.begin())) {
  159. return;
  160. }
  161. for (const ObjectID &oid : spawn_queue) {
  162. ERR_CONTINUE(!tracked_nodes.has(oid));
  163. TrackedNode &tobj = tracked_nodes[oid];
  164. MultiplayerSpawner *spawner = get_id_as<MultiplayerSpawner>(tobj.spawner);
  165. ERR_CONTINUE(!spawner);
  166. spawned_nodes.insert(oid);
  167. if (multiplayer->has_multiplayer_peer() && spawner->is_multiplayer_authority()) {
  168. if (tobj.net_id == 0) {
  169. tobj.net_id = ++last_net_id;
  170. }
  171. _update_spawn_visibility(0, oid);
  172. }
  173. }
  174. spawn_queue.clear();
  175. }
  176. Error SceneReplicationInterface::on_despawn(Object *p_obj, Variant p_config) {
  177. Node *node = Object::cast_to<Node>(p_obj);
  178. ERR_FAIL_COND_V(!node || p_config.get_type() != Variant::OBJECT, ERR_INVALID_PARAMETER);
  179. MultiplayerSpawner *spawner = Object::cast_to<MultiplayerSpawner>(p_config.get_validated_object());
  180. ERR_FAIL_COND_V(!p_obj || !spawner, ERR_INVALID_PARAMETER);
  181. // Forcibly despawn to all peers that knowns me.
  182. int len = 0;
  183. Error err = _make_despawn_packet(node, len);
  184. ERR_FAIL_COND_V(err != OK, ERR_BUG);
  185. const ObjectID oid = p_obj->get_instance_id();
  186. for (const KeyValue<int, PeerInfo> &E : peers_info) {
  187. if (!E.value.spawn_nodes.has(oid)) {
  188. continue;
  189. }
  190. _send_raw(packet_cache.ptr(), len, E.key, true);
  191. }
  192. // Also remove spawner tracking from the replication state.
  193. ERR_FAIL_COND_V(!tracked_nodes.has(oid), ERR_INVALID_PARAMETER);
  194. TrackedNode &tobj = _track(oid);
  195. ERR_FAIL_COND_V(tobj.spawner != spawner->get_instance_id(), ERR_INVALID_PARAMETER);
  196. tobj.spawner = ObjectID();
  197. spawned_nodes.erase(oid);
  198. for (KeyValue<int, PeerInfo> &E : peers_info) {
  199. E.value.spawn_nodes.erase(oid);
  200. }
  201. return OK;
  202. }
  203. Error SceneReplicationInterface::on_replication_start(Object *p_obj, Variant p_config) {
  204. Node *node = Object::cast_to<Node>(p_obj);
  205. ERR_FAIL_COND_V(!node || p_config.get_type() != Variant::OBJECT, ERR_INVALID_PARAMETER);
  206. MultiplayerSynchronizer *sync = Object::cast_to<MultiplayerSynchronizer>(p_config.get_validated_object());
  207. ERR_FAIL_COND_V(!sync, ERR_INVALID_PARAMETER);
  208. // Add to synchronizer list.
  209. TrackedNode &tobj = _track(p_obj->get_instance_id());
  210. const ObjectID sid = sync->get_instance_id();
  211. tobj.synchronizers.insert(sid);
  212. sync_nodes.insert(sid);
  213. // Update visibility.
  214. sync->connect("visibility_changed", callable_mp(this, &SceneReplicationInterface::_visibility_changed).bind(sync->get_instance_id()));
  215. _update_sync_visibility(0, sync);
  216. if (pending_spawn == p_obj->get_instance_id() && sync->get_multiplayer_authority() == pending_spawn_remote) {
  217. // Try to apply synchronizer Net ID
  218. ERR_FAIL_COND_V_MSG(pending_sync_net_ids.is_empty(), ERR_INVALID_DATA, vformat("The MultiplayerSynchronizer at path \"%s\" is unable to process the pending spawn since it has no network ID. This might happen when changing the multiplayer authority during the \"_ready\" callback. Make sure to only change the authority of multiplayer synchronizers during \"_enter_tree\" or the \"_spawn_custom\" callback of their multiplayer spawner.", sync->get_path()));
  219. ERR_FAIL_COND_V(!peers_info.has(pending_spawn_remote), ERR_INVALID_DATA);
  220. uint32_t net_id = pending_sync_net_ids[0];
  221. pending_sync_net_ids.pop_front();
  222. peers_info[pending_spawn_remote].recv_sync_ids[net_id] = sync->get_instance_id();
  223. // Try to apply spawn state (before ready).
  224. if (pending_buffer_size > 0) {
  225. ERR_FAIL_COND_V(!node || sync->get_replication_config().is_null(), ERR_UNCONFIGURED);
  226. int consumed = 0;
  227. const List<NodePath> props = sync->get_replication_config()->get_spawn_properties();
  228. Vector<Variant> vars;
  229. vars.resize(props.size());
  230. Error err = MultiplayerAPI::decode_and_decompress_variants(vars, pending_buffer, pending_buffer_size, consumed);
  231. ERR_FAIL_COND_V(err, err);
  232. if (consumed > 0) {
  233. pending_buffer += consumed;
  234. pending_buffer_size -= consumed;
  235. err = MultiplayerSynchronizer::set_state(props, node, vars);
  236. ERR_FAIL_COND_V(err, err);
  237. }
  238. }
  239. }
  240. return OK;
  241. }
  242. Error SceneReplicationInterface::on_replication_stop(Object *p_obj, Variant p_config) {
  243. Node *node = Object::cast_to<Node>(p_obj);
  244. ERR_FAIL_COND_V(!node || p_config.get_type() != Variant::OBJECT, ERR_INVALID_PARAMETER);
  245. MultiplayerSynchronizer *sync = Object::cast_to<MultiplayerSynchronizer>(p_config.get_validated_object());
  246. ERR_FAIL_COND_V(!sync, ERR_INVALID_PARAMETER);
  247. sync->disconnect("visibility_changed", callable_mp(this, &SceneReplicationInterface::_visibility_changed));
  248. // Untrack synchronizer.
  249. const ObjectID oid = node->get_instance_id();
  250. const ObjectID sid = sync->get_instance_id();
  251. ERR_FAIL_COND_V(!tracked_nodes.has(oid), ERR_INVALID_PARAMETER);
  252. TrackedNode &tobj = _track(oid);
  253. tobj.synchronizers.erase(sid);
  254. sync_nodes.erase(sid);
  255. for (KeyValue<int, PeerInfo> &E : peers_info) {
  256. E.value.sync_nodes.erase(sid);
  257. if (sync->get_net_id()) {
  258. E.value.recv_sync_ids.erase(sync->get_net_id());
  259. }
  260. }
  261. return OK;
  262. }
  263. void SceneReplicationInterface::_visibility_changed(int p_peer, ObjectID p_sid) {
  264. MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(p_sid);
  265. ERR_FAIL_COND(!sync); // Bug.
  266. Node *node = sync->get_root_node();
  267. ERR_FAIL_COND(!node); // Bug.
  268. const ObjectID oid = node->get_instance_id();
  269. if (spawned_nodes.has(oid) && p_peer != multiplayer->get_unique_id()) {
  270. _update_spawn_visibility(p_peer, oid);
  271. }
  272. _update_sync_visibility(p_peer, sync);
  273. }
  274. bool SceneReplicationInterface::is_rpc_visible(const ObjectID &p_oid, int p_peer) const {
  275. if (!tracked_nodes.has(p_oid)) {
  276. return true; // Untracked nodes are always visible to RPCs.
  277. }
  278. ERR_FAIL_COND_V(p_peer < 0, false);
  279. const TrackedNode &tnode = tracked_nodes[p_oid];
  280. if (tnode.synchronizers.is_empty()) {
  281. return true; // No synchronizers means no visibility restrictions.
  282. }
  283. if (tnode.remote_peer && uint32_t(p_peer) == tnode.remote_peer) {
  284. return true; // RPCs on spawned nodes are always visible to spawner.
  285. } else if (spawned_nodes.has(p_oid)) {
  286. // It's a spwaned node we control, this can be fast
  287. if (p_peer) {
  288. return peers_info.has(p_peer) && peers_info[p_peer].spawn_nodes.has(p_oid);
  289. } else {
  290. for (const KeyValue<int, PeerInfo> &E : peers_info) {
  291. if (!E.value.spawn_nodes.has(p_oid)) {
  292. return false; // Not public.
  293. }
  294. }
  295. return true; // All peers have this node.
  296. }
  297. } else {
  298. // Cycle object synchronizers to check visibility.
  299. for (const ObjectID &sid : tnode.synchronizers) {
  300. MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(sid);
  301. ERR_CONTINUE(!sync);
  302. // RPC visibility is composed using OR when multiple synchronizers are present.
  303. // Note that we don't really care about authority here which may lead to unexpected
  304. // results when using multiple synchronizers to control the same node.
  305. if (sync->is_visible_to(p_peer)) {
  306. return true;
  307. }
  308. }
  309. return false; // Not visible.
  310. }
  311. }
  312. Error SceneReplicationInterface::_update_sync_visibility(int p_peer, MultiplayerSynchronizer *p_sync) {
  313. ERR_FAIL_COND_V(!p_sync, ERR_BUG);
  314. if (!multiplayer->has_multiplayer_peer() || !p_sync->is_multiplayer_authority() || p_peer == multiplayer->get_unique_id()) {
  315. return OK;
  316. }
  317. const ObjectID &sid = p_sync->get_instance_id();
  318. bool is_visible = p_sync->is_visible_to(p_peer);
  319. if (p_peer == 0) {
  320. for (KeyValue<int, PeerInfo> &E : peers_info) {
  321. // Might be visible to this specific peer.
  322. bool is_visible_to_peer = is_visible || p_sync->is_visible_to(E.key);
  323. if (is_visible_to_peer == E.value.sync_nodes.has(sid)) {
  324. continue;
  325. }
  326. if (is_visible_to_peer) {
  327. E.value.sync_nodes.insert(sid);
  328. } else {
  329. E.value.sync_nodes.erase(sid);
  330. }
  331. }
  332. return OK;
  333. } else {
  334. ERR_FAIL_COND_V(!peers_info.has(p_peer), ERR_INVALID_PARAMETER);
  335. if (is_visible == peers_info[p_peer].sync_nodes.has(sid)) {
  336. return OK;
  337. }
  338. if (is_visible) {
  339. peers_info[p_peer].sync_nodes.insert(sid);
  340. } else {
  341. peers_info[p_peer].sync_nodes.erase(sid);
  342. }
  343. return OK;
  344. }
  345. }
  346. Error SceneReplicationInterface::_update_spawn_visibility(int p_peer, const ObjectID &p_oid) {
  347. const TrackedNode *tnode = tracked_nodes.getptr(p_oid);
  348. ERR_FAIL_COND_V(!tnode, ERR_BUG);
  349. MultiplayerSpawner *spawner = get_id_as<MultiplayerSpawner>(tnode->spawner);
  350. Node *node = get_id_as<Node>(p_oid);
  351. ERR_FAIL_COND_V(!node || !spawner || !spawner->is_multiplayer_authority(), ERR_BUG);
  352. ERR_FAIL_COND_V(!tracked_nodes.has(p_oid), ERR_BUG);
  353. const HashSet<ObjectID> synchronizers = tracked_nodes[p_oid].synchronizers;
  354. bool is_visible = true;
  355. for (const ObjectID &sid : synchronizers) {
  356. MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(sid);
  357. ERR_CONTINUE(!sync);
  358. if (!sync->is_multiplayer_authority()) {
  359. continue;
  360. }
  361. // Spawn visibility is composed using OR when multiple synchronizers are present.
  362. if (sync->is_visible_to(p_peer)) {
  363. is_visible = true;
  364. break;
  365. }
  366. is_visible = false;
  367. }
  368. // Spawn (and despawn) when needed.
  369. HashSet<int> to_spawn;
  370. HashSet<int> to_despawn;
  371. if (p_peer) {
  372. ERR_FAIL_COND_V(!peers_info.has(p_peer), ERR_INVALID_PARAMETER);
  373. if (is_visible == peers_info[p_peer].spawn_nodes.has(p_oid)) {
  374. return OK;
  375. }
  376. if (is_visible) {
  377. to_spawn.insert(p_peer);
  378. } else {
  379. to_despawn.insert(p_peer);
  380. }
  381. } else {
  382. // Check visibility for each peers.
  383. for (const KeyValue<int, PeerInfo> &E : peers_info) {
  384. if (is_visible) {
  385. // This is fast, since the the object is visible to everyone, we don't need to check each peer.
  386. if (E.value.spawn_nodes.has(p_oid)) {
  387. // Already spawned.
  388. continue;
  389. }
  390. to_spawn.insert(E.key);
  391. } else {
  392. // Need to check visibility for each peer.
  393. _update_spawn_visibility(E.key, p_oid);
  394. }
  395. }
  396. }
  397. if (to_spawn.size()) {
  398. int len = 0;
  399. _make_spawn_packet(node, spawner, len);
  400. for (int pid : to_spawn) {
  401. ERR_CONTINUE(!peers_info.has(pid));
  402. int path_id;
  403. multiplayer->get_path_cache()->send_object_cache(spawner, pid, path_id);
  404. _send_raw(packet_cache.ptr(), len, pid, true);
  405. peers_info[pid].spawn_nodes.insert(p_oid);
  406. }
  407. }
  408. if (to_despawn.size()) {
  409. int len = 0;
  410. _make_despawn_packet(node, len);
  411. for (int pid : to_despawn) {
  412. ERR_CONTINUE(!peers_info.has(pid));
  413. peers_info[pid].spawn_nodes.erase(p_oid);
  414. _send_raw(packet_cache.ptr(), len, pid, true);
  415. }
  416. }
  417. return OK;
  418. }
  419. Error SceneReplicationInterface::_send_raw(const uint8_t *p_buffer, int p_size, int p_peer, bool p_reliable) {
  420. ERR_FAIL_COND_V(!p_buffer || p_size < 1, ERR_INVALID_PARAMETER);
  421. ERR_FAIL_COND_V(!multiplayer->has_multiplayer_peer(), ERR_UNCONFIGURED);
  422. Ref<MultiplayerPeer> peer = multiplayer->get_multiplayer_peer();
  423. peer->set_transfer_channel(0);
  424. peer->set_transfer_mode(p_reliable ? MultiplayerPeer::TRANSFER_MODE_RELIABLE : MultiplayerPeer::TRANSFER_MODE_UNRELIABLE);
  425. return multiplayer->send_command(p_peer, p_buffer, p_size);
  426. }
  427. Error SceneReplicationInterface::_make_spawn_packet(Node *p_node, MultiplayerSpawner *p_spawner, int &r_len) {
  428. ERR_FAIL_COND_V(!multiplayer || !p_node || !p_spawner, ERR_BUG);
  429. const ObjectID oid = p_node->get_instance_id();
  430. const TrackedNode *tnode = tracked_nodes.getptr(oid);
  431. ERR_FAIL_COND_V(!tnode, ERR_INVALID_PARAMETER);
  432. uint32_t nid = tnode->net_id;
  433. ERR_FAIL_COND_V(!nid, ERR_UNCONFIGURED);
  434. // Prepare custom arg and scene_id
  435. uint8_t scene_id = p_spawner->find_spawnable_scene_index_from_object(oid);
  436. bool is_custom = scene_id == MultiplayerSpawner::INVALID_ID;
  437. Variant spawn_arg = p_spawner->get_spawn_argument(oid);
  438. int spawn_arg_size = 0;
  439. if (is_custom) {
  440. Error err = MultiplayerAPI::encode_and_compress_variant(spawn_arg, nullptr, spawn_arg_size, false);
  441. ERR_FAIL_COND_V(err, err);
  442. }
  443. // Prepare spawn state.
  444. List<NodePath> state_props;
  445. List<uint32_t> sync_ids;
  446. const HashSet<ObjectID> synchronizers = tnode->synchronizers;
  447. for (const ObjectID &sid : synchronizers) {
  448. MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(sid);
  449. if (!sync->is_multiplayer_authority()) {
  450. continue;
  451. }
  452. ERR_CONTINUE(!sync);
  453. ERR_FAIL_COND_V(sync->get_replication_config().is_null(), ERR_BUG);
  454. for (const NodePath &prop : sync->get_replication_config()->get_spawn_properties()) {
  455. state_props.push_back(prop);
  456. }
  457. // Ensure the synchronizer has an ID.
  458. if (sync->get_net_id() == 0) {
  459. sync->set_net_id(++last_net_id);
  460. }
  461. sync_ids.push_back(sync->get_net_id());
  462. }
  463. int state_size = 0;
  464. Vector<Variant> state_vars;
  465. Vector<const Variant *> state_varp;
  466. if (state_props.size()) {
  467. Error err = MultiplayerSynchronizer::get_state(state_props, p_node, state_vars, state_varp);
  468. ERR_FAIL_COND_V_MSG(err != OK, err, "Unable to retrieve spawn state.");
  469. err = MultiplayerAPI::encode_and_compress_variants(state_varp.ptrw(), state_varp.size(), nullptr, state_size);
  470. ERR_FAIL_COND_V_MSG(err != OK, err, "Unable to encode spawn state.");
  471. }
  472. // Encode scene ID, path ID, net ID, node name.
  473. int path_id = multiplayer->get_path_cache()->make_object_cache(p_spawner);
  474. CharString cname = p_node->get_name().operator String().utf8();
  475. int nlen = encode_cstring(cname.get_data(), nullptr);
  476. MAKE_ROOM(1 + 1 + 4 + 4 + 4 + 4 * sync_ids.size() + 4 + nlen + (is_custom ? 4 + spawn_arg_size : 0) + state_size);
  477. uint8_t *ptr = packet_cache.ptrw();
  478. ptr[0] = (uint8_t)SceneMultiplayer::NETWORK_COMMAND_SPAWN;
  479. ptr[1] = scene_id;
  480. int ofs = 2;
  481. ofs += encode_uint32(path_id, &ptr[ofs]);
  482. ofs += encode_uint32(nid, &ptr[ofs]);
  483. ofs += encode_uint32(sync_ids.size(), &ptr[ofs]);
  484. ofs += encode_uint32(nlen, &ptr[ofs]);
  485. for (uint32_t snid : sync_ids) {
  486. ofs += encode_uint32(snid, &ptr[ofs]);
  487. }
  488. ofs += encode_cstring(cname.get_data(), &ptr[ofs]);
  489. // Write args
  490. if (is_custom) {
  491. ofs += encode_uint32(spawn_arg_size, &ptr[ofs]);
  492. Error err = MultiplayerAPI::encode_and_compress_variant(spawn_arg, &ptr[ofs], spawn_arg_size, false);
  493. ERR_FAIL_COND_V(err, err);
  494. ofs += spawn_arg_size;
  495. }
  496. // Write state.
  497. if (state_size) {
  498. Error err = MultiplayerAPI::encode_and_compress_variants(state_varp.ptrw(), state_varp.size(), &ptr[ofs], state_size);
  499. ERR_FAIL_COND_V(err, err);
  500. ofs += state_size;
  501. }
  502. r_len = ofs;
  503. return OK;
  504. }
  505. Error SceneReplicationInterface::_make_despawn_packet(Node *p_node, int &r_len) {
  506. const ObjectID oid = p_node->get_instance_id();
  507. const TrackedNode *tnode = tracked_nodes.getptr(oid);
  508. ERR_FAIL_COND_V(!tnode, ERR_INVALID_PARAMETER);
  509. MAKE_ROOM(5);
  510. uint8_t *ptr = packet_cache.ptrw();
  511. ptr[0] = (uint8_t)SceneMultiplayer::NETWORK_COMMAND_DESPAWN;
  512. int ofs = 1;
  513. uint32_t nid = tnode->net_id;
  514. ofs += encode_uint32(nid, &ptr[ofs]);
  515. r_len = ofs;
  516. return OK;
  517. }
  518. Error SceneReplicationInterface::on_spawn_receive(int p_from, const uint8_t *p_buffer, int p_buffer_len) {
  519. ERR_FAIL_COND_V_MSG(p_buffer_len < 18, ERR_INVALID_DATA, "Invalid spawn packet received");
  520. int ofs = 1; // The spawn/despawn command.
  521. uint8_t scene_id = p_buffer[ofs];
  522. ofs += 1;
  523. uint32_t node_target = decode_uint32(&p_buffer[ofs]);
  524. ofs += 4;
  525. MultiplayerSpawner *spawner = Object::cast_to<MultiplayerSpawner>(multiplayer->get_path_cache()->get_cached_object(p_from, node_target));
  526. ERR_FAIL_COND_V(!spawner, ERR_DOES_NOT_EXIST);
  527. ERR_FAIL_COND_V(p_from != spawner->get_multiplayer_authority(), ERR_UNAUTHORIZED);
  528. uint32_t net_id = decode_uint32(&p_buffer[ofs]);
  529. ofs += 4;
  530. uint32_t sync_len = decode_uint32(&p_buffer[ofs]);
  531. ofs += 4;
  532. uint32_t name_len = decode_uint32(&p_buffer[ofs]);
  533. ofs += 4;
  534. ERR_FAIL_COND_V_MSG(name_len + (sync_len * 4) > uint32_t(p_buffer_len - ofs), ERR_INVALID_DATA, vformat("Invalid spawn packet size: %d, wants: %d", p_buffer_len, ofs + name_len + (sync_len * 4)));
  535. List<uint32_t> sync_ids;
  536. for (uint32_t i = 0; i < sync_len; i++) {
  537. sync_ids.push_back(decode_uint32(&p_buffer[ofs]));
  538. ofs += 4;
  539. }
  540. ERR_FAIL_COND_V_MSG(name_len < 1, ERR_INVALID_DATA, "Zero spawn name size.");
  541. // We need to make sure no trickery happens here, but we want to allow autogenerated ("@") node names.
  542. const String name = String::utf8((const char *)&p_buffer[ofs], name_len);
  543. ERR_FAIL_COND_V_MSG(name.validate_node_name() != name, ERR_INVALID_DATA, vformat("Invalid node name received: '%s'. Make sure to add nodes via 'add_child(node, true)' remotely.", name));
  544. ofs += name_len;
  545. // Check that we can spawn.
  546. Node *parent = spawner->get_node_or_null(spawner->get_spawn_path());
  547. ERR_FAIL_COND_V(!parent, ERR_UNCONFIGURED);
  548. ERR_FAIL_COND_V(parent->has_node(name), ERR_INVALID_DATA);
  549. Node *node = nullptr;
  550. if (scene_id == MultiplayerSpawner::INVALID_ID) {
  551. // Custom spawn.
  552. ERR_FAIL_COND_V(p_buffer_len - ofs < 4, ERR_INVALID_DATA);
  553. uint32_t arg_size = decode_uint32(&p_buffer[ofs]);
  554. ofs += 4;
  555. ERR_FAIL_COND_V(arg_size > uint32_t(p_buffer_len - ofs), ERR_INVALID_DATA);
  556. Variant v;
  557. Error err = MultiplayerAPI::decode_and_decompress_variant(v, &p_buffer[ofs], arg_size, nullptr, false);
  558. ERR_FAIL_COND_V(err != OK, err);
  559. ofs += arg_size;
  560. node = spawner->instantiate_custom(v);
  561. } else {
  562. // Scene based spawn.
  563. node = spawner->instantiate_scene(scene_id);
  564. }
  565. ERR_FAIL_COND_V(!node, ERR_UNAUTHORIZED);
  566. node->set_name(name);
  567. // Add and track remote
  568. ERR_FAIL_COND_V(!peers_info.has(p_from), ERR_UNAVAILABLE);
  569. ERR_FAIL_COND_V(peers_info[p_from].recv_nodes.has(net_id), ERR_ALREADY_IN_USE);
  570. ObjectID oid = node->get_instance_id();
  571. TrackedNode &tobj = _track(oid);
  572. tobj.spawner = spawner->get_instance_id();
  573. tobj.net_id = net_id;
  574. tobj.remote_peer = p_from;
  575. peers_info[p_from].recv_nodes[net_id] = oid;
  576. // The initial state will be applied during the sync config (i.e. before _ready).
  577. pending_spawn = node->get_instance_id();
  578. pending_spawn_remote = p_from;
  579. pending_buffer_size = p_buffer_len - ofs;
  580. pending_buffer = pending_buffer_size > 0 ? &p_buffer[ofs] : nullptr;
  581. pending_sync_net_ids = sync_ids;
  582. parent->add_child(node);
  583. spawner->emit_signal(SNAME("spawned"), node);
  584. pending_spawn = ObjectID();
  585. pending_spawn_remote = 0;
  586. pending_buffer = nullptr;
  587. pending_buffer_size = 0;
  588. if (pending_sync_net_ids.size()) {
  589. pending_sync_net_ids.clear();
  590. ERR_FAIL_V(ERR_INVALID_DATA); // Should have been consumed.
  591. }
  592. return OK;
  593. }
  594. Error SceneReplicationInterface::on_despawn_receive(int p_from, const uint8_t *p_buffer, int p_buffer_len) {
  595. ERR_FAIL_COND_V_MSG(p_buffer_len < 5, ERR_INVALID_DATA, "Invalid spawn packet received");
  596. int ofs = 1; // The spawn/despawn command.
  597. uint32_t net_id = decode_uint32(&p_buffer[ofs]);
  598. ofs += 4;
  599. // Untrack remote
  600. ERR_FAIL_COND_V(!peers_info.has(p_from), ERR_UNAUTHORIZED);
  601. PeerInfo &pinfo = peers_info[p_from];
  602. ERR_FAIL_COND_V(!pinfo.recv_nodes.has(net_id), ERR_UNAUTHORIZED);
  603. Node *node = get_id_as<Node>(pinfo.recv_nodes[net_id]);
  604. ERR_FAIL_COND_V(!node, ERR_BUG);
  605. pinfo.recv_nodes.erase(net_id);
  606. const ObjectID oid = node->get_instance_id();
  607. ERR_FAIL_COND_V(!tracked_nodes.has(oid), ERR_BUG);
  608. MultiplayerSpawner *spawner = get_id_as<MultiplayerSpawner>(tracked_nodes[oid].spawner);
  609. ERR_FAIL_COND_V(!spawner, ERR_DOES_NOT_EXIST);
  610. ERR_FAIL_COND_V(p_from != spawner->get_multiplayer_authority(), ERR_UNAUTHORIZED);
  611. if (node->get_parent() != nullptr) {
  612. node->get_parent()->remove_child(node);
  613. }
  614. node->queue_free();
  615. spawner->emit_signal(SNAME("despawned"), node);
  616. return OK;
  617. }
  618. void SceneReplicationInterface::_send_sync(int p_peer, const HashSet<ObjectID> p_synchronizers, uint16_t p_sync_net_time, uint64_t p_msec) {
  619. MAKE_ROOM(sync_mtu);
  620. uint8_t *ptr = packet_cache.ptrw();
  621. ptr[0] = SceneMultiplayer::NETWORK_COMMAND_SYNC;
  622. int ofs = 1;
  623. ofs += encode_uint16(p_sync_net_time, &ptr[1]);
  624. // Can only send updates for already notified nodes.
  625. // This is a lazy implementation, we could optimize much more here with by grouping by replication config.
  626. for (const ObjectID &oid : p_synchronizers) {
  627. MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(oid);
  628. ERR_CONTINUE(!sync || !sync->get_replication_config().is_valid() || !sync->is_multiplayer_authority());
  629. if (!sync->update_outbound_sync_time(p_msec)) {
  630. continue; // nothing to sync.
  631. }
  632. Node *node = sync->get_root_node();
  633. ERR_CONTINUE(!node);
  634. uint32_t net_id = sync->get_net_id();
  635. if (net_id == 0 || (net_id & 0x80000000)) {
  636. int path_id = 0;
  637. bool verified = multiplayer->get_path_cache()->send_object_cache(sync, p_peer, path_id);
  638. ERR_CONTINUE_MSG(path_id < 0, "This should never happen!");
  639. if (net_id == 0) {
  640. // First time path based ID.
  641. net_id = path_id | 0x80000000;
  642. sync->set_net_id(net_id | 0x80000000);
  643. }
  644. if (!verified) {
  645. // The path based sync is not yet confirmed, skipping.
  646. continue;
  647. }
  648. }
  649. int size;
  650. Vector<Variant> vars;
  651. Vector<const Variant *> varp;
  652. const List<NodePath> props = sync->get_replication_config()->get_sync_properties();
  653. Error err = MultiplayerSynchronizer::get_state(props, node, vars, varp);
  654. ERR_CONTINUE_MSG(err != OK, "Unable to retrieve sync state.");
  655. err = MultiplayerAPI::encode_and_compress_variants(varp.ptrw(), varp.size(), nullptr, size);
  656. ERR_CONTINUE_MSG(err != OK, "Unable to encode sync state.");
  657. // TODO Handle single state above MTU.
  658. ERR_CONTINUE_MSG(size > 3 + 4 + 4 + sync_mtu, vformat("Node states bigger then MTU will not be sent (%d > %d): %s", size, sync_mtu, node->get_path()));
  659. if (ofs + 4 + 4 + size > sync_mtu) {
  660. // Send what we got, and reset write.
  661. _send_raw(packet_cache.ptr(), ofs, p_peer, false);
  662. ofs = 3;
  663. }
  664. if (size) {
  665. ofs += encode_uint32(sync->get_net_id(), &ptr[ofs]);
  666. ofs += encode_uint32(size, &ptr[ofs]);
  667. MultiplayerAPI::encode_and_compress_variants(varp.ptrw(), varp.size(), &ptr[ofs], size);
  668. ofs += size;
  669. }
  670. #ifdef DEBUG_ENABLED
  671. _profile_node_data("sync_out", oid, size);
  672. #endif
  673. }
  674. if (ofs > 3) {
  675. // Got some left over to send.
  676. _send_raw(packet_cache.ptr(), ofs, p_peer, false);
  677. }
  678. }
  679. Error SceneReplicationInterface::on_sync_receive(int p_from, const uint8_t *p_buffer, int p_buffer_len) {
  680. ERR_FAIL_COND_V_MSG(p_buffer_len < 11, ERR_INVALID_DATA, "Invalid sync packet received");
  681. uint16_t time = decode_uint16(&p_buffer[1]);
  682. int ofs = 3;
  683. while (ofs + 8 < p_buffer_len) {
  684. uint32_t net_id = decode_uint32(&p_buffer[ofs]);
  685. ofs += 4;
  686. uint32_t size = decode_uint32(&p_buffer[ofs]);
  687. ofs += 4;
  688. ERR_FAIL_COND_V(size > uint32_t(p_buffer_len - ofs), ERR_INVALID_DATA);
  689. MultiplayerSynchronizer *sync = nullptr;
  690. if (net_id & 0x80000000) {
  691. sync = Object::cast_to<MultiplayerSynchronizer>(multiplayer->get_path_cache()->get_cached_object(p_from, net_id & 0x7FFFFFFF));
  692. } else if (peers_info[p_from].recv_sync_ids.has(net_id)) {
  693. const ObjectID &sid = peers_info[p_from].recv_sync_ids[net_id];
  694. sync = get_id_as<MultiplayerSynchronizer>(sid);
  695. }
  696. if (!sync) {
  697. // Not received yet.
  698. ofs += size;
  699. continue;
  700. }
  701. Node *node = sync->get_root_node();
  702. if (sync->get_multiplayer_authority() != p_from || !node) {
  703. // Not valid for me.
  704. ofs += size;
  705. ERR_CONTINUE_MSG(true, "Ignoring sync data from non-authority or for missing node.");
  706. }
  707. if (!sync->update_inbound_sync_time(time)) {
  708. // State is too old.
  709. ofs += size;
  710. continue;
  711. }
  712. const List<NodePath> props = sync->get_replication_config()->get_sync_properties();
  713. Vector<Variant> vars;
  714. vars.resize(props.size());
  715. int consumed;
  716. Error err = MultiplayerAPI::decode_and_decompress_variants(vars, &p_buffer[ofs], size, consumed);
  717. ERR_FAIL_COND_V(err, err);
  718. err = MultiplayerSynchronizer::set_state(props, node, vars);
  719. ERR_FAIL_COND_V(err, err);
  720. ofs += size;
  721. sync->emit_signal(SNAME("synchronized"));
  722. #ifdef DEBUG_ENABLED
  723. _profile_node_data("sync_in", sync->get_instance_id(), size);
  724. #endif
  725. }
  726. return OK;
  727. }