-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
187 lines (159 loc) · 6.16 KB
/
Copy pathmain.py
File metadata and controls
187 lines (159 loc) · 6.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import argparse
import sys
import traceback
from datetime import datetime, timezone
from pathlib import Path
from typing import cast
from UnityPy import Environment
from UnityPy.classes import TextAsset, Texture2D
from UnityPy.tools.extractor import exportTextAsset, exportTexture2D
APP_NAME = "QuickExtractSpineAssets"
def show_message_dialog(title: str, message: str, *, icon: int = 0x40) -> None:
"""Show a native Windows dialog; fall back to stderr elsewhere.
icon: MB_ICONERROR (0x10), MB_ICONWARNING (0x30), MB_ICONINFORMATION (0x40)
"""
if sys.platform == "win32":
try:
import ctypes
ctypes.windll.user32.MessageBoxW(0, message, title, icon)
return
except Exception:
pass
print(f"{title}: {message}", file=sys.stderr)
def write_run_error_file(
failures: list[tuple[Path, BaseException, str]],
) -> Path | None:
"""Write one error log for the whole run next to a target file. Skip if unavailable."""
stamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
parts = [
f"{APP_NAME} error\n",
f"Time: {stamp}\n",
f"Failures: {len(failures)}\n\n",
]
for bundle_file, error, tb in failures:
parts.append(f"File: {bundle_file}\n")
parts.append(f"{type(error).__name__}: {format_exception_message(error)}\n\n")
parts.append(f"{tb}\n")
parts.append("---\n\n")
content = "".join(parts)
for bundle_file, _, _ in failures:
error_path = bundle_file.parent / f"{APP_NAME}.error.txt"
if not error_path.parent.exists():
continue
try:
error_path.write_text(content, encoding="utf-8")
return error_path
except OSError:
continue
return None
def safe_load_unitypy(file: str | Path, environment: Environment | None = None) -> Environment:
"""Safely load Unity bundle file with fallback for corrupted files."""
env: Environment | None = environment
if not env:
env = Environment()
file = Path(file)
file_bytes = file.read_bytes()
try:
env.load_file(file_bytes, name=file.name, parent=env)
return env
except Exception:
for i in range(1, 100):
try:
env.load_file(file_bytes[:-i], name=file.name, parent=env)
return env
except Exception:
continue
raise RuntimeError(f"cannot load {file}")
def extract_bundle(bundle_file: str | Path) -> int:
"""Extract Spine assets from a bundle. Returns the number of assets exported."""
bundle_file_path = Path(bundle_file).resolve()
env = safe_load_unitypy(bundle_file_path)
exported = 0
for obj in env.objects:
if obj.container:
container = cast(str, obj.container)
if ".png" in container.lower():
filename = Path(container).name.split(".")[0]
exportTexture2D(
cast(Texture2D, obj),
str(bundle_file_path.parent / filename),
".png",
)
exported += 1
if ".skel" in container.lower():
filename = Path(container).name.split(".")[0]
exportTextAsset(
cast(TextAsset, obj),
str(bundle_file_path.parent / filename),
".skel",
)
exported += 1
if ".atlas" in container.lower():
filename = Path(container).name.split(".")[0]
exportTextAsset(
cast(TextAsset, obj),
str(bundle_file_path.parent / filename),
".atlas",
)
exported += 1
return exported
def format_exception_message(exc: BaseException) -> str:
"""Human-readable exception text (single backslashes in Windows paths)."""
if isinstance(exc, OSError) and exc.filename is not None:
errno_part = f"[Errno {exc.errno}] " if exc.errno is not None else ""
detail = exc.strerror or type(exc).__name__
return f'{errno_part}{detail}: "{exc.filename}"'
return str(exc)
def main(bundle_files: list[str]) -> int:
failures: list[tuple[Path, BaseException, str]] = []
total_exported = 0
empty_files: list[Path] = []
for bundle_file in bundle_files:
bundle_file_path = Path(bundle_file).resolve()
try:
exported = extract_bundle(bundle_file_path)
total_exported += exported
if exported == 0:
empty_files.append(bundle_file_path)
except Exception as exc:
failures.append((bundle_file_path, exc, traceback.format_exc()))
if failures:
error_path = write_run_error_file(failures)
lines = [f"Failed to extract {len(failures)} of {len(bundle_files)} file(s):\n"]
for bundle_path, exc, _ in failures:
lines.append(f"- {bundle_path.name}: {format_exception_message(exc)}")
if error_path is not None:
lines.append(f"\nDetails: {error_path}")
show_message_dialog(f"{APP_NAME} — Error", "\n".join(lines), icon=0x10)
return 1
if total_exported == 0:
names = "\n".join(f"• {path.name}" for path in empty_files)
show_message_dialog(
f"{APP_NAME} — No assets found",
"No extractable Spine assets (.png / .skel / .atlas) were found in:\n\n"
f"{names}",
icon=0x40,
)
return 0
return 0
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Extract Spine .png / .skel / .atlas assets from Unity .bundle files"
)
parser.add_argument(
"bundle_files",
nargs="*",
help="Path(s) to Unity .bundle file(s)",
)
args = parser.parse_args()
if not args.bundle_files:
show_message_dialog(
f"{APP_NAME} — Usage",
"No file selected.\n\n"
"Right-click a .bundle file and choose Quick Extract,\n"
"or run:\n"
f'{APP_NAME}.exe "path\\to\\file.bundle"',
icon=0x40,
)
raise SystemExit(2)
raise SystemExit(main(args.bundle_files))