ResourceCache.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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. std::string fixedPath = fixPath(path);
  51. std::string pathLower = toLower(fixedPath);
  52. // Check that the same path does not already exist
  53. for (unsigned i = 0; i < mResourcePaths.size(); ++i)
  54. {
  55. if (toLower(mResourcePaths[i]) == pathLower)
  56. return;
  57. }
  58. if (!directoryExists(path))
  59. {
  60. LOGERROR("Could not open directory " + path);
  61. return;
  62. }
  63. checkDirectoryAccess(path);
  64. mResourcePaths.push_back(fixedPath);
  65. // Scan the path for files recursively and add their hash-to-name mappings
  66. std::vector<std::string> fileNames;
  67. scanDirectory(fileNames, fixedPath, "*.*", SCAN_FILES, true);
  68. for (unsigned i = 0; i < fileNames.size(); ++i)
  69. registerHash(fileNames[i]);
  70. LOGINFO("Added resource path " + fixedPath);
  71. }
  72. void ResourceCache::addPackageFile(PackageFile* package, bool addAsFirst)
  73. {
  74. if (!package)
  75. return;
  76. if (addAsFirst)
  77. mPackages.insert(mPackages.begin(), SharedPtr<PackageFile>(package));
  78. else
  79. mPackages.push_back(SharedPtr<PackageFile>(package));
  80. // Scan the package for files and add their hash-to-name mappings
  81. const std::map<std::string, PackageEntry>& entries = package->getEntries();
  82. for (std::map<std::string, PackageEntry>::const_iterator i = entries.begin(); i != entries.end(); ++i)
  83. registerHash(i->first);
  84. LOGINFO("Added resource package " + package->getName());
  85. }
  86. bool ResourceCache::addManualResource(Resource* resource)
  87. {
  88. if (!resource)
  89. {
  90. LOGERROR("Null manual resource");
  91. return false;
  92. }
  93. if (resource->getName().empty())
  94. {
  95. LOGERROR("Manual resource with empty name, can not add");
  96. return false;
  97. }
  98. resource->resetUseTimer();
  99. mResourceGroups[resource->getType()].mResources[resource->getNameHash()] = resource;
  100. updateResourceGroup(resource->getType());
  101. return true;
  102. }
  103. void ResourceCache::removeResourcePath(const std::string& path)
  104. {
  105. for (std::vector<std::string>::iterator i = mResourcePaths.begin(); i != mResourcePaths.end();)
  106. {
  107. if (i->find(path) == 0)
  108. i = mResourcePaths.erase(i);
  109. else
  110. ++i;
  111. }
  112. }
  113. void ResourceCache::removePackageFile(PackageFile* package, bool releaseResources, bool forceRelease)
  114. {
  115. for (std::vector<SharedPtr<PackageFile> >::iterator i = mPackages.begin(); i != mPackages.end(); ++i)
  116. {
  117. if ((*i) == package)
  118. {
  119. if (releaseResources)
  120. releasePackageResources(*i, forceRelease);
  121. mPackages.erase(i);
  122. return;
  123. }
  124. }
  125. }
  126. void ResourceCache::removePackageFile(const std::string& fileName, bool releaseResources, bool forceRelease)
  127. {
  128. for (std::vector<SharedPtr<PackageFile> >::iterator i = mPackages.begin(); i != mPackages.end(); ++i)
  129. {
  130. if ((*i)->getName() == fileName)
  131. {
  132. if (releaseResources)
  133. releasePackageResources(*i, forceRelease);
  134. mPackages.erase(i);
  135. return;
  136. }
  137. }
  138. }
  139. void ResourceCache::releaseResource(ShortStringHash type, const std::string& name, bool force)
  140. {
  141. releaseResource(type, StringHash(name), force);
  142. }
  143. void ResourceCache::releaseResource(ShortStringHash type, StringHash nameHash, bool force)
  144. {
  145. const SharedPtr<Resource>& existingRes = findResource(type, nameHash);
  146. if (!existingRes)
  147. return;
  148. // If other references exist, do not release, unless forced
  149. if ((existingRes.getRefCount() == 1) || (force))
  150. {
  151. mResourceGroups[type].mResources.erase(nameHash);
  152. updateResourceGroup(type);
  153. }
  154. }
  155. void ResourceCache::releaseResources(ShortStringHash type, bool force)
  156. {
  157. bool released = false;
  158. for (std::map<ShortStringHash, ResourceGroup>::iterator i = mResourceGroups.begin();
  159. i != mResourceGroups.end(); ++i)
  160. {
  161. if (i->first == type)
  162. {
  163. for (std::map<StringHash, SharedPtr<Resource> >::iterator j = i->second.mResources.begin();
  164. j != i->second.mResources.end();)
  165. {
  166. std::map<StringHash, SharedPtr<Resource> >::iterator current = j++;
  167. // If other references exist, do not release, unless forced
  168. if ((current->second.getRefCount() == 1) || (force))
  169. {
  170. i->second.mResources.erase(current);
  171. released = true;
  172. }
  173. }
  174. }
  175. }
  176. if (released)
  177. updateResourceGroup(type);
  178. }
  179. void ResourceCache::releaseResources(ShortStringHash type, const std::string& partialName, bool force)
  180. {
  181. std::string partialNameLower = toLower(partialName);
  182. bool released = false;
  183. for (std::map<ShortStringHash, ResourceGroup>::iterator i = mResourceGroups.begin();
  184. i != mResourceGroups.end(); ++i)
  185. {
  186. if (i->first == type)
  187. {
  188. for (std::map<StringHash, SharedPtr<Resource> >::iterator j = i->second.mResources.begin();
  189. j != i->second.mResources.end();)
  190. {
  191. std::map<StringHash, SharedPtr<Resource> >::iterator current = j++;
  192. if (current->second->getName().find(partialNameLower) != std::string::npos)
  193. {
  194. // If other references exist, do not release, unless forced
  195. if ((current->second.getRefCount() == 1) || (force))
  196. {
  197. i->second.mResources.erase(current);
  198. released = true;
  199. }
  200. }
  201. }
  202. }
  203. }
  204. if (released)
  205. updateResourceGroup(type);
  206. }
  207. bool ResourceCache::reloadResource(Resource* resource)
  208. {
  209. if (!resource)
  210. return false;
  211. try
  212. {
  213. SharedPtr<File> file = getFile(resource->getName());
  214. resource->load(*(file.getPtr()), this);
  215. resource->resetUseTimer();
  216. updateResourceGroup(resource->getType());
  217. return true;
  218. }
  219. catch (...)
  220. {
  221. releaseResource(resource->getType(), resource->getNameHash());
  222. return false;
  223. }
  224. }
  225. void ResourceCache::setMemoryBudget(ShortStringHash type, unsigned budget)
  226. {
  227. mResourceGroups[type].mMemoryBudget = budget;
  228. }
  229. SharedPtr<File> ResourceCache::getFile(const std::string& name)
  230. {
  231. // Check first the packages
  232. for (unsigned i = 0; i < mPackages.size(); ++i)
  233. {
  234. if (mPackages[i]->exists(name))
  235. return SharedPtr<File>(new File(*mPackages[i], name));
  236. }
  237. // Then the filesystem
  238. for (unsigned i = 0; i < mResourcePaths.size(); ++i)
  239. {
  240. if (fileExists(mResourcePaths[i] + name))
  241. {
  242. // Construct the file first with full path, then rename it to not contain the resource path,
  243. // so that the file's name can be used in further getFile() calls (for example over the network)
  244. SharedPtr<File> file(new File(mResourcePaths[i] + name));
  245. file->setName(name);
  246. return file;
  247. }
  248. }
  249. EXCEPTION("Could not find resource " + name);
  250. }
  251. Resource* ResourceCache::getResource(ShortStringHash type, const std::string& name)
  252. {
  253. // Add the name to the hash map, so if this is an unknown resource, the error will not be unintelligible
  254. registerHash(name);
  255. return getResource(type, StringHash(name));
  256. }
  257. Resource* ResourceCache::getResource(ShortStringHash type, StringHash nameHash)
  258. {
  259. // If null hash, return null pointer immediately
  260. if (!nameHash)
  261. return 0;
  262. const SharedPtr<Resource>& existing = findResource(type, nameHash);
  263. if (existing)
  264. return existing;
  265. SharedPtr<Resource> resource;
  266. std::string name = hashToString(nameHash);
  267. for (unsigned i = 0; i < mFactories.size(); ++i)
  268. {
  269. resource = mFactories[i]->createResource(type, name);
  270. if (resource)
  271. break;
  272. }
  273. if (!resource)
  274. {
  275. LOGERROR("Could not load unknown resource type " + toString(type));
  276. return 0;
  277. }
  278. LOGDEBUG("Loading resource " + name);
  279. // Attempt to load the resource
  280. try
  281. {
  282. SharedPtr<File> file = getFile(name);
  283. resource->load(*(file.getPtr()), this);
  284. resource->resetUseTimer();
  285. // Store to cache
  286. mResourceGroups[type].mResources[nameHash] = resource;
  287. updateResourceGroup(type);
  288. return mResourceGroups[type].mResources[nameHash];
  289. }
  290. catch (...)
  291. {
  292. return 0;
  293. }
  294. }
  295. void ResourceCache::getResources(std::vector<Resource*>& result, ShortStringHash type) const
  296. {
  297. result.clear();
  298. std::map<ShortStringHash, ResourceGroup>::const_iterator i = mResourceGroups.find(type);
  299. if (i != mResourceGroups.end())
  300. {
  301. for (std::map<StringHash, SharedPtr<Resource> >::const_iterator j = i->second.mResources.begin();
  302. j != i->second.mResources.end(); ++j)
  303. result.push_back(j->second);
  304. }
  305. }
  306. bool ResourceCache::exists(const std::string& name) const
  307. {
  308. for (unsigned i = 0; i < mPackages.size(); ++i)
  309. {
  310. if (mPackages[i]->exists(name))
  311. return true;
  312. }
  313. for (unsigned i = 0; i < mResourcePaths.size(); ++i)
  314. {
  315. if (fileExists(mResourcePaths[i] + name))
  316. return true;
  317. }
  318. return false;
  319. }
  320. bool ResourceCache::exists(StringHash nameHash) const
  321. {
  322. std::string name = hashToString(nameHash);
  323. return exists(name);
  324. }
  325. unsigned ResourceCache::getMemoryBudget(ShortStringHash type) const
  326. {
  327. std::map<ShortStringHash, ResourceGroup>::const_iterator i = mResourceGroups.find(type);
  328. if (i != mResourceGroups.end())
  329. return i->second.mMemoryBudget;
  330. else
  331. return 0;
  332. }
  333. unsigned ResourceCache::getMemoryUse(ShortStringHash type) const
  334. {
  335. std::map<ShortStringHash, ResourceGroup>::const_iterator i = mResourceGroups.find(type);
  336. if (i != mResourceGroups.end())
  337. return i->second.mMemoryUse;
  338. else
  339. return 0;
  340. }
  341. unsigned ResourceCache::getTotalMemoryUse() const
  342. {
  343. unsigned total = 0;
  344. for (std::map<ShortStringHash, ResourceGroup>::const_iterator i = mResourceGroups.begin(); i != mResourceGroups.end(); ++i)
  345. total += i->second.mMemoryUse;
  346. return total;
  347. }
  348. const SharedPtr<Resource>& ResourceCache::findResource(ShortStringHash type, StringHash nameHash)
  349. {
  350. static const SharedPtr<Resource> noResource;
  351. std::map<ShortStringHash, ResourceGroup>::iterator i = mResourceGroups.find(type);
  352. if (i == mResourceGroups.end())
  353. return noResource;
  354. std::map<StringHash, SharedPtr<Resource> >::iterator j = i->second.mResources.find(nameHash);
  355. if (j == i->second.mResources.end())
  356. return noResource;
  357. return j->second;
  358. }
  359. void ResourceCache::releasePackageResources(PackageFile* package, bool force)
  360. {
  361. std::set<ShortStringHash> affectedGroups;
  362. const std::map<std::string, PackageEntry>& entries = package->getEntries();
  363. for (std::map<std::string, PackageEntry>::const_iterator i = entries.begin(); i != entries.end(); ++i)
  364. {
  365. StringHash nameHash(i->first);
  366. // We do not know the actual resource type, so search all type containers
  367. for (std::map<ShortStringHash, ResourceGroup>::iterator j = mResourceGroups.begin();
  368. j != mResourceGroups.end(); ++j)
  369. {
  370. std::map<StringHash, SharedPtr<Resource> >::iterator k = j->second.mResources.find(nameHash);
  371. if (k != j->second.mResources.end())
  372. {
  373. // If other references exist, do not release, unless forced
  374. if ((k->second.getRefCount() == 1) || (force))
  375. {
  376. j->second.mResources.erase(k);
  377. affectedGroups.insert(j->first);
  378. }
  379. break;
  380. }
  381. }
  382. }
  383. for (std::set<ShortStringHash>::iterator i = affectedGroups.begin(); i != affectedGroups.end(); ++i)
  384. updateResourceGroup(*i);
  385. }
  386. void ResourceCache::updateResourceGroup(ShortStringHash type)
  387. {
  388. std::map<ShortStringHash, ResourceGroup>::iterator i = mResourceGroups.find(type);
  389. if (i == mResourceGroups.end())
  390. return;
  391. for (;;)
  392. {
  393. unsigned totalSize = 0;
  394. unsigned oldestTimer = 0;
  395. std::map<StringHash, SharedPtr<Resource> >::iterator oldestResource = i->second.mResources.end();
  396. for (std::map<StringHash, SharedPtr<Resource> >::iterator j = i->second.mResources.begin();
  397. j != i->second.mResources.end(); ++j)
  398. {
  399. totalSize += j->second->getMemoryUse();
  400. unsigned useTimer = j->second->getUseTimer();
  401. if (useTimer > oldestTimer)
  402. {
  403. oldestTimer = useTimer;
  404. oldestResource = j;
  405. }
  406. }
  407. i->second.mMemoryUse = totalSize;
  408. // If memory budget defined and is exceeded, remove the oldest resource and loop again
  409. // (resources in use always return a zero timer and can not be removed)
  410. if ((i->second.mMemoryBudget) && (i->second.mMemoryUse > i->second.mMemoryBudget) &&
  411. (oldestResource != i->second.mResources.end()))
  412. {
  413. LOGDEBUG("Resource group " + oldestResource->second->getTypeName() + " over memory budget, releasing resource " +
  414. oldestResource->second->getName());
  415. i->second.mResources.erase(oldestResource);
  416. }
  417. else
  418. break;
  419. }
  420. }