BsResources.h 13 KB

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