resource_loader.cpp 34 KB

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