resource_loader.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  1. /*************************************************************************/
  2. /* resource_loader.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  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/os.h"
  35. #include "core/string/print_string.h"
  36. #include "core/string/translation.h"
  37. #include "core/variant/variant_parser.h"
  38. #ifdef DEBUG_LOAD_THREADED
  39. #define print_lt(m_text) print_line(m_text)
  40. #else
  41. #define print_lt(m_text)
  42. #endif
  43. Ref<ResourceFormatLoader> ResourceLoader::loader[ResourceLoader::MAX_LOADERS];
  44. int ResourceLoader::loader_count = 0;
  45. bool ResourceFormatLoader::recognize_path(const String &p_path, const String &p_for_type) const {
  46. String extension = p_path.get_extension();
  47. List<String> extensions;
  48. if (p_for_type.is_empty()) {
  49. get_recognized_extensions(&extensions);
  50. } else {
  51. get_recognized_extensions_for_type(p_for_type, &extensions);
  52. }
  53. for (const String &E : extensions) {
  54. if (E.nocasecmp_to(extension) == 0) {
  55. return true;
  56. }
  57. }
  58. return false;
  59. }
  60. bool ResourceFormatLoader::handles_type(const String &p_type) const {
  61. bool success = false;
  62. if (GDVIRTUAL_CALL(_handles_type, p_type, success)) {
  63. return success;
  64. }
  65. return false;
  66. }
  67. void ResourceFormatLoader::get_classes_used(const String &p_path, HashSet<StringName> *r_classes) {
  68. Vector<String> ret;
  69. if (GDVIRTUAL_CALL(_get_classes_used, p_path, ret)) {
  70. for (int i = 0; i < ret.size(); i++) {
  71. r_classes->insert(ret[i]);
  72. }
  73. return;
  74. }
  75. String res = get_resource_type(p_path);
  76. if (!res.is_empty()) {
  77. r_classes->insert(res);
  78. }
  79. }
  80. String ResourceFormatLoader::get_resource_type(const String &p_path) const {
  81. String ret;
  82. if (GDVIRTUAL_CALL(_get_resource_type, p_path, ret)) {
  83. return ret;
  84. }
  85. return "";
  86. }
  87. ResourceUID::ID ResourceFormatLoader::get_resource_uid(const String &p_path) const {
  88. int64_t uid = ResourceUID::INVALID_ID;
  89. if (GDVIRTUAL_CALL(_get_resource_uid, p_path, uid)) {
  90. return uid;
  91. }
  92. return ResourceUID::INVALID_ID;
  93. }
  94. void ResourceFormatLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
  95. if (p_type.is_empty() || handles_type(p_type)) {
  96. get_recognized_extensions(p_extensions);
  97. }
  98. }
  99. void ResourceLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) {
  100. for (int i = 0; i < loader_count; i++) {
  101. loader[i]->get_recognized_extensions_for_type(p_type, p_extensions);
  102. }
  103. }
  104. bool ResourceFormatLoader::exists(const String &p_path) const {
  105. bool success = false;
  106. if (GDVIRTUAL_CALL(_exists, p_path, success)) {
  107. return success;
  108. }
  109. return FileAccess::exists(p_path); //by default just check file
  110. }
  111. void ResourceFormatLoader::get_recognized_extensions(List<String> *p_extensions) const {
  112. PackedStringArray exts;
  113. if (GDVIRTUAL_CALL(_get_recognized_extensions, exts)) {
  114. const String *r = exts.ptr();
  115. for (int i = 0; i < exts.size(); ++i) {
  116. p_extensions->push_back(r[i]);
  117. }
  118. }
  119. }
  120. 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) {
  121. Variant res;
  122. if (GDVIRTUAL_CALL(_load, p_path, p_original_path, p_use_sub_threads, p_cache_mode, res)) {
  123. if (res.get_type() == Variant::INT) { // Error code, abort.
  124. if (r_error) {
  125. *r_error = (Error)res.operator int64_t();
  126. }
  127. return Ref<Resource>();
  128. } else { // Success, pass on result.
  129. if (r_error) {
  130. *r_error = OK;
  131. }
  132. return res;
  133. }
  134. }
  135. ERR_FAIL_V_MSG(Ref<Resource>(), "Failed to load resource '" + p_path + "'. ResourceFormatLoader::load was not implemented for this resource type.");
  136. }
  137. void ResourceFormatLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  138. PackedStringArray deps;
  139. if (GDVIRTUAL_CALL(_get_dependencies, p_path, p_add_types, deps)) {
  140. const String *r = deps.ptr();
  141. for (int i = 0; i < deps.size(); ++i) {
  142. p_dependencies->push_back(r[i]);
  143. }
  144. }
  145. }
  146. Error ResourceFormatLoader::rename_dependencies(const String &p_path, const HashMap<String, String> &p_map) {
  147. Dictionary deps_dict;
  148. for (KeyValue<String, String> E : p_map) {
  149. deps_dict[E.key] = E.value;
  150. }
  151. int64_t err = OK;
  152. if (GDVIRTUAL_CALL(_rename_dependencies, p_path, deps_dict, err)) {
  153. return (Error)err;
  154. }
  155. return OK;
  156. }
  157. void ResourceFormatLoader::_bind_methods() {
  158. BIND_ENUM_CONSTANT(CACHE_MODE_IGNORE);
  159. BIND_ENUM_CONSTANT(CACHE_MODE_REUSE);
  160. BIND_ENUM_CONSTANT(CACHE_MODE_REPLACE);
  161. GDVIRTUAL_BIND(_get_recognized_extensions);
  162. GDVIRTUAL_BIND(_handles_type, "type");
  163. GDVIRTUAL_BIND(_get_resource_type, "path");
  164. GDVIRTUAL_BIND(_get_resource_uid, "path");
  165. GDVIRTUAL_BIND(_get_dependencies, "path", "add_types");
  166. GDVIRTUAL_BIND(_rename_dependencies, "path", "renames");
  167. GDVIRTUAL_BIND(_exists, "path");
  168. GDVIRTUAL_BIND(_get_classes_used, "path");
  169. GDVIRTUAL_BIND(_load, "path", "original_path", "use_sub_threads", "cache_mode");
  170. }
  171. ///////////////////////////////////
  172. 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) {
  173. bool found = false;
  174. // Try all loaders and pick the first match for the type hint
  175. for (int i = 0; i < loader_count; i++) {
  176. if (!loader[i]->recognize_path(p_path, p_type_hint)) {
  177. continue;
  178. }
  179. found = true;
  180. 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);
  181. if (res.is_null()) {
  182. continue;
  183. }
  184. return res;
  185. }
  186. ERR_FAIL_COND_V_MSG(found, Ref<Resource>(),
  187. vformat("Failed loading resource: %s. Make sure resources have been imported by opening the project in the editor at least once.", p_path));
  188. #ifdef TOOLS_ENABLED
  189. Ref<FileAccess> file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);
  190. ERR_FAIL_COND_V_MSG(!file_check->file_exists(p_path), Ref<Resource>(), "Resource file not found: " + p_path + ".");
  191. #endif
  192. ERR_FAIL_V_MSG(Ref<Resource>(), "No loader found for resource: " + p_path + ".");
  193. }
  194. void ResourceLoader::_thread_load_function(void *p_userdata) {
  195. ThreadLoadTask &load_task = *(ThreadLoadTask *)p_userdata;
  196. load_task.loader_id = Thread::get_caller_id();
  197. if (load_task.semaphore) {
  198. //this is an actual thread, so wait for Ok from semaphore
  199. thread_load_semaphore->wait(); //wait until its ok to start loading
  200. }
  201. 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);
  202. load_task.progress = 1.0; //it was fully loaded at this point, so force progress to 1.0
  203. thread_load_mutex->lock();
  204. if (load_task.error != OK) {
  205. load_task.status = THREAD_LOAD_FAILED;
  206. } else {
  207. load_task.status = THREAD_LOAD_LOADED;
  208. }
  209. if (load_task.semaphore) {
  210. if (load_task.start_next && thread_waiting_count > 0) {
  211. thread_waiting_count--;
  212. //thread loading count remains constant, this ends but another one begins
  213. thread_load_semaphore->post();
  214. } else {
  215. thread_loading_count--; //no threads waiting, just reduce loading count
  216. }
  217. 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));
  218. for (int i = 0; i < load_task.poll_requests; i++) {
  219. load_task.semaphore->post();
  220. }
  221. memdelete(load_task.semaphore);
  222. load_task.semaphore = nullptr;
  223. }
  224. if (load_task.resource.is_valid()) {
  225. load_task.resource->set_path(load_task.local_path);
  226. if (load_task.xl_remapped) {
  227. load_task.resource->set_as_translation_remapped(true);
  228. }
  229. #ifdef TOOLS_ENABLED
  230. load_task.resource->set_edited(false);
  231. if (timestamp_on_load) {
  232. uint64_t mt = FileAccess::get_modified_time(load_task.remapped_path);
  233. //printf("mt %s: %lli\n",remapped_path.utf8().get_data(),mt);
  234. load_task.resource->set_last_modified_time(mt);
  235. }
  236. #endif
  237. if (_loaded_callback) {
  238. _loaded_callback(load_task.resource, load_task.local_path);
  239. }
  240. }
  241. thread_load_mutex->unlock();
  242. }
  243. static String _validate_local_path(const String &p_path) {
  244. ResourceUID::ID uid = ResourceUID::get_singleton()->text_to_id(p_path);
  245. if (uid != ResourceUID::INVALID_ID) {
  246. return ResourceUID::get_singleton()->get_id_path(uid);
  247. } else if (p_path.is_relative_path()) {
  248. return "res://" + p_path;
  249. } else {
  250. return ProjectSettings::get_singleton()->localize_path(p_path);
  251. }
  252. }
  253. 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) {
  254. String local_path = _validate_local_path(p_path);
  255. thread_load_mutex->lock();
  256. if (!p_source_resource.is_empty()) {
  257. //must be loading from this resource
  258. if (!thread_load_tasks.has(p_source_resource)) {
  259. thread_load_mutex->unlock();
  260. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "There is no thread loading source resource '" + p_source_resource + "'.");
  261. }
  262. //must be loading from this thread
  263. if (thread_load_tasks[p_source_resource].loader_id != Thread::get_caller_id()) {
  264. thread_load_mutex->unlock();
  265. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Threading loading resource'" + local_path + " failed: Source specified: '" + p_source_resource + "' but was not called by it.");
  266. }
  267. //must not be already added as s sub tasks
  268. if (thread_load_tasks[p_source_resource].sub_tasks.has(local_path)) {
  269. thread_load_mutex->unlock();
  270. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Thread loading source resource '" + p_source_resource + "' already is loading '" + local_path + "'.");
  271. }
  272. }
  273. if (thread_load_tasks.has(local_path)) {
  274. thread_load_tasks[local_path].requests++;
  275. if (!p_source_resource.is_empty()) {
  276. thread_load_tasks[p_source_resource].sub_tasks.insert(local_path);
  277. }
  278. thread_load_mutex->unlock();
  279. return OK;
  280. }
  281. {
  282. //create load task
  283. ThreadLoadTask load_task;
  284. load_task.requests = 1;
  285. load_task.remapped_path = _path_remap(local_path, &load_task.xl_remapped);
  286. load_task.local_path = local_path;
  287. load_task.type_hint = p_type_hint;
  288. load_task.cache_mode = p_cache_mode;
  289. load_task.use_sub_threads = p_use_sub_threads;
  290. { //must check if resource is already loaded before attempting to load it in a thread
  291. if (load_task.loader_id == Thread::get_caller_id()) {
  292. thread_load_mutex->unlock();
  293. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Attempted to load a resource already being loaded from this thread, cyclic reference?");
  294. }
  295. Ref<Resource> existing = ResourceCache::get_ref(local_path);
  296. if (existing.is_valid()) {
  297. //referencing is fine
  298. load_task.resource = existing;
  299. load_task.status = THREAD_LOAD_LOADED;
  300. load_task.progress = 1.0;
  301. }
  302. }
  303. if (!p_source_resource.is_empty()) {
  304. thread_load_tasks[p_source_resource].sub_tasks.insert(local_path);
  305. }
  306. thread_load_tasks[local_path] = load_task;
  307. }
  308. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  309. if (load_task.resource.is_null()) { //needs to be loaded in thread
  310. load_task.semaphore = memnew(Semaphore);
  311. if (thread_loading_count < thread_load_max) {
  312. thread_loading_count++;
  313. thread_load_semaphore->post(); //we have free threads, so allow one
  314. } else {
  315. thread_waiting_count++;
  316. }
  317. 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));
  318. load_task.thread = memnew(Thread);
  319. load_task.thread->start(_thread_load_function, &thread_load_tasks[local_path]);
  320. load_task.loader_id = load_task.thread->get_id();
  321. }
  322. thread_load_mutex->unlock();
  323. return OK;
  324. }
  325. float ResourceLoader::_dependency_get_progress(const String &p_path) {
  326. if (thread_load_tasks.has(p_path)) {
  327. ThreadLoadTask &load_task = thread_load_tasks[p_path];
  328. int dep_count = load_task.sub_tasks.size();
  329. if (dep_count > 0) {
  330. float dep_progress = 0;
  331. for (const String &E : load_task.sub_tasks) {
  332. dep_progress += _dependency_get_progress(E);
  333. }
  334. dep_progress /= float(dep_count);
  335. dep_progress *= 0.5;
  336. dep_progress += load_task.progress * 0.5;
  337. return dep_progress;
  338. } else {
  339. return load_task.progress;
  340. }
  341. } else {
  342. return 1.0; //assume finished loading it so it no longer exists
  343. }
  344. }
  345. ResourceLoader::ThreadLoadStatus ResourceLoader::load_threaded_get_status(const String &p_path, float *r_progress) {
  346. String local_path = _validate_local_path(p_path);
  347. thread_load_mutex->lock();
  348. if (!thread_load_tasks.has(local_path)) {
  349. thread_load_mutex->unlock();
  350. return THREAD_LOAD_INVALID_RESOURCE;
  351. }
  352. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  353. ThreadLoadStatus status;
  354. status = load_task.status;
  355. if (r_progress) {
  356. *r_progress = _dependency_get_progress(local_path);
  357. }
  358. thread_load_mutex->unlock();
  359. return status;
  360. }
  361. Ref<Resource> ResourceLoader::load_threaded_get(const String &p_path, Error *r_error) {
  362. String local_path = _validate_local_path(p_path);
  363. thread_load_mutex->lock();
  364. if (!thread_load_tasks.has(local_path)) {
  365. thread_load_mutex->unlock();
  366. if (r_error) {
  367. *r_error = ERR_INVALID_PARAMETER;
  368. }
  369. return Ref<Resource>();
  370. }
  371. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  372. //semaphore still exists, meaning it's still loading, request poll
  373. Semaphore *semaphore = load_task.semaphore;
  374. if (semaphore) {
  375. load_task.poll_requests++;
  376. {
  377. // As we got a semaphore, this means we are going to have to wait
  378. // until the sub-resource is done loading
  379. //
  380. // As this thread will become 'blocked' we should "exchange" its
  381. // active status with a waiting one, to ensure load continues.
  382. //
  383. // This ensures loading is never blocked and that is also within
  384. // the maximum number of active threads.
  385. if (thread_waiting_count > 0) {
  386. thread_waiting_count--;
  387. thread_loading_count++;
  388. thread_load_semaphore->post();
  389. load_task.start_next = false; //do not start next since we are doing it here
  390. }
  391. thread_suspended_count++;
  392. 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));
  393. }
  394. thread_load_mutex->unlock();
  395. semaphore->wait();
  396. thread_load_mutex->lock();
  397. thread_suspended_count--;
  398. if (!thread_load_tasks.has(local_path)) { //may have been erased during unlock and this was always an invalid call
  399. thread_load_mutex->unlock();
  400. if (r_error) {
  401. *r_error = ERR_INVALID_PARAMETER;
  402. }
  403. return Ref<Resource>();
  404. }
  405. }
  406. Ref<Resource> resource = load_task.resource;
  407. if (r_error) {
  408. *r_error = load_task.error;
  409. }
  410. load_task.requests--;
  411. if (load_task.requests == 0) {
  412. if (load_task.thread) { //thread may not have been used
  413. load_task.thread->wait_to_finish();
  414. memdelete(load_task.thread);
  415. }
  416. thread_load_tasks.erase(local_path);
  417. }
  418. thread_load_mutex->unlock();
  419. return resource;
  420. }
  421. Ref<Resource> ResourceLoader::load(const String &p_path, const String &p_type_hint, ResourceFormatLoader::CacheMode p_cache_mode, Error *r_error) {
  422. if (r_error) {
  423. *r_error = ERR_CANT_OPEN;
  424. }
  425. String local_path = _validate_local_path(p_path);
  426. if (p_cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
  427. thread_load_mutex->lock();
  428. //Is it already being loaded? poll until done
  429. if (thread_load_tasks.has(local_path)) {
  430. Error err = load_threaded_request(p_path, p_type_hint);
  431. if (err != OK) {
  432. if (r_error) {
  433. *r_error = err;
  434. }
  435. thread_load_mutex->unlock();
  436. return Ref<Resource>();
  437. }
  438. thread_load_mutex->unlock();
  439. return load_threaded_get(p_path, r_error);
  440. }
  441. //Is it cached?
  442. Ref<Resource> existing = ResourceCache::get_ref(local_path);
  443. if (existing.is_valid()) {
  444. thread_load_mutex->unlock();
  445. if (r_error) {
  446. *r_error = OK;
  447. }
  448. return existing; //use cached
  449. }
  450. //load using task (but this thread)
  451. ThreadLoadTask load_task;
  452. load_task.requests = 1;
  453. load_task.local_path = local_path;
  454. load_task.remapped_path = _path_remap(local_path, &load_task.xl_remapped);
  455. load_task.type_hint = p_type_hint;
  456. load_task.cache_mode = p_cache_mode; //ignore
  457. load_task.loader_id = Thread::get_caller_id();
  458. thread_load_tasks[local_path] = load_task;
  459. thread_load_mutex->unlock();
  460. _thread_load_function(&thread_load_tasks[local_path]);
  461. return load_threaded_get(p_path, r_error);
  462. } else {
  463. bool xl_remapped = false;
  464. String path = _path_remap(local_path, &xl_remapped);
  465. if (path.is_empty()) {
  466. ERR_FAIL_V_MSG(Ref<Resource>(), "Remapping '" + local_path + "' failed.");
  467. }
  468. print_verbose("Loading resource: " + path);
  469. float p;
  470. Ref<Resource> res = _load(path, local_path, p_type_hint, p_cache_mode, r_error, false, &p);
  471. if (res.is_null()) {
  472. print_verbose("Failed loading resource: " + path);
  473. return Ref<Resource>();
  474. }
  475. if (xl_remapped) {
  476. res->set_as_translation_remapped(true);
  477. }
  478. #ifdef TOOLS_ENABLED
  479. res->set_edited(false);
  480. if (timestamp_on_load) {
  481. uint64_t mt = FileAccess::get_modified_time(path);
  482. //printf("mt %s: %lli\n",remapped_path.utf8().get_data(),mt);
  483. res->set_last_modified_time(mt);
  484. }
  485. #endif
  486. return res;
  487. }
  488. }
  489. bool ResourceLoader::exists(const String &p_path, const String &p_type_hint) {
  490. String local_path = _validate_local_path(p_path);
  491. if (ResourceCache::has(local_path)) {
  492. return true; // If cached, it probably exists
  493. }
  494. bool xl_remapped = false;
  495. String path = _path_remap(local_path, &xl_remapped);
  496. // Try all loaders and pick the first match for the type hint
  497. for (int i = 0; i < loader_count; i++) {
  498. if (!loader[i]->recognize_path(path, p_type_hint)) {
  499. continue;
  500. }
  501. if (loader[i]->exists(path)) {
  502. return true;
  503. }
  504. }
  505. return false;
  506. }
  507. void ResourceLoader::add_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader, bool p_at_front) {
  508. ERR_FAIL_COND(p_format_loader.is_null());
  509. ERR_FAIL_COND(loader_count >= MAX_LOADERS);
  510. if (p_at_front) {
  511. for (int i = loader_count; i > 0; i--) {
  512. loader[i] = loader[i - 1];
  513. }
  514. loader[0] = p_format_loader;
  515. loader_count++;
  516. } else {
  517. loader[loader_count++] = p_format_loader;
  518. }
  519. }
  520. void ResourceLoader::remove_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader) {
  521. ERR_FAIL_COND(p_format_loader.is_null());
  522. // Find loader
  523. int i = 0;
  524. for (; i < loader_count; ++i) {
  525. if (loader[i] == p_format_loader) {
  526. break;
  527. }
  528. }
  529. ERR_FAIL_COND(i >= loader_count); // Not found
  530. // Shift next loaders up
  531. for (; i < loader_count - 1; ++i) {
  532. loader[i] = loader[i + 1];
  533. }
  534. loader[loader_count - 1].unref();
  535. --loader_count;
  536. }
  537. int ResourceLoader::get_import_order(const String &p_path) {
  538. String local_path = _path_remap(_validate_local_path(p_path));
  539. for (int i = 0; i < loader_count; i++) {
  540. if (!loader[i]->recognize_path(local_path)) {
  541. continue;
  542. }
  543. return loader[i]->get_import_order(p_path);
  544. }
  545. return 0;
  546. }
  547. String ResourceLoader::get_import_group_file(const String &p_path) {
  548. String local_path = _path_remap(_validate_local_path(p_path));
  549. for (int i = 0; i < loader_count; i++) {
  550. if (!loader[i]->recognize_path(local_path)) {
  551. continue;
  552. }
  553. return loader[i]->get_import_group_file(p_path);
  554. }
  555. return String(); //not found
  556. }
  557. bool ResourceLoader::is_import_valid(const String &p_path) {
  558. String local_path = _path_remap(_validate_local_path(p_path));
  559. for (int i = 0; i < loader_count; i++) {
  560. if (!loader[i]->recognize_path(local_path)) {
  561. continue;
  562. }
  563. return loader[i]->is_import_valid(p_path);
  564. }
  565. return false; //not found
  566. }
  567. bool ResourceLoader::is_imported(const String &p_path) {
  568. String local_path = _path_remap(_validate_local_path(p_path));
  569. for (int i = 0; i < loader_count; i++) {
  570. if (!loader[i]->recognize_path(local_path)) {
  571. continue;
  572. }
  573. return loader[i]->is_imported(p_path);
  574. }
  575. return false; //not found
  576. }
  577. void ResourceLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  578. String local_path = _path_remap(_validate_local_path(p_path));
  579. for (int i = 0; i < loader_count; i++) {
  580. if (!loader[i]->recognize_path(local_path)) {
  581. continue;
  582. }
  583. loader[i]->get_dependencies(local_path, p_dependencies, p_add_types);
  584. }
  585. }
  586. Error ResourceLoader::rename_dependencies(const String &p_path, const HashMap<String, String> &p_map) {
  587. String local_path = _path_remap(_validate_local_path(p_path));
  588. for (int i = 0; i < loader_count; i++) {
  589. if (!loader[i]->recognize_path(local_path)) {
  590. continue;
  591. }
  592. return loader[i]->rename_dependencies(local_path, p_map);
  593. }
  594. return OK; // ??
  595. }
  596. void ResourceLoader::get_classes_used(const String &p_path, HashSet<StringName> *r_classes) {
  597. String local_path = _validate_local_path(p_path);
  598. for (int i = 0; i < loader_count; i++) {
  599. if (!loader[i]->recognize_path(local_path)) {
  600. continue;
  601. }
  602. return loader[i]->get_classes_used(p_path, r_classes);
  603. }
  604. }
  605. String ResourceLoader::get_resource_type(const String &p_path) {
  606. String local_path = _validate_local_path(p_path);
  607. for (int i = 0; i < loader_count; i++) {
  608. String result = loader[i]->get_resource_type(local_path);
  609. if (!result.is_empty()) {
  610. return result;
  611. }
  612. }
  613. return "";
  614. }
  615. ResourceUID::ID ResourceLoader::get_resource_uid(const String &p_path) {
  616. String local_path = _validate_local_path(p_path);
  617. for (int i = 0; i < loader_count; i++) {
  618. ResourceUID::ID id = loader[i]->get_resource_uid(local_path);
  619. if (id != ResourceUID::INVALID_ID) {
  620. return id;
  621. }
  622. }
  623. return ResourceUID::INVALID_ID;
  624. }
  625. String ResourceLoader::_path_remap(const String &p_path, bool *r_translation_remapped) {
  626. String new_path = p_path;
  627. if (translation_remaps.has(p_path)) {
  628. // translation_remaps has the following format:
  629. // { "res://path.png": PackedStringArray( "res://path-ru.png:ru", "res://path-de.png:de" ) }
  630. // To find the path of the remapped resource, we extract the locale name after
  631. // the last ':' to match the project locale.
  632. // An extra remap may still be necessary afterwards due to the text -> binary converter on export.
  633. String locale = TranslationServer::get_singleton()->get_locale();
  634. ERR_FAIL_COND_V_MSG(locale.length() < 2, p_path, "Could not remap path '" + p_path + "' for translation as configured locale '" + locale + "' is invalid.");
  635. Vector<String> &res_remaps = *translation_remaps.getptr(new_path);
  636. int best_score = 0;
  637. for (int i = 0; i < res_remaps.size(); i++) {
  638. int split = res_remaps[i].rfind(":");
  639. if (split == -1) {
  640. continue;
  641. }
  642. String l = res_remaps[i].substr(split + 1).strip_edges();
  643. int score = TranslationServer::get_singleton()->compare_locales(locale, l);
  644. if (score > 0 && score >= best_score) {
  645. new_path = res_remaps[i].left(split);
  646. best_score = score;
  647. if (score == 10) {
  648. break; // Exact match, skip the rest.
  649. }
  650. }
  651. }
  652. if (r_translation_remapped) {
  653. *r_translation_remapped = true;
  654. }
  655. // Fallback to p_path if new_path does not exist.
  656. if (!FileAccess::exists(new_path)) {
  657. WARN_PRINT(vformat("Translation remap '%s' does not exist. Falling back to '%s'.", new_path, p_path));
  658. new_path = p_path;
  659. }
  660. }
  661. if (path_remaps.has(new_path)) {
  662. new_path = path_remaps[new_path];
  663. } else {
  664. // Try file remap.
  665. Error err;
  666. Ref<FileAccess> f = FileAccess::open(new_path + ".remap", FileAccess::READ, &err);
  667. if (f.is_valid()) {
  668. VariantParser::StreamFile stream;
  669. stream.f = f;
  670. String assign;
  671. Variant value;
  672. VariantParser::Tag next_tag;
  673. int lines = 0;
  674. String error_text;
  675. while (true) {
  676. assign = Variant();
  677. next_tag.fields.clear();
  678. next_tag.name = String();
  679. err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
  680. if (err == ERR_FILE_EOF) {
  681. break;
  682. } else if (err != OK) {
  683. ERR_PRINT("Parse error: " + p_path + ".remap:" + itos(lines) + " error: " + error_text + ".");
  684. break;
  685. }
  686. if (assign == "path") {
  687. new_path = value;
  688. break;
  689. } else if (next_tag.name != "remap") {
  690. break;
  691. }
  692. }
  693. }
  694. }
  695. return new_path;
  696. }
  697. String ResourceLoader::import_remap(const String &p_path) {
  698. if (ResourceFormatImporter::get_singleton()->recognize_path(p_path)) {
  699. return ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_path);
  700. }
  701. return p_path;
  702. }
  703. String ResourceLoader::path_remap(const String &p_path) {
  704. return _path_remap(p_path);
  705. }
  706. void ResourceLoader::reload_translation_remaps() {
  707. ResourceCache::lock.lock();
  708. List<Resource *> to_reload;
  709. SelfList<Resource> *E = remapped_list.first();
  710. while (E) {
  711. to_reload.push_back(E->self());
  712. E = E->next();
  713. }
  714. ResourceCache::lock.unlock();
  715. //now just make sure to not delete any of these resources while changing locale..
  716. while (to_reload.front()) {
  717. to_reload.front()->get()->reload_from_file();
  718. to_reload.pop_front();
  719. }
  720. }
  721. void ResourceLoader::load_translation_remaps() {
  722. if (!ProjectSettings::get_singleton()->has_setting("internationalization/locale/translation_remaps")) {
  723. return;
  724. }
  725. Dictionary remaps = ProjectSettings::get_singleton()->get("internationalization/locale/translation_remaps");
  726. List<Variant> keys;
  727. remaps.get_key_list(&keys);
  728. for (const Variant &E : keys) {
  729. Array langs = remaps[E];
  730. Vector<String> lang_remaps;
  731. lang_remaps.resize(langs.size());
  732. for (int i = 0; i < langs.size(); i++) {
  733. lang_remaps.write[i] = langs[i];
  734. }
  735. translation_remaps[String(E)] = lang_remaps;
  736. }
  737. }
  738. void ResourceLoader::clear_translation_remaps() {
  739. translation_remaps.clear();
  740. while (remapped_list.first() != nullptr) {
  741. remapped_list.remove(remapped_list.first());
  742. }
  743. }
  744. void ResourceLoader::load_path_remaps() {
  745. if (!ProjectSettings::get_singleton()->has_setting("path_remap/remapped_paths")) {
  746. return;
  747. }
  748. Vector<String> remaps = ProjectSettings::get_singleton()->get("path_remap/remapped_paths");
  749. int rc = remaps.size();
  750. ERR_FAIL_COND(rc & 1); //must be even
  751. const String *r = remaps.ptr();
  752. for (int i = 0; i < rc; i += 2) {
  753. path_remaps[r[i]] = r[i + 1];
  754. }
  755. }
  756. void ResourceLoader::clear_path_remaps() {
  757. path_remaps.clear();
  758. }
  759. void ResourceLoader::set_load_callback(ResourceLoadedCallback p_callback) {
  760. _loaded_callback = p_callback;
  761. }
  762. ResourceLoadedCallback ResourceLoader::_loaded_callback = nullptr;
  763. Ref<ResourceFormatLoader> ResourceLoader::_find_custom_resource_format_loader(String path) {
  764. for (int i = 0; i < loader_count; ++i) {
  765. if (loader[i]->get_script_instance() && loader[i]->get_script_instance()->get_script()->get_path() == path) {
  766. return loader[i];
  767. }
  768. }
  769. return Ref<ResourceFormatLoader>();
  770. }
  771. bool ResourceLoader::add_custom_resource_format_loader(String script_path) {
  772. if (_find_custom_resource_format_loader(script_path).is_valid()) {
  773. return false;
  774. }
  775. Ref<Resource> res = ResourceLoader::load(script_path);
  776. ERR_FAIL_COND_V(res.is_null(), false);
  777. ERR_FAIL_COND_V(!res->is_class("Script"), false);
  778. Ref<Script> s = res;
  779. StringName ibt = s->get_instance_base_type();
  780. bool valid_type = ClassDB::is_parent_class(ibt, "ResourceFormatLoader");
  781. ERR_FAIL_COND_V_MSG(!valid_type, false, "Script does not inherit a CustomResourceLoader: " + script_path + ".");
  782. Object *obj = ClassDB::instantiate(ibt);
  783. ERR_FAIL_COND_V_MSG(obj == nullptr, false, "Cannot instance script as custom resource loader, expected 'ResourceFormatLoader' inheritance, got: " + String(ibt) + ".");
  784. Ref<ResourceFormatLoader> crl = Object::cast_to<ResourceFormatLoader>(obj);
  785. crl->set_script(s);
  786. ResourceLoader::add_resource_format_loader(crl);
  787. return true;
  788. }
  789. void ResourceLoader::remove_custom_resource_format_loader(String script_path) {
  790. Ref<ResourceFormatLoader> custom_loader = _find_custom_resource_format_loader(script_path);
  791. if (custom_loader.is_valid()) {
  792. remove_resource_format_loader(custom_loader);
  793. }
  794. }
  795. void ResourceLoader::set_create_missing_resources_if_class_unavailable(bool p_enable) {
  796. create_missing_resources_if_class_unavailable = p_enable;
  797. }
  798. void ResourceLoader::add_custom_loaders() {
  799. // Custom loaders registration exploits global class names
  800. String custom_loader_base_class = ResourceFormatLoader::get_class_static();
  801. List<StringName> global_classes;
  802. ScriptServer::get_global_class_list(&global_classes);
  803. for (const StringName &class_name : global_classes) {
  804. StringName base_class = ScriptServer::get_global_class_native_base(class_name);
  805. if (base_class == custom_loader_base_class) {
  806. String path = ScriptServer::get_global_class_path(class_name);
  807. add_custom_resource_format_loader(path);
  808. }
  809. }
  810. }
  811. void ResourceLoader::remove_custom_loaders() {
  812. Vector<Ref<ResourceFormatLoader>> custom_loaders;
  813. for (int i = 0; i < loader_count; ++i) {
  814. if (loader[i]->get_script_instance()) {
  815. custom_loaders.push_back(loader[i]);
  816. }
  817. }
  818. for (int i = 0; i < custom_loaders.size(); ++i) {
  819. remove_resource_format_loader(custom_loaders[i]);
  820. }
  821. }
  822. void ResourceLoader::initialize() {
  823. thread_load_mutex = memnew(Mutex);
  824. thread_load_max = OS::get_singleton()->get_processor_count();
  825. thread_loading_count = 0;
  826. thread_waiting_count = 0;
  827. thread_suspended_count = 0;
  828. thread_load_semaphore = memnew(Semaphore);
  829. }
  830. void ResourceLoader::finalize() {
  831. memdelete(thread_load_mutex);
  832. memdelete(thread_load_semaphore);
  833. }
  834. ResourceLoadErrorNotify ResourceLoader::err_notify = nullptr;
  835. void *ResourceLoader::err_notify_ud = nullptr;
  836. DependencyErrorNotify ResourceLoader::dep_err_notify = nullptr;
  837. void *ResourceLoader::dep_err_notify_ud = nullptr;
  838. bool ResourceLoader::create_missing_resources_if_class_unavailable = false;
  839. bool ResourceLoader::abort_on_missing_resource = true;
  840. bool ResourceLoader::timestamp_on_load = false;
  841. Mutex *ResourceLoader::thread_load_mutex = nullptr;
  842. HashMap<String, ResourceLoader::ThreadLoadTask> ResourceLoader::thread_load_tasks;
  843. Semaphore *ResourceLoader::thread_load_semaphore = nullptr;
  844. int ResourceLoader::thread_loading_count = 0;
  845. int ResourceLoader::thread_waiting_count = 0;
  846. int ResourceLoader::thread_suspended_count = 0;
  847. int ResourceLoader::thread_load_max = 0;
  848. SelfList<Resource>::List ResourceLoader::remapped_list;
  849. HashMap<String, Vector<String>> ResourceLoader::translation_remaps;
  850. HashMap<String, String> ResourceLoader::path_remaps;
  851. ResourceLoaderImport ResourceLoader::import = nullptr;