LoadDll.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. using HybridCLR;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Threading.Tasks;
  9. using UnityEngine;
  10. using UnityEngine.Networking;
  11. using LitJson;
  12. using TMPro;
  13. using UnityEngine.UI;
  14. public class LoadDll : MonoBehaviour
  15. {
  16. public GameObject EditorGame;
  17. static LoadDll instance;
  18. private void Awake()
  19. {
  20. instance = this;
  21. }
  22. void Start()
  23. {
  24. this.transform.SetParent(OpenXRCamera.Instance.head.transform);
  25. this.transform.localPosition = Vector3.zero;
  26. this.transform.localEulerAngles = Vector3.zero;
  27. //PlayerPrefs.DeleteAll();
  28. #if ISLOCAL
  29. EditorGame.SetActive(true);
  30. this.gameObject.SetActive(false);
  31. #else
  32. StartCoroutine(DownLoadAssets());
  33. #endif
  34. }
  35. private static Dictionary<string, byte[]> s_assetDatas = new Dictionary<string, byte[]>();
  36. public static byte[] ReadBytesFromStreamingAssets(string dllName)
  37. {
  38. return s_assetDatas[dllName];
  39. }
  40. private string GetWebRequestPath(string asset)
  41. {
  42. var path = $"{Application.streamingAssetsPath}/{asset}";
  43. if (!path.Contains("://"))
  44. {
  45. path = "file://" + path;
  46. }
  47. return path;
  48. }
  49. private static List<string> AOTMetaAssemblyFiles { get; } = new List<string>()
  50. {
  51. "mscorlib.dll.bytes",
  52. "System.dll.bytes",
  53. "System.Core.dll.bytes",
  54. "UniTask.dll.bytes",
  55. "Minio.dll.bytes",
  56. "System.Runtime.CompilerServices.Unsafe.dll.bytes",
  57. "netstandard.dll.bytes",
  58. "COSXML.dll.bytes",
  59. "UniTask.Addressables.dll.bytes",
  60. "UniTask.DOTween.dll.bytes",
  61. "UniTask.Linq.dll.bytes",
  62. "UniTask.TextMeshPro.dll.bytes",
  63. };
  64. public Text text;
  65. public Text text2;
  66. public Slider slider;
  67. string HotUpdateScripts = "HotUpdateScripts";
  68. string HotUpdateAssets = "HotUpdateAssets";
  69. IEnumerator DownLoadAssets()
  70. {
  71. text.text = "正在获取网关数据";
  72. for (int i = 0; i < AOTMetaAssemblyFiles.Count; i++)
  73. {
  74. yield return DownLoadLocal(AOTMetaAssemblyFiles[i]);
  75. }
  76. slider.gameObject.SetActive(false);
  77. while (HttpSDKAction.Instance.jsonData==null || HttpSDKAction.Instance.jsonData=="")
  78. {
  79. yield return null;
  80. }
  81. JsonData data = new JsonData();
  82. string scUrl = "";
  83. string artUrl = "";
  84. try
  85. {
  86. data = JsonMapper.ToObject(HttpSDKAction.Instance.jsonData);
  87. scUrl = data[HotUpdateScripts].ToString();
  88. artUrl = data[HotUpdateAssets].ToString();
  89. }
  90. catch
  91. {
  92. }
  93. if(scUrl != "")
  94. {
  95. if (!bool.Parse(data["isHotUpdate"].ToString()))
  96. {
  97. text.text = "正在下载代码";
  98. yield return DownLoadAssets(scUrl, HotUpdateScripts, false);
  99. text.text = "正在下载配置";
  100. yield return DownLoadAssets(artUrl, HotUpdateAssets, false);
  101. }
  102. else if (PlayerPrefs.GetString("HotUpdateVersion") == data["HotUpdateVersion"].ToString())
  103. {
  104. text.text = "正在编译代码";
  105. string filePath = PlayerPrefs.GetString(HotUpdateScripts);
  106. Task<byte[]> Tb = File.ReadAllBytesAsync(filePath);
  107. yield return Tb;
  108. slider.gameObject.SetActive(false);
  109. Assembly.Load(Tb.Result);
  110. text.text = "正在解析配置";
  111. filePath = PlayerPrefs.GetString(HotUpdateAssets);
  112. Task<byte[]> Tb2 = File.ReadAllBytesAsync(filePath);
  113. yield return Tb2;
  114. text.text = "正在解析配置";
  115. slider.gameObject.SetActive(false);
  116. AssetBundleCreateRequest acr = AssetBundle.LoadFromMemoryAsync(Tb2.Result);
  117. while (!acr.isDone)
  118. {
  119. text2.text = (acr.progress*100).ToString("F2") + "%";
  120. slider.value = float.Parse((acr.progress ).ToString("F2"));
  121. yield return null;
  122. }
  123. slider.gameObject.SetActive(true);
  124. AssetBundleRequest abr = acr.assetBundle.LoadAssetAsync<GameObject>("LocalAsset");
  125. text.text = "正在加载配置";
  126. while (!abr.isDone)
  127. {
  128. text2.text = (abr.progress * 100).ToString("F2") + "%";
  129. slider.value = float.Parse((abr.progress ).ToString("F2"));
  130. yield return null;
  131. }
  132. copyGameObject(abr.asset);
  133. this.gameObject.SetActive(false);
  134. }
  135. else
  136. {
  137. text.text = "正在下载代码";
  138. yield return DownLoadAssets(scUrl, HotUpdateScripts);
  139. text.text = "正在下载配置";
  140. yield return DownLoadAssets(artUrl, HotUpdateAssets);
  141. }
  142. }
  143. else
  144. {
  145. text.text = "正在下载代码";
  146. yield return DownLoadAssets(scUrl, HotUpdateScripts, false);
  147. text.text = "正在下载配置";
  148. yield return DownLoadAssets(artUrl, HotUpdateAssets, false);
  149. }
  150. }
  151. public IEnumerator DownLoadLocal(string name)
  152. {
  153. slider.gameObject.SetActive(true);
  154. UnityWebRequest www = UnityWebRequest.Get(GetWebRequestPath(name));
  155. www.SendWebRequest();
  156. while (!www.isDone)
  157. {
  158. text2.text = (www.downloadProgress * 100).ToString("F2") + "%";
  159. slider.value = float.Parse((www.downloadProgress).ToString("F2"));
  160. yield return null;
  161. }
  162. #if UNITY_2020_1_OR_NEWER
  163. if (www.result != UnityWebRequest.Result.Success)
  164. {
  165. Debug.Log(www.error);
  166. }
  167. #else
  168. if (www.isHttpError || www.isNetworkError)
  169. {
  170. Debug.Log(www.error);
  171. }
  172. #endif
  173. HomologousImageMode mode = HomologousImageMode.SuperSet;
  174. LoadImageErrorCode err = RuntimeApi.LoadMetadataForAOTAssembly(www.downloadHandler.data, mode);
  175. Debug.Log($"LoadMetadataForAOTAssembly:{name}. mode:{mode} ret:{err}");
  176. }
  177. public IEnumerator DownLoadAssets(string dllPath,string name,bool isRemote=true)
  178. {
  179. slider.gameObject.SetActive(true);
  180. if(!isRemote)
  181. {
  182. dllPath = GetWebRequestPath(name);
  183. }
  184. UnityWebRequest www = UnityWebRequest.Get(dllPath);
  185. www.SendWebRequest();
  186. while (!www.isDone)
  187. {
  188. text2.text = (www.downloadProgress * 100).ToString("F2") + "%";
  189. slider.value = float.Parse((www.downloadProgress ).ToString("F2"));
  190. yield return null;
  191. }
  192. #if UNITY_2020_1_OR_NEWER
  193. if (www.result != UnityWebRequest.Result.Success)
  194. {
  195. Debug.Log(www.error);
  196. }
  197. #else
  198. if (www.isHttpError || www.isNetworkError)
  199. {
  200. Debug.Log(www.error);
  201. }
  202. #endif
  203. else
  204. {
  205. if(name == HotUpdateScripts)
  206. {
  207. text.text = "正在编译代码";
  208. slider.gameObject.SetActive(false);
  209. Assembly.Load(www.downloadHandler.data);
  210. string fileName = HotUpdateScripts;
  211. if (!Directory.Exists(Application.persistentDataPath + "/HotUpdate"))
  212. Directory.CreateDirectory(Application.persistentDataPath + "/HotUpdate" );
  213. string filePathname = Application.persistentDataPath + "/HotUpdate/" + fileName;
  214. // if (File.Exists(filePathname))
  215. // File.Delete(filePathname);
  216. File.WriteAllBytes(filePathname, www.downloadHandler.data);
  217. PlayerPrefs.SetString(HotUpdateScripts, filePathname);
  218. }
  219. else
  220. {
  221. text.text = "正在解析配置";
  222. slider.gameObject.SetActive(false);
  223. AssetBundleCreateRequest acr = AssetBundle.LoadFromMemoryAsync(www.downloadHandler.data);
  224. while (!acr.isDone)
  225. {
  226. text2.text = (acr.progress * 100).ToString("F2") + "%";
  227. slider.value = float.Parse((acr.progress ).ToString("F2"));
  228. yield return null;
  229. }
  230. slider.gameObject.SetActive(true);
  231. AssetBundleRequest abr = acr.assetBundle.LoadAssetAsync<GameObject>("LocalAsset");
  232. text.text = "正在加载配置";
  233. while (!abr.isDone)
  234. {
  235. text2.text = (abr.progress * 100).ToString("F2") + "%";
  236. slider.value = float.Parse((abr.progress ).ToString("F2"));
  237. yield return null;
  238. }
  239. copyGameObject(abr.asset);
  240. this.gameObject.SetActive(false);
  241. string fileName = HotUpdateAssets;
  242. if (!Directory.Exists(Application.persistentDataPath + "/HotUpdate"))
  243. Directory.CreateDirectory(Application.persistentDataPath + "/HotUpdate");
  244. string filePathname = Application.persistentDataPath + "/HotUpdate/" + fileName;
  245. // if (File.Exists(filePathname))
  246. // File.Delete(filePathname);
  247. File.WriteAllBytes(filePathname, www.downloadHandler.data);
  248. PlayerPrefs.SetString(HotUpdateAssets, filePathname);
  249. }
  250. }
  251. }
  252. void copyGameObject(UnityEngine.Object o)
  253. {
  254. Instantiate(o);
  255. }
  256. private static Assembly _hotUpdateAss;
  257. /// <summary>
  258. /// 为aot assembly加载原始metadata, 这个代码放aot或者热更新都行。
  259. /// 一旦加载后,如果AOT泛型函数对应native实现不存在,则自动替换为解释模式执行
  260. /// </summary>
  261. private static void LoadMetadataForAOTAssemblies()
  262. {
  263. /// 注意,补充元数据是给AOT dll补充元数据,而不是给热更新dll补充元数据。
  264. /// 热更新dll不缺元数据,不需要补充,如果调用LoadMetadataForAOTAssembly会返回错误
  265. ///
  266. HomologousImageMode mode = HomologousImageMode.SuperSet;
  267. foreach (var aotDllName in AOTMetaAssemblyFiles)
  268. {
  269. byte[] dllBytes = ReadBytesFromStreamingAssets(aotDllName);
  270. // 加载assembly对应的dll,会自动为它hook。一旦aot泛型函数的native函数不存在,用解释器版本代码
  271. LoadImageErrorCode err = RuntimeApi.LoadMetadataForAOTAssembly(dllBytes, mode);
  272. Debug.Log($"LoadMetadataForAOTAssembly:{aotDllName}. mode:{mode} ret:{err}");
  273. }
  274. }
  275. void StartGame()
  276. {
  277. // LoadMetadataForAOTAssemblies();
  278. /*
  279. #if !UNITY_EDITOR
  280. _hotUpdateAss = Assembly.Load(ReadBytesFromStreamingAssets("HotUpdate.dll.bytes"));
  281. #else
  282. _hotUpdateAss = System.AppDomain.CurrentDomain.GetAssemblies().First(a => a.GetName().Name == "HotUpdate");
  283. #endif
  284. */
  285. // Type entryType = _hotUpdateAss.GetType("Entry");
  286. // entryType.GetMethod("Start").Invoke(null, null);
  287. }
  288. }