ResourceCache.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Log.h"
  25. #include "PackageFile.h"
  26. #include "ResourceCache.h"
  27. #include "ResourceFactory.h"
  28. #include "StringUtils.h"
  29. #include "DebugNew.h"
  30. ResourceCache::ResourceCache()
  31. {
  32. LOGINFO("Resource cache created");
  33. }
  34. ResourceCache::~ResourceCache()
  35. {
  36. // At this point factories may be the only thing keeping subsystems alive; remove resources before factories so that
  37. // resources can be released cleanly
  38. mResourceGroups.clear();
  39. mFactories.clear();
  40. LOGINFO("Resource cache shut down");
  41. }
  42. void ResourceCache::addResourceFactory(ResourceFactory* factory)
  43. {
  44. if (!factory)
  45. return;
  46. mFactories.push_back(SharedPtr<ResourceFactory>(factory));
  47. }
  48. void ResourceCache::addResourcePath(const std::string& path)
  49. {
  50. checkDirectoryAccess(path);
  51. std::string fixedPath = fixPath(path);
  52. mResourcePaths.push_back(fixedPath);
  53. // Scan the path for files recursively and add their hash-to-name mappings
  54. std::vector<std::string> fileNames = scanDirectory(fixedPath, "*.*", true);
  55. for (unsigned i = 0; i < fileNames.size(); ++i)
  56. registerHash(fileNames[i]);
  57. LOGINFO("Added resource path " + fixedPath);
  58. }
  59. void ResourceCache::addPackageFile(PackageFile* package, bool addAsFirst)
  60. {
  61. if (!package)
  62. return;
  63. if (addAsFirst)
  64. mPackages.insert(mPackages.begin(), SharedPtr<PackageFile>(package));
  65. else
  66. mPackages.push_back(SharedPtr<PackageFile>(package));
  67. // Scan the package for files and add their hash-to-name mappings
  68. const std::map<std::string, PackageEntry>& entries = package->getEntries();
  69. for (std::map<std::string, PackageEntry>::const_iterator i = entries.begin(); i != entries.end(); ++i)
  70. registerHash(i->first);
  71. LOGINFO("Added resource package " + package->getName());
  72. }
  73. bool ResourceCache::addManualResource(Resource* resource)
  74. {
  75. if (!resource)
  76. {
  77. LOGERROR("Null manual resource");
  78. return false;
  79. }
  80. if (resource->getName().empty())
  81. {
  82. LOGERROR("Manual resource with empty name, can not add");
  83. return false;
  84. }
  85. resource->resetUseTimer();
  86. mResourceGroups[resource->getType()].mResources[resource->getNameHash()] = resource;
  87. updateResourceGroup(resource->getType());
  88. return true;
  89. }
  90. void ResourceCache::removeResourcePath(const std::string& path)
  91. {
  92. for (std::vector<std::string>::iterator i = mResourcePaths.begin(); i != mResourcePaths.end();)
  93. {
  94. if (i->find(path) == 0)
  95. i = mResourcePaths.erase(i);
  96. else
  97. ++i;
  98. }
  99. }
  100. void ResourceCache::removePackageFile(PackageFile* package, bool releaseResources, bool forceRelease)
  101. {
  102. for (std::vector<SharedPtr<PackageFile> >::iterator i = mPackages.begin(); i != mPackages.end(); ++i)
  103. {
  104. if ((*i) == package)
  105. {
  106. if (releaseResources)
  107. releasePackageResources(*i, forceRelease);
  108. mPackages.erase(i);
  109. return;
  110. }
  111. }
  112. }
  113. void ResourceCache::removePackageFile(const std::string& fileName, bool releaseResources, bool forceRelease)
  114. {
  115. for (std::vector<SharedPtr<PackageFile> >::iterator i = mPackages.begin(); i != mPackages.end(); ++i)
  116. {
  117. if ((*i)->getName() == fileName)
  118. {
  119. if (releaseResources)
  120. releasePackageResources(*i, forceRelease);
  121. mPackages.erase(i);
  122. return;
  123. }
  124. }
  125. }
  126. void ResourceCache::releaseResource(ShortStringHash type, const std::string& name, bool force)
  127. {
  128. releaseResource(type, StringHash(name), force);
  129. }
  130. void ResourceCache::releaseResource(ShortStringHash type, StringHash nameHash, bool force)
  131. {
  132. const SharedPtr<Resource>& existingRes = findResource(type, nameHash);
  133. if (!existingRes)
  134. return;
  135. // If other references exist, do not release, unless forced
  136. if ((existingRes.getRefCount() == 1) || (force))
  137. {
  138. mResourceGroups[type].mResources.erase(nameHash);
  139. updateResourceGroup(type);
  140. }
  141. }
  142. void ResourceCache::releaseResources(ShortStringHash type, bool force)
  143. {
  144. bool released = false;
  145. for (std::map<ShortStringHash, ResourceGroup>::iterator i = mResourceGroups.begin();
  146. i != mResourceGroups.end(); ++i)
  147. {
  148. if (i->first == type)
  149. {
  150. for (std::map<StringHash, SharedPtr<Resource> >::iterator j = i->second.mResources.begin();
  151. j != i->second.mResources.end();)
  152. {
  153. std::map<StringHash, SharedPtr<Resource> >::iterator current = j;
  154. ++j;
  155. // If other references exist, do not release, unless forced
  156. if ((current->second.getRefCount() == 1) || (force))
  157. {
  158. i->second.mResources.erase(current);
  159. released = true;
  160. }
  161. }
  162. }
  163. }
  164. if (released)
  165. updateResourceGroup(type);
  166. }
  167. void ResourceCache::releaseResources(ShortStringHash type, const std::string& partialName, bool force)
  168. {
  169. std::string partialNameLower = toLower(partialName);
  170. bool released = false;
  171. for (std::map<ShortStringHash, ResourceGroup>::iterator i = mResourceGroups.begin();
  172. i != mResourceGroups.end(); ++i)
  173. {
  174. if (i->first == type)
  175. {
  176. for (std::map<StringHash, SharedPtr<Resource> >::iterator j = i->second.mResources.begin();
  177. j != i->second.mResources.end();)
  178. {
  179. std::map<StringHash, SharedPtr<Resource> >::iterator current = j;
  180. ++j;
  181. if (current->second->getName().find(partialNameLower) != std::string::npos)
  182. {
  183. // If other references exist, do not release, unless forced
  184. if ((current->second.getRefCount() == 1) || (force))
  185. {
  186. i->second.mResources.erase(current);
  187. released = true;
  188. }
  189. }
  190. }
  191. }
  192. }
  193. if (released)
  194. updateResourceGroup(type);
  195. }
  196. bool ResourceCache::reloadResource(Resource* resource)
  197. {
  198. if (!resource)
  199. return false;
  200. try
  201. {
  202. SharedPtr<File> file = getFile(resource->getName());
  203. resource->load(*(file.getPtr()), this);
  204. resource->resetUseTimer();
  205. updateResourceGroup(resource->getType());
  206. return true;
  207. }
  208. catch (...)
  209. {
  210. releaseResource(resource->getType(), resource->getNameHash());
  211. return false;
  212. }
  213. }
  214. void ResourceCache::setMemoryBudget(ShortStringHash type, unsigned budget)
  215. {
  216. mResourceGroups[type].mMemoryBudget = budget;
  217. }
  218. SharedPtr<File> ResourceCache::getFile(const std::string& name)
  219. {
  220. // Check first the packages
  221. for (unsigned i = 0; i < mPackages.size(); ++i)
  222. {
  223. if (mPackages[i]->exists(name))
  224. return SharedPtr<File>(new File(*mPackages[i], name));
  225. }
  226. // Then the filesystem
  227. for (unsigned i = 0; i < mResourcePaths.size(); ++i)
  228. {
  229. if (fileExists(mResourcePaths[i] + name))
  230. {
  231. // Construct the file first with full path, then rename it to not contain the resource path,
  232. // so that the file's name can be used in further getFile() calls (for example over the network)
  233. SharedPtr<File> file(new File(mResourcePaths[i] + name));
  234. file->setName(name);
  235. return file;
  236. }
  237. }
  238. EXCEPTION("Could not find resource " + name);
  239. }
  240. Resource* ResourceCache::getResource(ShortStringHash type, const std::string& name)
  241. {
  242. // Add the name to the hash map, so if this is an unknown resource, the error will not be unintelligible
  243. registerHash(name);
  244. return getResource(type, StringHash(name));
  245. }
  246. Resource* ResourceCache::getResource(ShortStringHash type, StringHash nameHash)
  247. {
  248. // If null hash, return null pointer immediately
  249. if (!nameHash)
  250. return 0;
  251. const SharedPtr<Resource>& existing = findResource(type, nameHash);
  252. if (existing)
  253. return existing;
  254. SharedPtr<Resource> resource;
  255. std::string name = hashToString(nameHash);
  256. for (unsigned i = 0; i < mFactories.size(); ++i)
  257. {
  258. resource = mFactories[i]->createResource(type, name);
  259. if (resource)
  260. break;
  261. }
  262. if (!resource)
  263. {
  264. LOGERROR("Could not load unknown resource type " + toString(type));
  265. return 0;
  266. }
  267. LOGDEBUG("Loading resource " + name);
  268. // Attempt to load the resource
  269. try
  270. {
  271. SharedPtr<File> file = getFile(name);
  272. resource->load(*(file.getPtr()), this);
  273. resource->resetUseTimer();
  274. // Store to cache
  275. mResourceGroups[type].mResources[nameHash] = resource;
  276. updateResourceGroup(type);
  277. return mResourceGroups[type].mResources[nameHash];
  278. }
  279. catch (...)
  280. {
  281. return 0;
  282. }
  283. }
  284. std::vector<Resource*> ResourceCache::getResources(ShortStringHash type)
  285. {
  286. std::vector<Resource*> ret;
  287. std::map<ShortStringHash, ResourceGroup>::const_iterator i = mResourceGroups.find(type);
  288. if (i != mResourceGroups.end())
  289. {
  290. for (std::map<StringHash, SharedPtr<Resource> >::const_iterator j = i->second.mResources.begin();
  291. j != i->second.mResources.end(); ++j)
  292. ret.push_back(j->second);
  293. }
  294. return ret;
  295. }
  296. bool ResourceCache::exists(const std::string& name) const
  297. {
  298. for (unsigned i = 0; i < mPackages.size(); ++i)
  299. {
  300. if (mPackages[i]->exists(name))
  301. return true;
  302. }
  303. for (unsigned i = 0; i < mResourcePaths.size(); ++i)
  304. {
  305. if (fileExists(mResourcePaths[i] + name))
  306. return true;
  307. }
  308. return false;
  309. }
  310. bool ResourceCache::exists(StringHash nameHash) const
  311. {
  312. std::string name = hashToString(nameHash);
  313. return exists(name);
  314. }
  315. unsigned ResourceCache::getMemoryBudget(ShortStringHash type) const
  316. {
  317. std::map<ShortStringHash, ResourceGroup>::const_iterator i = mResourceGroups.find(type);
  318. if (i != mResourceGroups.end())
  319. return i->second.mMemoryBudget;
  320. else
  321. return 0;
  322. }
  323. unsigned ResourceCache::getMemoryUse(ShortStringHash type) const
  324. {
  325. std::map<ShortStringHash, ResourceGroup>::const_iterator i = mResourceGroups.find(type);
  326. if (i != mResourceGroups.end())
  327. return i->second.mMemoryUse;
  328. else
  329. return 0;
  330. }
  331. unsigned ResourceCache::getTotalMemoryUse() const
  332. {
  333. unsigned total = 0;
  334. for (std::map<ShortStringHash, ResourceGroup>::const_iterator i = mResourceGroups.begin(); i != mResourceGroups.end(); ++i)
  335. total += i->second.mMemoryUse;
  336. return total;
  337. }
  338. const SharedPtr<Resource>& ResourceCache::findResource(ShortStringHash type, StringHash nameHash)
  339. {
  340. static const SharedPtr<Resource> noResource;
  341. std::map<ShortStringHash, ResourceGroup>::iterator i = mResourceGroups.find(type);
  342. if (i == mResourceGroups.end())
  343. return noResource;
  344. std::map<StringHash, SharedPtr<Resource> >::iterator j = i->second.mResources.find(nameHash);
  345. if (j == i->second.mResources.end())
  346. return noResource;
  347. return j->second;
  348. }
  349. void ResourceCache::releasePackageResources(PackageFile* package, bool force)
  350. {
  351. std::set<ShortStringHash> affectedGroups;
  352. const std::map<std::string, PackageEntry>& entries = package->getEntries();
  353. for (std::map<std::string, PackageEntry>::const_iterator i = entries.begin(); i != entries.end(); ++i)
  354. {
  355. StringHash nameHash(i->first);
  356. // We do not know the actual resource type, so search all type containers
  357. for (std::map<ShortStringHash, ResourceGroup>::iterator j = mResourceGroups.begin();
  358. j != mResourceGroups.end(); ++j)
  359. {
  360. std::map<StringHash, SharedPtr<Resource> >::iterator k = j->second.mResources.find(nameHash);
  361. if (k != j->second.mResources.end())
  362. {
  363. // If other references exist, do not release, unless forced
  364. if ((k->second.getRefCount() == 1) || (force))
  365. {
  366. j->second.mResources.erase(k);
  367. affectedGroups.insert(j->first);
  368. }
  369. break;
  370. }
  371. }
  372. }
  373. for (std::set<ShortStringHash>::iterator i = affectedGroups.begin(); i != affectedGroups.end(); ++i)
  374. updateResourceGroup(*i);
  375. }
  376. void ResourceCache::updateResourceGroup(ShortStringHash type)
  377. {
  378. std::map<ShortStringHash, ResourceGroup>::iterator i = mResourceGroups.find(type);
  379. if (i == mResourceGroups.end())
  380. return;
  381. for (;;)
  382. {
  383. unsigned totalSize = 0;
  384. unsigned oldestTimer = 0;
  385. std::map<StringHash, SharedPtr<Resource> >::iterator oldestResource = i->second.mResources.end();
  386. for (std::map<StringHash, SharedPtr<Resource> >::iterator j = i->second.mResources.begin();
  387. j != i->second.mResources.end(); ++j)
  388. {
  389. totalSize += j->second->getMemoryUse();
  390. unsigned useTimer = j->second->getUseTimer();
  391. if (useTimer > oldestTimer)
  392. {
  393. oldestTimer = useTimer;
  394. oldestResource = j;
  395. }
  396. }
  397. i->second.mMemoryUse = totalSize;
  398. // If memory budget defined and is exceeded, remove the oldest resource and loop again
  399. // (resources in use always return a zero timer and can not be removed)
  400. if ((i->second.mMemoryBudget) && (i->second.mMemoryUse > i->second.mMemoryBudget) &&
  401. (oldestResource != i->second.mResources.end()))
  402. {
  403. LOGDEBUG("Resource group " + oldestResource->second->getTypeName() + " over memory budget, releasing resource " +
  404. oldestResource->second->getName());
  405. i->second.mResources.erase(oldestResource);
  406. }
  407. else
  408. break;
  409. }
  410. }