resource_format_text.cpp 62 KB

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