packed_scene.cpp 83 KB

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