Files
WoW-Hybrid-gateway/ops/sd_race_customization.py

372 lines
23 KiB
Python

#!/usr/bin/env python3
"""#52 (2026-11-25): SD (classic) bodies for the Turtle-only playable races, as native client DB2 rows.
The 70334 SD/HD toggle swaps a race's HD ChrModel for the SD ChrModel named in ChrModelAltVariant and shows that model's
ChrCustomizationOptions. High Elf (HD 19/20, the Blood Elf slot) had no SD model at all and Goblin SD (277/278) has only
2 native options, while include/gateway/sd_appearance_profile.hpp (the codec's SD inverse) already expects options
14000-14016 with choices 100000-100198 in Octo source order. This builds them:
ChrModel 279/280 High Elf SD = the native TBC Blood Elf SD bodies (CreatureDisplayInfo 15476/15475, the same
displays Octo's playable High Elf uses), texture layout 203 (classic sections)
ChrModelAltVariant 19/20 HD 19/20 -> SD 279/280
ChrCustomizationOption / Choice / Element / Material / Geoset, TextureFileData
from Octo CharSections (skin, face, facial-hair texture, hair texture, underwear),
CharHairGeosets and CharacterFacialHairStyles, with the native Human SD (ChrModel 257) shape:
skin target 1 (+13/14 underwear)
face targets 4 (lower) / 5 (upper), related to each skin choice
hair geoset type 0 + targets 10 (hair) / 11 / 12 (scalp), related to each hair colour
colour targets 7 / 8 (facial-hair texture), related to each facial-hair choice
facial geosets types 1 / 3 / 2 (CharacterFacialHairStyles 6 / 7 / 8)
ChrModelAltVariantOption / Choice
HD option/choice -> SD option/choice through the HD conversion profile (same source value),
so toggling keeps the selected look.
usage: sd_race_customization.py <native-csv-dir> <out-dir>
native-csv-dir: Db2Bake/dbdump CSVs of the parent build (ChrModel, ChrCustomizationOption, ChrCustomizationChoice,
ChrCustomizationElement, ChrCustomizationMaterial, ChrCustomizationGeoset, ChrModelAltVariant(+Option,+Choice),
TextureFileData).
Turtle-only textures are read from the Octo client into <out>/textures/<fdid>.blp (FileDataIDs 8840000+, listed in
imported-textures.json); ones Octo lacks too are listed in missing-textures.json.
"""
import collections
import csv
import json
import re
import struct
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE / 'maps14-20261122'))
import octo_mpq # noqa: E402
REPO = HERE.parent
SD_MODEL = {(9, 0): 277, (9, 1): 278, (10, 0): 279, (10, 1): 280}
HD_MODEL = {(9, 0): 17, (9, 1): 18, (10, 0): 19, (10, 1): 20}
NEW_CHR_MODEL = {279: dict(sex=0, display=15476, skeleton=199661, hd=19), 280: dict(sex=1, display=15475, skeleton=199660, hd=20)}
# Native Human SD (ChrModel 257) option shape per Classic appearance field.
FIELD = {0: dict(name='Skin Color', flags=16, order=1, req=141),
1: dict(name='Face', flags=0, order=2, req=144),
2: dict(name='Hair Style', flags=0, order=3, req=141),
3: dict(name='Hair Color', flags=2, order=4, req=141),
4: dict(name='Facial Hair', flags=0, order=5, req=141)}
BASE = dict(element=400000, material=300000, geoset=30000, mr=2200000, variant_option=94, variant_choice=1217, secondary=2000,
fdid=8840000)
def rows(path):
with open(path, newline='') as f:
r = list(csv.reader(f))
head = r[0]
return [dict(zip(head, x)) for x in r[1:] if len(x) == len(head)]
def octo_dbc(name):
raw = octo_mpq.read('DBFilesClient\\' + name)
n, f, rs, _ = struct.unpack_from('<4I', raw, 4)
strings = raw[20 + n * rs:]
text = lambda o: strings[o:strings.index(b'\0', o)].decode('latin1') if 0 <= o < len(strings) else ''
return [struct.unpack_from('<%di' % f, raw, 20 + i * rs) for i in range(n)], text
def sd_profile():
s = (REPO / 'include/gateway/sd_appearance_profile.hpp').read_text()
out = {}
for race, sex, field, option, size, choices in re.findall(r'\{(\d+), (\d+), (\d+), (\d+), (\d+), \{([\d, ]*)\}\}', s):
out[(int(race), int(sex), int(field))] = (int(option), [int(c) for c in choices.split(',')][:int(size)])
return out
def hd_conversions():
s = (REPO / 'include/gateway/character_creation_profile.hpp').read_text()
conv = [tuple(int(x) for x in t.split(',')) for t in
re.findall(r'\{([-0-9,]+)\}', re.search(r'Conversions\{\{(.*?)\}\};', s, re.S).group(1))]
choice_option = dict(tuple(int(x) for x in t.split(',')) for t in
re.findall(r'\{([-0-9,]+)\}', re.search(r'Choices\{\{(.*?)\}\};', s, re.S).group(1)))
return conv, choice_option
def main(csv_dir, out_dir):
csv_dir, out = Path(csv_dir), Path(out_dir)
out.mkdir(parents=True, exist_ok=True)
nat = {t: rows(csv_dir / f'{t}.csv') for t in ('ChrModel', 'ChrCustomizationOption', 'ChrCustomizationChoice',
'ChrCustomizationElement', 'ChrCustomizationMaterial', 'ChrCustomizationGeoset', 'ChrModelAltVariant',
'ChrModelAltVariantOption', 'ChrModelAltVariantChoice', 'TextureFileData')}
have = {t: {int(r['ID']) for r in v} for t, v in nat.items()}
listfile = {}
for line in open('/mnt/Games/@project/listfiles/community-listfile.csv', errors='replace'):
i, _, p = line.rstrip('\n').partition(';')
if i.isdigit():
listfile.setdefault(p.lower(), int(i))
texture_mr = {int(r['FileDataID']): int(r['MaterialResourcesID']) for r in nat['TextureFileData']}
mr_count = collections.Counter(texture_mr.values())
material_of = {(int(r['ChrModelTextureTargetID'].split('|')[0]), int(r['MaterialResourcesID'])): int(r['ID'])
for r in nat['ChrCustomizationMaterial']}
geoset_of = {(int(r['GeosetType']), int(r['GeosetID'])): int(r['ID']) for r in nat['ChrCustomizationGeoset'] if r['Modifier'] == '0'}
hd_choice = {int(r['ID']): r for r in nat['ChrCustomizationChoice']}
hd_option = {int(r['ID']): r for r in nat['ChrCustomizationOption']}
sections, text = octo_dbc('CharSections.dbc')
# Octo layout: ID, Race, Sex, BaseSection, Variation, Color, Texture[3], Flags
# Flags 1 rows are NPC-only skins (HumanMale_Pirate, BloodElfMaleSkin00_106DarkRanger); playable rows have flags 0.
sect = {(r[1], r[2], r[3], r[4], r[5]): [text(r[6 + k]) for k in range(3)] for r in sections if r[1] in (9, 10) and r[9] == 0}
hair_geoset = {(r[1], r[2], r[3]): r[4] for r in octo_dbc('CharHairGeosets.dbc')[0]}
facial = {(r[0], r[1], r[2]): (r[6], r[7], r[8]) for r in octo_dbc('CharacterFacialHairStyles.dbc')[0]}
profile = sd_profile()
conv, conv_option = hd_conversions()
new = collections.defaultdict(list)
missing, counters, imported = {}, collections.Counter(), {}
ids = dict(BASE)
def take(kind):
ids[kind] += 1
return ids[kind] - 1
def material(target, path):
if not path:
return None
fdid = listfile.get(path.lower().replace('\\', '/'))
if not fdid and path not in imported and path not in missing:
try:
raw = octo_mpq.read(path)
except Exception:
raw = None
if raw: # Turtle-only texture: import the Octo file under a new FileDataID (8840000+ block)
imported[path] = take('fdid')
(out / 'textures').mkdir(exist_ok=True)
(out / 'textures' / f'{imported[path]}.blp').write_bytes(raw)
else:
missing[path] = 'absent from listfile and Octo client (renders nothing on Octo either)'
fdid = fdid or imported.get(path)
if not fdid:
return None
mr = texture_mr.get(fdid)
if mr is None:
mr = take('mr')
texture_mr[fdid] = mr
mr_count[mr] += 1
new['TextureFileData'].append(dict(ID=fdid, UsageType=0, MaterialResourcesID=mr))
elif mr_count[mr] > 1:
counters['shared-material-resource'] += 1
key = (target, mr)
if key not in material_of:
material_of[key] = take('material')
new['ChrCustomizationMaterial'].append(dict(ID=material_of[key], ChrModelTextureTargetID=target, MaterialResourcesID=mr))
return material_of[key], fdid
def geoset(kind, value):
key = (kind, value)
if key not in geoset_of:
geoset_of[key] = take('geoset')
new['ChrCustomizationGeoset'].append(dict(ID=geoset_of[key], GeosetType=kind, GeosetID=value, Modifier=0))
return geoset_of[key]
def element(choice, related=0, geo=0, mat=0):
new['ChrCustomizationElement'].append(dict(ID=take('element'), ChrCustomizationChoiceID=choice,
RelatedChrCustomizationChoiceID=related, ChrCustomizationGeosetID=geo, ChrCustomizationSkinnedModelID=0,
ChrCustomizationMaterialID=mat, ChrCustomizationBoneSetID=0, ChrCustomizationCondModelID=0,
ChrCustomizationDisplayInfoID=0, ChrCustItemGeoModifyID=0, ChrCustomizationVoiceID=0, AnimKitID=0,
ParticleColorID=0, ChrCustGeoComponentLinkID=0))
texture_fdids = set()
for model_id, spec in NEW_CHR_MODEL.items():
if model_id in have['ChrModel']:
continue
hd = next(r for r in nat['ChrModel'] if int(r['ID']) == spec['hd'])
f3 = lambda v: [float(x) for x in v.split('|')]
new['ChrModel'].append(dict(ID=model_id, FaceCustomizationOffset=f3(hd['FaceCustomizationOffset']),
CustomizeOffset=f3(hd['CustomizeOffset']), Sex=spec['sex'], DisplayID=spec['display'],
CharComponentTextureLayoutID=203, Flags=int(hd['Flags']), SkeletonFileDataID=spec['skeleton'],
ModelFallbackChrModelID=0, TextureFallbackChrModelID=0, HelmVisFallbackChrModelID=0,
CustomizeScale=float(hd['CustomizeScale']), CustomizeFacing=float(hd['CustomizeFacing']),
CameraDistanceOffset=float(hd['CameraDistanceOffset']), BarberShopCameraOffsetScale=float(hd['BarberShopCameraOffsetScale']),
BarberShopCameraRotationFacing=float(hd['BarberShopCameraRotationFacing']),
BarberShopCameraRotationOffset=float(hd['BarberShopCameraRotationOffset'])))
new['ChrModelAltVariant'].append(dict(ID=spec['hd'], SourceChrModelID=spec['hd'], VariantChrModelID=model_id))
for (race, sex), sd_model in SD_MODEL.items():
choices = {f: profile[(race, sex, f)][1] for f in range(5)}
options = {f: profile[(race, sex, f)][0] for f in range(5)}
hd_by_field = collections.defaultdict(set)
for c in conv:
if c[1] == race and c[2] == sex:
hd_by_field[c[3] - 1].add(conv_option.get(c[5]))
for f in range(5):
opt = options[f]
if opt not in have['ChrCustomizationOption']:
hd_opt = hd_option.get(min(o for o in hd_by_field[f] if o in hd_option))
new['ChrCustomizationOption'].append(dict(ID=opt, Name_lang=hd_opt['Name_lang'] if hd_opt else FIELD[f]['name'],
SecondaryID=take('secondary'), Flags=FIELD[f]['flags'], ChrModelID=sd_model, OrderIndex=FIELD[f]['order'],
ChrCustomizationCategoryID=74, OptionType=0, BarberShopCostModifier=1,
ChrCustomizationID=int(hd_opt['ChrCustomizationID']) if hd_opt else f + 1, Requirement=0,
SecondaryOrderIndex=0, AddedInPatch=0))
for value, choice in enumerate(choices[f]):
if choice in have['ChrCustomizationChoice']:
counters['native-choice-kept'] += 1
continue
hd_twin = [hd_choice[c[5]] for c in conv if c[1] == race and c[2] == sex and c[3] == f + 1 and c[4] == value and c[5] in hd_choice]
twin = hd_twin[0] if hd_twin else None
new['ChrCustomizationChoice'].append(dict(ID=choice, Name_lang=twin['Name_lang'] if twin else '',
ChrCustomizationOptionID=opt, ChrCustomizationReqID=FIELD[f]['req'], ChrCustomizationVisReqID=0,
OrderIndex=value, UiOrderIndex=value, Flags=0, AddedInPatch=0, SoundKitID=0,
SwatchColor=[int(x) for x in twin['SwatchColor'].split('|')] if twin else [0, 0]))
# Elements (Human SD shape).
if f == 0:
tex = sect.get((race, sex, 0, 0, value), ['', '', ''])
under = sect.get((race, sex, 4, 0, value), ['', '', ''])
for target, path in ((1, tex[0]), (13, under[0]), (14, under[1])):
m = material(target, path)
if m:
element(choice, mat=m[0]); texture_fdids.add(m[1])
elif f == 1:
for skin_value, skin_choice in enumerate(choices[0]):
tex = sect.get((race, sex, 1, value, skin_value), ['', '', ''])
for target, path in ((4, tex[0]), (5, tex[1])):
m = material(target, path)
if m:
element(choice, related=skin_choice, mat=m[0]); texture_fdids.add(m[1])
elif f == 2:
element(choice, geo=geoset(0, hair_geoset.get((race, sex, value), 1)))
for color_value, color_choice in enumerate(choices[3]):
tex = sect.get((race, sex, 3, value, color_value), ['', '', ''])
for target, path in ((10, tex[0]), (11, tex[1]), (12, tex[2])):
m = material(target, path)
if m:
element(choice, related=color_choice, mat=m[0]); texture_fdids.add(m[1])
elif f == 3:
for style_value, style_choice in enumerate(choices[4]):
tex = sect.get((race, sex, 2, style_value, value), ['', '', ''])
for target, path in ((7, tex[0]), (8, tex[1])):
m = material(target, path)
if m:
element(choice, related=style_choice, mat=m[0]); texture_fdids.add(m[1])
else:
g = facial.get((race, sex, value), (0, 0, 0))
for kind, v in ((1, g[0]), (3, g[1]), (2, g[2])):
element(choice, geo=geoset(kind, v if v > 0 else 1))
# HD -> SD so the toggle keeps the selection.
variant = HD_MODEL[(race, sex)]
existing_opts = {(int(r['ChrModelAltVariantID']), int(r['SourceChrCustomizationOptionID'])) for r in nat['ChrModelAltVariantOption']}
existing_choices = {int(r['SourceChrCustomizationChoiceID']) for r in nat['ChrModelAltVariantChoice']}
for f in range(5):
for hd_opt in sorted(o for o in hd_by_field[f] if o):
if (variant, hd_opt) in existing_opts:
continue
vo = take('variant_option')
new['ChrModelAltVariantOption'].append(dict(ID=vo, ChrModelAltVariantID=variant,
SourceChrCustomizationOptionID=hd_opt, VariantChrCustomizationOptionID=options[f]))
for c in conv:
if c[1] == race and c[2] == sex and c[3] == f + 1 and conv_option.get(c[5]) == hd_opt and c[5] not in existing_choices \
and c[4] < len(choices[f]):
existing_choices.add(c[5])
new['ChrModelAltVariantChoice'].append(dict(ID=take('variant_choice'), ChrModelAltVariantOptionID=vo,
SourceChrCustomizationChoiceID=c[5], VariantChrCustomizationChoiceID=choices[f][c[4]]))
# Native SD options (Goblin 9483/9484/9485) must list exactly the profile's source-ordered choices (the codec rejects
# others): native choices outside the profile are detached (option 0; no CreatureDisplayInfoOption uses them) and kept
# native choices take their source order.
profile_choice = {c: v for (race, sex, f), (opt, cs) in profile.items() for v, c in enumerate(cs)}
profile_option = {opt for opt, _ in profile.values()}
changed = []
for r in nat['ChrCustomizationChoice']:
cid, opt = int(r['ID']), int(r['ChrCustomizationOptionID'])
if opt not in profile_option:
continue
if cid not in profile_choice:
changed.append(dict(ID=cid, ChrCustomizationOptionID=0))
elif int(r['OrderIndex']) != profile_choice[cid] or int(r['UiOrderIndex']) != profile_choice[cid]:
changed.append(dict(ID=cid, OrderIndex=profile_choice[cid], UiOrderIndex=profile_choice[cid]))
# Swatches: choices without an HD twin take the detached native choice at the same order, else the previous value's.
detached = {(int(r['ChrCustomizationOptionID']), int(r['OrderIndex'])): [int(x) for x in r['SwatchColor'].split('|')]
for r in nat['ChrCustomizationChoice'] if int(r['ID']) in {c['ID'] for c in changed if c.get('ChrCustomizationOptionID') == 0}}
previous = {}
for c in sorted(new['ChrCustomizationChoice'], key=lambda c: (c['ChrCustomizationOptionID'], c['OrderIndex'])):
if c['SwatchColor'] == [0, 0]:
c['SwatchColor'] = detached.get((c['ChrCustomizationOptionID'], c['OrderIndex'])) or previous.get(c['ChrCustomizationOptionID'], [0, 0])
counters['swatch-filled'] += c['SwatchColor'] != [0, 0]
previous[c['ChrCustomizationOptionID']] = c['SwatchColor']
(out / 'set-ChrCustomizationChoice.json').write_text(json.dumps(changed))
# Native SD options shared with the profile (Goblin 9483/9484/9485, NPC-era flags 80 = label "-Select-") take the
# Human SD player shape: flags/order of their source field.
field_of = {opt: f for (race, sex, f), (opt, _) in profile.items()}
native_opts = []
for r in nat['ChrCustomizationOption']:
opt = int(r['ID'])
if opt in field_of:
want = dict(Flags=FIELD[field_of[opt]]['flags'], OrderIndex=FIELD[field_of[opt]]['order'], SecondaryOrderIndex=0)
diff = {k: v for k, v in want.items() if int(r[k]) != v}
if diff:
native_opts.append(dict(ID=opt, **diff))
# Native Goblin HD->SD choice rows must land on the profile's choice for the same source value (create keeps the HD
# selection and derives the SD one through these rows; a detached target shows '-Select-').
want_variant, fill_option = {}, {}
for (race, sex), _ in SD_MODEL.items():
for c in conv:
if c[1] == race and c[2] == sex and c[4] < len(profile[(race, sex, c[3] - 1)][1]):
want_variant.setdefault(c[5], profile[(race, sex, c[3] - 1)][1][c[4]])
# HD choices the conversion profile does not cover (HD has more skins/faces than Octo) take the SD choice with the nearest
# swatch colour, else the nearest order position, so every HD selection has an SD look.
sd_choice_rows = {int(r['ID']): r for r in nat['ChrCustomizationChoice']}
sd_choice_rows.update({c['ID']: {k: (('|'.join(map(str, v))) if isinstance(v, list) else v) for k, v in c.items()}
for c in new['ChrCustomizationChoice']})
detached_ids = {c['ID'] for c in changed if c.get('ChrCustomizationOptionID') == 0}
def rgb(r):
v = int(str(r['SwatchColor']).split('|')[0]) & 0xFFFFFF
return (v >> 16 & 255, v >> 8 & 255, v & 255) if v else None
variant_options = [(int(r['ID']), int(r['ChrModelAltVariantID']), int(r['SourceChrCustomizationOptionID']), int(r['VariantChrCustomizationOptionID']))
for r in nat['ChrModelAltVariantOption']] + \
[(r['ID'], r['ChrModelAltVariantID'], r['SourceChrCustomizationOptionID'], r['VariantChrCustomizationOptionID'])
for r in new['ChrModelAltVariantOption']]
for vo, variant, src_opt, dst_opt in variant_options:
if variant not in HD_MODEL.values():
continue
targets = sorted((int(r['OrderIndex']), cid) for cid, r in sd_choice_rows.items()
if int(r['ChrCustomizationOptionID']) == dst_opt and cid not in detached_ids)
sources = sorted((int(r['OrderIndex']), int(r['ID'])) for r in nat['ChrCustomizationChoice'] if int(r['ChrCustomizationOptionID']) == src_opt)
if not targets:
continue
for k, (_, hd) in enumerate(sources):
if hd in want_variant:
continue
col = rgb(hd_choice[hd]) if hd in hd_choice else None
cols = [(rgb(sd_choice_rows[t]), t) for _, t in targets]
if col and all(c for c, _ in cols):
pick = min(cols, key=lambda ct: sum((a - b) ** 2 for a, b in zip(ct[0], col)))[1]
counters['hd-fill-swatch'] += 1
else:
pick = targets[min(len(targets) - 1, k * len(targets) // max(1, len(sources)))][1]
counters['hd-fill-order'] += 1
want_variant[hd] = pick
fill_option[hd] = vo
native_variant = []
have_variant = set()
for r in nat['ChrModelAltVariantChoice']:
src, dst = int(r['SourceChrCustomizationChoiceID']), int(r['VariantChrCustomizationChoiceID'])
have_variant.add(src)
if src in want_variant and want_variant[src] != dst:
native_variant.append(dict(ID=int(r['ID']), VariantChrCustomizationChoiceID=want_variant[src]))
have_variant |= {r['SourceChrCustomizationChoiceID'] for r in new['ChrModelAltVariantChoice']}
for hd, vo in sorted(fill_option.items()):
if hd not in have_variant:
new['ChrModelAltVariantChoice'].append(dict(ID=take('variant_choice'), ChrModelAltVariantOptionID=vo,
SourceChrCustomizationChoiceID=hd, VariantChrCustomizationChoiceID=want_variant[hd]))
counters['hd-fill-rows'] += 1
(out / 'set-ChrModelAltVariantChoice.json').write_text(json.dumps(native_variant))
counters['native-variant-choice-set'] = len(native_variant)
(out / 'set-ChrCustomizationOption.json').write_text(json.dumps(native_opts))
counters['native-option-set'] = len(native_opts)
counters['native-choice-set'] = len(changed)
for table, items in new.items():
(out / f'{table}.json').write_text(json.dumps(items))
(out / 'missing-textures.json').write_text(json.dumps(missing, indent=1))
(out / 'imported-textures.json').write_text(json.dumps({f: p.lower().replace('\\', '/') for p, f in imported.items()}, indent=1))
(out / 'texture-fdids.json').write_text(json.dumps(sorted(texture_fdids)))
summary = {t: len(v) for t, v in sorted(new.items())}
summary.update(counters, missing_textures=len(missing), imported_textures=len(imported), textures=len(texture_fdids))
(out / 'summary.json').write_text(json.dumps(summary, indent=1) + '\n')
print(summary)
if __name__ == '__main__':
main(*sys.argv[1:3])