FguiModule.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. using FairyGUI;
  2. using Spine.Unity;
  3. using System;
  4. using System.Collections.Generic;
  5. using UnityEngine;
  6. using XGame.Framework.Asset;
  7. using XGame.Framework.Asyncs;
  8. using XGame.Framework.Interfaces;
  9. using XGame.Framework.UI;
  10. using XGame.Framework.UI.View;
  11. namespace XGame.Framework.FGUI
  12. {
  13. public partial class FguiModule : IUIModule, IUpdate, ILateUpdate, IUIContextSetter, IDisposable
  14. {
  15. private UIContext _context;
  16. private IUITree _uitree;
  17. private IAssetModule _assetModule;
  18. /// <summary>
  19. /// 加载中的
  20. /// </summary>
  21. private Dictionary<string, IAsync> _loadingMap;
  22. /// <summary>
  23. /// 已打开的UI
  24. /// </summary>
  25. private Dictionary<string, IUIView> _openedMap;
  26. /// <summary>
  27. /// 已关闭的UI
  28. /// </summary>
  29. private Dictionary<string, IUIView> _closedMap;
  30. /// <summary>
  31. /// Update 和 LateUpdate用
  32. /// </summary>
  33. private List<IUIView> _updates;
  34. public FguiModule(IAssetModule assetModule, IUITree uitree)
  35. {
  36. _assetModule = assetModule;
  37. _uitree = uitree;
  38. _loadingMap = new Dictionary<string, IAsync>();
  39. _openedMap = new Dictionary<string, IUIView>();
  40. _closedMap = new Dictionary<string, IUIView>();
  41. _updates = new List<IUIView>();
  42. #region 只对PackageItem有效
  43. NTexture.CustomDestroyMethod += RecycleTexture;
  44. NAudioClip.CustomDestroyMethod += RecycleAudio;
  45. GLoader3D.CustomLoadSpine += OnLoadSpine;
  46. GLoader3D.CustomSpineDestroyMethod += RecycleSpine;
  47. #endregion
  48. UIObjectFactory.SetLoaderExtension(CreatCustomLoader);
  49. }
  50. public UIContext Context { get => _context; set => _context = value; }
  51. #region 接口实现
  52. Camera IUIModule.Camera => _uitree.Camera;
  53. Canvas IUIModule.GetCanvas(UILayer layer)
  54. {
  55. return _uitree.GetCanvas(layer);
  56. }
  57. IAsync IUIModule.OpenAsync(UIKey uikey, object intent)
  58. {
  59. string key = uikey;
  60. if (_loadingMap.ContainsKey(key))
  61. {
  62. return _loadingMap[key];
  63. }
  64. var asyncGroup = new AsyncGroup();
  65. if (_openedMap.ContainsKey(key))
  66. {
  67. Log.Warn($"重复开启UI:{key}");
  68. }
  69. else if (_closedMap.TryGetValue(key, out var closedView))
  70. { // 已关闭的UI
  71. asyncGroup.On(_ =>
  72. {
  73. _closedMap.Remove(key);
  74. _uitree.SetAsLastSibling(closedView.Panel);
  75. closedView.Enable(intent);
  76. _openedMap.Add(key, closedView);
  77. });
  78. }
  79. else
  80. {
  81. _loadingMap.Add(key, asyncGroup);
  82. var objLoadAsync = new GObjectFromPackageAsync(uikey.PackageName, uikey.PanelName);
  83. objLoadAsync.Join(asyncGroup);
  84. objLoadAsync.On(_ =>
  85. {
  86. _loadingMap.Remove(key);
  87. var panelObj = objLoadAsync.Result as GComponent;
  88. if (panelObj == null)
  89. {
  90. Log.Error($"UI加载结果为空. UIKey:{uikey}");
  91. return;
  92. }
  93. var panel = new FguiPanel(panelObj, UILayer.Normal);
  94. var view = Activator.CreateInstance(uikey.UIViewType) as IUIView;
  95. (view as UIView).Init(_context.Clone(), panel);
  96. _uitree.AddPanel(panel);
  97. view.Enable(intent);
  98. _openedMap.Add(key, view);
  99. });
  100. var pkgLoadAsync = LoadUIPackageAsync(uikey);
  101. if (pkgLoadAsync != null)
  102. {
  103. pkgLoadAsync.Join(asyncGroup);
  104. pkgLoadAsync.On(_ =>
  105. {
  106. objLoadAsync.Start();
  107. });
  108. }
  109. else
  110. {
  111. objLoadAsync.Start();
  112. }
  113. }
  114. asyncGroup.End();
  115. return asyncGroup;
  116. }
  117. void IUIModule.Close(UIKey uikey, bool isDestroy)
  118. {
  119. var key = uikey.Key;
  120. if (_loadingMap.TryGetValue(key, out var async))
  121. {
  122. _loadingMap.Remove(key);
  123. async.RemoveAll();
  124. return;
  125. }
  126. if (_openedMap.TryGetValue(key, out var uiView))
  127. {
  128. _openedMap.Remove(key);
  129. uiView.Disable();
  130. _uitree.RemovePanel(uiView.Panel);
  131. if (isDestroy)
  132. {
  133. DestroyView(uiView);
  134. }
  135. else
  136. {
  137. _closedMap.Add(key, uiView);
  138. }
  139. return;
  140. }
  141. if (isDestroy && _closedMap.TryGetValue(key, out uiView))
  142. {
  143. _closedMap.Remove(key);
  144. DestroyView(uiView);
  145. }
  146. }
  147. IAsync IUIModule.Preload(UIKey uikey)
  148. {
  149. var loadAsync = LoadUIPackageAsync(uikey);
  150. return loadAsync;
  151. }
  152. void IUpdate.Update(int millisecond)
  153. {
  154. if (_openedMap.Count == 0)
  155. return;
  156. _updates.Clear();
  157. _updates.AddRange(_openedMap.Values);
  158. for (var i = 0; i < _updates.Count;)
  159. {
  160. var view = _updates[i];
  161. view.Update(millisecond);
  162. if (view.Active)
  163. {
  164. i++;
  165. }
  166. else
  167. {
  168. _updates.RemoveAt(i);
  169. }
  170. }
  171. }
  172. void ILateUpdate.LateUpdate(int millisecond)
  173. {
  174. if (_updates.Count == 0)
  175. return;
  176. foreach (var uiview in _updates)
  177. {
  178. uiview.LateUpdate(millisecond);
  179. }
  180. _updates.Clear();
  181. }
  182. void IDisposable.Dispose()
  183. {
  184. _updates.Clear();
  185. foreach (var async in _loadingMap.Values)
  186. {
  187. async.RemoveAll();
  188. }
  189. _loadingMap.Clear();
  190. foreach (var uiview in _closedMap.Values)
  191. {
  192. DestroyView(uiview);
  193. }
  194. _closedMap.Clear();
  195. foreach (var uiview in _openedMap.Values)
  196. {
  197. DestroyView(uiview);
  198. }
  199. _openedMap.Clear();
  200. #region 清理FGUI緩存
  201. StageEngine.beingQuit = true;
  202. UIPackage.RemoveAllPackages();
  203. Stage.inst.Dispose();
  204. NTexture.CustomDestroyMethod -= RecycleTexture;
  205. NAudioClip.CustomDestroyMethod -= RecycleAudio;
  206. GLoader3D.CustomLoadSpine -= OnLoadSpine;
  207. GLoader3D.CustomSpineDestroyMethod -= RecycleSpine;
  208. UIObjectFactory.Clear();
  209. ClearGloaderAssets();
  210. #endregion
  211. (_uitree as IDisposable)?.Dispose();
  212. (_assetModule as IDisposable)?.Dispose();
  213. _assetModule = null;
  214. _context = null;
  215. }
  216. #endregion
  217. #region 内部函数
  218. /// <summary>
  219. /// 加载UIPackage
  220. /// </summary>
  221. /// <param name="uikey"></param>
  222. /// <returns></returns>
  223. private IAsync LoadUIPackageAsync(UIKey uikey)
  224. {
  225. if (UIPackage.GetByName(uikey.PackageName) == null)
  226. {
  227. var pkgAddressable = FguiUtils.ToDescFileName(uikey.PackageName);
  228. var pkgLoadAsync = _assetModule.LoadAsync<TextAsset>(pkgAddressable);
  229. pkgLoadAsync.On(_ =>
  230. {
  231. var pkgAsset = pkgLoadAsync.GetResult();
  232. var descData = pkgAsset?.bytes;
  233. _assetModule.Recycle(pkgAsset);
  234. if (descData == null || descData.Length == 0)
  235. {
  236. Log.Error($"UIPackage 加载失败. UIKey:{uikey}");
  237. return;
  238. }
  239. if (UIPackage.GetByName(uikey.PackageName) == null)
  240. {
  241. UIPackage.AddPackage(descData, string.Empty, LoadPackageItemAsync);
  242. }
  243. });
  244. return pkgLoadAsync;
  245. }
  246. else
  247. {
  248. Log.Info($"UIPackage已加载. UIKey:{uikey}");
  249. return null;
  250. }
  251. }
  252. /// <summary>
  253. /// 异步加载PackageItem
  254. /// UIPackage的Texture、AudioClip等资源
  255. /// </summary>
  256. /// <param name="name"></param>
  257. /// <param name="extension"></param>
  258. /// <param name="type"></param>
  259. /// <param name="item"></param>
  260. private void LoadPackageItemAsync(string name, string extension, System.Type type, PackageItem item)
  261. {
  262. Log.Info($"LoadPackageItemAsync name:{name} extension:{extension} type:{type} itemName:{item.name}");
  263. var addressable = $"{item.owner.name}_{name}";
  264. var loadAsync = _assetModule.LoadAsync<UnityEngine.Object>(addressable);
  265. loadAsync.On(_ =>
  266. {
  267. var asset = loadAsync.GetResult();
  268. item.owner.SetItemAsset(item, Convert(asset, type), DestroyMethod.Custom);
  269. });
  270. }
  271. private object Convert(UnityEngine.Object value, Type type)
  272. {
  273. if (value == null)
  274. return default;
  275. if (type.IsInstanceOfType(value))
  276. {
  277. return value;
  278. }
  279. if (type.IsClass)
  280. {
  281. if (type.IsSubclassOf(typeof(Component)))
  282. {
  283. var go = value as GameObject;
  284. if (go != null)
  285. {
  286. return go.GetComponent(type);
  287. }
  288. var component = value as Component;
  289. if (component != null)
  290. {
  291. return component.gameObject.GetComponent(type);
  292. }
  293. }
  294. else if (type == typeof(Sprite) && value is Texture2D texture)
  295. {
  296. object sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
  297. return sprite;
  298. }
  299. }
  300. Log.Error($"UIModuleFGUI object conver type Error. source type:{value.GetType()} name:{value} target:{type}");
  301. return value;
  302. }
  303. private void DestroyView(IUIView view)
  304. {
  305. var uiPanel = (view.Panel as FguiPanel).Panel;
  306. (view as IDisposable).Dispose();
  307. uiPanel.Dispose();
  308. }
  309. /// <summary>
  310. /// 只对LoadPackageItemAsync加载的资源有效
  311. /// </summary>
  312. /// <param name="texture"></param>
  313. private void RecycleTexture(Texture texture)
  314. {
  315. Log.Info($"RecycleTexture Texture:{texture.name}");
  316. _assetModule.Recycle(texture);
  317. }
  318. /// <summary>
  319. /// 只对LoadPackageItemAsync加载的资源有效
  320. /// </summary>
  321. /// <param name="audioClip"></param>
  322. private void RecycleAudio(AudioClip audioClip)
  323. {
  324. Log.Info($"RecycleAudio AudioClip:{audioClip.name}");
  325. _assetModule?.Recycle(audioClip);
  326. }
  327. private GLoader CreatCustomLoader()
  328. {
  329. return new CustomLoader(this);
  330. }
  331. private void OnLoadSpine(string addressable, Action<SkeletonDataAsset> action)
  332. {
  333. var loadAsync = _assetModule.LoadAsync<SkeletonDataAsset>(addressable);
  334. loadAsync.On(_ =>
  335. {
  336. var data = loadAsync.GetResult();
  337. if (data == null)
  338. {
  339. return;
  340. }
  341. action(data);
  342. });
  343. }
  344. private void RecycleSpine(SkeletonDataAsset asset)
  345. {
  346. _assetModule.Recycle(asset);
  347. }
  348. #endregion
  349. }
  350. }