BsProjectLibrary.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #pragma once
  4. #include "BsEditorPrerequisites.h"
  5. #include "Utility/BsModule.h"
  6. #include "Threading/BsAsyncOp.h"
  7. #include "Utility/BsUSPtr.h"
  8. namespace bs
  9. {
  10. /** @addtogroup Library
  11. * @{
  12. */
  13. /**
  14. * Project library is the primary location for interacting with all the resources in the current project. A complete
  15. * hierarchy of resources is provided which can be interacted with by importing new ones, deleting them, moving,
  16. * renaming and similar.
  17. */
  18. class BS_ED_EXPORT ProjectLibrary : public Module<ProjectLibrary>
  19. {
  20. public:
  21. struct LibraryEntry;
  22. struct FileEntry;
  23. struct DirectoryEntry;
  24. /** Types of elements in the library, either a file or a folder. */
  25. enum class LibraryEntryType
  26. {
  27. File,
  28. Directory
  29. };
  30. /** A generic library entry that may be a file or a folder depending on its type. */
  31. struct LibraryEntry
  32. {
  33. LibraryEntry();
  34. LibraryEntry(const Path& path, const String& name, DirectoryEntry* parent, LibraryEntryType type);
  35. LibraryEntryType type; /**< Specific type of this entry. */
  36. Path path; /**< Absolute path to the entry. */
  37. String elementName; /**< Name of the entry. */
  38. size_t elementNameHash = 0; /**< Hash of @p elementName, used for faster comparisons. */
  39. DirectoryEntry* parent = nullptr; /**< Folder this entry is located in. */
  40. };
  41. /** A library entry representing a file. Each file can have one or multiple resources. */
  42. struct FileEntry : public LibraryEntry
  43. {
  44. FileEntry() = default;
  45. FileEntry(const Path& path, const String& name, DirectoryEntry* parent);
  46. SPtr<ProjectFileMeta> meta; /**< Meta file containing various information about the resource(s). */
  47. std::time_t lastUpdateTime = 0; /**< Timestamp of when we last imported the resource. */
  48. };
  49. /** A library entry representing a folder that contains other entries. */
  50. struct DirectoryEntry : public LibraryEntry
  51. {
  52. DirectoryEntry() = default;
  53. DirectoryEntry(const Path& path, const String& name, DirectoryEntry* parent);
  54. Vector<USPtr<LibraryEntry>> mChildren; /**< Child files or folders. */
  55. };
  56. public:
  57. ProjectLibrary();
  58. ~ProjectLibrary();
  59. /**
  60. * Checks if any resources at the specified path have been modified, added or deleted, and updates the internal
  61. * hierarchy accordingly. Automatically imports dirty resources.
  62. *
  63. * @param[in] path Absolute path of the file or folder to check. If a folder is provided all its children will
  64. * be checked recursively.
  65. * @return Returns the number of resources that were queued for import during this call.
  66. */
  67. UINT32 checkForModifications(const Path& path);
  68. /** Returns the root library entry that references the entire library hierarchy. */
  69. const USPtr<DirectoryEntry>& getRootEntry() const { return mRootEntry; }
  70. /**
  71. * Attempts to a find a library entry at the specified path.
  72. *
  73. * @param[in] path Path to the entry, either absolute or relative to resources folder.
  74. * @return Found entry, or null if not found. Value returned by this method is transient, it may be
  75. * destroyed on any following ProjectLibrary call.
  76. */
  77. USPtr<LibraryEntry> findEntry(const Path& path) const;
  78. /**
  79. * Checks whether the provided path points to a sub-resource. Sub-resource is any resource that is not the primary
  80. * resource in the file.
  81. */
  82. bool isSubresource(const Path& path) const;
  83. /**
  84. * Attempts to a find a meta information for a resource at the specified path.
  85. *
  86. * @param[in] path Path to the entry, either absolute or relative to resources folder. If a sub-resource within
  87. * a file is needed, append the name of the subresource to the path
  88. * (for example mymesh.fbx/my_animation).
  89. * @return Found meta information for the resource, or null if not found.
  90. */
  91. SPtr<ProjectResourceMeta> findResourceMeta(const Path& path) const;
  92. /**
  93. * Searches the library for a pattern and returns all entries matching it.
  94. *
  95. * @param[in] pattern Pattern to search for. Use wildcard * to match any character(s).
  96. * @return A list of entries matching the pattern. Values returned by this method are transient, they may be
  97. * destroyed on any following ProjectLibrary call.
  98. */
  99. Vector<USPtr<LibraryEntry>> search(const String& pattern);
  100. /**
  101. * Searches the library for a pattern, but only among specific resource types.
  102. *
  103. * @param[in] pattern Pattern to search for. Use wildcard * to match any character(s).
  104. * @param[in] typeIds RTTI type IDs of the resource types we're interested in searching.
  105. * @return A list of entries matching the pattern. Values returned by this method are transient, they may be
  106. * destroyed on any following ProjectLibrary call.
  107. */
  108. Vector<USPtr<LibraryEntry>> search(const String& pattern, const Vector<UINT32>& typeIds);
  109. /**
  110. * Returns resource path based on its UUID.
  111. *
  112. * @param[in] uuid UUID of the resource to look for.
  113. * @return Absolute path to the resource.
  114. */
  115. Path uuidToPath(const UUID& uuid) const;
  116. /**
  117. * Registers a new resource in the library.
  118. *
  119. * @param[in] resource Resource instance to add to the library. A copy of the resource will be saved at the
  120. * provided path.
  121. * @param[in] path Path where where to store the resource. Absolute or relative to the resources folder.
  122. */
  123. void createEntry(const HResource& resource, const Path& path);
  124. /**
  125. * Creates a new folder in the library.
  126. *
  127. * @param[in] path Path where where to store the folder. Absolute or relative to the resources folder.
  128. */
  129. void createFolderEntry(const Path& path);
  130. /** Updates a resource that is already in the library. */
  131. void saveEntry(const HResource& resource);
  132. /**
  133. * Moves a library entry from one path to another.
  134. *
  135. * @param[in] oldPath Source path of the entry, absolute or relative to resources folder.
  136. * @param[in] newPath Destination path of the entry, absolute or relative to resources folder.
  137. * @param[in] overwrite If an entry already exists at the destination path, should it be overwritten.
  138. */
  139. void moveEntry(const Path& oldPath, const Path& newPath, bool overwrite = true);
  140. /**
  141. * Copies a library entry from one path to another.
  142. *
  143. * @param[in] oldPath Source path of the entry, absolute or relative to resources folder.
  144. * @param[in] newPath Destination path of the entry, absolute or relative to resources folder.
  145. * @param[in] overwrite If an entry already exists at the destination path, should it be overwritten.
  146. */
  147. void copyEntry(const Path& oldPath, const Path& newPath, bool overwrite = true);
  148. /**
  149. * Deletes an entry from the library.
  150. *
  151. * @param[in] path Path of the entry, absolute or relative to resources folder.
  152. */
  153. void deleteEntry(const Path& path);
  154. /**
  155. * Triggers a reimport of a resource using the provided import options, if needed.
  156. *
  157. * @param[in] path Path to the resource to reimport, absolute or relative to resources folder.
  158. * @param[in] importOptions Optional import options to use when importing the resource. Caller must ensure the
  159. * import options are of the correct type for the resource in question. If null is
  160. * provided default import options are used.
  161. * @param[in] forceReimport Should the resource be reimported even if no changes are detected. This should be
  162. * true if import options changed since last import.
  163. * @param[in] synchronous If true the import will happen synchronously on the calling thread. If false
  164. * the import operation will be queued for execution on a worker thread. You
  165. * then must call _finishQueuedImports() after the worker thread finishes to
  166. * actually finish the import.
  167. */
  168. void reimport(const Path& path, const SPtr<ImportOptions>& importOptions = nullptr, bool forceReimport = false,
  169. bool synchronous = false);
  170. /**
  171. * Checks how far along is the import for the specified file.
  172. *
  173. * @param[in] path Path to the resource to check the progress for, absolute or relative to the resources
  174. * folder.
  175. * @return Reports 1 if the file is fully imported. Reports 0 if the import has not started or the
  176. * file isn't even queued for import. Reports >= 0 if the file is in process of being
  177. * imported. Note that not all importers support fine grained progress reporting, in which
  178. * case the import progress will be reported as a binary 0 or 1.
  179. */
  180. float getImportProgress(const Path& path) const;
  181. /**
  182. * Cancels any queued import tasks. Note that you must call _finishQueuedImports() for the import state to be
  183. * updated. If the import task has already started you will need to wait until it finishes as there is no way to
  184. * stop running tasks. If the provided file entry isn't being imported, or has already finished imported, the
  185. * function does nothing.
  186. */
  187. void cancelImport();
  188. /**
  189. * Determines if this resource will always be included in the build, regardless if it's being referenced or not.
  190. *
  191. * @param[in] path Path to the resource to modify, absolute or relative to resources folder.
  192. * @param[in] force True if we want the resource to be included in the build, false otherwise.
  193. */
  194. void setIncludeInBuild(const Path& path, bool force);
  195. /**
  196. * Assigns a non-specific user data object to the resource at the specified path.
  197. *
  198. * @param[in] path Path to the resource to modify, absolute or relative to resources folder.
  199. * @param[in] userData User data to assign to the resource, which can later be retrieved from the resource's
  200. * meta-data as needed.
  201. */
  202. void setUserData(const Path& path, const SPtr<IReflectable>& userData);
  203. /**
  204. * Finds all top-level resource entries that should be included in a build. Values returned by this method are
  205. * transient, they may be destroyed on any following ProjectLibrary call.
  206. */
  207. Vector<USPtr<FileEntry>> getResourcesForBuild() const;
  208. /**
  209. * Loads a resource at the specified path, synchronously.
  210. *
  211. * @param[in] path Path of the resource, absolute or relative to resources folder. If a sub-resource within
  212. * a file is needed, append the name of the subresource to the path
  213. * (for example mymesh.fbx/my_animation).
  214. * @return Loaded resource, or null handle if one is not found.
  215. */
  216. HResource load(const Path& path);
  217. /** Returns the path to the project's resource folder where all the assets are stored. */
  218. const Path& getResourcesFolder() const { return mResourcesFolder; }
  219. /** Returns the number of resources currently queued for import. */
  220. UINT32 getInProgressImportCount() const { return (UINT32)mQueuedImports.size(); }
  221. /**
  222. * Saves all the project library data so it may be restored later, at the default save location in the project
  223. * folder. Project must be loaded when calling this.
  224. */
  225. void saveLibrary();
  226. /**
  227. * Loads previously saved project library data from the default save location in the project folder. Nothing is
  228. * loaded if it doesn't exist.Project must be loaded when calling this.
  229. */
  230. void loadLibrary();
  231. /** Clears all library data. */
  232. void unloadLibrary();
  233. /** Triggered whenever an entry is removed from the library. Path provided is absolute. */
  234. Event<void(const Path&)> onEntryRemoved;
  235. /** Triggered whenever an entry is added to the library. Path provided is absolute. */
  236. Event<void(const Path&)> onEntryAdded;
  237. /** Triggered when a resource is being (re)imported. Path provided is absolute. */
  238. Event<void(const Path&)> onEntryImported;
  239. /** @name Internal
  240. * @{
  241. */
  242. /** Returns the resource manifest managed by the project library. */
  243. const SPtr<ResourceManifest>& _getManifest() const { return mResourceManifest; }
  244. /**
  245. * Iterates over any queued import operations, checks if they have finished and finalizes them. This should be
  246. * called on a regular basis (e.g. every frame).
  247. *
  248. * @param[in] wait If true the method will block until all imports finish.
  249. */
  250. void _finishQueuedImports(bool wait = false);
  251. /** @} */
  252. static const Path RESOURCES_DIR;
  253. static const Path INTERNAL_RESOURCES_DIR;
  254. private:
  255. /** Name/resource pair for a single imported resource. */
  256. struct QueuedImportResource
  257. {
  258. QueuedImportResource(String name, SPtr<Resource> resource, const UUID& uuid)
  259. :name(std::move(name)), resource(std::move(resource)), uuid(uuid)
  260. { }
  261. QueuedImportResource(String name, const HResource& handle)
  262. :name(std::move(name)), resource(handle.getInternalPtr()), handle(handle), uuid(handle.getUUID())
  263. { }
  264. String name;
  265. SPtr<Resource> resource;
  266. HResource handle;
  267. UUID uuid;
  268. };
  269. /** Information about an asynchronously queued import. */
  270. struct QueuedImport
  271. {
  272. Path filePath;
  273. SPtr<Task> importTask;
  274. SPtr<ImportOptions> importOptions;
  275. Vector<QueuedImportResource> resources;
  276. SPtr<QueuedImport> dependsOn;
  277. bool pruneMetas = false;
  278. bool canceled = false;
  279. bool native = false;
  280. std::time_t timestamp = 0;
  281. };
  282. /**
  283. * Common code for adding a new resource entry to the library.
  284. *
  285. * @param[in] parent Parent of the new entry.
  286. * @param[in] filePath Absolute path to the resource.
  287. * @param[in] importOptions Optional import options to use when importing the resource. Caller must ensure the
  288. * import options are of the correct type for the resource in question. If null is
  289. * provided default import options are used.
  290. * @param[in] forceReimport Should the resource be reimported even if we detect no changes. This should be true
  291. * if import options changed since last import.
  292. * @param[in] synchronous If true the import will happen synchronously on the calling thread. If false
  293. * the import operation will be queued for execution on a worker thread. You
  294. * then must call _finishQueuedImports() after the worker thread finishes to
  295. * actually finish the import.
  296. * @return Newly added resource entry.
  297. */
  298. USPtr<FileEntry> addResourceInternal(DirectoryEntry* parent, const Path& filePath,
  299. const SPtr<ImportOptions>& importOptions = nullptr, bool forceReimport = false, bool synchronous = false);
  300. /**
  301. * Common code for adding a new folder entry to the library.
  302. *
  303. * @param[in] parent Parent of the new entry.
  304. * @param[in] dirPath Absolute path to the directory.
  305. * @return Newly added directory entry.
  306. */
  307. USPtr<DirectoryEntry> addDirectoryInternal(DirectoryEntry* parent, const Path& dirPath);
  308. /**
  309. * Common code for deleting a resource from the library. This code only removes the library entry, not the actual
  310. * resource file.
  311. *
  312. * @param[in] resource Entry to delete.
  313. */
  314. void deleteResourceInternal(USPtr<FileEntry> resource);
  315. /**
  316. * Common code for deleting a directory from the library. This code only removes the library entry, not the actual
  317. * directory.
  318. *
  319. * @param[in] directory Entry to delete.
  320. */
  321. void deleteDirectoryInternal(USPtr<DirectoryEntry> directory);
  322. /**
  323. * Triggers a reimport of a resource using the provided import options, if needed. Doesn't import dependencies.
  324. *
  325. * @param[in] fileEntry File entry of the resource to reimport.
  326. * @param[in] importOptions Optional import options to use when importing the resource. Caller must ensure
  327. * the import options are of the correct type for the resource in question. If null
  328. * is provided default import options are used.
  329. * @param[in] forceReimport Should the resource be reimported even if we detect no changes. This should be
  330. * true if import options changed since last import.
  331. * @param[in] pruneResourceMetas Determines should resource meta data for resources that no longer exist within
  332. * the file be deleted. Default behaviour is to keep these alive so that if their
  333. * resources are eventually restored, references to them will remain valid. If you
  334. * feel that you need to clear this data, set this to true but be aware that you
  335. * might need to re-apply those references.
  336. * @param[in] synchronous If true the import will happen synchronously on the calling thread. If false
  337. * the import operation will be queued for execution on a worker thread. You
  338. * then must call _finishQueuedImports() after the worker thread finishes to
  339. * actually finish the import.
  340. * @return Returns true if the resource was queued for import (or imported, if
  341. * synchronous), false otherwise.
  342. */
  343. bool reimportResourceInternal(FileEntry* fileEntry, const SPtr<ImportOptions>& importOptions = nullptr,
  344. bool forceReimport = false, bool pruneResourceMetas = false, bool synchronous = false);
  345. /**
  346. * Creates a full hierarchy of directory entries up to the provided directory, if any are needed.
  347. *
  348. * @param[in] fullPath Absolute path to a directory we are creating the hierarchy to.
  349. * @param[out] newHierarchyRoot First directory entry that already existed in our hierarchy.
  350. * @param[out] newHierarchyLeaf Leaf entry corresponding to the exact entry at \p fullPath.
  351. */
  352. void createInternalParentHierarchy(const Path& fullPath, DirectoryEntry** newHierarchyRoot,
  353. DirectoryEntry** newHierarchyLeaf);
  354. /** Checks has a file been modified since the last import. */
  355. bool isUpToDate(FileEntry* file) const;
  356. /** Checks is the resource a native engine resource that doesn't require importing. */
  357. bool isNative(const Path& path) const;
  358. /**
  359. * Returns a path to a .meta file based on the resource path.
  360. *
  361. * @param[in] path Absolute path to the resource.
  362. * @return Path to the .meta file.
  363. */
  364. Path getMetaPath(const Path& path) const;
  365. /** Checks does the path represent a .meta file. */
  366. bool isMeta(const Path& fullPath) const;
  367. /**
  368. * Returns a set of resource paths that are dependent on the provided resource entry. (for example a shader file
  369. * might be dependent on shader include file).
  370. */
  371. Vector<Path> getImportDependencies(const FileEntry* entry);
  372. /** Registers any import dependencies for the specified resource. */
  373. void addDependencies(const FileEntry* entry);
  374. /** Removes any import dependencies for the specified resource. */
  375. void removeDependencies(const FileEntry* entry);
  376. /** Finds dependants resource for the specified resource entry and reimports them. */
  377. void reimportDependants(const Path& entryPath);
  378. /** Makes all library entry paths relative to the current resources folder. */
  379. void makeEntriesRelative();
  380. /**
  381. * Makes all library entry paths absolute by appending them to the current resources folder. Entries must have
  382. * previously been made relative by calling makeEntriesRelative().
  383. */
  384. void makeEntriesAbsolute();
  385. /** Deletes all library entries. */
  386. void clearEntries();
  387. /**
  388. * Finalizes a queued import operation if the import task has finished (or immediately if no task is present).
  389. *
  390. * @param[in] fileEntry File entry for which the import is running.
  391. * @param[in] import Structure containing information about the import.
  392. * @param[in] wait If true waits until the asynchronous import task finishes before returning. Not
  393. * relevant if the import task is not present (synchronous import).
  394. * @return True if the import was finalized. Will be false if the async import task has not
  395. * yet finished and @p wait is false.
  396. */
  397. bool finishQueuedImport(FileEntry* fileEntry, const QueuedImport& import, bool wait);
  398. /**
  399. * Checks if there are any queued imports queued for the provided file entry, and if there are waits until they
  400. * finish before returning.s
  401. */
  402. void waitForQueuedImport(FileEntry* fileEntry);
  403. static const char* LIBRARY_ENTRIES_FILENAME;
  404. static const char* RESOURCE_MANIFEST_FILENAME;
  405. SPtr<ResourceManifest> mResourceManifest;
  406. USPtr<DirectoryEntry> mRootEntry;
  407. Path mProjectFolder;
  408. Path mResourcesFolder;
  409. bool mIsLoaded;
  410. Mutex mQueuedImportMutex;
  411. UnorderedMap<FileEntry*, SPtr<QueuedImport>> mQueuedImports;
  412. UnorderedMap<Path, Vector<Path>> mDependencies;
  413. UnorderedMap<UUID, Path> mUUIDToPath;
  414. };
  415. /** Provides easy access to ProjectLibrary. */
  416. BS_ED_EXPORT ProjectLibrary& gProjectLibrary();
  417. /** @} */
  418. }