TextureLoadHelp.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using UnityEngine;
  7. using UnityEngine.Networking;
  8. using UnityEngine.UI;
  9. public class TextureLoadHelp : MonoBehaviour
  10. {
  11. public static TextureLoadHelp _Instance;
  12. private Dictionary<string, TempTexData> tempTexList;
  13. private Dictionary<long, Material> waitLoadImgActionList;
  14. public float currentTotalSize = 0;
  15. public float maxSize = 500; //图片缓存-m
  16. private Dictionary<string, AssetBundle> loadDoneABList;
  17. private Dictionary<string, int> loadingABList;
  18. public Texture map_def;
  19. //临时存的封面图
  20. public Texture[] tempTextures;
  21. public string[] tempTextureName;
  22. public Texture GetTempTexture(string name)
  23. {
  24. int index = -1;
  25. for (int i = 0; i < tempTextureName.Length; i++)
  26. {
  27. if (tempTextureName[i].Equals(name))
  28. {
  29. index = i;
  30. break;
  31. }
  32. }
  33. if (index != -1)
  34. {
  35. return tempTextures[index];
  36. }
  37. else
  38. {
  39. return null;
  40. }
  41. }
  42. private void Awake()
  43. {
  44. _Instance = this;
  45. tempTexList = new Dictionary<string, TempTexData>();
  46. waitLoadImgActionList = new Dictionary<long, Material>();
  47. loadDoneABList = new Dictionary<string, AssetBundle>();
  48. loadingABList = new Dictionary<string, int>();
  49. }
  50. /// <summary>
  51. /// 加载图片
  52. /// </summary>
  53. /// <param name="path"></param>
  54. /// <param name="mat"></param>
  55. /// <returns></returns>
  56. public long LoadTexFromUrl(string path, Material mat)
  57. {
  58. long loadId = GetDownId();
  59. if (CheckCache(path))
  60. {
  61. mat.mainTexture = LoadFromCache(path);
  62. return 0;
  63. }
  64. if (tempTexList.TryGetValue(path, out var value))
  65. {
  66. value.isUsing = true;
  67. mat.mainTexture = value.tex;
  68. loadId = 0;
  69. }
  70. else
  71. {
  72. waitLoadImgActionList.Add(loadId, mat);
  73. StartCoroutine(DownLoadTex(path, loadId));
  74. }
  75. return loadId;
  76. }
  77. public long LoadTexFromUrl_AB(string ab_Name, string FileName, Material mat)
  78. {
  79. if (tempTexList.TryGetValue(FileName, out var value))
  80. {
  81. value.isUsing = true;
  82. mat.mainTexture = value.tex;
  83. return 0;
  84. }
  85. mat.mainTexture = map_def;
  86. long loadId = GetDownId();
  87. waitLoadImgActionList.Add(loadId, mat);
  88. StartCoroutine(DownLoadTex_AB(ab_Name, FileName, loadId));
  89. return loadId;
  90. }
  91. /// <summary>
  92. /// 取消加载
  93. /// </summary>
  94. /// <param name="loadId"></param>
  95. public void CancelLoad(long loadId)
  96. {
  97. if (waitLoadImgActionList.ContainsKey(loadId))
  98. {
  99. waitLoadImgActionList.Remove(loadId);
  100. }
  101. }
  102. /// <summary>
  103. /// 标记缓存图片为未使用
  104. /// </summary>
  105. /// <param name="path"></param>
  106. public void UnUsingTex(string path)
  107. {
  108. if (tempTexList.TryGetValue(path, out TempTexData disposeData))
  109. {
  110. disposeData.isUsing = false;
  111. }
  112. else
  113. {
  114. Debug.Log($"不存在缓存:{path}");
  115. }
  116. }
  117. IEnumerator DownLoadTex_AB(string ab_Name, string fileName, long loadId)
  118. {
  119. if (loadingABList.ContainsKey(ab_Name))
  120. {
  121. //Debug.Log($"{ab_Name} downloading...wait");
  122. yield return new WaitUntil(() => loadingABList[ab_Name] > 0);
  123. // if (loadingABList.ContainsKey(ab_Name))
  124. // {
  125. // loadingABList.Remove(ab_Name);
  126. // }
  127. }
  128. AssetBundle tempAb;
  129. Texture2D tex;
  130. if (loadDoneABList.TryGetValue(ab_Name, out var value))
  131. {
  132. tempAb = value;
  133. tex = tempAb.LoadAsset<Texture2D>(fileName);
  134. if (waitLoadImgActionList.TryGetValue(loadId, out Material targetMat))
  135. {
  136. if (targetMat != null && tex != null)
  137. {
  138. targetMat.mainTexture = tex;
  139. }
  140. else
  141. {
  142. if (targetMat == null)
  143. {
  144. Debug.Log($"{fileName} 材质球不存在");
  145. }
  146. if (tex == null)
  147. {
  148. Debug.Log($"{fileName} 图片不存在");
  149. }
  150. }
  151. waitLoadImgActionList.Remove(loadId);
  152. }
  153. }
  154. else
  155. {
  156. //添加到正在下载
  157. loadingABList.TryAdd(ab_Name, 0);
  158. #if UNITY_EDITOR
  159. WWW www = new WWW($"{Application.streamingAssetsPath}/{ab_Name}");
  160. #else
  161. WWW www = WWW.LoadFromCacheOrDownload($"{Application.streamingAssetsPath}/{ab_Name}",0);
  162. #endif
  163. yield return www;
  164. if (www.isDone)
  165. {
  166. tempAb = www.assetBundle;
  167. loadDoneABList.Add(ab_Name, tempAb);
  168. loadingABList[ab_Name] = 1;
  169. tex = tempAb.LoadAsset<Texture2D>(fileName);
  170. tempTexList.TryAdd(fileName, new TempTexData()
  171. {
  172. loadTime = GetTimeStamp(),
  173. name = fileName,
  174. tex = tex,
  175. size = 0,
  176. isUsing = true
  177. });
  178. if (waitLoadImgActionList.TryGetValue(loadId, out Material targetMat))
  179. {
  180. if (targetMat != null && tex != null)
  181. {
  182. targetMat.mainTexture = tex;
  183. }
  184. else
  185. {
  186. if (targetMat == null)
  187. {
  188. Debug.Log($"{fileName} 材质球不存在");
  189. }
  190. if (tex == null)
  191. {
  192. Debug.Log($"{fileName} 图片不存在");
  193. }
  194. }
  195. waitLoadImgActionList.Remove(loadId);
  196. }
  197. }
  198. else
  199. {
  200. loadingABList[ab_Name] = 2;
  201. Debug.LogError($"{ab_Name}下载失败:{www.error}");
  202. }
  203. www.Dispose();
  204. }
  205. }
  206. IEnumerator DownLoadTex(string path, long loadId)
  207. {
  208. UnityWebRequest www = UnityWebRequestTexture.GetTexture(path);
  209. yield return www.SendWebRequest();
  210. if (www.downloadHandler.isDone)
  211. {
  212. if (waitLoadImgActionList.ContainsKey(loadId))
  213. {
  214. var texture = ((DownloadHandlerTexture)www.downloadHandler).texture;
  215. float tempSize = GetSize_m(www.downloadedBytes);
  216. tempTexList.TryAdd(path, new TempTexData()
  217. {
  218. loadTime = GetTimeStamp(),
  219. name = path,
  220. tex = texture,
  221. size = tempSize,
  222. isUsing = true
  223. });
  224. currentTotalSize += tempSize;
  225. CheckSize();
  226. if (waitLoadImgActionList.TryGetValue(loadId, out Material targetMat))
  227. {
  228. if (targetMat != null)
  229. {
  230. targetMat.mainTexture = texture;
  231. }
  232. waitLoadImgActionList.Remove(loadId);
  233. }
  234. SaveInCache(path, www.downloadHandler.data);
  235. }
  236. else
  237. {
  238. www.disposeDownloadHandlerOnDispose = true;
  239. Debug.Log(path + " 下载已取消");
  240. }
  241. }
  242. else
  243. {
  244. Debug.LogError($"{path}下载失败:{www.downloadHandler.error}");
  245. }
  246. www.Dispose();
  247. }
  248. private void SaveInCache(string url, byte[] data)
  249. {
  250. string fileName = Path.GetFileName(url);
  251. string path = Application.persistentDataPath;
  252. File.WriteAllBytes(path + fileName, data);
  253. Debug.Log($"缓存:{path}{fileName}");
  254. }
  255. private Texture2D LoadFromCache(string url)
  256. {
  257. string fileName = Path.GetFileName(url);
  258. string path = Application.persistentDataPath;
  259. byte[] texBytes = File.ReadAllBytes(path + fileName);
  260. currentTotalSize += GetSize_m((ulong)texBytes.Length);
  261. Texture2D tempTex = new Texture2D(2, 2);
  262. tempTex.LoadImage(texBytes);
  263. tempTex.Apply();
  264. return tempTex;
  265. }
  266. private bool CheckCache(string url)
  267. {
  268. string fileName = Path.GetFileName(url);
  269. string path = Application.persistentDataPath;
  270. //Debug.Log($"CaChe:{path}");
  271. return File.Exists(path + fileName);
  272. }
  273. public void CheckSize()
  274. {
  275. if (currentTotalSize >= maxSize)
  276. {
  277. List<TempTexData> values = tempTexList.Values.ToList();
  278. values.Sort();
  279. for (int i = 0; i < values.Count; i++)
  280. {
  281. if (!values[i].isUsing)
  282. {
  283. if (tempTexList.TryGetValue(values[i].name, out TempTexData disposeData))
  284. {
  285. disposeData.tex = null;
  286. currentTotalSize -= disposeData.size;
  287. tempTexList.Remove(disposeData.name);
  288. }
  289. }
  290. if (currentTotalSize < maxSize)
  291. {
  292. break;
  293. }
  294. }
  295. if (currentTotalSize >= maxSize)
  296. {
  297. Debug.Log($"临时图片已超过限制大小且无可释放项!!!:{currentTotalSize}/{maxSize}");
  298. }
  299. }
  300. }
  301. /// <summary>
  302. /// 清空全部缓存
  303. /// </summary>
  304. public void ClearAllTempTex()
  305. {
  306. List<TempTexData> values = tempTexList.Values.ToList();
  307. for (int i = 0; i < values.Count; i++)
  308. {
  309. if (tempTexList.TryGetValue(values[i].name, out TempTexData disposeData))
  310. {
  311. disposeData.tex = null;
  312. currentTotalSize -= disposeData.size;
  313. tempTexList.Remove(disposeData.name);
  314. }
  315. }
  316. waitLoadImgActionList.Clear();
  317. tempTexList.Clear();
  318. Resources.UnloadUnusedAssets();
  319. GC.Collect();
  320. }
  321. private long GetDownId()
  322. {
  323. long id = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000);
  324. while (waitLoadImgActionList.ContainsKey(id))
  325. {
  326. id++;
  327. }
  328. return id;
  329. }
  330. private long GetTimeStamp()
  331. {
  332. return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
  333. }
  334. private float GetSize_m(ulong size_b)
  335. {
  336. return (size_b * 1.0f / (1024.0f * 1024.0f));
  337. }
  338. }
  339. public class TempTexData : IComparable<TempTexData>
  340. {
  341. public string name;
  342. public Texture tex;
  343. public long loadTime;
  344. public float size;
  345. public bool isUsing = true;
  346. public int CompareTo(TempTexData other)
  347. {
  348. if (other.loadTime < loadTime)
  349. {
  350. return 1;
  351. }
  352. if (other.loadTime == loadTime)
  353. {
  354. return 0;
  355. }
  356. return -1;
  357. }
  358. }