resource_format_text.cpp 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169
  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. Variant default_value = PropertyUtils::get_property_default_value(res.ptr(), name);
  1595. if (default_value.get_type() != Variant::NIL && bool(Variant::evaluate(Variant::OP_EQUAL, value, default_value))) {
  1596. continue;
  1597. }
  1598. if (pi.type == Variant::OBJECT && value.is_zero() && !(pi.usage & PROPERTY_USAGE_STORE_IF_NULL)) {
  1599. continue;
  1600. }
  1601. String vars;
  1602. VariantWriter::write_to_string(value, vars, _write_resources, this, use_compat);
  1603. f->store_string(name.property_name_encode() + " = " + vars + "\n");
  1604. }
  1605. }
  1606. if (E->next()) {
  1607. f->store_line(String());
  1608. }
  1609. }
  1610. if (packed_scene.is_valid()) {
  1611. // If this is a scene, save nodes and connections!
  1612. Ref<SceneState> state = packed_scene->get_state();
  1613. for (int i = 0; i < state->get_node_count(); i++) {
  1614. StringName type = state->get_node_type(i);
  1615. StringName name = state->get_node_name(i);
  1616. int index = state->get_node_index(i);
  1617. NodePath path = state->get_node_path(i, true);
  1618. NodePath owner = state->get_node_owner_path(i);
  1619. Ref<PackedScene> instance = state->get_node_instance(i);
  1620. String instance_placeholder = state->get_node_instance_placeholder(i);
  1621. Vector<StringName> groups = state->get_node_groups(i);
  1622. Vector<String> deferred_node_paths = state->get_node_deferred_nodepath_properties(i);
  1623. String header = "[node";
  1624. header += " name=\"" + String(name).c_escape() + "\"";
  1625. if (type != StringName()) {
  1626. header += " type=\"" + String(type) + "\"";
  1627. }
  1628. if (path != NodePath()) {
  1629. header += " parent=\"" + String(path.simplified()).c_escape() + "\"";
  1630. }
  1631. if (owner != NodePath() && owner != NodePath(".")) {
  1632. header += " owner=\"" + String(owner.simplified()).c_escape() + "\"";
  1633. }
  1634. if (index >= 0) {
  1635. header += " index=\"" + itos(index) + "\"";
  1636. }
  1637. if (deferred_node_paths.size()) {
  1638. header += " node_paths=" + Variant(deferred_node_paths).get_construct_string();
  1639. }
  1640. if (groups.size()) {
  1641. // Write all groups on the same line as they're part of a section header.
  1642. // This improves readability while not impacting VCS friendliness too much,
  1643. // since it's rare to have more than 5 groups assigned to a single node.
  1644. groups.sort_custom<StringName::AlphCompare>();
  1645. String sgroups = " groups=[";
  1646. for (int j = 0; j < groups.size(); j++) {
  1647. sgroups += "\"" + String(groups[j]).c_escape() + "\"";
  1648. if (j < groups.size() - 1) {
  1649. sgroups += ", ";
  1650. }
  1651. }
  1652. sgroups += "]";
  1653. header += sgroups;
  1654. }
  1655. f->store_string(header);
  1656. if (!instance_placeholder.is_empty()) {
  1657. String vars;
  1658. f->store_string(" instance_placeholder=");
  1659. VariantWriter::write_to_string(instance_placeholder, vars, _write_resources, this, use_compat);
  1660. f->store_string(vars);
  1661. }
  1662. if (instance.is_valid()) {
  1663. String vars;
  1664. f->store_string(" instance=");
  1665. VariantWriter::write_to_string(instance, vars, _write_resources, this, use_compat);
  1666. f->store_string(vars);
  1667. }
  1668. f->store_line("]");
  1669. for (int j = 0; j < state->get_node_property_count(i); j++) {
  1670. String vars;
  1671. VariantWriter::write_to_string(state->get_node_property_value(i, j), vars, _write_resources, this, use_compat);
  1672. f->store_string(String(state->get_node_property_name(i, j)).property_name_encode() + " = " + vars + "\n");
  1673. }
  1674. if (i < state->get_node_count() - 1) {
  1675. f->store_line(String());
  1676. }
  1677. }
  1678. for (int i = 0; i < state->get_connection_count(); i++) {
  1679. if (i == 0) {
  1680. f->store_line("");
  1681. }
  1682. String connstr = "[connection";
  1683. connstr += " signal=\"" + String(state->get_connection_signal(i)).c_escape() + "\"";
  1684. connstr += " from=\"" + String(state->get_connection_source(i).simplified()).c_escape() + "\"";
  1685. connstr += " to=\"" + String(state->get_connection_target(i).simplified()).c_escape() + "\"";
  1686. connstr += " method=\"" + String(state->get_connection_method(i)).c_escape() + "\"";
  1687. int flags = state->get_connection_flags(i);
  1688. if (flags != Object::CONNECT_PERSIST) {
  1689. connstr += " flags=" + itos(flags);
  1690. }
  1691. int unbinds = state->get_connection_unbinds(i);
  1692. if (unbinds > 0) {
  1693. connstr += " unbinds=" + itos(unbinds);
  1694. }
  1695. Array binds = state->get_connection_binds(i);
  1696. f->store_string(connstr);
  1697. if (binds.size()) {
  1698. String vars;
  1699. VariantWriter::write_to_string(binds, vars, _write_resources, this, use_compat);
  1700. f->store_string(" binds= " + vars);
  1701. }
  1702. f->store_line("]");
  1703. }
  1704. Vector<NodePath> editable_instances = state->get_editable_instances();
  1705. for (int i = 0; i < editable_instances.size(); i++) {
  1706. if (i == 0) {
  1707. f->store_line("");
  1708. }
  1709. f->store_line("[editable path=\"" + editable_instances[i].operator String().c_escape() + "\"]");
  1710. }
  1711. }
  1712. if (f->get_error() != OK && f->get_error() != ERR_FILE_EOF) {
  1713. return ERR_CANT_CREATE;
  1714. }
  1715. return OK;
  1716. }
  1717. Error ResourceLoaderText::set_uid(Ref<FileAccess> p_f, ResourceUID::ID p_uid) {
  1718. open(p_f, true);
  1719. ERR_FAIL_COND_V(error != OK, error);
  1720. ignore_resource_parsing = true;
  1721. Ref<FileAccess> fw;
  1722. fw = FileAccess::open(local_path + ".uidren", FileAccess::WRITE);
  1723. if (is_scene) {
  1724. fw->store_string("[gd_scene load_steps=" + itos(resources_total) + " format=" + itos(format_version) + " uid=\"" + ResourceUID::get_singleton()->id_to_text(p_uid) + "\"]");
  1725. } else {
  1726. String script_res_text;
  1727. if (!script_class.is_empty()) {
  1728. script_res_text = "script_class=\"" + script_class + "\" ";
  1729. }
  1730. 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) + "\"]");
  1731. }
  1732. uint8_t c = f->get_8();
  1733. while (!f->eof_reached()) {
  1734. fw->store_8(c);
  1735. c = f->get_8();
  1736. }
  1737. bool all_ok = fw->get_error() == OK;
  1738. if (!all_ok) {
  1739. return ERR_CANT_CREATE;
  1740. }
  1741. return OK;
  1742. }
  1743. Error ResourceFormatSaverText::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) {
  1744. if (p_path.ends_with(".tscn") && Ref<PackedScene>(p_resource).is_null()) {
  1745. return ERR_FILE_UNRECOGNIZED;
  1746. }
  1747. ResourceFormatSaverTextInstance saver;
  1748. return saver.save(p_path, p_resource, p_flags);
  1749. }
  1750. Error ResourceFormatSaverText::set_uid(const String &p_path, ResourceUID::ID p_uid) {
  1751. String lc = p_path.to_lower();
  1752. if (!lc.ends_with(".tscn") && !lc.ends_with(".tres")) {
  1753. return ERR_FILE_UNRECOGNIZED;
  1754. }
  1755. String local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  1756. Error err = OK;
  1757. {
  1758. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::READ);
  1759. if (file.is_null()) {
  1760. ERR_FAIL_V(ERR_CANT_OPEN);
  1761. }
  1762. ResourceLoaderText loader;
  1763. loader.local_path = local_path;
  1764. loader.res_path = loader.local_path;
  1765. err = loader.set_uid(file, p_uid);
  1766. }
  1767. if (err == OK) {
  1768. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  1769. da->remove(local_path);
  1770. da->rename(local_path + ".uidren", local_path);
  1771. }
  1772. return err;
  1773. }
  1774. bool ResourceFormatSaverText::recognize(const Ref<Resource> &p_resource) const {
  1775. return true; // All resources recognized!
  1776. }
  1777. void ResourceFormatSaverText::get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const {
  1778. if (Ref<PackedScene>(p_resource).is_valid()) {
  1779. p_extensions->push_back("tscn"); // Text scene.
  1780. } else {
  1781. p_extensions->push_back("tres"); // Text resource.
  1782. }
  1783. }
  1784. ResourceFormatSaverText *ResourceFormatSaverText::singleton = nullptr;
  1785. ResourceFormatSaverText::ResourceFormatSaverText() {
  1786. singleton = this;
  1787. }