resource_loader.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. /**************************************************************************/
  2. /* resource_loader.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "resource_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. void ResourceInteractiveLoader::set_no_subresource_cache(bool p_no_subresource_cache) {
  49. no_subresource_cache = p_no_subresource_cache;
  50. }
  51. bool ResourceInteractiveLoader::get_no_subresource_cache() {
  52. return no_subresource_cache;
  53. }
  54. ResourceInteractiveLoader::~ResourceInteractiveLoader() {
  55. if (path_loading != String()) {
  56. ResourceLoader::_remove_from_loading_map_and_thread(path_loading, path_loading_thread);
  57. }
  58. }
  59. bool ResourceFormatLoader::recognize_path(const String &p_path, const String &p_for_type) const {
  60. String extension = p_path.get_extension();
  61. List<String> extensions;
  62. if (p_for_type == String()) {
  63. get_recognized_extensions(&extensions);
  64. } else {
  65. get_recognized_extensions_for_type(p_for_type, &extensions);
  66. }
  67. for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
  68. if (E->get().nocasecmp_to(extension) == 0) {
  69. return true;
  70. }
  71. }
  72. return false;
  73. }
  74. bool ResourceFormatLoader::handles_type(const String &p_type) const {
  75. if (get_script_instance() && get_script_instance()->has_method("handles_type")) {
  76. // I guess custom loaders for custom resources should use "Resource"
  77. return get_script_instance()->call("handles_type", p_type);
  78. }
  79. return false;
  80. }
  81. String ResourceFormatLoader::get_resource_type(const String &p_path) const {
  82. if (get_script_instance() && get_script_instance()->has_method("get_resource_type")) {
  83. return get_script_instance()->call("get_resource_type", p_path);
  84. }
  85. return "";
  86. }
  87. void ResourceFormatLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
  88. if (p_type == "" || handles_type(p_type)) {
  89. get_recognized_extensions(p_extensions);
  90. }
  91. }
  92. void ResourceLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) {
  93. for (int i = 0; i < loader_count; i++) {
  94. loader[i]->get_recognized_extensions_for_type(p_type, p_extensions);
  95. }
  96. }
  97. void ResourceInteractiveLoader::_bind_methods() {
  98. ClassDB::bind_method(D_METHOD("get_resource"), &ResourceInteractiveLoader::get_resource);
  99. ClassDB::bind_method(D_METHOD("poll"), &ResourceInteractiveLoader::poll);
  100. ClassDB::bind_method(D_METHOD("wait"), &ResourceInteractiveLoader::wait);
  101. ClassDB::bind_method(D_METHOD("get_stage"), &ResourceInteractiveLoader::get_stage);
  102. ClassDB::bind_method(D_METHOD("get_stage_count"), &ResourceInteractiveLoader::get_stage_count);
  103. ClassDB::bind_method(D_METHOD("set_no_subresource_cache", "no_subresource_cache"), &ResourceInteractiveLoader::set_no_subresource_cache);
  104. ClassDB::bind_method(D_METHOD("get_no_subresource_cache"), &ResourceInteractiveLoader::get_no_subresource_cache);
  105. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "no_subresource_cache"), "set_no_subresource_cache", "get_no_subresource_cache");
  106. }
  107. class ResourceInteractiveLoaderDefault : public ResourceInteractiveLoader {
  108. GDCLASS(ResourceInteractiveLoaderDefault, ResourceInteractiveLoader);
  109. public:
  110. Ref<Resource> resource;
  111. virtual void set_local_path(const String &p_local_path) { /*scene->set_filename(p_local_path);*/
  112. }
  113. virtual Ref<Resource> get_resource() { return resource; }
  114. virtual Error poll() { return ERR_FILE_EOF; }
  115. virtual int get_stage() const { return 1; }
  116. virtual int get_stage_count() const { return 1; }
  117. virtual void set_translation_remapped(bool p_remapped) { resource->set_as_translation_remapped(p_remapped); }
  118. ResourceInteractiveLoaderDefault() {}
  119. };
  120. bool ResourceFormatLoader::exists(const String &p_path) const {
  121. return FileAccess::exists(p_path); //by default just check file
  122. }
  123. void ResourceFormatLoader::get_recognized_extensions(List<String> *p_extensions) const {
  124. if (get_script_instance() && get_script_instance()->has_method("get_recognized_extensions")) {
  125. PoolStringArray exts = get_script_instance()->call("get_recognized_extensions");
  126. {
  127. PoolStringArray::Read r = exts.read();
  128. for (int i = 0; i < exts.size(); ++i) {
  129. p_extensions->push_back(r[i]);
  130. }
  131. }
  132. }
  133. }
  134. // Warning: Derived classes must override either `load` or `load_interactive`. The base code
  135. // here can trigger an infinite recursion otherwise, since `load` calls `load_interactive`
  136. // vice versa.
  137. Ref<ResourceInteractiveLoader> ResourceFormatLoader::load_interactive(const String &p_path, const String &p_original_path, Error *r_error, bool p_no_subresource_cache) {
  138. // Warning: See previous note about the risk of infinite recursion.
  139. Ref<Resource> res = load(p_path, p_original_path, r_error, p_no_subresource_cache);
  140. if (res.is_null()) {
  141. return Ref<ResourceInteractiveLoader>();
  142. }
  143. Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>(memnew(ResourceInteractiveLoaderDefault));
  144. ril->set_no_subresource_cache(p_no_subresource_cache);
  145. ril->resource = res;
  146. return ril;
  147. }
  148. RES ResourceFormatLoader::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_no_subresource_cache) {
  149. // Check user-defined loader if there's any. Hard fail if it returns an error.
  150. if (get_script_instance() && get_script_instance()->has_method("load")) {
  151. Variant res = get_script_instance()->call("load", p_path, p_original_path, p_no_subresource_cache);
  152. if (res.get_type() == Variant::INT) { // Error code, abort.
  153. if (r_error) {
  154. *r_error = (Error)res.operator int64_t();
  155. }
  156. return RES();
  157. } else { // Success, pass on result.
  158. if (r_error) {
  159. *r_error = OK;
  160. }
  161. return res;
  162. }
  163. }
  164. // Warning: See previous note about the risk of infinite recursion.
  165. Ref<ResourceInteractiveLoader> ril = load_interactive(p_path, p_original_path, r_error, p_no_subresource_cache);
  166. if (!ril.is_valid()) {
  167. return RES();
  168. }
  169. ril->set_local_path(p_original_path);
  170. while (true) {
  171. Error err = ril->poll();
  172. if (err == ERR_FILE_EOF) {
  173. if (r_error) {
  174. *r_error = OK;
  175. }
  176. return ril->get_resource();
  177. }
  178. if (r_error) {
  179. *r_error = err;
  180. }
  181. ERR_FAIL_COND_V_MSG(err != OK, RES(), "Failed to load resource '" + p_path + "'.");
  182. }
  183. }
  184. void ResourceFormatLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  185. if (get_script_instance() && get_script_instance()->has_method("get_dependencies")) {
  186. PoolStringArray deps = get_script_instance()->call("get_dependencies", p_path, p_add_types);
  187. {
  188. PoolStringArray::Read r = deps.read();
  189. for (int i = 0; i < deps.size(); ++i) {
  190. p_dependencies->push_back(r[i]);
  191. }
  192. }
  193. }
  194. }
  195. Error ResourceFormatLoader::rename_dependencies(const String &p_path, const Map<String, String> &p_map) {
  196. if (get_script_instance() && get_script_instance()->has_method("rename_dependencies")) {
  197. Dictionary deps_dict;
  198. for (Map<String, String>::Element *E = p_map.front(); E; E = E->next()) {
  199. deps_dict[E->key()] = E->value();
  200. }
  201. int64_t res = get_script_instance()->call("rename_dependencies", deps_dict);
  202. return (Error)res;
  203. }
  204. return OK;
  205. }
  206. void ResourceFormatLoader::_bind_methods() {
  207. {
  208. MethodInfo info = MethodInfo(Variant::NIL, "load", PropertyInfo(Variant::STRING, "path"), PropertyInfo(Variant::STRING, "original_path"), PropertyInfo(Variant::BOOL, "no_subresource_cache"));
  209. info.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  210. ClassDB::add_virtual_method(get_class_static(), info);
  211. }
  212. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::POOL_STRING_ARRAY, "get_recognized_extensions"));
  213. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::BOOL, "handles_type", PropertyInfo(Variant::STRING, "typename")));
  214. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::STRING, "get_resource_type", PropertyInfo(Variant::STRING, "path")));
  215. ClassDB::add_virtual_method(get_class_static(), MethodInfo("get_dependencies", PropertyInfo(Variant::STRING, "path"), PropertyInfo(Variant::STRING, "add_types")));
  216. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::INT, "rename_dependencies", PropertyInfo(Variant::STRING, "path"), PropertyInfo(Variant::STRING, "renames")));
  217. }
  218. ///////////////////////////////////
  219. RES ResourceLoader::_load(const String &p_path, const String &p_original_path, const String &p_type_hint, bool p_no_cache, Error *r_error) {
  220. bool found = false;
  221. // Try all loaders and pick the first match for the type hint
  222. for (int i = 0; i < loader_count; i++) {
  223. if (!loader[i]->recognize_path(p_path, p_type_hint)) {
  224. continue;
  225. }
  226. found = true;
  227. RES res = loader[i]->load(p_path, p_original_path != String() ? p_original_path : p_path, r_error, p_no_cache);
  228. if (res.is_null()) {
  229. continue;
  230. }
  231. return res;
  232. }
  233. ERR_FAIL_COND_V_MSG(found, RES(),
  234. vformat("Failed loading resource: %s. Make sure resources have been imported by opening the project in the editor at least once.", p_path));
  235. #ifdef TOOLS_ENABLED
  236. FileAccessRef file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);
  237. ERR_FAIL_COND_V_MSG(!file_check->file_exists(p_path), RES(), "Resource file not found: " + p_path + ".");
  238. #endif
  239. ERR_FAIL_V_MSG(RES(), "No loader found for resource: " + p_path + ".");
  240. }
  241. bool ResourceLoader::_add_to_loading_map(const String &p_path) {
  242. bool success;
  243. loading_map_mutex.lock();
  244. LoadingMapKey key;
  245. key.path = p_path;
  246. key.thread = Thread::get_caller_id();
  247. if (loading_map.has(key)) {
  248. success = false;
  249. } else {
  250. loading_map[key] = true;
  251. success = true;
  252. }
  253. loading_map_mutex.unlock();
  254. return success;
  255. }
  256. void ResourceLoader::_remove_from_loading_map(const String &p_path) {
  257. loading_map_mutex.lock();
  258. LoadingMapKey key;
  259. key.path = p_path;
  260. key.thread = Thread::get_caller_id();
  261. loading_map.erase(key);
  262. loading_map_mutex.unlock();
  263. }
  264. void ResourceLoader::_remove_from_loading_map_and_thread(const String &p_path, Thread::ID p_thread) {
  265. loading_map_mutex.lock();
  266. LoadingMapKey key;
  267. key.path = p_path;
  268. key.thread = p_thread;
  269. loading_map.erase(key);
  270. loading_map_mutex.unlock();
  271. }
  272. RES ResourceLoader::load(const String &p_path, const String &p_type_hint, bool p_no_cache, Error *r_error) {
  273. if (r_error) {
  274. *r_error = ERR_CANT_OPEN;
  275. }
  276. String local_path;
  277. if (p_path.is_rel_path()) {
  278. local_path = "res://" + p_path;
  279. } else {
  280. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  281. }
  282. if (!p_no_cache) {
  283. {
  284. bool success = _add_to_loading_map(local_path);
  285. ERR_FAIL_COND_V_MSG(!success, RES(), "Resource: '" + local_path + "' is already being loaded. Cyclic reference?");
  286. }
  287. //lock first if possible
  288. ResourceCache::lock.read_lock();
  289. //get ptr
  290. Resource **rptr = ResourceCache::resources.getptr(local_path);
  291. if (rptr) {
  292. RES res(*rptr);
  293. //it is possible this resource was just freed in a thread. If so, this referencing will not work and resource is considered not cached
  294. if (res.is_valid()) {
  295. //referencing is fine
  296. if (r_error) {
  297. *r_error = OK;
  298. }
  299. ResourceCache::lock.read_unlock();
  300. _remove_from_loading_map(local_path);
  301. return res;
  302. }
  303. }
  304. ResourceCache::lock.read_unlock();
  305. }
  306. bool xl_remapped = false;
  307. String path = _path_remap(local_path, &xl_remapped);
  308. if (path == "") {
  309. if (!p_no_cache) {
  310. _remove_from_loading_map(local_path);
  311. }
  312. ERR_FAIL_V_MSG(RES(), "Remapping '" + local_path + "' failed.");
  313. }
  314. print_verbose("Loading resource: " + path);
  315. RES res = _load(path, local_path, p_type_hint, p_no_cache, r_error);
  316. if (res.is_null()) {
  317. if (!p_no_cache) {
  318. _remove_from_loading_map(local_path);
  319. }
  320. return RES();
  321. }
  322. if (!p_no_cache) {
  323. res->set_path(local_path);
  324. }
  325. if (xl_remapped) {
  326. res->set_as_translation_remapped(true);
  327. }
  328. #ifdef TOOLS_ENABLED
  329. res->set_edited(false);
  330. if (timestamp_on_load) {
  331. uint64_t mt = FileAccess::get_modified_time(path);
  332. //printf("mt %s: %lli\n",remapped_path.utf8().get_data(),mt);
  333. res->set_last_modified_time(mt);
  334. }
  335. #endif
  336. if (!p_no_cache) {
  337. _remove_from_loading_map(local_path);
  338. }
  339. if (_loaded_callback) {
  340. _loaded_callback(res, p_path);
  341. }
  342. return res;
  343. }
  344. bool ResourceLoader::exists(const String &p_path, const String &p_type_hint) {
  345. String local_path;
  346. if (p_path.is_rel_path()) {
  347. local_path = "res://" + p_path;
  348. } else {
  349. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  350. }
  351. if (ResourceCache::has(local_path)) {
  352. return true; // If cached, it probably exists
  353. }
  354. bool xl_remapped = false;
  355. String path = _path_remap(local_path, &xl_remapped);
  356. // Try all loaders and pick the first match for the type hint
  357. for (int i = 0; i < loader_count; i++) {
  358. if (!loader[i]->recognize_path(path, p_type_hint)) {
  359. continue;
  360. }
  361. if (loader[i]->exists(path)) {
  362. return true;
  363. }
  364. }
  365. return false;
  366. }
  367. Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_path, const String &p_type_hint, bool p_no_cache, Error *r_error) {
  368. if (r_error) {
  369. *r_error = ERR_CANT_OPEN;
  370. }
  371. String local_path;
  372. if (p_path.is_rel_path()) {
  373. local_path = "res://" + p_path;
  374. } else {
  375. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  376. }
  377. if (!p_no_cache) {
  378. bool success = _add_to_loading_map(local_path);
  379. ERR_FAIL_COND_V_MSG(!success, RES(), "Resource: '" + local_path + "' is already being loaded. Cyclic reference?");
  380. if (ResourceCache::has(local_path)) {
  381. print_verbose("Loading resource: " + local_path + " (cached)");
  382. Ref<Resource> res_cached = ResourceCache::get(local_path);
  383. Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>(memnew(ResourceInteractiveLoaderDefault));
  384. ril->resource = res_cached;
  385. ril->path_loading = local_path;
  386. ril->path_loading_thread = Thread::get_caller_id();
  387. return ril;
  388. }
  389. }
  390. bool xl_remapped = false;
  391. String path = _path_remap(local_path, &xl_remapped);
  392. if (path == "") {
  393. if (!p_no_cache) {
  394. _remove_from_loading_map(local_path);
  395. }
  396. ERR_FAIL_V_MSG(RES(), "Remapping '" + local_path + "' failed.");
  397. }
  398. print_verbose("Loading resource: " + path);
  399. bool found = false;
  400. for (int i = 0; i < loader_count; i++) {
  401. if (!loader[i]->recognize_path(path, p_type_hint)) {
  402. continue;
  403. }
  404. found = true;
  405. Ref<ResourceInteractiveLoader> ril = loader[i]->load_interactive(path, local_path, r_error, p_no_cache);
  406. if (ril.is_null()) {
  407. continue;
  408. }
  409. if (!p_no_cache) {
  410. ril->set_local_path(local_path);
  411. ril->path_loading = local_path;
  412. ril->path_loading_thread = Thread::get_caller_id();
  413. }
  414. if (xl_remapped) {
  415. ril->set_translation_remapped(true);
  416. }
  417. return ril;
  418. }
  419. if (!p_no_cache) {
  420. _remove_from_loading_map(local_path);
  421. }
  422. ERR_FAIL_COND_V_MSG(found, Ref<ResourceInteractiveLoader>(), "Failed loading resource: " + path + ".");
  423. ERR_FAIL_V_MSG(Ref<ResourceInteractiveLoader>(), "No loader found for resource: " + path + ".");
  424. }
  425. void ResourceLoader::add_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader, bool p_at_front) {
  426. ERR_FAIL_COND(p_format_loader.is_null());
  427. ERR_FAIL_COND(loader_count >= MAX_LOADERS);
  428. if (p_at_front) {
  429. for (int i = loader_count; i > 0; i--) {
  430. loader[i] = loader[i - 1];
  431. }
  432. loader[0] = p_format_loader;
  433. loader_count++;
  434. } else {
  435. loader[loader_count++] = p_format_loader;
  436. }
  437. }
  438. void ResourceLoader::remove_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader) {
  439. ERR_FAIL_COND(p_format_loader.is_null());
  440. // Find loader
  441. int i = 0;
  442. for (; i < loader_count; ++i) {
  443. if (loader[i] == p_format_loader) {
  444. break;
  445. }
  446. }
  447. ERR_FAIL_COND(i >= loader_count); // Not found
  448. // Shift next loaders up
  449. for (; i < loader_count - 1; ++i) {
  450. loader[i] = loader[i + 1];
  451. }
  452. loader[loader_count - 1].unref();
  453. --loader_count;
  454. }
  455. int ResourceLoader::get_import_order(const String &p_path) {
  456. String path = _path_remap(p_path);
  457. String local_path;
  458. if (path.is_rel_path()) {
  459. local_path = "res://" + path;
  460. } else {
  461. local_path = ProjectSettings::get_singleton()->localize_path(path);
  462. }
  463. for (int i = 0; i < loader_count; i++) {
  464. if (!loader[i]->recognize_path(local_path)) {
  465. continue;
  466. }
  467. /*
  468. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  469. continue;
  470. */
  471. return loader[i]->get_import_order(p_path);
  472. }
  473. return 0;
  474. }
  475. String ResourceLoader::get_import_group_file(const String &p_path) {
  476. String path = _path_remap(p_path);
  477. String local_path;
  478. if (path.is_rel_path()) {
  479. local_path = "res://" + path;
  480. } else {
  481. local_path = ProjectSettings::get_singleton()->localize_path(path);
  482. }
  483. for (int i = 0; i < loader_count; i++) {
  484. if (!loader[i]->recognize_path(local_path)) {
  485. continue;
  486. }
  487. /*
  488. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  489. continue;
  490. */
  491. return loader[i]->get_import_group_file(p_path);
  492. }
  493. return String(); //not found
  494. }
  495. bool ResourceLoader::is_import_valid(const String &p_path) {
  496. String path = _path_remap(p_path);
  497. String local_path;
  498. if (path.is_rel_path()) {
  499. local_path = "res://" + path;
  500. } else {
  501. local_path = ProjectSettings::get_singleton()->localize_path(path);
  502. }
  503. for (int i = 0; i < loader_count; i++) {
  504. if (!loader[i]->recognize_path(local_path)) {
  505. continue;
  506. }
  507. /*
  508. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  509. continue;
  510. */
  511. return loader[i]->is_import_valid(p_path);
  512. }
  513. return false; //not found
  514. }
  515. bool ResourceLoader::is_imported(const String &p_path) {
  516. String path = _path_remap(p_path);
  517. String local_path;
  518. if (path.is_rel_path()) {
  519. local_path = "res://" + path;
  520. } else {
  521. local_path = ProjectSettings::get_singleton()->localize_path(path);
  522. }
  523. for (int i = 0; i < loader_count; i++) {
  524. if (!loader[i]->recognize_path(local_path)) {
  525. continue;
  526. }
  527. /*
  528. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  529. continue;
  530. */
  531. return loader[i]->is_imported(p_path);
  532. }
  533. return false; //not found
  534. }
  535. void ResourceLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  536. String path = _path_remap(p_path);
  537. String local_path;
  538. if (path.is_rel_path()) {
  539. local_path = "res://" + path;
  540. } else {
  541. local_path = ProjectSettings::get_singleton()->localize_path(path);
  542. }
  543. for (int i = 0; i < loader_count; i++) {
  544. if (!loader[i]->recognize_path(local_path)) {
  545. continue;
  546. }
  547. /*
  548. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  549. continue;
  550. */
  551. loader[i]->get_dependencies(local_path, p_dependencies, p_add_types);
  552. }
  553. }
  554. Error ResourceLoader::rename_dependencies(const String &p_path, const Map<String, String> &p_map) {
  555. String path = _path_remap(p_path);
  556. String local_path;
  557. if (path.is_rel_path()) {
  558. local_path = "res://" + path;
  559. } else {
  560. local_path = ProjectSettings::get_singleton()->localize_path(path);
  561. }
  562. for (int i = 0; i < loader_count; i++) {
  563. if (!loader[i]->recognize_path(local_path)) {
  564. continue;
  565. }
  566. /*
  567. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  568. continue;
  569. */
  570. return loader[i]->rename_dependencies(local_path, p_map);
  571. }
  572. return OK; // ??
  573. }
  574. String ResourceLoader::get_resource_type(const String &p_path) {
  575. String local_path;
  576. if (p_path.is_rel_path()) {
  577. local_path = "res://" + p_path;
  578. } else {
  579. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  580. }
  581. for (int i = 0; i < loader_count; i++) {
  582. String result = loader[i]->get_resource_type(local_path);
  583. if (result != "") {
  584. return result;
  585. }
  586. }
  587. return "";
  588. }
  589. String ResourceLoader::_path_remap(const String &p_path, bool *r_translation_remapped) {
  590. String new_path = p_path;
  591. if (translation_remaps.has(p_path)) {
  592. // translation_remaps has the following format:
  593. // { "res://path.png": PoolStringArray( "res://path-ru.png:ru", "res://path-de.png:de" ) }
  594. // To find the path of the remapped resource, we extract the locale name after
  595. // the last ':' to match the project locale.
  596. // An extra remap may still be necessary afterwards due to the text -> binary converter on export.
  597. String locale = TranslationServer::get_singleton()->get_locale();
  598. ERR_FAIL_COND_V_MSG(locale.length() < 2, p_path, "Could not remap path '" + p_path + "' for translation as configured locale '" + locale + "' is invalid.");
  599. Vector<String> &res_remaps = *translation_remaps.getptr(new_path);
  600. int best_score = 0;
  601. for (int i = 0; i < res_remaps.size(); i++) {
  602. int split = res_remaps[i].rfind(":");
  603. if (split == -1) {
  604. continue;
  605. }
  606. String l = res_remaps[i].right(split + 1).strip_edges();
  607. int score = TranslationServer::get_singleton()->compare_locales(locale, l);
  608. if (score > 0 && score >= best_score) {
  609. new_path = res_remaps[i].left(split);
  610. best_score = score;
  611. if (score == 10) {
  612. break; // Exact match, skip the rest.
  613. }
  614. }
  615. }
  616. if (r_translation_remapped) {
  617. *r_translation_remapped = true;
  618. }
  619. }
  620. if (path_remaps.has(new_path)) {
  621. new_path = path_remaps[new_path];
  622. } else {
  623. // Try file remap.
  624. Error err;
  625. FileAccess *f = FileAccess::open(new_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;