resource_loader.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  1. /**************************************************************************/
  2. /* resource_loader.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "resource_loader.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/file_access.h"
  33. #include "core/io/resource_importer.h"
  34. #include "core/os/condition_variable.h"
  35. #include "core/os/os.h"
  36. #include "core/string/print_string.h"
  37. #include "core/string/translation.h"
  38. #include "core/variant/variant_parser.h"
  39. #ifdef DEBUG_LOAD_THREADED
  40. #define print_lt(m_text) print_line(m_text)
  41. #else
  42. #define print_lt(m_text)
  43. #endif
  44. Ref<ResourceFormatLoader> ResourceLoader::loader[ResourceLoader::MAX_LOADERS];
  45. int ResourceLoader::loader_count = 0;
  46. bool ResourceFormatLoader::recognize_path(const String &p_path, const String &p_for_type) const {
  47. bool ret = false;
  48. if (GDVIRTUAL_CALL(_recognize_path, p_path, p_for_type, ret)) {
  49. return ret;
  50. }
  51. String extension = p_path.get_extension();
  52. List<String> extensions;
  53. if (p_for_type.is_empty()) {
  54. get_recognized_extensions(&extensions);
  55. } else {
  56. get_recognized_extensions_for_type(p_for_type, &extensions);
  57. }
  58. for (const String &E : extensions) {
  59. if (E.nocasecmp_to(extension) == 0) {
  60. return true;
  61. }
  62. }
  63. return false;
  64. }
  65. bool ResourceFormatLoader::handles_type(const String &p_type) const {
  66. bool success = false;
  67. GDVIRTUAL_CALL(_handles_type, p_type, success);
  68. return success;
  69. }
  70. void ResourceFormatLoader::get_classes_used(const String &p_path, HashSet<StringName> *r_classes) {
  71. Vector<String> ret;
  72. if (GDVIRTUAL_CALL(_get_classes_used, p_path, ret)) {
  73. for (int i = 0; i < ret.size(); i++) {
  74. r_classes->insert(ret[i]);
  75. }
  76. return;
  77. }
  78. String res = get_resource_type(p_path);
  79. if (!res.is_empty()) {
  80. r_classes->insert(res);
  81. }
  82. }
  83. String ResourceFormatLoader::get_resource_type(const String &p_path) const {
  84. String ret;
  85. GDVIRTUAL_CALL(_get_resource_type, p_path, ret);
  86. return ret;
  87. }
  88. String ResourceFormatLoader::get_resource_script_class(const String &p_path) const {
  89. String ret;
  90. GDVIRTUAL_CALL(_get_resource_script_class, p_path, ret);
  91. return ret;
  92. }
  93. ResourceUID::ID ResourceFormatLoader::get_resource_uid(const String &p_path) const {
  94. int64_t uid = ResourceUID::INVALID_ID;
  95. GDVIRTUAL_CALL(_get_resource_uid, p_path, uid);
  96. return uid;
  97. }
  98. void ResourceFormatLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
  99. if (p_type.is_empty() || handles_type(p_type)) {
  100. get_recognized_extensions(p_extensions);
  101. }
  102. }
  103. void ResourceLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) {
  104. for (int i = 0; i < loader_count; i++) {
  105. loader[i]->get_recognized_extensions_for_type(p_type, p_extensions);
  106. }
  107. }
  108. bool ResourceFormatLoader::exists(const String &p_path) const {
  109. bool success = false;
  110. if (GDVIRTUAL_CALL(_exists, p_path, success)) {
  111. return success;
  112. }
  113. return FileAccess::exists(p_path); // By default just check file.
  114. }
  115. void ResourceFormatLoader::get_recognized_extensions(List<String> *p_extensions) const {
  116. PackedStringArray exts;
  117. if (GDVIRTUAL_CALL(_get_recognized_extensions, exts)) {
  118. const String *r = exts.ptr();
  119. for (int i = 0; i < exts.size(); ++i) {
  120. p_extensions->push_back(r[i]);
  121. }
  122. }
  123. }
  124. 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) {
  125. Variant res;
  126. if (GDVIRTUAL_CALL(_load, p_path, p_original_path, p_use_sub_threads, p_cache_mode, res)) {
  127. if (res.get_type() == Variant::INT) { // Error code, abort.
  128. if (r_error) {
  129. *r_error = (Error)res.operator int64_t();
  130. }
  131. return Ref<Resource>();
  132. } else { // Success, pass on result.
  133. if (r_error) {
  134. *r_error = OK;
  135. }
  136. return res;
  137. }
  138. }
  139. ERR_FAIL_V_MSG(Ref<Resource>(), "Failed to load resource '" + p_path + "'. ResourceFormatLoader::load was not implemented for this resource type.");
  140. }
  141. void ResourceFormatLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  142. PackedStringArray deps;
  143. if (GDVIRTUAL_CALL(_get_dependencies, p_path, p_add_types, deps)) {
  144. const String *r = deps.ptr();
  145. for (int i = 0; i < deps.size(); ++i) {
  146. p_dependencies->push_back(r[i]);
  147. }
  148. }
  149. }
  150. Error ResourceFormatLoader::rename_dependencies(const String &p_path, const HashMap<String, String> &p_map) {
  151. Dictionary deps_dict;
  152. for (KeyValue<String, String> E : p_map) {
  153. deps_dict[E.key] = E.value;
  154. }
  155. Error err = OK;
  156. GDVIRTUAL_CALL(_rename_dependencies, p_path, deps_dict, err);
  157. return err;
  158. }
  159. void ResourceFormatLoader::_bind_methods() {
  160. BIND_ENUM_CONSTANT(CACHE_MODE_IGNORE);
  161. BIND_ENUM_CONSTANT(CACHE_MODE_REUSE);
  162. BIND_ENUM_CONSTANT(CACHE_MODE_REPLACE);
  163. GDVIRTUAL_BIND(_get_recognized_extensions);
  164. GDVIRTUAL_BIND(_recognize_path, "path", "type");
  165. GDVIRTUAL_BIND(_handles_type, "type");
  166. GDVIRTUAL_BIND(_get_resource_type, "path");
  167. GDVIRTUAL_BIND(_get_resource_script_class, "path");
  168. GDVIRTUAL_BIND(_get_resource_uid, "path");
  169. GDVIRTUAL_BIND(_get_dependencies, "path", "add_types");
  170. GDVIRTUAL_BIND(_rename_dependencies, "path", "renames");
  171. GDVIRTUAL_BIND(_exists, "path");
  172. GDVIRTUAL_BIND(_get_classes_used, "path");
  173. GDVIRTUAL_BIND(_load, "path", "original_path", "use_sub_threads", "cache_mode");
  174. }
  175. ///////////////////////////////////
  176. // This should be robust enough to be called redundantly without issues.
  177. void ResourceLoader::LoadToken::clear() {
  178. thread_load_mutex.lock();
  179. Thread *thread_to_destroy = nullptr;
  180. if (!local_path.is_empty()) { // Empty is used for the special case where the load task is not registered.
  181. DEV_ASSERT(thread_load_tasks.has(local_path));
  182. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  183. thread_to_destroy = load_task.thread;
  184. load_task.thread = nullptr;
  185. thread_load_tasks.erase(local_path);
  186. local_path.clear();
  187. }
  188. if (!user_path.is_empty()) {
  189. DEV_ASSERT(user_load_tokens.has(user_path));
  190. user_load_tokens.erase(user_path);
  191. user_path.clear();
  192. }
  193. thread_load_mutex.unlock();
  194. // If thread is unused, destroy it here, locally, now the token data is consistent.
  195. if (thread_to_destroy) {
  196. if (thread_to_destroy->is_started()) {
  197. thread_to_destroy->wait_to_finish();
  198. }
  199. memdelete(thread_to_destroy);
  200. }
  201. }
  202. ResourceLoader::LoadToken::~LoadToken() {
  203. clear();
  204. }
  205. 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) {
  206. load_nesting++;
  207. if (load_paths_stack.size()) {
  208. thread_load_mutex.lock();
  209. HashMap<String, ThreadLoadTask>::Iterator E = thread_load_tasks.find(load_paths_stack[load_paths_stack.size() - 1]);
  210. if (E) {
  211. E->value.sub_tasks.insert(p_path);
  212. }
  213. thread_load_mutex.unlock();
  214. }
  215. load_paths_stack.push_back(p_path);
  216. // Try all loaders and pick the first match for the type hint
  217. bool found = false;
  218. Ref<Resource> res;
  219. for (int i = 0; i < loader_count; i++) {
  220. if (!loader[i]->recognize_path(p_path, p_type_hint)) {
  221. continue;
  222. }
  223. found = true;
  224. res = loader[i]->load(p_path, !p_original_path.is_empty() ? p_original_path : p_path, r_error, p_use_sub_threads, r_progress, p_cache_mode);
  225. if (!res.is_null()) {
  226. break;
  227. }
  228. }
  229. load_paths_stack.resize(load_paths_stack.size() - 1);
  230. load_nesting--;
  231. if (!res.is_null()) {
  232. return res;
  233. }
  234. ERR_FAIL_COND_V_MSG(found, Ref<Resource>(),
  235. vformat("Failed loading resource: %s. Make sure resources have been imported by opening the project in the editor at least once.", p_path));
  236. #ifdef TOOLS_ENABLED
  237. Ref<FileAccess> file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);
  238. ERR_FAIL_COND_V_MSG(!file_check->file_exists(p_path), Ref<Resource>(), "Resource file not found: " + p_path + ".");
  239. #endif
  240. ERR_FAIL_V_MSG(Ref<Resource>(), "No loader found for resource: " + p_path + ".");
  241. }
  242. void ResourceLoader::_thread_load_function(void *p_userdata) {
  243. ThreadLoadTask &load_task = *(ThreadLoadTask *)p_userdata;
  244. // Thread-safe either if it's the current thread or a brand new one.
  245. CallQueue *mq_override = nullptr;
  246. if (load_task.first_in_stack) {
  247. if (!load_task.dependent_path.is_empty()) {
  248. load_paths_stack.push_back(load_task.dependent_path);
  249. }
  250. if (!Thread::is_main_thread()) {
  251. mq_override = memnew(CallQueue);
  252. MessageQueue::set_thread_singleton_override(mq_override);
  253. }
  254. } else {
  255. DEV_ASSERT(load_task.dependent_path.is_empty());
  256. }
  257. // --
  258. Ref<Resource> res = _load(load_task.remapped_path, load_task.remapped_path != load_task.local_path ? load_task.local_path : String(), load_task.type_hint, load_task.cache_mode, &load_task.error, load_task.use_sub_threads, &load_task.progress);
  259. thread_load_mutex.lock();
  260. load_task.resource = res;
  261. load_task.progress = 1.0; //it was fully loaded at this point, so force progress to 1.0
  262. if (load_task.error != OK) {
  263. load_task.status = THREAD_LOAD_FAILED;
  264. } else {
  265. load_task.status = THREAD_LOAD_LOADED;
  266. }
  267. if (load_task.cond_var) {
  268. load_task.cond_var->notify_all();
  269. memdelete(load_task.cond_var);
  270. load_task.cond_var = nullptr;
  271. }
  272. if (load_task.resource.is_valid()) {
  273. if (load_task.cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
  274. load_task.resource->set_path(load_task.local_path);
  275. }
  276. if (load_task.xl_remapped) {
  277. load_task.resource->set_as_translation_remapped(true);
  278. }
  279. #ifdef TOOLS_ENABLED
  280. load_task.resource->set_edited(false);
  281. if (timestamp_on_load) {
  282. uint64_t mt = FileAccess::get_modified_time(load_task.remapped_path);
  283. //printf("mt %s: %lli\n",remapped_path.utf8().get_data(),mt);
  284. load_task.resource->set_last_modified_time(mt);
  285. }
  286. #endif
  287. if (_loaded_callback) {
  288. _loaded_callback(load_task.resource, load_task.local_path);
  289. }
  290. }
  291. if (load_nesting == 0) {
  292. thread_active_count--;
  293. if (thread_waiting_count) {
  294. thread_active_cond_var.notify_one();
  295. }
  296. }
  297. print_lt("END: load count: " + itos(thread_active_count + thread_suspended_count) + " / wait count: " + itos(thread_waiting_count) + " / suspended count: " + itos(thread_suspended_count) + " / active: " + itos(thread_active_count));
  298. thread_load_mutex.unlock();
  299. if (load_task.first_in_stack && mq_override) {
  300. memdelete(mq_override);
  301. MessageQueue::set_thread_singleton_override(nullptr);
  302. }
  303. }
  304. static String _validate_local_path(const String &p_path) {
  305. ResourceUID::ID uid = ResourceUID::get_singleton()->text_to_id(p_path);
  306. if (uid != ResourceUID::INVALID_ID) {
  307. return ResourceUID::get_singleton()->get_id_path(uid);
  308. } else if (p_path.is_relative_path()) {
  309. return "res://" + p_path;
  310. } else {
  311. return ProjectSettings::get_singleton()->localize_path(p_path);
  312. }
  313. }
  314. Error ResourceLoader::load_threaded_request(const String &p_path, const String &p_type_hint, bool p_use_sub_threads, ResourceFormatLoader::CacheMode p_cache_mode) {
  315. thread_load_mutex.lock();
  316. if (user_load_tokens.has(p_path)) {
  317. print_verbose("load_threaded_request(): Another threaded load for resource path '" + p_path + "' has been initiated. Not an error.");
  318. user_load_tokens[p_path]->reference(); // Additional request.
  319. thread_load_mutex.unlock();
  320. return OK;
  321. }
  322. user_load_tokens[p_path] = nullptr;
  323. thread_load_mutex.unlock();
  324. 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);
  325. if (token.is_valid()) {
  326. thread_load_mutex.lock();
  327. token->user_path = p_path;
  328. token->reference(); // First request.
  329. user_load_tokens[p_path] = token.ptr();
  330. print_lt("REQUEST: user load tokens: " + itos(user_load_tokens.size()));
  331. thread_load_mutex.unlock();
  332. return OK;
  333. } else {
  334. return FAILED;
  335. }
  336. }
  337. Ref<Resource> ResourceLoader::load(const String &p_path, const String &p_type_hint, ResourceFormatLoader::CacheMode p_cache_mode, Error *r_error) {
  338. if (r_error) {
  339. *r_error = OK;
  340. }
  341. Ref<LoadToken> load_token = _load_start(p_path, p_type_hint, LOAD_THREAD_FROM_CURRENT, p_cache_mode);
  342. if (!load_token.is_valid()) {
  343. if (r_error) {
  344. *r_error = FAILED;
  345. }
  346. return Ref<Resource>();
  347. }
  348. Ref<Resource> res = _load_complete(*load_token.ptr(), r_error);
  349. return res;
  350. }
  351. Ref<ResourceLoader::LoadToken> ResourceLoader::_load_start(const String &p_path, const String &p_type_hint, LoadThreadMode p_thread_mode, ResourceFormatLoader::CacheMode p_cache_mode) {
  352. String local_path = _validate_local_path(p_path);
  353. Ref<LoadToken> load_token;
  354. bool must_not_register = false;
  355. ThreadLoadTask unregistered_load_task; // Once set, must be valid up to the call to do the load.
  356. ThreadLoadTask *load_task_ptr = nullptr;
  357. bool run_on_current_thread = false;
  358. {
  359. MutexLock thread_load_lock(thread_load_mutex);
  360. if (thread_load_tasks.has(local_path)) {
  361. load_token = Ref<LoadToken>(thread_load_tasks[local_path].load_token);
  362. if (!load_token.is_valid()) {
  363. // The token is dying (reached 0 on another thread).
  364. // Ensure it's killed now so the path can be safely reused right away.
  365. thread_load_tasks[local_path].load_token->clear();
  366. } else {
  367. if (p_cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
  368. return load_token;
  369. }
  370. }
  371. }
  372. load_token.instantiate();
  373. load_token->local_path = local_path;
  374. //create load task
  375. {
  376. ThreadLoadTask load_task;
  377. load_task.remapped_path = _path_remap(local_path, &load_task.xl_remapped);
  378. load_task.load_token = load_token.ptr();
  379. load_task.local_path = local_path;
  380. load_task.type_hint = p_type_hint;
  381. load_task.cache_mode = p_cache_mode;
  382. load_task.use_sub_threads = p_thread_mode == LOAD_THREAD_DISTRIBUTE;
  383. if (p_cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
  384. Ref<Resource> existing = ResourceCache::get_ref(local_path);
  385. if (existing.is_valid()) {
  386. //referencing is fine
  387. load_task.resource = existing;
  388. load_task.status = THREAD_LOAD_LOADED;
  389. load_task.progress = 1.0;
  390. thread_load_tasks[local_path] = load_task;
  391. return load_token;
  392. }
  393. }
  394. // If we want to ignore cache, but there's another task loading it, we can't add this one to the map and we also have to finish unconditionally synchronously.
  395. must_not_register = thread_load_tasks.has(local_path) && p_cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE;
  396. if (must_not_register) {
  397. load_token->local_path.clear();
  398. unregistered_load_task = load_task;
  399. } else {
  400. thread_load_tasks[local_path] = load_task;
  401. }
  402. load_task_ptr = must_not_register ? &unregistered_load_task : &thread_load_tasks[local_path];
  403. }
  404. print_lt("REQUEST: load count: " + itos(thread_active_count + thread_suspended_count) + " / wait count: " + itos(thread_waiting_count) + " / suspended count: " + itos(thread_suspended_count) + " / active: " + itos(thread_active_count));
  405. run_on_current_thread = must_not_register || p_thread_mode == LOAD_THREAD_FROM_CURRENT;
  406. if (!run_on_current_thread && thread_active_count >= thread_active_max && load_nesting > 0) {
  407. // No free slots for another thread, but this one is already active, so keep working here.
  408. run_on_current_thread = true;
  409. }
  410. load_task_ptr->first_in_stack = run_on_current_thread ? load_nesting == 0 : true;
  411. if (load_task_ptr->first_in_stack) {
  412. if (!run_on_current_thread && load_paths_stack.size()) {
  413. // The paths stack is lost across thread boundaries, so we have to remember what was the topmost path.
  414. load_task_ptr->dependent_path = load_paths_stack[load_paths_stack.size() - 1];
  415. }
  416. if (thread_active_count >= thread_active_max) {
  417. // Either the current or a new thread needs to wait for a free slot to become active.
  418. thread_waiting_count++;
  419. do {
  420. thread_active_cond_var.wait(thread_load_lock);
  421. } while (thread_active_count >= thread_active_max);
  422. thread_waiting_count--;
  423. }
  424. thread_active_count++;
  425. }
  426. if (cleaning_tasks) {
  427. load_task_ptr->status = THREAD_LOAD_FAILED;
  428. return load_token;
  429. }
  430. if (run_on_current_thread) {
  431. load_task_ptr->loader_id = Thread::get_caller_id();
  432. if (must_not_register) {
  433. load_token->res_if_unregistered = load_task_ptr->resource;
  434. }
  435. } else {
  436. load_task_ptr->thread = memnew(Thread);
  437. load_task_ptr->loader_id = load_task_ptr->thread->start(_thread_load_function, load_task_ptr);
  438. }
  439. }
  440. if (run_on_current_thread) {
  441. _thread_load_function(load_task_ptr);
  442. }
  443. return load_token;
  444. }
  445. float ResourceLoader::_dependency_get_progress(const String &p_path) {
  446. if (thread_load_tasks.has(p_path)) {
  447. ThreadLoadTask &load_task = thread_load_tasks[p_path];
  448. int dep_count = load_task.sub_tasks.size();
  449. if (dep_count > 0) {
  450. float dep_progress = 0;
  451. for (const String &E : load_task.sub_tasks) {
  452. dep_progress += _dependency_get_progress(E);
  453. }
  454. dep_progress /= float(dep_count);
  455. dep_progress *= 0.5;
  456. dep_progress += load_task.progress * 0.5;
  457. return dep_progress;
  458. } else {
  459. return load_task.progress;
  460. }
  461. } else {
  462. return 1.0; //assume finished loading it so it no longer exists
  463. }
  464. }
  465. ResourceLoader::ThreadLoadStatus ResourceLoader::load_threaded_get_status(const String &p_path, float *r_progress) {
  466. MutexLock thread_load_lock(thread_load_mutex);
  467. if (!user_load_tokens.has(p_path)) {
  468. print_verbose("load_threaded_get_status(): No threaded load for resource path '" + p_path + "' has been initiated or its result has already been collected.");
  469. return THREAD_LOAD_INVALID_RESOURCE;
  470. }
  471. String local_path = _validate_local_path(p_path);
  472. if (!thread_load_tasks.has(local_path)) {
  473. #ifdef DEV_ENABLED
  474. CRASH_NOW();
  475. #endif
  476. // On non-dev, be defensive and at least avoid crashing (at this point at least).
  477. return THREAD_LOAD_INVALID_RESOURCE;
  478. }
  479. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  480. ThreadLoadStatus status;
  481. status = load_task.status;
  482. if (r_progress) {
  483. *r_progress = _dependency_get_progress(local_path);
  484. }
  485. return status;
  486. }
  487. Ref<Resource> ResourceLoader::load_threaded_get(const String &p_path, Error *r_error) {
  488. if (r_error) {
  489. *r_error = OK;
  490. }
  491. Ref<Resource> res;
  492. {
  493. MutexLock thread_load_lock(thread_load_mutex);
  494. if (!user_load_tokens.has(p_path)) {
  495. print_verbose("load_threaded_get(): No threaded load for resource path '" + p_path + "' has been initiated or its result has already been collected.");
  496. if (r_error) {
  497. *r_error = ERR_INVALID_PARAMETER;
  498. }
  499. return Ref<Resource>();
  500. }
  501. LoadToken *load_token = user_load_tokens[p_path];
  502. if (!load_token) {
  503. // This happens if requested from one thread and rapidly querying from another.
  504. if (r_error) {
  505. *r_error = ERR_BUSY;
  506. }
  507. return Ref<Resource>();
  508. }
  509. res = _load_complete_inner(*load_token, r_error, thread_load_lock);
  510. if (load_token->unreference()) {
  511. memdelete(load_token);
  512. }
  513. }
  514. print_lt("GET: user load tokens: " + itos(user_load_tokens.size()));
  515. return res;
  516. }
  517. Ref<Resource> ResourceLoader::_load_complete(LoadToken &p_load_token, Error *r_error) {
  518. MutexLock thread_load_lock(thread_load_mutex);
  519. return _load_complete_inner(p_load_token, r_error, thread_load_lock);
  520. }
  521. Ref<Resource> ResourceLoader::_load_complete_inner(LoadToken &p_load_token, Error *r_error, MutexLock<SafeBinaryMutex<BINARY_MUTEX_TAG>> &p_thread_load_lock) {
  522. if (r_error) {
  523. *r_error = OK;
  524. }
  525. if (!p_load_token.local_path.is_empty()) {
  526. if (!thread_load_tasks.has(p_load_token.local_path)) {
  527. #ifdef DEV_ENABLED
  528. CRASH_NOW();
  529. #endif
  530. // On non-dev, be defensive and at least avoid crashing (at this point at least).
  531. if (r_error) {
  532. *r_error = ERR_BUG;
  533. }
  534. return Ref<Resource>();
  535. }
  536. ThreadLoadTask &load_task = thread_load_tasks[p_load_token.local_path];
  537. if (load_task.status == THREAD_LOAD_IN_PROGRESS) {
  538. if (load_task.loader_id == Thread::get_caller_id()) {
  539. // Load is in progress, but it's precisely this thread the one in charge.
  540. // That means this is a cyclic load.
  541. if (r_error) {
  542. *r_error = ERR_BUSY;
  543. }
  544. return Ref<Resource>();
  545. } else if (!load_task.cond_var) {
  546. // This is the first time some thread needs to wait for this one.
  547. load_task.cond_var = memnew(ConditionVariable);
  548. }
  549. // Wait for load to complete.
  550. thread_suspended_count++;
  551. print_lt("GET: load count: " + itos(thread_active_count + thread_suspended_count) + " / wait count: " + itos(thread_waiting_count) + " / suspended count: " + itos(thread_suspended_count) + " / active: " + itos(thread_active_count));
  552. do {
  553. load_task.cond_var->wait(p_thread_load_lock);
  554. DEV_ASSERT(thread_load_tasks.has(p_load_token.local_path) && p_load_token.get_reference_count());
  555. } while (load_task.cond_var);
  556. thread_suspended_count--;
  557. }
  558. if (cleaning_tasks) {
  559. load_task.resource = Ref<Resource>();
  560. load_task.error = FAILED;
  561. }
  562. Ref<Resource> resource = load_task.resource;
  563. if (r_error) {
  564. *r_error = load_task.error;
  565. }
  566. return resource;
  567. } else {
  568. // Special case of an unregistered task.
  569. // The resource should have been loaded by now.
  570. Ref<Resource> resource = p_load_token.res_if_unregistered;
  571. if (!resource.is_valid()) {
  572. if (r_error) {
  573. *r_error = FAILED;
  574. }
  575. }
  576. return resource;
  577. }
  578. }
  579. bool ResourceLoader::exists(const String &p_path, const String &p_type_hint) {
  580. String local_path = _validate_local_path(p_path);
  581. if (ResourceCache::has(local_path)) {
  582. return true; // If cached, it probably exists
  583. }
  584. bool xl_remapped = false;
  585. String path = _path_remap(local_path, &xl_remapped);
  586. // Try all loaders and pick the first match for the type hint
  587. for (int i = 0; i < loader_count; i++) {
  588. if (!loader[i]->recognize_path(path, p_type_hint)) {
  589. continue;
  590. }
  591. if (loader[i]->exists(path)) {
  592. return true;
  593. }
  594. }
  595. return false;
  596. }
  597. void ResourceLoader::add_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader, bool p_at_front) {
  598. ERR_FAIL_COND(p_format_loader.is_null());
  599. ERR_FAIL_COND(loader_count >= MAX_LOADERS);
  600. if (p_at_front) {
  601. for (int i = loader_count; i > 0; i--) {
  602. loader[i] = loader[i - 1];
  603. }
  604. loader[0] = p_format_loader;
  605. loader_count++;
  606. } else {
  607. loader[loader_count++] = p_format_loader;
  608. }
  609. }
  610. void ResourceLoader::remove_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader) {
  611. ERR_FAIL_COND(p_format_loader.is_null());
  612. // Find loader
  613. int i = 0;
  614. for (; i < loader_count; ++i) {
  615. if (loader[i] == p_format_loader) {
  616. break;
  617. }
  618. }
  619. ERR_FAIL_COND(i >= loader_count); // Not found
  620. // Shift next loaders up
  621. for (; i < loader_count - 1; ++i) {
  622. loader[i] = loader[i + 1];
  623. }
  624. loader[loader_count - 1].unref();
  625. --loader_count;
  626. }
  627. int ResourceLoader::get_import_order(const String &p_path) {
  628. String local_path = _path_remap(_validate_local_path(p_path));
  629. for (int i = 0; i < loader_count; i++) {
  630. if (!loader[i]->recognize_path(local_path)) {
  631. continue;
  632. }
  633. return loader[i]->get_import_order(p_path);
  634. }
  635. return 0;
  636. }
  637. String ResourceLoader::get_import_group_file(const String &p_path) {
  638. String local_path = _path_remap(_validate_local_path(p_path));
  639. for (int i = 0; i < loader_count; i++) {
  640. if (!loader[i]->recognize_path(local_path)) {
  641. continue;
  642. }
  643. return loader[i]->get_import_group_file(p_path);
  644. }
  645. return String(); //not found
  646. }
  647. bool ResourceLoader::is_import_valid(const String &p_path) {
  648. String local_path = _path_remap(_validate_local_path(p_path));
  649. for (int i = 0; i < loader_count; i++) {
  650. if (!loader[i]->recognize_path(local_path)) {
  651. continue;
  652. }
  653. return loader[i]->is_import_valid(p_path);
  654. }
  655. return false; //not found
  656. }
  657. bool ResourceLoader::is_imported(const String &p_path) {
  658. String local_path = _path_remap(_validate_local_path(p_path));
  659. for (int i = 0; i < loader_count; i++) {
  660. if (!loader[i]->recognize_path(local_path)) {
  661. continue;
  662. }
  663. return loader[i]->is_imported(p_path);
  664. }
  665. return false; //not found
  666. }
  667. void ResourceLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  668. String local_path = _path_remap(_validate_local_path(p_path));
  669. for (int i = 0; i < loader_count; i++) {
  670. if (!loader[i]->recognize_path(local_path)) {
  671. continue;
  672. }
  673. loader[i]->get_dependencies(local_path, p_dependencies, p_add_types);
  674. }
  675. }
  676. Error ResourceLoader::rename_dependencies(const String &p_path, const HashMap<String, String> &p_map) {
  677. String local_path = _path_remap(_validate_local_path(p_path));
  678. for (int i = 0; i < loader_count; i++) {
  679. if (!loader[i]->recognize_path(local_path)) {
  680. continue;
  681. }
  682. return loader[i]->rename_dependencies(local_path, p_map);
  683. }
  684. return OK; // ??
  685. }
  686. void ResourceLoader::get_classes_used(const String &p_path, HashSet<StringName> *r_classes) {
  687. String local_path = _validate_local_path(p_path);
  688. for (int i = 0; i < loader_count; i++) {
  689. if (!loader[i]->recognize_path(local_path)) {
  690. continue;
  691. }
  692. return loader[i]->get_classes_used(p_path, r_classes);
  693. }
  694. }
  695. String ResourceLoader::get_resource_type(const String &p_path) {
  696. String local_path = _validate_local_path(p_path);
  697. for (int i = 0; i < loader_count; i++) {
  698. String result = loader[i]->get_resource_type(local_path);
  699. if (!result.is_empty()) {
  700. return result;
  701. }
  702. }
  703. return "";
  704. }
  705. String ResourceLoader::get_resource_script_class(const String &p_path) {
  706. String local_path = _validate_local_path(p_path);
  707. for (int i = 0; i < loader_count; i++) {
  708. String result = loader[i]->get_resource_script_class(local_path);
  709. if (!result.is_empty()) {
  710. return result;
  711. }
  712. }
  713. return "";
  714. }
  715. ResourceUID::ID ResourceLoader::get_resource_uid(const String &p_path) {
  716. String local_path = _validate_local_path(p_path);
  717. for (int i = 0; i < loader_count; i++) {
  718. ResourceUID::ID id = loader[i]->get_resource_uid(local_path);
  719. if (id != ResourceUID::INVALID_ID) {
  720. return id;
  721. }
  722. }
  723. return ResourceUID::INVALID_ID;
  724. }
  725. String ResourceLoader::_path_remap(const String &p_path, bool *r_translation_remapped) {
  726. String new_path = p_path;
  727. if (translation_remaps.has(p_path)) {
  728. // translation_remaps has the following format:
  729. // { "res://path.png": PackedStringArray( "res://path-ru.png:ru", "res://path-de.png:de" ) }
  730. // To find the path of the remapped resource, we extract the locale name after
  731. // the last ':' to match the project locale.
  732. // An extra remap may still be necessary afterwards due to the text -> binary converter on export.
  733. String locale = TranslationServer::get_singleton()->get_locale();
  734. ERR_FAIL_COND_V_MSG(locale.length() < 2, p_path, "Could not remap path '" + p_path + "' for translation as configured locale '" + locale + "' is invalid.");
  735. Vector<String> &res_remaps = *translation_remaps.getptr(new_path);
  736. int best_score = 0;
  737. for (int i = 0; i < res_remaps.size(); i++) {
  738. int split = res_remaps[i].rfind(":");
  739. if (split == -1) {
  740. continue;
  741. }
  742. String l = res_remaps[i].substr(split + 1).strip_edges();
  743. int score = TranslationServer::get_singleton()->compare_locales(locale, l);
  744. if (score > 0 && score >= best_score) {
  745. new_path = res_remaps[i].left(split);
  746. best_score = score;
  747. if (score == 10) {
  748. break; // Exact match, skip the rest.
  749. }
  750. }
  751. }
  752. if (r_translation_remapped) {
  753. *r_translation_remapped = true;
  754. }
  755. // Fallback to p_path if new_path does not exist.
  756. if (!FileAccess::exists(new_path)) {
  757. WARN_PRINT(vformat("Translation remap '%s' does not exist. Falling back to '%s'.", new_path, p_path));
  758. new_path = p_path;
  759. }
  760. }
  761. if (path_remaps.has(new_path)) {
  762. new_path = path_remaps[new_path];
  763. } else {
  764. // Try file remap.
  765. Error err;
  766. Ref<FileAccess> f = FileAccess::open(new_path + ".remap", FileAccess::READ, &err);
  767. if (f.is_valid()) {
  768. VariantParser::StreamFile stream;
  769. stream.f = f;
  770. String assign;
  771. Variant value;
  772. VariantParser::Tag next_tag;
  773. int lines = 0;
  774. String error_text;
  775. while (true) {
  776. assign = Variant();
  777. next_tag.fields.clear();
  778. next_tag.name = String();
  779. err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
  780. if (err == ERR_FILE_EOF) {
  781. break;
  782. } else if (err != OK) {
  783. ERR_PRINT("Parse error: " + p_path + ".remap:" + itos(lines) + " error: " + error_text + ".");
  784. break;
  785. }
  786. if (assign == "path") {
  787. new_path = value;
  788. break;
  789. } else if (next_tag.name != "remap") {
  790. break;
  791. }
  792. }
  793. }
  794. }
  795. return new_path;
  796. }
  797. String ResourceLoader::import_remap(const String &p_path) {
  798. if (ResourceFormatImporter::get_singleton()->recognize_path(p_path)) {
  799. return ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_path);
  800. }
  801. return p_path;
  802. }
  803. String ResourceLoader::path_remap(const String &p_path) {
  804. return _path_remap(p_path);
  805. }
  806. void ResourceLoader::reload_translation_remaps() {
  807. ResourceCache::lock.lock();
  808. List<Resource *> to_reload;
  809. SelfList<Resource> *E = remapped_list.first();
  810. while (E) {
  811. to_reload.push_back(E->self());
  812. E = E->next();
  813. }
  814. ResourceCache::lock.unlock();
  815. //now just make sure to not delete any of these resources while changing locale..
  816. while (to_reload.front()) {
  817. to_reload.front()->get()->reload_from_file();
  818. to_reload.pop_front();
  819. }
  820. }
  821. void ResourceLoader::load_translation_remaps() {
  822. if (!ProjectSettings::get_singleton()->has_setting("internationalization/locale/translation_remaps")) {
  823. return;
  824. }
  825. Dictionary remaps = GLOBAL_GET("internationalization/locale/translation_remaps");
  826. List<Variant> keys;
  827. remaps.get_key_list(&keys);
  828. for (const Variant &E : keys) {
  829. Array langs = remaps[E];
  830. Vector<String> lang_remaps;
  831. lang_remaps.resize(langs.size());
  832. for (int i = 0; i < langs.size(); i++) {
  833. lang_remaps.write[i] = langs[i];
  834. }
  835. translation_remaps[String(E)] = lang_remaps;
  836. }
  837. }
  838. void ResourceLoader::clear_translation_remaps() {
  839. translation_remaps.clear();
  840. while (remapped_list.first() != nullptr) {
  841. remapped_list.remove(remapped_list.first());
  842. }
  843. }
  844. void ResourceLoader::clear_thread_load_tasks() {
  845. // Bring the thing down as quickly as possible without causing deadlocks or leaks.
  846. thread_load_mutex.lock();
  847. cleaning_tasks = true;
  848. while (true) {
  849. bool none_running = true;
  850. if (thread_load_tasks.size()) {
  851. for (KeyValue<String, ResourceLoader::ThreadLoadTask> &E : thread_load_tasks) {
  852. if (E.value.status == THREAD_LOAD_IN_PROGRESS) {
  853. if (E.value.cond_var) {
  854. E.value.cond_var->notify_all();
  855. memdelete(E.value.cond_var);
  856. E.value.cond_var = nullptr;
  857. }
  858. none_running = false;
  859. }
  860. }
  861. }
  862. if (none_running) {
  863. break;
  864. }
  865. thread_active_cond_var.notify_all();
  866. thread_load_mutex.unlock();
  867. OS::get_singleton()->delay_usec(1000);
  868. thread_load_mutex.lock();
  869. }
  870. for (KeyValue<String, LoadToken *> &E : user_load_tokens) {
  871. memdelete(E.value);
  872. }
  873. user_load_tokens.clear();
  874. thread_load_tasks.clear();
  875. cleaning_tasks = false;
  876. thread_load_mutex.unlock();
  877. }
  878. void ResourceLoader::load_path_remaps() {
  879. if (!ProjectSettings::get_singleton()->has_setting("path_remap/remapped_paths")) {
  880. return;
  881. }
  882. Vector<String> remaps = GLOBAL_GET("path_remap/remapped_paths");
  883. int rc = remaps.size();
  884. ERR_FAIL_COND(rc & 1); //must be even
  885. const String *r = remaps.ptr();
  886. for (int i = 0; i < rc; i += 2) {
  887. path_remaps[r[i]] = r[i + 1];
  888. }
  889. }
  890. void ResourceLoader::clear_path_remaps() {
  891. path_remaps.clear();
  892. }
  893. void ResourceLoader::set_load_callback(ResourceLoadedCallback p_callback) {
  894. _loaded_callback = p_callback;
  895. }
  896. ResourceLoadedCallback ResourceLoader::_loaded_callback = nullptr;
  897. Ref<ResourceFormatLoader> ResourceLoader::_find_custom_resource_format_loader(String path) {
  898. for (int i = 0; i < loader_count; ++i) {
  899. if (loader[i]->get_script_instance() && loader[i]->get_script_instance()->get_script()->get_path() == path) {
  900. return loader[i];
  901. }
  902. }
  903. return Ref<ResourceFormatLoader>();
  904. }
  905. bool ResourceLoader::add_custom_resource_format_loader(String script_path) {
  906. if (_find_custom_resource_format_loader(script_path).is_valid()) {
  907. return false;
  908. }
  909. Ref<Resource> res = ResourceLoader::load(script_path);
  910. ERR_FAIL_COND_V(res.is_null(), false);
  911. ERR_FAIL_COND_V(!res->is_class("Script"), false);
  912. Ref<Script> s = res;
  913. StringName ibt = s->get_instance_base_type();
  914. bool valid_type = ClassDB::is_parent_class(ibt, "ResourceFormatLoader");
  915. ERR_FAIL_COND_V_MSG(!valid_type, false, "Script does not inherit a CustomResourceLoader: " + script_path + ".");
  916. Object *obj = ClassDB::instantiate(ibt);
  917. ERR_FAIL_COND_V_MSG(obj == nullptr, false, "Cannot instance script as custom resource loader, expected 'ResourceFormatLoader' inheritance, got: " + String(ibt) + ".");
  918. Ref<ResourceFormatLoader> crl = Object::cast_to<ResourceFormatLoader>(obj);
  919. crl->set_script(s);
  920. ResourceLoader::add_resource_format_loader(crl);
  921. return true;
  922. }
  923. void ResourceLoader::set_create_missing_resources_if_class_unavailable(bool p_enable) {
  924. create_missing_resources_if_class_unavailable = p_enable;
  925. }
  926. void ResourceLoader::add_custom_loaders() {
  927. // Custom loaders registration exploits global class names
  928. String custom_loader_base_class = ResourceFormatLoader::get_class_static();
  929. List<StringName> global_classes;
  930. ScriptServer::get_global_class_list(&global_classes);
  931. for (const StringName &class_name : global_classes) {
  932. StringName base_class = ScriptServer::get_global_class_native_base(class_name);
  933. if (base_class == custom_loader_base_class) {
  934. String path = ScriptServer::get_global_class_path(class_name);
  935. add_custom_resource_format_loader(path);
  936. }
  937. }
  938. }
  939. void ResourceLoader::remove_custom_loaders() {
  940. Vector<Ref<ResourceFormatLoader>> custom_loaders;
  941. for (int i = 0; i < loader_count; ++i) {
  942. if (loader[i]->get_script_instance()) {
  943. custom_loaders.push_back(loader[i]);
  944. }
  945. }
  946. for (int i = 0; i < custom_loaders.size(); ++i) {
  947. remove_resource_format_loader(custom_loaders[i]);
  948. }
  949. }
  950. bool ResourceLoader::is_cleaning_tasks() {
  951. MutexLock lock(thread_load_mutex);
  952. return cleaning_tasks;
  953. }
  954. void ResourceLoader::initialize() {
  955. thread_active_max = OS::get_singleton()->get_processor_count();
  956. thread_active_count = 0;
  957. thread_waiting_count = 0;
  958. thread_suspended_count = 0;
  959. }
  960. void ResourceLoader::finalize() {}
  961. ResourceLoadErrorNotify ResourceLoader::err_notify = nullptr;
  962. void *ResourceLoader::err_notify_ud = nullptr;
  963. DependencyErrorNotify ResourceLoader::dep_err_notify = nullptr;
  964. void *ResourceLoader::dep_err_notify_ud = nullptr;
  965. bool ResourceLoader::create_missing_resources_if_class_unavailable = false;
  966. bool ResourceLoader::abort_on_missing_resource = true;
  967. bool ResourceLoader::timestamp_on_load = false;
  968. thread_local int ResourceLoader::load_nesting = 0;
  969. thread_local Vector<String> ResourceLoader::load_paths_stack;
  970. template <>
  971. thread_local uint32_t SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG>::count = 0;
  972. SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG> ResourceLoader::thread_load_mutex;
  973. HashMap<String, ResourceLoader::ThreadLoadTask> ResourceLoader::thread_load_tasks;
  974. ConditionVariable ResourceLoader::thread_active_cond_var;
  975. int ResourceLoader::thread_active_count = 0;
  976. int ResourceLoader::thread_waiting_count = 0;
  977. int ResourceLoader::thread_suspended_count = 0;
  978. int ResourceLoader::thread_active_max = 0;
  979. bool ResourceLoader::cleaning_tasks = false;
  980. HashMap<String, ResourceLoader::LoadToken *> ResourceLoader::user_load_tokens;
  981. SelfList<Resource>::List ResourceLoader::remapped_list;
  982. HashMap<String, Vector<String>> ResourceLoader::translation_remaps;
  983. HashMap<String, String> ResourceLoader::path_remaps;
  984. ResourceLoaderImport ResourceLoader::import = nullptr;