ResourceCache.cpp 19 KB

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