BsResources.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. SPtr<Resource> 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, 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, bool)
  74. */
  75. HResource load(const WeakResourceHandle<Resource>& handle, bool loadDependencies = true, bool keepInternalReference = true);
  76. /** @copydoc load(const WeakResourceHandle<Resource>&, bool, 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. * @param[in] loadDependencies If true all resources referenced by the root resource will be loaded as well.
  88. * @param[in] keepInternalReference If true the resource system will keep an internal reference to the resource
  89. * so it doesn't get destroyed with it goes out of scope. You can call
  90. * release() to release the internal reference. Each call to load will create
  91. * a new internal reference and therefore must be followed by the same number
  92. * of release calls.
  93. * If dependencies are being loaded, they will not have internal references
  94. * created regardless of this parameter.
  95. *
  96. * @note
  97. * You can use returned invalid handle in many engine systems as the engine will check for handle validity before
  98. * using it.
  99. *
  100. * @see load(const Path&, bool)
  101. */
  102. HResource loadAsync(const Path& filePath, bool loadDependencies = true, bool keepInternalReference = true);
  103. /** @copydoc loadAsync */
  104. template <class T>
  105. ResourceHandle<T> loadAsync(const Path& filePath, bool loadDependencies = true, bool keepInternalReference = true)
  106. {
  107. return static_resource_cast<T>(loadAsync(filePath, loadDependencies, keepInternalReference));
  108. }
  109. /**
  110. * Loads the resource with the given UUID. Returns an empty handle if resource can't be loaded.
  111. *
  112. * @param[in] uuid UUID of the resource to load.
  113. * @param[in] async If true resource will be loaded asynchronously. Handle to non-loaded
  114. * resource will be returned immediately while loading will continue in the
  115. * background.
  116. * @param[in] loadDependencies If true all resources referenced by the root resource will be loaded as well.
  117. * @param[in] keepInternalReference If true the resource system will keep an internal reference to the resource
  118. * so it doesn't get destroyed with it goes out of scope. You can call
  119. * release() to release the internal reference. Each call to load will create
  120. * a new internal reference and therefore must be followed by the same number
  121. * of release calls.
  122. * If dependencies are being loaded, they will not have internal references
  123. * created regardless of this parameter.
  124. *
  125. * @see load(const Path&, bool)
  126. */
  127. HResource loadFromUUID(const String& uuid, bool async = false, bool loadDependencies = true, bool keepInternalReference = true);
  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. /** Returns an existing handle for the specified UUID if one exists, or creates a new one. */
  252. HResource _getResourceHandle(const String& uuid);
  253. /** @} */
  254. private:
  255. friend class ResourceHandleBase;
  256. /**
  257. * Starts resource loading or returns an already loaded resource. Both UUID and filePath must match the same
  258. * resource, although you may provide an empty path in which case the resource will be retrieved from memory if its
  259. * currently loaded.
  260. *
  261. * @param[in] incrementRef Determines should the internal reference count be incremented.
  262. */
  263. HResource loadInternal(const String& UUID, const Path& filePath, bool synchronous, bool loadDependencies, bool incrementRef);
  264. /** Performs actually reading and deserializing of the resource file. Called from various worker threads. */
  265. SPtr<Resource> loadFromDiskAndDeserialize(const Path& filePath);
  266. /** Triggered when individual resource has finished loading. */
  267. void loadComplete(HResource& resource);
  268. /** Callback triggered when the task manager is ready to process the loading task. */
  269. void loadCallback(const Path& filePath, HResource& resource);
  270. /** Destroys a resource, freeing its memory. */
  271. void destroy(ResourceHandleBase& resource);
  272. private:
  273. Vector<SPtr<ResourceManifest>> mResourceManifests;
  274. SPtr<ResourceManifest> mDefaultResourceManifest;
  275. Mutex mInProgressResourcesMutex;
  276. Mutex mLoadedResourceMutex;
  277. UnorderedMap<String, WeakResourceHandle<Resource>> mHandles;
  278. UnorderedMap<String, LoadedResourceData> mLoadedResources;
  279. UnorderedMap<String, ResourceLoadData*> mInProgressResources; // Resources that are being asynchronously loaded
  280. UnorderedMap<String, Vector<ResourceLoadData*>> mDependantLoads; // Allows dependency to be notified when a dependant is loaded
  281. };
  282. /** Provides easier access to Resources manager. */
  283. BS_CORE_EXPORT Resources& gResources();
  284. /** @} */
  285. }