367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
531 lines
27 KiB
Python
531 lines
27 KiB
Python
#!/usr/bin/env python3
|
|
"""Octo-only creature displays -> native 70334 CreatureDisplayInfo/CreatureModelData.
|
|
|
|
REA (runtime/continuation-20261111/creatures/rea-*.private.log):
|
|
- The gateway passes a Source UNIT_FIELD_DISPLAYID through unchanged
|
|
(src/forever_create.cpp), so the native client needs a CDI row with the
|
|
Source display ID. For the 10,529 Source displays the native client already
|
|
defines, BloodID, Alpha, NPCSoundID, SoundID, scale and ExtendedDisplayInfoID
|
|
equal the Source DBC values (>=99%); the other native fields are constants
|
|
(UnarmedWeaponType -1, PetInstanceScale 1, MountMaxBankingAngle 45, ...).
|
|
- 557 native CMD rows share a model path with a Source CMD row: Flags,
|
|
SizeClass, ModelScale, BloodID, footprint fields and FoleyMaterialID match;
|
|
Source SoundID (legacy field 13) equals native SoundID in 494/557; legacy
|
|
shake sizes map to camera-effect IDs (FOOTSTEP/DEATH_THUD below); WalkSpeed
|
|
equals the Walk (4) sequence move speed in 273/395. Native GeoBox is close
|
|
to the model's vertex extent; collision sizes were re-authored natively, so
|
|
the Source values (server semantics) are kept.
|
|
- Legacy v256 creature models carry portrait cameras (94/96), particles (19),
|
|
ribbons (2) and UV animation (6) that the reviewed equipment converter does
|
|
not convert. They are dropped (recorded per model) so geometry, skeleton,
|
|
animation and materials convert through the existing converter; creature
|
|
replaceable texture types 11-13 are restored after conversion.
|
|
|
|
Held-model repairs (``repair=True``; runtime/continuation-20261111/creature-held/rea-*.private.*):
|
|
- Source batch shading: the Source client (Octo WoW.exe GetPixelShaderId 0x71df30 /
|
|
GetVertexShaderId 0x71de50, receipts under runtime/rea-system-jobs-20261022) ignores the
|
|
stored batch shader word. Both texture stages take the combiner of
|
|
materials[materialIndex].blend via the table at 0x8120d4 (blend 0 -> opaque, 1-4 -> mod,
|
|
5-6 -> kind 3); a texture coordinate lookup of -1 selects environment mapping. On 3000
|
|
local native 70334 creature models the non-table shader word sets 0x10 exactly when the
|
|
material blend is non-zero (no exception), and UV/environment selection is carried by the
|
|
word (0x80 stage 0 env, 0x08 stage 1 env, 0x4000 second UV set), not by coordinate combos.
|
|
Every batch of a repaired model therefore gets the word computed from the Source inputs;
|
|
batch flags/priority plane are the same bytes natively and are kept.
|
|
- Empty skin sections (no vertices) and the batches drawing them are removed; replaceable
|
|
texture types the creature renderer never fills (3-10) stay unbound replaceable slots;
|
|
invalid animation windows become empty windows at 0; single keys at a nonzero time without
|
|
ranges move to 0 (Source FindKey uses the whole one-key array); unordered global-sequence
|
|
keys are sorted.
|
|
"""
|
|
import hashlib
|
|
import struct
|
|
|
|
import m2_equipment_convert as equipment
|
|
import m2_sequence_contract as sequences
|
|
|
|
# Legacy v256 header offsets (count, offset pairs).
|
|
DROPPED_FEATURES = (('texture transforms', 116), ('lights', 284), ('cameras', 292),
|
|
('camera lookup', 300), ('ribbons', 308), ('particles', 316))
|
|
KEPT_GLOBAL_FLAGS = 0x3 # tilt X/Y: same meaning natively
|
|
CREATURE_TEXTURE_TYPES = {1, 11, 12, 13}
|
|
# Legacy shake size -> native camera effect, modal mapping over the 557 shared models.
|
|
FOOTSTEP_CAMERA = {0: 0, 1: 1092, 2: 1095, 10: 1091}
|
|
DEATH_THUD_CAMERA = {0: 0, 10: 1091, 11: 1093, 12: 1094}
|
|
CDI_DEFAULTS = dict(ParticleColorID=0, PortraitCreatureDisplayInfoID=0, PortraitTextureFileDataID=0,
|
|
ObjectEffectPackageID=0, AnimReplacementSetID=0, Flags=0, StateSpellVisualKitID=0,
|
|
PlayerOverrideScale=0.0, PetInstanceScale=1.0, UnarmedWeaponType=-1,
|
|
MountPoofSpellVisualKitID=0, DissolveEffectID=0, DissolveOutEffectID=0,
|
|
CreatureModelMinLod=0, ConditionalCreatureModelID=0, MountMaxBankingAngle=45.0,
|
|
Field_11_0_0_54210_026=0)
|
|
CMD_DEFAULTS = dict(WorldEffectScale=1.0, CreatureGeosetDataID=0, HoverHeight=0.0, AttachedEffectScale=1.0,
|
|
MissileCollisionRadius=0.0, MissileCollisionPush=0.0, MissileCollisionRaise=0.0,
|
|
MountHeight=0.0, OverrideLootEffectScale=0.0, OverrideNameScale=0.0,
|
|
OverrideSelectionRadius=0.0, TamedPetBaseScale=1.0, MountScaleOtherIndex=0,
|
|
MountScaleSelf=1.0, Field_11_0_0_54210_032=0, MountScaleOther=[1.0, 1.0])
|
|
DEFAULT_WALK, DEFAULT_RUN = 2.5, 8.0
|
|
# Octo WoW.exe 0x8120d4: material blend mode -> Source texture-stage combiner kind.
|
|
SOURCE_BLEND_STAGE = (1, 2, 2, 2, 2, 3, 3)
|
|
UNBOUND_REPLACEABLE_TYPES = {3, 4, 5, 6, 7, 8, 9, 10}
|
|
|
|
|
|
def _f(value):
|
|
return struct.unpack('<f', struct.pack('<I', value))[0]
|
|
|
|
|
|
def _s(value):
|
|
return value - (1 << 32) if value >> 31 else value
|
|
|
|
|
|
def legacy_dbc(raw):
|
|
if raw[:4] != b'WDBC':
|
|
raise ValueError('Legacy WDBC required')
|
|
n, fields, size, strings = struct.unpack_from('<4I', raw, 4)
|
|
if size != 4 * fields or 20 + n * size + strings != len(raw):
|
|
raise ValueError('Legacy DBC extent mismatch')
|
|
table = 20 + n * size
|
|
rows = [struct.unpack_from('<%dI' % fields, raw, 20 + i * size) for i in range(n)]
|
|
|
|
def text(offset):
|
|
end = raw.index(b'\0', table + offset)
|
|
return raw[table + offset:end].decode('latin1')
|
|
return rows, text, fields
|
|
|
|
|
|
def source_displays(raw):
|
|
rows, text, fields = legacy_dbc(raw)
|
|
if fields != 12:
|
|
raise ValueError('Legacy CreatureDisplayInfo width 12 required')
|
|
return {r[0]: dict(ID=r[0], ModelID=r[1], SoundID=r[2], ExtendedDisplayInfoID=r[3],
|
|
CreatureModelScale=_f(r[4]), CreatureModelAlpha=r[5],
|
|
TextureVariation=[text(x) for x in r[6:9]], SizeClass=_s(r[9]), BloodID=r[10],
|
|
NPCSoundID=r[11]) for r in rows}
|
|
|
|
|
|
def source_models(raw):
|
|
rows, text, fields = legacy_dbc(raw)
|
|
if fields != 16:
|
|
raise ValueError('Legacy CreatureModelData width 16 required')
|
|
out = {}
|
|
for r in rows:
|
|
path = text(r[2]).replace('\\', '/').lower()
|
|
if path.endswith('.mdx') or path.endswith('.mdl'):
|
|
path = path[:-4] + '.m2'
|
|
out[r[0]] = dict(ID=r[0], Flags=r[1], Path=path, SizeClass=_s(r[3]), ModelScale=_f(r[4]), BloodID=r[5],
|
|
FootprintTextureID=r[6], FootprintTextureLength=_f(r[7]),
|
|
FootprintTextureWidth=_f(r[8]), FootprintParticleScale=_f(r[9]),
|
|
FoleyMaterialID=r[10], FootstepShakeSize=r[11], DeathThudShakeSize=r[12],
|
|
SoundID=r[13], CollisionWidth=_f(r[14]), CollisionHeight=_f(r[15]))
|
|
return out
|
|
|
|
|
|
def texture_path(model_path, token):
|
|
"""Legacy CDI texture variation token -> lowercase listfile path."""
|
|
path = token.replace('\\', '/').lower()
|
|
if '/' not in path:
|
|
path = model_path.rsplit('/', 1)[0] + '/' + path
|
|
return path if path.endswith('.blp') else path + '.blp'
|
|
|
|
|
|
def prepare_source_model(raw, repair=False):
|
|
"""Drop legacy features the equipment converter cannot express; record them."""
|
|
if raw[:4] != b'MD20' or struct.unpack_from('<I', raw, 4)[0] != 256:
|
|
raise ValueError('Legacy v256 creature model required')
|
|
out = bytearray(raw)
|
|
repairs = {}
|
|
if repair:
|
|
removed = remove_empty_sections(out)
|
|
if removed:
|
|
repairs['empty_sections_removed'] = removed
|
|
dropped = {}
|
|
for name, at in DROPPED_FEATURES:
|
|
count = struct.unpack_from('<I', raw, at)[0]
|
|
if count:
|
|
dropped[name] = count
|
|
struct.pack_into('<II', out, at, 0, 0)
|
|
if 'texture transforms' in dropped:
|
|
count, at = struct.unpack_from('<II', raw, 172)
|
|
struct.pack_into('<%dH' % count, out, at, *([0xFFFF] * count))
|
|
flags = struct.unpack_from('<I', raw, 16)[0]
|
|
struct.pack_into('<I', out, 16, 0)
|
|
count, at = struct.unpack_from('<II', raw, 92)
|
|
types = [struct.unpack_from('<I', raw, at + 16 * i)[0] for i in range(count)]
|
|
for i, kind in enumerate(types):
|
|
if kind in CREATURE_TEXTURE_TYPES or (repair and kind in UNBOUND_REPLACEABLE_TYPES):
|
|
struct.pack_into('<I', out, at + 16 * i, 0)
|
|
elif kind not in (0, 2):
|
|
raise ValueError('Unreviewed creature texture type %d' % kind)
|
|
count, at = struct.unpack_from('<II', raw, 28)
|
|
windows = [struct.unpack_from('<II', raw, at + 68 * i + 4) for i in range(count)]
|
|
if repair:
|
|
bad = [i for i, (s, e) in enumerate(windows) if e < s]
|
|
for i in bad:
|
|
struct.pack_into('<II', out, at + 68 * i + 4, 0, 0)
|
|
windows[i] = (0, 0)
|
|
if bad:
|
|
repairs['empty_windows'] = bad
|
|
if not count or any(e < s for s, e in windows):
|
|
raise ValueError('Invalid source animation window')
|
|
out, tracks = normalize_legacy_tracks(bytes(out), windows, repair)
|
|
audit = dict(dropped_features=dropped, source_global_flags=flags,
|
|
kept_global_flags=flags & KEPT_GLOBAL_FLAGS, texture_types=types, track_normalization=tracks)
|
|
if repair:
|
|
audit['repairs'] = repairs
|
|
return out, audit
|
|
|
|
|
|
def _views(raw):
|
|
count, at = struct.unpack_from('<II', raw, 76)
|
|
return [(at + 44 * v, struct.unpack_from('<11I', raw, at + 44 * v)) for v in range(count)]
|
|
|
|
|
|
def remove_empty_sections(out):
|
|
"""Remove skin sections without vertices (and their batches) from embedded v256 views, in place."""
|
|
removed = []
|
|
for view_at, h in _views(out):
|
|
sections = [bytes(out[h[7] + 32 * i:h[7] + 32 * i + 32]) for i in range(h[6])]
|
|
keep = [i for i, row in enumerate(sections) if struct.unpack_from('<H', row, 6)[0]]
|
|
if len(keep) == len(sections):
|
|
continue
|
|
remap = {old: new for new, old in enumerate(keep)}
|
|
out[h[7]:h[7] + 32 * len(keep)] = b''.join(sections[i] for i in keep)
|
|
batches = []
|
|
for i in range(h[8]):
|
|
row = bytearray(out[h[9] + 24 * i:h[9] + 24 * i + 24])
|
|
section, geoset = struct.unpack_from('<HH', row, 4)
|
|
if section not in remap:
|
|
continue
|
|
struct.pack_into('<HH', row, 4, remap[section], remap.get(geoset, remap[section]))
|
|
batches.append(bytes(row))
|
|
out[h[9]:h[9] + 24 * len(batches)] = b''.join(batches)
|
|
struct.pack_into('<I', out, view_at + 24, len(keep))
|
|
struct.pack_into('<I', out, view_at + 32, len(batches))
|
|
removed.append(dict(sections=[i for i in range(len(sections)) if i not in remap],
|
|
batches_removed=h[8] - len(batches)))
|
|
return removed
|
|
|
|
|
|
def native_shader_word(blend, coords):
|
|
"""Source batch shading inputs -> native non-table batch shader word.
|
|
|
|
blend: materials[materialIndex].blend; coords: texture coordinate lookup values
|
|
of each stage (-1 environment, 0 first UV set, 1 second UV set).
|
|
"""
|
|
if not 0 <= blend < len(SOURCE_BLEND_STAGE) or len(coords) not in (1, 2):
|
|
raise ValueError('Unreviewed Source batch blend or texture count')
|
|
if any(c not in (-1, 0, 1) for c in coords):
|
|
raise ValueError('Unreviewed Source texture coordinate lookup')
|
|
kind = SOURCE_BLEND_STAGE[blend]
|
|
word = 0 if kind == 1 else 0x10
|
|
if coords[0] == -1:
|
|
word |= 0x80
|
|
elif coords[0] == 1:
|
|
if len(coords) == 2:
|
|
raise ValueError('Second UV set on the first of two stages has no native word')
|
|
word |= 0x4000
|
|
if len(coords) == 2:
|
|
word |= 0 if kind == 1 else 1
|
|
if coords[1] == -1:
|
|
word |= 0x08
|
|
elif coords[1] == 1:
|
|
word |= 0x4000
|
|
return word
|
|
|
|
|
|
def qualify_source_batches(raw):
|
|
"""Plan native batch rows for every embedded view; return (gate-form raw, plan, audit).
|
|
|
|
The equipment converter copies batch rows verbatim but only admits single-texture
|
|
shader-0 rows; the gate form satisfies it and restore_native_batches puts the
|
|
planned rows (Source bytes + computed shader word) back into the converted skins.
|
|
"""
|
|
def lookup(offset, fmt):
|
|
count, at = struct.unpack_from('<II', raw, offset)
|
|
return [struct.unpack_from(fmt, raw, at + struct.calcsize(fmt) * i)[0] for i in range(count)]
|
|
count, at = struct.unpack_from('<II', raw, 132)
|
|
blends = [struct.unpack_from('<HH', raw, at + 4 * i)[1] for i in range(count)]
|
|
textures, coords = lookup(148, '<H'), lookup(156, '<h')
|
|
weights, transforms = lookup(164, '<H'), lookup(172, '<H')
|
|
out = bytearray(raw)
|
|
plan, audit = [], dict(words={}, two_stage=0, kind3_as_mod=0, changed_words=0)
|
|
# Two-stage rows authored for one shared batch weight can end at the last
|
|
# weight/transform lookup entry; the Source shaders read neither for stage 2.
|
|
# Pad those lookups (last weight repeated, no transform) so stage 2 resolves.
|
|
need_w = need_x = 0
|
|
for _, h in _views(raw):
|
|
for i in range(h[8]):
|
|
n, _, _, wco, xco = struct.unpack_from('<5H', raw, h[9] + 24 * i + 14)
|
|
need_w, need_x = max(need_w, wco + n), max(need_x, xco + n)
|
|
for offset, table, need, pad, fmt in ((164, weights, need_w, weights[-1:] or [0], '<H'),
|
|
(172, transforms, need_x, [0xFFFF], '<H')):
|
|
if table and need == len(table) + 1:
|
|
table.append(pad[0])
|
|
out.extend(bytes((-len(out)) % 16))
|
|
struct.pack_into('<II', out, offset, len(table), len(out))
|
|
out.extend(struct.pack('<%dH' % len(table), *table))
|
|
audit['padded_lookup_%d' % offset] = 1
|
|
for view_at, h in _views(raw):
|
|
rows = []
|
|
for i in range(h[8]):
|
|
at = h[9] + 24 * i
|
|
fl, pr, sh, sec, geo, col, mat, layer, n, tco, cco, wco, xco = struct.unpack_from('<Bb11H', raw, at)
|
|
if n not in (1, 2) or mat >= len(blends) or sec >= h[6] or geo >= h[6]:
|
|
raise ValueError('Unreviewed Source batch binding')
|
|
if tco + n > len(textures) or cco + n > len(coords) or wco + n > len(weights) or xco + n > len(transforms):
|
|
raise ValueError('Source batch combo outside lookup tables')
|
|
word = native_shader_word(blends[mat], coords[cco:cco + n])
|
|
row = bytearray(raw[at:at + 24])
|
|
struct.pack_into('<H', row, 2, word)
|
|
rows.append(bytes(row))
|
|
struct.pack_into('<BbH', out, at, 0, 0, 0)
|
|
struct.pack_into('<H', out, at + 14, 1)
|
|
key = '%d:%d->%d' % (n, sh, word)
|
|
audit['words'][key] = audit['words'].get(key, 0) + 1
|
|
audit['two_stage'] += n == 2
|
|
audit['kind3_as_mod'] += n == 2 and SOURCE_BLEND_STAGE[blends[mat]] == 3
|
|
audit['changed_words'] += sh != word
|
|
plan.append(rows)
|
|
return bytes(out), plan, audit
|
|
|
|
|
|
def restore_native_batches(skin_raw, rows):
|
|
"""Write planned batch rows into a converted native SKIN (rows copied verbatim by the converter)."""
|
|
count, at = struct.unpack_from('<II', skin_raw, 36)
|
|
if count != len(rows):
|
|
raise ValueError('Converted skin batch count differs from plan')
|
|
out = bytearray(skin_raw)
|
|
out[at:at + 24 * count] = b''.join(rows)
|
|
return bytes(out)
|
|
|
|
|
|
def sampled_textures(body, skins):
|
|
"""Texture indices a native272 body + skins actually sample (texture lookup per batch stage)."""
|
|
count, at = struct.unpack_from('<II', body, 0x80)
|
|
lookup = [struct.unpack_from('<H', body, at + 2 * i)[0] for i in range(count)]
|
|
used = set()
|
|
for skin_raw in skins:
|
|
n, ob = struct.unpack_from('<II', skin_raw, 36)
|
|
for i in range(n):
|
|
texture_count, combo = struct.unpack_from('<HH', skin_raw, ob + 24 * i + 14)
|
|
used.update(lookup[combo + k] for k in range(texture_count) if combo + k < len(lookup))
|
|
return used
|
|
|
|
|
|
_TRACK_STRIDES = {'vec3': 12, 'quaternion': 16, 'fixed16': 2, 'visibility': 1}
|
|
|
|
|
|
def _legacy_track_sites(raw):
|
|
"""(header offset, kind) of every animated track the equipment converter reads."""
|
|
sites = []
|
|
count, at = struct.unpack_from('<II', raw, 52)
|
|
for i in range(count):
|
|
base = at + 108 * i
|
|
sites += [(base + 12, 'vec3'), (base + 40, 'quaternion'), (base + 68, 'vec3')]
|
|
count, at = struct.unpack_from('<II', raw, 84)
|
|
for i in range(count):
|
|
sites += [(at + 56 * i, 'vec3'), (at + 56 * i + 28, 'fixed16')]
|
|
count, at = struct.unpack_from('<II', raw, 100)
|
|
sites += [(at + 28 * i, 'fixed16') for i in range(count)]
|
|
count, at = struct.unpack_from('<II', raw, 260)
|
|
sites += [(at + 48 * i + 20, 'visibility') for i in range(count)]
|
|
return sites
|
|
|
|
|
|
def normalize_legacy_tracks(raw, windows, repair=False):
|
|
"""Re-express legacy creature tracks/events in the form the reviewed converter admits.
|
|
|
|
Per animation: keep the authored inclusive key range, clamp timestamps into
|
|
the animation window (legacy FindKey brackets across window edges), reduce
|
|
Hermite/Bezier keys to their values (linear), give animations without a
|
|
range their first key at the window start, and drop ranges past the
|
|
sequence count. Events keep exclusive ranges with clamped times; events
|
|
without one range per animation are dropped. New arrays are appended.
|
|
"""
|
|
out = bytearray(raw)
|
|
audit = dict(clamped_keys=0, hermite_to_linear=0, ranges_padded=0, ranges_trimmed=0, events_dropped=[])
|
|
|
|
def put(data):
|
|
out.extend(bytes((-len(out)) % 16))
|
|
at = len(out)
|
|
out.extend(data)
|
|
return at
|
|
n = len(windows)
|
|
for site, kind in _legacy_track_sites(raw):
|
|
interp, gid, nr, ro, nt, to, nk, ko = struct.unpack_from('<Hh6I', raw, site)
|
|
if not nt:
|
|
continue
|
|
stride = _TRACK_STRIDES[kind]
|
|
width = stride * (3 if interp in (2, 3) else 1)
|
|
if nk != nt or ko + nk * width > len(raw) or to + 4 * nt > len(raw) or ro + 8 * nr > len(raw):
|
|
raise ValueError('Legacy track extent')
|
|
ranges = list(struct.iter_unpack('<II', raw[ro:ro + 8 * nr]))
|
|
times = struct.unpack_from('<%dI' % nt, raw, to)
|
|
keys = [raw[ko + k * width:ko + k * width + stride] for k in range(nk)]
|
|
if kind == 'quaternion':
|
|
fixed = [struct.pack('<4f', *(min(1.0, max(-1.0, c)) for c in struct.unpack('<4f', v))) for v in keys]
|
|
audit['quaternion_components_clamped'] = audit.get('quaternion_components_clamped', 0) + sum(a != b for a, b in zip(fixed, keys))
|
|
keys = fixed
|
|
if gid >= 0 or (nr == 0 and nt == 1):
|
|
new_to = to
|
|
if repair and gid < 0 and times[0]:
|
|
new_to = put(struct.pack('<I', 0))
|
|
audit['single_keys_to_zero'] = audit.get('single_keys_to_zero', 0) + 1
|
|
elif repair and gid >= 0 and any(a > b for a, b in zip(times, times[1:])):
|
|
order = sorted(range(nt), key=lambda k: times[k])
|
|
new_to = put(struct.pack('<%dI' % nt, *(times[k] for k in order)))
|
|
keys = [keys[k] for k in order]
|
|
audit['global_tracks_sorted'] = audit.get('global_tracks_sorted', 0) + 1
|
|
struct.pack_into('<Hh6I', out, site, min(interp, 1), gid, nr, ro, nt, new_to, nk, put(b''.join(keys)))
|
|
audit['hermite_to_linear'] += interp in (2, 3)
|
|
continue
|
|
if interp in (2, 3) or kind == 'quaternion' or new_to != to:
|
|
audit['hermite_to_linear'] += interp in (2, 3)
|
|
struct.pack_into('<Hh6I', out, site, min(interp, 1), gid, nr, ro, nt, new_to, nk, put(b''.join(keys)))
|
|
continue
|
|
if nr == n + 1 and ranges[-1] == (0, 0):
|
|
ranges.pop()
|
|
audit['ranges_trimmed'] += max(0, len(ranges) - n)
|
|
audit['ranges_padded'] += max(0, n - len(ranges))
|
|
new_times, new_keys, new_ranges = [], [], []
|
|
for i, (start, stop) in enumerate(windows):
|
|
begin, end = ranges[i] if i < len(ranges) else (0, 0)
|
|
if not 0 <= begin <= end < nt:
|
|
begin = end = min(begin, nt - 1)
|
|
if i >= len(ranges):
|
|
picked = [(start, keys[0])]
|
|
else:
|
|
picked = []
|
|
for k in range(begin, end + 1):
|
|
t = min(max(times[k], start), stop)
|
|
audit['clamped_keys'] += t != times[k]
|
|
picked.append((t, keys[k]))
|
|
picked.sort(key=lambda p: p[0])
|
|
first = len(new_times)
|
|
for t, v in picked:
|
|
new_times.append(t)
|
|
new_keys.append(v)
|
|
new_ranges.append((first, len(new_times) - 1))
|
|
if interp in (2, 3):
|
|
audit['hermite_to_linear'] += 1
|
|
struct.pack_into('<Hh6I', out, site, min(interp, 1), gid, n,
|
|
put(b''.join(struct.pack('<II', *r) for r in new_ranges)), len(new_times),
|
|
put(struct.pack('<%dI' % len(new_times), *new_times)), len(new_keys), put(b''.join(new_keys)))
|
|
count, at = struct.unpack_from('<II', raw, 276)
|
|
kept = []
|
|
for i in range(count):
|
|
event = bytearray(raw[at + 44 * i:at + 44 * i + 44])
|
|
interp, gid, nr, ro, nt, to = struct.unpack_from('<Hh4I', event, 24)
|
|
ranges = list(struct.iter_unpack('<II', raw[ro:ro + 8 * nr]))
|
|
if nr == n + 1 and ranges[-1] == (0, 0):
|
|
ranges.pop()
|
|
if interp or gid != -1 or len(ranges) != n:
|
|
audit['events_dropped'].append(bytes(event[:4]).decode('latin1'))
|
|
continue
|
|
times = struct.unpack_from('<%dI' % nt, raw, to)
|
|
new_times, new_ranges = [], []
|
|
for (begin, end), (start, stop) in zip(ranges, windows):
|
|
first = len(new_times)
|
|
for k in range(begin, min(end, nt)):
|
|
t = min(max(times[k], start), stop)
|
|
audit['clamped_keys'] += t != times[k]
|
|
new_times.append(t)
|
|
new_times[first:] = sorted(new_times[first:])
|
|
new_ranges.append((first, len(new_times)))
|
|
struct.pack_into('<Hh4I', event, 24, 0, -1, n, put(b''.join(struct.pack('<II', *r) for r in new_ranges)),
|
|
len(new_times), put(struct.pack('<%dI' % len(new_times), *new_times)) if new_times else 0)
|
|
kept.append(bytes(event))
|
|
if count:
|
|
struct.pack_into('<II', out, 276, len(kept), put(b''.join(kept)) if kept else 0)
|
|
return bytes(out), audit
|
|
|
|
|
|
def _append(body, data):
|
|
body.extend(bytes((-len(body)) % 16))
|
|
at = len(body)
|
|
body.extend(data)
|
|
return at
|
|
|
|
|
|
def convert_creature_model(raw, repair=False):
|
|
"""Legacy v256 creature M2 -> native272 MD20 body + skins + audit."""
|
|
prepared, audit = prepare_source_model(raw, repair)
|
|
if repair:
|
|
prepared, plan, audit['batch_shading'] = qualify_source_batches(prepared)
|
|
body, skins, report = equipment.convert_equipment(prepared)
|
|
if repair:
|
|
if len(skins) != len(plan):
|
|
raise ValueError('Converted view count differs from plan')
|
|
skins = [restore_native_batches(s, rows) for s, rows in zip(skins, plan)]
|
|
out = bytearray(body)
|
|
types = audit['texture_types']
|
|
count, at = struct.unpack_from('<II', out, 80)
|
|
if count != len(types):
|
|
raise ValueError('Native texture array differs from source')
|
|
for i, kind in enumerate(types):
|
|
struct.pack_into('<I', out, at + 16 * i, kind)
|
|
lc, lo = struct.unpack_from('<II', out, 104)
|
|
old = list(struct.unpack_from('<%dh' % lc, out, lo)) if lc else []
|
|
lookup = [-1] * (max(types) + 1 if types else 0)
|
|
for kind in (0, 2):
|
|
if kind < len(old) and kind < len(lookup):
|
|
lookup[kind] = old[kind]
|
|
for kind in set(types) & (CREATURE_TEXTURE_TYPES | (UNBOUND_REPLACEABLE_TYPES if repair else set())):
|
|
lookup[kind] = max(i for i, t in enumerate(types) if t == kind)
|
|
if lookup:
|
|
struct.pack_into('<II', out, 104, len(lookup),
|
|
_append(out, struct.pack('<%dh' % len(lookup), *lookup)))
|
|
struct.pack_into('<I', out, 16, audit['kept_global_flags'])
|
|
body, seq = sequences.normalize_m2_sequences(bytes(out))
|
|
body, stand = sequences.insert_stand(body)
|
|
body, keys = sequences.dedupe_track_keys(body)
|
|
audit.update(sequence_contract=seq, stand=stand, distinct_key_times=keys, replaceable_lookup=lookup,
|
|
source_sha256=hashlib.sha256(raw).hexdigest(),
|
|
native_body_sha256=hashlib.sha256(body).hexdigest(), skins=len(skins),
|
|
converter=report['kind'], installed=False, engine_loaded=False)
|
|
return body, skins, audit
|
|
|
|
|
|
def body_metrics(body):
|
|
"""Vertex extent (GeoBox) and Walk/Run move speeds of a native272 MD20 body."""
|
|
nv, ov = struct.unpack_from('<II', body, 0x3C)
|
|
points = [struct.unpack_from('<3f', body, ov + 48 * i) for i in range(nv)]
|
|
if points:
|
|
box = [min(p[k] for p in points) for k in range(3)] + [max(p[k] for p in points) for k in range(3)]
|
|
else: # vertexless (effect-only) model: header bounding box
|
|
box = list(struct.unpack_from('<6f', body, 0xA0))
|
|
ns, os_ = struct.unpack_from('<II', body, 0x1C)
|
|
speeds = {}
|
|
for k in range(ns):
|
|
animation, _, _, speed = struct.unpack_from('<HHIf', body, os_ + 64 * k)
|
|
speeds.setdefault(animation, speed)
|
|
return dict(geo_box=box, walk=speeds.get(4) or DEFAULT_WALK, run=DEFAULT_RUN)
|
|
|
|
|
|
def cmd_record(source, file_data_id, metrics):
|
|
record = dict(CMD_DEFAULTS)
|
|
record['MountScaleOther'] = list(CMD_DEFAULTS['MountScaleOther'])
|
|
record.update(GeoBox=[float(v) for v in metrics['geo_box']], Flags=source['Flags'],
|
|
FileDataID=file_data_id, WalkSpeed=float(metrics['walk']), RunSpeed=float(metrics['run']),
|
|
BloodID=source['BloodID'], FootprintTextureID=source['FootprintTextureID'],
|
|
FootprintTextureLength=source['FootprintTextureLength'],
|
|
FootprintTextureWidth=source['FootprintTextureWidth'],
|
|
FootprintParticleScale=source['FootprintParticleScale'],
|
|
FoleyMaterialID=source['FoleyMaterialID'],
|
|
FootstepCameraEffectID=FOOTSTEP_CAMERA.get(source['FootstepShakeSize'], 0),
|
|
DeathThudCameraEffectID=DEATH_THUD_CAMERA.get(source['DeathThudShakeSize'], 0),
|
|
SoundID=source['SoundID'], SizeClass=source['SizeClass'],
|
|
CollisionWidth=source['CollisionWidth'], CollisionHeight=source['CollisionHeight'],
|
|
ModelScale=source['ModelScale'])
|
|
return record
|
|
|
|
|
|
def cdi_record(source, model_id, textures, gender=2, extended=0):
|
|
if len(textures) != 3 or not 0 < model_id <= 0xFFFF:
|
|
raise ValueError('Native CDI needs a u16 ModelID and three texture slots')
|
|
record = dict(CDI_DEFAULTS)
|
|
record.update(ID=source['ID'], ModelID=model_id, SoundID=source['SoundID'], SizeClass=source['SizeClass'],
|
|
CreatureModelScale=source['CreatureModelScale'], CreatureModelAlpha=source['CreatureModelAlpha'],
|
|
BloodID=source['BloodID'], ExtendedDisplayInfoID=extended, NPCSoundID=source['NPCSoundID'],
|
|
Gender=gender, TextureVariationFileDataID=list(textures) + [0])
|
|
return record
|