GameLoadDll.cs 20 KB

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