ResourceBuilderController.cs 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567
  1. //------------------------------------------------------------
  2. // Game Framework
  3. // Copyright © 2013-2021 loyalsoft. All rights reserved.
  4. // Homepage: http://www.game7000.com/
  5. // Feedback: http://www.game7000.com/
  6. //------------------------------------------------------------
  7. using GameFramework;
  8. using GameFramework.FileSystem;
  9. using GameFramework.Resource;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Xml;
  15. using UnityEditor;
  16. using UnityEngine;
  17. using UnityGameFramework.Runtime;
  18. namespace UnityGameFramework.Editor.ResourceTools
  19. {
  20. public sealed partial class ResourceBuilderController
  21. {
  22. private const string RemoteVersionListFileName = "GameFrameworkVersion.dat";
  23. private const string LocalVersionListFileName = "GameFrameworkList.dat";
  24. private const string DefaultExtension = "dat";
  25. private const string NoneOptionName = "<None>";
  26. private static readonly int AssetsStringLength = "Assets".Length;
  27. private readonly string m_ConfigurationPath;
  28. private readonly ResourceCollection m_ResourceCollection;
  29. private readonly ResourceAnalyzerController m_ResourceAnalyzerController;
  30. private readonly SortedDictionary<string, ResourceData> m_ResourceDatas;
  31. private readonly Dictionary<string, IFileSystem> m_OutputPackageFileSystems;
  32. private readonly Dictionary<string, IFileSystem> m_OutputPackedFileSystems;
  33. private readonly BuildReport m_BuildReport;
  34. private readonly List<string> m_CompressionHelperTypeNames;
  35. private readonly List<string> m_BuildEventHandlerTypeNames;
  36. private IBuildEventHandler m_BuildEventHandler;
  37. private IFileSystemManager m_FileSystemManager;
  38. public ResourceBuilderController()
  39. {
  40. m_ConfigurationPath = Type.GetConfigurationPath<ResourceBuilderConfigPathAttribute>() ?? Utility.Path.GetRegularPath(Path.Combine(Application.dataPath, "GameFramework/Configs/ResourceBuilder.xml"));
  41. m_ResourceCollection = new ResourceCollection();
  42. m_ResourceCollection.OnLoadingResource += delegate (int index, int count)
  43. {
  44. if (OnLoadingResource != null)
  45. {
  46. OnLoadingResource(index, count);
  47. }
  48. };
  49. m_ResourceCollection.OnLoadingAsset += delegate (int index, int count)
  50. {
  51. if (OnLoadingAsset != null)
  52. {
  53. OnLoadingAsset(index, count);
  54. }
  55. };
  56. m_ResourceCollection.OnLoadCompleted += delegate ()
  57. {
  58. if (OnLoadCompleted != null)
  59. {
  60. OnLoadCompleted();
  61. }
  62. };
  63. m_ResourceAnalyzerController = new ResourceAnalyzerController(m_ResourceCollection);
  64. m_ResourceAnalyzerController.OnAnalyzingAsset += delegate (int index, int count)
  65. {
  66. if (OnAnalyzingAsset != null)
  67. {
  68. OnAnalyzingAsset(index, count);
  69. }
  70. };
  71. m_ResourceAnalyzerController.OnAnalyzeCompleted += delegate ()
  72. {
  73. if (OnAnalyzeCompleted != null)
  74. {
  75. OnAnalyzeCompleted();
  76. }
  77. };
  78. m_ResourceDatas = new SortedDictionary<string, ResourceData>(StringComparer.Ordinal);
  79. m_OutputPackageFileSystems = new Dictionary<string, IFileSystem>(StringComparer.Ordinal);
  80. m_OutputPackedFileSystems = new Dictionary<string, IFileSystem>(StringComparer.Ordinal);
  81. m_BuildReport = new BuildReport();
  82. m_CompressionHelperTypeNames = new List<string>
  83. {
  84. NoneOptionName
  85. };
  86. m_BuildEventHandlerTypeNames = new List<string>
  87. {
  88. NoneOptionName
  89. };
  90. m_CompressionHelperTypeNames.AddRange(Type.GetRuntimeOrEditorTypeNames(typeof(Utility.Compression.ICompressionHelper)));
  91. m_BuildEventHandlerTypeNames.AddRange(Type.GetRuntimeOrEditorTypeNames(typeof(IBuildEventHandler)));
  92. m_BuildEventHandler = null;
  93. m_FileSystemManager = null;
  94. Platforms = Platform.Undefined;
  95. AssetBundleCompression = AssetBundleCompressionType.LZ4;
  96. CompressionHelperTypeName = string.Empty;
  97. AdditionalCompressionSelected = false;
  98. ForceRebuildAssetBundleSelected = false;
  99. BuildEventHandlerTypeName = string.Empty;
  100. OutputDirectory = string.Empty;
  101. OutputPackageSelected = OutputFullSelected = OutputPackedSelected = true;
  102. }
  103. public string ProductName
  104. {
  105. get
  106. {
  107. return PlayerSettings.productName;
  108. }
  109. }
  110. public string CompanyName
  111. {
  112. get
  113. {
  114. return PlayerSettings.companyName;
  115. }
  116. }
  117. public string GameIdentifier
  118. {
  119. get
  120. {
  121. #if UNITY_5_6_OR_NEWER
  122. return PlayerSettings.applicationIdentifier;
  123. #else
  124. return PlayerSettings.bundleIdentifier;
  125. #endif
  126. }
  127. }
  128. public string GameFrameworkVersion
  129. {
  130. get
  131. {
  132. return GameFramework.Version.GameFrameworkVersion;
  133. }
  134. }
  135. public string UnityVersion
  136. {
  137. get
  138. {
  139. return Application.unityVersion;
  140. }
  141. }
  142. public string ApplicableGameVersion
  143. {
  144. get
  145. {
  146. return Application.version;
  147. }
  148. }
  149. public int InternalResourceVersion
  150. {
  151. get;
  152. set;
  153. }
  154. public Platform Platforms
  155. {
  156. get;
  157. set;
  158. }
  159. public AssetBundleCompressionType AssetBundleCompression
  160. {
  161. get;
  162. set;
  163. }
  164. public string CompressionHelperTypeName
  165. {
  166. get;
  167. set;
  168. }
  169. public bool AdditionalCompressionSelected
  170. {
  171. get;
  172. set;
  173. }
  174. public bool ForceRebuildAssetBundleSelected
  175. {
  176. get;
  177. set;
  178. }
  179. public string BuildEventHandlerTypeName
  180. {
  181. get;
  182. set;
  183. }
  184. public string OutputDirectory
  185. {
  186. get;
  187. set;
  188. }
  189. public bool OutputPackageSelected
  190. {
  191. get;
  192. set;
  193. }
  194. public bool OutputFullSelected
  195. {
  196. get;
  197. set;
  198. }
  199. public bool OutputPackedSelected
  200. {
  201. get;
  202. set;
  203. }
  204. public bool IsValidOutputDirectory
  205. {
  206. get
  207. {
  208. if (string.IsNullOrEmpty(OutputDirectory))
  209. {
  210. return false;
  211. }
  212. if (!Directory.Exists(OutputDirectory))
  213. {
  214. return false;
  215. }
  216. return true;
  217. }
  218. }
  219. public string WorkingPath
  220. {
  221. get
  222. {
  223. if (!IsValidOutputDirectory)
  224. {
  225. return string.Empty;
  226. }
  227. return Utility.Path.GetRegularPath(new DirectoryInfo(Utility.Text.Format("{0}/Working/", OutputDirectory)).FullName);
  228. }
  229. }
  230. public string OutputPackagePath
  231. {
  232. get
  233. {
  234. if (!IsValidOutputDirectory)
  235. {
  236. return string.Empty;
  237. }
  238. return Utility.Path.GetRegularPath(new DirectoryInfo(Utility.Text.Format("{0}/Package/{1}_{2}/", OutputDirectory, ApplicableGameVersion.Replace('.', '_'), InternalResourceVersion.ToString())).FullName);
  239. }
  240. }
  241. public string OutputFullPath
  242. {
  243. get
  244. {
  245. if (!IsValidOutputDirectory)
  246. {
  247. return string.Empty;
  248. }
  249. return Utility.Path.GetRegularPath(new DirectoryInfo(Utility.Text.Format("{0}/Full/{1}_{2}/", OutputDirectory, ApplicableGameVersion.Replace('.', '_'), InternalResourceVersion.ToString())).FullName);
  250. }
  251. }
  252. public string OutputPackedPath
  253. {
  254. get
  255. {
  256. if (!IsValidOutputDirectory)
  257. {
  258. return string.Empty;
  259. }
  260. return Utility.Path.GetRegularPath(new DirectoryInfo(Utility.Text.Format("{0}/Packed/{1}_{2}/", OutputDirectory, ApplicableGameVersion.Replace('.', '_'), InternalResourceVersion.ToString())).FullName);
  261. }
  262. }
  263. public string BuildReportPath
  264. {
  265. get
  266. {
  267. if (!IsValidOutputDirectory)
  268. {
  269. return string.Empty;
  270. }
  271. return Utility.Path.GetRegularPath(new DirectoryInfo(Utility.Text.Format("{0}/BuildReport/{1}_{2}/", OutputDirectory, ApplicableGameVersion.Replace('.', '_'), InternalResourceVersion.ToString())).FullName);
  272. }
  273. }
  274. public event GameFrameworkAction<int, int> OnLoadingResource = null;
  275. public event GameFrameworkAction<int, int> OnLoadingAsset = null;
  276. public event GameFrameworkAction OnLoadCompleted = null;
  277. public event GameFrameworkAction<int, int> OnAnalyzingAsset = null;
  278. public event GameFrameworkAction OnAnalyzeCompleted = null;
  279. public event GameFrameworkFunc<string, float, bool> ProcessingAssetBundle = null;
  280. public event GameFrameworkFunc<string, float, bool> ProcessingBinary = null;
  281. public event GameFrameworkAction<Platform> ProcessResourceComplete = null;
  282. public event GameFrameworkAction<string> BuildResourceError = null;
  283. public bool Load()
  284. {
  285. if (!File.Exists(m_ConfigurationPath))
  286. {
  287. return false;
  288. }
  289. try
  290. {
  291. XmlDocument xmlDocument = new XmlDocument();
  292. xmlDocument.Load(m_ConfigurationPath);
  293. XmlNode xmlRoot = xmlDocument.SelectSingleNode("UnityGameFramework");
  294. XmlNode xmlEditor = xmlRoot.SelectSingleNode("ResourceBuilder");
  295. XmlNode xmlSettings = xmlEditor.SelectSingleNode("Settings");
  296. XmlNodeList xmlNodeList = null;
  297. XmlNode xmlNode = null;
  298. xmlNodeList = xmlSettings.ChildNodes;
  299. for (int i = 0; i < xmlNodeList.Count; i++)
  300. {
  301. xmlNode = xmlNodeList.Item(i);
  302. switch (xmlNode.Name)
  303. {
  304. case "InternalResourceVersion":
  305. InternalResourceVersion = int.Parse(xmlNode.InnerText) + 1;
  306. break;
  307. case "Platforms":
  308. Platforms = (Platform)int.Parse(xmlNode.InnerText);
  309. break;
  310. case "AssetBundleCompression":
  311. AssetBundleCompression = (AssetBundleCompressionType)byte.Parse(xmlNode.InnerText);
  312. break;
  313. case "CompressionHelperTypeName":
  314. CompressionHelperTypeName = xmlNode.InnerText;
  315. break;
  316. case "AdditionalCompressionSelected":
  317. AdditionalCompressionSelected = bool.Parse(xmlNode.InnerText);
  318. break;
  319. case "ForceRebuildAssetBundleSelected":
  320. ForceRebuildAssetBundleSelected = bool.Parse(xmlNode.InnerText);
  321. break;
  322. case "BuildEventHandlerTypeName":
  323. BuildEventHandlerTypeName = xmlNode.InnerText;
  324. break;
  325. case "OutputDirectory":
  326. OutputDirectory = xmlNode.InnerText;
  327. break;
  328. case "OutputPackageSelected":
  329. OutputPackageSelected = bool.Parse(xmlNode.InnerText);
  330. break;
  331. case "OutputFullSelected":
  332. OutputFullSelected = bool.Parse(xmlNode.InnerText);
  333. break;
  334. case "OutputPackedSelected":
  335. OutputPackedSelected = bool.Parse(xmlNode.InnerText);
  336. break;
  337. }
  338. }
  339. }
  340. catch
  341. {
  342. File.Delete(m_ConfigurationPath);
  343. return false;
  344. }
  345. return true;
  346. }
  347. public bool Save()
  348. {
  349. try
  350. {
  351. XmlDocument xmlDocument = new XmlDocument();
  352. xmlDocument.AppendChild(xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null));
  353. XmlElement xmlRoot = xmlDocument.CreateElement("UnityGameFramework");
  354. xmlDocument.AppendChild(xmlRoot);
  355. XmlElement xmlBuilder = xmlDocument.CreateElement("ResourceBuilder");
  356. xmlRoot.AppendChild(xmlBuilder);
  357. XmlElement xmlSettings = xmlDocument.CreateElement("Settings");
  358. xmlBuilder.AppendChild(xmlSettings);
  359. XmlElement xmlElement = null;
  360. xmlElement = xmlDocument.CreateElement("InternalResourceVersion");
  361. xmlElement.InnerText = InternalResourceVersion.ToString();
  362. xmlSettings.AppendChild(xmlElement);
  363. xmlElement = xmlDocument.CreateElement("Platforms");
  364. xmlElement.InnerText = ((int)Platforms).ToString();
  365. xmlSettings.AppendChild(xmlElement);
  366. xmlElement = xmlDocument.CreateElement("AssetBundleCompression");
  367. xmlElement.InnerText = ((byte)AssetBundleCompression).ToString();
  368. xmlSettings.AppendChild(xmlElement);
  369. xmlElement = xmlDocument.CreateElement("CompressionHelperTypeName");
  370. xmlElement.InnerText = CompressionHelperTypeName;
  371. xmlSettings.AppendChild(xmlElement);
  372. xmlElement = xmlDocument.CreateElement("AdditionalCompressionSelected");
  373. xmlElement.InnerText = AdditionalCompressionSelected.ToString();
  374. xmlSettings.AppendChild(xmlElement);
  375. xmlElement = xmlDocument.CreateElement("ForceRebuildAssetBundleSelected");
  376. xmlElement.InnerText = ForceRebuildAssetBundleSelected.ToString();
  377. xmlSettings.AppendChild(xmlElement);
  378. xmlElement = xmlDocument.CreateElement("BuildEventHandlerTypeName");
  379. xmlElement.InnerText = BuildEventHandlerTypeName;
  380. xmlSettings.AppendChild(xmlElement);
  381. xmlElement = xmlDocument.CreateElement("OutputDirectory");
  382. xmlElement.InnerText = OutputDirectory;
  383. xmlSettings.AppendChild(xmlElement);
  384. xmlElement = xmlDocument.CreateElement("OutputPackageSelected");
  385. xmlElement.InnerText = OutputPackageSelected.ToString();
  386. xmlSettings.AppendChild(xmlElement);
  387. xmlElement = xmlDocument.CreateElement("OutputFullSelected");
  388. xmlElement.InnerText = OutputFullSelected.ToString();
  389. xmlSettings.AppendChild(xmlElement);
  390. xmlElement = xmlDocument.CreateElement("OutputPackedSelected");
  391. xmlElement.InnerText = OutputPackedSelected.ToString();
  392. xmlSettings.AppendChild(xmlElement);
  393. string configurationDirectoryName = Path.GetDirectoryName(m_ConfigurationPath);
  394. if (!Directory.Exists(configurationDirectoryName))
  395. {
  396. Directory.CreateDirectory(configurationDirectoryName);
  397. }
  398. xmlDocument.Save(m_ConfigurationPath);
  399. AssetDatabase.Refresh();
  400. return true;
  401. }
  402. catch
  403. {
  404. if (File.Exists(m_ConfigurationPath))
  405. {
  406. File.Delete(m_ConfigurationPath);
  407. }
  408. return false;
  409. }
  410. }
  411. public string[] GetCompressionHelperTypeNames()
  412. {
  413. return m_CompressionHelperTypeNames.ToArray();
  414. }
  415. public string[] GetBuildEventHandlerTypeNames()
  416. {
  417. return m_BuildEventHandlerTypeNames.ToArray();
  418. }
  419. public bool IsPlatformSelected(Platform platform)
  420. {
  421. return (Platforms & platform) != 0;
  422. }
  423. public void SelectPlatform(Platform platform, bool selected)
  424. {
  425. if (selected)
  426. {
  427. Platforms |= platform;
  428. }
  429. else
  430. {
  431. Platforms &= ~platform;
  432. }
  433. }
  434. public bool RefreshCompressionHelper()
  435. {
  436. bool retVal = false;
  437. if (!string.IsNullOrEmpty(CompressionHelperTypeName) && m_CompressionHelperTypeNames.Contains(CompressionHelperTypeName))
  438. {
  439. System.Type compressionHelperType = Utility.Assembly.GetType(CompressionHelperTypeName);
  440. if (compressionHelperType != null)
  441. {
  442. Utility.Compression.ICompressionHelper compressionHelper = (Utility.Compression.ICompressionHelper)Activator.CreateInstance(compressionHelperType);
  443. if (compressionHelper != null)
  444. {
  445. Utility.Compression.SetCompressionHelper(compressionHelper);
  446. return true;
  447. }
  448. }
  449. }
  450. else
  451. {
  452. retVal = true;
  453. }
  454. CompressionHelperTypeName = string.Empty;
  455. Utility.Compression.SetCompressionHelper(null);
  456. return retVal;
  457. }
  458. public bool RefreshBuildEventHandler()
  459. {
  460. bool retVal = false;
  461. if (!string.IsNullOrEmpty(BuildEventHandlerTypeName) && m_BuildEventHandlerTypeNames.Contains(BuildEventHandlerTypeName))
  462. {
  463. System.Type buildEventHandlerType = Utility.Assembly.GetType(BuildEventHandlerTypeName);
  464. if (buildEventHandlerType != null)
  465. {
  466. IBuildEventHandler buildEventHandler = (IBuildEventHandler)Activator.CreateInstance(buildEventHandlerType);
  467. if (buildEventHandler != null)
  468. {
  469. m_BuildEventHandler = buildEventHandler;
  470. return true;
  471. }
  472. }
  473. }
  474. else
  475. {
  476. retVal = true;
  477. }
  478. BuildEventHandlerTypeName = string.Empty;
  479. m_BuildEventHandler = null;
  480. return retVal;
  481. }
  482. public bool BuildResources()
  483. {
  484. if (!IsValidOutputDirectory)
  485. {
  486. return false;
  487. }
  488. if (Directory.Exists(OutputPackagePath))
  489. {
  490. Directory.Delete(OutputPackagePath, true);
  491. }
  492. Directory.CreateDirectory(OutputPackagePath);
  493. if (Directory.Exists(OutputFullPath))
  494. {
  495. Directory.Delete(OutputFullPath, true);
  496. }
  497. Directory.CreateDirectory(OutputFullPath);
  498. if (Directory.Exists(OutputPackedPath))
  499. {
  500. Directory.Delete(OutputPackedPath, true);
  501. }
  502. Directory.CreateDirectory(OutputPackedPath);
  503. if (Directory.Exists(BuildReportPath))
  504. {
  505. Directory.Delete(BuildReportPath, true);
  506. }
  507. Directory.CreateDirectory(BuildReportPath);
  508. BuildAssetBundleOptions buildAssetBundleOptions = GetBuildAssetBundleOptions();
  509. m_BuildReport.Initialize(BuildReportPath, ProductName, CompanyName, GameIdentifier, GameFrameworkVersion, UnityVersion, ApplicableGameVersion, InternalResourceVersion,
  510. Platforms, AssetBundleCompression, CompressionHelperTypeName, AdditionalCompressionSelected, ForceRebuildAssetBundleSelected, BuildEventHandlerTypeName, OutputDirectory, buildAssetBundleOptions, m_ResourceDatas);
  511. try
  512. {
  513. m_BuildReport.LogInfo("Build Start Time: {0}", DateTime.UtcNow.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss.fff"));
  514. if (m_BuildEventHandler != null)
  515. {
  516. m_BuildReport.LogInfo("Execute build event handler 'OnPreprocessAllPlatforms'...");
  517. m_BuildEventHandler.OnPreprocessAllPlatforms(ProductName, CompanyName, GameIdentifier, GameFrameworkVersion, UnityVersion, ApplicableGameVersion, InternalResourceVersion,
  518. Platforms, AssetBundleCompression, CompressionHelperTypeName, AdditionalCompressionSelected, ForceRebuildAssetBundleSelected, BuildEventHandlerTypeName, OutputDirectory, buildAssetBundleOptions,
  519. WorkingPath, OutputPackageSelected, OutputPackagePath, OutputFullSelected, OutputFullPath, OutputPackedSelected, OutputPackedPath, BuildReportPath);
  520. }
  521. m_BuildReport.LogInfo("Start prepare resource collection...");
  522. if (!m_ResourceCollection.Load())
  523. {
  524. m_BuildReport.LogError("Can not parse 'ResourceCollection.xml', please use 'Resource Editor' tool first.");
  525. if (m_BuildEventHandler != null)
  526. {
  527. m_BuildReport.LogInfo("Execute build event handler 'OnPostprocessAllPlatforms'...");
  528. m_BuildEventHandler.OnPostprocessAllPlatforms(ProductName, CompanyName, GameIdentifier, GameFrameworkVersion, UnityVersion, ApplicableGameVersion, InternalResourceVersion,
  529. Platforms, AssetBundleCompression, CompressionHelperTypeName, AdditionalCompressionSelected, ForceRebuildAssetBundleSelected, BuildEventHandlerTypeName, OutputDirectory, buildAssetBundleOptions,
  530. WorkingPath, OutputPackageSelected, OutputPackagePath, OutputFullSelected, OutputFullPath, OutputPackedSelected, OutputPackedPath, BuildReportPath);
  531. }
  532. m_BuildReport.SaveReport();
  533. return false;
  534. }
  535. if (Platforms == Platform.Undefined)
  536. {
  537. m_BuildReport.LogError("Platform undefined.");
  538. if (m_BuildEventHandler != null)
  539. {
  540. m_BuildReport.LogInfo("Execute build event handler 'OnPostprocessAllPlatforms'...");
  541. m_BuildEventHandler.OnPostprocessAllPlatforms(ProductName, CompanyName, GameIdentifier, GameFrameworkVersion, UnityVersion, ApplicableGameVersion, InternalResourceVersion,
  542. Platforms, AssetBundleCompression, CompressionHelperTypeName, AdditionalCompressionSelected, ForceRebuildAssetBundleSelected, BuildEventHandlerTypeName, OutputDirectory, buildAssetBundleOptions,
  543. WorkingPath, OutputPackageSelected, OutputPackagePath, OutputFullSelected, OutputFullPath, OutputPackedSelected, OutputPackedPath, BuildReportPath);
  544. }
  545. m_BuildReport.SaveReport();
  546. return false;
  547. }
  548. m_BuildReport.LogInfo("Prepare resource collection complete.");
  549. m_BuildReport.LogInfo("Start analyze assets dependency...");
  550. m_ResourceAnalyzerController.Analyze();
  551. m_BuildReport.LogInfo("Analyze assets dependency complete.");
  552. m_BuildReport.LogInfo("Start prepare build data...");
  553. AssetBundleBuild[] assetBundleBuildDatas = null;
  554. ResourceData[] assetBundleResourceDatas = null;
  555. ResourceData[] binaryResourceDatas = null;
  556. if (!PrepareBuildData(out assetBundleBuildDatas, out assetBundleResourceDatas, out binaryResourceDatas))
  557. {
  558. m_BuildReport.LogError("Prepare resource build data failure.");
  559. if (m_BuildEventHandler != null)
  560. {
  561. m_BuildReport.LogInfo("Execute build event handler 'OnPostprocessAllPlatforms'...");
  562. m_BuildEventHandler.OnPostprocessAllPlatforms(ProductName, CompanyName, GameIdentifier, GameFrameworkVersion, UnityVersion, ApplicableGameVersion, InternalResourceVersion,
  563. Platforms, AssetBundleCompression, CompressionHelperTypeName, AdditionalCompressionSelected, ForceRebuildAssetBundleSelected, BuildEventHandlerTypeName, OutputDirectory, buildAssetBundleOptions,
  564. WorkingPath, OutputPackageSelected, OutputPackagePath, OutputFullSelected, OutputFullPath, OutputPackedSelected, OutputPackedPath, BuildReportPath);
  565. }
  566. m_BuildReport.SaveReport();
  567. return false;
  568. }
  569. m_BuildReport.LogInfo("Prepare resource build data complete.");
  570. m_BuildReport.LogInfo("Start build resources for selected platforms...");
  571. bool watchResult = m_BuildEventHandler == null || !m_BuildEventHandler.ContinueOnFailure;
  572. bool isSuccess = false;
  573. isSuccess = BuildResources(Platform.Windows, assetBundleBuildDatas, buildAssetBundleOptions, assetBundleResourceDatas, binaryResourceDatas);
  574. if (!watchResult || isSuccess)
  575. {
  576. isSuccess = BuildResources(Platform.Windows64, assetBundleBuildDatas, buildAssetBundleOptions, assetBundleResourceDatas, binaryResourceDatas);
  577. }
  578. if (!watchResult || isSuccess)
  579. {
  580. isSuccess = BuildResources(Platform.MacOS, assetBundleBuildDatas, buildAssetBundleOptions, assetBundleResourceDatas, binaryResourceDatas);
  581. }
  582. if (!watchResult || isSuccess)
  583. {
  584. isSuccess = BuildResources(Platform.Linux, assetBundleBuildDatas, buildAssetBundleOptions, assetBundleResourceDatas, binaryResourceDatas);
  585. }
  586. if (!watchResult || isSuccess)
  587. {
  588. isSuccess = BuildResources(Platform.IOS, assetBundleBuildDatas, buildAssetBundleOptions, assetBundleResourceDatas, binaryResourceDatas);
  589. }
  590. if (!watchResult || isSuccess)
  591. {
  592. isSuccess = BuildResources(Platform.Android, assetBundleBuildDatas, buildAssetBundleOptions, assetBundleResourceDatas, binaryResourceDatas);
  593. }
  594. if (!watchResult || isSuccess)
  595. {
  596. isSuccess = BuildResources(Platform.WindowsStore, assetBundleBuildDatas, buildAssetBundleOptions, assetBundleResourceDatas, binaryResourceDatas);
  597. }
  598. if (!watchResult || isSuccess)
  599. {
  600. isSuccess = BuildResources(Platform.WebGL, assetBundleBuildDatas, buildAssetBundleOptions, assetBundleResourceDatas, binaryResourceDatas);
  601. }
  602. if (m_BuildEventHandler != null)
  603. {
  604. m_BuildReport.LogInfo("Execute build event handler 'OnPostprocessAllPlatforms'...");
  605. m_BuildEventHandler.OnPostprocessAllPlatforms(ProductName, CompanyName, GameIdentifier, GameFrameworkVersion, UnityVersion, ApplicableGameVersion, InternalResourceVersion,
  606. Platforms, AssetBundleCompression, CompressionHelperTypeName, AdditionalCompressionSelected, ForceRebuildAssetBundleSelected, BuildEventHandlerTypeName, OutputDirectory, buildAssetBundleOptions,
  607. WorkingPath, OutputPackageSelected, OutputPackagePath, OutputFullSelected, OutputFullPath, OutputPackedSelected, OutputPackedPath, BuildReportPath);
  608. }
  609. m_BuildReport.LogInfo("Build resources for selected platforms complete.");
  610. m_BuildReport.SaveReport();
  611. return true;
  612. }
  613. catch (Exception exception)
  614. {
  615. string errorMessage = exception.ToString();
  616. m_BuildReport.LogFatal(errorMessage);
  617. m_BuildReport.SaveReport();
  618. if (BuildResourceError != null)
  619. {
  620. BuildResourceError(errorMessage);
  621. }
  622. return false;
  623. }
  624. finally
  625. {
  626. m_OutputPackageFileSystems.Clear();
  627. m_OutputPackedFileSystems.Clear();
  628. if (m_FileSystemManager != null)
  629. {
  630. GameFrameworkEntry.Shutdown();
  631. m_FileSystemManager = null;
  632. }
  633. }
  634. }
  635. private bool BuildResources(Platform platform, AssetBundleBuild[] assetBundleBuildDatas, BuildAssetBundleOptions buildAssetBundleOptions, ResourceData[] assetBundleResourceDatas, ResourceData[] binaryResourceDatas)
  636. {
  637. if (!IsPlatformSelected(platform))
  638. {
  639. return true;
  640. }
  641. string platformName = platform.ToString();
  642. m_BuildReport.LogInfo("Start build resources for '{0}'...", platformName);
  643. string workingPath = Utility.Text.Format("{0}{1}/", WorkingPath, platformName);
  644. m_BuildReport.LogInfo("Working path is '{0}'.", workingPath);
  645. string outputPackagePath = Utility.Text.Format("{0}{1}/", OutputPackagePath, platformName);
  646. if (OutputPackageSelected)
  647. {
  648. Directory.CreateDirectory(outputPackagePath);
  649. m_BuildReport.LogInfo("Output package is selected, path is '{0}'.", outputPackagePath);
  650. }
  651. else
  652. {
  653. m_BuildReport.LogInfo("Output package is not selected.");
  654. }
  655. string outputFullPath = Utility.Text.Format("{0}{1}/", OutputFullPath, platformName);
  656. if (OutputFullSelected)
  657. {
  658. Directory.CreateDirectory(outputFullPath);
  659. m_BuildReport.LogInfo("Output full is selected, path is '{0}'.", outputFullPath);
  660. }
  661. else
  662. {
  663. m_BuildReport.LogInfo("Output full is not selected.");
  664. }
  665. string outputPackedPath = Utility.Text.Format("{0}{1}/", OutputPackedPath, platformName);
  666. if (OutputPackedSelected)
  667. {
  668. Directory.CreateDirectory(outputPackedPath);
  669. m_BuildReport.LogInfo("Output packed is selected, path is '{0}'.", outputPackedPath);
  670. }
  671. else
  672. {
  673. m_BuildReport.LogInfo("Output packed is not selected.");
  674. }
  675. // Clean working path
  676. List<string> validNames = new List<string>();
  677. foreach (ResourceData assetBundleResourceData in assetBundleResourceDatas)
  678. {
  679. validNames.Add(GetResourceFullName(assetBundleResourceData.Name, assetBundleResourceData.Variant).ToLowerInvariant());
  680. }
  681. if (Directory.Exists(workingPath))
  682. {
  683. Uri workingUri = new Uri(workingPath, UriKind.Absolute);
  684. string[] fileNames = Directory.GetFiles(workingPath, "*", SearchOption.AllDirectories);
  685. foreach (string fileName in fileNames)
  686. {
  687. if (fileName.EndsWith(".manifest", StringComparison.Ordinal))
  688. {
  689. continue;
  690. }
  691. string relativeName = workingUri.MakeRelativeUri(new Uri(fileName, UriKind.Absolute)).ToString();
  692. if (!validNames.Contains(relativeName))
  693. {
  694. File.Delete(fileName);
  695. }
  696. }
  697. string[] manifestNames = Directory.GetFiles(workingPath, "*.manifest", SearchOption.AllDirectories);
  698. foreach (string manifestName in manifestNames)
  699. {
  700. if (!File.Exists(manifestName.Substring(0, manifestName.LastIndexOf('.'))))
  701. {
  702. File.Delete(manifestName);
  703. }
  704. }
  705. Utility.Path.RemoveEmptyDirectory(workingPath);
  706. }
  707. if (!Directory.Exists(workingPath))
  708. {
  709. Directory.CreateDirectory(workingPath);
  710. }
  711. if (m_BuildEventHandler != null)
  712. {
  713. m_BuildReport.LogInfo("Execute build event handler 'OnPreprocessPlatform' for '{0}'...", platformName);
  714. m_BuildEventHandler.OnPreprocessPlatform(platform, workingPath, OutputPackageSelected, outputPackagePath, OutputFullSelected, outputFullPath, OutputPackedSelected, outputPackedPath);
  715. }
  716. // Build AssetBundles
  717. m_BuildReport.LogInfo("Unity start build asset bundles for '{0}'...", platformName);
  718. AssetBundleManifest assetBundleManifest = BuildPipeline.BuildAssetBundles(workingPath, assetBundleBuildDatas, buildAssetBundleOptions, GetBuildTarget(platform));
  719. if (assetBundleManifest == null)
  720. {
  721. m_BuildReport.LogError("Build asset bundles for '{0}' failure.", platformName);
  722. if (m_BuildEventHandler != null)
  723. {
  724. m_BuildReport.LogInfo("Execute build event handler 'OnPostprocessPlatform' for '{0}'...", platformName);
  725. m_BuildEventHandler.OnPostprocessPlatform(platform, workingPath, OutputPackageSelected, outputPackagePath, OutputFullSelected, outputFullPath, OutputPackedSelected, outputPackedPath, false);
  726. }
  727. return false;
  728. }
  729. if (m_BuildEventHandler != null)
  730. {
  731. m_BuildReport.LogInfo("Execute build event handler 'OnBuildAssetBundlesComplete' for '{0}'...", platformName);
  732. m_BuildEventHandler.OnBuildAssetBundlesComplete(platform, workingPath, OutputPackageSelected, outputPackagePath, OutputFullSelected, outputFullPath, OutputPackedSelected, outputPackedPath, assetBundleManifest);
  733. }
  734. m_BuildReport.LogInfo("Unity build asset bundles for '{0}' complete.", platformName);
  735. // Create FileSystems
  736. m_BuildReport.LogInfo("Start create file system for '{0}'...", platformName);
  737. if (OutputPackageSelected)
  738. {
  739. CreateFileSystems(m_ResourceDatas.Values, outputPackagePath, m_OutputPackageFileSystems);
  740. }
  741. if (OutputPackedSelected)
  742. {
  743. CreateFileSystems(GetPackedResourceDatas(), outputPackedPath, m_OutputPackedFileSystems);
  744. }
  745. m_BuildReport.LogInfo("Create file system for '{0}' complete.", platformName);
  746. // Process AssetBundles
  747. for (int i = 0; i < assetBundleResourceDatas.Length; i++)
  748. {
  749. string fullName = GetResourceFullName(assetBundleResourceDatas[i].Name, assetBundleResourceDatas[i].Variant);
  750. if (ProcessingAssetBundle != null)
  751. {
  752. if (ProcessingAssetBundle(fullName, (float)(i + 1) / assetBundleResourceDatas.Length))
  753. {
  754. m_BuildReport.LogWarning("The build has been canceled by user.");
  755. if (m_BuildEventHandler != null)
  756. {
  757. m_BuildReport.LogInfo("Execute build event handler 'OnPostprocessPlatform' for '{0}'...", platformName);
  758. m_BuildEventHandler.OnPostprocessPlatform(platform, workingPath, OutputPackageSelected, outputPackagePath, OutputFullSelected, outputFullPath, OutputPackedSelected, outputPackedPath, false);
  759. }
  760. return false;
  761. }
  762. }
  763. m_BuildReport.LogInfo("Start process asset bundle '{0}' for '{1}'...", fullName, platformName);
  764. if (!ProcessAssetBundle(platform, workingPath, outputPackagePath, outputFullPath, outputPackedPath, AdditionalCompressionSelected, assetBundleResourceDatas[i].Name, assetBundleResourceDatas[i].Variant, assetBundleResourceDatas[i].FileSystem))
  765. {
  766. return false;
  767. }
  768. m_BuildReport.LogInfo("Process asset bundle '{0}' for '{1}' complete.", fullName, platformName);
  769. }
  770. // Process Binaries
  771. for (int i = 0; i < binaryResourceDatas.Length; i++)
  772. {
  773. string fullName = GetResourceFullName(binaryResourceDatas[i].Name, binaryResourceDatas[i].Variant);
  774. if (ProcessingBinary != null)
  775. {
  776. if (ProcessingBinary(fullName, (float)(i + 1) / binaryResourceDatas.Length))
  777. {
  778. m_BuildReport.LogWarning("The build has been canceled by user.");
  779. if (m_BuildEventHandler != null)
  780. {
  781. m_BuildReport.LogInfo("Execute build event handler 'OnPostprocessPlatform' for '{0}'...", platformName);
  782. m_BuildEventHandler.OnPostprocessPlatform(platform, workingPath, OutputPackageSelected, outputPackagePath, OutputFullSelected, outputFullPath, OutputPackedSelected, outputPackedPath, false);
  783. }
  784. return false;
  785. }
  786. }
  787. m_BuildReport.LogInfo("Start process binary '{0}' for '{1}'...", fullName, platformName);
  788. if (!ProcessBinary(platform, workingPath, outputPackagePath, outputFullPath, outputPackedPath, AdditionalCompressionSelected, binaryResourceDatas[i].Name, binaryResourceDatas[i].Variant, binaryResourceDatas[i].FileSystem))
  789. {
  790. return false;
  791. }
  792. m_BuildReport.LogInfo("Process binary '{0}' for '{1}' complete.", fullName, platformName);
  793. }
  794. if (OutputPackageSelected)
  795. {
  796. ProcessPackageVersionList(outputPackagePath, platform);
  797. m_BuildReport.LogInfo("Process package version list for '{0}' complete.", platformName);
  798. }
  799. if (OutputFullSelected)
  800. {
  801. VersionListData versionListData = ProcessUpdatableVersionList(outputFullPath, platform);
  802. m_BuildReport.LogInfo("Process updatable version list for '{0}' complete, updatable version list path is '{1}', length is '{2}', hash code is '{3}[0x{3:X8}]', compressed length is '{4}', compressed hash code is '{5}[0x{5:X8}]'.", platformName, versionListData.Path, versionListData.Length.ToString(), versionListData.HashCode, versionListData.CompressedLength.ToString(), versionListData.CompressedHashCode);
  803. if (m_BuildEventHandler != null)
  804. {
  805. m_BuildReport.LogInfo("Execute build event handler 'OnOutputUpdatableVersionListData' for '{0}'...", platformName);
  806. m_BuildEventHandler.OnOutputUpdatableVersionListData(platform, versionListData.Path, versionListData.Length, versionListData.HashCode, versionListData.CompressedLength, versionListData.CompressedHashCode);
  807. }
  808. }
  809. if (OutputPackedSelected)
  810. {
  811. ProcessReadOnlyVersionList(outputPackedPath, platform);
  812. m_BuildReport.LogInfo("Process read-only version list for '{0}' complete.", platformName);
  813. }
  814. if (m_BuildEventHandler != null)
  815. {
  816. m_BuildReport.LogInfo("Execute build event handler 'OnPostprocessPlatform' for '{0}'...", platformName);
  817. m_BuildEventHandler.OnPostprocessPlatform(platform, workingPath, OutputPackageSelected, outputPackagePath, OutputFullSelected, outputFullPath, OutputPackedSelected, outputPackedPath, true);
  818. }
  819. if (ProcessResourceComplete != null)
  820. {
  821. ProcessResourceComplete(platform);
  822. }
  823. m_BuildReport.LogInfo("Build resources for '{0}' success.", platformName);
  824. return true;
  825. }
  826. private bool ProcessAssetBundle(Platform platform, string workingPath, string outputPackagePath, string outputFullPath, string outputPackedPath, bool additionalCompressionSelected, string name, string variant, string fileSystem)
  827. {
  828. string fullName = GetResourceFullName(name, variant);
  829. ResourceData resourceData = m_ResourceDatas[fullName];
  830. string workingName = Utility.Path.GetRegularPath(Path.Combine(workingPath, fullName.ToLowerInvariant()));
  831. byte[] bytes = File.ReadAllBytes(workingName);
  832. int length = bytes.Length;
  833. int hashCode = Utility.Verifier.GetCrc32(bytes);
  834. int compressedLength = length;
  835. int compressedHashCode = hashCode;
  836. byte[] hashBytes = Utility.Converter.GetBytes(hashCode);
  837. if (resourceData.LoadType == LoadType.LoadFromMemoryAndQuickDecrypt)
  838. {
  839. bytes = Utility.Encryption.GetQuickXorBytes(bytes, hashBytes);
  840. }
  841. else if (resourceData.LoadType == LoadType.LoadFromMemoryAndDecrypt)
  842. {
  843. bytes = Utility.Encryption.GetXorBytes(bytes, hashBytes);
  844. }
  845. return ProcessOutput(platform, outputPackagePath, outputFullPath, outputPackedPath, additionalCompressionSelected, name, variant, fileSystem, resourceData, bytes, length, hashCode, compressedLength, compressedHashCode);
  846. }
  847. private bool ProcessBinary(Platform platform, string workingPath, string outputPackagePath, string outputFullPath, string outputPackedPath, bool additionalCompressionSelected, string name, string variant, string fileSystem)
  848. {
  849. string fullName = GetResourceFullName(name, variant);
  850. ResourceData resourceData = m_ResourceDatas[fullName];
  851. string assetName = resourceData.GetAssetNames()[0];
  852. string assetPath = Utility.Path.GetRegularPath(Application.dataPath.Substring(0, Application.dataPath.Length - AssetsStringLength) + assetName);
  853. byte[] bytes = File.ReadAllBytes(assetPath);
  854. int length = bytes.Length;
  855. int hashCode = Utility.Verifier.GetCrc32(bytes);
  856. int compressedLength = length;
  857. int compressedHashCode = hashCode;
  858. byte[] hashBytes = Utility.Converter.GetBytes(hashCode);
  859. if (resourceData.LoadType == LoadType.LoadFromBinaryAndQuickDecrypt)
  860. {
  861. bytes = Utility.Encryption.GetQuickXorBytes(bytes, hashBytes);
  862. }
  863. else if (resourceData.LoadType == LoadType.LoadFromBinaryAndDecrypt)
  864. {
  865. bytes = Utility.Encryption.GetXorBytes(bytes, hashBytes);
  866. }
  867. return ProcessOutput(platform, outputPackagePath, outputFullPath, outputPackedPath, additionalCompressionSelected, name, variant, fileSystem, resourceData, bytes, length, hashCode, compressedLength, compressedHashCode);
  868. }
  869. private void ProcessPackageVersionList(string outputPackagePath, Platform platform)
  870. {
  871. Asset[] originalAssets = m_ResourceCollection.GetAssets();
  872. PackageVersionList.Asset[] assets = new PackageVersionList.Asset[originalAssets.Length];
  873. for (int i = 0; i < assets.Length; i++)
  874. {
  875. Asset originalAsset = originalAssets[i];
  876. assets[i] = new PackageVersionList.Asset(originalAsset.Name, GetDependencyAssetIndexes(originalAsset.Name));
  877. }
  878. SortedDictionary<string, ResourceData>.ValueCollection resourceDatas = m_ResourceDatas.Values;
  879. int index = 0;
  880. PackageVersionList.Resource[] resources = new PackageVersionList.Resource[m_ResourceCollection.ResourceCount];
  881. foreach (ResourceData resourceData in resourceDatas)
  882. {
  883. ResourceCode resourceCode = resourceData.GetCode(platform);
  884. resources[index++] = new PackageVersionList.Resource(resourceData.Name, resourceData.Variant, GetExtension(resourceData), (byte)resourceData.LoadType, resourceCode.Length, resourceCode.HashCode, GetAssetIndexes(resourceData));
  885. }
  886. string[] fileSystemNames = GetFileSystemNames(resourceDatas);
  887. PackageVersionList.FileSystem[] fileSystems = new PackageVersionList.FileSystem[fileSystemNames.Length];
  888. for (int i = 0; i < fileSystems.Length; i++)
  889. {
  890. fileSystems[i] = new PackageVersionList.FileSystem(fileSystemNames[i], GetResourceIndexesFromFileSystem(resourceDatas, fileSystemNames[i]));
  891. }
  892. string[] resourceGroupNames = GetResourceGroupNames(resourceDatas);
  893. PackageVersionList.ResourceGroup[] resourceGroups = new PackageVersionList.ResourceGroup[resourceGroupNames.Length];
  894. for (int i = 0; i < resourceGroups.Length; i++)
  895. {
  896. resourceGroups[i] = new PackageVersionList.ResourceGroup(resourceGroupNames[i], GetResourceIndexesFromResourceGroup(resourceDatas, resourceGroupNames[i]));
  897. }
  898. PackageVersionList versionList = new PackageVersionList(ApplicableGameVersion, InternalResourceVersion, assets, resources, fileSystems, resourceGroups);
  899. PackageVersionListSerializer serializer = new PackageVersionListSerializer();
  900. serializer.RegisterSerializeCallback(0, BuiltinVersionListSerializer.PackageVersionListSerializeCallback_V0);
  901. serializer.RegisterSerializeCallback(1, BuiltinVersionListSerializer.PackageVersionListSerializeCallback_V1);
  902. serializer.RegisterSerializeCallback(2, BuiltinVersionListSerializer.PackageVersionListSerializeCallback_V2);
  903. string packageVersionListPath = Utility.Path.GetRegularPath(Path.Combine(outputPackagePath, RemoteVersionListFileName));
  904. using (FileStream fileStream = new FileStream(packageVersionListPath, FileMode.Create, FileAccess.Write))
  905. {
  906. if (!serializer.Serialize(fileStream, versionList))
  907. {
  908. throw new GameFrameworkException("Serialize package version list failure.");
  909. }
  910. }
  911. }
  912. private VersionListData ProcessUpdatableVersionList(string outputFullPath, Platform platform)
  913. {
  914. Asset[] originalAssets = m_ResourceCollection.GetAssets();
  915. UpdatableVersionList.Asset[] assets = new UpdatableVersionList.Asset[originalAssets.Length];
  916. for (int i = 0; i < assets.Length; i++)
  917. {
  918. Asset originalAsset = originalAssets[i];
  919. assets[i] = new UpdatableVersionList.Asset(originalAsset.Name, GetDependencyAssetIndexes(originalAsset.Name));
  920. }
  921. SortedDictionary<string, ResourceData>.ValueCollection resourceDatas = m_ResourceDatas.Values;
  922. int index = 0;
  923. UpdatableVersionList.Resource[] resources = new UpdatableVersionList.Resource[m_ResourceCollection.ResourceCount];
  924. foreach (ResourceData resourceData in resourceDatas)
  925. {
  926. ResourceCode resourceCode = resourceData.GetCode(platform);
  927. resources[index++] = new UpdatableVersionList.Resource(resourceData.Name, resourceData.Variant, GetExtension(resourceData), (byte)resourceData.LoadType, resourceCode.Length, resourceCode.HashCode, resourceCode.CompressedLength, resourceCode.CompressedHashCode, GetAssetIndexes(resourceData));
  928. }
  929. string[] fileSystemNames = GetFileSystemNames(resourceDatas);
  930. UpdatableVersionList.FileSystem[] fileSystems = new UpdatableVersionList.FileSystem[fileSystemNames.Length];
  931. for (int i = 0; i < fileSystems.Length; i++)
  932. {
  933. fileSystems[i] = new UpdatableVersionList.FileSystem(fileSystemNames[i], GetResourceIndexesFromFileSystem(resourceDatas, fileSystemNames[i]));
  934. }
  935. string[] resourceGroupNames = GetResourceGroupNames(resourceDatas);
  936. UpdatableVersionList.ResourceGroup[] resourceGroups = new UpdatableVersionList.ResourceGroup[resourceGroupNames.Length];
  937. for (int i = 0; i < resourceGroups.Length; i++)
  938. {
  939. resourceGroups[i] = new UpdatableVersionList.ResourceGroup(resourceGroupNames[i], GetResourceIndexesFromResourceGroup(resourceDatas, resourceGroupNames[i]));
  940. }
  941. UpdatableVersionList versionList = new UpdatableVersionList(ApplicableGameVersion, InternalResourceVersion, assets, resources, fileSystems, resourceGroups);
  942. UpdatableVersionListSerializer serializer = new UpdatableVersionListSerializer();
  943. serializer.RegisterSerializeCallback(0, BuiltinVersionListSerializer.UpdatableVersionListSerializeCallback_V0);
  944. serializer.RegisterSerializeCallback(1, BuiltinVersionListSerializer.UpdatableVersionListSerializeCallback_V1);
  945. serializer.RegisterSerializeCallback(2, BuiltinVersionListSerializer.UpdatableVersionListSerializeCallback_V2);
  946. string updatableVersionListPath = Utility.Path.GetRegularPath(Path.Combine(outputFullPath, RemoteVersionListFileName));
  947. using (FileStream fileStream = new FileStream(updatableVersionListPath, FileMode.Create, FileAccess.Write))
  948. {
  949. if (!serializer.Serialize(fileStream, versionList))
  950. {
  951. throw new GameFrameworkException("Serialize updatable version list failure.");
  952. }
  953. }
  954. byte[] bytes = File.ReadAllBytes(updatableVersionListPath);
  955. int length = bytes.Length;
  956. int hashCode = Utility.Verifier.GetCrc32(bytes);
  957. bytes = Utility.Compression.Compress(bytes);
  958. int compressedLength = bytes.Length;
  959. File.WriteAllBytes(updatableVersionListPath, bytes);
  960. int compressedHashCode = Utility.Verifier.GetCrc32(bytes);
  961. int dotPosition = RemoteVersionListFileName.LastIndexOf('.');
  962. string versionListFullNameWithCrc32 = Utility.Text.Format("{0}.{2:x8}.{1}", RemoteVersionListFileName.Substring(0, dotPosition), RemoteVersionListFileName.Substring(dotPosition + 1), hashCode);
  963. string updatableVersionListPathWithCrc32 = Utility.Path.GetRegularPath(Path.Combine(outputFullPath, versionListFullNameWithCrc32));
  964. File.Move(updatableVersionListPath, updatableVersionListPathWithCrc32);
  965. return new VersionListData(updatableVersionListPathWithCrc32, length, hashCode, compressedLength, compressedHashCode);
  966. }
  967. private void ProcessReadOnlyVersionList(string outputPackedPath, Platform platform)
  968. {
  969. ResourceData[] packedResourceDatas = GetPackedResourceDatas();
  970. LocalVersionList.Resource[] resources = new LocalVersionList.Resource[packedResourceDatas.Length];
  971. for (int i = 0; i < resources.Length; i++)
  972. {
  973. ResourceData resourceData = packedResourceDatas[i];
  974. ResourceCode resourceCode = resourceData.GetCode(platform);
  975. resources[i] = new LocalVersionList.Resource(resourceData.Name, resourceData.Variant, GetExtension(resourceData), (byte)resourceData.LoadType, resourceCode.Length, resourceCode.HashCode);
  976. }
  977. string[] packedFileSystemNames = GetFileSystemNames(packedResourceDatas);
  978. LocalVersionList.FileSystem[] fileSystems = new LocalVersionList.FileSystem[packedFileSystemNames.Length];
  979. for (int i = 0; i < fileSystems.Length; i++)
  980. {
  981. fileSystems[i] = new LocalVersionList.FileSystem(packedFileSystemNames[i], GetResourceIndexesFromFileSystem(packedResourceDatas, packedFileSystemNames[i]));
  982. }
  983. LocalVersionList versionList = new LocalVersionList(resources, fileSystems);
  984. ReadOnlyVersionListSerializer serializer = new ReadOnlyVersionListSerializer();
  985. serializer.RegisterSerializeCallback(0, BuiltinVersionListSerializer.LocalVersionListSerializeCallback_V0);
  986. serializer.RegisterSerializeCallback(1, BuiltinVersionListSerializer.LocalVersionListSerializeCallback_V1);
  987. serializer.RegisterSerializeCallback(2, BuiltinVersionListSerializer.LocalVersionListSerializeCallback_V2);
  988. string readOnlyVersionListPath = Utility.Path.GetRegularPath(Path.Combine(outputPackedPath, LocalVersionListFileName));
  989. using (FileStream fileStream = new FileStream(readOnlyVersionListPath, FileMode.Create, FileAccess.Write))
  990. {
  991. if (!serializer.Serialize(fileStream, versionList))
  992. {
  993. throw new GameFrameworkException("Serialize read-only version list failure.");
  994. }
  995. }
  996. }
  997. private int[] GetDependencyAssetIndexes(string assetName)
  998. {
  999. List<int> dependencyAssetIndexes = new List<int>();
  1000. Asset[] assets = m_ResourceCollection.GetAssets();
  1001. DependencyData dependencyData = m_ResourceAnalyzerController.GetDependencyData(assetName);
  1002. foreach (Asset dependencyAsset in dependencyData.GetDependencyAssets())
  1003. {
  1004. for (int i = 0; i < assets.Length; i++)
  1005. {
  1006. if (assets[i] == dependencyAsset)
  1007. {
  1008. dependencyAssetIndexes.Add(i);
  1009. break;
  1010. }
  1011. }
  1012. }
  1013. dependencyAssetIndexes.Sort();
  1014. return dependencyAssetIndexes.ToArray();
  1015. }
  1016. private int[] GetAssetIndexes(ResourceData resourceData)
  1017. {
  1018. Asset[] assets = m_ResourceCollection.GetAssets();
  1019. string[] assetGuids = resourceData.GetAssetGuids();
  1020. int[] assetIndexes = new int[assetGuids.Length];
  1021. for (int i = 0; i < assetGuids.Length; i++)
  1022. {
  1023. assetIndexes[i] = Array.BinarySearch(assets, m_ResourceCollection.GetAsset(assetGuids[i]));
  1024. if (assetIndexes[i] < 0)
  1025. {
  1026. throw new GameFrameworkException("Asset is invalid.");
  1027. }
  1028. }
  1029. return assetIndexes;
  1030. }
  1031. private ResourceData[] GetPackedResourceDatas()
  1032. {
  1033. List<ResourceData> packedResourceDatas = new List<ResourceData>();
  1034. foreach (ResourceData resourceData in m_ResourceDatas.Values)
  1035. {
  1036. if (!resourceData.Packed)
  1037. {
  1038. continue;
  1039. }
  1040. packedResourceDatas.Add(resourceData);
  1041. }
  1042. return packedResourceDatas.ToArray();
  1043. }
  1044. private string[] GetFileSystemNames(IEnumerable<ResourceData> resourceDatas)
  1045. {
  1046. HashSet<string> fileSystemNames = new HashSet<string>();
  1047. foreach (ResourceData resourceData in resourceDatas)
  1048. {
  1049. if (resourceData.FileSystem == null)
  1050. {
  1051. continue;
  1052. }
  1053. fileSystemNames.Add(resourceData.FileSystem);
  1054. }
  1055. return fileSystemNames.OrderBy(x => x).ToArray();
  1056. }
  1057. private int[] GetResourceIndexesFromFileSystem(IEnumerable<ResourceData> resourceDatas, string fileSystemName)
  1058. {
  1059. int index = 0;
  1060. List<int> resourceIndexes = new List<int>();
  1061. foreach (ResourceData resourceData in resourceDatas)
  1062. {
  1063. if (resourceData.FileSystem == fileSystemName)
  1064. {
  1065. resourceIndexes.Add(index);
  1066. }
  1067. index++;
  1068. }
  1069. resourceIndexes.Sort();
  1070. return resourceIndexes.ToArray();
  1071. }
  1072. private string[] GetResourceGroupNames(IEnumerable<ResourceData> resourceDatas)
  1073. {
  1074. HashSet<string> resourceGroupNames = new HashSet<string>();
  1075. foreach (ResourceData resourceData in resourceDatas)
  1076. {
  1077. foreach (string resourceGroup in resourceData.GetResourceGroups())
  1078. {
  1079. resourceGroupNames.Add(resourceGroup);
  1080. }
  1081. }
  1082. return resourceGroupNames.OrderBy(x => x).ToArray();
  1083. }
  1084. private int[] GetResourceIndexesFromResourceGroup(IEnumerable<ResourceData> resourceDatas, string resourceGroupName)
  1085. {
  1086. int index = 0;
  1087. List<int> resourceIndexes = new List<int>();
  1088. foreach (ResourceData resourceData in resourceDatas)
  1089. {
  1090. foreach (string resourceGroup in resourceData.GetResourceGroups())
  1091. {
  1092. if (resourceGroup == resourceGroupName)
  1093. {
  1094. resourceIndexes.Add(index);
  1095. break;
  1096. }
  1097. }
  1098. index++;
  1099. }
  1100. resourceIndexes.Sort();
  1101. return resourceIndexes.ToArray();
  1102. }
  1103. private void CreateFileSystems(IEnumerable<ResourceData> resourceDatas, string outputPath, Dictionary<string, IFileSystem> outputFileSystem)
  1104. {
  1105. outputFileSystem.Clear();
  1106. string[] fileSystemNames = GetFileSystemNames(resourceDatas);
  1107. if (fileSystemNames.Length > 0 && m_FileSystemManager == null)
  1108. {
  1109. m_FileSystemManager = GameFrameworkEntry.GetModule<IFileSystemManager>();
  1110. m_FileSystemManager.SetFileSystemHelper(new FileSystemHelper());
  1111. }
  1112. foreach (string fileSystemName in fileSystemNames)
  1113. {
  1114. int fileCount = GetResourceIndexesFromFileSystem(resourceDatas, fileSystemName).Length;
  1115. string fullPath = Utility.Path.GetRegularPath(Path.Combine(outputPath, Utility.Text.Format("{0}.{1}", fileSystemName, DefaultExtension)));
  1116. string directory = Path.GetDirectoryName(fullPath);
  1117. if (!Directory.Exists(directory))
  1118. {
  1119. Directory.CreateDirectory(directory);
  1120. }
  1121. IFileSystem fileSystem = m_FileSystemManager.CreateFileSystem(fullPath, FileSystemAccess.Write, fileCount, fileCount);
  1122. outputFileSystem.Add(fileSystemName, fileSystem);
  1123. }
  1124. }
  1125. private bool ProcessOutput(Platform platform, string outputPackagePath, string outputFullPath, string outputPackedPath, bool additionalCompressionSelected, string name, string variant, string fileSystem, ResourceData resourceData, byte[] bytes, int length, int hashCode, int compressedLength, int compressedHashCode)
  1126. {
  1127. string fullNameWithExtension = Utility.Text.Format("{0}.{1}", GetResourceFullName(name, variant), GetExtension(resourceData));
  1128. if (OutputPackageSelected)
  1129. {
  1130. if (string.IsNullOrEmpty(fileSystem))
  1131. {
  1132. string packagePath = Utility.Path.GetRegularPath(Path.Combine(outputPackagePath, fullNameWithExtension));
  1133. string packageDirectoryName = Path.GetDirectoryName(packagePath);
  1134. if (!Directory.Exists(packageDirectoryName))
  1135. {
  1136. Directory.CreateDirectory(packageDirectoryName);
  1137. }
  1138. File.WriteAllBytes(packagePath, bytes);
  1139. }
  1140. else
  1141. {
  1142. if (!m_OutputPackageFileSystems[fileSystem].WriteFile(fullNameWithExtension, bytes))
  1143. {
  1144. return false;
  1145. }
  1146. }
  1147. }
  1148. if (OutputPackedSelected && resourceData.Packed)
  1149. {
  1150. if (string.IsNullOrEmpty(fileSystem))
  1151. {
  1152. string packedPath = Utility.Path.GetRegularPath(Path.Combine(outputPackedPath, fullNameWithExtension));
  1153. string packedDirectoryName = Path.GetDirectoryName(packedPath);
  1154. if (!Directory.Exists(packedDirectoryName))
  1155. {
  1156. Directory.CreateDirectory(packedDirectoryName);
  1157. }
  1158. File.WriteAllBytes(packedPath, bytes);
  1159. }
  1160. else
  1161. {
  1162. if (!m_OutputPackedFileSystems[fileSystem].WriteFile(fullNameWithExtension, bytes))
  1163. {
  1164. return false;
  1165. }
  1166. }
  1167. }
  1168. if (OutputFullSelected)
  1169. {
  1170. string fullNameWithCrc32AndExtension = variant != null ? Utility.Text.Format("{0}.{1}.{2:x8}.{3}", name, variant, hashCode, DefaultExtension) : Utility.Text.Format("{0}.{1:x8}.{2}", name, hashCode, DefaultExtension);
  1171. string fullPath = Utility.Path.GetRegularPath(Path.Combine(outputFullPath, fullNameWithCrc32AndExtension));
  1172. string fullDirectoryName = Path.GetDirectoryName(fullPath);
  1173. if (!Directory.Exists(fullDirectoryName))
  1174. {
  1175. Directory.CreateDirectory(fullDirectoryName);
  1176. }
  1177. if (additionalCompressionSelected)
  1178. {
  1179. byte[] compressedBytes = Utility.Compression.Compress(bytes);
  1180. compressedLength = compressedBytes.Length;
  1181. compressedHashCode = Utility.Verifier.GetCrc32(compressedBytes);
  1182. File.WriteAllBytes(fullPath, compressedBytes);
  1183. }
  1184. else
  1185. {
  1186. File.WriteAllBytes(fullPath, bytes);
  1187. }
  1188. }
  1189. resourceData.AddCode(platform, length, hashCode, compressedLength, compressedHashCode);
  1190. return true;
  1191. }
  1192. private BuildAssetBundleOptions GetBuildAssetBundleOptions()
  1193. {
  1194. BuildAssetBundleOptions buildOptions = BuildAssetBundleOptions.DeterministicAssetBundle;
  1195. if (ForceRebuildAssetBundleSelected)
  1196. {
  1197. buildOptions |= BuildAssetBundleOptions.ForceRebuildAssetBundle;
  1198. }
  1199. if (AssetBundleCompression == AssetBundleCompressionType.Uncompressed)
  1200. {
  1201. buildOptions |= BuildAssetBundleOptions.UncompressedAssetBundle;
  1202. }
  1203. else if (AssetBundleCompression == AssetBundleCompressionType.LZ4)
  1204. {
  1205. buildOptions |= BuildAssetBundleOptions.ChunkBasedCompression;
  1206. }
  1207. return buildOptions;
  1208. }
  1209. private bool PrepareBuildData(out AssetBundleBuild[] assetBundleBuildDatas, out ResourceData[] assetBundleResourceDatas, out ResourceData[] binaryResourceDatas)
  1210. {
  1211. assetBundleBuildDatas = null;
  1212. assetBundleResourceDatas = null;
  1213. binaryResourceDatas = null;
  1214. m_ResourceDatas.Clear();
  1215. Resource[] resources = m_ResourceCollection.GetResources();
  1216. foreach (Resource resource in resources)
  1217. {
  1218. m_ResourceDatas.Add(resource.FullName, new ResourceData(resource.Name, resource.Variant, resource.FileSystem, resource.LoadType, resource.Packed, resource.GetResourceGroups()));
  1219. }
  1220. Asset[] assets = m_ResourceCollection.GetAssets();
  1221. foreach (Asset asset in assets)
  1222. {
  1223. string assetName = asset.Name;
  1224. if (string.IsNullOrEmpty(assetName))
  1225. {
  1226. m_BuildReport.LogError("Can not find asset by guid '{0}'.", asset.Guid);
  1227. return false;
  1228. }
  1229. string assetFileFullName = Application.dataPath.Substring(0, Application.dataPath.Length - AssetsStringLength) + assetName;
  1230. if (!File.Exists(assetFileFullName))
  1231. {
  1232. m_BuildReport.LogError("Can not find asset '{0}'.", assetFileFullName);
  1233. return false;
  1234. }
  1235. byte[] assetBytes = File.ReadAllBytes(assetFileFullName);
  1236. int assetHashCode = Utility.Verifier.GetCrc32(assetBytes);
  1237. List<string> dependencyAssetNames = new List<string>();
  1238. DependencyData dependencyData = m_ResourceAnalyzerController.GetDependencyData(assetName);
  1239. Asset[] dependencyAssets = dependencyData.GetDependencyAssets();
  1240. foreach (Asset dependencyAsset in dependencyAssets)
  1241. {
  1242. dependencyAssetNames.Add(dependencyAsset.Name);
  1243. }
  1244. dependencyAssetNames.Sort();
  1245. m_ResourceDatas[asset.Resource.FullName].AddAssetData(asset.Guid, assetName, assetBytes.Length, assetHashCode, dependencyAssetNames.ToArray());
  1246. }
  1247. List<AssetBundleBuild> assetBundleBuildDataList = new List<AssetBundleBuild>();
  1248. List<ResourceData> assetBundleResourceDataList = new List<ResourceData>();
  1249. List<ResourceData> binaryResourceDataList = new List<ResourceData>();
  1250. foreach (ResourceData resourceData in m_ResourceDatas.Values)
  1251. {
  1252. if (resourceData.AssetCount <= 0)
  1253. {
  1254. m_BuildReport.LogError("Resource '{0}' has no asset.", GetResourceFullName(resourceData.Name, resourceData.Variant));
  1255. return false;
  1256. }
  1257. if (resourceData.IsLoadFromBinary)
  1258. {
  1259. binaryResourceDataList.Add(resourceData);
  1260. }
  1261. else
  1262. {
  1263. assetBundleResourceDataList.Add(resourceData);
  1264. AssetBundleBuild build = new AssetBundleBuild();
  1265. build.assetBundleName = resourceData.Name;
  1266. build.assetBundleVariant = resourceData.Variant;
  1267. build.assetNames = resourceData.GetAssetNames();
  1268. assetBundleBuildDataList.Add(build);
  1269. }
  1270. }
  1271. assetBundleBuildDatas = assetBundleBuildDataList.ToArray();
  1272. assetBundleResourceDatas = assetBundleResourceDataList.ToArray();
  1273. binaryResourceDatas = binaryResourceDataList.ToArray();
  1274. return true;
  1275. }
  1276. private static string GetResourceFullName(string name, string variant)
  1277. {
  1278. return !string.IsNullOrEmpty(variant) ? Utility.Text.Format("{0}.{1}", name, variant) : name;
  1279. }
  1280. private static BuildTarget GetBuildTarget(Platform platform)
  1281. {
  1282. switch (platform)
  1283. {
  1284. case Platform.Windows:
  1285. return BuildTarget.StandaloneWindows;
  1286. case Platform.Windows64:
  1287. return BuildTarget.StandaloneWindows64;
  1288. case Platform.MacOS:
  1289. #if UNITY_2017_3_OR_NEWER
  1290. return BuildTarget.StandaloneOSX;
  1291. #else
  1292. return BuildTarget.StandaloneOSXUniversal;
  1293. #endif
  1294. case Platform.Linux:
  1295. return BuildTarget.StandaloneLinux64;
  1296. case Platform.IOS:
  1297. return BuildTarget.iOS;
  1298. case Platform.Android:
  1299. return BuildTarget.Android;
  1300. case Platform.WindowsStore:
  1301. return BuildTarget.WSAPlayer;
  1302. case Platform.WebGL:
  1303. return BuildTarget.WebGL;
  1304. default:
  1305. throw new GameFrameworkException("Platform is invalid.");
  1306. }
  1307. }
  1308. private static string GetExtension(ResourceData data)
  1309. {
  1310. if (data.IsLoadFromBinary)
  1311. {
  1312. string assetName = data.GetAssetNames()[0];
  1313. int position = assetName.LastIndexOf('.');
  1314. if (position >= 0)
  1315. {
  1316. return assetName.Substring(position + 1);
  1317. }
  1318. }
  1319. return DefaultExtension;
  1320. }
  1321. }
  1322. }