beyarkay's picture
Blueprints from 11 sites + 31 save files
02f8da8 verified
Raw History Blame Contribute Delete
3.52 kB
"""Read a Factorio save's game version and mod list without running the game.
The header of `<save>/level-init.dat` (or `level.dat0`, zlib-deflated in >= 0.17; plain `level.dat` before)
starts with the version as 4 x u16 LE (major, minor, patch, build). Further in comes the mod list:
count (space-optimised uint: u8, or 0xFF + u32), then per mod a string (len u8|0xFF+u32, bytes),
version as 3 space-optimised u16 (u8, or 0xFF + u16), and a u32 CRC. The list always contains `base`,
and `base` also appears once earlier as the scenario's base mod, so the list is located as the
`\\x04base` occurrence that parses as a complete, plausible mod list.
Usage: python3 -I save_meta.py SAVE.zip [...] -> one JSON line per save
"""
import json
import struct
import sys
import zipfile
import zlib
DLC = {"base", "elevated-rails", "quality", "recycler", "space-age"}
def header_bytes(z: zipfile.ZipFile) -> bytes:
names = z.namelist()
for want in ("level-init.dat", "level.dat0", "level.dat"):
hit = [n for n in names if n.split("/")[-1] == want]
if hit:
with z.open(hit[0]) as f:
raw = f.read(4 << 20)
try:
return zlib.decompressobj().decompress(raw, 4 << 20)
except zlib.error:
return raw
raise ValueError("no level data in zip")
def _uint(b, i, wide):
if b[i] != 0xFF:
return b[i], i + 1
return (struct.unpack_from("<I", b, i + 1)[0], i + 5) if wide else (struct.unpack_from("<H", b, i + 1)[0], i + 3)
def parse_mods(b: bytes, start: int):
count, i = _uint(b, start, True)
if not 1 <= count <= 2000:
return None
mods = []
for _ in range(count):
n, i = _uint(b, i, True)
if not 1 <= n <= 200:
return None
name = b[i : i + n]
if not all(32 <= c < 127 for c in name):
return None
i += n
ver = []
for _ in range(3):
v, i = _uint(b, i, False)
ver.append(v)
i += 4
mods.append((name.decode(), ".".join(map(str, ver))))
return mods if any(m[0] == "base" for m in mods) else None
def meta(path: str) -> dict:
with zipfile.ZipFile(path) as z:
b = header_bytes(z)
has_replay = any(n.endswith("replay.dat") for n in z.namelist())
level_bytes = sum(i.file_size for i in z.infolist() if "/level.dat" in i.filename)
version = ".".join(map(str, struct.unpack_from("<4H", b, 0)[:3]))
mods = None
pos = b.find(b"\x04base")
while pos != -1 and mods is None:
# The count sits right before the first mod name; `base` is normally first, but scan back a little
# in case other mods precede it.
for back in range(1, 400):
if pos - back < 8:
break
mods = parse_mods(b, pos - back)
if mods:
break
pos = b.find(b"\x04base", pos + 1)
names = [n for n, _ in mods] if mods else None
return {
"factorio_version": version,
"mods": dict(mods) if mods else None,
"vanilla": names is not None and set(names) <= DLC,
"space_age": names is not None and "space-age" in names,
"has_replay": has_replay,
"level_dat_bytes": level_bytes,
}
if __name__ == "__main__":
for p in sys.argv[1:]:
try:
print(json.dumps({"file": p, **meta(p)}))
except Exception as e: # noqa: BLE001
print(json.dumps({"file": p, "error": repr(e)}))