convert_scene.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. import yaml
  2. import json
  3. import re
  4. import sys
  5. import argparse
  6. import os
  7. # Regex to capture the type ID and anchor ID from the document separator
  8. header_pattern = re.compile(r"--- !u!(\d+) &(\S+)")
  9. # Regex to find and remove the tags for the parser
  10. tag_remover_pattern = re.compile(r"!u!\d+\s")
  11. def preprocess_unity_yaml(yaml_content):
  12. """
  13. Preprocesses Unity YAML content to handle various edge cases that can break the parser.
  14. """
  15. lines = yaml_content.split('\n')
  16. processed_lines = []
  17. in_document = False
  18. for i, line in enumerate(lines):
  19. # Check if we're starting a new document
  20. if line.startswith('---'):
  21. in_document = True
  22. processed_lines.append(line)
  23. continue
  24. # Skip empty lines and comments
  25. if not line.strip() or line.strip().startswith('#'):
  26. processed_lines.append(line)
  27. continue
  28. if in_document:
  29. # Handle the case where a key starts at column 0 but should be indented
  30. # This often happens with Unity components like RectTransform, Transform, etc.
  31. if ':' in line and not line.startswith(' ') and not line.startswith('\t'):
  32. # Check if the previous line was a document separator or another component
  33. if i > 0 and not lines[i-1].startswith('---'):
  34. # Check if this looks like a Unity component name
  35. component_match = re.match(r'^([A-Z][a-zA-Z0-9]*):$', line.strip())
  36. if component_match:
  37. # This is likely a component that should be a key under the main object
  38. processed_lines.append(f" {line.strip()}")
  39. continue
  40. # Handle empty key issue (:: or just :)
  41. if line.strip().startswith(':') and 'Any' in line:
  42. processed_lines.append(line.replace(':', 'key_for_any:'))
  43. continue
  44. # Handle cases where there might be invalid indentation after colons
  45. if ':' in line and not line.strip().endswith(':'):
  46. # Check for malformed key-value pairs
  47. parts = line.split(':', 1)
  48. if len(parts) == 2 and parts[1].strip() == '':
  49. # This is a key with no value, which is fine in YAML
  50. processed_lines.append(line)
  51. continue
  52. processed_lines.append(line)
  53. return '\n'.join(processed_lines)
  54. def convert_unity_yaml_to_json(yaml_content, whitelist=None):
  55. """
  56. Parses a Unity YAML file string, preserving fileID references, and returns a JSON string.
  57. """
  58. json_data = []
  59. whitelist_set = None
  60. if whitelist is not None:
  61. # If whitelist is an empty string, create an empty set, meaning nothing is whitelisted.
  62. # Otherwise, split the string to create the set of whitelisted components.
  63. whitelist_set = set(whitelist.split(',')) if whitelist else set()
  64. # First, find all the original headers
  65. headers = header_pattern.findall(yaml_content)
  66. # Remove the problematic tags from the content
  67. sanitized_content = tag_remover_pattern.sub("", yaml_content)
  68. # Apply additional preprocessing to handle Unity-specific YAML issues
  69. preprocessed_content = preprocess_unity_yaml(sanitized_content)
  70. try:
  71. # Try to parse with safe_load_all
  72. documents = list(yaml.safe_load_all(preprocessed_content))
  73. except yaml.YAMLError as e:
  74. print(f"YAML parsing error: {e}", file=sys.stderr)
  75. print("Attempting to parse each document separately...", file=sys.stderr)
  76. # If that fails, try to split by document separators and parse each separately
  77. document_parts = re.split(r'\n---[^\n]*\n', preprocessed_content)
  78. documents = []
  79. for i, part in enumerate(document_parts):
  80. if not part.strip():
  81. continue
  82. try:
  83. # Add a temporary document separator for parsing
  84. if i > 0: # Skip the first part which might not need a separator
  85. part = '---\n' + part
  86. doc = yaml.safe_load(part)
  87. if doc is not None:
  88. documents.append(doc)
  89. except yaml.YAMLError as e2:
  90. print(f"Failed to parse document {i}: {e2}", file=sys.stderr)
  91. print(f"Document content preview: {part[:200]}...", file=sys.stderr)
  92. # Skip this document and continue
  93. continue
  94. # Filter out None documents and empty string documents
  95. documents = [doc for doc in documents if doc is not None and doc != '']
  96. # Remove the first document if it's just file info
  97. if documents and isinstance(documents[0], str) and 'YAML' in documents[0]:
  98. documents.pop(0)
  99. if len(headers) != len(documents):
  100. print(f"Warning: Mismatch between headers found ({len(headers)}) and documents parsed ({len(documents)}).", file=sys.stderr)
  101. print(f"Headers: {len(headers)}, Documents: {len(documents)}", file=sys.stderr)
  102. # Match documents with their headers
  103. for i, doc in enumerate(documents):
  104. if i < len(headers):
  105. type_id, anchor_id = headers[i]
  106. component_doc = doc
  107. # Check against whitelist if it has been initialized (is not None)
  108. if whitelist_set is not None and isinstance(doc, dict):
  109. component_name = next(iter(doc), None)
  110. if component_name and component_name not in whitelist_set:
  111. # If not in whitelist, replace data with an empty object
  112. component_doc = {component_name: {}}
  113. structured_doc = {
  114. 'type_id': type_id,
  115. 'anchor_id': anchor_id,
  116. 'data': component_doc
  117. }
  118. json_data.append(structured_doc)
  119. else:
  120. # Append any extra docs without headers (should be rare in Unity files)
  121. json_data.append({'data': doc})
  122. # Use compact encoding for the final JSON
  123. return json.dumps(json_data, separators=(',', ':')) # Use most compact encoding
  124. def main():
  125. parser = argparse.ArgumentParser(description='Convert Unity YAML assets to JSON.')
  126. parser.add_argument('input_path', type=str, help='Absolute path to the input Unity asset file.')
  127. parser.add_argument('output_path', type=str, help='Absolute path for the output JSON file.')
  128. parser.add_argument('--whitelist', type=str, help='Comma-separated list of component types to include.')
  129. parser.add_argument('--debug', action='store_true', help='Enable debug output')
  130. args = parser.parse_args()
  131. input_path = args.input_path
  132. output_path = args.output_path
  133. try:
  134. # Ensure the output directory exists
  135. output_dir = os.path.dirname(output_path)
  136. if not os.path.exists(output_dir):
  137. os.makedirs(output_dir)
  138. with open(input_path, 'r', encoding='utf-8') as f:
  139. content = f.read()
  140. if args.debug:
  141. print(f"Input file size: {len(content)} characters", file=sys.stderr)
  142. print(f"First 500 characters:\n{content[:500]}", file=sys.stderr)
  143. json_output = convert_unity_yaml_to_json(content, args.whitelist)
  144. with open(output_path, 'w', encoding='utf-8') as f:
  145. f.write(json_output)
  146. print(f"Successfully converted '{input_path}' to '{output_path}'")
  147. except Exception as e:
  148. print(f"An error occurred: {e}", file=sys.stderr)
  149. if args.debug:
  150. import traceback
  151. traceback.print_exc()
  152. sys.exit(1)
  153. if __name__ == "__main__":
  154. main()