packed_scene.cpp 74 KB

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