resource_loader.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193
  1. /**************************************************************************/
  2. /* resource_loader.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "resource_loader.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/file_access.h"
  33. #include "core/io/resource_importer.h"
  34. #include "core/object/script_language.h"
  35. #include "core/os/condition_variable.h"
  36. #include "core/os/os.h"
  37. #include "core/string/print_string.h"
  38. #include "core/string/translation.h"
  39. #include "core/variant/variant_parser.h"
  40. #ifdef DEBUG_LOAD_THREADED
  41. #define print_lt(m_text) print_line(m_text)
  42. #else
  43. #define print_lt(m_text)
  44. #endif
  45. Ref<ResourceFormatLoader> ResourceLoader::loader[ResourceLoader::MAX_LOADERS];
  46. int ResourceLoader::loader_count = 0;
  47. bool ResourceFormatLoader::recognize_path(const String &p_path, const String &p_for_type) const {
  48. bool ret = false;
  49. if (GDVIRTUAL_CALL(_recognize_path, p_path, p_for_type, ret)) {
  50. return ret;
  51. }
  52. String extension = p_path.get_extension();
  53. List<String> extensions;
  54. if (p_for_type.is_empty()) {
  55. get_recognized_extensions(&extensions);
  56. } else {
  57. get_recognized_extensions_for_type(p_for_type, &extensions);
  58. }
  59. for (const String &E : extensions) {
  60. if (E.nocasecmp_to(extension) == 0) {
  61. return true;
  62. }
  63. }
  64. return false;
  65. }
  66. bool ResourceFormatLoader::handles_type(const String &p_type) const {
  67. bool success = false;
  68. GDVIRTUAL_CALL(_handles_type, p_type, success);
  69. return success;
  70. }
  71. void ResourceFormatLoader::get_classes_used(const String &p_path, HashSet<StringName> *r_classes) {
  72. Vector<String> ret;
  73. if (GDVIRTUAL_CALL(_get_classes_used, p_path, ret)) {
  74. for (int i = 0; i < ret.size(); i++) {
  75. r_classes->insert(ret[i]);
  76. }
  77. return;
  78. }
  79. String res = get_resource_type(p_path);
  80. if (!res.is_empty()) {
  81. r_classes->insert(res);
  82. }
  83. }
  84. String ResourceFormatLoader::get_resource_type(const String &p_path) const {
  85. String ret;
  86. GDVIRTUAL_CALL(_get_resource_type, p_path, ret);
  87. return ret;
  88. }
  89. String ResourceFormatLoader::get_resource_script_class(const String &p_path) const {
  90. String ret;
  91. GDVIRTUAL_CALL(_get_resource_script_class, p_path, ret);
  92. return ret;
  93. }
  94. ResourceUID::ID ResourceFormatLoader::get_resource_uid(const String &p_path) const {
  95. int64_t uid = ResourceUID::INVALID_ID;
  96. GDVIRTUAL_CALL(_get_resource_uid, p_path, uid);
  97. return uid;
  98. }
  99. void ResourceFormatLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
  100. if (p_type.is_empty() || handles_type(p_type)) {
  101. get_recognized_extensions(p_extensions);
  102. }
  103. }
  104. void ResourceLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) {
  105. for (int i = 0; i < loader_count; i++) {
  106. loader[i]->get_recognized_extensions_for_type(p_type, p_extensions);
  107. }
  108. }
  109. bool ResourceFormatLoader::exists(const String &p_path) const {
  110. bool success = false;
  111. if (GDVIRTUAL_CALL(_exists, p_path, success)) {
  112. return success;
  113. }
  114. return FileAccess::exists(p_path); // By default just check file.
  115. }
  116. void ResourceFormatLoader::get_recognized_extensions(List<String> *p_extensions) const {
  117. PackedStringArray exts;
  118. if (GDVIRTUAL_CALL(_get_recognized_extensions, exts)) {
  119. const String *r = exts.ptr();
  120. for (int i = 0; i < exts.size(); ++i) {
  121. p_extensions->push_back(r[i]);
  122. }
  123. }
  124. }
  125. Ref<Resource> ResourceFormatLoader::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) {
  126. Variant res;
  127. if (GDVIRTUAL_CALL(_load, p_path, p_original_path, p_use_sub_threads, p_cache_mode, res)) {
  128. if (res.get_type() == Variant::INT) { // Error code, abort.
  129. if (r_error) {
  130. *r_error = (Error)res.operator int64_t();
  131. }
  132. return Ref<Resource>();
  133. } else { // Success, pass on result.
  134. if (r_error) {
  135. *r_error = OK;
  136. }
  137. return res;
  138. }
  139. }
  140. ERR_FAIL_V_MSG(Ref<Resource>(), "Failed to load resource '" + p_path + "'. ResourceFormatLoader::load was not implemented for this resource type.");
  141. }
  142. void ResourceFormatLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  143. PackedStringArray deps;
  144. if (GDVIRTUAL_CALL(_get_dependencies, p_path, p_add_types, deps)) {
  145. const String *r = deps.ptr();
  146. for (int i = 0; i < deps.size(); ++i) {
  147. p_dependencies->push_back(r[i]);
  148. }
  149. }
  150. }
  151. Error ResourceFormatLoader::rename_dependencies(const String &p_path, const HashMap<String, String> &p_map) {
  152. Dictionary deps_dict;
  153. for (KeyValue<String, String> E : p_map) {
  154. deps_dict[E.key] = E.value;
  155. }
  156. Error err = OK;
  157. GDVIRTUAL_CALL(_rename_dependencies, p_path, deps_dict, err);
  158. return err;
  159. }
  160. void ResourceFormatLoader::_bind_methods() {
  161. BIND_ENUM_CONSTANT(CACHE_MODE_IGNORE);
  162. BIND_ENUM_CONSTANT(CACHE_MODE_REUSE);
  163. BIND_ENUM_CONSTANT(CACHE_MODE_REPLACE);
  164. GDVIRTUAL_BIND(_get_recognized_extensions);
  165. GDVIRTUAL_BIND(_recognize_path, "path", "type");
  166. GDVIRTUAL_BIND(_handles_type, "type");
  167. GDVIRTUAL_BIND(_get_resource_type, "path");
  168. GDVIRTUAL_BIND(_get_resource_script_class, "path");
  169. GDVIRTUAL_BIND(_get_resource_uid, "path");
  170. GDVIRTUAL_BIND(_get_dependencies, "path", "add_types");
  171. GDVIRTUAL_BIND(_rename_dependencies, "path", "renames");
  172. GDVIRTUAL_BIND(_exists, "path");
  173. GDVIRTUAL_BIND(_get_classes_used, "path");
  174. GDVIRTUAL_BIND(_load, "path", "original_path", "use_sub_threads", "cache_mode");
  175. }
  176. ///////////////////////////////////
  177. // This should be robust enough to be called redundantly without issues.
  178. void ResourceLoader::LoadToken::clear() {
  179. thread_load_mutex.lock();
  180. WorkerThreadPool::TaskID task_to_await = 0;
  181. if (!local_path.is_empty()) { // Empty is used for the special case where the load task is not registered.
  182. DEV_ASSERT(thread_load_tasks.has(local_path));
  183. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  184. if (!load_task.awaited) {
  185. task_to_await = load_task.task_id;
  186. load_task.awaited = true;
  187. }
  188. thread_load_tasks.erase(local_path);
  189. local_path.clear();
  190. }
  191. if (!user_path.is_empty()) {
  192. DEV_ASSERT(user_load_tokens.has(user_path));
  193. user_load_tokens.erase(user_path);
  194. user_path.clear();
  195. }
  196. thread_load_mutex.unlock();
  197. // If task is unused, await it here, locally, now the token data is consistent.
  198. if (task_to_await) {
  199. WorkerThreadPool::get_singleton()->wait_for_task_completion(task_to_await);
  200. }
  201. }
  202. ResourceLoader::LoadToken::~LoadToken() {
  203. clear();
  204. }
  205. Ref<Resource> ResourceLoader::_load(const String &p_path, const String &p_original_path, const String &p_type_hint, ResourceFormatLoader::CacheMode p_cache_mode, Error *r_error, bool p_use_sub_threads, float *r_progress) {
  206. load_nesting++;
  207. if (load_paths_stack->size()) {
  208. thread_load_mutex.lock();
  209. HashMap<String, ThreadLoadTask>::Iterator E = thread_load_tasks.find(load_paths_stack->get(load_paths_stack->size() - 1));
  210. if (E) {
  211. E->value.sub_tasks.insert(p_path);
  212. }
  213. thread_load_mutex.unlock();
  214. }
  215. load_paths_stack->push_back(p_path);
  216. // Try all loaders and pick the first match for the type hint
  217. bool found = false;
  218. Ref<Resource> res;
  219. for (int i = 0; i < loader_count; i++) {
  220. if (!loader[i]->recognize_path(p_path, p_type_hint)) {
  221. continue;
  222. }
  223. found = true;
  224. res = loader[i]->load(p_path, !p_original_path.is_empty() ? p_original_path : p_path, r_error, p_use_sub_threads, r_progress, p_cache_mode);
  225. if (!res.is_null()) {
  226. break;
  227. }
  228. }
  229. load_paths_stack->resize(load_paths_stack->size() - 1);
  230. load_nesting--;
  231. if (!res.is_null()) {
  232. return res;
  233. }
  234. ERR_FAIL_COND_V_MSG(found, Ref<Resource>(),
  235. vformat("Failed loading resource: %s. Make sure resources have been imported by opening the project in the editor at least once.", p_path));
  236. #ifdef TOOLS_ENABLED
  237. Ref<FileAccess> file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);
  238. ERR_FAIL_COND_V_MSG(!file_check->file_exists(p_path), Ref<Resource>(), vformat("Resource file not found: %s (expected type: %s)", p_path, p_type_hint));
  239. #endif
  240. ERR_FAIL_V_MSG(Ref<Resource>(), vformat("No loader found for resource: %s (expected type: %s)", p_path, p_type_hint));
  241. }
  242. void ResourceLoader::_thread_load_function(void *p_userdata) {
  243. ThreadLoadTask &load_task = *(ThreadLoadTask *)p_userdata;
  244. thread_load_mutex.lock();
  245. caller_task_id = load_task.task_id;
  246. if (cleaning_tasks) {
  247. load_task.status = THREAD_LOAD_FAILED;
  248. thread_load_mutex.unlock();
  249. return;
  250. }
  251. thread_load_mutex.unlock();
  252. // Thread-safe either if it's the current thread or a brand new one.
  253. CallQueue *mq_override = nullptr;
  254. if (load_nesting == 0) {
  255. load_paths_stack = memnew(Vector<String>);
  256. if (!load_task.dependent_path.is_empty()) {
  257. load_paths_stack->push_back(load_task.dependent_path);
  258. }
  259. if (!Thread::is_main_thread()) {
  260. mq_override = memnew(CallQueue);
  261. MessageQueue::set_thread_singleton_override(mq_override);
  262. set_current_thread_safe_for_nodes(true);
  263. }
  264. } else {
  265. DEV_ASSERT(load_task.dependent_path.is_empty());
  266. }
  267. // --
  268. if (!Thread::is_main_thread()) {
  269. set_current_thread_safe_for_nodes(true);
  270. }
  271. Ref<Resource> res = _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);
  272. if (mq_override) {
  273. mq_override->flush();
  274. }
  275. thread_load_mutex.lock();
  276. load_task.resource = res;
  277. load_task.progress = 1.0; //it was fully loaded at this point, so force progress to 1.0
  278. if (load_task.error != OK) {
  279. load_task.status = THREAD_LOAD_FAILED;
  280. } else {
  281. load_task.status = THREAD_LOAD_LOADED;
  282. }
  283. if (load_task.cond_var) {
  284. load_task.cond_var->notify_all();
  285. memdelete(load_task.cond_var);
  286. load_task.cond_var = nullptr;
  287. }
  288. if (load_task.resource.is_valid()) {
  289. if (load_task.cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
  290. load_task.resource->set_path(load_task.local_path);
  291. }
  292. if (load_task.xl_remapped) {
  293. load_task.resource->set_as_translation_remapped(true);
  294. }
  295. #ifdef TOOLS_ENABLED
  296. load_task.resource->set_edited(false);
  297. if (timestamp_on_load) {
  298. uint64_t mt = FileAccess::get_modified_time(load_task.remapped_path);
  299. //printf("mt %s: %lli\n",remapped_path.utf8().get_data(),mt);
  300. load_task.resource->set_last_modified_time(mt);
  301. }
  302. #endif
  303. if (_loaded_callback) {
  304. _loaded_callback(load_task.resource, load_task.local_path);
  305. }
  306. }
  307. thread_load_mutex.unlock();
  308. if (load_nesting == 0) {
  309. if (mq_override) {
  310. memdelete(mq_override);
  311. }
  312. memdelete(load_paths_stack);
  313. }
  314. }
  315. static String _validate_local_path(const String &p_path) {
  316. ResourceUID::ID uid = ResourceUID::get_singleton()->text_to_id(p_path);
  317. if (uid != ResourceUID::INVALID_ID) {
  318. return ResourceUID::get_singleton()->get_id_path(uid);
  319. } else if (p_path.is_relative_path()) {
  320. return "res://" + p_path;
  321. } else {
  322. return ProjectSettings::get_singleton()->localize_path(p_path);
  323. }
  324. }
  325. Error ResourceLoader::load_threaded_request(const String &p_path, const String &p_type_hint, bool p_use_sub_threads, ResourceFormatLoader::CacheMode p_cache_mode) {
  326. thread_load_mutex.lock();
  327. if (user_load_tokens.has(p_path)) {
  328. print_verbose("load_threaded_request(): Another threaded load for resource path '" + p_path + "' has been initiated. Not an error.");
  329. user_load_tokens[p_path]->reference(); // Additional request.
  330. thread_load_mutex.unlock();
  331. return OK;
  332. }
  333. user_load_tokens[p_path] = nullptr;
  334. thread_load_mutex.unlock();
  335. Ref<ResourceLoader::LoadToken> token = _load_start(p_path, p_type_hint, p_use_sub_threads ? LOAD_THREAD_DISTRIBUTE : LOAD_THREAD_SPAWN_SINGLE, p_cache_mode);
  336. if (token.is_valid()) {
  337. thread_load_mutex.lock();
  338. token->user_path = p_path;
  339. token->reference(); // First request.
  340. user_load_tokens[p_path] = token.ptr();
  341. print_lt("REQUEST: user load tokens: " + itos(user_load_tokens.size()));
  342. thread_load_mutex.unlock();
  343. return OK;
  344. } else {
  345. return FAILED;
  346. }
  347. }
  348. Ref<Resource> ResourceLoader::load(const String &p_path, const String &p_type_hint, ResourceFormatLoader::CacheMode p_cache_mode, Error *r_error) {
  349. if (r_error) {
  350. *r_error = OK;
  351. }
  352. Ref<LoadToken> load_token = _load_start(p_path, p_type_hint, LOAD_THREAD_FROM_CURRENT, p_cache_mode);
  353. if (!load_token.is_valid()) {
  354. if (r_error) {
  355. *r_error = FAILED;
  356. }
  357. return Ref<Resource>();
  358. }
  359. Ref<Resource> res = _load_complete(*load_token.ptr(), r_error);
  360. return res;
  361. }
  362. Ref<ResourceLoader::LoadToken> ResourceLoader::_load_start(const String &p_path, const String &p_type_hint, LoadThreadMode p_thread_mode, ResourceFormatLoader::CacheMode p_cache_mode) {
  363. String local_path = _validate_local_path(p_path);
  364. Ref<LoadToken> load_token;
  365. bool must_not_register = false;
  366. ThreadLoadTask unregistered_load_task; // Once set, must be valid up to the call to do the load.
  367. ThreadLoadTask *load_task_ptr = nullptr;
  368. bool run_on_current_thread = false;
  369. {
  370. MutexLock thread_load_lock(thread_load_mutex);
  371. if (thread_load_tasks.has(local_path)) {
  372. load_token = Ref<LoadToken>(thread_load_tasks[local_path].load_token);
  373. if (!load_token.is_valid()) {
  374. // The token is dying (reached 0 on another thread).
  375. // Ensure it's killed now so the path can be safely reused right away.
  376. thread_load_tasks[local_path].load_token->clear();
  377. } else {
  378. if (p_cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
  379. return load_token;
  380. }
  381. }
  382. }
  383. load_token.instantiate();
  384. load_token->local_path = local_path;
  385. //create load task
  386. {
  387. ThreadLoadTask load_task;
  388. load_task.remapped_path = _path_remap(local_path, &load_task.xl_remapped);
  389. load_task.load_token = load_token.ptr();
  390. load_task.local_path = local_path;
  391. load_task.type_hint = p_type_hint;
  392. load_task.cache_mode = p_cache_mode;
  393. load_task.use_sub_threads = p_thread_mode == LOAD_THREAD_DISTRIBUTE;
  394. if (p_cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
  395. Ref<Resource> existing = ResourceCache::get_ref(local_path);
  396. if (existing.is_valid()) {
  397. //referencing is fine
  398. load_task.resource = existing;
  399. load_task.status = THREAD_LOAD_LOADED;
  400. load_task.progress = 1.0;
  401. thread_load_tasks[local_path] = load_task;
  402. return load_token;
  403. }
  404. }
  405. // If we want to ignore cache, but there's another task loading it, we can't add this one to the map and we also have to finish unconditionally synchronously.
  406. must_not_register = thread_load_tasks.has(local_path) && p_cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE;
  407. if (must_not_register) {
  408. load_token->local_path.clear();
  409. unregistered_load_task = load_task;
  410. } else {
  411. thread_load_tasks[local_path] = load_task;
  412. }
  413. load_task_ptr = must_not_register ? &unregistered_load_task : &thread_load_tasks[local_path];
  414. }
  415. run_on_current_thread = must_not_register || p_thread_mode == LOAD_THREAD_FROM_CURRENT;
  416. if (run_on_current_thread) {
  417. load_task_ptr->thread_id = Thread::get_caller_id();
  418. } else {
  419. load_task_ptr->task_id = WorkerThreadPool::get_singleton()->add_native_task(&ResourceLoader::_thread_load_function, load_task_ptr);
  420. }
  421. }
  422. if (run_on_current_thread) {
  423. _thread_load_function(load_task_ptr);
  424. if (must_not_register) {
  425. load_token->res_if_unregistered = load_task_ptr->resource;
  426. }
  427. }
  428. return load_token;
  429. }
  430. float ResourceLoader::_dependency_get_progress(const String &p_path) {
  431. if (thread_load_tasks.has(p_path)) {
  432. ThreadLoadTask &load_task = thread_load_tasks[p_path];
  433. int dep_count = load_task.sub_tasks.size();
  434. if (dep_count > 0) {
  435. float dep_progress = 0;
  436. for (const String &E : load_task.sub_tasks) {
  437. dep_progress += _dependency_get_progress(E);
  438. }
  439. dep_progress /= float(dep_count);
  440. dep_progress *= 0.5;
  441. dep_progress += load_task.progress * 0.5;
  442. return dep_progress;
  443. } else {
  444. return load_task.progress;
  445. }
  446. } else {
  447. return 1.0; //assume finished loading it so it no longer exists
  448. }
  449. }
  450. ResourceLoader::ThreadLoadStatus ResourceLoader::load_threaded_get_status(const String &p_path, float *r_progress) {
  451. MutexLock thread_load_lock(thread_load_mutex);
  452. if (!user_load_tokens.has(p_path)) {
  453. print_verbose("load_threaded_get_status(): No threaded load for resource path '" + p_path + "' has been initiated or its result has already been collected.");
  454. return THREAD_LOAD_INVALID_RESOURCE;
  455. }
  456. String local_path = _validate_local_path(p_path);
  457. if (!thread_load_tasks.has(local_path)) {
  458. #ifdef DEV_ENABLED
  459. CRASH_NOW();
  460. #endif
  461. // On non-dev, be defensive and at least avoid crashing (at this point at least).
  462. return THREAD_LOAD_INVALID_RESOURCE;
  463. }
  464. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  465. ThreadLoadStatus status;
  466. status = load_task.status;
  467. if (r_progress) {
  468. *r_progress = _dependency_get_progress(local_path);
  469. }
  470. return status;
  471. }
  472. Ref<Resource> ResourceLoader::load_threaded_get(const String &p_path, Error *r_error) {
  473. if (r_error) {
  474. *r_error = OK;
  475. }
  476. Ref<Resource> res;
  477. {
  478. MutexLock thread_load_lock(thread_load_mutex);
  479. if (!user_load_tokens.has(p_path)) {
  480. print_verbose("load_threaded_get(): No threaded load for resource path '" + p_path + "' has been initiated or its result has already been collected.");
  481. if (r_error) {
  482. *r_error = ERR_INVALID_PARAMETER;
  483. }
  484. return Ref<Resource>();
  485. }
  486. LoadToken *load_token = user_load_tokens[p_path];
  487. if (!load_token) {
  488. // This happens if requested from one thread and rapidly querying from another.
  489. if (r_error) {
  490. *r_error = ERR_BUSY;
  491. }
  492. return Ref<Resource>();
  493. }
  494. res = _load_complete_inner(*load_token, r_error, thread_load_lock);
  495. if (load_token->unreference()) {
  496. memdelete(load_token);
  497. }
  498. }
  499. print_lt("GET: user load tokens: " + itos(user_load_tokens.size()));
  500. return res;
  501. }
  502. Ref<Resource> ResourceLoader::_load_complete(LoadToken &p_load_token, Error *r_error) {
  503. MutexLock thread_load_lock(thread_load_mutex);
  504. return _load_complete_inner(p_load_token, r_error, thread_load_lock);
  505. }
  506. Ref<Resource> ResourceLoader::_load_complete_inner(LoadToken &p_load_token, Error *r_error, MutexLock<SafeBinaryMutex<BINARY_MUTEX_TAG>> &p_thread_load_lock) {
  507. if (r_error) {
  508. *r_error = OK;
  509. }
  510. if (!p_load_token.local_path.is_empty()) {
  511. if (!thread_load_tasks.has(p_load_token.local_path)) {
  512. #ifdef DEV_ENABLED
  513. CRASH_NOW();
  514. #endif
  515. // On non-dev, be defensive and at least avoid crashing (at this point at least).
  516. if (r_error) {
  517. *r_error = ERR_BUG;
  518. }
  519. return Ref<Resource>();
  520. }
  521. ThreadLoadTask &load_task = thread_load_tasks[p_load_token.local_path];
  522. if (load_task.status == THREAD_LOAD_IN_PROGRESS) {
  523. DEV_ASSERT((load_task.task_id == 0) != (load_task.thread_id == 0));
  524. if ((load_task.task_id != 0 && load_task.task_id == caller_task_id) ||
  525. (load_task.thread_id != 0 && load_task.thread_id == Thread::get_caller_id())) {
  526. // Load is in progress, but it's precisely this thread the one in charge.
  527. // That means this is a cyclic load.
  528. if (r_error) {
  529. *r_error = ERR_BUSY;
  530. }
  531. return Ref<Resource>();
  532. }
  533. if (load_task.task_id != 0) {
  534. // Loading thread is in the worker pool.
  535. load_task.awaited = true;
  536. thread_load_mutex.unlock();
  537. Error err = WorkerThreadPool::get_singleton()->wait_for_task_completion(load_task.task_id);
  538. if (err == ERR_BUSY) {
  539. // The WorkerThreadPool has scheduled tasks in a way that the current load depends on
  540. // another one in a lower stack frame. Restart such load here. When the stack is eventually
  541. // unrolled, the original load will have been notified to go on.
  542. #ifdef DEV_ENABLED
  543. print_verbose("ResourceLoader: Load task happened to wait on another one deep in the call stack. Attempting to avoid deadlock by re-issuing the load now.");
  544. #endif
  545. // CACHE_MODE_IGNORE is needed because, otherwise, the new request would just see there's
  546. // an ongoing load for that resource and wait for it again. This value forces a new load.
  547. Ref<ResourceLoader::LoadToken> token = _load_start(load_task.local_path, load_task.type_hint, LOAD_THREAD_DISTRIBUTE, ResourceFormatLoader::CACHE_MODE_IGNORE);
  548. Ref<Resource> resource = _load_complete(*token.ptr(), &err);
  549. if (r_error) {
  550. *r_error = err;
  551. }
  552. thread_load_mutex.lock();
  553. return resource;
  554. } else {
  555. DEV_ASSERT(err == OK);
  556. thread_load_mutex.lock();
  557. }
  558. } else {
  559. // Loading thread is main or user thread.
  560. if (!load_task.cond_var) {
  561. load_task.cond_var = memnew(ConditionVariable);
  562. }
  563. do {
  564. load_task.cond_var->wait(p_thread_load_lock);
  565. DEV_ASSERT(thread_load_tasks.has(p_load_token.local_path) && p_load_token.get_reference_count());
  566. } while (load_task.cond_var);
  567. }
  568. }
  569. if (cleaning_tasks) {
  570. load_task.resource = Ref<Resource>();
  571. load_task.error = FAILED;
  572. }
  573. Ref<Resource> resource = load_task.resource;
  574. if (r_error) {
  575. *r_error = load_task.error;
  576. }
  577. return resource;
  578. } else {
  579. // Special case of an unregistered task.
  580. // The resource should have been loaded by now.
  581. Ref<Resource> resource = p_load_token.res_if_unregistered;
  582. if (!resource.is_valid()) {
  583. if (r_error) {
  584. *r_error = FAILED;
  585. }
  586. }
  587. return resource;
  588. }
  589. }
  590. bool ResourceLoader::exists(const String &p_path, const String &p_type_hint) {
  591. String local_path = _validate_local_path(p_path);
  592. if (ResourceCache::has(local_path)) {
  593. return true; // If cached, it probably exists
  594. }
  595. bool xl_remapped = false;
  596. String path = _path_remap(local_path, &xl_remapped);
  597. // Try all loaders and pick the first match for the type hint
  598. for (int i = 0; i < loader_count; i++) {
  599. if (!loader[i]->recognize_path(path, p_type_hint)) {
  600. continue;
  601. }
  602. if (loader[i]->exists(path)) {
  603. return true;
  604. }
  605. }
  606. return false;
  607. }
  608. void ResourceLoader::add_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader, bool p_at_front) {
  609. ERR_FAIL_COND(p_format_loader.is_null());
  610. ERR_FAIL_COND(loader_count >= MAX_LOADERS);
  611. if (p_at_front) {
  612. for (int i = loader_count; i > 0; i--) {
  613. loader[i] = loader[i - 1];
  614. }
  615. loader[0] = p_format_loader;
  616. loader_count++;
  617. } else {
  618. loader[loader_count++] = p_format_loader;
  619. }
  620. }
  621. void ResourceLoader::remove_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader) {
  622. ERR_FAIL_COND(p_format_loader.is_null());
  623. // Find loader
  624. int i = 0;
  625. for (; i < loader_count; ++i) {
  626. if (loader[i] == p_format_loader) {
  627. break;
  628. }
  629. }
  630. ERR_FAIL_COND(i >= loader_count); // Not found
  631. // Shift next loaders up
  632. for (; i < loader_count - 1; ++i) {
  633. loader[i] = loader[i + 1];
  634. }
  635. loader[loader_count - 1].unref();
  636. --loader_count;
  637. }
  638. int ResourceLoader::get_import_order(const String &p_path) {
  639. String local_path = _path_remap(_validate_local_path(p_path));
  640. for (int i = 0; i < loader_count; i++) {
  641. if (!loader[i]->recognize_path(local_path)) {
  642. continue;
  643. }
  644. return loader[i]->get_import_order(p_path);
  645. }
  646. return 0;
  647. }
  648. String ResourceLoader::get_import_group_file(const String &p_path) {
  649. String local_path = _path_remap(_validate_local_path(p_path));
  650. for (int i = 0; i < loader_count; i++) {
  651. if (!loader[i]->recognize_path(local_path)) {
  652. continue;
  653. }
  654. return loader[i]->get_import_group_file(p_path);
  655. }
  656. return String(); //not found
  657. }
  658. bool ResourceLoader::is_import_valid(const String &p_path) {
  659. String local_path = _path_remap(_validate_local_path(p_path));
  660. for (int i = 0; i < loader_count; i++) {
  661. if (!loader[i]->recognize_path(local_path)) {
  662. continue;
  663. }
  664. return loader[i]->is_import_valid(p_path);
  665. }
  666. return false; //not found
  667. }
  668. bool ResourceLoader::is_imported(const String &p_path) {
  669. String local_path = _path_remap(_validate_local_path(p_path));
  670. for (int i = 0; i < loader_count; i++) {
  671. if (!loader[i]->recognize_path(local_path)) {
  672. continue;
  673. }
  674. return loader[i]->is_imported(p_path);
  675. }
  676. return false; //not found
  677. }
  678. void ResourceLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  679. String local_path = _path_remap(_validate_local_path(p_path));
  680. for (int i = 0; i < loader_count; i++) {
  681. if (!loader[i]->recognize_path(local_path)) {
  682. continue;
  683. }
  684. loader[i]->get_dependencies(local_path, p_dependencies, p_add_types);
  685. }
  686. }
  687. Error ResourceLoader::rename_dependencies(const String &p_path, const HashMap<String, String> &p_map) {
  688. String local_path = _path_remap(_validate_local_path(p_path));
  689. for (int i = 0; i < loader_count; i++) {
  690. if (!loader[i]->recognize_path(local_path)) {
  691. continue;
  692. }
  693. return loader[i]->rename_dependencies(local_path, p_map);
  694. }
  695. return OK; // ??
  696. }
  697. void ResourceLoader::get_classes_used(const String &p_path, HashSet<StringName> *r_classes) {
  698. String local_path = _validate_local_path(p_path);
  699. for (int i = 0; i < loader_count; i++) {
  700. if (!loader[i]->recognize_path(local_path)) {
  701. continue;
  702. }
  703. return loader[i]->get_classes_used(p_path, r_classes);
  704. }
  705. }
  706. String ResourceLoader::get_resource_type(const String &p_path) {
  707. String local_path = _validate_local_path(p_path);
  708. for (int i = 0; i < loader_count; i++) {
  709. String result = loader[i]->get_resource_type(local_path);
  710. if (!result.is_empty()) {
  711. return result;
  712. }
  713. }
  714. return "";
  715. }
  716. String ResourceLoader::get_resource_script_class(const String &p_path) {
  717. String local_path = _validate_local_path(p_path);
  718. for (int i = 0; i < loader_count; i++) {
  719. String result = loader[i]->get_resource_script_class(local_path);
  720. if (!result.is_empty()) {
  721. return result;
  722. }
  723. }
  724. return "";
  725. }
  726. ResourceUID::ID ResourceLoader::get_resource_uid(const String &p_path) {
  727. String local_path = _validate_local_path(p_path);
  728. for (int i = 0; i < loader_count; i++) {
  729. ResourceUID::ID id = loader[i]->get_resource_uid(local_path);
  730. if (id != ResourceUID::INVALID_ID) {
  731. return id;
  732. }
  733. }
  734. return ResourceUID::INVALID_ID;
  735. }
  736. String ResourceLoader::_path_remap(const String &p_path, bool *r_translation_remapped) {
  737. String new_path = p_path;
  738. if (translation_remaps.has(p_path)) {
  739. // translation_remaps has the following format:
  740. // { "res://path.png": PackedStringArray( "res://path-ru.png:ru", "res://path-de.png:de" ) }
  741. // To find the path of the remapped resource, we extract the locale name after
  742. // the last ':' to match the project locale.
  743. // An extra remap may still be necessary afterwards due to the text -> binary converter on export.
  744. String locale = TranslationServer::get_singleton()->get_locale();
  745. ERR_FAIL_COND_V_MSG(locale.length() < 2, p_path, "Could not remap path '" + p_path + "' for translation as configured locale '" + locale + "' is invalid.");
  746. Vector<String> &res_remaps = *translation_remaps.getptr(new_path);
  747. int best_score = 0;
  748. for (int i = 0; i < res_remaps.size(); i++) {
  749. int split = res_remaps[i].rfind(":");
  750. if (split == -1) {
  751. continue;
  752. }
  753. String l = res_remaps[i].substr(split + 1).strip_edges();
  754. int score = TranslationServer::get_singleton()->compare_locales(locale, l);
  755. if (score > 0 && score >= best_score) {
  756. new_path = res_remaps[i].left(split);
  757. best_score = score;
  758. if (score == 10) {
  759. break; // Exact match, skip the rest.
  760. }
  761. }
  762. }
  763. if (r_translation_remapped) {
  764. *r_translation_remapped = true;
  765. }
  766. // Fallback to p_path if new_path does not exist.
  767. if (!FileAccess::exists(new_path)) {
  768. WARN_PRINT(vformat("Translation remap '%s' does not exist. Falling back to '%s'.", new_path, p_path));
  769. new_path = p_path;
  770. }
  771. }
  772. if (path_remaps.has(new_path)) {
  773. new_path = path_remaps[new_path];
  774. } else {
  775. // Try file remap.
  776. Error err;
  777. Ref<FileAccess> f = FileAccess::open(new_path + ".remap", FileAccess::READ, &err);
  778. if (f.is_valid()) {
  779. VariantParser::StreamFile stream;
  780. stream.f = f;
  781. String assign;
  782. Variant value;
  783. VariantParser::Tag next_tag;
  784. int lines = 0;
  785. String error_text;
  786. while (true) {
  787. assign = Variant();
  788. next_tag.fields.clear();
  789. next_tag.name = String();
  790. err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
  791. if (err == ERR_FILE_EOF) {
  792. break;
  793. } else if (err != OK) {
  794. ERR_PRINT("Parse error: " + p_path + ".remap:" + itos(lines) + " error: " + error_text + ".");
  795. break;
  796. }
  797. if (assign == "path") {
  798. new_path = value;
  799. break;
  800. } else if (next_tag.name != "remap") {
  801. break;
  802. }
  803. }
  804. }
  805. }
  806. return new_path;
  807. }
  808. String ResourceLoader::import_remap(const String &p_path) {
  809. if (ResourceFormatImporter::get_singleton()->recognize_path(p_path)) {
  810. return ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_path);
  811. }
  812. return p_path;
  813. }
  814. String ResourceLoader::path_remap(const String &p_path) {
  815. return _path_remap(p_path);
  816. }
  817. void ResourceLoader::reload_translation_remaps() {
  818. ResourceCache::lock.lock();
  819. List<Resource *> to_reload;
  820. SelfList<Resource> *E = remapped_list.first();
  821. while (E) {
  822. to_reload.push_back(E->self());
  823. E = E->next();
  824. }
  825. ResourceCache::lock.unlock();
  826. //now just make sure to not delete any of these resources while changing locale..
  827. while (to_reload.front()) {
  828. to_reload.front()->get()->reload_from_file();
  829. to_reload.pop_front();
  830. }
  831. }
  832. void ResourceLoader::load_translation_remaps() {
  833. if (!ProjectSettings::get_singleton()->has_setting("internationalization/locale/translation_remaps")) {
  834. return;
  835. }
  836. Dictionary remaps = GLOBAL_GET("internationalization/locale/translation_remaps");
  837. List<Variant> keys;
  838. remaps.get_key_list(&keys);
  839. for (const Variant &E : keys) {
  840. Array langs = remaps[E];
  841. Vector<String> lang_remaps;
  842. lang_remaps.resize(langs.size());
  843. for (int i = 0; i < langs.size(); i++) {
  844. lang_remaps.write[i] = langs[i];
  845. }
  846. translation_remaps[String(E)] = lang_remaps;
  847. }
  848. }
  849. void ResourceLoader::clear_translation_remaps() {
  850. translation_remaps.clear();
  851. while (remapped_list.first() != nullptr) {
  852. remapped_list.remove(remapped_list.first());
  853. }
  854. }
  855. void ResourceLoader::clear_thread_load_tasks() {
  856. // Bring the thing down as quickly as possible without causing deadlocks or leaks.
  857. thread_load_mutex.lock();
  858. cleaning_tasks = true;
  859. while (true) {
  860. bool none_running = true;
  861. if (thread_load_tasks.size()) {
  862. for (KeyValue<String, ResourceLoader::ThreadLoadTask> &E : thread_load_tasks) {
  863. if (E.value.status == THREAD_LOAD_IN_PROGRESS) {
  864. if (E.value.cond_var) {
  865. E.value.cond_var->notify_all();
  866. memdelete(E.value.cond_var);
  867. E.value.cond_var = nullptr;
  868. }
  869. none_running = false;
  870. }
  871. }
  872. }
  873. if (none_running) {
  874. break;
  875. }
  876. thread_load_mutex.unlock();
  877. OS::get_singleton()->delay_usec(1000);
  878. thread_load_mutex.lock();
  879. }
  880. for (KeyValue<String, LoadToken *> &E : user_load_tokens) {
  881. memdelete(E.value);
  882. }
  883. user_load_tokens.clear();
  884. thread_load_tasks.clear();
  885. cleaning_tasks = false;
  886. thread_load_mutex.unlock();
  887. }
  888. void ResourceLoader::load_path_remaps() {
  889. if (!ProjectSettings::get_singleton()->has_setting("path_remap/remapped_paths")) {
  890. return;
  891. }
  892. Vector<String> remaps = GLOBAL_GET("path_remap/remapped_paths");
  893. int rc = remaps.size();
  894. ERR_FAIL_COND(rc & 1); //must be even
  895. const String *r = remaps.ptr();
  896. for (int i = 0; i < rc; i += 2) {
  897. path_remaps[r[i]] = r[i + 1];
  898. }
  899. }
  900. void ResourceLoader::clear_path_remaps() {
  901. path_remaps.clear();
  902. }
  903. void ResourceLoader::set_load_callback(ResourceLoadedCallback p_callback) {
  904. _loaded_callback = p_callback;
  905. }
  906. ResourceLoadedCallback ResourceLoader::_loaded_callback = nullptr;
  907. Ref<ResourceFormatLoader> ResourceLoader::_find_custom_resource_format_loader(String path) {
  908. for (int i = 0; i < loader_count; ++i) {
  909. if (loader[i]->get_script_instance() && loader[i]->get_script_instance()->get_script()->get_path() == path) {
  910. return loader[i];
  911. }
  912. }
  913. return Ref<ResourceFormatLoader>();
  914. }
  915. bool ResourceLoader::add_custom_resource_format_loader(String script_path) {
  916. if (_find_custom_resource_format_loader(script_path).is_valid()) {
  917. return false;
  918. }
  919. Ref<Resource> res = ResourceLoader::load(script_path);
  920. ERR_FAIL_COND_V(res.is_null(), false);
  921. ERR_FAIL_COND_V(!res->is_class("Script"), false);
  922. Ref<Script> s = res;
  923. StringName ibt = s->get_instance_base_type();
  924. bool valid_type = ClassDB::is_parent_class(ibt, "ResourceFormatLoader");
  925. ERR_FAIL_COND_V_MSG(!valid_type, false, "Script does not inherit a CustomResourceLoader: " + script_path + ".");
  926. Object *obj = ClassDB::instantiate(ibt);
  927. ERR_FAIL_NULL_V_MSG(obj, false, "Cannot instance script as custom resource loader, expected 'ResourceFormatLoader' inheritance, got: " + String(ibt) + ".");
  928. Ref<ResourceFormatLoader> crl = Object::cast_to<ResourceFormatLoader>(obj);
  929. crl->set_script(s);
  930. ResourceLoader::add_resource_format_loader(crl);
  931. return true;
  932. }
  933. void ResourceLoader::set_create_missing_resources_if_class_unavailable(bool p_enable) {
  934. create_missing_resources_if_class_unavailable = p_enable;
  935. }
  936. void ResourceLoader::add_custom_loaders() {
  937. // Custom loaders registration exploits global class names
  938. String custom_loader_base_class = ResourceFormatLoader::get_class_static();
  939. List<StringName> global_classes;
  940. ScriptServer::get_global_class_list(&global_classes);
  941. for (const StringName &class_name : global_classes) {
  942. StringName base_class = ScriptServer::get_global_class_native_base(class_name);
  943. if (base_class == custom_loader_base_class) {
  944. String path = ScriptServer::get_global_class_path(class_name);
  945. add_custom_resource_format_loader(path);
  946. }
  947. }
  948. }
  949. void ResourceLoader::remove_custom_loaders() {
  950. Vector<Ref<ResourceFormatLoader>> custom_loaders;
  951. for (int i = 0; i < loader_count; ++i) {
  952. if (loader[i]->get_script_instance()) {
  953. custom_loaders.push_back(loader[i]);
  954. }
  955. }
  956. for (int i = 0; i < custom_loaders.size(); ++i) {
  957. remove_resource_format_loader(custom_loaders[i]);
  958. }
  959. }
  960. bool ResourceLoader::is_cleaning_tasks() {
  961. MutexLock lock(thread_load_mutex);
  962. return cleaning_tasks;
  963. }
  964. void ResourceLoader::initialize() {}
  965. void ResourceLoader::finalize() {}
  966. ResourceLoadErrorNotify ResourceLoader::err_notify = nullptr;
  967. DependencyErrorNotify ResourceLoader::dep_err_notify = nullptr;
  968. bool ResourceLoader::create_missing_resources_if_class_unavailable = false;
  969. bool ResourceLoader::abort_on_missing_resource = true;
  970. bool ResourceLoader::timestamp_on_load = false;
  971. thread_local int ResourceLoader::load_nesting = 0;
  972. thread_local WorkerThreadPool::TaskID ResourceLoader::caller_task_id = 0;
  973. thread_local Vector<String> *ResourceLoader::load_paths_stack;
  974. template <>
  975. thread_local uint32_t SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG>::count = 0;
  976. SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG> ResourceLoader::thread_load_mutex;
  977. HashMap<String, ResourceLoader::ThreadLoadTask> ResourceLoader::thread_load_tasks;
  978. bool ResourceLoader::cleaning_tasks = false;
  979. HashMap<String, ResourceLoader::LoadToken *> ResourceLoader::user_load_tokens;
  980. SelfList<Resource>::List ResourceLoader::remapped_list;
  981. HashMap<String, Vector<String>> ResourceLoader::translation_remaps;
  982. HashMap<String, String> ResourceLoader::path_remaps;
  983. ResourceLoaderImport ResourceLoader::import = nullptr;