Files

158 lines
9.8 KiB
Python

"""#75 follow-up (2026-11-26): SD face and underwear overlays follow Octo for every Turtle skin value.
Praxis (Tauren male, skin 21 = Grimtotem) still showed no skull paint after content ee92d560 imported the Octo skin.
In 1.12 the face area of the skin texture is covered by CharSections section 1 (face lower/upper) and section 4
(naked pelvis/torso) for the same skin colour. Octo has no face or underwear rows for Grimtotem, so its skin paint shows.
Blizzard has faces and pelvis for Tauren colour 21, and the SD elements tied to that skin choice drew them over the paint.
Rule (races 1-8): skin value v -> Octo skin row (flags, ColorIndex) in Turtle order (flags-0 by colour, then flags-1),
SD skin choice S = alt[conv(field 1, v)].
- Section 1, VariationIndex f, same (flags, colour): SD face choice F = alt[conv(field 2, f)]; face lower = target 4,
upper = target 5; elements are (choice F, related S).
- Section 4, VariationIndex 0, same (flags, colour): pelvis = target 13, torso = target 14; elements are (choice S, related 0).
Octo row present: byte-identical texture stays; otherwise import the Octo file (new FDID, octo_ prefix when the name is
taken) and set/add the element. Octo row absent: delete the element, so nothing covers the skin (Octo draws nothing there).
Usage: octo_sd_face_import.py <dump dir> <CharSections.octo.tsv> <profile.hpp> <listfile> <root_fdids.txt> <prior imports.json> <out dir>"""
import collections, hashlib, json, re, struct, sys
from pathlib import Path
H = Path(__file__).resolve().parent
sys.path[:0] = [str(H), '/mnt/Games/@project/wt-master-merge/ops/maps14-20261122']
import frozen_store as fs, octo_mpq
FDID0, MR0, MAT0, ELEM0 = 8844000, 2204500, 304500, 403000
md5 = lambda b: hashlib.md5(b).hexdigest()
def rows(path):
for line in open(path, encoding='utf-8', errors='replace'):
f = line.rstrip('\n').split('\t')
yield dict(x.split('=', 1) for x in f[1:] if '=' in x)
def main(dump, octo_cs, profile, listfile, root_list, prior, out):
d = Path(dump); out = Path(out); (out / 'textures').mkdir(parents=True, exist_ok=True)
names = set()
for line in open(listfile, encoding='utf-8', errors='replace'):
names.add(line.rstrip('\n').partition(';')[2].lower())
names |= set(json.load(open(prior)).values())
have = set(int(x) for x in open(root_list).read().split()) | set(map(int, json.load(open(prior))))
assert not any(f in have for f in range(FDID0, FDID0 + 1000)), 'FDID block taken'
st = fs.Store(); root = st.root; idx = {}
for g in st.layout['groups']:
if not (g['locale'] & 2) or g.get('flags1'): continue
f = 0
for i, (x,) in enumerate(struct.iter_unpack('<I', memoryview(root)[g['ids_offset']:g['ckeys_offset']])):
f += x; idx.setdefault(f, g['ckeys_offset'] + i * 16); f += 1
native = lambda f: st.read(root[idx[f]:idx[f] + 16].hex())[2] if f in idx else None
mat = {int(r['ID']): r for r in rows(d / 'ChrCustomizationMaterial.tsv')}
assert max(mat) < MAT0
tfd = {}
for r in rows(d / 'TextureFileData.tsv'): tfd.setdefault(int(r['MaterialResourcesID']), int(r['FileDataID']))
assert max(tfd) < MR0
elems = list(rows(d / 'ChrCustomizationElement.tsv')); assert max(int(r['ID']) for r in elems) < ELEM0
el = collections.defaultdict(dict) # (choice, related) -> target -> (row, fdid)
for r in elems:
m = int(r['ChrCustomizationMaterialID'])
if m in mat:
key = (int(r['ChrCustomizationChoiceID']), int(r['RelatedChrCustomizationChoiceID']))
el[key].setdefault(mat[m]['ChrModelTextureTargetID'], (r, tfd.get(int(mat[m]['MaterialResourcesID']))))
alt = {int(r['SourceChrCustomizationChoiceID']): int(r['VariantChrCustomizationChoiceID']) for r in rows(d / 'ChrModelAltVariantChoice.tsv')}
# Conversion = {id,race,sex,field,value,choice,dependent,dependent_value,discriminator}. Face choices depend on the
# skin (dependent field 1): Tauren male face 0 is choice 1074 for skins 0-18 but 1079 for 19-21 (Grimtotem).
# 2026-11-26 fix: a Turtle face value also converts to a skin-dependent Eye Color choice (Human, Dwarf, NE, Gnome,
# Troll...). Taking that row as the face left the real SD face unowned, and a face value without Octo rows then
# deleted its overlays (Human male face 0 lost all 10 normal skins). Only choices on the Skin Color / Face options count.
opt_name = {int(r['ID']): r['Name_lang'] for r in rows(d / 'ChrCustomizationOption.tsv')}
ch_opt = {int(r['ID']): int(r['ChrCustomizationOptionID']) for r in rows(d / 'ChrCustomizationChoice.tsv')}
FIELD_OPT = {1: 'Skin Color', 2: 'Face'}
conv, dep = {}, {}
for m in re.finditer(r'\{(\d+),(\d+),(\d+),(\d+),(\d+),(\d+),(\d+),(\d+),', open(profile).read()):
_, r, s, fld, v, c, d, dv = map(int, m.groups())
if fld in FIELD_OPT and opt_name.get(ch_opt.get(c)) != FIELD_OPT[fld]: continue
conv.setdefault((r, s, fld, v), c)
if d == 1: dep.setdefault((r, s, fld, v, dv), c)
face_choice = lambda r, s, f, skin: dep.get((r, s, 2, f, skin), conv.get((r, s, 2, f)))
cs = list(rows(octo_cs))
skins = collections.defaultdict(list)
for flag in ('0', '1'):
for r in sorted((r for r in cs if r.get('BaseSection') == '0' and r.get('VariationIndex') == '0' and r['Flags'] == flag), key=lambda r: int(r['ColorIndex'])):
skins[(int(r['RaceID']), int(r['SexID']))].append((flag, r['ColorIndex']))
sec = {}
for r in cs:
if r.get('BaseSection') in ('1', '4'):
sec.setdefault((int(r['RaceID']), int(r['SexID']), r['BaseSection'], int(r['VariationIndex']), r['Flags'], r['ColorIndex']), r['TextureName'].split(',')[:2])
faces = collections.defaultdict(set)
for (race, sex, fld, v) in conv:
if fld == 2: faces[(race, sex)].add(v)
imported, mats, tfd_rows, set_el, add_el, del_el, report = {}, [], [], [], [], [], []
nf, nmr, nmat, nel = FDID0, MR0, MAT0, ELEM0
counts = collections.Counter()
def material(path, target):
nonlocal nf, nmr, nmat
key = (path.lower(), target)
if key in imported: return imported[key]
raw = bytes(octo_mpq.read(path))
p = path.lower().replace('\\', '/'); base = p.rsplit('/', 1)
same = [k for k in imported if k[0] == path.lower()]
if same:
fid, mr = imported[same[0]][1], imported[same[0]][2]
else:
if p in names: p = f'{base[0]}/octo_{base[1]}'
fid, mr = nf, nmr; nf += 1; nmr += 1
(out / 'textures' / f'{fid}.blp').write_bytes(raw)
tfd_rows.append(dict(ID=fid, FileDataID=fid, UsageType=0, MaterialResourcesID=mr))
names.add(p); report.append(dict(fdid=fid, path=p, octo=path))
mats.append(dict(ID=nmat, ChrModelTextureTargetID=int(target), MaterialResourcesID=mr))
imported[key] = (nmat, fid, mr); nmat += 1
return imported[key]
def apply(choice, related, targets, tex):
nonlocal nel
cur_all = el.get((choice, related), {})
for target in targets:
cur = cur_all.get(target)
path = tex[targets.index(target)] if tex else ''
if path and octo_mpq.read(path) is None: # Octo row names a file its MPQs lack: 1.12 draws nothing
counts['octo-file-missing'] += 1; path = ''
if not path:
if cur: del_el.append(int(cur[0]['ID'])); counts['delete'] += 1
continue
if cur and native(cur[1]) is not None and md5(native(cur[1])) == md5(bytes(octo_mpq.read(path))):
counts['identical'] += 1; continue
m, _, _ = material(path, target)
if cur: set_el.append(dict(ID=int(cur[0]['ID']), ChrCustomizationMaterialID=m)); counts['import'] += 1
else:
add_el.append(dict(ID=nel, ChrCustomizationChoiceID=choice, RelatedChrCustomizationChoiceID=related, ChrCustomizationMaterialID=m))
nel += 1; counts['import-new-element'] += 1
for (race, sex), lst in sorted(skins.items()):
if race > 8: continue
for v, (flag, color) in enumerate(lst):
S = alt.get(conv.get((race, sex, 1, v)))
if not S: counts['no-skin-conversion'] += 1; continue
# Several Turtle face values can share one SD face choice (values beyond Octo's faces were mapped onto the
# nearest one). Each SD face choice is owned by the lowest value mapping to it that Octo has face rows for.
octo_faces = {k[3] for k in sec if k[:3] == (race, sex, '1')}
owner = {}
for f in sorted(faces[(race, sex)]):
F = alt.get(face_choice(race, sex, f, v))
if F: owner.setdefault(F, []).append(f)
for F, fs_ in sorted(owner.items()):
f = min((x for x in fs_ if x in octo_faces), default=min(fs_))
apply(F, S, ['4', '5'], sec.get((race, sex, '1', f, flag, color)))
apply(S, 0, ['13', '14'], sec.get((race, sex, '4', 0, flag, color)))
assert len(del_el) == len(set(del_el))
assert not ({r['ID'] for r in set_el} & set(del_el)) and len({r['ID'] for r in set_el}) == len(set_el)
for name, data in (('set-ChrCustomizationElement', set_el), ('add-ChrCustomizationElement', add_el),
('add-ChrCustomizationMaterial', mats), ('add-TextureFileData', tfd_rows)):
(out / f'{name}.json').write_text(json.dumps(data, indent=1))
(out / 'del-ChrCustomizationElement.txt').write_text(','.join(map(str, sorted(del_el))))
(out / 'imported-textures.json').write_text(json.dumps({str(r['fdid']): r['path'] for r in report}, indent=1))
(out / 'report.json').write_text(json.dumps(dict(counts=counts, files=len(report)), indent=1))
print(dict(counts), 'files', len(report), 'materials', len(mats), 'deletes', len(del_el), file=sys.stderr)
if __name__ == '__main__': main(*sys.argv[1:8])