resource_loader.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. /*************************************************************************/
  2. /* resource_loader.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "resource_loader.h"
  31. #include "core/io/resource_importer.h"
  32. #include "core/os/file_access.h"
  33. #include "core/os/os.h"
  34. #include "core/path_remap.h"
  35. #include "core/print_string.h"
  36. #include "core/project_settings.h"
  37. #include "core/translation.h"
  38. #include "core/variant_parser.h"
  39. Ref<ResourceFormatLoader> ResourceLoader::loader[ResourceLoader::MAX_LOADERS];
  40. int ResourceLoader::loader_count = 0;
  41. Error ResourceInteractiveLoader::wait() {
  42. Error err = poll();
  43. while (err == OK) {
  44. err = poll();
  45. }
  46. return err;
  47. }
  48. ResourceInteractiveLoader::~ResourceInteractiveLoader() {
  49. if (path_loading != String()) {
  50. ResourceLoader::_remove_from_loading_map_and_thread(path_loading, path_loading_thread);
  51. }
  52. }
  53. bool ResourceFormatLoader::recognize_path(const String &p_path, const String &p_for_type) const {
  54. String extension = p_path.get_extension();
  55. List<String> extensions;
  56. if (p_for_type == String()) {
  57. get_recognized_extensions(&extensions);
  58. } else {
  59. get_recognized_extensions_for_type(p_for_type, &extensions);
  60. }
  61. for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
  62. if (E->get().nocasecmp_to(extension) == 0)
  63. return true;
  64. }
  65. return false;
  66. }
  67. bool ResourceFormatLoader::handles_type(const String &p_type) const {
  68. if (get_script_instance() && get_script_instance()->has_method("handles_type")) {
  69. // I guess custom loaders for custom resources should use "Resource"
  70. return get_script_instance()->call("handles_type", p_type);
  71. }
  72. return false;
  73. }
  74. String ResourceFormatLoader::get_resource_type(const String &p_path) const {
  75. if (get_script_instance() && get_script_instance()->has_method("get_resource_type")) {
  76. return get_script_instance()->call("get_resource_type", p_path);
  77. }
  78. return "";
  79. }
  80. void ResourceFormatLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
  81. if (p_type == "" || handles_type(p_type))
  82. get_recognized_extensions(p_extensions);
  83. }
  84. void ResourceLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) {
  85. for (int i = 0; i < loader_count; i++) {
  86. loader[i]->get_recognized_extensions_for_type(p_type, p_extensions);
  87. }
  88. }
  89. void ResourceInteractiveLoader::_bind_methods() {
  90. ClassDB::bind_method(D_METHOD("get_resource"), &ResourceInteractiveLoader::get_resource);
  91. ClassDB::bind_method(D_METHOD("poll"), &ResourceInteractiveLoader::poll);
  92. ClassDB::bind_method(D_METHOD("wait"), &ResourceInteractiveLoader::wait);
  93. ClassDB::bind_method(D_METHOD("get_stage"), &ResourceInteractiveLoader::get_stage);
  94. ClassDB::bind_method(D_METHOD("get_stage_count"), &ResourceInteractiveLoader::get_stage_count);
  95. }
  96. class ResourceInteractiveLoaderDefault : public ResourceInteractiveLoader {
  97. GDCLASS(ResourceInteractiveLoaderDefault, ResourceInteractiveLoader);
  98. public:
  99. Ref<Resource> resource;
  100. virtual void set_local_path(const String &p_local_path) { /*scene->set_filename(p_local_path);*/
  101. }
  102. virtual Ref<Resource> get_resource() { return resource; }
  103. virtual Error poll() { return ERR_FILE_EOF; }
  104. virtual int get_stage() const { return 1; }
  105. virtual int get_stage_count() const { return 1; }
  106. virtual void set_translation_remapped(bool p_remapped) { resource->set_as_translation_remapped(p_remapped); }
  107. ResourceInteractiveLoaderDefault() {}
  108. };
  109. bool ResourceFormatLoader::exists(const String &p_path) const {
  110. return FileAccess::exists(p_path); //by default just check file
  111. }
  112. void ResourceFormatLoader::get_recognized_extensions(List<String> *p_extensions) const {
  113. if (get_script_instance() && get_script_instance()->has_method("get_recognized_extensions")) {
  114. PoolStringArray exts = get_script_instance()->call("get_recognized_extensions");
  115. {
  116. PoolStringArray::Read r = exts.read();
  117. for (int i = 0; i < exts.size(); ++i) {
  118. p_extensions->push_back(r[i]);
  119. }
  120. }
  121. }
  122. }
  123. // Warning: Derived classes must override either `load` or `load_interactive`. The base code
  124. // here can trigger an infinite recursion otherwise, since `load` calls `load_interactive`
  125. // vice versa.
  126. Ref<ResourceInteractiveLoader> ResourceFormatLoader::load_interactive(const String &p_path, const String &p_original_path, Error *r_error) {
  127. // Warning: See previous note about the risk of infinite recursion.
  128. Ref<Resource> res = load(p_path, p_original_path, r_error);
  129. if (res.is_null()) {
  130. return Ref<ResourceInteractiveLoader>();
  131. }
  132. Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>(memnew(ResourceInteractiveLoaderDefault));
  133. ril->resource = res;
  134. return ril;
  135. }
  136. RES ResourceFormatLoader::load(const String &p_path, const String &p_original_path, Error *r_error) {
  137. // Check user-defined loader if there's any. Hard fail if it returns an error.
  138. if (get_script_instance() && get_script_instance()->has_method("load")) {
  139. Variant res = get_script_instance()->call("load", p_path, p_original_path);
  140. if (res.get_type() == Variant::INT) { // Error code, abort.
  141. if (r_error) {
  142. *r_error = (Error)res.operator int64_t();
  143. }
  144. return RES();
  145. } else { // Success, pass on result.
  146. if (r_error) {
  147. *r_error = OK;
  148. }
  149. return res;
  150. }
  151. }
  152. // Warning: See previous note about the risk of infinite recursion.
  153. Ref<ResourceInteractiveLoader> ril = load_interactive(p_path, p_original_path, r_error);
  154. if (!ril.is_valid())
  155. return RES();
  156. ril->set_local_path(p_original_path);
  157. while (true) {
  158. Error err = ril->poll();
  159. if (err == ERR_FILE_EOF) {
  160. if (r_error)
  161. *r_error = OK;
  162. return ril->get_resource();
  163. }
  164. if (r_error)
  165. *r_error = err;
  166. ERR_FAIL_COND_V_MSG(err != OK, RES(), "Failed to load resource '" + p_path + "'.");
  167. }
  168. }
  169. void ResourceFormatLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  170. if (get_script_instance() && get_script_instance()->has_method("get_dependencies")) {
  171. PoolStringArray deps = get_script_instance()->call("get_dependencies", p_path, p_add_types);
  172. {
  173. PoolStringArray::Read r = deps.read();
  174. for (int i = 0; i < deps.size(); ++i) {
  175. p_dependencies->push_back(r[i]);
  176. }
  177. }
  178. }
  179. }
  180. Error ResourceFormatLoader::rename_dependencies(const String &p_path, const Map<String, String> &p_map) {
  181. if (get_script_instance() && get_script_instance()->has_method("rename_dependencies")) {
  182. Dictionary deps_dict;
  183. for (Map<String, String>::Element *E = p_map.front(); E; E = E->next()) {
  184. deps_dict[E->key()] = E->value();
  185. }
  186. int64_t res = get_script_instance()->call("rename_dependencies", deps_dict);
  187. return (Error)res;
  188. }
  189. return OK;
  190. }
  191. void ResourceFormatLoader::_bind_methods() {
  192. {
  193. MethodInfo info = MethodInfo(Variant::NIL, "load", PropertyInfo(Variant::STRING, "path"), PropertyInfo(Variant::STRING, "original_path"));
  194. info.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  195. ClassDB::add_virtual_method(get_class_static(), info);
  196. }
  197. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::POOL_STRING_ARRAY, "get_recognized_extensions"));
  198. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::BOOL, "handles_type", PropertyInfo(Variant::STRING, "typename")));
  199. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::STRING, "get_resource_type", PropertyInfo(Variant::STRING, "path")));
  200. ClassDB::add_virtual_method(get_class_static(), MethodInfo("get_dependencies", PropertyInfo(Variant::STRING, "path"), PropertyInfo(Variant::STRING, "add_types")));
  201. ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::INT, "rename_dependencies", PropertyInfo(Variant::STRING, "path"), PropertyInfo(Variant::STRING, "renames")));
  202. }
  203. ///////////////////////////////////
  204. RES ResourceLoader::_load(const String &p_path, const String &p_original_path, const String &p_type_hint, bool p_no_cache, Error *r_error) {
  205. bool found = false;
  206. // Try all loaders and pick the first match for the type hint
  207. for (int i = 0; i < loader_count; i++) {
  208. if (!loader[i]->recognize_path(p_path, p_type_hint)) {
  209. continue;
  210. }
  211. found = true;
  212. RES res = loader[i]->load(p_path, p_original_path != String() ? p_original_path : p_path, r_error);
  213. if (res.is_null()) {
  214. continue;
  215. }
  216. return res;
  217. }
  218. ERR_FAIL_COND_V_MSG(found, RES(),
  219. vformat("Failed loading resource: %s. Make sure resources have been imported by opening the project in the editor at least once.", p_path));
  220. #ifdef TOOLS_ENABLED
  221. FileAccessRef file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES);
  222. ERR_FAIL_COND_V_MSG(!file_check->file_exists(p_path), RES(), "Resource file not found: " + p_path + ".");
  223. #endif
  224. ERR_FAIL_V_MSG(RES(), "No loader found for resource: " + p_path + ".");
  225. }
  226. bool ResourceLoader::_add_to_loading_map(const String &p_path) {
  227. bool success;
  228. loading_map_mutex.lock();
  229. LoadingMapKey key;
  230. key.path = p_path;
  231. key.thread = Thread::get_caller_id();
  232. if (loading_map.has(key)) {
  233. success = false;
  234. } else {
  235. loading_map[key] = true;
  236. success = true;
  237. }
  238. loading_map_mutex.unlock();
  239. return success;
  240. }
  241. void ResourceLoader::_remove_from_loading_map(const String &p_path) {
  242. loading_map_mutex.lock();
  243. LoadingMapKey key;
  244. key.path = p_path;
  245. key.thread = Thread::get_caller_id();
  246. loading_map.erase(key);
  247. loading_map_mutex.unlock();
  248. }
  249. void ResourceLoader::_remove_from_loading_map_and_thread(const String &p_path, Thread::ID p_thread) {
  250. loading_map_mutex.lock();
  251. LoadingMapKey key;
  252. key.path = p_path;
  253. key.thread = p_thread;
  254. loading_map.erase(key);
  255. loading_map_mutex.unlock();
  256. }
  257. RES ResourceLoader::load(const String &p_path, const String &p_type_hint, bool p_no_cache, Error *r_error) {
  258. if (r_error)
  259. *r_error = ERR_CANT_OPEN;
  260. String local_path;
  261. if (p_path.is_rel_path())
  262. local_path = "res://" + p_path;
  263. else
  264. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  265. if (!p_no_cache) {
  266. {
  267. bool success = _add_to_loading_map(local_path);
  268. ERR_FAIL_COND_V_MSG(!success, RES(), "Resource: '" + local_path + "' is already being loaded. Cyclic reference?");
  269. }
  270. //lock first if possible
  271. ResourceCache::lock.read_lock();
  272. //get ptr
  273. Resource **rptr = ResourceCache::resources.getptr(local_path);
  274. if (rptr) {
  275. RES res(*rptr);
  276. //it is possible this resource was just freed in a thread. If so, this referencing will not work and resource is considered not cached
  277. if (res.is_valid()) {
  278. //referencing is fine
  279. if (r_error)
  280. *r_error = OK;
  281. ResourceCache::lock.read_unlock();
  282. _remove_from_loading_map(local_path);
  283. return res;
  284. }
  285. }
  286. ResourceCache::lock.read_unlock();
  287. }
  288. bool xl_remapped = false;
  289. String path = _path_remap(local_path, &xl_remapped);
  290. if (path == "") {
  291. if (!p_no_cache) {
  292. _remove_from_loading_map(local_path);
  293. }
  294. ERR_FAIL_V_MSG(RES(), "Remapping '" + local_path + "' failed.");
  295. }
  296. print_verbose("Loading resource: " + path);
  297. RES res = _load(path, local_path, p_type_hint, p_no_cache, r_error);
  298. if (res.is_null()) {
  299. if (!p_no_cache) {
  300. _remove_from_loading_map(local_path);
  301. }
  302. return RES();
  303. }
  304. if (!p_no_cache)
  305. res->set_path(local_path);
  306. if (xl_remapped)
  307. res->set_as_translation_remapped(true);
  308. #ifdef TOOLS_ENABLED
  309. res->set_edited(false);
  310. if (timestamp_on_load) {
  311. uint64_t mt = FileAccess::get_modified_time(path);
  312. //printf("mt %s: %lli\n",remapped_path.utf8().get_data(),mt);
  313. res->set_last_modified_time(mt);
  314. }
  315. #endif
  316. if (!p_no_cache) {
  317. _remove_from_loading_map(local_path);
  318. }
  319. if (_loaded_callback) {
  320. _loaded_callback(res, p_path);
  321. }
  322. return res;
  323. }
  324. bool ResourceLoader::exists(const String &p_path, const String &p_type_hint) {
  325. String local_path;
  326. if (p_path.is_rel_path())
  327. local_path = "res://" + p_path;
  328. else
  329. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  330. if (ResourceCache::has(local_path)) {
  331. return true; // If cached, it probably exists
  332. }
  333. bool xl_remapped = false;
  334. String path = _path_remap(local_path, &xl_remapped);
  335. // Try all loaders and pick the first match for the type hint
  336. for (int i = 0; i < loader_count; i++) {
  337. if (!loader[i]->recognize_path(path, p_type_hint)) {
  338. continue;
  339. }
  340. if (loader[i]->exists(path))
  341. return true;
  342. }
  343. return false;
  344. }
  345. Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_path, const String &p_type_hint, bool p_no_cache, Error *r_error) {
  346. if (r_error)
  347. *r_error = ERR_CANT_OPEN;
  348. String local_path;
  349. if (p_path.is_rel_path())
  350. local_path = "res://" + p_path;
  351. else
  352. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  353. if (!p_no_cache) {
  354. bool success = _add_to_loading_map(local_path);
  355. ERR_FAIL_COND_V_MSG(!success, RES(), "Resource: '" + local_path + "' is already being loaded. Cyclic reference?");
  356. if (ResourceCache::has(local_path)) {
  357. print_verbose("Loading resource: " + local_path + " (cached)");
  358. Ref<Resource> res_cached = ResourceCache::get(local_path);
  359. Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>(memnew(ResourceInteractiveLoaderDefault));
  360. ril->resource = res_cached;
  361. ril->path_loading = local_path;
  362. ril->path_loading_thread = Thread::get_caller_id();
  363. return ril;
  364. }
  365. }
  366. bool xl_remapped = false;
  367. String path = _path_remap(local_path, &xl_remapped);
  368. if (path == "") {
  369. if (!p_no_cache) {
  370. _remove_from_loading_map(local_path);
  371. }
  372. ERR_FAIL_V_MSG(RES(), "Remapping '" + local_path + "' failed.");
  373. }
  374. print_verbose("Loading resource: " + path);
  375. bool found = false;
  376. for (int i = 0; i < loader_count; i++) {
  377. if (!loader[i]->recognize_path(path, p_type_hint))
  378. continue;
  379. found = true;
  380. Ref<ResourceInteractiveLoader> ril = loader[i]->load_interactive(path, local_path, r_error);
  381. if (ril.is_null())
  382. continue;
  383. if (!p_no_cache) {
  384. ril->set_local_path(local_path);
  385. ril->path_loading = local_path;
  386. ril->path_loading_thread = Thread::get_caller_id();
  387. }
  388. if (xl_remapped)
  389. ril->set_translation_remapped(true);
  390. return ril;
  391. }
  392. if (!p_no_cache) {
  393. _remove_from_loading_map(local_path);
  394. }
  395. ERR_FAIL_COND_V_MSG(found, Ref<ResourceInteractiveLoader>(), "Failed loading resource: " + path + ".");
  396. ERR_FAIL_V_MSG(Ref<ResourceInteractiveLoader>(), "No loader found for resource: " + path + ".");
  397. }
  398. void ResourceLoader::add_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader, bool p_at_front) {
  399. ERR_FAIL_COND(p_format_loader.is_null());
  400. ERR_FAIL_COND(loader_count >= MAX_LOADERS);
  401. if (p_at_front) {
  402. for (int i = loader_count; i > 0; i--) {
  403. loader[i] = loader[i - 1];
  404. }
  405. loader[0] = p_format_loader;
  406. loader_count++;
  407. } else {
  408. loader[loader_count++] = p_format_loader;
  409. }
  410. }
  411. void ResourceLoader::remove_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader) {
  412. ERR_FAIL_COND(p_format_loader.is_null());
  413. // Find loader
  414. int i = 0;
  415. for (; i < loader_count; ++i) {
  416. if (loader[i] == p_format_loader)
  417. break;
  418. }
  419. ERR_FAIL_COND(i >= loader_count); // Not found
  420. // Shift next loaders up
  421. for (; i < loader_count - 1; ++i) {
  422. loader[i] = loader[i + 1];
  423. }
  424. loader[loader_count - 1].unref();
  425. --loader_count;
  426. }
  427. int ResourceLoader::get_import_order(const String &p_path) {
  428. String path = _path_remap(p_path);
  429. String local_path;
  430. if (path.is_rel_path())
  431. local_path = "res://" + path;
  432. else
  433. local_path = ProjectSettings::get_singleton()->localize_path(path);
  434. for (int i = 0; i < loader_count; i++) {
  435. if (!loader[i]->recognize_path(local_path))
  436. continue;
  437. /*
  438. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  439. continue;
  440. */
  441. return loader[i]->get_import_order(p_path);
  442. }
  443. return 0;
  444. }
  445. String ResourceLoader::get_import_group_file(const String &p_path) {
  446. String path = _path_remap(p_path);
  447. String local_path;
  448. if (path.is_rel_path())
  449. local_path = "res://" + path;
  450. else
  451. local_path = ProjectSettings::get_singleton()->localize_path(path);
  452. for (int i = 0; i < loader_count; i++) {
  453. if (!loader[i]->recognize_path(local_path))
  454. continue;
  455. /*
  456. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  457. continue;
  458. */
  459. return loader[i]->get_import_group_file(p_path);
  460. }
  461. return String(); //not found
  462. }
  463. bool ResourceLoader::is_import_valid(const String &p_path) {
  464. String path = _path_remap(p_path);
  465. String local_path;
  466. if (path.is_rel_path())
  467. local_path = "res://" + path;
  468. else
  469. local_path = ProjectSettings::get_singleton()->localize_path(path);
  470. for (int i = 0; i < loader_count; i++) {
  471. if (!loader[i]->recognize_path(local_path))
  472. continue;
  473. /*
  474. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  475. continue;
  476. */
  477. return loader[i]->is_import_valid(p_path);
  478. }
  479. return false; //not found
  480. }
  481. bool ResourceLoader::is_imported(const String &p_path) {
  482. String path = _path_remap(p_path);
  483. String local_path;
  484. if (path.is_rel_path())
  485. local_path = "res://" + path;
  486. else
  487. local_path = ProjectSettings::get_singleton()->localize_path(path);
  488. for (int i = 0; i < loader_count; i++) {
  489. if (!loader[i]->recognize_path(local_path))
  490. continue;
  491. /*
  492. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  493. continue;
  494. */
  495. return loader[i]->is_imported(p_path);
  496. }
  497. return false; //not found
  498. }
  499. void ResourceLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
  500. String path = _path_remap(p_path);
  501. String local_path;
  502. if (path.is_rel_path())
  503. local_path = "res://" + path;
  504. else
  505. local_path = ProjectSettings::get_singleton()->localize_path(path);
  506. for (int i = 0; i < loader_count; i++) {
  507. if (!loader[i]->recognize_path(local_path))
  508. continue;
  509. /*
  510. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  511. continue;
  512. */
  513. loader[i]->get_dependencies(local_path, p_dependencies, p_add_types);
  514. }
  515. }
  516. Error ResourceLoader::rename_dependencies(const String &p_path, const Map<String, String> &p_map) {
  517. String path = _path_remap(p_path);
  518. String local_path;
  519. if (path.is_rel_path())
  520. local_path = "res://" + path;
  521. else
  522. local_path = ProjectSettings::get_singleton()->localize_path(path);
  523. for (int i = 0; i < loader_count; i++) {
  524. if (!loader[i]->recognize_path(local_path))
  525. continue;
  526. /*
  527. if (p_type_hint!="" && !loader[i]->handles_type(p_type_hint))
  528. continue;
  529. */
  530. return loader[i]->rename_dependencies(local_path, p_map);
  531. }
  532. return OK; // ??
  533. }
  534. String ResourceLoader::get_resource_type(const String &p_path) {
  535. String local_path;
  536. if (p_path.is_rel_path())
  537. local_path = "res://" + p_path;
  538. else
  539. local_path = ProjectSettings::get_singleton()->localize_path(p_path);
  540. for (int i = 0; i < loader_count; i++) {
  541. String result = loader[i]->get_resource_type(local_path);
  542. if (result != "")
  543. return result;
  544. }
  545. return "";
  546. }
  547. String ResourceLoader::_path_remap(const String &p_path, bool *r_translation_remapped) {
  548. String new_path = p_path;
  549. if (translation_remaps.has(p_path)) {
  550. // translation_remaps has the following format:
  551. // { "res://path.png": PoolStringArray( "res://path-ru.png:ru", "res://path-de.png:de" ) }
  552. // To find the path of the remapped resource, we extract the locale name after
  553. // the last ':' to match the project locale.
  554. // We also fall back in case of regional locales as done in TranslationServer::translate
  555. // (e.g. 'ru_RU' -> 'ru' if the former has no specific mapping).
  556. String locale = TranslationServer::get_singleton()->get_locale();
  557. ERR_FAIL_COND_V_MSG(locale.length() < 2, p_path, "Could not remap path '" + p_path + "' for translation as configured locale '" + locale + "' is invalid.");
  558. String lang = TranslationServer::get_language_code(locale);
  559. Vector<String> &res_remaps = *translation_remaps.getptr(new_path);
  560. bool near_match = false;
  561. for (int i = 0; i < res_remaps.size(); i++) {
  562. int split = res_remaps[i].find_last(":");
  563. if (split == -1) {
  564. continue;
  565. }
  566. String l = res_remaps[i].right(split + 1).strip_edges();
  567. if (l == locale) { // Exact match.
  568. new_path = res_remaps[i].left(split);
  569. break;
  570. } else if (near_match) {
  571. continue; // Already found near match, keep going for potential exact match.
  572. }
  573. // No exact match (e.g. locale 'ru_RU' but remap is 'ru'), let's look further
  574. // for a near match (same language code, i.e. first 2 or 3 letters before
  575. // regional code, if included).
  576. if (TranslationServer::get_language_code(l) == lang) {
  577. // Language code matches, that's a near match. Keep looking for exact match.
  578. near_match = true;
  579. new_path = res_remaps[i].left(split);
  580. continue;
  581. }
  582. }
  583. if (r_translation_remapped) {
  584. *r_translation_remapped = true;
  585. }
  586. }
  587. if (path_remaps.has(new_path)) {
  588. new_path = path_remaps[new_path];
  589. }
  590. if (new_path == p_path) { // Did not remap.
  591. // Try file remap.
  592. Error err;
  593. FileAccess *f = FileAccess::open(p_path + ".remap", FileAccess::READ, &err);
  594. if (f) {
  595. VariantParser::StreamFile stream;
  596. stream.f = f;
  597. String assign;
  598. Variant value;
  599. VariantParser::Tag next_tag;
  600. int lines = 0;
  601. String error_text;
  602. while (true) {
  603. assign = Variant();
  604. next_tag.fields.clear();
  605. next_tag.name = String();
  606. err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, NULL, true);
  607. if (err == ERR_FILE_EOF) {
  608. break;
  609. } else if (err != OK) {
  610. ERR_PRINTS("Parse error: " + p_path + ".remap:" + itos(lines) + " error: " + error_text + ".");
  611. break;
  612. }
  613. if (assign == "path") {
  614. new_path = value;
  615. break;
  616. } else if (next_tag.name != "remap") {
  617. break;
  618. }
  619. }
  620. memdelete(f);
  621. }
  622. }
  623. return new_path;
  624. }
  625. String ResourceLoader::import_remap(const String &p_path) {
  626. if (ResourceFormatImporter::get_singleton()->recognize_path(p_path)) {
  627. return ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_path);
  628. }
  629. return p_path;
  630. }
  631. String ResourceLoader::path_remap(const String &p_path) {
  632. return _path_remap(p_path);
  633. }
  634. void ResourceLoader::reload_translation_remaps() {
  635. ResourceCache::lock.read_lock();
  636. List<Resource *> to_reload;
  637. SelfList<Resource> *E = remapped_list.first();
  638. while (E) {
  639. to_reload.push_back(E->self());
  640. E = E->next();
  641. }
  642. ResourceCache::lock.read_unlock();
  643. //now just make sure to not delete any of these resources while changing locale..
  644. while (to_reload.front()) {
  645. to_reload.front()->get()->reload_from_file();
  646. to_reload.pop_front();
  647. }
  648. }
  649. void ResourceLoader::load_translation_remaps() {
  650. if (!ProjectSettings::get_singleton()->has_setting("locale/translation_remaps"))
  651. return;
  652. Dictionary remaps = ProjectSettings::get_singleton()->get("locale/translation_remaps");
  653. List<Variant> keys;
  654. remaps.get_key_list(&keys);
  655. for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
  656. Array langs = remaps[E->get()];
  657. Vector<String> lang_remaps;
  658. lang_remaps.resize(langs.size());
  659. for (int i = 0; i < langs.size(); i++) {
  660. lang_remaps.write[i] = langs[i];
  661. }
  662. translation_remaps[String(E->get())] = lang_remaps;
  663. }
  664. }
  665. void ResourceLoader::clear_translation_remaps() {
  666. translation_remaps.clear();
  667. while (remapped_list.first() != nullptr) {
  668. remapped_list.remove(remapped_list.first());
  669. }
  670. }
  671. void ResourceLoader::load_path_remaps() {
  672. if (!ProjectSettings::get_singleton()->has_setting("path_remap/remapped_paths"))
  673. return;
  674. PoolVector<String> remaps = ProjectSettings::get_singleton()->get("path_remap/remapped_paths");
  675. int rc = remaps.size();
  676. ERR_FAIL_COND(rc & 1); //must be even
  677. PoolVector<String>::Read r = remaps.read();
  678. for (int i = 0; i < rc; i += 2) {
  679. path_remaps[r[i]] = r[i + 1];
  680. }
  681. }
  682. void ResourceLoader::clear_path_remaps() {
  683. path_remaps.clear();
  684. }
  685. void ResourceLoader::set_load_callback(ResourceLoadedCallback p_callback) {
  686. _loaded_callback = p_callback;
  687. }
  688. ResourceLoadedCallback ResourceLoader::_loaded_callback = NULL;
  689. Ref<ResourceFormatLoader> ResourceLoader::_find_custom_resource_format_loader(String path) {
  690. for (int i = 0; i < loader_count; ++i) {
  691. if (loader[i]->get_script_instance() && loader[i]->get_script_instance()->get_script()->get_path() == path) {
  692. return loader[i];
  693. }
  694. }
  695. return Ref<ResourceFormatLoader>();
  696. }
  697. bool ResourceLoader::add_custom_resource_format_loader(String script_path) {
  698. if (_find_custom_resource_format_loader(script_path).is_valid())
  699. return false;
  700. Ref<Resource> res = ResourceLoader::load(script_path);
  701. ERR_FAIL_COND_V(res.is_null(), false);
  702. ERR_FAIL_COND_V(!res->is_class("Script"), false);
  703. Ref<Script> s = res;
  704. StringName ibt = s->get_instance_base_type();
  705. bool valid_type = ClassDB::is_parent_class(ibt, "ResourceFormatLoader");
  706. ERR_FAIL_COND_V_MSG(!valid_type, false, "Script does not inherit a CustomResourceLoader: " + script_path + ".");
  707. Object *obj = ClassDB::instance(ibt);
  708. ERR_FAIL_COND_V_MSG(obj == NULL, false, "Cannot instance script as custom resource loader, expected 'ResourceFormatLoader' inheritance, got: " + String(ibt) + ".");
  709. Ref<ResourceFormatLoader> crl = Object::cast_to<ResourceFormatLoader>(obj);
  710. crl->set_script(s.get_ref_ptr());
  711. ResourceLoader::add_resource_format_loader(crl);
  712. return true;
  713. }
  714. void ResourceLoader::remove_custom_resource_format_loader(String script_path) {
  715. Ref<ResourceFormatLoader> custom_loader = _find_custom_resource_format_loader(script_path);
  716. if (custom_loader.is_valid())
  717. remove_resource_format_loader(custom_loader);
  718. }
  719. void ResourceLoader::add_custom_loaders() {
  720. // Custom loaders registration exploits global class names
  721. String custom_loader_base_class = ResourceFormatLoader::get_class_static();
  722. List<StringName> global_classes;
  723. ScriptServer::get_global_class_list(&global_classes);
  724. for (List<StringName>::Element *E = global_classes.front(); E; E = E->next()) {
  725. StringName class_name = E->get();
  726. StringName base_class = ScriptServer::get_global_class_native_base(class_name);
  727. if (base_class == custom_loader_base_class) {
  728. String path = ScriptServer::get_global_class_path(class_name);
  729. add_custom_resource_format_loader(path);
  730. }
  731. }
  732. }
  733. void ResourceLoader::remove_custom_loaders() {
  734. Vector<Ref<ResourceFormatLoader> > custom_loaders;
  735. for (int i = 0; i < loader_count; ++i) {
  736. if (loader[i]->get_script_instance()) {
  737. custom_loaders.push_back(loader[i]);
  738. }
  739. }
  740. for (int i = 0; i < custom_loaders.size(); ++i) {
  741. remove_resource_format_loader(custom_loaders[i]);
  742. }
  743. }
  744. Mutex ResourceLoader::loading_map_mutex;
  745. HashMap<ResourceLoader::LoadingMapKey, int, ResourceLoader::LoadingMapKeyHasher> ResourceLoader::loading_map;
  746. void ResourceLoader::finalize() {
  747. #ifndef NO_THREADS
  748. const LoadingMapKey *K = NULL;
  749. while ((K = loading_map.next(K))) {
  750. ERR_PRINTS("Exited while resource is being loaded: " + K->path);
  751. }
  752. loading_map.clear();
  753. #endif
  754. }
  755. ResourceLoadErrorNotify ResourceLoader::err_notify = NULL;
  756. void *ResourceLoader::err_notify_ud = NULL;
  757. DependencyErrorNotify ResourceLoader::dep_err_notify = NULL;
  758. void *ResourceLoader::dep_err_notify_ud = NULL;
  759. bool ResourceLoader::abort_on_missing_resource = true;
  760. bool ResourceLoader::timestamp_on_load = false;
  761. SelfList<Resource>::List ResourceLoader::remapped_list;
  762. HashMap<String, Vector<String> > ResourceLoader::translation_remaps;
  763. HashMap<String, String> ResourceLoader::path_remaps;
  764. ResourceLoaderImport ResourceLoader::import = NULL;