resource_loader.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. /**************************************************************************/
  2. /* resource_loader.h */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #ifndef RESOURCE_LOADER_H
  31. #define RESOURCE_LOADER_H
  32. #include "core/io/resource.h"
  33. #include "core/object/gdvirtual.gen.inc"
  34. #include "core/object/worker_thread_pool.h"
  35. #include "core/os/semaphore.h"
  36. #include "core/os/thread.h"
  37. class ConditionVariable;
  38. template <int Tag>
  39. class SafeBinaryMutex;
  40. class ResourceFormatLoader : public RefCounted {
  41. GDCLASS(ResourceFormatLoader, RefCounted);
  42. public:
  43. enum CacheMode {
  44. CACHE_MODE_IGNORE,
  45. CACHE_MODE_REUSE,
  46. CACHE_MODE_REPLACE,
  47. CACHE_MODE_IGNORE_DEEP,
  48. CACHE_MODE_REPLACE_DEEP,
  49. };
  50. protected:
  51. static void _bind_methods();
  52. GDVIRTUAL0RC(Vector<String>, _get_recognized_extensions)
  53. GDVIRTUAL2RC(bool, _recognize_path, String, StringName)
  54. GDVIRTUAL1RC(bool, _handles_type, StringName)
  55. GDVIRTUAL1RC(String, _get_resource_type, String)
  56. GDVIRTUAL1RC(String, _get_resource_script_class, String)
  57. GDVIRTUAL1RC(ResourceUID::ID, _get_resource_uid, String)
  58. GDVIRTUAL2RC(Vector<String>, _get_dependencies, String, bool)
  59. GDVIRTUAL1RC(Vector<String>, _get_classes_used, String)
  60. GDVIRTUAL2RC(Error, _rename_dependencies, String, Dictionary)
  61. GDVIRTUAL1RC(bool, _exists, String)
  62. GDVIRTUAL4RC(Variant, _load, String, String, bool, int)
  63. public:
  64. virtual Ref<Resource> load(const String &p_path, const String &p_original_path = "", Error *r_error = nullptr, bool p_use_sub_threads = false, float *r_progress = nullptr, CacheMode p_cache_mode = CACHE_MODE_REUSE);
  65. virtual bool exists(const String &p_path) const;
  66. virtual void get_recognized_extensions(List<String> *p_extensions) const;
  67. virtual void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const;
  68. virtual bool recognize_path(const String &p_path, const String &p_for_type = String()) const;
  69. virtual bool handles_type(const String &p_type) const;
  70. virtual void get_classes_used(const String &p_path, HashSet<StringName> *r_classes);
  71. virtual String get_resource_type(const String &p_path) const;
  72. virtual String get_resource_script_class(const String &p_path) const;
  73. virtual ResourceUID::ID get_resource_uid(const String &p_path) const;
  74. virtual void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false);
  75. virtual Error rename_dependencies(const String &p_path, const HashMap<String, String> &p_map);
  76. virtual bool is_import_valid(const String &p_path) const { return true; }
  77. virtual bool is_imported(const String &p_path) const { return false; }
  78. virtual int get_import_order(const String &p_path) const { return 0; }
  79. virtual String get_import_group_file(const String &p_path) const { return ""; } //no group
  80. virtual ~ResourceFormatLoader() {}
  81. };
  82. VARIANT_ENUM_CAST(ResourceFormatLoader::CacheMode)
  83. typedef void (*ResourceLoadErrorNotify)(const String &p_text);
  84. typedef void (*DependencyErrorNotify)(const String &p_loading, const String &p_which, const String &p_type);
  85. typedef Error (*ResourceLoaderImport)(const String &p_path);
  86. typedef void (*ResourceLoadedCallback)(Ref<Resource> p_resource, const String &p_path);
  87. class ResourceLoader {
  88. friend class LoadToken;
  89. enum {
  90. MAX_LOADERS = 64
  91. };
  92. struct ThreadLoadTask;
  93. public:
  94. enum ThreadLoadStatus {
  95. THREAD_LOAD_INVALID_RESOURCE,
  96. THREAD_LOAD_IN_PROGRESS,
  97. THREAD_LOAD_FAILED,
  98. THREAD_LOAD_LOADED
  99. };
  100. enum LoadThreadMode {
  101. LOAD_THREAD_FROM_CURRENT,
  102. LOAD_THREAD_SPAWN_SINGLE,
  103. LOAD_THREAD_DISTRIBUTE,
  104. };
  105. struct LoadToken : public RefCounted {
  106. String local_path;
  107. String user_path;
  108. uint32_t user_rc = 0; // Having user RC implies regular RC incremented in one, until the user RC reaches zero.
  109. ThreadLoadTask *task_if_unregistered = nullptr;
  110. void clear();
  111. virtual ~LoadToken();
  112. };
  113. static const int BINARY_MUTEX_TAG = 1;
  114. static Ref<LoadToken> _load_start(const String &p_path, const String &p_type_hint, LoadThreadMode p_thread_mode, ResourceFormatLoader::CacheMode p_cache_mode, bool p_for_user = false);
  115. static Ref<Resource> _load_complete(LoadToken &p_load_token, Error *r_error);
  116. private:
  117. static LoadToken *_load_threaded_request_reuse_user_token(const String &p_path);
  118. static void _load_threaded_request_setup_user_token(LoadToken *p_token, const String &p_path);
  119. static Ref<Resource> _load_complete_inner(LoadToken &p_load_token, Error *r_error, MutexLock<SafeBinaryMutex<BINARY_MUTEX_TAG>> &p_thread_load_lock);
  120. static Ref<ResourceFormatLoader> loader[MAX_LOADERS];
  121. static int loader_count;
  122. static bool timestamp_on_load;
  123. static void *err_notify_ud;
  124. static ResourceLoadErrorNotify err_notify;
  125. static void *dep_err_notify_ud;
  126. static DependencyErrorNotify dep_err_notify;
  127. static bool abort_on_missing_resource;
  128. static bool create_missing_resources_if_class_unavailable;
  129. static HashMap<String, Vector<String>> translation_remaps;
  130. static HashMap<String, String> path_remaps;
  131. static String _path_remap(const String &p_path, bool *r_translation_remapped = nullptr);
  132. friend class Resource;
  133. static SelfList<Resource>::List remapped_list;
  134. friend class ResourceFormatImporter;
  135. static Ref<Resource> _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);
  136. static ResourceLoadedCallback _loaded_callback;
  137. static Ref<ResourceFormatLoader> _find_custom_resource_format_loader(const String &path);
  138. struct ThreadLoadTask {
  139. WorkerThreadPool::TaskID task_id = 0; // Used if run on a worker thread from the pool.
  140. Thread::ID thread_id = 0; // Used if running on an user thread (e.g., simple non-threaded load).
  141. bool awaited = false; // If it's in the pool, this helps not awaiting from more than one dependent thread.
  142. ConditionVariable *cond_var = nullptr; // In not in the worker pool or already awaiting, this is used as a secondary awaiting mechanism.
  143. uint32_t awaiters_count = 0;
  144. bool need_wait = true;
  145. LoadToken *load_token = nullptr;
  146. String local_path;
  147. String type_hint;
  148. float progress = 0.0f;
  149. float max_reported_progress = 0.0f;
  150. uint64_t last_progress_check_main_thread_frame = UINT64_MAX;
  151. ThreadLoadStatus status = THREAD_LOAD_IN_PROGRESS;
  152. ResourceFormatLoader::CacheMode cache_mode = ResourceFormatLoader::CACHE_MODE_REUSE;
  153. Error error = OK;
  154. Ref<Resource> resource;
  155. bool use_sub_threads = false;
  156. HashSet<String> sub_tasks;
  157. struct ResourceChangedConnection {
  158. Resource *source = nullptr;
  159. Callable callable;
  160. uint32_t flags = 0;
  161. };
  162. LocalVector<ResourceChangedConnection> resource_changed_connections;
  163. };
  164. static void _run_load_task(void *p_userdata);
  165. static thread_local int load_nesting;
  166. static thread_local HashMap<int, HashMap<String, Ref<Resource>>> res_ref_overrides; // Outermost key is nesting level.
  167. static thread_local Vector<String> load_paths_stack;
  168. static thread_local ThreadLoadTask *curr_load_task;
  169. static SafeBinaryMutex<BINARY_MUTEX_TAG> thread_load_mutex;
  170. friend SafeBinaryMutex<BINARY_MUTEX_TAG> &_get_res_loader_mutex();
  171. static HashMap<String, ThreadLoadTask> thread_load_tasks;
  172. static bool cleaning_tasks;
  173. static HashMap<String, LoadToken *> user_load_tokens;
  174. static float _dependency_get_progress(const String &p_path);
  175. static bool _ensure_load_progress();
  176. public:
  177. static Error load_threaded_request(const String &p_path, const String &p_type_hint = "", bool p_use_sub_threads = false, ResourceFormatLoader::CacheMode p_cache_mode = ResourceFormatLoader::CACHE_MODE_REUSE);
  178. static ThreadLoadStatus load_threaded_get_status(const String &p_path, float *r_progress = nullptr);
  179. static Ref<Resource> load_threaded_get(const String &p_path, Error *r_error = nullptr);
  180. static bool is_within_load() { return load_nesting > 0; };
  181. static void resource_changed_connect(Resource *p_source, const Callable &p_callable, uint32_t p_flags);
  182. static void resource_changed_disconnect(Resource *p_source, const Callable &p_callable);
  183. static void resource_changed_emit(Resource *p_source);
  184. static Ref<Resource> load(const String &p_path, const String &p_type_hint = "", ResourceFormatLoader::CacheMode p_cache_mode = ResourceFormatLoader::CACHE_MODE_REUSE, Error *r_error = nullptr);
  185. static bool exists(const String &p_path, const String &p_type_hint = "");
  186. static void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions);
  187. static void add_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader, bool p_at_front = false);
  188. static void remove_resource_format_loader(Ref<ResourceFormatLoader> p_format_loader);
  189. static void get_classes_used(const String &p_path, HashSet<StringName> *r_classes);
  190. static String get_resource_type(const String &p_path);
  191. static String get_resource_script_class(const String &p_path);
  192. static ResourceUID::ID get_resource_uid(const String &p_path);
  193. static void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false);
  194. static Error rename_dependencies(const String &p_path, const HashMap<String, String> &p_map);
  195. static bool is_import_valid(const String &p_path);
  196. static String get_import_group_file(const String &p_path);
  197. static bool is_imported(const String &p_path);
  198. static int get_import_order(const String &p_path);
  199. static void set_timestamp_on_load(bool p_timestamp) { timestamp_on_load = p_timestamp; }
  200. static bool get_timestamp_on_load() { return timestamp_on_load; }
  201. // Loaders can safely use this regardless which thread they are running on.
  202. static void notify_load_error(const String &p_err) {
  203. if (err_notify) {
  204. MessageQueue::get_main_singleton()->push_callable(callable_mp_static(err_notify).bind(p_err));
  205. }
  206. }
  207. static void set_error_notify_func(ResourceLoadErrorNotify p_err_notify) {
  208. err_notify = p_err_notify;
  209. }
  210. // Loaders can safely use this regardless which thread they are running on.
  211. static void notify_dependency_error(const String &p_path, const String &p_dependency, const String &p_type) {
  212. if (dep_err_notify) {
  213. if (Thread::get_caller_id() == Thread::get_main_id()) {
  214. dep_err_notify(p_path, p_dependency, p_type);
  215. } else {
  216. MessageQueue::get_main_singleton()->push_callable(callable_mp_static(dep_err_notify).bind(p_path, p_dependency, p_type));
  217. }
  218. }
  219. }
  220. static void set_dependency_error_notify_func(DependencyErrorNotify p_err_notify) {
  221. dep_err_notify = p_err_notify;
  222. }
  223. static void set_abort_on_missing_resources(bool p_abort) { abort_on_missing_resource = p_abort; }
  224. static bool get_abort_on_missing_resources() { return abort_on_missing_resource; }
  225. static String path_remap(const String &p_path);
  226. static String import_remap(const String &p_path);
  227. static void load_path_remaps();
  228. static void clear_path_remaps();
  229. static void reload_translation_remaps();
  230. static void load_translation_remaps();
  231. static void clear_translation_remaps();
  232. static void clear_thread_load_tasks();
  233. static void set_load_callback(ResourceLoadedCallback p_callback);
  234. static ResourceLoaderImport import;
  235. static bool add_custom_resource_format_loader(const String &script_path);
  236. static void add_custom_loaders();
  237. static void remove_custom_loaders();
  238. static void set_create_missing_resources_if_class_unavailable(bool p_enable);
  239. _FORCE_INLINE_ static bool is_creating_missing_resources_if_class_unavailable_enabled() { return create_missing_resources_if_class_unavailable; }
  240. static Ref<Resource> ensure_resource_ref_override_for_outer_load(const String &p_path, const String &p_res_type);
  241. static Ref<Resource> get_resource_ref_override(const String &p_path);
  242. static bool is_cleaning_tasks();
  243. static void initialize();
  244. static void finalize();
  245. };
  246. #endif // RESOURCE_LOADER_H