ResourcesComponent.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using UnityEngine;
  7. namespace ET.Client
  8. {
  9. [FriendOf(typeof(ABInfo))]
  10. public static class ABInfoSystem
  11. {
  12. [ObjectSystem]
  13. public class ABInfoAwakeSystem: AwakeSystem<ABInfo, string, AssetBundle>
  14. {
  15. protected override void Awake(ABInfo self, string abName, AssetBundle a)
  16. {
  17. self.AssetBundle = a;
  18. self.Name = abName;
  19. self.RefCount = 1;
  20. self.AlreadyLoadAssets = false;
  21. }
  22. }
  23. [ObjectSystem]
  24. public class ABInfoDestroySystem: DestroySystem<ABInfo>
  25. {
  26. protected override void Destroy(ABInfo self)
  27. {
  28. //Log.Debug($"desdroy assetbundle: {self.Name}");
  29. self.RefCount = 0;
  30. self.Name = "";
  31. self.AlreadyLoadAssets = false;
  32. self.AssetBundle = null;
  33. }
  34. }
  35. public static void Destroy(this ABInfo self, bool unload = true)
  36. {
  37. if (self.AssetBundle != null)
  38. {
  39. self.AssetBundle.Unload(unload);
  40. }
  41. self.Dispose();
  42. }
  43. }
  44. [ChildOf(typeof(ResourcesComponent))]
  45. public class ABInfo: Entity, IAwake<string, AssetBundle>, IDestroy
  46. {
  47. public string Name { get; set; }
  48. public int RefCount { get; set; }
  49. public AssetBundle AssetBundle;
  50. public bool AlreadyLoadAssets;
  51. }
  52. // 用于字符串转换,减少GC
  53. [FriendOf(typeof(ResourcesComponent))]
  54. public static class AssetBundleHelper
  55. {
  56. public static string IntToString(this int value)
  57. {
  58. string result;
  59. if (ResourcesComponent.Instance.IntToStringDict.TryGetValue(value, out result))
  60. {
  61. return result;
  62. }
  63. result = value.ToString();
  64. ResourcesComponent.Instance.IntToStringDict[value] = result;
  65. return result;
  66. }
  67. public static string StringToAB(this string value)
  68. {
  69. string result;
  70. if (ResourcesComponent.Instance.StringToABDict.TryGetValue(value, out result))
  71. {
  72. return result;
  73. }
  74. result = value + ".unity3d";
  75. ResourcesComponent.Instance.StringToABDict[value] = result;
  76. return result;
  77. }
  78. public static string IntToAB(this int value)
  79. {
  80. return value.IntToString().StringToAB();
  81. }
  82. public static string BundleNameToLower(this string value)
  83. {
  84. string result;
  85. if (ResourcesComponent.Instance.BundleNameToLowerDict.TryGetValue(value, out result))
  86. {
  87. return result;
  88. }
  89. result = value.ToLower();
  90. ResourcesComponent.Instance.BundleNameToLowerDict[value] = result;
  91. return result;
  92. }
  93. }
  94. [FriendOf(typeof(ABInfo))]
  95. [FriendOf(typeof(ResourcesComponent))]
  96. public static class ResourcesComponentSystem
  97. {
  98. [ObjectSystem]
  99. public class ResourcesComponentAwakeSystem: AwakeSystem<ResourcesComponent>
  100. {
  101. protected override void Awake(ResourcesComponent self)
  102. {
  103. ResourcesComponent.Instance = self;
  104. if (Define.IsAsync)
  105. {
  106. self.LoadOneBundle("StreamingAssets");
  107. self.AssetBundleManifestObject = (AssetBundleManifest)self.GetAsset("StreamingAssets", "AssetBundleManifest");
  108. self.UnloadBundle("StreamingAssets", false);
  109. }
  110. }
  111. }
  112. [ObjectSystem]
  113. public class ResourcesComponentDestroySystem: DestroySystem<ResourcesComponent>
  114. {
  115. protected override void Destroy(ResourcesComponent self)
  116. {
  117. ResourcesComponent.Instance = null;
  118. foreach (var abInfo in self.bundles)
  119. {
  120. abInfo.Value.Destroy();
  121. }
  122. self.bundles.Clear();
  123. self.resourceCache.Clear();
  124. self.IntToStringDict.Clear();
  125. self.StringToABDict.Clear();
  126. self.BundleNameToLowerDict.Clear();
  127. if (self.AssetBundleManifestObject != null)
  128. {
  129. UnityEngine.Object.Destroy(self.AssetBundleManifestObject);
  130. self.AssetBundleManifestObject = null;
  131. }
  132. }
  133. }
  134. private static string[] GetDependencies(this ResourcesComponent self, string assetBundleName)
  135. {
  136. string[] dependencies = Array.Empty<string>();
  137. if (self.DependenciesCache.TryGetValue(assetBundleName, out dependencies))
  138. {
  139. return dependencies;
  140. }
  141. if (!Define.IsAsync)
  142. {
  143. if (Define.IsEditor)
  144. {
  145. dependencies = Define.GetAssetBundleDependencies(assetBundleName, true);
  146. }
  147. }
  148. else
  149. {
  150. dependencies = self.AssetBundleManifestObject.GetAllDependencies(assetBundleName);
  151. }
  152. self.DependenciesCache.Add(assetBundleName, dependencies);
  153. return dependencies;
  154. }
  155. private static string[] GetSortedDependencies(this ResourcesComponent self, string assetBundleName)
  156. {
  157. var info = new Dictionary<string, int>();
  158. var parents = new List<string>();
  159. self.CollectDependencies(parents, assetBundleName, info);
  160. string[] ss = info.OrderBy(x => x.Value).Select(x => x.Key).ToArray();
  161. return ss;
  162. }
  163. private static void CollectDependencies(this ResourcesComponent self, List<string> parents, string assetBundleName, Dictionary<string, int> info)
  164. {
  165. parents.Add(assetBundleName);
  166. string[] deps = self.GetDependencies(assetBundleName);
  167. foreach (string parent in parents)
  168. {
  169. if (!info.ContainsKey(parent))
  170. {
  171. info[parent] = 0;
  172. }
  173. info[parent] += deps.Length;
  174. }
  175. foreach (string dep in deps)
  176. {
  177. if (parents.Contains(dep))
  178. {
  179. throw new Exception($"包有循环依赖,请重新标记: {assetBundleName} {dep}");
  180. }
  181. self.CollectDependencies(parents, dep, info);
  182. }
  183. parents.RemoveAt(parents.Count - 1);
  184. }
  185. public static bool Contains(this ResourcesComponent self, string bundleName)
  186. {
  187. return self.bundles.ContainsKey(bundleName);
  188. }
  189. public static UnityEngine.Object GetAsset(this ResourcesComponent self, string bundleName, string prefab)
  190. {
  191. Dictionary<string, UnityEngine.Object> dict;
  192. if (!self.resourceCache.TryGetValue(bundleName.BundleNameToLower(), out dict))
  193. {
  194. throw new Exception($"not found asset: {bundleName} {prefab}");
  195. }
  196. UnityEngine.Object resource = null;
  197. if (!dict.TryGetValue(prefab, out resource))
  198. {
  199. throw new Exception($"not found asset: {bundleName} {prefab}");
  200. }
  201. return resource;
  202. }
  203. // 一帧卸载一个包,避免卡死
  204. public static async ETTask UnloadBundleAsync(this ResourcesComponent self, string assetBundleName, bool unload = true)
  205. {
  206. assetBundleName = assetBundleName.BundleNameToLower();
  207. string[] dependencies = self.GetSortedDependencies(assetBundleName);
  208. //Log.Debug($"-----------dep unload start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  209. foreach (string dependency in dependencies)
  210. {
  211. CoroutineLock coroutineLock = null;
  212. try
  213. {
  214. coroutineLock = await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, assetBundleName.GetHashCode());
  215. self.UnloadOneBundle(dependency, unload);
  216. await TimerComponent.Instance.WaitFrameAsync();
  217. }
  218. finally
  219. {
  220. coroutineLock?.Dispose();
  221. }
  222. }
  223. //Log.Debug($"-----------dep unload finish {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  224. }
  225. // 只允许场景设置unload为false
  226. public static void UnloadBundle(this ResourcesComponent self, string assetBundleName, bool unload = true)
  227. {
  228. assetBundleName = assetBundleName.BundleNameToLower();
  229. string[] dependencies = self.GetSortedDependencies(assetBundleName);
  230. //Log.Debug($"-----------dep unload start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  231. foreach (string dependency in dependencies)
  232. {
  233. self.UnloadOneBundle(dependency, unload);
  234. }
  235. //Log.Debug($"-----------dep unload finish {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  236. }
  237. private static void UnloadOneBundle(this ResourcesComponent self, string assetBundleName, bool unload = true)
  238. {
  239. assetBundleName = assetBundleName.BundleNameToLower();
  240. ABInfo abInfo;
  241. if (!self.bundles.TryGetValue(assetBundleName, out abInfo))
  242. {
  243. return;
  244. }
  245. //Log.Debug($"---------------unload one bundle {assetBundleName} refcount: {abInfo.RefCount - 1}");
  246. --abInfo.RefCount;
  247. if (abInfo.RefCount > 0)
  248. {
  249. return;
  250. }
  251. //Log.Debug($"---------------truly unload one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  252. self.bundles.Remove(assetBundleName);
  253. self.resourceCache.Remove(assetBundleName);
  254. abInfo.Destroy(unload);
  255. // Log.Debug($"cache count: {self.cacheDictionary.Count}");
  256. }
  257. /// <summary>
  258. /// 同步加载assetbundle
  259. /// </summary>
  260. /// <param name="assetBundleName"></param>
  261. /// <returns></returns>
  262. public static void LoadBundle(this ResourcesComponent self, string assetBundleName)
  263. {
  264. assetBundleName = assetBundleName.ToLower();
  265. string[] dependencies = self.GetSortedDependencies(assetBundleName);
  266. //Log.Debug($"-----------dep load start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  267. foreach (string dependency in dependencies)
  268. {
  269. if (string.IsNullOrEmpty(dependency))
  270. {
  271. continue;
  272. }
  273. self.LoadOneBundle(dependency);
  274. }
  275. //Log.Debug($"-----------dep load finish {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  276. }
  277. private static void AddResource(this ResourcesComponent self, string bundleName, string assetName, UnityEngine.Object resource)
  278. {
  279. Dictionary<string, UnityEngine.Object> dict;
  280. if (!self.resourceCache.TryGetValue(bundleName.BundleNameToLower(), out dict))
  281. {
  282. dict = new Dictionary<string, UnityEngine.Object>();
  283. self.resourceCache[bundleName] = dict;
  284. }
  285. dict[assetName] = resource;
  286. }
  287. private static void LoadOneBundle(this ResourcesComponent self, string assetBundleName)
  288. {
  289. assetBundleName = assetBundleName.BundleNameToLower();
  290. ABInfo abInfo;
  291. if (self.bundles.TryGetValue(assetBundleName, out abInfo))
  292. {
  293. ++abInfo.RefCount;
  294. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  295. return;
  296. }
  297. if (!Define.IsAsync)
  298. {
  299. if (Define.IsEditor)
  300. {
  301. string[] realPath = null;
  302. realPath = Define.GetAssetPathsFromAssetBundle(assetBundleName);
  303. foreach (string s in realPath)
  304. {
  305. string assetName = Path.GetFileNameWithoutExtension(s);
  306. UnityEngine.Object resource = Define.LoadAssetAtPath(s);
  307. self.AddResource(assetBundleName, assetName, resource);
  308. }
  309. if (realPath.Length > 0)
  310. {
  311. abInfo = self.AddChild<ABInfo, string, AssetBundle>(assetBundleName, null);
  312. self.bundles[assetBundleName] = abInfo;
  313. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  314. }
  315. else
  316. {
  317. Log.Error($"assets bundle not found: {assetBundleName}");
  318. }
  319. }
  320. return;
  321. }
  322. string p = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
  323. AssetBundle assetBundle = null;
  324. if (File.Exists(p))
  325. {
  326. assetBundle = AssetBundle.LoadFromFile(p);
  327. }
  328. else
  329. {
  330. p = Path.Combine(PathHelper.AppResPath, assetBundleName);
  331. assetBundle = AssetBundle.LoadFromFile(p);
  332. }
  333. if (assetBundle == null)
  334. {
  335. // 获取资源的时候会抛异常,这个地方不直接抛异常,因为有些地方需要Load之后判断是否Load成功
  336. Log.Warning($"assets bundle not found: {assetBundleName}");
  337. return;
  338. }
  339. if (!assetBundle.isStreamedSceneAssetBundle)
  340. {
  341. // 异步load资源到内存cache住
  342. var assets = assetBundle.LoadAllAssets();
  343. foreach (UnityEngine.Object asset in assets)
  344. {
  345. self.AddResource(assetBundleName, asset.name, asset);
  346. }
  347. }
  348. abInfo = self.AddChild<ABInfo, string, AssetBundle>(assetBundleName, assetBundle);
  349. self.bundles[assetBundleName] = abInfo;
  350. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  351. }
  352. /// <summary>
  353. /// 异步加载assetbundle, 加载ab包分两部分,第一部分是从硬盘加载,第二部分加载all assets。两者不能同时并发
  354. /// </summary>
  355. public static async ETTask LoadBundleAsync(this ResourcesComponent self, string assetBundleName)
  356. {
  357. assetBundleName = assetBundleName.BundleNameToLower();
  358. string[] dependencies = self.GetSortedDependencies(assetBundleName);
  359. //Log.Debug($"-----------dep load async start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  360. using (ListComponent<ABInfo> abInfos = ListComponent<ABInfo>.Create())
  361. {
  362. async ETTask LoadDependency(string dependency, List<ABInfo> abInfosList)
  363. {
  364. CoroutineLock coroutineLock = null;
  365. try
  366. {
  367. coroutineLock = await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, dependency.GetHashCode());
  368. ABInfo abInfo = await self.LoadOneBundleAsync(dependency);
  369. if (abInfo == null || abInfo.RefCount > 1)
  370. {
  371. return;
  372. }
  373. abInfosList.Add(abInfo);
  374. }
  375. finally
  376. {
  377. coroutineLock?.Dispose();
  378. }
  379. }
  380. // LoadFromFileAsync部分可以并发加载
  381. using (ListComponent<ETTask> tasks = ListComponent<ETTask>.Create())
  382. {
  383. foreach (string dependency in dependencies)
  384. {
  385. tasks.Add(LoadDependency(dependency, abInfos));
  386. }
  387. await ETTaskHelper.WaitAll(tasks);
  388. // ab包从硬盘加载完成,可以再并发加载all assets
  389. tasks.Clear();
  390. foreach (ABInfo abInfo in abInfos)
  391. {
  392. tasks.Add(self.LoadOneBundleAllAssets(abInfo));
  393. }
  394. await ETTaskHelper.WaitAll(tasks);
  395. }
  396. }
  397. }
  398. private static async ETTask<ABInfo> LoadOneBundleAsync(this ResourcesComponent self, string assetBundleName)
  399. {
  400. assetBundleName = assetBundleName.BundleNameToLower();
  401. ABInfo abInfo;
  402. if (self.bundles.TryGetValue(assetBundleName, out abInfo))
  403. {
  404. ++abInfo.RefCount;
  405. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  406. return null;
  407. }
  408. string p = "";
  409. AssetBundle assetBundle = null;
  410. if (!Define.IsAsync)
  411. {
  412. if (Define.IsEditor)
  413. {
  414. string[] realPath = Define.GetAssetPathsFromAssetBundle(assetBundleName);
  415. foreach (string s in realPath)
  416. {
  417. string assetName = Path.GetFileNameWithoutExtension(s);
  418. UnityEngine.Object resource = Define.LoadAssetAtPath(s);
  419. self.AddResource(assetBundleName, assetName, resource);
  420. }
  421. if (realPath.Length > 0)
  422. {
  423. abInfo = self.AddChild<ABInfo, string, AssetBundle>(assetBundleName, null);
  424. self.bundles[assetBundleName] = abInfo;
  425. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  426. }
  427. else
  428. {
  429. Log.Error("Bundle not exist! BundleName: " + assetBundleName);
  430. }
  431. // 编辑器模式也不能同步加载
  432. await TimerComponent.Instance.WaitAsync(100);
  433. return abInfo;
  434. }
  435. }
  436. p = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
  437. if (!File.Exists(p))
  438. {
  439. p = Path.Combine(PathHelper.AppResPath, assetBundleName);
  440. }
  441. Log.Debug("Async load bundle BundleName : " + p);
  442. // if (!File.Exists(p))
  443. // {
  444. // Log.Error("Async load bundle not exist! BundleName : " + p);
  445. // return null;
  446. // }
  447. AssetBundleCreateRequest assetBundleCreateRequest = AssetBundle.LoadFromFileAsync(p);
  448. await assetBundleCreateRequest;
  449. assetBundle = assetBundleCreateRequest.assetBundle;
  450. if (assetBundle == null)
  451. {
  452. // 获取资源的时候会抛异常,这个地方不直接抛异常,因为有些地方需要Load之后判断是否Load成功
  453. Log.Warning($"assets bundle not found: {assetBundleName}");
  454. return null;
  455. }
  456. abInfo = self.AddChild<ABInfo, string, AssetBundle>(assetBundleName, assetBundle);
  457. self.bundles[assetBundleName] = abInfo;
  458. return abInfo;
  459. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  460. }
  461. // 加载ab包中的all assets
  462. private static async ETTask LoadOneBundleAllAssets(this ResourcesComponent self, ABInfo abInfo)
  463. {
  464. CoroutineLock coroutineLock = null;
  465. try
  466. {
  467. coroutineLock = await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, abInfo.Name.GetHashCode());
  468. if (abInfo.IsDisposed || abInfo.AlreadyLoadAssets)
  469. {
  470. return;
  471. }
  472. if (abInfo.AssetBundle != null && !abInfo.AssetBundle.isStreamedSceneAssetBundle)
  473. {
  474. // 异步load资源到内存cache住
  475. AssetBundleRequest request = abInfo.AssetBundle.LoadAllAssetsAsync();
  476. await request;
  477. UnityEngine.Object[] assets = request.allAssets;
  478. foreach (UnityEngine.Object asset in assets)
  479. {
  480. self.AddResource(abInfo.Name, asset.name, asset);
  481. }
  482. }
  483. abInfo.AlreadyLoadAssets = true;
  484. }
  485. finally
  486. {
  487. coroutineLock?.Dispose();
  488. }
  489. }
  490. public static string DebugString(this ResourcesComponent self)
  491. {
  492. StringBuilder sb = new StringBuilder();
  493. foreach (ABInfo abInfo in self.bundles.Values)
  494. {
  495. sb.Append($"{abInfo.Name}:{abInfo.RefCount}\n");
  496. }
  497. return sb.ToString();
  498. }
  499. }
  500. [ComponentOf]
  501. public class ResourcesComponent: Entity, IAwake, IDestroy
  502. {
  503. public static ResourcesComponent Instance { get; set; }
  504. public AssetBundleManifest AssetBundleManifestObject { get; set; }
  505. public Dictionary<int, string> IntToStringDict = new Dictionary<int, string>();
  506. public Dictionary<string, string> StringToABDict = new Dictionary<string, string>();
  507. public Dictionary<string, string> BundleNameToLowerDict = new Dictionary<string, string>() { { "StreamingAssets", "StreamingAssets" } };
  508. public readonly Dictionary<string, Dictionary<string, UnityEngine.Object>> resourceCache =
  509. new Dictionary<string, Dictionary<string, UnityEngine.Object>>();
  510. public readonly Dictionary<string, ABInfo> bundles = new Dictionary<string, ABInfo>();
  511. // 缓存包依赖,不用每次计算
  512. public readonly Dictionary<string, string[]> DependenciesCache = new Dictionary<string, string[]>();
  513. }
  514. }