resource_loader.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  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/core_bind.h"
  33. #include "core/io/dir_access.h"
  34. #include "core/io/file_access.h"
  35. #include "core/io/resource_importer.h"
  36. #include "core/object/script_language.h"
  37. #include "core/os/condition_variable.h"
  38. #include "core/os/os.h"
  39. #include "core/os/safe_binary_mutex.h"
  40. #include "core/string/print_string.h"
  41. #include "core/string/translation_server.h"
  42. #include "core/templates/rb_set.h"
  43. #include "core/variant/variant_parser.h"
  44. #include "servers/rendering_server.h"
  45. #ifdef DEBUG_LOAD_THREADED
  46. #define print_lt(m_text) print_line(m_text)
  47. #else
  48. #define print_lt(m_text)
  49. #endif
  50. Ref<ResourceFormatLoader> ResourceLoader::loader[ResourceLoader::MAX_LOADERS];
  51. int ResourceLoader::loader_count = 0;
  52. bool ResourceFormatLoader::recognize_path(const String &p_path, const String &p_for_type) const {
  53. bool ret = false;
  54. if (GDVIRTUAL_CALL(_recognize_path, p_path, p_for_type, ret)) {
  55. return ret;
  56. }
  57. List<String> extensions;
  58. if (p_for_type.is_empty()) {
  59. get_recognized_extensions(&extensions);
  60. } else {
  61. get_recognized_extensions_for_type(p_for_type, &extensions);
  62. }
  63. for (const String &E : extensions) {
  64. const String ext = !E.begins_with(".") ? "." + E : E;
  65. if (p_path.right(ext.length()).nocasecmp_to(ext) == 0) {
  66. return true;
  67. }
  68. }
  69. return false;
  70. }
  71. bool ResourceFormatLoader::handles_type(const String &p_type) const {
  72. bool success = false;
  73. GDVIRTUAL_CALL(_handles_type, p_type, success);
  74. return success;
  75. }
  76. void ResourceFormatLoader::get_classes_used(const String &p_path, HashSet<StringName> *r_classes) {
  77. Vector<String> ret;
  78. if (GDVIRTUAL_CALL(_get_classes_used, p_path, ret)) {
  79. for (int i = 0; i < ret.size(); i++) {
  80. r_classes->insert(ret[i]);
  81. }
  82. return;
  83. }
  84. String res = get_resource_type(p_path);
  85. if (!res.is_empty()) {
  86. r_classes->insert(res);
  87. }
  88. }
  89. String ResourceFormatLoader::get_resource_type(const String &p_path) const {
  90. String ret;
  91. GDVIRTUAL_CALL(_get_resource_type, p_path, ret);
  92. return ret;
  93. }
  94. String ResourceFormatLoader::get_resource_script_class(const String &p_path) const {
  95. String ret;
  96. GDVIRTUAL_CALL(_get_resource_script_class, p_path, ret);
  97. return ret;
  98. }
  99. ResourceUID::ID ResourceFormatLoader::get_resource_uid(const String &p_path) const {
  100. int64_t uid = ResourceUID::INVALID_ID;
  101. if (has_custom_uid_support()) {
  102. GDVIRTUAL_CALL(_get_resource_uid, p_path, uid);
  103. } else {
  104. Ref<FileAccess> file = FileAccess::open(p_path + ".uid", FileAccess::READ);
  105. if (file.is_valid()) {
  106. uid = ResourceUID::get_singleton()->text_to_id(file->get_line());
  107. }
  108. }
  109. return uid;
  110. }
  111. bool ResourceFormatLoader::has_custom_uid_support() const {
  112. return GDVIRTUAL_IS_OVERRIDDEN(_get_resource_uid);
  113. }
  114. void ResourceFormatLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
  115. if (p_type.is_empty() || handles_type(p_type)) {
  116. get_recognized_extensions(p_extensions);
  117. }
  118. }
  119. void ResourceLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) {
  120. for (int i = 0; i < loader_count; i++) {
  121. loader[i]->get_recognized_extensions_for_type(p_type, p_extensions);
  122. }
  123. }
  124. bool ResourceFormatLoader::exists(const String &p_path) const {
  125. bool success = false;
  126. if (GDVIRTUAL_CALL(_exists, p_path, success)) {
  127. return success;
  128. }
  129. return FileAccess::exists(p_path); // By default just check file.
  130. }
  131. void ResourceFormatLoader::get_recognized_extensions(List<String> *p_extensions) const {
  132. PackedStringArray exts;
  133. if (GDVIRTUAL_CALL(_get_recognized_extensions, exts)) {
  134. const String *r = exts.ptr();
  135. for (int i = 0; i < exts.size(); ++i) {
  136. p_extensions->push_back(r[i]);
  137. }
  138. }
  139. }
  140. 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) {
  141. Variant res;
  142. if (GDVIRTUAL_CALL(_load, p_path, p_original_path, p_use_sub_threads, p_cache_mode, res)) {
  143. if (res.get_type() == Variant::INT) { // Error code, abort.
  144. if (r_error) {
  145. *r_error = (Error)res.operator int64_t();
  146. }
  147. return Ref<Resource>();
  148. } else { // Success, pass on result.
  149. if (r_error) {
  150. *r_error = OK;
  151. }
  152. return res;
  153. }
  154. }
  155. ERR_FAIL_V_MSG(Ref<Resource>(), vformat("Failed to load resource '%s'. ResourceFormatLoader::load was not implemented for this resource type.", p_path));
  156. }
  157. void ResourceFormatLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  158. PackedStringArray deps;
  159. if (GDVIRTUAL_CALL(_get_dependencies, p_path, p_add_types, deps)) {
  160. const String *r = deps.ptr();
  161. for (int i = 0; i < deps.size(); ++i) {
  162. p_dependencies->push_back(r[i]);
  163. }
  164. }
  165. }
  166. Error ResourceFormatLoader::rename_dependencies(const String &p_path, const HashMap<String, String> &p_map) {
  167. Dictionary deps_dict;
  168. for (KeyValue<String, String> E : p_map) {
  169. deps_dict[E.key] = E.value;
  170. }
  171. Error err = OK;
  172. GDVIRTUAL_CALL(_rename_dependencies, p_path, deps_dict, err);
  173. return err;
  174. }
  175. void ResourceFormatLoader::_bind_methods() {
  176. BIND_ENUM_CONSTANT(CACHE_MODE_IGNORE);
  177. BIND_ENUM_CONSTANT(CACHE_MODE_REUSE);
  178. BIND_ENUM_CONSTANT(CACHE_MODE_REPLACE);
  179. BIND_ENUM_CONSTANT(CACHE_MODE_IGNORE_DEEP);
  180. BIND_ENUM_CONSTANT(CACHE_MODE_REPLACE_DEEP);
  181. GDVIRTUAL_BIND(_get_recognized_extensions);
  182. GDVIRTUAL_BIND(_recognize_path, "path", "type");
  183. GDVIRTUAL_BIND(_handles_type, "type");
  184. GDVIRTUAL_BIND(_get_resource_type, "path");
  185. GDVIRTUAL_BIND(_get_resource_script_class, "path");
  186. GDVIRTUAL_BIND(_get_resource_uid, "path");
  187. GDVIRTUAL_BIND(_get_dependencies, "path", "add_types");
  188. GDVIRTUAL_BIND(_rename_dependencies, "path", "renames");
  189. GDVIRTUAL_BIND(_exists, "path");
  190. GDVIRTUAL_BIND(_get_classes_used, "path");
  191. GDVIRTUAL_BIND(_load, "path", "original_path", "use_sub_threads", "cache_mode");
  192. }
  193. ///////////////////////////////////
  194. // These are used before and after a wait for a WorkerThreadPool task
  195. // because that can lead to another load started in the same thread,
  196. // something we must treat as a different stack for the purposes
  197. // of tracking nesting.
  198. #define PREPARE_FOR_WTP_WAIT \
  199. int load_nesting_backup = ResourceLoader::load_nesting; \
  200. Vector<String> load_paths_stack_backup = ResourceLoader::load_paths_stack; \
  201. ResourceLoader::load_nesting = 0; \
  202. ResourceLoader::load_paths_stack.clear();
  203. #define RESTORE_AFTER_WTP_WAIT \
  204. DEV_ASSERT(ResourceLoader::load_nesting == 0); \
  205. DEV_ASSERT(ResourceLoader::load_paths_stack.is_empty()); \
  206. ResourceLoader::load_nesting = load_nesting_backup; \
  207. ResourceLoader::load_paths_stack = load_paths_stack_backup; \
  208. load_paths_stack_backup.clear();
  209. // This should be robust enough to be called redundantly without issues.
  210. void ResourceLoader::LoadToken::clear() {
  211. WorkerThreadPool::TaskID task_to_await = 0;
  212. {
  213. MutexLock thread_load_lock(thread_load_mutex);
  214. // User-facing tokens shouldn't be deleted until completely claimed.
  215. DEV_ASSERT(user_rc == 0 && user_path.is_empty());
  216. if (!local_path.is_empty()) {
  217. if (task_if_unregistered) {
  218. memdelete(task_if_unregistered);
  219. task_if_unregistered = nullptr;
  220. } else {
  221. DEV_ASSERT(thread_load_tasks.has(local_path));
  222. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  223. if (load_task.task_id && !load_task.awaited) {
  224. task_to_await = load_task.task_id;
  225. }
  226. // Removing a task which is still in progress would be catastrophic.
  227. // Tokens must be alive until the task thread function is done.
  228. DEV_ASSERT(load_task.status == THREAD_LOAD_FAILED || load_task.status == THREAD_LOAD_LOADED);
  229. thread_load_tasks.erase(local_path);
  230. }
  231. local_path.clear(); // Mark as already cleared.
  232. if (task_to_await) {
  233. for (KeyValue<String, ResourceLoader::ThreadLoadTask> &E : thread_load_tasks) {
  234. if (E.value.task_id == task_to_await) {
  235. task_to_await = 0;
  236. break; // Same task is reused by nested loads, do not wait for completion here.
  237. }
  238. }
  239. }
  240. }
  241. }
  242. // If task is unused, await it here, locally, now the token data is consistent.
  243. if (task_to_await) {
  244. PREPARE_FOR_WTP_WAIT
  245. WorkerThreadPool::get_singleton()->wait_for_task_completion(task_to_await);
  246. RESTORE_AFTER_WTP_WAIT
  247. }
  248. }
  249. ResourceLoader::LoadToken::~LoadToken() {
  250. clear();
  251. }
  252. 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) {
  253. const String &original_path = p_original_path.is_empty() ? p_path : p_original_path;
  254. load_nesting++;
  255. if (load_paths_stack.size()) {
  256. MutexLock thread_load_lock(thread_load_mutex);
  257. const String &parent_task_path = load_paths_stack.get(load_paths_stack.size() - 1);
  258. HashMap<String, ThreadLoadTask>::Iterator E = thread_load_tasks.find(parent_task_path);
  259. // Avoid double-tracking, for progress reporting, resources that boil down to a remapped path containing the real payload (e.g., imported resources).
  260. bool is_remapped_load = original_path == parent_task_path;
  261. if (E && !is_remapped_load) {
  262. E->value.sub_tasks.insert(original_path);
  263. }
  264. }
  265. load_paths_stack.push_back(original_path);
  266. print_verbose(vformat("Loading resource: %s", p_path));
  267. // Try all loaders and pick the first match for the type hint
  268. bool found = false;
  269. Ref<Resource> res;
  270. for (int i = 0; i < loader_count; i++) {
  271. if (!loader[i]->recognize_path(p_path, p_type_hint)) {
  272. continue;
  273. }
  274. found = true;
  275. res = loader[i]->load(p_path, original_path, r_error, p_use_sub_threads, r_progress, p_cache_mode);
  276. if (res.is_valid()) {
  277. break;
  278. }
  279. }
  280. load_paths_stack.resize(load_paths_stack.size() - 1);
  281. res_ref_overrides.erase(load_nesting);
  282. load_nesting--;
  283. if (res.is_valid()) {
  284. return res;
  285. } else {
  286. print_verbose(vformat("Failed loading resource: %s", p_path));
  287. }
  288. #ifdef TOOLS_ENABLED
  289. if (Engine::get_singleton()->is_editor_hint()) {
  290. if (ResourceFormatImporter::get_singleton()->get_importer_by_file(p_path).is_valid()) {
  291. // The format is known to the editor, but the file hasn't been imported
  292. // (otherwise, ResourceFormatImporter would have been found as a suitable loader).
  293. found = true;
  294. if (r_error) {
  295. *r_error = ERR_FILE_NOT_FOUND;
  296. }
  297. }
  298. }
  299. #endif
  300. ERR_FAIL_COND_V_MSG(found, Ref<Resource>(), vformat("Failed loading resource: %s.", p_path));
  301. #ifdef TOOLS_ENABLED
  302. Ref<FileAccess> file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);
  303. if (!file_check->file_exists(p_path)) {
  304. if (r_error) {
  305. *r_error = ERR_FILE_NOT_FOUND;
  306. }
  307. ERR_FAIL_V_MSG(Ref<Resource>(), vformat("Resource file not found: %s (expected type: %s)", p_path, !p_type_hint.is_empty() ? p_type_hint : "unknown"));
  308. }
  309. #endif
  310. if (r_error) {
  311. *r_error = ERR_FILE_UNRECOGNIZED;
  312. }
  313. ERR_FAIL_V_MSG(Ref<Resource>(), vformat("No loader found for resource: %s (expected type: %s)", p_path, !p_type_hint.is_empty() ? p_type_hint : "unknown"));
  314. }
  315. // This implementation must allow re-entrancy for a task that started awaiting in a deeper stack frame.
  316. // The load task token must be manually re-referenced before this is called, which includes threaded runs.
  317. void ResourceLoader::_run_load_task(void *p_userdata) {
  318. ThreadLoadTask &load_task = *(ThreadLoadTask *)p_userdata;
  319. {
  320. MutexLock thread_load_lock(thread_load_mutex);
  321. if (cleaning_tasks) {
  322. load_task.status = THREAD_LOAD_FAILED;
  323. return;
  324. }
  325. }
  326. ThreadLoadTask *curr_load_task_backup = curr_load_task;
  327. curr_load_task = &load_task;
  328. // Thread-safe either if it's the current thread or a brand new one.
  329. CallQueue *own_mq_override = nullptr;
  330. if (load_nesting == 0) {
  331. DEV_ASSERT(load_paths_stack.is_empty());
  332. if (!Thread::is_main_thread()) {
  333. // Let the caller thread use its own, for added flexibility. Provide one otherwise.
  334. if (MessageQueue::get_singleton() == MessageQueue::get_main_singleton()) {
  335. own_mq_override = memnew(CallQueue);
  336. MessageQueue::set_thread_singleton_override(own_mq_override);
  337. }
  338. set_current_thread_safe_for_nodes(true);
  339. }
  340. }
  341. // --
  342. bool xl_remapped = false;
  343. const String &remapped_path = _path_remap(load_task.local_path, &xl_remapped);
  344. Error load_err = OK;
  345. Ref<Resource> res = _load(remapped_path, remapped_path != load_task.local_path ? load_task.local_path : String(), load_task.type_hint, load_task.cache_mode, &load_err, load_task.use_sub_threads, &load_task.progress);
  346. if (MessageQueue::get_singleton() != MessageQueue::get_main_singleton()) {
  347. MessageQueue::get_singleton()->flush();
  348. }
  349. thread_load_mutex.lock();
  350. load_task.resource = res;
  351. load_task.progress = 1.0; // It was fully loaded at this point, so force progress to 1.0.
  352. load_task.error = load_err;
  353. if (load_task.error != OK) {
  354. load_task.status = THREAD_LOAD_FAILED;
  355. } else {
  356. load_task.status = THREAD_LOAD_LOADED;
  357. }
  358. if (load_task.cond_var && load_task.need_wait) {
  359. load_task.cond_var->notify_all();
  360. }
  361. load_task.need_wait = false;
  362. bool ignoring = load_task.cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE || load_task.cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE_DEEP;
  363. bool replacing = load_task.cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE || load_task.cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE_DEEP;
  364. bool unlock_pending = true;
  365. if (load_task.resource.is_valid()) {
  366. // From now on, no critical section needed as no one will write to the task anymore.
  367. // Moreover, the mutex being unlocked is a requirement if some of the calls below
  368. // that set the resource up invoke code that in turn requests resource loading.
  369. thread_load_mutex.unlock();
  370. unlock_pending = false;
  371. if (!ignoring) {
  372. ResourceCache::lock.lock(); // Check and operations must happen atomically.
  373. bool pending_unlock = true;
  374. Ref<Resource> old_res = ResourceCache::get_ref(load_task.local_path);
  375. if (old_res.is_valid()) {
  376. if (old_res != load_task.resource) {
  377. // Resource can already exists at this point for two reasons:
  378. // a) The load uses replace mode.
  379. // b) There were more than one load in flight for the same path because of deadlock prevention.
  380. // Either case, we want to keep the resource that was already there.
  381. ResourceCache::lock.unlock();
  382. pending_unlock = false;
  383. if (replacing) {
  384. old_res->copy_from(load_task.resource);
  385. }
  386. load_task.resource = old_res;
  387. }
  388. } else {
  389. load_task.resource->set_path(load_task.local_path);
  390. }
  391. if (pending_unlock) {
  392. ResourceCache::lock.unlock();
  393. }
  394. } else {
  395. load_task.resource->set_path_cache(load_task.local_path);
  396. }
  397. if (xl_remapped) {
  398. load_task.resource->set_as_translation_remapped(true);
  399. }
  400. #ifdef TOOLS_ENABLED
  401. load_task.resource->set_edited(false);
  402. if (timestamp_on_load) {
  403. uint64_t mt = FileAccess::get_modified_time(remapped_path);
  404. //printf("mt %s: %lli\n",remapped_path.utf8().get_data(),mt);
  405. load_task.resource->set_last_modified_time(mt);
  406. }
  407. #endif
  408. if (_loaded_callback) {
  409. _loaded_callback(load_task.resource, load_task.local_path);
  410. }
  411. } else if (!ignoring) {
  412. Ref<Resource> existing = ResourceCache::get_ref(load_task.local_path);
  413. if (existing.is_valid()) {
  414. load_task.resource = existing;
  415. load_task.status = THREAD_LOAD_LOADED;
  416. load_task.progress = 1.0;
  417. thread_load_mutex.unlock();
  418. unlock_pending = false;
  419. if (_loaded_callback) {
  420. _loaded_callback(load_task.resource, load_task.local_path);
  421. }
  422. }
  423. }
  424. // It's safe now to let the task go in case no one else was grabbing the token.
  425. load_task.load_token->unreference();
  426. if (unlock_pending) {
  427. thread_load_mutex.unlock();
  428. }
  429. if (load_nesting == 0) {
  430. if (own_mq_override) {
  431. MessageQueue::set_thread_singleton_override(nullptr);
  432. memdelete(own_mq_override);
  433. }
  434. DEV_ASSERT(load_paths_stack.is_empty());
  435. }
  436. curr_load_task = curr_load_task_backup;
  437. }
  438. String ResourceLoader::_validate_local_path(const String &p_path) {
  439. ResourceUID::ID uid = ResourceUID::get_singleton()->text_to_id(p_path);
  440. if (uid != ResourceUID::INVALID_ID) {
  441. return ResourceUID::get_singleton()->get_id_path(uid);
  442. } else if (p_path.is_relative_path()) {
  443. return ("res://" + p_path).simplify_path();
  444. } else {
  445. return ProjectSettings::get_singleton()->localize_path(p_path);
  446. }
  447. }
  448. Error ResourceLoader::load_threaded_request(const String &p_path, const String &p_type_hint, bool p_use_sub_threads, ResourceFormatLoader::CacheMode p_cache_mode) {
  449. 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, true);
  450. return token.is_valid() ? OK : FAILED;
  451. }
  452. ResourceLoader::LoadToken *ResourceLoader::_load_threaded_request_reuse_user_token(const String &p_path) {
  453. HashMap<String, LoadToken *>::Iterator E = user_load_tokens.find(p_path);
  454. if (E) {
  455. print_verbose("load_threaded_request(): Another threaded load for resource path '" + p_path + "' has been initiated. Not an error.");
  456. LoadToken *token = E->value;
  457. token->user_rc++;
  458. return token;
  459. } else {
  460. return nullptr;
  461. }
  462. }
  463. void ResourceLoader::_load_threaded_request_setup_user_token(LoadToken *p_token, const String &p_path) {
  464. p_token->user_path = p_path;
  465. p_token->reference(); // Extra RC until all user requests have been gotten.
  466. p_token->user_rc = 1;
  467. user_load_tokens[p_path] = p_token;
  468. print_lt("REQUEST: user load tokens: " + itos(user_load_tokens.size()));
  469. }
  470. Ref<Resource> ResourceLoader::load(const String &p_path, const String &p_type_hint, ResourceFormatLoader::CacheMode p_cache_mode, Error *r_error) {
  471. if (r_error) {
  472. *r_error = OK;
  473. }
  474. LoadThreadMode thread_mode = LOAD_THREAD_FROM_CURRENT;
  475. if (WorkerThreadPool::get_singleton()->get_caller_task_id() != WorkerThreadPool::INVALID_TASK_ID) {
  476. // If user is initiating a single-threaded load from a WorkerThreadPool task,
  477. // we instead spawn a new task so there's a precondition that a load in a pool task
  478. // is always initiated by the engine. That makes certain aspects simpler, such as
  479. // cyclic load detection and awaiting.
  480. thread_mode = LOAD_THREAD_SPAWN_SINGLE;
  481. }
  482. Ref<LoadToken> load_token = _load_start(p_path, p_type_hint, thread_mode, p_cache_mode);
  483. if (load_token.is_null()) {
  484. if (r_error) {
  485. *r_error = FAILED;
  486. }
  487. return Ref<Resource>();
  488. }
  489. Ref<Resource> res = _load_complete(*load_token.ptr(), r_error);
  490. return res;
  491. }
  492. Ref<ResourceLoader::LoadToken> ResourceLoader::_load_start(const String &p_path, const String &p_type_hint, LoadThreadMode p_thread_mode, ResourceFormatLoader::CacheMode p_cache_mode, bool p_for_user) {
  493. String local_path = _validate_local_path(p_path);
  494. ERR_FAIL_COND_V(local_path.is_empty(), Ref<ResourceLoader::LoadToken>());
  495. bool ignoring_cache = p_cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE || p_cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE_DEEP;
  496. Ref<LoadToken> load_token;
  497. bool must_not_register = false;
  498. ThreadLoadTask *load_task_ptr = nullptr;
  499. {
  500. MutexLock thread_load_lock(thread_load_mutex);
  501. if (p_for_user) {
  502. LoadToken *existing_token = _load_threaded_request_reuse_user_token(p_path);
  503. if (existing_token) {
  504. return Ref<LoadToken>(existing_token);
  505. }
  506. }
  507. if (!ignoring_cache && thread_load_tasks.has(local_path)) {
  508. load_token = Ref<LoadToken>(thread_load_tasks[local_path].load_token);
  509. if (load_token.is_valid()) {
  510. if (p_for_user) {
  511. // Load task exists, with no user tokens at the moment.
  512. // Let's "attach" to it.
  513. _load_threaded_request_setup_user_token(load_token.ptr(), p_path);
  514. }
  515. return load_token;
  516. } else {
  517. // The token is dying (reached 0 on another thread).
  518. // Ensure it's killed now so the path can be safely reused right away.
  519. thread_load_tasks[local_path].load_token->clear();
  520. }
  521. }
  522. load_token.instantiate();
  523. load_token->local_path = local_path;
  524. if (p_for_user) {
  525. _load_threaded_request_setup_user_token(load_token.ptr(), p_path);
  526. }
  527. //create load task
  528. {
  529. ThreadLoadTask load_task;
  530. load_task.load_token = load_token.ptr();
  531. load_task.local_path = local_path;
  532. load_task.type_hint = p_type_hint;
  533. load_task.cache_mode = p_cache_mode;
  534. load_task.use_sub_threads = p_thread_mode == LOAD_THREAD_DISTRIBUTE;
  535. if (p_cache_mode == ResourceFormatLoader::CACHE_MODE_REUSE) {
  536. Ref<Resource> existing = ResourceCache::get_ref(local_path);
  537. if (existing.is_valid()) {
  538. //referencing is fine
  539. load_task.resource = existing;
  540. load_task.status = THREAD_LOAD_LOADED;
  541. load_task.progress = 1.0;
  542. DEV_ASSERT(!thread_load_tasks.has(local_path));
  543. thread_load_tasks[local_path] = load_task;
  544. return load_token;
  545. }
  546. }
  547. // If we want to ignore cache, but there's another task loading it, we can't add this one to the map.
  548. must_not_register = ignoring_cache && thread_load_tasks.has(local_path);
  549. if (must_not_register) {
  550. load_token->task_if_unregistered = memnew(ThreadLoadTask(load_task));
  551. load_task_ptr = load_token->task_if_unregistered;
  552. } else {
  553. DEV_ASSERT(!thread_load_tasks.has(local_path));
  554. HashMap<String, ResourceLoader::ThreadLoadTask>::Iterator E = thread_load_tasks.insert(local_path, load_task);
  555. load_task_ptr = &E->value;
  556. }
  557. }
  558. // It's important to keep the token alive because until the load completes,
  559. // which includes before the thread start, it may happen that no one is grabbing
  560. // the token anymore so it's released.
  561. load_task_ptr->load_token->reference();
  562. if (p_thread_mode == LOAD_THREAD_FROM_CURRENT) {
  563. // The current thread may happen to be a thread from the pool.
  564. WorkerThreadPool::TaskID tid = WorkerThreadPool::get_singleton()->get_caller_task_id();
  565. if (tid != WorkerThreadPool::INVALID_TASK_ID) {
  566. load_task_ptr->task_id = tid;
  567. } else {
  568. load_task_ptr->thread_id = Thread::get_caller_id();
  569. }
  570. } else {
  571. load_task_ptr->task_id = WorkerThreadPool::get_singleton()->add_native_task(&ResourceLoader::_run_load_task, load_task_ptr);
  572. }
  573. } // MutexLock(thread_load_mutex).
  574. if (p_thread_mode == LOAD_THREAD_FROM_CURRENT) {
  575. _run_load_task(load_task_ptr);
  576. }
  577. return load_token;
  578. }
  579. float ResourceLoader::_dependency_get_progress(const String &p_path) {
  580. if (thread_load_tasks.has(p_path)) {
  581. ThreadLoadTask &load_task = thread_load_tasks[p_path];
  582. float current_progress = 0.0;
  583. int dep_count = load_task.sub_tasks.size();
  584. if (dep_count > 0) {
  585. for (const String &E : load_task.sub_tasks) {
  586. current_progress += _dependency_get_progress(E);
  587. }
  588. current_progress /= float(dep_count);
  589. current_progress *= 0.5;
  590. current_progress += load_task.progress * 0.5;
  591. } else {
  592. current_progress = load_task.progress;
  593. }
  594. load_task.max_reported_progress = MAX(load_task.max_reported_progress, current_progress);
  595. return load_task.max_reported_progress;
  596. } else {
  597. return 1.0; //assume finished loading it so it no longer exists
  598. }
  599. }
  600. ResourceLoader::ThreadLoadStatus ResourceLoader::load_threaded_get_status(const String &p_path, float *r_progress) {
  601. bool ensure_progress = false;
  602. ThreadLoadStatus status = THREAD_LOAD_IN_PROGRESS;
  603. {
  604. MutexLock thread_load_lock(thread_load_mutex);
  605. if (!user_load_tokens.has(p_path)) {
  606. print_verbose("load_threaded_get_status(): No threaded load for resource path '" + p_path + "' has been initiated or its result has already been collected.");
  607. return THREAD_LOAD_INVALID_RESOURCE;
  608. }
  609. String local_path = _validate_local_path(p_path);
  610. ERR_FAIL_COND_V_MSG(!thread_load_tasks.has(local_path), THREAD_LOAD_INVALID_RESOURCE, "Bug in ResourceLoader logic, please report.");
  611. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  612. status = load_task.status;
  613. if (r_progress) {
  614. *r_progress = _dependency_get_progress(local_path);
  615. }
  616. // Support userland polling in a loop on the main thread.
  617. if (Thread::is_main_thread() && status == THREAD_LOAD_IN_PROGRESS) {
  618. uint64_t frame = Engine::get_singleton()->get_process_frames();
  619. if (frame == load_task.last_progress_check_main_thread_frame) {
  620. ensure_progress = true;
  621. } else {
  622. load_task.last_progress_check_main_thread_frame = frame;
  623. }
  624. }
  625. }
  626. if (ensure_progress) {
  627. _ensure_load_progress();
  628. }
  629. return status;
  630. }
  631. Ref<Resource> ResourceLoader::load_threaded_get(const String &p_path, Error *r_error) {
  632. if (r_error) {
  633. *r_error = OK;
  634. }
  635. Ref<Resource> res;
  636. {
  637. MutexLock thread_load_lock(thread_load_mutex);
  638. if (!user_load_tokens.has(p_path)) {
  639. print_verbose("load_threaded_get(): No threaded load for resource path '" + p_path + "' has been initiated or its result has already been collected.");
  640. if (r_error) {
  641. *r_error = ERR_INVALID_PARAMETER;
  642. }
  643. return Ref<Resource>();
  644. }
  645. LoadToken *load_token = user_load_tokens[p_path];
  646. DEV_ASSERT(load_token->user_rc >= 1);
  647. // Support userland requesting on the main thread before the load is reported to be complete.
  648. if (Thread::is_main_thread() && !load_token->local_path.is_empty()) {
  649. const ThreadLoadTask &load_task = thread_load_tasks[load_token->local_path];
  650. while (load_task.status == THREAD_LOAD_IN_PROGRESS) {
  651. thread_load_lock.temp_unlock();
  652. bool exit = !_ensure_load_progress();
  653. OS::get_singleton()->delay_usec(1000);
  654. thread_load_lock.temp_relock();
  655. if (exit) {
  656. break;
  657. }
  658. }
  659. }
  660. res = _load_complete_inner(*load_token, r_error, thread_load_lock);
  661. load_token->user_rc--;
  662. if (load_token->user_rc == 0) {
  663. load_token->user_path.clear();
  664. user_load_tokens.erase(p_path);
  665. if (load_token->unreference()) {
  666. memdelete(load_token);
  667. load_token = nullptr;
  668. }
  669. }
  670. }
  671. print_lt("GET: user load tokens: " + itos(user_load_tokens.size()));
  672. return res;
  673. }
  674. Ref<Resource> ResourceLoader::_load_complete(LoadToken &p_load_token, Error *r_error) {
  675. MutexLock thread_load_lock(thread_load_mutex);
  676. return _load_complete_inner(p_load_token, r_error, thread_load_lock);
  677. }
  678. void ResourceLoader::set_is_import_thread(bool p_import_thread) {
  679. import_thread = p_import_thread;
  680. }
  681. Ref<Resource> ResourceLoader::_load_complete_inner(LoadToken &p_load_token, Error *r_error, MutexLock<SafeBinaryMutex<BINARY_MUTEX_TAG>> &p_thread_load_lock) {
  682. if (r_error) {
  683. *r_error = OK;
  684. }
  685. ThreadLoadTask *load_task_ptr = nullptr;
  686. if (p_load_token.task_if_unregistered) {
  687. load_task_ptr = p_load_token.task_if_unregistered;
  688. } else {
  689. if (!thread_load_tasks.has(p_load_token.local_path)) {
  690. if (r_error) {
  691. *r_error = ERR_BUG;
  692. }
  693. ERR_FAIL_V_MSG(Ref<Resource>(), "Bug in ResourceLoader logic, please report.");
  694. }
  695. ThreadLoadTask &load_task = thread_load_tasks[p_load_token.local_path];
  696. if (load_task.status == THREAD_LOAD_IN_PROGRESS) {
  697. DEV_ASSERT((load_task.task_id == 0) != (load_task.thread_id == 0));
  698. if ((load_task.task_id != 0 && load_task.task_id == WorkerThreadPool::get_singleton()->get_caller_task_id()) ||
  699. (load_task.thread_id != 0 && load_task.thread_id == Thread::get_caller_id())) {
  700. // Load is in progress, but it's precisely this thread the one in charge.
  701. // That means this is a cyclic load.
  702. if (r_error) {
  703. *r_error = ERR_BUSY;
  704. }
  705. return Ref<Resource>();
  706. }
  707. bool loader_is_wtp = load_task.task_id != 0;
  708. if (loader_is_wtp) {
  709. // Loading thread is in the worker pool.
  710. p_thread_load_lock.temp_unlock();
  711. PREPARE_FOR_WTP_WAIT
  712. Error wait_err = WorkerThreadPool::get_singleton()->wait_for_task_completion(load_task.task_id);
  713. RESTORE_AFTER_WTP_WAIT
  714. DEV_ASSERT(!wait_err || wait_err == ERR_BUSY);
  715. if (wait_err == ERR_BUSY) {
  716. // The WorkerThreadPool has reported that the current task wants to await on an older one.
  717. // That't not allowed for safety, to avoid deadlocks. Fortunately, though, in the context of
  718. // resource loading that means that the task to wait for can be restarted here to break the
  719. // cycle, with as much recursion into this process as needed.
  720. // When the stack is eventually unrolled, the original load will have been notified to go on.
  721. load_task.load_token->reference();
  722. _run_load_task(&load_task);
  723. }
  724. p_thread_load_lock.temp_relock();
  725. load_task.awaited = true;
  726. // Mark nested loads with the same task id as awaited.
  727. for (KeyValue<String, ResourceLoader::ThreadLoadTask> &E : thread_load_tasks) {
  728. if (E.value.task_id == load_task.task_id) {
  729. E.value.awaited = true;
  730. }
  731. }
  732. DEV_ASSERT(load_task.status == THREAD_LOAD_FAILED || load_task.status == THREAD_LOAD_LOADED);
  733. } else if (load_task.need_wait) {
  734. // Loading thread is main or user thread.
  735. if (!load_task.cond_var) {
  736. load_task.cond_var = memnew(ConditionVariable);
  737. }
  738. load_task.awaiters_count++;
  739. do {
  740. load_task.cond_var->wait(p_thread_load_lock);
  741. DEV_ASSERT(thread_load_tasks.has(p_load_token.local_path) && p_load_token.get_reference_count());
  742. } while (load_task.need_wait);
  743. load_task.awaiters_count--;
  744. if (load_task.awaiters_count == 0) {
  745. memdelete(load_task.cond_var);
  746. load_task.cond_var = nullptr;
  747. }
  748. DEV_ASSERT(load_task.status == THREAD_LOAD_FAILED || load_task.status == THREAD_LOAD_LOADED);
  749. }
  750. }
  751. if (cleaning_tasks) {
  752. load_task.resource = Ref<Resource>();
  753. load_task.error = FAILED;
  754. }
  755. load_task_ptr = &load_task;
  756. }
  757. p_thread_load_lock.temp_unlock();
  758. Ref<Resource> resource = load_task_ptr->resource;
  759. if (r_error) {
  760. *r_error = load_task_ptr->error;
  761. }
  762. if (resource.is_valid()) {
  763. if (curr_load_task) {
  764. // A task awaiting another => Let the awaiter accumulate the resource changed connections.
  765. DEV_ASSERT(curr_load_task != load_task_ptr);
  766. for (const ThreadLoadTask::ResourceChangedConnection &rcc : load_task_ptr->resource_changed_connections) {
  767. curr_load_task->resource_changed_connections.push_back(rcc);
  768. }
  769. } else {
  770. // A leaf task being awaited => Propagate the resource changed connections.
  771. if (Thread::is_main_thread()) {
  772. // On the main thread it's safe to migrate the connections to the standard signal mechanism.
  773. for (const ThreadLoadTask::ResourceChangedConnection &rcc : load_task_ptr->resource_changed_connections) {
  774. if (rcc.callable.is_valid()) {
  775. rcc.source->connect_changed(rcc.callable, rcc.flags);
  776. }
  777. }
  778. } else {
  779. // On non-main threads, we have to queue and call it done when processed.
  780. if (!load_task_ptr->resource_changed_connections.is_empty()) {
  781. for (const ThreadLoadTask::ResourceChangedConnection &rcc : load_task_ptr->resource_changed_connections) {
  782. if (rcc.callable.is_valid()) {
  783. MessageQueue::get_main_singleton()->push_callable(callable_mp(rcc.source, &Resource::connect_changed).bind(rcc.callable, rcc.flags));
  784. }
  785. }
  786. if (!import_thread) { // Main thread is blocked by initial resource reimport, do not wait.
  787. CoreBind::Semaphore done;
  788. MessageQueue::get_main_singleton()->push_callable(callable_mp(&done, &CoreBind::Semaphore::post).bind(1));
  789. done.wait();
  790. }
  791. }
  792. }
  793. }
  794. }
  795. p_thread_load_lock.temp_relock();
  796. return resource;
  797. }
  798. bool ResourceLoader::_ensure_load_progress() {
  799. // Some servers may need a new engine iteration to allow the load to progress.
  800. // Since the only known one is the rendering server (in single thread mode), let's keep it simple and just sync it.
  801. // This may be refactored in the future to support other servers and have less coupling.
  802. if (OS::get_singleton()->is_separate_thread_rendering_enabled()) {
  803. return false; // Not needed.
  804. }
  805. RenderingServer::get_singleton()->sync();
  806. return true;
  807. }
  808. void ResourceLoader::resource_changed_connect(Resource *p_source, const Callable &p_callable, uint32_t p_flags) {
  809. print_lt(vformat("%d\t%ud:%s\t" FUNCTION_STR "\t%d", Thread::get_caller_id(), p_source->get_instance_id(), p_source->get_class(), p_callable.get_object_id()));
  810. MutexLock lock(thread_load_mutex);
  811. for (const ThreadLoadTask::ResourceChangedConnection &rcc : curr_load_task->resource_changed_connections) {
  812. if (unlikely(rcc.source == p_source && rcc.callable == p_callable)) {
  813. return;
  814. }
  815. }
  816. ThreadLoadTask::ResourceChangedConnection rcc;
  817. rcc.source = p_source;
  818. rcc.callable = p_callable;
  819. rcc.flags = p_flags;
  820. curr_load_task->resource_changed_connections.push_back(rcc);
  821. }
  822. void ResourceLoader::resource_changed_disconnect(Resource *p_source, const Callable &p_callable) {
  823. print_lt(vformat("%d\t%ud:%s\t" FUNCTION_STR "t%d", Thread::get_caller_id(), p_source->get_instance_id(), p_source->get_class(), p_callable.get_object_id()));
  824. MutexLock lock(thread_load_mutex);
  825. for (uint32_t i = 0; i < curr_load_task->resource_changed_connections.size(); ++i) {
  826. const ThreadLoadTask::ResourceChangedConnection &rcc = curr_load_task->resource_changed_connections[i];
  827. if (unlikely(rcc.source == p_source && rcc.callable == p_callable)) {
  828. curr_load_task->resource_changed_connections.remove_at_unordered(i);
  829. return;
  830. }
  831. }
  832. }
  833. void ResourceLoader::resource_changed_emit(Resource *p_source) {
  834. print_lt(vformat("%d\t%ud:%s\t" FUNCTION_STR, Thread::get_caller_id(), p_source->get_instance_id(), p_source->get_class()));
  835. MutexLock lock(thread_load_mutex);
  836. for (const ThreadLoadTask::ResourceChangedConnection &rcc : curr_load_task->resource_changed_connections) {
  837. if (unlikely(rcc.source == p_source)) {
  838. rcc.callable.call();
  839. }
  840. }
  841. }
  842. Ref<Resource> ResourceLoader::ensure_resource_ref_override_for_outer_load(const String &p_path, const String &p_res_type) {
  843. ERR_FAIL_COND_V(load_nesting == 0, Ref<Resource>()); // It makes no sense to use this from nesting level 0.
  844. const String &local_path = _validate_local_path(p_path);
  845. HashMap<String, Ref<Resource>> &overrides = res_ref_overrides[load_nesting - 1];
  846. HashMap<String, Ref<Resource>>::Iterator E = overrides.find(local_path);
  847. if (E) {
  848. return E->value;
  849. } else {
  850. Object *obj = ClassDB::instantiate(p_res_type);
  851. ERR_FAIL_NULL_V(obj, Ref<Resource>());
  852. Ref<Resource> res(obj);
  853. if (res.is_null()) {
  854. memdelete(obj);
  855. ERR_FAIL_V(Ref<Resource>());
  856. }
  857. overrides[local_path] = res;
  858. return res;
  859. }
  860. }
  861. Ref<Resource> ResourceLoader::get_resource_ref_override(const String &p_path) {
  862. DEV_ASSERT(p_path == _validate_local_path(p_path));
  863. HashMap<int, HashMap<String, Ref<Resource>>>::Iterator E = res_ref_overrides.find(load_nesting);
  864. if (!E) {
  865. return nullptr;
  866. }
  867. HashMap<String, Ref<Resource>>::Iterator F = E->value.find(p_path);
  868. if (!F) {
  869. return nullptr;
  870. }
  871. return F->value;
  872. }
  873. bool ResourceLoader::exists(const String &p_path, const String &p_type_hint) {
  874. String local_path = _validate_local_path(p_path);
  875. if (ResourceCache::has(local_path)) {
  876. return true; // If cached, it probably exists
  877. }
  878. bool xl_remapped = false;
  879. String path = _path_remap(local_path, &xl_remapped);
  880. // Try all loaders and pick the first match for the type hint
  881. for (int i = 0; i < loader_count; i++) {
  882. if (!loader[i]->recognize_path(path, p_type_hint)) {
  883. continue;
  884. }
  885. if (loader[i]->exists(path)) {
  886. return true;
  887. }
  888. }
  889. return false;
  890. }
  891. void ResourceLoader::add_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader, bool p_at_front) {
  892. ERR_FAIL_COND(p_format_loader.is_null());
  893. ERR_FAIL_COND(loader_count >= MAX_LOADERS);
  894. if (p_at_front) {
  895. for (int i = loader_count; i > 0; i--) {
  896. loader[i] = loader[i - 1];
  897. }
  898. loader[0] = p_format_loader;
  899. loader_count++;
  900. } else {
  901. loader[loader_count++] = p_format_loader;
  902. }
  903. }
  904. void ResourceLoader::remove_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader) {
  905. ERR_FAIL_COND(p_format_loader.is_null());
  906. // Find loader
  907. int i = 0;
  908. for (; i < loader_count; ++i) {
  909. if (loader[i] == p_format_loader) {
  910. break;
  911. }
  912. }
  913. ERR_FAIL_COND(i >= loader_count); // Not found
  914. // Shift next loaders up
  915. for (; i < loader_count - 1; ++i) {
  916. loader[i] = loader[i + 1];
  917. }
  918. loader[loader_count - 1].unref();
  919. --loader_count;
  920. }
  921. int ResourceLoader::get_import_order(const String &p_path) {
  922. String local_path = _path_remap(_validate_local_path(p_path));
  923. for (int i = 0; i < loader_count; i++) {
  924. if (!loader[i]->recognize_path(local_path)) {
  925. continue;
  926. }
  927. return loader[i]->get_import_order(p_path);
  928. }
  929. return 0;
  930. }
  931. String ResourceLoader::get_import_group_file(const String &p_path) {
  932. String local_path = _path_remap(_validate_local_path(p_path));
  933. for (int i = 0; i < loader_count; i++) {
  934. if (!loader[i]->recognize_path(local_path)) {
  935. continue;
  936. }
  937. return loader[i]->get_import_group_file(p_path);
  938. }
  939. return String(); //not found
  940. }
  941. bool ResourceLoader::is_import_valid(const String &p_path) {
  942. String local_path = _path_remap(_validate_local_path(p_path));
  943. for (int i = 0; i < loader_count; i++) {
  944. if (!loader[i]->recognize_path(local_path)) {
  945. continue;
  946. }
  947. return loader[i]->is_import_valid(p_path);
  948. }
  949. return false; //not found
  950. }
  951. bool ResourceLoader::is_imported(const String &p_path) {
  952. String local_path = _path_remap(_validate_local_path(p_path));
  953. for (int i = 0; i < loader_count; i++) {
  954. if (!loader[i]->recognize_path(local_path)) {
  955. continue;
  956. }
  957. return loader[i]->is_imported(p_path);
  958. }
  959. return false; //not found
  960. }
  961. void ResourceLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  962. String local_path = _path_remap(_validate_local_path(p_path));
  963. for (int i = 0; i < loader_count; i++) {
  964. if (!loader[i]->recognize_path(local_path)) {
  965. continue;
  966. }
  967. loader[i]->get_dependencies(local_path, p_dependencies, p_add_types);
  968. }
  969. }
  970. Error ResourceLoader::rename_dependencies(const String &p_path, const HashMap<String, String> &p_map) {
  971. String local_path = _path_remap(_validate_local_path(p_path));
  972. for (int i = 0; i < loader_count; i++) {
  973. if (!loader[i]->recognize_path(local_path)) {
  974. continue;
  975. }
  976. return loader[i]->rename_dependencies(local_path, p_map);
  977. }
  978. return OK; // ??
  979. }
  980. void ResourceLoader::get_classes_used(const String &p_path, HashSet<StringName> *r_classes) {
  981. String local_path = _validate_local_path(p_path);
  982. for (int i = 0; i < loader_count; i++) {
  983. if (!loader[i]->recognize_path(local_path)) {
  984. continue;
  985. }
  986. return loader[i]->get_classes_used(p_path, r_classes);
  987. }
  988. }
  989. String ResourceLoader::get_resource_type(const String &p_path) {
  990. String local_path = _validate_local_path(p_path);
  991. for (int i = 0; i < loader_count; i++) {
  992. String result = loader[i]->get_resource_type(local_path);
  993. if (!result.is_empty()) {
  994. return result;
  995. }
  996. }
  997. return "";
  998. }
  999. String ResourceLoader::get_resource_script_class(const String &p_path) {
  1000. String local_path = _validate_local_path(p_path);
  1001. for (int i = 0; i < loader_count; i++) {
  1002. String result = loader[i]->get_resource_script_class(local_path);
  1003. if (!result.is_empty()) {
  1004. return result;
  1005. }
  1006. }
  1007. return "";
  1008. }
  1009. ResourceUID::ID ResourceLoader::get_resource_uid(const String &p_path) {
  1010. String local_path = _validate_local_path(p_path);
  1011. for (int i = 0; i < loader_count; i++) {
  1012. ResourceUID::ID id = loader[i]->get_resource_uid(local_path);
  1013. if (id != ResourceUID::INVALID_ID) {
  1014. return id;
  1015. }
  1016. }
  1017. return ResourceUID::INVALID_ID;
  1018. }
  1019. bool ResourceLoader::has_custom_uid_support(const String &p_path) {
  1020. String local_path = _validate_local_path(p_path);
  1021. for (int i = 0; i < loader_count; i++) {
  1022. if (!loader[i]->recognize_path(local_path)) {
  1023. continue;
  1024. }
  1025. if (loader[i]->has_custom_uid_support()) {
  1026. return true;
  1027. }
  1028. }
  1029. return false;
  1030. }
  1031. bool ResourceLoader::should_create_uid_file(const String &p_path) {
  1032. const String local_path = _validate_local_path(p_path);
  1033. if (FileAccess::exists(local_path + ".uid")) {
  1034. return false;
  1035. }
  1036. for (int i = 0; i < loader_count; i++) {
  1037. if (loader[i]->recognize_path(local_path)) {
  1038. return !loader[i]->has_custom_uid_support();
  1039. }
  1040. }
  1041. return false;
  1042. }
  1043. String ResourceLoader::_path_remap(const String &p_path, bool *r_translation_remapped) {
  1044. String new_path = p_path;
  1045. if (translation_remaps.has(p_path)) {
  1046. // translation_remaps has the following format:
  1047. // { "res://path.png": PackedStringArray( "res://path-ru.png:ru", "res://path-de.png:de" ) }
  1048. // To find the path of the remapped resource, we extract the locale name after
  1049. // the last ':' to match the project locale.
  1050. // An extra remap may still be necessary afterwards due to the text -> binary converter on export.
  1051. String locale = TranslationServer::get_singleton()->get_locale();
  1052. ERR_FAIL_COND_V_MSG(locale.length() < 2, p_path, vformat("Could not remap path '%s' for translation as configured locale '%s' is invalid.", p_path, locale));
  1053. Vector<String> &res_remaps = *translation_remaps.getptr(new_path);
  1054. int best_score = 0;
  1055. for (int i = 0; i < res_remaps.size(); i++) {
  1056. int split = res_remaps[i].rfind_char(':');
  1057. if (split == -1) {
  1058. continue;
  1059. }
  1060. String l = res_remaps[i].substr(split + 1).strip_edges();
  1061. int score = TranslationServer::get_singleton()->compare_locales(locale, l);
  1062. if (score > 0 && score >= best_score) {
  1063. new_path = res_remaps[i].left(split);
  1064. best_score = score;
  1065. if (score == 10) {
  1066. break; // Exact match, skip the rest.
  1067. }
  1068. }
  1069. }
  1070. if (r_translation_remapped) {
  1071. *r_translation_remapped = true;
  1072. }
  1073. // Fallback to p_path if new_path does not exist.
  1074. if (!FileAccess::exists(new_path + ".import") &&
  1075. !FileAccess::exists(new_path + ".remap") &&
  1076. !FileAccess::exists(new_path)) {
  1077. WARN_PRINT(vformat("Translation remap '%s' does not exist. Falling back to '%s'.", new_path, p_path));
  1078. new_path = p_path;
  1079. }
  1080. }
  1081. // Usually, there's no remap file and FileAccess::exists() is faster than FileAccess::open().
  1082. new_path = ResourceUID::ensure_path(new_path);
  1083. if (FileAccess::exists(new_path + ".remap")) {
  1084. Error err;
  1085. Ref<FileAccess> f = FileAccess::open(new_path + ".remap", FileAccess::READ, &err);
  1086. if (f.is_valid()) {
  1087. VariantParser::StreamFile stream;
  1088. stream.f = f;
  1089. String assign;
  1090. Variant value;
  1091. VariantParser::Tag next_tag;
  1092. int lines = 0;
  1093. String error_text;
  1094. while (true) {
  1095. assign = Variant();
  1096. next_tag.fields.clear();
  1097. next_tag.name = String();
  1098. err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
  1099. if (err == ERR_FILE_EOF) {
  1100. break;
  1101. } else if (err != OK) {
  1102. ERR_PRINT(vformat("Parse error: %s.remap:%d error: %s.", p_path, lines, error_text));
  1103. break;
  1104. }
  1105. if (assign == "path") {
  1106. new_path = value;
  1107. break;
  1108. } else if (next_tag.name != "remap") {
  1109. break;
  1110. }
  1111. }
  1112. }
  1113. }
  1114. return new_path;
  1115. }
  1116. String ResourceLoader::import_remap(const String &p_path) {
  1117. if (ResourceFormatImporter::get_singleton()->recognize_path(p_path)) {
  1118. return ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_path);
  1119. }
  1120. return p_path;
  1121. }
  1122. String ResourceLoader::path_remap(const String &p_path) {
  1123. return _path_remap(p_path);
  1124. }
  1125. void ResourceLoader::reload_translation_remaps() {
  1126. List<Resource *> to_reload;
  1127. {
  1128. MutexLock lock(ResourceCache::lock);
  1129. SelfList<Resource> *E = remapped_list.first();
  1130. while (E) {
  1131. to_reload.push_back(E->self());
  1132. E = E->next();
  1133. }
  1134. }
  1135. //now just make sure to not delete any of these resources while changing locale..
  1136. while (to_reload.front()) {
  1137. to_reload.front()->get()->reload_from_file();
  1138. to_reload.pop_front();
  1139. }
  1140. }
  1141. void ResourceLoader::load_translation_remaps() {
  1142. if (!ProjectSettings::get_singleton()->has_setting("internationalization/locale/translation_remaps")) {
  1143. return;
  1144. }
  1145. Dictionary remaps = GLOBAL_GET("internationalization/locale/translation_remaps");
  1146. for (const KeyValue<Variant, Variant> &kv : remaps) {
  1147. Array langs = kv.value;
  1148. Vector<String> lang_remaps;
  1149. lang_remaps.resize(langs.size());
  1150. String *lang_remaps_ptrw = lang_remaps.ptrw();
  1151. for (const Variant &lang : langs) {
  1152. *lang_remaps_ptrw++ = lang;
  1153. }
  1154. translation_remaps[String(kv.key)] = lang_remaps;
  1155. }
  1156. }
  1157. void ResourceLoader::clear_translation_remaps() {
  1158. translation_remaps.clear();
  1159. while (remapped_list.first() != nullptr) {
  1160. remapped_list.remove(remapped_list.first());
  1161. }
  1162. }
  1163. void ResourceLoader::clear_thread_load_tasks() {
  1164. // Bring the thing down as quickly as possible without causing deadlocks or leaks.
  1165. MutexLock thread_load_lock(thread_load_mutex);
  1166. cleaning_tasks = true;
  1167. while (true) {
  1168. bool none_running = true;
  1169. if (thread_load_tasks.size()) {
  1170. for (KeyValue<String, ResourceLoader::ThreadLoadTask> &E : thread_load_tasks) {
  1171. if (E.value.status == THREAD_LOAD_IN_PROGRESS) {
  1172. if (E.value.cond_var && E.value.need_wait) {
  1173. E.value.cond_var->notify_all();
  1174. }
  1175. E.value.need_wait = false;
  1176. none_running = false;
  1177. }
  1178. }
  1179. }
  1180. if (none_running) {
  1181. break;
  1182. }
  1183. thread_load_lock.temp_unlock();
  1184. OS::get_singleton()->delay_usec(1000);
  1185. thread_load_lock.temp_relock();
  1186. }
  1187. while (user_load_tokens.begin()) {
  1188. LoadToken *user_token = user_load_tokens.begin()->value;
  1189. user_load_tokens.remove(user_load_tokens.begin());
  1190. DEV_ASSERT(user_token->user_rc > 0 && !user_token->user_path.is_empty());
  1191. user_token->user_path.clear();
  1192. user_token->user_rc = 0;
  1193. user_token->unreference();
  1194. }
  1195. thread_load_tasks.clear();
  1196. cleaning_tasks = false;
  1197. }
  1198. void ResourceLoader::set_load_callback(ResourceLoadedCallback p_callback) {
  1199. _loaded_callback = p_callback;
  1200. }
  1201. ResourceLoadedCallback ResourceLoader::_loaded_callback = nullptr;
  1202. Ref<ResourceFormatLoader> ResourceLoader::_find_custom_resource_format_loader(const String &path) {
  1203. for (int i = 0; i < loader_count; ++i) {
  1204. if (loader[i]->get_script_instance() && loader[i]->get_script_instance()->get_script()->get_path() == path) {
  1205. return loader[i];
  1206. }
  1207. }
  1208. return Ref<ResourceFormatLoader>();
  1209. }
  1210. bool ResourceLoader::add_custom_resource_format_loader(const String &script_path) {
  1211. if (_find_custom_resource_format_loader(script_path).is_valid()) {
  1212. return false;
  1213. }
  1214. Ref<Resource> res = ResourceLoader::load(script_path);
  1215. ERR_FAIL_COND_V(res.is_null(), false);
  1216. ERR_FAIL_COND_V(!res->is_class("Script"), false);
  1217. Ref<Script> s = res;
  1218. StringName ibt = s->get_instance_base_type();
  1219. bool valid_type = ClassDB::is_parent_class(ibt, "ResourceFormatLoader");
  1220. ERR_FAIL_COND_V_MSG(!valid_type, false, vformat("Failed to add a custom resource loader, script '%s' does not inherit 'ResourceFormatLoader'.", script_path));
  1221. Object *obj = ClassDB::instantiate(ibt);
  1222. ERR_FAIL_NULL_V_MSG(obj, false, vformat("Failed to add a custom resource loader, cannot instantiate '%s'.", ibt));
  1223. Ref<ResourceFormatLoader> crl = Object::cast_to<ResourceFormatLoader>(obj);
  1224. crl->set_script(s);
  1225. ResourceLoader::add_resource_format_loader(crl);
  1226. return true;
  1227. }
  1228. void ResourceLoader::set_create_missing_resources_if_class_unavailable(bool p_enable) {
  1229. create_missing_resources_if_class_unavailable = p_enable;
  1230. }
  1231. void ResourceLoader::add_custom_loaders() {
  1232. // Custom loaders registration exploits global class names
  1233. String custom_loader_base_class = ResourceFormatLoader::get_class_static();
  1234. List<StringName> global_classes;
  1235. ScriptServer::get_global_class_list(&global_classes);
  1236. for (const StringName &class_name : global_classes) {
  1237. StringName base_class = ScriptServer::get_global_class_native_base(class_name);
  1238. if (base_class == custom_loader_base_class) {
  1239. String path = ScriptServer::get_global_class_path(class_name);
  1240. add_custom_resource_format_loader(path);
  1241. }
  1242. }
  1243. }
  1244. void ResourceLoader::remove_custom_loaders() {
  1245. Vector<Ref<ResourceFormatLoader>> custom_loaders;
  1246. for (int i = 0; i < loader_count; ++i) {
  1247. if (loader[i]->get_script_instance()) {
  1248. custom_loaders.push_back(loader[i]);
  1249. }
  1250. }
  1251. for (int i = 0; i < custom_loaders.size(); ++i) {
  1252. remove_resource_format_loader(custom_loaders[i]);
  1253. }
  1254. }
  1255. bool ResourceLoader::is_cleaning_tasks() {
  1256. MutexLock lock(thread_load_mutex);
  1257. return cleaning_tasks;
  1258. }
  1259. Vector<String> ResourceLoader::list_directory(const String &p_directory) {
  1260. RBSet<String> files_found;
  1261. Ref<DirAccess> dir = DirAccess::open(p_directory);
  1262. if (dir.is_null()) {
  1263. return Vector<String>();
  1264. }
  1265. Error err = dir->list_dir_begin();
  1266. if (err != OK) {
  1267. return Vector<String>();
  1268. }
  1269. String d = dir->get_next();
  1270. while (!d.is_empty()) {
  1271. bool recognized = false;
  1272. if (dir->current_is_dir()) {
  1273. if (d != "." && d != "..") {
  1274. d += "/";
  1275. recognized = true;
  1276. }
  1277. } else {
  1278. if (d.ends_with(".import") || d.ends_with(".remap") || d.ends_with(".uid")) {
  1279. d = d.substr(0, d.rfind_char('.'));
  1280. }
  1281. if (d.ends_with(".gdc")) {
  1282. d = d.substr(0, d.rfind_char('.'));
  1283. d += ".gd";
  1284. }
  1285. const String full_path = p_directory.path_join(d);
  1286. // Try all loaders and pick the first match for the type hint.
  1287. for (int i = 0; i < loader_count; i++) {
  1288. if (loader[i]->recognize_path(full_path)) {
  1289. recognized = true;
  1290. break;
  1291. }
  1292. }
  1293. }
  1294. if (recognized) {
  1295. files_found.insert(d);
  1296. }
  1297. d = dir->get_next();
  1298. }
  1299. Vector<String> ret;
  1300. for (const String &f : files_found) {
  1301. ret.push_back(f);
  1302. }
  1303. return ret;
  1304. }
  1305. void ResourceLoader::initialize() {}
  1306. void ResourceLoader::finalize() {}
  1307. ResourceLoadErrorNotify ResourceLoader::err_notify = nullptr;
  1308. DependencyErrorNotify ResourceLoader::dep_err_notify = nullptr;
  1309. bool ResourceLoader::create_missing_resources_if_class_unavailable = false;
  1310. bool ResourceLoader::abort_on_missing_resource = true;
  1311. bool ResourceLoader::timestamp_on_load = false;
  1312. thread_local bool ResourceLoader::import_thread = false;
  1313. thread_local int ResourceLoader::load_nesting = 0;
  1314. thread_local Vector<String> ResourceLoader::load_paths_stack;
  1315. thread_local HashMap<int, HashMap<String, Ref<Resource>>> ResourceLoader::res_ref_overrides;
  1316. thread_local ResourceLoader::ThreadLoadTask *ResourceLoader::curr_load_task = nullptr;
  1317. SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG> &_get_res_loader_mutex() {
  1318. return ResourceLoader::thread_load_mutex;
  1319. }
  1320. template <>
  1321. thread_local SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG>::TLSData SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG>::tls_data(_get_res_loader_mutex());
  1322. SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG> ResourceLoader::thread_load_mutex;
  1323. HashMap<String, ResourceLoader::ThreadLoadTask> ResourceLoader::thread_load_tasks;
  1324. bool ResourceLoader::cleaning_tasks = false;
  1325. HashMap<String, ResourceLoader::LoadToken *> ResourceLoader::user_load_tokens;
  1326. SelfList<Resource>::List ResourceLoader::remapped_list;
  1327. HashMap<String, Vector<String>> ResourceLoader::translation_remaps;
  1328. ResourceLoaderImport ResourceLoader::import = nullptr;