using System; using System.Collections; using System.Collections.Generic; using System.IO; using FairyGUI; using SGModule.Common; using SGModule.NetKit; using TowerClimberChronicles; using UnityEditor; using UnityEngine; using UnityEngine.Events; using UnityEngine.Networking; using UnityEngine.Video; using Object = UnityEngine.Object; public class TextureHelper { public static void GetNTexture(string path, string name, UnityAction action) { if (!nTexturesDic.TryGetValue(path + name, out var spr)) try { LoadKit.Instance.LoadSprite(path, name, sprite => { if (sprite != null) { spr = new NTexture(sprite); action?.Invoke(spr); nTexturesDic.TryAdd(path + name, spr); } }); } catch (Exception e) { Debug.LogError(e); } else action?.Invoke(spr); } public static void GetItemIcon(int itemId, UnityAction action = null) { var itemIconPath = "Atlas.Item"; var name = itemId.ToString(); if (!true) if (itemId is 101 or 111) name = "102"; if (itemId is 102 or 106) name += "_normal"; GetNTexture(itemIconPath, name, action); } #region 缓存 private static readonly Dictionary nTexturesDic = new(); private static readonly Dictionary avatarNTexturesDic = new(); #endregion #region 加载Texture private static IEnumerator GetLocalTexture(string imagePath, Action action) { var file = $"{Application.persistentDataPath}/{imagePath}"; var fileInfo = new FileInfo(file); if (!fileInfo.Exists) { action?.Invoke(null); yield break; } var avatarPath = $"file://{file}"; var uwr = UnityWebRequestTexture.GetTexture(avatarPath); yield return uwr.SendWebRequest(); if (uwr.result is UnityWebRequest.Result.ConnectionError or UnityWebRequest.Result.ProtocolError) { action?.Invoke(null); yield break; } var texture2D = DownloadHandlerTexture.GetContent(uwr); action?.Invoke(texture2D); } public static string imgUrl = ""; #region 材质池 #endregion #region 图片加载接口 public static string getResPath() { // 删除旧资源 if (!DataMgr.curResVersion.Value.IsNullOrWhiteSpace() && DataMgr.curResVersion.Value != ConfigSystem.GetCommonConf().ResVersion) { var oldFolder = Path.Combine(Application.persistentDataPath, DataMgr.curResVersion.Value); if (Directory.Exists(oldFolder)) { Directory.Delete(oldFolder, true); } DataMgr.curResVersion.Value = ConfigSystem.GetCommonConf().ResVersion; } else if (DataMgr.curResVersion.Value.IsNullOrWhiteSpace()) { DataMgr.curResVersion.Value = ConfigSystem.GetCommonConf().ResVersion; } if (ConfigSystem.GetCommonConf().ResVersion.IsNullOrWhiteSpace()) { Debug.LogError("获取资源路径失败"); return Application.persistentDataPath; } string curFolder = Path.Combine(Application.persistentDataPath, ConfigSystem.GetCommonConf().ResVersion); return curFolder; } public static void SetImgLoader(GLoader loader, string fileName, Action callback, string folder, string localFolder, bool priority = true, bool isLoad = false, bool isGameBg = false, string image_type = "jpg") { var localPath = Path.Combine(getResPath(), localFolder, fileName + "." + image_type); Debug.Log("????????????????????" + localPath); if (File.Exists(localPath)) { Debug.Log($"[SetImgLoader] 本地存在,直接加载 {fileName}"); CrazyAsyKit.StartCoroutine(LoadTexture(fileName, loader, callback, localFolder, isGameBg, image_type)); return; } } #endregion #region 普通队列逻辑 public static IEnumerator LoadTexture(string fileName, GLoader loader, Action callback = null, string folder = "", bool isGameBg = false, string img_type = "jpg") { string encryptedPath = Path.Combine(getResPath(), folder, fileName + "." + img_type); Debug.Log($"[LoadEncryptedTexture] 开始加载加密图片: {fileName}"); Debug.Log($"[LoadTexture] 开始加载本地图片 {fileName}"); using (var www = UnityWebRequestTexture.GetTexture("file://")) // using (var www = UnityWebRequestTexture.GetTexture("file://" + GetDecryptedImagePath(fileName, folder, img_type))) { yield return www.SendWebRequest(); if (www.result == UnityWebRequest.Result.Success) { var tex = DownloadHandlerTexture.GetContent(www); var nTex = new NTexture(tex) { destroyMethod = DestroyMethod.Destroy }; tex.name = fileName; if (loader != null && loader.texture != null) { loader.texture.Dispose(); // 释放 GPU 资源 loader.texture = null; // 断开引用 } if (loader != null && !loader.isDisposed) { loader.texture = nTex; // Debug.Log($"[LoadTexture] 图片已设置到 Loader {fileName}"); callback?.Invoke(nTex); } else { // Debug.Log($"[LoadTexture] Loader 不存在或已销毁 {fileName}"); } //设置游戏背景时,传的是UGUI的,不传loader if (isGameBg) { callback?.Invoke(nTex); } } else { Debug.LogError($"[LoadTexture] 加载失败 {www.error}"); callback?.Invoke(null); } } if (loader != null && !loader.isDisposed) loader.visible = true; } public static void setPuzzle(string fileName, List image_list, List vec2_list) { Sprite _sprite = Resources.Load("puzzle/img/" + fileName); for (int i = 0; i < image_list.Count; i++) { image_list[i].sprite = _sprite; image_list[i].SetNativeSize(); image_list[i].rectTransform.anchoredPosition = vec2_list[i]; } // 调用统一的 SetImgLoader,不需要再自己写下载逻辑 // SetImgLoader(null, fileName, nTex => // { // Debug.Log("设置拼图的回调!!!!!!!!"); // if (nTex != null && nTex.nativeTexture != null) // { // var tex2D = nTex.nativeTexture as Texture2D; // if (tex2D == null) // { // Debug.LogError("NTexture 转换失败!"); // return; // } // // 创建 Sprite // var sprite = Sprite.Create( // tex2D, // new Rect(0, 0, tex2D.width, tex2D.height), // new Vector2(0.5f, 0.5f) // ); // for (int i = 0; i < image_list.Count; i++) // { // image_list[i].sprite = sprite; // image_list[i].SetNativeSize(); // image_list[i].rectTransform.anchoredPosition = vec2_list[i]; // } // } // else // { // Debug.LogError("背景图片加载失败!"); // } // }, FolderNames.Jigsaw + "/", FolderNames.Jigsaw, true, false, true, "png"); // ✅ 背景一般是立刻需要的,走优先下载 } #endregion #region 材质处理 #endregion /// /// 彻底清理材质池(切场景/退出游戏时调用) /// /// private static IEnumerator GetTextureFromNet(string type, int imgId, string imgUrl, Action action = null) { var imagePath = $"{CommonHelper.GetAppSavePath()}/{type}/{imgId}.jpg"; var fileInfo = new FileInfo(imagePath); if (fileInfo.Exists) { action?.Invoke(true); yield break; } var avatarRequest = UnityWebRequest.Get(imgUrl); yield return avatarRequest.SendWebRequest(); if (avatarRequest.result == UnityWebRequest.Result.ConnectionError || avatarRequest.result == UnityWebRequest.Result.ProtocolError) { action?.Invoke(false); } else { var avatarData = avatarRequest.downloadHandler.data; var dirPath = Path.GetDirectoryName(imagePath); if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); if (fileInfo.Exists) yield break; Stream stream = fileInfo.Create(); stream.Write(avatarData, 0, avatarData.Length); stream.Close(); stream.Dispose(); action?.Invoke(true); } } #endregion #region 头像相关 public static void SetAvatarToLoader(int avatarId, GLoader _GLoader, bool IsNeedDefAvatar = true) { if (!avatarNTexturesDic.TryGetValue(avatarId, out var spr)) try { Sprite sprite = null; if (avatarId == 0) { if (!PlayerPrefsKit.ReadBool("IsLogin")) { avatarId = 1; SetAvatarToLoader(avatarId, _GLoader); return; } if (PlayerPrefsKit.ReadString("AvatarUrl").IsNullOrWhiteSpace()) { _GLoader.url = "ui://pmf3wbjicxrg4"; return; } GetSelfFaceBookAvatar(texture => { if (_GLoader != null) { if (texture != null) _GLoader.texture = texture; else _GLoader.url = "ui://pmf3wbjicxrg4"; } }); return; } if (avatarId > 100) { if (IsNeedDefAvatar) _GLoader.url = "ui://pmf3wbjicxrg4"; GetFaceBookAvatar(avatarId, e => { if (_GLoader != null) { if (e == null) _GLoader.url = "ui://pmf3wbjicxrg4"; else _GLoader.texture = e; } }); return; } LoadKit.Instance.LoadSprite("Atlas.Avatar", avatarId.ToString(), spr => { sprite = spr; var spr1 = new NTexture(sprite); _GLoader.texture = spr1; avatarNTexturesDic.Add(avatarId, spr1); }); } catch (Exception e) { Debug.LogError(e); } else _GLoader.texture = spr; } private static IEnumerator GetAvatarLocal(int avatarId, Action action) { yield return GetLocalTexture($"Avatar/{avatarId}.jpg", action); } #endregion #region FaceBook头像相关 public static void GetFaceBookAvatar(int avatarId, Action action) { if (!avatarNTexturesDic.TryGetValue(avatarId, out var spr)) HallManager.Instance.StartCoroutine(GetAvatarLocal(avatarId, texture => { if (texture == null) { action?.Invoke(null); return; } spr = new NTexture(texture); if (avatarNTexturesDic.ContainsKey(avatarId)) avatarNTexturesDic.Add(avatarId, spr); action?.Invoke(spr); })); else action?.Invoke(spr); } public static void GetSelfFaceBookAvatar(Action action) { if (!avatarNTexturesDic.TryGetValue(0, out var spr)) { } else { action?.Invoke(spr); } } #endregion }