ResourcesComponent.cs 21 KB

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