ResourceCache.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193
  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. // ATOMIC BEGIN
  334. if (file)
  335. {
  336. #ifdef ATOMIC_PLATFORM_DESKTOP
  337. String ext = GetExtension(resource->GetName());
  338. if (ext == ".jpg" || ext == ".png" || ext == ".tga")
  339. {
  340. String ddsName = "DDS/" + resource->GetName() + ".dds";
  341. SharedPtr<File> ddsFile = GetFile(ddsName, false);
  342. if (ddsFile != NULL)
  343. success = resource->Load(*(ddsFile.Get()));
  344. else
  345. success = resource->Load(*(file.Get()));
  346. }
  347. else
  348. {
  349. success = resource->Load(*(file.Get()));
  350. }
  351. #else
  352. success = resource->Load(*(file.Get()));
  353. #endif
  354. }
  355. // ATOMIC END
  356. if (success)
  357. {
  358. resource->ResetUseTimer();
  359. UpdateResourceGroup(resource->GetType());
  360. resource->SendEvent(E_RELOADFINISHED);
  361. return true;
  362. }
  363. // If reloading failed, do not remove the resource from cache, to allow for a new live edit to
  364. // attempt loading again
  365. resource->SendEvent(E_RELOADFAILED);
  366. return false;
  367. }
  368. void ResourceCache::ReloadResourceWithDependencies(const String& fileName)
  369. {
  370. StringHash fileNameHash(fileName);
  371. // If the filename is a resource we keep track of, reload it
  372. const SharedPtr<Resource>& resource = FindResource(fileNameHash);
  373. if (resource)
  374. {
  375. ATOMIC_LOGDEBUG("Reloading changed resource " + fileName);
  376. ReloadResource(resource);
  377. }
  378. // Always perform dependency resource check for resource loaded from XML file as it could be used in inheritance
  379. if (!resource || GetExtension(resource->GetName()) == ".xml")
  380. {
  381. // Check if this is a dependency resource, reload dependents
  382. HashMap<StringHash, HashSet<StringHash> >::ConstIterator j = dependentResources_.Find(fileNameHash);
  383. if (j != dependentResources_.End())
  384. {
  385. // Reloading a resource may modify the dependency tracking structure. Therefore collect the
  386. // resources we need to reload first
  387. Vector<SharedPtr<Resource> > dependents;
  388. dependents.Reserve(j->second_.Size());
  389. for (HashSet<StringHash>::ConstIterator k = j->second_.Begin(); k != j->second_.End(); ++k)
  390. {
  391. const SharedPtr<Resource>& dependent = FindResource(*k);
  392. if (dependent)
  393. dependents.Push(dependent);
  394. }
  395. for (unsigned k = 0; k < dependents.Size(); ++k)
  396. {
  397. ATOMIC_LOGDEBUG("Reloading resource " + dependents[k]->GetName() + " depending on " + fileName);
  398. ReloadResource(dependents[k]);
  399. }
  400. }
  401. }
  402. }
  403. void ResourceCache::SetMemoryBudget(StringHash type, unsigned long long budget)
  404. {
  405. resourceGroups_[type].memoryBudget_ = budget;
  406. }
  407. void ResourceCache::SetAutoReloadResources(bool enable)
  408. {
  409. if (enable != autoReloadResources_)
  410. {
  411. if (enable)
  412. {
  413. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  414. {
  415. SharedPtr<FileWatcher> watcher(new FileWatcher(context_));
  416. watcher->StartWatching(resourceDirs_[i], true);
  417. fileWatchers_.Push(watcher);
  418. }
  419. }
  420. else
  421. fileWatchers_.Clear();
  422. autoReloadResources_ = enable;
  423. }
  424. }
  425. void ResourceCache::AddResourceRouter(ResourceRouter* router, bool addAsFirst)
  426. {
  427. // Check for duplicate
  428. for (unsigned i = 0; i < resourceRouters_.Size(); ++i)
  429. {
  430. if (resourceRouters_[i] == router)
  431. return;
  432. }
  433. if (addAsFirst)
  434. resourceRouters_.Insert(0, SharedPtr<ResourceRouter>(router));
  435. else
  436. resourceRouters_.Push(SharedPtr<ResourceRouter>(router));
  437. }
  438. void ResourceCache::RemoveResourceRouter(ResourceRouter* router)
  439. {
  440. for (unsigned i = 0; i < resourceRouters_.Size(); ++i)
  441. {
  442. if (resourceRouters_[i] == router)
  443. {
  444. resourceRouters_.Erase(i);
  445. return;
  446. }
  447. }
  448. }
  449. SharedPtr<File> ResourceCache::GetFile(const String& nameIn, bool sendEventOnFailure)
  450. {
  451. MutexLock lock(resourceMutex_);
  452. String name = SanitateResourceName(nameIn);
  453. if (!isRouting_)
  454. {
  455. isRouting_ = true;
  456. for (unsigned i = 0; i < resourceRouters_.Size(); ++i)
  457. resourceRouters_[i]->Route(name, RESOURCE_GETFILE);
  458. isRouting_ = false;
  459. }
  460. if (name.Length())
  461. {
  462. File* file = 0;
  463. if (searchPackagesFirst_)
  464. {
  465. file = SearchPackages(name);
  466. if (!file)
  467. file = SearchResourceDirs(name);
  468. }
  469. else
  470. {
  471. file = SearchResourceDirs(name);
  472. if (!file)
  473. file = SearchPackages(name);
  474. }
  475. if (file)
  476. return SharedPtr<File>(file);
  477. }
  478. if (sendEventOnFailure)
  479. {
  480. if (resourceRouters_.Size() && name.Empty() && !nameIn.Empty())
  481. ATOMIC_LOGERROR("Resource request " + nameIn + " was blocked");
  482. else
  483. ATOMIC_LOGERROR("Could not find resource " + name);
  484. if (Thread::IsMainThread())
  485. {
  486. using namespace ResourceNotFound;
  487. VariantMap& eventData = GetEventDataMap();
  488. eventData[P_RESOURCENAME] = name.Length() ? name : nameIn;
  489. SendEvent(E_RESOURCENOTFOUND, eventData);
  490. }
  491. }
  492. return SharedPtr<File>();
  493. }
  494. Resource* ResourceCache::GetExistingResource(StringHash type, const String& nameIn)
  495. {
  496. String name = SanitateResourceName(nameIn);
  497. if (!Thread::IsMainThread())
  498. {
  499. ATOMIC_LOGERROR("Attempted to get resource " + name + " from outside the main thread");
  500. return 0;
  501. }
  502. // If empty name, return null pointer immediately
  503. if (name.Empty())
  504. return 0;
  505. StringHash nameHash(name);
  506. const SharedPtr<Resource>& existing = FindResource(type, nameHash);
  507. return existing;
  508. }
  509. Resource* ResourceCache::GetResource(StringHash type, const String& nameIn, bool sendEventOnFailure)
  510. {
  511. String name = SanitateResourceName(nameIn);
  512. if (!Thread::IsMainThread())
  513. {
  514. ATOMIC_LOGERROR("Attempted to get resource " + name + " from outside the main thread");
  515. return 0;
  516. }
  517. // If empty name, return null pointer immediately
  518. if (name.Empty())
  519. return 0;
  520. StringHash nameHash(name);
  521. #ifdef ATOMIC_THREADING
  522. // Check if the resource is being background loaded but is now needed immediately
  523. backgroundLoader_->WaitForResource(type, nameHash);
  524. #endif
  525. const SharedPtr<Resource>& existing = FindResource(type, nameHash);
  526. if (existing)
  527. return existing;
  528. SharedPtr<Resource> resource;
  529. // Make sure the pointer is non-null and is a Resource subclass
  530. resource = DynamicCast<Resource>(context_->CreateObject(type));
  531. if (!resource)
  532. {
  533. ATOMIC_LOGERROR("Could not load unknown resource type " + String(type));
  534. if (sendEventOnFailure)
  535. {
  536. using namespace UnknownResourceType;
  537. VariantMap& eventData = GetEventDataMap();
  538. eventData[P_RESOURCETYPE] = type;
  539. SendEvent(E_UNKNOWNRESOURCETYPE, eventData);
  540. }
  541. return 0;
  542. }
  543. // Attempt to load the resource
  544. SharedPtr<File> file = GetFile(name, sendEventOnFailure);
  545. if (!file)
  546. return 0; // Error is already logged
  547. ATOMIC_LOGDEBUG("Loading resource " + name);
  548. resource->SetName(name);
  549. if (!resource->Load(*(file.Get())))
  550. {
  551. // Error should already been logged by corresponding resource descendant class
  552. if (sendEventOnFailure)
  553. {
  554. using namespace LoadFailed;
  555. VariantMap& eventData = GetEventDataMap();
  556. eventData[P_RESOURCENAME] = name;
  557. SendEvent(E_LOADFAILED, eventData);
  558. }
  559. if (!returnFailedResources_)
  560. return 0;
  561. }
  562. // Store to cache
  563. resource->ResetUseTimer();
  564. resourceGroups_[type].resources_[nameHash] = resource;
  565. UpdateResourceGroup(type);
  566. return resource;
  567. }
  568. bool ResourceCache::BackgroundLoadResource(StringHash type, const String& nameIn, bool sendEventOnFailure, Resource* caller)
  569. {
  570. #ifdef ATOMIC_THREADING
  571. // If empty name, fail immediately
  572. String name = SanitateResourceName(nameIn);
  573. if (name.Empty())
  574. return false;
  575. // First check if already exists as a loaded resource
  576. StringHash nameHash(name);
  577. if (FindResource(type, nameHash) != noResource)
  578. return false;
  579. return backgroundLoader_->QueueResource(type, name, sendEventOnFailure, caller);
  580. #else
  581. // When threading not supported, fall back to synchronous loading
  582. return GetResource(type, nameIn, sendEventOnFailure);
  583. #endif
  584. }
  585. SharedPtr<Resource> ResourceCache::GetTempResource(StringHash type, const String& nameIn, bool sendEventOnFailure)
  586. {
  587. String name = SanitateResourceName(nameIn);
  588. // If empty name, return null pointer immediately
  589. if (name.Empty())
  590. return SharedPtr<Resource>();
  591. SharedPtr<Resource> resource;
  592. // Make sure the pointer is non-null and is a Resource subclass
  593. resource = DynamicCast<Resource>(context_->CreateObject(type));
  594. if (!resource)
  595. {
  596. ATOMIC_LOGERROR("Could not load unknown resource type " + String(type));
  597. if (sendEventOnFailure)
  598. {
  599. using namespace UnknownResourceType;
  600. VariantMap& eventData = GetEventDataMap();
  601. eventData[P_RESOURCETYPE] = type;
  602. SendEvent(E_UNKNOWNRESOURCETYPE, eventData);
  603. }
  604. return SharedPtr<Resource>();
  605. }
  606. // ATOMIC BEGIN
  607. // Attempt to load the resource
  608. SharedPtr<File> file;
  609. // #623 BEGIN TODO: For now try to get DDS version of textures from /DDS cache sub directory,
  610. // ultimately should have per platform compressed versions saved in cache
  611. #ifdef ATOMIC_PLATFORM_DESKTOP
  612. String ext = Atomic::GetExtension(name);
  613. if (ext == ".jpg" || ext == ".png" || ext == ".tga")
  614. {
  615. String ddsName = "DDS/" + name + ".dds";
  616. file = GetFile(ddsName, false);
  617. if (file)
  618. ATOMIC_LOGDEBUG("Loaded cached DDS " + name + ".dds");
  619. }
  620. if (!file)
  621. file = GetFile(name, sendEventOnFailure);
  622. #else
  623. // #623 END TODO
  624. file = GetFile(name, sendEventOnFailure);
  625. #endif
  626. // ATOMIC END
  627. if (!file)
  628. return SharedPtr<Resource>(); // Error is already logged
  629. ATOMIC_LOGDEBUG("Loading temporary resource " + name);
  630. resource->SetName(file->GetName());
  631. if (!resource->Load(*(file.Get())))
  632. {
  633. // Error should already been logged by corresponding resource descendant class
  634. if (sendEventOnFailure)
  635. {
  636. using namespace LoadFailed;
  637. VariantMap& eventData = GetEventDataMap();
  638. eventData[P_RESOURCENAME] = name;
  639. SendEvent(E_LOADFAILED, eventData);
  640. }
  641. return SharedPtr<Resource>();
  642. }
  643. return resource;
  644. }
  645. unsigned ResourceCache::GetNumBackgroundLoadResources() const
  646. {
  647. #ifdef ATOMIC_THREADING
  648. return backgroundLoader_->GetNumQueuedResources();
  649. #else
  650. return 0;
  651. #endif
  652. }
  653. void ResourceCache::GetResources(PODVector<Resource*>& result, StringHash type) const
  654. {
  655. result.Clear();
  656. HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Find(type);
  657. if (i != resourceGroups_.End())
  658. {
  659. for (HashMap<StringHash, SharedPtr<Resource> >::ConstIterator j = i->second_.resources_.Begin();
  660. j != i->second_.resources_.End(); ++j)
  661. result.Push(j->second_);
  662. }
  663. }
  664. bool ResourceCache::Exists(const String& nameIn) const
  665. {
  666. MutexLock lock(resourceMutex_);
  667. String name = SanitateResourceName(nameIn);
  668. if (!isRouting_)
  669. {
  670. isRouting_ = true;
  671. for (unsigned i = 0; i < resourceRouters_.Size(); ++i)
  672. resourceRouters_[i]->Route(name, RESOURCE_CHECKEXISTS);
  673. isRouting_ = false;
  674. }
  675. if (name.Empty())
  676. return false;
  677. for (unsigned i = 0; i < packages_.Size(); ++i)
  678. {
  679. if (packages_[i]->Exists(name))
  680. return true;
  681. }
  682. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  683. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  684. {
  685. if (fileSystem->FileExists(resourceDirs_[i] + name))
  686. return true;
  687. }
  688. // Fallback using absolute path
  689. return fileSystem->FileExists(name);
  690. }
  691. unsigned long long ResourceCache::GetMemoryBudget(StringHash type) const
  692. {
  693. HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Find(type);
  694. return i != resourceGroups_.End() ? i->second_.memoryBudget_ : 0;
  695. }
  696. unsigned long long ResourceCache::GetMemoryUse(StringHash type) const
  697. {
  698. HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Find(type);
  699. return i != resourceGroups_.End() ? i->second_.memoryUse_ : 0;
  700. }
  701. unsigned long long ResourceCache::GetTotalMemoryUse() const
  702. {
  703. unsigned long long total = 0;
  704. for (HashMap<StringHash, ResourceGroup>::ConstIterator i = resourceGroups_.Begin(); i != resourceGroups_.End(); ++i)
  705. total += i->second_.memoryUse_;
  706. return total;
  707. }
  708. String ResourceCache::GetResourceFileName(const String& name) const
  709. {
  710. MutexLock lock(resourceMutex_);
  711. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  712. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  713. {
  714. if (fileSystem->FileExists(resourceDirs_[i] + name))
  715. return resourceDirs_[i] + name;
  716. }
  717. return String();
  718. }
  719. ResourceRouter* ResourceCache::GetResourceRouter(unsigned index) const
  720. {
  721. return index < resourceRouters_.Size() ? resourceRouters_[index] : (ResourceRouter*)0;
  722. }
  723. String ResourceCache::GetPreferredResourceDir(const String& path) const
  724. {
  725. String fixedPath = AddTrailingSlash(path);
  726. bool pathHasKnownDirs = false;
  727. bool parentHasKnownDirs = false;
  728. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  729. for (unsigned i = 0; checkDirs[i] != 0; ++i)
  730. {
  731. if (fileSystem->DirExists(fixedPath + checkDirs[i]))
  732. {
  733. pathHasKnownDirs = true;
  734. break;
  735. }
  736. }
  737. if (!pathHasKnownDirs)
  738. {
  739. String parentPath = GetParentPath(fixedPath);
  740. for (unsigned i = 0; checkDirs[i] != 0; ++i)
  741. {
  742. if (fileSystem->DirExists(parentPath + checkDirs[i]))
  743. {
  744. parentHasKnownDirs = true;
  745. break;
  746. }
  747. }
  748. // If path does not have known subdirectories, but the parent path has, use the parent instead
  749. if (parentHasKnownDirs)
  750. fixedPath = parentPath;
  751. }
  752. return fixedPath;
  753. }
  754. String ResourceCache::SanitateResourceName(const String& nameIn) const
  755. {
  756. // Sanitate unsupported constructs from the resource name
  757. String name = GetInternalPath(nameIn);
  758. name.Replace("../", "");
  759. name.Replace("./", "");
  760. // If the path refers to one of the resource directories, normalize the resource name
  761. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  762. if (resourceDirs_.Size())
  763. {
  764. String namePath = GetPath(name);
  765. String exePath = fileSystem->GetProgramDir();
  766. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  767. {
  768. String relativeResourcePath = resourceDirs_[i];
  769. if (relativeResourcePath.StartsWith(exePath))
  770. relativeResourcePath = relativeResourcePath.Substring(exePath.Length());
  771. if (namePath.StartsWith(resourceDirs_[i], false))
  772. namePath = namePath.Substring(resourceDirs_[i].Length());
  773. else if (namePath.StartsWith(relativeResourcePath, false))
  774. namePath = namePath.Substring(relativeResourcePath.Length());
  775. }
  776. name = namePath + GetFileNameAndExtension(name);
  777. }
  778. return name.Trimmed();
  779. }
  780. String ResourceCache::SanitateResourceDirName(const String& nameIn) const
  781. {
  782. String fixedPath = AddTrailingSlash(nameIn);
  783. if (!IsAbsolutePath(fixedPath))
  784. fixedPath = GetSubsystem<FileSystem>()->GetCurrentDir() + fixedPath;
  785. // Sanitate away /./ construct
  786. fixedPath.Replace("/./", "/");
  787. return fixedPath.Trimmed();
  788. }
  789. void ResourceCache::StoreResourceDependency(Resource* resource, const String& dependency)
  790. {
  791. if (!resource)
  792. return;
  793. MutexLock lock(resourceMutex_);
  794. StringHash nameHash(resource->GetName());
  795. HashSet<StringHash>& dependents = dependentResources_[dependency];
  796. dependents.Insert(nameHash);
  797. }
  798. void ResourceCache::ResetDependencies(Resource* resource)
  799. {
  800. if (!resource)
  801. return;
  802. MutexLock lock(resourceMutex_);
  803. StringHash nameHash(resource->GetName());
  804. for (HashMap<StringHash, HashSet<StringHash> >::Iterator i = dependentResources_.Begin(); i != dependentResources_.End();)
  805. {
  806. HashSet<StringHash>& dependents = i->second_;
  807. dependents.Erase(nameHash);
  808. if (dependents.Empty())
  809. i = dependentResources_.Erase(i);
  810. else
  811. ++i;
  812. }
  813. }
  814. String ResourceCache::PrintMemoryUsage() const
  815. {
  816. String output = "Resource Type Cnt Avg Max Budget Total\n\n";
  817. char outputLine[256];
  818. unsigned totalResourceCt = 0;
  819. unsigned long long totalLargest = 0;
  820. unsigned long long totalAverage = 0;
  821. unsigned long long totalUse = GetTotalMemoryUse();
  822. for (HashMap<StringHash, ResourceGroup>::ConstIterator cit = resourceGroups_.Begin(); cit != resourceGroups_.End(); ++cit)
  823. {
  824. const unsigned resourceCt = cit->second_.resources_.Size();
  825. unsigned long long average = 0;
  826. if (resourceCt > 0)
  827. average = cit->second_.memoryUse_ / resourceCt;
  828. else
  829. average = 0;
  830. unsigned long long largest = 0;
  831. for (HashMap<StringHash, SharedPtr<Resource> >::ConstIterator resIt = cit->second_.resources_.Begin(); resIt != cit->second_.resources_.End(); ++resIt)
  832. {
  833. if (resIt->second_->GetMemoryUse() > largest)
  834. largest = resIt->second_->GetMemoryUse();
  835. if (largest > totalLargest)
  836. totalLargest = largest;
  837. }
  838. totalResourceCt += resourceCt;
  839. const String countString(cit->second_.resources_.Size());
  840. const String memUseString = GetFileSizeString(average);
  841. const String memMaxString = GetFileSizeString(largest);
  842. const String memBudgetString = GetFileSizeString(cit->second_.memoryBudget_);
  843. const String memTotalString = GetFileSizeString(cit->second_.memoryUse_);
  844. const String resTypeName = context_->GetTypeName(cit->first_);
  845. memset(outputLine, ' ', 256);
  846. outputLine[255] = 0;
  847. sprintf(outputLine, "%-28s %4s %9s %9s %9s %9s\n", resTypeName.CString(), countString.CString(), memUseString.CString(), memMaxString.CString(), memBudgetString.CString(), memTotalString.CString());
  848. output += ((const char*)outputLine);
  849. }
  850. if (totalResourceCt > 0)
  851. totalAverage = totalUse / totalResourceCt;
  852. const String countString(totalResourceCt);
  853. const String memUseString = GetFileSizeString(totalAverage);
  854. const String memMaxString = GetFileSizeString(totalLargest);
  855. const String memTotalString = GetFileSizeString(totalUse);
  856. memset(outputLine, ' ', 256);
  857. outputLine[255] = 0;
  858. sprintf(outputLine, "%-28s %4s %9s %9s %9s %9s\n", "All", countString.CString(), memUseString.CString(), memMaxString.CString(), "-", memTotalString.CString());
  859. output += ((const char*)outputLine);
  860. return output;
  861. }
  862. const SharedPtr<Resource>& ResourceCache::FindResource(StringHash type, StringHash nameHash)
  863. {
  864. MutexLock lock(resourceMutex_);
  865. HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Find(type);
  866. if (i == resourceGroups_.End())
  867. return noResource;
  868. HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Find(nameHash);
  869. if (j == i->second_.resources_.End())
  870. return noResource;
  871. return j->second_;
  872. }
  873. const SharedPtr<Resource>& ResourceCache::FindResource(StringHash nameHash)
  874. {
  875. MutexLock lock(resourceMutex_);
  876. for (HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Begin(); i != resourceGroups_.End(); ++i)
  877. {
  878. HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Find(nameHash);
  879. if (j != i->second_.resources_.End())
  880. return j->second_;
  881. }
  882. return noResource;
  883. }
  884. void ResourceCache::ReleasePackageResources(PackageFile* package, bool force)
  885. {
  886. HashSet<StringHash> affectedGroups;
  887. const HashMap<String, PackageEntry>& entries = package->GetEntries();
  888. for (HashMap<String, PackageEntry>::ConstIterator i = entries.Begin(); i != entries.End(); ++i)
  889. {
  890. StringHash nameHash(i->first_);
  891. // We do not know the actual resource type, so search all type containers
  892. for (HashMap<StringHash, ResourceGroup>::Iterator j = resourceGroups_.Begin(); j != resourceGroups_.End(); ++j)
  893. {
  894. HashMap<StringHash, SharedPtr<Resource> >::Iterator k = j->second_.resources_.Find(nameHash);
  895. if (k != j->second_.resources_.End())
  896. {
  897. // If other references exist, do not release, unless forced
  898. if ((k->second_.Refs() == 1 && k->second_.WeakRefs() == 0) || force)
  899. {
  900. j->second_.resources_.Erase(k);
  901. affectedGroups.Insert(j->first_);
  902. }
  903. break;
  904. }
  905. }
  906. }
  907. for (HashSet<StringHash>::Iterator i = affectedGroups.Begin(); i != affectedGroups.End(); ++i)
  908. UpdateResourceGroup(*i);
  909. }
  910. void ResourceCache::UpdateResourceGroup(StringHash type)
  911. {
  912. HashMap<StringHash, ResourceGroup>::Iterator i = resourceGroups_.Find(type);
  913. if (i == resourceGroups_.End())
  914. return;
  915. for (;;)
  916. {
  917. unsigned totalSize = 0;
  918. unsigned oldestTimer = 0;
  919. HashMap<StringHash, SharedPtr<Resource> >::Iterator oldestResource = i->second_.resources_.End();
  920. for (HashMap<StringHash, SharedPtr<Resource> >::Iterator j = i->second_.resources_.Begin();
  921. j != i->second_.resources_.End(); ++j)
  922. {
  923. totalSize += j->second_->GetMemoryUse();
  924. unsigned useTimer = j->second_->GetUseTimer();
  925. if (useTimer > oldestTimer)
  926. {
  927. oldestTimer = useTimer;
  928. oldestResource = j;
  929. }
  930. }
  931. i->second_.memoryUse_ = totalSize;
  932. // If memory budget defined and is exceeded, remove the oldest resource and loop again
  933. // (resources in use always return a zero timer and can not be removed)
  934. if (i->second_.memoryBudget_ && i->second_.memoryUse_ > i->second_.memoryBudget_ &&
  935. oldestResource != i->second_.resources_.End())
  936. {
  937. ATOMIC_LOGDEBUG("Resource group " + oldestResource->second_->GetTypeName() + " over memory budget, releasing resource " +
  938. oldestResource->second_->GetName());
  939. i->second_.resources_.Erase(oldestResource);
  940. }
  941. else
  942. break;
  943. }
  944. }
  945. void ResourceCache::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  946. {
  947. for (unsigned i = 0; i < fileWatchers_.Size(); ++i)
  948. {
  949. String fileName;
  950. while (fileWatchers_[i]->GetNextChange(fileName))
  951. {
  952. ReloadResourceWithDependencies(fileName);
  953. // Finally send a general file changed event even if the file was not a tracked resource
  954. using namespace FileChanged;
  955. VariantMap& eventData = GetEventDataMap();
  956. eventData[P_FILENAME] = fileWatchers_[i]->GetPath() + fileName;
  957. eventData[P_RESOURCENAME] = fileName;
  958. SendEvent(E_FILECHANGED, eventData);
  959. }
  960. }
  961. // Check for background loaded resources that can be finished
  962. #ifdef ATOMIC_THREADING
  963. {
  964. ATOMIC_PROFILE(FinishBackgroundResources);
  965. backgroundLoader_->FinishResources(finishBackgroundResourcesMs_);
  966. }
  967. #endif
  968. }
  969. File* ResourceCache::SearchResourceDirs(const String& nameIn)
  970. {
  971. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  972. for (unsigned i = 0; i < resourceDirs_.Size(); ++i)
  973. {
  974. if (fileSystem->FileExists(resourceDirs_[i] + nameIn))
  975. {
  976. // Construct the file first with full path, then rename it to not contain the resource path,
  977. // so that the file's name can be used in further GetFile() calls (for example over the network)
  978. File* file(new File(context_, resourceDirs_[i] + nameIn));
  979. file->SetName(nameIn);
  980. return file;
  981. }
  982. }
  983. // Fallback using absolute path
  984. if (fileSystem->FileExists(nameIn))
  985. return new File(context_, nameIn);
  986. return 0;
  987. }
  988. File* ResourceCache::SearchPackages(const String& nameIn)
  989. {
  990. for (unsigned i = 0; i < packages_.Size(); ++i)
  991. {
  992. if (packages_[i]->Exists(nameIn))
  993. return new File(context_, packages_[i], nameIn);
  994. }
  995. return 0;
  996. }
  997. void RegisterResourceLibrary(Context* context)
  998. {
  999. Image::RegisterObject(context);
  1000. JSONFile::RegisterObject(context);
  1001. PListFile::RegisterObject(context);
  1002. XMLFile::RegisterObject(context);
  1003. }
  1004. }