ResourceManager.ResourceChecker.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. //------------------------------------------------------------
  2. // Game Framework
  3. // Copyright © 2013-2021 loyalsoft. All rights reserved.
  4. // Homepage: http://www.game7000.com/
  5. // Feedback: http://www.game7000.com/
  6. //------------------------------------------------------------
  7. using GameFramework.FileSystem;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. namespace GameFramework.Resource
  12. {
  13. internal sealed partial class ResourceManager : GameFrameworkModule, IResourceManager
  14. {
  15. /// <summary>
  16. /// 资源检查器。
  17. /// </summary>
  18. private sealed partial class ResourceChecker
  19. {
  20. private readonly ResourceManager m_ResourceManager;
  21. private readonly Dictionary<ResourceName, CheckInfo> m_CheckInfos;
  22. private string m_CurrentVariant;
  23. private bool m_IgnoreOtherVariant;
  24. private bool m_UpdatableVersionListReady;
  25. private bool m_ReadOnlyVersionListReady;
  26. private bool m_ReadWriteVersionListReady;
  27. public GameFrameworkAction<ResourceName, string, LoadType, int, int, int, int> ResourceNeedUpdate;
  28. public GameFrameworkAction<int, int, int, long, long> ResourceCheckComplete;
  29. /// <summary>
  30. /// 初始化资源检查器的新实例。
  31. /// </summary>
  32. /// <param name="resourceManager">资源管理器。</param>
  33. public ResourceChecker(ResourceManager resourceManager)
  34. {
  35. m_ResourceManager = resourceManager;
  36. m_CheckInfos = new Dictionary<ResourceName, CheckInfo>();
  37. m_CurrentVariant = null;
  38. m_IgnoreOtherVariant = false;
  39. m_UpdatableVersionListReady = false;
  40. m_ReadOnlyVersionListReady = false;
  41. m_ReadWriteVersionListReady = false;
  42. ResourceNeedUpdate = null;
  43. ResourceCheckComplete = null;
  44. }
  45. /// <summary>
  46. /// 关闭并清理资源检查器。
  47. /// </summary>
  48. public void Shutdown()
  49. {
  50. m_CheckInfos.Clear();
  51. }
  52. /// <summary>
  53. /// 检查资源。
  54. /// </summary>
  55. /// <param name="currentVariant">当前使用的变体。</param>
  56. /// <param name="ignoreOtherVariant">是否忽略处理其它变体的资源,若不忽略,将会移除其它变体的资源。</param>
  57. public void CheckResources(string currentVariant, bool ignoreOtherVariant)
  58. {
  59. if (m_ResourceManager.m_ResourceHelper == null)
  60. {
  61. throw new GameFrameworkException("Resource helper is invalid.");
  62. }
  63. if (string.IsNullOrEmpty(m_ResourceManager.m_ReadOnlyPath))
  64. {
  65. throw new GameFrameworkException("Read-only path is invalid.");
  66. }
  67. if (string.IsNullOrEmpty(m_ResourceManager.m_ReadWritePath))
  68. {
  69. throw new GameFrameworkException("Read-write path is invalid.");
  70. }
  71. m_CurrentVariant = currentVariant;
  72. m_IgnoreOtherVariant = ignoreOtherVariant;
  73. m_ResourceManager.m_ResourceHelper.LoadBytes(Utility.Path.GetRemotePath(Path.Combine(m_ResourceManager.m_ReadWritePath, RemoteVersionListFileName)), new LoadBytesCallbacks(OnLoadUpdatableVersionListSuccess, OnLoadUpdatableVersionListFailure), null);
  74. m_ResourceManager.m_ResourceHelper.LoadBytes(Utility.Path.GetRemotePath(Path.Combine(m_ResourceManager.m_ReadOnlyPath, LocalVersionListFileName)), new LoadBytesCallbacks(OnLoadReadOnlyVersionListSuccess, OnLoadReadOnlyVersionListFailure), null);
  75. m_ResourceManager.m_ResourceHelper.LoadBytes(Utility.Path.GetRemotePath(Path.Combine(m_ResourceManager.m_ReadWritePath, LocalVersionListFileName)), new LoadBytesCallbacks(OnLoadReadWriteVersionListSuccess, OnLoadReadWriteVersionListFailure), null);
  76. }
  77. private void SetCachedFileSystemName(ResourceName resourceName, string fileSystemName)
  78. {
  79. GetOrAddCheckInfo(resourceName).SetCachedFileSystemName(fileSystemName);
  80. }
  81. private void SetVersionInfo(ResourceName resourceName, LoadType loadType, int length, int hashCode, int compressedLength, int compressedHashCode)
  82. {
  83. GetOrAddCheckInfo(resourceName).SetVersionInfo(loadType, length, hashCode, compressedLength, compressedHashCode);
  84. }
  85. private void SetReadOnlyInfo(ResourceName resourceName, LoadType loadType, int length, int hashCode)
  86. {
  87. GetOrAddCheckInfo(resourceName).SetReadOnlyInfo(loadType, length, hashCode);
  88. }
  89. private void SetReadWriteInfo(ResourceName resourceName, LoadType loadType, int length, int hashCode)
  90. {
  91. GetOrAddCheckInfo(resourceName).SetReadWriteInfo(loadType, length, hashCode);
  92. }
  93. private CheckInfo GetOrAddCheckInfo(ResourceName resourceName)
  94. {
  95. CheckInfo checkInfo = null;
  96. if (m_CheckInfos.TryGetValue(resourceName, out checkInfo))
  97. {
  98. return checkInfo;
  99. }
  100. checkInfo = new CheckInfo(resourceName);
  101. m_CheckInfos.Add(checkInfo.ResourceName, checkInfo);
  102. return checkInfo;
  103. }
  104. private void RefreshCheckInfoStatus()
  105. {
  106. if (!m_UpdatableVersionListReady || !m_ReadOnlyVersionListReady || !m_ReadWriteVersionListReady)
  107. {
  108. return;
  109. }
  110. int movedCount = 0;
  111. int removedCount = 0;
  112. int updateCount = 0;
  113. long updateTotalLength = 0L;
  114. long updateTotalCompressedLength = 0L;
  115. foreach (KeyValuePair<ResourceName, CheckInfo> checkInfo in m_CheckInfos)
  116. {
  117. CheckInfo ci = checkInfo.Value;
  118. ci.RefreshStatus(m_CurrentVariant, m_IgnoreOtherVariant);
  119. if (ci.Status == CheckInfo.CheckStatus.StorageInReadOnly)
  120. {
  121. m_ResourceManager.m_ResourceInfos.Add(ci.ResourceName, new ResourceInfo(ci.ResourceName, ci.FileSystemName, ci.LoadType, ci.Length, ci.HashCode, ci.CompressedLength, true, true));
  122. }
  123. else if (ci.Status == CheckInfo.CheckStatus.StorageInReadWrite)
  124. {
  125. if (ci.NeedMoveToDisk || ci.NeedMoveToFileSystem)
  126. {
  127. movedCount++;
  128. string resourceFullName = ci.ResourceName.FullName;
  129. string resourcePath = Utility.Path.GetRegularPath(Path.Combine(m_ResourceManager.m_ReadWritePath, resourceFullName));
  130. if (ci.NeedMoveToDisk)
  131. {
  132. IFileSystem fileSystem = m_ResourceManager.GetFileSystem(ci.ReadWriteFileSystemName, false);
  133. if (!fileSystem.SaveAsFile(resourceFullName, resourcePath))
  134. {
  135. throw new GameFrameworkException(Utility.Text.Format("Save as file '{0}' to '{1}' from file system '{2}' error.", resourceFullName, resourcePath, fileSystem.FullPath));
  136. }
  137. fileSystem.DeleteFile(resourceFullName);
  138. }
  139. if (ci.NeedMoveToFileSystem)
  140. {
  141. IFileSystem fileSystem = m_ResourceManager.GetFileSystem(ci.FileSystemName, false);
  142. if (!fileSystem.WriteFile(resourceFullName, resourcePath))
  143. {
  144. throw new GameFrameworkException(Utility.Text.Format("Write resource '{0}' to file system '{1}' error.", resourceFullName, fileSystem.FullPath));
  145. }
  146. if (File.Exists(resourcePath))
  147. {
  148. File.Delete(resourcePath);
  149. }
  150. }
  151. }
  152. m_ResourceManager.m_ResourceInfos.Add(ci.ResourceName, new ResourceInfo(ci.ResourceName, ci.FileSystemName, ci.LoadType, ci.Length, ci.HashCode, ci.CompressedLength, false, true));
  153. m_ResourceManager.m_ReadWriteResourceInfos.Add(ci.ResourceName, new ReadWriteResourceInfo(ci.FileSystemName, ci.LoadType, ci.Length, ci.HashCode));
  154. }
  155. else if (ci.Status == CheckInfo.CheckStatus.Update)
  156. {
  157. m_ResourceManager.m_ResourceInfos.Add(ci.ResourceName, new ResourceInfo(ci.ResourceName, ci.FileSystemName, ci.LoadType, ci.Length, ci.HashCode, ci.CompressedLength, false, false));
  158. updateCount++;
  159. updateTotalLength += ci.Length;
  160. updateTotalCompressedLength += ci.CompressedLength;
  161. if (ResourceNeedUpdate != null)
  162. {
  163. ResourceNeedUpdate(ci.ResourceName, ci.FileSystemName, ci.LoadType, ci.Length, ci.HashCode, ci.CompressedLength, ci.CompressedHashCode);
  164. }
  165. }
  166. else if (ci.Status == CheckInfo.CheckStatus.Unavailable || ci.Status == CheckInfo.CheckStatus.Disuse)
  167. {
  168. // Do nothing.
  169. }
  170. else
  171. {
  172. throw new GameFrameworkException(Utility.Text.Format("Check resources '{0}' error with unknown status.", ci.ResourceName.FullName));
  173. }
  174. if (ci.NeedRemove)
  175. {
  176. removedCount++;
  177. if (ci.ReadWriteUseFileSystem)
  178. {
  179. IFileSystem fileSystem = m_ResourceManager.GetFileSystem(ci.ReadWriteFileSystemName, false);
  180. fileSystem.DeleteFile(ci.ResourceName.FullName);
  181. }
  182. else
  183. {
  184. string resourcePath = Utility.Path.GetRegularPath(Path.Combine(m_ResourceManager.m_ReadWritePath, ci.ResourceName.FullName));
  185. if (File.Exists(resourcePath))
  186. {
  187. File.Delete(resourcePath);
  188. }
  189. }
  190. }
  191. }
  192. if (movedCount > 0 || removedCount > 0)
  193. {
  194. RemoveEmptyFileSystems();
  195. Utility.Path.RemoveEmptyDirectory(m_ResourceManager.m_ReadWritePath);
  196. }
  197. if (ResourceCheckComplete != null)
  198. {
  199. ResourceCheckComplete(movedCount, removedCount, updateCount, updateTotalLength, updateTotalCompressedLength);
  200. }
  201. }
  202. private void RemoveEmptyFileSystems()
  203. {
  204. List<string> removedFileSystemNames = null;
  205. foreach (KeyValuePair<string, IFileSystem> fileSystem in m_ResourceManager.m_ReadWriteFileSystems)
  206. {
  207. if (fileSystem.Value.FileCount <= 0)
  208. {
  209. if (removedFileSystemNames == null)
  210. {
  211. removedFileSystemNames = new List<string>();
  212. }
  213. m_ResourceManager.m_FileSystemManager.DestroyFileSystem(fileSystem.Value, true);
  214. removedFileSystemNames.Add(fileSystem.Key);
  215. }
  216. }
  217. if (removedFileSystemNames != null)
  218. {
  219. foreach (string removedFileSystemName in removedFileSystemNames)
  220. {
  221. m_ResourceManager.m_ReadWriteFileSystems.Remove(removedFileSystemName);
  222. }
  223. }
  224. }
  225. private void OnLoadUpdatableVersionListSuccess(string fileUri, byte[] bytes, float duration, object userData)
  226. {
  227. if (m_UpdatableVersionListReady)
  228. {
  229. throw new GameFrameworkException("Updatable version list has been parsed.");
  230. }
  231. MemoryStream memoryStream = null;
  232. try
  233. {
  234. memoryStream = new MemoryStream(bytes, false);
  235. UpdatableVersionList versionList = m_ResourceManager.m_UpdatableVersionListSerializer.Deserialize(memoryStream);
  236. if (!versionList.IsValid)
  237. {
  238. throw new GameFrameworkException("Deserialize updatable version list failure.");
  239. }
  240. UpdatableVersionList.Asset[] assets = versionList.GetAssets();
  241. UpdatableVersionList.Resource[] resources = versionList.GetResources();
  242. UpdatableVersionList.FileSystem[] fileSystems = versionList.GetFileSystems();
  243. UpdatableVersionList.ResourceGroup[] resourceGroups = versionList.GetResourceGroups();
  244. m_ResourceManager.m_ApplicableGameVersion = versionList.ApplicableGameVersion;
  245. m_ResourceManager.m_InternalResourceVersion = versionList.InternalResourceVersion;
  246. m_ResourceManager.m_AssetInfos = new Dictionary<string, AssetInfo>(assets.Length, StringComparer.Ordinal);
  247. m_ResourceManager.m_ResourceInfos = new Dictionary<ResourceName, ResourceInfo>(resources.Length, new ResourceNameComparer());
  248. m_ResourceManager.m_ReadWriteResourceInfos = new SortedDictionary<ResourceName, ReadWriteResourceInfo>(new ResourceNameComparer());
  249. ResourceGroup defaultResourceGroup = m_ResourceManager.GetOrAddResourceGroup(string.Empty);
  250. foreach (UpdatableVersionList.FileSystem fileSystem in fileSystems)
  251. {
  252. int[] resourceIndexes = fileSystem.GetResourceIndexes();
  253. foreach (int resourceIndex in resourceIndexes)
  254. {
  255. UpdatableVersionList.Resource resource = resources[resourceIndex];
  256. if (resource.Variant != null && resource.Variant != m_CurrentVariant)
  257. {
  258. continue;
  259. }
  260. SetCachedFileSystemName(new ResourceName(resource.Name, resource.Variant, resource.Extension), fileSystem.Name);
  261. }
  262. }
  263. foreach (UpdatableVersionList.Resource resource in resources)
  264. {
  265. if (resource.Variant != null && resource.Variant != m_CurrentVariant)
  266. {
  267. continue;
  268. }
  269. ResourceName resourceName = new ResourceName(resource.Name, resource.Variant, resource.Extension);
  270. int[] assetIndexes = resource.GetAssetIndexes();
  271. foreach (int assetIndex in assetIndexes)
  272. {
  273. UpdatableVersionList.Asset asset = assets[assetIndex];
  274. int[] dependencyAssetIndexes = asset.GetDependencyAssetIndexes();
  275. int index = 0;
  276. string[] dependencyAssetNames = new string[dependencyAssetIndexes.Length];
  277. foreach (int dependencyAssetIndex in dependencyAssetIndexes)
  278. {
  279. dependencyAssetNames[index++] = assets[dependencyAssetIndex].Name;
  280. }
  281. m_ResourceManager.m_AssetInfos.Add(asset.Name, new AssetInfo(asset.Name, resourceName, dependencyAssetNames));
  282. }
  283. SetVersionInfo(resourceName, (LoadType)resource.LoadType, resource.Length, resource.HashCode, resource.CompressedLength, resource.CompressedHashCode);
  284. defaultResourceGroup.AddResource(resourceName, resource.Length, resource.CompressedLength);
  285. }
  286. foreach (UpdatableVersionList.ResourceGroup resourceGroup in resourceGroups)
  287. {
  288. ResourceGroup group = m_ResourceManager.GetOrAddResourceGroup(resourceGroup.Name);
  289. int[] resourceIndexes = resourceGroup.GetResourceIndexes();
  290. foreach (int resourceIndex in resourceIndexes)
  291. {
  292. UpdatableVersionList.Resource resource = resources[resourceIndex];
  293. if (resource.Variant != null && resource.Variant != m_CurrentVariant)
  294. {
  295. continue;
  296. }
  297. group.AddResource(new ResourceName(resource.Name, resource.Variant, resource.Extension), resource.Length, resource.CompressedLength);
  298. }
  299. }
  300. m_UpdatableVersionListReady = true;
  301. RefreshCheckInfoStatus();
  302. }
  303. catch (Exception exception)
  304. {
  305. if (exception is GameFrameworkException)
  306. {
  307. throw;
  308. }
  309. throw new GameFrameworkException(Utility.Text.Format("Parse updatable version list exception '{0}'.", exception), exception);
  310. }
  311. finally
  312. {
  313. if (memoryStream != null)
  314. {
  315. memoryStream.Dispose();
  316. memoryStream = null;
  317. }
  318. }
  319. }
  320. private void OnLoadUpdatableVersionListFailure(string fileUri, string errorMessage, object userData)
  321. {
  322. throw new GameFrameworkException(Utility.Text.Format("Updatable version list '{0}' is invalid, error message is '{1}'.", fileUri, string.IsNullOrEmpty(errorMessage) ? "<Empty>" : errorMessage));
  323. }
  324. private void OnLoadReadOnlyVersionListSuccess(string fileUri, byte[] bytes, float duration, object userData)
  325. {
  326. if (m_ReadOnlyVersionListReady)
  327. {
  328. throw new GameFrameworkException("Read-only version list has been parsed.");
  329. }
  330. MemoryStream memoryStream = null;
  331. try
  332. {
  333. memoryStream = new MemoryStream(bytes, false);
  334. LocalVersionList versionList = m_ResourceManager.m_ReadOnlyVersionListSerializer.Deserialize(memoryStream);
  335. if (!versionList.IsValid)
  336. {
  337. throw new GameFrameworkException("Deserialize read-only version list failure.");
  338. }
  339. LocalVersionList.Resource[] resources = versionList.GetResources();
  340. LocalVersionList.FileSystem[] fileSystems = versionList.GetFileSystems();
  341. foreach (LocalVersionList.FileSystem fileSystem in fileSystems)
  342. {
  343. int[] resourceIndexes = fileSystem.GetResourceIndexes();
  344. foreach (int resourceIndex in resourceIndexes)
  345. {
  346. LocalVersionList.Resource resource = resources[resourceIndex];
  347. SetCachedFileSystemName(new ResourceName(resource.Name, resource.Variant, resource.Extension), fileSystem.Name);
  348. }
  349. }
  350. foreach (LocalVersionList.Resource resource in resources)
  351. {
  352. SetReadOnlyInfo(new ResourceName(resource.Name, resource.Variant, resource.Extension), (LoadType)resource.LoadType, resource.Length, resource.HashCode);
  353. }
  354. m_ReadOnlyVersionListReady = true;
  355. RefreshCheckInfoStatus();
  356. }
  357. catch (Exception exception)
  358. {
  359. if (exception is GameFrameworkException)
  360. {
  361. throw;
  362. }
  363. throw new GameFrameworkException(Utility.Text.Format("Parse read-only version list exception '{0}'.", exception), exception);
  364. }
  365. finally
  366. {
  367. if (memoryStream != null)
  368. {
  369. memoryStream.Dispose();
  370. memoryStream = null;
  371. }
  372. }
  373. }
  374. private void OnLoadReadOnlyVersionListFailure(string fileUri, string errorMessage, object userData)
  375. {
  376. if (m_ReadOnlyVersionListReady)
  377. {
  378. throw new GameFrameworkException("Read-only version list has been parsed.");
  379. }
  380. m_ReadOnlyVersionListReady = true;
  381. RefreshCheckInfoStatus();
  382. }
  383. private void OnLoadReadWriteVersionListSuccess(string fileUri, byte[] bytes, float duration, object userData)
  384. {
  385. if (m_ReadWriteVersionListReady)
  386. {
  387. throw new GameFrameworkException("Read-write version list has been parsed.");
  388. }
  389. MemoryStream memoryStream = null;
  390. try
  391. {
  392. memoryStream = new MemoryStream(bytes, false);
  393. LocalVersionList versionList = m_ResourceManager.m_ReadWriteVersionListSerializer.Deserialize(memoryStream);
  394. if (!versionList.IsValid)
  395. {
  396. throw new GameFrameworkException("Deserialize read-write version list failure.");
  397. }
  398. LocalVersionList.Resource[] resources = versionList.GetResources();
  399. LocalVersionList.FileSystem[] fileSystems = versionList.GetFileSystems();
  400. foreach (LocalVersionList.FileSystem fileSystem in fileSystems)
  401. {
  402. int[] resourceIndexes = fileSystem.GetResourceIndexes();
  403. foreach (int resourceIndex in resourceIndexes)
  404. {
  405. LocalVersionList.Resource resource = resources[resourceIndex];
  406. SetCachedFileSystemName(new ResourceName(resource.Name, resource.Variant, resource.Extension), fileSystem.Name);
  407. }
  408. }
  409. foreach (LocalVersionList.Resource resource in resources)
  410. {
  411. SetReadWriteInfo(new ResourceName(resource.Name, resource.Variant, resource.Extension), (LoadType)resource.LoadType, resource.Length, resource.HashCode);
  412. }
  413. m_ReadWriteVersionListReady = true;
  414. RefreshCheckInfoStatus();
  415. }
  416. catch (Exception exception)
  417. {
  418. if (exception is GameFrameworkException)
  419. {
  420. throw;
  421. }
  422. throw new GameFrameworkException(Utility.Text.Format("Parse read-write version list exception '{0}'.", exception), exception);
  423. }
  424. finally
  425. {
  426. if (memoryStream != null)
  427. {
  428. memoryStream.Dispose();
  429. memoryStream = null;
  430. }
  431. }
  432. }
  433. private void OnLoadReadWriteVersionListFailure(string fileUri, string errorMessage, object userData)
  434. {
  435. if (m_ReadWriteVersionListReady)
  436. {
  437. throw new GameFrameworkException("Read-write version list has been parsed.");
  438. }
  439. m_ReadWriteVersionListReady = true;
  440. RefreshCheckInfoStatus();
  441. }
  442. }
  443. }
  444. }