resource_loader.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308
  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/config/project_settings.h"
  32. #include "core/io/file_access.h"
  33. #include "core/io/resource_importer.h"
  34. #include "core/object/script_language.h"
  35. #include "core/os/condition_variable.h"
  36. #include "core/os/os.h"
  37. #include "core/os/safe_binary_mutex.h"
  38. #include "core/string/print_string.h"
  39. #include "core/string/translation.h"
  40. #include "core/variant/variant_parser.h"
  41. #include "servers/rendering_server.h"
  42. #ifdef DEBUG_LOAD_THREADED
  43. #define print_lt(m_text) print_line(m_text)
  44. #else
  45. #define print_lt(m_text)
  46. #endif
  47. Ref<ResourceFormatLoader> ResourceLoader::loader[ResourceLoader::MAX_LOADERS];
  48. int ResourceLoader::loader_count = 0;
  49. bool ResourceFormatLoader::recognize_path(const String &p_path, const String &p_for_type) const {
  50. bool ret = false;
  51. if (GDVIRTUAL_CALL(_recognize_path, p_path, p_for_type, ret)) {
  52. return ret;
  53. }
  54. String extension = p_path.get_extension();
  55. List<String> extensions;
  56. if (p_for_type.is_empty()) {
  57. get_recognized_extensions(&extensions);
  58. } else {
  59. get_recognized_extensions_for_type(p_for_type, &extensions);
  60. }
  61. for (const String &E : extensions) {
  62. if (E.nocasecmp_to(extension) == 0) {
  63. return true;
  64. }
  65. }
  66. return false;
  67. }
  68. bool ResourceFormatLoader::handles_type(const String &p_type) const {
  69. bool success = false;
  70. GDVIRTUAL_CALL(_handles_type, p_type, success);
  71. return success;
  72. }
  73. void ResourceFormatLoader::get_classes_used(const String &p_path, HashSet<StringName> *r_classes) {
  74. Vector<String> ret;
  75. if (GDVIRTUAL_CALL(_get_classes_used, p_path, ret)) {
  76. for (int i = 0; i < ret.size(); i++) {
  77. r_classes->insert(ret[i]);
  78. }
  79. return;
  80. }
  81. String res = get_resource_type(p_path);
  82. if (!res.is_empty()) {
  83. r_classes->insert(res);
  84. }
  85. }
  86. String ResourceFormatLoader::get_resource_type(const String &p_path) const {
  87. String ret;
  88. GDVIRTUAL_CALL(_get_resource_type, p_path, ret);
  89. return ret;
  90. }
  91. String ResourceFormatLoader::get_resource_script_class(const String &p_path) const {
  92. String ret;
  93. GDVIRTUAL_CALL(_get_resource_script_class, p_path, ret);
  94. return ret;
  95. }
  96. ResourceUID::ID ResourceFormatLoader::get_resource_uid(const String &p_path) const {
  97. int64_t uid = ResourceUID::INVALID_ID;
  98. GDVIRTUAL_CALL(_get_resource_uid, p_path, uid);
  99. return uid;
  100. }
  101. void ResourceFormatLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
  102. if (p_type.is_empty() || handles_type(p_type)) {
  103. get_recognized_extensions(p_extensions);
  104. }
  105. }
  106. void ResourceLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) {
  107. for (int i = 0; i < loader_count; i++) {
  108. loader[i]->get_recognized_extensions_for_type(p_type, p_extensions);
  109. }
  110. }
  111. bool ResourceFormatLoader::exists(const String &p_path) const {
  112. bool success = false;
  113. if (GDVIRTUAL_CALL(_exists, p_path, success)) {
  114. return success;
  115. }
  116. return FileAccess::exists(p_path); // By default just check file.
  117. }
  118. void ResourceFormatLoader::get_recognized_extensions(List<String> *p_extensions) const {
  119. PackedStringArray exts;
  120. if (GDVIRTUAL_CALL(_get_recognized_extensions, exts)) {
  121. const String *r = exts.ptr();
  122. for (int i = 0; i < exts.size(); ++i) {
  123. p_extensions->push_back(r[i]);
  124. }
  125. }
  126. }
  127. Ref<Resource> ResourceFormatLoader::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) {
  128. Variant res;
  129. if (GDVIRTUAL_CALL(_load, p_path, p_original_path, p_use_sub_threads, p_cache_mode, res)) {
  130. if (res.get_type() == Variant::INT) { // Error code, abort.
  131. if (r_error) {
  132. *r_error = (Error)res.operator int64_t();
  133. }
  134. return Ref<Resource>();
  135. } else { // Success, pass on result.
  136. if (r_error) {
  137. *r_error = OK;
  138. }
  139. return res;
  140. }
  141. }
  142. ERR_FAIL_V_MSG(Ref<Resource>(), "Failed to load resource '" + p_path + "'. ResourceFormatLoader::load was not implemented for this resource type.");
  143. }
  144. void ResourceFormatLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  145. PackedStringArray deps;
  146. if (GDVIRTUAL_CALL(_get_dependencies, p_path, p_add_types, deps)) {
  147. const String *r = deps.ptr();
  148. for (int i = 0; i < deps.size(); ++i) {
  149. p_dependencies->push_back(r[i]);
  150. }
  151. }
  152. }
  153. Error ResourceFormatLoader::rename_dependencies(const String &p_path, const HashMap<String, String> &p_map) {
  154. Dictionary deps_dict;
  155. for (KeyValue<String, String> E : p_map) {
  156. deps_dict[E.key] = E.value;
  157. }
  158. Error err = OK;
  159. GDVIRTUAL_CALL(_rename_dependencies, p_path, deps_dict, err);
  160. return err;
  161. }
  162. void ResourceFormatLoader::_bind_methods() {
  163. BIND_ENUM_CONSTANT(CACHE_MODE_IGNORE);
  164. BIND_ENUM_CONSTANT(CACHE_MODE_REUSE);
  165. BIND_ENUM_CONSTANT(CACHE_MODE_REPLACE);
  166. BIND_ENUM_CONSTANT(CACHE_MODE_IGNORE_DEEP);
  167. BIND_ENUM_CONSTANT(CACHE_MODE_REPLACE_DEEP);
  168. GDVIRTUAL_BIND(_get_recognized_extensions);
  169. GDVIRTUAL_BIND(_recognize_path, "path", "type");
  170. GDVIRTUAL_BIND(_handles_type, "type");
  171. GDVIRTUAL_BIND(_get_resource_type, "path");
  172. GDVIRTUAL_BIND(_get_resource_script_class, "path");
  173. GDVIRTUAL_BIND(_get_resource_uid, "path");
  174. GDVIRTUAL_BIND(_get_dependencies, "path", "add_types");
  175. GDVIRTUAL_BIND(_rename_dependencies, "path", "renames");
  176. GDVIRTUAL_BIND(_exists, "path");
  177. GDVIRTUAL_BIND(_get_classes_used, "path");
  178. GDVIRTUAL_BIND(_load, "path", "original_path", "use_sub_threads", "cache_mode");
  179. }
  180. ///////////////////////////////////
  181. // This should be robust enough to be called redundantly without issues.
  182. void ResourceLoader::LoadToken::clear() {
  183. thread_load_mutex.lock();
  184. WorkerThreadPool::TaskID task_to_await = 0;
  185. if (!local_path.is_empty()) { // Empty is used for the special case where the load task is not registered.
  186. DEV_ASSERT(thread_load_tasks.has(local_path));
  187. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  188. if (!load_task.awaited) {
  189. task_to_await = load_task.task_id;
  190. load_task.awaited = true;
  191. }
  192. thread_load_tasks.erase(local_path);
  193. local_path.clear();
  194. }
  195. if (!user_path.is_empty()) {
  196. DEV_ASSERT(user_load_tokens.has(user_path));
  197. user_load_tokens.erase(user_path);
  198. user_path.clear();
  199. }
  200. thread_load_mutex.unlock();
  201. // If task is unused, await it here, locally, now the token data is consistent.
  202. if (task_to_await) {
  203. WorkerThreadPool::get_singleton()->wait_for_task_completion(task_to_await);
  204. }
  205. }
  206. ResourceLoader::LoadToken::~LoadToken() {
  207. clear();
  208. }
  209. Ref<Resource> ResourceLoader::_load(const String &p_path, const String &p_original_path, const String &p_type_hint, ResourceFormatLoader::CacheMode p_cache_mode, Error *r_error, bool p_use_sub_threads, float *r_progress) {
  210. const String &original_path = p_original_path.is_empty() ? p_path : p_original_path;
  211. load_nesting++;
  212. if (load_paths_stack->size()) {
  213. thread_load_mutex.lock();
  214. const String &parent_task_path = load_paths_stack->get(load_paths_stack->size() - 1);
  215. HashMap<String, ThreadLoadTask>::Iterator E = thread_load_tasks.find(parent_task_path);
  216. // Avoid double-tracking, for progress reporting, resources that boil down to a remapped path containing the real payload (e.g., imported resources).
  217. bool is_remapped_load = original_path == parent_task_path;
  218. if (E && !is_remapped_load) {
  219. E->value.sub_tasks.insert(p_original_path);
  220. }
  221. thread_load_mutex.unlock();
  222. }
  223. load_paths_stack->push_back(original_path);
  224. // Try all loaders and pick the first match for the type hint
  225. bool found = false;
  226. Ref<Resource> res;
  227. for (int i = 0; i < loader_count; i++) {
  228. if (!loader[i]->recognize_path(p_path, p_type_hint)) {
  229. continue;
  230. }
  231. found = true;
  232. res = loader[i]->load(p_path, original_path, r_error, p_use_sub_threads, r_progress, p_cache_mode);
  233. if (!res.is_null()) {
  234. break;
  235. }
  236. }
  237. load_paths_stack->resize(load_paths_stack->size() - 1);
  238. res_ref_overrides.erase(load_nesting);
  239. load_nesting--;
  240. if (!res.is_null()) {
  241. return res;
  242. }
  243. ERR_FAIL_COND_V_MSG(found, Ref<Resource>(),
  244. vformat("Failed loading resource: %s. Make sure resources have been imported by opening the project in the editor at least once.", p_path));
  245. #ifdef TOOLS_ENABLED
  246. Ref<FileAccess> file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);
  247. ERR_FAIL_COND_V_MSG(!file_check->file_exists(p_path), Ref<Resource>(), vformat("Resource file not found: %s (expected type: %s)", p_path, p_type_hint));
  248. #endif
  249. ERR_FAIL_V_MSG(Ref<Resource>(), vformat("No loader found for resource: %s (expected type: %s)", p_path, p_type_hint));
  250. }
  251. void ResourceLoader::_thread_load_function(void *p_userdata) {
  252. ThreadLoadTask &load_task = *(ThreadLoadTask *)p_userdata;
  253. thread_load_mutex.lock();
  254. caller_task_id = load_task.task_id;
  255. if (cleaning_tasks) {
  256. load_task.status = THREAD_LOAD_FAILED;
  257. thread_load_mutex.unlock();
  258. return;
  259. }
  260. thread_load_mutex.unlock();
  261. // Thread-safe either if it's the current thread or a brand new one.
  262. thread_local bool mq_override_present = false;
  263. CallQueue *own_mq_override = nullptr;
  264. if (load_nesting == 0) {
  265. mq_override_present = false;
  266. load_paths_stack = memnew(Vector<String>);
  267. if (!load_task.dependent_path.is_empty()) {
  268. load_paths_stack->push_back(load_task.dependent_path);
  269. }
  270. if (!Thread::is_main_thread()) {
  271. // Let the caller thread use its own, for added flexibility. Provide one otherwise.
  272. if (MessageQueue::get_singleton() == MessageQueue::get_main_singleton()) {
  273. own_mq_override = memnew(CallQueue);
  274. MessageQueue::set_thread_singleton_override(own_mq_override);
  275. }
  276. mq_override_present = true;
  277. set_current_thread_safe_for_nodes(true);
  278. }
  279. } else {
  280. DEV_ASSERT(load_task.dependent_path.is_empty());
  281. }
  282. // --
  283. Ref<Resource> res = _load(load_task.remapped_path, load_task.remapped_path != load_task.local_path ? load_task.local_path : String(), load_task.type_hint, load_task.cache_mode, &load_task.error, load_task.use_sub_threads, &load_task.progress);
  284. if (mq_override_present) {
  285. MessageQueue::get_singleton()->flush();
  286. }
  287. thread_load_mutex.lock();
  288. load_task.resource = res;
  289. load_task.progress = 1.0; //it was fully loaded at this point, so force progress to 1.0
  290. if (load_task.error != OK) {
  291. load_task.status = THREAD_LOAD_FAILED;
  292. } else {
  293. load_task.status = THREAD_LOAD_LOADED;
  294. }
  295. if (load_task.cond_var) {
  296. load_task.cond_var->notify_all();
  297. memdelete(load_task.cond_var);
  298. load_task.cond_var = nullptr;
  299. }
  300. bool ignoring = load_task.cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE || load_task.cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE_DEEP;
  301. bool replacing = load_task.cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE || load_task.cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE_DEEP;
  302. if (load_task.resource.is_valid()) {
  303. if (!ignoring) {
  304. if (replacing) {
  305. Ref<Resource> old_res = ResourceCache::get_ref(load_task.local_path);
  306. if (old_res.is_valid() && old_res != load_task.resource) {
  307. // If resource is already loaded, only replace its data, to avoid existing invalidating instances.
  308. old_res->copy_from(load_task.resource);
  309. load_task.resource = old_res;
  310. }
  311. }
  312. load_task.resource->set_path(load_task.local_path, replacing);
  313. } else {
  314. load_task.resource->set_path_cache(load_task.local_path);
  315. }
  316. if (load_task.xl_remapped) {
  317. load_task.resource->set_as_translation_remapped(true);
  318. }
  319. #ifdef TOOLS_ENABLED
  320. load_task.resource->set_edited(false);
  321. if (timestamp_on_load) {
  322. uint64_t mt = FileAccess::get_modified_time(load_task.remapped_path);
  323. //printf("mt %s: %lli\n",remapped_path.utf8().get_data(),mt);
  324. load_task.resource->set_last_modified_time(mt);
  325. }
  326. #endif
  327. if (_loaded_callback) {
  328. _loaded_callback(load_task.resource, load_task.local_path);
  329. }
  330. } else if (!ignoring) {
  331. Ref<Resource> existing = ResourceCache::get_ref(load_task.local_path);
  332. if (existing.is_valid()) {
  333. load_task.resource = existing;
  334. load_task.status = THREAD_LOAD_LOADED;
  335. load_task.progress = 1.0;
  336. if (_loaded_callback) {
  337. _loaded_callback(load_task.resource, load_task.local_path);
  338. }
  339. }
  340. }
  341. thread_load_mutex.unlock();
  342. if (load_nesting == 0) {
  343. if (own_mq_override) {
  344. MessageQueue::set_thread_singleton_override(nullptr);
  345. memdelete(own_mq_override);
  346. }
  347. memdelete(load_paths_stack);
  348. }
  349. }
  350. static String _validate_local_path(const String &p_path) {
  351. ResourceUID::ID uid = ResourceUID::get_singleton()->text_to_id(p_path);
  352. if (uid != ResourceUID::INVALID_ID) {
  353. return ResourceUID::get_singleton()->get_id_path(uid);
  354. } else if (p_path.is_relative_path()) {
  355. return ("res://" + p_path).simplify_path();
  356. } else {
  357. return ProjectSettings::get_singleton()->localize_path(p_path);
  358. }
  359. }
  360. Error ResourceLoader::load_threaded_request(const String &p_path, const String &p_type_hint, bool p_use_sub_threads, ResourceFormatLoader::CacheMode p_cache_mode) {
  361. thread_load_mutex.lock();
  362. if (user_load_tokens.has(p_path)) {
  363. print_verbose("load_threaded_request(): Another threaded load for resource path '" + p_path + "' has been initiated. Not an error.");
  364. user_load_tokens[p_path]->reference(); // Additional request.
  365. thread_load_mutex.unlock();
  366. return OK;
  367. }
  368. user_load_tokens[p_path] = nullptr;
  369. thread_load_mutex.unlock();
  370. Ref<ResourceLoader::LoadToken> token = _load_start(p_path, p_type_hint, p_use_sub_threads ? LOAD_THREAD_DISTRIBUTE : LOAD_THREAD_SPAWN_SINGLE, p_cache_mode);
  371. if (token.is_valid()) {
  372. thread_load_mutex.lock();
  373. token->user_path = p_path;
  374. token->reference(); // First request.
  375. user_load_tokens[p_path] = token.ptr();
  376. print_lt("REQUEST: user load tokens: " + itos(user_load_tokens.size()));
  377. thread_load_mutex.unlock();
  378. return OK;
  379. } else {
  380. return FAILED;
  381. }
  382. }
  383. Ref<Resource> ResourceLoader::load(const String &p_path, const String &p_type_hint, ResourceFormatLoader::CacheMode p_cache_mode, Error *r_error) {
  384. if (r_error) {
  385. *r_error = OK;
  386. }
  387. Ref<LoadToken> load_token = _load_start(p_path, p_type_hint, LOAD_THREAD_FROM_CURRENT, p_cache_mode);
  388. if (!load_token.is_valid()) {
  389. if (r_error) {
  390. *r_error = FAILED;
  391. }
  392. return Ref<Resource>();
  393. }
  394. Ref<Resource> res = _load_complete(*load_token.ptr(), r_error);
  395. return res;
  396. }
  397. Ref<ResourceLoader::LoadToken> ResourceLoader::_load_start(const String &p_path, const String &p_type_hint, LoadThreadMode p_thread_mode, ResourceFormatLoader::CacheMode p_cache_mode) {
  398. String local_path = _validate_local_path(p_path);
  399. bool ignoring_cache = p_cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE || p_cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE_DEEP;
  400. Ref<LoadToken> load_token;
  401. ThreadLoadTask unregistered_load_task; // Once set, must be valid up to the call to do the load.
  402. ThreadLoadTask *load_task_ptr = nullptr;
  403. bool run_on_current_thread = false;
  404. {
  405. MutexLock thread_load_lock(thread_load_mutex);
  406. if (!ignoring_cache && thread_load_tasks.has(local_path)) {
  407. load_token = Ref<LoadToken>(thread_load_tasks[local_path].load_token);
  408. if (!load_token.is_valid()) {
  409. // The token is dying (reached 0 on another thread).
  410. // Ensure it's killed now so the path can be safely reused right away.
  411. thread_load_tasks[local_path].load_token->clear();
  412. }
  413. return load_token;
  414. }
  415. load_token.instantiate();
  416. load_token->local_path = local_path;
  417. //create load task
  418. {
  419. ThreadLoadTask load_task;
  420. load_task.remapped_path = _path_remap(local_path, &load_task.xl_remapped);
  421. load_task.load_token = load_token.ptr();
  422. load_task.local_path = local_path;
  423. load_task.type_hint = p_type_hint;
  424. load_task.cache_mode = p_cache_mode;
  425. load_task.use_sub_threads = p_thread_mode == LOAD_THREAD_DISTRIBUTE;
  426. if (p_cache_mode == ResourceFormatLoader::CACHE_MODE_REUSE) {
  427. Ref<Resource> existing = ResourceCache::get_ref(local_path);
  428. if (existing.is_valid()) {
  429. //referencing is fine
  430. load_task.resource = existing;
  431. load_task.status = THREAD_LOAD_LOADED;
  432. load_task.progress = 1.0;
  433. thread_load_tasks[local_path] = load_task;
  434. return load_token;
  435. }
  436. }
  437. // Cache-ignoring tasks aren't registered in the map and so must finish within scope.
  438. if (ignoring_cache) {
  439. load_token->local_path.clear();
  440. unregistered_load_task = load_task;
  441. load_task_ptr = &unregistered_load_task;
  442. } else {
  443. DEV_ASSERT(!thread_load_tasks.has(local_path));
  444. HashMap<String, ResourceLoader::ThreadLoadTask>::Iterator E = thread_load_tasks.insert(local_path, load_task);
  445. load_task_ptr = &E->value;
  446. }
  447. }
  448. run_on_current_thread = ignoring_cache || p_thread_mode == LOAD_THREAD_FROM_CURRENT;
  449. if (run_on_current_thread) {
  450. load_task_ptr->thread_id = Thread::get_caller_id();
  451. } else {
  452. load_task_ptr->task_id = WorkerThreadPool::get_singleton()->add_native_task(&ResourceLoader::_thread_load_function, load_task_ptr);
  453. }
  454. }
  455. if (run_on_current_thread) {
  456. _thread_load_function(load_task_ptr);
  457. if (ignoring_cache) {
  458. load_token->res_if_unregistered = load_task_ptr->resource;
  459. }
  460. }
  461. return load_token;
  462. }
  463. float ResourceLoader::_dependency_get_progress(const String &p_path) {
  464. if (thread_load_tasks.has(p_path)) {
  465. ThreadLoadTask &load_task = thread_load_tasks[p_path];
  466. float current_progress = 0.0;
  467. int dep_count = load_task.sub_tasks.size();
  468. if (dep_count > 0) {
  469. for (const String &E : load_task.sub_tasks) {
  470. current_progress += _dependency_get_progress(E);
  471. }
  472. current_progress /= float(dep_count);
  473. current_progress *= 0.5;
  474. current_progress += load_task.progress * 0.5;
  475. } else {
  476. current_progress = load_task.progress;
  477. }
  478. load_task.max_reported_progress = MAX(load_task.max_reported_progress, current_progress);
  479. return load_task.max_reported_progress;
  480. } else {
  481. return 1.0; //assume finished loading it so it no longer exists
  482. }
  483. }
  484. ResourceLoader::ThreadLoadStatus ResourceLoader::load_threaded_get_status(const String &p_path, float *r_progress) {
  485. MutexLock thread_load_lock(thread_load_mutex);
  486. if (!user_load_tokens.has(p_path)) {
  487. print_verbose("load_threaded_get_status(): No threaded load for resource path '" + p_path + "' has been initiated or its result has already been collected.");
  488. return THREAD_LOAD_INVALID_RESOURCE;
  489. }
  490. String local_path = _validate_local_path(p_path);
  491. if (!thread_load_tasks.has(local_path)) {
  492. #ifdef DEV_ENABLED
  493. CRASH_NOW();
  494. #endif
  495. // On non-dev, be defensive and at least avoid crashing (at this point at least).
  496. return THREAD_LOAD_INVALID_RESOURCE;
  497. }
  498. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  499. ThreadLoadStatus status;
  500. status = load_task.status;
  501. if (r_progress) {
  502. *r_progress = _dependency_get_progress(local_path);
  503. }
  504. // Support userland polling in a loop on the main thread.
  505. if (Thread::is_main_thread() && status == THREAD_LOAD_IN_PROGRESS) {
  506. uint64_t frame = Engine::get_singleton()->get_process_frames();
  507. if (frame == load_task.last_progress_check_main_thread_frame) {
  508. _ensure_load_progress();
  509. } else {
  510. load_task.last_progress_check_main_thread_frame = frame;
  511. }
  512. }
  513. return status;
  514. }
  515. Ref<Resource> ResourceLoader::load_threaded_get(const String &p_path, Error *r_error) {
  516. if (r_error) {
  517. *r_error = OK;
  518. }
  519. Ref<Resource> res;
  520. {
  521. MutexLock thread_load_lock(thread_load_mutex);
  522. if (!user_load_tokens.has(p_path)) {
  523. print_verbose("load_threaded_get(): No threaded load for resource path '" + p_path + "' has been initiated or its result has already been collected.");
  524. if (r_error) {
  525. *r_error = ERR_INVALID_PARAMETER;
  526. }
  527. return Ref<Resource>();
  528. }
  529. LoadToken *load_token = user_load_tokens[p_path];
  530. if (!load_token) {
  531. // This happens if requested from one thread and rapidly querying from another.
  532. if (r_error) {
  533. *r_error = ERR_BUSY;
  534. }
  535. return Ref<Resource>();
  536. }
  537. // Support userland requesting on the main thread before the load is reported to be complete.
  538. if (Thread::is_main_thread() && !load_token->local_path.is_empty()) {
  539. const ThreadLoadTask &load_task = thread_load_tasks[load_token->local_path];
  540. while (load_task.status == THREAD_LOAD_IN_PROGRESS) {
  541. if (!_ensure_load_progress()) {
  542. // This local poll loop is not needed.
  543. break;
  544. }
  545. thread_load_lock.~MutexLock();
  546. OS::get_singleton()->delay_usec(1000);
  547. new (&thread_load_lock) MutexLock(thread_load_mutex);
  548. }
  549. }
  550. res = _load_complete_inner(*load_token, r_error, thread_load_lock);
  551. if (load_token->unreference()) {
  552. memdelete(load_token);
  553. }
  554. }
  555. print_lt("GET: user load tokens: " + itos(user_load_tokens.size()));
  556. return res;
  557. }
  558. Ref<Resource> ResourceLoader::_load_complete(LoadToken &p_load_token, Error *r_error) {
  559. MutexLock thread_load_lock(thread_load_mutex);
  560. return _load_complete_inner(p_load_token, r_error, thread_load_lock);
  561. }
  562. Ref<Resource> ResourceLoader::_load_complete_inner(LoadToken &p_load_token, Error *r_error, MutexLock<SafeBinaryMutex<BINARY_MUTEX_TAG>> &p_thread_load_lock) {
  563. if (r_error) {
  564. *r_error = OK;
  565. }
  566. if (!p_load_token.local_path.is_empty()) {
  567. if (!thread_load_tasks.has(p_load_token.local_path)) {
  568. #ifdef DEV_ENABLED
  569. CRASH_NOW();
  570. #endif
  571. // On non-dev, be defensive and at least avoid crashing (at this point at least).
  572. if (r_error) {
  573. *r_error = ERR_BUG;
  574. }
  575. return Ref<Resource>();
  576. }
  577. ThreadLoadTask &load_task = thread_load_tasks[p_load_token.local_path];
  578. if (load_task.status == THREAD_LOAD_IN_PROGRESS) {
  579. DEV_ASSERT((load_task.task_id == 0) != (load_task.thread_id == 0));
  580. if ((load_task.task_id != 0 && load_task.task_id == caller_task_id) ||
  581. (load_task.thread_id != 0 && load_task.thread_id == Thread::get_caller_id())) {
  582. // Load is in progress, but it's precisely this thread the one in charge.
  583. // That means this is a cyclic load.
  584. if (r_error) {
  585. *r_error = ERR_BUSY;
  586. }
  587. return Ref<Resource>();
  588. }
  589. bool loader_is_wtp = load_task.task_id != 0;
  590. Error wtp_task_err = FAILED;
  591. if (loader_is_wtp) {
  592. // Loading thread is in the worker pool.
  593. load_task.awaited = true;
  594. thread_load_mutex.unlock();
  595. wtp_task_err = WorkerThreadPool::get_singleton()->wait_for_task_completion(load_task.task_id);
  596. }
  597. if (load_task.status == THREAD_LOAD_IN_PROGRESS) { // If early errored, awaiting would deadlock.
  598. if (loader_is_wtp) {
  599. if (wtp_task_err == ERR_BUSY) {
  600. // The WorkerThreadPool has reported that the current task wants to await on an older one.
  601. // That't not allowed for safety, to avoid deadlocks. Fortunately, though, in the context of
  602. // resource loading that means that the task to wait for can be restarted here to break the
  603. // cycle, with as much recursion into this process as needed.
  604. // When the stack is eventually unrolled, the original load will have been notified to go on.
  605. // CACHE_MODE_IGNORE is needed because, otherwise, the new request would just see there's
  606. // an ongoing load for that resource and wait for it again. This value forces a new load.
  607. Ref<ResourceLoader::LoadToken> token = _load_start(load_task.local_path, load_task.type_hint, LOAD_THREAD_DISTRIBUTE, ResourceFormatLoader::CACHE_MODE_IGNORE);
  608. Ref<Resource> resource = _load_complete(*token.ptr(), &wtp_task_err);
  609. if (r_error) {
  610. *r_error = wtp_task_err;
  611. }
  612. thread_load_mutex.lock();
  613. return resource;
  614. } else {
  615. DEV_ASSERT(wtp_task_err == OK);
  616. thread_load_mutex.lock();
  617. }
  618. } else {
  619. // Loading thread is main or user thread.
  620. if (!load_task.cond_var) {
  621. load_task.cond_var = memnew(ConditionVariable);
  622. }
  623. do {
  624. load_task.cond_var->wait(p_thread_load_lock);
  625. DEV_ASSERT(thread_load_tasks.has(p_load_token.local_path) && p_load_token.get_reference_count());
  626. } while (load_task.cond_var);
  627. }
  628. } else {
  629. if (loader_is_wtp) {
  630. thread_load_mutex.lock();
  631. }
  632. }
  633. }
  634. if (cleaning_tasks) {
  635. load_task.resource = Ref<Resource>();
  636. load_task.error = FAILED;
  637. }
  638. Ref<Resource> resource = load_task.resource;
  639. if (r_error) {
  640. *r_error = load_task.error;
  641. }
  642. return resource;
  643. } else {
  644. // Special case of an unregistered task.
  645. // The resource should have been loaded by now.
  646. Ref<Resource> resource = p_load_token.res_if_unregistered;
  647. if (!resource.is_valid()) {
  648. if (r_error) {
  649. *r_error = FAILED;
  650. }
  651. }
  652. return resource;
  653. }
  654. }
  655. bool ResourceLoader::_ensure_load_progress() {
  656. // Some servers may need a new engine iteration to allow the load to progress.
  657. // Since the only known one is the rendering server (in single thread mode), let's keep it simple and just sync it.
  658. // This may be refactored in the future to support other servers and have less coupling.
  659. if (OS::get_singleton()->get_render_thread_mode() == OS::RENDER_SEPARATE_THREAD) {
  660. return false; // Not needed.
  661. }
  662. RenderingServer::get_singleton()->sync();
  663. return true;
  664. }
  665. Ref<Resource> ResourceLoader::ensure_resource_ref_override_for_outer_load(const String &p_path, const String &p_res_type) {
  666. ERR_FAIL_COND_V(load_nesting == 0, Ref<Resource>()); // It makes no sense to use this from nesting level 0.
  667. const String &local_path = _validate_local_path(p_path);
  668. HashMap<String, Ref<Resource>> &overrides = res_ref_overrides[load_nesting - 1];
  669. HashMap<String, Ref<Resource>>::Iterator E = overrides.find(local_path);
  670. if (E) {
  671. return E->value;
  672. } else {
  673. Object *obj = ClassDB::instantiate(p_res_type);
  674. ERR_FAIL_NULL_V(obj, Ref<Resource>());
  675. Ref<Resource> res(obj);
  676. if (!res.is_valid()) {
  677. memdelete(obj);
  678. ERR_FAIL_V(Ref<Resource>());
  679. }
  680. overrides[local_path] = res;
  681. return res;
  682. }
  683. }
  684. Ref<Resource> ResourceLoader::get_resource_ref_override(const String &p_path) {
  685. DEV_ASSERT(p_path == _validate_local_path(p_path));
  686. HashMap<int, HashMap<String, Ref<Resource>>>::Iterator E = res_ref_overrides.find(load_nesting);
  687. if (!E) {
  688. return nullptr;
  689. }
  690. HashMap<String, Ref<Resource>>::Iterator F = E->value.find(p_path);
  691. if (!F) {
  692. return nullptr;
  693. }
  694. return F->value;
  695. }
  696. bool ResourceLoader::exists(const String &p_path, const String &p_type_hint) {
  697. String local_path = _validate_local_path(p_path);
  698. if (ResourceCache::has(local_path)) {
  699. return true; // If cached, it probably exists
  700. }
  701. bool xl_remapped = false;
  702. String path = _path_remap(local_path, &xl_remapped);
  703. // Try all loaders and pick the first match for the type hint
  704. for (int i = 0; i < loader_count; i++) {
  705. if (!loader[i]->recognize_path(path, p_type_hint)) {
  706. continue;
  707. }
  708. if (loader[i]->exists(path)) {
  709. return true;
  710. }
  711. }
  712. return false;
  713. }
  714. void ResourceLoader::add_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader, bool p_at_front) {
  715. ERR_FAIL_COND(p_format_loader.is_null());
  716. ERR_FAIL_COND(loader_count >= MAX_LOADERS);
  717. if (p_at_front) {
  718. for (int i = loader_count; i > 0; i--) {
  719. loader[i] = loader[i - 1];
  720. }
  721. loader[0] = p_format_loader;
  722. loader_count++;
  723. } else {
  724. loader[loader_count++] = p_format_loader;
  725. }
  726. }
  727. void ResourceLoader::remove_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader) {
  728. ERR_FAIL_COND(p_format_loader.is_null());
  729. // Find loader
  730. int i = 0;
  731. for (; i < loader_count; ++i) {
  732. if (loader[i] == p_format_loader) {
  733. break;
  734. }
  735. }
  736. ERR_FAIL_COND(i >= loader_count); // Not found
  737. // Shift next loaders up
  738. for (; i < loader_count - 1; ++i) {
  739. loader[i] = loader[i + 1];
  740. }
  741. loader[loader_count - 1].unref();
  742. --loader_count;
  743. }
  744. int ResourceLoader::get_import_order(const String &p_path) {
  745. String local_path = _path_remap(_validate_local_path(p_path));
  746. for (int i = 0; i < loader_count; i++) {
  747. if (!loader[i]->recognize_path(local_path)) {
  748. continue;
  749. }
  750. return loader[i]->get_import_order(p_path);
  751. }
  752. return 0;
  753. }
  754. String ResourceLoader::get_import_group_file(const String &p_path) {
  755. String local_path = _path_remap(_validate_local_path(p_path));
  756. for (int i = 0; i < loader_count; i++) {
  757. if (!loader[i]->recognize_path(local_path)) {
  758. continue;
  759. }
  760. return loader[i]->get_import_group_file(p_path);
  761. }
  762. return String(); //not found
  763. }
  764. bool ResourceLoader::is_import_valid(const String &p_path) {
  765. String local_path = _path_remap(_validate_local_path(p_path));
  766. for (int i = 0; i < loader_count; i++) {
  767. if (!loader[i]->recognize_path(local_path)) {
  768. continue;
  769. }
  770. return loader[i]->is_import_valid(p_path);
  771. }
  772. return false; //not found
  773. }
  774. bool ResourceLoader::is_imported(const String &p_path) {
  775. String local_path = _path_remap(_validate_local_path(p_path));
  776. for (int i = 0; i < loader_count; i++) {
  777. if (!loader[i]->recognize_path(local_path)) {
  778. continue;
  779. }
  780. return loader[i]->is_imported(p_path);
  781. }
  782. return false; //not found
  783. }
  784. void ResourceLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  785. String local_path = _path_remap(_validate_local_path(p_path));
  786. for (int i = 0; i < loader_count; i++) {
  787. if (!loader[i]->recognize_path(local_path)) {
  788. continue;
  789. }
  790. loader[i]->get_dependencies(local_path, p_dependencies, p_add_types);
  791. }
  792. }
  793. Error ResourceLoader::rename_dependencies(const String &p_path, const HashMap<String, String> &p_map) {
  794. String local_path = _path_remap(_validate_local_path(p_path));
  795. for (int i = 0; i < loader_count; i++) {
  796. if (!loader[i]->recognize_path(local_path)) {
  797. continue;
  798. }
  799. return loader[i]->rename_dependencies(local_path, p_map);
  800. }
  801. return OK; // ??
  802. }
  803. void ResourceLoader::get_classes_used(const String &p_path, HashSet<StringName> *r_classes) {
  804. String local_path = _validate_local_path(p_path);
  805. for (int i = 0; i < loader_count; i++) {
  806. if (!loader[i]->recognize_path(local_path)) {
  807. continue;
  808. }
  809. return loader[i]->get_classes_used(p_path, r_classes);
  810. }
  811. }
  812. String ResourceLoader::get_resource_type(const String &p_path) {
  813. String local_path = _validate_local_path(p_path);
  814. for (int i = 0; i < loader_count; i++) {
  815. String result = loader[i]->get_resource_type(local_path);
  816. if (!result.is_empty()) {
  817. return result;
  818. }
  819. }
  820. return "";
  821. }
  822. String ResourceLoader::get_resource_script_class(const String &p_path) {
  823. String local_path = _validate_local_path(p_path);
  824. for (int i = 0; i < loader_count; i++) {
  825. String result = loader[i]->get_resource_script_class(local_path);
  826. if (!result.is_empty()) {
  827. return result;
  828. }
  829. }
  830. return "";
  831. }
  832. ResourceUID::ID ResourceLoader::get_resource_uid(const String &p_path) {
  833. String local_path = _validate_local_path(p_path);
  834. for (int i = 0; i < loader_count; i++) {
  835. ResourceUID::ID id = loader[i]->get_resource_uid(local_path);
  836. if (id != ResourceUID::INVALID_ID) {
  837. return id;
  838. }
  839. }
  840. return ResourceUID::INVALID_ID;
  841. }
  842. String ResourceLoader::_path_remap(const String &p_path, bool *r_translation_remapped) {
  843. String new_path = p_path;
  844. if (translation_remaps.has(p_path)) {
  845. // translation_remaps has the following format:
  846. // { "res://path.png": PackedStringArray( "res://path-ru.png:ru", "res://path-de.png:de" ) }
  847. // To find the path of the remapped resource, we extract the locale name after
  848. // the last ':' to match the project locale.
  849. // An extra remap may still be necessary afterwards due to the text -> binary converter on export.
  850. String locale = TranslationServer::get_singleton()->get_locale();
  851. ERR_FAIL_COND_V_MSG(locale.length() < 2, p_path, "Could not remap path '" + p_path + "' for translation as configured locale '" + locale + "' is invalid.");
  852. Vector<String> &res_remaps = *translation_remaps.getptr(new_path);
  853. int best_score = 0;
  854. for (int i = 0; i < res_remaps.size(); i++) {
  855. int split = res_remaps[i].rfind(":");
  856. if (split == -1) {
  857. continue;
  858. }
  859. String l = res_remaps[i].substr(split + 1).strip_edges();
  860. int score = TranslationServer::get_singleton()->compare_locales(locale, l);
  861. if (score > 0 && score >= best_score) {
  862. new_path = res_remaps[i].left(split);
  863. best_score = score;
  864. if (score == 10) {
  865. break; // Exact match, skip the rest.
  866. }
  867. }
  868. }
  869. if (r_translation_remapped) {
  870. *r_translation_remapped = true;
  871. }
  872. // Fallback to p_path if new_path does not exist.
  873. if (!FileAccess::exists(new_path + ".import") && !FileAccess::exists(new_path)) {
  874. WARN_PRINT(vformat("Translation remap '%s' does not exist. Falling back to '%s'.", new_path, p_path));
  875. new_path = p_path;
  876. }
  877. }
  878. if (path_remaps.has(new_path)) {
  879. new_path = path_remaps[new_path];
  880. } else {
  881. // Try file remap.
  882. Error err;
  883. Ref<FileAccess> f = FileAccess::open(new_path + ".remap", FileAccess::READ, &err);
  884. if (f.is_valid()) {
  885. VariantParser::StreamFile stream;
  886. stream.f = f;
  887. String assign;
  888. Variant value;
  889. VariantParser::Tag next_tag;
  890. int lines = 0;
  891. String error_text;
  892. while (true) {
  893. assign = Variant();
  894. next_tag.fields.clear();
  895. next_tag.name = String();
  896. err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
  897. if (err == ERR_FILE_EOF) {
  898. break;
  899. } else if (err != OK) {
  900. ERR_PRINT("Parse error: " + p_path + ".remap:" + itos(lines) + " error: " + error_text + ".");
  901. break;
  902. }
  903. if (assign == "path") {
  904. new_path = value;
  905. break;
  906. } else if (next_tag.name != "remap") {
  907. break;
  908. }
  909. }
  910. }
  911. }
  912. return new_path;
  913. }
  914. String ResourceLoader::import_remap(const String &p_path) {
  915. if (ResourceFormatImporter::get_singleton()->recognize_path(p_path)) {
  916. return ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_path);
  917. }
  918. return p_path;
  919. }
  920. String ResourceLoader::path_remap(const String &p_path) {
  921. return _path_remap(p_path);
  922. }
  923. void ResourceLoader::reload_translation_remaps() {
  924. ResourceCache::lock.lock();
  925. List<Resource *> to_reload;
  926. SelfList<Resource> *E = remapped_list.first();
  927. while (E) {
  928. to_reload.push_back(E->self());
  929. E = E->next();
  930. }
  931. ResourceCache::lock.unlock();
  932. //now just make sure to not delete any of these resources while changing locale..
  933. while (to_reload.front()) {
  934. to_reload.front()->get()->reload_from_file();
  935. to_reload.pop_front();
  936. }
  937. }
  938. void ResourceLoader::load_translation_remaps() {
  939. if (!ProjectSettings::get_singleton()->has_setting("internationalization/locale/translation_remaps")) {
  940. return;
  941. }
  942. Dictionary remaps = GLOBAL_GET("internationalization/locale/translation_remaps");
  943. List<Variant> keys;
  944. remaps.get_key_list(&keys);
  945. for (const Variant &E : keys) {
  946. Array langs = remaps[E];
  947. Vector<String> lang_remaps;
  948. lang_remaps.resize(langs.size());
  949. String *lang_remaps_ptrw = lang_remaps.ptrw();
  950. for (const Variant &lang : langs) {
  951. *lang_remaps_ptrw++ = lang;
  952. }
  953. translation_remaps[String(E)] = lang_remaps;
  954. }
  955. }
  956. void ResourceLoader::clear_translation_remaps() {
  957. translation_remaps.clear();
  958. while (remapped_list.first() != nullptr) {
  959. remapped_list.remove(remapped_list.first());
  960. }
  961. }
  962. void ResourceLoader::clear_thread_load_tasks() {
  963. // Bring the thing down as quickly as possible without causing deadlocks or leaks.
  964. thread_load_mutex.lock();
  965. cleaning_tasks = true;
  966. while (true) {
  967. bool none_running = true;
  968. if (thread_load_tasks.size()) {
  969. for (KeyValue<String, ResourceLoader::ThreadLoadTask> &E : thread_load_tasks) {
  970. if (E.value.status == THREAD_LOAD_IN_PROGRESS) {
  971. if (E.value.cond_var) {
  972. E.value.cond_var->notify_all();
  973. memdelete(E.value.cond_var);
  974. E.value.cond_var = nullptr;
  975. }
  976. none_running = false;
  977. }
  978. }
  979. }
  980. if (none_running) {
  981. break;
  982. }
  983. thread_load_mutex.unlock();
  984. OS::get_singleton()->delay_usec(1000);
  985. thread_load_mutex.lock();
  986. }
  987. while (user_load_tokens.begin()) {
  988. // User load tokens remove themselves from the map on destruction.
  989. memdelete(user_load_tokens.begin()->value);
  990. }
  991. user_load_tokens.clear();
  992. thread_load_tasks.clear();
  993. cleaning_tasks = false;
  994. thread_load_mutex.unlock();
  995. }
  996. void ResourceLoader::load_path_remaps() {
  997. if (!ProjectSettings::get_singleton()->has_setting("path_remap/remapped_paths")) {
  998. return;
  999. }
  1000. Vector<String> remaps = GLOBAL_GET("path_remap/remapped_paths");
  1001. int rc = remaps.size();
  1002. ERR_FAIL_COND(rc & 1); //must be even
  1003. const String *r = remaps.ptr();
  1004. for (int i = 0; i < rc; i += 2) {
  1005. path_remaps[r[i]] = r[i + 1];
  1006. }
  1007. }
  1008. void ResourceLoader::clear_path_remaps() {
  1009. path_remaps.clear();
  1010. }
  1011. void ResourceLoader::set_load_callback(ResourceLoadedCallback p_callback) {
  1012. _loaded_callback = p_callback;
  1013. }
  1014. ResourceLoadedCallback ResourceLoader::_loaded_callback = nullptr;
  1015. Ref<ResourceFormatLoader> ResourceLoader::_find_custom_resource_format_loader(const String &path) {
  1016. for (int i = 0; i < loader_count; ++i) {
  1017. if (loader[i]->get_script_instance() && loader[i]->get_script_instance()->get_script()->get_path() == path) {
  1018. return loader[i];
  1019. }
  1020. }
  1021. return Ref<ResourceFormatLoader>();
  1022. }
  1023. bool ResourceLoader::add_custom_resource_format_loader(const String &script_path) {
  1024. if (_find_custom_resource_format_loader(script_path).is_valid()) {
  1025. return false;
  1026. }
  1027. Ref<Resource> res = ResourceLoader::load(script_path);
  1028. ERR_FAIL_COND_V(res.is_null(), false);
  1029. ERR_FAIL_COND_V(!res->is_class("Script"), false);
  1030. Ref<Script> s = res;
  1031. StringName ibt = s->get_instance_base_type();
  1032. bool valid_type = ClassDB::is_parent_class(ibt, "ResourceFormatLoader");
  1033. ERR_FAIL_COND_V_MSG(!valid_type, false, vformat("Failed to add a custom resource loader, script '%s' does not inherit 'ResourceFormatLoader'.", script_path));
  1034. Object *obj = ClassDB::instantiate(ibt);
  1035. ERR_FAIL_NULL_V_MSG(obj, false, vformat("Failed to add a custom resource loader, cannot instantiate '%s'.", ibt));
  1036. Ref<ResourceFormatLoader> crl = Object::cast_to<ResourceFormatLoader>(obj);
  1037. crl->set_script(s);
  1038. ResourceLoader::add_resource_format_loader(crl);
  1039. return true;
  1040. }
  1041. void ResourceLoader::set_create_missing_resources_if_class_unavailable(bool p_enable) {
  1042. create_missing_resources_if_class_unavailable = p_enable;
  1043. }
  1044. void ResourceLoader::add_custom_loaders() {
  1045. // Custom loaders registration exploits global class names
  1046. String custom_loader_base_class = ResourceFormatLoader::get_class_static();
  1047. List<StringName> global_classes;
  1048. ScriptServer::get_global_class_list(&global_classes);
  1049. for (const StringName &class_name : global_classes) {
  1050. StringName base_class = ScriptServer::get_global_class_native_base(class_name);
  1051. if (base_class == custom_loader_base_class) {
  1052. String path = ScriptServer::get_global_class_path(class_name);
  1053. add_custom_resource_format_loader(path);
  1054. }
  1055. }
  1056. }
  1057. void ResourceLoader::remove_custom_loaders() {
  1058. Vector<Ref<ResourceFormatLoader>> custom_loaders;
  1059. for (int i = 0; i < loader_count; ++i) {
  1060. if (loader[i]->get_script_instance()) {
  1061. custom_loaders.push_back(loader[i]);
  1062. }
  1063. }
  1064. for (int i = 0; i < custom_loaders.size(); ++i) {
  1065. remove_resource_format_loader(custom_loaders[i]);
  1066. }
  1067. }
  1068. bool ResourceLoader::is_cleaning_tasks() {
  1069. MutexLock lock(thread_load_mutex);
  1070. return cleaning_tasks;
  1071. }
  1072. void ResourceLoader::initialize() {}
  1073. void ResourceLoader::finalize() {}
  1074. ResourceLoadErrorNotify ResourceLoader::err_notify = nullptr;
  1075. DependencyErrorNotify ResourceLoader::dep_err_notify = nullptr;
  1076. bool ResourceLoader::create_missing_resources_if_class_unavailable = false;
  1077. bool ResourceLoader::abort_on_missing_resource = true;
  1078. bool ResourceLoader::timestamp_on_load = false;
  1079. thread_local int ResourceLoader::load_nesting = 0;
  1080. thread_local WorkerThreadPool::TaskID ResourceLoader::caller_task_id = 0;
  1081. thread_local Vector<String> *ResourceLoader::load_paths_stack;
  1082. thread_local HashMap<int, HashMap<String, Ref<Resource>>> ResourceLoader::res_ref_overrides;
  1083. template <>
  1084. thread_local uint32_t SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG>::count = 0;
  1085. SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG> ResourceLoader::thread_load_mutex;
  1086. HashMap<String, ResourceLoader::ThreadLoadTask> ResourceLoader::thread_load_tasks;
  1087. bool ResourceLoader::cleaning_tasks = false;
  1088. HashMap<String, ResourceLoader::LoadToken *> ResourceLoader::user_load_tokens;
  1089. SelfList<Resource>::List ResourceLoader::remapped_list;
  1090. HashMap<String, Vector<String>> ResourceLoader::translation_remaps;
  1091. HashMap<String, String> ResourceLoader::path_remaps;
  1092. ResourceLoaderImport ResourceLoader::import = nullptr;