LoadDll.cs 11 KB

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