resource_loader.cpp 49 KB

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