extract_high_level.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. import argparse
  2. import os
  3. import sys
  4. import json
  5. from pathlib import Path
  6. # Add the utils directory to the Python path
  7. # This allows importing modules from the 'utils' subfolder
  8. utils_path = Path(__file__).parent / 'utils'
  9. sys.path.append(str(utils_path))
  10. from yaml_utils import load_unity_yaml, convert_to_plain_python_types
  11. from file_utils import find_files_by_extension, create_guid_to_path_map
  12. def parse_physics_settings(input_dir, project_mode):
  13. """
  14. Parses the appropriate physics settings file based on the project mode.
  15. """
  16. physics_data = {}
  17. if project_mode == "3D":
  18. asset_path = input_dir / "ProjectSettings" / "DynamicsManager.asset"
  19. if asset_path.is_file():
  20. docs = load_unity_yaml(str(asset_path))
  21. if docs:
  22. settings = convert_to_plain_python_types(docs[0]).get('PhysicsManager', {})
  23. physics_data['gravity'] = settings.get('m_Gravity')
  24. physics_data['sleepThreshold'] = settings.get('m_SleepThreshold')
  25. physics_data['solverType'] = settings.get('m_SolverType')
  26. physics_data['layerCollisionMatrix'] = settings.get('m_LayerCollisionMatrix')
  27. physics_data['autoSimulation'] = settings.get('m_AutoSimulation')
  28. physics_data['autoSyncTransforms'] = settings.get('m_AutoSyncTransforms')
  29. else: # 2D
  30. asset_path = input_dir / "ProjectSettings" / "Physics2DSettings.asset"
  31. if asset_path.is_file():
  32. docs = load_unity_yaml(str(asset_path))
  33. if docs:
  34. settings = convert_to_plain_python_types(docs[0]).get('Physics2DSettings', {})
  35. physics_data['gravity'] = settings.get('m_Gravity')
  36. physics_data['velocityIterations'] = settings.get('m_VelocityIterations')
  37. physics_data['positionIterations'] = settings.get('m_PositionIterations')
  38. physics_data['layerCollisionMatrix'] = settings.get('m_LayerCollisionMatrix')
  39. physics_data['autoSimulation'] = settings.get('m_AutoSimulation')
  40. physics_data['autoSyncTransforms'] = settings.get('m_AutoSyncTransforms')
  41. return physics_data
  42. def parse_project_settings(input_dir, output_dir):
  43. """
  44. Parses various project settings files to create a comprehensive manifest.
  45. """
  46. print("\n--- Starting Task 2: Comprehensive Project Settings Parser ---")
  47. manifest_data = {}
  48. guid_map = create_guid_to_path_map(str(input_dir))
  49. # --- ProjectSettings.asset ---
  50. project_settings_path = input_dir / "ProjectSettings" / "ProjectSettings.asset"
  51. if project_settings_path.is_file():
  52. docs = load_unity_yaml(str(project_settings_path))
  53. if docs:
  54. player_settings = convert_to_plain_python_types(docs[0]).get('PlayerSettings', {})
  55. manifest_data['productName'] = player_settings.get('productName')
  56. manifest_data['companyName'] = player_settings.get('companyName')
  57. manifest_data['bundleVersion'] = player_settings.get('bundleVersion')
  58. manifest_data['activeColorSpace'] = player_settings.get('m_ActiveColorSpace')
  59. # --- Mappers for human-readable values ---
  60. scripting_backend_map = {0: "Mono", 1: "IL2CPP"}
  61. api_compatibility_map = {3: ".NET Framework", 6: ".NET Standard 2.1"}
  62. # --- Extract and map platform-specific settings ---
  63. scripting_backends = player_settings.get('scriptingBackend', {})
  64. manifest_data['scriptingBackend'] = {
  65. platform: scripting_backend_map.get(val, f"Unknown ({val})")
  66. for platform, val in scripting_backends.items()
  67. }
  68. api_levels = player_settings.get('apiCompatibilityLevelPerPlatform', {})
  69. manifest_data['apiCompatibilityLevel'] = {
  70. platform: api_compatibility_map.get(val, f"Unknown ({val})")
  71. for platform, val in api_levels.items()
  72. }
  73. # Fallback for older Unity versions that use a single key
  74. if not api_levels and 'apiCompatibilityLevel' in player_settings:
  75. val = player_settings.get('apiCompatibilityLevel')
  76. manifest_data['apiCompatibilityLevel']['Standalone'] = api_compatibility_map.get(val, f"Unknown ({val})")
  77. manifest_data['activeInputHandler'] = player_settings.get('activeInputHandler')
  78. manifest_data['allowUnsafeCode'] = player_settings.get('allowUnsafeCode')
  79. manifest_data['managedStrippingLevel'] = player_settings.get('managedStrippingLevel')
  80. manifest_data['scriptingDefineSymbols'] = player_settings.get('scriptingDefineSymbols')
  81. # --- Deduce configured platforms from various settings ---
  82. configured_platforms = set()
  83. if 'applicationIdentifier' in player_settings:
  84. configured_platforms.update(player_settings['applicationIdentifier'].keys())
  85. if 'scriptingBackend' in player_settings:
  86. configured_platforms.update(player_settings['scriptingBackend'].keys())
  87. manifest_data['configuredPlatforms'] = sorted(list(configured_platforms))
  88. # --- Filter managedStrippingLevel based on configured platforms ---
  89. managed_stripping_level = player_settings.get('managedStrippingLevel', {})
  90. manifest_data['managedStrippingLevel'] = {
  91. platform: level
  92. for platform, level in managed_stripping_level.items()
  93. if platform in manifest_data['configuredPlatforms']
  94. }
  95. # --- Populate all configured platforms for scripting settings ---
  96. default_api_level = player_settings.get('apiCompatibilityLevel')
  97. final_scripting_backends = {}
  98. final_api_levels = {}
  99. for platform in manifest_data['configuredPlatforms']:
  100. # Scripting Backend (Default to Mono if not specified)
  101. backend_val = scripting_backends.get(platform, 0)
  102. final_scripting_backends[platform] = scripting_backend_map.get(backend_val, f"Unknown ({backend_val})")
  103. # API Compatibility Level (Default to project's global setting if not specified)
  104. level_val = api_levels.get(platform, default_api_level)
  105. final_api_levels[platform] = api_compatibility_map.get(level_val, f"Unknown ({level_val})")
  106. manifest_data['scriptingBackend'] = final_scripting_backends
  107. manifest_data['apiCompatibilityLevel'] = final_api_levels
  108. # --- EditorSettings.asset for 2D/3D Mode ---
  109. editor_settings_path = input_dir / "ProjectSettings" / "EditorSettings.asset"
  110. if editor_settings_path.is_file():
  111. docs = load_unity_yaml(str(editor_settings_path))
  112. if docs:
  113. editor_settings = convert_to_plain_python_types(docs[0]).get('EditorSettings', {})
  114. manifest_data['projectMode'] = "2D" if editor_settings.get('m_DefaultBehaviorMode') == 1 else "3D"
  115. # --- GraphicsSettings.asset for Render Pipeline ---
  116. graphics_settings_path = input_dir / "ProjectSettings" / "GraphicsSettings.asset"
  117. manifest_data['renderPipeline'] = 'Built-in'
  118. if graphics_settings_path.is_file():
  119. docs = load_unity_yaml(str(graphics_settings_path))
  120. if docs:
  121. graphics_settings = convert_to_plain_python_types(docs[0]).get('GraphicsSettings', {})
  122. pipeline_ref = graphics_settings.get('m_CustomRenderPipeline') or graphics_settings.get('m_SRPDefaultSettings', {}).get('UnityEngine.Rendering.Universal.UniversalRenderPipeline')
  123. if pipeline_ref and pipeline_ref.get('guid'):
  124. guid = pipeline_ref['guid']
  125. if guid in guid_map:
  126. asset_path = Path(guid_map[guid]).name.upper()
  127. if "URP" in asset_path: manifest_data['renderPipeline'] = 'URP'
  128. elif "HDRP" in asset_path: manifest_data['renderPipeline'] = 'HDRP'
  129. else: manifest_data['renderPipeline'] = 'Scriptable'
  130. # --- TagManager.asset ---
  131. tag_manager_path = input_dir / "ProjectSettings" / "TagManager.asset"
  132. if tag_manager_path.is_file():
  133. docs = load_unity_yaml(str(tag_manager_path))
  134. if docs:
  135. tag_manager = convert_to_plain_python_types(docs[0]).get('TagManager', {})
  136. manifest_data['tags'] = tag_manager.get('tags')
  137. layers_list = tag_manager.get('layers', [])
  138. # Only include layers that have a name, preserving their index
  139. manifest_data['layers'] = {i: name for i, name in enumerate(layers_list) if name}
  140. # --- EditorBuildSettings.asset ---
  141. build_settings_path = input_dir / "ProjectSettings" / "EditorBuildSettings.asset"
  142. if build_settings_path.is_file():
  143. docs = load_unity_yaml(str(build_settings_path))
  144. if docs:
  145. build_settings = convert_to_plain_python_types(docs[0]).get('EditorBuildSettings', {})
  146. manifest_data['buildScenes'] = [
  147. {'path': scene.get('path'), 'enabled': scene.get('enabled') == 1}
  148. for scene in build_settings.get('m_Scenes', [])
  149. ]
  150. # --- TimeManager.asset ---
  151. time_manager_path = input_dir / "ProjectSettings" / "TimeManager.asset"
  152. if time_manager_path.is_file():
  153. docs = load_unity_yaml(str(time_manager_path))
  154. if docs:
  155. time_manager = convert_to_plain_python_types(docs[0]).get('TimeManager', {})
  156. # Cherry-pick only the useful time settings
  157. manifest_data['timeSettings'] = {
  158. 'Fixed Timestep': time_manager.get('Fixed Timestep'),
  159. 'Maximum Allowed Timestep': time_manager.get('Maximum Allowed Timestep'),
  160. 'm_TimeScale': time_manager.get('m_TimeScale'),
  161. 'Maximum Particle Timestep': time_manager.get('Maximum Particle Timestep')
  162. }
  163. # --- Physics Settings ---
  164. manifest_data['physicsSettings'] = parse_physics_settings(input_dir, manifest_data.get('projectMode', '3D'))
  165. # --- Write manifest.json ---
  166. manifest_output_path = output_dir / "manifest.json"
  167. try:
  168. with open(manifest_output_path, 'w', encoding='utf-8') as f:
  169. json.dump(manifest_data, f, separators=(',', ':'))
  170. print(f"Successfully created manifest.json at {manifest_output_path}")
  171. except IOError as e:
  172. print(f"Error writing to {manifest_output_path}. {e}", file=sys.stderr)
  173. def parse_package_manifests(input_dir, output_dir):
  174. """
  175. Parses the primary package manifest and creates a clean packages.json file.
  176. """
  177. print("\n--- Starting Task 3: Package Manifest Extractor ---")
  178. manifest_path = input_dir / "Packages" / "manifest.json"
  179. if manifest_path.is_file():
  180. try:
  181. with open(manifest_path, 'r', encoding='utf-8') as f:
  182. packages_data = json.load(f)
  183. packages_output_path = output_dir / "packages.json"
  184. with open(packages_output_path, 'w', encoding='utf-8') as f:
  185. json.dump(packages_data, f, separators=(',', ':')) # Compact output
  186. print(f"Successfully created packages.json at {packages_output_path}")
  187. except (IOError, json.JSONDecodeError) as e:
  188. print(f"Error processing {manifest_path}: {e}", file=sys.stderr)
  189. else:
  190. print(f"Warning: {manifest_path} not found.")
  191. def generate_guid_mappers(input_dir, output_dir):
  192. """
  193. Finds all .meta files and generates JSON files mapping GUIDs to asset paths.
  194. """
  195. print("\n--- Starting Task 4: GUID Mapper Generator ---")
  196. assets_dir = input_dir / "Assets"
  197. if not assets_dir.is_dir():
  198. print(f"Error: 'Assets' directory not found in '{input_dir}'", file=sys.stderr)
  199. return
  200. meta_files = find_files_by_extension(str(assets_dir), '.meta')
  201. print(f"Found {len(meta_files)} .meta files to process.")
  202. asset_type_map = {
  203. '.prefab': 'prefabs', '.unity': 'scenes', '.mat': 'materials',
  204. '.cs': 'scripts', '.png': 'textures', '.jpg': 'textures',
  205. '.jpeg': 'textures', '.asset': 'scriptable_objects',
  206. }
  207. guid_maps = {value: {} for value in asset_type_map.values()}
  208. guid_maps['others'] = {}
  209. for meta_file_path_str in meta_files:
  210. meta_file_path = Path(meta_file_path_str)
  211. asset_file_path = Path(meta_file_path_str.rsplit('.meta', 1)[0])
  212. # THE FIX: Ensure that the corresponding path is a file, not a directory
  213. if not asset_file_path.is_file():
  214. continue
  215. guid = None
  216. try:
  217. with open(meta_file_path, 'r', encoding='utf-8') as f:
  218. for line in f:
  219. if line.strip().startswith('guid:'):
  220. guid = line.strip().split(':')[1].strip()
  221. break
  222. except Exception as e:
  223. print(f"Warning: Could not read or parse guid from {meta_file_path}. {e}", file=sys.stderr)
  224. continue
  225. if guid:
  226. asset_ext = asset_file_path.suffix.lower()
  227. asset_type = asset_type_map.get(asset_ext, 'others')
  228. relative_path = asset_file_path.relative_to(input_dir).as_posix()
  229. guid_maps[asset_type][guid] = relative_path
  230. mappers_dir = output_dir / "GuidMappers"
  231. try:
  232. mappers_dir.mkdir(parents=True, exist_ok=True)
  233. for asset_type, guid_map in guid_maps.items():
  234. if guid_map:
  235. output_path = mappers_dir / f"{asset_type}.json"
  236. with open(output_path, 'w', encoding='utf-8') as f:
  237. json.dump(guid_map, f, separators=(',', ':')) # Compact output
  238. print(f"Successfully created GUID mappers in {mappers_dir}")
  239. except OSError as e:
  240. print(f"Error: Could not create GUID mapper directory or files. {e}", file=sys.stderr)
  241. def main():
  242. """
  243. Main function to run the high-level data extraction process.
  244. """
  245. parser = argparse.ArgumentParser(
  246. description="Extracts high-level summary data from a Unity project."
  247. )
  248. parser.add_argument("--input", type=str, required=True, help="The root directory of the target Unity project.")
  249. parser.add_argument("--output", type=str, required=True, help="The directory where the generated output folder will be saved.")
  250. args = parser.parse_args()
  251. input_dir = Path(args.input)
  252. output_dir = Path(args.output)
  253. if not input_dir.is_dir():
  254. print(f"Error: Input path '{input_dir}' is not a valid directory.", file=sys.stderr)
  255. sys.exit(1)
  256. high_level_output_dir = output_dir / "HighLevel"
  257. try:
  258. high_level_output_dir.mkdir(parents=True, exist_ok=True)
  259. print(f"Output will be saved to: {high_level_output_dir}")
  260. except OSError as e:
  261. print(f"Error: Could not create output directory '{high_level_output_dir}'. {e}", file=sys.stderr)
  262. sys.exit(1)
  263. parse_project_settings(input_dir, high_level_output_dir)
  264. parse_package_manifests(input_dir, high_level_output_dir)
  265. generate_guid_mappers(input_dir, high_level_output_dir)
  266. print("\nHigh-level extraction complete.")
  267. if __name__ == "__main__":
  268. main()