Skip to content

armgit / godot

Public Imported from GitHub
0

Godot Engine – Multi-platform 2D and 3D game engine

Add support for metadata in text scenes

Leandro (cerberus1746) Benedet Garcia554db51ec895
diff --git a/scene/resources/resource_format_text.cpp b/scene/resources/resource_format_text.cpp
index da8f6185de4..47d9ba42a49 100644
--- a/scene/resources/resource_format_text.cpp
+++ b/scene/resources/resource_format_text.cpp
@@ -36,6 +36,7 @@
#include "core/object/class_db.h"
#include "core/object/script_language.h"
#include "scene/property_utils.h"
+#include "scene/resources/packed_scene.h"
String ResourceLoaderText::_get_error_string() {
return vformat("%s:%d - Parse Error: %s.", res_path, lines, error_text);
@@ -181,12 +182,7 @@ Error ResourceLoaderText::_parse_ext_resource(VariantParser::Stream *p_stream, R
return err;
}
-Ref<PackedScene> ResourceLoaderText::_parse_node_tag(VariantParser::ResourceParser &parser) {
- Ref<PackedScene> packed_scene = ResourceLoader::get_resource_ref_override(local_path);
- if (packed_scene.is_null()) {
- packed_scene.instantiate();
- }
-
+Ref<PackedScene> ResourceLoaderText::_parse_node_tag(const Ref<PackedScene> &p_current_scene, VariantParser::ResourceParser &p_parser) {
while (true) {
if (next_tag.name == "node") {
int parent = -1;
@@ -200,7 +196,7 @@ Ref<PackedScene> ResourceLoaderText::_parse_node_tag(VariantParser::ResourcePars
//int base_scene=-1;
if (next_tag.fields.has("name")) {
- name = packed_scene->get_state()->add_name(next_tag.fields["name"]);
+ name = p_current_scene->get_state()->add_name(next_tag.fields["name"]);
} else {
error = ERR_FILE_CORRUPT;
error_text = "Missing 'name' field from node tag";
@@ -215,14 +211,14 @@ Ref<PackedScene> ResourceLoaderText::_parse_node_tag(VariantParser::ResourcePars
if (next_tag.fields.has("parent_id_path")) {
np_id = next_tag.fields["parent_id_path"];
}
- parent = packed_scene->get_state()->add_node_path(np, np_id);
+ parent = p_current_scene->get_state()->add_node_path(np, np_id);
}
if (next_tag.fields.has("unique_id")) {
unique_id = next_tag.fields["unique_id"];
}
if (next_tag.fields.has("type")) {
- type = packed_scene->get_state()->add_name(next_tag.fields["type"]);
+ type = p_current_scene->get_state()->add_name(next_tag.fields["type"]);
} else {
type = SceneState::TYPE_INSTANTIATED; //no type? assume this was instantiated
}
@@ -237,10 +233,10 @@ Ref<PackedScene> ResourceLoaderText::_parse_node_tag(VariantParser::ResourcePars
}
if (next_tag.fields.has("instance")) {
- instance = packed_scene->get_state()->add_value(next_tag.fields["instance"]);
+ instance = p_current_scene->get_state()->add_value(next_tag.fields["instance"]);
- if (packed_scene->get_state()->get_node_count() == 0 && parent == -1) {
- packed_scene->get_state()->set_base_scene(instance);
+ if (p_current_scene->get_state()->get_node_count() == 0 && parent == -1) {
+ p_current_scene->get_state()->set_base_scene(instance);
instance = -1;
}
}
@@ -248,9 +244,9 @@ Ref<PackedScene> ResourceLoaderText::_parse_node_tag(VariantParser::ResourcePars
if (next_tag.fields.has("instance_placeholder")) {
String path = next_tag.fields["instance_placeholder"];
- int path_v = packed_scene->get_state()->add_value(path);
+ int path_v = p_current_scene->get_state()->add_value(path);
- if (packed_scene->get_state()->get_node_count() == 0) {
+ if (p_current_scene->get_state()->get_node_count() == 0) {
error = ERR_FILE_CORRUPT;
error_text = "Instance Placeholder can't be used for inheritance";
ERR_PRINT(_get_error_string());
@@ -265,7 +261,7 @@ Ref<PackedScene> ResourceLoaderText::_parse_node_tag(VariantParser::ResourcePars
if (next_tag.fields.has("owner_uid_path")) {
np_id = next_tag.fields["owner_uid_path"];
}
- owner = packed_scene->get_state()->add_node_path(next_tag.fields["owner"], np_id);
+ owner = p_current_scene->get_state()->add_node_path(next_tag.fields["owner"], np_id);
} else {
if (parent != -1 && !(type == SceneState::TYPE_INSTANTIATED && instance == -1)) {
owner = 0; //if no owner, owner is root
@@ -276,12 +272,12 @@ Ref<PackedScene> ResourceLoaderText::_parse_node_tag(VariantParser::ResourcePars
index = next_tag.fields["index"];
}
- int node_id = packed_scene->get_state()->add_node(parent, owner, type, name, instance, index, unique_id);
+ int node_id = p_current_scene->get_state()->add_node(parent, owner, type, name, instance, index, unique_id);
if (next_tag.fields.has("groups")) {
Array groups = next_tag.fields["groups"];
for (const Variant &group : groups) {
- packed_scene->get_state()->add_node_group(node_id, packed_scene->get_state()->add_name(group));
+ p_current_scene->get_state()->add_node_group(node_id, p_current_scene->get_state()->add_name(group));
}
}
@@ -289,7 +285,7 @@ Ref<PackedScene> ResourceLoaderText::_parse_node_tag(VariantParser::ResourcePars
String assign;
Variant value;
- error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &parser);
+ error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &p_parser);
if (error) {
if (error == ERR_FILE_MISSING_DEPENDENCIES) {
@@ -299,15 +295,15 @@ Ref<PackedScene> ResourceLoaderText::_parse_node_tag(VariantParser::ResourcePars
return Ref<PackedScene>();
} else {
error = OK;
- return packed_scene;
+ return p_current_scene;
}
}
if (!assign.is_empty()) {
StringName assign_name = assign;
- int nameidx = packed_scene->get_state()->add_name(assign_name);
- int valueidx = packed_scene->get_state()->add_value(value);
- packed_scene->get_state()->add_node_property(node_id, nameidx, valueidx, path_properties.has(assign_name));
+ int nameidx = p_current_scene->get_state()->add_name(assign_name);
+ int valueidx = p_current_scene->get_state()->add_value(value);
+ p_current_scene->get_state()->add_node_property(node_id, nameidx, valueidx, path_properties.has(assign_name));
//it's assignment
} else if (!next_tag.name.is_empty()) {
break;
@@ -374,19 +370,19 @@ Ref<PackedScene> ResourceLoaderText::_parse_node_tag(VariantParser::ResourcePars
Vector<int> bind_ints;
for (const Variant &bind : binds) {
- bind_ints.push_back(packed_scene->get_state()->add_value(bind));
+ bind_ints.push_back(p_current_scene->get_state()->add_value(bind));
}
- packed_scene->get_state()->add_connection(
- packed_scene->get_state()->add_node_path(from.simplified(), from_id),
- packed_scene->get_state()->add_node_path(to.simplified(), to_id),
- packed_scene->get_state()->add_name(signal),
- packed_scene->get_state()->add_name(method),
+ p_current_scene->get_state()->add_connection(
+ p_current_scene->get_state()->add_node_path(from.simplified(), from_id),
+ p_current_scene->get_state()->add_node_path(to.simplified(), to_id),
+ p_current_scene->get_state()->add_name(signal),
+ p_current_scene->get_state()->add_name(method),
flags,
unbinds,
bind_ints);
- error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &parser);
+ error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &p_parser);
if (error) {
if (error != ERR_FILE_EOF) {
@@ -394,7 +390,7 @@ Ref<PackedScene> ResourceLoaderText::_parse_node_tag(VariantParser::ResourcePars
return Ref<PackedScene>();
} else {
error = OK;
- return packed_scene;
+ return p_current_scene;
}
}
} else if (next_tag.name == "editable") {
@@ -407,9 +403,9 @@ Ref<PackedScene> ResourceLoaderText::_parse_node_tag(VariantParser::ResourcePars
NodePath path = next_tag.fields["path"];
- packed_scene->get_state()->add_editable_instance(path.simplified());
+ p_current_scene->get_state()->add_editable_instance(path.simplified());
- error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &parser);
+ error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &p_parser);
if (error) {
if (error != ERR_FILE_EOF) {
@@ -417,9 +413,12 @@ Ref<PackedScene> ResourceLoaderText::_parse_node_tag(VariantParser::ResourcePars
return Ref<PackedScene>();
} else {
error = OK;
- return packed_scene;
+ return p_current_scene;
}
}
+ // If it's a nested packed scene, and there's a resource after, we return without errors.
+ } else if (p_current_scene != packed_scene && (next_tag.name == "sub_resource" || next_tag.name == "resource")) {
+ return p_current_scene;
} else {
error = ERR_FILE_CORRUPT;
error_text = vformat("Unknown tag '%s' in file", next_tag.name);
@@ -706,6 +705,10 @@ Error ResourceLoaderText::load() {
}
//it's assignment
} else if (!next_tag.name.is_empty()) {
+ if (type == "PackedScene" && next_tag.name == "node") {
+ res = _parse_node_tag(res, rp);
+ }
+
error = OK;
break;
} else {
@@ -725,53 +728,54 @@ Error ResourceLoaderText::load() {
}
}
+ if (is_scene) {
+ packed_scene = ResourceLoader::get_resource_ref_override(local_path);
+ if (packed_scene.is_null()) {
+ packed_scene.instantiate();
+ }
+ }
+
while (true) {
if (next_tag.name != "resource") {
break;
}
- if (is_scene) {
- error_text = "Unexpected 'resource' tag in a scene file";
- ERR_PRINT(_get_error_string());
- error = ERR_FILE_CORRUPT;
- return error;
- }
-
Ref<MissingResource> missing_resource;
+ if (!is_scene) {
+ resource = ResourceLoader::get_resource_ref_override(local_path);
+ if (resource.is_null()) {
+ Ref<Resource> cache = ResourceCache::get_ref(local_path);
+ if (cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE && cache.is_valid() && cache->get_class() == res_type) {
+ cache->reset_state();
+ resource = cache;
+ }
- resource = ResourceLoader::get_resource_ref_override(local_path);
- if (resource.is_null()) {
- Ref<Resource> cache = ResourceCache::get_ref(local_path);
- if (cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE && cache.is_valid() && cache->get_class() == res_type) {
- cache->reset_state();
- resource = cache;
- }
+ if (resource.is_null()) {
+ Object *obj = ClassDB::instantiate(res_type);
+ if (!obj) {
+ if (ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
+ missing_resource = memnew(MissingResource);
+ missing_resource->set_original_class(res_type);
+ missing_resource->set_recording_properties(true);
+ obj = missing_resource.ptr();
+ } else {
+ error_text = vformat("Can't create sub resource of type '%s'", res_type);
+ ERR_PRINT(_get_error_string());
+ error = ERR_FILE_CORRUPT;
+ return error;
+ }
+ }
- if (resource.is_null()) {
- Object *obj = ClassDB::instantiate(res_type);
- if (!obj) {
- if (ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
- missing_resource = memnew(MissingResource);
- missing_resource->set_original_class(res_type);
- missing_resource->set_recording_properties(true);
- obj = missing_resource.ptr();
- } else {
- error_text = vformat("Can't create sub resource of type '%s'", res_type);
+ Resource *r = Object::cast_to<Resource>(obj);
+ if (!r) {
+ error_text = vformat("Can't create sub resource of type '%s' as it's not a resource type", res_type);
ERR_PRINT(_get_error_string());
error = ERR_FILE_CORRUPT;
return error;
}
- }
- Resource *r = Object::cast_to<Resource>(obj);
- if (!r) {
- error_text = vformat("Can't create sub resource of type '%s' as it's not a resource type", res_type);
- ERR_PRINT(_get_error_string());
- error = ERR_FILE_CORRUPT;
- return error;
+ resource = Ref<Resource>(r);
}
-
- resource = Ref<Resource>(r);
}
}
@@ -783,8 +787,17 @@ Error ResourceLoaderText::load() {
error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp);
+ bool empty_assign = assign.is_empty();
if (error) {
- if (error != ERR_FILE_EOF) {
+ if (error == ERR_FILE_EOF) {
+ if (is_scene) {
+ error_text = "Scene files need to have at least one node. None was found.";
+ error = ERR_FILE_CORRUPT;
+ ERR_PRINT(_get_error_string());
+ return error;
+ }
+
+ } else {
ERR_PRINT(_get_error_string());
return error;
}
@@ -801,7 +814,7 @@ Error ResourceLoaderText::load() {
break;
}
- if (!assign.is_empty()) {
+ if (!empty_assign) {
bool set_valid = true;
if (value.get_type() == Variant::OBJECT && missing_resource.is_null() && ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
@@ -842,10 +855,14 @@ Error ResourceLoaderText::load() {
}
if (set_valid) {
- resource->set(assign, value);
+ if (is_scene) {
+ packed_scene->set(assign, value);
+ } else {
+ resource->set(assign, value);
+ }
}
//it's assignment
- } else if (!next_tag.name.is_empty()) {
+ } else if (!is_scene && !next_tag.name.is_empty()) {
error = ERR_FILE_CORRUPT;
error_text = "Extra tag found when parsing main resource file";
ERR_PRINT(_get_error_string());
@@ -869,9 +886,10 @@ Error ResourceLoaderText::load() {
resource->set_meta(META_MISSING_RESOURCES, missing_resource_properties);
}
- error = OK;
-
- return error;
+ if (!is_scene) {
+ error = OK;
+ return error;
+ }
}
//for scene files
@@ -884,7 +902,7 @@ Error ResourceLoaderText::load() {
return error;
}
- Ref<PackedScene> packed_scene = _parse_node_tag(rp);
+ packed_scene = _parse_node_tag(packed_scene, rp);
if (packed_scene.is_null()) {
return error;
@@ -1766,6 +1784,153 @@ static String _resource_get_class(Ref<Resource> p_resource) {
}
}
+void ResourceFormatSaverTextInstance::_parse_nodes(const Ref<PackedScene> &curr_scene, const Ref<FileAccess> &p_file) {
+ // If this is a scene, save nodes and connections!
+ Ref<SceneState> state = curr_scene->get_state();
+ for (int i = 0; i < state->get_node_count(); i++) {
+ StringName type = state->get_node_type(i);
+ StringName name = state->get_node_name(i);
+ int index = state->get_node_index(i);
+ int unique_id = state->get_node_unique_id(i);
+ NodePath parent_path = state->get_node_path(i, true);
+ PackedInt32Array parent_id_path = state->get_node_parent_id_path(i);
+ PackedInt32Array owner_id_path = state->get_node_owner_id_path(i);
+ NodePath owner = state->get_node_owner_path(i);
+ Ref<PackedScene> instance = state->get_node_instance(i);
+ String instance_placeholder = state->get_node_instance_placeholder(i);
+ Vector<StringName> groups = state->get_node_groups(i);
+ Vector<String> deferred_node_paths = state->get_node_deferred_nodepath_properties(i);
+
+ String header = "[node";
+ header += " name=\"" + String(name).c_escape() + "\"";
+ if (type != StringName()) {
+ header += " type=\"" + String(type) + "\"";
+ }
+ if (parent_path != NodePath()) {
+ header += " parent=\"" + String(parent_path.simplified()).c_escape() + "\"";
+ if (parent_id_path.size()) {
+ header += " parent_id_path=" + Variant(parent_id_path).get_construct_string();
+ }
+ }
+
+ if (owner != NodePath() && owner != NodePath(".")) {
+ header += " owner=\"" + String(owner.simplified()).c_escape() + "\"";
+ if (owner_id_path.size()) {
+ header += " owner_uid_path=" + Variant(owner_id_path).get_construct_string();
+ }
+ }
+ if (index >= 0) {
+ header += " index=\"" + itos(index) + "\"";
+ }
+
+ if (unique_id != Node::UNIQUE_SCENE_ID_UNASSIGNED) {
+ header += " unique_id=" + itos(unique_id) + "";
+ }
+
+ if (deferred_node_paths.size()) {
+ header += " node_paths=" + Variant(deferred_node_paths).get_construct_string();
+ }
+
+ if (groups.size()) {
+ // Write all groups on the same line as they're part of a section header.
+ // This improves readability while not impacting VCS friendliness too much,
+ // since it's rare to have more than 5 groups assigned to a single node.
+ groups.sort_custom<StringName::AlphCompare>();
+ String sgroups = " groups=[";
+ for (int j = 0; j < groups.size(); j++) {
+ sgroups += "\"" + String(groups[j]).c_escape() + "\"";
+ if (j < groups.size() - 1) {
+ sgroups += ", ";
+ }
+ }
+ sgroups += "]";
+ header += sgroups;
+ }
+
+ p_file->store_string(header);
+
+ if (!instance_placeholder.is_empty()) {
+ String vars;
+ p_file->store_string(" instance_placeholder=");
+ VariantWriter::write_to_string(instance_placeholder, vars, true, _write_resources, this, use_compat);
+ p_file->store_string(vars);
+ }
+
+ if (instance.is_valid()) {
+ String vars;
+ p_file->store_string(" instance=");
+ VariantWriter::write_to_string(instance, vars, true, _write_resources, this, use_compat);
+ p_file->store_string(vars);
+ }
+
+ p_file->store_line("]");
+
+ for (int j = 0; j < state->get_node_property_count(i); j++) {
+ String vars;
+ VariantWriter::write_to_string(state->get_node_property_value(i, j), vars, true, _write_resources, this, use_compat);
+
+ p_file->store_string(String(state->get_node_property_name(i, j)).property_name_encode() + " = " + vars + "\n");
+ }
+
+ if (i < state->get_node_count() - 1) {
+ p_file->store_line(String());
+ }
+ }
+
+ for (int i = 0; i < state->get_connection_count(); i++) {
+ if (i == 0) {
+ p_file->store_line("");
+ }
+
+ String connstr = "[connection";
+ connstr += " signal=\"" + String(state->get_connection_signal(i)).c_escape() + "\"";
+ connstr += " from=\"" + String(state->get_connection_source(i).simplified()).c_escape() + "\"";
+ connstr += " to=\"" + String(state->get_connection_target(i).simplified()).c_escape() + "\"";
+ connstr += " method=\"" + String(state->get_connection_method(i)).c_escape() + "\"";
+ int flags = state->get_connection_flags(i);
+ if (flags != Object::CONNECT_PERSIST) {
+ connstr += " flags=" + itos(flags);
+ }
+
+ {
+ PackedInt32Array from_idp = state->get_connection_source_id_path(i);
+ if (from_idp.size()) {
+ connstr += " from_uid_path=" + Variant(from_idp).get_construct_string();
+ }
+ }
+
+ {
+ PackedInt32Array to_idp = state->get_connection_target_id_path(i);
+ if (to_idp.size()) {
+ connstr += " to_uid_path=" + Variant(to_idp).get_construct_string();
+ }
+ }
+
+ int unbinds = state->get_connection_unbinds(i);
+ if (unbinds > 0) {
+ connstr += " unbinds=" + itos(unbinds);
+ }
+
+ Array binds = state->get_connection_binds(i);
+ p_file->store_string(connstr);
+ if (binds.size()) {
+ String vars;
+ VariantWriter::write_to_string(binds, vars, true, _write_resources, this, use_compat);
+ p_file->store_string(" binds= " + vars);
+ }
+
+ p_file->store_line("]");
+ }
+
+ Vector<NodePath> editable_instances = state->get_editable_instances();
+ for (int i = 0; i < editable_instances.size(); i++) {
+ if (i == 0) {
+ p_file->store_line("");
+ }
+ p_file->store_line("[editable path=\"" + editable_instances[i].operator String().c_escape() + "\"]");
+ }
+}
+
Error ResourceFormatSaverTextInstance::save(const String &p_path, const Ref<Resource> &p_resource, uint32_t p_flags) {
Resource::seed_scene_unique_id(p_path.hash()); // Seeding for save path should make it deterministic for importers.
@@ -1918,18 +2083,17 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path, const Ref<Reso
}
}
+ bool first_meta = true;
+ bool has_nested_scene = false;
for (List<Ref<Resource>>::Element *E = saved_resources.front(); E; E = E->next()) {
Ref<Resource> res = E->get();
ERR_CONTINUE(!resource_set.has(res));
bool main = (E->next() == nullptr);
- if (main && packed_scene.is_valid()) {
- break; // Save as a scene.
- }
-
- if (main) {
+ bool is_scene = res->is_class("PackedScene");
+ if (main && !is_scene) {
f->store_line("[resource]");
- } else {
+ } else if (!main) {
String line = "[sub_resource ";
if (res->get_scene_unique_id().is_empty()) {
String new_id;
@@ -1963,15 +2127,20 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path, const Ref<Reso
List<PropertyInfo> property_list;
res->get_property_list(&property_list);
for (const PropertyInfo &pi : property_list) {
- if (skip_editor && pi.name.begins_with("__editor")) {
+ String name = pi.name;
+ if (skip_editor && name.begins_with("__editor")) {
continue;
}
- if (pi.name == META_PROPERTY_MISSING_RESOURCES) {
+
+ if (name == META_PROPERTY_MISSING_RESOURCES) {
+ continue;
+ }
+
+ if (is_scene && name == "_bundled") {
continue;
}
if (pi.usage & PROPERTY_USAGE_STORAGE || missing_resource_properties.has(pi.name)) {
- String name = pi.name;
Variant value;
if (pi.usage & PROPERTY_USAGE_RESOURCE_NOT_PERSISTENT) {
NonPersistentKey npk;
@@ -2005,160 +2174,38 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path, const Ref<Reso
String vars;
VariantWriter::write_to_string(value, vars, true, _write_resources, this, use_compat);
+
+ // This is here to avoid a change in all old scenes that didn't have have metadata support
+ // The scenes only need to have a resource tag if they have metadata
+ if (is_scene && main && first_meta) {
+ f->store_line("[resource]");
+ first_meta = false;
+ }
f->store_string(name.property_name_encode() + " = " + vars + "\n");
}
}
- if (E->next()) {
- f->store_line(String());
+ if (!main && is_scene && res.is_valid()) {
+ _parse_nodes(res, f);
+ has_nested_scene = true;
}
- }
-
- if (packed_scene.is_valid()) {
- // If this is a scene, save nodes and connections!
- Ref<SceneState> state = packed_scene->get_state();
- for (int i = 0; i < state->get_node_count(); i++) {
- StringName type = state->get_node_type(i);
- StringName name = state->get_node_name(i);
- int index = state->get_node_index(i);
- int unique_id = state->get_node_unique_id(i);
- NodePath parent_path = state->get_node_path(i, true);
- PackedInt32Array parent_id_path = state->get_node_parent_id_path(i);
- PackedInt32Array owner_id_path = state->get_node_owner_id_path(i);
- NodePath owner = state->get_node_owner_path(i);
- Ref<PackedScene> instance = state->get_node_instance(i);
- String instance_placeholder = state->get_node_instance_placeholder(i);
- Vector<StringName> groups = state->get_node_groups(i);
- Vector<String> deferred_node_paths = state->get_node_deferred_nodepath_properties(i);
-
- String header = "[node";
- header += " name=\"" + String(name).c_escape() + "\"";
- if (type != StringName()) {
- header += " type=\"" + String(type) + "\"";
- }
- if (parent_path != NodePath()) {
- header += " parent=\"" + String(parent_path.simplified()).c_escape() + "\"";
- if (parent_id_path.size()) {
- header += " parent_id_path=" + Variant(parent_id_path).get_construct_string();
- }
- }
-
- if (owner != NodePath() && owner != NodePath(".")) {
- header += " owner=\"" + String(owner.simplified()).c_escape() + "\"";
- if (owner_id_path.size()) {
- header += " owner_uid_path=" + Variant(owner_id_path).get_construct_string();
- }
- }
- if (index >= 0) {
- header += " index=\"" + itos(index) + "\"";
- }
-
- if (unique_id != Node::UNIQUE_SCENE_ID_UNASSIGNED) {
- header += " unique_id=" + itos(unique_id) + "";
- }
-
- if (deferred_node_paths.size()) {
- header += " node_paths=" + Variant(deferred_node_paths).get_construct_string();
- }
- if (groups.size()) {
- // Write all groups on the same line as they're part of a section header.
- // This improves readability while not impacting VCS friendliness too much,
- // since it's rare to have more than 5 groups assigned to a single node.
- groups.sort_custom<StringName::AlphCompare>();
- String sgroups = " groups=[";
- for (int j = 0; j < groups.size(); j++) {
- sgroups += "\"" + String(groups[j]).c_escape() + "\"";
- if (j < groups.size() - 1) {
- sgroups += ", ";
- }
- }
- sgroups += "]";
- header += sgroups;
- }
-
- f->store_string(header);
-
- if (!instance_placeholder.is_empty()) {
- String vars;
- f->store_string(" instance_placeholder=");
- VariantWriter::write_to_string(instance_placeholder, vars, true, _write_resources, this, use_compat);
- f->store_string(vars);
- }
-
- if (instance.is_valid()) {
- String vars;
- f->store_string(" instance=");
- VariantWriter::write_to_string(instance, vars, true, _write_resources, this, use_compat);
- f->store_string(vars);
- }
-
- f->store_line("]");
-
- for (int j = 0; j < state->get_node_property_count(i); j++) {
- String vars;
- VariantWriter::write_to_string(state->get_node_property_value(i, j), vars, true, _write_resources, this, use_compat);
-
- f->store_string(String(state->get_node_property_name(i, j)).property_name_encode() + " = " + vars + "\n");
- }
-
- if (i < state->get_node_count() - 1) {
- f->store_line(String());
- }
+ if (is_scene && main && first_meta && has_nested_scene) {
+ f->store_line("[resource]");
+ first_meta = false;
}
- for (int i = 0; i < state->get_connection_count(); i++) {
- if (i == 0) {
- f->store_line("");
- }
-
- String connstr = "[connection";
- connstr += " signal=\"" + String(state->get_connection_signal(i)).c_escape() + "\"";
- connstr += " from=\"" + String(state->get_connection_source(i).simplified()).c_escape() + "\"";
- connstr += " to=\"" + String(state->get_connection_target(i).simplified()).c_escape() + "\"";
- connstr += " method=\"" + String(state->get_connection_method(i)).c_escape() + "\"";
- int flags = state->get_connection_flags(i);
- if (flags != Object::CONNECT_PERSIST) {
- connstr += " flags=" + itos(flags);
- }
-
- {
- PackedInt32Array from_idp = state->get_connection_source_id_path(i);
- if (from_idp.size()) {
- connstr += " from_uid_path=" + Variant(from_idp).get_construct_string();
- }
- }
-
- {
- PackedInt32Array to_idp = state->get_connection_target_id_path(i);
- if (to_idp.size()) {
- connstr += " to_uid_path=" + Variant(to_idp).get_construct_string();
- }
- }
-
- int unbinds = state->get_connection_unbinds(i);
- if (unbinds > 0) {
- connstr += " unbinds=" + itos(unbinds);
- }
-
- Array binds = state->get_connection_binds(i);
- f->store_string(connstr);
- if (binds.size()) {
- String vars;
- VariantWriter::write_to_string(binds, vars, true, _write_resources, this, use_compat);
- f->store_string(" binds= " + vars);
- }
-
- f->store_line("]");
+ if (E->next()) {
+ f->store_line(String());
}
+ }
- Vector<NodePath> editable_instances = state->get_editable_instances();
- for (int i = 0; i < editable_instances.size(); i++) {
- if (i == 0) {
- f->store_line("");
- }
- f->store_line("[editable path=\"" + editable_instances[i].operator String().c_escape() + "\"]");
- }
+ if (!first_meta) {
+ f->store_string("\n");
+ }
+
+ if (packed_scene.is_valid()) {
+ _parse_nodes(packed_scene, f);
}
if (f->get_error() != OK && f->get_error() != ERR_FILE_EOF) {
diff --git a/scene/resources/resource_format_text.h b/scene/resources/resource_format_text.h
index 72861a9a710..61bdcecb75d 100644
--- a/scene/resources/resource_format_text.h
+++ b/scene/resources/resource_format_text.h
@@ -123,8 +123,9 @@ private:
Error error = OK;
Ref<Resource> resource;
+ Ref<PackedScene> packed_scene;
- Ref<PackedScene> _parse_node_tag(VariantParser::ResourceParser &parser);
+ Ref<PackedScene> _parse_node_tag(const Ref<PackedScene> &p_current_scene, VariantParser::ResourceParser &p_parser);
public:
Ref<Resource> get_resource();
@@ -199,6 +200,7 @@ class ResourceFormatSaverTextInstance {
};
void _find_resources(const Variant &p_variant, bool p_main = false);
+ void _parse_nodes(const Ref<PackedScene> &curr_scene, const Ref<FileAccess> &p_file);
static String _write_resources(void *ud, const Ref<Resource> &p_resource);
String _write_resource(const Ref<Resource> &res);
diff --git a/tests/core/io/test_scenes.cpp b/tests/core/io/test_scenes.cpp
new file mode 100644
index 00000000000..5c8bef4d7d3
--- /dev/null
+++ b/tests/core/io/test_scenes.cpp
@@ -0,0 +1,271 @@
+/**************************************************************************/
+/* test_scenes.cpp */
+/**************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/**************************************************************************/
+/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/**************************************************************************/
+
+#include "tests/test_macros.h"
+
+TEST_FORCE_LINK(test_scenes)
+
+#include "core/io/file_access.h"
+#include "core/io/resource.h"
+#include "core/io/resource_loader.h"
+#include "core/io/resource_saver.h"
+#include "core/object/class_db.h"
+#include "core/object/object.h"
+#include "core/object/property_info.h"
+#include "core/os/memory.h"
+#include "core/string/string_name.h"
+#include "core/variant/variant.h"
+#include "scene/main/node.h"
+#include "scene/resources/packed_scene.h"
+#include "tests/test_utils.h"
+
+namespace TestScenes {
+
+class _TestNodeForTestingNestedScenes : public Node {
+ GDCLASS(_TestNodeForTestingNestedScenes, Node);
+
+ Ref<PackedScene> _inner_scene;
+
+public:
+ void set_inner_scene(const Ref<PackedScene> p_scene) {
+ _inner_scene = p_scene;
+ }
+
+ Ref<PackedScene> get_inner_scene() const {
+ return _inner_scene;
+ }
+
+ static void _bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_inner_scene", "p_scene"), &_TestNodeForTestingNestedScenes::set_inner_scene);
+ ClassDB::bind_method(D_METHOD("get_inner_scene"), &_TestNodeForTestingNestedScenes::get_inner_scene);
+
+ ADD_PROPERTY(
+ PropertyInfo(Variant::OBJECT, "inner_scene", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE),
+ "set_inner_scene", "get_inner_scene");
+ }
+};
+
+void prepare_scene(Ref<PackedScene> scene) {
+ Ref<Resource> child_resource = memnew(Resource);
+ child_resource->set_name("I'm a child resource");
+ scene->set_meta("other_resource", child_resource);
+
+ scene->set_name("Hello world");
+ scene->set_meta("ExampleMetadata", Vector2i(40, 80));
+ scene->set_meta("string", "The\nstring\nwith\nunnecessary\nline\n\t\\\nbreaks");
+}
+
+void validate_scene(Ref<PackedScene> loaded_scene) {
+ CHECK_MESSAGE(
+ loaded_scene->get_name() == "Hello world",
+ "The loaded resource name should be equal to the expected value.");
+ CHECK_MESSAGE(
+ loaded_scene->get_meta("ExampleMetadata") == Vector2i(40, 80),
+ "The loaded resource metadata should be equal to the expected value.");
+ CHECK_MESSAGE(
+ loaded_scene->get_meta("string") == "The\nstring\nwith\nunnecessary\nline\n\t\\\nbreaks",
+ "The loaded resource metadata should be equal to the expected value.");
+
+ const Ref<Resource> &meta_resource = loaded_scene->get_meta("other_resource");
+ CHECK_MESSAGE(
+ meta_resource->get_name() == "I'm a child resource",
+ "The loaded child resource name should be equal to the expected value.");
+}
+
+void validate_and_instantiate_scene(Ref<PackedScene> loaded_scene) {
+ bool is_null = loaded_scene.is_null();
+ CHECK_MESSAGE(!is_null, "Could not open scene file");
+
+ if (is_null) {
+ return;
+ }
+
+ validate_scene(loaded_scene);
+
+ Node *new_node = static_cast<Node *>(loaded_scene->instantiate());
+ CHECK_MESSAGE(
+ new_node->get_name() == "named_node",
+ "The instantiated node has invalid name.");
+
+ const Ref<PackedScene> &inner_loaded_scene = loaded_scene->get_meta("inner_scene");
+ validate_scene(inner_loaded_scene);
+
+ Node *inner_new_node = static_cast<Node *>(inner_loaded_scene->instantiate());
+ CHECK_MESSAGE(
+ inner_new_node->get_name() == "inner_named_node",
+ "The instantiated node has invalid name.");
+
+ memdelete(new_node);
+ memdelete(inner_new_node);
+}
+
+TEST_CASE("[Scenes] Scene Saving and loading") {
+ Node *inner_node = memnew(Node);
+ inner_node->set_name("inner_named_node");
+
+ Ref<PackedScene> inner_scene = memnew(PackedScene);
+ inner_scene->pack(inner_node);
+ prepare_scene(inner_scene);
+
+ Node *node = memnew(Node);
+ node->set_name("named_node");
+
+ Ref<PackedScene> scene = memnew(PackedScene);
+ scene->pack(node);
+ prepare_scene(scene);
+ scene->set_meta("inner_scene", inner_scene);
+
+ Ref<Resource> child_resource = memnew(Resource);
+ child_resource->set_name("I'm a child resource");
+ scene->set_meta("other_resource", child_resource);
+
+ const String save_path_binary = TestUtils::get_temp_path("scene.res");
+ const String save_path_text = TestUtils::get_temp_path("scene.tscn");
+
+ ResourceSaver::save(scene, save_path_binary);
+ ResourceSaver::save(scene, save_path_text);
+
+ const Ref<PackedScene> &loaded_resource_binary = ResourceLoader::load(save_path_binary);
+ validate_and_instantiate_scene(loaded_resource_binary);
+
+ const Ref<PackedScene> &loaded_resource_text = ResourceLoader::load(save_path_text);
+ validate_and_instantiate_scene(loaded_resource_text);
+
+ memdelete(node);
+ memdelete(inner_node);
+}
+
+void validate_nested_scene(Ref<PackedScene> loaded_scene) {
+ bool is_null = loaded_scene.is_null();
+ CHECK_MESSAGE(!is_null, "Could not open scene file");
+
+ if (is_null) {
+ return;
+ }
+
+ _TestNodeForTestingNestedScenes *node_for_testing = static_cast<_TestNodeForTestingNestedScenes *>(loaded_scene->instantiate());
+ Ref<PackedScene> inner_scene = node_for_testing->get_inner_scene();
+ Node *inner_node = inner_scene->instantiate();
+
+ CHECK_MESSAGE(
+ inner_node->get_name() == "named_node",
+ "The instantiated node has invalid name.");
+
+ memdelete(node_for_testing);
+ memdelete(inner_node);
+}
+
+// This is to test a specific bug that can happen.
+TEST_CASE("[Scenes] Scene Saving and loading as property") {
+ ClassDB::register_class<_TestNodeForTestingNestedScenes>();
+
+ Node *inner_node = memnew(Node);
+ const Ref<PackedScene> inner_scene = memnew(PackedScene);
+ inner_node->set_name("named_node");
+ inner_scene->pack(inner_node);
+
+ _TestNodeForTestingNestedScenes *nested_scene_node = memnew(_TestNodeForTestingNestedScenes);
+ nested_scene_node->set_inner_scene(inner_scene);
+
+ Ref<PackedScene> scene = memnew(PackedScene);
+ scene->pack(nested_scene_node);
+
+ const String save_path_binary = TestUtils::get_temp_path("nested_scene_test.res");
+ const String save_path_text = TestUtils::get_temp_path("nested_scene_test.tscn");
+
+ ResourceSaver::save(scene, save_path_binary);
+ ResourceSaver::save(scene, save_path_text);
+
+ memdelete(inner_node);
+ memdelete(nested_scene_node);
+
+ const Ref<PackedScene> &loaded_resource_binary = ResourceLoader::load(save_path_binary);
+ validate_nested_scene(loaded_resource_binary);
+
+ const Ref<PackedScene> &loaded_resource_text = ResourceLoader::load(save_path_text);
+ validate_nested_scene(loaded_resource_text);
+}
+
+void validate_simple_scene(Ref<PackedScene> loaded_scene) {
+ bool is_null = loaded_scene.is_null();
+ CHECK(!is_null);
+
+ if (is_null) {
+ return;
+ }
+
+ Node *instanced_node = static_cast<Node *>(loaded_scene->instantiate());
+ CHECK_MESSAGE(
+ instanced_node->get_name() == "SimpleNode",
+ "The instantiated node has invalid name..");
+
+ memdelete(instanced_node);
+}
+
+TEST_CASE("[Scenes] Simple scene saving and loading") {
+ Node *node = memnew(Node);
+ node->set_name("SimpleNode");
+
+ Ref<PackedScene> scene = memnew(PackedScene);
+ scene->pack(node);
+
+ const String save_path_binary = TestUtils::get_temp_path("simple_scene_test.res");
+ const String save_path_text = TestUtils::get_temp_path("simple_scene_test.tscn");
+
+ ResourceSaver::save(scene, save_path_binary);
+ ResourceSaver::save(scene, save_path_text);
+
+ memdelete(node);
+
+ const Ref<PackedScene> &loaded_resource_binary = ResourceLoader::load(save_path_binary);
+ validate_simple_scene(loaded_resource_binary);
+
+ const Ref<PackedScene> &loaded_resource_text = ResourceLoader::load(save_path_text);
+ validate_simple_scene(loaded_resource_text);
+
+ // Simple scenes should not have a [resource] tag, so let's validate it.
+ Ref<FileAccess> f = FileAccess::open(save_path_text, FileAccess::READ);
+ bool is_null = f.is_null();
+ CHECK(!is_null);
+
+ if (is_null) {
+ return;
+ }
+
+ while (!f->eof_reached()) {
+ String line;
+ line = f->get_line();
+ CHECK_MESSAGE(
+ line != "[resource]",
+ "The scene file cannot have the [resource] tag");
+ }
+ f->close();
+}
+} // namespace TestScenes