ResourcesComponent.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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");
  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. }
  128. }
  129. private static string[] GetDependencies(this ResourcesComponent self, string assetBundleName)
  130. {
  131. string[] dependencies = Array.Empty<string>();
  132. if (self.DependenciesCache.TryGetValue(assetBundleName, out dependencies))
  133. {
  134. return dependencies;
  135. }
  136. if (!Define.IsAsync)
  137. {
  138. if (Define.IsEditor)
  139. {
  140. dependencies = Define.GetAssetBundleDependencies(assetBundleName, true);
  141. }
  142. }
  143. else
  144. {
  145. dependencies = self.AssetBundleManifestObject.GetAllDependencies(assetBundleName);
  146. }
  147. self.DependenciesCache.Add(assetBundleName, dependencies);
  148. return dependencies;
  149. }
  150. private static string[] GetSortedDependencies(this ResourcesComponent self, string assetBundleName)
  151. {
  152. var info = new Dictionary<string, int>();
  153. var parents = new List<string>();
  154. self.CollectDependencies(parents, assetBundleName, info);
  155. string[] ss = info.OrderBy(x => x.Value).Select(x => x.Key).ToArray();
  156. return ss;
  157. }
  158. private static void CollectDependencies(this ResourcesComponent self, List<string> parents, string assetBundleName, Dictionary<string, int> info)
  159. {
  160. parents.Add(assetBundleName);
  161. string[] deps = self.GetDependencies(assetBundleName);
  162. foreach (string parent in parents)
  163. {
  164. if (!info.ContainsKey(parent))
  165. {
  166. info[parent] = 0;
  167. }
  168. info[parent] += deps.Length;
  169. }
  170. foreach (string dep in deps)
  171. {
  172. if (parents.Contains(dep))
  173. {
  174. throw new Exception($"包有循环依赖,请重新标记: {assetBundleName} {dep}");
  175. }
  176. self.CollectDependencies(parents, dep, info);
  177. }
  178. parents.RemoveAt(parents.Count - 1);
  179. }
  180. public static bool Contains(this ResourcesComponent self, string bundleName)
  181. {
  182. return self.bundles.ContainsKey(bundleName);
  183. }
  184. public static UnityEngine.Object GetAsset(this ResourcesComponent self, string bundleName, string prefab)
  185. {
  186. Dictionary<string, UnityEngine.Object> dict;
  187. if (!self.resourceCache.TryGetValue(bundleName.BundleNameToLower(), out dict))
  188. {
  189. throw new Exception($"not found asset: {bundleName} {prefab}");
  190. }
  191. UnityEngine.Object resource = null;
  192. if (!dict.TryGetValue(prefab, out resource))
  193. {
  194. throw new Exception($"not found asset: {bundleName} {prefab}");
  195. }
  196. return resource;
  197. }
  198. // 一帧卸载一个包,避免卡死
  199. public static async ETTask UnloadBundleAsync(this ResourcesComponent self, string assetBundleName, bool unload = true)
  200. {
  201. assetBundleName = assetBundleName.BundleNameToLower();
  202. string[] dependencies = self.GetSortedDependencies(assetBundleName);
  203. //Log.Debug($"-----------dep unload start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  204. foreach (string dependency in dependencies)
  205. {
  206. CoroutineLock coroutineLock = null;
  207. try
  208. {
  209. coroutineLock = await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, assetBundleName.GetHashCode());
  210. self.UnloadOneBundle(dependency, unload);
  211. await TimerComponent.Instance.WaitFrameAsync();
  212. }
  213. finally
  214. {
  215. coroutineLock?.Dispose();
  216. }
  217. }
  218. //Log.Debug($"-----------dep unload finish {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  219. }
  220. // 只允许场景设置unload为false
  221. public static void UnloadBundle(this ResourcesComponent self, string assetBundleName, bool unload = true)
  222. {
  223. assetBundleName = assetBundleName.BundleNameToLower();
  224. string[] dependencies = self.GetSortedDependencies(assetBundleName);
  225. //Log.Debug($"-----------dep unload start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  226. foreach (string dependency in dependencies)
  227. {
  228. self.UnloadOneBundle(dependency, unload);
  229. }
  230. //Log.Debug($"-----------dep unload finish {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  231. }
  232. private static void UnloadOneBundle(this ResourcesComponent self, string assetBundleName, bool unload = true)
  233. {
  234. assetBundleName = assetBundleName.BundleNameToLower();
  235. ABInfo abInfo;
  236. if (!self.bundles.TryGetValue(assetBundleName, out abInfo))
  237. {
  238. return;
  239. }
  240. //Log.Debug($"---------------unload one bundle {assetBundleName} refcount: {abInfo.RefCount - 1}");
  241. --abInfo.RefCount;
  242. if (abInfo.RefCount > 0)
  243. {
  244. return;
  245. }
  246. //Log.Debug($"---------------truly unload one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  247. self.bundles.Remove(assetBundleName);
  248. self.resourceCache.Remove(assetBundleName);
  249. abInfo.Destroy(unload);
  250. // Log.Debug($"cache count: {self.cacheDictionary.Count}");
  251. }
  252. /// <summary>
  253. /// 同步加载assetbundle
  254. /// </summary>
  255. /// <param name="assetBundleName"></param>
  256. /// <returns></returns>
  257. public static void LoadBundle(this ResourcesComponent self, string assetBundleName)
  258. {
  259. assetBundleName = assetBundleName.ToLower();
  260. string[] dependencies = self.GetSortedDependencies(assetBundleName);
  261. //Log.Debug($"-----------dep load start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  262. foreach (string dependency in dependencies)
  263. {
  264. if (string.IsNullOrEmpty(dependency))
  265. {
  266. continue;
  267. }
  268. self.LoadOneBundle(dependency);
  269. }
  270. //Log.Debug($"-----------dep load finish {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  271. }
  272. private static void AddResource(this ResourcesComponent self, string bundleName, string assetName, UnityEngine.Object resource)
  273. {
  274. Dictionary<string, UnityEngine.Object> dict;
  275. if (!self.resourceCache.TryGetValue(bundleName.BundleNameToLower(), out dict))
  276. {
  277. dict = new Dictionary<string, UnityEngine.Object>();
  278. self.resourceCache[bundleName] = dict;
  279. }
  280. dict[assetName] = resource;
  281. }
  282. private static void LoadOneBundle(this ResourcesComponent self, string assetBundleName)
  283. {
  284. assetBundleName = assetBundleName.BundleNameToLower();
  285. ABInfo abInfo;
  286. if (self.bundles.TryGetValue(assetBundleName, out abInfo))
  287. {
  288. ++abInfo.RefCount;
  289. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  290. return;
  291. }
  292. if (!Define.IsAsync)
  293. {
  294. if (Define.IsEditor)
  295. {
  296. string[] realPath = null;
  297. realPath = Define.GetAssetPathsFromAssetBundle(assetBundleName);
  298. foreach (string s in realPath)
  299. {
  300. string assetName = Path.GetFileNameWithoutExtension(s);
  301. UnityEngine.Object resource = Define.LoadAssetAtPath(s);
  302. self.AddResource(assetBundleName, assetName, resource);
  303. }
  304. if (realPath.Length > 0)
  305. {
  306. abInfo = self.AddChild<ABInfo, string, AssetBundle>(assetBundleName, null);
  307. self.bundles[assetBundleName] = abInfo;
  308. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  309. }
  310. else
  311. {
  312. Log.Error($"assets bundle not found: {assetBundleName}");
  313. }
  314. }
  315. return;
  316. }
  317. string p = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
  318. AssetBundle assetBundle = null;
  319. if (File.Exists(p))
  320. {
  321. assetBundle = AssetBundle.LoadFromFile(p);
  322. }
  323. else
  324. {
  325. p = Path.Combine(PathHelper.AppResPath, assetBundleName);
  326. assetBundle = AssetBundle.LoadFromFile(p);
  327. }
  328. if (assetBundle == null)
  329. {
  330. // 获取资源的时候会抛异常,这个地方不直接抛异常,因为有些地方需要Load之后判断是否Load成功
  331. Log.Warning($"assets bundle not found: {assetBundleName}");
  332. return;
  333. }
  334. if (!assetBundle.isStreamedSceneAssetBundle)
  335. {
  336. // 异步load资源到内存cache住
  337. var assets = assetBundle.LoadAllAssets();
  338. foreach (UnityEngine.Object asset in assets)
  339. {
  340. self.AddResource(assetBundleName, asset.name, asset);
  341. }
  342. }
  343. abInfo = self.AddChild<ABInfo, string, AssetBundle>(assetBundleName, assetBundle);
  344. self.bundles[assetBundleName] = abInfo;
  345. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  346. }
  347. /// <summary>
  348. /// 异步加载assetbundle, 加载ab包分两部分,第一部分是从硬盘加载,第二部分加载all assets。两者不能同时并发
  349. /// </summary>
  350. public static async ETTask LoadBundleAsync(this ResourcesComponent self, string assetBundleName)
  351. {
  352. assetBundleName = assetBundleName.BundleNameToLower();
  353. string[] dependencies = self.GetSortedDependencies(assetBundleName);
  354. //Log.Debug($"-----------dep load async start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
  355. using (ListComponent<ABInfo> abInfos = ListComponent<ABInfo>.Create())
  356. {
  357. async ETTask LoadDependency(string dependency, List<ABInfo> abInfosList)
  358. {
  359. CoroutineLock coroutineLock = null;
  360. try
  361. {
  362. coroutineLock = await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, dependency.GetHashCode());
  363. ABInfo abInfo = await self.LoadOneBundleAsync(dependency);
  364. if (abInfo == null || abInfo.RefCount > 1)
  365. {
  366. return;
  367. }
  368. abInfosList.Add(abInfo);
  369. }
  370. finally
  371. {
  372. coroutineLock?.Dispose();
  373. }
  374. }
  375. // LoadFromFileAsync部分可以并发加载
  376. using (ListComponent<ETTask> tasks = ListComponent<ETTask>.Create())
  377. {
  378. foreach (string dependency in dependencies)
  379. {
  380. tasks.Add(LoadDependency(dependency, abInfos));
  381. }
  382. await ETTaskHelper.WaitAll(tasks);
  383. // ab包从硬盘加载完成,可以再并发加载all assets
  384. tasks.Clear();
  385. foreach (ABInfo abInfo in abInfos)
  386. {
  387. tasks.Add(self.LoadOneBundleAllAssets(abInfo));
  388. }
  389. await ETTaskHelper.WaitAll(tasks);
  390. }
  391. }
  392. }
  393. private static async ETTask<ABInfo> LoadOneBundleAsync(this ResourcesComponent self, string assetBundleName)
  394. {
  395. assetBundleName = assetBundleName.BundleNameToLower();
  396. ABInfo abInfo;
  397. if (self.bundles.TryGetValue(assetBundleName, out abInfo))
  398. {
  399. ++abInfo.RefCount;
  400. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  401. return null;
  402. }
  403. string p = "";
  404. AssetBundle assetBundle = null;
  405. if (!Define.IsAsync)
  406. {
  407. if (Define.IsEditor)
  408. {
  409. string[] realPath = Define.GetAssetPathsFromAssetBundle(assetBundleName);
  410. foreach (string s in realPath)
  411. {
  412. string assetName = Path.GetFileNameWithoutExtension(s);
  413. UnityEngine.Object resource = Define.LoadAssetAtPath(s);
  414. self.AddResource(assetBundleName, assetName, resource);
  415. }
  416. if (realPath.Length > 0)
  417. {
  418. abInfo = self.AddChild<ABInfo, string, AssetBundle>(assetBundleName, null);
  419. self.bundles[assetBundleName] = abInfo;
  420. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  421. }
  422. else
  423. {
  424. Log.Error("Bundle not exist! BundleName: " + assetBundleName);
  425. }
  426. // 编辑器模式也不能同步加载
  427. await TimerComponent.Instance.WaitAsync(100);
  428. return abInfo;
  429. }
  430. }
  431. p = Path.Combine(PathHelper.AppHotfixResPath, assetBundleName);
  432. if (!File.Exists(p))
  433. {
  434. p = Path.Combine(PathHelper.AppResPath, assetBundleName);
  435. }
  436. Log.Debug("Async load bundle BundleName : " + p);
  437. // if (!File.Exists(p))
  438. // {
  439. // Log.Error("Async load bundle not exist! BundleName : " + p);
  440. // return null;
  441. // }
  442. AssetBundleCreateRequest assetBundleCreateRequest = AssetBundle.LoadFromFileAsync(p);
  443. await assetBundleCreateRequest;
  444. assetBundle = assetBundleCreateRequest.assetBundle;
  445. if (assetBundle == null)
  446. {
  447. // 获取资源的时候会抛异常,这个地方不直接抛异常,因为有些地方需要Load之后判断是否Load成功
  448. Log.Warning($"assets bundle not found: {assetBundleName}");
  449. return null;
  450. }
  451. abInfo = self.AddChild<ABInfo, string, AssetBundle>(assetBundleName, assetBundle);
  452. self.bundles[assetBundleName] = abInfo;
  453. return abInfo;
  454. //Log.Debug($"---------------load one bundle {assetBundleName} refcount: {abInfo.RefCount}");
  455. }
  456. // 加载ab包中的all assets
  457. private static async ETTask LoadOneBundleAllAssets(this ResourcesComponent self, ABInfo abInfo)
  458. {
  459. CoroutineLock coroutineLock = null;
  460. try
  461. {
  462. coroutineLock = await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, abInfo.Name.GetHashCode());
  463. if (abInfo.IsDisposed || abInfo.AlreadyLoadAssets)
  464. {
  465. return;
  466. }
  467. if (abInfo.AssetBundle != null && !abInfo.AssetBundle.isStreamedSceneAssetBundle)
  468. {
  469. // 异步load资源到内存cache住
  470. AssetBundleRequest request = abInfo.AssetBundle.LoadAllAssetsAsync();
  471. await request;
  472. UnityEngine.Object[] assets = request.allAssets;
  473. foreach (UnityEngine.Object asset in assets)
  474. {
  475. self.AddResource(abInfo.Name, asset.name, asset);
  476. }
  477. }
  478. abInfo.AlreadyLoadAssets = true;
  479. }
  480. finally
  481. {
  482. coroutineLock?.Dispose();
  483. }
  484. }
  485. public static string DebugString(this ResourcesComponent self)
  486. {
  487. StringBuilder sb = new StringBuilder();
  488. foreach (ABInfo abInfo in self.bundles.Values)
  489. {
  490. sb.Append($"{abInfo.Name}:{abInfo.RefCount}\n");
  491. }
  492. return sb.ToString();
  493. }
  494. }
  495. [ComponentOf]
  496. public class ResourcesComponent: Entity, IAwake, IDestroy
  497. {
  498. public static ResourcesComponent Instance { get; set; }
  499. public AssetBundleManifest AssetBundleManifestObject { get; set; }
  500. public Dictionary<int, string> IntToStringDict = new Dictionary<int, string>();
  501. public Dictionary<string, string> StringToABDict = new Dictionary<string, string>();
  502. public Dictionary<string, string> BundleNameToLowerDict = new Dictionary<string, string>() { { "StreamingAssets", "StreamingAssets" } };
  503. public readonly Dictionary<string, Dictionary<string, UnityEngine.Object>> resourceCache =
  504. new Dictionary<string, Dictionary<string, UnityEngine.Object>>();
  505. public readonly Dictionary<string, ABInfo> bundles = new Dictionary<string, ABInfo>();
  506. // 缓存包依赖,不用每次计算
  507. public readonly Dictionary<string, string[]> DependenciesCache = new Dictionary<string, string[]>();
  508. }
  509. }