BsResources.h 13 KB

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