BuildTask.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using GFGEditor;
  5. using UnityEditor;
  6. using UnityEngine;
  7. using GFGGame;
  8. namespace VEngine.Editor.Builds
  9. {
  10. public class BuildTask
  11. {
  12. private readonly string[] EXCLUDE_EXTS = new string[] { ".meta" };
  13. private readonly string[] EXCLUDE_DIRS = new string[] { "Assets/Res/.svn", ImportArtResTool.Md5FilePath };
  14. private readonly BuildAssetBundleOptions buildAssetBundleOptions;
  15. private readonly List<Asset> bundledAssets = new List<Asset>();
  16. private readonly string bundleExtension;
  17. public readonly string name;
  18. private readonly Dictionary<string, Asset> pathWithAssets = new Dictionary<string, Asset>();
  19. public BuildTask()
  20. {
  21. name = nameof(Manifest);
  22. buildAssetBundleOptions = BuildAssetBundleOptions.ChunkBasedCompression |
  23. BuildAssetBundleOptions.AppendHashToAssetBundleName;
  24. bundleExtension = ".unity3d";
  25. }
  26. public Record record { get; private set; }
  27. private static string GetRecordsPath(string buildName)
  28. {
  29. return Settings.GetBuildPath($"build_records_for_{buildName}.json");
  30. }
  31. private static void WriteRecord(Record record)
  32. {
  33. var records = GetRecords(record.build);
  34. records.data.Insert(0, record);
  35. File.WriteAllText(GetRecordsPath(record.build), JsonUtility.ToJson(records));
  36. }
  37. private static Records GetRecords(string build)
  38. {
  39. var records = ScriptableObject.CreateInstance<Records>();
  40. var path = GetRecordsPath(build);
  41. if (File.Exists(path)) JsonUtility.FromJsonOverwrite(File.ReadAllText(path), records);
  42. return records;
  43. }
  44. private static void DisplayProgressBar(string title, string content, int index, int max)
  45. {
  46. EditorUtility.DisplayProgressBar($"{title}({index}/{max}) ", content,
  47. index * 1f / max);
  48. }
  49. public void BuildBundles()
  50. {
  51. var assetBundleNames = AssetDatabase.GetAllAssetBundleNames();
  52. for (var i = 0; i < assetBundleNames.Length; i++)
  53. {
  54. var assetBundleName = assetBundleNames[i];
  55. DisplayProgressBar("采集资源", assetBundleName, i, assetBundleNames.Length);
  56. var assetNames = AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleName);
  57. bundledAssets.AddRange(Array.ConvertAll(assetNames, input => new Asset
  58. {
  59. path = input,
  60. bundle = assetBundleName
  61. }));
  62. }
  63. CheckAssets();
  64. EditorUtility.ClearProgressBar();
  65. FinishBuild();
  66. }
  67. public void BuildCustomBundles(string[] resRootDirNames, string setName)
  68. {
  69. DllHelper.BuildDll(LauncherConfig.DllDirHotfix, EditorUserBuildSettings.activeBuildTarget);
  70. DllHelper.CopyAOTDll(LauncherConfig.DllDirAOT, EditorUserBuildSettings.activeBuildTarget);
  71. foreach (var resRootDirName in resRootDirNames)
  72. {
  73. CreateBundles(resRootDirName, setName);
  74. }
  75. CheckAssets();
  76. EditorUtility.ClearProgressBar();
  77. FinishBuild();
  78. }
  79. private void CreateBundles(string resRootDirName, string setName)
  80. {
  81. var path = Path.Combine(Application.dataPath, resRootDirName);
  82. var buildSetting = GFGEditor.BuildSetting.GetBuildSetting(setName);
  83. var dirBundleList = buildSetting.dirBundleList;
  84. var excludeDirs = buildSetting.dirBundleList.GetRange(0, buildSetting.dirBundleList.Count);
  85. excludeDirs.AddRange(EXCLUDE_DIRS);
  86. GFGEditor.FileUtil.ForeachFileInDir(path, excludeDirs, (string file) =>
  87. {
  88. var ext = Path.GetExtension(file);
  89. if (Array.IndexOf(EXCLUDE_EXTS, ext) < 0)
  90. {
  91. file = file.Replace('\\', '/');
  92. string curDir = Environment.CurrentDirectory.Replace("\\", "/");
  93. string filePath = file.Replace(curDir + "/", "");
  94. EditorUtility.DisplayProgressBar("采集资源", filePath, 1f);
  95. var bundle = filePath.Replace($"Assets/{resRootDirName}/", "");
  96. bundle = bundle.Replace('/', '_');
  97. var i = bundle.IndexOf(".");
  98. bundle = bundle.Substring(0, i);
  99. bundle = bundle.ToLower();
  100. //以文件名标识分组
  101. for (int j = 0; j < buildSetting.dirTypeList.Count; j++)
  102. {
  103. string str = buildSetting.dirTypeList[j];
  104. if (bundle.IndexOf(str) >= 0)
  105. {
  106. bundle = str.Substring(0, str.Length - 1);
  107. break;
  108. }
  109. }
  110. bundledAssets.Add(new Asset
  111. {
  112. path = filePath,
  113. bundle = bundle
  114. });
  115. }
  116. });
  117. //以子文件夹为单位分组
  118. foreach (var dir in dirBundleList)
  119. {
  120. var dirPath = Path.Combine(Environment.CurrentDirectory, dir);
  121. if (!GFGEditor.FileUtil.CheckPathInParent(dirPath, path))
  122. {
  123. continue;
  124. }
  125. GFGEditor.FileUtil.ForeachDirInDir(dirPath, (string subDirPath) =>
  126. {
  127. var targetDirPath = subDirPath.Replace('\\', '/');
  128. string curDirPath = Environment.CurrentDirectory.Replace("\\", "/");
  129. string subDir = targetDirPath.Replace(curDirPath + "/", "");
  130. var bundle = subDir.Replace($"Assets/{resRootDirName}/", "");
  131. bundle = bundle.Replace('/', '_');
  132. bundle = bundle.ToLower();
  133. GFGEditor.FileUtil.ForeachFileInDir(subDirPath, null, (string file) =>
  134. {
  135. var ext = Path.GetExtension(file);
  136. file = file.Replace('\\', '/');
  137. string curDir = Environment.CurrentDirectory.Replace("\\", "/");
  138. string filePath = file.Replace(curDir + "/", "");
  139. EditorUtility.DisplayProgressBar("采集资源", filePath, 1f);
  140. bundledAssets.Add(new Asset
  141. {
  142. path = filePath,
  143. bundle = bundle
  144. });
  145. });
  146. });
  147. }
  148. }
  149. private void CheckAssets()
  150. {
  151. for (var i = 0; i < bundledAssets.Count; i++)
  152. {
  153. var asset = bundledAssets[i];
  154. //去重
  155. if (!pathWithAssets.TryGetValue(asset.path, out var ba))
  156. {
  157. pathWithAssets[asset.path] = asset;
  158. }
  159. else
  160. {
  161. bundledAssets.RemoveAt(i);
  162. i--;
  163. Debug.LogWarningFormat("{0} can't pack with {1}, because already pack to {2}", asset.path,
  164. asset.bundle, ba.bundle);
  165. }
  166. }
  167. }
  168. private void FinishBuild()
  169. {
  170. var bundles = new List<ManifestBundle>();
  171. var dictionary = new Dictionary<string, List<string>>();
  172. //分组
  173. foreach (var asset in bundledAssets)
  174. {
  175. if (!dictionary.TryGetValue(asset.bundle, out var assets))
  176. {
  177. assets = new List<string>();
  178. dictionary.Add(asset.bundle, assets);
  179. bundles.Add(new ManifestBundle
  180. {
  181. name = asset.bundle,
  182. assets = assets
  183. });
  184. }
  185. assets.Add(asset.path);
  186. }
  187. var unityBuildPath = Settings.PlatformBuildPath;
  188. if (!string.IsNullOrEmpty(GFGGame.LauncherConfig.resKey))
  189. {
  190. unityBuildPath = Settings.UnityBuildPath;
  191. }
  192. if (bundles.Count <= 0) return;
  193. var manifest = BuildPipeline.BuildAssetBundles(unityBuildPath, bundles.ConvertAll(bundle =>
  194. new AssetBundleBuild
  195. {
  196. assetNames = bundle.assets.ToArray(),
  197. assetBundleName = bundle.name
  198. }).ToArray(),
  199. buildAssetBundleOptions | BuildAssetBundleOptions.AppendHashToAssetBundleName,
  200. EditorUserBuildSettings.activeBuildTarget);
  201. if (manifest == null)
  202. {
  203. Debug.LogErrorFormat("Failed to build {0}.", name);
  204. return;
  205. }
  206. //if (!string.IsNullOrEmpty(GFGGame.LauncherConfig.resKey))
  207. //{
  208. // string buildPath = Settings.PlatformBuildPath;
  209. // CreateEncryptAssets(unityBuildPath, buildPath, manifest, GFGGame.LauncherConfig.resKey);
  210. //}
  211. AfterBuildBundles(bundles, manifest);
  212. }
  213. /// <summary>
  214. /// 创建加密的AssetBundle
  215. /// </summary>
  216. //public static void CreateEncryptAssets(string bundlePackagePath, string encryptAssetPath, AssetBundleManifest manifest, string secretKey)
  217. //{
  218. // if (!Directory.Exists(encryptAssetPath))
  219. // {
  220. // Directory.CreateDirectory(encryptAssetPath);
  221. // }
  222. // string[] assetBundles = manifest.GetAllAssetBundles();
  223. // foreach (string assetBundle in assetBundles)
  224. // {
  225. // string bundlePath = Path.Combine(bundlePackagePath, assetBundle);
  226. // byte[] encryptBytes = EncryptHelper.CreateEncryptData(bundlePath, secretKey);
  227. // using (FileStream fs = new FileStream(Path.Combine(encryptAssetPath, assetBundle), FileMode.OpenOrCreate))
  228. // {
  229. // fs.SetLength(0);
  230. // fs.Write(encryptBytes, 0, encryptBytes.Length);
  231. // }
  232. // }
  233. //}
  234. /// <summary>
  235. /// 创建加密的AssetBundle
  236. /// </summary>
  237. public static void CreateEncryptAsset(string unityBundlesPath, string bundlesPath, string unityBundle, string secretKey)
  238. {
  239. if (!Directory.Exists(bundlesPath))
  240. {
  241. Directory.CreateDirectory(bundlesPath);
  242. }
  243. string unityBundlePath = Path.Combine(unityBundlesPath, unityBundle);
  244. byte[] encryptBytes = EncryptHelper.CreateEncryptData(unityBundlePath, secretKey);
  245. using (FileStream fs = new FileStream(Path.Combine(bundlesPath, unityBundle), FileMode.OpenOrCreate))
  246. {
  247. fs.SetLength(0);
  248. fs.Write(encryptBytes, 0, encryptBytes.Length);
  249. }
  250. }
  251. private string GetOriginBundle(string assetBundle)
  252. {
  253. var pos = assetBundle.LastIndexOf("_", StringComparison.Ordinal) + 1;
  254. var hash = assetBundle.Substring(pos);
  255. if (!string.IsNullOrEmpty(bundleExtension)) hash = hash.Replace(bundleExtension, "");
  256. var originBundle = $"{assetBundle.Replace("_" + hash, "")}";
  257. return originBundle;
  258. }
  259. private void AfterBuildBundles(List<ManifestBundle> bundles,
  260. AssetBundleManifest manifest)
  261. {
  262. var nameWithBundles = new Dictionary<string, ManifestBundle>();
  263. for (var i = 0; i < bundles.Count; i++)
  264. {
  265. var bundle = bundles[i];
  266. bundle.id = i;
  267. nameWithBundles[bundle.name] = bundle;
  268. }
  269. if (manifest != null)
  270. {
  271. var assetBundles = manifest.GetAllAssetBundles();
  272. foreach (var assetBundle in assetBundles)
  273. {
  274. var originBundle = GetOriginBundle(assetBundle);
  275. var dependencies = Array.ConvertAll(manifest.GetAllDependencies(assetBundle), GetOriginBundle);
  276. if (nameWithBundles.TryGetValue(originBundle, out var manifestBundle))
  277. {
  278. manifestBundle.nameWithAppendHash = assetBundle;
  279. manifestBundle.dependencies = Array.ConvertAll(dependencies, input => nameWithBundles[input].id);
  280. }
  281. else
  282. {
  283. Debug.LogErrorFormat("Bundle not exist: {0}", originBundle);
  284. }
  285. }
  286. }
  287. CreateManifest(bundles);
  288. }
  289. private void CreateManifest(List<ManifestBundle> bundles)
  290. {
  291. var manifest = Settings.GetManifest();
  292. manifest.version++;
  293. manifest.appVersion = UnityEditor.PlayerSettings.bundleVersion;
  294. var getBundles = manifest.GetBundles();
  295. var newFiles = new List<string>();
  296. var newSize = 0L;
  297. foreach (var bundle in bundles)
  298. {
  299. if (!getBundles.TryGetValue(bundle.name, out var value) ||
  300. value.nameWithAppendHash != bundle.nameWithAppendHash)
  301. {
  302. newFiles.Add(bundle.nameWithAppendHash);
  303. if (!string.IsNullOrEmpty(GFGGame.LauncherConfig.resKey))
  304. {
  305. string buildPath = Settings.PlatformBuildPath;
  306. CreateEncryptAsset(Settings.UnityBuildPath, buildPath, bundle.nameWithAppendHash, GFGGame.LauncherConfig.resKey);
  307. }
  308. }
  309. var file = Settings.GetBuildPath(bundle.nameWithAppendHash);
  310. if (File.Exists(file))
  311. using (var stream = File.OpenRead(file))
  312. {
  313. bundle.size = stream.Length;
  314. bundle.crc = Utility.ComputeCRC32(stream);
  315. }
  316. else
  317. Debug.LogErrorFormat("File not found: {0}", file);
  318. newSize += bundle.size;
  319. }
  320. manifest.bundles = bundles;
  321. var newFilesSize = Utility.FormatBytes(newSize);
  322. newFiles.AddRange(WriteManifest(manifest));
  323. // write upload files
  324. var filename = Settings.GetBuildPath($"upload_files_for_{manifest.name}_{manifest.version}.txt");
  325. File.WriteAllText(filename, string.Join("\n", newFiles.ToArray()));
  326. record = new Record
  327. {
  328. build = name,
  329. version = manifest.version,
  330. files = newFiles,
  331. size = newSize,
  332. time = DateTime.Now.ToFileTime()
  333. };
  334. WriteRecord(record);
  335. Debug.LogFormat("Build bundles with {0}({1}) files with version {2} for {3}.", newFiles.Count, newFilesSize,
  336. manifest.version, manifest.name);
  337. }
  338. private static IEnumerable<string> WriteManifest(Manifest manifest)
  339. {
  340. var newFiles = new List<string>();
  341. var filename = $"{manifest.name}";
  342. var version = manifest.version;
  343. WriteJson(manifest, filename, newFiles);
  344. var path = Settings.GetBuildPath(filename);
  345. var crc = Utility.ComputeCRC32(path);
  346. var info = new FileInfo(path);
  347. WriteJson(manifest, $"{filename}_v{version}_{crc}", newFiles);
  348. // for version file
  349. var manifestVersion = ScriptableObject.CreateInstance<ManifestVersion>();
  350. manifestVersion.crc = crc;
  351. manifestVersion.size = info.Length;
  352. manifestVersion.version = version;
  353. manifestVersion.appVersion = manifest.appVersion;
  354. WriteJson(manifestVersion, Manifest.GetVersionFile(filename), newFiles);
  355. WriteJson(manifestVersion, $"{filename}_v{version}_{crc}.version", newFiles);
  356. return newFiles;
  357. }
  358. private static void WriteJson(ScriptableObject so, string file, List<string> newFiles)
  359. {
  360. newFiles.Add(file);
  361. var json = JsonUtility.ToJson(so);
  362. File.WriteAllText(Settings.GetBuildPath(file), json);
  363. }
  364. }
  365. }