2
0

resource_format_text.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785
  1. /*************************************************************************/
  2. /* resource_format_text.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  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/io/resource_format_binary.h"
  32. #include "core/os/dir_access.h"
  33. #include "core/project_settings.h"
  34. #include "core/version.h"
  35. //version 2: changed names for basis, aabb, poolvectors, etc.
  36. #define FORMAT_VERSION 2
  37. #include "core/os/dir_access.h"
  38. #include "core/version.h"
  39. #define _printerr() ERR_PRINT(String(res_path + ":" + itos(lines) + " - Parse Error: " + error_text).utf8().get_data());
  40. ///
  41. void ResourceInteractiveLoaderText::set_local_path(const String &p_local_path) {
  42. res_path = p_local_path;
  43. }
  44. Ref<Resource> ResourceInteractiveLoaderText::get_resource() {
  45. return resource;
  46. }
  47. Error ResourceInteractiveLoaderText::_parse_sub_resource_dummy(DummyReadData *p_data, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
  48. VariantParser::Token token;
  49. VariantParser::get_token(p_stream, token, line, r_err_str);
  50. if (token.type != VariantParser::TK_NUMBER) {
  51. r_err_str = "Expected number (sub-resource index)";
  52. return ERR_PARSE_ERROR;
  53. }
  54. int index = token.value;
  55. if (!p_data->resource_map.has(index)) {
  56. Ref<DummyResource> dr;
  57. dr.instance();
  58. dr->set_subindex(index);
  59. p_data->resource_map[index] = dr;
  60. p_data->resource_set.insert(dr);
  61. }
  62. r_res = p_data->resource_map[index];
  63. VariantParser::get_token(p_stream, token, line, r_err_str);
  64. if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
  65. r_err_str = "Expected ')'";
  66. return ERR_PARSE_ERROR;
  67. }
  68. return OK;
  69. }
  70. Error ResourceInteractiveLoaderText::_parse_ext_resource_dummy(DummyReadData *p_data, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
  71. VariantParser::Token token;
  72. VariantParser::get_token(p_stream, token, line, r_err_str);
  73. if (token.type != VariantParser::TK_NUMBER) {
  74. r_err_str = "Expected number (sub-resource index)";
  75. return ERR_PARSE_ERROR;
  76. }
  77. int id = token.value;
  78. ERR_FAIL_COND_V(!p_data->rev_external_resources.has(id), ERR_PARSE_ERROR);
  79. r_res = p_data->rev_external_resources[id];
  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 ResourceInteractiveLoaderText::_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) {
  91. r_err_str = "Expected number (sub-resource index)";
  92. return ERR_PARSE_ERROR;
  93. }
  94. int index = token.value;
  95. String path = local_path + "::" + itos(index);
  96. if (!ignore_resource_parsing) {
  97. if (!ResourceCache::has(path)) {
  98. r_err_str = "Can't load cached sub-resource: " + path;
  99. return ERR_PARSE_ERROR;
  100. }
  101. r_res = RES(ResourceCache::get(path));
  102. } else {
  103. r_res = RES();
  104. }
  105. VariantParser::get_token(p_stream, token, line, r_err_str);
  106. if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
  107. r_err_str = "Expected ')'";
  108. return ERR_PARSE_ERROR;
  109. }
  110. return OK;
  111. }
  112. Error ResourceInteractiveLoaderText::_parse_ext_resource(VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
  113. VariantParser::Token token;
  114. VariantParser::get_token(p_stream, token, line, r_err_str);
  115. if (token.type != VariantParser::TK_NUMBER) {
  116. r_err_str = "Expected number (sub-resource index)";
  117. return ERR_PARSE_ERROR;
  118. }
  119. int id = token.value;
  120. if (!ignore_resource_parsing) {
  121. if (!ext_resources.has(id)) {
  122. r_err_str = "Can't load cached ext-resource #" + itos(id);
  123. return ERR_PARSE_ERROR;
  124. }
  125. String path = ext_resources[id].path;
  126. String type = ext_resources[id].type;
  127. if (path.find("://") == -1 && path.is_rel_path()) {
  128. // path is relative to file being loaded, so convert to a resource path
  129. path = ProjectSettings::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path));
  130. }
  131. r_res = ResourceLoader::load(path, type);
  132. if (r_res.is_null()) {
  133. WARN_PRINT(String("Couldn't load external resource: " + path).utf8().get_data());
  134. }
  135. } else {
  136. r_res = RES();
  137. }
  138. VariantParser::get_token(p_stream, token, line, r_err_str);
  139. if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
  140. r_err_str = "Expected ')'";
  141. return ERR_PARSE_ERROR;
  142. }
  143. return OK;
  144. }
  145. Ref<PackedScene> ResourceInteractiveLoaderText::_parse_node_tag(VariantParser::ResourceParser &parser) {
  146. Ref<PackedScene> packed_scene;
  147. packed_scene.instance();
  148. while (true) {
  149. if (next_tag.name == "node") {
  150. int parent = -1;
  151. int owner = -1;
  152. int type = -1;
  153. int name = -1;
  154. int instance = -1;
  155. int index = -1;
  156. //int base_scene=-1;
  157. if (next_tag.fields.has("name")) {
  158. name = packed_scene->get_state()->add_name(next_tag.fields["name"]);
  159. }
  160. if (next_tag.fields.has("parent")) {
  161. NodePath np = next_tag.fields["parent"];
  162. np.prepend_period(); //compatible to how it manages paths internally
  163. parent = packed_scene->get_state()->add_node_path(np);
  164. }
  165. if (next_tag.fields.has("type")) {
  166. type = packed_scene->get_state()->add_name(next_tag.fields["type"]);
  167. } else {
  168. type = SceneState::TYPE_INSTANCED; //no type? assume this was instanced
  169. }
  170. if (next_tag.fields.has("instance")) {
  171. instance = packed_scene->get_state()->add_value(next_tag.fields["instance"]);
  172. if (packed_scene->get_state()->get_node_count() == 0 && parent == -1) {
  173. packed_scene->get_state()->set_base_scene(instance);
  174. instance = -1;
  175. }
  176. }
  177. if (next_tag.fields.has("instance_placeholder")) {
  178. String path = next_tag.fields["instance_placeholder"];
  179. int path_v = packed_scene->get_state()->add_value(path);
  180. if (packed_scene->get_state()->get_node_count() == 0) {
  181. error = ERR_FILE_CORRUPT;
  182. error_text = "Instance Placeholder can't be used for inheritance.";
  183. _printerr();
  184. return Ref<PackedScene>();
  185. }
  186. instance = path_v | SceneState::FLAG_INSTANCE_IS_PLACEHOLDER;
  187. }
  188. if (next_tag.fields.has("owner")) {
  189. owner = packed_scene->get_state()->add_node_path(next_tag.fields["owner"]);
  190. } else {
  191. if (parent != -1 && !(type == SceneState::TYPE_INSTANCED && instance == -1))
  192. owner = 0; //if no owner, owner is root
  193. }
  194. if (next_tag.fields.has("index")) {
  195. index = next_tag.fields["index"];
  196. }
  197. int node_id = packed_scene->get_state()->add_node(parent, owner, type, name, instance, index);
  198. if (next_tag.fields.has("groups")) {
  199. Array groups = next_tag.fields["groups"];
  200. for (int i = 0; i < groups.size(); i++) {
  201. packed_scene->get_state()->add_node_group(node_id, packed_scene->get_state()->add_name(groups[i]));
  202. }
  203. }
  204. while (true) {
  205. String assign;
  206. Variant value;
  207. error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &parser);
  208. if (error) {
  209. if (error != ERR_FILE_EOF) {
  210. _printerr();
  211. return Ref<PackedScene>();
  212. } else {
  213. return packed_scene;
  214. }
  215. }
  216. if (assign != String()) {
  217. int nameidx = packed_scene->get_state()->add_name(assign);
  218. int valueidx = packed_scene->get_state()->add_value(value);
  219. packed_scene->get_state()->add_node_property(node_id, nameidx, valueidx);
  220. //it's assignment
  221. } else if (next_tag.name != String()) {
  222. break;
  223. }
  224. }
  225. } else if (next_tag.name == "connection") {
  226. if (!next_tag.fields.has("from")) {
  227. error = ERR_FILE_CORRUPT;
  228. error_text = "missing 'from' field from connection tag";
  229. return Ref<PackedScene>();
  230. }
  231. if (!next_tag.fields.has("to")) {
  232. error = ERR_FILE_CORRUPT;
  233. error_text = "missing 'to' field from connection tag";
  234. return Ref<PackedScene>();
  235. }
  236. if (!next_tag.fields.has("signal")) {
  237. error = ERR_FILE_CORRUPT;
  238. error_text = "missing 'signal' field from connection tag";
  239. return Ref<PackedScene>();
  240. }
  241. if (!next_tag.fields.has("method")) {
  242. error = ERR_FILE_CORRUPT;
  243. error_text = "missing 'method' field from connection tag";
  244. return Ref<PackedScene>();
  245. }
  246. NodePath from = next_tag.fields["from"];
  247. NodePath to = next_tag.fields["to"];
  248. StringName method = next_tag.fields["method"];
  249. StringName signal = next_tag.fields["signal"];
  250. int flags = CONNECT_PERSIST;
  251. Array binds;
  252. if (next_tag.fields.has("flags")) {
  253. flags = next_tag.fields["flags"];
  254. }
  255. if (next_tag.fields.has("binds")) {
  256. binds = next_tag.fields["binds"];
  257. }
  258. Vector<int> bind_ints;
  259. for (int i = 0; i < binds.size(); i++) {
  260. bind_ints.push_back(packed_scene->get_state()->add_value(binds[i]));
  261. }
  262. packed_scene->get_state()->add_connection(
  263. packed_scene->get_state()->add_node_path(from.simplified()),
  264. packed_scene->get_state()->add_node_path(to.simplified()),
  265. packed_scene->get_state()->add_name(signal),
  266. packed_scene->get_state()->add_name(method),
  267. flags,
  268. bind_ints);
  269. error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &parser);
  270. if (error) {
  271. if (error != ERR_FILE_EOF) {
  272. _printerr();
  273. return Ref<PackedScene>();
  274. } else {
  275. return packed_scene;
  276. }
  277. }
  278. } else if (next_tag.name == "editable") {
  279. if (!next_tag.fields.has("path")) {
  280. error = ERR_FILE_CORRUPT;
  281. error_text = "missing 'path' field from connection tag";
  282. _printerr();
  283. return Ref<PackedScene>();
  284. }
  285. NodePath path = next_tag.fields["path"];
  286. packed_scene->get_state()->add_editable_instance(path.simplified());
  287. error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &parser);
  288. if (error) {
  289. if (error != ERR_FILE_EOF) {
  290. _printerr();
  291. return Ref<PackedScene>();
  292. } else {
  293. return packed_scene;
  294. }
  295. }
  296. } else {
  297. error = ERR_FILE_CORRUPT;
  298. _printerr();
  299. return Ref<PackedScene>();
  300. }
  301. }
  302. return packed_scene;
  303. }
  304. Error ResourceInteractiveLoaderText::poll() {
  305. if (error != OK)
  306. return error;
  307. if (next_tag.name == "ext_resource") {
  308. if (!next_tag.fields.has("path")) {
  309. error = ERR_FILE_CORRUPT;
  310. error_text = "Missing 'path' in external resource tag";
  311. _printerr();
  312. return error;
  313. }
  314. if (!next_tag.fields.has("type")) {
  315. error = ERR_FILE_CORRUPT;
  316. error_text = "Missing 'type' in external resource tag";
  317. _printerr();
  318. return error;
  319. }
  320. if (!next_tag.fields.has("id")) {
  321. error = ERR_FILE_CORRUPT;
  322. error_text = "Missing 'id' in external resource tag";
  323. _printerr();
  324. return error;
  325. }
  326. String path = next_tag.fields["path"];
  327. String type = next_tag.fields["type"];
  328. int index = next_tag.fields["id"];
  329. if (path.find("://") == -1 && path.is_rel_path()) {
  330. // path is relative to file being loaded, so convert to a resource path
  331. path = ProjectSettings::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path));
  332. }
  333. if (remaps.has(path)) {
  334. path = remaps[path];
  335. }
  336. RES res = ResourceLoader::load(path, type);
  337. if (res.is_null()) {
  338. if (ResourceLoader::get_abort_on_missing_resources()) {
  339. error = ERR_FILE_CORRUPT;
  340. error_text = "[ext_resource] referenced nonexistent resource at: " + path;
  341. _printerr();
  342. return error;
  343. } else {
  344. ResourceLoader::notify_dependency_error(local_path, path, type);
  345. }
  346. } else {
  347. resource_cache.push_back(res);
  348. }
  349. ExtResource er;
  350. er.path = path;
  351. er.type = type;
  352. ext_resources[index] = er;
  353. error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
  354. if (error) {
  355. _printerr();
  356. }
  357. resource_current++;
  358. return error;
  359. } else if (next_tag.name == "sub_resource") {
  360. if (!next_tag.fields.has("type")) {
  361. error = ERR_FILE_CORRUPT;
  362. error_text = "Missing 'type' in external resource tag";
  363. _printerr();
  364. return error;
  365. }
  366. if (!next_tag.fields.has("id")) {
  367. error = ERR_FILE_CORRUPT;
  368. error_text = "Missing 'index' in external resource tag";
  369. _printerr();
  370. return error;
  371. }
  372. String type = next_tag.fields["type"];
  373. int id = next_tag.fields["id"];
  374. String path = local_path + "::" + itos(id);
  375. //bool exists=ResourceCache::has(path);
  376. Ref<Resource> res;
  377. if (!ResourceCache::has(path)) { //only if it doesn't exist
  378. Object *obj = ClassDB::instance(type);
  379. if (!obj) {
  380. error_text += "Can't create sub resource of type: " + type;
  381. _printerr();
  382. error = ERR_FILE_CORRUPT;
  383. return error;
  384. }
  385. Resource *r = Object::cast_to<Resource>(obj);
  386. if (!r) {
  387. error_text += "Can't create sub resource of type, because not a resource: " + type;
  388. _printerr();
  389. error = ERR_FILE_CORRUPT;
  390. return error;
  391. }
  392. res = Ref<Resource>(r);
  393. resource_cache.push_back(res);
  394. res->set_path(path);
  395. }
  396. resource_current++;
  397. while (true) {
  398. String assign;
  399. Variant value;
  400. error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp);
  401. if (error) {
  402. _printerr();
  403. return error;
  404. }
  405. if (assign != String()) {
  406. if (res.is_valid()) {
  407. res->set(assign, value);
  408. }
  409. //it's assignment
  410. } else if (next_tag.name != String()) {
  411. error = OK;
  412. break;
  413. } else {
  414. error = ERR_FILE_CORRUPT;
  415. error_text = "Premature end of file while parsing [sub_resource]";
  416. _printerr();
  417. return error;
  418. }
  419. }
  420. return OK;
  421. } else if (next_tag.name == "resource") {
  422. if (is_scene) {
  423. error_text += "found the 'resource' tag on a scene file!";
  424. _printerr();
  425. error = ERR_FILE_CORRUPT;
  426. return error;
  427. }
  428. Object *obj = ClassDB::instance(res_type);
  429. if (!obj) {
  430. error_text += "Can't create sub resource of type: " + res_type;
  431. _printerr();
  432. error = ERR_FILE_CORRUPT;
  433. return error;
  434. }
  435. Resource *r = Object::cast_to<Resource>(obj);
  436. if (!r) {
  437. error_text += "Can't create sub resource of type, because not a resource: " + res_type;
  438. _printerr();
  439. error = ERR_FILE_CORRUPT;
  440. return error;
  441. }
  442. resource = Ref<Resource>(r);
  443. resource_current++;
  444. while (true) {
  445. String assign;
  446. Variant value;
  447. error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp);
  448. if (error) {
  449. if (error != ERR_FILE_EOF) {
  450. _printerr();
  451. } else {
  452. if (!ResourceCache::has(res_path)) {
  453. resource->set_path(res_path);
  454. }
  455. resource->set_as_translation_remapped(translation_remapped);
  456. }
  457. return error;
  458. }
  459. if (assign != String()) {
  460. resource->set(assign, value);
  461. //it's assignment
  462. } else if (next_tag.name != String()) {
  463. error = ERR_FILE_CORRUPT;
  464. error_text = "Extra tag found when parsing main resource file";
  465. _printerr();
  466. return error;
  467. } else {
  468. error = ERR_FILE_EOF;
  469. return error;
  470. }
  471. }
  472. return OK;
  473. } else if (next_tag.name == "node") {
  474. if (!is_scene) {
  475. error_text += "found the 'node' tag on a resource file!";
  476. _printerr();
  477. error = ERR_FILE_CORRUPT;
  478. return error;
  479. }
  480. Ref<PackedScene> packed_scene = _parse_node_tag(rp);
  481. if (!packed_scene.is_valid())
  482. return error;
  483. error = ERR_FILE_EOF;
  484. //get it here
  485. resource = packed_scene;
  486. if (!ResourceCache::has(res_path)) {
  487. packed_scene->set_path(res_path);
  488. }
  489. return error;
  490. } else {
  491. error_text += "Unknown tag in file: " + next_tag.name;
  492. _printerr();
  493. error = ERR_FILE_CORRUPT;
  494. return error;
  495. }
  496. return OK;
  497. }
  498. int ResourceInteractiveLoaderText::get_stage() const {
  499. return resource_current;
  500. }
  501. int ResourceInteractiveLoaderText::get_stage_count() const {
  502. return resources_total; //+ext_resources;
  503. }
  504. void ResourceInteractiveLoaderText::set_translation_remapped(bool p_remapped) {
  505. translation_remapped = p_remapped;
  506. }
  507. ResourceInteractiveLoaderText::ResourceInteractiveLoaderText() {
  508. translation_remapped = false;
  509. }
  510. ResourceInteractiveLoaderText::~ResourceInteractiveLoaderText() {
  511. memdelete(f);
  512. }
  513. void ResourceInteractiveLoaderText::get_dependencies(FileAccess *p_f, List<String> *p_dependencies, bool p_add_types) {
  514. open(p_f);
  515. ignore_resource_parsing = true;
  516. ERR_FAIL_COND(error != OK);
  517. while (next_tag.name == "ext_resource") {
  518. if (!next_tag.fields.has("type")) {
  519. error = ERR_FILE_CORRUPT;
  520. error_text = "Missing 'type' in external resource tag";
  521. _printerr();
  522. return;
  523. }
  524. if (!next_tag.fields.has("id")) {
  525. error = ERR_FILE_CORRUPT;
  526. error_text = "Missing 'index' in external resource tag";
  527. _printerr();
  528. return;
  529. }
  530. String path = next_tag.fields["path"];
  531. String type = next_tag.fields["type"];
  532. if (path.find("://") == -1 && path.is_rel_path()) {
  533. // path is relative to file being loaded, so convert to a resource path
  534. path = ProjectSettings::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path));
  535. }
  536. if (p_add_types) {
  537. path += "::" + type;
  538. }
  539. p_dependencies->push_back(path);
  540. Error err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
  541. if (err) {
  542. print_line(error_text + " - " + itos(lines));
  543. error_text = "Unexpected end of file";
  544. _printerr();
  545. error = ERR_FILE_CORRUPT;
  546. }
  547. }
  548. }
  549. Error ResourceInteractiveLoaderText::rename_dependencies(FileAccess *p_f, const String &p_path, const Map<String, String> &p_map) {
  550. open(p_f, true);
  551. ERR_FAIL_COND_V(error != OK, error);
  552. ignore_resource_parsing = true;
  553. //FileAccess
  554. FileAccess *fw = NULL;
  555. String base_path = local_path.get_base_dir();
  556. uint64_t tag_end = f->get_position();
  557. while (true) {
  558. Error err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
  559. if (err != OK) {
  560. if (fw) {
  561. memdelete(fw);
  562. }
  563. error = ERR_FILE_CORRUPT;
  564. ERR_FAIL_V(error);
  565. }
  566. if (next_tag.name != "ext_resource") {
  567. //nothing was done
  568. if (!fw)
  569. return OK;
  570. break;
  571. } else {
  572. if (!fw) {
  573. fw = FileAccess::open(p_path + ".depren", FileAccess::WRITE);
  574. if (is_scene) {
  575. fw->store_line("[gd_scene load_steps=" + itos(resources_total) + " format=" + itos(FORMAT_VERSION) + "]\n");
  576. } else {
  577. fw->store_line("[gd_resource type=\"" + res_type + "\" load_steps=" + itos(resources_total) + " format=" + itos(FORMAT_VERSION) + "]\n");
  578. }
  579. }
  580. if (!next_tag.fields.has("path") || !next_tag.fields.has("id") || !next_tag.fields.has("type")) {
  581. memdelete(fw);
  582. error = ERR_FILE_CORRUPT;
  583. ERR_FAIL_V(error);
  584. }
  585. String path = next_tag.fields["path"];
  586. int index = next_tag.fields["id"];
  587. String type = next_tag.fields["type"];
  588. bool relative = false;
  589. if (!path.begins_with("res://")) {
  590. path = base_path.plus_file(path).simplify_path();
  591. relative = true;
  592. }
  593. if (p_map.has(path)) {
  594. String np = p_map[path];
  595. path = np;
  596. }
  597. if (relative) {
  598. //restore relative
  599. path = base_path.path_to_file(path);
  600. }
  601. fw->store_line("[ext_resource path=\"" + path + "\" type=\"" + type + "\" id=" + itos(index) + "]");
  602. tag_end = f->get_position();
  603. }
  604. }
  605. f->seek(tag_end);
  606. uint8_t c = f->get_8();
  607. while (!f->eof_reached()) {
  608. fw->store_8(c);
  609. c = f->get_8();
  610. }
  611. f->close();
  612. bool all_ok = fw->get_error() == OK;
  613. memdelete(fw);
  614. if (!all_ok) {
  615. return ERR_CANT_CREATE;
  616. }
  617. DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  618. da->remove(p_path);
  619. da->rename(p_path + ".depren", p_path);
  620. memdelete(da);
  621. return OK;
  622. }
  623. void ResourceInteractiveLoaderText::open(FileAccess *p_f, bool p_skip_first_tag) {
  624. error = OK;
  625. lines = 1;
  626. f = p_f;
  627. stream.f = f;
  628. is_scene = false;
  629. ignore_resource_parsing = false;
  630. resource_current = 0;
  631. VariantParser::Tag tag;
  632. Error err = VariantParser::parse_tag(&stream, lines, error_text, tag);
  633. if (err) {
  634. error = err;
  635. _printerr();
  636. return;
  637. }
  638. if (tag.fields.has("format")) {
  639. int fmt = tag.fields["format"];
  640. if (fmt > FORMAT_VERSION) {
  641. error_text = "Saved with newer format version";
  642. _printerr();
  643. error = ERR_PARSE_ERROR;
  644. return;
  645. }
  646. }
  647. if (tag.name == "gd_scene") {
  648. is_scene = true;
  649. } else if (tag.name == "gd_resource") {
  650. if (!tag.fields.has("type")) {
  651. error_text = "Missing 'type' field in 'gd_resource' tag";
  652. _printerr();
  653. error = ERR_PARSE_ERROR;
  654. return;
  655. }
  656. res_type = tag.fields["type"];
  657. } else {
  658. error_text = "Unrecognized file type: " + tag.name;
  659. _printerr();
  660. error = ERR_PARSE_ERROR;
  661. return;
  662. }
  663. if (tag.fields.has("load_steps")) {
  664. resources_total = tag.fields["load_steps"];
  665. } else {
  666. resources_total = 0;
  667. }
  668. if (!p_skip_first_tag) {
  669. err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
  670. if (err) {
  671. error_text = "Unexpected end of file";
  672. _printerr();
  673. error = ERR_FILE_CORRUPT;
  674. }
  675. }
  676. rp.ext_func = _parse_ext_resources;
  677. rp.sub_func = _parse_sub_resources;
  678. rp.func = NULL;
  679. rp.userdata = this;
  680. }
  681. static void bs_save_unicode_string(FileAccess *f, const String &p_string, bool p_bit_on_len = false) {
  682. CharString utf8 = p_string.utf8();
  683. if (p_bit_on_len) {
  684. f->store_32((utf8.length() + 1) | 0x80000000);
  685. } else {
  686. f->store_32(utf8.length() + 1);
  687. }
  688. f->store_buffer((const uint8_t *)utf8.get_data(), utf8.length() + 1);
  689. }
  690. Error ResourceInteractiveLoaderText::save_as_binary(FileAccess *p_f, const String &p_path) {
  691. if (error)
  692. return error;
  693. FileAccessRef wf = FileAccess::open(p_path, FileAccess::WRITE);
  694. if (!wf) {
  695. return ERR_CANT_OPEN;
  696. }
  697. //save header compressed
  698. static const uint8_t header[4] = { 'R', 'S', 'R', 'C' };
  699. wf->store_buffer(header, 4);
  700. wf->store_32(0); //endianness, little endian
  701. wf->store_32(0); //64 bits file, false for now
  702. wf->store_32(VERSION_MAJOR);
  703. wf->store_32(VERSION_MINOR);
  704. static const int save_format_version = 3; //use format version 3 for saving
  705. wf->store_32(save_format_version);
  706. bs_save_unicode_string(wf.f, is_scene ? "PackedScene" : resource_type);
  707. wf->store_64(0); //offset to import metadata, this is no longer used
  708. for (int i = 0; i < 14; i++)
  709. wf->store_32(0); // reserved
  710. wf->store_32(0); //string table size, will not be in use
  711. size_t ext_res_count_pos = wf->get_position();
  712. wf->store_32(0); //zero ext resources, still parsing them
  713. //go with external resources
  714. DummyReadData dummy_read;
  715. VariantParser::ResourceParser rp;
  716. rp.ext_func = _parse_ext_resource_dummys;
  717. rp.sub_func = _parse_sub_resource_dummys;
  718. rp.userdata = &dummy_read;
  719. while (next_tag.name == "ext_resource") {
  720. if (!next_tag.fields.has("path")) {
  721. error = ERR_FILE_CORRUPT;
  722. error_text = "Missing 'path' in external resource tag";
  723. _printerr();
  724. return error;
  725. }
  726. if (!next_tag.fields.has("type")) {
  727. error = ERR_FILE_CORRUPT;
  728. error_text = "Missing 'type' in external resource tag";
  729. _printerr();
  730. return error;
  731. }
  732. if (!next_tag.fields.has("id")) {
  733. error = ERR_FILE_CORRUPT;
  734. error_text = "Missing 'id' in external resource tag";
  735. _printerr();
  736. return error;
  737. }
  738. String path = next_tag.fields["path"];
  739. String type = next_tag.fields["type"];
  740. int index = next_tag.fields["id"];
  741. bs_save_unicode_string(wf.f, type);
  742. bs_save_unicode_string(wf.f, path);
  743. int lindex = dummy_read.external_resources.size();
  744. Ref<DummyResource> dr;
  745. dr.instance();
  746. dr->set_path("res://dummy" + itos(lindex)); //anything is good to detect it for saving as external
  747. dummy_read.external_resources[dr] = lindex;
  748. dummy_read.rev_external_resources[index] = dr;
  749. error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
  750. if (error) {
  751. _printerr();
  752. return error;
  753. }
  754. }
  755. // save external resource table
  756. wf->seek(ext_res_count_pos);
  757. wf->store_32(dummy_read.external_resources.size());
  758. wf->seek_end();
  759. //now, save resources to a separate file, for now
  760. size_t sub_res_count_pos = wf->get_position();
  761. wf->store_32(0); //zero sub resources, still parsing them
  762. String temp_file = p_path + ".temp";
  763. FileAccessRef wf2 = FileAccess::open(temp_file, FileAccess::WRITE);
  764. if (!wf2) {
  765. return ERR_CANT_OPEN;
  766. }
  767. Vector<size_t> local_offsets;
  768. Vector<size_t> local_pointers_pos;
  769. while (next_tag.name == "sub_resource" || next_tag.name == "resource") {
  770. String type;
  771. int id = -1;
  772. bool main_res;
  773. if (next_tag.name == "sub_resource") {
  774. if (!next_tag.fields.has("type")) {
  775. error = ERR_FILE_CORRUPT;
  776. error_text = "Missing 'type' in external resource tag";
  777. _printerr();
  778. return error;
  779. }
  780. if (!next_tag.fields.has("id")) {
  781. error = ERR_FILE_CORRUPT;
  782. error_text = "Missing 'index' in external resource tag";
  783. _printerr();
  784. return error;
  785. }
  786. type = next_tag.fields["type"];
  787. id = next_tag.fields["id"];
  788. main_res = false;
  789. } else {
  790. type = res_type;
  791. id = 0; //used for last anyway
  792. main_res = true;
  793. }
  794. local_offsets.push_back(wf2->get_position());
  795. bs_save_unicode_string(wf, "local://" + itos(id));
  796. local_pointers_pos.push_back(wf->get_position());
  797. wf->store_64(0); //temp local offset
  798. bs_save_unicode_string(wf2, type);
  799. size_t propcount_ofs = wf2->get_position();
  800. wf2->store_32(0);
  801. int prop_count = 0;
  802. while (true) {
  803. String assign;
  804. Variant value;
  805. error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp);
  806. if (error) {
  807. if (main_res && error == ERR_FILE_EOF) {
  808. next_tag.name = ""; //exit
  809. break;
  810. }
  811. _printerr();
  812. return error;
  813. }
  814. if (assign != String()) {
  815. Map<StringName, int> empty_string_map; //unused
  816. bs_save_unicode_string(wf2, assign, true);
  817. ResourceFormatSaverBinaryInstance::write_variant(wf2, value, dummy_read.resource_set, dummy_read.external_resources, empty_string_map);
  818. prop_count++;
  819. } else if (next_tag.name != String()) {
  820. error = OK;
  821. break;
  822. } else {
  823. error = ERR_FILE_CORRUPT;
  824. error_text = "Premature end of file while parsing [sub_resource]";
  825. _printerr();
  826. return error;
  827. }
  828. }
  829. wf2->seek(propcount_ofs);
  830. wf2->store_32(prop_count);
  831. wf2->seek_end();
  832. }
  833. if (next_tag.name == "node") {
  834. //this is a node, must save one more!
  835. if (!is_scene) {
  836. error_text += "found the 'node' tag on a resource file!";
  837. _printerr();
  838. error = ERR_FILE_CORRUPT;
  839. return error;
  840. }
  841. Ref<PackedScene> packed_scene = _parse_node_tag(rp);
  842. if (!packed_scene.is_valid())
  843. return error;
  844. error = OK;
  845. //get it here
  846. List<PropertyInfo> props;
  847. packed_scene->get_property_list(&props);
  848. bs_save_unicode_string(wf, "local://0");
  849. local_pointers_pos.push_back(wf->get_position());
  850. wf->store_64(0); //temp local offset
  851. local_offsets.push_back(wf2->get_position());
  852. bs_save_unicode_string(wf2, "PackedScene");
  853. size_t propcount_ofs = wf2->get_position();
  854. wf2->store_32(0);
  855. int prop_count = 0;
  856. for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
  857. if (!(E->get().usage & PROPERTY_USAGE_STORAGE))
  858. continue;
  859. String name = E->get().name;
  860. Variant value = packed_scene->get(name);
  861. Map<StringName, int> empty_string_map; //unused
  862. bs_save_unicode_string(wf2, name, true);
  863. ResourceFormatSaverBinaryInstance::write_variant(wf2, value, dummy_read.resource_set, dummy_read.external_resources, empty_string_map);
  864. prop_count++;
  865. }
  866. wf2->seek(propcount_ofs);
  867. wf2->store_32(prop_count);
  868. wf2->seek_end();
  869. }
  870. wf2->close();
  871. size_t offset_from = wf->get_position();
  872. wf->seek(sub_res_count_pos); //plus one because the saved one
  873. wf->store_32(local_offsets.size());
  874. for (int i = 0; i < local_offsets.size(); i++) {
  875. wf->seek(local_pointers_pos[i]);
  876. wf->store_64(local_offsets[i] + offset_from);
  877. }
  878. wf->seek_end();
  879. Vector<uint8_t> data = FileAccess::get_file_as_array(temp_file);
  880. wf->store_buffer(data.ptr(), data.size());
  881. {
  882. DirAccessRef dar = DirAccess::open(temp_file.get_base_dir());
  883. dar->remove(temp_file);
  884. }
  885. wf->store_buffer((const uint8_t *)"RSRC", 4); //magic at end
  886. wf->close();
  887. return OK;
  888. }
  889. String ResourceInteractiveLoaderText::recognize(FileAccess *p_f) {
  890. error = OK;
  891. lines = 1;
  892. f = p_f;
  893. stream.f = f;
  894. ignore_resource_parsing = true;
  895. VariantParser::Tag tag;
  896. Error err = VariantParser::parse_tag(&stream, lines, error_text, tag);
  897. if (err) {
  898. _printerr();
  899. return "";
  900. }
  901. if (tag.fields.has("format")) {
  902. int fmt = tag.fields["format"];
  903. if (fmt > FORMAT_VERSION) {
  904. error_text = "Saved with newer format version";
  905. _printerr();
  906. return "";
  907. }
  908. }
  909. if (tag.name == "gd_scene")
  910. return "PackedScene";
  911. if (tag.name != "gd_resource")
  912. return "";
  913. if (!tag.fields.has("type")) {
  914. error_text = "Missing 'type' field in 'gd_resource' tag";
  915. _printerr();
  916. return "";
  917. }
  918. return tag.fields["type"];
  919. }
  920. /////////////////////
  921. Ref<ResourceInteractiveLoader> ResourceFormatLoaderText::load_interactive(const String &p_path, const String &p_original_path, Error *r_error) {
  922. if (r_error)
  923. *r_error = ERR_CANT_OPEN;
  924. Error err;
  925. FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
  926. if (err != OK) {
  927. ERR_FAIL_COND_V(err != OK, Ref<ResourceInteractiveLoader>());
  928. }
  929. Ref<ResourceInteractiveLoaderText> ria = memnew(ResourceInteractiveLoaderText);
  930. String path = p_original_path != "" ? p_original_path : p_path;
  931. ria->local_path = ProjectSettings::get_singleton()->localize_path(path);
  932. ria->res_path = ria->local_path;
  933. //ria->set_local_path( ProjectSettings::get_singleton()->localize_path(p_path) );
  934. ria->open(f);
  935. return ria;
  936. }
  937. void ResourceFormatLoaderText::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
  938. if (p_type == "") {
  939. get_recognized_extensions(p_extensions);
  940. return;
  941. }
  942. if (p_type == "PackedScene")
  943. p_extensions->push_back("tscn");
  944. else
  945. p_extensions->push_back("tres");
  946. }
  947. void ResourceFormatLoaderText::get_recognized_extensions(List<String> *p_extensions) const {
  948. p_extensions->push_back("tscn");
  949. p_extensions->push_back("tres");
  950. }
  951. bool ResourceFormatLoaderText::handles_type(const String &p_type) const {
  952. return true;
  953. }
  954. String ResourceFormatLoaderText::get_resource_type(const String &p_path) const {
  955. String ext = p_path.get_extension().to_lower();
  956. if (ext == "tscn")
  957. return "PackedScene";
  958. else if (ext != "tres")
  959. return String();
  960. //for anyhting else must test..
  961. FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
  962. if (!f) {
  963. return ""; //could not rwead
  964. }
  965. Ref<ResourceInteractiveLoaderText> ria = memnew(ResourceInteractiveLoaderText);
  966. ria->local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  967. ria->res_path = ria->local_path;
  968. //ria->set_local_path( ProjectSettings::get_singleton()->localize_path(p_path) );
  969. String r = ria->recognize(f);
  970. return r;
  971. }
  972. void ResourceFormatLoaderText::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  973. FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
  974. if (!f) {
  975. ERR_FAIL();
  976. }
  977. Ref<ResourceInteractiveLoaderText> ria = memnew(ResourceInteractiveLoaderText);
  978. ria->local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  979. ria->res_path = ria->local_path;
  980. //ria->set_local_path( ProjectSettings::get_singleton()->localize_path(p_path) );
  981. ria->get_dependencies(f, p_dependencies, p_add_types);
  982. }
  983. Error ResourceFormatLoaderText::rename_dependencies(const String &p_path, const Map<String, String> &p_map) {
  984. FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
  985. if (!f) {
  986. ERR_FAIL_V(ERR_CANT_OPEN);
  987. }
  988. Ref<ResourceInteractiveLoaderText> ria = memnew(ResourceInteractiveLoaderText);
  989. ria->local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  990. ria->res_path = ria->local_path;
  991. //ria->set_local_path( ProjectSettings::get_singleton()->localize_path(p_path) );
  992. return ria->rename_dependencies(f, p_path, p_map);
  993. }
  994. ResourceFormatLoaderText *ResourceFormatLoaderText::singleton = NULL;
  995. Error ResourceFormatLoaderText::convert_file_to_binary(const String &p_src_path, const String &p_dst_path) {
  996. Error err;
  997. FileAccess *f = FileAccess::open(p_src_path, FileAccess::READ, &err);
  998. if (err != OK) {
  999. ERR_FAIL_COND_V(err != OK, ERR_CANT_OPEN);
  1000. }
  1001. Ref<ResourceInteractiveLoaderText> ria = memnew(ResourceInteractiveLoaderText);
  1002. String path = p_src_path;
  1003. ria->local_path = ProjectSettings::get_singleton()->localize_path(path);
  1004. ria->res_path = ria->local_path;
  1005. //ria->set_local_path( ProjectSettings::get_singleton()->localize_path(p_path) );
  1006. ria->open(f);
  1007. return ria->save_as_binary(f, p_dst_path);
  1008. }
  1009. /*****************************************************************************************************/
  1010. /*****************************************************************************************************/
  1011. /*****************************************************************************************************/
  1012. /*****************************************************************************************************/
  1013. /*****************************************************************************************************/
  1014. /*****************************************************************************************************/
  1015. /*****************************************************************************************************/
  1016. /*****************************************************************************************************/
  1017. /*****************************************************************************************************/
  1018. /*****************************************************************************************************/
  1019. String ResourceFormatSaverTextInstance::_write_resources(void *ud, const RES &p_resource) {
  1020. ResourceFormatSaverTextInstance *rsi = (ResourceFormatSaverTextInstance *)ud;
  1021. return rsi->_write_resource(p_resource);
  1022. }
  1023. String ResourceFormatSaverTextInstance::_write_resource(const RES &res) {
  1024. if (external_resources.has(res)) {
  1025. return "ExtResource( " + itos(external_resources[res] + 1) + " )";
  1026. } else {
  1027. if (internal_resources.has(res)) {
  1028. return "SubResource( " + itos(internal_resources[res]) + " )";
  1029. } else if (res->get_path().length() && res->get_path().find("::") == -1) {
  1030. if (res->get_path() == local_path) { //circular reference attempt
  1031. return "null";
  1032. }
  1033. //external resource
  1034. String path = relative_paths ? local_path.path_to_file(res->get_path()) : res->get_path();
  1035. return "Resource( \"" + path + "\" )";
  1036. } else {
  1037. ERR_EXPLAIN("Resource was not pre cached for the resource section, bug?");
  1038. ERR_FAIL_V("null");
  1039. //internal resource
  1040. }
  1041. }
  1042. return "null";
  1043. }
  1044. void ResourceFormatSaverTextInstance::_find_resources(const Variant &p_variant, bool p_main) {
  1045. switch (p_variant.get_type()) {
  1046. case Variant::OBJECT: {
  1047. RES res = p_variant.operator RefPtr();
  1048. if (res.is_null() || external_resources.has(res))
  1049. return;
  1050. if (!p_main && (!bundle_resources) && res->get_path().length() && res->get_path().find("::") == -1) {
  1051. if (res->get_path() == local_path) {
  1052. ERR_PRINTS("Circular reference to resource being saved found: '" + local_path + "' will be null next time it's loaded.");
  1053. return;
  1054. }
  1055. int index = external_resources.size();
  1056. external_resources[res] = index;
  1057. return;
  1058. }
  1059. if (resource_set.has(res))
  1060. return;
  1061. List<PropertyInfo> property_list;
  1062. res->get_property_list(&property_list);
  1063. property_list.sort();
  1064. List<PropertyInfo>::Element *I = property_list.front();
  1065. while (I) {
  1066. PropertyInfo pi = I->get();
  1067. if (pi.usage & PROPERTY_USAGE_STORAGE) {
  1068. Variant v = res->get(I->get().name);
  1069. if (pi.usage & PROPERTY_USAGE_RESOURCE_NOT_PERSISTENT) {
  1070. RES sres = v;
  1071. if (sres.is_valid()) {
  1072. NonPersistentKey npk;
  1073. npk.base = res;
  1074. npk.property = pi.name;
  1075. non_persistent_map[npk] = sres;
  1076. resource_set.insert(sres);
  1077. saved_resources.push_back(sres);
  1078. }
  1079. } else {
  1080. _find_resources(v);
  1081. }
  1082. }
  1083. I = I->next();
  1084. }
  1085. resource_set.insert(res); //saved after, so the children it needs are available when loaded
  1086. saved_resources.push_back(res);
  1087. } break;
  1088. case Variant::ARRAY: {
  1089. Array varray = p_variant;
  1090. int len = varray.size();
  1091. for (int i = 0; i < len; i++) {
  1092. Variant v = varray.get(i);
  1093. _find_resources(v);
  1094. }
  1095. } break;
  1096. case Variant::DICTIONARY: {
  1097. Dictionary d = p_variant;
  1098. List<Variant> keys;
  1099. d.get_key_list(&keys);
  1100. for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
  1101. Variant v = d[E->get()];
  1102. _find_resources(v);
  1103. }
  1104. } break;
  1105. default: {}
  1106. }
  1107. }
  1108. static String _valprop(const String &p_name) {
  1109. // Escape and quote strings with extended ASCII or further Unicode characters
  1110. // as well as '"', '=' or ' ' (32)
  1111. const CharType *cstr = p_name.c_str();
  1112. for (int i = 0; cstr[i]; i++) {
  1113. if (cstr[i] == '=' || cstr[i] == '"' || cstr[i] < 33 || cstr[i] > 126) {
  1114. return "\"" + p_name.c_escape_multiline() + "\"";
  1115. }
  1116. }
  1117. // Keep as is
  1118. return p_name;
  1119. }
  1120. Error ResourceFormatSaverTextInstance::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
  1121. if (p_path.ends_with(".tscn")) {
  1122. packed_scene = p_resource;
  1123. }
  1124. Error err;
  1125. f = FileAccess::open(p_path, FileAccess::WRITE, &err);
  1126. ERR_FAIL_COND_V(err, ERR_CANT_OPEN);
  1127. FileAccessRef _fref(f);
  1128. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  1129. relative_paths = p_flags & ResourceSaver::FLAG_RELATIVE_PATHS;
  1130. skip_editor = p_flags & ResourceSaver::FLAG_OMIT_EDITOR_PROPERTIES;
  1131. bundle_resources = p_flags & ResourceSaver::FLAG_BUNDLE_RESOURCES;
  1132. takeover_paths = p_flags & ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS;
  1133. if (!p_path.begins_with("res://")) {
  1134. takeover_paths = false;
  1135. }
  1136. // save resources
  1137. _find_resources(p_resource, true);
  1138. if (packed_scene.is_valid()) {
  1139. //add instances to external resources if saving a packed scene
  1140. for (int i = 0; i < packed_scene->get_state()->get_node_count(); i++) {
  1141. if (packed_scene->get_state()->is_node_instance_placeholder(i))
  1142. continue;
  1143. Ref<PackedScene> instance = packed_scene->get_state()->get_node_instance(i);
  1144. if (instance.is_valid() && !external_resources.has(instance)) {
  1145. int index = external_resources.size();
  1146. external_resources[instance] = index;
  1147. }
  1148. }
  1149. }
  1150. ERR_FAIL_COND_V(err != OK, err);
  1151. {
  1152. String title = packed_scene.is_valid() ? "[gd_scene " : "[gd_resource ";
  1153. if (packed_scene.is_null())
  1154. title += "type=\"" + p_resource->get_class() + "\" ";
  1155. int load_steps = saved_resources.size() + external_resources.size();
  1156. /*
  1157. if (packed_scene.is_valid()) {
  1158. load_steps+=packed_scene->get_node_count();
  1159. }
  1160. //no, better to not use load steps from nodes, no point to that
  1161. */
  1162. if (load_steps > 1) {
  1163. title += "load_steps=" + itos(load_steps) + " ";
  1164. }
  1165. title += "format=" + itos(FORMAT_VERSION) + "";
  1166. f->store_string(title);
  1167. f->store_line("]\n"); //one empty line
  1168. }
  1169. Vector<RES> sorted_er;
  1170. sorted_er.resize(external_resources.size());
  1171. for (Map<RES, int>::Element *E = external_resources.front(); E; E = E->next()) {
  1172. sorted_er.write[E->get()] = E->key();
  1173. }
  1174. for (int i = 0; i < sorted_er.size(); i++) {
  1175. String p = sorted_er[i]->get_path();
  1176. f->store_string("[ext_resource path=\"" + p + "\" type=\"" + sorted_er[i]->get_save_class() + "\" id=" + itos(i + 1) + "]\n"); //bundled
  1177. }
  1178. if (external_resources.size())
  1179. f->store_line(String()); //separate
  1180. Set<int> used_indices;
  1181. for (List<RES>::Element *E = saved_resources.front(); E; E = E->next()) {
  1182. RES res = E->get();
  1183. if (E->next() && (res->get_path() == "" || res->get_path().find("::") != -1)) {
  1184. if (res->get_subindex() != 0) {
  1185. if (used_indices.has(res->get_subindex())) {
  1186. res->set_subindex(0); //repeated
  1187. } else {
  1188. used_indices.insert(res->get_subindex());
  1189. }
  1190. }
  1191. }
  1192. }
  1193. for (List<RES>::Element *E = saved_resources.front(); E; E = E->next()) {
  1194. RES res = E->get();
  1195. ERR_CONTINUE(!resource_set.has(res));
  1196. bool main = (E->next() == NULL);
  1197. if (main && packed_scene.is_valid())
  1198. break; //save as a scene
  1199. if (main) {
  1200. f->store_line("[resource]");
  1201. } else {
  1202. String line = "[sub_resource ";
  1203. if (res->get_subindex() == 0) {
  1204. int new_subindex = 1;
  1205. if (used_indices.size()) {
  1206. new_subindex = used_indices.back()->get() + 1;
  1207. }
  1208. res->set_subindex(new_subindex);
  1209. used_indices.insert(new_subindex);
  1210. }
  1211. int idx = res->get_subindex();
  1212. line += "type=\"" + res->get_class() + "\" id=" + itos(idx);
  1213. f->store_line(line + "]");
  1214. if (takeover_paths) {
  1215. res->set_path(p_path + "::" + itos(idx), true);
  1216. }
  1217. internal_resources[res] = idx;
  1218. #ifdef TOOLS_ENABLED
  1219. res->set_edited(false);
  1220. #endif
  1221. }
  1222. List<PropertyInfo> property_list;
  1223. res->get_property_list(&property_list);
  1224. //property_list.sort();
  1225. for (List<PropertyInfo>::Element *PE = property_list.front(); PE; PE = PE->next()) {
  1226. if (skip_editor && PE->get().name.begins_with("__editor"))
  1227. continue;
  1228. if (PE->get().usage & PROPERTY_USAGE_STORAGE) {
  1229. String name = PE->get().name;
  1230. Variant value;
  1231. if (PE->get().usage & PROPERTY_USAGE_RESOURCE_NOT_PERSISTENT) {
  1232. NonPersistentKey npk;
  1233. npk.base = res;
  1234. npk.property = name;
  1235. if (non_persistent_map.has(npk)) {
  1236. value = non_persistent_map[npk];
  1237. }
  1238. } else {
  1239. value = res->get(name);
  1240. }
  1241. Variant default_value = ClassDB::class_get_default_property_value(res->get_class(), name);
  1242. if (default_value.get_type() != Variant::NIL && bool(Variant::evaluate(Variant::OP_EQUAL, value, default_value))) {
  1243. continue;
  1244. }
  1245. if (PE->get().type == Variant::OBJECT && value.is_zero() && !(PE->get().usage & PROPERTY_USAGE_STORE_IF_NULL))
  1246. continue;
  1247. String vars;
  1248. VariantWriter::write_to_string(value, vars, _write_resources, this);
  1249. f->store_string(_valprop(name) + " = " + vars + "\n");
  1250. }
  1251. }
  1252. f->store_string("\n");
  1253. }
  1254. if (packed_scene.is_valid()) {
  1255. //if this is a scene, save nodes and connections!
  1256. Ref<SceneState> state = packed_scene->get_state();
  1257. for (int i = 0; i < state->get_node_count(); i++) {
  1258. StringName type = state->get_node_type(i);
  1259. StringName name = state->get_node_name(i);
  1260. int index = state->get_node_index(i);
  1261. NodePath path = state->get_node_path(i, true);
  1262. NodePath owner = state->get_node_owner_path(i);
  1263. Ref<PackedScene> instance = state->get_node_instance(i);
  1264. String instance_placeholder = state->get_node_instance_placeholder(i);
  1265. Vector<StringName> groups = state->get_node_groups(i);
  1266. String header = "[node";
  1267. header += " name=\"" + String(name) + "\"";
  1268. if (type != StringName()) {
  1269. header += " type=\"" + String(type) + "\"";
  1270. }
  1271. if (path != NodePath()) {
  1272. header += " parent=\"" + String(path.simplified()) + "\"";
  1273. }
  1274. if (owner != NodePath() && owner != NodePath(".")) {
  1275. header += " owner=\"" + String(owner.simplified()) + "\"";
  1276. }
  1277. if (index >= 0) {
  1278. header += " index=\"" + itos(index) + "\"";
  1279. }
  1280. if (groups.size()) {
  1281. String sgroups = " groups=[\n";
  1282. for (int j = 0; j < groups.size(); j++) {
  1283. sgroups += "\"" + String(groups[j]).c_escape() + "\",\n";
  1284. }
  1285. sgroups += "]";
  1286. header += sgroups;
  1287. }
  1288. f->store_string(header);
  1289. if (instance_placeholder != String()) {
  1290. String vars;
  1291. f->store_string(" instance_placeholder=");
  1292. VariantWriter::write_to_string(instance_placeholder, vars, _write_resources, this);
  1293. f->store_string(vars);
  1294. }
  1295. if (instance.is_valid()) {
  1296. String vars;
  1297. f->store_string(" instance=");
  1298. VariantWriter::write_to_string(instance, vars, _write_resources, this);
  1299. f->store_string(vars);
  1300. }
  1301. f->store_line("]");
  1302. for (int j = 0; j < state->get_node_property_count(i); j++) {
  1303. String vars;
  1304. VariantWriter::write_to_string(state->get_node_property_value(i, j), vars, _write_resources, this);
  1305. f->store_string(_valprop(String(state->get_node_property_name(i, j))) + " = " + vars + "\n");
  1306. }
  1307. f->store_line(String());
  1308. }
  1309. for (int i = 0; i < state->get_connection_count(); i++) {
  1310. String connstr = "[connection";
  1311. connstr += " signal=\"" + String(state->get_connection_signal(i)) + "\"";
  1312. connstr += " from=\"" + String(state->get_connection_source(i).simplified()) + "\"";
  1313. connstr += " to=\"" + String(state->get_connection_target(i).simplified()) + "\"";
  1314. connstr += " method=\"" + String(state->get_connection_method(i)) + "\"";
  1315. int flags = state->get_connection_flags(i);
  1316. if (flags != Object::CONNECT_PERSIST) {
  1317. connstr += " flags=" + itos(flags);
  1318. }
  1319. Array binds = state->get_connection_binds(i);
  1320. f->store_string(connstr);
  1321. if (binds.size()) {
  1322. String vars;
  1323. VariantWriter::write_to_string(binds, vars, _write_resources, this);
  1324. f->store_string(" binds= " + vars);
  1325. }
  1326. f->store_line("]");
  1327. }
  1328. Vector<NodePath> editable_instances = state->get_editable_instances();
  1329. for (int i = 0; i < editable_instances.size(); i++) {
  1330. f->store_line("\n[editable path=\"" + editable_instances[i].operator String() + "\"]");
  1331. }
  1332. }
  1333. if (f->get_error() != OK && f->get_error() != ERR_FILE_EOF) {
  1334. f->close();
  1335. return ERR_CANT_CREATE;
  1336. }
  1337. f->close();
  1338. //memdelete(f);
  1339. return OK;
  1340. }
  1341. Error ResourceFormatSaverText::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
  1342. if (p_path.ends_with(".sct") && p_resource->get_class() != "PackedScene") {
  1343. return ERR_FILE_UNRECOGNIZED;
  1344. }
  1345. ResourceFormatSaverTextInstance saver;
  1346. return saver.save(p_path, p_resource, p_flags);
  1347. }
  1348. bool ResourceFormatSaverText::recognize(const RES &p_resource) const {
  1349. return true; // all recognized!
  1350. }
  1351. void ResourceFormatSaverText::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
  1352. if (p_resource->get_class() == "PackedScene")
  1353. p_extensions->push_back("tscn"); //text scene
  1354. else
  1355. p_extensions->push_back("tres"); //text resource
  1356. }
  1357. ResourceFormatSaverText *ResourceFormatSaverText::singleton = NULL;
  1358. ResourceFormatSaverText::ResourceFormatSaverText() {
  1359. singleton = this;
  1360. }