ResourceCache.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  1. //
  2. // Copyright (c) 2008-2016 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/CoreEvents.h"
  25. #include "../Core/Profiler.h"
  26. #include "../Core/WorkQueue.h"
  27. #include "../IO/FileSystem.h"
  28. #include "../IO/FileWatcher.h"
  29. #include "../IO/Log.h"
  30. #include "../IO/PackageFile.h"
  31. #include "../Resource/BackgroundLoader.h"
  32. #include "../Resource/Image.h"
  33. #include "../Resource/JSONFile.h"
  34. #include "../Resource/PListFile.h"
  35. #include "../Resource/ResourceCache.h"
  36. #include "../Resource/ResourceEvents.h"
  37. #include "../Resource/XMLFile.h"
  38. #include "../DebugNew.h"
  39. #include <cstdio>
  40. namespace Atomic
  41. {
  42. // ATOMIC BEGIN
  43. const char* PAK_EXTENSION = ".pak";
  44. // ATOMIC END
  45. static const char* checkDirs[] =
  46. {
  47. "Fonts",
  48. "Materials",
  49. "Models",
  50. "Music",
  51. "Objects",
  52. "Particle",
  53. "PostProcess",
  54. "RenderPaths",
  55. "Scenes",
  56. "Scripts",
  57. "Sounds",
  58. "Shaders",
  59. "Techniques",
  60. "Textures",
  61. "UI",
  62. 0
  63. };
  64. static const SharedPtr<Resource> noResource;
  65. ResourceCache::ResourceCache(Context* context) :
  66. Object(context),
  67. autoReloadResources_(false),
  68. returnFailedResources_(false),
  69. searchPackagesFirst_(true),
  70. isRouting_(false),
  71. finishBackgroundResourcesMs_(5)
  72. {
  73. // Register Resource library object factories
  74. RegisterResourceLibrary(context_);
  75. #ifdef ATOMIC_THREADING
  76. // Create resource background loader. Its thread will start on the first background request
  77. backgroundLoader_ = new BackgroundLoader(this);
  78. #endif
  79. // Subscribe BeginFrame for handling directory watchers and background loaded resource finalization
  80. SubscribeToEvent(E_BEGINFRAME, ATOMIC_HANDLER(ResourceCache, HandleBeginFrame));
  81. }
  82. ResourceCache::~ResourceCache()
  83. {
  84. #ifdef ATOMIC_THREADING
  85. // Shut down the background loader first
  86. backgroundLoader_.Reset();
  87. #endif
  88. }
  89. bool ResourceCache::AddResourceDir(const String& pathName, unsigned priority)
  90. {
  91. MutexLock lock(resourceMutex_);
  92. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  93. if (!fileSystem || !fileSystem->DirExists(pathName))
  94. {
  95. ATOMIC_LOGERROR("Could not open directory " + pathName);
  96. return false;
  97. }
  98. // Convert path to absolute
  99. String fixedPath = SanitateResourceDirName(pathName);
  100. // Check that the same path does not already exist
  101. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  102. {
  103. if (!resourceDirs_[i].Compare(fixedPath, false))
  104. return true;
  105. }
  106. if (priority < resourceDirs_.Size())
  107. resourceDirs_.Insert(priority, fixedPath);
  108. else
  109. resourceDirs_.Push(fixedPath);
  110. // If resource auto-reloading active, create a file watcher for the directory
  111. if (autoReloadResources_)
  112. {
  113. SharedPtr<FileWatcher> watcher(new FileWatcher(context_));
  114. watcher->StartWatching(fixedPath, true);
  115. fileWatchers_.Push(watcher);
  116. }
  117. ATOMIC_LOGINFO("Added resource path " + fixedPath);
  118. return true;
  119. }
  120. bool ResourceCache::AddPackageFile(PackageFile* package, unsigned priority)
  121. {
  122. MutexLock lock(resourceMutex_);
  123. // Do not add packages that failed to load
  124. if (!package || !package->GetNumFiles())
  125. {
  126. ATOMIC_LOGERRORF("Could not add package file %s due to load failure", package->GetName().CString());
  127. return false;
  128. }
  129. if (priority < packages_.Size())
  130. packages_.Insert(priority, SharedPtr<PackageFile>(package));
  131. else
  132. packages_.Push(SharedPtr<PackageFile>(package));
  133. ATOMIC_LOGINFO("Added resource package " + package->GetName());
  134. return true;
  135. }
  136. bool ResourceCache::AddPackageFile(const String& fileName, unsigned priority)
  137. {
  138. SharedPtr<PackageFile> package(new PackageFile(context_));
  139. return package->Open(fileName) && AddPackageFile(package);
  140. }
  141. bool ResourceCache::AddManualResource(Resource* resource)
  142. {
  143. if (!resource)
  144. {
  145. ATOMIC_LOGERROR("Null manual resource");
  146. return false;
  147. }
  148. const String& name = resource->GetName();
  149. if (name.Empty())
  150. {
  151. ATOMIC_LOGERROR("Manual resource with empty name, can not add");
  152. return false;
  153. }
  154. resource->ResetUseTimer();
  155. resourceGroups_[resource->GetType()].resources_[resource->GetNameHash()] = resource;
  156. UpdateResourceGroup(resource->GetType());
  157. return true;
  158. }
  159. void ResourceCache::RemoveResourceDir(const String& pathName)
  160. {
  161. MutexLock lock(resourceMutex_);
  162. String fixedPath = SanitateResourceDirName(pathName);
  163. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  164. {
  165. if (!resourceDirs_[i].Compare(fixedPath, false))
  166. {
  167. resourceDirs_.Erase(i);
  168. // Remove the filewatcher with the matching path
  169. for (unsigned j = 0; j < fileWatchers_.Size(); ++j)
  170. {
  171. if (!fileWatchers_[j]->GetPath().Compare(fixedPath, false))
  172. {
  173. fileWatchers_.Erase(j);
  174. break;
  175. }
  176. }
  177. ATOMIC_LOGINFO("Removed resource path " + fixedPath);
  178. return;
  179. }
  180. }
  181. }
  182. void ResourceCache::RemovePackageFile(PackageFile* package, bool releaseResources, bool forceRelease)
  183. {
  184. MutexLock lock(resourceMutex_);
  185. for (Vector<SharedPtr<PackageFile> >::Iterator i = packages_.Begin(); i != packages_.End(); ++i)
  186. {
  187. if (*i == package)
  188. {
  189. if (releaseResources)
  190. ReleasePackageResources(*i, forceRelease);
  191. ATOMIC_LOGINFO("Removed resource package " + (*i)->GetName());
  192. packages_.Erase(i);
  193. return;
  194. }
  195. }
  196. }
  197. void ResourceCache::RemovePackageFile(const String& fileName, bool releaseResources, bool forceRelease)
  198. {
  199. MutexLock lock(resourceMutex_);
  200. // Compare the name and extension only, not the path
  201. String fileNameNoPath = GetFileNameAndExtension(fileName);
  202. for (Vector<SharedPtr<PackageFile> >::Iterator i = packages_.Begin(); i != packages_.End(); ++i)
  203. {
  204. if (!GetFileNameAndExtension((*i)->GetName()).Compare(fileNameNoPath, false))
  205. {
  206. if (releaseResources)
  207. ReleasePackageResources(*i, forceRelease);
  208. ATOMIC_LOGINFO("Removed resource package " + (*i)->GetName());
  209. packages_.Erase(i);
  210. return;
  211. }
  212. }
  213. }
  214. void ResourceCache::ReleaseResource(StringHash type, const String& name, bool force)
  215. {
  216. StringHash nameHash(name);
  217. const SharedPtr<Resource>& existingRes = FindResource(type, nameHash);
  218. if (!existingRes)
  219. return;
  220. // If other references exist, do not release, unless forced
  221. if ((existingRes.Refs() == 1 && existingRes.WeakRefs() == 0) || force)
  222. {
  223. resourceGroups_[type].resources_.Erase(nameHash);
  224. UpdateResourceGroup(type);
  225. }
  226. }
  227. void ResourceCache::ReleaseResources(StringHash type, bool force)
  228. {
  229. bool released = false;
  230. HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Find(type);
  231. if (i != resourceGroups_.End())
  232. {
  233. for (HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin();
  234. j != i->second_.resources_.End();)
  235. {
  236. HashMap<StringHash, SharedPtr<Resource> >::Iterator current = j++;
  237. // If other references exist, do not release, unless forced
  238. if ((current->second_.Refs() == 1 && current->second_.WeakRefs() == 0) || force)
  239. {
  240. i->second_.resources_.Erase(current);
  241. released = true;
  242. }
  243. }
  244. }
  245. if (released)
  246. UpdateResourceGroup(type);
  247. }
  248. void ResourceCache::ReleaseResources(StringHash type, const String& partialName, bool force)
  249. {
  250. bool released = false;
  251. HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Find(type);
  252. if (i != resourceGroups_.End())
  253. {
  254. for (HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin();
  255. j != i->second_.resources_.End();)
  256. {
  257. HashMap<StringHash, SharedPtr<Resource> >::Iterator current = j++;
  258. if (current->second_->GetName().Contains(partialName))
  259. {
  260. // If other references exist, do not release, unless forced
  261. if ((current->second_.Refs() == 1 && current->second_.WeakRefs() == 0) || force)
  262. {
  263. i->second_.resources_.Erase(current);
  264. released = true;
  265. }
  266. }
  267. }
  268. }
  269. if (released)
  270. UpdateResourceGroup(type);
  271. }
  272. void ResourceCache::ReleaseResources(const String& partialName, bool force)
  273. {
  274. // Some resources refer to others, like materials to textures. Release twice to ensure these get released.
  275. // This is not necessary if forcing release
  276. unsigned repeat = force ? 1 : 2;
  277. while (repeat--)
  278. {
  279. for (HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Begin(); i != resourceGroups_.End(); ++i)
  280. {
  281. bool released = false;
  282. for (HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin();
  283. j != i->second_.resources_.End();)
  284. {
  285. HashMap<StringHash, SharedPtr<Resource> >::Iterator current = j++;
  286. if (current->second_->GetName().Contains(partialName))
  287. {
  288. // If other references exist, do not release, unless forced
  289. if ((current->second_.Refs() == 1 && current->second_.WeakRefs() == 0) || force)
  290. {
  291. i->second_.resources_.Erase(current);
  292. released = true;
  293. }
  294. }
  295. }
  296. if (released)
  297. UpdateResourceGroup(i->first_);
  298. }
  299. }
  300. }
  301. void ResourceCache::ReleaseAllResources(bool force)
  302. {
  303. unsigned repeat = force ? 1 : 2;
  304. while (repeat--)
  305. {
  306. for (HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Begin();
  307. i != resourceGroups_.End(); ++i)
  308. {
  309. bool released = false;
  310. for (HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin();
  311. j != i->second_.resources_.End();)
  312. {
  313. HashMap<StringHash, SharedPtr<Resource> >::Iterator current = j++;
  314. // If other references exist, do not release, unless forced
  315. if ((current->second_.Refs() == 1 && current->second_.WeakRefs() == 0) || force)
  316. {
  317. i->second_.resources_.Erase(current);
  318. released = true;
  319. }
  320. }
  321. if (released)
  322. UpdateResourceGroup(i->first_);
  323. }
  324. }
  325. }
  326. bool ResourceCache::ReloadResource(Resource* resource)
  327. {
  328. if (!resource)
  329. return false;
  330. resource->SendEvent(E_RELOADSTARTED);
  331. bool success = false;
  332. SharedPtr<File> file = GetFile(resource->GetName());
  333. if (file)
  334. success = resource->Load(*(file.Get()));
  335. if (success)
  336. {
  337. resource->ResetUseTimer();
  338. UpdateResourceGroup(resource->GetType());
  339. resource->SendEvent(E_RELOADFINISHED);
  340. return true;
  341. }
  342. // If reloading failed, do not remove the resource from cache, to allow for a new live edit to
  343. // attempt loading again
  344. resource->SendEvent(E_RELOADFAILED);
  345. return false;
  346. }
  347. void ResourceCache::ReloadResourceWithDependencies(const String& fileName)
  348. {
  349. StringHash fileNameHash(fileName);
  350. // If the filename is a resource we keep track of, reload it
  351. const SharedPtr<Resource>& resource = FindResource(fileNameHash);
  352. if (resource)
  353. {
  354. ATOMIC_LOGDEBUG("Reloading changed resource " + fileName);
  355. ReloadResource(resource);
  356. }
  357. // Always perform dependency resource check for resource loaded from XML file as it could be used in inheritance
  358. if (!resource || GetExtension(resource->GetName()) == ".xml")
  359. {
  360. // Check if this is a dependency resource, reload dependents
  361. HashMap<StringHash, HashSet<StringHash> >::ConstIterator j = dependentResources_.Find(fileNameHash);
  362. if (j != dependentResources_.End())
  363. {
  364. // Reloading a resource may modify the dependency tracking structure. Therefore collect the
  365. // resources we need to reload first
  366. Vector<SharedPtr<Resource> > dependents;
  367. dependents.Reserve(j->second_.Size());
  368. for (HashSet<StringHash>::ConstIterator k = j->second_.Begin(); k != j->second_.End(); ++k)
  369. {
  370. const SharedPtr<Resource>& dependent = FindResource(*k);
  371. if (dependent)
  372. dependents.Push(dependent);
  373. }
  374. for (unsigned k = 0; k < dependents.Size(); ++k)
  375. {
  376. ATOMIC_LOGDEBUG("Reloading resource " + dependents[k]->GetName() + " depending on " + fileName);
  377. ReloadResource(dependents[k]);
  378. }
  379. }
  380. }
  381. }
  382. void ResourceCache::SetMemoryBudget(StringHash type, unsigned long long budget)
  383. {
  384. resourceGroups_[type].memoryBudget_ = budget;
  385. }
  386. void ResourceCache::SetAutoReloadResources(bool enable)
  387. {
  388. if (enable != autoReloadResources_)
  389. {
  390. if (enable)
  391. {
  392. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  393. {
  394. SharedPtr<FileWatcher> watcher(new FileWatcher(context_));
  395. watcher->StartWatching(resourceDirs_[i], true);
  396. fileWatchers_.Push(watcher);
  397. }
  398. }
  399. else
  400. fileWatchers_.Clear();
  401. autoReloadResources_ = enable;
  402. }
  403. }
  404. void ResourceCache::AddResourceRouter(ResourceRouter* router, bool addAsFirst)
  405. {
  406. // Check for duplicate
  407. for (unsigned i = 0; i < resourceRouters_.Size(); ++i)
  408. {
  409. if (resourceRouters_[i] == router)
  410. return;
  411. }
  412. if (addAsFirst)
  413. resourceRouters_.Insert(0, SharedPtr<ResourceRouter>(router));
  414. else
  415. resourceRouters_.Push(SharedPtr<ResourceRouter>(router));
  416. }
  417. void ResourceCache::RemoveResourceRouter(ResourceRouter* router)
  418. {
  419. for (unsigned i = 0; i < resourceRouters_.Size(); ++i)
  420. {
  421. if (resourceRouters_[i] == router)
  422. {
  423. resourceRouters_.Erase(i);
  424. return;
  425. }
  426. }
  427. }
  428. SharedPtr<File> ResourceCache::GetFile(const String& nameIn, bool sendEventOnFailure)
  429. {
  430. MutexLock lock(resourceMutex_);
  431. String name = SanitateResourceName(nameIn);
  432. if (!isRouting_)
  433. {
  434. isRouting_ = true;
  435. for (unsigned i = 0; i < resourceRouters_.Size(); ++i)
  436. resourceRouters_[i]->Route(name, RESOURCE_GETFILE);
  437. isRouting_ = false;
  438. }
  439. if (name.Length())
  440. {
  441. File* file = 0;
  442. if (searchPackagesFirst_)
  443. {
  444. file = SearchPackages(name);
  445. if (!file)
  446. file = SearchResourceDirs(name);
  447. }
  448. else
  449. {
  450. file = SearchResourceDirs(name);
  451. if (!file)
  452. file = SearchPackages(name);
  453. }
  454. if (file)
  455. return SharedPtr<File>(file);
  456. }
  457. if (sendEventOnFailure)
  458. {
  459. if (resourceRouters_.Size() && name.Empty() && !nameIn.Empty())
  460. ATOMIC_LOGERROR("Resource request " + nameIn + " was blocked");
  461. else
  462. ATOMIC_LOGERROR("Could not find resource " + name);
  463. if (Thread::IsMainThread())
  464. {
  465. using namespace ResourceNotFound;
  466. VariantMap& eventData = GetEventDataMap();
  467. eventData[P_RESOURCENAME] = name.Length() ? name : nameIn;
  468. SendEvent(E_RESOURCENOTFOUND, eventData);
  469. }
  470. }
  471. return SharedPtr<File>();
  472. }
  473. Resource* ResourceCache::GetExistingResource(StringHash type, const String& nameIn)
  474. {
  475. String name = SanitateResourceName(nameIn);
  476. if (!Thread::IsMainThread())
  477. {
  478. ATOMIC_LOGERROR("Attempted to get resource " + name + " from outside the main thread");
  479. return 0;
  480. }
  481. // If empty name, return null pointer immediately
  482. if (name.Empty())
  483. return 0;
  484. StringHash nameHash(name);
  485. const SharedPtr<Resource>& existing = FindResource(type, nameHash);
  486. return existing;
  487. }
  488. Resource* ResourceCache::GetResource(StringHash type, const String& nameIn, bool sendEventOnFailure)
  489. {
  490. String name = SanitateResourceName(nameIn);
  491. if (!Thread::IsMainThread())
  492. {
  493. ATOMIC_LOGERROR("Attempted to get resource " + name + " from outside the main thread");
  494. return 0;
  495. }
  496. // If empty name, return null pointer immediately
  497. if (name.Empty())
  498. return 0;
  499. StringHash nameHash(name);
  500. #ifdef ATOMIC_THREADING
  501. // Check if the resource is being background loaded but is now needed immediately
  502. backgroundLoader_->WaitForResource(type, nameHash);
  503. #endif
  504. const SharedPtr<Resource>& existing = FindResource(type, nameHash);
  505. if (existing)
  506. return existing;
  507. SharedPtr<Resource> resource;
  508. // Make sure the pointer is non-null and is a Resource subclass
  509. resource = DynamicCast<Resource>(context_->CreateObject(type));
  510. if (!resource)
  511. {
  512. ATOMIC_LOGERROR("Could not load unknown resource type " + String(type));
  513. if (sendEventOnFailure)
  514. {
  515. using namespace UnknownResourceType;
  516. VariantMap& eventData = GetEventDataMap();
  517. eventData[P_RESOURCETYPE] = type;
  518. SendEvent(E_UNKNOWNRESOURCETYPE, eventData);
  519. }
  520. return 0;
  521. }
  522. // Attempt to load the resource
  523. SharedPtr<File> file = GetFile(name, sendEventOnFailure);
  524. if (!file)
  525. return 0; // Error is already logged
  526. ATOMIC_LOGDEBUG("Loading resource " + name);
  527. resource->SetName(name);
  528. if (!resource->Load(*(file.Get())))
  529. {
  530. // Error should already been logged by corresponding resource descendant class
  531. if (sendEventOnFailure)
  532. {
  533. using namespace LoadFailed;
  534. VariantMap& eventData = GetEventDataMap();
  535. eventData[P_RESOURCENAME] = name;
  536. SendEvent(E_LOADFAILED, eventData);
  537. }
  538. if (!returnFailedResources_)
  539. return 0;
  540. }
  541. // Store to cache
  542. resource->ResetUseTimer();
  543. resourceGroups_[type].resources_[nameHash] = resource;
  544. UpdateResourceGroup(type);
  545. return resource;
  546. }
  547. bool ResourceCache::BackgroundLoadResource(StringHash type, const String& nameIn, bool sendEventOnFailure, Resource* caller)
  548. {
  549. #ifdef ATOMIC_THREADING
  550. // If empty name, fail immediately
  551. String name = SanitateResourceName(nameIn);
  552. if (name.Empty())
  553. return false;
  554. // First check if already exists as a loaded resource
  555. StringHash nameHash(name);
  556. if (FindResource(type, nameHash) != noResource)
  557. return false;
  558. return backgroundLoader_->QueueResource(type, name, sendEventOnFailure, caller);
  559. #else
  560. // When threading not supported, fall back to synchronous loading
  561. return GetResource(type, nameIn, sendEventOnFailure);
  562. #endif
  563. }
  564. SharedPtr<Resource> ResourceCache::GetTempResource(StringHash type, const String& nameIn, bool sendEventOnFailure)
  565. {
  566. String name = SanitateResourceName(nameIn);
  567. // If empty name, return null pointer immediately
  568. if (name.Empty())
  569. return SharedPtr<Resource>();
  570. SharedPtr<Resource> resource;
  571. // Make sure the pointer is non-null and is a Resource subclass
  572. resource = DynamicCast<Resource>(context_->CreateObject(type));
  573. if (!resource)
  574. {
  575. ATOMIC_LOGERROR("Could not load unknown resource type " + String(type));
  576. if (sendEventOnFailure)
  577. {
  578. using namespace UnknownResourceType;
  579. VariantMap& eventData = GetEventDataMap();
  580. eventData[P_RESOURCETYPE] = type;
  581. SendEvent(E_UNKNOWNRESOURCETYPE, eventData);
  582. }
  583. return SharedPtr<Resource>();
  584. }
  585. // Attempt to load the resource
  586. SharedPtr<File> file = GetFile(name, sendEventOnFailure);
  587. if (!file)
  588. return SharedPtr<Resource>(); // Error is already logged
  589. ATOMIC_LOGDEBUG("Loading temporary resource " + name);
  590. resource->SetName(file->GetName());
  591. if (!resource->Load(*(file.Get())))
  592. {
  593. // Error should already been logged by corresponding resource descendant class
  594. if (sendEventOnFailure)
  595. {
  596. using namespace LoadFailed;
  597. VariantMap& eventData = GetEventDataMap();
  598. eventData[P_RESOURCENAME] = name;
  599. SendEvent(E_LOADFAILED, eventData);
  600. }
  601. return SharedPtr<Resource>();
  602. }
  603. return resource;
  604. }
  605. unsigned ResourceCache::GetNumBackgroundLoadResources() const
  606. {
  607. #ifdef ATOMIC_THREADING
  608. return backgroundLoader_->GetNumQueuedResources();
  609. #else
  610. return 0;
  611. #endif
  612. }
  613. void ResourceCache::GetResources(PODVector<Resource*>& result, StringHash type) const
  614. {
  615. result.Clear();
  616. HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Find(type);
  617. if (i != resourceGroups_.End())
  618. {
  619. for (HashMap<StringHash, SharedPtr<Resource> >::ConstIterator j = i->second_.resources_.Begin();
  620. j != i->second_.resources_.End(); ++j)
  621. result.Push(j->second_);
  622. }
  623. }
  624. bool ResourceCache::Exists(const String& nameIn) const
  625. {
  626. MutexLock lock(resourceMutex_);
  627. String name = SanitateResourceName(nameIn);
  628. if (!isRouting_)
  629. {
  630. isRouting_ = true;
  631. for (unsigned i = 0; i < resourceRouters_.Size(); ++i)
  632. resourceRouters_[i]->Route(name, RESOURCE_CHECKEXISTS);
  633. isRouting_ = false;
  634. }
  635. if (name.Empty())
  636. return false;
  637. for (unsigned i = 0; i < packages_.Size(); ++i)
  638. {
  639. if (packages_[i]->Exists(name))
  640. return true;
  641. }
  642. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  643. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  644. {
  645. if (fileSystem->FileExists(resourceDirs_[i] + name))
  646. return true;
  647. }
  648. // Fallback using absolute path
  649. return fileSystem->FileExists(name);
  650. }
  651. unsigned long long ResourceCache::GetMemoryBudget(StringHash type) const
  652. {
  653. HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Find(type);
  654. return i != resourceGroups_.End() ? i->second_.memoryBudget_ : 0;
  655. }
  656. unsigned long long ResourceCache::GetMemoryUse(StringHash type) const
  657. {
  658. HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Find(type);
  659. return i != resourceGroups_.End() ? i->second_.memoryUse_ : 0;
  660. }
  661. unsigned long long ResourceCache::GetTotalMemoryUse() const
  662. {
  663. unsigned long long total = 0;
  664. for (HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Begin(); i != resourceGroups_.End(); ++i)
  665. total += i->second_.memoryUse_;
  666. return total;
  667. }
  668. String ResourceCache::GetResourceFileName(const String& name) const
  669. {
  670. MutexLock lock(resourceMutex_);
  671. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  672. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  673. {
  674. if (fileSystem->FileExists(resourceDirs_[i] + name))
  675. return resourceDirs_[i] + name;
  676. }
  677. return String();
  678. }
  679. ResourceRouter* ResourceCache::GetResourceRouter(unsigned index) const
  680. {
  681. return index < resourceRouters_.Size() ? resourceRouters_[index] : (ResourceRouter*)0;
  682. }
  683. String ResourceCache::GetPreferredResourceDir(const String& path) const
  684. {
  685. String fixedPath = AddTrailingSlash(path);
  686. bool pathHasKnownDirs = false;
  687. bool parentHasKnownDirs = false;
  688. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  689. for (unsigned i = 0; checkDirs[i] != 0; ++i)
  690. {
  691. if (fileSystem->DirExists(fixedPath + checkDirs[i]))
  692. {
  693. pathHasKnownDirs = true;
  694. break;
  695. }
  696. }
  697. if (!pathHasKnownDirs)
  698. {
  699. String parentPath = GetParentPath(fixedPath);
  700. for (unsigned i = 0; checkDirs[i] != 0; ++i)
  701. {
  702. if (fileSystem->DirExists(parentPath + checkDirs[i]))
  703. {
  704. parentHasKnownDirs = true;
  705. break;
  706. }
  707. }
  708. // If path does not have known subdirectories, but the parent path has, use the parent instead
  709. if (parentHasKnownDirs)
  710. fixedPath = parentPath;
  711. }
  712. return fixedPath;
  713. }
  714. String ResourceCache::SanitateResourceName(const String& nameIn) const
  715. {
  716. // Sanitate unsupported constructs from the resource name
  717. String name = GetInternalPath(nameIn);
  718. name.Replace("../", "");
  719. name.Replace("./", "");
  720. // If the path refers to one of the resource directories, normalize the resource name
  721. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  722. if (resourceDirs_.Size())
  723. {
  724. String namePath = GetPath(name);
  725. String exePath = fileSystem->GetProgramDir();
  726. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  727. {
  728. String relativeResourcePath = resourceDirs_[i];
  729. if (relativeResourcePath.StartsWith(exePath))
  730. relativeResourcePath = relativeResourcePath.Substring(exePath.Length());
  731. if (namePath.StartsWith(resourceDirs_[i], false))
  732. namePath = namePath.Substring(resourceDirs_[i].Length());
  733. else if (namePath.StartsWith(relativeResourcePath, false))
  734. namePath = namePath.Substring(relativeResourcePath.Length());
  735. }
  736. name = namePath + GetFileNameAndExtension(name);
  737. }
  738. return name.Trimmed();
  739. }
  740. String ResourceCache::SanitateResourceDirName(const String& nameIn) const
  741. {
  742. String fixedPath = AddTrailingSlash(nameIn);
  743. if (!IsAbsolutePath(fixedPath))
  744. fixedPath = GetSubsystem<FileSystem>()->GetCurrentDir() + fixedPath;
  745. // Sanitate away /./ construct
  746. fixedPath.Replace("/./", "/");
  747. return fixedPath.Trimmed();
  748. }
  749. void ResourceCache::StoreResourceDependency(Resource* resource, const String& dependency)
  750. {
  751. if (!resource)
  752. return;
  753. MutexLock lock(resourceMutex_);
  754. StringHash nameHash(resource->GetName());
  755. HashSet<StringHash>& dependents = dependentResources_[dependency];
  756. dependents.Insert(nameHash);
  757. }
  758. void ResourceCache::ResetDependencies(Resource* resource)
  759. {
  760. if (!resource)
  761. return;
  762. MutexLock lock(resourceMutex_);
  763. StringHash nameHash(resource->GetName());
  764. for (HashMap<StringHash, HashSet<StringHash> >::Iterator i = dependentResources_.Begin(); i != dependentResources_.End();)
  765. {
  766. HashSet<StringHash>& dependents = i->second_;
  767. dependents.Erase(nameHash);
  768. if (dependents.Empty())
  769. i = dependentResources_.Erase(i);
  770. else
  771. ++i;
  772. }
  773. }
  774. String ResourceCache::PrintMemoryUsage() const
  775. {
  776. String output = "Resource Type Cnt Avg Max Budget Total\n\n";
  777. char outputLine[256];
  778. unsigned totalResourceCt = 0;
  779. unsigned long long totalLargest = 0;
  780. unsigned long long totalAverage = 0;
  781. unsigned long long totalUse = GetTotalMemoryUse();
  782. for (HashMap<StringHash, ResourceGroup>::ConstIterator cit = resourceGroups_.Begin(); cit != resourceGroups_.End(); ++cit)
  783. {
  784. const unsigned resourceCt = cit->second_.resources_.Size();
  785. unsigned long long average = 0;
  786. if (resourceCt > 0)
  787. average = cit->second_.memoryUse_ / resourceCt;
  788. else
  789. average = 0;
  790. unsigned long long largest = 0;
  791. for (HashMap<StringHash, SharedPtr<Resource> >::ConstIterator resIt = cit->second_.resources_.Begin(); resIt != cit->second_.resources_.End(); ++resIt)
  792. {
  793. if (resIt->second_->GetMemoryUse() > largest)
  794. largest = resIt->second_->GetMemoryUse();
  795. if (largest > totalLargest)
  796. totalLargest = largest;
  797. }
  798. totalResourceCt += resourceCt;
  799. const String countString(cit->second_.resources_.Size());
  800. const String memUseString = GetFileSizeString(average);
  801. const String memMaxString = GetFileSizeString(largest);
  802. const String memBudgetString = GetFileSizeString(cit->second_.memoryBudget_);
  803. const String memTotalString = GetFileSizeString(cit->second_.memoryUse_);
  804. const String resTypeName = context_->GetTypeName(cit->first_);
  805. memset(outputLine, ' ', 256);
  806. outputLine[255] = 0;
  807. sprintf(outputLine, "%-28s %4s %9s %9s %9s %9s\n", resTypeName.CString(), countString.CString(), memUseString.CString(), memMaxString.CString(), memBudgetString.CString(), memTotalString.CString());
  808. output += ((const char*)outputLine);
  809. }
  810. if (totalResourceCt > 0)
  811. totalAverage = totalUse / totalResourceCt;
  812. const String countString(totalResourceCt);
  813. const String memUseString = GetFileSizeString(totalAverage);
  814. const String memMaxString = GetFileSizeString(totalLargest);
  815. const String memTotalString = GetFileSizeString(totalUse);
  816. memset(outputLine, ' ', 256);
  817. outputLine[255] = 0;
  818. sprintf(outputLine, "%-28s %4s %9s %9s %9s %9s\n", "All", countString.CString(), memUseString.CString(), memMaxString.CString(), "-", memTotalString.CString());
  819. output += ((const char*)outputLine);
  820. return output;
  821. }
  822. const SharedPtr<Resource>& ResourceCache::FindResource(StringHash type, StringHash nameHash)
  823. {
  824. MutexLock lock(resourceMutex_);
  825. HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Find(type);
  826. if (i == resourceGroups_.End())
  827. return noResource;
  828. HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Find(nameHash);
  829. if (j == i->second_.resources_.End())
  830. return noResource;
  831. return j->second_;
  832. }
  833. const SharedPtr<Resource>& ResourceCache::FindResource(StringHash nameHash)
  834. {
  835. MutexLock lock(resourceMutex_);
  836. for (HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Begin(); i != resourceGroups_.End(); ++i)
  837. {
  838. HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Find(nameHash);
  839. if (j != i->second_.resources_.End())
  840. return j->second_;
  841. }
  842. return noResource;
  843. }
  844. void ResourceCache::ReleasePackageResources(PackageFile* package, bool force)
  845. {
  846. HashSet<StringHash> affectedGroups;
  847. const HashMap<String, PackageEntry>& entries = package->GetEntries();
  848. for (HashMap<String, PackageEntry>::ConstIterator i = entries.Begin(); i != entries.End(); ++i)
  849. {
  850. StringHash nameHash(i->first_);
  851. // We do not know the actual resource type, so search all type containers
  852. for (HashMap<StringHash, ResourceGroup>::Iterator j = resourceGroups_.Begin(); j != resourceGroups_.End(); ++j)
  853. {
  854. HashMap<StringHash, SharedPtr<Resource> >::Iterator k = j->second_.resources_.Find(nameHash);
  855. if (k != j->second_.resources_.End())
  856. {
  857. // If other references exist, do not release, unless forced
  858. if ((k->second_.Refs() == 1 && k->second_.WeakRefs() == 0) || force)
  859. {
  860. j->second_.resources_.Erase(k);
  861. affectedGroups.Insert(j->first_);
  862. }
  863. break;
  864. }
  865. }
  866. }
  867. for (HashSet<StringHash>::Iterator i = affectedGroups.Begin(); i != affectedGroups.End(); ++i)
  868. UpdateResourceGroup(*i);
  869. }
  870. void ResourceCache::UpdateResourceGroup(StringHash type)
  871. {
  872. HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Find(type);
  873. if (i == resourceGroups_.End())
  874. return;
  875. for (;;)
  876. {
  877. unsigned totalSize = 0;
  878. unsigned oldestTimer = 0;
  879. HashMap<StringHash, SharedPtr<Resource> >::Iterator oldestResource = i->second_.resources_.End();
  880. for (HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin();
  881. j != i->second_.resources_.End(); ++j)
  882. {
  883. totalSize += j->second_->GetMemoryUse();
  884. unsigned useTimer = j->second_->GetUseTimer();
  885. if (useTimer > oldestTimer)
  886. {
  887. oldestTimer = useTimer;
  888. oldestResource = j;
  889. }
  890. }
  891. i->second_.memoryUse_ = totalSize;
  892. // If memory budget defined and is exceeded, remove the oldest resource and loop again
  893. // (resources in use always return a zero timer and can not be removed)
  894. if (i->second_.memoryBudget_ && i->second_.memoryUse_ > i->second_.memoryBudget_ &&
  895. oldestResource != i->second_.resources_.End())
  896. {
  897. ATOMIC_LOGDEBUG("Resource group " + oldestResource->second_->GetTypeName() + " over memory budget, releasing resource " +
  898. oldestResource->second_->GetName());
  899. i->second_.resources_.Erase(oldestResource);
  900. }
  901. else
  902. break;
  903. }
  904. }
  905. void ResourceCache::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  906. {
  907. for (unsigned i = 0; i < fileWatchers_.Size(); ++i)
  908. {
  909. String fileName;
  910. while (fileWatchers_[i]->GetNextChange(fileName))
  911. {
  912. ReloadResourceWithDependencies(fileName);
  913. // Finally send a general file changed event even if the file was not a tracked resource
  914. using namespace FileChanged;
  915. VariantMap& eventData = GetEventDataMap();
  916. eventData[P_FILENAME] = fileWatchers_[i]->GetPath() + fileName;
  917. eventData[P_RESOURCENAME] = fileName;
  918. SendEvent(E_FILECHANGED, eventData);
  919. }
  920. }
  921. // Check for background loaded resources that can be finished
  922. #ifdef ATOMIC_THREADING
  923. {
  924. ATOMIC_PROFILE(FinishBackgroundResources);
  925. backgroundLoader_->FinishResources(finishBackgroundResourcesMs_);
  926. }
  927. #endif
  928. }
  929. File* ResourceCache::SearchResourceDirs(const String& nameIn)
  930. {
  931. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  932. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  933. {
  934. if (fileSystem->FileExists(resourceDirs_[i] + nameIn))
  935. {
  936. // Construct the file first with full path, then rename it to not contain the resource path,
  937. // so that the file's name can be used in further GetFile() calls (for example over the network)
  938. File* file(new File(context_, resourceDirs_[i] + nameIn));
  939. file->SetName(nameIn);
  940. return file;
  941. }
  942. }
  943. // Fallback using absolute path
  944. if (fileSystem->FileExists(nameIn))
  945. return new File(context_, nameIn);
  946. return 0;
  947. }
  948. File* ResourceCache::SearchPackages(const String& nameIn)
  949. {
  950. for (unsigned i = 0; i < packages_.Size(); ++i)
  951. {
  952. if (packages_[i]->Exists(nameIn))
  953. return new File(context_, packages_[i], nameIn);
  954. }
  955. return 0;
  956. }
  957. void RegisterResourceLibrary(Context* context)
  958. {
  959. Image::RegisterObject(context);
  960. JSONFile::RegisterObject(context);
  961. PListFile::RegisterObject(context);
  962. XMLFile::RegisterObject(context);
  963. }
  964. }