multiplayer_synchronizer.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. /**************************************************************************/
  2. /* multiplayer_synchronizer.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 "multiplayer_synchronizer.h"
  31. #include "core/config/engine.h"
  32. #include "scene/main/multiplayer_api.h"
  33. Object *MultiplayerSynchronizer::_get_prop_target(Object *p_obj, const NodePath &p_path) {
  34. if (p_path.get_name_count() == 0) {
  35. return p_obj;
  36. }
  37. Node *node = Object::cast_to<Node>(p_obj);
  38. ERR_FAIL_COND_V_MSG(!node || !node->has_node(p_path), nullptr, vformat("Node '%s' not found.", p_path));
  39. return node->get_node(p_path);
  40. }
  41. void MultiplayerSynchronizer::_stop() {
  42. #ifdef TOOLS_ENABLED
  43. if (Engine::get_singleton()->is_editor_hint()) {
  44. return;
  45. }
  46. #endif
  47. root_node_cache = ObjectID();
  48. reset();
  49. Node *node = is_inside_tree() ? get_node_or_null(root_path) : nullptr;
  50. if (node) {
  51. get_multiplayer()->object_configuration_remove(node, this);
  52. }
  53. }
  54. void MultiplayerSynchronizer::_start() {
  55. #ifdef TOOLS_ENABLED
  56. if (Engine::get_singleton()->is_editor_hint()) {
  57. return;
  58. }
  59. #endif
  60. root_node_cache = ObjectID();
  61. reset();
  62. Node *node = is_inside_tree() ? get_node_or_null(root_path) : nullptr;
  63. if (node) {
  64. root_node_cache = node->get_instance_id();
  65. get_multiplayer()->object_configuration_add(node, this);
  66. _update_process();
  67. }
  68. }
  69. void MultiplayerSynchronizer::_update_process() {
  70. #ifdef TOOLS_ENABLED
  71. if (Engine::get_singleton()->is_editor_hint()) {
  72. return;
  73. }
  74. #endif
  75. Node *node = is_inside_tree() ? get_node_or_null(root_path) : nullptr;
  76. if (!node) {
  77. return;
  78. }
  79. set_process_internal(false);
  80. set_physics_process_internal(false);
  81. if (!visibility_filters.size()) {
  82. return;
  83. }
  84. switch (visibility_update_mode) {
  85. case VISIBILITY_PROCESS_IDLE:
  86. set_process_internal(true);
  87. break;
  88. case VISIBILITY_PROCESS_PHYSICS:
  89. set_physics_process_internal(true);
  90. break;
  91. case VISIBILITY_PROCESS_NONE:
  92. break;
  93. }
  94. }
  95. Node *MultiplayerSynchronizer::get_root_node() {
  96. return root_node_cache.is_valid() ? Object::cast_to<Node>(ObjectDB::get_instance(root_node_cache)) : nullptr;
  97. }
  98. void MultiplayerSynchronizer::reset() {
  99. net_id = 0;
  100. last_sync_usec = 0;
  101. last_inbound_sync = 0;
  102. }
  103. uint32_t MultiplayerSynchronizer::get_net_id() const {
  104. return net_id;
  105. }
  106. void MultiplayerSynchronizer::set_net_id(uint32_t p_net_id) {
  107. net_id = p_net_id;
  108. }
  109. bool MultiplayerSynchronizer::update_outbound_sync_time(uint64_t p_usec) {
  110. if (last_sync_usec == p_usec) {
  111. // last_sync_usec has been updated in this frame.
  112. return true;
  113. }
  114. if (p_usec < last_sync_usec + sync_interval_usec) {
  115. // Too soon, should skip this synchronization frame.
  116. return false;
  117. }
  118. last_sync_usec = p_usec;
  119. return true;
  120. }
  121. bool MultiplayerSynchronizer::update_inbound_sync_time(uint16_t p_network_time) {
  122. if (p_network_time <= last_inbound_sync && last_inbound_sync - p_network_time < 32767) {
  123. return false;
  124. }
  125. last_inbound_sync = p_network_time;
  126. return true;
  127. }
  128. PackedStringArray MultiplayerSynchronizer::get_configuration_warnings() const {
  129. PackedStringArray warnings = Node::get_configuration_warnings();
  130. if (root_path.is_empty() || !has_node(root_path)) {
  131. warnings.push_back(RTR("A valid NodePath must be set in the \"Root Path\" property in order for MultiplayerSynchronizer to be able to synchronize properties."));
  132. }
  133. return warnings;
  134. }
  135. Error MultiplayerSynchronizer::get_state(const List<NodePath> &p_properties, Object *p_obj, Vector<Variant> &r_variant, Vector<const Variant *> &r_variant_ptrs) {
  136. ERR_FAIL_COND_V(!p_obj, ERR_INVALID_PARAMETER);
  137. r_variant.resize(p_properties.size());
  138. r_variant_ptrs.resize(r_variant.size());
  139. int i = 0;
  140. for (const NodePath &prop : p_properties) {
  141. bool valid = false;
  142. const Object *obj = _get_prop_target(p_obj, prop);
  143. ERR_FAIL_COND_V(!obj, FAILED);
  144. r_variant.write[i] = obj->get(prop.get_concatenated_subnames(), &valid);
  145. r_variant_ptrs.write[i] = &r_variant[i];
  146. ERR_FAIL_COND_V_MSG(!valid, ERR_INVALID_DATA, vformat("Property '%s' not found.", prop));
  147. i++;
  148. }
  149. return OK;
  150. }
  151. Error MultiplayerSynchronizer::set_state(const List<NodePath> &p_properties, Object *p_obj, const Vector<Variant> &p_state) {
  152. ERR_FAIL_COND_V(!p_obj, ERR_INVALID_PARAMETER);
  153. int i = 0;
  154. for (const NodePath &prop : p_properties) {
  155. Object *obj = _get_prop_target(p_obj, prop);
  156. ERR_FAIL_COND_V(!obj, FAILED);
  157. obj->set(prop.get_concatenated_subnames(), p_state[i]);
  158. i += 1;
  159. }
  160. return OK;
  161. }
  162. bool MultiplayerSynchronizer::is_visibility_public() const {
  163. return peer_visibility.has(0);
  164. }
  165. void MultiplayerSynchronizer::set_visibility_public(bool p_visible) {
  166. set_visibility_for(0, p_visible);
  167. }
  168. bool MultiplayerSynchronizer::is_visible_to(int p_peer) {
  169. if (visibility_filters.size()) {
  170. Variant arg = p_peer;
  171. const Variant *argv[1] = { &arg };
  172. for (Callable filter : visibility_filters) {
  173. Variant ret;
  174. Callable::CallError err;
  175. filter.callp(argv, 1, ret, err);
  176. ERR_FAIL_COND_V(err.error != Callable::CallError::CALL_OK || ret.get_type() != Variant::BOOL, false);
  177. if (!ret.operator bool()) {
  178. return false;
  179. }
  180. }
  181. }
  182. return peer_visibility.has(0) || peer_visibility.has(p_peer);
  183. }
  184. void MultiplayerSynchronizer::add_visibility_filter(Callable p_callback) {
  185. visibility_filters.insert(p_callback);
  186. _update_process();
  187. }
  188. void MultiplayerSynchronizer::remove_visibility_filter(Callable p_callback) {
  189. visibility_filters.erase(p_callback);
  190. _update_process();
  191. }
  192. void MultiplayerSynchronizer::set_visibility_for(int p_peer, bool p_visible) {
  193. if (peer_visibility.has(p_peer) == p_visible) {
  194. return;
  195. }
  196. if (p_visible) {
  197. peer_visibility.insert(p_peer);
  198. } else {
  199. peer_visibility.erase(p_peer);
  200. }
  201. update_visibility(p_peer);
  202. }
  203. bool MultiplayerSynchronizer::get_visibility_for(int p_peer) const {
  204. return peer_visibility.has(p_peer);
  205. }
  206. void MultiplayerSynchronizer::set_visibility_update_mode(VisibilityUpdateMode p_mode) {
  207. visibility_update_mode = p_mode;
  208. _update_process();
  209. }
  210. MultiplayerSynchronizer::VisibilityUpdateMode MultiplayerSynchronizer::get_visibility_update_mode() const {
  211. return visibility_update_mode;
  212. }
  213. void MultiplayerSynchronizer::_bind_methods() {
  214. ClassDB::bind_method(D_METHOD("set_root_path", "path"), &MultiplayerSynchronizer::set_root_path);
  215. ClassDB::bind_method(D_METHOD("get_root_path"), &MultiplayerSynchronizer::get_root_path);
  216. ClassDB::bind_method(D_METHOD("set_replication_interval", "milliseconds"), &MultiplayerSynchronizer::set_replication_interval);
  217. ClassDB::bind_method(D_METHOD("get_replication_interval"), &MultiplayerSynchronizer::get_replication_interval);
  218. ClassDB::bind_method(D_METHOD("set_delta_interval", "milliseconds"), &MultiplayerSynchronizer::set_delta_interval);
  219. ClassDB::bind_method(D_METHOD("get_delta_interval"), &MultiplayerSynchronizer::get_delta_interval);
  220. ClassDB::bind_method(D_METHOD("set_replication_config", "config"), &MultiplayerSynchronizer::set_replication_config);
  221. ClassDB::bind_method(D_METHOD("get_replication_config"), &MultiplayerSynchronizer::get_replication_config);
  222. ClassDB::bind_method(D_METHOD("set_visibility_update_mode", "mode"), &MultiplayerSynchronizer::set_visibility_update_mode);
  223. ClassDB::bind_method(D_METHOD("get_visibility_update_mode"), &MultiplayerSynchronizer::get_visibility_update_mode);
  224. ClassDB::bind_method(D_METHOD("update_visibility", "for_peer"), &MultiplayerSynchronizer::update_visibility, DEFVAL(0));
  225. ClassDB::bind_method(D_METHOD("set_visibility_public", "visible"), &MultiplayerSynchronizer::set_visibility_public);
  226. ClassDB::bind_method(D_METHOD("is_visibility_public"), &MultiplayerSynchronizer::is_visibility_public);
  227. ClassDB::bind_method(D_METHOD("add_visibility_filter", "filter"), &MultiplayerSynchronizer::add_visibility_filter);
  228. ClassDB::bind_method(D_METHOD("remove_visibility_filter", "filter"), &MultiplayerSynchronizer::remove_visibility_filter);
  229. ClassDB::bind_method(D_METHOD("set_visibility_for", "peer", "visible"), &MultiplayerSynchronizer::set_visibility_for);
  230. ClassDB::bind_method(D_METHOD("get_visibility_for", "peer"), &MultiplayerSynchronizer::get_visibility_for);
  231. ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "root_path"), "set_root_path", "get_root_path");
  232. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "replication_interval", PROPERTY_HINT_RANGE, "0,5,0.001,suffix:s"), "set_replication_interval", "get_replication_interval");
  233. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "delta_interval", PROPERTY_HINT_RANGE, "0,5,0.001,suffix:s"), "set_delta_interval", "get_delta_interval");
  234. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "replication_config", PROPERTY_HINT_RESOURCE_TYPE, "SceneReplicationConfig", PROPERTY_USAGE_NO_EDITOR), "set_replication_config", "get_replication_config");
  235. ADD_PROPERTY(PropertyInfo(Variant::INT, "visibility_update_mode", PROPERTY_HINT_ENUM, "Idle,Physics,None"), "set_visibility_update_mode", "get_visibility_update_mode");
  236. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "public_visibility"), "set_visibility_public", "is_visibility_public");
  237. BIND_ENUM_CONSTANT(VISIBILITY_PROCESS_IDLE);
  238. BIND_ENUM_CONSTANT(VISIBILITY_PROCESS_PHYSICS);
  239. BIND_ENUM_CONSTANT(VISIBILITY_PROCESS_NONE);
  240. ADD_SIGNAL(MethodInfo("synchronized"));
  241. ADD_SIGNAL(MethodInfo("delta_synchronized"));
  242. ADD_SIGNAL(MethodInfo("visibility_changed", PropertyInfo(Variant::INT, "for_peer")));
  243. }
  244. void MultiplayerSynchronizer::_notification(int p_what) {
  245. #ifdef TOOLS_ENABLED
  246. if (Engine::get_singleton()->is_editor_hint()) {
  247. return;
  248. }
  249. #endif
  250. if (root_path.is_empty()) {
  251. return;
  252. }
  253. switch (p_what) {
  254. case NOTIFICATION_ENTER_TREE: {
  255. _start();
  256. } break;
  257. case NOTIFICATION_EXIT_TREE: {
  258. _stop();
  259. } break;
  260. case NOTIFICATION_INTERNAL_PROCESS:
  261. case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
  262. update_visibility(0);
  263. } break;
  264. }
  265. }
  266. void MultiplayerSynchronizer::set_replication_interval(double p_interval) {
  267. ERR_FAIL_COND_MSG(p_interval < 0, "Interval must be greater or equal to 0 (where 0 means default)");
  268. sync_interval_usec = uint64_t(p_interval * 1000 * 1000);
  269. }
  270. double MultiplayerSynchronizer::get_replication_interval() const {
  271. return double(sync_interval_usec) / 1000.0 / 1000.0;
  272. }
  273. void MultiplayerSynchronizer::set_delta_interval(double p_interval) {
  274. ERR_FAIL_COND_MSG(p_interval < 0, "Interval must be greater or equal to 0 (where 0 means default)");
  275. delta_interval_usec = uint64_t(p_interval * 1000 * 1000);
  276. }
  277. double MultiplayerSynchronizer::get_delta_interval() const {
  278. return double(delta_interval_usec) / 1000.0 / 1000.0;
  279. }
  280. void MultiplayerSynchronizer::set_replication_config(Ref<SceneReplicationConfig> p_config) {
  281. replication_config = p_config;
  282. }
  283. Ref<SceneReplicationConfig> MultiplayerSynchronizer::get_replication_config() {
  284. return replication_config;
  285. }
  286. void MultiplayerSynchronizer::update_visibility(int p_for_peer) {
  287. #ifdef TOOLS_ENABLED
  288. if (Engine::get_singleton()->is_editor_hint()) {
  289. return;
  290. }
  291. #endif
  292. Node *node = is_inside_tree() ? get_node_or_null(root_path) : nullptr;
  293. if (node && get_multiplayer()->has_multiplayer_peer() && is_multiplayer_authority()) {
  294. emit_signal(SNAME("visibility_changed"), p_for_peer);
  295. }
  296. }
  297. void MultiplayerSynchronizer::set_root_path(const NodePath &p_path) {
  298. _stop();
  299. root_path = p_path;
  300. _start();
  301. }
  302. NodePath MultiplayerSynchronizer::get_root_path() const {
  303. return root_path;
  304. }
  305. void MultiplayerSynchronizer::set_multiplayer_authority(int p_peer_id, bool p_recursive) {
  306. Node *node = is_inside_tree() ? get_node_or_null(root_path) : nullptr;
  307. if (!node || get_multiplayer_authority() == p_peer_id) {
  308. Node::set_multiplayer_authority(p_peer_id, p_recursive);
  309. return;
  310. }
  311. get_multiplayer()->object_configuration_remove(node, this);
  312. Node::set_multiplayer_authority(p_peer_id, p_recursive);
  313. get_multiplayer()->object_configuration_add(node, this);
  314. }
  315. Error MultiplayerSynchronizer::_watch_changes(uint64_t p_usec) {
  316. ERR_FAIL_COND_V(replication_config.is_null(), FAILED);
  317. const List<NodePath> props = replication_config->get_watch_properties();
  318. if (props.size() != watchers.size()) {
  319. watchers.resize(props.size());
  320. }
  321. if (props.size() == 0) {
  322. return OK;
  323. }
  324. Node *node = get_root_node();
  325. ERR_FAIL_COND_V(!node, FAILED);
  326. int idx = -1;
  327. Watcher *ptr = watchers.ptrw();
  328. for (const NodePath &prop : props) {
  329. idx++;
  330. bool valid = false;
  331. const Object *obj = _get_prop_target(node, prop);
  332. ERR_CONTINUE_MSG(!obj, vformat("Node not found for property '%s'.", prop));
  333. Variant v = obj->get(prop.get_concatenated_subnames(), &valid);
  334. ERR_CONTINUE_MSG(!valid, vformat("Property '%s' not found.", prop));
  335. Watcher &w = ptr[idx];
  336. if (w.prop != prop) {
  337. w.prop = prop;
  338. w.value = v.duplicate(true);
  339. w.last_change_usec = p_usec;
  340. } else if (!w.value.hash_compare(v)) {
  341. w.value = v.duplicate(true);
  342. w.last_change_usec = p_usec;
  343. }
  344. }
  345. return OK;
  346. }
  347. List<Variant> MultiplayerSynchronizer::get_delta_state(uint64_t p_cur_usec, uint64_t p_last_usec, uint64_t &r_indexes) {
  348. r_indexes = 0;
  349. List<Variant> out;
  350. if (last_watch_usec == p_cur_usec) {
  351. // We already watched for changes in this frame.
  352. } else if (p_cur_usec < p_last_usec + delta_interval_usec) {
  353. // Too soon skip delta synchronization.
  354. return out;
  355. } else {
  356. // Watch for changes.
  357. Error err = _watch_changes(p_cur_usec);
  358. ERR_FAIL_COND_V(err != OK, out);
  359. last_watch_usec = p_cur_usec;
  360. }
  361. const Watcher *ptr = watchers.size() ? watchers.ptr() : nullptr;
  362. for (int i = 0; i < watchers.size(); i++) {
  363. const Watcher &w = ptr[i];
  364. if (w.last_change_usec <= p_last_usec) {
  365. continue;
  366. }
  367. out.push_back(w.value);
  368. r_indexes |= 1ULL << i;
  369. }
  370. return out;
  371. }
  372. List<NodePath> MultiplayerSynchronizer::get_delta_properties(uint64_t p_indexes) {
  373. List<NodePath> out;
  374. ERR_FAIL_COND_V(replication_config.is_null(), out);
  375. const List<NodePath> watch_props = replication_config->get_watch_properties();
  376. int idx = 0;
  377. for (const NodePath &prop : watch_props) {
  378. if ((p_indexes & (1ULL << idx++)) == 0) {
  379. continue;
  380. }
  381. out.push_back(prop);
  382. }
  383. return out;
  384. }
  385. MultiplayerSynchronizer::MultiplayerSynchronizer() {
  386. // Publicly visible by default.
  387. peer_visibility.insert(0);
  388. }