Files
myrzx_bot/tools/build_battle_simulation_data.py
T

142 lines
7.2 KiB
Python

"""Reproducibly bundle original, public combat configuration. No account inputs.
Run from the repo root: python tools/build_battle_simulation_data.py
Only this build tool opens the supplied, hash-checked original APK. Runtime
loads a small immutable cache from combat_tables.json.gz instead.
"""
from __future__ import annotations
import argparse
import gzip
import hashlib
import json
from pathlib import Path
import re
import struct
import sys
import zipfile
import zlib
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from tools.research_battle_v12 import recover_table
ORIGINAL_APK_SHA256 = "01678ee3a8465d818d32cbbd94baa0d8253b04b4c57b70ebc5544ed341f1015d"
TABLES = ("monster_info", "monster_skill", "monster_setting", "game_setting",
"team_info", "setting", "potential_info", "entangle_info", "upstar_info",
"item_info", "stage_info", "task_info")
# HitAction1..10, verified at the sendHit callbacks, not sound/visual timing.
ACTION_HIT_MS = {"JUMP_HIT": 200, "Y_SCALE_SHOOT": 100, "HORIZON_HIT": 200,
"DOWN_HIT": 200, "NONE": 0, "HORIZON_HIT_DELAY": 0,
"HORIZON_HIT_QUICK": 100, "FRONT_HIT": 200,
"JUMP_HIT2": 200, "X_SCALE_SHOOT": 200}
def compact(value):
if isinstance(value, dict):
return {str(k): compact(v) for k, v in value.items() if not str(k).startswith("c_")}
if isinstance(value, list):
return [compact(v) for v in value]
return value
def attack_profiles(sources):
folder = sources / "net/pixvi/myr/view/attack"
factory = (folder / "type/AttackType.as").read_text(encoding="utf-8")
profiles, fingerprints = {}, {}
paths = list(folder.glob("AttackType*.as")) + list((folder / "action").rglob("*.as"))
paths += [folder / "type/AttackType.as", folder / "BaseAttack.as"]
for path in sorted(paths):
fingerprints[path.relative_to(sources).as_posix()] = hashlib.sha256(path.read_bytes()).hexdigest()
for key, cls in re.findall(r'case "(\d+)":\s*attack = new (AttackType\d+)\(\);', factory):
source = (folder / (cls + ".as")).read_text(encoding="utf-8")
action = re.search(r"type_action\s*=\s*HitActionType\.(\w+)", source)
speed = re.search(r"spd_bullet\s*=\s*([\d.]+)", source)
if not action or action.group(1) not in ACTION_HIT_MS:
raise ValueError(f"Unreviewed attack timing: {cls}")
profiles[key] = {"source_class": cls,
"projectile": bool(re.search(r"shotter\s*=\s*true", source)),
"projectile_speed": float(speed.group(1)) if speed else 6,
"hit_delay_ms": ACTION_HIT_MS[action.group(1)],
"action": action.group(1)}
return profiles, fingerprints
def build(apk, output, *, sources=None):
apk, output = Path(apk), Path(output)
source_hash = hashlib.sha256(apk.read_bytes()).hexdigest()
if source_hash != ORIGINAL_APK_SHA256:
raise ValueError("Expected the unmodified original 1.9.68 APK (SHA-256 mismatch)")
data, table_meta = {"schema_version": 1}, {}
with zipfile.ZipFile(apk) as archive:
swf = archive.read("assets/MYRMain.app")
swf_body = zlib.decompress(swf[8:]) if swf[:3] == b"CWS" else swf[8:]
rect_bytes = (5 + 4 * (swf_body[0] >> 3) + 7) // 8
fps = struct.unpack_from("<H", swf_body, rect_bytes)[0] / 256
if fps != 50:
raise ValueError("Unreviewed original frame rate")
for name in TABLES:
value, meta = recover_table(archive, name)
if isinstance(value, dict):
value = value.get("datas", value)
if name == "stage_info":
value = {str(row["id"]): {"id": row["id"], "level": row.get("level", {})}
for row in value}
if name == "task_info":
value = {str(k): {"id": row["id"], "type": row.get("type"),
"steps": [{k: v for k, v in step.items()
if k in ("type", "battle", "stage", "level", "value", "statusType", "statusValue")}
for step in row.get("steps", [])]}
for k, row in value.items()}
data[name] = compact(value)
table_meta[name] = dict(meta, record_count=len(value))
# Preserve all combat values; discard images, descriptions and quest rewards.
data["monster_info"] = {k: {f: v for f, v in row.items() if f in (
"type", "name", "atk", "def", "hp", "dex", "star", "element", "job",
"pow", "powdef", "spd_atk", "spd_move", "atk_dis", "atk_type1", "atk_type2",
"skill_1", "skill_2", "move_1", "move_2", "entangleSkills") or "_grow_" in f}
for k, row in data["monster_info"].items()}
data["setting"] = {k: data["setting"][k] for k in ("defaultField", "groundObject", "groundType")}
data["attack_profiles"], source_files = attack_profiles(sources or ROOT / "analysis/as3/scripts")
data["clock"] = {"fps": fps, "frame_ms": 1000 / fps}
battles = {k: data.pop(k) for k in ("stage_info", "task_info")}
battles["schema_version"] = 1
# Simulation already receives one battle config. Do not decode all original
# stage battles in each worker merely to compute species stats.
artifacts = {}
output.mkdir(parents=True, exist_ok=True)
for name, value in (("combat_tables.json.gz", data), ("combat_battles.json.gz", battles)):
encoded = json.dumps(value, ensure_ascii=False, allow_nan=False,
sort_keys=True, separators=(",", ":")).encode("utf-8")
artifact = gzip.compress(encoded, mtime=0)
artifacts[name] = {"name": name, "bytes": len(artifact),
"sha256": hashlib.sha256(artifact).hexdigest(),
"decoded_sha256": hashlib.sha256(encoded).hexdigest()}
(output / name).write_bytes(artifact)
manifest = {"schema_version": 1, "source": {"apk_sha256": source_hash,
"main_swf_sha256": "c6838331a198a22ffa486cbf61cc74c97619e011bc3364c8bb8dc99e269036cf"},
"tables": table_meta, "attack_sources": source_files, "original_frame_rate": fps,
"artifact": artifacts["combat_tables.json.gz"], "artifacts": artifacts,
"scope": "Public original combat tables; experimental simulator, not engine fidelity."}
(output / "combat_manifest.json").write_text(json.dumps(manifest, ensure_ascii=True,
sort_keys=True, indent=2) + "\n", encoding="utf-8")
return manifest
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--apk", type=Path)
parser.add_argument("--output", type=Path, default=ROOT / "ranch_assistant/data")
args = parser.parse_args(argv)
candidates = list(ROOT.glob("*_1.9.68.apk"))
apk = args.apk or (candidates[0] if len(candidates) == 1 else None)
if apk is None:
parser.error("Supply exactly one original APK with --apk")
manifest = build(apk, args.output)
print(json.dumps({"artifact": manifest["artifact"],
"table_counts": {k: v["record_count"] for k, v in manifest["tables"].items()}}))
if __name__ == "__main__":
main()