/*************************************************************************/ /* packed_scene.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "packed_scene.h" #include "core/config/engine.h" #include "core/config/project_settings.h" #include "core/core_string_names.h" #include "core/io/resource_loader.h" #include "scene/2d/node_2d.h" #include "scene/3d/node_3d.h" #include "scene/gui/control.h" #include "scene/main/instance_placeholder.h" #define PACKED_SCENE_VERSION 2 bool SceneState::can_instantiate() const { return nodes.size() > 0; } Node *SceneState::instantiate(GenEditState p_edit_state) const { // nodes where instancing failed (because something is missing) List stray_instances; #define NODE_FROM_ID(p_name, p_id) \ Node *p_name; \ if (p_id & FLAG_ID_IS_PATH) { \ NodePath np = node_paths[p_id & FLAG_MASK]; \ p_name = ret_nodes[0]->get_node_or_null(np); \ } else { \ ERR_FAIL_INDEX_V(p_id &FLAG_MASK, nc, nullptr); \ p_name = ret_nodes[p_id & FLAG_MASK]; \ } int nc = nodes.size(); ERR_FAIL_COND_V(nc == 0, nullptr); const StringName *snames = nullptr; int sname_count = names.size(); if (sname_count) { snames = &names[0]; } const Variant *props = nullptr; int prop_count = variants.size(); if (prop_count) { props = &variants[0]; } //Vector properties; const NodeData *nd = &nodes[0]; Node **ret_nodes = (Node **)alloca(sizeof(Node *) * nc); bool gen_node_path_cache = p_edit_state != GEN_EDIT_STATE_DISABLED && node_path_cache.is_empty(); Map, Ref> resources_local_to_scene; for (int i = 0; i < nc; i++) { const NodeData &n = nd[i]; Node *parent = nullptr; if (i > 0) { ERR_FAIL_COND_V_MSG(n.parent == -1, nullptr, vformat("Invalid scene: node %s does not specify its parent node.", snames[n.name])); NODE_FROM_ID(nparent, n.parent); #ifdef DEBUG_ENABLED if (!nparent && (n.parent & FLAG_ID_IS_PATH)) { WARN_PRINT(String("Parent path '" + String(node_paths[n.parent & FLAG_MASK]) + "' for node '" + String(snames[n.name]) + "' has vanished when instancing: '" + get_path() + "'.").ascii().get_data()); } #endif parent = nparent; } else { // i == 0 is root node. Confirm that it doesn't have a parent defined. ERR_FAIL_COND_V_MSG(n.parent != -1, nullptr, vformat("Invalid scene: root node %s cannot specify a parent node.", snames[n.name])); } Node *node = nullptr; if (i == 0 && base_scene_idx >= 0) { //scene inheritance on root node Ref sdata = props[base_scene_idx]; ERR_FAIL_COND_V(!sdata.is_valid(), nullptr); node = sdata->instantiate(p_edit_state == GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE); //only main gets main edit state ERR_FAIL_COND_V(!node, nullptr); if (p_edit_state != GEN_EDIT_STATE_DISABLED) { node->set_scene_inherited_state(sdata->get_state()); } } else if (n.instance >= 0) { //instance a scene into this node if (n.instance & FLAG_INSTANCE_IS_PLACEHOLDER) { String path = props[n.instance & FLAG_MASK]; if (disable_placeholders) { Ref sdata = ResourceLoader::load(path, "PackedScene"); ERR_FAIL_COND_V(!sdata.is_valid(), nullptr); node = sdata->instantiate(p_edit_state == GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE); ERR_FAIL_COND_V(!node, nullptr); } else { InstancePlaceholder *ip = memnew(InstancePlaceholder); ip->set_instance_path(path); node = ip; } node->set_scene_instance_load_placeholder(true); } else { Ref sdata = props[n.instance & FLAG_MASK]; ERR_FAIL_COND_V(!sdata.is_valid(), nullptr); node = sdata->instantiate(p_edit_state == GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE); ERR_FAIL_COND_V(!node, nullptr); } } else if (n.type == TYPE_INSTANCED) { //get the node from somewhere, it likely already exists from another instance if (parent) { node = parent->_get_child_by_name(snames[n.name]); #ifdef DEBUG_ENABLED if (!node) { WARN_PRINT(String("Node '" + String(ret_nodes[0]->get_path_to(parent)) + "/" + String(snames[n.name]) + "' was modified from inside an instance, but it has vanished.").ascii().get_data()); } #endif } } else { Object *obj = nullptr; if (ClassDB::is_class_enabled(snames[n.type])) { //node belongs to this scene and must be created obj = ClassDB::instantiate(snames[n.type]); } if (!Object::cast_to(obj)) { if (obj) { memdelete(obj); obj = nullptr; } WARN_PRINT(vformat("Node %s of type %s cannot be created. A placeholder will be created instead.", snames[n.name], snames[n.type]).ascii().get_data()); if (n.parent >= 0 && n.parent < nc && ret_nodes[n.parent]) { if (Object::cast_to(ret_nodes[n.parent])) { obj = memnew(Control); } else if (Object::cast_to(ret_nodes[n.parent])) { obj = memnew(Node2D); #ifndef _3D_DISABLED } else if (Object::cast_to(ret_nodes[n.parent])) { obj = memnew(Node3D); #endif // _3D_DISABLED } } if (!obj) { obj = memnew(Node); } } node = Object::cast_to(obj); } if (node) { // may not have found the node (part of instantiated scene and removed) // if found all is good, otherwise ignore //properties int nprop_count = n.properties.size(); if (nprop_count) { const NodeData::Property *nprops = &n.properties[0]; for (int j = 0; j < nprop_count; j++) { bool valid; ERR_FAIL_INDEX_V(nprops[j].name, sname_count, nullptr); ERR_FAIL_INDEX_V(nprops[j].value, prop_count, nullptr); if (snames[nprops[j].name] == CoreStringNames::get_singleton()->_script) { //work around to avoid old script variables from disappearing, should be the proper fix to: //https://github.com/godotengine/godot/issues/2958 //store old state List> old_state; if (node->get_script_instance()) { node->get_script_instance()->get_property_state(old_state); } node->set(snames[nprops[j].name], props[nprops[j].value], &valid); //restore old state for new script, if exists for (const Pair &E : old_state) { node->set(E.first, E.second); } } else { Variant value = props[nprops[j].value]; if (value.get_type() == Variant::OBJECT) { //handle resources that are local to scene by duplicating them if needed Ref res = value; if (res.is_valid()) { if (res->is_local_to_scene()) { Map, Ref>::Element *E = resources_local_to_scene.find(res); if (E) { value = E->get(); } else { Node *base = i == 0 ? node : ret_nodes[0]; if (p_edit_state == GEN_EDIT_STATE_MAIN) { //for the main scene, use the resource as is res->configure_for_local_scene(base, resources_local_to_scene); resources_local_to_scene[res] = res; } else { //for instances, a copy must be made Node *base2 = i == 0 ? node : ret_nodes[0]; Ref local_dupe = res->duplicate_for_local_scene(base2, resources_local_to_scene); resources_local_to_scene[res] = local_dupe; res = local_dupe; value = local_dupe; } } //must make a copy, because this res is local to scene } } } else if (p_edit_state == GEN_EDIT_STATE_INSTANCE) { value = value.duplicate(true); // Duplicate arrays and dictionaries for the editor } node->set(snames[nprops[j].name], value, &valid); } } } //name //groups for (int j = 0; j < n.groups.size(); j++) { ERR_FAIL_INDEX_V(n.groups[j], sname_count, nullptr); node->add_to_group(snames[n.groups[j]], true); } if (n.instance >= 0 || n.type != TYPE_INSTANCED || i == 0) { //if node was not part of instance, must set its name, parenthood and ownership if (i > 0) { if (parent) { parent->_add_child_nocheck(node, snames[n.name]); if (n.index >= 0 && n.index < parent->get_child_count() - 1) { parent->move_child(node, n.index); } } else { //it may be possible that an instantiated scene has changed //and the node has nowhere to go anymore stray_instances.push_back(node); //can't be added, go to stray list } } else { if (Engine::get_singleton()->is_editor_hint()) { //validate name if using editor, to avoid broken node->set_name(snames[n.name]); } else { node->_set_name_nocheck(snames[n.name]); } } } if (n.owner >= 0) { NODE_FROM_ID(owner, n.owner); if (owner) { node->_set_owner_nocheck(owner); } } } ret_nodes[i] = node; if (node && gen_node_path_cache && ret_nodes[0]) { NodePath n2 = ret_nodes[0]->get_path_to(node); node_path_cache[n2] = i; } } for (Map, Ref>::Element *E = resources_local_to_scene.front(); E; E = E->next()) { E->get()->setup_local_to_scene(); } //do connections int cc = connections.size(); const ConnectionData *cdata = connections.ptr(); for (int i = 0; i < cc; i++) { const ConnectionData &c = cdata[i]; //ERR_FAIL_INDEX_V( c.from, nc, nullptr ); //ERR_FAIL_INDEX_V( c.to, nc, nullptr ); NODE_FROM_ID(cfrom, c.from); NODE_FROM_ID(cto, c.to); if (!cfrom || !cto) { continue; } Vector binds; if (c.binds.size()) { binds.resize(c.binds.size()); for (int j = 0; j < c.binds.size(); j++) { binds.write[j] = props[c.binds[j]]; } } cfrom->connect(snames[c.signal], Callable(cto, snames[c.method]), binds, CONNECT_PERSIST | c.flags); } //Node *s = ret_nodes[0]; //remove nodes that could not be added, likely as a result that while (stray_instances.size()) { memdelete(stray_instances.front()->get()); stray_instances.pop_front(); } for (int i = 0; i < editable_instances.size(); i++) { Node *ei = ret_nodes[0]->get_node_or_null(editable_instances[i]); if (ei) { ret_nodes[0]->set_editable_instance(ei, true); } } return ret_nodes[0]; } static int _nm_get_string(const String &p_string, Map &name_map) { if (name_map.has(p_string)) { return name_map[p_string]; } int idx = name_map.size(); name_map[p_string] = idx; return idx; } static int _vm_get_variant(const Variant &p_variant, HashMap &variant_map) { if (variant_map.has(p_variant)) { return variant_map[p_variant]; } int idx = variant_map.size(); variant_map[p_variant] = idx; return idx; } Error SceneState::_parse_node(Node *p_owner, Node *p_node, int p_parent_idx, Map &name_map, HashMap &variant_map, Map &node_map, Map &nodepath_map) { // this function handles all the work related to properly packing scenes, be it // instantiated or inherited. // given the complexity of this process, an attempt will be made to properly // document it. if you fail to understand something, please ask! //discard nodes that do not belong to be processed if (p_node != p_owner && p_node->get_owner() != p_owner && !p_owner->is_editable_instance(p_node->get_owner())) { return OK; } // save the child instantiated scenes that are chosen as editable, so they can be restored // upon load back if (p_node != p_owner && p_node->get_filename() != String() && p_owner->is_editable_instance(p_node)) { editable_instances.push_back(p_owner->get_path_to(p_node)); } NodeData nd; nd.name = _nm_get_string(p_node->get_name(), name_map); nd.instance = -1; //not instantiated by default //really convoluted condition, but it basically checks that index is only saved when part of an inherited scene OR the node parent is from the edited scene if (p_owner->get_scene_inherited_state().is_null() && (p_node == p_owner || (p_node->get_owner() == p_owner && (p_node->get_parent() == p_owner || p_node->get_parent()->get_owner() == p_owner)))) { //do not save index, because it belongs to saved scene and scene is not inherited nd.index = -1; } else if (p_node == p_owner) { //This (hopefully) happens if the node is a scene root, so its index is irrelevant. nd.index = -1; } else { //part of an inherited scene, or parent is from an instantiated scene nd.index = p_node->get_index(); } // if this node is part of an instantiated scene or sub-instantiated scene // we need to get the corresponding instance states. // with the instance states, we can query for identical properties/groups // and only save what has changed List pack_state_stack; bool instantiated_by_owner = true; { Node *n = p_node; while (n) { if (n == p_owner) { Ref state = n->get_scene_inherited_state(); if (state.is_valid()) { int node = state->find_node_by_path(n->get_path_to(p_node)); if (node >= 0) { //this one has state for this node, save PackState ps; ps.node = node; ps.state = state; pack_state_stack.push_back(ps); instantiated_by_owner = false; } } if (p_node->get_filename() != String() && p_node->get_owner() == p_owner && instantiated_by_owner) { if (p_node->get_scene_instance_load_placeholder()) { //it's a placeholder, use the placeholder path nd.instance = _vm_get_variant(p_node->get_filename(), variant_map); nd.instance |= FLAG_INSTANCE_IS_PLACEHOLDER; } else { //must instance ourselves Ref instance = ResourceLoader::load(p_node->get_filename()); if (!instance.is_valid()) { return ERR_CANT_OPEN; } nd.instance = _vm_get_variant(instance, variant_map); } } n = nullptr; } else { if (n->get_filename() != String()) { //is an instance Ref state = n->get_scene_instance_state(); if (state.is_valid()) { int node = state->find_node_by_path(n->get_path_to(p_node)); if (node >= 0) { //this one has state for this node, save PackState ps; ps.node = node; ps.state = state; pack_state_stack.push_back(ps); } } } n = n->get_owner(); } } } // all setup, we then proceed to check all properties for the node // and save the ones that are worth saving List plist; p_node->get_property_list(&plist); StringName type = p_node->get_class(); Ref