resource_loader.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  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. 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) {
  177. bool found = false;
  178. // Try all loaders and pick the first match for the type hint
  179. for (int i = 0; i < loader_count; i++) {
  180. if (!loader[i]->recognize_path(p_path, p_type_hint)) {
  181. continue;
  182. }
  183. found = true;
  184. Ref<Resource> 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);
  185. if (res.is_null()) {
  186. continue;
  187. }
  188. return res;
  189. }
  190. ERR_FAIL_COND_V_MSG(found, Ref<Resource>(),
  191. vformat("Failed loading resource: %s. Make sure resources have been imported by opening the project in the editor at least once.", p_path));
  192. #ifdef TOOLS_ENABLED
  193. Ref<FileAccess> file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);
  194. ERR_FAIL_COND_V_MSG(!file_check->file_exists(p_path), Ref<Resource>(), "Resource file not found: " + p_path + ".");
  195. #endif
  196. ERR_FAIL_V_MSG(Ref<Resource>(), "No loader found for resource: " + p_path + ".");
  197. }
  198. void ResourceLoader::_thread_load_function(void *p_userdata) {
  199. ThreadLoadTask &load_task = *(ThreadLoadTask *)p_userdata;
  200. load_task.loader_id = Thread::get_caller_id();
  201. if (load_task.cond_var) {
  202. //this is an actual thread, so wait for Ok from semaphore
  203. thread_load_semaphore->wait(); //wait until its ok to start loading
  204. }
  205. load_task.resource = _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);
  206. load_task.progress = 1.0; //it was fully loaded at this point, so force progress to 1.0
  207. thread_load_mutex->lock();
  208. if (load_task.error != OK) {
  209. load_task.status = THREAD_LOAD_FAILED;
  210. } else {
  211. load_task.status = THREAD_LOAD_LOADED;
  212. }
  213. if (load_task.cond_var) {
  214. if (load_task.start_next && thread_waiting_count > 0) {
  215. thread_waiting_count--;
  216. //thread loading count remains constant, this ends but another one begins
  217. thread_load_semaphore->post();
  218. } else {
  219. thread_loading_count--; //no threads waiting, just reduce loading count
  220. }
  221. print_lt("END: load count: " + itos(thread_loading_count) + " / wait count: " + itos(thread_waiting_count) + " / suspended count: " + itos(thread_suspended_count) + " / active: " + itos(thread_loading_count - thread_suspended_count));
  222. load_task.cond_var->notify_all();
  223. memdelete(load_task.cond_var);
  224. load_task.cond_var = nullptr;
  225. }
  226. if (load_task.resource.is_valid()) {
  227. load_task.resource->set_path(load_task.local_path);
  228. if (load_task.xl_remapped) {
  229. load_task.resource->set_as_translation_remapped(true);
  230. }
  231. #ifdef TOOLS_ENABLED
  232. load_task.resource->set_edited(false);
  233. if (timestamp_on_load) {
  234. uint64_t mt = FileAccess::get_modified_time(load_task.remapped_path);
  235. //printf("mt %s: %lli\n",remapped_path.utf8().get_data(),mt);
  236. load_task.resource->set_last_modified_time(mt);
  237. }
  238. #endif
  239. if (_loaded_callback) {
  240. _loaded_callback(load_task.resource, load_task.local_path);
  241. }
  242. }
  243. thread_load_mutex->unlock();
  244. }
  245. static String _validate_local_path(const String &p_path) {
  246. ResourceUID::ID uid = ResourceUID::get_singleton()->text_to_id(p_path);
  247. if (uid != ResourceUID::INVALID_ID) {
  248. return ResourceUID::get_singleton()->get_id_path(uid);
  249. } else if (p_path.is_relative_path()) {
  250. return "res://" + p_path;
  251. } else {
  252. return ProjectSettings::get_singleton()->localize_path(p_path);
  253. }
  254. }
  255. Error ResourceLoader::load_threaded_request(const String &p_path, const String &p_type_hint, bool p_use_sub_threads, ResourceFormatLoader::CacheMode p_cache_mode, const String &p_source_resource) {
  256. String local_path = _validate_local_path(p_path);
  257. thread_load_mutex->lock();
  258. if (!p_source_resource.is_empty()) {
  259. //must be loading from this resource
  260. if (!thread_load_tasks.has(p_source_resource)) {
  261. thread_load_mutex->unlock();
  262. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "There is no thread loading source resource '" + p_source_resource + "'.");
  263. }
  264. //must be loading from this thread
  265. if (thread_load_tasks[p_source_resource].loader_id != Thread::get_caller_id()) {
  266. thread_load_mutex->unlock();
  267. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Threading loading resource'" + local_path + " failed: Source specified: '" + p_source_resource + "' but was not called by it.");
  268. }
  269. //must not be already added as s sub tasks
  270. if (thread_load_tasks[p_source_resource].sub_tasks.has(local_path)) {
  271. thread_load_mutex->unlock();
  272. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Thread loading source resource '" + p_source_resource + "' already is loading '" + local_path + "'.");
  273. }
  274. }
  275. if (thread_load_tasks.has(local_path)) {
  276. thread_load_tasks[local_path].requests++;
  277. if (!p_source_resource.is_empty()) {
  278. thread_load_tasks[p_source_resource].sub_tasks.insert(local_path);
  279. }
  280. thread_load_mutex->unlock();
  281. return OK;
  282. }
  283. {
  284. //create load task
  285. ThreadLoadTask load_task;
  286. load_task.requests = 1;
  287. load_task.remapped_path = _path_remap(local_path, &load_task.xl_remapped);
  288. load_task.local_path = local_path;
  289. load_task.type_hint = p_type_hint;
  290. load_task.cache_mode = p_cache_mode;
  291. load_task.use_sub_threads = p_use_sub_threads;
  292. { //must check if resource is already loaded before attempting to load it in a thread
  293. if (load_task.loader_id == Thread::get_caller_id()) {
  294. thread_load_mutex->unlock();
  295. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Attempted to load a resource already being loaded from this thread, cyclic reference?");
  296. }
  297. Ref<Resource> existing = ResourceCache::get_ref(local_path);
  298. if (existing.is_valid()) {
  299. //referencing is fine
  300. load_task.resource = existing;
  301. load_task.status = THREAD_LOAD_LOADED;
  302. load_task.progress = 1.0;
  303. }
  304. }
  305. if (!p_source_resource.is_empty()) {
  306. thread_load_tasks[p_source_resource].sub_tasks.insert(local_path);
  307. }
  308. thread_load_tasks[local_path] = load_task;
  309. }
  310. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  311. if (load_task.resource.is_null()) { //needs to be loaded in thread
  312. load_task.cond_var = memnew(ConditionVariable);
  313. if (thread_loading_count < thread_load_max) {
  314. thread_loading_count++;
  315. thread_load_semaphore->post(); //we have free threads, so allow one
  316. } else {
  317. thread_waiting_count++;
  318. }
  319. print_lt("REQUEST: load count: " + itos(thread_loading_count) + " / wait count: " + itos(thread_waiting_count) + " / suspended count: " + itos(thread_suspended_count) + " / active: " + itos(thread_loading_count - thread_suspended_count));
  320. load_task.thread = memnew(Thread);
  321. load_task.thread->start(_thread_load_function, &thread_load_tasks[local_path]);
  322. load_task.loader_id = load_task.thread->get_id();
  323. }
  324. thread_load_mutex->unlock();
  325. return OK;
  326. }
  327. float ResourceLoader::_dependency_get_progress(const String &p_path) {
  328. if (thread_load_tasks.has(p_path)) {
  329. ThreadLoadTask &load_task = thread_load_tasks[p_path];
  330. int dep_count = load_task.sub_tasks.size();
  331. if (dep_count > 0) {
  332. float dep_progress = 0;
  333. for (const String &E : load_task.sub_tasks) {
  334. dep_progress += _dependency_get_progress(E);
  335. }
  336. dep_progress /= float(dep_count);
  337. dep_progress *= 0.5;
  338. dep_progress += load_task.progress * 0.5;
  339. return dep_progress;
  340. } else {
  341. return load_task.progress;
  342. }
  343. } else {
  344. return 1.0; //assume finished loading it so it no longer exists
  345. }
  346. }
  347. ResourceLoader::ThreadLoadStatus ResourceLoader::load_threaded_get_status(const String &p_path, float *r_progress) {
  348. String local_path = _validate_local_path(p_path);
  349. thread_load_mutex->lock();
  350. if (!thread_load_tasks.has(local_path)) {
  351. thread_load_mutex->unlock();
  352. return THREAD_LOAD_INVALID_RESOURCE;
  353. }
  354. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  355. ThreadLoadStatus status;
  356. status = load_task.status;
  357. if (r_progress) {
  358. *r_progress = _dependency_get_progress(local_path);
  359. }
  360. thread_load_mutex->unlock();
  361. return status;
  362. }
  363. Ref<Resource> ResourceLoader::load_threaded_get(const String &p_path, Error *r_error) {
  364. String local_path = _validate_local_path(p_path);
  365. MutexLock thread_load_lock(*thread_load_mutex);
  366. if (!thread_load_tasks.has(local_path)) {
  367. if (r_error) {
  368. *r_error = ERR_INVALID_PARAMETER;
  369. }
  370. return Ref<Resource>();
  371. }
  372. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  373. if (load_task.status == THREAD_LOAD_IN_PROGRESS) {
  374. if (load_task.loader_id == Thread::get_caller_id()) {
  375. // Load is in progress, but it's precisely this thread the one in charge.
  376. // That means this is a cyclic load.
  377. if (r_error) {
  378. *r_error = ERR_BUSY;
  379. }
  380. return Ref<Resource>();
  381. } else if (!load_task.cond_var) {
  382. // Load is in progress, but a condition variable was never created for it.
  383. // That happens when a load has been initiated with subthreads disabled,
  384. // but now another load thread needs to interact with this one (either
  385. // because of subthreads being used this time, or because it's simply a
  386. // threaded load running on a different thread).
  387. // Since we want to be notified when the load ends, we must create the
  388. // condition variable now.
  389. load_task.cond_var = memnew(ConditionVariable);
  390. }
  391. }
  392. //cond var still exists, meaning it's still loading, request poll
  393. if (load_task.cond_var) {
  394. {
  395. // As we got a cond var, this means we are going to have to wait
  396. // until the sub-resource is done loading
  397. //
  398. // As this thread will become 'blocked' we should "exchange" its
  399. // active status with a waiting one, to ensure load continues.
  400. //
  401. // This ensures loading is never blocked and that is also within
  402. // the maximum number of active threads.
  403. if (thread_waiting_count > 0) {
  404. thread_waiting_count--;
  405. thread_loading_count++;
  406. thread_load_semaphore->post();
  407. load_task.start_next = false; //do not start next since we are doing it here
  408. }
  409. thread_suspended_count++;
  410. print_lt("GET: load count: " + itos(thread_loading_count) + " / wait count: " + itos(thread_waiting_count) + " / suspended count: " + itos(thread_suspended_count) + " / active: " + itos(thread_loading_count - thread_suspended_count));
  411. }
  412. do {
  413. load_task.cond_var->wait(thread_load_lock);
  414. } while (load_task.cond_var); // In case of spurious wakeup.
  415. thread_suspended_count--;
  416. if (!thread_load_tasks.has(local_path)) { //may have been erased during unlock and this was always an invalid call
  417. if (r_error) {
  418. *r_error = ERR_INVALID_PARAMETER;
  419. }
  420. return Ref<Resource>();
  421. }
  422. }
  423. Ref<Resource> resource = load_task.resource;
  424. if (r_error) {
  425. *r_error = load_task.error;
  426. }
  427. load_task.requests--;
  428. if (load_task.requests == 0) {
  429. if (load_task.thread) { //thread may not have been used
  430. load_task.thread->wait_to_finish();
  431. memdelete(load_task.thread);
  432. }
  433. thread_load_tasks.erase(local_path);
  434. }
  435. return resource;
  436. }
  437. Ref<Resource> ResourceLoader::load(const String &p_path, const String &p_type_hint, ResourceFormatLoader::CacheMode p_cache_mode, Error *r_error) {
  438. if (r_error) {
  439. *r_error = ERR_CANT_OPEN;
  440. }
  441. String local_path = _validate_local_path(p_path);
  442. if (p_cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
  443. thread_load_mutex->lock();
  444. //Is it already being loaded? poll until done
  445. if (thread_load_tasks.has(local_path)) {
  446. Error err = load_threaded_request(p_path, p_type_hint);
  447. if (err != OK) {
  448. if (r_error) {
  449. *r_error = err;
  450. }
  451. thread_load_mutex->unlock();
  452. return Ref<Resource>();
  453. }
  454. thread_load_mutex->unlock();
  455. return load_threaded_get(p_path, r_error);
  456. }
  457. //Is it cached?
  458. Ref<Resource> existing = ResourceCache::get_ref(local_path);
  459. if (existing.is_valid()) {
  460. thread_load_mutex->unlock();
  461. if (r_error) {
  462. *r_error = OK;
  463. }
  464. return existing; //use cached
  465. }
  466. //load using task (but this thread)
  467. ThreadLoadTask load_task;
  468. load_task.requests = 1;
  469. load_task.local_path = local_path;
  470. load_task.remapped_path = _path_remap(local_path, &load_task.xl_remapped);
  471. load_task.type_hint = p_type_hint;
  472. load_task.cache_mode = p_cache_mode; //ignore
  473. load_task.loader_id = Thread::get_caller_id();
  474. thread_load_tasks[local_path] = load_task;
  475. thread_load_mutex->unlock();
  476. _thread_load_function(&thread_load_tasks[local_path]);
  477. return load_threaded_get(p_path, r_error);
  478. } else {
  479. bool xl_remapped = false;
  480. String path = _path_remap(local_path, &xl_remapped);
  481. if (path.is_empty()) {
  482. ERR_FAIL_V_MSG(Ref<Resource>(), "Remapping '" + local_path + "' failed.");
  483. }
  484. print_verbose("Loading resource: " + path);
  485. float p;
  486. Ref<Resource> res = _load(path, local_path, p_type_hint, p_cache_mode, r_error, false, &p);
  487. if (res.is_null()) {
  488. print_verbose("Failed loading resource: " + path);
  489. return Ref<Resource>();
  490. }
  491. if (xl_remapped) {
  492. res->set_as_translation_remapped(true);
  493. }
  494. #ifdef TOOLS_ENABLED
  495. res->set_edited(false);
  496. if (timestamp_on_load) {
  497. uint64_t mt = FileAccess::get_modified_time(path);
  498. //printf("mt %s: %lli\n",remapped_path.utf8().get_data(),mt);
  499. res->set_last_modified_time(mt);
  500. }
  501. #endif
  502. return res;
  503. }
  504. }
  505. bool ResourceLoader::exists(const String &p_path, const String &p_type_hint) {
  506. String local_path = _validate_local_path(p_path);
  507. if (ResourceCache::has(local_path)) {
  508. return true; // If cached, it probably exists
  509. }
  510. bool xl_remapped = false;
  511. String path = _path_remap(local_path, &xl_remapped);
  512. // Try all loaders and pick the first match for the type hint
  513. for (int i = 0; i < loader_count; i++) {
  514. if (!loader[i]->recognize_path(path, p_type_hint)) {
  515. continue;
  516. }
  517. if (loader[i]->exists(path)) {
  518. return true;
  519. }
  520. }
  521. return false;
  522. }
  523. void ResourceLoader::add_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader, bool p_at_front) {
  524. ERR_FAIL_COND(p_format_loader.is_null());
  525. ERR_FAIL_COND(loader_count >= MAX_LOADERS);
  526. if (p_at_front) {
  527. for (int i = loader_count; i > 0; i--) {
  528. loader[i] = loader[i - 1];
  529. }
  530. loader[0] = p_format_loader;
  531. loader_count++;
  532. } else {
  533. loader[loader_count++] = p_format_loader;
  534. }
  535. }
  536. void ResourceLoader::remove_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader) {
  537. ERR_FAIL_COND(p_format_loader.is_null());
  538. // Find loader
  539. int i = 0;
  540. for (; i < loader_count; ++i) {
  541. if (loader[i] == p_format_loader) {
  542. break;
  543. }
  544. }
  545. ERR_FAIL_COND(i >= loader_count); // Not found
  546. // Shift next loaders up
  547. for (; i < loader_count - 1; ++i) {
  548. loader[i] = loader[i + 1];
  549. }
  550. loader[loader_count - 1].unref();
  551. --loader_count;
  552. }
  553. int ResourceLoader::get_import_order(const String &p_path) {
  554. String local_path = _path_remap(_validate_local_path(p_path));
  555. for (int i = 0; i < loader_count; i++) {
  556. if (!loader[i]->recognize_path(local_path)) {
  557. continue;
  558. }
  559. return loader[i]->get_import_order(p_path);
  560. }
  561. return 0;
  562. }
  563. String ResourceLoader::get_import_group_file(const String &p_path) {
  564. String local_path = _path_remap(_validate_local_path(p_path));
  565. for (int i = 0; i < loader_count; i++) {
  566. if (!loader[i]->recognize_path(local_path)) {
  567. continue;
  568. }
  569. return loader[i]->get_import_group_file(p_path);
  570. }
  571. return String(); //not found
  572. }
  573. bool ResourceLoader::is_import_valid(const String &p_path) {
  574. String local_path = _path_remap(_validate_local_path(p_path));
  575. for (int i = 0; i < loader_count; i++) {
  576. if (!loader[i]->recognize_path(local_path)) {
  577. continue;
  578. }
  579. return loader[i]->is_import_valid(p_path);
  580. }
  581. return false; //not found
  582. }
  583. bool ResourceLoader::is_imported(const String &p_path) {
  584. String local_path = _path_remap(_validate_local_path(p_path));
  585. for (int i = 0; i < loader_count; i++) {
  586. if (!loader[i]->recognize_path(local_path)) {
  587. continue;
  588. }
  589. return loader[i]->is_imported(p_path);
  590. }
  591. return false; //not found
  592. }
  593. void ResourceLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  594. String local_path = _path_remap(_validate_local_path(p_path));
  595. for (int i = 0; i < loader_count; i++) {
  596. if (!loader[i]->recognize_path(local_path)) {
  597. continue;
  598. }
  599. loader[i]->get_dependencies(local_path, p_dependencies, p_add_types);
  600. }
  601. }
  602. Error ResourceLoader::rename_dependencies(const String &p_path, const HashMap<String, String> &p_map) {
  603. String local_path = _path_remap(_validate_local_path(p_path));
  604. for (int i = 0; i < loader_count; i++) {
  605. if (!loader[i]->recognize_path(local_path)) {
  606. continue;
  607. }
  608. return loader[i]->rename_dependencies(local_path, p_map);
  609. }
  610. return OK; // ??
  611. }
  612. void ResourceLoader::get_classes_used(const String &p_path, HashSet<StringName> *r_classes) {
  613. String local_path = _validate_local_path(p_path);
  614. for (int i = 0; i < loader_count; i++) {
  615. if (!loader[i]->recognize_path(local_path)) {
  616. continue;
  617. }
  618. return loader[i]->get_classes_used(p_path, r_classes);
  619. }
  620. }
  621. String ResourceLoader::get_resource_type(const String &p_path) {
  622. String local_path = _validate_local_path(p_path);
  623. for (int i = 0; i < loader_count; i++) {
  624. String result = loader[i]->get_resource_type(local_path);
  625. if (!result.is_empty()) {
  626. return result;
  627. }
  628. }
  629. return "";
  630. }
  631. String ResourceLoader::get_resource_script_class(const String &p_path) {
  632. String local_path = _validate_local_path(p_path);
  633. for (int i = 0; i < loader_count; i++) {
  634. String result = loader[i]->get_resource_script_class(local_path);
  635. if (!result.is_empty()) {
  636. return result;
  637. }
  638. }
  639. return "";
  640. }
  641. ResourceUID::ID ResourceLoader::get_resource_uid(const String &p_path) {
  642. String local_path = _validate_local_path(p_path);
  643. for (int i = 0; i < loader_count; i++) {
  644. ResourceUID::ID id = loader[i]->get_resource_uid(local_path);
  645. if (id != ResourceUID::INVALID_ID) {
  646. return id;
  647. }
  648. }
  649. return ResourceUID::INVALID_ID;
  650. }
  651. String ResourceLoader::_path_remap(const String &p_path, bool *r_translation_remapped) {
  652. String new_path = p_path;
  653. if (translation_remaps.has(p_path)) {
  654. // translation_remaps has the following format:
  655. // { "res://path.png": PackedStringArray( "res://path-ru.png:ru", "res://path-de.png:de" ) }
  656. // To find the path of the remapped resource, we extract the locale name after
  657. // the last ':' to match the project locale.
  658. // An extra remap may still be necessary afterwards due to the text -> binary converter on export.
  659. String locale = TranslationServer::get_singleton()->get_locale();
  660. ERR_FAIL_COND_V_MSG(locale.length() < 2, p_path, "Could not remap path '" + p_path + "' for translation as configured locale '" + locale + "' is invalid.");
  661. Vector<String> &res_remaps = *translation_remaps.getptr(new_path);
  662. int best_score = 0;
  663. for (int i = 0; i < res_remaps.size(); i++) {
  664. int split = res_remaps[i].rfind(":");
  665. if (split == -1) {
  666. continue;
  667. }
  668. String l = res_remaps[i].substr(split + 1).strip_edges();
  669. int score = TranslationServer::get_singleton()->compare_locales(locale, l);
  670. if (score > 0 && score >= best_score) {
  671. new_path = res_remaps[i].left(split);
  672. best_score = score;
  673. if (score == 10) {
  674. break; // Exact match, skip the rest.
  675. }
  676. }
  677. }
  678. if (r_translation_remapped) {
  679. *r_translation_remapped = true;
  680. }
  681. // Fallback to p_path if new_path does not exist.
  682. if (!FileAccess::exists(new_path)) {
  683. WARN_PRINT(vformat("Translation remap '%s' does not exist. Falling back to '%s'.", new_path, p_path));
  684. new_path = p_path;
  685. }
  686. }
  687. if (path_remaps.has(new_path)) {
  688. new_path = path_remaps[new_path];
  689. } else {
  690. // Try file remap.
  691. Error err;
  692. Ref<FileAccess> f = FileAccess::open(new_path + ".remap", FileAccess::READ, &err);
  693. if (f.is_valid()) {
  694. VariantParser::StreamFile stream;
  695. stream.f = f;
  696. String assign;
  697. Variant value;
  698. VariantParser::Tag next_tag;
  699. int lines = 0;
  700. String error_text;
  701. while (true) {
  702. assign = Variant();
  703. next_tag.fields.clear();
  704. next_tag.name = String();
  705. err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
  706. if (err == ERR_FILE_EOF) {
  707. break;
  708. } else if (err != OK) {
  709. ERR_PRINT("Parse error: " + p_path + ".remap:" + itos(lines) + " error: " + error_text + ".");
  710. break;
  711. }
  712. if (assign == "path") {
  713. new_path = value;
  714. break;
  715. } else if (next_tag.name != "remap") {
  716. break;
  717. }
  718. }
  719. }
  720. }
  721. return new_path;
  722. }
  723. String ResourceLoader::import_remap(const String &p_path) {
  724. if (ResourceFormatImporter::get_singleton()->recognize_path(p_path)) {
  725. return ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_path);
  726. }
  727. return p_path;
  728. }
  729. String ResourceLoader::path_remap(const String &p_path) {
  730. return _path_remap(p_path);
  731. }
  732. void ResourceLoader::reload_translation_remaps() {
  733. ResourceCache::lock.lock();
  734. List<Resource *> to_reload;
  735. SelfList<Resource> *E = remapped_list.first();
  736. while (E) {
  737. to_reload.push_back(E->self());
  738. E = E->next();
  739. }
  740. ResourceCache::lock.unlock();
  741. //now just make sure to not delete any of these resources while changing locale..
  742. while (to_reload.front()) {
  743. to_reload.front()->get()->reload_from_file();
  744. to_reload.pop_front();
  745. }
  746. }
  747. void ResourceLoader::load_translation_remaps() {
  748. if (!ProjectSettings::get_singleton()->has_setting("internationalization/locale/translation_remaps")) {
  749. return;
  750. }
  751. Dictionary remaps = GLOBAL_GET("internationalization/locale/translation_remaps");
  752. List<Variant> keys;
  753. remaps.get_key_list(&keys);
  754. for (const Variant &E : keys) {
  755. Array langs = remaps[E];
  756. Vector<String> lang_remaps;
  757. lang_remaps.resize(langs.size());
  758. for (int i = 0; i < langs.size(); i++) {
  759. lang_remaps.write[i] = langs[i];
  760. }
  761. translation_remaps[String(E)] = lang_remaps;
  762. }
  763. }
  764. void ResourceLoader::clear_translation_remaps() {
  765. translation_remaps.clear();
  766. while (remapped_list.first() != nullptr) {
  767. remapped_list.remove(remapped_list.first());
  768. }
  769. }
  770. void ResourceLoader::clear_thread_load_tasks() {
  771. thread_load_mutex->lock();
  772. for (KeyValue<String, ResourceLoader::ThreadLoadTask> &E : thread_load_tasks) {
  773. switch (E.value.status) {
  774. case ResourceLoader::ThreadLoadStatus::THREAD_LOAD_LOADED: {
  775. E.value.resource = Ref<Resource>();
  776. } break;
  777. case ResourceLoader::ThreadLoadStatus::THREAD_LOAD_IN_PROGRESS: {
  778. if (E.value.thread != nullptr) {
  779. E.value.thread->wait_to_finish();
  780. memdelete(E.value.thread);
  781. E.value.thread = nullptr;
  782. }
  783. E.value.resource = Ref<Resource>();
  784. } break;
  785. case ResourceLoader::ThreadLoadStatus::THREAD_LOAD_FAILED:
  786. default: {
  787. // do nothing
  788. }
  789. }
  790. }
  791. thread_load_tasks.clear();
  792. thread_load_mutex->unlock();
  793. }
  794. void ResourceLoader::load_path_remaps() {
  795. if (!ProjectSettings::get_singleton()->has_setting("path_remap/remapped_paths")) {
  796. return;
  797. }
  798. Vector<String> remaps = GLOBAL_GET("path_remap/remapped_paths");
  799. int rc = remaps.size();
  800. ERR_FAIL_COND(rc & 1); //must be even
  801. const String *r = remaps.ptr();
  802. for (int i = 0; i < rc; i += 2) {
  803. path_remaps[r[i]] = r[i + 1];
  804. }
  805. }
  806. void ResourceLoader::clear_path_remaps() {
  807. path_remaps.clear();
  808. }
  809. void ResourceLoader::set_load_callback(ResourceLoadedCallback p_callback) {
  810. _loaded_callback = p_callback;
  811. }
  812. ResourceLoadedCallback ResourceLoader::_loaded_callback = nullptr;
  813. Ref<ResourceFormatLoader> ResourceLoader::_find_custom_resource_format_loader(String path) {
  814. for (int i = 0; i < loader_count; ++i) {
  815. if (loader[i]->get_script_instance() && loader[i]->get_script_instance()->get_script()->get_path() == path) {
  816. return loader[i];
  817. }
  818. }
  819. return Ref<ResourceFormatLoader>();
  820. }
  821. bool ResourceLoader::add_custom_resource_format_loader(String script_path) {
  822. if (_find_custom_resource_format_loader(script_path).is_valid()) {
  823. return false;
  824. }
  825. Ref<Resource> res = ResourceLoader::load(script_path);
  826. ERR_FAIL_COND_V(res.is_null(), false);
  827. ERR_FAIL_COND_V(!res->is_class("Script"), false);
  828. Ref<Script> s = res;
  829. StringName ibt = s->get_instance_base_type();
  830. bool valid_type = ClassDB::is_parent_class(ibt, "ResourceFormatLoader");
  831. ERR_FAIL_COND_V_MSG(!valid_type, false, "Script does not inherit a CustomResourceLoader: " + script_path + ".");
  832. Object *obj = ClassDB::instantiate(ibt);
  833. ERR_FAIL_COND_V_MSG(obj == nullptr, false, "Cannot instance script as custom resource loader, expected 'ResourceFormatLoader' inheritance, got: " + String(ibt) + ".");
  834. Ref<ResourceFormatLoader> crl = Object::cast_to<ResourceFormatLoader>(obj);
  835. crl->set_script(s);
  836. ResourceLoader::add_resource_format_loader(crl);
  837. return true;
  838. }
  839. void ResourceLoader::set_create_missing_resources_if_class_unavailable(bool p_enable) {
  840. create_missing_resources_if_class_unavailable = p_enable;
  841. }
  842. void ResourceLoader::add_custom_loaders() {
  843. // Custom loaders registration exploits global class names
  844. String custom_loader_base_class = ResourceFormatLoader::get_class_static();
  845. List<StringName> global_classes;
  846. ScriptServer::get_global_class_list(&global_classes);
  847. for (const StringName &class_name : global_classes) {
  848. StringName base_class = ScriptServer::get_global_class_native_base(class_name);
  849. if (base_class == custom_loader_base_class) {
  850. String path = ScriptServer::get_global_class_path(class_name);
  851. add_custom_resource_format_loader(path);
  852. }
  853. }
  854. }
  855. void ResourceLoader::remove_custom_loaders() {
  856. Vector<Ref<ResourceFormatLoader>> custom_loaders;
  857. for (int i = 0; i < loader_count; ++i) {
  858. if (loader[i]->get_script_instance()) {
  859. custom_loaders.push_back(loader[i]);
  860. }
  861. }
  862. for (int i = 0; i < custom_loaders.size(); ++i) {
  863. remove_resource_format_loader(custom_loaders[i]);
  864. }
  865. }
  866. void ResourceLoader::initialize() {
  867. thread_load_mutex = memnew(SafeBinaryMutex<BINARY_MUTEX_TAG>);
  868. thread_load_max = OS::get_singleton()->get_processor_count();
  869. thread_loading_count = 0;
  870. thread_waiting_count = 0;
  871. thread_suspended_count = 0;
  872. thread_load_semaphore = memnew(Semaphore);
  873. }
  874. void ResourceLoader::finalize() {
  875. memdelete(thread_load_mutex);
  876. memdelete(thread_load_semaphore);
  877. }
  878. ResourceLoadErrorNotify ResourceLoader::err_notify = nullptr;
  879. void *ResourceLoader::err_notify_ud = nullptr;
  880. DependencyErrorNotify ResourceLoader::dep_err_notify = nullptr;
  881. void *ResourceLoader::dep_err_notify_ud = nullptr;
  882. bool ResourceLoader::create_missing_resources_if_class_unavailable = false;
  883. bool ResourceLoader::abort_on_missing_resource = true;
  884. bool ResourceLoader::timestamp_on_load = false;
  885. template <>
  886. thread_local uint32_t SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG>::count = 0;
  887. SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG> *ResourceLoader::thread_load_mutex = nullptr;
  888. HashMap<String, ResourceLoader::ThreadLoadTask> ResourceLoader::thread_load_tasks;
  889. Semaphore *ResourceLoader::thread_load_semaphore = nullptr;
  890. int ResourceLoader::thread_loading_count = 0;
  891. int ResourceLoader::thread_waiting_count = 0;
  892. int ResourceLoader::thread_suspended_count = 0;
  893. int ResourceLoader::thread_load_max = 0;
  894. SelfList<Resource>::List ResourceLoader::remapped_list;
  895. HashMap<String, Vector<String>> ResourceLoader::translation_remaps;
  896. HashMap<String, String> ResourceLoader::path_remaps;
  897. ResourceLoaderImport ResourceLoader::import = nullptr;