ResourceCache.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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 "Context.h"
  25. #include "FileSystem.h"
  26. #include "Image.h"
  27. #include "Log.h"
  28. #include "PackageFile.h"
  29. #include "ResourceCache.h"
  30. #include "ResourceEvents.h"
  31. #include "XMLFile.h"
  32. #include "DebugNew.h"
  33. static const String checkDirs[] = {
  34. "Fonts",
  35. "Materials",
  36. "Models",
  37. "Music",
  38. "Objects",
  39. "Particle",
  40. "Scenes",
  41. "Scripts",
  42. "Sounds",
  43. "Shaders",
  44. "Techniques",
  45. "Textures",
  46. "UI",
  47. ""
  48. };
  49. static const String noName;
  50. static const SharedPtr<Resource> noResource;
  51. OBJECTTYPESTATIC(ResourceCache);
  52. ResourceCache::ResourceCache(Context* context) :
  53. Object(context)
  54. {
  55. }
  56. ResourceCache::~ResourceCache()
  57. {
  58. }
  59. bool ResourceCache::AddResourceDir(const String& pathName)
  60. {
  61. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  62. if (!fileSystem || !fileSystem->DirExists(pathName))
  63. {
  64. LOGERROR("Could not open directory " + pathName);
  65. return false;
  66. }
  67. String fixedPath = AddTrailingSlash(pathName);
  68. // Check that the same path does not already exist
  69. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  70. {
  71. if (!resourceDirs_[i].Compare(fixedPath, false))
  72. return true;
  73. }
  74. resourceDirs_.Push(fixedPath);
  75. // Scan the path for files recursively and add their hash-to-name mappings
  76. Vector<String> fileNames;
  77. fileSystem->ScanDir(fileNames, fixedPath, "*.*", SCAN_FILES, true);
  78. for (unsigned i = 0; i < fileNames.Size(); ++i)
  79. StoreNameHash(fileNames[i]);
  80. LOGINFO("Added resource path " + fixedPath);
  81. return true;
  82. }
  83. void ResourceCache::AddPackageFile(PackageFile* package, bool addAsFirst)
  84. {
  85. // Do not add packages that failed to load
  86. if (!package || !package->GetNumFiles())
  87. return;
  88. if (addAsFirst)
  89. packages_.Insert(packages_.Begin(), SharedPtr<PackageFile>(package));
  90. else
  91. packages_.Push(SharedPtr<PackageFile>(package));
  92. // Scan the package for files and add their hash-to-name mappings
  93. const Map<String, PackageEntry>& entries = package->GetEntries();
  94. for (Map<String, PackageEntry>::ConstIterator i = entries.Begin(); i != entries.End(); ++i)
  95. StoreNameHash(i->first_);
  96. LOGINFO("Added resource package " + package->GetName());
  97. }
  98. bool ResourceCache::AddManualResource(Resource* resource)
  99. {
  100. if (!resource)
  101. {
  102. LOGERROR("Null manual resource");
  103. return false;
  104. }
  105. const String& name = resource->GetName();
  106. if (name.Empty())
  107. {
  108. LOGERROR("Manual resource with empty name, can not add");
  109. return false;
  110. }
  111. StoreNameHash(name);
  112. resource->ResetUseTimer();
  113. resourceGroups_[resource->GetType()].resources_[resource->GetNameHash()] = resource;
  114. UpdateResourceGroup(resource->GetType());
  115. return true;
  116. }
  117. void ResourceCache::RemoveResourceDir(const String& path)
  118. {
  119. String fixedPath = AddTrailingSlash(path);
  120. for (Vector<String>::Iterator i = resourceDirs_.Begin(); i != resourceDirs_.End(); ++i)
  121. {
  122. if (!i->Compare(path, false))
  123. {
  124. resourceDirs_.Erase(i);
  125. LOGINFO("Removed resource path " + fixedPath);
  126. return;
  127. }
  128. }
  129. }
  130. void ResourceCache::RemovePackageFile(PackageFile* package, bool releaseResources, bool forceRelease)
  131. {
  132. for (Vector<SharedPtr<PackageFile> >::Iterator i = packages_.Begin(); i != packages_.End(); ++i)
  133. {
  134. if (*i == package)
  135. {
  136. if (releaseResources)
  137. ReleasePackageResources(*i, forceRelease);
  138. LOGINFO("Removed resource package " + (*i)->GetName());
  139. packages_.Erase(i);
  140. return;
  141. }
  142. }
  143. }
  144. void ResourceCache::RemovePackageFile(const String& fileName, bool releaseResources, bool forceRelease)
  145. {
  146. // Compare the name and extension only, not the path
  147. String fileNameNoPath = GetFileNameAndExtension(fileName);
  148. for (Vector<SharedPtr<PackageFile> >::Iterator i = packages_.Begin(); i != packages_.End(); ++i)
  149. {
  150. if (!GetFileNameAndExtension((*i)->GetName()).Compare(fileNameNoPath, false))
  151. {
  152. if (releaseResources)
  153. ReleasePackageResources(*i, forceRelease);
  154. LOGINFO("Removed resource package " + (*i)->GetName());
  155. packages_.Erase(i);
  156. return;
  157. }
  158. }
  159. }
  160. void ResourceCache::ReleaseResource(ShortStringHash type, const String& name, bool force)
  161. {
  162. ReleaseResource(type, StringHash(name), force);
  163. }
  164. void ResourceCache::ReleaseResource(ShortStringHash type, StringHash nameHash, bool force)
  165. {
  166. const SharedPtr<Resource>& existingRes = FindResource(type, nameHash);
  167. if (!existingRes)
  168. return;
  169. // If other references exist, do not release, unless forced
  170. if (existingRes.Refs() == 1 || force)
  171. {
  172. resourceGroups_[type].resources_.Erase(nameHash);
  173. UpdateResourceGroup(type);
  174. }
  175. }
  176. void ResourceCache::ReleaseResources(ShortStringHash type, bool force)
  177. {
  178. bool released = false;
  179. for (Map<ShortStringHash, ResourceGroup>::Iterator i = resourceGroups_.Begin();
  180. i != resourceGroups_.End(); ++i)
  181. {
  182. if (i->first_ == type)
  183. {
  184. for (Map<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin();
  185. j != i->second_.resources_.End();)
  186. {
  187. Map<StringHash, SharedPtr<Resource> >::Iterator current = j++;
  188. // If other references exist, do not release, unless forced
  189. if (current->second_.Refs() == 1 || force)
  190. {
  191. i->second_.resources_.Erase(current);
  192. released = true;
  193. }
  194. }
  195. }
  196. }
  197. if (released)
  198. UpdateResourceGroup(type);
  199. }
  200. void ResourceCache::ReleaseResources(ShortStringHash type, const String& partialName, bool force)
  201. {
  202. bool released = false;
  203. for (Map<ShortStringHash, ResourceGroup>::Iterator i = resourceGroups_.Begin();
  204. i != resourceGroups_.End(); ++i)
  205. {
  206. if (i->first_ == type)
  207. {
  208. for (Map<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin();
  209. j != i->second_.resources_.End();)
  210. {
  211. Map<StringHash, SharedPtr<Resource> >::Iterator current = j++;
  212. if (current->second_->GetName().Find(partialName) != String::NPOS)
  213. {
  214. // If other references exist, do not release, unless forced
  215. if (current->second_.Refs() == 1 || force)
  216. {
  217. i->second_.resources_.Erase(current);
  218. released = true;
  219. }
  220. }
  221. }
  222. }
  223. }
  224. if (released)
  225. UpdateResourceGroup(type);
  226. }
  227. void ResourceCache::ReleaseAllResources(bool force)
  228. {
  229. for (Map<ShortStringHash, ResourceGroup>::Iterator i = resourceGroups_.Begin();
  230. i != resourceGroups_.End(); ++i)
  231. {
  232. bool released = false;
  233. for (Map<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin();
  234. j != i->second_.resources_.End();)
  235. {
  236. Map<StringHash, SharedPtr<Resource> >::Iterator current = j++;
  237. // If other references exist, do not release, unless forced
  238. if (current->second_.Refs() == 1 || force)
  239. {
  240. i->second_.resources_.Erase(current);
  241. released = true;
  242. }
  243. }
  244. if (released)
  245. UpdateResourceGroup(i->first_);
  246. }
  247. }
  248. bool ResourceCache::ReloadResource(Resource* resource)
  249. {
  250. if (!resource)
  251. return false;
  252. resource->SendEvent(E_RELOADSTARTED);
  253. bool success = false;
  254. SharedPtr<File> file = GetFile(resource->GetName());
  255. if (file)
  256. success = resource->Load(*(file.Get()));
  257. if (success)
  258. {
  259. resource->ResetUseTimer();
  260. UpdateResourceGroup(resource->GetType());
  261. resource->SendEvent(E_RELOADFINISHED);
  262. return true;
  263. }
  264. // If reloading failed, remove the resource from cache
  265. resource->SendEvent(E_RELOADFAILED);
  266. ReleaseResource(resource->GetType(), resource->GetNameHash());
  267. return false;
  268. }
  269. void ResourceCache::SetMemoryBudget(ShortStringHash type, unsigned budget)
  270. {
  271. resourceGroups_[type].memoryBudget_ = budget;
  272. }
  273. SharedPtr<File> ResourceCache::GetFile(const String& name)
  274. {
  275. // Check first the packages
  276. for (unsigned i = 0; i < packages_.Size(); ++i)
  277. {
  278. if (packages_[i]->Exists(name))
  279. return SharedPtr<File>(new File(context_, packages_[i], name));
  280. }
  281. // Then the filesystem
  282. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  283. if (fileSystem)
  284. {
  285. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  286. {
  287. if (fileSystem->FileExists(resourceDirs_[i] + name))
  288. {
  289. // Construct the file first with full path, then rename it to not contain the resource path,
  290. // so that the file's name can be used in further GetFile() calls (for example over the network)
  291. SharedPtr<File> file(new File(context_, resourceDirs_[i] + name));
  292. file->SetName(name);
  293. return file;
  294. }
  295. }
  296. }
  297. LOGERROR("Could not find resource " + name);
  298. return SharedPtr<File>();
  299. }
  300. Resource* ResourceCache::GetResource(ShortStringHash type, const String& name)
  301. {
  302. // Add the name to the hash map, so if this is an unknown resource, the error will not be unintelligible
  303. StoreNameHash(name);
  304. return GetResource(type, StringHash(name));
  305. }
  306. Resource* ResourceCache::GetResource(ShortStringHash type, StringHash nameHash)
  307. {
  308. // If null hash, return null pointer immediately
  309. if (!nameHash)
  310. return 0;
  311. const SharedPtr<Resource>& existing = FindResource(type, nameHash);
  312. if (existing)
  313. return existing;
  314. SharedPtr<Resource> resource;
  315. const String& name = GetResourceName(nameHash);
  316. if (name.Empty())
  317. {
  318. LOGERROR("Could not load unknown resource " + String(nameHash));
  319. return 0;
  320. }
  321. // Make sure the pointer is non-null and is a Resource subclass
  322. resource = DynamicCast<Resource>(context_->CreateObject(type));
  323. if (!resource)
  324. {
  325. LOGERROR("Could not load unknown resource type " + String(type));
  326. return 0;
  327. }
  328. // Attempt to load the resource
  329. SharedPtr<File> file = GetFile(name);
  330. if (!file)
  331. return 0;
  332. LOGDEBUG("Loading resource " + name);
  333. resource->SetName(file->GetName());
  334. if (!resource->Load(*(file.Get())))
  335. return 0;
  336. // Store to cache
  337. resource->ResetUseTimer();
  338. resourceGroups_[type].resources_[nameHash] = resource;
  339. UpdateResourceGroup(type);
  340. return resource;
  341. }
  342. void ResourceCache::GetResources(PODVector<Resource*>& result, ShortStringHash type) const
  343. {
  344. result.Clear();
  345. Map<ShortStringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Find(type);
  346. if (i != resourceGroups_.End())
  347. {
  348. for (Map<StringHash, SharedPtr<Resource> >::ConstIterator j = i->second_.resources_.Begin();
  349. j != i->second_.resources_.End(); ++j)
  350. result.Push(j->second_);
  351. }
  352. }
  353. bool ResourceCache::Exists(const String& name) const
  354. {
  355. for (unsigned i = 0; i < packages_.Size(); ++i)
  356. {
  357. if (packages_[i]->Exists(name))
  358. return true;
  359. }
  360. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  361. if (fileSystem)
  362. {
  363. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  364. {
  365. if (fileSystem->FileExists(resourceDirs_[i] + name))
  366. return true;
  367. }
  368. }
  369. return false;
  370. }
  371. bool ResourceCache::Exists(StringHash nameHash) const
  372. {
  373. return Exists(GetResourceName(nameHash));
  374. }
  375. unsigned ResourceCache::GetMemoryBudget(ShortStringHash type) const
  376. {
  377. Map<ShortStringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Find(type);
  378. if (i != resourceGroups_.End())
  379. return i->second_.memoryBudget_;
  380. else
  381. return 0;
  382. }
  383. unsigned ResourceCache::GetMemoryUse(ShortStringHash type) const
  384. {
  385. Map<ShortStringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Find(type);
  386. if (i != resourceGroups_.End())
  387. return i->second_.memoryUse_;
  388. else
  389. return 0;
  390. }
  391. unsigned ResourceCache::GetTotalMemoryUse() const
  392. {
  393. unsigned total = 0;
  394. for (Map<ShortStringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Begin(); i != resourceGroups_.End(); ++i)
  395. total += i->second_.memoryUse_;
  396. return total;
  397. }
  398. const String& ResourceCache::GetResourceName(StringHash nameHash) const
  399. {
  400. Map<StringHash, String>::ConstIterator i = hashToName_.Find(nameHash);
  401. if (i == hashToName_.End())
  402. return noName;
  403. else
  404. return i->second_;
  405. }
  406. String ResourceCache::GetPreferredResourceDir(const String& path)
  407. {
  408. String fixedPath = AddTrailingSlash(path);
  409. bool pathHasKnownDirs = false;
  410. bool parentHasKnownDirs = false;
  411. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  412. // If no filesystem, can not check directory existence, so just return the original path
  413. if (!fileSystem)
  414. return fixedPath;
  415. for (unsigned i = 0; !checkDirs[i].Empty(); ++i)
  416. {
  417. if (fileSystem->DirExists(fixedPath + checkDirs[i]))
  418. {
  419. pathHasKnownDirs = true;
  420. break;
  421. }
  422. }
  423. if (!pathHasKnownDirs)
  424. {
  425. String parentPath = GetParentPath(fixedPath);
  426. for (unsigned i = 0; !checkDirs[i].Empty(); ++i)
  427. {
  428. if (fileSystem->DirExists(parentPath + checkDirs[i]))
  429. {
  430. parentHasKnownDirs = true;
  431. break;
  432. }
  433. }
  434. // If path does not have known subdirectories, but the parent path has, use the parent instead
  435. if (parentHasKnownDirs)
  436. fixedPath = parentPath;
  437. }
  438. return fixedPath;
  439. }
  440. void ResourceCache::StoreNameHash(const String& name)
  441. {
  442. if (name.Empty())
  443. return;
  444. hashToName_[StringHash(name)] = name;
  445. }
  446. const SharedPtr<Resource>& ResourceCache::FindResource(ShortStringHash type, StringHash nameHash)
  447. {
  448. Map<ShortStringHash, ResourceGroup>::Iterator i = resourceGroups_.Find(type);
  449. if (i == resourceGroups_.End())
  450. return noResource;
  451. Map<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Find(nameHash);
  452. if (j == i->second_.resources_.End())
  453. return noResource;
  454. return j->second_;
  455. }
  456. void ResourceCache::ReleasePackageResources(PackageFile* package, bool force)
  457. {
  458. HashSet<ShortStringHash> affectedGroups;
  459. const Map<String, PackageEntry>& entries = package->GetEntries();
  460. for (Map<String, PackageEntry>::ConstIterator i = entries.Begin(); i != entries.End(); ++i)
  461. {
  462. StringHash nameHash(i->first_);
  463. // We do not know the actual resource type, so search all type containers
  464. for (Map<ShortStringHash, ResourceGroup>::Iterator j = resourceGroups_.Begin();
  465. j != resourceGroups_.End(); ++j)
  466. {
  467. Map<StringHash, SharedPtr<Resource> >::Iterator k = j->second_.resources_.Find(nameHash);
  468. if (k != j->second_.resources_.End())
  469. {
  470. // If other references exist, do not release, unless forced
  471. if (k->second_.Refs() == 1 || force)
  472. {
  473. j->second_.resources_.Erase(k);
  474. affectedGroups.Insert(j->first_);
  475. }
  476. break;
  477. }
  478. }
  479. }
  480. for (HashSet<ShortStringHash>::Iterator i = affectedGroups.Begin(); i != affectedGroups.End(); ++i)
  481. UpdateResourceGroup(*i);
  482. }
  483. void ResourceCache::UpdateResourceGroup(ShortStringHash type)
  484. {
  485. Map<ShortStringHash, ResourceGroup>::Iterator i = resourceGroups_.Find(type);
  486. if (i == resourceGroups_.End())
  487. return;
  488. for (;;)
  489. {
  490. unsigned totalSize = 0;
  491. unsigned oldestTimer = 0;
  492. Map<StringHash, SharedPtr<Resource> >::Iterator oldestResource = i->second_.resources_.End();
  493. for (Map<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin();
  494. j != i->second_.resources_.End(); ++j)
  495. {
  496. totalSize += j->second_->GetMemoryUse();
  497. unsigned useTimer = j->second_->GetUseTimer();
  498. if (useTimer > oldestTimer)
  499. {
  500. oldestTimer = useTimer;
  501. oldestResource = j;
  502. }
  503. }
  504. i->second_.memoryUse_ = totalSize;
  505. // If memory budget defined and is exceeded, remove the oldest resource and loop again
  506. // (resources in use always return a zero timer and can not be removed)
  507. if (i->second_.memoryBudget_ && i->second_.memoryUse_ > i->second_.memoryBudget_ &&
  508. oldestResource != i->second_.resources_.End())
  509. {
  510. LOGDEBUG("Resource group " + oldestResource->second_->GetTypeName() + " over memory budget, releasing resource " +
  511. oldestResource->second_->GetName());
  512. i->second_.resources_.Erase(oldestResource);
  513. }
  514. else
  515. break;
  516. }
  517. }
  518. void RegisterResourceLibrary(Context* context)
  519. {
  520. Image::RegisterObject(context);
  521. XMLFile::RegisterObject(context);
  522. }