resource_loader.cpp 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589
  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/core_bind.h"
  33. #include "core/io/dir_access.h"
  34. #include "core/io/file_access.h"
  35. #include "core/io/resource_importer.h"
  36. #include "core/object/script_language.h"
  37. #include "core/os/condition_variable.h"
  38. #include "core/os/os.h"
  39. #include "core/os/safe_binary_mutex.h"
  40. #include "core/string/print_string.h"
  41. #include "core/string/translation_server.h"
  42. #include "core/templates/rb_set.h"
  43. #include "core/variant/variant_parser.h"
  44. #include "servers/rendering_server.h"
  45. #ifdef DEBUG_LOAD_THREADED
  46. #define print_lt(m_text) print_line(m_text)
  47. #else
  48. #define print_lt(m_text)
  49. #endif
  50. Ref<ResourceFormatLoader> ResourceLoader::loader[ResourceLoader::MAX_LOADERS];
  51. int ResourceLoader::loader_count = 0;
  52. bool ResourceFormatLoader::recognize_path(const String &p_path, const String &p_for_type) const {
  53. bool ret = false;
  54. if (GDVIRTUAL_CALL(_recognize_path, p_path, p_for_type, ret)) {
  55. return ret;
  56. }
  57. String extension = p_path.get_extension();
  58. List<String> extensions;
  59. if (p_for_type.is_empty()) {
  60. get_recognized_extensions(&extensions);
  61. } else {
  62. get_recognized_extensions_for_type(p_for_type, &extensions);
  63. }
  64. for (const String &E : extensions) {
  65. if (E.nocasecmp_to(extension) == 0) {
  66. return true;
  67. }
  68. }
  69. return false;
  70. }
  71. bool ResourceFormatLoader::handles_type(const String &p_type) const {
  72. bool success = false;
  73. GDVIRTUAL_CALL(_handles_type, p_type, success);
  74. return success;
  75. }
  76. void ResourceFormatLoader::get_classes_used(const String &p_path, HashSet<StringName> *r_classes) {
  77. Vector<String> ret;
  78. if (GDVIRTUAL_CALL(_get_classes_used, p_path, ret)) {
  79. for (int i = 0; i < ret.size(); i++) {
  80. r_classes->insert(ret[i]);
  81. }
  82. return;
  83. }
  84. String res = get_resource_type(p_path);
  85. if (!res.is_empty()) {
  86. r_classes->insert(res);
  87. }
  88. }
  89. String ResourceFormatLoader::get_resource_type(const String &p_path) const {
  90. String ret;
  91. GDVIRTUAL_CALL(_get_resource_type, p_path, ret);
  92. return ret;
  93. }
  94. String ResourceFormatLoader::get_resource_script_class(const String &p_path) const {
  95. String ret;
  96. GDVIRTUAL_CALL(_get_resource_script_class, p_path, ret);
  97. return ret;
  98. }
  99. ResourceUID::ID ResourceFormatLoader::get_resource_uid(const String &p_path) const {
  100. int64_t uid = ResourceUID::INVALID_ID;
  101. if (has_custom_uid_support()) {
  102. GDVIRTUAL_CALL(_get_resource_uid, p_path, uid);
  103. } else {
  104. Ref<FileAccess> file = FileAccess::open(p_path + ".uid", FileAccess::READ);
  105. if (file.is_valid()) {
  106. uid = ResourceUID::get_singleton()->text_to_id(file->get_line());
  107. }
  108. }
  109. return uid;
  110. }
  111. bool ResourceFormatLoader::has_custom_uid_support() const {
  112. return GDVIRTUAL_IS_OVERRIDDEN(_get_resource_uid);
  113. }
  114. void ResourceFormatLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
  115. if (p_type.is_empty() || handles_type(p_type)) {
  116. get_recognized_extensions(p_extensions);
  117. }
  118. }
  119. void ResourceLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) {
  120. for (int i = 0; i < loader_count; i++) {
  121. loader[i]->get_recognized_extensions_for_type(p_type, p_extensions);
  122. }
  123. }
  124. bool ResourceFormatLoader::exists(const String &p_path) const {
  125. bool success = false;
  126. if (GDVIRTUAL_CALL(_exists, p_path, success)) {
  127. return success;
  128. }
  129. return FileAccess::exists(p_path); // By default just check file.
  130. }
  131. void ResourceFormatLoader::get_recognized_extensions(List<String> *p_extensions) const {
  132. PackedStringArray exts;
  133. if (GDVIRTUAL_CALL(_get_recognized_extensions, exts)) {
  134. const String *r = exts.ptr();
  135. for (int i = 0; i < exts.size(); ++i) {
  136. p_extensions->push_back(r[i]);
  137. }
  138. }
  139. }
  140. 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) {
  141. Variant res;
  142. if (GDVIRTUAL_CALL(_load, p_path, p_original_path, p_use_sub_threads, p_cache_mode, res)) {
  143. if (res.get_type() == Variant::INT) { // Error code, abort.
  144. if (r_error) {
  145. *r_error = (Error)res.operator int64_t();
  146. }
  147. return Ref<Resource>();
  148. } else { // Success, pass on result.
  149. if (r_error) {
  150. *r_error = OK;
  151. }
  152. return res;
  153. }
  154. }
  155. ERR_FAIL_V_MSG(Ref<Resource>(), vformat("Failed to load resource '%s'. ResourceFormatLoader::load was not implemented for this resource type.", p_path));
  156. }
  157. void ResourceFormatLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  158. PackedStringArray deps;
  159. if (GDVIRTUAL_CALL(_get_dependencies, p_path, p_add_types, deps)) {
  160. const String *r = deps.ptr();
  161. for (int i = 0; i < deps.size(); ++i) {
  162. p_dependencies->push_back(r[i]);
  163. }
  164. }
  165. }
  166. Error ResourceFormatLoader::rename_dependencies(const String &p_path, const HashMap<String, String> &p_map) {
  167. Dictionary deps_dict;
  168. for (KeyValue<String, String> E : p_map) {
  169. deps_dict[E.key] = E.value;
  170. }
  171. Error err = OK;
  172. GDVIRTUAL_CALL(_rename_dependencies, p_path, deps_dict, err);
  173. return err;
  174. }
  175. void ResourceFormatLoader::_bind_methods() {
  176. BIND_ENUM_CONSTANT(CACHE_MODE_IGNORE);
  177. BIND_ENUM_CONSTANT(CACHE_MODE_REUSE);
  178. BIND_ENUM_CONSTANT(CACHE_MODE_REPLACE);
  179. BIND_ENUM_CONSTANT(CACHE_MODE_IGNORE_DEEP);
  180. BIND_ENUM_CONSTANT(CACHE_MODE_REPLACE_DEEP);
  181. GDVIRTUAL_BIND(_get_recognized_extensions);
  182. GDVIRTUAL_BIND(_recognize_path, "path", "type");
  183. GDVIRTUAL_BIND(_handles_type, "type");
  184. GDVIRTUAL_BIND(_get_resource_type, "path");
  185. GDVIRTUAL_BIND(_get_resource_script_class, "path");
  186. GDVIRTUAL_BIND(_get_resource_uid, "path");
  187. GDVIRTUAL_BIND(_get_dependencies, "path", "add_types");
  188. GDVIRTUAL_BIND(_rename_dependencies, "path", "renames");
  189. GDVIRTUAL_BIND(_exists, "path");
  190. GDVIRTUAL_BIND(_get_classes_used, "path");
  191. GDVIRTUAL_BIND(_load, "path", "original_path", "use_sub_threads", "cache_mode");
  192. }
  193. ///////////////////////////////////
  194. // These are used before and after a wait for a WorkerThreadPool task
  195. // because that can lead to another load started in the same thread,
  196. // something we must treat as a different stack for the purposes
  197. // of tracking nesting.
  198. #define PREPARE_FOR_WTP_WAIT \
  199. int load_nesting_backup = ResourceLoader::load_nesting; \
  200. Vector<String> load_paths_stack_backup = ResourceLoader::load_paths_stack; \
  201. ResourceLoader::load_nesting = 0; \
  202. ResourceLoader::load_paths_stack.clear();
  203. #define RESTORE_AFTER_WTP_WAIT \
  204. DEV_ASSERT(ResourceLoader::load_nesting == 0); \
  205. DEV_ASSERT(ResourceLoader::load_paths_stack.is_empty()); \
  206. ResourceLoader::load_nesting = load_nesting_backup; \
  207. ResourceLoader::load_paths_stack = load_paths_stack_backup; \
  208. load_paths_stack_backup.clear();
  209. // This should be robust enough to be called redundantly without issues.
  210. void ResourceLoader::LoadToken::clear() {
  211. WorkerThreadPool::TaskID task_to_await = 0;
  212. {
  213. MutexLock thread_load_lock(thread_load_mutex);
  214. // User-facing tokens shouldn't be deleted until completely claimed.
  215. DEV_ASSERT(user_rc == 0 && user_path.is_empty());
  216. if (!local_path.is_empty()) {
  217. if (task_if_unregistered) {
  218. memdelete(task_if_unregistered);
  219. task_if_unregistered = nullptr;
  220. } else {
  221. DEV_ASSERT(thread_load_tasks.has(local_path));
  222. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  223. if (load_task.task_id && !load_task.awaited) {
  224. task_to_await = load_task.task_id;
  225. }
  226. // Removing a task which is still in progress would be catastrophic.
  227. // Tokens must be alive until the task thread function is done.
  228. DEV_ASSERT(load_task.status == THREAD_LOAD_FAILED || load_task.status == THREAD_LOAD_LOADED);
  229. thread_load_tasks.erase(local_path);
  230. }
  231. local_path.clear(); // Mark as already cleared.
  232. }
  233. }
  234. // If task is unused, await it here, locally, now the token data is consistent.
  235. if (task_to_await) {
  236. PREPARE_FOR_WTP_WAIT
  237. WorkerThreadPool::get_singleton()->wait_for_task_completion(task_to_await);
  238. RESTORE_AFTER_WTP_WAIT
  239. }
  240. }
  241. ResourceLoader::LoadToken::~LoadToken() {
  242. clear();
  243. }
  244. 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) {
  245. const String &original_path = p_original_path.is_empty() ? p_path : p_original_path;
  246. load_nesting++;
  247. if (load_paths_stack.size()) {
  248. MutexLock thread_load_lock(thread_load_mutex);
  249. const String &parent_task_path = load_paths_stack.get(load_paths_stack.size() - 1);
  250. HashMap<String, ThreadLoadTask>::Iterator E = thread_load_tasks.find(parent_task_path);
  251. // Avoid double-tracking, for progress reporting, resources that boil down to a remapped path containing the real payload (e.g., imported resources).
  252. bool is_remapped_load = original_path == parent_task_path;
  253. if (E && !is_remapped_load) {
  254. E->value.sub_tasks.insert(p_original_path);
  255. }
  256. }
  257. load_paths_stack.push_back(original_path);
  258. print_verbose(vformat("Loading resource: %s", p_path));
  259. // Try all loaders and pick the first match for the type hint
  260. bool found = false;
  261. Ref<Resource> res;
  262. for (int i = 0; i < loader_count; i++) {
  263. if (!loader[i]->recognize_path(p_path, p_type_hint)) {
  264. continue;
  265. }
  266. found = true;
  267. res = loader[i]->load(p_path, original_path, r_error, p_use_sub_threads, r_progress, p_cache_mode);
  268. if (res.is_valid()) {
  269. break;
  270. }
  271. }
  272. load_paths_stack.resize(load_paths_stack.size() - 1);
  273. res_ref_overrides.erase(load_nesting);
  274. load_nesting--;
  275. if (res.is_valid()) {
  276. return res;
  277. } else {
  278. print_verbose(vformat("Failed loading resource: %s", p_path));
  279. }
  280. #ifdef TOOLS_ENABLED
  281. if (Engine::get_singleton()->is_editor_hint()) {
  282. if (ResourceFormatImporter::get_singleton()->get_importer_by_extension(p_path.get_extension()).is_valid()) {
  283. // The format is known to the editor, but the file hasn't been imported
  284. // (otherwise, ResourceFormatImporter would have been found as a suitable loader).
  285. found = true;
  286. if (r_error) {
  287. *r_error = ERR_FILE_NOT_FOUND;
  288. }
  289. }
  290. }
  291. #endif
  292. ERR_FAIL_COND_V_MSG(found, Ref<Resource>(),
  293. vformat("Failed loading resource: %s. Make sure resources have been imported by opening the project in the editor at least once.", p_path));
  294. #ifdef TOOLS_ENABLED
  295. Ref<FileAccess> file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);
  296. if (!file_check->file_exists(p_path)) {
  297. if (r_error) {
  298. *r_error = ERR_FILE_NOT_FOUND;
  299. }
  300. ERR_FAIL_V_MSG(Ref<Resource>(), vformat("Resource file not found: %s (expected type: %s)", p_path, p_type_hint));
  301. }
  302. #endif
  303. if (r_error) {
  304. *r_error = ERR_FILE_UNRECOGNIZED;
  305. }
  306. ERR_FAIL_V_MSG(Ref<Resource>(), vformat("No loader found for resource: %s (expected type: %s)", p_path, p_type_hint));
  307. }
  308. // This implementation must allow re-entrancy for a task that started awaiting in a deeper stack frame.
  309. // The load task token must be manually re-referenced before this is called, which includes threaded runs.
  310. void ResourceLoader::_run_load_task(void *p_userdata) {
  311. ThreadLoadTask &load_task = *(ThreadLoadTask *)p_userdata;
  312. {
  313. MutexLock thread_load_lock(thread_load_mutex);
  314. if (cleaning_tasks) {
  315. load_task.status = THREAD_LOAD_FAILED;
  316. return;
  317. }
  318. }
  319. ThreadLoadTask *curr_load_task_backup = curr_load_task;
  320. curr_load_task = &load_task;
  321. // Thread-safe either if it's the current thread or a brand new one.
  322. CallQueue *own_mq_override = nullptr;
  323. if (load_nesting == 0) {
  324. DEV_ASSERT(load_paths_stack.is_empty());
  325. if (!Thread::is_main_thread()) {
  326. // Let the caller thread use its own, for added flexibility. Provide one otherwise.
  327. if (MessageQueue::get_singleton() == MessageQueue::get_main_singleton()) {
  328. own_mq_override = memnew(CallQueue);
  329. MessageQueue::set_thread_singleton_override(own_mq_override);
  330. }
  331. set_current_thread_safe_for_nodes(true);
  332. }
  333. }
  334. // --
  335. bool xl_remapped = false;
  336. const String &remapped_path = _path_remap(load_task.local_path, &xl_remapped);
  337. Error load_err = OK;
  338. Ref<Resource> res = _load(remapped_path, remapped_path != load_task.local_path ? load_task.local_path : String(), load_task.type_hint, load_task.cache_mode, &load_err, load_task.use_sub_threads, &load_task.progress);
  339. if (MessageQueue::get_singleton() != MessageQueue::get_main_singleton()) {
  340. MessageQueue::get_singleton()->flush();
  341. }
  342. thread_load_mutex.lock();
  343. load_task.resource = res;
  344. load_task.progress = 1.0; // It was fully loaded at this point, so force progress to 1.0.
  345. load_task.error = load_err;
  346. if (load_task.error != OK) {
  347. load_task.status = THREAD_LOAD_FAILED;
  348. } else {
  349. load_task.status = THREAD_LOAD_LOADED;
  350. }
  351. if (load_task.cond_var && load_task.need_wait) {
  352. load_task.cond_var->notify_all();
  353. }
  354. load_task.need_wait = false;
  355. bool ignoring = load_task.cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE || load_task.cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE_DEEP;
  356. bool replacing = load_task.cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE || load_task.cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE_DEEP;
  357. bool unlock_pending = true;
  358. if (load_task.resource.is_valid()) {
  359. // From now on, no critical section needed as no one will write to the task anymore.
  360. // Moreover, the mutex being unlocked is a requirement if some of the calls below
  361. // that set the resource up invoke code that in turn requests resource loading.
  362. thread_load_mutex.unlock();
  363. unlock_pending = false;
  364. if (!ignoring) {
  365. ResourceCache::lock.lock(); // Check and operations must happen atomically.
  366. bool pending_unlock = true;
  367. Ref<Resource> old_res = ResourceCache::get_ref(load_task.local_path);
  368. if (old_res.is_valid()) {
  369. if (old_res != load_task.resource) {
  370. // Resource can already exists at this point for two reasons:
  371. // a) The load uses replace mode.
  372. // b) There were more than one load in flight for the same path because of deadlock prevention.
  373. // Either case, we want to keep the resource that was already there.
  374. ResourceCache::lock.unlock();
  375. pending_unlock = false;
  376. if (replacing) {
  377. old_res->copy_from(load_task.resource);
  378. }
  379. load_task.resource = old_res;
  380. }
  381. } else {
  382. load_task.resource->set_path(load_task.local_path);
  383. }
  384. if (pending_unlock) {
  385. ResourceCache::lock.unlock();
  386. }
  387. } else {
  388. load_task.resource->set_path_cache(load_task.local_path);
  389. }
  390. if (xl_remapped) {
  391. load_task.resource->set_as_translation_remapped(true);
  392. }
  393. #ifdef TOOLS_ENABLED
  394. load_task.resource->set_edited(false);
  395. if (timestamp_on_load) {
  396. uint64_t mt = FileAccess::get_modified_time(remapped_path);
  397. //printf("mt %s: %lli\n",remapped_path.utf8().get_data(),mt);
  398. load_task.resource->set_last_modified_time(mt);
  399. }
  400. #endif
  401. if (_loaded_callback) {
  402. _loaded_callback(load_task.resource, load_task.local_path);
  403. }
  404. } else if (!ignoring) {
  405. Ref<Resource> existing = ResourceCache::get_ref(load_task.local_path);
  406. if (existing.is_valid()) {
  407. load_task.resource = existing;
  408. load_task.status = THREAD_LOAD_LOADED;
  409. load_task.progress = 1.0;
  410. thread_load_mutex.unlock();
  411. unlock_pending = false;
  412. if (_loaded_callback) {
  413. _loaded_callback(load_task.resource, load_task.local_path);
  414. }
  415. }
  416. }
  417. // It's safe now to let the task go in case no one else was grabbing the token.
  418. load_task.load_token->unreference();
  419. if (unlock_pending) {
  420. thread_load_mutex.unlock();
  421. }
  422. if (load_nesting == 0) {
  423. if (own_mq_override) {
  424. MessageQueue::set_thread_singleton_override(nullptr);
  425. memdelete(own_mq_override);
  426. }
  427. DEV_ASSERT(load_paths_stack.is_empty());
  428. }
  429. curr_load_task = curr_load_task_backup;
  430. }
  431. String ResourceLoader::_validate_local_path(const String &p_path) {
  432. ResourceUID::ID uid = ResourceUID::get_singleton()->text_to_id(p_path);
  433. if (uid != ResourceUID::INVALID_ID) {
  434. return ResourceUID::get_singleton()->get_id_path(uid);
  435. } else if (p_path.is_relative_path()) {
  436. return ("res://" + p_path).simplify_path();
  437. } else {
  438. return ProjectSettings::get_singleton()->localize_path(p_path);
  439. }
  440. }
  441. Error ResourceLoader::load_threaded_request(const String &p_path, const String &p_type_hint, bool p_use_sub_threads, ResourceFormatLoader::CacheMode p_cache_mode) {
  442. 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, true);
  443. return token.is_valid() ? OK : FAILED;
  444. }
  445. ResourceLoader::LoadToken *ResourceLoader::_load_threaded_request_reuse_user_token(const String &p_path) {
  446. HashMap<String, LoadToken *>::Iterator E = user_load_tokens.find(p_path);
  447. if (E) {
  448. print_verbose("load_threaded_request(): Another threaded load for resource path '" + p_path + "' has been initiated. Not an error.");
  449. LoadToken *token = E->value;
  450. token->user_rc++;
  451. return token;
  452. } else {
  453. return nullptr;
  454. }
  455. }
  456. void ResourceLoader::_load_threaded_request_setup_user_token(LoadToken *p_token, const String &p_path) {
  457. p_token->user_path = p_path;
  458. p_token->reference(); // Extra RC until all user requests have been gotten.
  459. p_token->user_rc = 1;
  460. user_load_tokens[p_path] = p_token;
  461. print_lt("REQUEST: user load tokens: " + itos(user_load_tokens.size()));
  462. }
  463. Ref<Resource> ResourceLoader::load(const String &p_path, const String &p_type_hint, ResourceFormatLoader::CacheMode p_cache_mode, Error *r_error) {
  464. if (r_error) {
  465. *r_error = OK;
  466. }
  467. LoadThreadMode thread_mode = LOAD_THREAD_FROM_CURRENT;
  468. if (WorkerThreadPool::get_singleton()->get_caller_task_id() != WorkerThreadPool::INVALID_TASK_ID) {
  469. // If user is initiating a single-threaded load from a WorkerThreadPool task,
  470. // we instead spawn a new task so there's a precondition that a load in a pool task
  471. // is always initiated by the engine. That makes certain aspects simpler, such as
  472. // cyclic load detection and awaiting.
  473. thread_mode = LOAD_THREAD_SPAWN_SINGLE;
  474. }
  475. Ref<LoadToken> load_token = _load_start(p_path, p_type_hint, thread_mode, p_cache_mode);
  476. if (load_token.is_null()) {
  477. if (r_error) {
  478. *r_error = FAILED;
  479. }
  480. return Ref<Resource>();
  481. }
  482. Ref<Resource> res = _load_complete(*load_token.ptr(), r_error);
  483. return res;
  484. }
  485. Ref<ResourceLoader::LoadToken> ResourceLoader::_load_start(const String &p_path, const String &p_type_hint, LoadThreadMode p_thread_mode, ResourceFormatLoader::CacheMode p_cache_mode, bool p_for_user) {
  486. String local_path = _validate_local_path(p_path);
  487. bool ignoring_cache = p_cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE || p_cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE_DEEP;
  488. Ref<LoadToken> load_token;
  489. bool must_not_register = false;
  490. ThreadLoadTask *load_task_ptr = nullptr;
  491. {
  492. MutexLock thread_load_lock(thread_load_mutex);
  493. if (p_for_user) {
  494. LoadToken *existing_token = _load_threaded_request_reuse_user_token(p_path);
  495. if (existing_token) {
  496. return Ref<LoadToken>(existing_token);
  497. }
  498. }
  499. if (!ignoring_cache && thread_load_tasks.has(local_path)) {
  500. load_token = Ref<LoadToken>(thread_load_tasks[local_path].load_token);
  501. if (load_token.is_valid()) {
  502. if (p_for_user) {
  503. // Load task exists, with no user tokens at the moment.
  504. // Let's "attach" to it.
  505. _load_threaded_request_setup_user_token(load_token.ptr(), p_path);
  506. }
  507. return load_token;
  508. } else {
  509. // The token is dying (reached 0 on another thread).
  510. // Ensure it's killed now so the path can be safely reused right away.
  511. thread_load_tasks[local_path].load_token->clear();
  512. }
  513. }
  514. load_token.instantiate();
  515. load_token->local_path = local_path;
  516. if (p_for_user) {
  517. _load_threaded_request_setup_user_token(load_token.ptr(), p_path);
  518. }
  519. //create load task
  520. {
  521. ThreadLoadTask load_task;
  522. load_task.load_token = load_token.ptr();
  523. load_task.local_path = local_path;
  524. load_task.type_hint = p_type_hint;
  525. load_task.cache_mode = p_cache_mode;
  526. load_task.use_sub_threads = p_thread_mode == LOAD_THREAD_DISTRIBUTE;
  527. if (p_cache_mode == ResourceFormatLoader::CACHE_MODE_REUSE) {
  528. Ref<Resource> existing = ResourceCache::get_ref(local_path);
  529. if (existing.is_valid()) {
  530. //referencing is fine
  531. load_task.resource = existing;
  532. load_task.status = THREAD_LOAD_LOADED;
  533. load_task.progress = 1.0;
  534. DEV_ASSERT(!thread_load_tasks.has(local_path));
  535. thread_load_tasks[local_path] = load_task;
  536. return load_token;
  537. }
  538. }
  539. // If we want to ignore cache, but there's another task loading it, we can't add this one to the map.
  540. must_not_register = ignoring_cache && thread_load_tasks.has(local_path);
  541. if (must_not_register) {
  542. load_token->task_if_unregistered = memnew(ThreadLoadTask(load_task));
  543. load_task_ptr = load_token->task_if_unregistered;
  544. } else {
  545. DEV_ASSERT(!thread_load_tasks.has(local_path));
  546. HashMap<String, ResourceLoader::ThreadLoadTask>::Iterator E = thread_load_tasks.insert(local_path, load_task);
  547. load_task_ptr = &E->value;
  548. }
  549. }
  550. // It's important to keep the token alive because until the load completes,
  551. // which includes before the thread start, it may happen that no one is grabbing
  552. // the token anymore so it's released.
  553. load_task_ptr->load_token->reference();
  554. if (p_thread_mode == LOAD_THREAD_FROM_CURRENT) {
  555. // The current thread may happen to be a thread from the pool.
  556. WorkerThreadPool::TaskID tid = WorkerThreadPool::get_singleton()->get_caller_task_id();
  557. if (tid != WorkerThreadPool::INVALID_TASK_ID) {
  558. load_task_ptr->task_id = tid;
  559. } else {
  560. load_task_ptr->thread_id = Thread::get_caller_id();
  561. }
  562. } else {
  563. load_task_ptr->task_id = WorkerThreadPool::get_singleton()->add_native_task(&ResourceLoader::_run_load_task, load_task_ptr);
  564. }
  565. } // MutexLock(thread_load_mutex).
  566. if (p_thread_mode == LOAD_THREAD_FROM_CURRENT) {
  567. _run_load_task(load_task_ptr);
  568. }
  569. return load_token;
  570. }
  571. float ResourceLoader::_dependency_get_progress(const String &p_path) {
  572. if (thread_load_tasks.has(p_path)) {
  573. ThreadLoadTask &load_task = thread_load_tasks[p_path];
  574. float current_progress = 0.0;
  575. int dep_count = load_task.sub_tasks.size();
  576. if (dep_count > 0) {
  577. for (const String &E : load_task.sub_tasks) {
  578. current_progress += _dependency_get_progress(E);
  579. }
  580. current_progress /= float(dep_count);
  581. current_progress *= 0.5;
  582. current_progress += load_task.progress * 0.5;
  583. } else {
  584. current_progress = load_task.progress;
  585. }
  586. load_task.max_reported_progress = MAX(load_task.max_reported_progress, current_progress);
  587. return load_task.max_reported_progress;
  588. } else {
  589. return 1.0; //assume finished loading it so it no longer exists
  590. }
  591. }
  592. ResourceLoader::ThreadLoadStatus ResourceLoader::load_threaded_get_status(const String &p_path, float *r_progress) {
  593. bool ensure_progress = false;
  594. ThreadLoadStatus status = THREAD_LOAD_IN_PROGRESS;
  595. {
  596. MutexLock thread_load_lock(thread_load_mutex);
  597. if (!user_load_tokens.has(p_path)) {
  598. print_verbose("load_threaded_get_status(): No threaded load for resource path '" + p_path + "' has been initiated or its result has already been collected.");
  599. return THREAD_LOAD_INVALID_RESOURCE;
  600. }
  601. String local_path = _validate_local_path(p_path);
  602. ERR_FAIL_COND_V_MSG(!thread_load_tasks.has(local_path), THREAD_LOAD_INVALID_RESOURCE, "Bug in ResourceLoader logic, please report.");
  603. ThreadLoadTask &load_task = thread_load_tasks[local_path];
  604. status = load_task.status;
  605. if (r_progress) {
  606. *r_progress = _dependency_get_progress(local_path);
  607. }
  608. // Support userland polling in a loop on the main thread.
  609. if (Thread::is_main_thread() && status == THREAD_LOAD_IN_PROGRESS) {
  610. uint64_t frame = Engine::get_singleton()->get_process_frames();
  611. if (frame == load_task.last_progress_check_main_thread_frame) {
  612. ensure_progress = true;
  613. } else {
  614. load_task.last_progress_check_main_thread_frame = frame;
  615. }
  616. }
  617. }
  618. if (ensure_progress) {
  619. _ensure_load_progress();
  620. }
  621. return status;
  622. }
  623. Ref<Resource> ResourceLoader::load_threaded_get(const String &p_path, Error *r_error) {
  624. if (r_error) {
  625. *r_error = OK;
  626. }
  627. Ref<Resource> res;
  628. {
  629. MutexLock thread_load_lock(thread_load_mutex);
  630. if (!user_load_tokens.has(p_path)) {
  631. print_verbose("load_threaded_get(): No threaded load for resource path '" + p_path + "' has been initiated or its result has already been collected.");
  632. if (r_error) {
  633. *r_error = ERR_INVALID_PARAMETER;
  634. }
  635. return Ref<Resource>();
  636. }
  637. LoadToken *load_token = user_load_tokens[p_path];
  638. DEV_ASSERT(load_token->user_rc >= 1);
  639. // Support userland requesting on the main thread before the load is reported to be complete.
  640. if (Thread::is_main_thread() && !load_token->local_path.is_empty()) {
  641. const ThreadLoadTask &load_task = thread_load_tasks[load_token->local_path];
  642. while (load_task.status == THREAD_LOAD_IN_PROGRESS) {
  643. thread_load_lock.temp_unlock();
  644. bool exit = !_ensure_load_progress();
  645. OS::get_singleton()->delay_usec(1000);
  646. thread_load_lock.temp_relock();
  647. if (exit) {
  648. break;
  649. }
  650. }
  651. }
  652. res = _load_complete_inner(*load_token, r_error, thread_load_lock);
  653. load_token->user_rc--;
  654. if (load_token->user_rc == 0) {
  655. load_token->user_path.clear();
  656. user_load_tokens.erase(p_path);
  657. if (load_token->unreference()) {
  658. memdelete(load_token);
  659. load_token = nullptr;
  660. }
  661. }
  662. }
  663. print_lt("GET: user load tokens: " + itos(user_load_tokens.size()));
  664. return res;
  665. }
  666. Ref<Resource> ResourceLoader::_load_complete(LoadToken &p_load_token, Error *r_error) {
  667. MutexLock thread_load_lock(thread_load_mutex);
  668. return _load_complete_inner(p_load_token, r_error, thread_load_lock);
  669. }
  670. Ref<Resource> ResourceLoader::_load_complete_inner(LoadToken &p_load_token, Error *r_error, MutexLock<SafeBinaryMutex<BINARY_MUTEX_TAG>> &p_thread_load_lock) {
  671. if (r_error) {
  672. *r_error = OK;
  673. }
  674. ThreadLoadTask *load_task_ptr = nullptr;
  675. if (p_load_token.task_if_unregistered) {
  676. load_task_ptr = p_load_token.task_if_unregistered;
  677. } else {
  678. if (!thread_load_tasks.has(p_load_token.local_path)) {
  679. if (r_error) {
  680. *r_error = ERR_BUG;
  681. }
  682. ERR_FAIL_V_MSG(Ref<Resource>(), "Bug in ResourceLoader logic, please report.");
  683. }
  684. ThreadLoadTask &load_task = thread_load_tasks[p_load_token.local_path];
  685. if (load_task.status == THREAD_LOAD_IN_PROGRESS) {
  686. DEV_ASSERT((load_task.task_id == 0) != (load_task.thread_id == 0));
  687. if ((load_task.task_id != 0 && load_task.task_id == WorkerThreadPool::get_singleton()->get_caller_task_id()) ||
  688. (load_task.thread_id != 0 && load_task.thread_id == Thread::get_caller_id())) {
  689. // Load is in progress, but it's precisely this thread the one in charge.
  690. // That means this is a cyclic load.
  691. if (r_error) {
  692. *r_error = ERR_BUSY;
  693. }
  694. return Ref<Resource>();
  695. }
  696. bool loader_is_wtp = load_task.task_id != 0;
  697. if (loader_is_wtp) {
  698. // Loading thread is in the worker pool.
  699. p_thread_load_lock.temp_unlock();
  700. PREPARE_FOR_WTP_WAIT
  701. Error wait_err = WorkerThreadPool::get_singleton()->wait_for_task_completion(load_task.task_id);
  702. RESTORE_AFTER_WTP_WAIT
  703. DEV_ASSERT(!wait_err || wait_err == ERR_BUSY);
  704. if (wait_err == ERR_BUSY) {
  705. // The WorkerThreadPool has reported that the current task wants to await on an older one.
  706. // That't not allowed for safety, to avoid deadlocks. Fortunately, though, in the context of
  707. // resource loading that means that the task to wait for can be restarted here to break the
  708. // cycle, with as much recursion into this process as needed.
  709. // When the stack is eventually unrolled, the original load will have been notified to go on.
  710. load_task.load_token->reference();
  711. _run_load_task(&load_task);
  712. }
  713. p_thread_load_lock.temp_relock();
  714. load_task.awaited = true;
  715. DEV_ASSERT(load_task.status == THREAD_LOAD_FAILED || load_task.status == THREAD_LOAD_LOADED);
  716. } else if (load_task.need_wait) {
  717. // Loading thread is main or user thread.
  718. if (!load_task.cond_var) {
  719. load_task.cond_var = memnew(ConditionVariable);
  720. }
  721. load_task.awaiters_count++;
  722. do {
  723. load_task.cond_var->wait(p_thread_load_lock);
  724. DEV_ASSERT(thread_load_tasks.has(p_load_token.local_path) && p_load_token.get_reference_count());
  725. } while (load_task.need_wait);
  726. load_task.awaiters_count--;
  727. if (load_task.awaiters_count == 0) {
  728. memdelete(load_task.cond_var);
  729. load_task.cond_var = nullptr;
  730. }
  731. DEV_ASSERT(load_task.status == THREAD_LOAD_FAILED || load_task.status == THREAD_LOAD_LOADED);
  732. }
  733. }
  734. if (cleaning_tasks) {
  735. load_task.resource = Ref<Resource>();
  736. load_task.error = FAILED;
  737. }
  738. load_task_ptr = &load_task;
  739. }
  740. p_thread_load_lock.temp_unlock();
  741. Ref<Resource> resource = load_task_ptr->resource;
  742. if (r_error) {
  743. *r_error = load_task_ptr->error;
  744. }
  745. if (resource.is_valid()) {
  746. if (curr_load_task) {
  747. // A task awaiting another => Let the awaiter accumulate the resource changed connections.
  748. DEV_ASSERT(curr_load_task != load_task_ptr);
  749. for (const ThreadLoadTask::ResourceChangedConnection &rcc : load_task_ptr->resource_changed_connections) {
  750. curr_load_task->resource_changed_connections.push_back(rcc);
  751. }
  752. } else {
  753. // A leaf task being awaited => Propagate the resource changed connections.
  754. if (Thread::is_main_thread()) {
  755. // On the main thread it's safe to migrate the connections to the standard signal mechanism.
  756. for (const ThreadLoadTask::ResourceChangedConnection &rcc : load_task_ptr->resource_changed_connections) {
  757. if (rcc.callable.is_valid()) {
  758. rcc.source->connect_changed(rcc.callable, rcc.flags);
  759. }
  760. }
  761. } else {
  762. // On non-main threads, we have to queue and call it done when processed.
  763. if (!load_task_ptr->resource_changed_connections.is_empty()) {
  764. for (const ThreadLoadTask::ResourceChangedConnection &rcc : load_task_ptr->resource_changed_connections) {
  765. if (rcc.callable.is_valid()) {
  766. MessageQueue::get_main_singleton()->push_callable(callable_mp(rcc.source, &Resource::connect_changed).bind(rcc.callable, rcc.flags));
  767. }
  768. }
  769. core_bind::Semaphore done;
  770. MessageQueue::get_main_singleton()->push_callable(callable_mp(&done, &core_bind::Semaphore::post).bind(1));
  771. done.wait();
  772. }
  773. }
  774. }
  775. }
  776. p_thread_load_lock.temp_relock();
  777. return resource;
  778. }
  779. bool ResourceLoader::_ensure_load_progress() {
  780. // Some servers may need a new engine iteration to allow the load to progress.
  781. // Since the only known one is the rendering server (in single thread mode), let's keep it simple and just sync it.
  782. // This may be refactored in the future to support other servers and have less coupling.
  783. if (OS::get_singleton()->is_separate_thread_rendering_enabled()) {
  784. return false; // Not needed.
  785. }
  786. RenderingServer::get_singleton()->sync();
  787. return true;
  788. }
  789. void ResourceLoader::resource_changed_connect(Resource *p_source, const Callable &p_callable, uint32_t p_flags) {
  790. print_lt(vformat("%d\t%ud:%s\t" FUNCTION_STR "\t%d", Thread::get_caller_id(), p_source->get_instance_id(), p_source->get_class(), p_callable.get_object_id()));
  791. MutexLock lock(thread_load_mutex);
  792. for (const ThreadLoadTask::ResourceChangedConnection &rcc : curr_load_task->resource_changed_connections) {
  793. if (unlikely(rcc.source == p_source && rcc.callable == p_callable)) {
  794. return;
  795. }
  796. }
  797. ThreadLoadTask::ResourceChangedConnection rcc;
  798. rcc.source = p_source;
  799. rcc.callable = p_callable;
  800. rcc.flags = p_flags;
  801. curr_load_task->resource_changed_connections.push_back(rcc);
  802. }
  803. void ResourceLoader::resource_changed_disconnect(Resource *p_source, const Callable &p_callable) {
  804. print_lt(vformat("%d\t%ud:%s\t" FUNCTION_STR "t%d", Thread::get_caller_id(), p_source->get_instance_id(), p_source->get_class(), p_callable.get_object_id()));
  805. MutexLock lock(thread_load_mutex);
  806. for (uint32_t i = 0; i < curr_load_task->resource_changed_connections.size(); ++i) {
  807. const ThreadLoadTask::ResourceChangedConnection &rcc = curr_load_task->resource_changed_connections[i];
  808. if (unlikely(rcc.source == p_source && rcc.callable == p_callable)) {
  809. curr_load_task->resource_changed_connections.remove_at_unordered(i);
  810. return;
  811. }
  812. }
  813. }
  814. void ResourceLoader::resource_changed_emit(Resource *p_source) {
  815. print_lt(vformat("%d\t%ud:%s\t" FUNCTION_STR, Thread::get_caller_id(), p_source->get_instance_id(), p_source->get_class()));
  816. MutexLock lock(thread_load_mutex);
  817. for (const ThreadLoadTask::ResourceChangedConnection &rcc : curr_load_task->resource_changed_connections) {
  818. if (unlikely(rcc.source == p_source)) {
  819. rcc.callable.call();
  820. }
  821. }
  822. }
  823. Ref<Resource> ResourceLoader::ensure_resource_ref_override_for_outer_load(const String &p_path, const String &p_res_type) {
  824. ERR_FAIL_COND_V(load_nesting == 0, Ref<Resource>()); // It makes no sense to use this from nesting level 0.
  825. const String &local_path = _validate_local_path(p_path);
  826. HashMap<String, Ref<Resource>> &overrides = res_ref_overrides[load_nesting - 1];
  827. HashMap<String, Ref<Resource>>::Iterator E = overrides.find(local_path);
  828. if (E) {
  829. return E->value;
  830. } else {
  831. Object *obj = ClassDB::instantiate(p_res_type);
  832. ERR_FAIL_NULL_V(obj, Ref<Resource>());
  833. Ref<Resource> res(obj);
  834. if (res.is_null()) {
  835. memdelete(obj);
  836. ERR_FAIL_V(Ref<Resource>());
  837. }
  838. overrides[local_path] = res;
  839. return res;
  840. }
  841. }
  842. Ref<Resource> ResourceLoader::get_resource_ref_override(const String &p_path) {
  843. DEV_ASSERT(p_path == _validate_local_path(p_path));
  844. HashMap<int, HashMap<String, Ref<Resource>>>::Iterator E = res_ref_overrides.find(load_nesting);
  845. if (!E) {
  846. return nullptr;
  847. }
  848. HashMap<String, Ref<Resource>>::Iterator F = E->value.find(p_path);
  849. if (!F) {
  850. return nullptr;
  851. }
  852. return F->value;
  853. }
  854. bool ResourceLoader::exists(const String &p_path, const String &p_type_hint) {
  855. String local_path = _validate_local_path(p_path);
  856. if (ResourceCache::has(local_path)) {
  857. return true; // If cached, it probably exists
  858. }
  859. bool xl_remapped = false;
  860. String path = _path_remap(local_path, &xl_remapped);
  861. // Try all loaders and pick the first match for the type hint
  862. for (int i = 0; i < loader_count; i++) {
  863. if (!loader[i]->recognize_path(path, p_type_hint)) {
  864. continue;
  865. }
  866. if (loader[i]->exists(path)) {
  867. return true;
  868. }
  869. }
  870. return false;
  871. }
  872. void ResourceLoader::add_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader, bool p_at_front) {
  873. ERR_FAIL_COND(p_format_loader.is_null());
  874. ERR_FAIL_COND(loader_count >= MAX_LOADERS);
  875. if (p_at_front) {
  876. for (int i = loader_count; i > 0; i--) {
  877. loader[i] = loader[i - 1];
  878. }
  879. loader[0] = p_format_loader;
  880. loader_count++;
  881. } else {
  882. loader[loader_count++] = p_format_loader;
  883. }
  884. }
  885. void ResourceLoader::remove_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader) {
  886. ERR_FAIL_COND(p_format_loader.is_null());
  887. // Find loader
  888. int i = 0;
  889. for (; i < loader_count; ++i) {
  890. if (loader[i] == p_format_loader) {
  891. break;
  892. }
  893. }
  894. ERR_FAIL_COND(i >= loader_count); // Not found
  895. // Shift next loaders up
  896. for (; i < loader_count - 1; ++i) {
  897. loader[i] = loader[i + 1];
  898. }
  899. loader[loader_count - 1].unref();
  900. --loader_count;
  901. }
  902. int ResourceLoader::get_import_order(const String &p_path) {
  903. String local_path = _path_remap(_validate_local_path(p_path));
  904. for (int i = 0; i < loader_count; i++) {
  905. if (!loader[i]->recognize_path(local_path)) {
  906. continue;
  907. }
  908. return loader[i]->get_import_order(p_path);
  909. }
  910. return 0;
  911. }
  912. String ResourceLoader::get_import_group_file(const String &p_path) {
  913. String local_path = _path_remap(_validate_local_path(p_path));
  914. for (int i = 0; i < loader_count; i++) {
  915. if (!loader[i]->recognize_path(local_path)) {
  916. continue;
  917. }
  918. return loader[i]->get_import_group_file(p_path);
  919. }
  920. return String(); //not found
  921. }
  922. bool ResourceLoader::is_import_valid(const String &p_path) {
  923. String local_path = _path_remap(_validate_local_path(p_path));
  924. for (int i = 0; i < loader_count; i++) {
  925. if (!loader[i]->recognize_path(local_path)) {
  926. continue;
  927. }
  928. return loader[i]->is_import_valid(p_path);
  929. }
  930. return false; //not found
  931. }
  932. bool ResourceLoader::is_imported(const String &p_path) {
  933. String local_path = _path_remap(_validate_local_path(p_path));
  934. for (int i = 0; i < loader_count; i++) {
  935. if (!loader[i]->recognize_path(local_path)) {
  936. continue;
  937. }
  938. return loader[i]->is_imported(p_path);
  939. }
  940. return false; //not found
  941. }
  942. void ResourceLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  943. String local_path = _path_remap(_validate_local_path(p_path));
  944. for (int i = 0; i < loader_count; i++) {
  945. if (!loader[i]->recognize_path(local_path)) {
  946. continue;
  947. }
  948. loader[i]->get_dependencies(local_path, p_dependencies, p_add_types);
  949. }
  950. }
  951. Error ResourceLoader::rename_dependencies(const String &p_path, const HashMap<String, String> &p_map) {
  952. String local_path = _path_remap(_validate_local_path(p_path));
  953. for (int i = 0; i < loader_count; i++) {
  954. if (!loader[i]->recognize_path(local_path)) {
  955. continue;
  956. }
  957. return loader[i]->rename_dependencies(local_path, p_map);
  958. }
  959. return OK; // ??
  960. }
  961. void ResourceLoader::get_classes_used(const String &p_path, HashSet<StringName> *r_classes) {
  962. String local_path = _validate_local_path(p_path);
  963. for (int i = 0; i < loader_count; i++) {
  964. if (!loader[i]->recognize_path(local_path)) {
  965. continue;
  966. }
  967. return loader[i]->get_classes_used(p_path, r_classes);
  968. }
  969. }
  970. String ResourceLoader::get_resource_type(const String &p_path) {
  971. String local_path = _validate_local_path(p_path);
  972. for (int i = 0; i < loader_count; i++) {
  973. String result = loader[i]->get_resource_type(local_path);
  974. if (!result.is_empty()) {
  975. return result;
  976. }
  977. }
  978. return "";
  979. }
  980. String ResourceLoader::get_resource_script_class(const String &p_path) {
  981. String local_path = _validate_local_path(p_path);
  982. for (int i = 0; i < loader_count; i++) {
  983. String result = loader[i]->get_resource_script_class(local_path);
  984. if (!result.is_empty()) {
  985. return result;
  986. }
  987. }
  988. return "";
  989. }
  990. ResourceUID::ID ResourceLoader::get_resource_uid(const String &p_path) {
  991. String local_path = _validate_local_path(p_path);
  992. for (int i = 0; i < loader_count; i++) {
  993. ResourceUID::ID id = loader[i]->get_resource_uid(local_path);
  994. if (id != ResourceUID::INVALID_ID) {
  995. return id;
  996. }
  997. }
  998. return ResourceUID::INVALID_ID;
  999. }
  1000. bool ResourceLoader::has_custom_uid_support(const String &p_path) {
  1001. String local_path = _validate_local_path(p_path);
  1002. for (int i = 0; i < loader_count; i++) {
  1003. if (!loader[i]->recognize_path(local_path)) {
  1004. continue;
  1005. }
  1006. if (loader[i]->has_custom_uid_support()) {
  1007. return true;
  1008. }
  1009. }
  1010. return false;
  1011. }
  1012. bool ResourceLoader::should_create_uid_file(const String &p_path) {
  1013. const String local_path = _validate_local_path(p_path);
  1014. if (FileAccess::exists(local_path + ".uid")) {
  1015. return false;
  1016. }
  1017. for (int i = 0; i < loader_count; i++) {
  1018. if (loader[i]->recognize_path(local_path)) {
  1019. return !loader[i]->has_custom_uid_support();
  1020. }
  1021. }
  1022. return false;
  1023. }
  1024. String ResourceLoader::_path_remap(const String &p_path, bool *r_translation_remapped) {
  1025. String new_path = p_path;
  1026. if (translation_remaps.has(p_path)) {
  1027. // translation_remaps has the following format:
  1028. // { "res://path.png": PackedStringArray( "res://path-ru.png:ru", "res://path-de.png:de" ) }
  1029. // To find the path of the remapped resource, we extract the locale name after
  1030. // the last ':' to match the project locale.
  1031. // An extra remap may still be necessary afterwards due to the text -> binary converter on export.
  1032. String locale = TranslationServer::get_singleton()->get_locale();
  1033. ERR_FAIL_COND_V_MSG(locale.length() < 2, p_path, vformat("Could not remap path '%s' for translation as configured locale '%s' is invalid.", p_path, locale));
  1034. Vector<String> &res_remaps = *translation_remaps.getptr(new_path);
  1035. int best_score = 0;
  1036. for (int i = 0; i < res_remaps.size(); i++) {
  1037. int split = res_remaps[i].rfind_char(':');
  1038. if (split == -1) {
  1039. continue;
  1040. }
  1041. String l = res_remaps[i].substr(split + 1).strip_edges();
  1042. int score = TranslationServer::get_singleton()->compare_locales(locale, l);
  1043. if (score > 0 && score >= best_score) {
  1044. new_path = res_remaps[i].left(split);
  1045. best_score = score;
  1046. if (score == 10) {
  1047. break; // Exact match, skip the rest.
  1048. }
  1049. }
  1050. }
  1051. if (r_translation_remapped) {
  1052. *r_translation_remapped = true;
  1053. }
  1054. // Fallback to p_path if new_path does not exist.
  1055. if (!FileAccess::exists(new_path + ".import") && !FileAccess::exists(new_path)) {
  1056. WARN_PRINT(vformat("Translation remap '%s' does not exist. Falling back to '%s'.", new_path, p_path));
  1057. new_path = p_path;
  1058. }
  1059. }
  1060. if (path_remaps.has(new_path)) {
  1061. new_path = path_remaps[new_path];
  1062. } else {
  1063. // Try file remap.
  1064. // Usually, there's no remap file and FileAccess::exists() is faster than FileAccess::open().
  1065. new_path = ResourceUID::ensure_path(new_path);
  1066. if (FileAccess::exists(new_path + ".remap")) {
  1067. Error err;
  1068. Ref<FileAccess> f = FileAccess::open(new_path + ".remap", FileAccess::READ, &err);
  1069. if (f.is_valid()) {
  1070. VariantParser::StreamFile stream;
  1071. stream.f = f;
  1072. String assign;
  1073. Variant value;
  1074. VariantParser::Tag next_tag;
  1075. int lines = 0;
  1076. String error_text;
  1077. while (true) {
  1078. assign = Variant();
  1079. next_tag.fields.clear();
  1080. next_tag.name = String();
  1081. err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true);
  1082. if (err == ERR_FILE_EOF) {
  1083. break;
  1084. } else if (err != OK) {
  1085. ERR_PRINT(vformat("Parse error: %s.remap:%d error: %s.", p_path, lines, error_text));
  1086. break;
  1087. }
  1088. if (assign == "path") {
  1089. new_path = value;
  1090. break;
  1091. } else if (next_tag.name != "remap") {
  1092. break;
  1093. }
  1094. }
  1095. }
  1096. }
  1097. }
  1098. return new_path;
  1099. }
  1100. String ResourceLoader::import_remap(const String &p_path) {
  1101. if (ResourceFormatImporter::get_singleton()->recognize_path(p_path)) {
  1102. return ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_path);
  1103. }
  1104. return p_path;
  1105. }
  1106. String ResourceLoader::path_remap(const String &p_path) {
  1107. return _path_remap(p_path);
  1108. }
  1109. void ResourceLoader::reload_translation_remaps() {
  1110. List<Resource *> to_reload;
  1111. {
  1112. MutexLock lock(ResourceCache::lock);
  1113. SelfList<Resource> *E = remapped_list.first();
  1114. while (E) {
  1115. to_reload.push_back(E->self());
  1116. E = E->next();
  1117. }
  1118. }
  1119. //now just make sure to not delete any of these resources while changing locale..
  1120. while (to_reload.front()) {
  1121. to_reload.front()->get()->reload_from_file();
  1122. to_reload.pop_front();
  1123. }
  1124. }
  1125. void ResourceLoader::load_translation_remaps() {
  1126. if (!ProjectSettings::get_singleton()->has_setting("internationalization/locale/translation_remaps")) {
  1127. return;
  1128. }
  1129. Dictionary remaps = GLOBAL_GET("internationalization/locale/translation_remaps");
  1130. List<Variant> keys;
  1131. remaps.get_key_list(&keys);
  1132. for (const Variant &E : keys) {
  1133. Array langs = remaps[E];
  1134. Vector<String> lang_remaps;
  1135. lang_remaps.resize(langs.size());
  1136. String *lang_remaps_ptrw = lang_remaps.ptrw();
  1137. for (const Variant &lang : langs) {
  1138. *lang_remaps_ptrw++ = lang;
  1139. }
  1140. translation_remaps[String(E)] = lang_remaps;
  1141. }
  1142. }
  1143. void ResourceLoader::clear_translation_remaps() {
  1144. translation_remaps.clear();
  1145. while (remapped_list.first() != nullptr) {
  1146. remapped_list.remove(remapped_list.first());
  1147. }
  1148. }
  1149. void ResourceLoader::clear_thread_load_tasks() {
  1150. // Bring the thing down as quickly as possible without causing deadlocks or leaks.
  1151. MutexLock thread_load_lock(thread_load_mutex);
  1152. cleaning_tasks = true;
  1153. while (true) {
  1154. bool none_running = true;
  1155. if (thread_load_tasks.size()) {
  1156. for (KeyValue<String, ResourceLoader::ThreadLoadTask> &E : thread_load_tasks) {
  1157. if (E.value.status == THREAD_LOAD_IN_PROGRESS) {
  1158. if (E.value.cond_var && E.value.need_wait) {
  1159. E.value.cond_var->notify_all();
  1160. }
  1161. E.value.need_wait = false;
  1162. none_running = false;
  1163. }
  1164. }
  1165. }
  1166. if (none_running) {
  1167. break;
  1168. }
  1169. thread_load_lock.temp_unlock();
  1170. OS::get_singleton()->delay_usec(1000);
  1171. thread_load_lock.temp_relock();
  1172. }
  1173. while (user_load_tokens.begin()) {
  1174. LoadToken *user_token = user_load_tokens.begin()->value;
  1175. user_load_tokens.remove(user_load_tokens.begin());
  1176. DEV_ASSERT(user_token->user_rc > 0 && !user_token->user_path.is_empty());
  1177. user_token->user_path.clear();
  1178. user_token->user_rc = 0;
  1179. user_token->unreference();
  1180. }
  1181. thread_load_tasks.clear();
  1182. cleaning_tasks = false;
  1183. }
  1184. void ResourceLoader::load_path_remaps() {
  1185. if (!ProjectSettings::get_singleton()->has_setting("path_remap/remapped_paths")) {
  1186. return;
  1187. }
  1188. Vector<String> remaps = GLOBAL_GET("path_remap/remapped_paths");
  1189. int rc = remaps.size();
  1190. ERR_FAIL_COND(rc & 1); //must be even
  1191. const String *r = remaps.ptr();
  1192. for (int i = 0; i < rc; i += 2) {
  1193. path_remaps[r[i]] = r[i + 1];
  1194. }
  1195. }
  1196. void ResourceLoader::clear_path_remaps() {
  1197. path_remaps.clear();
  1198. }
  1199. void ResourceLoader::set_load_callback(ResourceLoadedCallback p_callback) {
  1200. _loaded_callback = p_callback;
  1201. }
  1202. ResourceLoadedCallback ResourceLoader::_loaded_callback = nullptr;
  1203. Ref<ResourceFormatLoader> ResourceLoader::_find_custom_resource_format_loader(const String &path) {
  1204. for (int i = 0; i < loader_count; ++i) {
  1205. if (loader[i]->get_script_instance() && loader[i]->get_script_instance()->get_script()->get_path() == path) {
  1206. return loader[i];
  1207. }
  1208. }
  1209. return Ref<ResourceFormatLoader>();
  1210. }
  1211. bool ResourceLoader::add_custom_resource_format_loader(const String &script_path) {
  1212. if (_find_custom_resource_format_loader(script_path).is_valid()) {
  1213. return false;
  1214. }
  1215. Ref<Resource> res = ResourceLoader::load(script_path);
  1216. ERR_FAIL_COND_V(res.is_null(), false);
  1217. ERR_FAIL_COND_V(!res->is_class("Script"), false);
  1218. Ref<Script> s = res;
  1219. StringName ibt = s->get_instance_base_type();
  1220. bool valid_type = ClassDB::is_parent_class(ibt, "ResourceFormatLoader");
  1221. ERR_FAIL_COND_V_MSG(!valid_type, false, vformat("Failed to add a custom resource loader, script '%s' does not inherit 'ResourceFormatLoader'.", script_path));
  1222. Object *obj = ClassDB::instantiate(ibt);
  1223. ERR_FAIL_NULL_V_MSG(obj, false, vformat("Failed to add a custom resource loader, cannot instantiate '%s'.", ibt));
  1224. Ref<ResourceFormatLoader> crl = Object::cast_to<ResourceFormatLoader>(obj);
  1225. crl->set_script(s);
  1226. ResourceLoader::add_resource_format_loader(crl);
  1227. return true;
  1228. }
  1229. void ResourceLoader::set_create_missing_resources_if_class_unavailable(bool p_enable) {
  1230. create_missing_resources_if_class_unavailable = p_enable;
  1231. }
  1232. void ResourceLoader::add_custom_loaders() {
  1233. // Custom loaders registration exploits global class names
  1234. String custom_loader_base_class = ResourceFormatLoader::get_class_static();
  1235. List<StringName> global_classes;
  1236. ScriptServer::get_global_class_list(&global_classes);
  1237. for (const StringName &class_name : global_classes) {
  1238. StringName base_class = ScriptServer::get_global_class_native_base(class_name);
  1239. if (base_class == custom_loader_base_class) {
  1240. String path = ScriptServer::get_global_class_path(class_name);
  1241. add_custom_resource_format_loader(path);
  1242. }
  1243. }
  1244. }
  1245. void ResourceLoader::remove_custom_loaders() {
  1246. Vector<Ref<ResourceFormatLoader>> custom_loaders;
  1247. for (int i = 0; i < loader_count; ++i) {
  1248. if (loader[i]->get_script_instance()) {
  1249. custom_loaders.push_back(loader[i]);
  1250. }
  1251. }
  1252. for (int i = 0; i < custom_loaders.size(); ++i) {
  1253. remove_resource_format_loader(custom_loaders[i]);
  1254. }
  1255. }
  1256. bool ResourceLoader::is_cleaning_tasks() {
  1257. MutexLock lock(thread_load_mutex);
  1258. return cleaning_tasks;
  1259. }
  1260. Vector<String> ResourceLoader::list_directory(const String &p_directory) {
  1261. RBSet<String> files_found;
  1262. Ref<DirAccess> dir = DirAccess::open(p_directory);
  1263. if (dir.is_null()) {
  1264. return Vector<String>();
  1265. }
  1266. Error err = dir->list_dir_begin();
  1267. if (err != OK) {
  1268. return Vector<String>();
  1269. }
  1270. String d = dir->get_next();
  1271. while (!d.is_empty()) {
  1272. bool recognized = false;
  1273. if (dir->current_is_dir()) {
  1274. if (d != "." && d != "..") {
  1275. d += "/";
  1276. recognized = true;
  1277. }
  1278. } else {
  1279. if (d.ends_with(".import") || d.ends_with(".remap") || d.ends_with(".uid")) {
  1280. d = d.substr(0, d.rfind_char('.'));
  1281. }
  1282. if (d.ends_with(".gdc")) {
  1283. d = d.substr(0, d.rfind_char('.'));
  1284. d += ".gd";
  1285. }
  1286. const String full_path = p_directory.path_join(d);
  1287. // Try all loaders and pick the first match for the type hint.
  1288. for (int i = 0; i < loader_count; i++) {
  1289. if (loader[i]->recognize_path(full_path)) {
  1290. recognized = true;
  1291. break;
  1292. }
  1293. }
  1294. }
  1295. if (recognized) {
  1296. files_found.insert(d);
  1297. }
  1298. d = dir->get_next();
  1299. }
  1300. Vector<String> ret;
  1301. for (const String &f : files_found) {
  1302. ret.push_back(f);
  1303. }
  1304. return ret;
  1305. }
  1306. void ResourceLoader::initialize() {}
  1307. void ResourceLoader::finalize() {}
  1308. ResourceLoadErrorNotify ResourceLoader::err_notify = nullptr;
  1309. DependencyErrorNotify ResourceLoader::dep_err_notify = nullptr;
  1310. bool ResourceLoader::create_missing_resources_if_class_unavailable = false;
  1311. bool ResourceLoader::abort_on_missing_resource = true;
  1312. bool ResourceLoader::timestamp_on_load = false;
  1313. thread_local int ResourceLoader::load_nesting = 0;
  1314. thread_local Vector<String> ResourceLoader::load_paths_stack;
  1315. thread_local HashMap<int, HashMap<String, Ref<Resource>>> ResourceLoader::res_ref_overrides;
  1316. thread_local ResourceLoader::ThreadLoadTask *ResourceLoader::curr_load_task = nullptr;
  1317. SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG> &_get_res_loader_mutex() {
  1318. return ResourceLoader::thread_load_mutex;
  1319. }
  1320. template <>
  1321. thread_local SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG>::TLSData SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG>::tls_data(_get_res_loader_mutex());
  1322. SafeBinaryMutex<ResourceLoader::BINARY_MUTEX_TAG> ResourceLoader::thread_load_mutex;
  1323. HashMap<String, ResourceLoader::ThreadLoadTask> ResourceLoader::thread_load_tasks;
  1324. bool ResourceLoader::cleaning_tasks = false;
  1325. HashMap<String, ResourceLoader::LoadToken *> ResourceLoader::user_load_tokens;
  1326. SelfList<Resource>::List ResourceLoader::remapped_list;
  1327. HashMap<String, Vector<String>> ResourceLoader::translation_remaps;
  1328. HashMap<String, String> ResourceLoader::path_remaps;
  1329. ResourceLoaderImport ResourceLoader::import = nullptr;