BsResources.h 13 KB

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