BuildTask.cs 14 KB

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