resource_loader.cpp 33 KB

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