2
0

ResourceCache.h 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #pragma once
  23. #include "File.h"
  24. #include "HashSet.h"
  25. #include "Resource.h"
  26. namespace Urho3D
  27. {
  28. class FileWatcher;
  29. class PackageFile;
  30. /// Sets to priority so that a package or file is pushed to the end of the vector.
  31. static const unsigned int PRIORITY_LAST = -1;
  32. /// Container of resources with specific type.
  33. struct ResourceGroup
  34. {
  35. /// Construct with defaults.
  36. ResourceGroup() :
  37. memoryBudget_(0),
  38. memoryUse_(0)
  39. {
  40. }
  41. /// Memory budget.
  42. unsigned memoryBudget_;
  43. /// Current memory use.
  44. unsigned memoryUse_;
  45. /// Resources.
  46. HashMap<StringHash, SharedPtr<Resource> > resources_;
  47. };
  48. /// %Resource cache subsystem. Loads resources on demand and stores them for later access.
  49. class URHO3D_API ResourceCache : public Object
  50. {
  51. OBJECT(ResourceCache);
  52. public:
  53. /// Construct.
  54. ResourceCache(Context* context);
  55. /// Destruct. Free all resources.
  56. virtual ~ResourceCache();
  57. /// Add a resource load directory. Optional priority parameter which will control search order.
  58. bool AddResourceDir(const String& pathName, unsigned int priority = PRIORITY_LAST );
  59. /// Add a package file for loading resources from. Optional priority parameter which will control search order.
  60. void AddPackageFile(PackageFile* package, unsigned int priority = PRIORITY_LAST );
  61. /// Add a manually created resource. Must be uniquely named.
  62. bool AddManualResource(Resource* resource);
  63. /// Remove a resource load directory.
  64. void RemoveResourceDir(const String& pathName);
  65. /// Remove a package file. Optionally release the resources loaded from it.
  66. void RemovePackageFile(PackageFile* package, bool releaseResources = true, bool forceRelease = false);
  67. /// Remove a package file by name. Optionally release the resources loaded from it.
  68. void RemovePackageFile(const String& fileName, bool releaseResources = true, bool forceRelease = false);
  69. /// Release a resource by name.
  70. void ReleaseResource(ShortStringHash type, const String& name, bool force = false);
  71. /// Release all resources of a specific type.
  72. void ReleaseResources(ShortStringHash type, bool force = false);
  73. /// Release resources of a specific type and partial name.
  74. void ReleaseResources(ShortStringHash type, const String& partialName, bool force = false);
  75. /// Release resources of all types by partial name.
  76. void ReleaseResources(const String& partialName, bool force = false);
  77. /// Release all resources. When called with the force flag false, releases all currently unused resources.
  78. void ReleaseAllResources(bool force = false);
  79. /// Reload a resource. Return false and release it if fails.
  80. bool ReloadResource(Resource* resource);
  81. /// Set memory budget for a specific resource type, default 0 is unlimited.
  82. void SetMemoryBudget(ShortStringHash type, unsigned budget);
  83. /// Enable or disable automatic reloading of resources as files are modified.
  84. void SetAutoReloadResources(bool enable);
  85. /// Define whether when getting resources should check package files or directories first. True for packages, false for directories.
  86. void SetSearchPackagesFirst(bool value) { searchPackagesFirst_ = value; }
  87. /// Open and return a file from the resource load paths or from inside a package file. If not found, use a fallback search with absolute path. Return null if fails.
  88. SharedPtr<File> GetFile(const String& name);
  89. /// Return a resource by type and name. Load if not loaded yet. Return null if fails.
  90. Resource* GetResource(ShortStringHash type, const String& name);
  91. /// Return a resource by type and name. Load if not loaded yet. Return null if fails.
  92. Resource* GetResource(ShortStringHash type, const char* name);
  93. /// Return all loaded resources of a specific type.
  94. void GetResources(PODVector<Resource*>& result, ShortStringHash type) const;
  95. /// Return all loaded resources.
  96. const HashMap<ShortStringHash, ResourceGroup>& GetAllResources() const { return resourceGroups_; }
  97. /// Return added resource load directories.
  98. const Vector<String>& GetResourceDirs() const { return resourceDirs_; }
  99. /// Return added package files.
  100. const Vector<SharedPtr<PackageFile> >& GetPackageFiles() const { return packages_; }
  101. /// Template version of returning a resource by name.
  102. template <class T> T* GetResource(const String& name);
  103. /// Template version of returning a resource by name.
  104. template <class T> T* GetResource(const char* name);
  105. /// Template version of returning loaded resources of a specific type.
  106. template <class T> void GetResources(PODVector<T*>& result) const;
  107. /// Return whether a file exists by name.
  108. bool Exists(const String& name) const;
  109. /// Return memory budget for a resource type.
  110. unsigned GetMemoryBudget(ShortStringHash type) const;
  111. /// Return total memory use for a resource type.
  112. unsigned GetMemoryUse(ShortStringHash type) const;
  113. /// Return total memory use for all resources.
  114. unsigned GetTotalMemoryUse() const;
  115. /// Return full absolute file name of resource if possible.
  116. String GetResourceFileName(const String& name) const;
  117. /// Return whether automatic resource reloading is enabled.
  118. bool GetAutoReloadResources() const { return autoReloadResources_; }
  119. /// Define whether when getting resources should check package files or directories first.
  120. bool GetSearchPackagesFirst() const { return searchPackagesFirst_; }
  121. /// Return either the path itself or its parent, based on which of them has recognized resource subdirectories.
  122. String GetPreferredResourceDir(const String& path) const;
  123. /// Remove unsupported constructs from the resource name to prevent ambiguity, and normalize absolute filename to resource path relative if possible.
  124. String SanitateResourceName(const String& name) const;
  125. /// Remove unnecessary constructs from a resource directory name and ensure it to be an absolute path.
  126. String SanitateResourceDirName(const String& name) const;
  127. /// Store a dependency for a resource. If a dependency file changes, the resource will be reloaded.
  128. void StoreResourceDependency(Resource* resource, const String& dependency);
  129. /// Reset dependencies for a resource.
  130. void ResetDependencies(Resource* resource);
  131. private:
  132. /// Find a resource.
  133. const SharedPtr<Resource>& FindResource(ShortStringHash type, StringHash nameHash);
  134. /// Find a resource by name only. Searches all type groups.
  135. const SharedPtr<Resource>& FindResource(StringHash nameHash);
  136. /// Release resources loaded from a package file.
  137. void ReleasePackageResources(PackageFile* package, bool force = false);
  138. /// Update a resource group. Recalculate memory use and release resources if over memory budget.
  139. void UpdateResourceGroup(ShortStringHash type);
  140. /// Handle begin frame event. Automatic resource reloads are processed here.
  141. void HandleBeginFrame(StringHash eventType, VariantMap& eventData);
  142. /// Search FileSystem for File.
  143. File* SearchResourceDirs(const String& nameIn);
  144. /// Search Packages for File.
  145. File* SearchPackages(const String& nameIn);
  146. /// Resources by type.
  147. HashMap<ShortStringHash, ResourceGroup> resourceGroups_;
  148. /// Resource load directories.
  149. Vector<String> resourceDirs_;
  150. /// File watchers for resource directories, if automatic reloading enabled.
  151. Vector<SharedPtr<FileWatcher> > fileWatchers_;
  152. /// Package files.
  153. Vector<SharedPtr<PackageFile> > packages_;
  154. /// Dependent resources.
  155. HashMap<StringHash, HashSet<StringHash> > dependentResources_;
  156. /// Automatic resource reloading flag.
  157. bool autoReloadResources_;
  158. /// Search priority flag.
  159. bool searchPackagesFirst_;
  160. };
  161. template <class T> T* ResourceCache::GetResource(const String& name)
  162. {
  163. ShortStringHash type = T::GetTypeStatic();
  164. return static_cast<T*>(GetResource(type, name));
  165. }
  166. template <class T> T* ResourceCache::GetResource(const char* name)
  167. {
  168. ShortStringHash type = T::GetTypeStatic();
  169. return static_cast<T*>(GetResource(type, name));
  170. }
  171. template <class T> void ResourceCache::GetResources(PODVector<T*>& result) const
  172. {
  173. PODVector<Resource*>& resources = reinterpret_cast<PODVector<Resource*>&>(result);
  174. ShortStringHash type = T::GetTypeStatic();
  175. GetResources(resources, type);
  176. // Perform conversion of the returned pointers
  177. for (unsigned i = 0; i < result.Size(); ++i)
  178. {
  179. Resource* resource = resources[i];
  180. result[i] = static_cast<T*>(resource);
  181. }
  182. }
  183. /// Register Resource library subsystems and objects.
  184. void URHO3D_API RegisterResourceLibrary(Context* context);
  185. }