GameLoadDll.cs 19 KB

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