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