ResourceCache.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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. bool ResourceCache::addResourcePath(const std::string& path)
  49. {
  50. if (!directoryExists(path))
  51. {
  52. LOGERROR("Could not open directory " + path);
  53. return false;
  54. }
  55. std::string fixedPath = fixPath(path);
  56. std::string pathLower = toLower(fixedPath);
  57. // Check that the same path does not already exist
  58. for (unsigned i = 0; i < mResourcePaths.size(); ++i)
  59. {
  60. if (toLower(mResourcePaths[i]) == pathLower)
  61. return true;
  62. }
  63. mResourcePaths.push_back(fixedPath);
  64. // Scan the path for files recursively and add their hash-to-name mappings
  65. std::vector<std::string> fileNames;
  66. scanDirectory(fileNames, fixedPath, "*.*", SCAN_FILES, true);
  67. for (unsigned i = 0; i < fileNames.size(); ++i)
  68. registerHash(fileNames[i]);
  69. LOGINFO("Added resource path " + fixedPath);
  70. return true;
  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. std::string fixedPath = toLower(fixPath(path));
  106. for (std::vector<std::string>::iterator i = mResourcePaths.begin(); i != mResourcePaths.end(); ++i)
  107. {
  108. if (toLower(*i) == fixedPath)
  109. {
  110. mResourcePaths.erase(i);
  111. return;
  112. }
  113. }
  114. }
  115. void ResourceCache::removePackageFile(PackageFile* package, bool releaseResources, bool forceRelease)
  116. {
  117. for (std::vector<SharedPtr<PackageFile> >::iterator i = mPackages.begin(); i != mPackages.end(); ++i)
  118. {
  119. if ((*i) == package)
  120. {
  121. if (releaseResources)
  122. releasePackageResources(*i, forceRelease);
  123. mPackages.erase(i);
  124. return;
  125. }
  126. }
  127. }
  128. void ResourceCache::removePackageFile(const std::string& fileName, bool releaseResources, bool forceRelease)
  129. {
  130. std::string fileNameLower = toLower(fileName);
  131. for (std::vector<SharedPtr<PackageFile> >::iterator i = mPackages.begin(); i != mPackages.end(); ++i)
  132. {
  133. if (toLower((*i)->getName()) == fileNameLower)
  134. {
  135. if (releaseResources)
  136. releasePackageResources(*i, forceRelease);
  137. mPackages.erase(i);
  138. return;
  139. }
  140. }
  141. }
  142. void ResourceCache::releaseResource(ShortStringHash type, const std::string& name, bool force)
  143. {
  144. releaseResource(type, StringHash(name), force);
  145. }
  146. void ResourceCache::releaseResource(ShortStringHash type, StringHash nameHash, bool force)
  147. {
  148. const SharedPtr<Resource>& existingRes = findResource(type, nameHash);
  149. if (!existingRes)
  150. return;
  151. // If other references exist, do not release, unless forced
  152. if ((existingRes.getRefCount() == 1) || (force))
  153. {
  154. mResourceGroups[type].mResources.erase(nameHash);
  155. updateResourceGroup(type);
  156. }
  157. }
  158. void ResourceCache::releaseResources(ShortStringHash type, bool force)
  159. {
  160. bool released = false;
  161. for (std::map<ShortStringHash, ResourceGroup>::iterator i = mResourceGroups.begin();
  162. i != mResourceGroups.end(); ++i)
  163. {
  164. if (i->first == type)
  165. {
  166. for (std::map<StringHash, SharedPtr<Resource> >::iterator j = i->second.mResources.begin();
  167. j != i->second.mResources.end();)
  168. {
  169. std::map<StringHash, SharedPtr<Resource> >::iterator current = j++;
  170. // If other references exist, do not release, unless forced
  171. if ((current->second.getRefCount() == 1) || (force))
  172. {
  173. i->second.mResources.erase(current);
  174. released = true;
  175. }
  176. }
  177. }
  178. }
  179. if (released)
  180. updateResourceGroup(type);
  181. }
  182. void ResourceCache::releaseResources(ShortStringHash type, const std::string& partialName, bool force)
  183. {
  184. std::string partialNameLower = toLower(partialName);
  185. bool released = false;
  186. for (std::map<ShortStringHash, ResourceGroup>::iterator i = mResourceGroups.begin();
  187. i != mResourceGroups.end(); ++i)
  188. {
  189. if (i->first == type)
  190. {
  191. for (std::map<StringHash, SharedPtr<Resource> >::iterator j = i->second.mResources.begin();
  192. j != i->second.mResources.end();)
  193. {
  194. std::map<StringHash, SharedPtr<Resource> >::iterator current = j++;
  195. if (current->second->getName().find(partialNameLower) != std::string::npos)
  196. {
  197. // If other references exist, do not release, unless forced
  198. if ((current->second.getRefCount() == 1) || (force))
  199. {
  200. i->second.mResources.erase(current);
  201. released = true;
  202. }
  203. }
  204. }
  205. }
  206. }
  207. if (released)
  208. updateResourceGroup(type);
  209. }
  210. void ResourceCache::releaseAllResources(bool force)
  211. {
  212. for (std::map<ShortStringHash, ResourceGroup>::iterator i = mResourceGroups.begin();
  213. i != mResourceGroups.end(); ++i)
  214. {
  215. bool released = false;
  216. for (std::map<StringHash, SharedPtr<Resource> >::iterator j = i->second.mResources.begin();
  217. j != i->second.mResources.end();)
  218. {
  219. std::map<StringHash, SharedPtr<Resource> >::iterator current = j++;
  220. // If other references exist, do not release, unless forced
  221. if ((current->second.getRefCount() == 1) || (force))
  222. {
  223. i->second.mResources.erase(current);
  224. released = true;
  225. }
  226. }
  227. if (released)
  228. updateResourceGroup(i->first);
  229. }
  230. }
  231. bool ResourceCache::reloadResource(Resource* resource)
  232. {
  233. if (!resource)
  234. return false;
  235. try
  236. {
  237. SharedPtr<File> file = getFile(resource->getName());
  238. resource->load(*(file.getPtr()), this);
  239. resource->resetUseTimer();
  240. updateResourceGroup(resource->getType());
  241. return true;
  242. }
  243. catch (...)
  244. {
  245. releaseResource(resource->getType(), resource->getNameHash());
  246. return false;
  247. }
  248. }
  249. void ResourceCache::setMemoryBudget(ShortStringHash type, unsigned budget)
  250. {
  251. mResourceGroups[type].mMemoryBudget = budget;
  252. }
  253. SharedPtr<File> ResourceCache::getFile(const std::string& name)
  254. {
  255. // Check first the packages
  256. for (unsigned i = 0; i < mPackages.size(); ++i)
  257. {
  258. if (mPackages[i]->exists(name))
  259. return SharedPtr<File>(new File(*mPackages[i], name));
  260. }
  261. // Then the filesystem
  262. for (unsigned i = 0; i < mResourcePaths.size(); ++i)
  263. {
  264. if (fileExists(mResourcePaths[i] + name))
  265. {
  266. // Construct the file first with full path, then rename it to not contain the resource path,
  267. // so that the file's name can be used in further getFile() calls (for example over the network)
  268. SharedPtr<File> file(new File(mResourcePaths[i] + name));
  269. file->setName(name);
  270. return file;
  271. }
  272. }
  273. EXCEPTION("Could not find resource " + name);
  274. }
  275. Resource* ResourceCache::getResource(ShortStringHash type, const std::string& name)
  276. {
  277. // Add the name to the hash map, so if this is an unknown resource, the error will not be unintelligible
  278. registerHash(name);
  279. return getResource(type, StringHash(name));
  280. }
  281. Resource* ResourceCache::getResource(ShortStringHash type, StringHash nameHash)
  282. {
  283. // If null hash, return null pointer immediately
  284. if (!nameHash)
  285. return 0;
  286. const SharedPtr<Resource>& existing = findResource(type, nameHash);
  287. if (existing)
  288. return existing;
  289. SharedPtr<Resource> resource;
  290. std::string name = hashToString(nameHash);
  291. for (unsigned i = 0; i < mFactories.size(); ++i)
  292. {
  293. resource = mFactories[i]->createResource(type, name);
  294. if (resource)
  295. break;
  296. }
  297. if (!resource)
  298. {
  299. LOGERROR("Could not load unknown resource type " + toString(type));
  300. return 0;
  301. }
  302. LOGDEBUG("Loading resource " + name);
  303. // Attempt to load the resource
  304. try
  305. {
  306. SharedPtr<File> file = getFile(name);
  307. resource->load(*(file.getPtr()), this);
  308. resource->resetUseTimer();
  309. // Store to cache
  310. mResourceGroups[type].mResources[nameHash] = resource;
  311. updateResourceGroup(type);
  312. return mResourceGroups[type].mResources[nameHash];
  313. }
  314. catch (...)
  315. {
  316. return 0;
  317. }
  318. }
  319. void ResourceCache::getResources(std::vector<Resource*>& result, ShortStringHash type) const
  320. {
  321. result.clear();
  322. std::map<ShortStringHash, ResourceGroup>::const_iterator i = mResourceGroups.find(type);
  323. if (i != mResourceGroups.end())
  324. {
  325. for (std::map<StringHash, SharedPtr<Resource> >::const_iterator j = i->second.mResources.begin();
  326. j != i->second.mResources.end(); ++j)
  327. result.push_back(j->second);
  328. }
  329. }
  330. bool ResourceCache::exists(const std::string& name) const
  331. {
  332. for (unsigned i = 0; i < mPackages.size(); ++i)
  333. {
  334. if (mPackages[i]->exists(name))
  335. return true;
  336. }
  337. for (unsigned i = 0; i < mResourcePaths.size(); ++i)
  338. {
  339. if (fileExists(mResourcePaths[i] + name))
  340. return true;
  341. }
  342. return false;
  343. }
  344. bool ResourceCache::exists(StringHash nameHash) const
  345. {
  346. std::string name = hashToString(nameHash);
  347. return exists(name);
  348. }
  349. unsigned ResourceCache::getMemoryBudget(ShortStringHash type) const
  350. {
  351. std::map<ShortStringHash, ResourceGroup>::const_iterator i = mResourceGroups.find(type);
  352. if (i != mResourceGroups.end())
  353. return i->second.mMemoryBudget;
  354. else
  355. return 0;
  356. }
  357. unsigned ResourceCache::getMemoryUse(ShortStringHash type) const
  358. {
  359. std::map<ShortStringHash, ResourceGroup>::const_iterator i = mResourceGroups.find(type);
  360. if (i != mResourceGroups.end())
  361. return i->second.mMemoryUse;
  362. else
  363. return 0;
  364. }
  365. unsigned ResourceCache::getTotalMemoryUse() const
  366. {
  367. unsigned total = 0;
  368. for (std::map<ShortStringHash, ResourceGroup>::const_iterator i = mResourceGroups.begin(); i != mResourceGroups.end(); ++i)
  369. total += i->second.mMemoryUse;
  370. return total;
  371. }
  372. std::string ResourceCache::getPreferredResourcePath(const std::string& path)
  373. {
  374. std::string fixedPath = fixPath(path);
  375. // Check for the existence of some known resource subdirectories to decide if we should add the parent directory instead
  376. static const std::string checkDirs[] = {
  377. "Fonts",
  378. "Materials",
  379. "Models",
  380. "Music",
  381. "Particle",
  382. "Physics",
  383. "Scripts",
  384. "Sounds",
  385. "Shaders",
  386. "Textures",
  387. "UI",
  388. ""
  389. };
  390. bool pathHasKnownDirs = false;
  391. bool parentHasKnownDirs = false;
  392. for (unsigned i = 0; !checkDirs[i].empty(); ++i)
  393. {
  394. if (directoryExists(fixedPath + checkDirs[i]))
  395. {
  396. pathHasKnownDirs = true;
  397. break;
  398. }
  399. }
  400. if (!pathHasKnownDirs)
  401. {
  402. std::string parentPath = getParentPath(fixedPath);
  403. for (unsigned i = 0; !checkDirs[i].empty(); ++i)
  404. {
  405. if (directoryExists(parentPath + checkDirs[i]))
  406. {
  407. parentHasKnownDirs = true;
  408. break;
  409. }
  410. }
  411. // If path does not have known subdirectories, but the parent path has, use the parent instead
  412. if (parentHasKnownDirs)
  413. fixedPath = parentPath;
  414. }
  415. return fixedPath;
  416. }
  417. const SharedPtr<Resource>& ResourceCache::findResource(ShortStringHash type, StringHash nameHash)
  418. {
  419. static const SharedPtr<Resource> noResource;
  420. std::map<ShortStringHash, ResourceGroup>::iterator i = mResourceGroups.find(type);
  421. if (i == mResourceGroups.end())
  422. return noResource;
  423. std::map<StringHash, SharedPtr<Resource> >::iterator j = i->second.mResources.find(nameHash);
  424. if (j == i->second.mResources.end())
  425. return noResource;
  426. return j->second;
  427. }
  428. void ResourceCache::releasePackageResources(PackageFile* package, bool force)
  429. {
  430. std::set<ShortStringHash> affectedGroups;
  431. const std::map<std::string, PackageEntry>& entries = package->getEntries();
  432. for (std::map<std::string, PackageEntry>::const_iterator i = entries.begin(); i != entries.end(); ++i)
  433. {
  434. StringHash nameHash(i->first);
  435. // We do not know the actual resource type, so search all type containers
  436. for (std::map<ShortStringHash, ResourceGroup>::iterator j = mResourceGroups.begin();
  437. j != mResourceGroups.end(); ++j)
  438. {
  439. std::map<StringHash, SharedPtr<Resource> >::iterator k = j->second.mResources.find(nameHash);
  440. if (k != j->second.mResources.end())
  441. {
  442. // If other references exist, do not release, unless forced
  443. if ((k->second.getRefCount() == 1) || (force))
  444. {
  445. j->second.mResources.erase(k);
  446. affectedGroups.insert(j->first);
  447. }
  448. break;
  449. }
  450. }
  451. }
  452. for (std::set<ShortStringHash>::iterator i = affectedGroups.begin(); i != affectedGroups.end(); ++i)
  453. updateResourceGroup(*i);
  454. }
  455. void ResourceCache::updateResourceGroup(ShortStringHash type)
  456. {
  457. std::map<ShortStringHash, ResourceGroup>::iterator i = mResourceGroups.find(type);
  458. if (i == mResourceGroups.end())
  459. return;
  460. for (;;)
  461. {
  462. unsigned totalSize = 0;
  463. unsigned oldestTimer = 0;
  464. std::map<StringHash, SharedPtr<Resource> >::iterator oldestResource = i->second.mResources.end();
  465. for (std::map<StringHash, SharedPtr<Resource> >::iterator j = i->second.mResources.begin();
  466. j != i->second.mResources.end(); ++j)
  467. {
  468. totalSize += j->second->getMemoryUse();
  469. unsigned useTimer = j->second->getUseTimer();
  470. if (useTimer > oldestTimer)
  471. {
  472. oldestTimer = useTimer;
  473. oldestResource = j;
  474. }
  475. }
  476. i->second.mMemoryUse = totalSize;
  477. // If memory budget defined and is exceeded, remove the oldest resource and loop again
  478. // (resources in use always return a zero timer and can not be removed)
  479. if ((i->second.mMemoryBudget) && (i->second.mMemoryUse > i->second.mMemoryBudget) &&
  480. (oldestResource != i->second.mResources.end()))
  481. {
  482. LOGDEBUG("Resource group " + oldestResource->second->getTypeName() + " over memory budget, releasing resource " +
  483. oldestResource->second->getName());
  484. i->second.mResources.erase(oldestResource);
  485. }
  486. else
  487. break;
  488. }
  489. }