packed_scene.cpp 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319
  1. /**************************************************************************/
  2. /* packed_scene.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. #include "packed_scene.h"
  31. #include "core/config/engine.h"
  32. #include "core/io/missing_resource.h"
  33. #include "core/io/resource_loader.h"
  34. #include "core/templates/local_vector.h"
  35. #include "scene/2d/node_2d.h"
  36. #include "scene/gui/control.h"
  37. #include "scene/main/instance_placeholder.h"
  38. #include "scene/main/missing_node.h"
  39. #include "scene/property_utils.h"
  40. #ifndef _3D_DISABLED
  41. #include "scene/3d/node_3d.h"
  42. #endif // _3D_DISABLED
  43. #define PACKED_SCENE_VERSION 3
  44. #ifdef TOOLS_ENABLED
  45. SceneState::InstantiationWarningNotify SceneState::instantiation_warn_notify = nullptr;
  46. #endif
  47. bool SceneState::can_instantiate() const {
  48. return nodes.size() > 0;
  49. }
  50. static Array _sanitize_node_pinned_properties(Node *p_node) {
  51. Array pinned = p_node->get_meta("_edit_pinned_properties_", Array());
  52. if (pinned.is_empty()) {
  53. return Array();
  54. }
  55. HashSet<StringName> storable_properties;
  56. p_node->get_storable_properties(storable_properties);
  57. int i = 0;
  58. do {
  59. if (storable_properties.has(pinned[i])) {
  60. i++;
  61. } else {
  62. pinned.remove_at(i);
  63. }
  64. } while (i < pinned.size());
  65. if (pinned.is_empty()) {
  66. p_node->remove_meta("_edit_pinned_properties_");
  67. }
  68. return pinned;
  69. }
  70. Ref<Resource> SceneState::get_remap_resource(const Ref<Resource> &p_resource, HashMap<Ref<Resource>, Ref<Resource>> &remap_cache, const Ref<Resource> &p_fallback, Node *p_for_scene) {
  71. ERR_FAIL_COND_V(p_resource.is_null(), Ref<Resource>());
  72. Ref<Resource> remap_resource;
  73. // Find the shared copy of the source resource.
  74. HashMap<Ref<Resource>, Ref<Resource>>::Iterator R = remap_cache.find(p_resource);
  75. if (R) {
  76. remap_resource = R->value;
  77. } else if (p_fallback.is_valid() && p_fallback->is_local_to_scene() && p_fallback->get_class() == p_resource->get_class()) {
  78. // Simply copy the data from the source resource to update the fallback resource that was previously set.
  79. p_fallback->reset_state(); // May want to reset state.
  80. List<PropertyInfo> pi;
  81. p_resource->get_property_list(&pi);
  82. for (const PropertyInfo &E : pi) {
  83. if (!(E.usage & PROPERTY_USAGE_STORAGE)) {
  84. continue;
  85. }
  86. if (E.name == "resource_path") {
  87. continue; // Do not change path.
  88. }
  89. Variant value = p_resource->get(E.name);
  90. // The local-to-scene subresource instance is preserved, thus maintaining the previous sharing relationship.
  91. // This is mainly used when the sub-scene root is reset in the main scene.
  92. Ref<Resource> sub_res_of_from = value;
  93. if (sub_res_of_from.is_valid() && sub_res_of_from->is_local_to_scene()) {
  94. value = get_remap_resource(sub_res_of_from, remap_cache, p_fallback->get(E.name), p_fallback->get_local_scene());
  95. }
  96. p_fallback->set(E.name, value);
  97. }
  98. p_fallback->set_scene_unique_id(p_resource->get_scene_unique_id()); // Get the id from the main scene, in case the id changes again when saving the scene.
  99. remap_cache[p_resource] = p_fallback;
  100. remap_resource = p_fallback;
  101. } else { // A copy of the source resource is required to overwrite the previous one.
  102. Ref<Resource> local_dupe = p_resource->duplicate_for_local_scene(p_for_scene, remap_cache);
  103. remap_cache[p_resource] = local_dupe;
  104. remap_resource = local_dupe;
  105. }
  106. return remap_resource;
  107. }
  108. Node *SceneState::instantiate(GenEditState p_edit_state) const {
  109. // Nodes where instantiation failed (because something is missing.)
  110. List<Node *> stray_instances;
  111. #define NODE_FROM_ID(p_name, p_id) \
  112. Node *p_name; \
  113. if (p_id & FLAG_ID_IS_PATH) { \
  114. NodePath np = node_paths[p_id & FLAG_MASK]; \
  115. p_name = ret_nodes[0]->get_node_or_null(np); \
  116. } else { \
  117. ERR_FAIL_INDEX_V(p_id & FLAG_MASK, nc, nullptr); \
  118. p_name = ret_nodes[p_id & FLAG_MASK]; \
  119. }
  120. int nc = nodes.size();
  121. ERR_FAIL_COND_V_MSG(nc == 0, nullptr, vformat("Failed to instantiate scene state of \"%s\", node count is 0. Make sure the PackedScene resource is valid.", path));
  122. const StringName *snames = nullptr;
  123. int sname_count = names.size();
  124. if (sname_count) {
  125. snames = &names[0];
  126. }
  127. const Variant *props = nullptr;
  128. int prop_count = variants.size();
  129. if (prop_count) {
  130. props = &variants[0];
  131. }
  132. //Vector<Variant> properties;
  133. const NodeData *nd = &nodes[0];
  134. Node **ret_nodes = (Node **)alloca(sizeof(Node *) * nc);
  135. bool gen_node_path_cache = p_edit_state != GEN_EDIT_STATE_DISABLED && node_path_cache.is_empty();
  136. HashMap<Ref<Resource>, Ref<Resource>> resources_local_to_scene;
  137. LocalVector<DeferredNodePathProperties> deferred_node_paths;
  138. for (int i = 0; i < nc; i++) {
  139. const NodeData &n = nd[i];
  140. Node *parent = nullptr;
  141. String old_parent_path;
  142. if (i > 0) {
  143. ERR_FAIL_COND_V_MSG(n.parent == -1, nullptr, vformat("Invalid scene: node %s does not specify its parent node.", snames[n.name]));
  144. NODE_FROM_ID(nparent, n.parent);
  145. #ifdef DEBUG_ENABLED
  146. if (!nparent && (n.parent & FLAG_ID_IS_PATH)) {
  147. WARN_PRINT(String("Parent path '" + String(node_paths[n.parent & FLAG_MASK]) + "' for node '" + String(snames[n.name]) + "' has vanished when instantiating: '" + get_path() + "'.").ascii().get_data());
  148. old_parent_path = String(node_paths[n.parent & FLAG_MASK]).trim_prefix("./").replace_char('/', '@');
  149. nparent = ret_nodes[0];
  150. }
  151. #endif
  152. parent = nparent;
  153. } else {
  154. // i == 0 is root node.
  155. ERR_FAIL_COND_V_MSG(n.parent != -1, nullptr, vformat("Invalid scene: root node %s cannot specify a parent node.", snames[n.name]));
  156. ERR_FAIL_COND_V_MSG(n.type == TYPE_INSTANTIATED && base_scene_idx < 0, nullptr, vformat("Invalid scene: root node %s in an instance, but there's no base scene.", snames[n.name]));
  157. }
  158. Node *node = nullptr;
  159. MissingNode *missing_node = nullptr;
  160. bool is_inherited_scene = false;
  161. if (i == 0 && base_scene_idx >= 0) {
  162. // Scene inheritance on root node.
  163. Ref<PackedScene> sdata = props[base_scene_idx];
  164. ERR_FAIL_COND_V(sdata.is_null(), nullptr);
  165. 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
  166. ERR_FAIL_NULL_V(node, nullptr);
  167. if (p_edit_state != GEN_EDIT_STATE_DISABLED) {
  168. node->set_scene_inherited_state(sdata->get_state());
  169. }
  170. is_inherited_scene = true;
  171. } else if (n.instance >= 0) {
  172. // Instance a scene into this node.
  173. if (n.instance & FLAG_INSTANCE_IS_PLACEHOLDER) {
  174. const String scene_path = props[n.instance & FLAG_MASK];
  175. if (disable_placeholders) {
  176. Ref<PackedScene> sdata = ResourceLoader::load(scene_path, "PackedScene");
  177. if (sdata.is_valid()) {
  178. node = sdata->instantiate(p_edit_state == GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE);
  179. ERR_FAIL_NULL_V(node, nullptr);
  180. } else if (ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
  181. missing_node = memnew(MissingNode);
  182. missing_node->set_original_scene(scene_path);
  183. missing_node->set_recording_properties(true);
  184. node = missing_node;
  185. } else {
  186. ERR_FAIL_V_MSG(nullptr, "Placeholder scene is missing.");
  187. }
  188. } else {
  189. InstancePlaceholder *ip = memnew(InstancePlaceholder);
  190. ip->set_instance_path(scene_path);
  191. node = ip;
  192. }
  193. node->set_scene_instance_load_placeholder(true);
  194. } else {
  195. Ref<Resource> res = props[n.instance & FLAG_MASK];
  196. Ref<PackedScene> sdata = res;
  197. if (sdata.is_valid()) {
  198. node = sdata->instantiate(p_edit_state == GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE);
  199. ERR_FAIL_NULL_V_MSG(node, nullptr, vformat("Failed to load scene dependency: \"%s\". Make sure the required scene is valid.", sdata->get_path()));
  200. } else if (ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
  201. missing_node = memnew(MissingNode);
  202. #ifdef TOOLS_ENABLED
  203. if (res.is_valid()) {
  204. missing_node->set_original_scene(res->get_meta("__load_path__", ""));
  205. }
  206. #endif
  207. missing_node->set_recording_properties(true);
  208. node = missing_node;
  209. } else {
  210. ERR_FAIL_V_MSG(nullptr, "Scene instance is missing.");
  211. }
  212. }
  213. } else if (n.type == TYPE_INSTANTIATED) {
  214. // Get the node from somewhere, it likely already exists from another instance.
  215. if (parent) {
  216. node = parent->_get_child_by_name(snames[n.name]);
  217. #ifdef DEBUG_ENABLED
  218. if (!node) {
  219. 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());
  220. }
  221. #endif
  222. }
  223. } else {
  224. // Node belongs to this scene and must be created.
  225. Object *obj = ClassDB::instantiate(snames[n.type]);
  226. node = Object::cast_to<Node>(obj);
  227. if (!node) {
  228. if (obj) {
  229. memdelete(obj);
  230. obj = nullptr;
  231. }
  232. if (ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
  233. missing_node = memnew(MissingNode);
  234. missing_node->set_original_class(snames[n.type]);
  235. missing_node->set_recording_properties(true);
  236. node = missing_node;
  237. obj = missing_node;
  238. } else {
  239. 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());
  240. if (n.parent >= 0 && n.parent < nc && ret_nodes[n.parent]) {
  241. if (Object::cast_to<Control>(ret_nodes[n.parent])) {
  242. obj = memnew(Control);
  243. } else if (Object::cast_to<Node2D>(ret_nodes[n.parent])) {
  244. obj = memnew(Node2D);
  245. #ifndef _3D_DISABLED
  246. } else if (Object::cast_to<Node3D>(ret_nodes[n.parent])) {
  247. obj = memnew(Node3D);
  248. #endif // _3D_DISABLED
  249. }
  250. }
  251. if (!obj) {
  252. obj = memnew(Node);
  253. }
  254. node = Object::cast_to<Node>(obj);
  255. }
  256. }
  257. }
  258. if (node) {
  259. // may not have found the node (part of instantiated scene and removed)
  260. // if found all is good, otherwise ignore
  261. //properties
  262. int nprop_count = n.properties.size();
  263. if (nprop_count) {
  264. const NodeData::Property *nprops = &n.properties[0];
  265. Dictionary missing_resource_properties;
  266. HashMap<Ref<Resource>, Ref<Resource>> resources_local_to_sub_scene; // Record the mappings in the sub-scene.
  267. for (int j = 0; j < nprop_count; j++) {
  268. bool valid;
  269. ERR_FAIL_INDEX_V(nprops[j].value, prop_count, nullptr);
  270. if (nprops[j].name & FLAG_PATH_PROPERTY_IS_NODE) {
  271. if (!Engine::get_singleton()->is_editor_hint() && node->get_scene_instance_load_placeholder()) {
  272. // We cannot know if the referenced nodes exist yet, so instead of deferring, we write the NodePaths directly.
  273. uint32_t name_idx = nprops[j].name & (FLAG_PATH_PROPERTY_IS_NODE - 1);
  274. ERR_FAIL_UNSIGNED_INDEX_V(name_idx, (uint32_t)sname_count, nullptr);
  275. node->set(snames[name_idx], props[nprops[j].value], &valid);
  276. continue;
  277. }
  278. uint32_t name_idx = nprops[j].name & (FLAG_PATH_PROPERTY_IS_NODE - 1);
  279. ERR_FAIL_UNSIGNED_INDEX_V(name_idx, (uint32_t)sname_count, nullptr);
  280. DeferredNodePathProperties dnp;
  281. dnp.value = props[nprops[j].value];
  282. dnp.base = node->get_instance_id();
  283. dnp.property = snames[name_idx];
  284. deferred_node_paths.push_back(dnp);
  285. continue;
  286. }
  287. ERR_FAIL_INDEX_V(nprops[j].name, sname_count, nullptr);
  288. if (snames[nprops[j].name] == CoreStringName(script)) {
  289. //work around to avoid old script variables from disappearing, should be the proper fix to:
  290. //https://github.com/godotengine/godot/issues/2958
  291. //store old state
  292. List<Pair<StringName, Variant>> old_state;
  293. if (node->get_script_instance()) {
  294. node->get_script_instance()->get_property_state(old_state);
  295. }
  296. node->set(snames[nprops[j].name], props[nprops[j].value], &valid);
  297. //restore old state for new script, if exists
  298. for (const Pair<StringName, Variant> &E : old_state) {
  299. node->set(E.first, E.second);
  300. }
  301. } else {
  302. Variant value = props[nprops[j].value];
  303. if (value.get_type() == Variant::OBJECT) {
  304. //handle resources that are local to scene by duplicating them if needed
  305. Ref<Resource> res = value;
  306. if (res.is_valid()) {
  307. value = make_local_resource(value, n, resources_local_to_sub_scene, node, snames[nprops[j].name], resources_local_to_scene, i, ret_nodes, p_edit_state);
  308. }
  309. } else {
  310. // Making sure that instances of inherited scenes don't share the same
  311. // reference between them.
  312. if (is_inherited_scene) {
  313. value = value.duplicate(true);
  314. }
  315. }
  316. if (value.get_type() == Variant::ARRAY) {
  317. Array set_array = value;
  318. bool is_get_valid = false;
  319. Variant get_value = node->get(snames[nprops[j].name], &is_get_valid);
  320. if (is_get_valid && get_value.get_type() == Variant::ARRAY) {
  321. Array get_array = get_value;
  322. if (set_array.is_same_typed(get_array)) {
  323. set_array = set_array.duplicate();
  324. } else {
  325. set_array = Array(set_array, get_array.get_typed_builtin(), get_array.get_typed_class_name(), get_array.get_typed_script());
  326. }
  327. }
  328. value = setup_resources_in_array(set_array, n, resources_local_to_sub_scene, node, snames[nprops[j].name], resources_local_to_scene, i, ret_nodes, p_edit_state);
  329. }
  330. if (value.get_type() == Variant::DICTIONARY) {
  331. Dictionary set_dict = value;
  332. bool is_get_valid = false;
  333. Variant get_value = node->get(snames[nprops[j].name], &is_get_valid);
  334. if (is_get_valid && get_value.get_type() == Variant::DICTIONARY) {
  335. Dictionary get_dict = get_value;
  336. if (set_dict.is_same_typed(get_dict)) {
  337. set_dict = set_dict.duplicate();
  338. } else {
  339. set_dict = Dictionary(set_dict, get_dict.get_typed_key_builtin(), get_dict.get_typed_key_class_name(), get_dict.get_typed_key_script(), get_dict.get_typed_value_builtin(), get_dict.get_typed_value_class_name(), get_dict.get_typed_value_script());
  340. }
  341. }
  342. value = setup_resources_in_dictionary(set_dict, n, resources_local_to_sub_scene, node, snames[nprops[j].name], resources_local_to_scene, i, ret_nodes, p_edit_state);
  343. }
  344. bool set_valid = true;
  345. if (ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled() && value.get_type() == Variant::OBJECT) {
  346. Ref<MissingResource> mr = value;
  347. if (mr.is_valid()) {
  348. missing_resource_properties[snames[nprops[j].name]] = mr;
  349. set_valid = false;
  350. }
  351. }
  352. if (set_valid) {
  353. node->set(snames[nprops[j].name], value, &valid);
  354. }
  355. if (p_edit_state == GEN_EDIT_STATE_INSTANCE && value.get_type() != Variant::OBJECT) {
  356. value = value.duplicate(true); // Duplicate arrays and dictionaries for the editor.
  357. }
  358. }
  359. }
  360. if (!missing_resource_properties.is_empty()) {
  361. node->set_meta(META_MISSING_RESOURCES, missing_resource_properties);
  362. }
  363. for (KeyValue<Ref<Resource>, Ref<Resource>> &E : resources_local_to_sub_scene) {
  364. if (E.value->get_local_scene() == node) {
  365. E.value->setup_local_to_scene(); // Setup may be required for the resource to work properly.
  366. }
  367. }
  368. }
  369. //name
  370. //groups
  371. for (int j = 0; j < n.groups.size(); j++) {
  372. ERR_FAIL_INDEX_V(n.groups[j], sname_count, nullptr);
  373. node->add_to_group(snames[n.groups[j]], true);
  374. }
  375. if (n.instance >= 0 || n.type != TYPE_INSTANTIATED || i == 0) {
  376. //if node was not part of instance, must set its name, parenthood and ownership
  377. if (i > 0) {
  378. if (parent) {
  379. bool pending_add = true;
  380. #ifdef TOOLS_ENABLED
  381. if (Engine::get_singleton()->is_editor_hint()) {
  382. Node *existing = parent->_get_child_by_name(snames[n.name]);
  383. if (existing) {
  384. // There's already a node in the same parent with the same name.
  385. // This means that somehow the node was added both to the scene being
  386. // loaded and another one instantiated in the former, maybe because of
  387. // manual editing, or a bug in scene saving, or a loophole in the workflow
  388. // (with any of the bugs possibly already fixed).
  389. // Bring consistency back by letting it be assigned a non-clashing name.
  390. // This simple workaround at least avoids leaks and helps the user realize
  391. // something awkward has happened.
  392. if (instantiation_warn_notify) {
  393. instantiation_warn_notify(vformat(
  394. TTR("An incoming node's name clashes with %s already in the scene (presumably, from a more nested instance).\nThe less nested node will be renamed. Please fix and re-save the scene."),
  395. ret_nodes[0]->get_path_to(existing)));
  396. }
  397. node->set_name(snames[n.name]);
  398. parent->add_child(node, true);
  399. pending_add = false;
  400. }
  401. }
  402. #endif
  403. if (pending_add) {
  404. parent->_add_child_nocheck(node, snames[n.name]);
  405. }
  406. if (n.index >= 0 && n.index < parent->get_child_count() - 1) {
  407. parent->move_child(node, n.index);
  408. }
  409. } else {
  410. //it may be possible that an instantiated scene has changed
  411. //and the node has nowhere to go anymore
  412. stray_instances.push_back(node); //can't be added, go to stray list
  413. }
  414. } else {
  415. if (Engine::get_singleton()->is_editor_hint()) {
  416. //validate name if using editor, to avoid broken
  417. node->set_name(snames[n.name]);
  418. } else {
  419. node->_set_name_nocheck(snames[n.name]);
  420. }
  421. }
  422. }
  423. if (!old_parent_path.is_empty()) {
  424. node->set_name(old_parent_path + "#" + node->get_name());
  425. }
  426. if (n.owner >= 0) {
  427. NODE_FROM_ID(owner, n.owner);
  428. if (owner) {
  429. node->_set_owner_nocheck(owner);
  430. if (node->data.unique_name_in_owner) {
  431. node->_acquire_unique_name_in_owner();
  432. }
  433. }
  434. }
  435. // We only want to deal with pinned flag if instantiating as pure main (no instance, no inheriting.)
  436. if (p_edit_state == GEN_EDIT_STATE_MAIN) {
  437. _sanitize_node_pinned_properties(node);
  438. } else {
  439. node->remove_meta("_edit_pinned_properties_");
  440. }
  441. }
  442. if (missing_node) {
  443. missing_node->set_recording_properties(false);
  444. }
  445. ret_nodes[i] = node;
  446. if (node && gen_node_path_cache && ret_nodes[0]) {
  447. NodePath n2 = ret_nodes[0]->get_path_to(node);
  448. node_path_cache[n2] = i;
  449. }
  450. }
  451. for (const DeferredNodePathProperties &dnp : deferred_node_paths) {
  452. // Replace properties stored as NodePaths with actual Nodes.
  453. Node *base = ObjectDB::get_instance<Node>(dnp.base);
  454. ERR_CONTINUE_EDMSG(!base, vformat("Failed to set deferred property '%s' as the base node disappeared.", dnp.property));
  455. if (dnp.value.get_type() == Variant::ARRAY) {
  456. Array paths = dnp.value;
  457. bool valid;
  458. Array array = base->get(dnp.property, &valid);
  459. ERR_CONTINUE_EDMSG(!valid, vformat("Failed to get property '%s' from node '%s'.", dnp.property, base->get_name()));
  460. array = array.duplicate();
  461. array.resize(paths.size());
  462. for (int i = 0; i < array.size(); i++) {
  463. array.set(i, base->get_node_or_null(paths[i]));
  464. }
  465. base->set(dnp.property, array);
  466. } else if (dnp.value.get_type() == Variant::DICTIONARY) {
  467. Dictionary paths = dnp.value;
  468. bool valid;
  469. Dictionary dict = base->get(dnp.property, &valid);
  470. ERR_CONTINUE_EDMSG(!valid, vformat("Failed to get property '%s' from node '%s'.", dnp.property, base->get_name()));
  471. dict = dict.duplicate();
  472. bool convert_key = dict.get_typed_key_builtin() == Variant::OBJECT &&
  473. ClassDB::is_parent_class(dict.get_typed_key_class_name(), "Node");
  474. bool convert_value = dict.get_typed_value_builtin() == Variant::OBJECT &&
  475. ClassDB::is_parent_class(dict.get_typed_value_class_name(), "Node");
  476. for (const KeyValue<Variant, Variant> &kv : paths) {
  477. Variant key = kv.key;
  478. if (convert_key) {
  479. key = base->get_node_or_null(key);
  480. }
  481. Variant value = kv.value;
  482. if (convert_value) {
  483. value = base->get_node_or_null(value);
  484. }
  485. dict[key] = value;
  486. }
  487. base->set(dnp.property, dict);
  488. } else {
  489. base->set(dnp.property, base->get_node_or_null(dnp.value));
  490. }
  491. }
  492. for (KeyValue<Ref<Resource>, Ref<Resource>> &E : resources_local_to_scene) {
  493. if (E.value->get_local_scene() == ret_nodes[0]) {
  494. E.value->setup_local_to_scene();
  495. }
  496. }
  497. //do connections
  498. int cc = connections.size();
  499. const ConnectionData *cdata = connections.ptr();
  500. for (int i = 0; i < cc; i++) {
  501. const ConnectionData &c = cdata[i];
  502. //ERR_FAIL_INDEX_V( c.from, nc, nullptr );
  503. //ERR_FAIL_INDEX_V( c.to, nc, nullptr );
  504. NODE_FROM_ID(cfrom, c.from);
  505. NODE_FROM_ID(cto, c.to);
  506. if (!cfrom || !cto) {
  507. continue;
  508. }
  509. Callable callable(cto, snames[c.method]);
  510. if (c.unbinds > 0) {
  511. callable = callable.unbind(c.unbinds);
  512. } else {
  513. Array binds;
  514. if (c.flags & CONNECT_APPEND_SOURCE_OBJECT) {
  515. binds.push_back(cfrom);
  516. }
  517. if (!c.binds.is_empty()) {
  518. for (int j = 0; j < c.binds.size(); j++) {
  519. binds.push_back(props[c.binds[j]]);
  520. }
  521. }
  522. if (!binds.is_empty()) {
  523. callable = callable.bindv(binds);
  524. }
  525. }
  526. cfrom->connect(snames[c.signal], callable, CONNECT_PERSIST | c.flags | (p_edit_state == GEN_EDIT_STATE_MAIN ? 0 : CONNECT_INHERITED));
  527. }
  528. //Node *s = ret_nodes[0];
  529. //remove nodes that could not be added, likely as a result that
  530. while (stray_instances.size()) {
  531. memdelete(stray_instances.front()->get());
  532. stray_instances.pop_front();
  533. }
  534. for (int i = 0; i < editable_instances.size(); i++) {
  535. Node *ei = ret_nodes[0]->get_node_or_null(editable_instances[i]);
  536. if (ei) {
  537. ret_nodes[0]->set_editable_instance(ei, true);
  538. }
  539. }
  540. return ret_nodes[0];
  541. }
  542. Variant SceneState::make_local_resource(Variant &p_value, const SceneState::NodeData &p_node_data, HashMap<Ref<Resource>, Ref<Resource>> &p_resources_local_to_sub_scene, Node *p_node, const StringName p_sname, HashMap<Ref<Resource>, Ref<Resource>> &p_resources_local_to_scene, int p_i, Node **p_ret_nodes, SceneState::GenEditState p_edit_state) const {
  543. Ref<Resource> res = p_value;
  544. if (res.is_null() || !res->is_local_to_scene()) {
  545. return p_value;
  546. }
  547. if (p_node_data.instance >= 0) { // For the root node of a sub-scene, treat it as part of the sub-scene.
  548. return get_remap_resource(res, p_resources_local_to_sub_scene, p_node->get(p_sname), p_node);
  549. } else {
  550. HashMap<Ref<Resource>, Ref<Resource>>::Iterator E = p_resources_local_to_scene.find(res);
  551. Node *base = p_i == 0 ? p_node : p_ret_nodes[0];
  552. if (E) {
  553. return E->value;
  554. } else if (p_edit_state == GEN_EDIT_STATE_MAIN) { // For the main scene, use the resource as is
  555. res->configure_for_local_scene(base, p_resources_local_to_scene);
  556. p_resources_local_to_scene[res] = res;
  557. return res;
  558. } else { // For instances, a copy must be made.
  559. Ref<Resource> local_dupe = res->duplicate_for_local_scene(base, p_resources_local_to_scene);
  560. p_resources_local_to_scene[res] = local_dupe;
  561. return local_dupe;
  562. }
  563. }
  564. }
  565. Array SceneState::setup_resources_in_array(Array &p_array_to_scan, const SceneState::NodeData &p_n, HashMap<Ref<Resource>, Ref<Resource>> &p_resources_local_to_sub_scene, Node *p_node, const StringName p_sname, HashMap<Ref<Resource>, Ref<Resource>> &p_resources_local_to_scene, int p_i, Node **p_ret_nodes, SceneState::GenEditState p_edit_state) const {
  566. for (int i = 0; i < p_array_to_scan.size(); i++) {
  567. if (p_array_to_scan[i].get_type() == Variant::OBJECT) {
  568. p_array_to_scan[i] = make_local_resource(p_array_to_scan[i], p_n, p_resources_local_to_sub_scene, p_node, p_sname, p_resources_local_to_scene, p_i, p_ret_nodes, p_edit_state);
  569. }
  570. }
  571. return p_array_to_scan;
  572. }
  573. Dictionary SceneState::setup_resources_in_dictionary(Dictionary &p_dictionary_to_scan, const SceneState::NodeData &p_n, HashMap<Ref<Resource>, Ref<Resource>> &p_resources_local_to_sub_scene, Node *p_node, const StringName p_sname, HashMap<Ref<Resource>, Ref<Resource>> &p_resources_local_to_scene, int p_i, Node **p_ret_nodes, SceneState::GenEditState p_edit_state) const {
  574. const Array keys = p_dictionary_to_scan.keys();
  575. const Array values = p_dictionary_to_scan.values();
  576. if (has_local_resource(values) || has_local_resource(keys)) {
  577. Array duplicated_keys = keys.duplicate(true);
  578. Array duplicated_values = values.duplicate(true);
  579. duplicated_keys = setup_resources_in_array(duplicated_keys, p_n, p_resources_local_to_sub_scene, p_node, p_sname, p_resources_local_to_scene, p_i, p_ret_nodes, p_edit_state);
  580. duplicated_values = setup_resources_in_array(duplicated_values, p_n, p_resources_local_to_sub_scene, p_node, p_sname, p_resources_local_to_scene, p_i, p_ret_nodes, p_edit_state);
  581. p_dictionary_to_scan.clear();
  582. for (int i = 0; i < keys.size(); i++) {
  583. p_dictionary_to_scan[duplicated_keys[i]] = duplicated_values[i];
  584. }
  585. }
  586. return p_dictionary_to_scan;
  587. }
  588. bool SceneState::has_local_resource(const Array &p_array) const {
  589. for (int i = 0; i < p_array.size(); i++) {
  590. Ref<Resource> res = p_array[i];
  591. if (res.is_valid() && res->is_local_to_scene()) {
  592. return true;
  593. }
  594. }
  595. return false;
  596. }
  597. static int _nm_get_string(const String &p_string, HashMap<StringName, int> &name_map) {
  598. if (name_map.has(p_string)) {
  599. return name_map[p_string];
  600. }
  601. int idx = name_map.size();
  602. name_map[p_string] = idx;
  603. return idx;
  604. }
  605. static int _vm_get_variant(const Variant &p_variant, HashMap<Variant, int, VariantHasher, VariantComparator> &variant_map) {
  606. if (variant_map.has(p_variant)) {
  607. return variant_map[p_variant];
  608. }
  609. int idx = variant_map.size();
  610. variant_map[p_variant] = idx;
  611. return idx;
  612. }
  613. Error SceneState::_parse_node(Node *p_owner, Node *p_node, int p_parent_idx, HashMap<StringName, int> &name_map, HashMap<Variant, int, VariantHasher, VariantComparator> &variant_map, HashMap<Node *, int> &node_map, HashMap<Node *, int> &nodepath_map) {
  614. // this function handles all the work related to properly packing scenes, be it
  615. // instantiated or inherited.
  616. // given the complexity of this process, an attempt will be made to properly
  617. // document it. if you fail to understand something, please ask!
  618. //discard nodes that do not belong to be processed
  619. if (p_node != p_owner && p_node->get_owner() != p_owner && !p_owner->is_editable_instance(p_node->get_owner())) {
  620. return OK;
  621. }
  622. bool is_editable_instance = false;
  623. // save the child instantiated scenes that are chosen as editable, so they can be restored
  624. // upon load back
  625. if (p_node != p_owner && !p_node->get_scene_file_path().is_empty() && p_owner->is_editable_instance(p_node)) {
  626. editable_instances.push_back(p_owner->get_path_to(p_node));
  627. // Node is the root of an editable instance.
  628. is_editable_instance = true;
  629. } else if (p_node->get_owner() && p_owner->is_ancestor_of(p_node->get_owner()) && p_owner->is_editable_instance(p_node->get_owner())) {
  630. // Node is part of an editable instance.
  631. is_editable_instance = true;
  632. }
  633. NodeData nd;
  634. nd.name = _nm_get_string(p_node->get_name(), name_map);
  635. nd.instance = -1; //not instantiated by default
  636. //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
  637. 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)))) {
  638. //do not save index, because it belongs to saved scene and scene is not inherited
  639. nd.index = -1;
  640. } else if (p_node == p_owner) {
  641. //This (hopefully) happens if the node is a scene root, so its index is irrelevant.
  642. nd.index = -1;
  643. } else {
  644. //part of an inherited scene, or parent is from an instantiated scene
  645. nd.index = p_node->get_index();
  646. }
  647. // if this node is part of an instantiated scene or sub-instantiated scene
  648. // we need to get the corresponding instance states.
  649. // with the instance states, we can query for identical properties/groups
  650. // and only save what has changed
  651. bool instantiated_by_owner = false;
  652. Vector<SceneState::PackState> states_stack = PropertyUtils::get_node_states_stack(p_node, p_owner, &instantiated_by_owner);
  653. if (!p_node->get_scene_file_path().is_empty() && p_node->get_owner() == p_owner && instantiated_by_owner) {
  654. if (p_node->get_scene_instance_load_placeholder()) {
  655. //it's a placeholder, use the placeholder path
  656. nd.instance = _vm_get_variant(p_node->get_scene_file_path(), variant_map);
  657. nd.instance |= FLAG_INSTANCE_IS_PLACEHOLDER;
  658. } else {
  659. //must instance ourselves
  660. Ref<PackedScene> instance = ResourceLoader::load(p_node->get_scene_file_path());
  661. if (instance.is_null()) {
  662. return ERR_CANT_OPEN;
  663. }
  664. nd.instance = _vm_get_variant(instance, variant_map);
  665. }
  666. }
  667. // all setup, we then proceed to check all properties for the node
  668. // and save the ones that are worth saving
  669. List<PropertyInfo> plist;
  670. p_node->get_property_list(&plist);
  671. Array pinned_props = _sanitize_node_pinned_properties(p_node);
  672. Dictionary missing_resource_properties = p_node->get_meta(META_MISSING_RESOURCES, Dictionary());
  673. for (const PropertyInfo &E : plist) {
  674. if (!(E.usage & PROPERTY_USAGE_STORAGE) && !missing_resource_properties.has(E.name)) {
  675. continue;
  676. }
  677. if (E.name == META_PROPERTY_MISSING_RESOURCES) {
  678. continue; // Ignore this property when packing.
  679. }
  680. // If instance or inheriting, not saving if property requested so.
  681. if (!states_stack.is_empty()) {
  682. if ((E.usage & PROPERTY_USAGE_NO_INSTANCE_STATE)) {
  683. continue;
  684. }
  685. }
  686. StringName name = E.name;
  687. Variant value = p_node->get(name);
  688. bool use_deferred_node_path_bit = false;
  689. if (E.type == Variant::OBJECT && E.hint == PROPERTY_HINT_NODE_TYPE) {
  690. if (value.get_type() == Variant::OBJECT) {
  691. if (Node *n = Object::cast_to<Node>(value)) {
  692. value = p_node->get_path_to(n);
  693. }
  694. use_deferred_node_path_bit = true;
  695. }
  696. if (value.get_type() != Variant::NODE_PATH) {
  697. continue; //was never set, ignore.
  698. }
  699. } else if (E.type == Variant::OBJECT && missing_resource_properties.has(E.name)) {
  700. // Was this missing resource overridden? If so do not save the old value.
  701. Ref<Resource> ures = value;
  702. if (ures.is_null()) {
  703. value = missing_resource_properties[E.name];
  704. }
  705. } else if (E.type == Variant::ARRAY && E.hint == PROPERTY_HINT_TYPE_STRING) {
  706. int hint_subtype_separator = E.hint_string.find_char(':');
  707. if (hint_subtype_separator >= 0) {
  708. String subtype_string = E.hint_string.substr(0, hint_subtype_separator);
  709. int slash_pos = subtype_string.find_char('/');
  710. PropertyHint subtype_hint = PropertyHint::PROPERTY_HINT_NONE;
  711. if (slash_pos >= 0) {
  712. subtype_hint = PropertyHint(subtype_string.get_slicec('/', 1).to_int());
  713. subtype_string = subtype_string.substr(0, slash_pos);
  714. }
  715. Variant::Type subtype = Variant::Type(subtype_string.to_int());
  716. if (subtype == Variant::OBJECT && subtype_hint == PROPERTY_HINT_NODE_TYPE) {
  717. use_deferred_node_path_bit = true;
  718. Array array = value;
  719. Array new_array;
  720. for (int i = 0; i < array.size(); i++) {
  721. Variant elem = array[i];
  722. if (elem.get_type() == Variant::OBJECT) {
  723. if (Node *n = Object::cast_to<Node>(elem)) {
  724. new_array.push_back(p_node->get_path_to(n));
  725. continue;
  726. }
  727. }
  728. new_array.push_back(elem);
  729. }
  730. value = new_array;
  731. }
  732. }
  733. } else if (E.type == Variant::DICTIONARY && E.hint == PROPERTY_HINT_TYPE_STRING) {
  734. int key_value_separator = E.hint_string.find_char(';');
  735. if (key_value_separator >= 0) {
  736. int key_subtype_separator = E.hint_string.find_char(':');
  737. String key_subtype_string = E.hint_string.substr(0, key_subtype_separator);
  738. int key_slash_pos = key_subtype_string.find_char('/');
  739. PropertyHint key_subtype_hint = PropertyHint::PROPERTY_HINT_NONE;
  740. if (key_slash_pos >= 0) {
  741. key_subtype_hint = PropertyHint(key_subtype_string.get_slicec('/', 1).to_int());
  742. key_subtype_string = key_subtype_string.substr(0, key_slash_pos);
  743. }
  744. Variant::Type key_subtype = Variant::Type(key_subtype_string.to_int());
  745. bool convert_key = key_subtype == Variant::OBJECT && key_subtype_hint == PROPERTY_HINT_NODE_TYPE;
  746. int value_subtype_separator = E.hint_string.find_char(':', key_value_separator) - (key_value_separator + 1);
  747. String value_subtype_string = E.hint_string.substr(key_value_separator + 1, value_subtype_separator);
  748. int value_slash_pos = value_subtype_string.find_char('/');
  749. PropertyHint value_subtype_hint = PropertyHint::PROPERTY_HINT_NONE;
  750. if (value_slash_pos >= 0) {
  751. value_subtype_hint = PropertyHint(value_subtype_string.get_slicec('/', 1).to_int());
  752. value_subtype_string = value_subtype_string.substr(0, value_slash_pos);
  753. }
  754. Variant::Type value_subtype = Variant::Type(value_subtype_string.to_int());
  755. bool convert_value = value_subtype == Variant::OBJECT && value_subtype_hint == PROPERTY_HINT_NODE_TYPE;
  756. if (convert_key || convert_value) {
  757. use_deferred_node_path_bit = true;
  758. Dictionary dict = value;
  759. Dictionary new_dict;
  760. for (const KeyValue<Variant, Variant> &kv : dict) {
  761. Variant new_key = kv.key;
  762. if (convert_key && new_key.get_type() == Variant::OBJECT) {
  763. if (Node *n = Object::cast_to<Node>(new_key)) {
  764. new_key = p_node->get_path_to(n);
  765. }
  766. }
  767. Variant new_value = kv.value;
  768. if (convert_value && new_value.get_type() == Variant::OBJECT) {
  769. if (Node *n = Object::cast_to<Node>(new_value)) {
  770. new_value = p_node->get_path_to(n);
  771. }
  772. }
  773. new_dict[new_key] = new_value;
  774. }
  775. value = new_dict;
  776. }
  777. }
  778. }
  779. if (!pinned_props.has(name)) {
  780. bool is_valid_default = false;
  781. Variant default_value = PropertyUtils::get_property_default_value(p_node, name, &is_valid_default, &states_stack, true);
  782. if (is_valid_default && !PropertyUtils::is_property_value_different(p_node, value, default_value)) {
  783. if (value.get_type() == Variant::ARRAY && has_local_resource(value)) {
  784. // Save anyway
  785. } else if (value.get_type() == Variant::DICTIONARY) {
  786. Dictionary dictionary = value;
  787. if (!has_local_resource(dictionary.values()) && !has_local_resource(dictionary.keys())) {
  788. continue;
  789. }
  790. } else {
  791. continue;
  792. }
  793. }
  794. }
  795. NodeData::Property prop;
  796. prop.name = _nm_get_string(name, name_map);
  797. prop.value = _vm_get_variant(value, variant_map);
  798. if (use_deferred_node_path_bit) {
  799. prop.name |= FLAG_PATH_PROPERTY_IS_NODE;
  800. }
  801. nd.properties.push_back(prop);
  802. }
  803. // save the groups this node is into
  804. // discard groups that come from the original scene
  805. List<Node::GroupInfo> groups;
  806. p_node->get_groups(&groups);
  807. for (const Node::GroupInfo &gi : groups) {
  808. if (!gi.persistent) {
  809. continue;
  810. }
  811. bool skip = false;
  812. for (const SceneState::PackState &ia : states_stack) {
  813. //check all levels of pack to see if the group was added somewhere
  814. if (ia.state->is_node_in_group(ia.node, gi.name)) {
  815. skip = true;
  816. break;
  817. }
  818. }
  819. if (skip) {
  820. continue;
  821. }
  822. nd.groups.push_back(_nm_get_string(gi.name, name_map));
  823. }
  824. // save the right owner
  825. // for the saved scene root this is -1
  826. // for nodes of the saved scene this is 0
  827. // for nodes of instantiated scenes this is >0
  828. if (p_node == p_owner) {
  829. //saved scene root
  830. nd.owner = -1;
  831. } else if (p_node->get_owner() == p_owner) {
  832. //part of saved scene
  833. nd.owner = 0;
  834. } else {
  835. nd.owner = -1;
  836. }
  837. MissingNode *missing_node = Object::cast_to<MissingNode>(p_node);
  838. // Save the right type. If this node was created by an instance
  839. // then flag that the node should not be created but reused
  840. if (states_stack.is_empty() && !is_editable_instance) {
  841. //This node is not part of an instantiation process, so save the type.
  842. if (missing_node != nullptr) {
  843. // It's a missing node (type non existent on load).
  844. nd.type = _nm_get_string(missing_node->get_original_class(), name_map);
  845. } else {
  846. nd.type = _nm_get_string(p_node->get_class(), name_map);
  847. }
  848. } else {
  849. // this node is part of an instantiated process, so do not save the type.
  850. // instead, save that it was instantiated
  851. nd.type = TYPE_INSTANTIATED;
  852. }
  853. // determine whether to save this node or not
  854. // if this node is part of an instantiated sub-scene, we can skip storing it if basically
  855. // no properties changed and no groups were added to it.
  856. // below condition is true for all nodes of the scene being saved, and ones in subscenes
  857. // that hold changes
  858. bool save_node = nd.properties.size() || nd.groups.size(); // some local properties or groups exist
  859. save_node = save_node || p_node == p_owner; // owner is always saved
  860. save_node = save_node || (p_node->get_owner() == p_owner && instantiated_by_owner); //part of scene and not instanced
  861. int idx = nodes.size();
  862. int parent_node = NO_PARENT_SAVED;
  863. if (save_node) {
  864. //don't save the node if nothing and subscene
  865. node_map[p_node] = idx;
  866. //ok validate parent node
  867. if (p_parent_idx == NO_PARENT_SAVED) {
  868. int sidx;
  869. if (nodepath_map.has(p_node->get_parent())) {
  870. sidx = nodepath_map[p_node->get_parent()];
  871. } else {
  872. sidx = nodepath_map.size();
  873. nodepath_map[p_node->get_parent()] = sidx;
  874. }
  875. nd.parent = FLAG_ID_IS_PATH | sidx;
  876. } else {
  877. nd.parent = p_parent_idx;
  878. }
  879. parent_node = idx;
  880. nodes.push_back(nd);
  881. }
  882. for (int i = 0; i < p_node->get_child_count(); i++) {
  883. Node *c = p_node->get_child(i);
  884. Error err = _parse_node(p_owner, c, parent_node, name_map, variant_map, node_map, nodepath_map);
  885. if (err) {
  886. return err;
  887. }
  888. }
  889. return OK;
  890. }
  891. Error SceneState::_parse_connections(Node *p_owner, Node *p_node, HashMap<StringName, int> &name_map, HashMap<Variant, int, VariantHasher, VariantComparator> &variant_map, HashMap<Node *, int> &node_map, HashMap<Node *, int> &nodepath_map) {
  892. // Ignore nodes that are within a scene instance.
  893. if (p_node != p_owner && p_node->get_owner() && p_node->get_owner() != p_owner && !p_owner->is_editable_instance(p_node->get_owner())) {
  894. return OK;
  895. }
  896. List<MethodInfo> _signals;
  897. p_node->get_signal_list(&_signals);
  898. _signals.sort();
  899. //ERR_FAIL_COND_V( !node_map.has(p_node), ERR_BUG);
  900. //NodeData &nd = nodes[node_map[p_node]];
  901. for (const MethodInfo &E : _signals) {
  902. List<Node::Connection> conns;
  903. p_node->get_signal_connection_list(E.name, &conns);
  904. conns.sort();
  905. for (const Node::Connection &F : conns) {
  906. const Node::Connection &c = F;
  907. // Don't save connections that are not persistent.
  908. if (!(c.flags & CONNECT_PERSIST)) {
  909. continue;
  910. }
  911. // only connections that originate or end into main saved scene are saved
  912. // everything else is discarded
  913. Node *target = Object::cast_to<Node>(c.callable.get_object());
  914. if (!target) {
  915. continue;
  916. }
  917. Vector<Variant> binds;
  918. int unbinds = 0;
  919. Callable base_callable;
  920. if (c.callable.is_custom()) {
  921. CallableCustomBind *ccb = dynamic_cast<CallableCustomBind *>(c.callable.get_custom());
  922. if (ccb) {
  923. binds = ccb->get_binds();
  924. // The source object may already be bound, ignore it to avoid saving the source object.
  925. if ((c.flags & CONNECT_APPEND_SOURCE_OBJECT) && (p_node == binds[0])) {
  926. binds.remove_at(0);
  927. }
  928. base_callable = ccb->get_callable();
  929. }
  930. CallableCustomUnbind *ccu = dynamic_cast<CallableCustomUnbind *>(c.callable.get_custom());
  931. if (ccu) {
  932. unbinds = ccu->get_unbinds();
  933. base_callable = ccu->get_callable();
  934. }
  935. } else {
  936. base_callable = c.callable;
  937. }
  938. //find if this connection already exists
  939. Node *common_parent = target->find_common_parent_with(p_node);
  940. ERR_CONTINUE(!common_parent);
  941. if (common_parent != p_owner && common_parent->get_scene_file_path().is_empty()) {
  942. common_parent = common_parent->get_owner();
  943. }
  944. bool exists = false;
  945. //go through ownership chain to see if this exists
  946. while (common_parent) {
  947. Ref<SceneState> ps;
  948. if (common_parent == p_owner) {
  949. ps = common_parent->get_scene_inherited_state();
  950. } else {
  951. ps = common_parent->get_scene_instance_state();
  952. }
  953. if (ps.is_valid()) {
  954. NodePath signal_from = common_parent->get_path_to(p_node);
  955. NodePath signal_to = common_parent->get_path_to(target);
  956. if (ps->has_connection(signal_from, c.signal.get_name(), signal_to, base_callable.get_method())) {
  957. exists = true;
  958. break;
  959. }
  960. }
  961. if (common_parent == p_owner) {
  962. break;
  963. } else {
  964. common_parent = common_parent->get_owner();
  965. }
  966. }
  967. if (exists) { //already exists (comes from instance or inheritance), so don't save
  968. continue;
  969. }
  970. {
  971. Node *nl = p_node;
  972. bool exists2 = false;
  973. while (nl) {
  974. if (nl == p_owner) {
  975. Ref<SceneState> state = nl->get_scene_inherited_state();
  976. if (state.is_valid()) {
  977. int from_node = state->find_node_by_path(nl->get_path_to(p_node));
  978. int to_node = state->find_node_by_path(nl->get_path_to(target));
  979. if (from_node >= 0 && to_node >= 0) {
  980. //this one has state for this node, save
  981. if (state->is_connection(from_node, c.signal.get_name(), to_node, base_callable.get_method())) {
  982. exists2 = true;
  983. break;
  984. }
  985. }
  986. }
  987. nl = nullptr;
  988. } else {
  989. if (!nl->get_scene_file_path().is_empty()) {
  990. //is an instance
  991. Ref<SceneState> state = nl->get_scene_instance_state();
  992. if (state.is_valid()) {
  993. int from_node = state->find_node_by_path(nl->get_path_to(p_node));
  994. int to_node = state->find_node_by_path(nl->get_path_to(target));
  995. if (from_node >= 0 && to_node >= 0) {
  996. //this one has state for this node, save
  997. if (state->is_connection(from_node, c.signal.get_name(), to_node, base_callable.get_method())) {
  998. exists2 = true;
  999. break;
  1000. }
  1001. }
  1002. }
  1003. }
  1004. nl = nl->get_owner();
  1005. }
  1006. }
  1007. if (exists2) {
  1008. continue;
  1009. }
  1010. }
  1011. int src_id;
  1012. if (node_map.has(p_node)) {
  1013. src_id = node_map[p_node];
  1014. } else {
  1015. if (nodepath_map.has(p_node)) {
  1016. src_id = FLAG_ID_IS_PATH | nodepath_map[p_node];
  1017. } else {
  1018. int sidx = nodepath_map.size();
  1019. nodepath_map[p_node] = sidx;
  1020. src_id = FLAG_ID_IS_PATH | sidx;
  1021. }
  1022. }
  1023. int target_id;
  1024. if (node_map.has(target)) {
  1025. target_id = node_map[target];
  1026. } else {
  1027. if (nodepath_map.has(target)) {
  1028. target_id = FLAG_ID_IS_PATH | nodepath_map[target];
  1029. } else {
  1030. int sidx = nodepath_map.size();
  1031. nodepath_map[target] = sidx;
  1032. target_id = FLAG_ID_IS_PATH | sidx;
  1033. }
  1034. }
  1035. ConnectionData cd;
  1036. cd.from = src_id;
  1037. cd.to = target_id;
  1038. cd.method = _nm_get_string(base_callable.get_method(), name_map);
  1039. cd.signal = _nm_get_string(c.signal.get_name(), name_map);
  1040. cd.flags = c.flags & ~CONNECT_INHERITED; // Do not store inherited.
  1041. cd.unbinds = unbinds;
  1042. for (int i = 0; i < binds.size(); i++) {
  1043. cd.binds.push_back(_vm_get_variant(binds[i], variant_map));
  1044. }
  1045. connections.push_back(cd);
  1046. }
  1047. }
  1048. // Recursively parse child connections.
  1049. for (int i = 0; i < p_node->get_child_count(); i++) {
  1050. Node *child = p_node->get_child(i);
  1051. Error err = _parse_connections(p_owner, child, name_map, variant_map, node_map, nodepath_map);
  1052. if (err) {
  1053. return err;
  1054. }
  1055. }
  1056. return OK;
  1057. }
  1058. Error SceneState::pack(Node *p_scene) {
  1059. ERR_FAIL_NULL_V(p_scene, ERR_INVALID_PARAMETER);
  1060. clear();
  1061. Node *scene = p_scene;
  1062. HashMap<StringName, int> name_map;
  1063. HashMap<Variant, int, VariantHasher, VariantComparator> variant_map;
  1064. HashMap<Node *, int> node_map;
  1065. HashMap<Node *, int> nodepath_map;
  1066. // If using scene inheritance, pack the scene it inherits from.
  1067. if (scene->get_scene_inherited_state().is_valid()) {
  1068. String scene_path = scene->get_scene_inherited_state()->get_path();
  1069. Ref<PackedScene> instance = ResourceLoader::load(scene_path);
  1070. if (instance.is_valid()) {
  1071. base_scene_idx = _vm_get_variant(instance, variant_map);
  1072. }
  1073. }
  1074. // Instanced, only direct sub-scenes are supported of course.
  1075. Error err = _parse_node(scene, scene, -1, name_map, variant_map, node_map, nodepath_map);
  1076. if (err) {
  1077. clear();
  1078. ERR_FAIL_V(err);
  1079. }
  1080. err = _parse_connections(scene, scene, name_map, variant_map, node_map, nodepath_map);
  1081. if (err) {
  1082. clear();
  1083. ERR_FAIL_V(err);
  1084. }
  1085. names.resize(name_map.size());
  1086. for (const KeyValue<StringName, int> &E : name_map) {
  1087. names.write[E.value] = E.key;
  1088. }
  1089. variants.resize(variant_map.size());
  1090. for (const KeyValue<Variant, int> &E : variant_map) {
  1091. int idx = E.value;
  1092. variants.write[idx] = E.key;
  1093. }
  1094. node_paths.resize(nodepath_map.size());
  1095. for (const KeyValue<Node *, int> &E : nodepath_map) {
  1096. node_paths.write[E.value] = scene->get_path_to(E.key);
  1097. }
  1098. if (Engine::get_singleton()->is_editor_hint()) {
  1099. // Build node path cache
  1100. for (const KeyValue<Node *, int> &E : node_map) {
  1101. node_path_cache[scene->get_path_to(E.key)] = E.value;
  1102. }
  1103. }
  1104. return OK;
  1105. }
  1106. void SceneState::set_path(const String &p_path) {
  1107. path = p_path;
  1108. }
  1109. String SceneState::get_path() const {
  1110. return path;
  1111. }
  1112. void SceneState::clear() {
  1113. names.clear();
  1114. variants.clear();
  1115. nodes.clear();
  1116. connections.clear();
  1117. node_path_cache.clear();
  1118. node_paths.clear();
  1119. editable_instances.clear();
  1120. base_scene_idx = -1;
  1121. }
  1122. Error SceneState::copy_from(const Ref<SceneState> &p_scene_state) {
  1123. ERR_FAIL_COND_V(p_scene_state.is_null(), ERR_INVALID_PARAMETER);
  1124. clear();
  1125. for (const StringName &E : p_scene_state->names) {
  1126. names.append(E);
  1127. }
  1128. for (const Variant &E : p_scene_state->variants) {
  1129. variants.append(E);
  1130. }
  1131. for (const SceneState::NodeData &E : p_scene_state->nodes) {
  1132. nodes.append(E);
  1133. }
  1134. for (const SceneState::ConnectionData &E : p_scene_state->connections) {
  1135. connections.append(E);
  1136. }
  1137. for (KeyValue<NodePath, int> &E : p_scene_state->node_path_cache) {
  1138. node_path_cache.insert(E.key, E.value);
  1139. }
  1140. for (const NodePath &E : p_scene_state->node_paths) {
  1141. node_paths.append(E);
  1142. }
  1143. for (const NodePath &E : p_scene_state->editable_instances) {
  1144. editable_instances.append(E);
  1145. }
  1146. base_scene_idx = p_scene_state->base_scene_idx;
  1147. return OK;
  1148. }
  1149. Ref<SceneState> SceneState::get_base_scene_state() const {
  1150. if (base_scene_idx >= 0) {
  1151. Ref<PackedScene> ps = variants[base_scene_idx];
  1152. if (ps.is_valid()) {
  1153. return ps->get_state();
  1154. }
  1155. }
  1156. return Ref<SceneState>();
  1157. }
  1158. int SceneState::find_node_by_path(const NodePath &p_node) const {
  1159. ERR_FAIL_COND_V_MSG(node_path_cache.is_empty(), -1, "This operation requires the node cache to have been built.");
  1160. if (!node_path_cache.has(p_node)) {
  1161. if (get_base_scene_state().is_valid()) {
  1162. int idx = get_base_scene_state()->find_node_by_path(p_node);
  1163. if (idx != -1) {
  1164. int rkey = _find_base_scene_node_remap_key(idx);
  1165. if (rkey == -1) {
  1166. rkey = nodes.size() + base_scene_node_remap.size();
  1167. base_scene_node_remap[rkey] = idx;
  1168. }
  1169. return rkey;
  1170. }
  1171. }
  1172. return -1;
  1173. }
  1174. int nid = node_path_cache[p_node];
  1175. if (get_base_scene_state().is_valid() && !base_scene_node_remap.has(nid)) {
  1176. //for nodes that _do_ exist in current scene, still try to look for
  1177. //the node in the instantiated scene, as a property may be missing
  1178. //from the local one
  1179. int idx = get_base_scene_state()->find_node_by_path(p_node);
  1180. if (idx != -1) {
  1181. base_scene_node_remap[nid] = idx;
  1182. }
  1183. }
  1184. return nid;
  1185. }
  1186. int SceneState::_find_base_scene_node_remap_key(int p_idx) const {
  1187. for (const KeyValue<int, int> &E : base_scene_node_remap) {
  1188. if (E.value == p_idx) {
  1189. return E.key;
  1190. }
  1191. }
  1192. return -1;
  1193. }
  1194. Variant SceneState::get_property_value(int p_node, const StringName &p_property, bool &r_found, bool &r_node_deferred) const {
  1195. r_found = false;
  1196. r_node_deferred = false;
  1197. ERR_FAIL_COND_V(p_node < 0, Variant());
  1198. if (p_node < nodes.size()) {
  1199. // Find in built-in nodes.
  1200. int pc = nodes[p_node].properties.size();
  1201. const StringName *namep = names.ptr();
  1202. const NodeData::Property *p = nodes[p_node].properties.ptr();
  1203. for (int i = 0; i < pc; i++) {
  1204. if (p_property == namep[p[i].name & FLAG_PROP_NAME_MASK]) {
  1205. r_found = true;
  1206. r_node_deferred = p[i].name & FLAG_PATH_PROPERTY_IS_NODE;
  1207. return variants[p[i].value];
  1208. }
  1209. }
  1210. }
  1211. // Property not found, try on instance.
  1212. HashMap<int, int>::ConstIterator I = base_scene_node_remap.find(p_node);
  1213. if (I) {
  1214. return get_base_scene_state()->get_property_value(I->value, p_property, r_found, r_node_deferred);
  1215. }
  1216. return Variant();
  1217. }
  1218. bool SceneState::is_node_in_group(int p_node, const StringName &p_group) const {
  1219. ERR_FAIL_COND_V(p_node < 0, false);
  1220. if (p_node < nodes.size()) {
  1221. const StringName *namep = names.ptr();
  1222. for (int i = 0; i < nodes[p_node].groups.size(); i++) {
  1223. if (namep[nodes[p_node].groups[i]] == p_group) {
  1224. return true;
  1225. }
  1226. }
  1227. }
  1228. if (base_scene_node_remap.has(p_node)) {
  1229. return get_base_scene_state()->is_node_in_group(base_scene_node_remap[p_node], p_group);
  1230. }
  1231. return false;
  1232. }
  1233. bool SceneState::disable_placeholders = false;
  1234. void SceneState::set_disable_placeholders(bool p_disable) {
  1235. disable_placeholders = p_disable;
  1236. }
  1237. bool SceneState::is_connection(int p_node, const StringName &p_signal, int p_to_node, const StringName &p_to_method) const {
  1238. ERR_FAIL_COND_V(p_node < 0, false);
  1239. ERR_FAIL_COND_V(p_to_node < 0, false);
  1240. if (p_node < nodes.size() && p_to_node < nodes.size()) {
  1241. int signal_idx = -1;
  1242. int method_idx = -1;
  1243. for (int i = 0; i < names.size(); i++) {
  1244. if (names[i] == p_signal) {
  1245. signal_idx = i;
  1246. } else if (names[i] == p_to_method) {
  1247. method_idx = i;
  1248. }
  1249. }
  1250. if (signal_idx >= 0 && method_idx >= 0) {
  1251. //signal and method strings are stored..
  1252. for (int i = 0; i < connections.size(); i++) {
  1253. if (connections[i].from == p_node && connections[i].to == p_to_node && connections[i].signal == signal_idx && connections[i].method == method_idx) {
  1254. return true;
  1255. }
  1256. }
  1257. }
  1258. }
  1259. if (base_scene_node_remap.has(p_node) && base_scene_node_remap.has(p_to_node)) {
  1260. return get_base_scene_state()->is_connection(base_scene_node_remap[p_node], p_signal, base_scene_node_remap[p_to_node], p_to_method);
  1261. }
  1262. return false;
  1263. }
  1264. void SceneState::set_bundled_scene(const Dictionary &p_dictionary) {
  1265. ERR_FAIL_COND(!p_dictionary.has("names"));
  1266. ERR_FAIL_COND(!p_dictionary.has("variants"));
  1267. ERR_FAIL_COND(!p_dictionary.has("node_count"));
  1268. ERR_FAIL_COND(!p_dictionary.has("nodes"));
  1269. ERR_FAIL_COND(!p_dictionary.has("conn_count"));
  1270. ERR_FAIL_COND(!p_dictionary.has("conns"));
  1271. //ERR_FAIL_COND( !p_dictionary.has("path"));
  1272. int version = 1;
  1273. if (p_dictionary.has("version")) {
  1274. version = p_dictionary["version"];
  1275. }
  1276. ERR_FAIL_COND_MSG(version > PACKED_SCENE_VERSION, "Save format version too new.");
  1277. const int node_count = p_dictionary["node_count"];
  1278. const Vector<int> snodes = p_dictionary["nodes"];
  1279. ERR_FAIL_COND(snodes.size() < node_count);
  1280. const int conn_count = p_dictionary["conn_count"];
  1281. const Vector<int> sconns = p_dictionary["conns"];
  1282. ERR_FAIL_COND(sconns.size() < conn_count);
  1283. Vector<String> snames = p_dictionary["names"];
  1284. if (snames.size()) {
  1285. int namecount = snames.size();
  1286. names.resize(namecount);
  1287. const String *r = snames.ptr();
  1288. for (int i = 0; i < names.size(); i++) {
  1289. names.write[i] = r[i];
  1290. }
  1291. }
  1292. Array svariants = p_dictionary["variants"];
  1293. if (svariants.size()) {
  1294. int varcount = svariants.size();
  1295. variants.resize(varcount);
  1296. for (int i = 0; i < varcount; i++) {
  1297. variants.write[i] = svariants[i];
  1298. }
  1299. } else {
  1300. variants.clear();
  1301. }
  1302. nodes.resize(node_count);
  1303. if (node_count) {
  1304. const int *r = snodes.ptr();
  1305. int idx = 0;
  1306. for (int i = 0; i < node_count; i++) {
  1307. NodeData &nd = nodes.write[i];
  1308. nd.parent = r[idx++];
  1309. nd.owner = r[idx++];
  1310. nd.type = r[idx++];
  1311. uint32_t name_index = r[idx++];
  1312. nd.name = name_index & ((1 << NAME_INDEX_BITS) - 1);
  1313. nd.index = (name_index >> NAME_INDEX_BITS);
  1314. nd.index--; //0 is invalid, stored as 1
  1315. nd.instance = r[idx++];
  1316. nd.properties.resize(r[idx++]);
  1317. for (int j = 0; j < nd.properties.size(); j++) {
  1318. nd.properties.write[j].name = r[idx++];
  1319. nd.properties.write[j].value = r[idx++];
  1320. }
  1321. nd.groups.resize(r[idx++]);
  1322. for (int j = 0; j < nd.groups.size(); j++) {
  1323. nd.groups.write[j] = r[idx++];
  1324. }
  1325. }
  1326. }
  1327. connections.resize(conn_count);
  1328. if (conn_count) {
  1329. const int *r = sconns.ptr();
  1330. int idx = 0;
  1331. for (int i = 0; i < conn_count; i++) {
  1332. ConnectionData &cd = connections.write[i];
  1333. cd.from = r[idx++];
  1334. cd.to = r[idx++];
  1335. cd.signal = r[idx++];
  1336. cd.method = r[idx++];
  1337. cd.flags = r[idx++];
  1338. cd.binds.resize(r[idx++]);
  1339. for (int j = 0; j < cd.binds.size(); j++) {
  1340. cd.binds.write[j] = r[idx++];
  1341. }
  1342. if (version >= 3) {
  1343. cd.unbinds = r[idx++];
  1344. }
  1345. }
  1346. }
  1347. Array np;
  1348. if (p_dictionary.has("node_paths")) {
  1349. np = p_dictionary["node_paths"];
  1350. }
  1351. node_paths.resize(np.size());
  1352. for (int i = 0; i < np.size(); i++) {
  1353. node_paths.write[i] = np[i];
  1354. }
  1355. Array ei;
  1356. if (p_dictionary.has("editable_instances")) {
  1357. ei = p_dictionary["editable_instances"];
  1358. }
  1359. if (p_dictionary.has("base_scene")) {
  1360. base_scene_idx = p_dictionary["base_scene"];
  1361. }
  1362. editable_instances.resize(ei.size());
  1363. for (int i = 0; i < editable_instances.size(); i++) {
  1364. editable_instances.write[i] = ei[i];
  1365. }
  1366. //path=p_dictionary["path"];
  1367. }
  1368. Dictionary SceneState::get_bundled_scene() const {
  1369. Vector<String> rnames;
  1370. rnames.resize(names.size());
  1371. if (names.size()) {
  1372. String *r = rnames.ptrw();
  1373. for (int i = 0; i < names.size(); i++) {
  1374. r[i] = names[i];
  1375. }
  1376. }
  1377. Dictionary d;
  1378. d["names"] = rnames;
  1379. d["variants"] = variants;
  1380. Vector<int> rnodes;
  1381. d["node_count"] = nodes.size();
  1382. for (int i = 0; i < nodes.size(); i++) {
  1383. const NodeData &nd = nodes[i];
  1384. rnodes.push_back(nd.parent);
  1385. rnodes.push_back(nd.owner);
  1386. rnodes.push_back(nd.type);
  1387. uint32_t name_index = nd.name;
  1388. if (nd.index < (1 << (32 - NAME_INDEX_BITS)) - 1) { //save if less than 16k children
  1389. name_index |= uint32_t(nd.index + 1) << NAME_INDEX_BITS; //for backwards compatibility, index 0 is no index
  1390. }
  1391. rnodes.push_back(name_index);
  1392. rnodes.push_back(nd.instance);
  1393. rnodes.push_back(nd.properties.size());
  1394. for (int j = 0; j < nd.properties.size(); j++) {
  1395. rnodes.push_back(nd.properties[j].name);
  1396. rnodes.push_back(nd.properties[j].value);
  1397. }
  1398. rnodes.push_back(nd.groups.size());
  1399. for (int j = 0; j < nd.groups.size(); j++) {
  1400. rnodes.push_back(nd.groups[j]);
  1401. }
  1402. }
  1403. d["nodes"] = rnodes;
  1404. Vector<int> rconns;
  1405. d["conn_count"] = connections.size();
  1406. for (int i = 0; i < connections.size(); i++) {
  1407. const ConnectionData &cd = connections[i];
  1408. rconns.push_back(cd.from);
  1409. rconns.push_back(cd.to);
  1410. rconns.push_back(cd.signal);
  1411. rconns.push_back(cd.method);
  1412. rconns.push_back(cd.flags);
  1413. rconns.push_back(cd.binds.size());
  1414. for (int j = 0; j < cd.binds.size(); j++) {
  1415. rconns.push_back(cd.binds[j]);
  1416. }
  1417. rconns.push_back(cd.unbinds);
  1418. }
  1419. d["conns"] = rconns;
  1420. Array rnode_paths;
  1421. rnode_paths.resize(node_paths.size());
  1422. for (int i = 0; i < node_paths.size(); i++) {
  1423. rnode_paths[i] = node_paths[i];
  1424. }
  1425. d["node_paths"] = rnode_paths;
  1426. Array reditable_instances;
  1427. reditable_instances.resize(editable_instances.size());
  1428. for (int i = 0; i < editable_instances.size(); i++) {
  1429. reditable_instances[i] = editable_instances[i];
  1430. }
  1431. d["editable_instances"] = reditable_instances;
  1432. if (base_scene_idx >= 0) {
  1433. d["base_scene"] = base_scene_idx;
  1434. }
  1435. d["version"] = PACKED_SCENE_VERSION;
  1436. return d;
  1437. }
  1438. int SceneState::get_node_count() const {
  1439. return nodes.size();
  1440. }
  1441. StringName SceneState::get_node_type(int p_idx) const {
  1442. ERR_FAIL_INDEX_V(p_idx, nodes.size(), StringName());
  1443. if (nodes[p_idx].type == TYPE_INSTANTIATED) {
  1444. return StringName();
  1445. }
  1446. return names[nodes[p_idx].type];
  1447. }
  1448. StringName SceneState::get_node_name(int p_idx) const {
  1449. ERR_FAIL_INDEX_V(p_idx, nodes.size(), StringName());
  1450. return names[nodes[p_idx].name];
  1451. }
  1452. int SceneState::get_node_index(int p_idx) const {
  1453. ERR_FAIL_INDEX_V(p_idx, nodes.size(), -1);
  1454. return nodes[p_idx].index;
  1455. }
  1456. bool SceneState::is_node_instance_placeholder(int p_idx) const {
  1457. ERR_FAIL_INDEX_V(p_idx, nodes.size(), false);
  1458. return nodes[p_idx].instance >= 0 && (nodes[p_idx].instance & FLAG_INSTANCE_IS_PLACEHOLDER);
  1459. }
  1460. Ref<PackedScene> SceneState::get_node_instance(int p_idx) const {
  1461. ERR_FAIL_INDEX_V(p_idx, nodes.size(), Ref<PackedScene>());
  1462. if (nodes[p_idx].instance >= 0) {
  1463. if (nodes[p_idx].instance & FLAG_INSTANCE_IS_PLACEHOLDER) {
  1464. return Ref<PackedScene>();
  1465. } else {
  1466. return variants[nodes[p_idx].instance & FLAG_MASK];
  1467. }
  1468. } else if (nodes[p_idx].parent < 0 || nodes[p_idx].parent == NO_PARENT_SAVED) {
  1469. if (base_scene_idx >= 0) {
  1470. return variants[base_scene_idx];
  1471. }
  1472. }
  1473. return Ref<PackedScene>();
  1474. }
  1475. String SceneState::get_node_instance_placeholder(int p_idx) const {
  1476. ERR_FAIL_INDEX_V(p_idx, nodes.size(), String());
  1477. if (nodes[p_idx].instance >= 0 && (nodes[p_idx].instance & FLAG_INSTANCE_IS_PLACEHOLDER)) {
  1478. return variants[nodes[p_idx].instance & FLAG_MASK];
  1479. }
  1480. return String();
  1481. }
  1482. Vector<StringName> SceneState::get_node_groups(int p_idx) const {
  1483. ERR_FAIL_INDEX_V(p_idx, nodes.size(), Vector<StringName>());
  1484. Vector<StringName> groups;
  1485. for (int i = 0; i < nodes[p_idx].groups.size(); i++) {
  1486. groups.push_back(names[nodes[p_idx].groups[i]]);
  1487. }
  1488. return groups;
  1489. }
  1490. NodePath SceneState::get_node_path(int p_idx, bool p_for_parent) const {
  1491. ERR_FAIL_INDEX_V(p_idx, nodes.size(), NodePath());
  1492. if (nodes[p_idx].parent < 0 || nodes[p_idx].parent == NO_PARENT_SAVED) {
  1493. if (p_for_parent) {
  1494. return NodePath();
  1495. } else {
  1496. return NodePath(".");
  1497. }
  1498. }
  1499. Vector<StringName> sub_path;
  1500. NodePath base_path;
  1501. int nidx = p_idx;
  1502. while (true) {
  1503. if (nodes[nidx].parent == NO_PARENT_SAVED || nodes[nidx].parent < 0) {
  1504. sub_path.insert(0, ".");
  1505. break;
  1506. }
  1507. if (!p_for_parent || p_idx != nidx) {
  1508. sub_path.insert(0, names[nodes[nidx].name]);
  1509. }
  1510. if (nodes[nidx].parent & FLAG_ID_IS_PATH) {
  1511. base_path = node_paths[nodes[nidx].parent & FLAG_MASK];
  1512. break;
  1513. } else {
  1514. nidx = nodes[nidx].parent & FLAG_MASK;
  1515. }
  1516. }
  1517. for (int i = base_path.get_name_count() - 1; i >= 0; i--) {
  1518. sub_path.insert(0, base_path.get_name(i));
  1519. }
  1520. if (sub_path.is_empty()) {
  1521. return NodePath(".");
  1522. }
  1523. return NodePath(sub_path, false);
  1524. }
  1525. int SceneState::get_node_property_count(int p_idx) const {
  1526. ERR_FAIL_INDEX_V(p_idx, nodes.size(), -1);
  1527. return nodes[p_idx].properties.size();
  1528. }
  1529. StringName SceneState::get_node_property_name(int p_idx, int p_prop) const {
  1530. ERR_FAIL_INDEX_V(p_idx, nodes.size(), StringName());
  1531. ERR_FAIL_INDEX_V(p_prop, nodes[p_idx].properties.size(), StringName());
  1532. return names[nodes[p_idx].properties[p_prop].name & FLAG_PROP_NAME_MASK];
  1533. }
  1534. Vector<String> SceneState::get_node_deferred_nodepath_properties(int p_idx) const {
  1535. Vector<String> ret;
  1536. ERR_FAIL_COND_V(p_idx < 0, ret);
  1537. if (p_idx < nodes.size()) {
  1538. // Find in built-in nodes.
  1539. for (int i = 0; i < nodes[p_idx].properties.size(); i++) {
  1540. uint32_t idx = nodes[p_idx].properties[i].name;
  1541. if (idx & FLAG_PATH_PROPERTY_IS_NODE) {
  1542. ret.push_back(names[idx & FLAG_PROP_NAME_MASK]);
  1543. }
  1544. }
  1545. return ret;
  1546. }
  1547. // Property not found, try on instance.
  1548. HashMap<int, int>::ConstIterator I = base_scene_node_remap.find(p_idx);
  1549. if (I) {
  1550. return get_base_scene_state()->get_node_deferred_nodepath_properties(I->value);
  1551. }
  1552. return ret;
  1553. }
  1554. Variant SceneState::get_node_property_value(int p_idx, int p_prop) const {
  1555. ERR_FAIL_INDEX_V(p_idx, nodes.size(), Variant());
  1556. ERR_FAIL_INDEX_V(p_prop, nodes[p_idx].properties.size(), Variant());
  1557. return variants[nodes[p_idx].properties[p_prop].value];
  1558. }
  1559. NodePath SceneState::get_node_owner_path(int p_idx) const {
  1560. ERR_FAIL_INDEX_V(p_idx, nodes.size(), NodePath());
  1561. if (nodes[p_idx].owner < 0 || nodes[p_idx].owner == NO_PARENT_SAVED) {
  1562. return NodePath(); //root likely
  1563. }
  1564. if (nodes[p_idx].owner & FLAG_ID_IS_PATH) {
  1565. return node_paths[nodes[p_idx].owner & FLAG_MASK];
  1566. } else {
  1567. return get_node_path(nodes[p_idx].owner & FLAG_MASK);
  1568. }
  1569. }
  1570. int SceneState::get_connection_count() const {
  1571. return connections.size();
  1572. }
  1573. NodePath SceneState::get_connection_source(int p_idx) const {
  1574. ERR_FAIL_INDEX_V(p_idx, connections.size(), NodePath());
  1575. if (connections[p_idx].from & FLAG_ID_IS_PATH) {
  1576. return node_paths[connections[p_idx].from & FLAG_MASK];
  1577. } else {
  1578. return get_node_path(connections[p_idx].from & FLAG_MASK);
  1579. }
  1580. }
  1581. StringName SceneState::get_connection_signal(int p_idx) const {
  1582. ERR_FAIL_INDEX_V(p_idx, connections.size(), StringName());
  1583. return names[connections[p_idx].signal];
  1584. }
  1585. NodePath SceneState::get_connection_target(int p_idx) const {
  1586. ERR_FAIL_INDEX_V(p_idx, connections.size(), NodePath());
  1587. if (connections[p_idx].to & FLAG_ID_IS_PATH) {
  1588. return node_paths[connections[p_idx].to & FLAG_MASK];
  1589. } else {
  1590. return get_node_path(connections[p_idx].to & FLAG_MASK);
  1591. }
  1592. }
  1593. StringName SceneState::get_connection_method(int p_idx) const {
  1594. ERR_FAIL_INDEX_V(p_idx, connections.size(), StringName());
  1595. return names[connections[p_idx].method];
  1596. }
  1597. int SceneState::get_connection_flags(int p_idx) const {
  1598. ERR_FAIL_INDEX_V(p_idx, connections.size(), -1);
  1599. return connections[p_idx].flags;
  1600. }
  1601. int SceneState::get_connection_unbinds(int p_idx) const {
  1602. ERR_FAIL_INDEX_V(p_idx, connections.size(), -1);
  1603. return connections[p_idx].unbinds;
  1604. }
  1605. Array SceneState::get_connection_binds(int p_idx) const {
  1606. ERR_FAIL_INDEX_V(p_idx, connections.size(), Array());
  1607. Array binds;
  1608. for (int i = 0; i < connections[p_idx].binds.size(); i++) {
  1609. binds.push_back(variants[connections[p_idx].binds[i]]);
  1610. }
  1611. return binds;
  1612. }
  1613. bool SceneState::has_connection(const NodePath &p_node_from, const StringName &p_signal, const NodePath &p_node_to, const StringName &p_method, bool p_no_inheritance) {
  1614. // this method cannot be const because of this
  1615. Ref<SceneState> ss = this;
  1616. do {
  1617. for (int i = 0; i < ss->connections.size(); i++) {
  1618. const ConnectionData &c = ss->connections[i];
  1619. NodePath np_from;
  1620. if (c.from & FLAG_ID_IS_PATH) {
  1621. np_from = ss->node_paths[c.from & FLAG_MASK];
  1622. } else {
  1623. np_from = ss->get_node_path(c.from);
  1624. }
  1625. NodePath np_to;
  1626. if (c.to & FLAG_ID_IS_PATH) {
  1627. np_to = ss->node_paths[c.to & FLAG_MASK];
  1628. } else {
  1629. np_to = ss->get_node_path(c.to);
  1630. }
  1631. StringName sn_signal = ss->names[c.signal];
  1632. StringName sn_method = ss->names[c.method];
  1633. if (np_from == p_node_from && sn_signal == p_signal && np_to == p_node_to && sn_method == p_method) {
  1634. return true;
  1635. }
  1636. }
  1637. if (p_no_inheritance) {
  1638. break;
  1639. }
  1640. ss = ss->get_base_scene_state();
  1641. } while (ss.is_valid());
  1642. return false;
  1643. }
  1644. Vector<NodePath> SceneState::get_editable_instances() const {
  1645. return editable_instances;
  1646. }
  1647. Ref<Resource> SceneState::get_sub_resource(const String &p_path) {
  1648. for (const Variant &v : variants) {
  1649. const Ref<Resource> &res = v;
  1650. if (res.is_valid() && res->get_path() == p_path) {
  1651. return res;
  1652. }
  1653. }
  1654. return Ref<Resource>();
  1655. }
  1656. Vector<Ref<Resource>> SceneState::get_sub_resources() {
  1657. const String path_prefix = get_path() + "::";
  1658. Vector<Ref<Resource>> sub_resources;
  1659. for (const Variant &v : variants) {
  1660. const Ref<Resource> &res = v;
  1661. if (res.is_valid() && res->get_path().begins_with(path_prefix)) {
  1662. sub_resources.push_back(res);
  1663. }
  1664. }
  1665. return sub_resources;
  1666. }
  1667. //add
  1668. int SceneState::add_name(const StringName &p_name) {
  1669. names.push_back(p_name);
  1670. return names.size() - 1;
  1671. }
  1672. int SceneState::add_value(const Variant &p_value) {
  1673. variants.push_back(p_value);
  1674. return variants.size() - 1;
  1675. }
  1676. int SceneState::add_node_path(const NodePath &p_path) {
  1677. node_paths.push_back(p_path);
  1678. return (node_paths.size() - 1) | FLAG_ID_IS_PATH;
  1679. }
  1680. int SceneState::add_node(int p_parent, int p_owner, int p_type, int p_name, int p_instance, int p_index) {
  1681. NodeData nd;
  1682. nd.parent = p_parent;
  1683. nd.owner = p_owner;
  1684. nd.type = p_type;
  1685. nd.name = p_name;
  1686. nd.instance = p_instance;
  1687. nd.index = p_index;
  1688. nodes.push_back(nd);
  1689. return nodes.size() - 1;
  1690. }
  1691. void SceneState::add_node_property(int p_node, int p_name, int p_value, bool p_deferred_node_path) {
  1692. ERR_FAIL_INDEX(p_node, nodes.size());
  1693. ERR_FAIL_INDEX(p_name, names.size());
  1694. ERR_FAIL_INDEX(p_value, variants.size());
  1695. NodeData::Property prop;
  1696. prop.name = p_name;
  1697. if (p_deferred_node_path) {
  1698. prop.name |= FLAG_PATH_PROPERTY_IS_NODE;
  1699. }
  1700. prop.value = p_value;
  1701. nodes.write[p_node].properties.push_back(prop);
  1702. }
  1703. void SceneState::add_node_group(int p_node, int p_group) {
  1704. ERR_FAIL_INDEX(p_node, nodes.size());
  1705. ERR_FAIL_INDEX(p_group, names.size());
  1706. nodes.write[p_node].groups.push_back(p_group);
  1707. }
  1708. void SceneState::set_base_scene(int p_idx) {
  1709. ERR_FAIL_INDEX(p_idx, variants.size());
  1710. base_scene_idx = p_idx;
  1711. }
  1712. void SceneState::add_connection(int p_from, int p_to, int p_signal, int p_method, int p_flags, int p_unbinds, const Vector<int> &p_binds) {
  1713. ERR_FAIL_INDEX(p_signal, names.size());
  1714. ERR_FAIL_INDEX(p_method, names.size());
  1715. for (int i = 0; i < p_binds.size(); i++) {
  1716. ERR_FAIL_INDEX(p_binds[i], variants.size());
  1717. }
  1718. ConnectionData c;
  1719. c.from = p_from;
  1720. c.to = p_to;
  1721. c.signal = p_signal;
  1722. c.method = p_method;
  1723. c.flags = p_flags;
  1724. c.unbinds = p_unbinds;
  1725. c.binds = p_binds;
  1726. connections.push_back(c);
  1727. }
  1728. void SceneState::add_editable_instance(const NodePath &p_path) {
  1729. editable_instances.push_back(p_path);
  1730. }
  1731. bool SceneState::remove_group_references(const StringName &p_name) {
  1732. bool edited = false;
  1733. for (NodeData &node : nodes) {
  1734. for (const int &group : node.groups) {
  1735. if (names[group] == p_name) {
  1736. node.groups.erase(group);
  1737. edited = true;
  1738. break;
  1739. }
  1740. }
  1741. }
  1742. return edited;
  1743. }
  1744. bool SceneState::rename_group_references(const StringName &p_old_name, const StringName &p_new_name) {
  1745. bool edited = false;
  1746. for (const NodeData &node : nodes) {
  1747. for (const int &group : node.groups) {
  1748. if (names[group] == p_old_name) {
  1749. names.write[group] = p_new_name;
  1750. edited = true;
  1751. break;
  1752. }
  1753. }
  1754. }
  1755. return edited;
  1756. }
  1757. HashSet<StringName> SceneState::get_all_groups() {
  1758. HashSet<StringName> ret;
  1759. for (const NodeData &node : nodes) {
  1760. for (const int &group : node.groups) {
  1761. ret.insert(names[group]);
  1762. }
  1763. }
  1764. return ret;
  1765. }
  1766. Vector<String> SceneState::_get_node_groups(int p_idx) const {
  1767. Vector<StringName> groups = get_node_groups(p_idx);
  1768. Vector<String> ret;
  1769. for (int i = 0; i < groups.size(); i++) {
  1770. ret.push_back(groups[i]);
  1771. }
  1772. return ret;
  1773. }
  1774. void SceneState::_bind_methods() {
  1775. //unbuild API
  1776. ClassDB::bind_method(D_METHOD("get_path"), &SceneState::get_path);
  1777. ClassDB::bind_method(D_METHOD("get_base_scene_state"), &SceneState::get_base_scene_state);
  1778. ClassDB::bind_method(D_METHOD("get_node_count"), &SceneState::get_node_count);
  1779. ClassDB::bind_method(D_METHOD("get_node_type", "idx"), &SceneState::get_node_type);
  1780. ClassDB::bind_method(D_METHOD("get_node_name", "idx"), &SceneState::get_node_name);
  1781. ClassDB::bind_method(D_METHOD("get_node_path", "idx", "for_parent"), &SceneState::get_node_path, DEFVAL(false));
  1782. ClassDB::bind_method(D_METHOD("get_node_owner_path", "idx"), &SceneState::get_node_owner_path);
  1783. ClassDB::bind_method(D_METHOD("is_node_instance_placeholder", "idx"), &SceneState::is_node_instance_placeholder);
  1784. ClassDB::bind_method(D_METHOD("get_node_instance_placeholder", "idx"), &SceneState::get_node_instance_placeholder);
  1785. ClassDB::bind_method(D_METHOD("get_node_instance", "idx"), &SceneState::get_node_instance);
  1786. ClassDB::bind_method(D_METHOD("get_node_groups", "idx"), &SceneState::_get_node_groups);
  1787. ClassDB::bind_method(D_METHOD("get_node_index", "idx"), &SceneState::get_node_index);
  1788. ClassDB::bind_method(D_METHOD("get_node_property_count", "idx"), &SceneState::get_node_property_count);
  1789. ClassDB::bind_method(D_METHOD("get_node_property_name", "idx", "prop_idx"), &SceneState::get_node_property_name);
  1790. ClassDB::bind_method(D_METHOD("get_node_property_value", "idx", "prop_idx"), &SceneState::get_node_property_value);
  1791. ClassDB::bind_method(D_METHOD("get_connection_count"), &SceneState::get_connection_count);
  1792. ClassDB::bind_method(D_METHOD("get_connection_source", "idx"), &SceneState::get_connection_source);
  1793. ClassDB::bind_method(D_METHOD("get_connection_signal", "idx"), &SceneState::get_connection_signal);
  1794. ClassDB::bind_method(D_METHOD("get_connection_target", "idx"), &SceneState::get_connection_target);
  1795. ClassDB::bind_method(D_METHOD("get_connection_method", "idx"), &SceneState::get_connection_method);
  1796. ClassDB::bind_method(D_METHOD("get_connection_flags", "idx"), &SceneState::get_connection_flags);
  1797. ClassDB::bind_method(D_METHOD("get_connection_binds", "idx"), &SceneState::get_connection_binds);
  1798. ClassDB::bind_method(D_METHOD("get_connection_unbinds", "idx"), &SceneState::get_connection_unbinds);
  1799. BIND_ENUM_CONSTANT(GEN_EDIT_STATE_DISABLED);
  1800. BIND_ENUM_CONSTANT(GEN_EDIT_STATE_INSTANCE);
  1801. BIND_ENUM_CONSTANT(GEN_EDIT_STATE_MAIN);
  1802. BIND_ENUM_CONSTANT(GEN_EDIT_STATE_MAIN_INHERITED);
  1803. }
  1804. SceneState::SceneState() {
  1805. }
  1806. ////////////////
  1807. void PackedScene::_set_bundled_scene(const Dictionary &p_scene) {
  1808. state->set_bundled_scene(p_scene);
  1809. }
  1810. Dictionary PackedScene::_get_bundled_scene() const {
  1811. return state->get_bundled_scene();
  1812. }
  1813. Error PackedScene::pack(Node *p_scene) {
  1814. return state->pack(p_scene);
  1815. }
  1816. void PackedScene::clear() {
  1817. state->clear();
  1818. }
  1819. void PackedScene::reload_from_file() {
  1820. String path = get_path();
  1821. if (!path.is_resource_file()) {
  1822. return;
  1823. }
  1824. Ref<PackedScene> s = ResourceLoader::load(ResourceLoader::path_remap(path), get_class(), ResourceFormatLoader::CACHE_MODE_IGNORE);
  1825. if (s.is_null()) {
  1826. return;
  1827. }
  1828. // Backup the loaded_state
  1829. Ref<SceneState> loaded_state = s->get_state();
  1830. // This assigns a new state to s->state
  1831. // We do this because of the next step
  1832. s->recreate_state();
  1833. // This has a side-effect to clear s->state
  1834. copy_from(s);
  1835. // Then, we copy the backed-up loaded_state to state
  1836. state->copy_from(loaded_state);
  1837. }
  1838. bool PackedScene::can_instantiate() const {
  1839. return state->can_instantiate();
  1840. }
  1841. Node *PackedScene::instantiate(GenEditState p_edit_state) const {
  1842. #ifndef TOOLS_ENABLED
  1843. ERR_FAIL_COND_V_MSG(p_edit_state != GEN_EDIT_STATE_DISABLED, nullptr, "Edit state is only for editors, does not work without tools compiled.");
  1844. #endif
  1845. Node *s = state->instantiate((SceneState::GenEditState)p_edit_state);
  1846. if (!s) {
  1847. return nullptr;
  1848. }
  1849. if (p_edit_state != GEN_EDIT_STATE_DISABLED) {
  1850. s->set_scene_instance_state(state);
  1851. }
  1852. if (!is_built_in()) {
  1853. s->set_scene_file_path(get_path());
  1854. }
  1855. s->notification(Node::NOTIFICATION_SCENE_INSTANTIATED);
  1856. return s;
  1857. }
  1858. void PackedScene::replace_state(Ref<SceneState> p_by) {
  1859. state = p_by;
  1860. state->set_path(get_path());
  1861. #ifdef TOOLS_ENABLED
  1862. state->set_last_modified_time(get_last_modified_time());
  1863. #endif
  1864. }
  1865. void PackedScene::recreate_state() {
  1866. state.instantiate();
  1867. state->set_path(get_path());
  1868. #ifdef TOOLS_ENABLED
  1869. state->set_last_modified_time(get_last_modified_time());
  1870. #endif
  1871. }
  1872. #ifdef TOOLS_ENABLED
  1873. HashSet<StringName> PackedScene::get_scene_groups(const String &p_path) {
  1874. {
  1875. Ref<PackedScene> packed_scene = ResourceCache::get_ref(p_path);
  1876. if (packed_scene.is_valid()) {
  1877. return packed_scene->get_state()->get_all_groups();
  1878. }
  1879. }
  1880. if (p_path.get_extension() == "tscn") {
  1881. Ref<FileAccess> scene_file = FileAccess::open(p_path, FileAccess::READ);
  1882. ERR_FAIL_COND_V(scene_file.is_null(), HashSet<StringName>());
  1883. HashSet<StringName> ret;
  1884. while (!scene_file->eof_reached()) {
  1885. const String line = scene_file->get_line();
  1886. if (!line.begins_with("[node")) {
  1887. continue;
  1888. }
  1889. int i = line.find("groups=[");
  1890. if (i == -1) {
  1891. continue;
  1892. }
  1893. int j = line.find_char(']', i);
  1894. while (i < j) {
  1895. i = line.find_char('"', i);
  1896. if (i == -1) {
  1897. break;
  1898. }
  1899. int k = line.find_char('"', i + 1);
  1900. if (k == -1) {
  1901. break;
  1902. }
  1903. ret.insert(line.substr(i + 1, k - i - 1));
  1904. i = k + 1;
  1905. }
  1906. }
  1907. return ret;
  1908. } else {
  1909. Ref<PackedScene> packed_scene = ResourceLoader::load(p_path);
  1910. ERR_FAIL_COND_V(packed_scene.is_null(), HashSet<StringName>());
  1911. return packed_scene->get_state()->get_all_groups();
  1912. }
  1913. }
  1914. #endif
  1915. Ref<SceneState> PackedScene::get_state() const {
  1916. return state;
  1917. }
  1918. void PackedScene::set_path(const String &p_path, bool p_take_over) {
  1919. state->set_path(p_path);
  1920. Resource::set_path(p_path, p_take_over);
  1921. }
  1922. void PackedScene::set_path_cache(const String &p_path) {
  1923. state->set_path(p_path);
  1924. Resource::set_path_cache(p_path);
  1925. }
  1926. void PackedScene::reset_state() {
  1927. clear();
  1928. }
  1929. void PackedScene::_bind_methods() {
  1930. ClassDB::bind_method(D_METHOD("pack", "path"), &PackedScene::pack);
  1931. ClassDB::bind_method(D_METHOD("instantiate", "edit_state"), &PackedScene::instantiate, DEFVAL(GEN_EDIT_STATE_DISABLED));
  1932. ClassDB::bind_method(D_METHOD("can_instantiate"), &PackedScene::can_instantiate);
  1933. ClassDB::bind_method(D_METHOD("_set_bundled_scene", "scene"), &PackedScene::_set_bundled_scene);
  1934. ClassDB::bind_method(D_METHOD("_get_bundled_scene"), &PackedScene::_get_bundled_scene);
  1935. ClassDB::bind_method(D_METHOD("get_state"), &PackedScene::get_state);
  1936. ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "_bundled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL), "_set_bundled_scene", "_get_bundled_scene");
  1937. BIND_ENUM_CONSTANT(GEN_EDIT_STATE_DISABLED);
  1938. BIND_ENUM_CONSTANT(GEN_EDIT_STATE_INSTANCE);
  1939. BIND_ENUM_CONSTANT(GEN_EDIT_STATE_MAIN);
  1940. BIND_ENUM_CONSTANT(GEN_EDIT_STATE_MAIN_INHERITED);
  1941. }
  1942. PackedScene::PackedScene() {
  1943. state.instantiate();
  1944. }