ProviderBase.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Threading.Tasks;
  5. namespace YooAsset
  6. {
  7. internal abstract class ProviderBase
  8. {
  9. public enum EStatus
  10. {
  11. None = 0,
  12. CheckBundle,
  13. Loading,
  14. Checking,
  15. Succeed,
  16. Failed,
  17. }
  18. /// <summary>
  19. /// 资源提供者唯一标识符
  20. /// </summary>
  21. public string ProviderGUID { private set; get; }
  22. /// <summary>
  23. /// 所属资源系统
  24. /// </summary>
  25. public AssetSystemImpl Impl { private set; get; }
  26. /// <summary>
  27. /// 资源信息
  28. /// </summary>
  29. public AssetInfo MainAssetInfo { private set; get; }
  30. /// <summary>
  31. /// 获取的资源对象
  32. /// </summary>
  33. public UnityEngine.Object AssetObject { protected set; get; }
  34. /// <summary>
  35. /// 获取的资源对象集合
  36. /// </summary>
  37. public UnityEngine.Object[] AllAssetObjects { protected set; get; }
  38. /// <summary>
  39. /// 获取的场景对象
  40. /// </summary>
  41. public UnityEngine.SceneManagement.Scene SceneObject { protected set; get; }
  42. /// <summary>
  43. /// 原生文件路径
  44. /// </summary>
  45. public string RawFilePath { protected set; get; }
  46. /// <summary>
  47. /// 当前的加载状态
  48. /// </summary>
  49. public EStatus Status { protected set; get; } = EStatus.None;
  50. /// <summary>
  51. /// 最近的错误信息
  52. /// </summary>
  53. public string LastError { protected set; get; } = string.Empty;
  54. /// <summary>
  55. /// 加载进度
  56. /// </summary>
  57. public float Progress { protected set; get; } = 0f;
  58. /// <summary>
  59. /// 引用计数
  60. /// </summary>
  61. public int RefCount { private set; get; } = 0;
  62. /// <summary>
  63. /// 是否已经销毁
  64. /// </summary>
  65. public bool IsDestroyed { private set; get; } = false;
  66. /// <summary>
  67. /// 是否完毕(成功或失败)
  68. /// </summary>
  69. public bool IsDone
  70. {
  71. get
  72. {
  73. return Status == EStatus.Succeed || Status == EStatus.Failed;
  74. }
  75. }
  76. protected BundleLoaderBase OwnerBundle { private set; get; }
  77. protected DependAssetBundles DependBundles { private set; get; }
  78. protected bool IsWaitForAsyncComplete { private set; get; } = false;
  79. private readonly List<OperationHandleBase> _handles = new List<OperationHandleBase>();
  80. public ProviderBase(AssetSystemImpl impl, string providerGUID, AssetInfo assetInfo)
  81. {
  82. Impl = impl;
  83. ProviderGUID = providerGUID;
  84. MainAssetInfo = assetInfo;
  85. // 创建资源包加载器
  86. if (impl != null)
  87. {
  88. OwnerBundle = impl.CreateOwnerAssetBundleLoader(assetInfo);
  89. OwnerBundle.Reference();
  90. OwnerBundle.AddProvider(this);
  91. var dependList = impl.CreateDependAssetBundleLoaders(assetInfo);
  92. DependBundles = new DependAssetBundles(dependList);
  93. DependBundles.Reference();
  94. }
  95. }
  96. /// <summary>
  97. /// 轮询更新方法
  98. /// </summary>
  99. public abstract void Update();
  100. /// <summary>
  101. /// 销毁资源对象
  102. /// </summary>
  103. public virtual void Destroy()
  104. {
  105. IsDestroyed = true;
  106. // 释放资源包加载器
  107. if (OwnerBundle != null)
  108. {
  109. OwnerBundle.Release();
  110. OwnerBundle = null;
  111. }
  112. if (DependBundles != null)
  113. {
  114. DependBundles.Release();
  115. DependBundles = null;
  116. }
  117. }
  118. /// <summary>
  119. /// 是否可以销毁
  120. /// </summary>
  121. public bool CanDestroy()
  122. {
  123. if (IsDone == false)
  124. return false;
  125. return RefCount <= 0;
  126. }
  127. /// <summary>
  128. /// 是否为场景提供者
  129. /// </summary>
  130. public bool IsSceneProvider()
  131. {
  132. if (this is BundledSceneProvider || this is DatabaseSceneProvider)
  133. return true;
  134. else
  135. return false;
  136. }
  137. /// <summary>
  138. /// 创建操作句柄
  139. /// </summary>
  140. public T CreateHandle<T>() where T : OperationHandleBase
  141. {
  142. // 引用计数增加
  143. RefCount++;
  144. OperationHandleBase handle;
  145. if (typeof(T) == typeof(AssetOperationHandle))
  146. handle = new AssetOperationHandle(this);
  147. else if (typeof(T) == typeof(SceneOperationHandle))
  148. handle = new SceneOperationHandle(this);
  149. else if (typeof(T) == typeof(SubAssetsOperationHandle))
  150. handle = new SubAssetsOperationHandle(this);
  151. else if (typeof(T) == typeof(AllAssetsOperationHandle))
  152. handle = new AllAssetsOperationHandle(this);
  153. else if (typeof(T) == typeof(RawFileOperationHandle))
  154. handle = new RawFileOperationHandle(this);
  155. else
  156. throw new System.NotImplementedException();
  157. _handles.Add(handle);
  158. return handle as T;
  159. }
  160. /// <summary>
  161. /// 释放操作句柄
  162. /// </summary>
  163. public void ReleaseHandle(OperationHandleBase handle)
  164. {
  165. if (RefCount <= 0)
  166. YooLogger.Warning("Asset provider reference count is already zero. There may be resource leaks !");
  167. if (_handles.Remove(handle) == false)
  168. throw new System.Exception("Should never get here !");
  169. // 引用计数减少
  170. RefCount--;
  171. }
  172. /// <summary>
  173. /// 等待异步执行完毕
  174. /// </summary>
  175. public void WaitForAsyncComplete()
  176. {
  177. IsWaitForAsyncComplete = true;
  178. // 注意:主动轮询更新完成同步加载
  179. Update();
  180. // 验证结果
  181. if (IsDone == false)
  182. {
  183. YooLogger.Warning($"WaitForAsyncComplete failed to loading : {MainAssetInfo.AssetPath}");
  184. }
  185. }
  186. /// <summary>
  187. /// 处理特殊异常
  188. /// </summary>
  189. protected void ProcessCacheBundleException()
  190. {
  191. if (OwnerBundle.IsDestroyed)
  192. throw new System.Exception("Should never get here !");
  193. if (OwnerBundle.MainBundleInfo.Bundle.IsRawFile)
  194. {
  195. Status = EStatus.Failed;
  196. LastError = $"Cannot load asset bundle file using {nameof(ResourcePackage.LoadRawFileAsync)} method !";
  197. YooLogger.Error(LastError);
  198. InvokeCompletion();
  199. }
  200. else
  201. {
  202. Status = EStatus.Failed;
  203. LastError = $"The bundle {OwnerBundle.MainBundleInfo.Bundle.BundleName} has been destroyed by unity bugs !";
  204. YooLogger.Error(LastError);
  205. InvokeCompletion();
  206. }
  207. }
  208. /// <summary>
  209. /// 异步操作任务
  210. /// </summary>
  211. public Task Task
  212. {
  213. get
  214. {
  215. if (_taskCompletionSource == null)
  216. {
  217. _taskCompletionSource = new TaskCompletionSource<object>();
  218. if (IsDone)
  219. _taskCompletionSource.SetResult(null);
  220. }
  221. return _taskCompletionSource.Task;
  222. }
  223. }
  224. #region 异步编程相关
  225. private TaskCompletionSource<object> _taskCompletionSource;
  226. protected void InvokeCompletion()
  227. {
  228. DebugEndRecording();
  229. // 进度百分百完成
  230. Progress = 1f;
  231. // 注意:创建临时列表是为了防止外部逻辑在回调函数内创建或者释放资源句柄。
  232. // 注意:回调方法如果发生异常,会阻断列表里的后续回调方法!
  233. List<OperationHandleBase> tempers = new List<OperationHandleBase>(_handles);
  234. foreach (var hande in tempers)
  235. {
  236. if (hande.IsValid)
  237. {
  238. hande.InvokeCallback();
  239. }
  240. }
  241. if (_taskCompletionSource != null)
  242. _taskCompletionSource.TrySetResult(null);
  243. }
  244. #endregion
  245. #region 调试信息相关
  246. /// <summary>
  247. /// 出生的场景
  248. /// </summary>
  249. public string SpawnScene = string.Empty;
  250. /// <summary>
  251. /// 出生的时间
  252. /// </summary>
  253. public string SpawnTime = string.Empty;
  254. /// <summary>
  255. /// 加载耗时(单位:毫秒)
  256. /// </summary>
  257. public long LoadingTime { protected set; get; }
  258. // 加载耗时统计
  259. private Stopwatch _watch = null;
  260. [Conditional("DEBUG")]
  261. public void InitSpawnDebugInfo()
  262. {
  263. SpawnScene = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name; ;
  264. SpawnTime = SpawnTimeToString(UnityEngine.Time.realtimeSinceStartup);
  265. }
  266. private string SpawnTimeToString(float spawnTime)
  267. {
  268. float h = UnityEngine.Mathf.FloorToInt(spawnTime / 3600f);
  269. float m = UnityEngine.Mathf.FloorToInt(spawnTime / 60f - h * 60f);
  270. float s = UnityEngine.Mathf.FloorToInt(spawnTime - m * 60f - h * 3600f);
  271. return h.ToString("00") + ":" + m.ToString("00") + ":" + s.ToString("00");
  272. }
  273. [Conditional("DEBUG")]
  274. protected void DebugBeginRecording()
  275. {
  276. if (_watch == null)
  277. {
  278. _watch = Stopwatch.StartNew();
  279. }
  280. }
  281. [Conditional("DEBUG")]
  282. private void DebugEndRecording()
  283. {
  284. if (_watch != null)
  285. {
  286. LoadingTime = _watch.ElapsedMilliseconds;
  287. _watch = null;
  288. }
  289. }
  290. /// <summary>
  291. /// 获取下载报告
  292. /// </summary>
  293. internal DownloadReport GetDownloadReport()
  294. {
  295. DownloadReport result = new DownloadReport();
  296. result.TotalSize = (ulong)OwnerBundle.MainBundleInfo.Bundle.FileSize;
  297. result.DownloadedBytes = OwnerBundle.DownloadedBytes;
  298. foreach (var dependBundle in DependBundles.DependList)
  299. {
  300. result.TotalSize += (ulong)dependBundle.MainBundleInfo.Bundle.FileSize;
  301. result.DownloadedBytes += dependBundle.DownloadedBytes;
  302. }
  303. result.Progress = (float)result.DownloadedBytes / result.TotalSize;
  304. return result;
  305. }
  306. /// <summary>
  307. /// 获取资源包的调试信息列表
  308. /// </summary>
  309. internal void GetBundleDebugInfos(List<DebugBundleInfo> output)
  310. {
  311. var bundleInfo = new DebugBundleInfo();
  312. bundleInfo.BundleName = OwnerBundle.MainBundleInfo.Bundle.BundleName;
  313. bundleInfo.RefCount = OwnerBundle.RefCount;
  314. bundleInfo.Status = OwnerBundle.Status.ToString();
  315. output.Add(bundleInfo);
  316. DependBundles.GetBundleDebugInfos(output);
  317. }
  318. #endregion
  319. }
  320. }