BsResources.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. #pragma once
  2. #include "BsCorePrerequisites.h"
  3. #include "BsModule.h"
  4. namespace BansheeEngine
  5. {
  6. /** @addtogroup Resources
  7. * @{
  8. */
  9. /**
  10. * Manager for dealing with all engine resources. It allows you to save new resources and load existing ones.
  11. *
  12. * @note Sim thread only.
  13. */
  14. class BS_CORE_EXPORT Resources : public Module<Resources>
  15. {
  16. struct LoadedResourceData
  17. {
  18. LoadedResourceData()
  19. :numInternalRefs(0)
  20. { }
  21. LoadedResourceData(const WeakResourceHandle<Resource>& resource)
  22. :resource(resource), numInternalRefs(0)
  23. { }
  24. WeakResourceHandle<Resource> resource;
  25. UINT32 numInternalRefs;
  26. };
  27. struct ResourceLoadData
  28. {
  29. ResourceLoadData(const WeakResourceHandle<Resource>& resource, UINT32 numDependencies)
  30. :resData(resource), remainingDependencies(numDependencies)
  31. { }
  32. LoadedResourceData resData;
  33. ResourcePtr loadedData;
  34. UINT32 remainingDependencies;
  35. Vector<HResource> dependencies;
  36. bool notifyImmediately;
  37. };
  38. public:
  39. Resources();
  40. ~Resources();
  41. /**
  42. * Loads the resource from a given path. Returns an empty handle if resource can't be loaded. Resource is loaded
  43. * synchronously.
  44. *
  45. * All loaded resources are reference counted and will be automatically unloaded when all of their references go out
  46. * of scope.
  47. *
  48. * @param[in] filePath File path to the resource to load. This can be absolute or relative to
  49. * the working folder.
  50. * @param[in] loadDependencies If true all resources referenced by the root resource will be loaded as well.
  51. * @param[in] keepInternalReference If true the resource system will keep an internal reference to the resource
  52. * so it doesn't get destroyed with it goes out of scope. You can call
  53. * release() to release the internal reference. Each call to load will create
  54. * a new internal reference and therefore must be followed by the same number
  55. * of release calls.
  56. * If dependencies are being loaded, they will not have internal references
  57. * created regardless of this parameter.
  58. *
  59. * @see release(ResourceHandleBase&), unloadAllUnused()
  60. */
  61. HResource load(const Path& filePath, bool loadDependencies = true, bool keepInternalReference = true);
  62. /** @copydoc load(const Path&, bool) */
  63. template <class T>
  64. ResourceHandle<T> load(const Path& filePath, bool loadDependencies = true, bool keepInternalReference = true)
  65. {
  66. return static_resource_cast<T>(load(filePath, loadDependencies, keepInternalReference));
  67. }
  68. /**
  69. * Loads the resource for the provided weak resource handle, or returns a loaded resource if already loaded.
  70. *
  71. * @see load(const Path&, bool)
  72. */
  73. HResource load(const WeakResourceHandle<Resource>& handle, bool loadDependencies = true, bool keepInternalReference = true);
  74. /** @copydoc load(const WeakResourceHandle<T>&, bool) */
  75. template <class T>
  76. ResourceHandle<T> load(const WeakResourceHandle<T>& handle, bool loadDependencies = true, bool keepInternalReference = true)
  77. {
  78. return static_resource_cast<T>(load((const WeakResourceHandle<Resource>&)handle, loadDependencies, keepInternalReference));
  79. }
  80. /**
  81. * Loads the resource asynchronously. Initially returned resource handle will be invalid until resource loading is
  82. * done.
  83. *
  84. * @param[in] filePath Full pathname of the file.
  85. *
  86. * @note
  87. * You can use returned invalid handle in many engine systems as the engine will check for handle validity before
  88. * using it.
  89. *
  90. * @see load(const Path&, bool)
  91. */
  92. HResource loadAsync(const Path& filePath, bool loadDependencies = true, bool keepInternalReference = true);
  93. /** @copydoc loadAsync */
  94. template <class T>
  95. ResourceHandle<T> loadAsync(const Path& filePath, bool loadDependencies = true, bool keepInternalReference = true)
  96. {
  97. return static_resource_cast<T>(loadAsync(filePath, loadDependencies, keepInternalReference));
  98. }
  99. /**
  100. * Loads the resource with the given UUID. Returns an empty handle if resource can't be loaded.
  101. *
  102. * @param[in] uuid UUID of the resource to load.
  103. * @param[in] async If true resource will be loaded asynchronously. Handle to non-loaded
  104. * resource will be returned immediately while loading will continue in the
  105. * background.
  106. * @param[in] loadDependencies If true all resources referenced by the root resource will be loaded as well.
  107. * @param[in] keepInternalReference If true the resource system will keep an internal reference to the resource
  108. * so it doesn't get destroyed with it goes out of scope. You can call
  109. * release() to release the internal reference. Each call to load will create
  110. * a new internal reference and therefore must be followed by the same number
  111. * of release calls.
  112. * If dependencies are being loaded, they will not have internal references
  113. * created regardless of this parameter.
  114. *
  115. * @see load(const Path&, bool)
  116. */
  117. HResource loadFromUUID(const String& uuid, bool async = false, bool loadDependencies = true, bool keepInternalReference = true);
  118. /**
  119. * Releases an internal reference to the resource held by the resources system. This allows the resource to be
  120. * unloaded when it goes out of scope, if the resource was loaded with @p keepInternalReference parameter.
  121. *
  122. * Alternatively you can also skip manually calling release() and call ::unloadAllUnused which will unload all
  123. * resources that do not have any external references, but you lose the fine grained control of what will be
  124. * unloaded.
  125. *
  126. * @param resourceHandle Handle of the resource to release.
  127. */
  128. void release(ResourceHandleBase& resource);
  129. /**
  130. * Finds all resources that aren't being referenced outside of the resources system and unloads them.
  131. *
  132. * @see release(ResourceHandleBase&)
  133. */
  134. void unloadAllUnused();
  135. /**
  136. * Saves the resource at the specified location.
  137. *
  138. * @param[in] resource Handle to the resource.
  139. * @param[in] filePath Full pathname of the file to save as.
  140. * @param[in] overwrite (optional) If true, any existing resource at the specified location will be overwritten.
  141. *
  142. * @note
  143. * If the resource is a GpuResource and you are in some way modifying it from the core thread, make sure all those
  144. * commands are submitted before you call this method. Otherwise an obsolete version of the resource might get saved.
  145. * @note
  146. * If saving a core thread resource this is a potentially very slow operation as we must wait on the core thread
  147. * and the GPU in order to read the resource.
  148. */
  149. void save(const HResource& resource, const Path& filePath, bool overwrite);
  150. /**
  151. * @brief Saves an existing resource to its previous location.
  152. *
  153. * @param resource Handle to the resource.
  154. *
  155. * @note
  156. * If the resource is a GpuResource and you are in some way modifying it from the Core thread, make sure all those
  157. * commands are submitted before you call this method. Otherwise an obsolete version of the resource might get saved.
  158. * @note
  159. * If saving a core thread resource this is a potentially very slow operation as we must wait on the core thread
  160. * and the GPU in order to read the resource.
  161. */
  162. void save(const HResource& resource);
  163. /**
  164. * Updates an existing resource handle with a new resource. Caller must ensure that new resource type matches the
  165. * original resource type.
  166. */
  167. void update(HResource& handle, const ResourcePtr& resource);
  168. /**
  169. * Returns a list of dependencies from the resources at the specified path. Resource will not be loaded or parsed,
  170. * but instead the saved list of dependencies will be read from the file and returned.
  171. *
  172. * @param[in] filePath Full path to the resource to get dependencies for.
  173. * @return List of dependencies represented as UUIDs.
  174. */
  175. Vector<String> getDependencies(const Path& filePath);
  176. /**
  177. * Checks is the resource with the specified UUID loaded.
  178. *
  179. * @param[in] uuid UUID of the resource to check.
  180. * @param[in] checkInProgress Should this method also check resources that are in progress of being
  181. * asynchronously loaded.
  182. * @return True if loaded or loading in progress, false otherwise.
  183. */
  184. bool isLoaded(const String& uuid, bool checkInProgress = true);
  185. /**
  186. *Allows you to set a resource manifest containing UUID <-> file path mapping that is used when resolving
  187. * resource references.
  188. *
  189. * @note
  190. * If you want objects that reference resources (using ResourceHandles) to be able to find that resource even after
  191. * application restart, then you must save the resource manifest before closing the application and restore it
  192. * upon startup. Otherwise resources will be assigned brand new UUIDs and references will be broken.
  193. */
  194. void registerResourceManifest(const ResourceManifestPtr& manifest);
  195. /** Unregisters a resource manifest previously registered with registerResourceManifest(). */
  196. void unregisterResourceManifest(const ResourceManifestPtr& manifest);
  197. /**
  198. * Allows you to retrieve resource manifest containing UUID <-> file path mapping that is used when resolving
  199. * resource references.
  200. *
  201. * @note
  202. * Resources module internally holds a "Default" manifest that it automatically updated whenever a resource is saved.
  203. *
  204. * @see registerResourceManifest
  205. */
  206. ResourceManifestPtr getResourceManifest(const String& name) const;
  207. /** Attempts to retrieve file path from the provided UUID. Returns true if successful, false otherwise. */
  208. bool getFilePathFromUUID(const String& uuid, Path& filePath) const;
  209. /** Attempts to retrieve UUID from the provided file path. Returns true if successful, false otherwise. */
  210. bool getUUIDFromFilePath(const Path& path, String& uuid) const;
  211. /** @cond INTERNAL */
  212. /**
  213. * Creates a new resource handle from a resource pointer.
  214. *
  215. * @note Internal method used primarily be resource factory methods.
  216. */
  217. HResource _createResourceHandle(const ResourcePtr& obj);
  218. /** Returns an existing handle for the specified UUID if one exists, or creates a new one. */
  219. HResource _getResourceHandle(const String& uuid);
  220. /** @endcond */
  221. /**
  222. * Called when the resource has been successfully loaded.
  223. *
  224. * @note
  225. * It is undefined from which thread this will get called from. Most definitely not the sim thread if resource was
  226. * being loaded asynchronously.
  227. */
  228. Event<void(const HResource&)> onResourceLoaded;
  229. /**
  230. * Called when the resource has been destroyed. Provides UUID of the destroyed resource.
  231. *
  232. * @note It is undefined from which thread this will get called from.
  233. */
  234. Event<void(const String&)> onResourceDestroyed;
  235. /**
  236. * Called when the internal resource the handle is pointing to has changed.
  237. *
  238. * @note It is undefined from which thread this will get called from.
  239. */
  240. Event<void(const HResource&)> onResourceModified;
  241. private:
  242. friend class ResourceHandleBase;
  243. /**
  244. * Starts resource loading or returns an already loaded resource. Both UUID and filePath must match the same
  245. * resource, although you may provide an empty path in which case the resource will be retrieved from memory if its
  246. * currently loaded.
  247. *
  248. * @param[in] incrementRef Determines should the internal reference count be incremented.
  249. */
  250. HResource loadInternal(const String& UUID, const Path& filePath, bool synchronous, bool loadDependencies, bool incrementRef);
  251. /** Performs actually reading and deserializing of the resource file. Called from various worker threads. */
  252. ResourcePtr loadFromDiskAndDeserialize(const Path& filePath);
  253. /** Triggered when individual resource has finished loading. */
  254. void loadComplete(HResource& resource);
  255. /** Callback triggered when the task manager is ready to process the loading task. */
  256. void loadCallback(const Path& filePath, HResource& resource);
  257. /** Destroys a resource, freeing its memory. */
  258. void destroy(ResourceHandleBase& resource);
  259. private:
  260. Vector<ResourceManifestPtr> mResourceManifests;
  261. ResourceManifestPtr mDefaultResourceManifest;
  262. BS_MUTEX(mInProgressResourcesMutex);
  263. BS_MUTEX(mLoadedResourceMutex);
  264. UnorderedMap<String, WeakResourceHandle<Resource>> mHandles;
  265. UnorderedMap<String, LoadedResourceData> mLoadedResources;
  266. UnorderedMap<String, ResourceLoadData*> mInProgressResources; // Resources that are being asynchronously loaded
  267. UnorderedMap<String, Vector<ResourceLoadData*>> mDependantLoads; // Allows dependency to be notified when a dependant is loaded
  268. };
  269. /** Provides easier access to Resources manager. */
  270. BS_CORE_EXPORT Resources& gResources();
  271. /** @} */
  272. }