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