ResourceCache.cpp 35 KB

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