2
0

resource_loader.cpp 29 KB

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