LoadDll.cs 11 KB

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