resource_loader.cpp 31 KB

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