GameLoadDll.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Http;
  8. using System.Threading.Tasks;
  9. using hirdParty.DownloadSystem;
  10. using HybridCLR;
  11. using ThirdParty;
  12. using ThirdParty.DownloadSystem;
  13. using UnityEditor;
  14. using UnityEngine;
  15. public class GameLoadDll
  16. {
  17. private bool _isHadNetwork;
  18. private bool _hadEnterGame;
  19. private float _per;
  20. private float _currentProgress;
  21. private bool _isMarkClose;
  22. private readonly Dictionary<string, byte[]> _assetBytes = new Dictionary<string, byte[]>();
  23. string versionName = "versionInfo.txt";
  24. private System.Action callBack;
  25. private AssetMD5Info remoteMD5Info;
  26. private GameStartUIPanel _downloadUI;
  27. private string[] localVersionInfo;
  28. private GameStart gameStart;
  29. public void StartLoadDll(GameStart gameStart, string url, System.Action callBack)
  30. {
  31. this.gameStart = gameStart;
  32. // _downloadUI = HotSyncContent.DownloadUI;
  33. _downloadUI.SetMassge("开始校验脚本");
  34. this.callBack = callBack;
  35. if (HotSyncContent.isOpenHotFix)
  36. {
  37. if (HotSyncContent.isOpenDllStreamingLoad)
  38. {
  39. LoadStreamingDllLoad();
  40. }
  41. else
  42. {
  43. LoadBenDiVersion();
  44. }
  45. }
  46. }
  47. private void LoadStreamingDllLoad()
  48. {
  49. string DllMD5 = HotSyncContent.GetDllWebRequestPath("DllMD5.txt");
  50. DownloadFileData versiondownloadFileData = new DownloadFileData();
  51. versiondownloadFileData.remoteUrl = DllMD5;
  52. DownloadHander downloadHander = FileDownloadSystem.Instance.DownloadFile(versiondownloadFileData);
  53. downloadHander.OnFinishCallBack = delegate(DownloadHander hander)
  54. {
  55. remoteMD5Info =
  56. JsonUtility.FromJson(hander.Text, typeof(AssetMD5Info)) as AssetMD5Info;
  57. LoadLoaclDll();
  58. };
  59. }
  60. private byte[] GetAssetBytes(string dllName)
  61. {
  62. if (_assetBytes.ContainsKey(dllName))
  63. {
  64. return _assetBytes[dllName];
  65. }
  66. else
  67. {
  68. Debug.Log("没有找到dll数据" + dllName);
  69. return new byte[] { };
  70. }
  71. }
  72. // private void LoadVersion()
  73. // {
  74. // string md5Name = "DllMD5.txt";
  75. // string versionInfoUrl = ($"{HotSyncContent.AssetURL}/{HotSyncContent.platform}/{versionName}");
  76. // DownloadFileData versiondownloadFileData = new DownloadFileData();
  77. // versiondownloadFileData.remoteUrl = versionInfoUrl;
  78. // DownloadHander downloadHander = FileDownloadSystem.Instance.DownloadFile(versiondownloadFileData);
  79. // downloadHander.OnFinishCallBack = delegate(DownloadHander hander)
  80. // {
  81. // string[] remoteVersionInfo = hander.Text.Split('\n');
  82. // string versionInfo =
  83. // $"{remoteVersionInfo[0].Split('=')[1]}.{remoteVersionInfo[1].Split('=')[1]}.{remoteVersionInfo[2].Split('=')[1]}";
  84. // HotSyncContent.Currversion = versionInfo;
  85. // if (localVersionInfo[0]!=remoteVersionInfo[0])
  86. // {
  87. // // 本地版本和远程一致也需要更新,防止散文件错误
  88. // Debug.Log("本地版本更大,不需要更新");
  89. // }
  90. // else
  91. // {
  92. // LoadMD5();
  93. // }
  94. // };
  95. // }
  96. private void LoadBenDiVersion()
  97. {
  98. string versionInfoUrl = HotSyncContent.GetWebRequestPath(versionName);
  99. DownloadFileData versiondownloadFileData = new DownloadFileData();
  100. versiondownloadFileData.remoteUrl = versionInfoUrl;
  101. DownloadHander downloadHander = FileDownloadSystem.Instance.DownloadFile(versiondownloadFileData);
  102. downloadHander.OnFinishCallBack = delegate(DownloadHander hander)
  103. {
  104. localVersionInfo = hander.Text.Split('\n');
  105. GetAssetUrl();
  106. };
  107. }
  108. private async void GetAssetUrl()
  109. {
  110. #if UNITY_EDITOR || UNITY_STANDALONE_WIN
  111. string appSettingPath = "file://" + Application.streamingAssetsPath + "/AppSetting.txt";
  112. #elif UNITY_ANDROID
  113. string appSettingPath = Application.streamingAssetsPath + "/AppSetting.txt";
  114. #elif UNITY_IPHONE
  115. string appSettingPath = "file://"+ Application.streamingAssetsPath+"/AppSetting.txt";
  116. #endif
  117. WWW loader = new WWW(appSettingPath);
  118. while (!loader.isDone)
  119. {
  120. }
  121. if (!string.IsNullOrEmpty(loader.error))
  122. {
  123. Debug.LogError(appSettingPath);
  124. Debug.LogError(loader.error);
  125. }
  126. string url = "";
  127. string settingData = loader.text;
  128. string[] datas = settingData.Split('\n');
  129. for (int i = 0; i < datas.Length; i++)
  130. {
  131. datas[i] = datas[i].Replace("\r", "");
  132. string[] configInfo = datas[i].Split('=');
  133. if (configInfo[0].Contains("//") || configInfo.Length <= 1)
  134. {
  135. continue;
  136. }
  137. if (configInfo[0].Equals("loginServer"))
  138. {
  139. url = configInfo[1];
  140. }
  141. }
  142. url += "/client_config";
  143. LoadAsset(url, localVersionInfo[0].Split('=')[1]);
  144. }
  145. private async Task LoadAsset(string url, string v)
  146. {
  147. var replace = v.Replace("\r", "");
  148. _downloadUI.SetMassge($"等待服务器地址");
  149. Debug.Log("等待下载资源服地址" + url);
  150. Dictionary<string, string> dictionary = new Dictionary<string, string>();
  151. dictionary.Add("buildVer", replace);
  152. FormUrlEncodedContent formUrlEncodedContent = new FormUrlEncodedContent(dictionary);
  153. HttpClient httpClient = new HttpClient();
  154. httpClient.Timeout = TimeSpan.FromSeconds(5);
  155. string json = "";
  156. try
  157. {
  158. HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(url, formUrlEncodedContent);
  159. if (httpResponseMessage.StatusCode != HttpStatusCode.OK)
  160. {
  161. Debug.LogError(httpResponseMessage.RequestMessage);
  162. _downloadUI.SetMassge($"获取配置错误,正在在重新获取!");
  163. LoadAsset(url, v);
  164. return;
  165. }
  166. json = await httpResponseMessage.Content.ReadAsStringAsync();
  167. }
  168. catch (Exception e)
  169. {
  170. Debug.LogError(e);
  171. LoadAsset(url, v);
  172. return;
  173. }
  174. httpClient.Dispose();
  175. Debug.Log(json);
  176. _downloadUI.SetMassge($"地址获取成功");
  177. // UnityWebRequest webRequest = UnityWebRequest.Post(url, dictionary);
  178. // webRequest.timeout = 5;
  179. // UnityWebRequestAsyncOperation unityWebRequestAsyncOperation = webRequest.SendWebRequest();
  180. // while (!unityWebRequestAsyncOperation.isDone)
  181. // {
  182. // yield return 0;
  183. // }
  184. // if (!string.IsNullOrEmpty(webRequest.error))
  185. // {
  186. // Debug.LogError(webRequest.error);
  187. // _downloadUI.SetMassge($"获取配置错误,正在在重新获取!");
  188. // gameStart.StartCoroutine(LoadAsset(url, v));
  189. // }
  190. // string json = webRequest.downloadHandler.text;
  191. AssetUrlInfo assetUrlInfo = JsonUtility.FromJson<AssetUrlInfo>(json);
  192. HotSyncContent.AssetURL = assetUrlInfo.assetsUrl;
  193. // webRequest.Dispose();
  194. //HotSyncContent.AssetURL = "http://42.192.110.229/010";
  195. HotSyncContent.loadType = assetUrlInfo.loadType;
  196. HotSyncContent.assetsVer = assetUrlInfo.assetsVer;
  197. HotSyncContent.Currversion = $"{assetUrlInfo.apkVer}.{assetUrlInfo.buildVer}.{assetUrlInfo.assetsVer}";
  198. Debug.Log("版本号:" + HotSyncContent.Currversion);
  199. Debug.Log(HotSyncContent.Currversion + "获得的下载资源服地址" + HotSyncContent.AssetURL);
  200. if (localVersionInfo[0].Split('=')[1] != assetUrlInfo.apkVer.ToString())
  201. {
  202. Debug.Log("版本号:" + HotSyncContent.Currversion);
  203. Debug.Log(HotSyncContent.Currversion + "获得的下载资源服地址" + HotSyncContent.AssetURL);
  204. if (localVersionInfo[0].Split('=')[1] != assetUrlInfo.apkVer.ToString())
  205. {
  206. // 本地版本和远程一致也需要更新,防止散文件错误
  207. Debug.LogError("本地版本更大,不需要更新");
  208. }
  209. else
  210. {
  211. LoadMD5();
  212. }
  213. }
  214. else
  215. {
  216. LoadMD5();
  217. }
  218. // LoadVersion();
  219. // Debug.Log(assetUrlInfo.assetsUrl);
  220. }
  221. private void LoadBenDiVersion(string[] remoteVersionInfo)
  222. {
  223. string versionInfoUrl = HotSyncContent.GetWebRequestPath(versionName);
  224. DownloadFileData versiondownloadFileData = new DownloadFileData();
  225. versiondownloadFileData.remoteUrl = versionInfoUrl;
  226. DownloadHander downloadHander = FileDownloadSystem.Instance.DownloadFile(versiondownloadFileData);
  227. downloadHander.OnFinishCallBack = delegate(DownloadHander hander) { };
  228. }
  229. private void LoadMD5()
  230. {
  231. _downloadUI.SetMassge($"资源检查中");
  232. string md5Url =
  233. $"{HotSyncContent.AssetURL}/{HotSyncContent.platform}/{HotSyncContent.Currversion}/DLL/DllMD5.txt";
  234. DownloadFileData versiondownloadFileData = new DownloadFileData();
  235. versiondownloadFileData.remoteUrl = md5Url;
  236. versiondownloadFileData.maxCount = int.MaxValue;
  237. versiondownloadFileData.timeOut = 10;
  238. DownloadHander downloadHander = FileDownloadSystem.Instance.DownloadFile(versiondownloadFileData);
  239. downloadHander.OnFinishCallBack = delegate(DownloadHander hander)
  240. {
  241. remoteMD5Info =
  242. JsonUtility.FromJson(hander.Text, typeof(AssetMD5Info)) as AssetMD5Info;
  243. if (HotSyncContent.loadType == 1)
  244. {
  245. LoadLoaclDll();
  246. }
  247. else
  248. {
  249. JianYan();
  250. }
  251. };
  252. }
  253. private void JianYan()
  254. {
  255. List<MD5FileInfo> CheckFile = new List<MD5FileInfo>();
  256. CheckFile.AddRange(remoteMD5Info.fileInfo);
  257. string rootPath = HotSyncContent.AppHotfixResPath;
  258. CheckFilePool _checkFileThrans = new CheckFilePool();
  259. _checkFileThrans.isStreamingAssetsPath = true;
  260. _checkFileThrans.streamingAssetsPath = HotSyncContent.RootStreamingURL + "/Dll/";
  261. SliderData sliderData = new SliderData();
  262. sliderData.maxValue = CheckFile.Count;
  263. _downloadUI.SetMassge($"校验本地文件");
  264. sliderData.CcurrValue = delegate
  265. {
  266. float m = _checkFileThrans.FileCount();
  267. if (_checkFileThrans.isFinish)
  268. {
  269. // _downloadUI.ClearSlider();
  270. if (_checkFileThrans.shiBaiFile != null && _checkFileThrans.shiBaiFile.Count > 0)
  271. {
  272. DownJiaoBen(_checkFileThrans.shiBaiFile);
  273. }
  274. else
  275. {
  276. LoadLoaclDll();
  277. }
  278. }
  279. else
  280. {
  281. _downloadUI.SetMassge(
  282. $"校验本地文件{m} / {sliderData.maxValue}");
  283. }
  284. return m;
  285. };
  286. // _downloadUI.SetSlider(sliderData);
  287. _checkFileThrans.Start(rootPath, CheckFile);
  288. }
  289. private void DownJiaoBen(List<MD5FileInfo> updateFlieInfo)
  290. {
  291. DownLoadHanderGroup downLoadHanderGroup = new DownLoadHanderGroup();
  292. long size = 0;
  293. for (int i = 0; i < updateFlieInfo.Count; i++)
  294. {
  295. MD5FileInfo md5FileInfo = updateFlieInfo[i];
  296. if (md5FileInfo.size <= 0)
  297. {
  298. continue;
  299. }
  300. DownloadFileData downloadFileData = new DownloadFileData();
  301. size += md5FileInfo.size;
  302. downloadFileData.remoteUrl =
  303. $"{HotSyncContent.AssetURL}/{HotSyncContent.platform}/{HotSyncContent.Currversion}/DLL/{md5FileInfo.fileName}";
  304. Debug.Log("下载文件" + downloadFileData.remoteUrl);
  305. downloadFileData.localPath = Path.Combine(HotSyncContent.AppHotfixResPath, md5FileInfo.fileName);
  306. DownloadHander fileDow = FileDownloadSystem.Instance.DownloadFile(downloadFileData);
  307. downLoadHanderGroup.AddHander(fileDow);
  308. }
  309. float sizeM = size / 1024f / 1024f;
  310. SliderData sliderData = new SliderData();
  311. sliderData.maxValue = size;
  312. _downloadUI.SetMassge($"开始下载文件,个数{updateFlieInfo.Count} 大小{sizeM}");
  313. sliderData.CcurrValue = delegate
  314. {
  315. float m = downLoadHanderGroup.size / 1024f / 1024f;
  316. float speed = downLoadHanderGroup.speed / 1024f;
  317. _downloadUI.SetMassge(
  318. $"开始下载文件,个数{updateFlieInfo.Count} 大小{m.ToString("0.00")}M / {sizeM.ToString("0.00")}M 速度{speed.ToString(".00")} Kb");
  319. return downLoadHanderGroup.size;
  320. };
  321. // _downloadUI.SetSlider(sliderData);
  322. downLoadHanderGroup.OnCallBack = JianYan;
  323. downLoadHanderGroup.StartUpdate();
  324. }
  325. private void LoadLoaclDll()
  326. {
  327. DownLoadHanderGroup downLoadHanderGroup = new DownLoadHanderGroup();
  328. for (int i = 0; i < remoteMD5Info.fileInfo.Count; i++)
  329. {
  330. MD5FileInfo md5FileInfo = remoteMD5Info.fileInfo[i];
  331. DownloadFileData downloadFileData = new DownloadFileData();
  332. downloadFileData.remoteUrl = HotSyncContent.GetDllWebRequestPath(md5FileInfo.fileName);
  333. Debug.Log("下载文件" + downloadFileData.remoteUrl);
  334. DownloadHander fileDow = FileDownloadSystem.Instance.DownloadFile(downloadFileData);
  335. fileDow.OnFinishCallBack = delegate(DownloadHander hander)
  336. {
  337. byte[] dllBytes = hander.Data;
  338. // dllBytes = DllTool.Instance.KeyDecryption(dllBytes);
  339. _assetBytes[md5FileInfo.fileName] = dllBytes;
  340. Debug.Log($"资源:{md5FileInfo.fileName} 大小:{dllBytes.Length}");
  341. HomologousImageMode mode = HomologousImageMode.SuperSet;
  342. // 加载Assembly对应的Dll,会自动为它hook。一旦AOT泛型函数的Native函数不存在,用解释器版本代码
  343. LoadImageErrorCode err = RuntimeApi.LoadMetadataForAOTAssembly(dllBytes, mode);
  344. Debug.Log($"LoadMetadataForAOTAssembly:{md5FileInfo.fileName}. mode:{mode} ret:{err}");
  345. };
  346. downLoadHanderGroup.AddHander(fileDow);
  347. }
  348. downLoadHanderGroup.OnCallBack = LoadDll;
  349. downLoadHanderGroup.StartUpdate();
  350. }
  351. private void LoadDll()
  352. {
  353. _downloadUI.SetMassge($"初始化资源中,请稍等");
  354. Debug.Log("开始Fort23.Proto");
  355. System.Reflection.Assembly.Load(GetAssetBytes("Fort23.Proto.dll.bytes"));
  356. // Debug.Log("开始FMODUnity");
  357. // System.Reflection.Assembly.Load(GetAssetBytes("FMODUnity.dll.bytes"));
  358. // Debug.Log("开始FMODUnityResonance");
  359. // System.Reflection.Assembly.Load(GetAssetBytes("FMODUnityResonance.dll.bytes"));
  360. Debug.Log("开始Fort23.Core");
  361. System.Reflection.Assembly.Load(GetAssetBytes("Fort23.Core.dll.bytes"));
  362. Debug.Log("开始BGMController");
  363. System.Reflection.Assembly.Load(GetAssetBytes("BGMController.dll.bytes"));
  364. Debug.Log("开始Fort23.GameData");
  365. System.Reflection.Assembly.Load(GetAssetBytes("Fort23.GameData.dll.bytes"));
  366. Debug.Log("开始spine-unity");
  367. System.Reflection.Assembly.Load(GetAssetBytes("spine-unity.dll.bytes"));
  368. Debug.Log("开始spine-timeline");
  369. System.Reflection.Assembly.Load(GetAssetBytes("spine-timeline.dll.bytes"));
  370. Debug.Log("开始Fort23.CombatCore");
  371. System.Reflection.Assembly.Load(GetAssetBytes("Fort23.CombatCore.dll.bytes"));
  372. Debug.Log("开始Fort23.UTool");
  373. System.Reflection.Assembly.Load(GetAssetBytes("Fort23.UTool.dll.bytes"));
  374. Debug.Log("开始Fort23.Combat");
  375. System.Reflection.Assembly.Load(GetAssetBytes("Fort23.Combat.dll.bytes"));
  376. Debug.Log("开始Fort23.Mono");
  377. System.Reflection.Assembly.Load(GetAssetBytes("Fort23.Mono.dll.bytes"));
  378. // Debug.Log("spine-unity");
  379. // System.Reflection.Assembly.Load(GetAssetBytes("spine-unity.dll"));
  380. // Debug.Log("spine-timeline");
  381. // System.Reflection.Assembly.Load(GetAssetBytes("spine-timeline.dll"));
  382. Debug.Log("开始Assembly-CSharp");
  383. System.Reflection.Assembly.Load(GetAssetBytes("Assembly-CSharp.dll.bytes"));
  384. AppDomain.CurrentDomain.GetAssemblies()
  385. .First(assembly => assembly.GetName().Name == "Assembly-CSharp");
  386. Debug.Log("Assembly-CSharp.dll加载成功");
  387. // 2. 开始执行热更新代码逻辑,加载Init进入游戏流程
  388. Debug.Log("开始加载进入游戏");
  389. string path = Application.persistentDataPath + "/Bundle/init";
  390. if (!File.Exists(path))
  391. {
  392. path = Application.streamingAssetsPath + "/Bundle/init";
  393. }
  394. Debug.Log("path=" + path);
  395. // string[] assemblyNames =
  396. // {
  397. // "Fort23.Core.dll", "Fort23.MonoCore.dll", "Fort23.Mono.dll", "Fort23.Model.dll",
  398. // "Fort23.CommonCore.dll", "Fort23.Common.dll", "Assembly-CSharp.dll", "Fort23.UTool.dll",
  399. // "Fort23.GameData.dll", "spine-unity.dll", "spine-timeline.dll", "BGMController.dll", "Fort23.Combat.dll",
  400. // "Fort23.CombatCore.dll"
  401. // };
  402. // int addCount = 0;
  403. // foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
  404. // {
  405. // string assemblyName = $"{assembly.GetName().Name}.dll";
  406. // if (!((IList) assemblyNames).Contains(assemblyName))
  407. // {
  408. // continue;
  409. // }
  410. // Debug.Log(assemblyName);
  411. // foreach (var type in assembly.GetTypes())
  412. // {
  413. //
  414. // if ((typeof(MonoBehaviour).IsAssignableFrom(type)))
  415. // {
  416. // Debug.Log(type.Name);
  417. // var go = new GameObject();
  418. // // 我们不希望挂载到这个GameObject上的脚本执行
  419. // go.SetActive(false);
  420. // go.AddComponent(type);
  421. // GameObject.Destroy(go);
  422. // addCount++;
  423. // }
  424. // }
  425. //
  426. // }
  427. callBack?.Invoke();
  428. }
  429. }