multiplayer_spawner.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /**************************************************************************/
  2. /* multiplayer_spawner.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_spawner.h"
  31. #include "scene/main/multiplayer_api.h"
  32. #ifdef TOOLS_ENABLED
  33. /* This is editor only */
  34. bool MultiplayerSpawner::_set(const StringName &p_name, const Variant &p_value) {
  35. if (p_name == "_spawnable_scene_count") {
  36. spawnable_scenes.resize(p_value);
  37. notify_property_list_changed();
  38. return true;
  39. } else {
  40. String ns = p_name;
  41. if (ns.begins_with("scenes/")) {
  42. uint32_t index = ns.get_slicec('/', 1).to_int();
  43. ERR_FAIL_UNSIGNED_INDEX_V(index, spawnable_scenes.size(), false);
  44. spawnable_scenes[index].path = ResourceUID::ensure_path(p_value);
  45. return true;
  46. }
  47. }
  48. return false;
  49. }
  50. bool MultiplayerSpawner::_get(const StringName &p_name, Variant &r_ret) const {
  51. if (p_name == "_spawnable_scene_count") {
  52. r_ret = spawnable_scenes.size();
  53. return true;
  54. } else {
  55. String ns = p_name;
  56. if (ns.begins_with("scenes/")) {
  57. uint32_t index = ns.get_slicec('/', 1).to_int();
  58. ERR_FAIL_UNSIGNED_INDEX_V(index, spawnable_scenes.size(), false);
  59. r_ret = ResourceUID::path_to_uid(spawnable_scenes[index].path);
  60. return true;
  61. }
  62. }
  63. return false;
  64. }
  65. void MultiplayerSpawner::_get_property_list(List<PropertyInfo> *p_list) const {
  66. p_list->push_back(PropertyInfo(Variant::INT, "_spawnable_scene_count", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_ARRAY, "Auto Spawn List,scenes/"));
  67. List<String> exts;
  68. ResourceLoader::get_recognized_extensions_for_type("PackedScene", &exts);
  69. String ext_hint;
  70. for (const String &E : exts) {
  71. if (!ext_hint.is_empty()) {
  72. ext_hint += ",";
  73. }
  74. ext_hint += "*." + E;
  75. }
  76. for (uint32_t i = 0; i < spawnable_scenes.size(); i++) {
  77. p_list->push_back(PropertyInfo(Variant::STRING, "scenes/" + itos(i), PROPERTY_HINT_FILE, ext_hint, PROPERTY_USAGE_EDITOR));
  78. }
  79. }
  80. #endif
  81. PackedStringArray MultiplayerSpawner::get_configuration_warnings() const {
  82. PackedStringArray warnings = Node::get_configuration_warnings();
  83. if (spawn_path.is_empty() || !has_node(spawn_path)) {
  84. warnings.push_back(RTR("A valid NodePath must be set in the \"Spawn Path\" property in order for MultiplayerSpawner to be able to spawn Nodes."));
  85. }
  86. return warnings;
  87. }
  88. void MultiplayerSpawner::add_spawnable_scene(const String &p_path) {
  89. SpawnableScene sc;
  90. sc.path = ResourceUID::ensure_path(p_path);
  91. if (Engine::get_singleton()->is_editor_hint()) {
  92. ERR_FAIL_COND(!ResourceLoader::exists(sc.path));
  93. }
  94. spawnable_scenes.push_back(sc);
  95. #ifdef TOOLS_ENABLED
  96. if (Engine::get_singleton()->is_editor_hint()) {
  97. return;
  98. }
  99. #endif
  100. Node *node = get_spawn_node();
  101. if (spawnable_scenes.size() == 1 && node && !node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) {
  102. node->connect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));
  103. }
  104. }
  105. int MultiplayerSpawner::get_spawnable_scene_count() const {
  106. return spawnable_scenes.size();
  107. }
  108. String MultiplayerSpawner::get_spawnable_scene(int p_idx) const {
  109. ERR_FAIL_INDEX_V(p_idx, (int)spawnable_scenes.size(), "");
  110. return spawnable_scenes[p_idx].path;
  111. }
  112. void MultiplayerSpawner::clear_spawnable_scenes() {
  113. spawnable_scenes.clear();
  114. #ifdef TOOLS_ENABLED
  115. if (Engine::get_singleton()->is_editor_hint()) {
  116. return;
  117. }
  118. #endif
  119. Node *node = get_spawn_node();
  120. if (node && node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) {
  121. node->disconnect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));
  122. }
  123. }
  124. Vector<String> MultiplayerSpawner::_get_spawnable_scenes() const {
  125. Vector<String> ss;
  126. ss.resize(spawnable_scenes.size());
  127. for (int i = 0; i < ss.size(); i++) {
  128. ss.write[i] = ResourceUID::path_to_uid(spawnable_scenes[i].path);
  129. }
  130. return ss;
  131. }
  132. void MultiplayerSpawner::_set_spawnable_scenes(const Vector<String> &p_scenes) {
  133. clear_spawnable_scenes();
  134. for (int i = 0; i < p_scenes.size(); i++) {
  135. add_spawnable_scene(p_scenes[i]);
  136. }
  137. }
  138. void MultiplayerSpawner::_bind_methods() {
  139. ClassDB::bind_method(D_METHOD("add_spawnable_scene", "path"), &MultiplayerSpawner::add_spawnable_scene);
  140. ClassDB::bind_method(D_METHOD("get_spawnable_scene_count"), &MultiplayerSpawner::get_spawnable_scene_count);
  141. ClassDB::bind_method(D_METHOD("get_spawnable_scene", "index"), &MultiplayerSpawner::get_spawnable_scene);
  142. ClassDB::bind_method(D_METHOD("clear_spawnable_scenes"), &MultiplayerSpawner::clear_spawnable_scenes);
  143. ClassDB::bind_method(D_METHOD("_get_spawnable_scenes"), &MultiplayerSpawner::_get_spawnable_scenes);
  144. ClassDB::bind_method(D_METHOD("_set_spawnable_scenes", "scenes"), &MultiplayerSpawner::_set_spawnable_scenes);
  145. ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "_spawnable_scenes", PROPERTY_HINT_NONE, "", (PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL)), "_set_spawnable_scenes", "_get_spawnable_scenes");
  146. ClassDB::bind_method(D_METHOD("spawn", "data"), &MultiplayerSpawner::spawn, DEFVAL(Variant()));
  147. ClassDB::bind_method(D_METHOD("get_spawn_path"), &MultiplayerSpawner::get_spawn_path);
  148. ClassDB::bind_method(D_METHOD("set_spawn_path", "path"), &MultiplayerSpawner::set_spawn_path);
  149. ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "spawn_path", PROPERTY_HINT_NONE, ""), "set_spawn_path", "get_spawn_path");
  150. ClassDB::bind_method(D_METHOD("get_spawn_limit"), &MultiplayerSpawner::get_spawn_limit);
  151. ClassDB::bind_method(D_METHOD("set_spawn_limit", "limit"), &MultiplayerSpawner::set_spawn_limit);
  152. ADD_PROPERTY(PropertyInfo(Variant::INT, "spawn_limit", PROPERTY_HINT_RANGE, "0,1024,1,or_greater"), "set_spawn_limit", "get_spawn_limit");
  153. ClassDB::bind_method(D_METHOD("get_spawn_function"), &MultiplayerSpawner::get_spawn_function);
  154. ClassDB::bind_method(D_METHOD("set_spawn_function", "spawn_function"), &MultiplayerSpawner::set_spawn_function);
  155. ADD_PROPERTY(PropertyInfo(Variant::CALLABLE, "spawn_function", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_spawn_function", "get_spawn_function");
  156. ADD_SIGNAL(MethodInfo("despawned", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
  157. ADD_SIGNAL(MethodInfo("spawned", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
  158. }
  159. void MultiplayerSpawner::_update_spawn_node() {
  160. #ifdef TOOLS_ENABLED
  161. if (Engine::get_singleton()->is_editor_hint()) {
  162. return;
  163. }
  164. #endif
  165. if (spawn_node.is_valid()) {
  166. Node *node = Object::cast_to<Node>(ObjectDB::get_instance(spawn_node));
  167. if (node && node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) {
  168. node->disconnect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));
  169. }
  170. }
  171. Node *node = spawn_path.is_empty() && is_inside_tree() ? nullptr : get_node_or_null(spawn_path);
  172. if (node) {
  173. spawn_node = node->get_instance_id();
  174. if (get_spawnable_scene_count()) {
  175. node->connect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));
  176. }
  177. } else {
  178. spawn_node = ObjectID();
  179. }
  180. }
  181. void MultiplayerSpawner::_notification(int p_what) {
  182. switch (p_what) {
  183. case NOTIFICATION_POST_ENTER_TREE: {
  184. _update_spawn_node();
  185. } break;
  186. case NOTIFICATION_EXIT_TREE: {
  187. _update_spawn_node();
  188. for (const KeyValue<ObjectID, SpawnInfo> &E : tracked_nodes) {
  189. Node *node = Object::cast_to<Node>(ObjectDB::get_instance(E.key));
  190. ERR_CONTINUE(!node);
  191. node->disconnect(SceneStringName(tree_exiting), callable_mp(this, &MultiplayerSpawner::_node_exit));
  192. get_multiplayer()->object_configuration_remove(node, this);
  193. }
  194. tracked_nodes.clear();
  195. } break;
  196. }
  197. }
  198. void MultiplayerSpawner::_node_added(Node *p_node) {
  199. if (!get_multiplayer()->has_multiplayer_peer() || !is_multiplayer_authority()) {
  200. return;
  201. }
  202. if (tracked_nodes.has(p_node->get_instance_id())) {
  203. return;
  204. }
  205. const Node *parent = get_spawn_node();
  206. if (!parent || p_node->get_parent() != parent) {
  207. return;
  208. }
  209. int id = find_spawnable_scene_index_from_path(p_node->get_scene_file_path());
  210. if (id == INVALID_ID) {
  211. return;
  212. }
  213. const String name = p_node->get_name();
  214. ERR_FAIL_COND_MSG(name.validate_node_name() != name, vformat("Unable to auto-spawn node with reserved name: %s. Make sure to add your replicated scenes via 'add_child(node, true)' to produce valid names.", name));
  215. _track(p_node, Variant(), id);
  216. }
  217. NodePath MultiplayerSpawner::get_spawn_path() const {
  218. return spawn_path;
  219. }
  220. void MultiplayerSpawner::set_spawn_path(const NodePath &p_path) {
  221. spawn_path = p_path;
  222. _update_spawn_node();
  223. update_configuration_warnings();
  224. }
  225. void MultiplayerSpawner::_track(Node *p_node, const Variant &p_argument, int p_scene_id) {
  226. ObjectID oid = p_node->get_instance_id();
  227. if (!tracked_nodes.has(oid)) {
  228. tracked_nodes[oid] = SpawnInfo(p_argument.duplicate(true), p_scene_id);
  229. p_node->connect(SceneStringName(tree_exiting), callable_mp(this, &MultiplayerSpawner::_node_exit).bind(p_node->get_instance_id()), CONNECT_ONE_SHOT);
  230. _spawn_notify(p_node->get_instance_id());
  231. }
  232. }
  233. void MultiplayerSpawner::_spawn_notify(ObjectID p_id) {
  234. get_multiplayer()->object_configuration_add(ObjectDB::get_instance(p_id), this);
  235. }
  236. void MultiplayerSpawner::_node_exit(ObjectID p_id) {
  237. Node *node = Object::cast_to<Node>(ObjectDB::get_instance(p_id));
  238. ERR_FAIL_NULL(node);
  239. if (tracked_nodes.has(p_id)) {
  240. tracked_nodes.erase(p_id);
  241. get_multiplayer()->object_configuration_remove(node, this);
  242. }
  243. }
  244. int MultiplayerSpawner::find_spawnable_scene_index_from_path(const String &p_scene) const {
  245. for (uint32_t i = 0; i < spawnable_scenes.size(); i++) {
  246. if (spawnable_scenes[i].path == p_scene) {
  247. return i;
  248. }
  249. }
  250. return INVALID_ID;
  251. }
  252. int MultiplayerSpawner::find_spawnable_scene_index_from_object(const ObjectID &p_id) const {
  253. const SpawnInfo *info = tracked_nodes.getptr(p_id);
  254. return info ? info->id : INVALID_ID;
  255. }
  256. const Variant MultiplayerSpawner::get_spawn_argument(const ObjectID &p_id) const {
  257. const SpawnInfo *info = tracked_nodes.getptr(p_id);
  258. return info ? info->args : Variant();
  259. }
  260. Node *MultiplayerSpawner::instantiate_scene(int p_id) {
  261. ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!");
  262. ERR_FAIL_UNSIGNED_INDEX_V((uint32_t)p_id, spawnable_scenes.size(), nullptr);
  263. SpawnableScene &sc = spawnable_scenes[p_id];
  264. if (sc.cache.is_null()) {
  265. sc.cache = ResourceLoader::load(sc.path);
  266. }
  267. ERR_FAIL_COND_V_MSG(sc.cache.is_null(), nullptr, "Invalid spawnable scene: " + sc.path);
  268. return sc.cache->instantiate();
  269. }
  270. Node *MultiplayerSpawner::instantiate_custom(const Variant &p_data) {
  271. ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!");
  272. ERR_FAIL_COND_V_MSG(!spawn_function.is_valid(), nullptr, "Custom spawn requires a valid 'spawn_function'.");
  273. const Variant *argv[1] = { &p_data };
  274. Variant ret;
  275. Callable::CallError ce;
  276. spawn_function.callp(argv, 1, ret, ce);
  277. ERR_FAIL_COND_V_MSG(ce.error != Callable::CallError::CALL_OK, nullptr, "Failed to call spawn function.");
  278. ERR_FAIL_COND_V_MSG(ret.get_type() != Variant::OBJECT, nullptr, "The spawn function must return a Node.");
  279. return Object::cast_to<Node>(ret.operator Object *());
  280. }
  281. Node *MultiplayerSpawner::spawn(const Variant &p_data) {
  282. ERR_FAIL_COND_V(!is_inside_tree() || !get_multiplayer()->has_multiplayer_peer() || !is_multiplayer_authority(), nullptr);
  283. ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!");
  284. ERR_FAIL_COND_V_MSG(!spawn_function.is_valid(), nullptr, "Custom spawn requires the 'spawn_function' property to be a valid callable.");
  285. Node *parent = get_spawn_node();
  286. ERR_FAIL_NULL_V_MSG(parent, nullptr, "Cannot find spawn node.");
  287. Node *node = instantiate_custom(p_data);
  288. ERR_FAIL_NULL_V_MSG(node, nullptr, "The 'spawn_function' callable must return a valid node.");
  289. _track(node, p_data);
  290. parent->add_child(node, true);
  291. return node;
  292. }