Skip to content

Commit 0454144

Browse files
committed
1.5.2
new release for UserUnknownFactor's PRs examples
1 parent b7efee2 commit 0454144

9 files changed

Lines changed: 372 additions & 4 deletions

File tree

‎README.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,8 +144,9 @@ Some games save binary data as TextFile, so it's usually better to use ``.script
144144

145145
### [MonoBehaviour](UnityPy/classes/MonoBehaviour.py)
146146

147-
MonoBehaviour assets are usually binary data that has to be decoded.
148-
(e.g. via msgpack, protobuf, kaitaistruct etc)
147+
MonoBehaviour assets are usually used to save the class instances with their values.
148+
If a type tree exists it can be used to read the whole data,
149+
but if it doesn't, then it is usually necessary to investigate the class that loads the specific MonoBehaviour to extract the data.
149150

150151
* ``.name``
151152
* ``.script``- binary data (bytes)

‎UnityPy/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
__version__ = "1.5.1"
1+
__version__ = "1.5.2"
22

33
from .environment import Environment
44

‎UnityPy/classes/MonoBehaviour.py‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,16 @@ def __init__(self, reader):
88
self.script = PPtr(reader)
99
self.name = reader.read_aligned_string()
1010

11-
self.read_type_tree()
11+
if self.assets_file._enable_type_tree:
12+
self.read_type_tree()
13+
self._raw_offset = reader.Position
14+
15+
@property
16+
def raw_data(self) -> bytes:
17+
"""
18+
Reads the undocumentated data following the default init.
19+
This is usefull for classes that are stored via MonoBehaviours.
20+
"""
21+
reader = self.reader
22+
reader.Position = self._raw_offset
23+
return reader.read_bytes(reader.byte_size - (self._raw_offset - reader.byte_start))

‎examples/AssetBatchConverter.py‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
import os
2+
from UnityPy import AssetsManager
3+
from collections import Counter
4+
import zipfile
5+
6+
TYPES = ['Sprite', 'Texture2D', 'TextAsset']
7+
8+
ROOT = os.path.dirname(os.path.realpath(__file__))
9+
10+
# source folder
11+
ASSETS = os.path.join(ROOT, 'assets')
12+
# destination folder
13+
DST = os.path.join(ROOT, 'extracted')
14+
# number of dirs to ignore
15+
# e.g. IGNOR_DIR_COUNT = 2 will reduce
16+
# 'assets/assetbundles/images/story_picture/small/15.png'
17+
# to
18+
# 'images/story_picture/small/15.png'
19+
20+
IGNOR_DIR_COUNT = 2
21+
22+
os.makedirs(DST, exist_ok=True)
23+
24+
25+
def main():
26+
for root, dirs, files in os.walk(ASSETS, topdown=False):
27+
if '.git' in root:
28+
continue
29+
for f in files:
30+
print(f)
31+
extension = os.path.splitext(f)[1]
32+
src = os.path.realpath(os.path.join(root, f))
33+
34+
if extension == ".zip":
35+
archive = zipfile.ZipFile(src, 'r')
36+
for zf in archive.namelist():
37+
extract_assets(archive.open(zf))
38+
else:
39+
extract_assets(src)
40+
41+
42+
def extract_assets(src):
43+
# load source
44+
am = AssetsManager(src)
45+
46+
# iterate over assets
47+
for asset in am.assets.values():
48+
# assets without container / internal path will be ignored for now
49+
if not asset.container:
50+
continue
51+
52+
# check which mode we will have to use
53+
num_cont = sum(1 for obj in asset.container.values() if obj.type in TYPES)
54+
num_objs = sum(1 for obj in asset.objects.values() if obj.type in TYPES)
55+
56+
# check if container contains all important assets, if yes, just ignore the container
57+
if num_objs <= num_cont * 2:
58+
for asset_path, obj in asset.container.items():
59+
fp = os.path.join(DST, *asset_path.split('/')[IGNOR_DIR_COUNT:])
60+
export_obj(obj, fp)
61+
62+
# otherwise use the container to generate a path for the normal objects
63+
else:
64+
extracted = []
65+
# find the most common path
66+
occurence_count = Counter(os.path.splitext(asset_path)[0] for asset_path in asset.container.keys())
67+
local_path = os.path.join(DST, *occurence_count.most_common(1)[0][0].split('/')[IGNOR_DIR_COUNT:])
68+
69+
for obj in asset.objects.values():
70+
if obj.path_id not in extracted:
71+
extracted.extend(export_obj(obj, local_path, append_name=True))
72+
73+
74+
def export_obj(obj, fp: str, append_name: bool = False) -> list:
75+
if obj.type not in TYPES:
76+
return []
77+
data = obj.read()
78+
if append_name:
79+
fp = os.path.join(fp, data.name)
80+
81+
fp, extension = os.path.splitext(fp)
82+
os.makedirs(os.path.dirname(fp), exist_ok=True)
83+
84+
if obj.type == 'TextAsset':
85+
if not extension:
86+
extension = '.txt'
87+
with open(f"{fp}{extension}", 'wb') as f:
88+
f.write(data.script)
89+
90+
elif obj.type == "Sprite":
91+
extension = ".png"
92+
data.image.save(f"{fp}{extension}")
93+
94+
return [obj.path_id, data.m_RD.texture.path_id, getattr(data.m_RD.alphaTexture, 'path_id', None)]
95+
96+
elif obj.type == "Texture2D":
97+
extension = ".png"
98+
fp = f"{fp}{extension}"
99+
if not os.path.exists(fp):
100+
try:
101+
data.image.save(fp)
102+
except EOFError:
103+
pass
104+
105+
return [obj.path_id]
106+
107+
108+
if __name__ == '__main__':
109+
main()

‎examples/AssetPatch/522608825‎

930 KB
Binary file not shown.

‎examples/AssetPatch/patch.py‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import json
2+
import os
3+
import time
4+
import UnityPy
5+
from googletrans import Translator
6+
7+
root = os.path.dirname(os.path.realpath(__file__))
8+
9+
def main():
10+
# load the original japanese localisation
11+
src = os.path.join(root, "522608825")
12+
e = UnityPy.load(src)
13+
# iterate over all localisation assets
14+
for cont, obj in e.container.items():
15+
# read the asset data
16+
data = obj.read()
17+
# get the localisation data
18+
script = json.loads(bytes(data.script)) # bytes wrapper to handle memoryview
19+
if hasattr(script, "infos"):
20+
continue
21+
print(data.name)
22+
# translate the localisation
23+
for entry in script["infos"]:
24+
entry["value"] = translate(entry["value"])
25+
# overwrite the original
26+
data.script = json.dumps(
27+
script,
28+
ensure_ascii=False, indent=4
29+
).encode("utf8")
30+
# apply the changes
31+
data.save()
32+
33+
# save the modified Bundle as file
34+
with open(os.path.join(root, "522608825_patched"), "wb") as f:
35+
f.write(e.file.save())
36+
37+
38+
# simple cache for already translated strings
39+
# prevents requesting the same string multiple times
40+
# therefore saving time and reducing the chance of being IP-blocked
41+
TL_CACHE = {}
42+
def translate(text):
43+
# check if the text is valid
44+
if not text.strip(" "):
45+
return text
46+
# check if the text was already translated once
47+
if text in TL_CACHE:
48+
return TL_CACHE[text]
49+
50+
# actual google translation
51+
translator = Translator(service_urls=['translate.googleapis.com'])
52+
try:
53+
ret = translator.translate(text, "en", "ja").text
54+
TL_CACHE[text] = ret
55+
return ret
56+
except json.JSONDecodeError:
57+
input("DecodeError")
58+
return translate(text)
59+
except (ConnectionError, AttributeError) as e:
60+
print(e)
61+
time.sleep(1)
62+
return translate(text)
63+
64+
if __name__ == "__main__":
65+
main()
8.46 MB
Binary file not shown.
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""
2+
This example shows how to write a custom MonoBehaviour class.
3+
4+
5+
The script is for a game that generates its encryption key based on a specific image.
6+
This image is linked to by a MonoBheaviour called "ScriptableTexture2D".
7+
It is linked to by a pointer after the default MonoBehaviour structure.
8+
This intel was acquired from the assembly of the game.
9+
10+
Unfortunately, the asset doesn't have a type-tree, so the default MonoBehaviour class can't find the pointer.
11+
So a custom MonoBehaviour class is required to get the pointer comfortably.
12+
Doing so is simple, as seen in the following code.
13+
"""
14+
15+
import os
16+
import UnityPy
17+
from UnityPy.classes import MonoBehaviour, PPtr
18+
19+
class ScriptableTexture2D(MonoBehaviour):
20+
def __init__(self, reader):
21+
# calls the default MonoBehaviour init
22+
super().__init__(reader=reader)
23+
# here goes the implementation of the extra data
24+
self.texture = PPtr(reader)
25+
26+
# set the path for the target file
27+
root = os.path.dirname(os.path.realpath(__file__))
28+
fp = os.path.join(root,"data.unity3d")
29+
30+
env = UnityPy.load(fp)
31+
32+
# find the correct asset
33+
for obj in env.objects:
34+
if obj.type == "MonoBehaviour":
35+
data = obj.read()
36+
if data.name == "ScriptableTexture2D":
37+
# correct obj found
38+
# lets read it with the custom class
39+
st = ScriptableTexture2D(obj)
40+
# read the linked image and save it
41+
tex = st.texture.read()
42+
print(st.texture.read().name)
43+
#tex.image.save(os.path.join(root, f"{tex.name}.png"))

‎examples/rebundle.py‎

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
"""
2+
This script shows how to create a bundle from dumped assets from the memory.
3+
4+
The dumped assets consist of SerializedFiles and their resources(cabs).
5+
A sample file of the original game is required for this script.
6+
This example uses the globalgamemanager as this asset should exist in all Unity games.
7+
"""
8+
9+
import os
10+
import uuid
11+
import random
12+
from copy import copy
13+
import re
14+
15+
import UnityPy
16+
from UnityPy.enums import ClassIDType
17+
from UnityPy.files import BundleFile
18+
from UnityPy.files.SerializedFile import FileIdentifier, ObjectReader, SerializedType
19+
20+
21+
SERIALIZED_PATH = "globalgamemanagers"
22+
DATA_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "data")
23+
24+
25+
def main():
26+
bf = Fake(
27+
signature="UnityFS",
28+
version=6,
29+
format=6,
30+
version_engine="2017.4.30f1",
31+
version_player="5.x.x",
32+
_class=BundleFile,
33+
files={},
34+
)
35+
# load default serialized file and prepare some variables for easier access to key objects
36+
env = UnityPy.load(SERIALIZED_PATH)
37+
sf = env.file # serialized file
38+
or_bp = list(sf.objects.values())[0].__dict__ # object data
39+
40+
bf.files["serialized_file"] = sf
41+
sf._flag = 4
42+
43+
# remove all unnesessary stuff
44+
for key in list(sf.objects.keys()):
45+
del sf.objects[key]
46+
sf.externals = []
47+
48+
# add all files from DATA_PATH
49+
for root, dirs, files in os.walk(DATA_PATH):
50+
for f in files:
51+
fp = os.path.join(root, f)
52+
if f[:3] == "CAB":
53+
add_cab(bf, sf, root, f)
54+
else:
55+
add_object(sf, fp, or_bp)
56+
57+
# save edited bundle
58+
open("bundle_edited.unity3d", "wb").write(bf.save())
59+
60+
61+
def add_cab(bf, sf, root, f):
62+
fp = os.path.join(root, f)
63+
bf.files[f] = Fake(data=open(fp, "rb").read(), _flag=4)
64+
sf.externals.append(
65+
Fake(
66+
temp_empty="",
67+
guid=generate_16_byte_uid(),
68+
path=f"archive:/{os.path.basename(root)}/{f}",
69+
type=0,
70+
_class=FileIdentifier,
71+
)
72+
)
73+
74+
75+
def add_object(sf, fp, or_bp):
76+
# get correct type id
77+
path_id, class_name = os.path.splitext(os.path.basename(fp))
78+
path_id = int(path_id) if re.match(
79+
r"^\d+$", path_id) else generate_path_id(sf.objects)
80+
class_id = getattr(
81+
ClassIDType, class_name[1:], ClassIDType.UnknownType).value
82+
type_id = -1
83+
for i, styp in enumerate(sf.types):
84+
if styp.class_id == class_id:
85+
type_id = i
86+
if type_id == -1: # not found, add type
87+
type_id = len(sf.types)
88+
sf.types.append(
89+
Fake(
90+
class_id=class_id,
91+
is_stripped_type=False,
92+
node=[],
93+
script_type_index=-1,
94+
old_type_hash=generate_16_byte_uid(),
95+
_class=SerializedType,
96+
)
97+
)
98+
99+
# add new object
100+
odata = copy(or_bp)
101+
odata.update(
102+
{
103+
"data": open(fp, "rb").read(),
104+
"path_id": generate_path_id(sf.objects),
105+
"class_id": class_id,
106+
"type_id": type_id,
107+
}
108+
)
109+
sf.objects[path_id] = Fake(**odata, _class=ObjectReader)
110+
111+
112+
def generate_path_id(objects):
113+
while True:
114+
uid = random.randint(-(2 ** 16), 2 ** 16 - 1)
115+
if uid not in objects:
116+
return uid
117+
118+
119+
def generate_16_byte_uid():
120+
return uuid.uuid1().urn[-16:].encode("ascii")
121+
122+
123+
class Fake(object):
124+
"""
125+
fake class for easy class creation without init call
126+
"""
127+
128+
def __init__(self, **kwargs):
129+
self.__dict__.update(kwargs)
130+
if "_class" in kwargs:
131+
self.__class__ = kwargs["_class"]
132+
133+
def save(self):
134+
return self.data
135+
136+
137+
if __name__ == "__main__":
138+
main()

0 commit comments

Comments
 (0)