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