scene_replication_interface.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. /*************************************************************************/
  2. /* scene_replication_interface.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  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/io/marshalls.h"
  33. #include "scene/main/node.h"
  34. #include "scene/scene_string_names.h"
  35. #define MAKE_ROOM(m_amount) \
  36. if (packet_cache.size() < m_amount) \
  37. packet_cache.resize(m_amount);
  38. SceneReplicationInterface::TrackedNode &SceneReplicationInterface::_track(const ObjectID &p_id) {
  39. if (!tracked_nodes.has(p_id)) {
  40. tracked_nodes[p_id] = TrackedNode(p_id);
  41. Node *node = get_id_as<Node>(p_id);
  42. node->connect(SceneStringNames::get_singleton()->tree_exited, callable_mp(this, &SceneReplicationInterface::_untrack).bind(p_id), Node::CONNECT_ONE_SHOT);
  43. }
  44. return tracked_nodes[p_id];
  45. }
  46. void SceneReplicationInterface::_untrack(const ObjectID &p_id) {
  47. if (!tracked_nodes.has(p_id)) {
  48. return;
  49. }
  50. uint32_t net_id = tracked_nodes[p_id].net_id;
  51. uint32_t peer = tracked_nodes[p_id].remote_peer;
  52. tracked_nodes.erase(p_id);
  53. // If it was spawned by a remote, remove it from the received nodes.
  54. if (peer && peers_info.has(peer)) {
  55. peers_info[peer].recv_nodes.erase(net_id);
  56. }
  57. // If we spawned or synced it, we need to remove it from any peer it was sent to.
  58. if (net_id || peer == 0) {
  59. for (KeyValue<int, PeerInfo> &E : peers_info) {
  60. E.value.spawn_nodes.erase(p_id);
  61. }
  62. }
  63. }
  64. void SceneReplicationInterface::_free_remotes(const PeerInfo &p_info) {
  65. for (const KeyValue<uint32_t, ObjectID> &E : p_info.recv_nodes) {
  66. Node *node = tracked_nodes.has(E.value) ? get_id_as<Node>(E.value) : nullptr;
  67. ERR_CONTINUE(!node);
  68. node->queue_delete();
  69. }
  70. }
  71. void SceneReplicationInterface::on_peer_change(int p_id, bool p_connected) {
  72. if (p_connected) {
  73. peers_info[p_id] = PeerInfo();
  74. for (const ObjectID &oid : spawned_nodes) {
  75. _update_spawn_visibility(p_id, oid);
  76. }
  77. for (const ObjectID &oid : sync_nodes) {
  78. _update_sync_visibility(p_id, get_id_as<MultiplayerSynchronizer>(oid));
  79. }
  80. } else {
  81. ERR_FAIL_COND(!peers_info.has(p_id));
  82. _free_remotes(peers_info[p_id]);
  83. peers_info.erase(p_id);
  84. }
  85. }
  86. void SceneReplicationInterface::on_reset() {
  87. for (const KeyValue<int, PeerInfo> &E : peers_info) {
  88. _free_remotes(E.value);
  89. }
  90. peers_info.clear();
  91. // Tracked nodes are cleared on deletion, here we only reset the ids so they can be later re-assigned.
  92. for (KeyValue<ObjectID, TrackedNode> &E : tracked_nodes) {
  93. TrackedNode &tobj = E.value;
  94. tobj.net_id = 0;
  95. tobj.remote_peer = 0;
  96. }
  97. for (const ObjectID &oid : sync_nodes) {
  98. MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(oid);
  99. ERR_CONTINUE(!sync);
  100. sync->reset();
  101. }
  102. last_net_id = 0;
  103. }
  104. void SceneReplicationInterface::on_network_process() {
  105. uint64_t msec = OS::get_singleton()->get_ticks_msec();
  106. for (KeyValue<int, PeerInfo> &E : peers_info) {
  107. const HashSet<ObjectID> to_sync = E.value.sync_nodes;
  108. if (to_sync.is_empty()) {
  109. continue; // Nothing to sync
  110. }
  111. uint16_t sync_net_time = ++E.value.last_sent_sync;
  112. _send_sync(E.key, to_sync, sync_net_time, msec);
  113. }
  114. }
  115. Error SceneReplicationInterface::on_spawn(Object *p_obj, Variant p_config) {
  116. Node *node = Object::cast_to<Node>(p_obj);
  117. ERR_FAIL_COND_V(!node || p_config.get_type() != Variant::OBJECT, ERR_INVALID_PARAMETER);
  118. MultiplayerSpawner *spawner = Object::cast_to<MultiplayerSpawner>(p_config.get_validated_object());
  119. ERR_FAIL_COND_V(!spawner, ERR_INVALID_PARAMETER);
  120. // Track node.
  121. const ObjectID oid = node->get_instance_id();
  122. TrackedNode &tobj = _track(oid);
  123. ERR_FAIL_COND_V(tobj.spawner != ObjectID(), ERR_ALREADY_IN_USE);
  124. tobj.spawner = spawner->get_instance_id();
  125. spawned_nodes.insert(oid);
  126. if (multiplayer->has_multiplayer_peer() && spawner->is_multiplayer_authority()) {
  127. if (tobj.net_id == 0) {
  128. tobj.net_id = ++last_net_id;
  129. }
  130. _update_spawn_visibility(0, oid);
  131. }
  132. return OK;
  133. }
  134. Error SceneReplicationInterface::on_despawn(Object *p_obj, Variant p_config) {
  135. Node *node = Object::cast_to<Node>(p_obj);
  136. ERR_FAIL_COND_V(!node || p_config.get_type() != Variant::OBJECT, ERR_INVALID_PARAMETER);
  137. MultiplayerSpawner *spawner = Object::cast_to<MultiplayerSpawner>(p_config.get_validated_object());
  138. ERR_FAIL_COND_V(!p_obj || !spawner, ERR_INVALID_PARAMETER);
  139. // Forcibly despawn to all peers that knowns me.
  140. int len = 0;
  141. Error err = _make_despawn_packet(node, len);
  142. ERR_FAIL_COND_V(err != OK, ERR_BUG);
  143. const ObjectID oid = p_obj->get_instance_id();
  144. for (const KeyValue<int, PeerInfo> &E : peers_info) {
  145. if (!E.value.spawn_nodes.has(oid)) {
  146. continue;
  147. }
  148. _send_raw(packet_cache.ptr(), len, E.key, true);
  149. }
  150. // Also remove spawner tracking from the replication state.
  151. ERR_FAIL_COND_V(!tracked_nodes.has(oid), ERR_INVALID_PARAMETER);
  152. TrackedNode &tobj = _track(oid);
  153. ERR_FAIL_COND_V(tobj.spawner != spawner->get_instance_id(), ERR_INVALID_PARAMETER);
  154. tobj.spawner = ObjectID();
  155. spawned_nodes.erase(oid);
  156. for (KeyValue<int, PeerInfo> &E : peers_info) {
  157. E.value.spawn_nodes.erase(oid);
  158. }
  159. return OK;
  160. }
  161. Error SceneReplicationInterface::on_replication_start(Object *p_obj, Variant p_config) {
  162. Node *node = Object::cast_to<Node>(p_obj);
  163. ERR_FAIL_COND_V(!node || p_config.get_type() != Variant::OBJECT, ERR_INVALID_PARAMETER);
  164. MultiplayerSynchronizer *sync = Object::cast_to<MultiplayerSynchronizer>(p_config.get_validated_object());
  165. ERR_FAIL_COND_V(!sync, ERR_INVALID_PARAMETER);
  166. // Add to synchronizer list.
  167. TrackedNode &tobj = _track(p_obj->get_instance_id());
  168. const ObjectID sid = sync->get_instance_id();
  169. tobj.synchronizers.insert(sid);
  170. sync_nodes.insert(sid);
  171. // Update visibility.
  172. sync->connect("visibility_changed", callable_mp(this, &SceneReplicationInterface::_visibility_changed).bind(sync->get_instance_id()));
  173. _update_sync_visibility(0, sync);
  174. if (pending_spawn == p_obj->get_instance_id() && sync->get_multiplayer_authority() == pending_spawn_remote) {
  175. // Try to apply synchronizer Net ID
  176. 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()));
  177. ERR_FAIL_COND_V(!peers_info.has(pending_spawn_remote), ERR_INVALID_DATA);
  178. uint32_t net_id = pending_sync_net_ids[0];
  179. pending_sync_net_ids.pop_front();
  180. peers_info[pending_spawn_remote].recv_sync_ids[net_id] = sync->get_instance_id();
  181. // Try to apply spawn state (before ready).
  182. if (pending_buffer_size > 0) {
  183. ERR_FAIL_COND_V(!node || sync->get_replication_config().is_null(), ERR_UNCONFIGURED);
  184. int consumed = 0;
  185. const List<NodePath> props = sync->get_replication_config()->get_spawn_properties();
  186. Vector<Variant> vars;
  187. vars.resize(props.size());
  188. Error err = MultiplayerAPI::decode_and_decompress_variants(vars, pending_buffer, pending_buffer_size, consumed);
  189. ERR_FAIL_COND_V(err, err);
  190. if (consumed > 0) {
  191. pending_buffer += consumed;
  192. pending_buffer_size -= consumed;
  193. err = MultiplayerSynchronizer::set_state(props, node, vars);
  194. ERR_FAIL_COND_V(err, err);
  195. }
  196. }
  197. }
  198. return OK;
  199. }
  200. Error SceneReplicationInterface::on_replication_stop(Object *p_obj, Variant p_config) {
  201. Node *node = Object::cast_to<Node>(p_obj);
  202. ERR_FAIL_COND_V(!node || p_config.get_type() != Variant::OBJECT, ERR_INVALID_PARAMETER);
  203. MultiplayerSynchronizer *sync = Object::cast_to<MultiplayerSynchronizer>(p_config.get_validated_object());
  204. ERR_FAIL_COND_V(!sync, ERR_INVALID_PARAMETER);
  205. sync->disconnect("visibility_changed", callable_mp(this, &SceneReplicationInterface::_visibility_changed));
  206. // Untrack synchronizer.
  207. const ObjectID oid = node->get_instance_id();
  208. const ObjectID sid = sync->get_instance_id();
  209. ERR_FAIL_COND_V(!tracked_nodes.has(oid), ERR_INVALID_PARAMETER);
  210. TrackedNode &tobj = _track(oid);
  211. tobj.synchronizers.erase(sid);
  212. sync_nodes.erase(sid);
  213. for (KeyValue<int, PeerInfo> &E : peers_info) {
  214. E.value.sync_nodes.erase(sid);
  215. if (sync->get_net_id()) {
  216. E.value.recv_sync_ids.erase(sync->get_net_id());
  217. }
  218. }
  219. return OK;
  220. }
  221. void SceneReplicationInterface::_visibility_changed(int p_peer, ObjectID p_sid) {
  222. MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(p_sid);
  223. ERR_FAIL_COND(!sync); // Bug.
  224. Node *node = sync->get_root_node();
  225. ERR_FAIL_COND(!node); // Bug.
  226. const ObjectID oid = node->get_instance_id();
  227. if (spawned_nodes.has(oid)) {
  228. _update_spawn_visibility(p_peer, oid);
  229. }
  230. _update_sync_visibility(p_peer, sync);
  231. }
  232. Error SceneReplicationInterface::_update_sync_visibility(int p_peer, MultiplayerSynchronizer *p_sync) {
  233. ERR_FAIL_COND_V(!p_sync, ERR_BUG);
  234. if (!multiplayer->has_multiplayer_peer() || !p_sync->is_multiplayer_authority()) {
  235. return OK;
  236. }
  237. const ObjectID &sid = p_sync->get_instance_id();
  238. bool is_visible = p_sync->is_visible_to(p_peer);
  239. if (p_peer == 0) {
  240. for (KeyValue<int, PeerInfo> &E : peers_info) {
  241. // Might be visible to this specific peer.
  242. is_visible = is_visible || p_sync->is_visible_to(E.key);
  243. if (is_visible == E.value.sync_nodes.has(sid)) {
  244. continue;
  245. }
  246. if (is_visible) {
  247. E.value.sync_nodes.insert(sid);
  248. } else {
  249. E.value.sync_nodes.erase(sid);
  250. }
  251. }
  252. return OK;
  253. } else {
  254. ERR_FAIL_COND_V(!peers_info.has(p_peer), ERR_INVALID_PARAMETER);
  255. if (is_visible == peers_info[p_peer].sync_nodes.has(sid)) {
  256. return OK;
  257. }
  258. if (is_visible) {
  259. peers_info[p_peer].sync_nodes.insert(sid);
  260. } else {
  261. peers_info[p_peer].sync_nodes.erase(sid);
  262. }
  263. return OK;
  264. }
  265. }
  266. Error SceneReplicationInterface::_update_spawn_visibility(int p_peer, const ObjectID &p_oid) {
  267. const TrackedNode *tnode = tracked_nodes.getptr(p_oid);
  268. ERR_FAIL_COND_V(!tnode, ERR_BUG);
  269. MultiplayerSpawner *spawner = get_id_as<MultiplayerSpawner>(tnode->spawner);
  270. Node *node = get_id_as<Node>(p_oid);
  271. ERR_FAIL_COND_V(!node || !spawner || !spawner->is_multiplayer_authority(), ERR_BUG);
  272. ERR_FAIL_COND_V(!tracked_nodes.has(p_oid), ERR_BUG);
  273. const HashSet<ObjectID> synchronizers = tracked_nodes[p_oid].synchronizers;
  274. bool is_visible = true;
  275. for (const ObjectID &sid : synchronizers) {
  276. MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(sid);
  277. ERR_CONTINUE(!sync);
  278. if (!sync->is_multiplayer_authority()) {
  279. continue;
  280. }
  281. // Spawn visibility is composed using OR when multiple synchronizers are present.
  282. if (sync->is_visible_to(p_peer)) {
  283. is_visible = true;
  284. break;
  285. }
  286. is_visible = false;
  287. }
  288. // Spawn (and despawn) when needed.
  289. HashSet<int> to_spawn;
  290. HashSet<int> to_despawn;
  291. if (p_peer) {
  292. ERR_FAIL_COND_V(!peers_info.has(p_peer), ERR_INVALID_PARAMETER);
  293. if (is_visible == peers_info[p_peer].spawn_nodes.has(p_oid)) {
  294. return OK;
  295. }
  296. if (is_visible) {
  297. to_spawn.insert(p_peer);
  298. } else {
  299. to_despawn.insert(p_peer);
  300. }
  301. } else {
  302. // Check visibility for each peers.
  303. for (const KeyValue<int, PeerInfo> &E : peers_info) {
  304. if (is_visible) {
  305. // This is fast, since the the object is visibile to everyone, we don't need to check each peer.
  306. if (E.value.spawn_nodes.has(p_oid)) {
  307. // Already spawned.
  308. continue;
  309. }
  310. to_spawn.insert(E.key);
  311. } else {
  312. // Need to check visibility for each peer.
  313. _update_spawn_visibility(E.key, p_oid);
  314. }
  315. }
  316. }
  317. if (to_spawn.size()) {
  318. int len = 0;
  319. _make_spawn_packet(node, spawner, len);
  320. for (int pid : to_spawn) {
  321. ERR_CONTINUE(!peers_info.has(pid));
  322. int path_id;
  323. multiplayer->get_path_cache()->send_object_cache(spawner, pid, path_id);
  324. _send_raw(packet_cache.ptr(), len, pid, true);
  325. peers_info[pid].spawn_nodes.insert(p_oid);
  326. }
  327. }
  328. if (to_despawn.size()) {
  329. int len = 0;
  330. _make_despawn_packet(node, len);
  331. for (int pid : to_despawn) {
  332. ERR_CONTINUE(!peers_info.has(pid));
  333. peers_info[pid].spawn_nodes.erase(p_oid);
  334. _send_raw(packet_cache.ptr(), len, pid, true);
  335. }
  336. }
  337. return OK;
  338. }
  339. Error SceneReplicationInterface::_send_raw(const uint8_t *p_buffer, int p_size, int p_peer, bool p_reliable) {
  340. ERR_FAIL_COND_V(!p_buffer || p_size < 1, ERR_INVALID_PARAMETER);
  341. ERR_FAIL_COND_V(!multiplayer, ERR_UNCONFIGURED);
  342. ERR_FAIL_COND_V(!multiplayer->has_multiplayer_peer(), ERR_UNCONFIGURED);
  343. #ifdef DEBUG_ENABLED
  344. multiplayer->profile_bandwidth("out", p_size);
  345. #endif
  346. Ref<MultiplayerPeer> peer = multiplayer->get_multiplayer_peer();
  347. peer->set_target_peer(p_peer);
  348. peer->set_transfer_channel(0);
  349. peer->set_transfer_mode(p_reliable ? MultiplayerPeer::TRANSFER_MODE_RELIABLE : MultiplayerPeer::TRANSFER_MODE_UNRELIABLE);
  350. return peer->put_packet(p_buffer, p_size);
  351. }
  352. Error SceneReplicationInterface::_make_spawn_packet(Node *p_node, MultiplayerSpawner *p_spawner, int &r_len) {
  353. ERR_FAIL_COND_V(!multiplayer || !p_node || !p_spawner, ERR_BUG);
  354. const ObjectID oid = p_node->get_instance_id();
  355. const TrackedNode *tnode = tracked_nodes.getptr(oid);
  356. ERR_FAIL_COND_V(!tnode, ERR_INVALID_PARAMETER);
  357. uint32_t nid = tnode->net_id;
  358. ERR_FAIL_COND_V(!nid, ERR_UNCONFIGURED);
  359. // Prepare custom arg and scene_id
  360. uint8_t scene_id = p_spawner->find_spawnable_scene_index_from_object(oid);
  361. bool is_custom = scene_id == MultiplayerSpawner::INVALID_ID;
  362. Variant spawn_arg = p_spawner->get_spawn_argument(oid);
  363. int spawn_arg_size = 0;
  364. if (is_custom) {
  365. Error err = MultiplayerAPI::encode_and_compress_variant(spawn_arg, nullptr, spawn_arg_size, false);
  366. ERR_FAIL_COND_V(err, err);
  367. }
  368. // Prepare spawn state.
  369. List<NodePath> state_props;
  370. List<uint32_t> sync_ids;
  371. const HashSet<ObjectID> synchronizers = tnode->synchronizers;
  372. for (const ObjectID &sid : synchronizers) {
  373. MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(sid);
  374. if (!sync->is_multiplayer_authority()) {
  375. continue;
  376. }
  377. ERR_CONTINUE(!sync);
  378. ERR_FAIL_COND_V(sync->get_replication_config().is_null(), ERR_BUG);
  379. for (const NodePath &prop : sync->get_replication_config()->get_spawn_properties()) {
  380. state_props.push_back(prop);
  381. }
  382. // Ensure the synchronizer has an ID.
  383. if (sync->get_net_id() == 0) {
  384. sync->set_net_id(++last_net_id);
  385. }
  386. sync_ids.push_back(sync->get_net_id());
  387. }
  388. int state_size = 0;
  389. Vector<Variant> state_vars;
  390. Vector<const Variant *> state_varp;
  391. if (state_props.size()) {
  392. Error err = MultiplayerSynchronizer::get_state(state_props, p_node, state_vars, state_varp);
  393. ERR_FAIL_COND_V_MSG(err != OK, err, "Unable to retrieve spawn state.");
  394. err = MultiplayerAPI::encode_and_compress_variants(state_varp.ptrw(), state_varp.size(), nullptr, state_size);
  395. ERR_FAIL_COND_V_MSG(err != OK, err, "Unable to encode spawn state.");
  396. }
  397. // Encode scene ID, path ID, net ID, node name.
  398. int path_id = multiplayer->get_path_cache()->make_object_cache(p_spawner);
  399. CharString cname = p_node->get_name().operator String().utf8();
  400. int nlen = encode_cstring(cname.get_data(), nullptr);
  401. MAKE_ROOM(1 + 1 + 4 + 4 + 4 + 4 * sync_ids.size() + 4 + nlen + (is_custom ? 4 + spawn_arg_size : 0) + state_size);
  402. uint8_t *ptr = packet_cache.ptrw();
  403. ptr[0] = (uint8_t)SceneMultiplayer::NETWORK_COMMAND_SPAWN;
  404. ptr[1] = scene_id;
  405. int ofs = 2;
  406. ofs += encode_uint32(path_id, &ptr[ofs]);
  407. ofs += encode_uint32(nid, &ptr[ofs]);
  408. ofs += encode_uint32(sync_ids.size(), &ptr[ofs]);
  409. ofs += encode_uint32(nlen, &ptr[ofs]);
  410. for (uint32_t snid : sync_ids) {
  411. ofs += encode_uint32(snid, &ptr[ofs]);
  412. }
  413. ofs += encode_cstring(cname.get_data(), &ptr[ofs]);
  414. // Write args
  415. if (is_custom) {
  416. ofs += encode_uint32(spawn_arg_size, &ptr[ofs]);
  417. Error err = MultiplayerAPI::encode_and_compress_variant(spawn_arg, &ptr[ofs], spawn_arg_size, false);
  418. ERR_FAIL_COND_V(err, err);
  419. ofs += spawn_arg_size;
  420. }
  421. // Write state.
  422. if (state_size) {
  423. Error err = MultiplayerAPI::encode_and_compress_variants(state_varp.ptrw(), state_varp.size(), &ptr[ofs], state_size);
  424. ERR_FAIL_COND_V(err, err);
  425. ofs += state_size;
  426. }
  427. r_len = ofs;
  428. return OK;
  429. }
  430. Error SceneReplicationInterface::_make_despawn_packet(Node *p_node, int &r_len) {
  431. const ObjectID oid = p_node->get_instance_id();
  432. const TrackedNode *tnode = tracked_nodes.getptr(oid);
  433. ERR_FAIL_COND_V(!tnode, ERR_INVALID_PARAMETER);
  434. MAKE_ROOM(5);
  435. uint8_t *ptr = packet_cache.ptrw();
  436. ptr[0] = (uint8_t)SceneMultiplayer::NETWORK_COMMAND_DESPAWN;
  437. int ofs = 1;
  438. uint32_t nid = tnode->net_id;
  439. ofs += encode_uint32(nid, &ptr[ofs]);
  440. r_len = ofs;
  441. return OK;
  442. }
  443. Error SceneReplicationInterface::on_spawn_receive(int p_from, const uint8_t *p_buffer, int p_buffer_len) {
  444. ERR_FAIL_COND_V_MSG(p_buffer_len < 18, ERR_INVALID_DATA, "Invalid spawn packet received");
  445. int ofs = 1; // The spawn/despawn command.
  446. uint8_t scene_id = p_buffer[ofs];
  447. ofs += 1;
  448. uint32_t node_target = decode_uint32(&p_buffer[ofs]);
  449. ofs += 4;
  450. MultiplayerSpawner *spawner = Object::cast_to<MultiplayerSpawner>(multiplayer->get_path_cache()->get_cached_object(p_from, node_target));
  451. ERR_FAIL_COND_V(!spawner, ERR_DOES_NOT_EXIST);
  452. ERR_FAIL_COND_V(p_from != spawner->get_multiplayer_authority(), ERR_UNAUTHORIZED);
  453. uint32_t net_id = decode_uint32(&p_buffer[ofs]);
  454. ofs += 4;
  455. uint32_t sync_len = decode_uint32(&p_buffer[ofs]);
  456. ofs += 4;
  457. uint32_t name_len = decode_uint32(&p_buffer[ofs]);
  458. ofs += 4;
  459. 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)));
  460. List<uint32_t> sync_ids;
  461. for (uint32_t i = 0; i < sync_len; i++) {
  462. sync_ids.push_back(decode_uint32(&p_buffer[ofs]));
  463. ofs += 4;
  464. }
  465. ERR_FAIL_COND_V_MSG(name_len < 1, ERR_INVALID_DATA, "Zero spawn name size.");
  466. // We need to make sure no trickery happens here, but we want to allow autogenerated ("@") node names.
  467. const String name = String::utf8((const char *)&p_buffer[ofs], name_len);
  468. 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));
  469. ofs += name_len;
  470. // Check that we can spawn.
  471. Node *parent = spawner->get_node_or_null(spawner->get_spawn_path());
  472. ERR_FAIL_COND_V(!parent, ERR_UNCONFIGURED);
  473. ERR_FAIL_COND_V(parent->has_node(name), ERR_INVALID_DATA);
  474. Node *node = nullptr;
  475. if (scene_id == MultiplayerSpawner::INVALID_ID) {
  476. // Custom spawn.
  477. ERR_FAIL_COND_V(p_buffer_len - ofs < 4, ERR_INVALID_DATA);
  478. uint32_t arg_size = decode_uint32(&p_buffer[ofs]);
  479. ofs += 4;
  480. ERR_FAIL_COND_V(arg_size > uint32_t(p_buffer_len - ofs), ERR_INVALID_DATA);
  481. Variant v;
  482. Error err = MultiplayerAPI::decode_and_decompress_variant(v, &p_buffer[ofs], arg_size, nullptr, false);
  483. ERR_FAIL_COND_V(err != OK, err);
  484. ofs += arg_size;
  485. node = spawner->instantiate_custom(v);
  486. } else {
  487. // Scene based spawn.
  488. node = spawner->instantiate_scene(scene_id);
  489. }
  490. ERR_FAIL_COND_V(!node, ERR_UNAUTHORIZED);
  491. node->set_name(name);
  492. // Add and track remote
  493. ERR_FAIL_COND_V(!peers_info.has(p_from), ERR_UNAVAILABLE);
  494. ERR_FAIL_COND_V(peers_info[p_from].recv_nodes.has(net_id), ERR_ALREADY_IN_USE);
  495. ObjectID oid = node->get_instance_id();
  496. TrackedNode &tobj = _track(oid);
  497. tobj.spawner = spawner->get_instance_id();
  498. tobj.net_id = net_id;
  499. tobj.remote_peer = p_from;
  500. peers_info[p_from].recv_nodes[net_id] = oid;
  501. // The initial state will be applied during the sync config (i.e. before _ready).
  502. pending_spawn = node->get_instance_id();
  503. pending_spawn_remote = p_from;
  504. pending_buffer_size = p_buffer_len - ofs;
  505. pending_buffer = pending_buffer_size > 0 ? &p_buffer[ofs] : nullptr;
  506. pending_sync_net_ids = sync_ids;
  507. parent->add_child(node);
  508. spawner->emit_signal(SNAME("spawned"), node);
  509. pending_spawn = ObjectID();
  510. pending_spawn_remote = 0;
  511. pending_buffer = nullptr;
  512. pending_buffer_size = 0;
  513. if (pending_sync_net_ids.size()) {
  514. pending_sync_net_ids.clear();
  515. ERR_FAIL_V(ERR_INVALID_DATA); // Should have been consumed.
  516. }
  517. return OK;
  518. }
  519. Error SceneReplicationInterface::on_despawn_receive(int p_from, const uint8_t *p_buffer, int p_buffer_len) {
  520. ERR_FAIL_COND_V_MSG(p_buffer_len < 5, ERR_INVALID_DATA, "Invalid spawn packet received");
  521. int ofs = 1; // The spawn/despawn command.
  522. uint32_t net_id = decode_uint32(&p_buffer[ofs]);
  523. ofs += 4;
  524. // Untrack remote
  525. ERR_FAIL_COND_V(!peers_info.has(p_from), ERR_UNAUTHORIZED);
  526. PeerInfo &pinfo = peers_info[p_from];
  527. ERR_FAIL_COND_V(!pinfo.recv_nodes.has(net_id), ERR_UNAUTHORIZED);
  528. Node *node = get_id_as<Node>(pinfo.recv_nodes[net_id]);
  529. ERR_FAIL_COND_V(!node, ERR_BUG);
  530. pinfo.recv_nodes.erase(net_id);
  531. const ObjectID oid = node->get_instance_id();
  532. ERR_FAIL_COND_V(!tracked_nodes.has(oid), ERR_BUG);
  533. MultiplayerSpawner *spawner = get_id_as<MultiplayerSpawner>(tracked_nodes[oid].spawner);
  534. ERR_FAIL_COND_V(!spawner, ERR_DOES_NOT_EXIST);
  535. ERR_FAIL_COND_V(p_from != spawner->get_multiplayer_authority(), ERR_UNAUTHORIZED);
  536. if (node->get_parent() != nullptr) {
  537. node->get_parent()->remove_child(node);
  538. }
  539. node->queue_delete();
  540. spawner->emit_signal(SNAME("despawned"), node);
  541. return OK;
  542. }
  543. void SceneReplicationInterface::_send_sync(int p_peer, const HashSet<ObjectID> p_synchronizers, uint16_t p_sync_net_time, uint64_t p_msec) {
  544. MAKE_ROOM(sync_mtu);
  545. uint8_t *ptr = packet_cache.ptrw();
  546. ptr[0] = SceneMultiplayer::NETWORK_COMMAND_SYNC;
  547. int ofs = 1;
  548. ofs += encode_uint16(p_sync_net_time, &ptr[1]);
  549. // Can only send updates for already notified nodes.
  550. // This is a lazy implementation, we could optimize much more here with by grouping by replication config.
  551. for (const ObjectID &oid : p_synchronizers) {
  552. MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(oid);
  553. ERR_CONTINUE(!sync || !sync->get_replication_config().is_valid() || !sync->is_multiplayer_authority());
  554. if (!sync->update_outbound_sync_time(p_msec)) {
  555. continue; // nothing to sync.
  556. }
  557. Node *node = sync->get_root_node();
  558. ERR_CONTINUE(!node);
  559. uint32_t net_id = sync->get_net_id();
  560. if (net_id == 0 || (net_id & 0x80000000)) {
  561. int path_id = 0;
  562. bool verified = multiplayer->get_path_cache()->send_object_cache(sync, p_peer, path_id);
  563. ERR_CONTINUE_MSG(path_id < 0, "This should never happen!");
  564. if (net_id == 0) {
  565. // First time path based ID.
  566. net_id = path_id | 0x80000000;
  567. sync->set_net_id(net_id | 0x80000000);
  568. }
  569. if (!verified) {
  570. // The path based sync is not yet confirmed, skipping.
  571. continue;
  572. }
  573. }
  574. int size;
  575. Vector<Variant> vars;
  576. Vector<const Variant *> varp;
  577. const List<NodePath> props = sync->get_replication_config()->get_sync_properties();
  578. Error err = MultiplayerSynchronizer::get_state(props, node, vars, varp);
  579. ERR_CONTINUE_MSG(err != OK, "Unable to retrieve sync state.");
  580. err = MultiplayerAPI::encode_and_compress_variants(varp.ptrw(), varp.size(), nullptr, size);
  581. ERR_CONTINUE_MSG(err != OK, "Unable to encode sync state.");
  582. // TODO Handle single state above MTU.
  583. 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()));
  584. if (ofs + 4 + 4 + size > sync_mtu) {
  585. // Send what we got, and reset write.
  586. _send_raw(packet_cache.ptr(), ofs, p_peer, false);
  587. ofs = 3;
  588. }
  589. if (size) {
  590. ofs += encode_uint32(sync->get_net_id(), &ptr[ofs]);
  591. ofs += encode_uint32(size, &ptr[ofs]);
  592. MultiplayerAPI::encode_and_compress_variants(varp.ptrw(), varp.size(), &ptr[ofs], size);
  593. ofs += size;
  594. }
  595. }
  596. if (ofs > 3) {
  597. // Got some left over to send.
  598. _send_raw(packet_cache.ptr(), ofs, p_peer, false);
  599. }
  600. }
  601. Error SceneReplicationInterface::on_sync_receive(int p_from, const uint8_t *p_buffer, int p_buffer_len) {
  602. ERR_FAIL_COND_V_MSG(p_buffer_len < 11, ERR_INVALID_DATA, "Invalid sync packet received");
  603. uint16_t time = decode_uint16(&p_buffer[1]);
  604. int ofs = 3;
  605. while (ofs + 8 < p_buffer_len) {
  606. uint32_t net_id = decode_uint32(&p_buffer[ofs]);
  607. ofs += 4;
  608. uint32_t size = decode_uint32(&p_buffer[ofs]);
  609. ofs += 4;
  610. MultiplayerSynchronizer *sync = nullptr;
  611. if (net_id & 0x80000000) {
  612. sync = Object::cast_to<MultiplayerSynchronizer>(multiplayer->get_path_cache()->get_cached_object(p_from, net_id & 0x7FFFFFFF));
  613. } else if (peers_info[p_from].recv_sync_ids.has(net_id)) {
  614. const ObjectID &sid = peers_info[p_from].recv_sync_ids[net_id];
  615. sync = get_id_as<MultiplayerSynchronizer>(sid);
  616. }
  617. if (!sync) {
  618. // Not received yet.
  619. ofs += size;
  620. continue;
  621. }
  622. Node *node = sync->get_root_node();
  623. if (sync->get_multiplayer_authority() != p_from || !node) {
  624. ERR_CONTINUE(true);
  625. }
  626. if (!sync->update_inbound_sync_time(time)) {
  627. // State is too old.
  628. ofs += size;
  629. continue;
  630. }
  631. ERR_FAIL_COND_V(size > uint32_t(p_buffer_len - ofs), ERR_BUG);
  632. const List<NodePath> props = sync->get_replication_config()->get_sync_properties();
  633. Vector<Variant> vars;
  634. vars.resize(props.size());
  635. int consumed;
  636. Error err = MultiplayerAPI::decode_and_decompress_variants(vars, &p_buffer[ofs], size, consumed);
  637. ERR_FAIL_COND_V(err, err);
  638. err = MultiplayerSynchronizer::set_state(props, node, vars);
  639. ERR_FAIL_COND_V(err, err);
  640. ofs += size;
  641. }
  642. return OK;
  643. }