resource_loader.cpp 33 KB

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