Debian Codegraph @

scene/resources/resource_format_text.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* resource_format_text.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 "resource_format_text.h"
32
33 #include "core/config/project_settings.h"
34 #include "core/io/dir_access.h"
35 #include "core/io/missing_resource.h"
36 #include "core/object/script_language.h"
37 #include "scene/property_utils.h"
38
39 void ResourceLoaderText::_printerr() {
40 ERR_PRINT(vformat("%s:%d - Parse Error: %s.", res_path, lines, error_text));
41 }
42
43 Ref<Resource> ResourceLoaderText::get_resource() {
44 return resource;
45 }
46
47 Error ResourceLoaderText::_parse_sub_resource_dummy(DummyReadData *p_data, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
48 VariantParser::Token token;
49 VariantParser::get_token(p_stream, token, line, r_err_str);
50 if (token.type != VariantParser::TK_NUMBER && token.type != VariantParser::TK_STRING) {
51 r_err_str = "Expected number (old style) or string (sub-resource index)";
52 return ERR_PARSE_ERROR;
53 }
54
55 if (p_data->no_placeholders) {
56 r_res.unref();
57 } else {
58 String unique_id = token.value;
59
60 if (!p_data->resource_map.has(unique_id)) {
61 r_err_str = "Found unique_id reference before mapping, sub-resources stored out of order in resource file";
62 return ERR_PARSE_ERROR;
63 }
64
65 r_res = p_data->resource_map[unique_id];
66 }
67
68 VariantParser::get_token(p_stream, token, line, r_err_str);
69 if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
70 r_err_str = "Expected ')'";
71 return ERR_PARSE_ERROR;
72 }
73
74 return OK;
75 }
76
77 Error ResourceLoaderText::_parse_ext_resource_dummy(DummyReadData *p_data, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
78 VariantParser::Token token;
79 VariantParser::get_token(p_stream, token, line, r_err_str);
80 if (token.type != VariantParser::TK_NUMBER && token.type != VariantParser::TK_STRING) {
81 r_err_str = "Expected number (old style sub-resource index) or String (ext-resource ID)";
82 return ERR_PARSE_ERROR;
83 }
84
85 if (p_data->no_placeholders) {
86 r_res.unref();
87 } else {
88 String id = token.value;
89
90 ERR_FAIL_COND_V(!p_data->rev_external_resources.has(id), ERR_PARSE_ERROR);
91
92 r_res = p_data->rev_external_resources[id];
93 }
94
95 VariantParser::get_token(p_stream, token, line, r_err_str);
96 if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
97 r_err_str = "Expected ')'";
98 return ERR_PARSE_ERROR;
99 }
100
101 return OK;
102 }
103
104 Error ResourceLoaderText::_parse_sub_resource(VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
105 VariantParser::Token token;
106 VariantParser::get_token(p_stream, token, line, r_err_str);
107 if (token.type != VariantParser::TK_NUMBER && token.type != VariantParser::TK_STRING) {
108 r_err_str = "Expected number (old style sub-resource index) or string";
109 return ERR_PARSE_ERROR;
110 }
111
112 String id = token.value;
113 ERR_FAIL_COND_V(!int_resources.has(id), ERR_INVALID_PARAMETER);
114 r_res = int_resources[id];
115
116 VariantParser::get_token(p_stream, token, line, r_err_str);
117 if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
118 r_err_str = "Expected ')'";
119 return ERR_PARSE_ERROR;
120 }
121
122 return OK;
123 }
124
125 Error ResourceLoaderText::_parse_ext_resource(VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
126 VariantParser::Token token;
127 VariantParser::get_token(p_stream, token, line, r_err_str);
128 if (token.type != VariantParser::TK_NUMBER && token.type != VariantParser::TK_STRING) {
129 r_err_str = "Expected number (old style sub-resource index) or String (ext-resource ID)";
130 return ERR_PARSE_ERROR;
131 }
132
133 String id = token.value;
134 Error err = OK;
135
136 if (!ignore_resource_parsing) {
137 if (!ext_resources.has(id)) {
138 r_err_str = "Can't load cached ext-resource id: " + id;
139 return ERR_PARSE_ERROR;
140 }
141
142 String path = ext_resources[id].path;
143 String type = ext_resources[id].type;
144 Ref<ResourceLoader::LoadToken> &load_token = ext_resources[id].load_token;
145
146 if (load_token.is_valid()) { // If not valid, it's OK since then we know this load accepts broken dependencies.
147 Ref<Resource> res = ResourceLoader::_load_complete(*load_token.ptr(), &err);
148 if (res.is_null()) {
149 if (!ResourceLoader::is_cleaning_tasks()) {
150 if (ResourceLoader::get_abort_on_missing_resources()) {
151 error = ERR_FILE_MISSING_DEPENDENCIES;
152 error_text = "[ext_resource] referenced non-existent resource at: " + path;
153 _printerr();
154 err = error;
155 } else {
156 ResourceLoader::notify_dependency_error(local_path, path, type);
157 }
158 }
159 } else {
160 r_res = res;
161 }
162 } else {
163 r_res = Ref<Resource>();
164 }
165 #ifdef TOOLS_ENABLED
166 if (r_res.is_null()) {
167 // Hack to allow checking original path.
168 r_res.instantiate();
169 r_res->set_meta("__load_path__", ext_resources[id].path);
170 }
171 #endif
172 }
173
174 VariantParser::get_token(p_stream, token, line, r_err_str);
175 if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
176 r_err_str = "Expected ')'";
177 return ERR_PARSE_ERROR;
178 }
179
180 return err;
181 }
182
183 Ref<PackedScene> ResourceLoaderText::_parse_node_tag(VariantParser::ResourceParser &parser) {
184 Ref<PackedScene> packed_scene = ResourceLoader::get_resource_ref_override(local_path);
185 if (packed_scene.is_null()) {
186 packed_scene.instantiate();
187 }
188
189 while (true) {
190 if (next_tag.name == "node") {
191 int parent = -1;
192 int owner = -1;
193 int type = -1;
194 int name = -1;
195 int instance = -1;
196 int index = -1;
197 int unique_id = Node::UNIQUE_SCENE_ID_UNASSIGNED;
198
199 //int base_scene=-1;
200
201 if (next_tag.fields.has("name")) {
202 name = packed_scene->get_state()->add_name(next_tag.fields["name"]);
203 }
204
205 if (next_tag.fields.has("parent")) {
206 NodePath np = next_tag.fields["parent"];
207 np.prepend_period();
208 PackedInt32Array np_id;
209 if (next_tag.fields.has("parent_id_path")) {
210 np_id = next_tag.fields["parent_id_path"];
211 }
212 parent = packed_scene->get_state()->add_node_path(np, np_id);
213 }
214 if (next_tag.fields.has("unique_id")) {
215 unique_id = next_tag.fields["unique_id"];
216 }
217
218 if (next_tag.fields.has("type")) {
219 type = packed_scene->get_state()->add_name(next_tag.fields["type"]);
220 } else {
221 type = SceneState::TYPE_INSTANTIATED; //no type? assume this was instantiated
222 }
223
224 HashSet<StringName> path_properties;
225
226 if (next_tag.fields.has("node_paths")) {
227 Vector<String> paths = next_tag.fields["node_paths"];
228 for (int i = 0; i < paths.size(); i++) {
229 path_properties.insert(paths[i]);
230 }
231 }
232
233 if (next_tag.fields.has("instance")) {
234 instance = packed_scene->get_state()->add_value(next_tag.fields["instance"]);
235
236 if (packed_scene->get_state()->get_node_count() == 0 && parent == -1) {
237 packed_scene->get_state()->set_base_scene(instance);
238 instance = -1;
239 }
240 }
241
242 if (next_tag.fields.has("instance_placeholder")) {
243 String path = next_tag.fields["instance_placeholder"];
244
245 int path_v = packed_scene->get_state()->add_value(path);
246
247 if (packed_scene->get_state()->get_node_count() == 0) {
248 error = ERR_FILE_CORRUPT;
249 error_text = "Instance Placeholder can't be used for inheritance";
250 _printerr();
251 return Ref<PackedScene>();
252 }
253
254 instance = path_v | SceneState::FLAG_INSTANCE_IS_PLACEHOLDER;
255 }
256
257 if (next_tag.fields.has("owner")) {
258 PackedInt32Array np_id;
259 if (next_tag.fields.has("owner_uid_path")) {
260 np_id = next_tag.fields["owner_uid_path"];
261 }
262 owner = packed_scene->get_state()->add_node_path(next_tag.fields["owner"], np_id);
263 } else {
264 if (parent != -1 && !(type == SceneState::TYPE_INSTANTIATED && instance == -1)) {
265 owner = 0; //if no owner, owner is root
266 }
267 }
268
269 if (next_tag.fields.has("index")) {
270 index = next_tag.fields["index"];
271 }
272
273 int node_id = packed_scene->get_state()->add_node(parent, owner, type, name, instance, index, unique_id);
274
275 if (next_tag.fields.has("groups")) {
276 Array groups = next_tag.fields["groups"];
277 for (const Variant &group : groups) {
278 packed_scene->get_state()->add_node_group(node_id, packed_scene->get_state()->add_name(group));
279 }
280 }
281
282 while (true) {
283 String assign;
284 Variant value;
285
286 error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &parser);
287
288 if (error) {
289 if (error == ERR_FILE_MISSING_DEPENDENCIES) {
290 // Resource loading error, just skip it.
291 } else if (error != ERR_FILE_EOF) {
292 ERR_PRINT(vformat("Parse Error: %s. [Resource file %s:%d]", error_names[error], res_path, lines));
293 return Ref<PackedScene>();
294 } else {
295 error = OK;
296 return packed_scene;
297 }
298 }
299
300 if (!assign.is_empty()) {
301 StringName assign_name = assign;
302 int nameidx = packed_scene->get_state()->add_name(assign_name);
303 int valueidx = packed_scene->get_state()->add_value(value);
304 packed_scene->get_state()->add_node_property(node_id, nameidx, valueidx, path_properties.has(assign_name));
305 //it's assignment
306 } else if (!next_tag.name.is_empty()) {
307 break;
308 }
309 }
310 } else if (next_tag.name == "connection") {
311 if (!next_tag.fields.has("from")) {
312 error = ERR_FILE_CORRUPT;
313 error_text = "missing 'from' field from connection tag";
314 return Ref<PackedScene>();
315 }
316
317 if (!next_tag.fields.has("to")) {
318 error = ERR_FILE_CORRUPT;
319 error_text = "missing 'to' field from connection tag";
320 return Ref<PackedScene>();
321 }
322
323 if (!next_tag.fields.has("signal")) {
324 error = ERR_FILE_CORRUPT;
325 error_text = "missing 'signal' field from connection tag";
326 return Ref<PackedScene>();
327 }
328
329 if (!next_tag.fields.has("method")) {
330 error = ERR_FILE_CORRUPT;
331 error_text = "missing 'method' field from connection tag";
332 return Ref<PackedScene>();
333 }
334
335 NodePath from = next_tag.fields["from"];
336 NodePath to = next_tag.fields["to"];
337 StringName method = next_tag.fields["method"];
338 StringName signal = next_tag.fields["signal"];
339 int flags = Object::CONNECT_PERSIST;
340 int unbinds = 0;
341 Array binds;
342
343 PackedInt32Array from_id;
344 if (next_tag.fields.has("from_uid_path")) {
345 from_id = next_tag.fields["from_uid_path"];
346 }
347
348 PackedInt32Array to_id;
349 if (next_tag.fields.has("to_uid_path")) {
350 to_id = next_tag.fields["to_uid_path"];
351 }
352
353 if (next_tag.fields.has("flags")) {
354 flags = next_tag.fields["flags"];
355 }
356
357 if (next_tag.fields.has("binds")) {
358 binds = next_tag.fields["binds"];
359 }
360
361 if (next_tag.fields.has("unbinds")) {
362 unbinds = next_tag.fields["unbinds"];
363 }
364
365 Vector<int> bind_ints;
366 for (const Variant &bind : binds) {
367 bind_ints.push_back(packed_scene->get_state()->add_value(bind));
368 }
369
370 packed_scene->get_state()->add_connection(
371 packed_scene->get_state()->add_node_path(from.simplified(), from_id),
372 packed_scene->get_state()->add_node_path(to.simplified(), to_id),
373 packed_scene->get_state()->add_name(signal),
374 packed_scene->get_state()->add_name(method),
375 flags,
376 unbinds,
377 bind_ints);
378
379 error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &parser);
380
381 if (error) {
382 if (error != ERR_FILE_EOF) {
383 _printerr();
384 return Ref<PackedScene>();
385 } else {
386 error = OK;
387 return packed_scene;
388 }
389 }
390 } else if (next_tag.name == "editable") {
391 if (!next_tag.fields.has("path")) {
392 error = ERR_FILE_CORRUPT;
393 error_text = "Missing 'path' field from editable tag";
394 _printerr();
395 return Ref<PackedScene>();
396 }
397
398 NodePath path = next_tag.fields["path"];
399
400 packed_scene->get_state()->add_editable_instance(path.simplified());
401
402 error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &parser);
403
404 if (error) {
405 if (error != ERR_FILE_EOF) {
406 _printerr();
407 return Ref<PackedScene>();
408 } else {
409 error = OK;
410 return packed_scene;
411 }
412 }
413 } else {
414 error = ERR_FILE_CORRUPT;
415 error_text = vformat("Unknown tag '%s' in file", next_tag.name);
416 _printerr();
417 return Ref<PackedScene>();
418 }
419 }
420 }
421
422 void ResourceLoaderText::_count_resources() {
423 Ref<FileAccess> scan_f = FileAccess::open(f->get_path(), FileAccess::READ);
424 if (scan_f.is_null()) {
425 return;
426 }
427
428 resources_total = 0;
429 resource_current = 0;
430
431 bool has_main_resource = false;
432 while (!scan_f->eof_reached()) {
433 String line = scan_f->get_line().strip_edges();
434
435 // Only count resources that contribute to progress
436 // (ext_resources are loaded asynchronously and don't count).
437 // Note: nodes are all parsed together as part of the main resource (PackedScene),
438 // so they only contribute 1 to the progress count, not one per node.
439 if (line.begins_with("[sub_resource ")) {
440 resources_total++;
441 } else if (line.begins_with("[resource]") || line.begins_with("[node ")) {
442 // Main resource or scene with nodes - only count once.
443 if (!has_main_resource) {
444 resources_total++;
445 has_main_resource = true;
446 }
447 }
448 }
449 }
450
451 Error ResourceLoaderText::load() {
452 if (error != OK) {
453 return error;
454 }
455
456 if (progress) {
457 _count_resources();
458 }
459
460 while (true) {
461 if (next_tag.name != "ext_resource") {
462 break;
463 }
464
465 if (!next_tag.fields.has("path")) {
466 error = ERR_FILE_CORRUPT;
467 error_text = "Missing 'path' in external resource tag";
468 _printerr();
469 return error;
470 }
471
472 if (!next_tag.fields.has("type")) {
473 error = ERR_FILE_CORRUPT;
474 error_text = "Missing 'type' in external resource tag";
475 _printerr();
476 return error;
477 }
478
479 if (!next_tag.fields.has("id")) {
480 error = ERR_FILE_CORRUPT;
481 error_text = "Missing 'id' in external resource tag";
482 _printerr();
483 return error;
484 }
485
486 String path = next_tag.fields["path"];
487 String type = next_tag.fields["type"];
488 String id = next_tag.fields["id"];
489
490 if (next_tag.fields.has("uid")) {
491 String uidt = next_tag.fields["uid"];
492 ResourceUID::ID uid = ResourceUID::get_singleton()->text_to_id(uidt);
493 if (uid != ResourceUID::INVALID_ID && ResourceUID::get_singleton()->has_id(uid)) {
494 // If a UID is found and the path is valid, it will be used, otherwise, it falls back to the path.
495 path = ResourceUID::get_singleton()->get_id_path(uid);
496 } else {
497 #ifdef TOOLS_ENABLED
498 // Silence a warning that can happen during the initial filesystem scan due to cache being regenerated.
499 if (ResourceLoader::get_resource_uid(path) != uid) {
500 WARN_PRINT(String(res_path + ":" + itos(lines) + " - ext_resource, invalid UID: " + uidt + " - using text path instead: " + path).utf8().get_data());
501 }
502 #else
503 WARN_PRINT(String(res_path + ":" + itos(lines) + " - ext_resource, invalid UID: " + uidt + " - using text path instead: " + path).utf8().get_data());
504 #endif
505 }
506 }
507
508 if (!path.contains("://") && path.is_relative_path()) {
509 // path is relative to file being loaded, so convert to a resource path
510 path = ProjectSettings::get_singleton()->localize_path(local_path.get_base_dir().path_join(path));
511 }
512
513 if (remaps.has(path)) {
514 path = remaps[path];
515 }
516
517 ext_resources[id].path = path;
518 ext_resources[id].type = type;
519 ext_resources[id].load_token = ResourceLoader::_load_start(path, type, use_sub_threads ? ResourceLoader::LOAD_THREAD_DISTRIBUTE : ResourceLoader::LOAD_THREAD_FROM_CURRENT, cache_mode_for_external);
520 if (ext_resources[id].load_token.is_null()) {
521 if (ResourceLoader::get_abort_on_missing_resources()) {
522 error = ERR_FILE_CORRUPT;
523 error_text = "[ext_resource] referenced non-existent resource at: " + path;
524 _printerr();
525 return error;
526 } else {
527 ResourceLoader::notify_dependency_error(local_path, path, type);
528 }
529 }
530
531 error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
532
533 if (error) {
534 _printerr();
535 return error;
536 }
537 }
538
539 #ifdef TOOLS_ENABLED
540 for (const KeyValue<String, ExtResource> &E : ext_resources) {
541 // Remember ID for saving.
542 Resource::set_resource_id_for_path(local_path, E.value.path, E.key);
543 }
544 #endif
545
546 while (true) {
547 if (next_tag.name != "sub_resource") {
548 break;
549 }
550
551 if (!next_tag.fields.has("type")) {
552 error = ERR_FILE_CORRUPT;
553 error_text = "Missing 'type' in external resource tag";
554 _printerr();
555 return error;
556 }
557
558 if (!next_tag.fields.has("id")) {
559 error = ERR_FILE_CORRUPT;
560 error_text = "Missing 'id' in external resource tag";
561 _printerr();
562 return error;
563 }
564
565 String type = next_tag.fields["type"];
566 String id = next_tag.fields["id"];
567
568 String path = local_path + "::" + id;
569
570 //bool exists=ResourceCache::has(path);
571
572 Ref<Resource> res;
573 bool do_assign = false;
574
575 if (cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE && ResourceCache::has(path)) {
576 //reuse existing
577 Ref<Resource> cache = ResourceCache::get_ref(path);
578 if (cache.is_valid() && cache->get_class() == type) {
579 res = cache;
580 res->reset_state();
581 do_assign = true;
582 }
583 }
584
585 MissingResource *missing_resource = nullptr;
586
587 if (res.is_null()) { //not reuse
588 Ref<Resource> cache = ResourceCache::get_ref(path);
589 if (cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE && cache.is_valid()) { //only if it doesn't exist
590 //cached, do not assign
591 res = cache;
592 } else {
593 //create
594
595 Object *obj = ClassDB::instantiate(type);
596 if (!obj) {
597 if (ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
598 missing_resource = memnew(MissingResource);
599 missing_resource->set_original_class(type);
600 missing_resource->set_recording_properties(true);
601 obj = missing_resource;
602 } else {
603 error_text = vformat("Can't create sub resource of type '%s'", type);
604 _printerr();
605 error = ERR_FILE_CORRUPT;
606 return error;
607 }
608 }
609
610 Resource *r = Object::cast_to<Resource>(obj);
611 if (!r) {
612 error_text = vformat("Can't create sub resource of type '%s' as it's not a resource type", type);
613 _printerr();
614 error = ERR_FILE_CORRUPT;
615 return error;
616 }
617
618 res = Ref<Resource>(r);
619 do_assign = true;
620 }
621 }
622
623 resource_current++;
624
625 if (progress && resources_total > 0) {
626 *progress = resource_current / float(resources_total);
627 }
628
629 int_resources[id] = res; // Always assign int resources.
630 if (do_assign) {
631 if (cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
632 res->set_path(path, cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE);
633 } else {
634 res->set_path_cache(path);
635 }
636 res->set_scene_unique_id(id);
637 }
638
639 Dictionary missing_resource_properties;
640
641 while (true) {
642 String assign;
643 Variant value;
644
645 error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp);
646
647 if (error) {
648 _printerr();
649 return error;
650 }
651
652 if (!assign.is_empty()) {
653 if (do_assign) {
654 bool set_valid = true;
655
656 if (value.get_type() == Variant::OBJECT && missing_resource == nullptr && ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
657 // If the property being set is a missing resource (and the parent is not),
658 // then setting it will most likely not work.
659 // Instead, save it as metadata.
660
661 Ref<MissingResource> mr = value;
662 if (mr.is_valid()) {
663 missing_resource_properties[assign] = mr;
664 set_valid = false;
665 }
666 }
667
668 if (value.get_type() == Variant::ARRAY) {
669 Array set_array = value;
670 bool is_get_valid = false;
671 Variant get_value = res->get(assign, &is_get_valid);
672 if (is_get_valid && get_value.get_type() == Variant::ARRAY) {
673 Array get_array = get_value;
674 if (!set_array.is_same_typed(get_array)) {
675 value = Array(set_array, get_array.get_typed_builtin(), get_array.get_typed_class_name(), get_array.get_typed_script());
676 }
677 }
678 }
679
680 if (value.get_type() == Variant::DICTIONARY) {
681 Dictionary set_dict = value;
682 bool is_get_valid = false;
683 Variant get_value = res->get(assign, &is_get_valid);
684 if (is_get_valid && get_value.get_type() == Variant::DICTIONARY) {
685 Dictionary get_dict = get_value;
686 if (!set_dict.is_same_typed(get_dict)) {
687 value = Dictionary(set_dict, get_dict.get_typed_key_builtin(), get_dict.get_typed_key_class_name(), get_dict.get_typed_key_script(),
688 get_dict.get_typed_value_builtin(), get_dict.get_typed_value_class_name(), get_dict.get_typed_value_script());
689 }
690 }
691 }
692
693 if (set_valid) {
694 res->set(assign, value);
695 }
696 }
697 //it's assignment
698 } else if (!next_tag.name.is_empty()) {
699 error = OK;
700 break;
701 } else {
702 error = ERR_FILE_CORRUPT;
703 error_text = "Premature end of file while parsing [sub_resource]";
704 _printerr();
705 return error;
706 }
707 }
708
709 if (missing_resource) {
710 missing_resource->set_recording_properties(false);
711 }
712
713 if (!missing_resource_properties.is_empty()) {
714 res->set_meta(META_MISSING_RESOURCES, missing_resource_properties);
715 }
716 }
717
718 while (true) {
719 if (next_tag.name != "resource") {
720 break;
721 }
722
723 if (is_scene) {
724 error_text = "Unexpected 'resource' tag in a scene file";
725 _printerr();
726 error = ERR_FILE_CORRUPT;
727 return error;
728 }
729
730 MissingResource *missing_resource = nullptr;
731
732 resource = ResourceLoader::get_resource_ref_override(local_path);
733 if (resource.is_null()) {
734 Ref<Resource> cache = ResourceCache::get_ref(local_path);
735 if (cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE && cache.is_valid() && cache->get_class() == res_type) {
736 cache->reset_state();
737 resource = cache;
738 }
739
740 if (resource.is_null()) {
741 Object *obj = ClassDB::instantiate(res_type);
742 if (!obj) {
743 if (ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
744 missing_resource = memnew(MissingResource);
745 missing_resource->set_original_class(res_type);
746 missing_resource->set_recording_properties(true);
747 obj = missing_resource;
748 } else {
749 error_text = vformat("Can't create sub resource of type '%s'", res_type);
750 _printerr();
751 error = ERR_FILE_CORRUPT;
752 return error;
753 }
754 }
755
756 Resource *r = Object::cast_to<Resource>(obj);
757 if (!r) {
758 error_text = vformat("Can't create sub resource of type '%s' as it's not a resource type", res_type);
759 _printerr();
760 error = ERR_FILE_CORRUPT;
761 return error;
762 }
763
764 resource = Ref<Resource>(r);
765 }
766 }
767
768 Dictionary missing_resource_properties;
769
770 while (true) {
771 String assign;
772 Variant value;
773
774 error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp);
775
776 if (error) {
777 if (error != ERR_FILE_EOF) {
778 _printerr();
779 return error;
780 }
781 // EOF, Done parsing.
782 error = OK;
783 if (cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
784 if (!ResourceCache::has(res_path)) {
785 resource->set_path(res_path);
786 }
787 resource->set_as_translation_remapped(translation_remapped);
788 } else {
789 resource->set_path_cache(res_path);
790 }
791 break;
792 }
793
794 if (!assign.is_empty()) {
795 bool set_valid = true;
796
797 if (value.get_type() == Variant::OBJECT && missing_resource == nullptr && ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
798 // If the property being set is a missing resource (and the parent is not),
799 // then setting it will most likely not work.
800 // Instead, save it as metadata.
801
802 Ref<MissingResource> mr = value;
803 if (mr.is_valid()) {
804 missing_resource_properties[assign] = mr;
805 set_valid = false;
806 }
807 }
808
809 if (value.get_type() == Variant::ARRAY) {
810 Array set_array = value;
811 bool is_get_valid = false;
812 Variant get_value = resource->get(assign, &is_get_valid);
813 if (is_get_valid && get_value.get_type() == Variant::ARRAY) {
814 Array get_array = get_value;
815 if (!set_array.is_same_typed(get_array)) {
816 value = Array(set_array, get_array.get_typed_builtin(), get_array.get_typed_class_name(), get_array.get_typed_script());
817 }
818 }
819 }
820
821 if (value.get_type() == Variant::DICTIONARY) {
822 Dictionary set_dict = value;
823 bool is_get_valid = false;
824 Variant get_value = resource->get(assign, &is_get_valid);
825 if (is_get_valid && get_value.get_type() == Variant::DICTIONARY) {
826 Dictionary get_dict = get_value;
827 if (!set_dict.is_same_typed(get_dict)) {
828 value = Dictionary(set_dict, get_dict.get_typed_key_builtin(), get_dict.get_typed_key_class_name(), get_dict.get_typed_key_script(),
829 get_dict.get_typed_value_builtin(), get_dict.get_typed_value_class_name(), get_dict.get_typed_value_script());
830 }
831 }
832 }
833
834 if (set_valid) {
835 resource->set(assign, value);
836 }
837 //it's assignment
838 } else if (!next_tag.name.is_empty()) {
839 error = ERR_FILE_CORRUPT;
840 error_text = "Extra tag found when parsing main resource file";
841 _printerr();
842 return error;
843 } else {
844 break;
845 }
846 }
847
848 resource_current++;
849
850 if (progress && resources_total > 0) {
851 *progress = resource_current / float(resources_total);
852 }
853
854 if (missing_resource) {
855 missing_resource->set_recording_properties(false);
856 }
857
858 if (!missing_resource_properties.is_empty()) {
859 resource->set_meta(META_MISSING_RESOURCES, missing_resource_properties);
860 }
861
862 error = OK;
863
864 return error;
865 }
866
867 //for scene files
868
869 if (next_tag.name == "node") {
870 if (!is_scene) {
871 error_text = "Unexpected 'node' tag in a resource file";
872 _printerr();
873 error = ERR_FILE_CORRUPT;
874 return error;
875 }
876
877 Ref<PackedScene> packed_scene = _parse_node_tag(rp);
878
879 if (packed_scene.is_null()) {
880 return error;
881 }
882
883 error = OK;
884 //get it here
885 resource = packed_scene;
886 if (cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
887 if (!ResourceCache::has(res_path)) {
888 packed_scene->set_path(res_path);
889 }
890 } else {
891 packed_scene->get_state()->set_path(res_path);
892 packed_scene->set_path_cache(res_path);
893 }
894
895 resource_current++;
896
897 if (progress && resources_total > 0) {
898 *progress = resource_current / float(resources_total);
899 }
900
901 return error;
902 } else {
903 error_text = vformat("Unknown tag '%s' in file", next_tag.name);
904 _printerr();
905 error = ERR_FILE_CORRUPT;
906 return error;
907 }
908 }
909
910 int ResourceLoaderText::get_stage() const {
911 return resource_current;
912 }
913
914 int ResourceLoaderText::get_stage_count() const {
915 return resources_total; //+ext_resources;
916 }
917
918 void ResourceLoaderText::set_translation_remapped(bool p_remapped) {
919 translation_remapped = p_remapped;
920 }
921
922 ResourceLoaderText::ResourceLoaderText() :
923 stream(false), format_version(FORMAT_VERSION) {}
924
925 void ResourceLoaderText::get_dependencies(Ref<FileAccess> p_f, List<String> *p_dependencies, bool p_add_types) {
926 open(p_f);
927 ignore_resource_parsing = true;
928 ERR_FAIL_COND(error != OK);
929
930 while (next_tag.name == "ext_resource") {
931 if (!next_tag.fields.has("type")) {
932 error = ERR_FILE_CORRUPT;
933 error_text = "Missing 'type' in external resource tag";
934 _printerr();
935 return;
936 }
937
938 if (!next_tag.fields.has("id")) {
939 error = ERR_FILE_CORRUPT;
940 error_text = "Missing 'id' in external resource tag";
941 _printerr();
942 return;
943 }
944
945 String path = next_tag.fields["path"];
946 String type = next_tag.fields["type"];
947 String fallback_path;
948
949 bool using_uid = false;
950 if (next_tag.fields.has("uid")) {
951 // If uid exists, return uid in text format, not the path.
952 String uidt = next_tag.fields["uid"];
953 ResourceUID::ID uid = ResourceUID::get_singleton()->text_to_id(uidt);
954 if (uid != ResourceUID::INVALID_ID) {
955 fallback_path = path; // Used by Dependency Editor, in case uid path fails.
956 path = ResourceUID::get_singleton()->id_to_text(uid);
957 using_uid = true;
958 }
959 }
960
961 if (!using_uid && !path.contains("://") && path.is_relative_path()) {
962 // Path is relative to file being loaded, so convert to a resource path.
963 path = ProjectSettings::get_singleton()->localize_path(local_path.get_base_dir().path_join(path));
964 }
965
966 if (p_add_types) {
967 path += "::" + type;
968 }
969 if (!fallback_path.is_empty()) {
970 if (!p_add_types) {
971 path += "::"; // Ensure that path comes third, even if there is no type.
972 }
973 path += "::" + fallback_path;
974 }
975
976 p_dependencies->push_back(path);
977
978 Error err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
979
980 if (err) {
981 print_line(error_text + " - " + itos(lines));
982 error_text = "Unexpected end of file";
983 _printerr();
984 error = ERR_FILE_CORRUPT;
985 return;
986 }
987 }
988 }
989
990 Error ResourceLoaderText::rename_dependencies(Ref<FileAccess> p_f, const String &p_path, const HashMap<String, String> &p_map) {
991 open(p_f, true);
992 ERR_FAIL_COND_V(error != OK, error);
993 ignore_resource_parsing = true;
994 //FileAccess
995
996 Ref<FileAccess> fw;
997
998 String base_path = local_path.get_base_dir();
999
1000 uint64_t tag_end = f->get_position();
1001
1002 while (true) {
1003 Error err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
1004
1005 if (err != OK) {
1006 error = ERR_FILE_CORRUPT;
1007 ERR_FAIL_V(error);
1008 }
1009
1010 if (next_tag.name != "ext_resource") {
1011 //nothing was done
1012 if (fw.is_null()) {
1013 return OK;
1014 }
1015
1016 break;
1017
1018 } else {
1019 if (fw.is_null()) {
1020 fw = FileAccess::open(p_path + ".depren", FileAccess::WRITE);
1021
1022 if (res_uid == ResourceUID::INVALID_ID) {
1023 res_uid = ResourceSaver::get_resource_id_for_path(p_path);
1024 }
1025
1026 String uid_text = "";
1027 if (res_uid != ResourceUID::INVALID_ID) {
1028 uid_text = " uid=\"" + ResourceUID::get_singleton()->id_to_text(res_uid) + "\"";
1029 }
1030
1031 if (is_scene) {
1032 fw->store_line("[gd_scene format=" + itos(format_version) + uid_text + "]\n");
1033 } else {
1034 String script_res_text;
1035 if (!script_class.is_empty()) {
1036 script_res_text = "script_class=\"" + script_class + "\" ";
1037 }
1038 fw->store_line("[gd_resource type=\"" + res_type + "\" " + script_res_text + "format=" + itos(format_version) + uid_text + "]\n");
1039 }
1040 }
1041
1042 if (!next_tag.fields.has("path") || !next_tag.fields.has("id") || !next_tag.fields.has("type")) {
1043 error = ERR_FILE_CORRUPT;
1044 ERR_FAIL_V(error);
1045 }
1046
1047 String path = next_tag.fields["path"];
1048 String id = next_tag.fields["id"];
1049 String type = next_tag.fields["type"];
1050
1051 if (next_tag.fields.has("uid")) {
1052 String uidt = next_tag.fields["uid"];
1053 ResourceUID::ID uid = ResourceUID::get_singleton()->text_to_id(uidt);
1054 if (uid != ResourceUID::INVALID_ID && ResourceUID::get_singleton()->has_id(uid)) {
1055 // If a UID is found and the path is valid, it will be used, otherwise, it falls back to the path.
1056 path = ResourceUID::get_singleton()->get_id_path(uid);
1057 }
1058 }
1059 bool relative = false;
1060 if (!path.begins_with("res://")) {
1061 path = base_path.path_join(path).simplify_path();
1062 relative = true;
1063 }
1064
1065 if (p_map.has(path)) {
1066 path = p_map[path];
1067 }
1068
1069 if (relative) {
1070 //restore relative
1071 path = base_path.path_to_file(path);
1072 }
1073
1074 String s = "[ext_resource type=\"" + type + "\"";
1075
1076 ResourceUID::ID uid = ResourceSaver::get_resource_id_for_path(path);
1077 if (uid != ResourceUID::INVALID_ID) {
1078 s += " uid=\"" + ResourceUID::get_singleton()->id_to_text(uid) + "\"";
1079 }
1080 s += " path=\"" + path + "\" id=\"" + id + "\"]";
1081 fw->store_line(s); // Bundled.
1082
1083 tag_end = f->get_position();
1084 }
1085 }
1086
1087 f->seek(tag_end);
1088
1089 const uint32_t buffer_size = 2048;
1090 uint8_t *buffer = (uint8_t *)alloca(buffer_size);
1091 uint32_t num_read;
1092
1093 num_read = f->get_buffer(buffer, buffer_size);
1094 ERR_FAIL_COND_V_MSG(num_read == UINT32_MAX, ERR_CANT_CREATE, "Failed to allocate memory for buffer.");
1095 ERR_FAIL_COND_V(num_read == 0, ERR_FILE_CORRUPT);
1096
1097 if (*buffer == '\n') {
1098 // Skip first newline character since we added one.
1099 if (num_read > 1) {
1100 fw->store_buffer(buffer + 1, num_read - 1);
1101 }
1102 } else {
1103 fw->store_buffer(buffer, num_read);
1104 }
1105
1106 while (!f->eof_reached()) {
1107 num_read = f->get_buffer(buffer, buffer_size);
1108 fw->store_buffer(buffer, num_read);
1109 }
1110
1111 bool all_ok = fw->get_error() == OK;
1112
1113 if (!all_ok) {
1114 return ERR_CANT_CREATE;
1115 }
1116
1117 return OK;
1118 }
1119
1120 void ResourceLoaderText::open(Ref<FileAccess> p_f, bool p_skip_first_tag) {
1121 error = OK;
1122
1123 lines = 1;
1124 f = p_f;
1125
1126 stream.f = f;
1127 is_scene = false;
1128 ignore_resource_parsing = false;
1129
1130 VariantParser::Tag tag;
1131 Error err = VariantParser::parse_tag(&stream, lines, error_text, tag);
1132
1133 if (err) {
1134 error = err;
1135 _printerr();
1136 return;
1137 }
1138
1139 if (tag.fields.has("format")) {
1140 format_version = tag.fields["format"];
1141 if (format_version > FORMAT_VERSION) {
1142 error_text = "Saved with newer format version";
1143 _printerr();
1144 error = ERR_FILE_UNRECOGNIZED;
1145 return;
1146 }
1147 } else {
1148 format_version = FORMAT_VERSION;
1149 }
1150
1151 if (tag.name == "gd_scene") {
1152 is_scene = true;
1153
1154 } else if (tag.name == "gd_resource") {
1155 if (!tag.fields.has("type")) {
1156 error_text = "Missing 'type' field in 'gd_resource' tag";
1157 _printerr();
1158 error = ERR_PARSE_ERROR;
1159 return;
1160 }
1161
1162 if (tag.fields.has("script_class")) {
1163 script_class = tag.fields["script_class"];
1164 }
1165
1166 res_type = tag.fields["type"];
1167
1168 } else {
1169 error_text = vformat("Unrecognized file type '%s'", tag.name);
1170 _printerr();
1171 error = ERR_PARSE_ERROR;
1172 return;
1173 }
1174
1175 if (tag.fields.has("uid")) {
1176 res_uid = ResourceUID::get_singleton()->text_to_id(tag.fields["uid"]);
1177 } else {
1178 res_uid = ResourceUID::INVALID_ID;
1179 }
1180
1181 if (!p_skip_first_tag) {
1182 err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
1183
1184 if (err) {
1185 error_text = "Unexpected end of file";
1186 _printerr();
1187 error = ERR_FILE_CORRUPT;
1188 }
1189 }
1190
1191 rp.ext_func = _parse_ext_resources;
1192 rp.sub_func = _parse_sub_resources;
1193 rp.userdata = this;
1194 }
1195
1196 Error ResourceLoaderText::get_classes_used(HashSet<StringName> *r_classes) {
1197 if (error) {
1198 return error;
1199 }
1200
1201 ignore_resource_parsing = true;
1202
1203 DummyReadData dummy_read;
1204 dummy_read.no_placeholders = true;
1205 VariantParser::ResourceParser rp_new;
1206 rp_new.ext_func = _parse_ext_resource_dummys;
1207 rp_new.sub_func = _parse_sub_resource_dummys;
1208 rp_new.userdata = &dummy_read;
1209
1210 while (next_tag.name == "ext_resource") {
1211 error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp_new);
1212
1213 if (error) {
1214 _printerr();
1215 return error;
1216 }
1217 }
1218
1219 while (next_tag.name == "sub_resource" || next_tag.name == "resource") {
1220 if (next_tag.name == "sub_resource") {
1221 if (!next_tag.fields.has("type")) {
1222 error = ERR_FILE_CORRUPT;
1223 error_text = "Missing 'type' in external resource tag";
1224 _printerr();
1225 return error;
1226 }
1227
1228 r_classes->insert(next_tag.fields["type"]);
1229
1230 } else {
1231 r_classes->insert(next_tag.fields["res_type"]);
1232 }
1233
1234 while (true) {
1235 String assign;
1236 Variant value;
1237
1238 error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp_new);
1239
1240 if (error) {
1241 if (error == ERR_FILE_EOF) {
1242 return OK;
1243 }
1244
1245 _printerr();
1246 return error;
1247 }
1248
1249 if (!assign.is_empty()) {
1250 continue;
1251 } else if (!next_tag.name.is_empty()) {
1252 error = OK;
1253 break;
1254 } else {
1255 error = ERR_FILE_CORRUPT;
1256 error_text = "Premature end of file while parsing [sub_resource]";
1257 _printerr();
1258 return error;
1259 }
1260 }
1261 }
1262
1263 while (next_tag.name == "node") {
1264 // This is a node, must save one more!
1265
1266 if (!is_scene) {
1267 error = ERR_FILE_CORRUPT;
1268 error_text = "Unexpected 'node' tag in a resource file";
1269 _printerr();
1270 return error;
1271 }
1272
1273 if (next_tag.fields.has("type")) {
1274 r_classes->insert(next_tag.fields["type"]);
1275 }
1276
1277 while (true) {
1278 String assign;
1279 Variant value;
1280
1281 error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp_new);
1282
1283 if (error) {
1284 if (error == ERR_FILE_MISSING_DEPENDENCIES) {
1285 // Resource loading error, just skip it.
1286 } else if (error != ERR_FILE_EOF) {
1287 _printerr();
1288 return error;
1289 } else {
1290 return OK;
1291 }
1292 }
1293
1294 if (!assign.is_empty()) {
1295 continue;
1296 } else if (!next_tag.name.is_empty()) {
1297 error = OK;
1298 break;
1299 } else {
1300 error = ERR_FILE_CORRUPT;
1301 error_text = "Premature end of file while parsing [sub_resource]";
1302 _printerr();
1303 return error;
1304 }
1305 }
1306 }
1307
1308 return OK;
1309 }
1310
1311 String ResourceLoaderText::recognize_script_class(Ref<FileAccess> p_f) {
1312 error = OK;
1313
1314 lines = 1;
1315 f = p_f;
1316
1317 stream.f = f;
1318
1319 ignore_resource_parsing = true;
1320
1321 VariantParser::Tag tag;
1322 Error err = VariantParser::parse_tag(&stream, lines, error_text, tag);
1323
1324 if (err) {
1325 _printerr();
1326 return "";
1327 }
1328
1329 if (tag.fields.has("format")) {
1330 int fmt = tag.fields["format"];
1331 if (fmt > FORMAT_VERSION) {
1332 error_text = "Saved with newer format version";
1333 _printerr();
1334 return "";
1335 }
1336 }
1337
1338 if (tag.name != "gd_resource") {
1339 return "";
1340 }
1341
1342 if (tag.fields.has("script_class")) {
1343 return tag.fields["script_class"];
1344 }
1345
1346 return "";
1347 }
1348
1349 String ResourceLoaderText::recognize(Ref<FileAccess> p_f) {
1350 error = OK;
1351
1352 lines = 1;
1353 f = p_f;
1354
1355 stream.f = f;
1356
1357 ignore_resource_parsing = true;
1358
1359 VariantParser::Tag tag;
1360 Error err = VariantParser::parse_tag(&stream, lines, error_text, tag);
1361
1362 if (err) {
1363 _printerr();
1364 return "";
1365 }
1366
1367 if (tag.fields.has("format")) {
1368 int fmt = tag.fields["format"];
1369 if (fmt > FORMAT_VERSION) {
1370 error_text = "Saved with newer format version";
1371 _printerr();
1372 return "";
1373 }
1374 }
1375
1376 if (tag.name == "gd_scene") {
1377 return "PackedScene";
1378 }
1379
1380 if (tag.name != "gd_resource") {
1381 return "";
1382 }
1383
1384 if (!tag.fields.has("type")) {
1385 error_text = "Missing 'type' field in 'gd_resource' tag";
1386 _printerr();
1387 return "";
1388 }
1389
1390 return tag.fields["type"];
1391 }
1392
1393 ResourceUID::ID ResourceLoaderText::get_uid(Ref<FileAccess> p_f) {
1394 error = OK;
1395
1396 lines = 1;
1397 f = p_f;
1398
1399 stream.f = f;
1400
1401 ignore_resource_parsing = true;
1402
1403 VariantParser::Tag tag;
1404 Error err = VariantParser::parse_tag(&stream, lines, error_text, tag);
1405
1406 if (err) {
1407 _printerr();
1408 return ResourceUID::INVALID_ID;
1409 }
1410
1411 if (tag.fields.has("uid")) { //field is optional
1412 String uidt = tag.fields["uid"];
1413 return ResourceUID::get_singleton()->text_to_id(uidt);
1414 }
1415
1416 return ResourceUID::INVALID_ID;
1417 }
1418
1419 /////////////////////
1420
1421 Ref<Resource> ResourceFormatLoaderText::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) {
1422 if (r_error) {
1423 *r_error = ERR_CANT_OPEN;
1424 }
1425
1426 Error err;
1427
1428 Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);
1429
1430 ERR_FAIL_COND_V_MSG(err != OK, Ref<Resource>(), "Cannot open file '" + p_path + "'.");
1431
1432 ResourceLoaderText loader;
1433 String path = !p_original_path.is_empty() ? p_original_path : p_path;
1434 switch (p_cache_mode) {
1435 case CACHE_MODE_IGNORE:
1436 case CACHE_MODE_REUSE:
1437 case CACHE_MODE_REPLACE:
1438 loader.cache_mode = p_cache_mode;
1439 loader.cache_mode_for_external = CACHE_MODE_REUSE;
1440 break;
1441 case CACHE_MODE_IGNORE_DEEP:
1442 loader.cache_mode = ResourceFormatLoader::CACHE_MODE_IGNORE;
1443 loader.cache_mode_for_external = p_cache_mode;
1444 break;
1445 case CACHE_MODE_REPLACE_DEEP:
1446 loader.cache_mode = ResourceFormatLoader::CACHE_MODE_REPLACE;
1447 loader.cache_mode_for_external = p_cache_mode;
1448 break;
1449 }
1450 loader.use_sub_threads = p_use_sub_threads;
1451 loader.local_path = ProjectSettings::get_singleton()->localize_path(path);
1452 loader.progress = r_progress;
1453 loader.res_path = loader.local_path;
1454 loader.open(f);
1455 err = loader.load();
1456 if (r_error) {
1457 *r_error = err;
1458 }
1459 if (err == OK) {
1460 return loader.get_resource();
1461 } else {
1462 return Ref<Resource>();
1463 }
1464 }
1465
1466 void ResourceFormatLoaderText::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
1467 if (p_type.is_empty()) {
1468 get_recognized_extensions(p_extensions);
1469 return;
1470 }
1471
1472 if (ClassDB::is_parent_class("PackedScene", p_type)) {
1473 p_extensions->push_back("tscn");
1474 }
1475
1476 // Don't allow .tres for PackedScenes or GDExtension.
1477 if (p_type != "PackedScene" && p_type != "GDExtension") {
1478 p_extensions->push_back("tres");
1479 }
1480 }
1481
1482 void ResourceFormatLoaderText::get_recognized_extensions(List<String> *p_extensions) const {
1483 p_extensions->push_back("tscn");
1484 p_extensions->push_back("tres");
1485 }
1486
1487 bool ResourceFormatLoaderText::handles_type(const String &p_type) const {
1488 return true;
1489 }
1490
1491 void ResourceFormatLoaderText::get_classes_used(const String &p_path, HashSet<StringName> *r_classes) {
1492 const String type = get_resource_type(p_path);
1493 if (!type.is_empty()) {
1494 r_classes->insert(type);
1495 }
1496
1497 // ...for anything else must test...
1498
1499 Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
1500 if (f.is_null()) {
1501 return; // Could not read.
1502 }
1503
1504 ResourceLoaderText loader;
1505 loader.local_path = ProjectSettings::get_singleton()->localize_path(p_path);
1506 loader.res_path = loader.local_path;
1507 loader.open(f);
1508 loader.get_classes_used(r_classes);
1509 }
1510
1511 String ResourceFormatLoaderText::get_resource_type(const String &p_path) const {
1512 const String ext = p_path.get_extension().to_lower();
1513 if (ext == "tscn") {
1514 return "PackedScene";
1515 } else if (ext != "tres") {
1516 return String();
1517 }
1518
1519 // ...for anything else must test...
1520
1521 Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
1522 if (f.is_null()) {
1523 return ""; //could not read
1524 }
1525
1526 ResourceLoaderText loader;
1527 loader.local_path = ProjectSettings::get_singleton()->localize_path(p_path);
1528 loader.res_path = loader.local_path;
1529 String r = loader.recognize(f);
1530 return ClassDB::get_compatibility_remapped_class(r);
1531 }
1532
1533 String ResourceFormatLoaderText::get_resource_script_class(const String &p_path) const {
1534 if (!p_path.has_extension("tres")) {
1535 return String();
1536 }
1537
1538 // ...for anything else must test...
1539
1540 Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
1541 if (f.is_null()) {
1542 return ""; //could not read
1543 }
1544
1545 ResourceLoaderText loader;
1546 loader.local_path = ProjectSettings::get_singleton()->localize_path(p_path);
1547 loader.res_path = loader.local_path;
1548 return loader.recognize_script_class(f);
1549 }
1550
1551 ResourceUID::ID ResourceFormatLoaderText::get_resource_uid(const String &p_path) const {
1552 const String ext = p_path.get_extension().to_lower();
1553 if (ext != "tscn" && ext != "tres") {
1554 return ResourceUID::INVALID_ID;
1555 }
1556
1557 Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
1558 if (f.is_null()) {
1559 return ResourceUID::INVALID_ID; //could not read
1560 }
1561
1562 ResourceLoaderText loader;
1563 loader.local_path = ProjectSettings::get_singleton()->localize_path(p_path);
1564 loader.res_path = loader.local_path;
1565 return loader.get_uid(f);
1566 }
1567
1568 bool ResourceFormatLoaderText::has_custom_uid_support() const {
1569 return true;
1570 }
1571
1572 void ResourceFormatLoaderText::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
1573 Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
1574 if (f.is_null()) {
1575 ERR_FAIL();
1576 }
1577
1578 ResourceLoaderText loader;
1579 loader.local_path = ProjectSettings::get_singleton()->localize_path(p_path);
1580 loader.res_path = loader.local_path;
1581 loader.get_dependencies(f, p_dependencies, p_add_types);
1582 }
1583
1584 Error ResourceFormatLoaderText::rename_dependencies(const String &p_path, const HashMap<String, String> &p_map) {
1585 Error err = OK;
1586 {
1587 Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
1588 if (f.is_null()) {
1589 ERR_FAIL_V(ERR_CANT_OPEN);
1590 }
1591
1592 ResourceLoaderText loader;
1593 loader.local_path = ProjectSettings::get_singleton()->localize_path(p_path);
1594 loader.res_path = loader.local_path;
1595 err = loader.rename_dependencies(f, p_path, p_map);
1596 }
1597
1598 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
1599 if (err == OK && da->file_exists(p_path + ".depren")) {
1600 da->remove(p_path);
1601 da->rename(p_path + ".depren", p_path);
1602 }
1603
1604 return err;
1605 }
1606
1607 ResourceFormatLoaderText *ResourceFormatLoaderText::singleton = nullptr;
1608
1609 /*****************************************************************************************************/
1610
1611 String ResourceFormatSaverTextInstance::_write_resources(void *ud, const Ref<Resource> &p_resource) {
1612 ResourceFormatSaverTextInstance *rsi = static_cast<ResourceFormatSaverTextInstance *>(ud);
1613 return rsi->_write_resource(p_resource);
1614 }
1615
1616 String ResourceFormatSaverTextInstance::_write_resource(const Ref<Resource> &res) {
1617 if (res->get_meta(SNAME("_skip_save_"), false)) {
1618 return "null";
1619 }
1620
1621 if (external_resources.has(res)) {
1622 return "ExtResource(\"" + external_resources[res] + "\")";
1623 } else {
1624 if (internal_resources.has(res)) {
1625 return "SubResource(\"" + internal_resources[res] + "\")";
1626 } else if (!res->is_built_in()) {
1627 if (res->get_path() == local_path) { //circular reference attempt
1628 return "null";
1629 }
1630 //external resource
1631 String path = relative_paths ? local_path.path_to_file(res->get_path()) : res->get_path();
1632 return "Resource(\"" + path + "\")";
1633 } else {
1634 ERR_FAIL_V_MSG("null", "Resource was not pre cached for the resource section, bug?");
1635 //internal resource
1636 }
1637 }
1638 }
1639
1640 void ResourceFormatSaverTextInstance::_find_resources(const Variant &p_variant, bool p_main) {
1641 switch (p_variant.get_type()) {
1642 case Variant::OBJECT: {
1643 Ref<Resource> res = p_variant;
1644
1645 if (res.is_null() || external_resources.has(res) || res->get_meta(SNAME("_skip_save_"), false)) {
1646 return;
1647 }
1648
1649 if (!p_main && (!bundle_resources) && !res->is_built_in()) {
1650 if (res->get_path() == local_path) {
1651 ERR_PRINT("Circular reference to resource being saved found: '" + local_path + "' will be null next time it's loaded.");
1652 return;
1653 }
1654
1655 // Use a numeric ID as a base, because they are sorted in natural order before saving.
1656 // This increases the chances of thread loading to fetch them first.
1657 String id = itos(external_resources.size() + 1) + "_" + Resource::generate_scene_unique_id();
1658 external_resources[res] = id;
1659 return;
1660 }
1661
1662 if (resource_set.has(res)) {
1663 return;
1664 }
1665
1666 resource_set.insert(res);
1667
1668 List<PropertyInfo> property_list;
1669
1670 res->get_property_list(&property_list);
1671 property_list.sort();
1672
1673 List<PropertyInfo>::Element *I = property_list.front();
1674
1675 while (I) {
1676 PropertyInfo pi = I->get();
1677
1678 if (pi.usage & PROPERTY_USAGE_STORAGE) {
1679 Variant v = res->get(I->get().name);
1680
1681 if (pi.usage & PROPERTY_USAGE_RESOURCE_NOT_PERSISTENT) {
1682 NonPersistentKey npk;
1683 npk.base = res;
1684 npk.property = pi.name;
1685 non_persistent_map[npk] = v;
1686
1687 Ref<Resource> sres = v;
1688 if (sres.is_valid()) {
1689 resource_set.insert(sres);
1690 saved_resources.push_back(sres);
1691 } else {
1692 _find_resources(v);
1693 }
1694 } else {
1695 _find_resources(v);
1696 }
1697 }
1698
1699 I = I->next();
1700 }
1701
1702 saved_resources.push_back(res); // Saved after, so the children it needs are available when loaded
1703
1704 } break;
1705 case Variant::ARRAY: {
1706 Array varray = p_variant;
1707 _find_resources(varray.get_typed_script());
1708 for (const Variant &var : varray) {
1709 _find_resources(var);
1710 }
1711
1712 } break;
1713 case Variant::DICTIONARY: {
1714 Dictionary d = p_variant;
1715 _find_resources(d.get_typed_key_script());
1716 _find_resources(d.get_typed_value_script());
1717 for (const KeyValue<Variant, Variant> &kv : d) {
1718 // Of course keys should also be cached, after all we can't prevent users from using resources as keys, right?
1719 // See also ResourceFormatSaverBinaryInstance::_find_resources (when p_variant is of type Variant::DICTIONARY)
1720 _find_resources(kv.key);
1721 _find_resources(kv.value);
1722 }
1723 } break;
1724 case Variant::PACKED_BYTE_ARRAY: {
1725 // Balance between compatibility and performance.
1726 if (use_compat && p_variant.operator PackedByteArray().size() > 64) {
1727 use_compat = false;
1728 }
1729 } break;
1730 case Variant::PACKED_VECTOR4_ARRAY: {
1731 use_compat = false;
1732 } break;
1733 default: {
1734 }
1735 }
1736 }
1737
1738 static String _resource_get_class(Ref<Resource> p_resource) {
1739 Ref<MissingResource> missing_resource = p_resource;
1740 if (missing_resource.is_valid()) {
1741 return missing_resource->get_original_class();
1742 } else {
1743 return p_resource->get_class();
1744 }
1745 }
1746
1747 Error ResourceFormatSaverTextInstance::save(const String &p_path, const Ref<Resource> &p_resource, uint32_t p_flags) {
1748 Resource::seed_scene_unique_id(p_path.hash()); // Seeding for save path should make it deterministic for importers.
1749
1750 if (p_path.ends_with(".tscn")) {
1751 packed_scene = p_resource;
1752 }
1753
1754 Error err;
1755 Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE, &err);
1756 ERR_FAIL_COND_V_MSG(err, ERR_CANT_OPEN, "Cannot save file '" + p_path + "'.");
1757 Ref<FileAccess> _fref(f);
1758
1759 local_path = ProjectSettings::get_singleton()->localize_path(p_path);
1760
1761 relative_paths = p_flags & ResourceSaver::FLAG_RELATIVE_PATHS;
1762 skip_editor = p_flags & ResourceSaver::FLAG_OMIT_EDITOR_PROPERTIES;
1763 bundle_resources = p_flags & ResourceSaver::FLAG_BUNDLE_RESOURCES;
1764 takeover_paths = p_flags & ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS;
1765 if (!p_path.begins_with("res://")) {
1766 takeover_paths = false;
1767 }
1768
1769 // Save resources.
1770 use_compat = true; // _find_resources() changes this.
1771 _find_resources(p_resource, true);
1772
1773 if (packed_scene.is_valid()) {
1774 // Add instances to external resources if saving a packed scene.
1775 for (int i = 0; i < packed_scene->get_state()->get_node_count(); i++) {
1776 if (packed_scene->get_state()->is_node_instance_placeholder(i)) {
1777 continue;
1778 }
1779
1780 Ref<PackedScene> instance = packed_scene->get_state()->get_node_instance(i);
1781 if (instance.is_valid() && !external_resources.has(instance)) {
1782 int index = external_resources.size() + 1;
1783 external_resources[instance] = itos(index) + "_" + Resource::generate_scene_unique_id(); // Keep the order for improved thread loading performance.
1784 }
1785 }
1786 }
1787
1788 {
1789 String title = packed_scene.is_valid() ? "[gd_scene " : "[gd_resource ";
1790 if (packed_scene.is_null()) {
1791 title += "type=\"" + _resource_get_class(p_resource) + "\" ";
1792 Ref<Script> script = p_resource->get_script();
1793 if (script.is_valid() && script->get_global_name()) {
1794 title += "script_class=\"" + String(script->get_global_name()) + "\" ";
1795 }
1796 }
1797
1798 title += "format=" + itos(use_compat ? ResourceLoaderText::FORMAT_VERSION_COMPAT : ResourceLoaderText::FORMAT_VERSION) + "";
1799
1800 ResourceUID::ID uid = ResourceSaver::get_resource_id_for_path(local_path, true);
1801
1802 if (uid != ResourceUID::INVALID_ID) {
1803 title += " uid=\"" + ResourceUID::get_singleton()->id_to_text(uid) + "\"";
1804 }
1805
1806 f->store_string(title);
1807 f->store_line("]\n"); // One empty line.
1808 }
1809
1810 #ifdef TOOLS_ENABLED
1811 // Keep order from cached ids.
1812 HashSet<String> cached_ids_found;
1813 for (KeyValue<Ref<Resource>, String> &E : external_resources) {
1814 String cached_id = E.key->get_id_for_path(local_path);
1815 if (cached_id.is_empty() || cached_ids_found.has(cached_id)) {
1816 int sep_pos = E.value.find_char('_');
1817 if (sep_pos != -1) {
1818 E.value = E.value.substr(0, sep_pos + 1); // Keep the order found, for improved thread loading performance.
1819 } else {
1820 E.value = "";
1821 }
1822
1823 } else {
1824 E.value = cached_id;
1825 cached_ids_found.insert(cached_id);
1826 }
1827 }
1828 // Create IDs for non cached resources.
1829 for (KeyValue<Ref<Resource>, String> &E : external_resources) {
1830 if (cached_ids_found.has(E.value)) { // Already cached, go on.
1831 continue;
1832 }
1833
1834 String attempt;
1835 while (true) {
1836 attempt = E.value + Resource::generate_scene_unique_id();
1837 if (!cached_ids_found.has(attempt)) {
1838 break;
1839 }
1840 }
1841
1842 cached_ids_found.insert(attempt);
1843 E.value = attempt;
1844 // Update also in resource.
1845 Ref<Resource> res = E.key;
1846 res->set_id_for_path(local_path, attempt);
1847 }
1848 #else
1849 // Make sure to start from one, as it makes format more readable.
1850 int counter = 1;
1851 for (KeyValue<Ref<Resource>, String> &E : external_resources) {
1852 E.value = itos(counter++);
1853 }
1854 #endif
1855
1856 Vector<ResourceSort> sorted_er;
1857
1858 for (const KeyValue<Ref<Resource>, String> &E : external_resources) {
1859 ResourceSort rs;
1860 rs.resource = E.key;
1861 rs.id = E.value;
1862 sorted_er.push_back(rs);
1863 }
1864
1865 sorted_er.sort();
1866
1867 for (int i = 0; i < sorted_er.size(); i++) {
1868 String p = sorted_er[i].resource->get_path();
1869
1870 String s = "[ext_resource type=\"" + sorted_er[i].resource->get_save_class() + "\"";
1871
1872 ResourceUID::ID uid = ResourceSaver::get_resource_id_for_path(p, false);
1873 if (uid != ResourceUID::INVALID_ID) {
1874 s += " uid=\"" + ResourceUID::get_singleton()->id_to_text(uid) + "\"";
1875 }
1876 s += " path=\"" + p + "\" id=\"" + sorted_er[i].id + "\"]\n";
1877 f->store_string(s); // Bundled.
1878 }
1879
1880 if (external_resources.size()) {
1881 f->store_line(String()); // Separate.
1882 }
1883
1884 HashSet<String> used_unique_ids;
1885
1886 for (List<Ref<Resource>>::Element *E = saved_resources.front(); E; E = E->next()) {
1887 Ref<Resource> res = E->get();
1888 if (E->next() && res->is_built_in()) {
1889 if (!res->get_scene_unique_id().is_empty()) {
1890 if (used_unique_ids.has(res->get_scene_unique_id())) {
1891 res->set_scene_unique_id(""); // Repeated.
1892 } else {
1893 used_unique_ids.insert(res->get_scene_unique_id());
1894 }
1895 }
1896 }
1897 }
1898
1899 for (List<Ref<Resource>>::Element *E = saved_resources.front(); E; E = E->next()) {
1900 Ref<Resource> res = E->get();
1901 ERR_CONTINUE(!resource_set.has(res));
1902 bool main = (E->next() == nullptr);
1903
1904 if (main && packed_scene.is_valid()) {
1905 break; // Save as a scene.
1906 }
1907
1908 if (main) {
1909 f->store_line("[resource]");
1910 } else {
1911 String line = "[sub_resource ";
1912 if (res->get_scene_unique_id().is_empty()) {
1913 String new_id;
1914 while (true) {
1915 new_id = _resource_get_class(res) + "_" + Resource::generate_scene_unique_id();
1916
1917 if (!used_unique_ids.has(new_id)) {
1918 break;
1919 }
1920 }
1921
1922 res->set_scene_unique_id(new_id);
1923 used_unique_ids.insert(new_id);
1924 }
1925
1926 String id = res->get_scene_unique_id();
1927 line += "type=\"" + _resource_get_class(res) + "\" id=\"" + id;
1928 f->store_line(line + "\"]");
1929 if (takeover_paths) {
1930 res->set_path(p_path + "::" + id, true);
1931 }
1932
1933 internal_resources[res] = id;
1934 #ifdef TOOLS_ENABLED
1935 res->set_edited(false);
1936 #endif
1937 }
1938
1939 Dictionary missing_resource_properties = res->get_meta(META_MISSING_RESOURCES, Dictionary());
1940
1941 List<PropertyInfo> property_list;
1942 res->get_property_list(&property_list);
1943 for (const PropertyInfo &pi : property_list) {
1944 if (skip_editor && pi.name.begins_with("__editor")) {
1945 continue;
1946 }
1947 if (pi.name == META_PROPERTY_MISSING_RESOURCES) {
1948 continue;
1949 }
1950
1951 if (pi.usage & PROPERTY_USAGE_STORAGE || missing_resource_properties.has(pi.name)) {
1952 String name = pi.name;
1953 Variant value;
1954 if (pi.usage & PROPERTY_USAGE_RESOURCE_NOT_PERSISTENT) {
1955 NonPersistentKey npk;
1956 npk.base = res;
1957 npk.property = name;
1958 if (non_persistent_map.has(npk)) {
1959 value = non_persistent_map[npk];
1960 }
1961 } else {
1962 value = res->get(name);
1963 }
1964
1965 if (pi.type == Variant::OBJECT && missing_resource_properties.has(pi.name)) {
1966 // Was this missing resource overridden? If so do not save the old value.
1967 Ref<Resource> ures = value;
1968 if (ures.is_null()) {
1969 value = missing_resource_properties[pi.name];
1970 }
1971 }
1972
1973 bool is_script = name == CoreStringName(script);
1974 Variant default_value = is_script ? Variant() : PropertyUtils::get_property_default_value(res.ptr(), name);
1975
1976 if (default_value.get_type() != Variant::NIL && bool(Variant::evaluate(Variant::OP_EQUAL, value, default_value))) {
1977 continue;
1978 }
1979
1980 if (pi.type == Variant::OBJECT && value.is_zero() && !(pi.usage & PROPERTY_USAGE_STORE_IF_NULL)) {
1981 continue;
1982 }
1983
1984 String vars;
1985 VariantWriter::write_to_string(value, vars, _write_resources, this, use_compat);
1986 f->store_string(name.property_name_encode() + " = " + vars + "\n");
1987 }
1988 }
1989
1990 if (E->next()) {
1991 f->store_line(String());
1992 }
1993 }
1994
1995 if (packed_scene.is_valid()) {
1996 // If this is a scene, save nodes and connections!
1997 Ref<SceneState> state = packed_scene->get_state();
1998 for (int i = 0; i < state->get_node_count(); i++) {
1999 StringName type = state->get_node_type(i);
2000 StringName name = state->get_node_name(i);
2001 int index = state->get_node_index(i);
2002 int unique_id = state->get_node_unique_id(i);
2003 NodePath parent_path = state->get_node_path(i, true);
2004 PackedInt32Array parent_id_path = state->get_node_parent_id_path(i);
2005 PackedInt32Array owner_id_path = state->get_node_owner_id_path(i);
2006 NodePath owner = state->get_node_owner_path(i);
2007 Ref<PackedScene> instance = state->get_node_instance(i);
2008 String instance_placeholder = state->get_node_instance_placeholder(i);
2009 Vector<StringName> groups = state->get_node_groups(i);
2010 Vector<String> deferred_node_paths = state->get_node_deferred_nodepath_properties(i);
2011
2012 String header = "[node";
2013 header += " name=\"" + String(name).c_escape() + "\"";
2014 if (type != StringName()) {
2015 header += " type=\"" + String(type) + "\"";
2016 }
2017 if (parent_path != NodePath()) {
2018 header += " parent=\"" + String(parent_path.simplified()).c_escape() + "\"";
2019 if (parent_id_path.size()) {
2020 header += " parent_id_path=" + Variant(parent_id_path).get_construct_string();
2021 }
2022 }
2023
2024 if (owner != NodePath() && owner != NodePath(".")) {
2025 header += " owner=\"" + String(owner.simplified()).c_escape() + "\"";
2026 if (owner_id_path.size()) {
2027 header += " owner_uid_path=" + Variant(owner_id_path).get_construct_string();
2028 }
2029 }
2030 if (index >= 0) {
2031 header += " index=\"" + itos(index) + "\"";
2032 }
2033
2034 if (unique_id != Node::UNIQUE_SCENE_ID_UNASSIGNED) {
2035 header += " unique_id=" + itos(unique_id) + "";
2036 }
2037
2038 if (deferred_node_paths.size()) {
2039 header += " node_paths=" + Variant(deferred_node_paths).get_construct_string();
2040 }
2041
2042 if (groups.size()) {
2043 // Write all groups on the same line as they're part of a section header.
2044 // This improves readability while not impacting VCS friendliness too much,
2045 // since it's rare to have more than 5 groups assigned to a single node.
2046 groups.sort_custom<StringName::AlphCompare>();
2047 String sgroups = " groups=[";
2048 for (int j = 0; j < groups.size(); j++) {
2049 sgroups += "\"" + String(groups[j]).c_escape() + "\"";
2050 if (j < groups.size() - 1) {
2051 sgroups += ", ";
2052 }
2053 }
2054 sgroups += "]";
2055 header += sgroups;
2056 }
2057
2058 f->store_string(header);
2059
2060 if (!instance_placeholder.is_empty()) {
2061 String vars;
2062 f->store_string(" instance_placeholder=");
2063 VariantWriter::write_to_string(instance_placeholder, vars, _write_resources, this, use_compat);
2064 f->store_string(vars);
2065 }
2066
2067 if (instance.is_valid()) {
2068 String vars;
2069 f->store_string(" instance=");
2070 VariantWriter::write_to_string(instance, vars, _write_resources, this, use_compat);
2071 f->store_string(vars);
2072 }
2073
2074 f->store_line("]");
2075
2076 for (int j = 0; j < state->get_node_property_count(i); j++) {
2077 String vars;
2078 VariantWriter::write_to_string(state->get_node_property_value(i, j), vars, _write_resources, this, use_compat);
2079
2080 f->store_string(String(state->get_node_property_name(i, j)).property_name_encode() + " = " + vars + "\n");
2081 }
2082
2083 if (i < state->get_node_count() - 1) {
2084 f->store_line(String());
2085 }
2086 }
2087
2088 for (int i = 0; i < state->get_connection_count(); i++) {
2089 if (i == 0) {
2090 f->store_line("");
2091 }
2092
2093 String connstr = "[connection";
2094 connstr += " signal=\"" + String(state->get_connection_signal(i)).c_escape() + "\"";
2095 connstr += " from=\"" + String(state->get_connection_source(i).simplified()).c_escape() + "\"";
2096 connstr += " to=\"" + String(state->get_connection_target(i).simplified()).c_escape() + "\"";
2097 connstr += " method=\"" + String(state->get_connection_method(i)).c_escape() + "\"";
2098 int flags = state->get_connection_flags(i);
2099 if (flags != Object::CONNECT_PERSIST) {
2100 connstr += " flags=" + itos(flags);
2101 }
2102
2103 {
2104 PackedInt32Array from_idp = state->get_connection_source_id_path(i);
2105 if (from_idp.size()) {
2106 connstr += " from_uid_path=" + Variant(from_idp).get_construct_string();
2107 }
2108 }
2109
2110 {
2111 PackedInt32Array to_idp = state->get_connection_target_id_path(i);
2112 if (to_idp.size()) {
2113 connstr += " to_uid_path=" + Variant(to_idp).get_construct_string();
2114 }
2115 }
2116
2117 int unbinds = state->get_connection_unbinds(i);
2118 if (unbinds > 0) {
2119 connstr += " unbinds=" + itos(unbinds);
2120 }
2121
2122 Array binds = state->get_connection_binds(i);
2123 f->store_string(connstr);
2124 if (binds.size()) {
2125 String vars;
2126 VariantWriter::write_to_string(binds, vars, _write_resources, this, use_compat);
2127 f->store_string(" binds= " + vars);
2128 }
2129
2130 f->store_line("]");
2131 }
2132
2133 Vector<NodePath> editable_instances = state->get_editable_instances();
2134 for (int i = 0; i < editable_instances.size(); i++) {
2135 if (i == 0) {
2136 f->store_line("");
2137 }
2138 f->store_line("[editable path=\"" + editable_instances[i].operator String().c_escape() + "\"]");
2139 }
2140 }
2141
2142 if (f->get_error() != OK && f->get_error() != ERR_FILE_EOF) {
2143 return ERR_CANT_CREATE;
2144 }
2145
2146 return OK;
2147 }
2148
2149 Error ResourceLoaderText::set_uid(Ref<FileAccess> p_f, ResourceUID::ID p_uid) {
2150 open(p_f, true);
2151 ERR_FAIL_COND_V(error != OK, error);
2152 ignore_resource_parsing = true;
2153
2154 Ref<FileAccess> fw;
2155
2156 fw = FileAccess::open(local_path + ".uidren", FileAccess::WRITE);
2157 if (is_scene) {
2158 fw->store_string("[gd_scene format=" + itos(format_version) + " uid=\"" + ResourceUID::get_singleton()->id_to_text(p_uid) + "\"]");
2159 } else {
2160 String script_res_text;
2161 if (!script_class.is_empty()) {
2162 script_res_text = "script_class=\"" + script_class + "\" ";
2163 }
2164
2165 fw->store_string("[gd_resource type=\"" + res_type + "\" " + script_res_text + "format=" + itos(format_version) + " uid=\"" + ResourceUID::get_singleton()->id_to_text(p_uid) + "\"]");
2166 }
2167
2168 uint8_t c = f->get_8();
2169 while (!f->eof_reached()) {
2170 fw->store_8(c);
2171 c = f->get_8();
2172 }
2173
2174 bool all_ok = fw->get_error() == OK;
2175
2176 if (!all_ok) {
2177 return ERR_CANT_CREATE;
2178 }
2179
2180 return OK;
2181 }
2182
2183 Error ResourceFormatSaverText::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) {
2184 if (p_path.ends_with(".tscn") && Ref<PackedScene>(p_resource).is_null()) {
2185 return ERR_FILE_UNRECOGNIZED;
2186 }
2187
2188 ResourceFormatSaverTextInstance saver;
2189 return saver.save(p_path, p_resource, p_flags);
2190 }
2191
2192 Error ResourceFormatSaverText::set_uid(const String &p_path, ResourceUID::ID p_uid) {
2193 String lc = p_path.to_lower();
2194 if (!lc.ends_with(".tscn") && !lc.ends_with(".tres")) {
2195 return ERR_FILE_UNRECOGNIZED;
2196 }
2197
2198 String local_path = ProjectSettings::get_singleton()->localize_path(p_path);
2199 Error err = OK;
2200 {
2201 Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::READ);
2202 if (file.is_null()) {
2203 ERR_FAIL_V(ERR_CANT_OPEN);
2204 }
2205
2206 ResourceLoaderText loader;
2207 loader.local_path = local_path;
2208 loader.res_path = loader.local_path;
2209 err = loader.set_uid(file, p_uid);
2210 }
2211
2212 if (err == OK) {
2213 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
2214 da->remove(local_path);
2215 da->rename(local_path + ".uidren", local_path);
2216 }
2217
2218 return err;
2219 }
2220
2221 bool ResourceFormatSaverText::recognize(const Ref<Resource> &p_resource) const {
2222 return true; // All resources recognized!
2223 }
2224
2225 void ResourceFormatSaverText::get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const {
2226 if (Ref<PackedScene>(p_resource).is_valid()) {
2227 p_extensions->push_back("tscn"); // Text scene.
2228 } else {
2229 p_extensions->push_back("tres"); // Text resource.
2230 }
2231 }
2232
2233 ResourceFormatSaverText *ResourceFormatSaverText::singleton = nullptr;
2234 ResourceFormatSaverText::ResourceFormatSaverText() {
2235 singleton = this;
2236 }