resource_loader.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. /*************************************************************************/
  2. /* resource_loader.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 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_loader.h"
  31. #include "core/io/resource_importer.h"
  32. #include "core/os/file_access.h"
  33. #include "core/os/os.h"
  34. #include "core/path_remap.h"
  35. #include "core/print_string.h"
  36. #include "core/project_settings.h"
  37. #include "core/translation.h"
  38. #include "core/variant_parser.h"
  39. Ref<ResourceFormatLoader> ResourceLoader::loader[ResourceLoader::MAX_LOADERS];
  40. int ResourceLoader::loader_count = 0;
  41. Error ResourceInteractiveLoader::wait() {
  42. Error err = poll();
  43. while (err == OK) {
  44. err = poll();
  45. }
  46. return err;
  47. }
  48. ResourceInteractiveLoader::~ResourceInteractiveLoader() {
  49. if (path_loading != String()) {
  50. ResourceLoader::_remove_from_loading_map_and_thread(path_loading, path_loading_thread);
  51. }
  52. }
  53. bool ResourceFormatLoader::recognize_path(const String &p_path, const String &p_for_type) const {
  54. String extension = p_path.get_extension();
  55. List<String> extensions;
  56. if (p_for_type == String()) {
  57. get_recognized_extensions(&extensions);
  58. } else {
  59. get_recognized_extensions_for_type(p_for_type, &extensions);
  60. }
  61. for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
  62. if (E->get().nocasecmp_to(extension) == 0) {
  63. return true;
  64. }
  65. }
  66. return false;
  67. }
  68. bool ResourceFormatLoader::handles_type(const String &p_type) const {
  69. if (get_script_instance() && get_script_instance()->has_method("handles_type")) {
  70. // I guess custom loaders for custom resources should use "Resource"
  71. return get_script_instance()->call("handles_type", p_type);
  72. }
  73. return false;
  74. }
  75. String ResourceFormatLoader::get_resource_type(const String &p_path) const {
  76. if (get_script_instance() && get_script_instance()->has_method("get_resource_type")) {
  77. return get_script_instance()->call("get_resource_type", p_path);
  78. }
  79. return "";
  80. }
  81. void ResourceFormatLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
  82. if (p_type == "" || handles_type(p_type)) {
  83. get_recognized_extensions(p_extensions);
  84. }
  85. }
  86. void ResourceLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) {
  87. for (int i = 0; i < loader_count; i++) {
  88. loader[i]->get_recognized_extensions_for_type(p_type, p_extensions);
  89. }
  90. }
  91. void ResourceInteractiveLoader::_bind_methods() {
  92. ClassDB::bind_method(D_METHOD("get_resource"), &ResourceInteractiveLoader::get_resource);
  93. ClassDB::bind_method(D_METHOD("poll"), &ResourceInteractiveLoader::poll);
  94. ClassDB::bind_method(D_METHOD("wait"), &ResourceInteractiveLoader::wait);
  95. ClassDB::bind_method(D_METHOD("get_stage"), &ResourceInteractiveLoader::get_stage);
  96. ClassDB::bind_method(D_METHOD("get_stage_count"), &ResourceInteractiveLoader::get_stage_count);
  97. }
  98. class ResourceInteractiveLoaderDefault : public ResourceInteractiveLoader {
  99. GDCLASS(ResourceInteractiveLoaderDefault, ResourceInteractiveLoader);
  100. public:
  101. Ref<Resource> resource;
  102. virtual void set_local_path(const String &p_local_path) { /*scene->set_filename(p_local_path);*/
  103. }
  104. virtual Ref<Resource> get_resource() { return resource; }
  105. virtual Error poll() { return ERR_FILE_EOF; }
  106. virtual int get_stage() const { return 1; }
  107. virtual int get_stage_count() const { return 1; }
  108. virtual void set_translation_remapped(bool p_remapped) { resource->set_as_translation_remapped(p_remapped); }
  109. ResourceInteractiveLoaderDefault() {}
  110. };
  111. bool ResourceFormatLoader::exists(const String &p_path) const {
  112. return FileAccess::exists(p_path); //by default just check file
  113. }
  114. void ResourceFormatLoader::get_recognized_extensions(List<String> *p_extensions) const {
  115. if (get_script_instance() && get_script_instance()->has_method("get_recognized_extensions")) {
  116. PoolStringArray exts = get_script_instance()->call("get_recognized_extensions");
  117. {
  118. PoolStringArray::Read r = exts.read();
  119. for (int i = 0; i < exts.size(); ++i) {
  120. p_extensions->push_back(r[i]);
  121. }
  122. }
  123. }
  124. }
  125. // Warning: Derived classes must override either `load` or `load_interactive`. The base code
  126. // here can trigger an infinite recursion otherwise, since `load` calls `load_interactive`
  127. // vice versa.
  128. Ref<ResourceInteractiveLoader> ResourceFormatLoader::load_interactive(const String &p_path, const String &p_original_path, Error *r_error) {
  129. // Warning: See previous note about the risk of infinite recursion.
  130. Ref<Resource> res = load(p_path, p_original_path, r_error);
  131. if (res.is_null()) {
  132. return Ref<ResourceInteractiveLoader>();
  133. }
  134. Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>(memnew(ResourceInteractiveLoaderDefault));
  135. ril->resource = res;
  136. return ril;
  137. }
  138. RES ResourceFormatLoader::load(const String &p_path, const String &p_original_path, Error *r_error) {
  139. // Check user-defined loader if there's any. Hard fail if it returns an error.
  140. if (get_script_instance() && get_script_instance()->has_method("load")) {
  141. Variant res = get_script_instance()->call("load", p_path, p_original_path);
  142. if (res.get_type() == Variant::INT) { // Error code, abort.
  143. if (r_error) {
  144. *r_error = (Error)res.operator int64_t();
  145. }
  146. return RES();
  147. } else { // Success, pass on result.
  148. if (r_error) {
  149. *r_error = OK;
  150. }
  151. return res;
  152. }
  153. }
  154. // Warning: See previous note about the risk of infinite recursion.
  155. Ref<ResourceInteractiveLoader> ril = load_interactive(p_path, p_original_path, r_error);
  156. if (!ril.is_valid()) {
  157. return RES();
  158. }
  159. ril->set_local_path(p_original_path);
  160. while (true) {
  161. Error err = ril->poll();
  162. if (err == ERR_FILE_EOF) {
  163. if (r_error) {
  164. *r_error = OK;
  165. }
  166. return ril->get_resource();
  167. }
  168. if (r_error) {
  169. *r_error = err;
  170. }
  171. ERR_FAIL_COND_V_MSG(err != OK, RES(), "Failed to load resource '" + p_path + "'.");
  172. }
  173. }
  174. void ResourceFormatLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  175. if (get_script_instance() && get_script_instance()->has_method("get_dependencies")) {
  176. PoolStringArray deps = get_script_instance()->call("get_dependencies", p_path, p_add_types);
  177. {
  178. PoolStringArray::Read r = deps.read();
  179. for (int i = 0; i < deps.size(); ++i) {
  180. p_dependencies->push_back(r[i]);
  181. }
  182. }
  183. }
  184. }
  185. Error ResourceFormatLoader::rename_dependencies(const String &p_path, const Map<String, String> &p_map) {
  186. if (get_script_instance() && get_script_instance()->has_method("rename_dependencies")) {
  187. Dictionary deps_dict;
  188. for (Map<String, String>::Element *E = p_map.front(); E; E = E->next()) {
  189. deps_dict[E->key()] = E->value();
  190. }
  191. int64_t res = get_script_instance()->call("rename_dependencies", deps_dict);
  192. return (Error)res;
  193. }
  194. return OK;
  195. }
  196. void ResourceFormatLoader::_bind_methods() {
  197. {
  198. MethodInfo info = MethodInfo(Variant::NIL, "load", PropertyInfo(Variant::STRING, "path"), PropertyInfo(Variant::STRING, "original_path"));
  199. info.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  200. ClassDB::add_virtual_method(get_class_static(), info);
  201. }
  202. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::POOL_STRING_ARRAY, "get_recognized_extensions"));
  203. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::BOOL, "handles_type", PropertyInfo(Variant::STRING, "typename")));
  204. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::STRING, "get_resource_type", PropertyInfo(Variant::STRING, "path")));
  205. ClassDB::add_virtual_method(get_class_static(), MethodInfo("get_dependencies", PropertyInfo(Variant::STRING, "path"), PropertyInfo(Variant::STRING, "add_types")));
  206. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::INT, "rename_dependencies", PropertyInfo(Variant::STRING, "path"), PropertyInfo(Variant::STRING, "renames")));
  207. }
  208. ///////////////////////////////////
  209. RES ResourceLoader::_load(const String &p_path, const String &p_original_path, const String &p_type_hint, bool p_no_cache, Error *r_error) {
  210. bool found = false;
  211. // Try all loaders and pick the first match for the type hint
  212. for (int i = 0; i < loader_count; i++) {
  213. if (!loader[i]->recognize_path(p_path, p_type_hint)) {
  214. continue;
  215. }
  216. found = true;
  217. RES res = loader[i]->load(p_path, p_original_path != String() ? p_original_path : p_path, r_error);
  218. if (res.is_null()) {
  219. continue;
  220. }
  221. return res;
  222. }
  223. ERR_FAIL_COND_V_MSG(found, RES(),
  224. vformat("Failed loading resource: %s. Make sure resources have been imported by opening the project in the editor at least once.", p_path));
  225. #ifdef TOOLS_ENABLED
  226. FileAccessRef file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);
  227. ERR_FAIL_COND_V_MSG(!file_check->file_exists(p_path), RES(), "Resource file not found: " + p_path + ".");
  228. #endif
  229. ERR_FAIL_V_MSG(RES(), "No loader found for resource: " + p_path + ".");
  230. }
  231. bool ResourceLoader::_add_to_loading_map(const String &p_path) {
  232. bool success;
  233. loading_map_mutex.lock();
  234. LoadingMapKey key;
  235. key.path = p_path;
  236. key.thread = Thread::get_caller_id();
  237. if (loading_map.has(key)) {
  238. success = false;
  239. } else {
  240. loading_map[key] = true;
  241. success = true;
  242. }
  243. loading_map_mutex.unlock();
  244. return success;
  245. }
  246. void ResourceLoader::_remove_from_loading_map(const String &p_path) {
  247. loading_map_mutex.lock();
  248. LoadingMapKey key;
  249. key.path = p_path;
  250. key.thread = Thread::get_caller_id();
  251. loading_map.erase(key);
  252. loading_map_mutex.unlock();
  253. }
  254. void ResourceLoader::_remove_from_loading_map_and_thread(const String &p_path, Thread::ID p_thread) {
  255. loading_map_mutex.lock();
  256. LoadingMapKey key;
  257. key.path = p_path;
  258. key.thread = p_thread;
  259. loading_map.erase(key);
  260. loading_map_mutex.unlock();
  261. }
  262. RES ResourceLoader::load(const String &p_path, const String &p_type_hint, bool p_no_cache, Error *r_error) {
  263. if (r_error) {
  264. *r_error = ERR_CANT_OPEN;
  265. }
  266. String local_path;
  267. if (p_path.is_rel_path()) {
  268. local_path = "res://" + p_path;
  269. } else {
  270. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  271. }
  272. if (!p_no_cache) {
  273. {
  274. bool success = _add_to_loading_map(local_path);
  275. ERR_FAIL_COND_V_MSG(!success, RES(), "Resource: '" + local_path + "' is already being loaded. Cyclic reference?");
  276. }
  277. //lock first if possible
  278. ResourceCache::lock.read_lock();
  279. //get ptr
  280. Resource **rptr = ResourceCache::resources.getptr(local_path);
  281. if (rptr) {
  282. RES res(*rptr);
  283. //it is possible this resource was just freed in a thread. If so, this referencing will not work and resource is considered not cached
  284. if (res.is_valid()) {
  285. //referencing is fine
  286. if (r_error) {
  287. *r_error = OK;
  288. }
  289. ResourceCache::lock.read_unlock();
  290. _remove_from_loading_map(local_path);
  291. return res;
  292. }
  293. }
  294. ResourceCache::lock.read_unlock();
  295. }
  296. bool xl_remapped = false;
  297. String path = _path_remap(local_path, &xl_remapped);
  298. if (path == "") {
  299. if (!p_no_cache) {
  300. _remove_from_loading_map(local_path);
  301. }
  302. ERR_FAIL_V_MSG(RES(), "Remapping '" + local_path + "' failed.");
  303. }
  304. print_verbose("Loading resource: " + path);
  305. RES res = _load(path, local_path, p_type_hint, p_no_cache, r_error);
  306. if (res.is_null()) {
  307. if (!p_no_cache) {
  308. _remove_from_loading_map(local_path);
  309. }
  310. return RES();
  311. }
  312. if (!p_no_cache) {
  313. res->set_path(local_path);
  314. }
  315. if (xl_remapped) {
  316. res->set_as_translation_remapped(true);
  317. }
  318. #ifdef TOOLS_ENABLED
  319. res->set_edited(false);
  320. if (timestamp_on_load) {
  321. uint64_t mt = FileAccess::get_modified_time(path);
  322. //printf("mt %s: %lli\n",remapped_path.utf8().get_data(),mt);
  323. res->set_last_modified_time(mt);
  324. }
  325. #endif
  326. if (!p_no_cache) {
  327. _remove_from_loading_map(local_path);
  328. }
  329. if (_loaded_callback) {
  330. _loaded_callback(res, p_path);
  331. }
  332. return res;
  333. }
  334. bool ResourceLoader::exists(const String &p_path, const String &p_type_hint) {
  335. String local_path;
  336. if (p_path.is_rel_path()) {
  337. local_path = "res://" + p_path;
  338. } else {
  339. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  340. }
  341. if (ResourceCache::has(local_path)) {
  342. return true; // If cached, it probably exists
  343. }
  344. bool xl_remapped = false;
  345. String path = _path_remap(local_path, &xl_remapped);
  346. // Try all loaders and pick the first match for the type hint
  347. for (int i = 0; i < loader_count; i++) {
  348. if (!loader[i]->recognize_path(path, p_type_hint)) {
  349. continue;
  350. }
  351. if (loader[i]->exists(path)) {
  352. return true;
  353. }
  354. }
  355. return false;
  356. }
  357. Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_path, const String &p_type_hint, bool p_no_cache, Error *r_error) {
  358. if (r_error) {
  359. *r_error = ERR_CANT_OPEN;
  360. }
  361. String local_path;
  362. if (p_path.is_rel_path()) {
  363. local_path = "res://" + p_path;
  364. } else {
  365. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  366. }
  367. if (!p_no_cache) {
  368. bool success = _add_to_loading_map(local_path);
  369. ERR_FAIL_COND_V_MSG(!success, RES(), "Resource: '" + local_path + "' is already being loaded. Cyclic reference?");
  370. if (ResourceCache::has(local_path)) {
  371. print_verbose("Loading resource: " + local_path + " (cached)");
  372. Ref<Resource> res_cached = ResourceCache::get(local_path);
  373. Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>(memnew(ResourceInteractiveLoaderDefault));
  374. ril->resource = res_cached;
  375. ril->path_loading = local_path;
  376. ril->path_loading_thread = Thread::get_caller_id();
  377. return ril;
  378. }
  379. }
  380. bool xl_remapped = false;
  381. String path = _path_remap(local_path, &xl_remapped);
  382. if (path == "") {
  383. if (!p_no_cache) {
  384. _remove_from_loading_map(local_path);
  385. }
  386. ERR_FAIL_V_MSG(RES(), "Remapping '" + local_path + "' failed.");
  387. }
  388. print_verbose("Loading resource: " + path);
  389. bool found = false;
  390. for (int i = 0; i < loader_count; i++) {
  391. if (!loader[i]->recognize_path(path, p_type_hint)) {
  392. continue;
  393. }
  394. found = true;
  395. Ref<ResourceInteractiveLoader> ril = loader[i]->load_interactive(path, local_path, r_error);
  396. if (ril.is_null()) {
  397. continue;
  398. }
  399. if (!p_no_cache) {
  400. ril->set_local_path(local_path);
  401. ril->path_loading = local_path;
  402. ril->path_loading_thread = Thread::get_caller_id();
  403. }
  404. if (xl_remapped) {
  405. ril->set_translation_remapped(true);
  406. }
  407. return ril;
  408. }
  409. if (!p_no_cache) {
  410. _remove_from_loading_map(local_path);
  411. }
  412. ERR_FAIL_COND_V_MSG(found, Ref<ResourceInteractiveLoader>(), "Failed loading resource: " + path + ".");
  413. ERR_FAIL_V_MSG(Ref<ResourceInteractiveLoader>(), "No loader found for resource: " + path + ".");
  414. }
  415. void ResourceLoader::add_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader, bool p_at_front) {
  416. ERR_FAIL_COND(p_format_loader.is_null());
  417. ERR_FAIL_COND(loader_count >= MAX_LOADERS);
  418. if (p_at_front) {
  419. for (int i = loader_count; i > 0; i--) {
  420. loader[i] = loader[i - 1];
  421. }
  422. loader[0] = p_format_loader;
  423. loader_count++;
  424. } else {
  425. loader[loader_count++] = p_format_loader;
  426. }
  427. }
  428. void ResourceLoader::remove_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader) {
  429. ERR_FAIL_COND(p_format_loader.is_null());
  430. // Find loader
  431. int i = 0;
  432. for (; i < loader_count; ++i) {
  433. if (loader[i] == p_format_loader) {
  434. break;
  435. }
  436. }
  437. ERR_FAIL_COND(i >= loader_count); // Not found
  438. // Shift next loaders up
  439. for (; i < loader_count - 1; ++i) {
  440. loader[i] = loader[i + 1];
  441. }
  442. loader[loader_count - 1].unref();
  443. --loader_count;
  444. }
  445. int ResourceLoader::get_import_order(const String &p_path) {
  446. String path = _path_remap(p_path);
  447. String local_path;
  448. if (path.is_rel_path()) {
  449. local_path = "res://" + path;
  450. } else {
  451. local_path = ProjectSettings::get_singleton()->localize_path(path);
  452. }
  453. for (int i = 0; i < loader_count; i++) {
  454. if (!loader[i]->recognize_path(local_path)) {
  455. continue;
  456. }
  457. /*
  458. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  459. continue;
  460. */
  461. return loader[i]->get_import_order(p_path);
  462. }
  463. return 0;
  464. }
  465. String ResourceLoader::get_import_group_file(const String &p_path) {
  466. String path = _path_remap(p_path);
  467. String local_path;
  468. if (path.is_rel_path()) {
  469. local_path = "res://" + path;
  470. } else {
  471. local_path = ProjectSettings::get_singleton()->localize_path(path);
  472. }
  473. for (int i = 0; i < loader_count; i++) {
  474. if (!loader[i]->recognize_path(local_path)) {
  475. continue;
  476. }
  477. /*
  478. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  479. continue;
  480. */
  481. return loader[i]->get_import_group_file(p_path);
  482. }
  483. return String(); //not found
  484. }
  485. bool ResourceLoader::is_import_valid(const String &p_path) {
  486. String path = _path_remap(p_path);
  487. String local_path;
  488. if (path.is_rel_path()) {
  489. local_path = "res://" + path;
  490. } else {
  491. local_path = ProjectSettings::get_singleton()->localize_path(path);
  492. }
  493. for (int i = 0; i < loader_count; i++) {
  494. if (!loader[i]->recognize_path(local_path)) {
  495. continue;
  496. }
  497. /*
  498. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  499. continue;
  500. */
  501. return loader[i]->is_import_valid(p_path);
  502. }
  503. return false; //not found
  504. }
  505. bool ResourceLoader::is_imported(const String &p_path) {
  506. String path = _path_remap(p_path);
  507. String local_path;
  508. if (path.is_rel_path()) {
  509. local_path = "res://" + path;
  510. } else {
  511. local_path = ProjectSettings::get_singleton()->localize_path(path);
  512. }
  513. for (int i = 0; i < loader_count; i++) {
  514. if (!loader[i]->recognize_path(local_path)) {
  515. continue;
  516. }
  517. /*
  518. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  519. continue;
  520. */
  521. return loader[i]->is_imported(p_path);
  522. }
  523. return false; //not found
  524. }
  525. void ResourceLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  526. String path = _path_remap(p_path);
  527. String local_path;
  528. if (path.is_rel_path()) {
  529. local_path = "res://" + path;
  530. } else {
  531. local_path = ProjectSettings::get_singleton()->localize_path(path);
  532. }
  533. for (int i = 0; i < loader_count; i++) {
  534. if (!loader[i]->recognize_path(local_path)) {
  535. continue;
  536. }
  537. /*
  538. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  539. continue;
  540. */
  541. loader[i]->get_dependencies(local_path, p_dependencies, p_add_types);
  542. }
  543. }
  544. Error ResourceLoader::rename_dependencies(const String &p_path, const Map<String, String> &p_map) {
  545. String path = _path_remap(p_path);
  546. String local_path;
  547. if (path.is_rel_path()) {
  548. local_path = "res://" + path;
  549. } else {
  550. local_path = ProjectSettings::get_singleton()->localize_path(path);
  551. }
  552. for (int i = 0; i < loader_count; i++) {
  553. if (!loader[i]->recognize_path(local_path)) {
  554. continue;
  555. }
  556. /*
  557. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  558. continue;
  559. */
  560. return loader[i]->rename_dependencies(local_path, p_map);
  561. }
  562. return OK; // ??
  563. }
  564. String ResourceLoader::get_resource_type(const String &p_path) {
  565. String local_path;
  566. if (p_path.is_rel_path()) {
  567. local_path = "res://" + p_path;
  568. } else {
  569. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  570. }
  571. for (int i = 0; i < loader_count; i++) {
  572. String result = loader[i]->get_resource_type(local_path);
  573. if (result != "") {
  574. return result;
  575. }
  576. }
  577. return "";
  578. }
  579. String ResourceLoader::_path_remap(const String &p_path, bool *r_translation_remapped) {
  580. String new_path = p_path;
  581. if (translation_remaps.has(p_path)) {
  582. // translation_remaps has the following format:
  583. // { "res://path.png": PoolStringArray( "res://path-ru.png:ru", "res://path-de.png:de" ) }
  584. // To find the path of the remapped resource, we extract the locale name after
  585. // the last ':' to match the project locale.
  586. // We also fall back in case of regional locales as done in TranslationServer::translate
  587. // (e.g. 'ru_RU' -> 'ru' if the former has no specific mapping).
  588. String locale = TranslationServer::get_singleton()->get_locale();
  589. ERR_FAIL_COND_V_MSG(locale.length() < 2, p_path, "Could not remap path '" + p_path + "' for translation as configured locale '" + locale + "' is invalid.");
  590. String lang = TranslationServer::get_language_code(locale);
  591. Vector<String> &res_remaps = *translation_remaps.getptr(new_path);
  592. bool near_match = false;
  593. for (int i = 0; i < res_remaps.size(); i++) {
  594. int split = res_remaps[i].find_last(":");
  595. if (split == -1) {
  596. continue;
  597. }
  598. String l = res_remaps[i].right(split + 1).strip_edges();
  599. if (l == locale) { // Exact match.
  600. new_path = res_remaps[i].left(split);
  601. break;
  602. } else if (near_match) {
  603. continue; // Already found near match, keep going for potential exact match.
  604. }
  605. // No exact match (e.g. locale 'ru_RU' but remap is 'ru'), let's look further
  606. // for a near match (same language code, i.e. first 2 or 3 letters before
  607. // regional code, if included).
  608. if (TranslationServer::get_language_code(l) == lang) {
  609. // Language code matches, that's a near match. Keep looking for exact match.
  610. near_match = true;
  611. new_path = res_remaps[i].left(split);
  612. continue;
  613. }
  614. }
  615. if (r_translation_remapped) {
  616. *r_translation_remapped = true;
  617. }
  618. }
  619. if (path_remaps.has(new_path)) {
  620. new_path = path_remaps[new_path];
  621. }
  622. if (new_path == p_path) { // Did not remap.
  623. // Try file remap.
  624. Error err;
  625. FileAccess *f = FileAccess::open(p_path + ".remap", FileAccess::READ, &err);
  626. if (f) {
  627. VariantParser::StreamFile stream;
  628. stream.f = f;
  629. String assign;
  630. Variant value;
  631. VariantParser::Tag next_tag;
  632. int lines = 0;
  633. String error_text;
  634. while (true) {
  635. assign = Variant();
  636. next_tag.fields.clear();
  637. next_tag.name = String();
  638. err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
  639. if (err == ERR_FILE_EOF) {
  640. break;
  641. } else if (err != OK) {
  642. ERR_PRINT("Parse error: " + p_path + ".remap:" + itos(lines) + " error: " + error_text + ".");
  643. break;
  644. }
  645. if (assign == "path") {
  646. new_path = value;
  647. break;
  648. } else if (next_tag.name != "remap") {
  649. break;
  650. }
  651. }
  652. memdelete(f);
  653. }
  654. }
  655. return new_path;
  656. }
  657. String ResourceLoader::import_remap(const String &p_path) {
  658. if (ResourceFormatImporter::get_singleton()->recognize_path(p_path)) {
  659. return ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_path);
  660. }
  661. return p_path;
  662. }
  663. String ResourceLoader::path_remap(const String &p_path) {
  664. return _path_remap(p_path);
  665. }
  666. void ResourceLoader::reload_translation_remaps() {
  667. ResourceCache::lock.read_lock();
  668. List<Resource *> to_reload;
  669. SelfList<Resource> *E = remapped_list.first();
  670. while (E) {
  671. to_reload.push_back(E->self());
  672. E = E->next();
  673. }
  674. ResourceCache::lock.read_unlock();
  675. //now just make sure to not delete any of these resources while changing locale..
  676. while (to_reload.front()) {
  677. to_reload.front()->get()->reload_from_file();
  678. to_reload.pop_front();
  679. }
  680. }
  681. void ResourceLoader::load_translation_remaps() {
  682. if (!ProjectSettings::get_singleton()->has_setting("locale/translation_remaps")) {
  683. return;
  684. }
  685. Dictionary remaps = ProjectSettings::get_singleton()->get("locale/translation_remaps");
  686. List<Variant> keys;
  687. remaps.get_key_list(&keys);
  688. for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
  689. Array langs = remaps[E->get()];
  690. Vector<String> lang_remaps;
  691. lang_remaps.resize(langs.size());
  692. for (int i = 0; i < langs.size(); i++) {
  693. lang_remaps.write[i] = langs[i];
  694. }
  695. translation_remaps[String(E->get())] = lang_remaps;
  696. }
  697. }
  698. void ResourceLoader::clear_translation_remaps() {
  699. translation_remaps.clear();
  700. while (remapped_list.first() != nullptr) {
  701. remapped_list.remove(remapped_list.first());
  702. }
  703. }
  704. void ResourceLoader::load_path_remaps() {
  705. if (!ProjectSettings::get_singleton()->has_setting("path_remap/remapped_paths")) {
  706. return;
  707. }
  708. PoolVector<String> remaps = ProjectSettings::get_singleton()->get("path_remap/remapped_paths");
  709. int rc = remaps.size();
  710. ERR_FAIL_COND(rc & 1); //must be even
  711. PoolVector<String>::Read r = remaps.read();
  712. for (int i = 0; i < rc; i += 2) {
  713. path_remaps[r[i]] = r[i + 1];
  714. }
  715. }
  716. void ResourceLoader::clear_path_remaps() {
  717. path_remaps.clear();
  718. }
  719. void ResourceLoader::set_load_callback(ResourceLoadedCallback p_callback) {
  720. _loaded_callback = p_callback;
  721. }
  722. ResourceLoadedCallback ResourceLoader::_loaded_callback = nullptr;
  723. Ref<ResourceFormatLoader> ResourceLoader::_find_custom_resource_format_loader(String path) {
  724. for (int i = 0; i < loader_count; ++i) {
  725. if (loader[i]->get_script_instance() && loader[i]->get_script_instance()->get_script()->get_path() == path) {
  726. return loader[i];
  727. }
  728. }
  729. return Ref<ResourceFormatLoader>();
  730. }
  731. bool ResourceLoader::add_custom_resource_format_loader(String script_path) {
  732. if (_find_custom_resource_format_loader(script_path).is_valid()) {
  733. return false;
  734. }
  735. Ref<Resource> res = ResourceLoader::load(script_path);
  736. ERR_FAIL_COND_V(res.is_null(), false);
  737. ERR_FAIL_COND_V(!res->is_class("Script"), false);
  738. Ref<Script> s = res;
  739. StringName ibt = s->get_instance_base_type();
  740. bool valid_type = ClassDB::is_parent_class(ibt, "ResourceFormatLoader");
  741. ERR_FAIL_COND_V_MSG(!valid_type, false, "Script does not inherit a CustomResourceLoader: " + script_path + ".");
  742. Object *obj = ClassDB::instance(ibt);
  743. ERR_FAIL_COND_V_MSG(obj == nullptr, false, "Cannot instance script as custom resource loader, expected 'ResourceFormatLoader' inheritance, got: " + String(ibt) + ".");
  744. Ref<ResourceFormatLoader> crl = Object::cast_to<ResourceFormatLoader>(obj);
  745. crl->set_script(s.get_ref_ptr());
  746. ResourceLoader::add_resource_format_loader(crl);
  747. return true;
  748. }
  749. void ResourceLoader::remove_custom_resource_format_loader(String script_path) {
  750. Ref<ResourceFormatLoader> custom_loader = _find_custom_resource_format_loader(script_path);
  751. if (custom_loader.is_valid()) {
  752. remove_resource_format_loader(custom_loader);
  753. }
  754. }
  755. void ResourceLoader::add_custom_loaders() {
  756. // Custom loaders registration exploits global class names
  757. String custom_loader_base_class = ResourceFormatLoader::get_class_static();
  758. List<StringName> global_classes;
  759. ScriptServer::get_global_class_list(&global_classes);
  760. for (List<StringName>::Element *E = global_classes.front(); E; E = E->next()) {
  761. StringName class_name = E->get();
  762. StringName base_class = ScriptServer::get_global_class_native_base(class_name);
  763. if (base_class == custom_loader_base_class) {
  764. String path = ScriptServer::get_global_class_path(class_name);
  765. add_custom_resource_format_loader(path);
  766. }
  767. }
  768. }
  769. void ResourceLoader::remove_custom_loaders() {
  770. Vector<Ref<ResourceFormatLoader>> custom_loaders;
  771. for (int i = 0; i < loader_count; ++i) {
  772. if (loader[i]->get_script_instance()) {
  773. custom_loaders.push_back(loader[i]);
  774. }
  775. }
  776. for (int i = 0; i < custom_loaders.size(); ++i) {
  777. remove_resource_format_loader(custom_loaders[i]);
  778. }
  779. }
  780. Mutex ResourceLoader::loading_map_mutex;
  781. HashMap<ResourceLoader::LoadingMapKey, int, ResourceLoader::LoadingMapKeyHasher> ResourceLoader::loading_map;
  782. void ResourceLoader::finalize() {
  783. #ifndef NO_THREADS
  784. const LoadingMapKey *K = nullptr;
  785. while ((K = loading_map.next(K))) {
  786. ERR_PRINT("Exited while resource is being loaded: " + K->path);
  787. }
  788. loading_map.clear();
  789. #endif
  790. }
  791. ResourceLoadErrorNotify ResourceLoader::err_notify = nullptr;
  792. void *ResourceLoader::err_notify_ud = nullptr;
  793. DependencyErrorNotify ResourceLoader::dep_err_notify = nullptr;
  794. void *ResourceLoader::dep_err_notify_ud = nullptr;
  795. bool ResourceLoader::abort_on_missing_resource = true;
  796. bool ResourceLoader::timestamp_on_load = false;
  797. SelfList<Resource>::List ResourceLoader::remapped_list;
  798. HashMap<String, Vector<String>> ResourceLoader::translation_remaps;
  799. HashMap<String, String> ResourceLoader::path_remaps;
  800. ResourceLoaderImport ResourceLoader::import = nullptr;