-
Notifications
You must be signed in to change notification settings - Fork 0
/
savegame.py
194 lines (179 loc) · 7.16 KB
/
savegame.py
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
188
189
190
191
192
193
194
# -*- coding: utf-8 -*-
"""
SkyAlchemy
Copyright ©2016 Ronan Paixão
Licensed under the terms of the MIT License.
See LICENSE for details.
@author: Ronan Paixão
"""
from __future__ import unicode_literals
import struct
from collections import OrderedDict
from io import BytesIO
import os
import os.path as osp
import ctypes
import ctypes.wintypes
#%% unpack and data
from skyrimtypes import unpack, RefID
import skyrimdata
#%%
class Savegame(object):
"""This class loads a The Elder Scrolls V: Skyrim savegame file and parses
useful information.
"""
def __init__(self, filename, load_now=True):
self.filename = filename
if load_now:
for i in self.loadGame():
pass
def loadGame(self):
filename = self.filename
#%%
d = OrderedDict() # Data storage
f = open(filename, 'rb') # TODO: replace
f.seek(0)
if True:
# with open(filename, 'rb') as f:
# File
d['magic'] = f.read(13)
yield f.tell()
if d['magic'] != b'TESV_SAVEGAME':
raise AssertionError("Incorrect magic in file header")
d['headerSize'] = unpack("uint32", f)
# Header
header = BytesIO(f.read(d['headerSize']))
d['version'] = unpack("uint32", header)
if not 7 <= d['version'] <= 9:
raise AssertionError("Only versions 7 to 9 are supported")
d['saveNumber'] = unpack("uint32", header)
d['playerName'] = unpack("wstring", header)
d['playerLevel'] = unpack("uint32", header)
d['playerLocation'] = unpack("wstring", header)
d['gameDate'] = unpack("wstring", header)
d['playerRaceEditorId'] = unpack("wstring", header)
d['playerSex'] = {0: "male", 1: "female"}[unpack("uint16", header)]
d['playerCurExp'] = unpack("float32", header)
d['playerLvlUpExp'] = unpack("float32", header)
d['filetime'] = unpack("filetime", header)
d['shotWidth'] = unpack("uint32", header)
d['shotHeight'] = unpack("uint32", header)
yield f.tell()
# Back to file
d['screenshotData'] = f.read(3*d['shotWidth']*d['shotHeight'])
from PIL import Image
d['screenshotImage'] = Image.frombytes("RGB",
(d['shotWidth'], d['shotHeight']),
d['screenshotData'])
yield f.tell()
d['formVersion'] = unpack("uint8", f)
d['pluginInfoSize'] = unpack("uint32", f)
# Plugin
plugin = BytesIO(f.read(d['pluginInfoSize']))
d['pluginCount'] = unpack("uint8", plugin)
d['plugins'] = [unpack("wstring", plugin)
for i in range(d['pluginCount'])]
yield f.tell()
# File Location Table
formIDArrayCountOffset = unpack("uint32", f)
unknownTable3Offset = unpack("uint32", f)
globalDataTable1Offset = unpack("uint32", f)
globalDataTable2Offset = unpack("uint32", f)
changeFormsOffset = unpack("uint32", f)
globalDataTable3Offset = unpack("uint32", f)
globalDataTable1Count = unpack("uint32", f)
globalDataTable2Count = unpack("uint32", f)
globalDataTable3Count = unpack("uint32", f)
changeFormCount = unpack("uint32", f)
f.read(4*15) # unused
yield f.tell()
# Global Data 1
f.seek(globalDataTable1Offset)
gdata1 = []
for i in range(globalDataTable1Count):
gdata1.append(unpack("globalData", f))
yield f.tell()
# Global Data 2
f.seek(globalDataTable2Offset)
gdata2 = []
for i in range(globalDataTable2Count):
gdata2.append(unpack("globalData", f))
yield f.tell()
# changeForms
f.seek(changeFormsOffset)
d_changeforms = []
for i in range(changeFormCount):
d_changeforms.append(unpack("ChangeForm", f))
yield f.tell()
d['changeforms'] = d_changeforms
# Global Data 3
yield f.tell()
f.seek(globalDataTable3Offset)
gdata3 = []
for i in range(globalDataTable3Count):
gdata3.append(unpack("globalData", f))
yield f.tell()
d['gdata'] = {v[1]:v[2] for v in (gdata1 + gdata2 + gdata3)}
# formID
f.seek(formIDArrayCountOffset)
formIDArrayCount = unpack("uint32", f)
d['formid'] = struct.Struct('{}I'.format(formIDArrayCount)).unpack(
f.read(formIDArrayCount*4))
yield f.tell()
# Visited Worldspace
visitedWorldspaceArrayCount = unpack("uint32", f)
d['visitedWorldspaceArray'] = struct.Struct('{}I'.format(
visitedWorldspaceArrayCount)).unpack(f.read(
visitedWorldspaceArrayCount*4))
yield f.tell()
# unknownTable3
f.seek(unknownTable3Offset)
ukt3count = unpack("uint32", f)
assert(len(f.read()) == ukt3count)
# EOF
assert(f.read() == b"")
yield f.tell()
# Inventory
for cf in d['changeforms']:
if cf.type == 1 and cf.formid.value == 0x14:
break
d['inventory'] = cf.d['inventory']
self.d = d
def populate_ids(self):
for k, created in self.d['gdata']['Created Objects'].items():
for item in created:
# print "Created", k, hex(item.refID.value)
RefID.createdid[item.refID.value] = item
for i, formid in enumerate(self.d['formid']):
if formid in RefID.defaultid:
RefID.formid[i+1] = RefID.defaultid[formid]
elif formid in RefID.createdid:
RefID.formid[i+1] = RefID.createdid[formid]
def player_ingrs(self):
for inv_item in self.d['inventory']:
if (inv_item.item.type not in {'C', 'F'} and
inv_item.item.name.type == "INGR"):
yield (inv_item.itemcount, inv_item.item.value)
#%%
def getSaveGames():
"""Get list of savegame files"""
dll = ctypes.windll.shell32
buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH + 1)
try:
if dll.SHGetSpecialFolderPathW(None, buf, 0x0005, False):
savedir = osp.join(buf.value, "My Games", "Skyrim", "Saves")
if not osp.exists(savedir) or not osp.isdir(savedir):
raise RuntimeError("Could not find savegame directory.")
else:
raise RuntimeError("Could not find savegame directory.")
except:
raise RuntimeError("Could not find savegame directory.")
savegames = [osp.join(savedir, f) for f in os.listdir(savedir) if f.endswith(".ess")]
return savegames
#%%
def test_savegame():
#%%
savegames = getSaveGames()
for filename in savegames:
sg = Savegame(filename)
sg.populate_createdid()