136 lines
6.9 KiB
Python
136 lines
6.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Generate direct spell-kit playback bindings from the two client tables and the imported kits."""
|
|
import argparse
|
|
import collections
|
|
import csv
|
|
import hashlib
|
|
import itertools
|
|
import json
|
|
import struct
|
|
from pathlib import Path
|
|
|
|
|
|
def dbc(data):
|
|
if len(data) < 20 or data[:4] != b"WDBC":
|
|
raise ValueError("expected a WDBC table")
|
|
count, columns, stride, string_size = struct.unpack_from("<4I", data, 4)
|
|
records_end = 20 + count * stride
|
|
if columns == 0 or stride != 4 * columns or len(data) != records_end + string_size:
|
|
raise ValueError("invalid WDBC record layout")
|
|
rows = {r[0]: r for r in struct.iter_unpack(f"<{columns}I", data[20:records_end])}
|
|
if len(rows) != count:
|
|
raise ValueError("duplicate source IDs")
|
|
return rows, data[records_end:]
|
|
|
|
|
|
def native_identities(source, native, base, effect_names, native_content, listfile):
|
|
# Blizzard reworks of stock 1.12 kits keep their identity. For additions,
|
|
# compare actual model filenames through the native kit effect and attach tables.
|
|
source_effects, strings = dbc(effect_names)
|
|
source_models = {}
|
|
for key, row in source_effects.items():
|
|
path = strings[row[2]:strings.index(b"\0", row[2])].decode("latin1").lower().replace("\\", "/")
|
|
source_models[key] = path.removesuffix(".mdx") + ".m2" if path.endswith(".mdx") else path
|
|
|
|
def load_table(name):
|
|
return json.loads((native_content / f"n-{name}.json").read_bytes())
|
|
|
|
model_ids = {r["ID"]: r["ModelFileDataID"] for r in load_table("SpellVisualEffectName")}
|
|
required_files = set(model_ids.values())
|
|
model_paths = {}
|
|
with listfile.open(newline="") as stream:
|
|
for file_id, path in csv.reader(stream, delimiter=";"):
|
|
file_id = int(file_id)
|
|
if file_id in required_files:
|
|
model_paths[file_id] = path.lower()
|
|
attaches = {r["ID"]: r["SpellVisualEffectNameID"] for r in load_table("SpellVisualKitModelAttach")}
|
|
models = collections.defaultdict(set)
|
|
sounds = collections.defaultdict(set)
|
|
for r in load_table("SpellVisualKitEffect"):
|
|
kit, effect = r["ParentSpellVisualKitID"], r["Effect"]
|
|
if r["EffectType"] == 2:
|
|
path = model_paths.get(model_ids.get(attaches.get(effect)))
|
|
if path:
|
|
models[kit].add(path)
|
|
elif r["EffectType"] == 5:
|
|
sounds[kit].add(effect)
|
|
|
|
shared = set(source) & native
|
|
identities = shared & set(json.loads(base)["SpellVisualKit"])
|
|
for kit in shared - identities:
|
|
row = source[kit]
|
|
source_paths = {source_models[fx] for fx in row[3:13]
|
|
if fx not in (0, 0xffffffff) and fx in source_models}
|
|
if source_paths or models[kit]:
|
|
matches = bool(source_paths & models[kit])
|
|
else:
|
|
matches = ({row[13]} if row[13] else set()) == sounds[kit]
|
|
if matches:
|
|
identities.add(kit)
|
|
return identities
|
|
|
|
|
|
def ranges(ids):
|
|
for _, group in itertools.groupby(enumerate(sorted(ids)), lambda item: item[1] - item[0]):
|
|
values = [value for _, value in group]
|
|
yield values[0], values[-1]
|
|
|
|
|
|
def generate(source_data, native_data, component_data, base, effect_names, native_content, listfile):
|
|
source, _ = dbc(source_data)
|
|
native = {row["ID"] for row in json.loads(native_data)}
|
|
component = json.loads(component_data)
|
|
imported = {r["id"] for r in component["records"] if r["table_name"] == "SpellVisualKit"}
|
|
shared = native_identities(source, native, base, effect_names, native_content, listfile)
|
|
remaps = {}
|
|
for key, dest in component["kit_map"].items():
|
|
key = int(key)
|
|
if key not in source or dest <= 0 or dest > 0x7fffffff:
|
|
raise ValueError(f"invalid source/destination kit {key} -> {dest}")
|
|
if key in shared:
|
|
if dest != key:
|
|
raise ValueError(f"attempt to replace native kit {key}")
|
|
elif dest not in imported or dest in native:
|
|
raise ValueError(f"missing or colliding imported kit {dest}")
|
|
else:
|
|
remaps[key] = dest
|
|
|
|
text = ["// Generated by ops/spell_visual_kit_profile.py."]
|
|
for label, data in (("source kits", source_data), ("native kits", native_data), ("kit imports", component_data),
|
|
("stock 1.12 IDs", base), ("source effect names", effect_names)):
|
|
text.append("// " + label + " SHA-256 " + hashlib.sha256(data).hexdigest())
|
|
text += ["#pragma once", "#include <algorithm>", "#include <cstdint>", "#include <iterator>",
|
|
"#include <utility>", "", "namespace gateway::spell_visual_kit_profile {"]
|
|
for name, pairs in (("shared_ranges", list(ranges(shared))), ("imported_kits", sorted(remaps.items()))):
|
|
text.append(f"inline constexpr std::pair<uint32_t, uint32_t> {name}[] = {{")
|
|
# Group adjacent data entries for a compact generated profile.
|
|
for start in range(0, len(pairs), 6):
|
|
text.append(" " + " ".join(f"{{{a}, {b}}}," for a, b in pairs[start:start + 6]))
|
|
text += ["};", ""]
|
|
text += ["inline uint32_t resolve(uint32_t kit) {",
|
|
" auto range = std::lower_bound(std::begin(shared_ranges), std::end(shared_ranges), kit,",
|
|
" [](auto interval, uint32_t id) { return interval.second < id; });",
|
|
" if (range != std::end(shared_ranges) && range->first <= kit) return kit;",
|
|
" auto imported = std::lower_bound(std::begin(imported_kits), std::end(imported_kits), kit,",
|
|
" [](auto pair, uint32_t id) { return pair.first < id; });",
|
|
" if (imported != std::end(imported_kits) && imported->first == kit) return imported->second;",
|
|
" return 0;",
|
|
"}", "} // namespace gateway::spell_visual_kit_profile", ""]
|
|
return "\n".join(text)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("source_dbc", type=Path)
|
|
parser.add_argument("native_export", type=Path, help="70334 DB2Gameplay JSON export of SpellVisualKit")
|
|
parser.add_argument("component", type=Path)
|
|
parser.add_argument("output", type=Path)
|
|
parser.add_argument("--base-ids", type=Path, required=True, help="stock 1.12 SpellVisualKit ID export")
|
|
parser.add_argument("--source-effect-names", type=Path, required=True, help="source SpellVisualEffectName.dbc")
|
|
parser.add_argument("--native-content", type=Path, required=True, help="directory of n-{table}.json DB2Gameplay exports")
|
|
parser.add_argument("--listfile", type=Path, required=True, help="FileDataID;path list for identifying native models")
|
|
args = parser.parse_args()
|
|
args.output.write_text(generate(args.source_dbc.read_bytes(), args.native_export.read_bytes(),
|
|
args.component.read_bytes(), args.base_ids.read_bytes(),
|
|
args.source_effect_names.read_bytes(), args.native_content, args.listfile))
|