ProjectExporterController.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using AssetBank.Editor.SceneSchema;
  7. using AssetBank.Editor.SchemaConverter;
  8. using AssetBank.Editor.Tools;
  9. using AssetBank.Settings;
  10. using UnityEditor;
  11. using UnityEditor.Animations;
  12. using UnityEngine;
  13. using UnityEngine.Audio;
  14. using UnityEngine.Video;
  15. namespace AssetBank.DockableWindow
  16. {
  17. public class ProjectExporterController
  18. {
  19. private static readonly string ProjectRoot = Path.GetDirectoryName(Application.dataPath);
  20. private readonly ProjectExporterSettings _settings;
  21. public ProjectExporterController()
  22. {
  23. _settings = ProjectExporterSettings.GetOrCreateSettings();
  24. }
  25. // Finds assets based on a search filter (e.g., "t:Scene") and builds a hierarchical model.
  26. public static AssetModel GetAssets(string filter, string category)
  27. {
  28. var root = new AssetModel("Assets", "Assets", category);
  29. var assetGuids = AssetDatabase.FindAssets(filter, new[] { "Assets" });
  30. foreach (var guid in assetGuids)
  31. {
  32. var path = AssetDatabase.GUIDToAssetPath(guid);
  33. if (filter.Contains("t:ScriptableObject") && !path.EndsWith(".asset"))
  34. {
  35. continue;
  36. }
  37. var parts = path.Split('/');
  38. var currentNode = root;
  39. for (int i = 1; i < parts.Length; i++) // Start at 1 to skip "Assets"
  40. {
  41. var part = parts[i];
  42. var child = currentNode.Children.FirstOrDefault(c => c.Name == part);
  43. if (child == null)
  44. {
  45. var currentPath = string.Join("/", parts.Take(i + 1));
  46. child = new AssetModel(currentPath, part, category);
  47. currentNode.Children.Add(child);
  48. }
  49. currentNode = child;
  50. }
  51. }
  52. return root;
  53. }
  54. // Lists all files in the ProjectSettings directory.
  55. public AssetModel GetProjectSettingsFiles()
  56. {
  57. const string category = "Settings";
  58. var settingsRootPath = Path.Combine(ProjectRoot, "ProjectSettings");
  59. var root = new AssetModel(settingsRootPath, "ProjectSettings", category);
  60. if (Directory.Exists(settingsRootPath))
  61. {
  62. // Filter to only include *.asset files.
  63. var files = Directory.GetFiles(settingsRootPath, "*.asset", SearchOption.AllDirectories);
  64. foreach (var file in files)
  65. {
  66. var relativePath = Path.GetRelativePath(ProjectRoot, file);
  67. root.Children.Add(new AssetModel(relativePath, Path.GetFileName(file), category));
  68. }
  69. }
  70. return root;
  71. }
  72. // Scans the entire Assets folder for .meta files and builds a hierarchical model.
  73. public AssetModel GetAllMetaFiles()
  74. {
  75. const string category = "Meta Files";
  76. var assetsRootPath = Application.dataPath; // This is the "Assets" folder
  77. var root = new AssetModel("Assets", "Assets", category);
  78. var files = Directory.GetFiles(assetsRootPath, "*.meta", SearchOption.AllDirectories);
  79. foreach (var file in files)
  80. {
  81. var relativePath = "Assets/" + Path.GetRelativePath(assetsRootPath, file).Replace('\\', '/');
  82. var parts = relativePath.Split('/');
  83. var currentNode = root;
  84. for (int i = 1; i < parts.Length; i++) // Start at 1 to skip "Assets"
  85. {
  86. var part = parts[i];
  87. var child = currentNode.Children.FirstOrDefault(c => c.Name == part);
  88. if (child == null)
  89. {
  90. var currentPath = string.Join("/", parts.Take(i + 1));
  91. child = new AssetModel(currentPath, part, category);
  92. currentNode.Children.Add(child);
  93. }
  94. currentNode = child;
  95. }
  96. }
  97. return root;
  98. }
  99. private string FindPythonExecutable()
  100. {
  101. var venvPath = Path.Combine(ProjectRoot, "venv", "bin", "python3");
  102. if (File.Exists(venvPath))
  103. {
  104. return venvPath;
  105. }
  106. venvPath = Path.Combine(ProjectRoot, "venv", "bin", "python");
  107. if (File.Exists(venvPath))
  108. {
  109. return venvPath;
  110. }
  111. return "python3";
  112. }
  113. private string GetConversionScriptPath()
  114. {
  115. var guids = AssetDatabase.FindAssets("convert_scene");
  116. if (guids.Length == 0)
  117. {
  118. UnityEngine.Debug.LogError("Conversion script 'convert_scene.py' not found.");
  119. return null;
  120. }
  121. var path = AssetDatabase.GUIDToAssetPath(guids[0]);
  122. return Path.Combine(ProjectRoot, path);
  123. }
  124. // Executes the Python conversion script for the selected assets.
  125. public void ExportAssets(AssetModel rootNode, string customExportPath = null)
  126. {
  127. var assetsToExport = new List<AssetModel>();
  128. CollectSelectedAssets(rootNode, assetsToExport);
  129. var filteredAssets = FilterAssets(assetsToExport.Select(a => a.Path).ToList())
  130. .ToHashSet();
  131. var finalAssetsToExport = assetsToExport.Where(a => filteredAssets.Contains(a.Path)).ToList();
  132. var pythonExecutable = FindPythonExecutable();
  133. var conversionScript = GetConversionScriptPath();
  134. if (string.IsNullOrEmpty(conversionScript)) return;
  135. var outputDirectory = customExportPath ?? Path.Combine(ProjectRoot, "Library", "ProjectDataExport");
  136. Directory.CreateDirectory(outputDirectory);
  137. EditorUtility.DisplayProgressBar("Exporting...", "Starting export process...", 0f);
  138. try
  139. {
  140. for (int i = 0; i < finalAssetsToExport.Count; i++)
  141. {
  142. var asset = finalAssetsToExport[i];
  143. var relativeAssetPath = asset.Path;
  144. var progress = (float)i / finalAssetsToExport.Count;
  145. EditorUtility.DisplayProgressBar("Exporting...", $"Processing {Path.GetFileName(relativeAssetPath)}", progress);
  146. var absoluteAssetPath = Path.Combine(ProjectRoot, relativeAssetPath);
  147. var outputJsonPath = Path.Combine(outputDirectory, relativeAssetPath.Replace('/', Path.DirectorySeparatorChar) + ".json");
  148. var fileOutputDir = Path.GetDirectoryName(outputJsonPath);
  149. if (!Directory.Exists(fileOutputDir))
  150. {
  151. Directory.CreateDirectory(fileOutputDir);
  152. }
  153. var exitCode = asset.Category == "Scenes" ?
  154. ProcessUsingSimpleSceneSerializer(relativeAssetPath, outputJsonPath, out var output, out var error) :
  155. ProcessUsingPythonTool(conversionScript, absoluteAssetPath, outputJsonPath, pythonExecutable, out output, out error);
  156. if (exitCode != 0)
  157. {
  158. UnityEngine.Debug.LogError($"Error exporting {relativeAssetPath}: {error}");
  159. }
  160. else
  161. {
  162. if (_settings.OptimiseExport && _settings.CategoriesToOptimise.Contains(asset.Category))
  163. {
  164. var rawJson = File.ReadAllText(outputJsonPath);
  165. var processedJson = JsonDataTrimmer.Process(rawJson, _settings);
  166. File.WriteAllText(outputJsonPath, processedJson);
  167. }
  168. if (_settings.ConvertToNewSchema && asset.Category == "Scenes")
  169. {
  170. var jsonToConvert = File.ReadAllText(outputJsonPath);
  171. var convertedJson = JsonSchemaConverter.Convert(jsonToConvert);
  172. File.WriteAllText(outputJsonPath, convertedJson);
  173. }
  174. UnityEngine.Debug.Log($"Successfully exported {relativeAssetPath}: {output}");
  175. }
  176. }
  177. }
  178. finally
  179. {
  180. EditorUtility.ClearProgressBar();
  181. }
  182. }
  183. private static int ProcessUsingPythonTool(string conversionScript, string absoluteAssetPath, string outputJsonPath, string pythonExecutable, out string output, out string error)
  184. {
  185. var arguments =
  186. $"\"{conversionScript}\" \"{absoluteAssetPath}\" \"{outputJsonPath}\"";
  187. var process = new Process
  188. {
  189. StartInfo = new ProcessStartInfo
  190. {
  191. FileName = pythonExecutable,
  192. Arguments = arguments,
  193. RedirectStandardOutput = true,
  194. RedirectStandardError = true,
  195. UseShellExecute = false,
  196. CreateNoWindow = true
  197. }
  198. };
  199. process.Start();
  200. output = process.StandardOutput.ReadToEnd();
  201. error = process.StandardError.ReadToEnd();
  202. process.WaitForExit();
  203. return process.ExitCode;
  204. }
  205. private static int ProcessUsingSimpleSceneSerializer(string relativeAssetPath, string outputJsonPath, out string output, out string error)
  206. {
  207. SceneParser.Process(relativeAssetPath, outputJsonPath, out output, out error);
  208. return error == null ? 0 : 1;
  209. }
  210. private List<string> FilterAssets(List<string> assetPaths)
  211. {
  212. if (_settings == null)
  213. {
  214. UnityEngine.Debug.LogWarning("ProjectExporterSettings not found. Skipping filtering.");
  215. return assetPaths;
  216. }
  217. var ignoredFolders = _settings.FoldersToIgnore;
  218. var ignoredExtensions = _settings.FileExtensionsToIgnore.Select(ext => ext.StartsWith(".") ? ext : "." + ext).ToList();
  219. var ignoredUnityTypes = _settings.UnityTypesToIgnore;
  220. var filteredList = new List<string>();
  221. foreach (var path in assetPaths)
  222. {
  223. if (ignoredFolders.Any(folder => path.StartsWith(folder, StringComparison.OrdinalIgnoreCase)))
  224. {
  225. continue;
  226. }
  227. var extension = Path.GetExtension(path);
  228. if (ignoredExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
  229. {
  230. continue;
  231. }
  232. var assetPathForTypeCheck = path.EndsWith(".meta") ? path[..^5] : path;
  233. var assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPathForTypeCheck);
  234. if (assetType != null && IsTypeIgnored(assetType, ignoredUnityTypes))
  235. {
  236. continue;
  237. }
  238. filteredList.Add(path);
  239. }
  240. return filteredList;
  241. }
  242. private bool IsTypeIgnored(Type assetType, List<IgnoredUnityType> ignoredTypes)
  243. {
  244. foreach (var ignoredType in ignoredTypes)
  245. {
  246. if (ignoredType.assetType == UnityAssetType.Custom)
  247. {
  248. if (!string.IsNullOrEmpty(ignoredType.customType) && assetType.Name.Equals(ignoredType.customType, StringComparison.OrdinalIgnoreCase))
  249. {
  250. return true;
  251. }
  252. }
  253. else if (GetSystemTypeForEnum(ignoredType.assetType) == assetType)
  254. {
  255. return true;
  256. }
  257. }
  258. return false;
  259. }
  260. private Type GetSystemTypeForEnum(UnityAssetType unityAssetType)
  261. {
  262. switch (unityAssetType)
  263. {
  264. case UnityAssetType.Animation: return typeof(AnimationClip);
  265. case UnityAssetType.AnimatorController: return typeof(AnimatorController);
  266. case UnityAssetType.AnimatorOverrideController: return typeof(AnimatorOverrideController);
  267. case UnityAssetType.AudioClip: return typeof(AudioClip);
  268. case UnityAssetType.AudioMixer: return typeof(AudioMixer);
  269. case UnityAssetType.ComputeShader: return typeof(ComputeShader);
  270. case UnityAssetType.Font: return typeof(Font);
  271. case UnityAssetType.GUISkin: return typeof(GUISkin);
  272. case UnityAssetType.Material: return typeof(Material);
  273. case UnityAssetType.Mesh: return typeof(Mesh);
  274. case UnityAssetType.Model: return typeof(GameObject);
  275. case UnityAssetType.PhysicMaterial: return typeof(PhysicMaterial);
  276. case UnityAssetType.Prefab: return typeof(GameObject);
  277. case UnityAssetType.Scene: return typeof(SceneAsset);
  278. case UnityAssetType.Script: return typeof(MonoScript);
  279. case UnityAssetType.Shader: return typeof(Shader);
  280. case UnityAssetType.Sprite: return typeof(Sprite);
  281. case UnityAssetType.Texture: return typeof(Texture2D);
  282. case UnityAssetType.VideoClip: return typeof(VideoClip);
  283. case UnityAssetType.RenderTexture: return typeof(RenderTexture);
  284. case UnityAssetType.LightmapParameters: return typeof(LightmapParameters);
  285. default: return null;
  286. }
  287. }
  288. // Recursively collects the paths of all selected assets.
  289. private void CollectSelectedAssets(AssetModel node, List<AssetModel> selectedAssets)
  290. {
  291. // If the node itself is a file and is selected, add it.
  292. if (node.Children.Count == 0 && node.IsSelected)
  293. {
  294. selectedAssets.Add(node);
  295. }
  296. // Recurse into children
  297. foreach (var child in node.Children)
  298. {
  299. CollectSelectedAssets(child, selectedAssets);
  300. }
  301. }
  302. }
  303. }