resource_format_text.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170
  1. /**************************************************************************/
  2. /* resource_format_text.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 "resource_format_text.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/dir_access.h"
  33. #include "core/io/missing_resource.h"
  34. #include "core/object/script_language.h"
  35. #include "scene/property_utils.h"
  36. void ResourceLoaderText::_printerr() {
  37. ERR_PRINT(vformat("%s:%d - Parse Error: %s.", res_path, lines, error_text));
  38. }
  39. Ref<Resource> ResourceLoaderText::get_resource() {
  40. return resource;
  41. }
  42. Error ResourceLoaderText::_parse_sub_resource_dummy(DummyReadData *p_data, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
  43. VariantParser::Token token;
  44. VariantParser::get_token(p_stream, token, line, r_err_str);
  45. if (token.type != VariantParser::TK_NUMBER && token.type != VariantParser::TK_STRING) {
  46. r_err_str = "Expected number (old style) or string (sub-resource index)";
  47. return ERR_PARSE_ERROR;
  48. }
  49. if (p_data->no_placeholders) {
  50. r_res.unref();
  51. } else {
  52. String unique_id = token.value;
  53. if (!p_data->resource_map.has(unique_id)) {
  54. r_err_str = "Found unique_id reference before mapping, sub-resources stored out of order in resource file";
  55. return ERR_PARSE_ERROR;
  56. }
  57. r_res = p_data->resource_map[unique_id];
  58. }
  59. VariantParser::get_token(p_stream, token, line, r_err_str);
  60. if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
  61. r_err_str = "Expected ')'";
  62. return ERR_PARSE_ERROR;
  63. }
  64. return OK;
  65. }
  66. Error ResourceLoaderText::_parse_ext_resource_dummy(DummyReadData *p_data, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
  67. VariantParser::Token token;
  68. VariantParser::get_token(p_stream, token, line, r_err_str);
  69. if (token.type != VariantParser::TK_NUMBER && token.type != VariantParser::TK_STRING) {
  70. r_err_str = "Expected number (old style sub-resource index) or String (ext-resource ID)";
  71. return ERR_PARSE_ERROR;
  72. }
  73. if (p_data->no_placeholders) {
  74. r_res.unref();
  75. } else {
  76. String id = token.value;
  77. ERR_FAIL_COND_V(!p_data->rev_external_resources.has(id), ERR_PARSE_ERROR);
  78. r_res = p_data->rev_external_resources[id];
  79. }
  80. VariantParser::get_token(p_stream, token, line, r_err_str);
  81. if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
  82. r_err_str = "Expected ')'";
  83. return ERR_PARSE_ERROR;
  84. }
  85. return OK;
  86. }
  87. Error ResourceLoaderText::_parse_sub_resource(VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
  88. VariantParser::Token token;
  89. VariantParser::get_token(p_stream, token, line, r_err_str);
  90. if (token.type != VariantParser::TK_NUMBER && token.type != VariantParser::TK_STRING) {
  91. r_err_str = "Expected number (old style sub-resource index) or string";
  92. return ERR_PARSE_ERROR;
  93. }
  94. String id = token.value;
  95. ERR_FAIL_COND_V(!int_resources.has(id), ERR_INVALID_PARAMETER);
  96. r_res = int_resources[id];
  97. VariantParser::get_token(p_stream, token, line, r_err_str);
  98. if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
  99. r_err_str = "Expected ')'";
  100. return ERR_PARSE_ERROR;
  101. }
  102. return OK;
  103. }
  104. Error ResourceLoaderText::_parse_ext_resource(VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
  105. VariantParser::Token token;
  106. VariantParser::get_token(p_stream, token, line, r_err_str);
  107. if (token.type != VariantParser::TK_NUMBER && token.type != VariantParser::TK_STRING) {
  108. r_err_str = "Expected number (old style sub-resource index) or String (ext-resource ID)";
  109. return ERR_PARSE_ERROR;
  110. }
  111. String id = token.value;
  112. Error err = OK;
  113. if (!ignore_resource_parsing) {
  114. if (!ext_resources.has(id)) {
  115. r_err_str = "Can't load cached ext-resource id: " + id;
  116. return ERR_PARSE_ERROR;
  117. }
  118. String path = ext_resources[id].path;
  119. String type = ext_resources[id].type;
  120. Ref<ResourceLoader::LoadToken> &load_token = ext_resources[id].load_token;
  121. if (load_token.is_valid()) { // If not valid, it's OK since then we know this load accepts broken dependencies.
  122. Ref<Resource> res = ResourceLoader::_load_complete(*load_token.ptr(), &err);
  123. if (res.is_null()) {
  124. if (!ResourceLoader::is_cleaning_tasks()) {
  125. if (ResourceLoader::get_abort_on_missing_resources()) {
  126. error = ERR_FILE_MISSING_DEPENDENCIES;
  127. error_text = "[ext_resource] referenced non-existent resource at: " + path;
  128. _printerr();
  129. err = error;
  130. } else {
  131. ResourceLoader::notify_dependency_error(local_path, path, type);
  132. }
  133. }
  134. } else {
  135. #ifdef TOOLS_ENABLED
  136. //remember ID for saving
  137. res->set_id_for_path(local_path, id);
  138. #endif
  139. r_res = res;
  140. }
  141. } else {
  142. r_res = Ref<Resource>();
  143. }
  144. #ifdef TOOLS_ENABLED
  145. if (r_res.is_null()) {
  146. // Hack to allow checking original path.
  147. r_res.instantiate();
  148. r_res->set_meta("__load_path__", ext_resources[id].path);
  149. }
  150. #endif
  151. }
  152. VariantParser::get_token(p_stream, token, line, r_err_str);
  153. if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
  154. r_err_str = "Expected ')'";
  155. return ERR_PARSE_ERROR;
  156. }
  157. return err;
  158. }
  159. Ref<PackedScene> ResourceLoaderText::_parse_node_tag(VariantParser::ResourceParser &parser) {
  160. Ref<PackedScene> packed_scene = ResourceLoader::get_resource_ref_override(local_path);
  161. if (packed_scene.is_null()) {
  162. packed_scene.instantiate();
  163. }
  164. while (true) {
  165. if (next_tag.name == "node") {
  166. int parent = -1;
  167. int owner = -1;
  168. int type = -1;
  169. int name = -1;
  170. int instance = -1;
  171. int index = -1;
  172. //int base_scene=-1;
  173. if (next_tag.fields.has("name")) {
  174. name = packed_scene->get_state()->add_name(next_tag.fields["name"]);
  175. }
  176. if (next_tag.fields.has("parent")) {
  177. NodePath np = next_tag.fields["parent"];
  178. np.prepend_period(); //compatible to how it manages paths internally
  179. parent = packed_scene->get_state()->add_node_path(np);
  180. }
  181. if (next_tag.fields.has("type")) {
  182. type = packed_scene->get_state()->add_name(next_tag.fields["type"]);
  183. } else {
  184. type = SceneState::TYPE_INSTANTIATED; //no type? assume this was instantiated
  185. }
  186. HashSet<StringName> path_properties;
  187. if (next_tag.fields.has("node_paths")) {
  188. Vector<String> paths = next_tag.fields["node_paths"];
  189. for (int i = 0; i < paths.size(); i++) {
  190. path_properties.insert(paths[i]);
  191. }
  192. }
  193. if (next_tag.fields.has("instance")) {
  194. instance = packed_scene->get_state()->add_value(next_tag.fields["instance"]);
  195. if (packed_scene->get_state()->get_node_count() == 0 && parent == -1) {
  196. packed_scene->get_state()->set_base_scene(instance);
  197. instance = -1;
  198. }
  199. }
  200. if (next_tag.fields.has("instance_placeholder")) {
  201. String path = next_tag.fields["instance_placeholder"];
  202. int path_v = packed_scene->get_state()->add_value(path);
  203. if (packed_scene->get_state()->get_node_count() == 0) {
  204. error = ERR_FILE_CORRUPT;
  205. error_text = "Instance Placeholder can't be used for inheritance";
  206. _printerr();
  207. return Ref<PackedScene>();
  208. }
  209. instance = path_v | SceneState::FLAG_INSTANCE_IS_PLACEHOLDER;
  210. }
  211. if (next_tag.fields.has("owner")) {
  212. owner = packed_scene->get_state()->add_node_path(next_tag.fields["owner"]);
  213. } else {
  214. if (parent != -1 && !(type == SceneState::TYPE_INSTANTIATED && instance == -1)) {
  215. owner = 0; //if no owner, owner is root
  216. }
  217. }
  218. if (next_tag.fields.has("index")) {
  219. index = next_tag.fields["index"];
  220. }
  221. int node_id = packed_scene->get_state()->add_node(parent, owner, type, name, instance, index);
  222. if (next_tag.fields.has("groups")) {
  223. Array groups = next_tag.fields["groups"];
  224. for (const Variant &group : groups) {
  225. packed_scene->get_state()->add_node_group(node_id, packed_scene->get_state()->add_name(group));
  226. }
  227. }
  228. while (true) {
  229. String assign;
  230. Variant value;
  231. error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &parser);
  232. if (error) {
  233. if (error == ERR_FILE_MISSING_DEPENDENCIES) {
  234. // Resource loading error, just skip it.
  235. } else if (error != ERR_FILE_EOF) {
  236. ERR_PRINT(vformat("Parse Error: %s. [Resource file %s:%d]", error_names[error], res_path, lines));
  237. return Ref<PackedScene>();
  238. } else {
  239. error = OK;
  240. return packed_scene;
  241. }
  242. }
  243. if (!assign.is_empty()) {
  244. StringName assign_name = assign;
  245. int nameidx = packed_scene->get_state()->add_name(assign_name);
  246. int valueidx = packed_scene->get_state()->add_value(value);
  247. packed_scene->get_state()->add_node_property(node_id, nameidx, valueidx, path_properties.has(assign_name));
  248. //it's assignment
  249. } else if (!next_tag.name.is_empty()) {
  250. break;
  251. }
  252. }
  253. } else if (next_tag.name == "connection") {
  254. if (!next_tag.fields.has("from")) {
  255. error = ERR_FILE_CORRUPT;
  256. error_text = "missing 'from' field from connection tag";
  257. return Ref<PackedScene>();
  258. }
  259. if (!next_tag.fields.has("to")) {
  260. error = ERR_FILE_CORRUPT;
  261. error_text = "missing 'to' field from connection tag";
  262. return Ref<PackedScene>();
  263. }
  264. if (!next_tag.fields.has("signal")) {
  265. error = ERR_FILE_CORRUPT;
  266. error_text = "missing 'signal' field from connection tag";
  267. return Ref<PackedScene>();
  268. }
  269. if (!next_tag.fields.has("method")) {
  270. error = ERR_FILE_CORRUPT;
  271. error_text = "missing 'method' field from connection tag";
  272. return Ref<PackedScene>();
  273. }
  274. NodePath from = next_tag.fields["from"];
  275. NodePath to = next_tag.fields["to"];
  276. StringName method = next_tag.fields["method"];
  277. StringName signal = next_tag.fields["signal"];
  278. int flags = Object::CONNECT_PERSIST;
  279. int unbinds = 0;
  280. Array binds;
  281. if (next_tag.fields.has("flags")) {
  282. flags = next_tag.fields["flags"];
  283. }
  284. if (next_tag.fields.has("binds")) {
  285. binds = next_tag.fields["binds"];
  286. }
  287. if (next_tag.fields.has("unbinds")) {
  288. unbinds = next_tag.fields["unbinds"];
  289. }
  290. Vector<int> bind_ints;
  291. for (const Variant &bind : binds) {
  292. bind_ints.push_back(packed_scene->get_state()->add_value(bind));
  293. }
  294. packed_scene->get_state()->add_connection(
  295. packed_scene->get_state()->add_node_path(from.simplified()),
  296. packed_scene->get_state()->add_node_path(to.simplified()),
  297. packed_scene->get_state()->add_name(signal),
  298. packed_scene->get_state()->add_name(method),
  299. flags,
  300. unbinds,
  301. bind_ints);
  302. error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &parser);
  303. if (error) {
  304. if (error != ERR_FILE_EOF) {
  305. _printerr();
  306. return Ref<PackedScene>();
  307. } else {
  308. error = OK;
  309. return packed_scene;
  310. }
  311. }
  312. } else if (next_tag.name == "editable") {
  313. if (!next_tag.fields.has("path")) {
  314. error = ERR_FILE_CORRUPT;
  315. error_text = "Missing 'path' field from editable tag";
  316. _printerr();
  317. return Ref<PackedScene>();
  318. }
  319. NodePath path = next_tag.fields["path"];
  320. packed_scene->get_state()->add_editable_instance(path.simplified());
  321. error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &parser);
  322. if (error) {
  323. if (error != ERR_FILE_EOF) {
  324. _printerr();
  325. return Ref<PackedScene>();
  326. } else {
  327. error = OK;
  328. return packed_scene;
  329. }
  330. }
  331. } else {
  332. error = ERR_FILE_CORRUPT;
  333. error_text = vformat("Unknown tag '%s' in file", next_tag.name);
  334. _printerr();
  335. return Ref<PackedScene>();
  336. }
  337. }
  338. }
  339. Error ResourceLoaderText::load() {
  340. if (error != OK) {
  341. return error;
  342. }
  343. while (true) {
  344. if (next_tag.name != "ext_resource") {
  345. break;
  346. }
  347. if (!next_tag.fields.has("path")) {
  348. error = ERR_FILE_CORRUPT;
  349. error_text = "Missing 'path' in external resource tag";
  350. _printerr();
  351. return error;
  352. }
  353. if (!next_tag.fields.has("type")) {
  354. error = ERR_FILE_CORRUPT;
  355. error_text = "Missing 'type' in external resource tag";
  356. _printerr();
  357. return error;
  358. }
  359. if (!next_tag.fields.has("id")) {
  360. error = ERR_FILE_CORRUPT;
  361. error_text = "Missing 'id' in external resource tag";
  362. _printerr();
  363. return error;
  364. }
  365. String path = next_tag.fields["path"];
  366. String type = next_tag.fields["type"];
  367. String id = next_tag.fields["id"];
  368. if (next_tag.fields.has("uid")) {
  369. String uidt = next_tag.fields["uid"];
  370. ResourceUID::ID uid = ResourceUID::get_singleton()->text_to_id(uidt);
  371. if (uid != ResourceUID::INVALID_ID && ResourceUID::get_singleton()->has_id(uid)) {
  372. // If a UID is found and the path is valid, it will be used, otherwise, it falls back to the path.
  373. path = ResourceUID::get_singleton()->get_id_path(uid);
  374. } else {
  375. #ifdef TOOLS_ENABLED
  376. // Silence a warning that can happen during the initial filesystem scan due to cache being regenerated.
  377. if (ResourceLoader::get_resource_uid(path) != uid) {
  378. WARN_PRINT(String(res_path + ":" + itos(lines) + " - ext_resource, invalid UID: " + uidt + " - using text path instead: " + path).utf8().get_data());
  379. }
  380. #else
  381. WARN_PRINT(String(res_path + ":" + itos(lines) + " - ext_resource, invalid UID: " + uidt + " - using text path instead: " + path).utf8().get_data());
  382. #endif
  383. }
  384. }
  385. if (!path.contains("://") && path.is_relative_path()) {
  386. // path is relative to file being loaded, so convert to a resource path
  387. path = ProjectSettings::get_singleton()->localize_path(local_path.get_base_dir().path_join(path));
  388. }
  389. if (remaps.has(path)) {
  390. path = remaps[path];
  391. }
  392. ext_resources[id].path = path;
  393. ext_resources[id].type = type;
  394. ext_resources[id].load_token = ResourceLoader::_load_start(path, type, use_sub_threads ? ResourceLoader::LOAD_THREAD_DISTRIBUTE : ResourceLoader::LOAD_THREAD_FROM_CURRENT, cache_mode_for_external);
  395. if (ext_resources[id].load_token.is_null()) {
  396. if (ResourceLoader::get_abort_on_missing_resources()) {
  397. error = ERR_FILE_CORRUPT;
  398. error_text = "[ext_resource] referenced non-existent resource at: " + path;
  399. _printerr();
  400. return error;
  401. } else {
  402. ResourceLoader::notify_dependency_error(local_path, path, type);
  403. }
  404. }
  405. error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
  406. if (error) {
  407. _printerr();
  408. return error;
  409. }
  410. resource_current++;
  411. }
  412. //these are the ones that count
  413. resources_total -= resource_current;
  414. resource_current = 0;
  415. while (true) {
  416. if (next_tag.name != "sub_resource") {
  417. break;
  418. }
  419. if (!next_tag.fields.has("type")) {
  420. error = ERR_FILE_CORRUPT;
  421. error_text = "Missing 'type' in external resource tag";
  422. _printerr();
  423. return error;
  424. }
  425. if (!next_tag.fields.has("id")) {
  426. error = ERR_FILE_CORRUPT;
  427. error_text = "Missing 'id' in external resource tag";
  428. _printerr();
  429. return error;
  430. }
  431. String type = next_tag.fields["type"];
  432. String id = next_tag.fields["id"];
  433. String path = local_path + "::" + id;
  434. //bool exists=ResourceCache::has(path);
  435. Ref<Resource> res;
  436. bool do_assign = false;
  437. if (cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE && ResourceCache::has(path)) {
  438. //reuse existing
  439. Ref<Resource> cache = ResourceCache::get_ref(path);
  440. if (cache.is_valid() && cache->get_class() == type) {
  441. res = cache;
  442. res->reset_state();
  443. do_assign = true;
  444. }
  445. }
  446. MissingResource *missing_resource = nullptr;
  447. if (res.is_null()) { //not reuse
  448. Ref<Resource> cache = ResourceCache::get_ref(path);
  449. if (cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE && cache.is_valid()) { //only if it doesn't exist
  450. //cached, do not assign
  451. res = cache;
  452. } else {
  453. //create
  454. Object *obj = ClassDB::instantiate(type);
  455. if (!obj) {
  456. if (ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
  457. missing_resource = memnew(MissingResource);
  458. missing_resource->set_original_class(type);
  459. missing_resource->set_recording_properties(true);
  460. obj = missing_resource;
  461. } else {
  462. error_text = vformat("Can't create sub resource of type '%s'", type);
  463. _printerr();
  464. error = ERR_FILE_CORRUPT;
  465. return error;
  466. }
  467. }
  468. Resource *r = Object::cast_to<Resource>(obj);
  469. if (!r) {
  470. error_text = vformat("Can't create sub resource of type '%s' as it's not a resource type", type);
  471. _printerr();
  472. error = ERR_FILE_CORRUPT;
  473. return error;
  474. }
  475. res = Ref<Resource>(r);
  476. do_assign = true;
  477. }
  478. }
  479. resource_current++;
  480. if (progress && resources_total > 0) {
  481. *progress = resource_current / float(resources_total);
  482. }
  483. int_resources[id] = res; // Always assign int resources.
  484. if (do_assign) {
  485. if (cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
  486. res->set_path(path, cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE);
  487. } else {
  488. res->set_path_cache(path);
  489. }
  490. res->set_scene_unique_id(id);
  491. }
  492. Dictionary missing_resource_properties;
  493. while (true) {
  494. String assign;
  495. Variant value;
  496. error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp);
  497. if (error) {
  498. _printerr();
  499. return error;
  500. }
  501. if (!assign.is_empty()) {
  502. if (do_assign) {
  503. bool set_valid = true;
  504. if (value.get_type() == Variant::OBJECT && missing_resource == nullptr && ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
  505. // If the property being set is a missing resource (and the parent is not),
  506. // then setting it will most likely not work.
  507. // Instead, save it as metadata.
  508. Ref<MissingResource> mr = value;
  509. if (mr.is_valid()) {
  510. missing_resource_properties[assign] = mr;
  511. set_valid = false;
  512. }
  513. }
  514. if (value.get_type() == Variant::ARRAY) {
  515. Array set_array = value;
  516. bool is_get_valid = false;
  517. Variant get_value = res->get(assign, &is_get_valid);
  518. if (is_get_valid && get_value.get_type() == Variant::ARRAY) {
  519. Array get_array = get_value;
  520. if (!set_array.is_same_typed(get_array)) {
  521. value = Array(set_array, get_array.get_typed_builtin(), get_array.get_typed_class_name(), get_array.get_typed_script());
  522. }
  523. }
  524. }
  525. if (value.get_type() == Variant::DICTIONARY) {
  526. Dictionary set_dict = value;
  527. bool is_get_valid = false;
  528. Variant get_value = res->get(assign, &is_get_valid);
  529. if (is_get_valid && get_value.get_type() == Variant::DICTIONARY) {
  530. Dictionary get_dict = get_value;
  531. if (!set_dict.is_same_typed(get_dict)) {
  532. value = Dictionary(set_dict, get_dict.get_typed_key_builtin(), get_dict.get_typed_key_class_name(), get_dict.get_typed_key_script(),
  533. get_dict.get_typed_value_builtin(), get_dict.get_typed_value_class_name(), get_dict.get_typed_value_script());
  534. }
  535. }
  536. }
  537. if (set_valid) {
  538. res->set(assign, value);
  539. }
  540. }
  541. //it's assignment
  542. } else if (!next_tag.name.is_empty()) {
  543. error = OK;
  544. break;
  545. } else {
  546. error = ERR_FILE_CORRUPT;
  547. error_text = "Premature end of file while parsing [sub_resource]";
  548. _printerr();
  549. return error;
  550. }
  551. }
  552. if (missing_resource) {
  553. missing_resource->set_recording_properties(false);
  554. }
  555. if (!missing_resource_properties.is_empty()) {
  556. res->set_meta(META_MISSING_RESOURCES, missing_resource_properties);
  557. }
  558. }
  559. while (true) {
  560. if (next_tag.name != "resource") {
  561. break;
  562. }
  563. if (is_scene) {
  564. error_text = "Unexpected 'resource' tag in a scene file";
  565. _printerr();
  566. error = ERR_FILE_CORRUPT;
  567. return error;
  568. }
  569. MissingResource *missing_resource = nullptr;
  570. resource = ResourceLoader::get_resource_ref_override(local_path);
  571. if (resource.is_null()) {
  572. Ref<Resource> cache = ResourceCache::get_ref(local_path);
  573. if (cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE && cache.is_valid() && cache->get_class() == res_type) {
  574. cache->reset_state();
  575. resource = cache;
  576. }
  577. if (resource.is_null()) {
  578. Object *obj = ClassDB::instantiate(res_type);
  579. if (!obj) {
  580. if (ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
  581. missing_resource = memnew(MissingResource);
  582. missing_resource->set_original_class(res_type);
  583. missing_resource->set_recording_properties(true);
  584. obj = missing_resource;
  585. } else {
  586. error_text = vformat("Can't create sub resource of type '%s'", res_type);
  587. _printerr();
  588. error = ERR_FILE_CORRUPT;
  589. return error;
  590. }
  591. }
  592. Resource *r = Object::cast_to<Resource>(obj);
  593. if (!r) {
  594. error_text = vformat("Can't create sub resource of type '%s' as it's not a resource type", res_type);
  595. _printerr();
  596. error = ERR_FILE_CORRUPT;
  597. return error;
  598. }
  599. resource = Ref<Resource>(r);
  600. }
  601. }
  602. Dictionary missing_resource_properties;
  603. while (true) {
  604. String assign;
  605. Variant value;
  606. error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp);
  607. if (error) {
  608. if (error != ERR_FILE_EOF) {
  609. _printerr();
  610. return error;
  611. }
  612. // EOF, Done parsing.
  613. error = OK;
  614. if (cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
  615. if (!ResourceCache::has(res_path)) {
  616. resource->set_path(res_path);
  617. }
  618. resource->set_as_translation_remapped(translation_remapped);
  619. } else {
  620. resource->set_path_cache(res_path);
  621. }
  622. break;
  623. }
  624. if (!assign.is_empty()) {
  625. bool set_valid = true;
  626. if (value.get_type() == Variant::OBJECT && missing_resource == nullptr && ResourceLoader::is_creating_missing_resources_if_class_unavailable_enabled()) {
  627. // If the property being set is a missing resource (and the parent is not),
  628. // then setting it will most likely not work.
  629. // Instead, save it as metadata.
  630. Ref<MissingResource> mr = value;
  631. if (mr.is_valid()) {
  632. missing_resource_properties[assign] = mr;
  633. set_valid = false;
  634. }
  635. }
  636. if (value.get_type() == Variant::ARRAY) {
  637. Array set_array = value;
  638. bool is_get_valid = false;
  639. Variant get_value = resource->get(assign, &is_get_valid);
  640. if (is_get_valid && get_value.get_type() == Variant::ARRAY) {
  641. Array get_array = get_value;
  642. if (!set_array.is_same_typed(get_array)) {
  643. value = Array(set_array, get_array.get_typed_builtin(), get_array.get_typed_class_name(), get_array.get_typed_script());
  644. }
  645. }
  646. }
  647. if (value.get_type() == Variant::DICTIONARY) {
  648. Dictionary set_dict = value;
  649. bool is_get_valid = false;
  650. Variant get_value = resource->get(assign, &is_get_valid);
  651. if (is_get_valid && get_value.get_type() == Variant::DICTIONARY) {
  652. Dictionary get_dict = get_value;
  653. if (!set_dict.is_same_typed(get_dict)) {
  654. value = Dictionary(set_dict, get_dict.get_typed_key_builtin(), get_dict.get_typed_key_class_name(), get_dict.get_typed_key_script(),
  655. get_dict.get_typed_value_builtin(), get_dict.get_typed_value_class_name(), get_dict.get_typed_value_script());
  656. }
  657. }
  658. }
  659. if (set_valid) {
  660. resource->set(assign, value);
  661. }
  662. //it's assignment
  663. } else if (!next_tag.name.is_empty()) {
  664. error = ERR_FILE_CORRUPT;
  665. error_text = "Extra tag found when parsing main resource file";
  666. _printerr();
  667. return error;
  668. } else {
  669. break;
  670. }
  671. }
  672. resource_current++;
  673. if (progress && resources_total > 0) {
  674. *progress = resource_current / float(resources_total);
  675. }
  676. if (missing_resource) {
  677. missing_resource->set_recording_properties(false);
  678. }
  679. if (!missing_resource_properties.is_empty()) {
  680. resource->set_meta(META_MISSING_RESOURCES, missing_resource_properties);
  681. }
  682. error = OK;
  683. return error;
  684. }
  685. //for scene files
  686. if (next_tag.name == "node") {
  687. if (!is_scene) {
  688. error_text = "Unexpected 'node' tag in a resource file";
  689. _printerr();
  690. error = ERR_FILE_CORRUPT;
  691. return error;
  692. }
  693. Ref<PackedScene> packed_scene = _parse_node_tag(rp);
  694. if (packed_scene.is_null()) {
  695. return error;
  696. }
  697. error = OK;
  698. //get it here
  699. resource = packed_scene;
  700. if (cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
  701. if (!ResourceCache::has(res_path)) {
  702. packed_scene->set_path(res_path);
  703. }
  704. } else {
  705. packed_scene->get_state()->set_path(res_path);
  706. packed_scene->set_path_cache(res_path);
  707. }
  708. resource_current++;
  709. if (progress && resources_total > 0) {
  710. *progress = resource_current / float(resources_total);
  711. }
  712. return error;
  713. } else {
  714. error_text = vformat("Unknown tag '%s' in file", next_tag.name);
  715. _printerr();
  716. error = ERR_FILE_CORRUPT;
  717. return error;
  718. }
  719. }
  720. int ResourceLoaderText::get_stage() const {
  721. return resource_current;
  722. }
  723. int ResourceLoaderText::get_stage_count() const {
  724. return resources_total; //+ext_resources;
  725. }
  726. void ResourceLoaderText::set_translation_remapped(bool p_remapped) {
  727. translation_remapped = p_remapped;
  728. }
  729. ResourceLoaderText::ResourceLoaderText() :
  730. stream(false), format_version(FORMAT_VERSION) {}
  731. void ResourceLoaderText::get_dependencies(Ref<FileAccess> p_f, List<String> *p_dependencies, bool p_add_types) {
  732. open(p_f);
  733. ignore_resource_parsing = true;
  734. ERR_FAIL_COND(error != OK);
  735. while (next_tag.name == "ext_resource") {
  736. if (!next_tag.fields.has("type")) {
  737. error = ERR_FILE_CORRUPT;
  738. error_text = "Missing 'type' in external resource tag";
  739. _printerr();
  740. return;
  741. }
  742. if (!next_tag.fields.has("id")) {
  743. error = ERR_FILE_CORRUPT;
  744. error_text = "Missing 'id' in external resource tag";
  745. _printerr();
  746. return;
  747. }
  748. String path = next_tag.fields["path"];
  749. String type = next_tag.fields["type"];
  750. String fallback_path;
  751. bool using_uid = false;
  752. if (next_tag.fields.has("uid")) {
  753. // If uid exists, return uid in text format, not the path.
  754. String uidt = next_tag.fields["uid"];
  755. ResourceUID::ID uid = ResourceUID::get_singleton()->text_to_id(uidt);
  756. if (uid != ResourceUID::INVALID_ID) {
  757. fallback_path = path; // Used by Dependency Editor, in case uid path fails.
  758. path = ResourceUID::get_singleton()->id_to_text(uid);
  759. using_uid = true;
  760. }
  761. }
  762. if (!using_uid && !path.contains("://") && path.is_relative_path()) {
  763. // Path is relative to file being loaded, so convert to a resource path.
  764. path = ProjectSettings::get_singleton()->localize_path(local_path.get_base_dir().path_join(path));
  765. }
  766. if (p_add_types) {
  767. path += "::" + type;
  768. }
  769. if (!fallback_path.is_empty()) {
  770. if (!p_add_types) {
  771. path += "::"; // Ensure that path comes third, even if there is no type.
  772. }
  773. path += "::" + fallback_path;
  774. }
  775. p_dependencies->push_back(path);
  776. Error err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
  777. if (err) {
  778. print_line(error_text + " - " + itos(lines));
  779. error_text = "Unexpected end of file";
  780. _printerr();
  781. error = ERR_FILE_CORRUPT;
  782. return;
  783. }
  784. }
  785. }
  786. Error ResourceLoaderText::rename_dependencies(Ref<FileAccess> p_f, const String &p_path, const HashMap<String, String> &p_map) {
  787. open(p_f, true);
  788. ERR_FAIL_COND_V(error != OK, error);
  789. ignore_resource_parsing = true;
  790. //FileAccess
  791. Ref<FileAccess> fw;
  792. String base_path = local_path.get_base_dir();
  793. uint64_t tag_end = f->get_position();
  794. while (true) {
  795. Error err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
  796. if (err != OK) {
  797. error = ERR_FILE_CORRUPT;
  798. ERR_FAIL_V(error);
  799. }
  800. if (next_tag.name != "ext_resource") {
  801. //nothing was done
  802. if (fw.is_null()) {
  803. return OK;
  804. }
  805. break;
  806. } else {
  807. if (fw.is_null()) {
  808. fw = FileAccess::open(p_path + ".depren", FileAccess::WRITE);
  809. if (res_uid == ResourceUID::INVALID_ID) {
  810. res_uid = ResourceSaver::get_resource_id_for_path(p_path);
  811. }
  812. String uid_text = "";
  813. if (res_uid != ResourceUID::INVALID_ID) {
  814. uid_text = " uid=\"" + ResourceUID::get_singleton()->id_to_text(res_uid) + "\"";
  815. }
  816. if (is_scene) {
  817. fw->store_line("[gd_scene load_steps=" + itos(resources_total) + " format=" + itos(format_version) + uid_text + "]\n");
  818. } else {
  819. String script_res_text;
  820. if (!script_class.is_empty()) {
  821. script_res_text = "script_class=\"" + script_class + "\" ";
  822. }
  823. fw->store_line("[gd_resource type=\"" + res_type + "\" " + script_res_text + "load_steps=" + itos(resources_total) + " format=" + itos(format_version) + uid_text + "]\n");
  824. }
  825. }
  826. if (!next_tag.fields.has("path") || !next_tag.fields.has("id") || !next_tag.fields.has("type")) {
  827. error = ERR_FILE_CORRUPT;
  828. ERR_FAIL_V(error);
  829. }
  830. String path = next_tag.fields["path"];
  831. String id = next_tag.fields["id"];
  832. String type = next_tag.fields["type"];
  833. if (next_tag.fields.has("uid")) {
  834. String uidt = next_tag.fields["uid"];
  835. ResourceUID::ID uid = ResourceUID::get_singleton()->text_to_id(uidt);
  836. if (uid != ResourceUID::INVALID_ID && ResourceUID::get_singleton()->has_id(uid)) {
  837. // If a UID is found and the path is valid, it will be used, otherwise, it falls back to the path.
  838. path = ResourceUID::get_singleton()->get_id_path(uid);
  839. }
  840. }
  841. bool relative = false;
  842. if (!path.begins_with("res://")) {
  843. path = base_path.path_join(path).simplify_path();
  844. relative = true;
  845. }
  846. if (p_map.has(path)) {
  847. path = p_map[path];
  848. }
  849. if (relative) {
  850. //restore relative
  851. path = base_path.path_to_file(path);
  852. }
  853. String s = "[ext_resource type=\"" + type + "\"";
  854. ResourceUID::ID uid = ResourceSaver::get_resource_id_for_path(path);
  855. if (uid != ResourceUID::INVALID_ID) {
  856. s += " uid=\"" + ResourceUID::get_singleton()->id_to_text(uid) + "\"";
  857. }
  858. s += " path=\"" + path + "\" id=\"" + id + "\"]";
  859. fw->store_line(s); // Bundled.
  860. tag_end = f->get_position();
  861. }
  862. }
  863. f->seek(tag_end);
  864. const uint32_t buffer_size = 2048;
  865. uint8_t *buffer = (uint8_t *)alloca(buffer_size);
  866. uint32_t num_read;
  867. num_read = f->get_buffer(buffer, buffer_size);
  868. ERR_FAIL_COND_V_MSG(num_read == UINT32_MAX, ERR_CANT_CREATE, "Failed to allocate memory for buffer.");
  869. ERR_FAIL_COND_V(num_read == 0, ERR_FILE_CORRUPT);
  870. if (*buffer == '\n') {
  871. // Skip first newline character since we added one.
  872. if (num_read > 1) {
  873. fw->store_buffer(buffer + 1, num_read - 1);
  874. }
  875. } else {
  876. fw->store_buffer(buffer, num_read);
  877. }
  878. while (!f->eof_reached()) {
  879. num_read = f->get_buffer(buffer, buffer_size);
  880. fw->store_buffer(buffer, num_read);
  881. }
  882. bool all_ok = fw->get_error() == OK;
  883. if (!all_ok) {
  884. return ERR_CANT_CREATE;
  885. }
  886. return OK;
  887. }
  888. void ResourceLoaderText::open(Ref<FileAccess> p_f, bool p_skip_first_tag) {
  889. error = OK;
  890. lines = 1;
  891. f = p_f;
  892. stream.f = f;
  893. is_scene = false;
  894. ignore_resource_parsing = false;
  895. resource_current = 0;
  896. VariantParser::Tag tag;
  897. Error err = VariantParser::parse_tag(&stream, lines, error_text, tag);
  898. if (err) {
  899. error = err;
  900. _printerr();
  901. return;
  902. }
  903. if (tag.fields.has("format")) {
  904. format_version = tag.fields["format"];
  905. if (format_version > FORMAT_VERSION) {
  906. error_text = "Saved with newer format version";
  907. _printerr();
  908. error = ERR_FILE_UNRECOGNIZED;
  909. return;
  910. }
  911. } else {
  912. format_version = FORMAT_VERSION;
  913. }
  914. if (tag.name == "gd_scene") {
  915. is_scene = true;
  916. } else if (tag.name == "gd_resource") {
  917. if (!tag.fields.has("type")) {
  918. error_text = "Missing 'type' field in 'gd_resource' tag";
  919. _printerr();
  920. error = ERR_PARSE_ERROR;
  921. return;
  922. }
  923. if (tag.fields.has("script_class")) {
  924. script_class = tag.fields["script_class"];
  925. }
  926. res_type = tag.fields["type"];
  927. } else {
  928. error_text = vformat("Unrecognized file type '%s'", tag.name);
  929. _printerr();
  930. error = ERR_PARSE_ERROR;
  931. return;
  932. }
  933. if (tag.fields.has("uid")) {
  934. res_uid = ResourceUID::get_singleton()->text_to_id(tag.fields["uid"]);
  935. } else {
  936. res_uid = ResourceUID::INVALID_ID;
  937. }
  938. if (tag.fields.has("load_steps")) {
  939. resources_total = tag.fields["load_steps"];
  940. } else {
  941. resources_total = 0;
  942. }
  943. if (!p_skip_first_tag) {
  944. err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
  945. if (err) {
  946. error_text = "Unexpected end of file";
  947. _printerr();
  948. error = ERR_FILE_CORRUPT;
  949. }
  950. }
  951. rp.ext_func = _parse_ext_resources;
  952. rp.sub_func = _parse_sub_resources;
  953. rp.userdata = this;
  954. }
  955. Error ResourceLoaderText::get_classes_used(HashSet<StringName> *r_classes) {
  956. if (error) {
  957. return error;
  958. }
  959. ignore_resource_parsing = true;
  960. DummyReadData dummy_read;
  961. dummy_read.no_placeholders = true;
  962. VariantParser::ResourceParser rp_new;
  963. rp_new.ext_func = _parse_ext_resource_dummys;
  964. rp_new.sub_func = _parse_sub_resource_dummys;
  965. rp_new.userdata = &dummy_read;
  966. while (next_tag.name == "ext_resource") {
  967. error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp_new);
  968. if (error) {
  969. _printerr();
  970. return error;
  971. }
  972. }
  973. while (next_tag.name == "sub_resource" || next_tag.name == "resource") {
  974. if (next_tag.name == "sub_resource") {
  975. if (!next_tag.fields.has("type")) {
  976. error = ERR_FILE_CORRUPT;
  977. error_text = "Missing 'type' in external resource tag";
  978. _printerr();
  979. return error;
  980. }
  981. r_classes->insert(next_tag.fields["type"]);
  982. } else {
  983. r_classes->insert(next_tag.fields["res_type"]);
  984. }
  985. while (true) {
  986. String assign;
  987. Variant value;
  988. error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp_new);
  989. if (error) {
  990. if (error == ERR_FILE_EOF) {
  991. return OK;
  992. }
  993. _printerr();
  994. return error;
  995. }
  996. if (!assign.is_empty()) {
  997. continue;
  998. } else if (!next_tag.name.is_empty()) {
  999. error = OK;
  1000. break;
  1001. } else {
  1002. error = ERR_FILE_CORRUPT;
  1003. error_text = "Premature end of file while parsing [sub_resource]";
  1004. _printerr();
  1005. return error;
  1006. }
  1007. }
  1008. }
  1009. while (next_tag.name == "node") {
  1010. // This is a node, must save one more!
  1011. if (!is_scene) {
  1012. error = ERR_FILE_CORRUPT;
  1013. error_text = "Unexpected 'node' tag in a resource file";
  1014. _printerr();
  1015. return error;
  1016. }
  1017. if (next_tag.fields.has("type")) {
  1018. r_classes->insert(next_tag.fields["type"]);
  1019. }
  1020. while (true) {
  1021. String assign;
  1022. Variant value;
  1023. error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp_new);
  1024. if (error) {
  1025. if (error == ERR_FILE_MISSING_DEPENDENCIES) {
  1026. // Resource loading error, just skip it.
  1027. } else if (error != ERR_FILE_EOF) {
  1028. _printerr();
  1029. return error;
  1030. } else {
  1031. return OK;
  1032. }
  1033. }
  1034. if (!assign.is_empty()) {
  1035. continue;
  1036. } else if (!next_tag.name.is_empty()) {
  1037. error = OK;
  1038. break;
  1039. } else {
  1040. error = ERR_FILE_CORRUPT;
  1041. error_text = "Premature end of file while parsing [sub_resource]";
  1042. _printerr();
  1043. return error;
  1044. }
  1045. }
  1046. }
  1047. return OK;
  1048. }
  1049. String ResourceLoaderText::recognize_script_class(Ref<FileAccess> p_f) {
  1050. error = OK;
  1051. lines = 1;
  1052. f = p_f;
  1053. stream.f = f;
  1054. ignore_resource_parsing = true;
  1055. VariantParser::Tag tag;
  1056. Error err = VariantParser::parse_tag(&stream, lines, error_text, tag);
  1057. if (err) {
  1058. _printerr();
  1059. return "";
  1060. }
  1061. if (tag.fields.has("format")) {
  1062. int fmt = tag.fields["format"];
  1063. if (fmt > FORMAT_VERSION) {
  1064. error_text = "Saved with newer format version";
  1065. _printerr();
  1066. return "";
  1067. }
  1068. }
  1069. if (tag.name != "gd_resource") {
  1070. return "";
  1071. }
  1072. if (tag.fields.has("script_class")) {
  1073. return tag.fields["script_class"];
  1074. }
  1075. return "";
  1076. }
  1077. String ResourceLoaderText::recognize(Ref<FileAccess> p_f) {
  1078. error = OK;
  1079. lines = 1;
  1080. f = p_f;
  1081. stream.f = f;
  1082. ignore_resource_parsing = true;
  1083. VariantParser::Tag tag;
  1084. Error err = VariantParser::parse_tag(&stream, lines, error_text, tag);
  1085. if (err) {
  1086. _printerr();
  1087. return "";
  1088. }
  1089. if (tag.fields.has("format")) {
  1090. int fmt = tag.fields["format"];
  1091. if (fmt > FORMAT_VERSION) {
  1092. error_text = "Saved with newer format version";
  1093. _printerr();
  1094. return "";
  1095. }
  1096. }
  1097. if (tag.name == "gd_scene") {
  1098. return "PackedScene";
  1099. }
  1100. if (tag.name != "gd_resource") {
  1101. return "";
  1102. }
  1103. if (!tag.fields.has("type")) {
  1104. error_text = "Missing 'type' field in 'gd_resource' tag";
  1105. _printerr();
  1106. return "";
  1107. }
  1108. return tag.fields["type"];
  1109. }
  1110. ResourceUID::ID ResourceLoaderText::get_uid(Ref<FileAccess> p_f) {
  1111. error = OK;
  1112. lines = 1;
  1113. f = p_f;
  1114. stream.f = f;
  1115. ignore_resource_parsing = true;
  1116. VariantParser::Tag tag;
  1117. Error err = VariantParser::parse_tag(&stream, lines, error_text, tag);
  1118. if (err) {
  1119. _printerr();
  1120. return ResourceUID::INVALID_ID;
  1121. }
  1122. if (tag.fields.has("uid")) { //field is optional
  1123. String uidt = tag.fields["uid"];
  1124. return ResourceUID::get_singleton()->text_to_id(uidt);
  1125. }
  1126. return ResourceUID::INVALID_ID;
  1127. }
  1128. /////////////////////
  1129. Ref<Resource> ResourceFormatLoaderText::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) {
  1130. if (r_error) {
  1131. *r_error = ERR_CANT_OPEN;
  1132. }
  1133. Error err;
  1134. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err);
  1135. ERR_FAIL_COND_V_MSG(err != OK, Ref<Resource>(), "Cannot open file '" + p_path + "'.");
  1136. ResourceLoaderText loader;
  1137. String path = !p_original_path.is_empty() ? p_original_path : p_path;
  1138. switch (p_cache_mode) {
  1139. case CACHE_MODE_IGNORE:
  1140. case CACHE_MODE_REUSE:
  1141. case CACHE_MODE_REPLACE:
  1142. loader.cache_mode = p_cache_mode;
  1143. loader.cache_mode_for_external = CACHE_MODE_REUSE;
  1144. break;
  1145. case CACHE_MODE_IGNORE_DEEP:
  1146. loader.cache_mode = ResourceFormatLoader::CACHE_MODE_IGNORE;
  1147. loader.cache_mode_for_external = p_cache_mode;
  1148. break;
  1149. case CACHE_MODE_REPLACE_DEEP:
  1150. loader.cache_mode = ResourceFormatLoader::CACHE_MODE_REPLACE;
  1151. loader.cache_mode_for_external = p_cache_mode;
  1152. break;
  1153. }
  1154. loader.use_sub_threads = p_use_sub_threads;
  1155. loader.local_path = ProjectSettings::get_singleton()->localize_path(path);
  1156. loader.progress = r_progress;
  1157. loader.res_path = loader.local_path;
  1158. loader.open(f);
  1159. err = loader.load();
  1160. if (r_error) {
  1161. *r_error = err;
  1162. }
  1163. if (err == OK) {
  1164. return loader.get_resource();
  1165. } else {
  1166. return Ref<Resource>();
  1167. }
  1168. }
  1169. void ResourceFormatLoaderText::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
  1170. if (p_type.is_empty()) {
  1171. get_recognized_extensions(p_extensions);
  1172. return;
  1173. }
  1174. if (ClassDB::is_parent_class("PackedScene", p_type)) {
  1175. p_extensions->push_back("tscn");
  1176. }
  1177. // Don't allow .tres for PackedScenes or GDExtension.
  1178. if (p_type != "PackedScene" && p_type != "GDExtension") {
  1179. p_extensions->push_back("tres");
  1180. }
  1181. }
  1182. void ResourceFormatLoaderText::get_recognized_extensions(List<String> *p_extensions) const {
  1183. p_extensions->push_back("tscn");
  1184. p_extensions->push_back("tres");
  1185. }
  1186. bool ResourceFormatLoaderText::handles_type(const String &p_type) const {
  1187. return true;
  1188. }
  1189. void ResourceFormatLoaderText::get_classes_used(const String &p_path, HashSet<StringName> *r_classes) {
  1190. const String type = get_resource_type(p_path);
  1191. if (!type.is_empty()) {
  1192. r_classes->insert(type);
  1193. }
  1194. // ...for anything else must test...
  1195. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
  1196. if (f.is_null()) {
  1197. return; // Could not read.
  1198. }
  1199. ResourceLoaderText loader;
  1200. loader.local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  1201. loader.res_path = loader.local_path;
  1202. loader.open(f);
  1203. loader.get_classes_used(r_classes);
  1204. }
  1205. String ResourceFormatLoaderText::get_resource_type(const String &p_path) const {
  1206. String ext = p_path.get_extension().to_lower();
  1207. if (ext == "tscn") {
  1208. return "PackedScene";
  1209. } else if (ext != "tres") {
  1210. return String();
  1211. }
  1212. // ...for anything else must test...
  1213. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
  1214. if (f.is_null()) {
  1215. return ""; //could not read
  1216. }
  1217. ResourceLoaderText loader;
  1218. loader.local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  1219. loader.res_path = loader.local_path;
  1220. String r = loader.recognize(f);
  1221. return ClassDB::get_compatibility_remapped_class(r);
  1222. }
  1223. String ResourceFormatLoaderText::get_resource_script_class(const String &p_path) const {
  1224. String ext = p_path.get_extension().to_lower();
  1225. if (ext != "tres") {
  1226. return String();
  1227. }
  1228. // ...for anything else must test...
  1229. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
  1230. if (f.is_null()) {
  1231. return ""; //could not read
  1232. }
  1233. ResourceLoaderText loader;
  1234. loader.local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  1235. loader.res_path = loader.local_path;
  1236. return loader.recognize_script_class(f);
  1237. }
  1238. ResourceUID::ID ResourceFormatLoaderText::get_resource_uid(const String &p_path) const {
  1239. String ext = p_path.get_extension().to_lower();
  1240. if (ext != "tscn" && ext != "tres") {
  1241. return ResourceUID::INVALID_ID;
  1242. }
  1243. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
  1244. if (f.is_null()) {
  1245. return ResourceUID::INVALID_ID; //could not read
  1246. }
  1247. ResourceLoaderText loader;
  1248. loader.local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  1249. loader.res_path = loader.local_path;
  1250. return loader.get_uid(f);
  1251. }
  1252. bool ResourceFormatLoaderText::has_custom_uid_support() const {
  1253. return true;
  1254. }
  1255. void ResourceFormatLoaderText::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  1256. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
  1257. if (f.is_null()) {
  1258. ERR_FAIL();
  1259. }
  1260. ResourceLoaderText loader;
  1261. loader.local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  1262. loader.res_path = loader.local_path;
  1263. loader.get_dependencies(f, p_dependencies, p_add_types);
  1264. }
  1265. Error ResourceFormatLoaderText::rename_dependencies(const String &p_path, const HashMap<String, String> &p_map) {
  1266. Error err = OK;
  1267. {
  1268. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
  1269. if (f.is_null()) {
  1270. ERR_FAIL_V(ERR_CANT_OPEN);
  1271. }
  1272. ResourceLoaderText loader;
  1273. loader.local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  1274. loader.res_path = loader.local_path;
  1275. err = loader.rename_dependencies(f, p_path, p_map);
  1276. }
  1277. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  1278. if (err == OK && da->file_exists(p_path + ".depren")) {
  1279. da->remove(p_path);
  1280. da->rename(p_path + ".depren", p_path);
  1281. }
  1282. return err;
  1283. }
  1284. ResourceFormatLoaderText *ResourceFormatLoaderText::singleton = nullptr;
  1285. /*****************************************************************************************************/
  1286. String ResourceFormatSaverTextInstance::_write_resources(void *ud, const Ref<Resource> &p_resource) {
  1287. ResourceFormatSaverTextInstance *rsi = static_cast<ResourceFormatSaverTextInstance *>(ud);
  1288. return rsi->_write_resource(p_resource);
  1289. }
  1290. String ResourceFormatSaverTextInstance::_write_resource(const Ref<Resource> &res) {
  1291. if (res->get_meta(SNAME("_skip_save_"), false)) {
  1292. return "null";
  1293. }
  1294. if (external_resources.has(res)) {
  1295. return "ExtResource(\"" + external_resources[res] + "\")";
  1296. } else {
  1297. if (internal_resources.has(res)) {
  1298. return "SubResource(\"" + internal_resources[res] + "\")";
  1299. } else if (!res->is_built_in()) {
  1300. if (res->get_path() == local_path) { //circular reference attempt
  1301. return "null";
  1302. }
  1303. //external resource
  1304. String path = relative_paths ? local_path.path_to_file(res->get_path()) : res->get_path();
  1305. return "Resource(\"" + path + "\")";
  1306. } else {
  1307. ERR_FAIL_V_MSG("null", "Resource was not pre cached for the resource section, bug?");
  1308. //internal resource
  1309. }
  1310. }
  1311. }
  1312. void ResourceFormatSaverTextInstance::_find_resources(const Variant &p_variant, bool p_main) {
  1313. switch (p_variant.get_type()) {
  1314. case Variant::OBJECT: {
  1315. Ref<Resource> res = p_variant;
  1316. if (res.is_null() || external_resources.has(res) || res->get_meta(SNAME("_skip_save_"), false)) {
  1317. return;
  1318. }
  1319. if (!p_main && (!bundle_resources) && !res->is_built_in()) {
  1320. if (res->get_path() == local_path) {
  1321. ERR_PRINT("Circular reference to resource being saved found: '" + local_path + "' will be null next time it's loaded.");
  1322. return;
  1323. }
  1324. // Use a numeric ID as a base, because they are sorted in natural order before saving.
  1325. // This increases the chances of thread loading to fetch them first.
  1326. String id = itos(external_resources.size() + 1) + "_" + Resource::generate_scene_unique_id();
  1327. external_resources[res] = id;
  1328. return;
  1329. }
  1330. if (resource_set.has(res)) {
  1331. return;
  1332. }
  1333. resource_set.insert(res);
  1334. List<PropertyInfo> property_list;
  1335. res->get_property_list(&property_list);
  1336. property_list.sort();
  1337. List<PropertyInfo>::Element *I = property_list.front();
  1338. while (I) {
  1339. PropertyInfo pi = I->get();
  1340. if (pi.usage & PROPERTY_USAGE_STORAGE) {
  1341. Variant v = res->get(I->get().name);
  1342. if (pi.usage & PROPERTY_USAGE_RESOURCE_NOT_PERSISTENT) {
  1343. NonPersistentKey npk;
  1344. npk.base = res;
  1345. npk.property = pi.name;
  1346. non_persistent_map[npk] = v;
  1347. Ref<Resource> sres = v;
  1348. if (sres.is_valid()) {
  1349. resource_set.insert(sres);
  1350. saved_resources.push_back(sres);
  1351. } else {
  1352. _find_resources(v);
  1353. }
  1354. } else {
  1355. _find_resources(v);
  1356. }
  1357. }
  1358. I = I->next();
  1359. }
  1360. saved_resources.push_back(res); // Saved after, so the children it needs are available when loaded
  1361. } break;
  1362. case Variant::ARRAY: {
  1363. Array varray = p_variant;
  1364. _find_resources(varray.get_typed_script());
  1365. for (const Variant &var : varray) {
  1366. _find_resources(var);
  1367. }
  1368. } break;
  1369. case Variant::DICTIONARY: {
  1370. Dictionary d = p_variant;
  1371. _find_resources(d.get_typed_key_script());
  1372. _find_resources(d.get_typed_value_script());
  1373. for (const KeyValue<Variant, Variant> &kv : d) {
  1374. // Of course keys should also be cached, after all we can't prevent users from using resources as keys, right?
  1375. // See also ResourceFormatSaverBinaryInstance::_find_resources (when p_variant is of type Variant::DICTIONARY)
  1376. _find_resources(kv.key);
  1377. _find_resources(kv.value);
  1378. }
  1379. } break;
  1380. case Variant::PACKED_BYTE_ARRAY: {
  1381. // Balance between compatibility and performance.
  1382. if (use_compat && p_variant.operator PackedByteArray().size() > 64) {
  1383. use_compat = false;
  1384. }
  1385. } break;
  1386. case Variant::PACKED_VECTOR4_ARRAY: {
  1387. use_compat = false;
  1388. } break;
  1389. default: {
  1390. }
  1391. }
  1392. }
  1393. static String _resource_get_class(Ref<Resource> p_resource) {
  1394. Ref<MissingResource> missing_resource = p_resource;
  1395. if (missing_resource.is_valid()) {
  1396. return missing_resource->get_original_class();
  1397. } else {
  1398. return p_resource->get_class();
  1399. }
  1400. }
  1401. Error ResourceFormatSaverTextInstance::save(const String &p_path, const Ref<Resource> &p_resource, uint32_t p_flags) {
  1402. Resource::seed_scene_unique_id(p_path.hash()); // Seeding for save path should make it deterministic for importers.
  1403. if (p_path.ends_with(".tscn")) {
  1404. packed_scene = p_resource;
  1405. }
  1406. Error err;
  1407. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE, &err);
  1408. ERR_FAIL_COND_V_MSG(err, ERR_CANT_OPEN, "Cannot save file '" + p_path + "'.");
  1409. Ref<FileAccess> _fref(f);
  1410. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  1411. relative_paths = p_flags & ResourceSaver::FLAG_RELATIVE_PATHS;
  1412. skip_editor = p_flags & ResourceSaver::FLAG_OMIT_EDITOR_PROPERTIES;
  1413. bundle_resources = p_flags & ResourceSaver::FLAG_BUNDLE_RESOURCES;
  1414. takeover_paths = p_flags & ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS;
  1415. if (!p_path.begins_with("res://")) {
  1416. takeover_paths = false;
  1417. }
  1418. // Save resources.
  1419. use_compat = true; // _find_resources() changes this.
  1420. _find_resources(p_resource, true);
  1421. if (packed_scene.is_valid()) {
  1422. // Add instances to external resources if saving a packed scene.
  1423. for (int i = 0; i < packed_scene->get_state()->get_node_count(); i++) {
  1424. if (packed_scene->get_state()->is_node_instance_placeholder(i)) {
  1425. continue;
  1426. }
  1427. Ref<PackedScene> instance = packed_scene->get_state()->get_node_instance(i);
  1428. if (instance.is_valid() && !external_resources.has(instance)) {
  1429. int index = external_resources.size() + 1;
  1430. external_resources[instance] = itos(index) + "_" + Resource::generate_scene_unique_id(); // Keep the order for improved thread loading performance.
  1431. }
  1432. }
  1433. }
  1434. {
  1435. String title = packed_scene.is_valid() ? "[gd_scene " : "[gd_resource ";
  1436. if (packed_scene.is_null()) {
  1437. title += "type=\"" + _resource_get_class(p_resource) + "\" ";
  1438. Ref<Script> script = p_resource->get_script();
  1439. if (script.is_valid() && script->get_global_name()) {
  1440. title += "script_class=\"" + String(script->get_global_name()) + "\" ";
  1441. }
  1442. }
  1443. int load_steps = saved_resources.size() + external_resources.size();
  1444. if (load_steps > 1) {
  1445. title += "load_steps=" + itos(load_steps) + " ";
  1446. }
  1447. title += "format=" + itos(use_compat ? ResourceLoaderText::FORMAT_VERSION_COMPAT : ResourceLoaderText::FORMAT_VERSION) + "";
  1448. ResourceUID::ID uid = ResourceSaver::get_resource_id_for_path(local_path, true);
  1449. if (uid != ResourceUID::INVALID_ID) {
  1450. title += " uid=\"" + ResourceUID::get_singleton()->id_to_text(uid) + "\"";
  1451. }
  1452. f->store_string(title);
  1453. f->store_line("]\n"); // One empty line.
  1454. }
  1455. #ifdef TOOLS_ENABLED
  1456. // Keep order from cached ids.
  1457. HashSet<String> cached_ids_found;
  1458. for (KeyValue<Ref<Resource>, String> &E : external_resources) {
  1459. String cached_id = E.key->get_id_for_path(local_path);
  1460. if (cached_id.is_empty() || cached_ids_found.has(cached_id)) {
  1461. int sep_pos = E.value.find_char('_');
  1462. if (sep_pos != -1) {
  1463. E.value = E.value.substr(0, sep_pos + 1); // Keep the order found, for improved thread loading performance.
  1464. } else {
  1465. E.value = "";
  1466. }
  1467. } else {
  1468. E.value = cached_id;
  1469. cached_ids_found.insert(cached_id);
  1470. }
  1471. }
  1472. // Create IDs for non cached resources.
  1473. for (KeyValue<Ref<Resource>, String> &E : external_resources) {
  1474. if (cached_ids_found.has(E.value)) { // Already cached, go on.
  1475. continue;
  1476. }
  1477. String attempt;
  1478. while (true) {
  1479. attempt = E.value + Resource::generate_scene_unique_id();
  1480. if (!cached_ids_found.has(attempt)) {
  1481. break;
  1482. }
  1483. }
  1484. cached_ids_found.insert(attempt);
  1485. E.value = attempt;
  1486. // Update also in resource.
  1487. Ref<Resource> res = E.key;
  1488. res->set_id_for_path(local_path, attempt);
  1489. }
  1490. #else
  1491. // Make sure to start from one, as it makes format more readable.
  1492. int counter = 1;
  1493. for (KeyValue<Ref<Resource>, String> &E : external_resources) {
  1494. E.value = itos(counter++);
  1495. }
  1496. #endif
  1497. Vector<ResourceSort> sorted_er;
  1498. for (const KeyValue<Ref<Resource>, String> &E : external_resources) {
  1499. ResourceSort rs;
  1500. rs.resource = E.key;
  1501. rs.id = E.value;
  1502. sorted_er.push_back(rs);
  1503. }
  1504. sorted_er.sort();
  1505. for (int i = 0; i < sorted_er.size(); i++) {
  1506. String p = sorted_er[i].resource->get_path();
  1507. String s = "[ext_resource type=\"" + sorted_er[i].resource->get_save_class() + "\"";
  1508. ResourceUID::ID uid = ResourceSaver::get_resource_id_for_path(p, false);
  1509. if (uid != ResourceUID::INVALID_ID) {
  1510. s += " uid=\"" + ResourceUID::get_singleton()->id_to_text(uid) + "\"";
  1511. }
  1512. s += " path=\"" + p + "\" id=\"" + sorted_er[i].id + "\"]\n";
  1513. f->store_string(s); // Bundled.
  1514. }
  1515. if (external_resources.size()) {
  1516. f->store_line(String()); // Separate.
  1517. }
  1518. HashSet<String> used_unique_ids;
  1519. for (List<Ref<Resource>>::Element *E = saved_resources.front(); E; E = E->next()) {
  1520. Ref<Resource> res = E->get();
  1521. if (E->next() && res->is_built_in()) {
  1522. if (!res->get_scene_unique_id().is_empty()) {
  1523. if (used_unique_ids.has(res->get_scene_unique_id())) {
  1524. res->set_scene_unique_id(""); // Repeated.
  1525. } else {
  1526. used_unique_ids.insert(res->get_scene_unique_id());
  1527. }
  1528. }
  1529. }
  1530. }
  1531. for (List<Ref<Resource>>::Element *E = saved_resources.front(); E; E = E->next()) {
  1532. Ref<Resource> res = E->get();
  1533. ERR_CONTINUE(!resource_set.has(res));
  1534. bool main = (E->next() == nullptr);
  1535. if (main && packed_scene.is_valid()) {
  1536. break; // Save as a scene.
  1537. }
  1538. if (main) {
  1539. f->store_line("[resource]");
  1540. } else {
  1541. String line = "[sub_resource ";
  1542. if (res->get_scene_unique_id().is_empty()) {
  1543. String new_id;
  1544. while (true) {
  1545. new_id = _resource_get_class(res) + "_" + Resource::generate_scene_unique_id();
  1546. if (!used_unique_ids.has(new_id)) {
  1547. break;
  1548. }
  1549. }
  1550. res->set_scene_unique_id(new_id);
  1551. used_unique_ids.insert(new_id);
  1552. }
  1553. String id = res->get_scene_unique_id();
  1554. line += "type=\"" + _resource_get_class(res) + "\" id=\"" + id;
  1555. f->store_line(line + "\"]");
  1556. if (takeover_paths) {
  1557. res->set_path(p_path + "::" + id, true);
  1558. }
  1559. internal_resources[res] = id;
  1560. #ifdef TOOLS_ENABLED
  1561. res->set_edited(false);
  1562. #endif
  1563. }
  1564. Dictionary missing_resource_properties = res->get_meta(META_MISSING_RESOURCES, Dictionary());
  1565. List<PropertyInfo> property_list;
  1566. res->get_property_list(&property_list);
  1567. for (const PropertyInfo &pi : property_list) {
  1568. if (skip_editor && pi.name.begins_with("__editor")) {
  1569. continue;
  1570. }
  1571. if (pi.name == META_PROPERTY_MISSING_RESOURCES) {
  1572. continue;
  1573. }
  1574. if (pi.usage & PROPERTY_USAGE_STORAGE || missing_resource_properties.has(pi.name)) {
  1575. String name = pi.name;
  1576. Variant value;
  1577. if (pi.usage & PROPERTY_USAGE_RESOURCE_NOT_PERSISTENT) {
  1578. NonPersistentKey npk;
  1579. npk.base = res;
  1580. npk.property = name;
  1581. if (non_persistent_map.has(npk)) {
  1582. value = non_persistent_map[npk];
  1583. }
  1584. } else {
  1585. value = res->get(name);
  1586. }
  1587. if (pi.type == Variant::OBJECT && missing_resource_properties.has(pi.name)) {
  1588. // Was this missing resource overridden? If so do not save the old value.
  1589. Ref<Resource> ures = value;
  1590. if (ures.is_null()) {
  1591. value = missing_resource_properties[pi.name];
  1592. }
  1593. }
  1594. bool is_script = name == CoreStringName(script);
  1595. Variant default_value = is_script ? Variant() : PropertyUtils::get_property_default_value(res.ptr(), name);
  1596. if (default_value.get_type() != Variant::NIL && bool(Variant::evaluate(Variant::OP_EQUAL, value, default_value))) {
  1597. continue;
  1598. }
  1599. if (pi.type == Variant::OBJECT && value.is_zero() && !(pi.usage & PROPERTY_USAGE_STORE_IF_NULL)) {
  1600. continue;
  1601. }
  1602. String vars;
  1603. VariantWriter::write_to_string(value, vars, _write_resources, this, use_compat);
  1604. f->store_string(name.property_name_encode() + " = " + vars + "\n");
  1605. }
  1606. }
  1607. if (E->next()) {
  1608. f->store_line(String());
  1609. }
  1610. }
  1611. if (packed_scene.is_valid()) {
  1612. // If this is a scene, save nodes and connections!
  1613. Ref<SceneState> state = packed_scene->get_state();
  1614. for (int i = 0; i < state->get_node_count(); i++) {
  1615. StringName type = state->get_node_type(i);
  1616. StringName name = state->get_node_name(i);
  1617. int index = state->get_node_index(i);
  1618. NodePath path = state->get_node_path(i, true);
  1619. NodePath owner = state->get_node_owner_path(i);
  1620. Ref<PackedScene> instance = state->get_node_instance(i);
  1621. String instance_placeholder = state->get_node_instance_placeholder(i);
  1622. Vector<StringName> groups = state->get_node_groups(i);
  1623. Vector<String> deferred_node_paths = state->get_node_deferred_nodepath_properties(i);
  1624. String header = "[node";
  1625. header += " name=\"" + String(name).c_escape() + "\"";
  1626. if (type != StringName()) {
  1627. header += " type=\"" + String(type) + "\"";
  1628. }
  1629. if (path != NodePath()) {
  1630. header += " parent=\"" + String(path.simplified()).c_escape() + "\"";
  1631. }
  1632. if (owner != NodePath() && owner != NodePath(".")) {
  1633. header += " owner=\"" + String(owner.simplified()).c_escape() + "\"";
  1634. }
  1635. if (index >= 0) {
  1636. header += " index=\"" + itos(index) + "\"";
  1637. }
  1638. if (deferred_node_paths.size()) {
  1639. header += " node_paths=" + Variant(deferred_node_paths).get_construct_string();
  1640. }
  1641. if (groups.size()) {
  1642. // Write all groups on the same line as they're part of a section header.
  1643. // This improves readability while not impacting VCS friendliness too much,
  1644. // since it's rare to have more than 5 groups assigned to a single node.
  1645. groups.sort_custom<StringName::AlphCompare>();
  1646. String sgroups = " groups=[";
  1647. for (int j = 0; j < groups.size(); j++) {
  1648. sgroups += "\"" + String(groups[j]).c_escape() + "\"";
  1649. if (j < groups.size() - 1) {
  1650. sgroups += ", ";
  1651. }
  1652. }
  1653. sgroups += "]";
  1654. header += sgroups;
  1655. }
  1656. f->store_string(header);
  1657. if (!instance_placeholder.is_empty()) {
  1658. String vars;
  1659. f->store_string(" instance_placeholder=");
  1660. VariantWriter::write_to_string(instance_placeholder, vars, _write_resources, this, use_compat);
  1661. f->store_string(vars);
  1662. }
  1663. if (instance.is_valid()) {
  1664. String vars;
  1665. f->store_string(" instance=");
  1666. VariantWriter::write_to_string(instance, vars, _write_resources, this, use_compat);
  1667. f->store_string(vars);
  1668. }
  1669. f->store_line("]");
  1670. for (int j = 0; j < state->get_node_property_count(i); j++) {
  1671. String vars;
  1672. VariantWriter::write_to_string(state->get_node_property_value(i, j), vars, _write_resources, this, use_compat);
  1673. f->store_string(String(state->get_node_property_name(i, j)).property_name_encode() + " = " + vars + "\n");
  1674. }
  1675. if (i < state->get_node_count() - 1) {
  1676. f->store_line(String());
  1677. }
  1678. }
  1679. for (int i = 0; i < state->get_connection_count(); i++) {
  1680. if (i == 0) {
  1681. f->store_line("");
  1682. }
  1683. String connstr = "[connection";
  1684. connstr += " signal=\"" + String(state->get_connection_signal(i)).c_escape() + "\"";
  1685. connstr += " from=\"" + String(state->get_connection_source(i).simplified()).c_escape() + "\"";
  1686. connstr += " to=\"" + String(state->get_connection_target(i).simplified()).c_escape() + "\"";
  1687. connstr += " method=\"" + String(state->get_connection_method(i)).c_escape() + "\"";
  1688. int flags = state->get_connection_flags(i);
  1689. if (flags != Object::CONNECT_PERSIST) {
  1690. connstr += " flags=" + itos(flags);
  1691. }
  1692. int unbinds = state->get_connection_unbinds(i);
  1693. if (unbinds > 0) {
  1694. connstr += " unbinds=" + itos(unbinds);
  1695. }
  1696. Array binds = state->get_connection_binds(i);
  1697. f->store_string(connstr);
  1698. if (binds.size()) {
  1699. String vars;
  1700. VariantWriter::write_to_string(binds, vars, _write_resources, this, use_compat);
  1701. f->store_string(" binds= " + vars);
  1702. }
  1703. f->store_line("]");
  1704. }
  1705. Vector<NodePath> editable_instances = state->get_editable_instances();
  1706. for (int i = 0; i < editable_instances.size(); i++) {
  1707. if (i == 0) {
  1708. f->store_line("");
  1709. }
  1710. f->store_line("[editable path=\"" + editable_instances[i].operator String().c_escape() + "\"]");
  1711. }
  1712. }
  1713. if (f->get_error() != OK && f->get_error() != ERR_FILE_EOF) {
  1714. return ERR_CANT_CREATE;
  1715. }
  1716. return OK;
  1717. }
  1718. Error ResourceLoaderText::set_uid(Ref<FileAccess> p_f, ResourceUID::ID p_uid) {
  1719. open(p_f, true);
  1720. ERR_FAIL_COND_V(error != OK, error);
  1721. ignore_resource_parsing = true;
  1722. Ref<FileAccess> fw;
  1723. fw = FileAccess::open(local_path + ".uidren", FileAccess::WRITE);
  1724. if (is_scene) {
  1725. fw->store_string("[gd_scene load_steps=" + itos(resources_total) + " format=" + itos(format_version) + " uid=\"" + ResourceUID::get_singleton()->id_to_text(p_uid) + "\"]");
  1726. } else {
  1727. String script_res_text;
  1728. if (!script_class.is_empty()) {
  1729. script_res_text = "script_class=\"" + script_class + "\" ";
  1730. }
  1731. fw->store_string("[gd_resource type=\"" + res_type + "\" " + script_res_text + "load_steps=" + itos(resources_total) + " format=" + itos(format_version) + " uid=\"" + ResourceUID::get_singleton()->id_to_text(p_uid) + "\"]");
  1732. }
  1733. uint8_t c = f->get_8();
  1734. while (!f->eof_reached()) {
  1735. fw->store_8(c);
  1736. c = f->get_8();
  1737. }
  1738. bool all_ok = fw->get_error() == OK;
  1739. if (!all_ok) {
  1740. return ERR_CANT_CREATE;
  1741. }
  1742. return OK;
  1743. }
  1744. Error ResourceFormatSaverText::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) {
  1745. if (p_path.ends_with(".tscn") && Ref<PackedScene>(p_resource).is_null()) {
  1746. return ERR_FILE_UNRECOGNIZED;
  1747. }
  1748. ResourceFormatSaverTextInstance saver;
  1749. return saver.save(p_path, p_resource, p_flags);
  1750. }
  1751. Error ResourceFormatSaverText::set_uid(const String &p_path, ResourceUID::ID p_uid) {
  1752. String lc = p_path.to_lower();
  1753. if (!lc.ends_with(".tscn") && !lc.ends_with(".tres")) {
  1754. return ERR_FILE_UNRECOGNIZED;
  1755. }
  1756. String local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  1757. Error err = OK;
  1758. {
  1759. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::READ);
  1760. if (file.is_null()) {
  1761. ERR_FAIL_V(ERR_CANT_OPEN);
  1762. }
  1763. ResourceLoaderText loader;
  1764. loader.local_path = local_path;
  1765. loader.res_path = loader.local_path;
  1766. err = loader.set_uid(file, p_uid);
  1767. }
  1768. if (err == OK) {
  1769. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  1770. da->remove(local_path);
  1771. da->rename(local_path + ".uidren", local_path);
  1772. }
  1773. return err;
  1774. }
  1775. bool ResourceFormatSaverText::recognize(const Ref<Resource> &p_resource) const {
  1776. return true; // All resources recognized!
  1777. }
  1778. void ResourceFormatSaverText::get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const {
  1779. if (Ref<PackedScene>(p_resource).is_valid()) {
  1780. p_extensions->push_back("tscn"); // Text scene.
  1781. } else {
  1782. p_extensions->push_back("tres"); // Text resource.
  1783. }
  1784. }
  1785. ResourceFormatSaverText *ResourceFormatSaverText::singleton = nullptr;
  1786. ResourceFormatSaverText::ResourceFormatSaverText() {
  1787. singleton = this;
  1788. }