151 lines
7.1 KiB
Python
151 lines
7.1 KiB
Python
#!/usr/bin/env python3
|
|
"""Generate native tradeskill-trainer contexts and recipe bindings from the two catalogues."""
|
|
import argparse
|
|
from collections import defaultdict
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import struct
|
|
|
|
|
|
def sql_tables(path):
|
|
sql = path.read_text()
|
|
header = re.compile(r'(?:REPLACE|INSERT(?:\s+IGNORE)?)\s+INTO\s+`(creature_trainer|trainer|trainer_spell)`'
|
|
r'[^;]{0,512}?\bVALUES\s*', re.IGNORECASE)
|
|
# Greetings may contain semicolons or escaped quotes.
|
|
quoted_string_or_end = re.compile(r"'(?:\\.|''|[^'\\])*'|;", re.DOTALL)
|
|
offset = 0
|
|
while match := header.search(sql, offset):
|
|
for token in quoted_string_or_end.finditer(sql, match.end()):
|
|
if token.group() == ';':
|
|
yield match.group(1).lower(), sql[match.end():token.start()]
|
|
offset = token.end()
|
|
break
|
|
else:
|
|
raise ValueError(f'Unterminated {match.group(1)} statement in {path}')
|
|
|
|
|
|
def db2_rows(path):
|
|
for line in path.open():
|
|
yield dict(cell.split('=', 1) for cell in line.rstrip().split('\t')[1:] if '=' in cell)
|
|
|
|
|
|
def profession_effects(path):
|
|
effects = defaultdict(set)
|
|
steps = defaultdict(set)
|
|
skills = defaultdict(set)
|
|
for line in path.open():
|
|
row = json.loads(line)['fields']
|
|
if row['Effect'] == 36 and row['DifficultyID'] == 0:
|
|
effects[row['SpellID']].add(row['EffectTriggerSpell'])
|
|
if row['DifficultyID'] == 0 and row['Effect'] in (44, 118):
|
|
bits = row['EffectBasePointsF']['f32_bits']
|
|
tier = struct.unpack('<f', struct.pack('<I', bits))[0]
|
|
if tier.is_integer() and 1 <= tier <= 255:
|
|
table = steps if row['Effect'] == 44 else skills
|
|
table[row['SpellID']].add((int(tier), row['EffectMiscValue'][0]))
|
|
return effects, steps, skills
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
for name in ('venues', 'trainers', 'recipes', 'source_spells', 'native_names',
|
|
'native_effects', 'native_abilities', 'native_categories', 'native_skills', 'output'):
|
|
parser.add_argument(name, type=Path)
|
|
args = parser.parse_args()
|
|
venues = defaultdict(set)
|
|
types = {}
|
|
reference = set()
|
|
for path in (args.venues, args.trainers, args.recipes):
|
|
for table, text in sql_tables(path):
|
|
if table == 'trainer':
|
|
types.update((int(i), int(t)) for i, t in re.findall(r'\((\d+),\s*(\d+),', text))
|
|
elif table == 'creature_trainer':
|
|
for values in re.findall(r'\(([\d, ]+)\)', text):
|
|
entry, trainer, menu, option = map(int, values.split(','))
|
|
venues[entry].add(trainer)
|
|
else:
|
|
for values in re.findall(r'\(([\d, ]+)\)', text):
|
|
trainer, spell, cost, skill, rank, req1, req2, req3, level, build = map(int, values.split(','))
|
|
reference.add((trainer, spell, skill))
|
|
|
|
names = {int(row['id']) for line in args.native_names.open()
|
|
if (row := json.loads(line))['fields']['Name_lang']}
|
|
effects, steps, skills = profession_effects(args.native_effects)
|
|
wrappers = defaultdict(set)
|
|
for line in args.source_spells.open():
|
|
service, name, taught, effect, misc = line.rstrip('\n').split('\t')
|
|
service, taught = int(service), int(taught)
|
|
if effect == '36' and service in names and taught in names and effects[service] == {taught}:
|
|
wrappers[taught].add(service)
|
|
|
|
categories = {int(r['ID']): r for r in db2_rows(args.native_categories)}
|
|
skill_parents = {int(r["ID"]): int(r["ParentSkillLineID"]) for r in db2_rows(args.native_skills)}
|
|
abilities = defaultdict(set)
|
|
skill_steps = defaultdict(set)
|
|
for row in db2_rows(args.native_abilities):
|
|
category = int(row['TradeSkillCategoryID'])
|
|
skill = int(row['SkillLine'])
|
|
if not category:
|
|
skill_steps[int(row["Spell"])].add(skill)
|
|
continue
|
|
ancestors = set()
|
|
while category and category not in ancestors:
|
|
entry = categories.get(category)
|
|
if not entry or not entry['Name_lang']:
|
|
break
|
|
category_skill = int(entry['SkillLineID'])
|
|
if category_skill != skill and skill_parents.get(category_skill) != skill:
|
|
break
|
|
ancestors.add(category)
|
|
category = int(entry['ParentTradeSkillCategoryID'])
|
|
if not category:
|
|
abilities[int(row['Spell'])].add(skill)
|
|
|
|
trainers = {entry: next(iter(ids)) for entry, ids in venues.items()
|
|
if len(ids) == 1 and types.get(next(iter(ids))) == 2}
|
|
trainer_ids = set(trainers.values())
|
|
bindings = set()
|
|
venue_skills = set()
|
|
for trainer, learned, skill in reference:
|
|
if trainer not in trainer_ids:
|
|
continue
|
|
if skill > 0 and skill in abilities[learned] and wrappers[learned]:
|
|
# Source controls which recipes a particular trainer offers. Other
|
|
# trainers of the same profession use the same native recipe ID.
|
|
venue_skills.add((trainer, skill))
|
|
bindings.update((0, service, learned, skill) for service in wrappers[learned])
|
|
elif skill == 0:
|
|
for service in wrappers[learned]:
|
|
ranks = {skill for tier, skill in steps[service] & skills[learned]
|
|
if tier == 1 and skill in skill_steps[learned]}
|
|
if len(ranks) == 1:
|
|
# First-rank confirmations require the exact native trainer.
|
|
bindings.add((trainer, service, learned, 0))
|
|
venue_skills.add((trainer, next(iter(ranks))))
|
|
assert len(bindings) == len({(t, s, k) for t, s, d, k in bindings})
|
|
approved = {t for t, k in venue_skills}
|
|
trainers = {e: t for e, t in trainers.items() if t in approved}
|
|
with args.output.open('w') as out:
|
|
out.write('#pragma once\n// Generated by ops/tradeskill_trainer_offers.py. Input SHA-256:\n')
|
|
for key, path in vars(args).items():
|
|
if key != 'output':
|
|
out.write(f'// {key}: {hashlib.sha256(path.read_bytes()).hexdigest()}\n')
|
|
out.write('#include <cstdint>\nnamespace gateway::tradeskill_trainers {\n')
|
|
out.write('inline constexpr struct Venue { uint32_t entry, trainer; } Venues[] = {\n')
|
|
for entry, trainer in sorted(trainers.items()):
|
|
out.write(f' {{{entry},{trainer}}},\n')
|
|
out.write('};\ninline constexpr struct Specialty { uint32_t trainer, skill; } Specialties[] = {\n')
|
|
for trainer, skill in sorted(venue_skills):
|
|
out.write(f' {{{trainer},{skill}}},\n')
|
|
out.write('};\ninline constexpr struct Offer { uint32_t trainer, service, learned, skill; } Offers[] = {\n')
|
|
for trainer, service, learned, skill in sorted(bindings):
|
|
out.write(f' {{{trainer},{service},{learned},{skill}}},\n')
|
|
out.write('};\n}\n')
|
|
print(f'{len(trainers)} venues, {len(approved)} native trainer IDs, {len(bindings)} recipe bindings')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|