367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
3042 lines
181 KiB
Python
3042 lines
181 KiB
Python
#!/usr/bin/env python3
|
|
"""Map dependency component of the local Octo -> Forever content pipeline.
|
|
|
|
Read-only candidate inventory, never an installer or a claim of map support.
|
|
Uses existing DBC ingestion and WoWee's chunked WDT conventions. Candidate
|
|
archive order, same names, and WDT version numbers are not equivalence proofs.
|
|
"""
|
|
from collections import defaultdict, namedtuple
|
|
import hashlib
|
|
import re
|
|
import struct
|
|
|
|
from item_icon_preflight import MAX_LISTFILE_BYTES
|
|
|
|
|
|
def map_requests(dbc):
|
|
# First five columns agree in the reviewed legacy Map DBD blocks. Installed
|
|
# Turtle/Octo adds columns (42 vs base37); remaining fields stay opaque.
|
|
if dbc.fields not in (37,42):
|
|
raise ValueError('Unreviewed source Map column count')
|
|
if len(dbc.rows)>4096:raise ValueError('Map candidate count bound')
|
|
if len({r[0]for r in dbc.rows})!=len(dbc.rows):raise ValueError('Duplicate source map identity')
|
|
records=[]
|
|
for row in sorted(dbc.rows):
|
|
directory=dbc.string(row[1])
|
|
if not re.fullmatch(r"[A-Za-z0-9_' -]{1,128}",directory) or directory.strip()!=directory:
|
|
raise ValueError('Unsafe source map directory')
|
|
path='world/maps/'+directory.lower()+'/'+directory.lower()+'.wdt'
|
|
records.append(dict(source_map_id=row[0],directory=directory,
|
|
name_enUS=dbc.string(row[4]),wdt_path=path,
|
|
raw_row_sha256=hashlib.sha256(struct.pack('<'+'I'*dbc.fields,*row)).hexdigest()))
|
|
return dict(source_dbc_sha256=dbc.digest(),fields=dbc.fields,records=records,
|
|
effective_source_verified=False,full_field_semantics_reviewed=False,
|
|
converted=False,installed=False)
|
|
|
|
|
|
def native_wdt_names(stream,paths):
|
|
if not isinstance(paths,set) or len(paths)>4096:raise ValueError('Map path count bound')
|
|
for path in paths:
|
|
m=re.fullmatch(r"world/maps/([a-z0-9_' -]{1,128})/([a-z0-9_' -]{1,128})\.wdt",path)
|
|
if not m or m[1]!=m[2]:raise ValueError('Canonical WDT path required')
|
|
found=defaultdict(set);digest=hashlib.sha256();total=0;lines=0
|
|
while raw:=stream.readline(4097):
|
|
total+=len(raw);lines+=1
|
|
if len(raw)>4096 or total>MAX_LISTFILE_BYTES or lines>5000000:
|
|
raise ValueError('Target listfile bounds')
|
|
digest.update(raw);key,sep,value=raw.strip().partition(b';')
|
|
if not sep or not re.fullmatch(rb'[0-9]{1,10}',key) or not 0<int(key)<=0xffffffff:
|
|
raise ValueError('Malformed native file identity')
|
|
try:name=value.decode('utf-8').lower()
|
|
except UnicodeDecodeError:continue
|
|
if name in paths:found[name].add(int(key))
|
|
return dict(listfile_sha256=digest.hexdigest(),listfile_lines=lines,
|
|
records=[dict(path=p,native_file_ids=sorted(found[p]),name_present=bool(found[p]),
|
|
native_bytes_verified=False)for p in sorted(paths)],
|
|
map_id_conflicts_checked=False,terrain_equivalent=False,installed=False)
|
|
|
|
|
|
def wdt_structure(raw,directory):
|
|
"""Inventory source v18 WDT tile references, retaining opaque extensions.
|
|
|
|
MAIN is 64x64 entries of flags/async-ID; bit0 declares an ADT. Chunk names
|
|
use little-endian uint32 tags (e.g. REVM bytes), as in WoWee's WDT reader.
|
|
This does not parse ADT/WMO/M2 dependencies or assert target compatibility.
|
|
"""
|
|
if not isinstance(raw,bytes)or not 12<=len(raw)<=16777216:
|
|
raise ValueError('Bounded WDT bytes required')
|
|
if not isinstance(directory,str)or not re.fullmatch("[a-z0-9_' -]{1,128}",directory)or directory.strip()!=directory:
|
|
raise ValueError('Canonical WDT directory required')
|
|
chunks={};pos=0
|
|
while pos<len(raw):
|
|
if len(raw)-pos<8 or len(chunks)>=64:raise ValueError('Truncated/count-bounded WDT chunk')
|
|
tag,size=struct.unpack_from('<4sI',raw,pos);pos+=8;name=tag[::-1].decode('ascii')
|
|
if name in chunks or size>len(raw)-pos:raise ValueError('Duplicate/truncated WDT chunk')
|
|
chunks[name]=raw[pos:pos+size];pos+=size
|
|
if len(chunks.get('MVER',b''))!=4 or struct.unpack('<I',chunks['MVER'])[0]!=18:
|
|
raise ValueError('Unreviewed WDT version')
|
|
if len(chunks.get('MPHD',b''))!=32:raise ValueError('Unreviewed WDT MPHD extent')
|
|
tiles=[]
|
|
if 'MAIN' in chunks:
|
|
if len(chunks['MAIN'])!=64*64*8:raise ValueError('Unreviewed WDT MAIN extent')
|
|
for i,(flags,async_id)in enumerate(struct.iter_unpack('<II',chunks['MAIN'])):
|
|
if flags&1:
|
|
x,y=i%64,i//64
|
|
tiles.append(dict(x=x,y=y,flags=flags,async_id=async_id,
|
|
path=f'world/maps/{directory}/{directory}_{x}_{y}.adt'))
|
|
models=[]
|
|
if chunks.get('MWMO'):
|
|
data=chunks['MWMO']
|
|
if not data.endswith(b'\0'):raise ValueError('Unterminated WDT WMO names')
|
|
for value in data.split(b'\0'):
|
|
if not value:continue
|
|
name=value.decode('ascii').replace('\\','/').lower()
|
|
if (len(name)>1024 or not name.endswith('.wmo')or ':'in name or
|
|
any(p in('','.','..')for p in name.split('/'))or any(ord(c)<32 for c in name)):
|
|
raise ValueError('Unsafe WDT WMO path')
|
|
models.append(name)
|
|
native_tiles=[]
|
|
if 'MAID'in chunks:
|
|
# Exact target70334 contract: Trinity Forever map_extractor/wdt.h::wdt_MAID.
|
|
# MAI2 is a separate observed extension and deliberately remains opaque.
|
|
if len(chunks['MAID'])!=64*64*32:raise ValueError('Unreviewed WDT MAID extent')
|
|
names=('rootADT','obj0ADT','obj1ADT','tex0ADT','lodADT','mapTexture','mapTextureN','minimapTexture')
|
|
for i,ids in enumerate(struct.iter_unpack('<8I',chunks['MAID'])):
|
|
if any(ids):native_tiles.append(dict(x=i%64,y=i//64,files=dict(zip(names,ids))))
|
|
return dict(wdt_sha256=hashlib.sha256(raw).hexdigest(),version=18,
|
|
chunks=[dict(tag=k,bytes=len(v),sha256=hashlib.sha256(v).hexdigest())for k,v in chunks.items()],
|
|
mphd_flags=struct.unpack_from('<I',chunks['MPHD'])[0],tiles=tiles,
|
|
root_wmo_paths=models,modern_MAID_present='MAID'in chunks,
|
|
native_tile_file_ids=native_tiles,
|
|
dependency_complete=False,terrain_equivalent=False,
|
|
converted=False,installed=False,engine_verified=False)
|
|
|
|
|
|
def reuse_saved_outdoor_area_profiles(assessment, manifest, component):
|
|
"""Reuse the owning 319-row profile proof; do not construct or publish rows.
|
|
|
|
Callers must pin the owning assessment, manifest and component before passing
|
|
their decoded values. Six profiles lack the Map binding needed for composition.
|
|
Original-client UI projection and runtime behavior are separate boundaries.
|
|
"""
|
|
if (assessment.get('status') != 'PASS_FULL_OUTDOOR319_PROFILE_AND_CURRENT_MAP0_1_AREA313_COMPOSITION'
|
|
or assessment.get('complete_profile_rows') != 319
|
|
or assessment.get('current_Map0_1_rows') != 313
|
|
or assessment.get('other_common_rows_uncomposed') != 6
|
|
or manifest.get('status') != 'FULL_OUTDOOR_MISSING_AREA_DEFINITION_AND_PARENT_CLOSURE_SELECTED_FROM_FROZEN404'
|
|
or manifest.get('missing_native_area_definitions') != 319
|
|
or manifest.get('parent_closed_definition_rows') != 319
|
|
or component.get('kind') != 'owned-outdoor-AreaTable-native-profile-component-v1'
|
|
or component.get('status') != 'PASS_OUTDOOR319_PROFILE_ROWS_AND_INDEPENDENT_ENCODER_ROUNDTRIP'
|
|
or component.get('total') != 319 or component.get('Map0_1_ready_rows') != 313
|
|
or component.get('other_common_rows_pending') != 6
|
|
or component.get('exploration_state_unprojected') is not True
|
|
or component.get('runtime_verified') is not False):
|
|
raise ValueError('Owning saved outdoor Area profile proof required')
|
|
source_rows = manifest.get('rows'); rows = component.get('rows')
|
|
if not isinstance(source_rows, list) or not isinstance(rows, list) or len(source_rows) != 319 or len(rows) != 319:
|
|
raise ValueError('Complete saved outdoor Area cohort required')
|
|
by_id = {r['source_area_id']: r for r in source_rows}
|
|
if len(by_id) != 319:
|
|
raise ValueError('Unique source Area identities required')
|
|
ready, held, seen = [], [], set()
|
|
for row in rows:
|
|
ident = row.get('id'); source = by_id.get(ident); record = row.get('record')
|
|
if (source is None or ident in seen or not isinstance(record, dict)
|
|
or row.get('table_name') != 'AreaTable' or row.get('table_hash') != '0x7253EB43'
|
|
or row.get('record_status') != 'valid' or record.get('ID') != ident
|
|
or row.get('source_input') != source.get('full_Source_fragment')
|
|
or record.get('ContinentID') != source.get('Source_MapID')
|
|
or record.get('AreaName_lang') != source.get('source_name')
|
|
or row.get('original_Map0_1_binding_ready') != source.get('original_Map0_1_binding_ready')
|
|
or row.get('profile_audit', {}).get('native_runtime_verified') is not False):
|
|
raise ValueError('Saved Area profile or source relationship differs')
|
|
seen.add(ident)
|
|
if row['original_Map0_1_binding_ready'] is True and record['ContinentID'] in (0, 1):
|
|
ready.append(row)
|
|
elif row['original_Map0_1_binding_ready'] is False and record['ContinentID'] not in (0, 1):
|
|
held.append(row)
|
|
else:
|
|
raise ValueError('Saved Area map binding classification differs')
|
|
if len(ready) != 313 or len(held) != 6:
|
|
raise ValueError('Saved Area map binding counts differ')
|
|
return dict(kind='saved-outdoor-area-profile-reuse-v1', ready_rows=ready, held_rows=held,
|
|
saved_profile_rows=319, composed_map0_1_rows=313, uncomposed_map_rows=6,
|
|
ui_projection_verified=False, scene_rendering_verified=False,
|
|
exploration_and_source_behavior_projected=False, native_runtime_verified=False)
|
|
|
|
|
|
def area_native_landscape_profile_candidate(source, native_profiles, *, native_id,
|
|
map_id, parent_area_id, zone_name,
|
|
behavior_policy):
|
|
"""Author a missing area using explicit observed native presentation profiles.
|
|
|
|
Identity/Map/parent bindings are caller-owned, not inferred native aliases.
|
|
Source known-role flags select whole native behavior records; unknown Source
|
|
bits are retained in provenance. Exploration state is deliberately not
|
|
projected by this metadata operation.
|
|
"""
|
|
policy='owned-outdoor-area-original-native-profile-exploration-unprojected-v1'
|
|
if behavior_policy!=policy:
|
|
raise ValueError('Explicit owned outdoor AreaTable profile required')
|
|
if (not isinstance(source,dict) or type(native_id) is not int
|
|
or native_id!=source.get('ID') or not 0<native_id<=0x7fff
|
|
or type(map_id) is not int or not 0<=map_id<=0x7fff
|
|
or type(parent_area_id) is not int or not 0<=parent_area_id<=0x7fff
|
|
or zone_name!='WoWHybridArea_'+str(native_id)):
|
|
raise ValueError('Explicit owned area/Map/parent/internal-name bindings required')
|
|
if not isinstance(source.get('AreaName_lang'),str):
|
|
raise ValueError('Exact Source English display field required')
|
|
flags=source.get('Flags_raw');faction=source.get('FactionGroupMask')
|
|
if (type(flags) is not int or not 0<=flags<=0xffffffff
|
|
or type(faction) is not int or faction not in (0,2,4)):
|
|
raise ValueError('Reviewed Source flag/faction-role inputs required')
|
|
if flags&0x80 or flags&0x200:
|
|
raise ValueError('Arena/legacy special-city profile requires separate authority')
|
|
# Explicit Source faction roles select observed native field/profile values.
|
|
# Custom standalone Maps use the declared original Map0 landscape seed.
|
|
group={0:616,2:148,4:14} if map_id==1 else {0:33,2:40,4:85}
|
|
faction_profile_id=group[faction]
|
|
if flags&0x100:
|
|
if faction not in (2,4):
|
|
raise ValueError('Neutral capital requires an explicit original profile')
|
|
behavior_id=1519 if faction==2 else 1637
|
|
role='SOURCE_CAPITAL_ORIGINAL_NATIVE_CITY_PROFILE'
|
|
elif flags&1:
|
|
behavior_id=618 if faction==0 else 1
|
|
role='SOURCE_SNOW_ORIGINAL_NATIVE_SNOW_LANDSCAPE_PROFILE'
|
|
elif flags&0x40:
|
|
behavior_id=faction_profile_id
|
|
role='SOURCE_DUEL_ORIGINAL_NATIVE_LANDSCAPE_PROFILE'
|
|
else:
|
|
behavior_id=15531
|
|
role='SOURCE_NO_DUEL_ORIGINAL_NATIVE_NEUTRAL_PROFILE'
|
|
try:
|
|
base=native_profiles[behavior_id]
|
|
faction_profile=native_profiles[faction_profile_id]
|
|
untracked=native_profiles[15531]
|
|
except (KeyError,TypeError):
|
|
raise ValueError('Frozen original native profile records required') from None
|
|
required={'ID','ZoneName','AreaName_lang','ContinentID','ParentAreaID','AreaBit',
|
|
'SoundProviderPref','SoundProviderPrefUnderwater','AmbienceID','UwAmbience',
|
|
'ZoneMusic','UwZoneMusic','ExplorationLevel','IntroSound','UwIntroSound',
|
|
'FactionGroupMask','Ambient_multiplier','MountFlags','PvpCombatWorldStateID',
|
|
'WildBattlePetLevelMin','WildBattlePetLevelMax','WindSettingsID','ContentTuningID',
|
|
'Flags','LiquidTypeID'}
|
|
if (any(set(r)!=required for r in (base,faction_profile,untracked))
|
|
or untracked['ID']!=15531 or untracked['AreaBit']!=0
|
|
or untracked['Flags']!=[0,128] or untracked['MountFlags']!=1
|
|
or base['MountFlags']!=1 or faction_profile['FactionGroupMask']!=faction):
|
|
raise ValueError('Observed landscape/no-exploration profile operands differ')
|
|
import copy
|
|
record=copy.deepcopy(base)
|
|
record.update(ID=native_id,ZoneName=zone_name,AreaName_lang=source['AreaName_lang'],
|
|
ContinentID=map_id,ParentAreaID=parent_area_id,
|
|
AreaBit=untracked['AreaBit'],
|
|
FactionGroupMask=faction_profile['FactionGroupMask'])
|
|
# This is the observed tuple, not a claim about an unobserved client branch.
|
|
record['Flags'][1]=untracked['Flags'][1]
|
|
from spell_passive_compat import (AREA_CLASSIC_PROFILE, area_parent_projection,
|
|
area_classic_optional_none_fields)
|
|
record.update(area_parent_projection(source['ParentAreaID'],parent_area_id,
|
|
record['Flags'],profile=AREA_CLASSIC_PROFILE))
|
|
record.update(area_classic_optional_none_fields(profile=AREA_CLASSIC_PROFILE))
|
|
return record,dict(kind='owned-outdoor-AreaTable-observed-native-profile-v1',
|
|
behavior_policy=policy,original_behavior_profile_id=behavior_id,
|
|
original_faction_profile_id=faction_profile_id,
|
|
original_exploration_tuple_profile_id=15531,source_role=role,
|
|
Source_flags_raw=flags,Source_flags_not_projected=flags&~0x141,
|
|
Source_AreaBit_retained_not_projected=source.get('AreaBit'),
|
|
Source_ExplorationLevel_retained_not_projected=source.get('ExplorationLevel'),
|
|
Source_LiquidTypeID_retained_not_projected=source.get('LiquidTypeID'),
|
|
reviewed_None_fields=['PvpCombatWorldStateID','WildBattlePetLevelMin','WildBattlePetLevelMax'],
|
|
only_derived_flag='IsSubzone=ParentAreaID!=0',
|
|
internal_ZoneName_explicitly_owned_not_inferred=True,
|
|
Source_audio_mount_tuning_and_other_behavior_equivalence=False,
|
|
exploration_state_projection_implemented=False,
|
|
original_NotExplorable_client_branch_verified=False,
|
|
native_runtime_verified=False)
|
|
|
|
|
|
_GlobalWmoTemplate = namedtuple('_GlobalWmoTemplate', 'raw modf_payload_offset sha256')
|
|
_GLOBAL_WMO_NATIVE34_SHA256 = '4581b1120faaa588e9ce22be969656f73e31877df3d778a9c6f3d39f6ba76d83'
|
|
|
|
|
|
def _global_wmo_chunk_spans(raw):
|
|
if not isinstance(raw, bytes) or not 12 <= len(raw) <= 16777216:
|
|
raise ValueError('Bounded global WDT bytes required')
|
|
chunks = {}; pos = 0
|
|
while pos < len(raw):
|
|
if len(raw)-pos < 8 or len(chunks) >= 64:
|
|
raise ValueError('Truncated/count-bounded global WDT chunk')
|
|
tag, size = struct.unpack_from('<4sI', raw, pos)
|
|
try: name = tag[::-1].decode('ascii')
|
|
except UnicodeDecodeError: raise ValueError('Invalid global WDT chunk tag') from None
|
|
if name in chunks or size > len(raw)-pos-8:
|
|
raise ValueError('Duplicate/truncated global WDT chunk')
|
|
chunks[name] = (pos+8, size); pos += 8+size
|
|
return chunks
|
|
|
|
|
|
def wdt_global_wmo_native_template(raw):
|
|
"""Prepare the exact original70334 Map34 control once per source family.
|
|
|
|
This is structural authority only. Its nonempty TEX and unknown MPHD word7
|
|
are retained opaque values, not approved defaults for another map.
|
|
"""
|
|
chunks = _global_wmo_chunk_spans(raw)
|
|
digest = hashlib.sha256(raw).hexdigest()
|
|
if digest != _GLOBAL_WMO_NATIVE34_SHA256:
|
|
raise ValueError('Exact original native34 global WDT template required')
|
|
if list(chunks) != ['MVER', 'MPHD', 'MAIN', 'MAID', 'MODF']:
|
|
raise ValueError('Unreviewed native global WDT chunk family')
|
|
return _GlobalWmoTemplate(raw, chunks['MODF'][0], digest)
|
|
|
|
|
|
def wdt_global_wmo_candidate(template, source, *, directory, source_wmo_path,
|
|
mapped_root_file_data_id):
|
|
"""Build a private, held global-WMO WDT under the observed native layout.
|
|
|
|
A mapped root ID is an explicit caller binding, never inferred from names or
|
|
source IDs. This function does not establish that binding's resource proof.
|
|
Source placement/bounds bits survive exactly. All opaque native companions,
|
|
empty MAIN/MAID, and the unscaled native MODF tail remain unchanged.
|
|
"""
|
|
import math
|
|
if type(template) is not _GlobalWmoTemplate:
|
|
raise ValueError('Prepared exact native global WDT template required')
|
|
if not isinstance(directory, str) or not re.fullmatch("[a-z0-9_' -]{1,128}", directory) or directory.strip() != directory:
|
|
raise ValueError('Canonical global map directory required')
|
|
if (not isinstance(source_wmo_path, str) or len(source_wmo_path) > 1024 or
|
|
not source_wmo_path.endswith('.wmo') or source_wmo_path != source_wmo_path.lower() or
|
|
'\\' in source_wmo_path or ':' in source_wmo_path or
|
|
any(p in ('', '.', '..') for p in source_wmo_path.split('/')) or
|
|
any(ord(c) < 32 or ord(c) > 126 for c in source_wmo_path)):
|
|
raise ValueError('Canonical source global WMO path required')
|
|
if type(mapped_root_file_data_id) is not int or not 0 < mapped_root_file_data_id <= 0xffffffff:
|
|
raise ValueError('Explicit mapped global WMO FileDataID required')
|
|
chunks = _global_wmo_chunk_spans(source)
|
|
if list(chunks) != ['MVER', 'MPHD', 'MAIN', 'MWMO', 'MODF']:
|
|
raise ValueError('Unreviewed source global WDT chunk family')
|
|
values = {k: source[o:o+n] for k, (o,n) in chunks.items()}
|
|
if values['MVER'] != struct.pack('<I', 18) or values['MPHD'] != struct.pack('<8I', 1,0,0,0,0,0,0,0):
|
|
raise ValueError('Unreviewed source global WDT version/flags/extensions')
|
|
if len(values['MAIN']) != 32768 or any(values['MAIN']):
|
|
raise ValueError('Terrain/async data in source global-only WDT')
|
|
names = values['MWMO']
|
|
if not names.endswith(b'\0') or names.count(b'\0') != 1:
|
|
raise ValueError('Exactly one source global WMO name required')
|
|
try: actual_path = names[:-1].decode('ascii').replace('\\', '/').lower()
|
|
except UnicodeDecodeError: raise ValueError('Non-ASCII source global WMO path') from None
|
|
if actual_path != source_wmo_path:
|
|
raise ValueError('Mapped global WMO path differs from source name')
|
|
modf = values['MODF']
|
|
if len(modf) != 64:
|
|
raise ValueError('Exactly one source global MODF required')
|
|
name_index, unique = struct.unpack_from('<II', modf)
|
|
if name_index != 0 or unique != 0xffffffff:
|
|
raise ValueError('Unreviewed source global MODF identity')
|
|
if struct.unpack_from('<4H', modf, 56) != (0,0,0,0):
|
|
raise ValueError('Unreviewed source global MODF flags/sets/unused word')
|
|
floats = struct.unpack_from('<12f', modf, 8)
|
|
if not all(math.isfinite(v) for v in floats) or any(floats[6+i] > floats[9+i] for i in range(3)):
|
|
raise ValueError('Nonfinite/reversed source global MODF placement/bounds')
|
|
out = bytearray(template.raw); at = template.modf_payload_offset
|
|
struct.pack_into('<I', out, at, mapped_root_file_data_id)
|
|
out[at+4:at+56] = modf[4:56]
|
|
# Native34 flags8 selects FileDataID; scale bit4 is clear. Its existing
|
|
# unscaled tail is retained. Source's last uint16 is not promoted to scale.
|
|
output = bytes(out)
|
|
return output, dict(kind='private-global-WMO-WDT-structural-candidate',
|
|
status='HELD_UNPUBLISHED_GLOBAL_WMO_CONSTRUCTOR', directory=directory,
|
|
native_template_sha256=template.sha256, source_wmo_path=source_wmo_path,
|
|
mapped_root_file_data_id=mapped_root_file_data_id,
|
|
source_MODF_placement_bounds_and_unique_bytes_preserved=True,
|
|
source_MODF_unused_word=0, native_MODF_flags=8, native_MODF_scale_word=1024,
|
|
opaque_MPHD_words_preserved=True, MPHD_word7_role='unknown; not assumed FileDataID',
|
|
native_MAIN_MAID_preserved=True, source_terrain_tiles=0,
|
|
held=['Nonempty native TEX conditional/default authority',
|
|
'Unknown MPHD word7 conditional authority',
|
|
'Caller root binding/resource and WMO material/set closure',
|
|
'Actual source fork and original native rendering acceptance'],
|
|
publishable=False, installed=False, engine_verified=False)
|
|
|
|
|
|
def wdt_native_global_links_candidate(native, *, map_id, baseline_file_data_id,
|
|
baseline_sha256, expected_root_file_data_id,
|
|
expected_tex_file_data_id,
|
|
root_file_data_id, tex_file_data_id):
|
|
"""Rebind a frozen same-map global WDT's root and explicit global TEX only.
|
|
|
|
The caller supplies its accepted baseline identity and old operands. No
|
|
template, companion default, source placement or variant is selected here.
|
|
"""
|
|
if (type(map_id) is not int or not 0<=map_id<=0xffffffff
|
|
or type(baseline_file_data_id) is not int
|
|
or not 0<baseline_file_data_id<=0xffffffff
|
|
or not isinstance(baseline_sha256,str)
|
|
or not re.fullmatch('[0-9a-f]{64}',baseline_sha256)):
|
|
raise ValueError('Frozen same-map global WDT baseline identity required')
|
|
for value in (expected_root_file_data_id,root_file_data_id,tex_file_data_id):
|
|
if type(value) is not int or not 0<value<=0xffffffff:
|
|
raise ValueError('Explicit positive root and TEX bindings required')
|
|
if (type(expected_tex_file_data_id) is not int
|
|
or not 0<=expected_tex_file_data_id<=0xffffffff):
|
|
raise ValueError('Explicit old global TEX operand required')
|
|
chunks=_global_wmo_chunk_spans(native)
|
|
if (not {'MVER','MPHD','MAIN','MAID','MODF'}<=set(chunks)
|
|
or chunks['MVER'][1]!=4 or chunks['MPHD'][1]!=32
|
|
or chunks['MAIN'][1]!=32768 or chunks['MAID'][1]!=131072
|
|
or chunks['MODF'][1]!=64
|
|
or struct.unpack_from('<I',native,chunks['MVER'][0])[0]!=18):
|
|
raise ValueError('Qualified native global WDT framing required')
|
|
mphd=chunks['MPHD'][0];modf=chunks['MODF'][0]
|
|
if (not struct.unpack_from('<I',native,mphd)[0]&1
|
|
or any(native[chunks['MAIN'][0]:sum(chunks['MAIN'])])
|
|
or any(native[chunks['MAID'][0]:sum(chunks['MAID'])])):
|
|
raise ValueError('Same-map global-only native profile required')
|
|
if (struct.unpack_from('<H',native,modf+56)[0]!=8
|
|
or struct.unpack_from('<H',native,modf+62)[0]!=1024):
|
|
raise ValueError('Existing native FileDataID/unscaled MODF tail required')
|
|
if (struct.unpack_from('<I',native,modf)[0]!=expected_root_file_data_id
|
|
or struct.unpack_from('<I',native,mphd+20)[0]!=expected_tex_file_data_id):
|
|
raise ValueError('Frozen same-map global root/TEX operands differ')
|
|
output=bytearray(native);changes=[]
|
|
for role,offset,old,new in (('MODF_ROOT',modf,expected_root_file_data_id,root_file_data_id),
|
|
('MPHD_TEX',mphd+20,expected_tex_file_data_id,tex_file_data_id)):
|
|
if old==new:continue
|
|
struct.pack_into('<I',output,offset,new)
|
|
changes.append(dict(role=role,offset=offset,old_file_data_id=old,new_file_data_id=new))
|
|
return bytes(output),dict(kind='same-map-native-global-WDT-root-TEX-link-candidate-v1',
|
|
status='PASS_SAME_MAP_GLOBAL_ROOT_TEX_LINK_FIELDS',MapID=map_id,
|
|
baseline_file_data_id=baseline_file_data_id,baseline_sha256=baseline_sha256,
|
|
changes=changes,source_MODF_52_placement_bytes_preserved=True,
|
|
native_MODF_8_tail_bytes_preserved=True,
|
|
MPHD_flags_LGT_OCC_FOGS_MPV_WDL_and_word7_preserved=True,
|
|
MAIN_MAID_MAI2_and_all_other_bytes_preserved=True,
|
|
default_companions_selected=False,installed=False,runtime_verified=False)
|
|
|
|
|
|
_TerrainWdtTemplate = namedtuple('_TerrainWdtTemplate', 'raw sha256')
|
|
_TERRAIN_WDT_NATIVE33_SHA256 = '211c2d2c6ed20e1c320a72d1f79e16f4c9f76dfa4f6ac85b918e8784ee4937a4'
|
|
_TERRAIN_WDT_TILE_ROLES = ('rootADT', 'obj0ADT', 'obj1ADT', 'tex0ADT',
|
|
'lodADT', 'mapTexture', 'mapTextureN', 'minimapTexture')
|
|
_TERRAIN_WDT_GLOBAL_ROLES = ('lgt', 'occ', 'fogs', 'mpv', 'tex', 'wdl')
|
|
|
|
|
|
def wdt_azeroth_root_links_candidate(native, *, root_file_data_ids):
|
|
"""Private original-Azeroth clone with only the three admitted ROOT links.
|
|
|
|
This retains the shipped MPHD/MAIN, all seven companion operands and opaque
|
|
MAI2 bytes. It does not establish which table a native loading path selects,
|
|
Source ROOT compatibility with those companions, or Map cache application.
|
|
The caller must obtain the new IDs from its accepted registry/SDK receipts.
|
|
"""
|
|
if (not isinstance(native, bytes) or
|
|
hashlib.sha256(native).hexdigest() !=
|
|
'160452dec4c2b0ae4cbe7468ce52fee91ac7ec521d2cb0f28e955def0d087137'):
|
|
raise ValueError('Exact retained original70334 Azeroth WDT required')
|
|
expected = {(28, 36): 777167, (29, 34): 777357, (30, 33): 777552}
|
|
if (type(root_file_data_ids) is not dict or set(root_file_data_ids) != set(expected)
|
|
or any(type(xy) is not tuple or len(xy) != 2 or
|
|
any(type(v) is not int for v in xy) for xy in root_file_data_ids)
|
|
or any(type(v) is not int or not 0 < v <= 0xffffffff
|
|
for v in root_file_data_ids.values())
|
|
or len(set(root_file_data_ids.values())) != 3):
|
|
raise ValueError('Exact three distinct registered Azeroth ROOT links required')
|
|
chunks = _global_wmo_chunk_spans(native)
|
|
if (list(chunks) != ['MVER', 'MPHD', 'MAIN', 'MAID', 'MAI2']
|
|
or chunks['MAIN'][1] != 4096 * 8
|
|
or chunks['MAID'][1] != 4096 * 32
|
|
or chunks['MAI2'][1] != 4096 * 32):
|
|
raise ValueError('Original Azeroth MAIN/MAID and opaque MAI2 extents required')
|
|
output = bytearray(native)
|
|
changes = []
|
|
for (x, y), old in sorted(expected.items()):
|
|
index = y * 64 + x
|
|
flags, async_id = struct.unpack_from('<II', native, chunks['MAIN'][0] + index * 8)
|
|
offset = chunks['MAID'][0] + index * 32
|
|
old_roles = struct.unpack_from('<8I', native, offset)
|
|
new = root_file_data_ids[(x, y)]
|
|
if flags != 1 or async_id or old_roles[0] != old or new == old:
|
|
raise ValueError('Exact active original MAID ROOT relationship required')
|
|
struct.pack_into('<I', output, offset, new)
|
|
changes.append(dict(tile=[x, y], offset=offset,
|
|
old_ROOT_file_data_id=old, new_ROOT_file_data_id=new,
|
|
unchanged_companion_file_data_ids=dict(zip(_TERRAIN_WDT_TILE_ROLES[1:], old_roles[1:]))))
|
|
return bytes(output), dict(
|
|
kind='private-original-Azeroth-three-ROOT-association',
|
|
status='PRIVATE_STRUCTURAL_ASSOCIATION_RUNTIME_HELD',
|
|
original_WDT_file_data_id=775971, changes=changes,
|
|
original_MPHD_MAIN_and_other_Map_WDT_fields_preserved=True,
|
|
all_seven_MAID_companion_roles_preserved=True, opaque_MAI2_bytes_preserved=True,
|
|
Source_TEX_alpha_profile_or_blank_companions_introduced=False,
|
|
publishable=False, runtime_activation_verified=False,
|
|
held=['Original native MAID/MAI2 selection consumer',
|
|
'Source ROOT flags/material/placement compatibility with unchanged native companions',
|
|
'Owned WDT registration and Map0 WdtFileDataID-only cache application'])
|
|
|
|
|
|
|
|
def wdt_native_component_links_candidate(native, *, tile_file_data_ids,
|
|
native_file_data_id, native_sha256,
|
|
allow_source_obj0=False,
|
|
source_empty_obj1_tiles=(),
|
|
presentation_profile=None,
|
|
source_active_tiles=()):
|
|
"""Clone a reviewed native terrain WDT; change explicit ROOT/TEX0 and opt-in OBJ0 words.
|
|
|
|
Identity comes from the caller's frozen original SDK/body receipt. This
|
|
Default behavior preserves native mode/MAIN/MAI2 and companion bytes.
|
|
The explicit original529 profile selects its complete 0x24a five-role
|
|
presentation for Map0/1 only. It is a private presentation candidate,
|
|
not a claim about individual flag bits or Source rendering equivalence.
|
|
"""
|
|
if (not isinstance(native, bytes) or type(native_file_data_id) is not int
|
|
or not 0 < native_file_data_id <= 0xffffffff
|
|
or not isinstance(native_sha256, str)
|
|
or not re.fullmatch('[0-9a-f]{64}', native_sha256)):
|
|
raise ValueError('Reviewed native WDT identity required')
|
|
if type(allow_source_obj0) is not bool:
|
|
raise ValueError('Explicit Source OBJ0 link policy required')
|
|
profile = presentation_profile == 'original529-five-role-MAI2'
|
|
if presentation_profile is not None and not profile:
|
|
raise ValueError('Exact reviewed original529 presentation profile required')
|
|
if (type(source_active_tiles) not in (tuple, set, frozenset)
|
|
or any(type(xy) is not tuple or len(xy) != 2
|
|
or any(type(v) is not int or not 0 <= v < 64 for v in xy)
|
|
for xy in source_active_tiles)
|
|
or source_active_tiles and not profile):
|
|
raise ValueError('Explicit Source MAIN-active coordinates require the presentation policy')
|
|
source_active_tiles = set(source_active_tiles)
|
|
if (type(source_empty_obj1_tiles) not in (tuple, set)
|
|
or any(type(xy) is not tuple or len(xy) != 2
|
|
or any(type(v) is not int or not 0 <= v < 64 for v in xy)
|
|
for xy in source_empty_obj1_tiles)
|
|
or source_empty_obj1_tiles and not allow_source_obj0):
|
|
raise ValueError('Qualified empty Source object tiles require OBJ0 policy')
|
|
empty_obj1_tiles = set(source_empty_obj1_tiles)
|
|
allowed_roles = {'ROOT', 'TEX0', 'OBJ0'} if allow_source_obj0 else {'ROOT', 'TEX0'}
|
|
if empty_obj1_tiles:
|
|
allowed_roles.add('OBJ1')
|
|
if profile:
|
|
if not allow_source_obj0:
|
|
raise ValueError('Five-role presentation requires explicit object link policy')
|
|
allowed_roles.update(('OBJ1', 'MINIMAP'))
|
|
chunks = _global_wmo_chunk_spans(native)
|
|
if (not {'MVER', 'MPHD', 'MAIN', 'MAID'} <= set(chunks)
|
|
or chunks['MVER'][1] != 4
|
|
or native[chunks['MVER'][0]:chunks['MVER'][0]+4] != struct.pack('<I', 18)
|
|
or chunks['MPHD'][1] != 32 or chunks['MAIN'][1] != 32768
|
|
or chunks['MAID'][1] != 131072):
|
|
raise ValueError('Original terrain MAIN/MAID framing required')
|
|
if struct.unpack_from('<I', native, chunks['MPHD'][0])[0] & 1:
|
|
raise ValueError('Global-WMO profile outside terrain link clone')
|
|
profile_map = None
|
|
if profile:
|
|
# These are the original continent controls and their retained owned
|
|
# WDT link-clone identities. No other Map/profile is selected by name.
|
|
profile_map = {775971: 0, 8551265: 0, 782779: 1, 8551266: 1}.get(native_file_data_id)
|
|
original_global_words = {
|
|
0: (970, 1100798, 1101056, 1668812, 2488184, 775969, 775970, 0),
|
|
1: (970, 1100658, 1100779, 1668820, 2023510, 782777, 782778, 0),
|
|
}
|
|
if (profile_map is None
|
|
or list(chunks) != ['MVER', 'MPHD', 'MAIN', 'MAID', 'MAI2']
|
|
or chunks['MAI2'][1] != 131072
|
|
or struct.unpack_from('<8I', native, chunks['MPHD'][0])
|
|
!= original_global_words[profile_map]):
|
|
raise ValueError('Exact original Map0/1 profile and own global companions required')
|
|
if not isinstance(tile_file_data_ids, dict) or not tile_file_data_ids:
|
|
raise ValueError('Nonempty explicit registered terrain links required')
|
|
output = bytearray(native); changes = []; activated = []
|
|
api_fields = {'ROOT': 'rootADT', 'TEX0': 'tex0ADT', 'OBJ0': 'obj0ADT',
|
|
'OBJ1': 'obj1ADT', 'MINIMAP': 'minimapTexture'}
|
|
for xy, bindings in sorted(tile_file_data_ids.items()):
|
|
if (type(xy) is not tuple or len(xy) != 2
|
|
or any(type(v) is not int or not 0 <= v < 64 for v in xy)
|
|
or not isinstance(bindings, dict) or not bindings
|
|
or not set(bindings) <= allowed_roles
|
|
or any(type(v) is not int or not 0 < v <= 0xffffffff
|
|
for v in bindings.values())):
|
|
raise ValueError('Only explicit reviewed terrain tile link roles admitted')
|
|
x,y=xy; index=y*64+x
|
|
flags,async_id=struct.unpack_from('<II',native,chunks['MAIN'][0]+index*8)
|
|
off=chunks['MAID'][0]+index*32
|
|
old=dict(zip(_TERRAIN_WDT_TILE_ROLES,struct.unpack_from('<8I',native,off)))
|
|
new_cell = flags != 1 or async_id != 0
|
|
if new_cell:
|
|
if (not profile or (flags, async_id) != (2, 0)
|
|
or any(old.values()) or xy not in source_active_tiles
|
|
or set(bindings) != set(api_fields)):
|
|
raise ValueError('New cell requires inactive(2,0), zero MAID8, Source MAIN and all five explicit roles')
|
|
struct.pack_into('<2I',output,chunks['MAIN'][0]+index*8,1,0)
|
|
activated.append(dict(tile=[x,y],offset=chunks['MAIN'][0]+index*8,
|
|
old=[2,0],new=[1,0]))
|
|
if 'OBJ1' in bindings:
|
|
empty = xy in empty_obj1_tiles
|
|
if (not profile and (not empty or bindings['OBJ1'] != 790799 or 'OBJ0' not in bindings)
|
|
or profile and (empty != (bindings['OBJ1'] == 790799))):
|
|
raise ValueError('Empty OBJ1 requires exact qualified790799 membership; nonempty profile links remain explicit')
|
|
modified={}
|
|
for role,value in bindings.items():
|
|
field = api_fields[role]
|
|
if value == old[field]: continue
|
|
at=off+4*_TERRAIN_WDT_TILE_ROLES.index(field)
|
|
struct.pack_into('<I',output,at,value)
|
|
modified[role]=dict(old_file_data_id=old[field],new_file_data_id=value,offset=at)
|
|
if modified: changes.append(dict(tile=[x,y],roles=modified,original_all_roles=old))
|
|
if profile:
|
|
# Select the complete observed Map529 profile, not inferred bit edits.
|
|
# Every active row follows its five-present/three-zero presentation;
|
|
# all own global references and opaque MAI2 bytes remain unchanged.
|
|
struct.pack_into('<I', output, chunks['MPHD'][0], 0x24a)
|
|
by_tile = {tuple(row['tile']): row for row in changes}
|
|
for index in range(4096):
|
|
state = struct.unpack_from('<2I', output, chunks['MAIN'][0]+index*8)
|
|
if state == (2, 0):
|
|
continue
|
|
if state != (1, 0):
|
|
raise ValueError('Unreviewed continent MAIN state')
|
|
off = chunks['MAID'][0]+index*32
|
|
current = struct.unpack_from('<8I', output, off)
|
|
if not all(current[i] for i in (0, 1, 2, 3, 7)):
|
|
raise ValueError('Every active five-role presentation row requires ROOT/OBJ0/OBJ1/TEX0/minimap')
|
|
for i, role in ((4, 'LOD'), (5, 'MAPTEXTURE'), (6, 'MAPTEXTUREN')):
|
|
if not current[i]: continue
|
|
xy = (index % 64, index // 64)
|
|
if xy not in by_tile:
|
|
by_tile[xy] = dict(tile=list(xy), roles={}, original_all_roles=dict(
|
|
zip(_TERRAIN_WDT_TILE_ROLES, struct.unpack_from('<8I', native, off))))
|
|
at = off+4*i
|
|
by_tile[xy]['roles'][role] = dict(old_file_data_id=current[i], new_file_data_id=0, offset=at)
|
|
struct.pack_into('<I', output, at, 0)
|
|
changes = [by_tile[xy] for xy in sorted(by_tile)]
|
|
if not changes: raise ValueError('No new terrain links to compose')
|
|
return bytes(output), dict(
|
|
kind=('native-wdt-original529-five-role-MAI2-presentation-v1' if profile else
|
|
'native-wdt-maid-root-tex-object-links-v1' if empty_obj1_tiles else
|
|
'native-wdt-maid-root-tex-obj0-links-v1' if allow_source_obj0
|
|
else 'native-wdt-maid-root-tex-links-v1'),
|
|
status='PRIVATE_STRUCTURAL_SOURCE_COMPONENT_ASSOCIATION',
|
|
original_WDT_file_data_id=native_file_data_id,
|
|
original_WDT_sha256=native_sha256, changes=changes,
|
|
original_MPHD_MAIN_preserved=not profile, opaque_MAI2_bytes_preserved=True,
|
|
all_other_MAID_roles_preserved=True, native_profile_flags_preserved=not profile,
|
|
Source_OBJ0_link_policy=allow_source_obj0,
|
|
Source_empty_OBJ1_tiles=[list(xy) for xy in sorted(empty_obj1_tiles)],
|
|
presentation_profile=presentation_profile, presentation_MapID=profile_map,
|
|
complete_observed_MPHD_flag_word=(0x24a if profile else None),
|
|
native_profile_flags_preserved_by_default=not profile,
|
|
own_global6_and_MPHD_word7_preserved=True, activated_MAIN_cells=activated,
|
|
original529_profile_control=790377 if profile else None,
|
|
individual_flag_semantics_inferred=False,
|
|
runtime_activation_verified=False, publishable=False,
|
|
holds=['MAID/MAI2 runtime selection where not observed',
|
|
'Source material/alpha/area/placement applicability',
|
|
'Map row/cache application and actual scene acceptance'])
|
|
|
|
|
|
def wdt_original_continent_profile_candidate(native, *, map_id,
|
|
effective_parent_file_data_id, effective_parent_sha256,
|
|
original_lod_links):
|
|
"""Restore each continent's own observed profile, never mix inferred bits.
|
|
|
|
The caller supplies original LOD3 words from the pinned pre529 removal
|
|
audit. Current ROOT/TEX/OBJ/minimap, MAIN (including owned new cells),
|
|
global6 and MAI2 stay exact. Original source-only cells without LOD3 are
|
|
deliberately left at zero; their runtime acceptance remains separate.
|
|
"""
|
|
original = {
|
|
0: (970, 1100798, 1101056, 1668812, 2488184, 775969, 775970, 0),
|
|
1: (970, 1100658, 1100779, 1668820, 2023510, 782777, 782778, 0),
|
|
}
|
|
if (type(map_id) is not int or map_id not in original
|
|
or effective_parent_file_data_id != {0: 8554294, 1: 8554295}[map_id]
|
|
or not re.fullmatch('[0-9a-f]{64}', effective_parent_sha256 or '')
|
|
or not isinstance(native, bytes)):
|
|
raise ValueError('Exact current owned continent and profile authority required')
|
|
chunks = _global_wmo_chunk_spans(native)
|
|
if (list(chunks) != ['MVER', 'MPHD', 'MAIN', 'MAID', 'MAI2']
|
|
or chunks['MPHD'][1] != 32 or chunks['MAIN'][1] != 32768
|
|
or chunks['MAID'][1] != 131072 or chunks['MAI2'][1] != 131072
|
|
or struct.unpack_from('<I', native, chunks['MVER'][0])[0] != 18
|
|
or struct.unpack_from('<8I', native, chunks['MPHD'][0])
|
|
!= (586,) + original[map_id][1:]):
|
|
raise ValueError('Current whole529 profile with exact own global6 required')
|
|
if not isinstance(original_lod_links, dict) or not original_lod_links:
|
|
raise ValueError('Explicit original LOD3 restoration operands required')
|
|
output = bytearray(native)
|
|
output[chunks['MPHD'][0]:chunks['MPHD'][0] + 32] = struct.pack('<8I', *original[map_id])
|
|
changes = []
|
|
roles = {'LOD': 4, 'MAPTEXTURE': 5, 'MAPTEXTUREN': 6}
|
|
for xy, links in sorted(original_lod_links.items()):
|
|
if (type(xy) is not tuple or len(xy) != 2
|
|
or any(type(v) is not int or not 0 <= v < 64 for v in xy)
|
|
or not isinstance(links, dict) or not links or not set(links) <= set(roles)
|
|
or any(type(v) is not int or not 0 < v <= 0xffffffff for v in links.values())):
|
|
raise ValueError('Positive exact original LOD3 roles required')
|
|
index = xy[1] * 64 + xy[0]
|
|
if struct.unpack_from('<2I', native, chunks['MAIN'][0] + index * 8) != (1, 0):
|
|
raise ValueError('Original LOD3 may be restored only on current active cells')
|
|
for role, ident in links.items():
|
|
at = chunks['MAID'][0] + index * 32 + roles[role] * 4
|
|
if struct.unpack_from('<I', native, at)[0] != 0:
|
|
raise ValueError('Only the removed zero LOD3 words may be restored')
|
|
struct.pack_into('<I', output, at, ident)
|
|
changes.append(dict(tile=list(xy), role=role, offset=at,
|
|
old_file_data_id=0, new_file_data_id=ident))
|
|
return bytes(output), dict(
|
|
kind='original-continent-whole-MPHD-and-LOD3-restoration-v1',
|
|
MapID=map_id, effective_parent_file_data_id=effective_parent_file_data_id,
|
|
effective_parent_sha256=effective_parent_sha256,
|
|
old_MPHD=(586,) + original[map_id][1:], restored_MPHD=original[map_id],
|
|
MPHD_offset=chunks['MPHD'][0], MAID_offset=chunks['MAID'][0],
|
|
changes=changes, MAIN_global6_MAI2_preserved=True,
|
|
ROOT_TEX0_OBJ0_OBJ1_MINIMAP_preserved=True,
|
|
new_Source_only_zero_LOD3_preserved=True,
|
|
native_flag_bit_semantics_inferred=False, runtime_verified=False)
|
|
|
|
|
|
def wdt_terrain_native_template(raw):
|
|
"""Prepare only the measured70334 Map33 non-LOD structural profile.
|
|
|
|
This proves an existing layout with zero per-tile LOD/texture/normal IDs,
|
|
not the profile's applicability to another Map or optional global files.
|
|
"""
|
|
chunks = _global_wmo_chunk_spans(raw)
|
|
digest = hashlib.sha256(raw).hexdigest()
|
|
if digest != _TERRAIN_WDT_NATIVE33_SHA256:
|
|
raise ValueError('Exact original native33 terrain WDT template required')
|
|
if list(chunks) != ['MVER', 'MPHD', 'MAIN', 'MAID']:
|
|
raise ValueError('Unreviewed native terrain WDT chunk family')
|
|
return _TerrainWdtTemplate(raw, digest)
|
|
|
|
|
|
def wdt_terrain_candidate(template, source, *, directory, tile_file_data_ids,
|
|
global_file_data_ids):
|
|
"""Build a PRIVATE/HELD non-LOD WDT with complete explicit role bindings.
|
|
|
|
No ID is allocated/inferred here. Even a populated binding does not prove
|
|
source-native content, OBJ1 generation, scene companions, or MapType/profile
|
|
activation. In particular, the original OBJ1 control is nonempty and must
|
|
never be replaced by an invented empty file. Source MAIN survives exactly.
|
|
"""
|
|
if type(template) is not _TerrainWdtTemplate:
|
|
raise ValueError('Prepared exact native terrain WDT template required')
|
|
if (not isinstance(directory, str) or
|
|
not re.fullmatch("[a-z0-9_' -]{1,128}", directory) or directory.strip() != directory):
|
|
raise ValueError('Canonical terrain map directory required')
|
|
chunks = _global_wmo_chunk_spans(source)
|
|
if list(chunks) not in (['MVER', 'MPHD', 'MAIN'], ['MVER', 'MPHD', 'MAIN', 'MWMO']):
|
|
raise ValueError('Unreviewed source terrain WDT chunk family')
|
|
values = {name: source[at:at+size] for name, (at, size) in chunks.items()}
|
|
if (values['MVER'] != struct.pack('<I', 18) or
|
|
values['MPHD'] != bytes(32) or values.get('MWMO', b'') != b''):
|
|
raise ValueError('Unreviewed source terrain WDT version/flags/global names')
|
|
main = values['MAIN']
|
|
if len(main) != 32768:
|
|
raise ValueError('Unreviewed source terrain MAIN extent')
|
|
active = set()
|
|
for index, (flags, async_id) in enumerate(struct.iter_unpack('<II', main)):
|
|
if flags not in (0, 1) or async_id != 0:
|
|
raise ValueError('Unreviewed source terrain MAIN flags/async role')
|
|
if flags: active.add((index % 64, index // 64))
|
|
if not active:
|
|
raise ValueError('Nonempty source terrain tile set required')
|
|
if not isinstance(tile_file_data_ids, dict) or set(tile_file_data_ids) != active:
|
|
raise ValueError('Exact complete source MAIN tile binding set required')
|
|
if (not isinstance(global_file_data_ids, dict) or
|
|
set(global_file_data_ids) != set(_TERRAIN_WDT_GLOBAL_ROLES) or
|
|
any(type(v) is not int or not 0 < v <= 0xffffffff for v in global_file_data_ids.values())):
|
|
raise ValueError('All six explicit nonzero global companion FileDataIDs required')
|
|
maid = bytearray(131072)
|
|
for coordinate in sorted(active):
|
|
# Exact tuple type prevents bool/int coordinate aliasing in dict keys.
|
|
if (type(coordinate) is not tuple or len(coordinate) != 2 or
|
|
any(type(v) is not int for v in coordinate)):
|
|
raise ValueError('Exact integer source tile coordinates required')
|
|
bindings = tile_file_data_ids[coordinate]
|
|
if not isinstance(bindings, dict) or set(bindings) != set(_TERRAIN_WDT_TILE_ROLES):
|
|
raise ValueError('All eight explicit MAID role bindings required')
|
|
ids = tuple(bindings[role] for role in _TERRAIN_WDT_TILE_ROLES)
|
|
if any(type(v) is not int or not 0 <= v <= 0xffffffff for v in ids):
|
|
raise ValueError('Bounded integer MAID FileDataIDs required')
|
|
if not all(ids[i] for i in (0, 1, 2, 3, 7)) or any(ids[i] for i in (4, 5, 6)):
|
|
raise ValueError('Exact native33 five-present/three-zero MAID profile required')
|
|
x, y = coordinate
|
|
struct.pack_into('<8I', maid, (y*64+x)*32, *ids)
|
|
# Preserve the original profile flags and opaque word7. All six global
|
|
# references are explicit caller inputs; original scene files are not defaults.
|
|
native_chunks = _global_wmo_chunk_spans(template.raw)
|
|
mphd_at = native_chunks['MPHD'][0]
|
|
mphd = bytearray(template.raw[mphd_at:mphd_at+32])
|
|
struct.pack_into('<6I', mphd, 4, *(global_file_data_ids[r] for r in _TERRAIN_WDT_GLOBAL_ROLES))
|
|
payloads = [('MVER', values['MVER']), ('MPHD', bytes(mphd)), ('MAIN', main), ('MAID', bytes(maid))]
|
|
output = b''.join(tag[::-1].encode('ascii')+struct.pack('<I', len(body))+body for tag, body in payloads)
|
|
return output, dict(kind='private-terrain-WDT-structural-candidate',
|
|
status='HELD_UNPUBLISHED_TERRAIN_WDT_CONSTRUCTOR', directory=directory,
|
|
native_template_sha256=template.sha256, native_profile_flags=0x248,
|
|
source_MAIN_bytes_preserved=True, source_terrain_tiles=len(active),
|
|
per_tile_required_roles=['rootADT', 'obj0ADT', 'obj1ADT', 'tex0ADT', 'minimapTexture'],
|
|
per_tile_zero_roles=['lodADT', 'mapTexture', 'mapTextureN'],
|
|
explicit_global_companion_file_data_ids=dict(global_file_data_ids),
|
|
unknown_MPHD_word7_preserved=True,
|
|
held=['Native33 profile applicability/MapType and actual source fork',
|
|
'Source inactive MAIN flags0 vs original33 inactive flags2 consumer role',
|
|
'Every explicit tile/global binding content and scene-specific authority',
|
|
'Nonempty OBJ1 placement/LOD companion producer and minimap closure',
|
|
'Global LGT/OCC/FOGS/MPV/TEX/WDL and opaque MPHD word7 consumer roles',
|
|
'Original native map loading/rendering acceptance'],
|
|
publishable=False, installed=False, engine_verified=False)
|
|
|
|
|
|
def wdl_source_height_native_profile_candidate(source, *, native_profile):
|
|
"""Preserve legacy WDL geometry under an explicit native presentation policy.
|
|
|
|
Original70334 WDL790795 contains25 MARE rows but only21 MAOE rows;
|
|
MAOE is therefore not an unconditional per-row format requirement. This
|
|
policy emits no invented MAOE data and makes no claim about its rendering
|
|
semantics. The four empty ML* categories use the original791059/790795
|
|
representation. Scene/resource closure and runtime acceptance are separate.
|
|
"""
|
|
policy = 'original70334-source-heights-no-extra-MAOE'
|
|
if native_profile != policy:
|
|
raise ValueError('Explicit original-native WDL presentation profile required')
|
|
records = _wmo_chunk_records(source, maximum=12290)
|
|
if (len(records) < 2 or records[0] != ('MVER', struct.pack('<I', 18))
|
|
or records[1][0] != 'MAOF' or len(records[1][1]) != 4096 * 4):
|
|
raise ValueError('Exact Source18 WDL MVER/MAOF prefix required')
|
|
offsets = struct.unpack('<4096I', records[1][1])
|
|
groups = {}
|
|
cursor = 12 + 8 + 4096 * 4
|
|
last_group = None
|
|
hole_rows = 0
|
|
for tag, payload in records[2:]:
|
|
if tag == 'MARE':
|
|
if len(payload) != 1090:
|
|
raise ValueError('Source WDL MARE must retain545 signed16 heights')
|
|
groups[cursor] = False
|
|
last_group = cursor
|
|
elif tag == 'MAHO':
|
|
if last_group is None or groups[last_group] or len(payload) != 32:
|
|
raise ValueError('Source WDL MAHO must follow one MARE exactly once')
|
|
groups[last_group] = True
|
|
hole_rows += 1
|
|
else:
|
|
raise ValueError('Unreviewed Source WDL extension or object records')
|
|
cursor += 8 + len(payload)
|
|
selected = [offset for offset in offsets if offset]
|
|
if len(selected) != len(set(selected)) or set(selected) != set(groups):
|
|
raise ValueError('Source WDL MAOF must select every MARE exactly once')
|
|
if not groups:
|
|
output, receipt = wdl_explicit_empty_candidate(source)
|
|
return output, dict(receipt, native_profile=policy)
|
|
|
|
def chunk(tag, payload):
|
|
return tag.encode('ascii')[::-1] + struct.pack('<I', len(payload)) + payload
|
|
|
|
# Only the four empty8-byte category headers are inserted. All terrain
|
|
# payload bytes, their order and each logical MAOF coordinate are retained.
|
|
shift = 4 * 8
|
|
if any(offset > 0xffffffff - shift for offset in selected):
|
|
raise ValueError('Source WDL offset exceeds native uint32 after prefix')
|
|
new_offsets = [offset + shift if offset else 0 for offset in offsets]
|
|
output = (source[:12]
|
|
+ b''.join(chunk(tag, b'') for tag in ('MLDD', 'MLDX', 'MLMD', 'MLMX'))
|
|
+ chunk('MAOF', struct.pack('<4096I', *new_offsets))
|
|
+ source[12 + 8 + 4096 * 4:])
|
|
return output, dict(
|
|
kind='original70334-Source-height-WDL-native-presentation-profile',
|
|
native_profile=policy, original_format_controls=[790795, 791059],
|
|
content_key=hashlib.md5(output).hexdigest(), bytes=len(output),
|
|
terrain_rows=len(groups), hole_rows=hole_rows,
|
|
source_MARE_MAHO_payloads_preserved=True,
|
|
source_MAOF_coordinates_preserved=True, source_objects_dropped=False,
|
|
original_zero_entry_ML_chunks=True, synthesized_MAOE_rows=0,
|
|
source_native_hole_rendering_equivalence=False,
|
|
runtime_verified=False, publishable=False,
|
|
held=['Whole WDT/resource graph and caller selection',
|
|
'Actual native rendering acceptance of explicit presentation profile'])
|
|
|
|
|
|
def wdl_explicit_empty_candidate(source):
|
|
"""Resolve only an authored zero-terrain WDL to the original34 category.
|
|
|
|
The Source WDL parser indexes all terrain through MAOF. Requiring the exact
|
|
two-chunk Source family excludes authored holes, objects and extensions;
|
|
absence of a Source file is never accepted. Original70334 Map34 supplies the
|
|
zero-entry ML* representation. This is one companion role, not approval of
|
|
a WDT profile, scene resource graph or runtime feature absence.
|
|
"""
|
|
spans = _global_wmo_chunk_spans(source)
|
|
if list(spans) != ['MVER', 'MAOF']:
|
|
raise ValueError('Exact explicit empty Source WDL chunk family required')
|
|
values = {tag: source[offset:offset+size] for tag, (offset,size) in spans.items()}
|
|
if values['MVER'] != struct.pack('<I', 18):
|
|
raise ValueError('Unreviewed Source WDL version')
|
|
if len(values['MAOF']) != 4096*4 or any(values['MAOF']):
|
|
raise ValueError('Explicit zero Source WDL terrain index required')
|
|
def chunk(tag, payload):
|
|
return tag.encode('ascii')[::-1]+struct.pack('<I',len(payload))+payload
|
|
output = (chunk('MVER', values['MVER']) +
|
|
b''.join(chunk(tag,b'') for tag in ('MLDD','MLDX','MLMD','MLMX')) +
|
|
chunk('MAOF', values['MAOF']))
|
|
content_key = hashlib.md5(output).hexdigest()
|
|
if len(output) != 16436 or content_key != '8bd400a68bfb54a8e645e8f403236999':
|
|
raise ValueError('Original34 empty WDL content identity differs')
|
|
return output, dict(kind='original70334-explicit-empty-WDL-reuse',
|
|
original_file_data_id=791059, content_key=content_key, bytes=len(output),
|
|
source_explicit_zero_MAOF=True, source_unknown_chunks_admitted=False,
|
|
original_zero_entry_ML_chunks=True, new_asset_required=False,
|
|
source_geometry_dropped=False, runtime_verified=False, publishable=False,
|
|
held=['Caller Source WDL selection and WDT/global companion activation',
|
|
'Actual Source fork and original native rendering acceptance'])
|
|
|
|
|
|
def classic_adt_dependencies(raw):
|
|
"""Read the legacy monolithic ADT's explicit asset/placement references.
|
|
|
|
No conversion: native split ADT/M2/WMO formats need separate handling.
|
|
Repeated MCNK chunks are valid; duplicated name/reference tables are not.
|
|
MDDF/MODF name IDs index MMID/MWID, which in turn hold string offsets.
|
|
"""
|
|
if not isinstance(raw,bytes) or not 12<=len(raw)<=67108864:
|
|
raise ValueError('Bounded ADT bytes required')
|
|
chunks={};pos=0;terrain=0;tags=[];padding=0
|
|
while pos<len(raw):
|
|
# Observed Sunnyglade tile has all256 cells followed by32KiB of zero
|
|
# allocation padding. Retain the complete source hash and report the
|
|
# padding explicitly; never treat it as thousands of duplicate chunks.
|
|
# Only a complete tile and a bounded entirely-zero suffix qualify.
|
|
if raw[pos:pos+8]==bytes(8):
|
|
padding=len(raw)-pos
|
|
if terrain!=256 or padding>65536 or any(raw[pos:]):
|
|
raise ValueError('Unreviewed ADT trailing data')
|
|
break
|
|
if len(raw)-pos<8 or len(tags)>=4096:raise ValueError('Truncated/count-bounded ADT chunks')
|
|
tag,size=struct.unpack_from('<4sI',raw,pos);pos+=8
|
|
try:name=tag[::-1].decode('ascii')
|
|
except UnicodeDecodeError:raise ValueError('Invalid ADT chunk tag')from None
|
|
if size>len(raw)-pos:raise ValueError('Truncated ADT chunk')
|
|
tags.append(name)
|
|
if name=='MCNK':terrain+=1
|
|
else:
|
|
if name in chunks:raise ValueError('Duplicate ADT reference chunk')
|
|
chunks[name]=raw[pos:pos+size]
|
|
pos+=size
|
|
if chunks.get('MVER')!=struct.pack('<I',18):raise ValueError('Unreviewed ADT version')
|
|
if 'MDID'in chunks or 'MHID'in chunks or 'MAID'in chunks:
|
|
raise ValueError('Modern ADT needs its own dependency reader')
|
|
def names(tag,extension):
|
|
data=chunks.get(tag,b'');result={};at=0
|
|
if data and not data.endswith(b'\0'):raise ValueError('Unterminated ADT asset paths')
|
|
for item in data.split(b'\0'):
|
|
if item:
|
|
try:path=item.decode('ascii').replace('\\','/').lower()
|
|
except UnicodeDecodeError:raise ValueError('Non-ASCII ADT asset path')from None
|
|
if (len(path)>1024 or ':'in path or path.startswith('/')or
|
|
any(p in ('','.','..')for p in path.split('/'))or
|
|
any(ord(c)<32 for c in path)or not path.endswith(extension)):
|
|
raise ValueError('Unsafe/unreviewed ADT asset path')
|
|
result[at]=path
|
|
at+=len(item)+1
|
|
return result
|
|
textures=names('MTEX',('.blp',));models=names('MMDX',('.m2','.mdx'));wmos=names('MWMO',('.wmo',))
|
|
def placements(index_tag,record_tag,width,names):
|
|
index=chunks.get(index_tag,b'');records=chunks.get(record_tag,b'')
|
|
if len(index)%4 or len(records)%width:raise ValueError('Unreviewed ADT placement/index extent')
|
|
offsets=[v[0]for v in struct.iter_unpack('<I',index)]
|
|
if any(v not in names for v in offsets):raise ValueError('ADT string-offset reference missing')
|
|
used=set()
|
|
for at in range(0,len(records),width):
|
|
ident=struct.unpack_from('<I',records,at)[0]
|
|
if ident>=len(offsets):raise ValueError('ADT placement name index out of range')
|
|
used.add(names[offsets[ident]])
|
|
return dict(count=len(records)//width,referenced_assets=sorted(used))
|
|
return dict(sha256=hashlib.sha256(raw).hexdigest(),format='legacy-monolithic-adt-v18',
|
|
terrain_chunks=terrain,trailing_zero_padding_bytes=padding,chunks=tags,textures=sorted(set(textures.values())),
|
|
models=sorted(set(models.values())),wmos=sorted(set(wmos.values())),
|
|
model_placements=placements('MMID','MDDF',36,models),
|
|
wmo_placements=placements('MWID','MODF',64,wmos),
|
|
terrain_converted=False,dependencies_resolved=False,installed=False,engine_verified=False)
|
|
|
|
|
|
# Pinned Source5875/5014 root parser 0x6c3a60 reads this fixed sequence,
|
|
# then probes only optional MCVP through 0x6c3a20 and returns at 0x6c3d61.
|
|
# A non-MCVP suffix is not another chunk; its first FourCC alone is observed.
|
|
# Keep this opt-in for Source roots; generic/group/native readers stay strict.
|
|
_WMO_SOURCE_ROOT_PROFILE='source5875-fixed-root-optional-mcvp-v1'
|
|
_WMO_SOURCE_ROOT_TAGS=('MVER','MOHD','MOTX','MOMT','MOGN','MOGI','MOSB',
|
|
'MOPV','MOPT','MOPR','MOVV','MOVB','MOLT','MODS','MODN','MODD','MFOG')
|
|
|
|
|
|
def _wmo_chunk_records(raw,maximum=128,*,source5875_root=False):
|
|
if not isinstance(raw,bytes)or len(raw)>67108864:raise ValueError('Bounded WMO chunks required')
|
|
if type(source5875_root)is not bool:raise ValueError('Explicit Source WMO root policy required')
|
|
records=[];pos=0
|
|
while pos<len(raw):
|
|
if source5875_root and len(records)>=len(_WMO_SOURCE_ROOT_TAGS):
|
|
if len(records)>len(_WMO_SOURCE_ROOT_TAGS):break
|
|
if len(raw)-pos<4:raise ValueError('Truncated Source optional WMO tag')
|
|
if raw[pos:pos+4]!=b'PVCM':break
|
|
if len(raw)-pos<8 or len(records)>=maximum:raise ValueError('Truncated/count-bounded WMO chunks')
|
|
tag,size=struct.unpack_from('<4sI',raw,pos);pos+=8
|
|
try:name=tag[::-1].decode('ascii')
|
|
except UnicodeDecodeError:raise ValueError('Invalid WMO chunk tag')from None
|
|
if size>len(raw)-pos:raise ValueError('Truncated WMO chunk')
|
|
if source5875_root:
|
|
expected=(_WMO_SOURCE_ROOT_TAGS[len(records)]
|
|
if len(records)<len(_WMO_SOURCE_ROOT_TAGS)else'MCVP')
|
|
if name!=expected:raise ValueError('Unreviewed Source fixed WMO root order')
|
|
records.append((name,raw[pos:pos+size]));pos+=size
|
|
if source5875_root and len(records)<len(_WMO_SOURCE_ROOT_TAGS):
|
|
raise ValueError('Incomplete Source fixed WMO root')
|
|
return records
|
|
|
|
|
|
def numeric_wmo_model_references(modi,modd):
|
|
"""Separate the complete MODI catalogue from MODD-indexed dependencies.
|
|
|
|
Numeric v17 roots retain unused model catalogue entries, including IDs
|
|
absent from their own original ROOT. Preserve that catalogue and expose
|
|
only indices actually selected by 40-byte MODD placements as dependencies.
|
|
An indexed zero remains an unresolved placement, never an inferred absence.
|
|
"""
|
|
if (not isinstance(modi,bytes)or not isinstance(modd,bytes)or
|
|
len(modi)%4 or len(modd)%40 or
|
|
len(modi)>4*1048576 or len(modd)>40*1048576):
|
|
raise ValueError('Bounded numeric WMO model catalogue and placements required')
|
|
models=[row[0]for row in struct.iter_unpack('<I',modi)]
|
|
used=set()
|
|
for at in range(0,len(modd),40):
|
|
index=struct.unpack_from('<I',modd,at)[0]&0xffffff
|
|
if index>=len(models):raise ValueError('WMO placement model index outside MODI')
|
|
used.add(index)
|
|
return dict(model_file_ids=models,referenced_model_indices=sorted(used),
|
|
referenced_model_file_ids=sorted({models[i]for i in used if models[i]}),
|
|
unresolved_zero_model_indices=sorted(i for i in used if not models[i]),
|
|
unused_model_indices=[i for i in range(len(models))if i not in used],
|
|
placement_count=len(modd)//40,placement_flag_bits_preserved=True)
|
|
|
|
|
|
def _classic_wmo_root_chunks(raw,root_path,*,source_root_profile=None):
|
|
"""Inventory v17 root WMO groups and named assets, never assume native parity.
|
|
|
|
Header/group naming follows the local Tortoise/Forever WMO extractors and
|
|
WoWee root reader. Material shaders and group geometry remain unconverted.
|
|
"""
|
|
if (not isinstance(raw,bytes)or not 12<=len(raw)<=67108864 or
|
|
not isinstance(root_path,str)or not re.fullmatch(r'[a-z0-9_ /-]+\.wmo',root_path)or
|
|
any(p in ('','.','..')or p!=p.strip()for p in root_path.split('/'))):
|
|
raise ValueError('Bounded canonical root WMO required')
|
|
if source_root_profile not in(None,_WMO_SOURCE_ROOT_PROFILE):
|
|
raise ValueError('Unreviewed explicit Source WMO root profile')
|
|
records=_wmo_chunk_records(raw,source5875_root=source_root_profile is not None);chunks=dict(records)
|
|
if len(records)!=len(chunks):raise ValueError('Duplicate/truncated WMO chunk')
|
|
if chunks.get('MVER')!=struct.pack('<I',17)or len(chunks.get('MOHD',b''))!=64:
|
|
raise ValueError('Unreviewed WMO root version/header')
|
|
materials,groups=struct.unpack_from('<2I',chunks['MOHD'])
|
|
if materials>65536 or groups>4096:raise ValueError('WMO dependency count bound')
|
|
if len(chunks.get('MOMT',b''))!=64*materials or len(chunks.get('MOGI',b''))!=32*groups:
|
|
raise ValueError('Unreviewed WMO material/group extent')
|
|
consumed=sum(8+len(body)for _,body in records)
|
|
source_reader=(dict(profile=source_root_profile,original_parser='5014/5875:0x6c3a60',
|
|
optional_chunk_reader='0x6c3a20',consumed_bytes=consumed,
|
|
ignored_suffix_bytes=len(raw)-consumed,
|
|
ignored_suffix_sha256=hashlib.sha256(raw[consumed:]).hexdigest()if consumed<len(raw)else None,
|
|
ignored_suffix_is_padding=False,original_source_bytes_preserved=True)
|
|
if source_root_profile is not None else None)
|
|
return chunks,materials,groups,source_reader
|
|
|
|
|
|
def classic_wmo_dependencies(raw,root_path,*,source_root_profile=None):
|
|
chunks,materials,groups,source_reader=_classic_wmo_root_chunks(
|
|
raw,root_path,source_root_profile=source_root_profile)
|
|
def paths(tag,extensions):
|
|
data=chunks.get(tag,b'');result=set()
|
|
if data and not data.endswith(b'\0'):raise ValueError('Unterminated WMO asset names')
|
|
for item in data.split(b'\0'):
|
|
if not item:continue
|
|
try:path=item.decode('ascii').replace('\\','/').lower()
|
|
except UnicodeDecodeError:raise ValueError('Non-ASCII WMO asset path')from None
|
|
if (len(path)>1024 or ':'in path or path.startswith('/')or not path.endswith(extensions)or
|
|
any(p in ('','.','..')for p in path.split('/'))or any(ord(c)<32 for c in path)):
|
|
raise ValueError('Unsafe/unreviewed WMO asset name')
|
|
result.add(path)
|
|
return sorted(result)
|
|
return dict(sha256=hashlib.sha256(raw).hexdigest(),version=17,material_count=materials,
|
|
group_count=groups,group_paths=[root_path[:-4]+f'_{i:03}.wmo'for i in range(groups)],
|
|
textures=paths('MOTX',('.blp',)),doodads=paths('MODN',('.mdx','.m2','.mdl')),
|
|
source_root_reader=source_reader,converted=False,dependencies_resolved=False,installed=False,engine_verified=False)
|
|
|
|
# Original Source5014/5875 material realization0x6c3db0 resolves only MOTX
|
|
# +12/+24; +36 remains opaque here. These tuples are observed70334 assets,
|
|
# a structural candidate filter, not a proof of shader equivalence.
|
|
_WMO_STRUCTURAL_MATERIAL_TUPLES=frozenset({
|
|
(0,0,0),(0,0,1),(0,4,0),(0,5,0),(1,0,0),(4,0,0),(4,0,1),
|
|
(4,4,0),(16,0,0),(40,0,0),(128,0,0),(192,0,0),(192,0,1),
|
|
(192,4,0),(196,0,1),(196,4,0),(200,0,0),(208,0,0)})
|
|
|
|
|
|
def classic_wmo_group_structure(raw):
|
|
"""Bound v17 geometry arrays; retain every unknown chunk/flag verbatim."""
|
|
records=_wmo_chunk_records(raw);parts={k:b for k,b in records}
|
|
if any(sum(t==tag for t,b in records)!=1 for tag in('MVER','MOGP')):
|
|
raise ValueError('WMO group core chunk multiplicity')
|
|
if parts.get('MVER')!=struct.pack('<I',17)or len(parts.get('MOGP',b''))<68:
|
|
raise ValueError('Unreviewed WMO group version/header')
|
|
nested=_wmo_chunk_records(parts['MOGP'][68:],maximum=4096)
|
|
by=defaultdict(list)
|
|
for tag,body in nested:by[tag].append(body)
|
|
strides={'MOPY':2,'MOVI':2,'MOVT':12,'MONR':12,'MOTV':8,'MOBA':24}
|
|
for tag,stride in strides.items():
|
|
if not by[tag]or any(len(b)%stride for b in by[tag]):
|
|
raise ValueError('WMO group required array/stride')
|
|
if tag!='MOTV'and len(by[tag])!=1:raise ValueError('Repeated WMO group core array')
|
|
vertices=len(by['MOVT'][0])//12;indices=len(by['MOVI'][0])//2
|
|
if len(by['MONR'][0])//12!=vertices or any(len(b)//8!=vertices for b in by['MOTV']):
|
|
raise ValueError('WMO group vertex attribute count')
|
|
if indices!=3*(len(by['MOPY'][0])//2):raise ValueError('WMO group triangle count')
|
|
if any(i>=vertices for(i,)in struct.iter_unpack('<H',by['MOVI'][0])):
|
|
raise ValueError('WMO group vertex index bound')
|
|
for at in range(0,len(by['MOBA'][0]),24):
|
|
start,count=struct.unpack_from('<IH',by['MOBA'][0],at+12)
|
|
if start>indices or count>indices-start:raise ValueError('WMO group batch index extent')
|
|
return dict(version=17,MOGP_header_bytes=68,vertices=vertices,indices=indices,
|
|
triangles=indices//3,batches=len(by['MOBA'][0])//24,
|
|
chunks=[dict(tag=t,bytes=len(b))for t,b in nested],
|
|
unknown_chunks=[t for t,b in nested if t not in strides],
|
|
all_unknown_chunks_and_flags_preserved=True,converted=False,
|
|
material_or_original_engine_acceptance=False)
|
|
|
|
|
|
|
|
def classic_wmo_group_candidate(raw):
|
|
"""Normalize only proven Source5875 zero/header-only MOGP extents.
|
|
|
|
Source6c3f80 starts at file+20, advances68 then fixes nested arrays by
|
|
their own extents. Native108632 carries the complete outer extent. Every
|
|
geometry byte, nested extent, flag and opaque chunk stays unchanged.
|
|
"""
|
|
if not isinstance(raw,bytes)or not 88<=len(raw)<=67108864:
|
|
raise ValueError('Bounded WMO group required')
|
|
declared=struct.unpack_from('<I',raw,16)[0]
|
|
legacy=(raw[:4]==b'REVM'and struct.unpack_from('<II',raw,4)==(4,17)and
|
|
raw[12:16]==b'PGOM'and declared in(0,64))
|
|
output=raw
|
|
if legacy:output=raw[:16]+struct.pack('<I',len(raw)-20)+raw[20:]
|
|
detail=classic_wmo_group_structure(output)
|
|
detail.update(status='HELD_WMO_GROUP_STRUCTURAL_CANDIDATE',
|
|
legacy_MOGP_extent_normalized=legacy,legacy_declared_MOGP_extent=declared,
|
|
legacy_zero_MOGP_extent_normalized=legacy and declared==0,
|
|
changed_byte_extent=[16,20]if legacy else None,
|
|
all_geometry_nested_extents_and_flags_preserved=True,publishable=False,
|
|
native_group_control=108632,original_Source_consumer='5014/5875:6c3f80->6c40c0',
|
|
material_fidelity_proven=False,engine_verified=False)
|
|
return output,detail
|
|
|
|
|
|
# Source5875 normal shader0 drawers consume no MOMT+36 value and pass no
|
|
# material pointer to a shader callee. Source70/449/450's 73 exact original
|
|
# group bodies bind the same material indices; all 95 paired MOMT rows differ
|
|
# only in resource words+12/+24 and word+36. The 59 nonzero paired fields
|
|
# become zero in the original70334 records. For the exact opaque shader0
|
|
# class this is an unused Source word, independent of its numeric bit pattern.
|
|
# The profile name is retained for compatibility; no float conversion,
|
|
# tolerance, third-texture resolution or other shader equivalence is implied.
|
|
_WMO_LEGACY_MATERIAL_PROFILE='source5875-shader0-float36-native70334-zero-v1'
|
|
_WMO_PROFILE_EXTRA_TUPLES=frozenset({(0,1,0),(16,1,0)})
|
|
|
|
|
|
def _wmo_numeric_materials(materials,tex,texture_bindings,legacy_material_profile=None):
|
|
"""Translate only the independently proved material/resource role."""
|
|
if legacy_material_profile not in (None,_WMO_LEGACY_MATERIAL_PROFILE):
|
|
raise ValueError('Unreviewed explicit legacy WMO material profile')
|
|
if not isinstance(materials,bytes)or len(materials)%64:
|
|
raise ValueError('Unreviewed WMO material extent')
|
|
valid=lambda i:type(i)is int and 0<i<=0xffffffff
|
|
mat=bytearray(materials)
|
|
canonicalized_float36=[];profile_material_tuples=[]
|
|
allowed=_WMO_STRUCTURAL_MATERIAL_TUPLES
|
|
if legacy_material_profile is not None:allowed=allowed|_WMO_PROFILE_EXTRA_TUPLES
|
|
for at in range(0,len(mat),64):
|
|
flags,shader,blend=struct.unpack_from('<3I',mat,at)
|
|
material_tuple=(flags,shader,blend)
|
|
# Both complete pinned normal shader0 drawers observe flag mask0xF7;
|
|
# bit0x08 reaches no state/sampler/color operand. Source24 therefore
|
|
# reduces to Source16, whose same16 native target is independently
|
|
# paired (kl_pvpbarracks material8). Do not mask arbitrary flags or
|
|
# infer new native combinations. The strict default stays unchanged.
|
|
if legacy_material_profile is not None and material_tuple==(24,0,0):
|
|
flags=16;material_tuple=(16,0,0)
|
|
struct.pack_into('<I',mat,at,flags)
|
|
# The same pinned normal drawers make Source8 equivalent to Source0;
|
|
# nineteen original Source0/native0 pairs qualify that target. Admit
|
|
# only the observed opaque, zero-word36 case (shipwreck material1).
|
|
# Other flag combinations and the strict default remain unchanged.
|
|
elif legacy_material_profile is not None and material_tuple==(8,0,0) and struct.unpack_from('<I',mat,at+36)[0]==0:
|
|
flags=0;material_tuple=(0,0,0)
|
|
struct.pack_into('<I',mat,at,flags)
|
|
if material_tuple not in allowed:
|
|
raise ValueError('Unreviewed WMO material tuple')
|
|
if material_tuple in _WMO_PROFILE_EXTRA_TUPLES:profile_material_tuples.append(at//64)
|
|
legacy36=struct.unpack_from('<I',mat,at+36)[0]
|
|
if legacy36:
|
|
if legacy_material_profile is None or material_tuple!=(0,0,0):
|
|
raise ValueError('Unproved nonzero source material +36 role')
|
|
struct.pack_into('<I',mat,at+36,0)
|
|
canonicalized_float36.append(dict(material=at//64,source_word=legacy36,native_word=0,
|
|
semantic_class='Source-normal-opaque-shader0-unused-word36',
|
|
numeric_value_or_float_similarity_used=False))
|
|
for off in(12,24):
|
|
index=struct.unpack_from('<I',mat,at+off)[0]
|
|
if index not in tex:raise ValueError('WMO texture offset not a string start')
|
|
path=tex[index]
|
|
if not path:
|
|
if off==12:raise ValueError('Unbound primary WMO texture')
|
|
ident=0 # Source5875 explicit empty-secondary => NULL handle.
|
|
else:
|
|
ident=texture_bindings.get(path)
|
|
if not path.endswith('.blp')or not valid(ident):
|
|
raise ValueError('Unbound WMO texture')
|
|
struct.pack_into('<I',mat,at+off,ident)
|
|
return bytes(mat),canonicalized_float36,profile_material_tuples
|
|
|
|
|
|
def classic_wmo_numeric_candidate(raw,root_path,*,texture_bindings,group_bindings,doodad_bindings,
|
|
legacy_material_profile=None,referenced_doodads_only=False,source_root_profile=None,
|
|
sky_binding=None):
|
|
"""Prepare an unpublished numeric-resource root with explicit held fidelity.
|
|
|
|
Binding values must come from owning byte-identity/registry receipts. This
|
|
helper never invents IDs, resolves names from a live client or publishes.
|
|
"""
|
|
if type(referenced_doodads_only)is not bool:
|
|
raise ValueError('Explicit referenced WMO doodad policy required')
|
|
if legacy_material_profile not in (None,_WMO_LEGACY_MATERIAL_PROFILE):
|
|
raise ValueError('Unreviewed explicit legacy WMO material profile')
|
|
chunks,materials,groups,source_reader=_classic_wmo_root_chunks(
|
|
raw,root_path,source_root_profile=source_root_profile)
|
|
if 'GFID'in chunks or 'MODI'in chunks:raise ValueError('Already numeric WMO root')
|
|
valid=lambda i:type(i)is int and 0<i<=0xffffffff
|
|
if (not isinstance(group_bindings,list)or len(group_bindings)!=groups or
|
|
any(not valid(i)for i in group_bindings)):
|
|
raise ValueError('Complete bound WMO groups required')
|
|
if not isinstance(texture_bindings,dict)or not isinstance(doodad_bindings,dict):
|
|
raise ValueError('Explicit WMO resource bindings required')
|
|
def names(tag):
|
|
b=chunks.get(tag,b'');out={};at=0
|
|
if b and not b.endswith(b'\0'):raise ValueError('Unterminated WMO name block')
|
|
while at<len(b):
|
|
end=b.index(0,at)
|
|
try:p=b[at:end].decode('ascii').replace('\\','/').lower()
|
|
except UnicodeDecodeError:raise ValueError('Non-ASCII WMO name')from None
|
|
if p and(':'in p or p.startswith('/')or any(x in('','.','..')for x in p.split('/'))):
|
|
raise ValueError('Unsafe WMO resource name')
|
|
out[at]=p;at=end+1
|
|
return out
|
|
tex=names('MOTX');models=names('MODN');mat=bytearray(chunks['MOMT'])
|
|
mat,canonicalized_float36,profile_material_tuples=_wmo_numeric_materials(
|
|
chunks['MOMT'],tex,texture_bindings,legacy_material_profile)
|
|
flag_canonicalizations=[dict(material=at//64,
|
|
source_flags=struct.unpack_from('<I',chunks['MOMT'],at)[0],
|
|
native_flags=struct.unpack_from('<I',mat,at)[0],
|
|
semantic_class='Source-normal-opaque-shader0-unobserved-bit08-to-qualified%d'%struct.unpack_from('<I',mat,at)[0],
|
|
other_flag_bits_preserved=True)
|
|
for at in range(0,len(mat),64)
|
|
if mat[at:at+4]!=chunks['MOMT'][at:at+4]]
|
|
mod=bytearray(chunks.get('MODD',b''))
|
|
if len(mod)%40:raise ValueError('Unreviewed WMO doodad extent')
|
|
used_offsets={struct.unpack_from('<I',mod,at)[0]&0xffffff for at in range(0,len(mod),40)}
|
|
if any(offset not in models or not models[offset]for offset in used_offsets):
|
|
raise ValueError('WMO doodad name offset')
|
|
ordered=[(offset,path)for offset,path in models.items()if path and
|
|
(not referenced_doodads_only or offset in used_offsets)];indices={};model_ids=[]
|
|
for offset,path in ordered:
|
|
ident=doodad_bindings.get(path)
|
|
if not path.endswith(('.mdx','.m2','.mdl'))or not valid(ident):
|
|
raise ValueError('Unbound WMO doodad resource')
|
|
indices[offset]=len(model_ids);model_ids.append(ident)
|
|
for at in range(0,len(mod),40):
|
|
value=struct.unpack_from('<I',mod,at)[0];index=value&0xffffff
|
|
if index not in indices:raise ValueError('WMO doodad name offset')
|
|
struct.pack_into('<I',mod,at,(value&0xff000000)|indices[index])
|
|
has_sky=any(chunks.get('MOSB',b''))
|
|
if has_sky and not valid(sky_binding):raise ValueError('Unbound WMO sky resource')
|
|
if not has_sky and sky_binding is not None:raise ValueError('Unexpected WMO sky binding')
|
|
header=bytearray(chunks['MOHD']);flags=struct.unpack_from('<H',header,60)[0]
|
|
if flags&0x10:raise ValueError('Unreviewed source LOD flag')
|
|
struct.pack_into('<I',header,16,len(model_ids));struct.pack_into('<H',header,62,1)
|
|
changes={'MOHD':bytes(header),'MOMT':bytes(mat),'MODD':bytes(mod)}
|
|
output=[]
|
|
def add(tag,body):output.append(tag[::-1].encode('ascii')+struct.pack('<I',len(body))+body)
|
|
for tag,body in chunks.items():
|
|
if tag not in('MOTX','MODN','MOSB') or (tag=='MOSB' and not has_sky):add(tag,changes.get(tag,body))
|
|
if has_sky:add('MOSI',struct.pack('<I',sky_binding))
|
|
if model_ids:add('MODI',struct.pack('<'+'I'*len(model_ids),*model_ids))
|
|
add('GFID',struct.pack('<'+'I'*len(group_bindings),*group_bindings))
|
|
return b''.join(output),dict(status='HELD_NUMERIC_WMO_STRUCTURAL_CANDIDATE',
|
|
material_count=materials,groups=groups,doodad_resources=len(model_ids),
|
|
source_root_reader=source_reader,
|
|
source_texture_operands_rewritten=[12,24],
|
|
source_other_material_bytes_preserved=not canonicalized_float36 and not flag_canonicalizations,
|
|
legacy_material_profile=legacy_material_profile,
|
|
shader0_unused_float36_canonicalizations=canonicalized_float36,
|
|
shader0_unused_flag08_canonicalizations=flag_canonicalizations,
|
|
additional_original_native_material_tuple_rows=profile_material_tuples,
|
|
material_bytes_except_bound_textures_and_explicit_float36_preserved=not flag_canonicalizations,
|
|
material_bytes_except_bound_textures_and_explicit_Source_semantic_profile_preserved=True,
|
|
source_doodad_transform_and_upper_flags_preserved=True,
|
|
referenced_doodads_only=referenced_doodads_only,
|
|
unused_name_resources_excluded=sum(bool(path)for path in models.values())-len(ordered),
|
|
source_doodad_placement_count=len(mod)//40,
|
|
all_source_doodad_placements_preserved=True,
|
|
unknown_chunks_and_MOHD_flags_preserved=True,native_group_format_control=108632,
|
|
single_LOD_record_control='native md_crypt_d.wmo flags5,numLod1,19GFID',
|
|
material_fidelity_proven=False,actual_Octo_fork_proven=False,
|
|
publishable=False,installed=False,engine_verified=False)
|
|
|
|
|
|
def inventory_local_maps(client, output, listfile, reader_source):
|
|
"""Inventory every Map candidate and requested WDT across local archives.
|
|
|
|
Archive candidates remain independent. Equal bytes establish only agreement
|
|
of available candidates; they never establish the launcher's effective order.
|
|
No client files are changed and no asset is converted or installed.
|
|
"""
|
|
import ctypes as C
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
from octo_icon_assets import archive_paths, cached_reader
|
|
from octo_client_data import read_member
|
|
from turtle_data import DBC
|
|
root=Path(__file__).resolve().parents[1]
|
|
client=Path(client).resolve();output=Path(output)
|
|
if (output.is_symlink()or output.exists()or
|
|
not output.resolve().is_relative_to(root/'runtime')or
|
|
output.resolve().is_relative_to(client)):
|
|
raise ValueError('Use a fresh workspace runtime map inventory')
|
|
archives=archive_paths(client);stats={p:(p.stat().st_size,p.stat().st_mtime_ns)for p in archives}
|
|
api,reader_sha=cached_reader(Path(reader_source))
|
|
output.mkdir(parents=True);payloads=output/'payloads';payloads.mkdir()
|
|
consumed=0;tables=[];found=[];requests={};unique=set()
|
|
def retain(raw,suffix):
|
|
nonlocal consumed
|
|
digest=hashlib.sha256(raw).hexdigest()
|
|
if digest not in unique:
|
|
consumed+=len(raw)
|
|
if consumed>268435456:raise ValueError('Map inventory unique payload byte bound')
|
|
(payloads/(digest+suffix)).write_bytes(raw);unique.add(digest)
|
|
return digest,payloads/(digest+suffix)
|
|
def scan(callback):
|
|
for archive in archives:
|
|
handle=C.c_void_p()
|
|
status=api.libmpq__archive_open(C.byref(handle),os.fsencode(archive),0)
|
|
if status:raise ValueError('Map inventory archive cannot be opened: '+archive.name)
|
|
try:callback(archive,handle)
|
|
finally:
|
|
if api.libmpq__archive_close(handle):raise ValueError('Map inventory archive close failed')
|
|
if (archive.stat().st_size,archive.stat().st_mtime_ns)!=stats[archive]:raise ValueError('Source archive changed')
|
|
def table(archive,handle):
|
|
raw=read_member(api,handle,'DBFilesClient\\Map.dbc')
|
|
if raw is None:return
|
|
digest,path=retain(raw,'.dbc');row=dict(archive=str(archive.relative_to(client/'Data')),sha256=digest)
|
|
try:
|
|
plan=map_requests(DBC(path));row['map_table']=plan
|
|
for entry in plan['records']:
|
|
requests.setdefault(entry['wdt_path'],[]).append(dict(
|
|
source_map_id=entry['source_map_id'],name=entry['name_enUS'],map_dbc_sha256=digest))
|
|
except ValueError as error:row['blocked']=str(error)
|
|
tables.append(row)
|
|
scan(table)
|
|
if not requests:raise ValueError('No reviewed source Map candidate available')
|
|
if len(requests)>4096:raise ValueError('Map directory union bound')
|
|
parsed={}
|
|
def wdts(archive,handle):
|
|
for member in sorted(requests):
|
|
raw=read_member(api,handle,member.replace('/','\\'))
|
|
if raw is None:continue
|
|
digest,path=retain(raw,'.wdt');key=(digest,member)
|
|
if key not in parsed:
|
|
try:parsed[key]=wdt_structure(raw,member.split('/')[2])
|
|
except ValueError as error:parsed[key]=dict(blocked=str(error))
|
|
found.append(dict(archive=str(archive.relative_to(client/'Data')),member=member,
|
|
sha256=digest,payload=path.name,structure=parsed[key]))
|
|
scan(wdts)
|
|
with Path(listfile).open('rb')as stream:native=native_wdt_names(stream,set(requests))
|
|
by_path={}
|
|
for row in found:by_path.setdefault(row['member'],[]).append(row)
|
|
native_by_path={r['path']:r for r in native['records']};maps=[]
|
|
for member,origins in sorted(requests.items()):
|
|
candidates=by_path.get(member,[]);hashes=sorted({r['sha256']for r in candidates})
|
|
maps.append(dict(path=member,source_map_candidates=origins,
|
|
source_wdt_candidates=[dict(archive=r['archive'],sha256=r['sha256'])for r in candidates],
|
|
candidate_status='missing-scanned-archives'if not hashes else'single-content-candidate'if len(hashes)==1 else'conflicting-archive-candidates',
|
|
native_name=native_by_path[member],source_wdt_hashes=hashes))
|
|
if archive_paths(client)!=archives or any((p.stat().st_size,p.stat().st_mtime_ns)!=stats[p]for p in archives):raise ValueError('Source archive set changed')
|
|
report=dict(kind='all-source-map-candidate-inventory',reader_source_sha256=reader_sha,
|
|
source_installation=str(client),archives=[dict(path=str(p.relative_to(client/'Data')),bytes=stats[p][0],mtime_ns=stats[p][1])for p in archives],
|
|
source_map_tables=tables,maps=maps,wdt_candidates=found,
|
|
unique_payload_bytes=consumed,native_listfile_sha256=native['listfile_sha256'],
|
|
effective_archive_precedence_verified=False,native_payloads_verified=False,
|
|
converted=False,installed=False,engine_verified=False,
|
|
limits=['All reviewed Map candidates are included, without choosing an arbitrary patch winner.',
|
|
'Missing WDT in scanned archives or absent listfile name is not proof of unavailable content.',
|
|
'ADT/WMO/M2/material dependency conversion, map-ID conflicts, terrain equivalence and actual-engine testing remain required.'])
|
|
(output/'report.json').write_text(json.dumps(report,sort_keys=True,indent=2)+'\n')
|
|
from collections import Counter
|
|
summary=dict(map_table_candidates=len(tables),map_directories=len(maps),wdt_candidates=len(found),
|
|
candidate_status_counts=dict(Counter(r['candidate_status']for r in maps)),
|
|
absent_native_wdt_names=sum(not r['native_name']['name_present']for r in maps),
|
|
unique_payload_bytes=consumed,converted=False,installed=False)
|
|
(output/'summary.json').write_text(json.dumps(summary,indent=2)+'\n')
|
|
return summary
|
|
|
|
|
|
if __name__=='__main__':
|
|
import argparse,json
|
|
from pathlib import Path
|
|
p=argparse.ArgumentParser(description=__doc__)
|
|
p.add_argument('--inventory-local',action='store_true',required=True)
|
|
p.add_argument('--client',type=Path,default=Path.home()/'Games/octo/drive_c/Octowow')
|
|
p.add_argument('--output',type=Path,required=True)
|
|
p.add_argument('--listfile',type=Path,default=Path.home()/'Projects/WoW-Hybrid/listfiles/community-listfile.csv')
|
|
p.add_argument('--reader-source',type=Path,default=Path.home()/'Servers/tortoise-wow/dep/libmpq/libmpq')
|
|
a=p.parse_args()
|
|
print(json.dumps(inventory_local_maps(a.client,a.output,a.listfile,a.reader_source),sort_keys=True))
|
|
|
|
|
|
def _adt_terrain_child(raw, bounds, tag, sizes):
|
|
"""Reuse the accepted unique named terrain-child/extent relationship."""
|
|
body, end = bounds; found = []
|
|
for offset in range(body + 128, end - 7):
|
|
if raw[offset:offset+4] in (tag, tag[::-1]):
|
|
size = struct.unpack_from('<I', raw, offset+4)[0]
|
|
if size in sizes and offset+8+size <= end:
|
|
found.append((offset+8, size))
|
|
if len(found) != 1:
|
|
raise ValueError('Near-terrain named child missing/ambiguous: ' + tag.decode())
|
|
return found[0]
|
|
|
|
|
|
def adt_height_profile(raw, tile, *, include_normals=False):
|
|
"""Bounded v18 ADT terrain-only diagnostic, never a map conversion.
|
|
|
|
Reuses the pinned original map_extractor MCNK/MCVT -> V9/V8 algorithm
|
|
(System.cpp:504-572, adt.h). Axis order is intentional: MCNK iy is the
|
|
world-X sample row and ix the world-Y column. WMO/liquid/collision and an
|
|
actor's actual native position remain separate authorities.
|
|
"""
|
|
import math
|
|
if (not isinstance(raw, bytes) or not 12 <= len(raw) <= 67108864
|
|
or not isinstance(tile, tuple) or len(tile) != 2
|
|
or any(type(v) is not int or not 0 <= v < 64 for v in tile)):
|
|
raise ValueError('Bounded ADT bytes and exact (filename-x, filename-y) tile required')
|
|
if type(include_normals) is not bool:
|
|
raise ValueError('Explicit normal-grid diagnostic mode required')
|
|
v9 = [math.nan] * (129 * 129)
|
|
v8 = [math.nan] * (128 * 128)
|
|
n9 = [None] * (129 * 129) if include_normals else None
|
|
n8 = [None] * (128 * 128) if include_normals else None
|
|
cells = {}; pos = 0; version = None; chunks = 0; padding = 0
|
|
while pos < len(raw):
|
|
if raw[pos:pos + 8] == bytes(8):
|
|
padding = len(raw) - pos
|
|
if len(cells) != 256 or padding > 65536 or any(raw[pos:]):
|
|
raise ValueError('Unreviewed ADT height trailing data')
|
|
break
|
|
if len(raw) - pos < 8 or chunks >= 4096:
|
|
raise ValueError('ADT height chunk framing/count bound')
|
|
tag, size = struct.unpack_from('<4sI', raw, pos); pos += 8; chunks += 1
|
|
if size > len(raw) - pos:
|
|
raise ValueError('Truncated ADT height chunk')
|
|
data = raw[pos:pos + size]; pos += size
|
|
if tag == b'REVM':
|
|
if version is not None or data != struct.pack('<I', 18):
|
|
raise ValueError('Unreviewed ADT height version')
|
|
version = 18
|
|
if tag != b'KNCM':
|
|
continue
|
|
if len(data) < 128:
|
|
raise ValueError('Truncated MCNK height header')
|
|
flags, ix, iy = struct.unpack_from('<III', data)
|
|
if ix >= 16 or iy >= 16 or (ix, iy) in cells:
|
|
raise ValueError('Duplicate/out-of-range MCNK cell')
|
|
base = struct.unpack_from('<f', data, 112)[0]
|
|
if not math.isfinite(base) or abs(base) > 100000:
|
|
raise ValueError('Nonfinite/out-of-bound MCNK base height')
|
|
# Original FileChunk::GetSubChunk locates MCVT by its typed chunk tag.
|
|
# Retain only a unique, complete145-float occurrence; do not infer a
|
|
# modern high-resolution-hole union to be the legacy MCVT offset.
|
|
found = []; at = 128
|
|
while True:
|
|
at = data.find(b'TVCM', at)
|
|
if at < 0: break
|
|
if at + 8 <= len(data):
|
|
extent = struct.unpack_from('<I', data, at + 4)[0]
|
|
if extent == 145 * 4 and at + 8 + extent <= len(data): found.append(at)
|
|
at += 4
|
|
if len(found) > 1:
|
|
raise ValueError('Ambiguous MCNK MCVT height chunk')
|
|
offset = struct.unpack_from('<I', data, 20)[0]
|
|
if not flags & 0x10000 and offset:
|
|
if not found or offset != found[0] + 8:
|
|
raise ValueError('Legacy MCNK MCVT offset/tag relationship differs')
|
|
heights = struct.unpack_from('<145f', data, found[0] + 8) if found else (0.0,) * 145
|
|
if any(not math.isfinite(v) or abs(v) > 100000 for v in heights):
|
|
raise ValueError('Nonfinite/out-of-bound MCVT height')
|
|
normals = None; normal_metadata = {}
|
|
if include_normals:
|
|
if not found:
|
|
raise ValueError('Explicit MCVT required for normal-grid diagnostics')
|
|
normal_at, normal_size = _adt_terrain_child(data, (0, len(data)), b'MCNR', (435, 448))
|
|
normals = tuple(struct.iter_unpack('<bbb', data[normal_at:normal_at+435]))
|
|
normal_metadata = dict(normal_payload_bytes=normal_size,
|
|
normal_tail_hex=data[normal_at+435:normal_at+normal_size].hex())
|
|
# Round the addition to the original float storage, not Python double.
|
|
f32 = lambda v: struct.unpack('<f', struct.pack('<f', v))[0]
|
|
for y in range(9):
|
|
for x in range(9):
|
|
v9[(iy * 8 + y) * 129 + ix * 8 + x] = f32(base + heights[y * 17 + x])
|
|
if normals is not None:
|
|
n9[(iy * 8 + y) * 129 + ix * 8 + x] = normals[y * 17 + x]
|
|
for y in range(8):
|
|
for x in range(8):
|
|
v8[(iy * 8 + y) * 128 + ix * 8 + x] = f32(base + heights[y * 17 + 9 + x])
|
|
if normals is not None:
|
|
n8[(iy * 8 + y) * 128 + ix * 8 + x] = normals[y * 17 + 9 + x]
|
|
if flags & 0x10000:
|
|
holes = int.from_bytes(data[20:28], 'little')
|
|
else:
|
|
low = struct.unpack_from('<H', data, 60)[0]; holes = 0
|
|
for y in range(8):
|
|
for x in range(8):
|
|
if low & (1 << ((y // 2) * 4 + x // 2)): holes |= 1 << (y * 8 + x)
|
|
cells[(ix, iy)] = dict(flags=flags, base_height=base, holes=holes,
|
|
MCVT_present=bool(found), header_world_x=struct.unpack_from('<f', data, 104)[0],
|
|
header_world_y=struct.unpack_from('<f', data, 108)[0], **normal_metadata)
|
|
if version != 18 or len(cells) != 256 or any(not math.isfinite(v) for v in v9 + v8):
|
|
raise ValueError('Complete v18 ADT terrain tile required')
|
|
result = dict(tile=tile, cells=cells, V9=v9, V8=v8, chunks=chunks,
|
|
trailing_zero_padding_bytes=padding, terrain_only=True)
|
|
if include_normals:
|
|
result.update(N9=n9, N8=n8, normal_axis_transform='identity-signed-storage',
|
|
normal_derivation=False, renderer_normal_map_authority=False)
|
|
return result
|
|
|
|
|
|
def adt_height_sample(profile, world_x, world_y):
|
|
"""Original GridMap::getHeightFromFloat four-triangle diagnostic.
|
|
|
|
float32 operation boundaries mirror the original sampler. Returns a held
|
|
hole explicitly; it never substitutes liquid/WMO/actor-Z or alters terrain.
|
|
"""
|
|
import math
|
|
f32 = lambda v: struct.unpack('<f', struct.pack('<f', v))[0]
|
|
if any(type(v) not in (float, int) or not math.isfinite(v) or abs(v) > 100000 for v in (world_x, world_y)):
|
|
raise ValueError('Finite bounded world XY required')
|
|
grid = f32(533.3333)
|
|
gx = f32(32.0 - f32(f32(world_x) / grid)); gy = f32(32.0 - f32(f32(world_y) / grid))
|
|
if (int(gy), int(gx)) != tuple(profile['tile']):
|
|
raise ValueError('World point outside exact ADT tile')
|
|
xx = f32(128.0 * gx); yy = f32(128.0 * gy)
|
|
xi, yi = int(xx), int(yy); x, y = f32(xx - xi), f32(yy - yi); xi &= 127; yi &= 127
|
|
cell = profile['cells'][(yi // 8, xi // 8)]
|
|
if cell['holes'] & (1 << ((xi % 8) * 8 + yi % 8)):
|
|
return dict(status='HELD_TERRAIN_HOLE', cell=[yi // 8, xi // 8], sample=[xi, yi], height=None)
|
|
v9, v8 = profile['V9'], profile['V8']
|
|
h1 = v9[xi * 129 + yi]; h2 = v9[(xi + 1) * 129 + yi]
|
|
h3 = v9[xi * 129 + yi + 1]; h4 = v9[(xi + 1) * 129 + yi + 1]
|
|
h5 = f32(2.0 * v8[xi * 128 + yi])
|
|
if f32(x + y) < 1:
|
|
if x > y:
|
|
a, b, c, triangle = f32(h2 - h1), f32(f32(h5 - h1) - h2), h1, 1
|
|
else:
|
|
a, b, c, triangle = f32(f32(h5 - h1) - h3), f32(h3 - h1), h1, 2
|
|
elif x > y:
|
|
a, b, c, triangle = f32(f32(h2 + h4) - h5), f32(h4 - h2), f32(h5 - h4), 3
|
|
else:
|
|
a, b, c, triangle = f32(h4 - h3), f32(f32(h3 + h4) - h5), f32(h5 - h4), 4
|
|
height = f32(f32(f32(a * x) + f32(b * y)) + c)
|
|
return dict(status='SAMPLED_TERRAIN_ONLY', height=height, cell=[yi // 8, xi // 8],
|
|
sample=[xi, yi], triangle=triangle, fractional_xy=[x, y])
|
|
|
|
|
|
def _adt_terrain_edge(profile, axis, side):
|
|
"""Read one filename-grid edge; no normal swizzle or height synthesis."""
|
|
if (axis not in (0, 1) or side not in (0, 1) or len(profile.get('V9', [])) != 16641
|
|
or len(profile.get('N9', [])) != 16641 or len(profile.get('cells', {})) != 256):
|
|
raise ValueError('Complete height/normal tile edge required')
|
|
indices = [i*129 + side*128 if axis == 0 else side*128*129+i for i in range(129)]
|
|
heights = [profile['V9'][i] for i in indices]
|
|
normals = [profile['N9'][i] for i in indices]
|
|
import math
|
|
if (any(type(v) not in (int, float) or not math.isfinite(v) for v in heights)
|
|
or any(not isinstance(v, (list, tuple)) or len(v) != 3
|
|
or any(type(c) is not int or not -128 <= c <= 127 for c in v) for v in normals)):
|
|
raise ValueError('Finite heights and exact signed normal vectors required')
|
|
holes = []
|
|
for i in range(128):
|
|
xy = (side*15, i//8) if axis == 0 else (i//8, side*15)
|
|
bit = (i%8)*8 + side*7 if axis == 0 else side*56+i%8
|
|
holes.append((profile['cells'][xy]['holes'] >> bit) & 1)
|
|
return heights, normals, holes
|
|
|
|
|
|
def _adt_edge_difference(first, second):
|
|
def ordered(value):
|
|
bits = struct.unpack('<I', struct.pack('<f', value))[0]
|
|
return 0x80000000-(bits & 0x7fffffff) if bits & 0x80000000 else 0x80000000+bits
|
|
ah, an, ao = first; bh, bn, bo = second
|
|
changed = [i for i, (a, b) in enumerate(zip(ah, bh)) if ordered(a) != ordered(b)]
|
|
return dict(height_vertices_different=len(changed),
|
|
max_absolute_height_difference=max((abs(ah[i]-bh[i]) for i in changed), default=0),
|
|
max_float32_ULP_difference=max((abs(ordered(ah[i])-ordered(bh[i])) for i in changed), default=0),
|
|
normal_vertices_different=sum(tuple(a) != tuple(b) for a, b in zip(an, bn)),
|
|
hole_segments_different=sum(a != b for a, b in zip(ao, bo)))
|
|
|
|
|
|
def adt_terrain_family_diagnostics(source_profiles, native_profiles, *, known_present_tiles=None):
|
|
"""Measure every retained shared edge and changed open boundary as a family.
|
|
|
|
Unchanged outer edges reuse the original native neighbor relationship.
|
|
Changed edges require a neighbor rather than silently accepting a tile in
|
|
isolation. Diagnostics never establish renderer/LOD or source-version proof.
|
|
"""
|
|
def valid_tile(tile):
|
|
return isinstance(tile, tuple) and len(tile) == 2 and all(type(v) is int and 0 <= v < 64 for v in tile)
|
|
if (not isinstance(source_profiles, dict) or not isinstance(native_profiles, dict)
|
|
or set(source_profiles) != set(native_profiles) or not 1 <= len(source_profiles) <= 4096
|
|
or any(not valid_tile(t) or tuple(source_profiles[t].get('tile', ())) != t
|
|
or tuple(native_profiles[t].get('tile', ())) != t for t in source_profiles)):
|
|
raise ValueError('Matched complete source/native tile family required')
|
|
if known_present_tiles is not None and (not isinstance(known_present_tiles, set)
|
|
or any(not valid_tile(t) for t in known_present_tiles) or not set(source_profiles) <= known_present_tiles):
|
|
raise ValueError('Explicit same-map WDT present-tile set required')
|
|
seams = []; boundaries = []; needed = set()
|
|
for tile in sorted(source_profiles):
|
|
for axis in (0, 1):
|
|
neighbor = list(tile); neighbor[axis] += 1; neighbor = tuple(neighbor)
|
|
if neighbor in source_profiles:
|
|
seams.append(dict(first=list(tile), second=list(neighbor), filename_axis=axis,
|
|
source=_adt_edge_difference(_adt_terrain_edge(source_profiles[tile], axis, 1),
|
|
_adt_terrain_edge(source_profiles[neighbor], axis, 0)),
|
|
native_baseline=_adt_edge_difference(_adt_terrain_edge(native_profiles[tile], axis, 1),
|
|
_adt_terrain_edge(native_profiles[neighbor], axis, 0))))
|
|
for side in (0, 1):
|
|
neighbor = list(tile); neighbor[axis] += 1 if side else -1; neighbor = tuple(neighbor)
|
|
if neighbor in source_profiles:
|
|
continue
|
|
difference = _adt_edge_difference(_adt_terrain_edge(source_profiles[tile], axis, side),
|
|
_adt_terrain_edge(native_profiles[tile], axis, side))
|
|
changed = any(difference[k] for k in ('height_vertices_different', 'normal_vertices_different', 'hole_segments_different'))
|
|
exists = valid_tile(neighbor) and (known_present_tiles is None or neighbor in known_present_tiles)
|
|
if changed and exists:
|
|
needed.add(neighbor)
|
|
boundaries.append(dict(tile=list(tile), neighbor=list(neighbor), filename_axis=axis, side=side,
|
|
source_vs_native=difference, preserved_native_edge=not changed,
|
|
missing_neighbor_required=bool(changed and exists), WDT_presence_proven=known_present_tiles is not None))
|
|
return dict(kind='retained-terrain-family-edge-diagnostic', tiles=len(source_profiles), shared_seams=seams,
|
|
outer_boundaries=boundaries, required_neighbor_tiles=[list(t) for t in sorted(needed)],
|
|
preserved_native_outer_boundaries=sum(r['preserved_native_edge'] for r in boundaries),
|
|
map_FK_authority='Caller must bind the family to one source/native Map/WDT; integer equality is not proof.',
|
|
normal_derivation=False, renderer_LOD_or_mapTextureN_authority=False,
|
|
installable=False, published=False)
|
|
|
|
|
|
def adt_lod_geometry_profile(raw, *, near_profile=None):
|
|
"""Inspect the observed native v18 LOD geometry family without generating it.
|
|
|
|
Complete index-range partition and the height/skirt relations come from
|
|
retained original native assets. The first level float and remaining
|
|
header/node/shadow fields deliberately retain their unknown semantics.
|
|
"""
|
|
import math
|
|
if not isinstance(raw, bytes) or not 12 <= len(raw) <= 67108864:
|
|
raise ValueError('Bounded original LOD ADT required')
|
|
chunks = {}; pos = 0
|
|
while pos < len(raw):
|
|
if pos+8 > len(raw):
|
|
raise ValueError('LOD chunk header truncated')
|
|
tag, size = struct.unpack_from('<4sI', raw, pos); pos += 8
|
|
tag = tag[::-1].decode('ascii', 'replace')
|
|
if tag in chunks or size > len(raw)-pos:
|
|
raise ValueError('LOD duplicate/truncated chunk')
|
|
chunks[tag] = raw[pos:pos+size]; pos += size
|
|
required = {'MVER', 'MLHD', 'MLVH', 'MLLL', 'MLND', 'MLVI', 'MLSI', 'MLLD', 'MASD', 'MALP'}
|
|
if set(chunks) != required or chunks['MVER'] != struct.pack('<I', 18) or len(chunks['MLHD']) != 28:
|
|
raise ValueError('Unreviewed native LOD chunk family/version')
|
|
if (len(chunks['MLVH']) % 4 or len(chunks['MLVI']) % 6
|
|
or len(chunks['MLSI']) % 2 or not len(chunks['MLLL']) or len(chunks['MLLL']) % 20):
|
|
raise ValueError('LOD height/index/level framing differs')
|
|
heights = list(struct.unpack('<'+'f'*(len(chunks['MLVH'])//4), chunks['MLVH']))
|
|
indices = list(struct.unpack('<'+'H'*(len(chunks['MLVI'])//2), chunks['MLVI']))
|
|
skirts = list(struct.unpack('<'+'H'*(len(chunks['MLSI'])//2), chunks['MLSI']))
|
|
prefix_count = 129*129+128*128
|
|
if (len(heights) != prefix_count+len(skirts) or len(heights) > 65535
|
|
or any(not math.isfinite(v) or abs(v) > 100000 for v in heights)
|
|
or any(i >= len(heights) for i in indices) or any(i >= prefix_count for i in skirts)):
|
|
raise ValueError('LOD finite height/vertex-index relationship differs')
|
|
levels = []; cursor = 0
|
|
for first, start, count, skirt_count, skirt_start in struct.iter_unpack('<f4I', chunks['MLLL']):
|
|
if (not math.isfinite(first) or first <= 0 or start != cursor or count % 3 or skirt_count % 3
|
|
or start+count+skirt_count > len(indices)
|
|
or (skirt_count and skirt_start != start+count)):
|
|
raise ValueError('LOD level index partition differs')
|
|
levels.append(dict(first_float=first, index_start=start, index_count=count,
|
|
skirt_index_count=skirt_count, skirt_index_start=skirt_start))
|
|
cursor += count+skirt_count
|
|
if cursor != len(indices):
|
|
raise ValueError('LOD index stream not exhausted by levels')
|
|
f32 = lambda v: struct.unpack('<f', struct.pack('<f', v))[0]
|
|
result = dict(kind='original-native-LOD-geometry-diagnostic', heights=heights, skirt_source_indices=skirts,
|
|
vertex_count=len(heights), regular_vertex_count=prefix_count, index_count=len(indices), levels=levels,
|
|
header_raw_u32=list(struct.unpack('<7I', chunks['MLHD'])),
|
|
chunk_sizes={k: len(v) for k, v in chunks.items()},
|
|
observed_first_level_float_skirt_matches=sum(f32(heights[i]-levels[0]['first_float']) == heights[prefix_count+j]
|
|
for j, i in enumerate(skirts)),
|
|
generation_safe=False, normal_map_generation_proven=False, installable=False, published=False,
|
|
holds=['Original LOD simplification/morph/error and header/node/shadow application semantics',
|
|
'Original mapTextureN encoding and derivation/renderer consumption'])
|
|
if near_profile is not None:
|
|
if len(near_profile.get('V9', [])) != 16641 or len(near_profile.get('V8', [])) != 16384:
|
|
raise ValueError('Complete same-tile near-height profile required')
|
|
comparisons = {}
|
|
for label, begin, values in (('V9', 0, near_profile['V9']), ('V8', 16641, near_profile['V8'])):
|
|
differences = [(a, heights[begin+i]) for i, a in enumerate(values)
|
|
if struct.pack('<f', a) != struct.pack('<f', heights[begin+i])]
|
|
comparisons[label] = dict(vertices=len(values), bit_differences=len(differences),
|
|
max_absolute_difference=max((abs(a-b) for a, b in differences), default=0))
|
|
result['near_height_comparison'] = comparisons
|
|
return result
|
|
|
|
|
|
NATIVE_NEAR_TERRAIN_PROFILE_V1 = {'kind': 'native-near-terrain-geometry-70334-v1', 'native_MCNK_flags': 98368, 'native_MCVT_bytes': 580, 'source_MCVT_bytes': 580, 'native_MCNR_bytes': 448, 'source_MCNR_bytes': 435, 'world_basis': 'equal-xy-float32-within-two-ULPs', 'holes': 'unchanged', 'scope': 'private-geometry-only'}
|
|
NATIVE_NEAR_TERRAIN_NO_MCCV_PROFILE_V1 = {
|
|
**NATIVE_NEAR_TERRAIN_PROFILE_V1,
|
|
'kind': 'native-near-terrain-geometry-without-MCCV-70334-v1',
|
|
'native_MCNK_flags': 0x18000, 'native_MCCV_presence': 'absent'}
|
|
|
|
|
|
def adt_near_terrain_candidate(native_raw, source_raw, tile, *, map_id, native_file_data_id):
|
|
"""Retain the original single-tile prototype admission contract."""
|
|
if (map_id, tuple(tile), native_file_data_id) != (1, (40, 29), 786640):
|
|
raise ValueError('Unreviewed private near-terrain map/tile/FileDataID binding')
|
|
return adt_near_terrain_profile_candidate(native_raw, source_raw, tile,
|
|
map_id=map_id, native_file_data_id=native_file_data_id,
|
|
native_profile=NATIVE_NEAR_TERRAIN_PROFILE_V1)
|
|
|
|
|
|
def adt_near_terrain_profile_candidate(native_raw, source_raw, tile, *, map_id,
|
|
native_file_data_id, native_profile,
|
|
hole_policy='strict'):
|
|
"""Patch an existing native geometry layout using the proved field class.
|
|
|
|
This generalizes the prototype's data-layout contract, not its renderer or
|
|
scene acceptance. Every cell still requires the exact native flags, world
|
|
basis, and measured Source/native MCVT/MCNR extents. The explicit private
|
|
preserve-native-holes and source-expanded-holes modes stage mismatched
|
|
geometry without claiming a native renderer/collision interpretation.
|
|
Materials, liquids, areas, neighbors and LODs remain separate dependencies.
|
|
Inputs are never changed and the returned candidate is not installable.
|
|
"""
|
|
import math
|
|
if native_profile not in (NATIVE_NEAR_TERRAIN_PROFILE_V1,
|
|
NATIVE_NEAR_TERRAIN_NO_MCCV_PROFILE_V1):
|
|
raise ValueError('Unqualified native near-terrain geometry profile')
|
|
if hole_policy not in ('strict', 'preserve-native-holes-private',
|
|
'source-expanded-holes-private'):
|
|
raise ValueError('Unqualified near-terrain hole policy')
|
|
if (type(map_id) is not int or not 0 <= map_id <= 0xffffffff or
|
|
type(native_file_data_id) is not int or not 0 < native_file_data_id <= 0xffffffff or
|
|
not isinstance(tile, (tuple, list)) or len(tile) != 2 or
|
|
any(type(v) is not int or not 0 <= v < 64 for v in tile)):
|
|
raise ValueError('Explicit map/tile/native FileDataID identity required')
|
|
native = adt_height_profile(native_raw, tuple(tile))
|
|
source = adt_height_profile(source_raw, tuple(tile))
|
|
if set(native['cells']) != set(source['cells']):
|
|
raise ValueError('Near-terrain cell identity differs')
|
|
|
|
def spans(raw):
|
|
result = {}; pos = 0
|
|
while pos < len(raw):
|
|
if not any(raw[pos:]):
|
|
break
|
|
if pos + 8 > len(raw):
|
|
raise ValueError('Near-terrain chunk header truncated')
|
|
tag, size = struct.unpack_from('<4sI', raw, pos)
|
|
body = pos + 8; end = body + size
|
|
if end > len(raw):
|
|
raise ValueError('Near-terrain chunk extent')
|
|
if tag in (b'MCNK', b'KNCM'):
|
|
if size < 128:
|
|
raise ValueError('Near-terrain MCNK header truncated')
|
|
xy = struct.unpack_from('<2I', raw, body + 4)
|
|
if xy in result:
|
|
raise ValueError('Near-terrain duplicate cell')
|
|
result[xy] = (body, end)
|
|
pos = end
|
|
return result
|
|
|
|
def child(raw, bounds, tag, size):
|
|
return _adt_terrain_child(raw, bounds, tag, (size,))[0]
|
|
|
|
native_spans = spans(native_raw); source_spans = spans(source_raw)
|
|
if set(native_spans) != set(native['cells']) or set(source_spans) != set(source['cells']):
|
|
raise ValueError('Near-terrain byte/profile cell scope differs')
|
|
output = bytearray(native_raw); changed = []; hole_mismatches = []
|
|
for xy in sorted(native_spans):
|
|
n = native['cells'][xy]; s = source['cells'][xy]
|
|
if (n['flags'] != native_profile['native_MCNK_flags'] or
|
|
not n['MCVT_present'] or not s['MCVT_present']):
|
|
raise ValueError('Unreviewed native near-terrain layout/height context')
|
|
if native_profile == NATIVE_NEAR_TERRAIN_NO_MCCV_PROFILE_V1:
|
|
# The retained 0x18000 ROOT class omits the optional color child.
|
|
# Named MCVT/MCNR reads and every write remain independent of it.
|
|
nb, end = native_spans[xy]
|
|
records = _adt_split_records(native_raw[nb+128:end])
|
|
if (struct.unpack_from('<I', native_raw, nb+116)[0] != 0 or
|
|
any(tag == 'MCCV' for tag, _, _ in records)):
|
|
raise ValueError('Native no-MCCV profile contains color relationship')
|
|
if n['holes'] != s['holes']:
|
|
if hole_policy == 'strict':
|
|
raise ValueError('Near-terrain hole change requires a separate contract')
|
|
hole_mismatches.append(dict(cell=list(xy), source_holes=s['holes'],
|
|
native_holes=n['holes']))
|
|
for axis in ('header_world_x', 'header_world_y'):
|
|
if not math.isfinite(n[axis]) or not math.isfinite(s[axis]):
|
|
raise ValueError('Near-terrain world basis must be finite')
|
|
value = max(abs(n[axis]), abs(s[axis]), 1.0)
|
|
# At most two float32 ULPs; no cell/tile translation is invented.
|
|
tolerance = max(0.0001, math.ldexp(1.0, math.frexp(value)[1] - 23))
|
|
if abs(n[axis] - s[axis]) > tolerance:
|
|
raise ValueError('Near-terrain source/native world basis differs')
|
|
nb = native_spans[xy][0]; sb = source_spans[xy][0]
|
|
nh = child(native_raw, native_spans[xy], b'MCVT', 580)
|
|
sh = child(source_raw, source_spans[xy], b'MCVT', 580)
|
|
nn = child(native_raw, native_spans[xy], b'MCNR', 448)
|
|
sn = _adt_terrain_child(source_raw, source_spans[xy], b'MCNR', (435, 448))[0]
|
|
for kind, target, origin, length in (('baseZ', nb+112, sb+112, 4),
|
|
('MCVT', nh, sh, 580),
|
|
('existing_MCNR', nn, sn, 435)):
|
|
output[target:target+length] = source_raw[origin:origin+length]
|
|
changed.append(dict(cell=list(xy), kind=kind, native_offset=target,
|
|
source_offset=origin, bytes=length))
|
|
if hole_policy == 'source-expanded-holes-private' and n['holes'] != s['holes']:
|
|
output[nb+20:nb+28] = s['holes'].to_bytes(8, 'little')
|
|
changed.append(dict(cell=list(xy), kind='source_expanded_holes',
|
|
native_offset=nb+20, source_offset=None, bytes=8,
|
|
derivation='Source_legacy_16bit_holes_to_8x8_expanded_bits'))
|
|
return bytes(output), dict(kind='private-near-terrain-candidate', map_id=map_id,
|
|
tile=list(tile), native_root_file_data_id=native_file_data_id,
|
|
cells=len(native_spans), source_existing_data_only=True,
|
|
allowed_spans=changed, normal_derivation=False,
|
|
hole_policy=hole_policy,
|
|
native_holes_preserved=hole_policy != 'source-expanded-holes-private',
|
|
source_expanded_holes_written=hole_policy == 'source-expanded-holes-private',
|
|
hole_mismatch_cells=hole_mismatches,
|
|
native_MCNR_tail_preserved_bytes=13, native_size_unchanged=True,
|
|
installable=False, installed=False, published=False,
|
|
dependency_complete=False, engine_accepted=False,
|
|
holds=['Native renderer/normal-map consumption and LOD/companion updates unproved',
|
|
'Neighbor/tile-edge and non-height terrain relationships unreviewed',
|
|
('Source-expanded hole bits written privately; original native renderer/collision consumer unproved'
|
|
if hole_policy == 'source-expanded-holes-private' else
|
|
'Differing Source/native hole masks retain native layout; original native renderer/collision consumer unproved'
|
|
if hole_mismatches else 'Native hole renderer/collision consumer unproved'),
|
|
'Frozen source snapshot is not current remote-fork/update authority'])
|
|
|
|
|
|
|
|
def _adt_split_chunk(tag, payload):
|
|
return tag.encode('ascii')[::-1] + struct.pack('<I', len(payload)) + payload
|
|
|
|
|
|
def _adt_split_records(raw, *, legacy_normals=False, legacy_liquid_extent=None, legacy_alpha_extent=None, maximum=4096):
|
|
"""Bounded chunk records; retain the accepted legacy MCNR13-byte tail."""
|
|
result = []; pos = 0
|
|
while pos < len(raw):
|
|
if len(raw)-pos < 8 or len(result) >= maximum:
|
|
raise ValueError('Split ADT chunk extent/count bound')
|
|
tag, size = struct.unpack_from('<4sI', raw, pos)
|
|
try: name = tag[::-1].decode('ascii')
|
|
except UnicodeDecodeError: raise ValueError('Invalid split ADT tag') from None
|
|
if name == 'MCAL' and size == 0xfffff800 and legacy_alpha_extent is not None:
|
|
parent_offset, parent_size = legacy_alpha_extent
|
|
layers = [p for t,p,tail in result if t=='MCLY']
|
|
layer = layers[0] if len(layers)==1 else None
|
|
no_alpha = layer == b'' or (layer is not None and len(layer)==16 and
|
|
struct.unpack_from('<I',layer,4)[0]==0 and struct.unpack_from('<I',layer,8)[0]==0)
|
|
# Observed Source empty-alpha underflow: the parent owns exactly
|
|
# the8-byte MCAL header; zero layers or one opaque base need no map.
|
|
# Source readers use parent sizeAlpha, not this invalid child word.
|
|
if parent_offset != pos or parent_size != 8 or not no_alpha:
|
|
raise ValueError('Unreviewed empty parent-owned MCAL underflow')
|
|
size = 0
|
|
if name == 'MCLQ' and size == 0 and legacy_liquid_extent is not None:
|
|
parent_offset, parent_size = legacy_liquid_extent
|
|
if parent_size > 8:
|
|
# Actual Source legacy files use a zero child-size word while
|
|
# MCNK owns the complete8+N*804 byte liquid span. N is
|
|
# retained as opaque bytes, not declared a native layer count.
|
|
# Original map_extractor::System.cpp gates on sizeMCLQ>8 and
|
|
# reads adt_MCLQ through that parent relationship.
|
|
if parent_offset != pos or parent_size-8 < 804 or (parent_size-8) % 804:
|
|
raise ValueError('Unreviewed parent-bounded legacy MCLQ extent')
|
|
size = parent_size-8
|
|
if not all(32 <= ord(c) <= 126 for c in name) or size > len(raw)-pos-8:
|
|
raise ValueError('Truncated/invalid split ADT chunk')
|
|
payload = raw[pos+8:pos+8+size]; tail = b''
|
|
if legacy_normals and name == 'MCNR' and size == 435:
|
|
if len(raw)-pos-8-size < 13:
|
|
raise ValueError('Legacy MCNR13-byte tail missing')
|
|
tail = raw[pos+8+size:pos+8+size+13]
|
|
result.append((name, payload, tail)); pos += 8+size+len(tail)
|
|
return result
|
|
|
|
|
|
def _adt_split_names(raw, extensions):
|
|
if not raw: return {}, []
|
|
if not raw.endswith(b'\0'):
|
|
raise ValueError('Unterminated split ADT name table')
|
|
offsets = {}; names = []; at = 0
|
|
for item in raw.split(b'\0')[:-1]:
|
|
if not item:
|
|
raise ValueError('Empty interior split ADT name entry')
|
|
try: path = item.decode('ascii').replace('\\', '/').lower()
|
|
except UnicodeDecodeError: raise ValueError('Non-ASCII split ADT path') from None
|
|
if (len(path) > 1024 or ':' in path or path.startswith('/') or
|
|
not path.endswith(extensions) or any(p in ('', '.', '..') for p in path.split('/')) or
|
|
any(ord(c) < 32 for c in path)):
|
|
raise ValueError('Unsafe split ADT reference path')
|
|
offsets[at] = path; names.append(path); at += len(item)+1
|
|
return offsets, names
|
|
|
|
|
|
def adt_split_candidate(source, tile, *, file_data_ids, roles=('root', 'tex0', 'obj0'),
|
|
normalize_edge_invariant_alpha8=False,
|
|
normalize_dry_liquid_absence=False,
|
|
normalize_flat_ocean_liquid=False,
|
|
preserve_equivalent_ocean_liquid=False):
|
|
"""Serialize private held70334 ROOT/TEX0/OBJ0 from a complete Sourcev18 tile.
|
|
|
|
Every selected external-ID role requires a complete explicit binding map.
|
|
Roles may be selected independently; an unavailable TEX/OBJ is never replaced
|
|
with blank terrain or donor data. Raw geometry/unknown data is retained, but
|
|
this structural constructor does not admit Source flags, alpha/liquid/area
|
|
semantics, external asset fidelity, LODs, or native rendering.
|
|
"""
|
|
if (not isinstance(source, bytes) or not 12 <= len(source) <= 67108864 or
|
|
not isinstance(tile, tuple) or len(tile) != 2 or
|
|
any(type(v) is not int or not 0 <= v < 64 for v in tile)):
|
|
raise ValueError('Bounded Source ADT and exact filename tile required')
|
|
if (not isinstance(roles, tuple) or not roles or len(set(roles)) != len(roles) or
|
|
any(r not in ('root', 'tex0', 'obj0') for r in roles) or not isinstance(file_data_ids, dict)):
|
|
raise ValueError('Explicit split roles and external FileDataID map required')
|
|
if type(normalize_edge_invariant_alpha8) is not bool or (normalize_edge_invariant_alpha8 and 'tex0' not in roles):
|
|
raise ValueError('Explicit alpha8 opt-in requires a selected TEX0 role')
|
|
if type(normalize_dry_liquid_absence) is not bool or (normalize_dry_liquid_absence and 'root' not in roles):
|
|
raise ValueError('Explicit dry-liquid absence opt-in requires a selected ROOT role')
|
|
if (type(normalize_flat_ocean_liquid) is not bool
|
|
or (normalize_flat_ocean_liquid and ('root' not in roles or normalize_dry_liquid_absence))):
|
|
raise ValueError('Explicit flat-ocean opt-in requires ROOT and a distinct liquid constructor')
|
|
if (type(preserve_equivalent_ocean_liquid) is not bool
|
|
or (preserve_equivalent_ocean_liquid and ('root' not in roles
|
|
or normalize_dry_liquid_absence or normalize_flat_ocean_liquid))):
|
|
raise ValueError('Equivalent Ocean preservation requires ROOT and a distinct liquid path')
|
|
# The accepted Source family may have a bounded zero allocation suffix.
|
|
pos = 0; extent = len(source); padding = 0; cells_seen = 0
|
|
while pos < extent:
|
|
if source[pos:pos+8] == bytes(8):
|
|
padding = extent-pos
|
|
if cells_seen != 256 or padding > 65536 or any(source[pos:]):
|
|
raise ValueError('Unreviewed Source split trailing data')
|
|
extent = pos; break
|
|
if extent-pos < 8: raise ValueError('Truncated Source split top chunk')
|
|
tag, n = struct.unpack_from('<4sI', source, pos)
|
|
if n > extent-pos-8: raise ValueError('Truncated Source split top payload')
|
|
cells_seen += tag == b'KNCM'; pos += 8+n
|
|
top = _adt_split_records(source[:extent]); common = {}; cell_data = {}
|
|
for tag, data, tail in top:
|
|
if tag == 'MCNK':
|
|
if len(data) < 128: raise ValueError('Source MCNK128 header required')
|
|
ix, iy = struct.unpack_from('<II', data, 4)
|
|
if ix >= 16 or iy >= 16 or (ix, iy) in cell_data:
|
|
raise ValueError('Duplicate/out-of-range Source split cell')
|
|
cell_data[ix, iy] = data
|
|
else:
|
|
if tag in common: raise ValueError('Duplicate Source split top chunk')
|
|
common[tag] = data
|
|
if common.get('MVER') != struct.pack('<I', 18) or len(common.get('MHDR', b'')) != 64:
|
|
raise ValueError('Source split requires reviewed v18/MHDR64')
|
|
if len(cell_data) != 256 or set(cell_data) != {(x,y) for y in range(16) for x in range(16)}:
|
|
raise ValueError('Complete256-cell Source split grid required')
|
|
if any(t in common for t in ('MDID', 'MHID', 'MAID')):
|
|
raise ValueError('Already-modern Source texture IDs require separate authority')
|
|
texture_offsets, textures = _adt_split_names(common.get('MTEX', b''), ('.blp',))
|
|
model_names, _ = _adt_split_names(common.get('MMDX', b''), ('.mdx', '.m2'))
|
|
wmo_names, _ = _adt_split_names(common.get('MWMO', b''), ('.wmo',))
|
|
def indices(tag, names):
|
|
data = common.get(tag, b'')
|
|
if len(data) % 4: raise ValueError('Split name-index extent')
|
|
values = [v[0] for v in struct.iter_unpack('<I', data)]
|
|
if any(v not in names for v in values): raise ValueError('Split name offset missing')
|
|
return [names[v] for v in values]
|
|
models = indices('MMID', model_names); wmos = indices('MWID', wmo_names)
|
|
placements = {}; required = {'tex0': set(textures), 'obj0': set(), 'root': set()}
|
|
for tag, width, names, flag_offset, marker in (
|
|
('MDDF', 36, models, 34, 0x40), ('MODF', 64, wmos, 56, 0x8)):
|
|
data = common.get(tag, b'')
|
|
if len(data) % width: raise ValueError('Split placement extent')
|
|
result = bytearray(data)
|
|
for at in range(0, len(data), width):
|
|
name_id = struct.unpack_from('<I', data, at)[0]
|
|
flags = struct.unpack_from('<H', data, at+flag_offset)[0]
|
|
if name_id >= len(names) or flags & marker:
|
|
raise ValueError('Unreviewed Source numeric placement/name index')
|
|
path = names[name_id]; required['obj0'].add(path)
|
|
if 'obj0' in roles:
|
|
ident = file_data_ids.get(path)
|
|
if type(ident) is not int or not 0 < ident <= 0xffffffff:
|
|
raise ValueError('Complete explicit OBJ0 asset bindings required: '+path)
|
|
struct.pack_into('<I', result, at, ident)
|
|
struct.pack_into('<H', result, at+flag_offset, flags | marker)
|
|
placements[tag] = bytes(result)
|
|
if 'tex0' in roles:
|
|
for path in textures:
|
|
ident = file_data_ids.get(path)
|
|
if type(ident) is not int or not 0 < ident <= 0xffffffff:
|
|
raise ValueError('Complete explicit TEX0 texture bindings required: '+path)
|
|
root_cells = []; tex_cells = []; obj_cells = []; cell_audit = []; unknown_tags = set()
|
|
for iy in range(16):
|
|
for ix in range(16):
|
|
data = cell_data[ix, iy]; header = bytearray(data[:128]); words = list(struct.unpack('<32I', header))
|
|
children = _adt_split_records(data[128:], legacy_normals=True,
|
|
legacy_liquid_extent=(words[24]-136,words[25]),
|
|
legacy_alpha_extent=(words[9]-136,words[10]), maximum=128)
|
|
parts = {}
|
|
for tag, payload, tail in children:
|
|
if tag in parts: raise ValueError('Duplicate Source MCNK child')
|
|
parts[tag] = payload+tail
|
|
if len(parts.get('MCVT', b'')) != 580 or len(parts.get('MCNR', b'')) != 448:
|
|
raise ValueError('Source MCVT580/physical MCNR448 required')
|
|
if len(parts.get('MCLY', b'')) != words[3]*16:
|
|
raise ValueError('Source layer-count/extent differs')
|
|
for at in range(0, len(parts.get('MCLY', b'')), 16):
|
|
if struct.unpack_from('<I', parts['MCLY'], at)[0] >= len(textures):
|
|
raise ValueError('Source layer texture index outside MTEX')
|
|
refs = parts.get('MCRF', b''); nd, nw = words[4], words[14]
|
|
if len(refs) != 4*(nd+nw): raise ValueError('Source MCRF count/extent differs')
|
|
doodad = refs[:nd*4]; wmoref = refs[nd*4:]
|
|
if any(v[0] >= len(placements['MDDF'])//36 for v in struct.iter_unpack('<I', doodad)) or any(v[0] >= len(placements['MODF'])//64 for v in struct.iter_unpack('<I', wmoref)):
|
|
raise ValueError('Source cell placement reference outside records')
|
|
# Reuse the already accepted legacy4x4 -> native8x8 hole relationship.
|
|
if words[0] & 0x10000: holes = int.from_bytes(data[20:28], 'little')
|
|
else:
|
|
low = words[15] & 0xffff; holes = 0
|
|
for y in range(8):
|
|
for x in range(8):
|
|
if low & (1 << ((y//2)*4+x//2)): holes |= 1 << (y*8+x)
|
|
struct.pack_into('<I', header, 0, words[0] | 0x10000)
|
|
struct.pack_into('<Q', header, 20, holes)
|
|
# Native ROOT controls move layers and references to headerless TEX/OBJ.
|
|
for word in (3,4,7,8,9,10,11,12,14): struct.pack_into('<I', header, word*4, 0)
|
|
struct.pack_into('<I', header, 60, words[15] & 0xffff0000)
|
|
moved = {'MCLY','MCAL','MCSH','MCRF'}
|
|
root_order = [t for t in ('MCVT','MCCV','MCNR','MCSE','MCLQ') if t in parts]
|
|
root_order += [tag for tag,payload,tail in children if tag not in moved and tag not in root_order]
|
|
if 'MCSE' not in parts:
|
|
if words[23]: raise ValueError('Source sound count lacks MCSE')
|
|
parts['MCSE'] = b''; root_order.append('MCSE')
|
|
root_payload = bytearray(header); offsets = {}
|
|
for tag in root_order:
|
|
offsets[tag] = len(root_payload)+8 # relative MCNK chunk start -> child tag
|
|
root_payload += _adt_split_chunk(tag, parts[tag])
|
|
for word, tag in ((22,'MCSE'), (24,'MCLQ'), (29,'MCCV')):
|
|
value = offsets.get(tag, offsets.get('MCSE', 0) if tag=='MCLQ' else 0)
|
|
struct.pack_into('<I', root_payload, word*4, value)
|
|
# MCLQ size word and unknown header words remain Source-authoritative;
|
|
# positive native liquid interpretation is explicitly held.
|
|
tex_payload = b''.join(_adt_split_chunk(t, parts[t]) for t in ('MCLY','MCAL','MCSH') if t in parts)
|
|
obj_payload = (_adt_split_chunk('MCRD',doodad) if doodad else b'') + (_adt_split_chunk('MCRW',wmoref) if wmoref else b'')
|
|
root_cells.append(_adt_split_chunk('MCNK', bytes(root_payload)))
|
|
tex_cells.append(_adt_split_chunk('MCNK', tex_payload)); obj_cells.append(_adt_split_chunk('MCNK',obj_payload))
|
|
unknown = [tag for tag in parts if tag not in moved|{'MCVT','MCCV','MCNR','MCSE','MCLQ'}]; unknown_tags.update(unknown)
|
|
cell_audit.append(dict(cell=[ix,iy],Source_flags=words[0],Source_area_id=words[13],native_holes=holes,root_child_offsets=offsets,unknown_root_children=unknown))
|
|
output = {}; top_unknown = []; root_header = bytearray(common['MHDR'])
|
|
if 'root' in roles:
|
|
for word in range(1,12): struct.pack_into('<I',root_header,word*4,0)
|
|
extras = []; source_removed = {'MVER','MHDR','MCIN','MTEX','MMDX','MMID','MWMO','MWID','MDDF','MODF'}
|
|
# Offsets in MHDR are relative to its payload. Keep opaque Source chunks
|
|
# instead of declaring them native defaults or silently dropping them.
|
|
cursor = 64
|
|
for tag,payload,tail in top:
|
|
if tag == 'MCNK' or tag in source_removed: continue
|
|
if tag in ('MFBO','MH2O','MTXF'):
|
|
struct.pack_into('<I',root_header,{'MFBO':9,'MH2O':10,'MTXF':11}[tag]*4,cursor)
|
|
if tag != 'MH2O':top_unknown.append(tag)
|
|
encoded = _adt_split_chunk(tag,payload);extras.append(encoded);cursor += len(encoded)
|
|
output['root'] = _adt_split_chunk('MVER',common['MVER'])+_adt_split_chunk('MHDR',bytes(root_header))+b''.join(extras)+b''.join(root_cells)
|
|
if 'tex0' in roles:
|
|
mdid = b''.join(struct.pack('<I',file_data_ids[p]) for p in textures)
|
|
output['tex0'] = _adt_split_chunk('MVER',common['MVER'])+_adt_split_chunk('MAMP',struct.pack('<I',0))+_adt_split_chunk('MDID',mdid)+_adt_split_chunk('MHID',bytes(len(mdid)))+b''.join(tex_cells)
|
|
if 'obj0' in roles:
|
|
output['obj0'] = _adt_split_chunk('MVER',common['MVER'])+_adt_split_chunk('MDDF',placements['MDDF'])+_adt_split_chunk('MODF',placements['MODF'])+b''.join(obj_cells)
|
|
alpha8_audit = None
|
|
if normalize_edge_invariant_alpha8:
|
|
output['tex0'], alpha8_audit = adt_tex0_alpha8_candidate(output['tex0'])
|
|
receipt = dict(kind='private-Source-v18-native-split-ADT-structural-candidate',status='HELD_UNPUBLISHED_SPLIT_ADT',tile=list(tile),roles=list(roles),cells=256,source_trailing_zero_padding_retained_in_input=padding,source_MCVT_and_base_world_values_preserved=True,source_normal435_and13tail_preserved=True,source_unknown_cell_tags=sorted(unknown_tags),source_unknown_top_roles=top_unknown,cell_audit=cell_audit,required_bindings={role:sorted(paths) for role,paths in required.items()},MAMP=0,MHID_absence_values=0,MDDF_FileDataID_flag=0x40,MODF_FileDataID_flag=8,held=['Source low flags / alpha encoding / shadow and unknown chunk roles','Source liquid / sound / ground-effect and native AreaTable authority','External asset fidelity and omitted role delivery, LOD/mapTexture/mapTextureN','Actual source fork and native scene rendering'],publishable=False,installed=False,engine_verified=False)
|
|
if alpha8_audit is not None: receipt['alpha8_encoding_candidate'] = alpha8_audit
|
|
if normalize_dry_liquid_absence:
|
|
output['root'], receipt['dry_liquid_absence_candidate'] = adt_root_dry_liquid_candidate(output['root'])
|
|
if normalize_flat_ocean_liquid:
|
|
output['root'], receipt['flat_ocean_liquid_candidate'] = adt_root_flat_ocean_candidate(output['root'])
|
|
if preserve_equivalent_ocean_liquid:
|
|
output['root'], receipt['equivalent_ocean_liquid_candidate'] = adt_root_equivalent_ocean_candidate(output['root'])
|
|
return output,receipt
|
|
|
|
|
|
def _adt_flat_ocean_source_surface(block, *, allow_zero_surface_flt_min_bounds=False):
|
|
"""Accepted Source Ocean operand/attribute predicate shared by both paths."""
|
|
import math
|
|
if type(allow_zero_surface_flt_min_bounds) is not bool:
|
|
raise ValueError('Explicit exact FLT_MIN Ocean bound policy required')
|
|
if not isinstance(block, bytes) or len(block) != 804:
|
|
raise ValueError('Exactly804B Source Ocean block required')
|
|
bounds = struct.unpack_from('<2f', block)
|
|
exact_zero_flt_min = block[:8] == struct.pack('<2I', 0, 0x00800000)
|
|
if (bounds != (0., 0.)
|
|
and not (allow_zero_surface_flt_min_bounds and exact_zero_flt_min)
|
|
or struct.unpack_from('<I', block, 720)[0] or any(block[724:804])):
|
|
raise ValueError('Nonzero Source Ocean height bounds or flow remains held')
|
|
if any(block[9 + v * 8:12 + v * 8] != bytes(3) for v in range(81)):
|
|
raise ValueError('Unrepresented Source Ocean vertex-union operands remain held')
|
|
heights = [struct.unpack_from('<f', block, 12 + v * 8)[0] for v in range(81)]
|
|
bitmap = 0
|
|
fishable = 0
|
|
deep = 0
|
|
for cell, flag in enumerate(block[656:720]):
|
|
if flag & 0x0f == 0x0f:
|
|
continue
|
|
# Explicit Source boolean roles, not an arbitrary numeric flag copy.
|
|
if flag not in (0x01, 0x41, 0x81, 0xc1):
|
|
raise ValueError('Source Ocean fishability/dark-water attributes do not match this profile')
|
|
y, x = divmod(cell, 8)
|
|
vertices = (y * 9 + x, y * 9 + x + 1, (y + 1) * 9 + x, (y + 1) * 9 + x + 1)
|
|
if any(not math.isfinite(heights[v]) or abs(heights[v]) >= 1e9 for v in vertices):
|
|
continue
|
|
if any(heights[v] != 0. for v in vertices):
|
|
raise ValueError('Nonflat Source Ocean vertices cannot use native depth-only mode')
|
|
bitmap |= 1 << cell
|
|
if flag & 0x40:
|
|
fishable |= 1 << cell
|
|
if flag & 0x80:
|
|
deep |= 1 << cell
|
|
if not bitmap:
|
|
raise ValueError('Source Ocean without drawn cells requires separate absence proof')
|
|
if exact_zero_flt_min and (not all(math.isfinite(v) for v in bounds)
|
|
or not bounds[0] <= 0. <= bounds[1]):
|
|
raise ValueError('Exact Source bounds must enclose the proved used zero surface')
|
|
return bitmap, fishable, deep, bytes(block[8 + v * 8] for v in range(81)), block[:8]
|
|
|
|
|
|
def adt_root_flat_ocean_candidate(root, *, source_legacy_authoritative=False,
|
|
allow_zero_surface_flt_min_bounds=False):
|
|
"""Private sea-level Ocean-only MCLQ -> measured70334 Ocean MH2O profile.
|
|
|
|
Source ADT class1 is the ocean_h queue, independent of header liquid bits.
|
|
Its depth is byte/255. The original native Ocean2/legacy42 profile uses
|
|
depth-only vertices, height0 and Fishable=exists. The independent Deep
|
|
bitfield role is retained without borrowing the PBR control's material.
|
|
Flow, arbitrary
|
|
classes/heights, existing MH2O and nonzero vertex-union operands are held.
|
|
Source0x40 and0x80 project to independent native Fishable/Deep bitmaps,
|
|
supported by original wet true/false controls, never a material alias.
|
|
Unknown bit categories are refused, never erased. The explicit private
|
|
Source5014 policy may replace an existing MH2O using only its certified
|
|
reachable legacy surface; it never claims preservation of that MH2O.
|
|
A separate explicit policy admits only raw min0/maxIEEE-FLT_MIN bounds
|
|
enclosing an all-used-height0 surface. Its original bound bytes survive;
|
|
the original native runtime bounds consumer remains unverified.
|
|
"""
|
|
import math
|
|
if type(source_legacy_authoritative) is not bool:
|
|
raise ValueError('Explicit Source legacy authority policy required')
|
|
if type(allow_zero_surface_flt_min_bounds) is not bool:
|
|
raise ValueError('Explicit exact FLT_MIN Ocean bound policy required')
|
|
if not isinstance(root, bytes) or not 12 <= len(root) <= 64 * 1024 * 1024:
|
|
raise ValueError('Bounded private ROOT required for flat Ocean')
|
|
top = _adt_split_records(root)
|
|
old_liquids = [data for tag, data, tail in top if tag == 'MH2O']
|
|
if old_liquids and not source_legacy_authoritative:
|
|
raise ValueError('Existing MH2O cannot be replaced by flat Ocean')
|
|
if source_legacy_authoritative:
|
|
if (len(old_liquids) != 1 or len(old_liquids[0]) < 3072
|
|
or len(top) < 259 or top[0][:2] != ('MVER', struct.pack('<I', 18))
|
|
or top[1][0] != 'MHDR' or len(top[1][1]) != 64):
|
|
raise ValueError('Source legacy authority requires one existing bounded MH2O in split ROOT')
|
|
cursor = 0
|
|
original_offsets = {}
|
|
for tag, data, tail in top:
|
|
if tag in ('MFBO', 'MH2O', 'MTXF'):
|
|
if tag in original_offsets or tail:
|
|
raise ValueError('Duplicate or unreviewed replaced ROOT role')
|
|
original_offsets[tag] = cursor - 20
|
|
cursor += 8 + len(data) + len(tail)
|
|
for word, tag in ((9, 'MFBO'), (10, 'MH2O'), (11, 'MTXF')):
|
|
if struct.unpack_from('<I', top[1][1], word * 4)[0] != original_offsets.get(tag, 0):
|
|
raise ValueError('Replaced Source MH2O/top-role header binding differs')
|
|
prepared = []
|
|
oceans = {}
|
|
unreachable_records = 0
|
|
for tag, data, tail in top:
|
|
if tag != 'MCNK':
|
|
if source_legacy_authoritative and tag == 'MH2O':
|
|
continue
|
|
prepared.append((tag, data, tail))
|
|
continue
|
|
if len(data) < 128:
|
|
raise ValueError('Complete MCNK required for flat Ocean')
|
|
words = struct.unpack_from('<32I', data)
|
|
children = _adt_split_records(data[128:], maximum=128)
|
|
count = (words[0] & 0x3c).bit_count()
|
|
liquids = [payload for child, payload, child_tail in children if child == 'MCLQ']
|
|
if not count and (any(liquids) or words[25] not in (0, 8)):
|
|
raise ValueError('Unrepresented inactive Source MCLQ contents remain held')
|
|
if count:
|
|
if (count != 1 or len(liquids) != 1
|
|
or (len(liquids[0]) != 804 or words[25] != 812)
|
|
and not (source_legacy_authoritative and len(liquids[0]) >= 804
|
|
and len(liquids[0]) % 804 == 0
|
|
and words[25] == 8 + len(liquids[0]))):
|
|
raise ValueError('Flat Ocean requires exactly one parent-proved804B Source block')
|
|
# Pinned Source5014 6AF970 binds the first payload through ofsLiquid;
|
|
# 6AF760 consumes one804B record per selected header bit. Extra
|
|
# physical records are not an alternative input to this policy.
|
|
surface = _adt_flat_ocean_source_surface(liquids[0][:804],
|
|
allow_zero_surface_flt_min_bounds=allow_zero_surface_flt_min_bounds)
|
|
unreachable_records += len(liquids[0]) // 804 - 1
|
|
xy = words[1:3]
|
|
if xy in oceans or any(v >= 16 for v in xy):
|
|
raise ValueError('Unique complete MCNK coordinates required')
|
|
oceans[xy] = surface
|
|
header = bytearray(data[:128])
|
|
struct.pack_into('<I', header, 0, words[0] & ~0x3c)
|
|
struct.pack_into('<I', header, 25 * 4, 8 if liquids else words[25])
|
|
# Reuse the existing dry ROOT relocation/validation on an intermediate
|
|
# with empty obsolete MCLQ. This intermediate is never returned.
|
|
prepared.append((tag, bytes(header) + b''.join(
|
|
_adt_split_chunk(child, b'' if child == 'MCLQ' else payload) + child_tail
|
|
for child, payload, child_tail in children), tail))
|
|
if not oceans:
|
|
raise ValueError('Flat Ocean requires at least one proved Source surface')
|
|
if source_legacy_authoritative:
|
|
# Reuse the dry normalizer after removing the explicitly superseded
|
|
# representation. Relocate only the existing known top-level roles.
|
|
offsets = {}
|
|
cursor = 0
|
|
for tag, data, tail in prepared:
|
|
if tag in ('MFBO', 'MTXF'):
|
|
if tag in offsets:
|
|
raise ValueError('Duplicate Source ROOT top-level role')
|
|
offsets[tag] = cursor - 20
|
|
cursor += 8 + len(data) + len(tail)
|
|
header = bytearray(prepared[1][1])
|
|
struct.pack_into('<I', header, 40, 0)
|
|
for word, tag in ((9, 'MFBO'), (11, 'MTXF')):
|
|
struct.pack_into('<I', header, word * 4, offsets.get(tag, 0))
|
|
prepared[1] = ('MHDR', bytes(header), prepared[1][2])
|
|
normalized, absence = adt_root_dry_liquid_candidate(b''.join(
|
|
_adt_split_chunk(tag, data) + tail for tag, data, tail in prepared))
|
|
mh2o = bytearray(256 * 12)
|
|
|
|
def align8():
|
|
mh2o.extend(bytes((-len(mh2o)) % 8))
|
|
|
|
for (x, y), (bitmap, fishable, deep, depths, bounds) in sorted(oceans.items(), key=lambda r: (r[0][1], r[0][0])):
|
|
align8()
|
|
instance = len(mh2o)
|
|
mh2o.extend(bytes(24))
|
|
attributes = len(mh2o)
|
|
mh2o.extend(struct.pack('<QQ', fishable, deep))
|
|
exists = len(mh2o)
|
|
mh2o.extend(struct.pack('<Q', bitmap))
|
|
vertices = len(mh2o)
|
|
mh2o.extend(depths)
|
|
struct.pack_into('<3I', mh2o, (y * 16 + x) * 12, instance, 1, attributes)
|
|
mh2o[instance:instance + 24] = (struct.pack('<HH', 2, 42) + bounds
|
|
+ struct.pack('<4BII', 0, 0, 8, 8, exists, vertices))
|
|
output = b''.join(_adt_split_chunk(tag, bytes(mh2o) if tag == 'MH2O' else data) + tail
|
|
for tag, data, tail in _adt_split_records(normalized))
|
|
audit = dict(kind='private-70334-flat-Ocean-depth-candidate', cells=256,
|
|
Ocean_cells=len(oceans), LiquidType=2, LVF_field=42,
|
|
Source_depth_bytes_preserved=len(oceans) * 81,
|
|
Source_union_high3_and_flow_zero=True, Fishable='Source0x40 wet-cell bitmap', Deep='Source0x80 wet-cell bitmap',
|
|
Source_flag_mask_removed=0x3c, Source_0x40_0x80_attributes_copied=False,
|
|
absence_relocation=absence, publishable=False,
|
|
Source_raw_bounds_bytes_preserved=True,
|
|
exact_zero_surface_FLT_MIN_bounds_policy=allow_zero_surface_flt_min_bounds,
|
|
Source_exact_FLT_MIN_bound_cells=sum(
|
|
value[4] == struct.pack('<2I', 0, 0x00800000) for value in oceans.values()),
|
|
original_native_runtime_bounds_consumer_verified=False,
|
|
held=['Native material/asset/fork/gameplay/terrain integration and runtime acceptance remain separate'])
|
|
if source_legacy_authoritative:
|
|
audit.update(authority_policy='source5014-reachable-legacy-Ocean-v1',
|
|
Source_original_consumer='6AF970 pointer binding / 6AF760 four-mask loop',
|
|
Source_unreachable_physical_records_ignored=unreachable_records,
|
|
existing_MH2O_replaced=True, existing_MH2O_bytes=len(old_liquids[0]),
|
|
existing_MH2O_preservation_claim=False,
|
|
Source_fork_loader_equivalence_verified=False)
|
|
return output, audit
|
|
|
|
|
|
def _adt_source_water_render_class(flag):
|
|
"""Pinned5014 Still/Ocean index builders accept exact nibble4/1 only."""
|
|
if type(flag) is not int or not 0 <= flag <= 255 or flag & 0x3f not in (4, 1):
|
|
raise ValueError('Unproved Source water raw render nibble or flags')
|
|
return 0 if flag & 15 == 4 else 1
|
|
|
|
|
|
def adt_root_still_river_candidate(root, *, source_legacy_authoritative=False,
|
|
native_magma_presentation=False,
|
|
source_count0_tail_authoritative=False,
|
|
normalize_unused_magma_height_sentinels=False,
|
|
normalize_unused_still_height_sentinels=False):
|
|
"""Project bounded Source Still/Ocean surfaces into the typed HeightDepth profile.
|
|
|
|
Source5014 6AF760 selects consecutive804B records by MCNK mask count;
|
|
68D540 reads absolute heights and68D790 reads the Still depth byte.
|
|
Its original index builders select raw nibble4 for Still and1 for Ocean;
|
|
the low2 class alone cannot admit authored0/8/12 cells as drawn water.
|
|
Original70334 LiquidType1/Material1 names the same lake_a family and
|
|
Material1 selects HeightDepth0. Direct LVF0 encodes81 floats then81 bytes.
|
|
This preserves authored operands, not cross-client shading equivalence.
|
|
The default refuses flow and nonzero unused flow records. The private template
|
|
passed to the existing Ocean normalizer proves relocation only, never
|
|
Source liquid absence or Source Ocean identity.
|
|
The explicit magma presentation opt-in adds exact nibble6 and the observed
|
|
Slow Magma7/HeightTextureCoord1 profile; water defaults remain strict.
|
|
The separate count0-tail authority also applies to Still: the pinned
|
|
loader, Still render paths and status query leave unselected slots unread.
|
|
Unused-height presentation remains bounded by its paired liquid controls.
|
|
"""
|
|
import math
|
|
if type(source_legacy_authoritative) is not bool:
|
|
raise ValueError('Explicit Source legacy authority policy required')
|
|
if type(native_magma_presentation) is not bool:
|
|
raise ValueError('Explicit native magma presentation policy required')
|
|
if type(source_count0_tail_authoritative) is not bool:
|
|
raise ValueError('Explicit count0 tail authority policy required')
|
|
if (type(normalize_unused_magma_height_sentinels) is not bool
|
|
or normalize_unused_magma_height_sentinels and not native_magma_presentation):
|
|
raise ValueError('Unused magma sentinel normalization requires its native profile')
|
|
if (type(normalize_unused_still_height_sentinels) is not bool
|
|
or normalize_unused_still_height_sentinels and not (
|
|
source_count0_tail_authoritative)):
|
|
raise ValueError('Unused Still sentinel normalization requires explicit count0 authority')
|
|
if not isinstance(root, bytes) or not 12 <= len(root) <= 64 * 1024 * 1024:
|
|
raise ValueError('Bounded private ROOT required for Still/River')
|
|
top = _adt_split_records(root)
|
|
template = []
|
|
surfaces = {}
|
|
ignored = 0
|
|
normalized_magma_vertices = 0
|
|
normalized_still_vertices = 0
|
|
for tag, data, tail in top:
|
|
if tag != 'MCNK':
|
|
template.append((tag, data, tail))
|
|
continue
|
|
if len(data) < 128 or tail:
|
|
raise ValueError('Complete split ROOT cell required for Still/River')
|
|
words = struct.unpack_from('<32I', data)
|
|
xy = words[1:3]
|
|
if any(v >= 16 for v in xy) or xy in surfaces:
|
|
raise ValueError('Unique bounded Still/River coordinates required')
|
|
children = _adt_split_records(data[128:], maximum=128)
|
|
blocks = [p for t, p, z in children if t == 'MCLQ']
|
|
count = (words[0] & 0x3c).bit_count()
|
|
if not count:
|
|
if any(blocks) or words[25] not in (0, 8):
|
|
raise ValueError('Inactive nonempty Source liquid remains held')
|
|
template.append((tag, data, tail))
|
|
continue
|
|
if (len(blocks) != 1 or len(blocks[0]) % 804
|
|
or len(blocks[0]) < count * 804
|
|
or words[25] != 8 + len(blocks[0])):
|
|
raise ValueError('Parent-proved Source layer extent required')
|
|
if len(blocks[0]) != count * 804 and not source_legacy_authoritative:
|
|
raise ValueError('Explicit authority required for unreachable liquid records')
|
|
cell_surfaces = []
|
|
for layer in range(count):
|
|
block = blocks[0][layer * 804:(layer + 1) * 804]
|
|
bounds = struct.unpack_from('<2f', block)
|
|
if (not all(math.isfinite(v) for v in bounds) or bounds[0] > bounds[1]
|
|
or struct.unpack_from('<I', block, 720)[0]
|
|
or any(block[724:804]) and not source_count0_tail_authoritative):
|
|
raise ValueError('Unproved Still/River bounds or flow records')
|
|
heights = [struct.unpack_from('<f', block, 12 + v * 8)[0] for v in range(81)]
|
|
wet = fish = deep = 0
|
|
classes = set()
|
|
used = set()
|
|
for index, flag in enumerate(block[656:720]):
|
|
if flag & 15 == 15:
|
|
continue
|
|
if native_magma_presentation and flag & 0x3f == 6:
|
|
classes.add(2)
|
|
else:
|
|
classes.add(_adt_source_water_render_class(flag))
|
|
wet |= 1 << index
|
|
if flag & 0x40:
|
|
fish |= 1 << index
|
|
if flag & 0x80:
|
|
deep |= 1 << index
|
|
y, x = divmod(index, 8)
|
|
used.update((y * 9 + x, y * 9 + x + 1,
|
|
(y + 1) * 9 + x, (y + 1) * 9 + x + 1))
|
|
if len(classes) != 1 or not wet:
|
|
raise ValueError('One nonempty render class per Source liquid layer required')
|
|
kind = next(iter(classes))
|
|
if (source_count0_tail_authoritative and not native_magma_presentation
|
|
and kind != 0 and any(block[724:804])):
|
|
raise ValueError('Count0 tail authority is qualified for Still water only')
|
|
height_bytes = bytearray(b''.join(
|
|
block[12 + v * 8:16 + v * 8] for v in range(81)))
|
|
for v, height in enumerate(heights):
|
|
if math.isfinite(height) and abs(height) < 1e9:
|
|
continue
|
|
if (((kind == 2 and normalize_unused_magma_height_sentinels)
|
|
or (kind == 0 and normalize_unused_still_height_sentinels))
|
|
and v not in used
|
|
and height_bytes[v * 4:v * 4 + 4] == b'\xff\xff\x7f\x7f'):
|
|
# Original778417 LVF1 and original40_29 LVF0 controls
|
|
# both contain +0 heights outside their wet corners.
|
|
height_bytes[v * 4:v * 4 + 4] = bytes(4)
|
|
if kind == 2:
|
|
normalized_magma_vertices += 1
|
|
else:
|
|
normalized_still_vertices += 1
|
|
else:
|
|
raise ValueError('Nonfinite or sentinel water vertices remain held')
|
|
if any(not bounds[0] <= heights[v] <= bounds[1] for v in used):
|
|
raise ValueError('Source bounds do not enclose used water heights')
|
|
if kind != 2 and any(block[9 + v * 8:12 + v * 8] != bytes(3)
|
|
for v in range(81)):
|
|
raise ValueError('Unrepresented water vertex-union bytes')
|
|
cell_surfaces.append(dict(LiquidType=7 if kind == 2 else 1 if kind == 0 else 2,
|
|
LVF=1 if kind == 2 else 0,
|
|
wet=wet, fish=fish, deep=deep, bounds=block[:8],
|
|
heights=bytes(height_bytes),
|
|
vertex_tail=(b''.join(block[8 + v * 8:12 + v * 8] for v in range(81))
|
|
if kind == 2 else bytes(block[8 + v * 8] for v in range(81)))))
|
|
# MH2O attributes are per MCNK, not per instance. Do not OR away
|
|
# conflicting authored per-layer Fishable/Deep relationships.
|
|
if len({(s['fish'], s['deep']) for s in cell_surfaces}) != 1:
|
|
raise ValueError('Per-layer water attributes cannot share one native cell profile')
|
|
surfaces[xy] = cell_surfaces
|
|
ignored += len(blocks[0]) // 804 - count
|
|
dummy = bytearray(804)
|
|
dummy[656:720] = bytes([0x41]) * 64
|
|
h = bytearray(data[:128])
|
|
struct.pack_into('<I', h, 0, (words[0] & ~0x3c) | 4)
|
|
struct.pack_into('<I', h, 100, 812)
|
|
template.append((tag, bytes(h) + b''.join(
|
|
_adt_split_chunk(t, bytes(dummy) if t == 'MCLQ' else p) + z
|
|
for t, p, z in children), tail))
|
|
if not surfaces:
|
|
raise ValueError('At least one Still/River surface required')
|
|
if native_magma_presentation and not any(
|
|
s['LVF'] == 1 for layers in surfaces.values() for s in layers):
|
|
raise ValueError('At least one exact-nibble6 magma surface required')
|
|
liquid_types = {s['LiquidType'] for layers in surfaces.values() for s in layers}
|
|
if normalize_unused_still_height_sentinels:
|
|
qualified_types = (liquid_types == {1, 7} if native_magma_presentation else
|
|
1 in liquid_types and liquid_types <= {1, 2})
|
|
if not qualified_types:
|
|
raise ValueError('Exact Still/Magma mixture required for the unused Still height profile'
|
|
if native_magma_presentation else
|
|
'Still/Ocean water with a Still surface required for its unused height profile')
|
|
relocated, template_audit = adt_root_flat_ocean_candidate(
|
|
b''.join(_adt_split_chunk(t, p) + z for t, p, z in template),
|
|
source_legacy_authoritative=(source_legacy_authoritative
|
|
and any(t == 'MH2O' for t, p, z in template)))
|
|
liquid = bytearray(256 * 12)
|
|
for (x, y), layers in sorted(surfaces.items(), key=lambda r: (r[0][1], r[0][0])):
|
|
liquid.extend(bytes((-len(liquid)) % 8))
|
|
first = len(liquid)
|
|
liquid.extend(bytes(24 * len(layers)))
|
|
attributes = len(liquid)
|
|
liquid.extend(struct.pack('<QQ', layers[0]['fish'], layers[0]['deep']))
|
|
for n, surface in enumerate(layers):
|
|
exists = len(liquid)
|
|
liquid.extend(struct.pack('<Q', surface['wet']))
|
|
vertex = len(liquid)
|
|
liquid.extend(surface['heights'] + surface['vertex_tail'])
|
|
at = first + n * 24
|
|
liquid[at:at + 24] = (struct.pack('<HH', surface['LiquidType'], surface['LVF'])
|
|
+ surface['bounds'] + struct.pack('<4BII', 0, 0, 8, 8, exists, vertex))
|
|
struct.pack_into('<3I', liquid, (y * 16 + x) * 12, first, len(layers), attributes)
|
|
output = b''.join(_adt_split_chunk(t, bytes(liquid) if t == 'MH2O' else p) + z
|
|
for t, p, z in _adt_split_records(relocated))
|
|
audit = dict(kind='private-Source-Still-Ocean-native-HeightDepth-profile',
|
|
authority_policy='source5014-exact-nibble-Still-Ocean-height-depth-zero-flow-v2',
|
|
cells=256, active_cells=len(surfaces),
|
|
instances=sum(map(len, surfaces.values())),
|
|
Still_instances=sum(s['LiquidType'] == 1 for a in surfaces.values() for s in a),
|
|
Ocean_instances=sum(s['LiquidType'] == 2 for a in surfaces.values() for s in a),
|
|
Source_absolute_height_bytes_preserved=True, Source_depth_bytes_preserved=True,
|
|
Source_raw_bounds_bytes_preserved=True, Source_drawn_Fishable_Deep_preserved=True,
|
|
Source_unreachable_physical_records_ignored=ignored,
|
|
existing_MH2O_replaced=any(t == 'MH2O' for t, p, z in top),
|
|
relocation_only_template_audit=template_audit,
|
|
native_depth_shading_equivalence_verified=False,
|
|
original_native_runtime_HeightDepth_consumer_verified=False,
|
|
publishable=False, installed=False, engine_verified=False)
|
|
if native_magma_presentation:
|
|
audit.update(kind='private-Source-liquid-native-magma-presentation-profile',
|
|
authority_policy='source5014-exact-nibble6-native-Slow-Magma7-LVF1-zero-flow-v1',
|
|
Magma_instances=sum(s['LVF'] == 1 for a in surfaces.values() for s in a),
|
|
Source_magma_u16_UV_bytes_preserved=True,
|
|
native_profile_control_file_data_id=778417,
|
|
native_profile_LiquidType=7, native_profile_LiquidMaterial=2,
|
|
native_profile_LiquidVertexFormat=1,
|
|
Source_depth_bytes_preserved='water_instances_only',
|
|
native_magma_shading_and_flow_equivalence_verified=False)
|
|
if normalize_unused_magma_height_sentinels:
|
|
audit.update(
|
|
Source_absolute_height_bytes_preserved=not (
|
|
normalized_magma_vertices or normalized_still_vertices),
|
|
Source_used_height_bytes_preserved=True,
|
|
native_unused_magma_height_policy='original778417-unused-FLT_MAX-to-positive-zero-v1',
|
|
normalized_unused_magma_vertices=normalized_magma_vertices,
|
|
Source_nonfinite_or_used_sentinel_height_admitted=False)
|
|
if normalize_unused_still_height_sentinels:
|
|
audit.update(
|
|
Source_absolute_height_bytes_preserved=not (
|
|
normalized_magma_vertices or normalized_still_vertices),
|
|
Source_used_height_bytes_preserved=True,
|
|
Source_water_depth_bytes_preserved=True,
|
|
native_unused_still_height_policy='original40_29-LVF0-unused-FLT_MAX-to-positive-zero-v1',
|
|
normalized_unused_still_vertices=normalized_still_vertices,
|
|
mixed_Still_Magma_only=True,
|
|
Source_nonfinite_or_used_sentinel_height_admitted=False)
|
|
elif normalize_unused_still_height_sentinels:
|
|
audit.update(
|
|
Source_absolute_height_bytes_preserved=not normalized_still_vertices,
|
|
Source_used_height_bytes_preserved=True,
|
|
Source_water_depth_bytes_preserved=True,
|
|
native_unused_still_height_policy='original40_29-LVF0-unused-FLT_MAX-to-positive-zero-v1',
|
|
normalized_unused_still_vertices=normalized_still_vertices,
|
|
Still_only=liquid_types == {1},
|
|
Still_Ocean_only=True,
|
|
Source_nonfinite_or_used_sentinel_height_admitted=False)
|
|
if source_count0_tail_authoritative:
|
|
audit.update(
|
|
authority_policy=(
|
|
'source5014-exact-nibble6-native-Slow-Magma7-LVF1-literal-count0-v2'
|
|
if native_magma_presentation else
|
|
'source5014-exact-nibble-Still-Ocean-height-depth-Still-count0-v4'
|
|
if 2 in liquid_types else
|
|
'source5014-exact-nibble-Still-height-depth-literal-count0-v3'),
|
|
Source_literal_flow_count_zero_required=True,
|
|
Source_physical_count0_tail_ignored=True,
|
|
Source_count0_query_zero_flow_vector_verified=True,
|
|
Source_count0_query_consumer='69B6D0 count69B84A zero-arm69B9F3',
|
|
Source_nonzero_flow_count_admitted=False)
|
|
return output, audit
|
|
|
|
|
|
def adt_root_magma_candidate(root, *, source_legacy_authoritative=False,
|
|
source_count0_tail_authoritative=False,
|
|
normalize_unused_magma_height_sentinels=False,
|
|
normalize_unused_still_height_sentinels=False):
|
|
"""Use observed original778417 Slow Magma/HeightTextureCoord presentation.
|
|
|
|
Source5014 68DCA0 selects exact nibble6 via68D9B0;68D890 reads the
|
|
union as two unsigned16 coordinates, each multiplied by3/256. Original
|
|
778417 stores the same authored UV pairs after its float height array,
|
|
with LiquidType7/Material2/LVF1. This explicit profile preserves those
|
|
operands and zero-flow guards, not cross-client shading equivalence.
|
|
The separate count0 opt-in consumes the pinned69B6D0 query proof: literal
|
|
zero writes a zero flow vector without reading the physical80-byte tail.
|
|
Counts1/2 and all other nonzero counts remain refused.
|
|
A separate original778417 presentation opt-in normalizes exact FLT_MAX
|
|
only outside every wet cell's four corners; all used heights stay exact.
|
|
The count0 mixed Still/Magma-only opt-in also uses original40_29's same
|
|
HeightDepth0 inactive-height role for Still; water defaults stay strict.
|
|
"""
|
|
return adt_root_still_river_candidate(root,
|
|
source_legacy_authoritative=source_legacy_authoritative,
|
|
native_magma_presentation=True,
|
|
source_count0_tail_authoritative=source_count0_tail_authoritative,
|
|
normalize_unused_magma_height_sentinels=normalize_unused_magma_height_sentinels,
|
|
normalize_unused_still_height_sentinels=normalize_unused_still_height_sentinels)
|
|
|
|
|
|
def _adt_mh2o_matches_source_ocean(liquid, cell_index, surface):
|
|
"""Compare used operands to Source, not numeric namespace/name equality."""
|
|
bitmap, source_fishable, deep, depths, bounds = surface
|
|
offset, count, attributes = struct.unpack_from('<3I', liquid, cell_index * 12)
|
|
if count != 1 or offset < 3072 or offset + 24 > len(liquid):
|
|
raise ValueError('Equivalent Ocean requires one bounded MH2O instance per Source surface')
|
|
typ, fmt, lo, hi, ox, oy, width, height, bits, vertices = struct.unpack_from('<HHffBBBBII', liquid, offset)
|
|
if (typ != 2 or fmt not in (0, 2) or lo != 0. or hi != 0.
|
|
or not 1 <= width <= 8 or not 1 <= height <= 8
|
|
or ox + width > 8 or oy + height > 8 or not vertices):
|
|
raise ValueError('MH2O is not the corresponding proved flat Ocean vertex profile')
|
|
if attributes:
|
|
if attributes < 3072 or attributes + 16 > len(liquid):
|
|
raise ValueError('MH2O attribute extent is unproved')
|
|
fishable, native_deep = struct.unpack_from('<QQ', liquid, attributes)
|
|
else:
|
|
fishable = native_deep = (1 << 64) - 1
|
|
if fishable & bitmap != source_fishable or native_deep & bitmap != deep:
|
|
raise ValueError('Source/MH2O fishability or dark-water operands differ')
|
|
bitmap_bytes = (width * height + 7) // 8
|
|
if bits:
|
|
if bits < 3072 or bits + bitmap_bytes > len(liquid):
|
|
raise ValueError('MH2O compact existence bitmap extent is unproved')
|
|
local = int.from_bytes(liquid[bits:bits + bitmap_bytes], 'little')
|
|
else:
|
|
local = (1 << (width * height)) - 1
|
|
native_bitmap = 0
|
|
used = {}
|
|
for y in range(height):
|
|
for x in range(width):
|
|
if not local >> (y * width + x) & 1:
|
|
continue
|
|
native_bitmap |= 1 << ((oy + y) * 8 + ox + x)
|
|
for vy, vx in ((y, x), (y, x + 1), (y + 1, x), (y + 1, x + 1)):
|
|
used[(oy + vy) * 9 + ox + vx] = vy * (width + 1) + vx
|
|
if native_bitmap != bitmap:
|
|
raise ValueError('Source/MH2O drawn surface masks differ')
|
|
vertex_count = (width + 1) * (height + 1)
|
|
depth_start = vertices + vertex_count * 4 if fmt == 0 else vertices
|
|
if vertices < 3072 or depth_start + vertex_count > len(liquid):
|
|
raise ValueError('MH2O vertex extent is unproved')
|
|
for source_vertex, native_vertex in used.items():
|
|
native_height = struct.unpack_from('<f', liquid, vertices + native_vertex * 4)[0] if fmt == 0 else 0.
|
|
if native_height != 0. or liquid[depth_start + native_vertex] != depths[source_vertex]:
|
|
raise ValueError('Source/MH2O used height or depth operands differ')
|
|
return dict(format=fmt, wet_cells=bitmap.bit_count(), used_vertices=len(used))
|
|
|
|
|
|
def adt_root_equivalent_ocean_candidate(root):
|
|
"""Keep an exact existing MH2O only after complete Source Ocean equivalence."""
|
|
if not isinstance(root, bytes) or not 12 <= len(root) <= 64 * 1024 * 1024:
|
|
raise ValueError('Bounded private split ROOT required for equivalent Ocean')
|
|
top = _adt_split_records(root)
|
|
if (len(top) < 259 or top[0][:2] != ('MVER', struct.pack('<I', 18))
|
|
or top[1][0] != 'MHDR' or len(top[1][1]) != 64):
|
|
raise ValueError('Equivalent Ocean requires the established split ROOT layout')
|
|
forbidden = {'MCIN', 'MTEX', 'MMDX', 'MMID', 'MWMO', 'MWID', 'MDDF', 'MODF'}
|
|
if any(t in forbidden or t in ('MVER', 'MHDR') for t, d, x in top[2:]):
|
|
raise ValueError('Unsplit or duplicate roles cannot be declared equivalent Ocean')
|
|
matches = [d for t, d, x in top if t == 'MH2O']
|
|
if len(matches) != 1 or len(matches[0]) < 3072:
|
|
raise ValueError('Exactly one complete existing MH2O required')
|
|
liquid = matches[0]
|
|
cursor = 0
|
|
for tag, data, tail in top:
|
|
if tag == 'MH2O' and struct.unpack_from('<I', top[1][1], 40)[0] != cursor - 20:
|
|
raise ValueError('Existing MHDR/MH2O binding is not exact')
|
|
cursor += 8 + len(data) + len(tail)
|
|
output = []
|
|
cells = set()
|
|
proof = []
|
|
for tag, data, tail in top:
|
|
if tag != 'MCNK':
|
|
if cells:
|
|
raise ValueError('Equivalent Ocean extras must precede all cells')
|
|
output.append(_adt_split_chunk(tag, data) + tail)
|
|
continue
|
|
if len(data) < 128:
|
|
raise ValueError('Equivalent Ocean requires complete MCNK headers')
|
|
words = struct.unpack_from('<32I', data)
|
|
xy = words[1:3]
|
|
if xy in cells or any(v >= 16 for v in xy) or not words[0] & 0x10000:
|
|
raise ValueError('Equivalent Ocean requires unique split ROOT cell coordinates')
|
|
cells.add(xy)
|
|
children = _adt_split_records(data[128:], maximum=128)
|
|
names = [t for t, d, x in children]
|
|
if len(names) != len(set(names)):
|
|
raise ValueError('Duplicate MCNK child cannot prove equivalent Ocean')
|
|
legacy = [d + x for t, d, x in children if t == 'MCLQ']
|
|
index = xy[1] * 16 + xy[0]
|
|
count = (words[0] & 0x3c).bit_count()
|
|
if count:
|
|
if count != 1 or len(legacy) != 1 or words[25] != 812:
|
|
raise ValueError('Source multilayer/physical Ocean role remains held')
|
|
surface = _adt_flat_ocean_source_surface(legacy[0])
|
|
proof.append(_adt_mh2o_matches_source_ocean(liquid, index, surface))
|
|
else:
|
|
if any(legacy) or words[25] not in (0, 8) or struct.unpack_from('<3I', liquid, index * 12) != (0, 0, 0):
|
|
raise ValueError('Source/MH2O inactive cell roles differ')
|
|
header = bytearray(data[:128])
|
|
struct.pack_into('<I', header, 0, words[0] & ~0x3c)
|
|
retained = [r for r in children if r[0] != 'MCLQ']
|
|
output.append(_adt_split_chunk('MCNK', _adt_root_retained_liquid_children(header, retained)))
|
|
if len(cells) != 256 or not proof:
|
|
raise ValueError('Equivalent Ocean requires all256 cells and a matched active surface')
|
|
return b''.join(output), dict(kind='private-equivalent-Source-MH2O-Ocean-preservation', cells=256,
|
|
active_cells=len(proof), LiquidType=2, formats=sorted({r['format'] for r in proof}),
|
|
entire_existing_MH2O_byte_exact=True, Source_surface_depth_wet_fishability_Deep_equal=True,
|
|
removed_only_redundant_MCLQ_and_Source_mask=0x3c, publishable=False,
|
|
held=['Remaining terrain/material/resource/fork/runtime activation boundaries are independent'])
|
|
|
|
|
|
def _adt_root_retained_liquid_children(header, children):
|
|
"""Relocate an already-authorized retained child list; no removal authority."""
|
|
if len(header) != 128 or any(tag == 'MCLQ' for tag, payload, tail in children):
|
|
raise ValueError('Retained ROOT children must exclude separately-proved obsolete MCLQ')
|
|
rebuilt = bytearray(header)
|
|
offsets = {}
|
|
for child, payload, tail in children:
|
|
offsets[child] = len(rebuilt) + 8
|
|
rebuilt += _adt_split_chunk(child, payload) + tail
|
|
for word, child in ((22, 'MCSE'), (29, 'MCCV')):
|
|
struct.pack_into('<I', rebuilt, word * 4, offsets.get(child, 0))
|
|
struct.pack_into('<II', rebuilt, 24 * 4, 0, 0)
|
|
return bytes(rebuilt)
|
|
|
|
|
|
def adt_root_dry_liquid_candidate(root):
|
|
"""Normalize proved absence in a private split ROOT, never active liquid.
|
|
|
|
Source bits2..5 create no liquid blocks when zero. Declared MCLQ size0
|
|
alone is insufficient. Native70334 absence is an independent zero-instance
|
|
12B MH2O record; the explicit constructor emits all256 absent records.
|
|
"""
|
|
if not isinstance(root, bytes) or not 12 <= len(root) <= 64 * 1024 * 1024:
|
|
raise ValueError('Bounded private split ROOT required for dry-liquid absence')
|
|
top = _adt_split_records(root)
|
|
if (len(top) < 258 or top[0][:2] != ('MVER', struct.pack('<I', 18))
|
|
or top[1][0] != 'MHDR' or len(top[1][1]) != 64):
|
|
raise ValueError('Dry-liquid absence requires the existing v18 split ROOT layout')
|
|
forbidden = {'MH2O', 'MCIN', 'MTEX', 'MMDX', 'MMID', 'MWMO', 'MWID', 'MDDF', 'MODF'}
|
|
if (any(tag in forbidden for tag, payload, tail in top)
|
|
or any(tag in ('MVER', 'MHDR') for tag, payload, tail in top[2:])
|
|
or struct.unpack_from('<I', top[1][1], 40)[0]):
|
|
raise ValueError('Existing MH2O or unsplit external roles cannot be replaced as dry')
|
|
extras, cells, seen = [], [], set()
|
|
removed = 0
|
|
for tag, data, tail in top[2:]:
|
|
if tag != 'MCNK':
|
|
if cells:
|
|
raise ValueError('Private ROOT extras must precede all terrain cells')
|
|
extras.append((tag, data, tail))
|
|
continue
|
|
if len(data) < 128:
|
|
raise ValueError('Dry ROOT requires complete MCNK headers')
|
|
words = struct.unpack_from('<32I', data)
|
|
xy = words[1:3]
|
|
if (any(v >= 16 for v in xy) or xy in seen or not words[0] & 0x10000
|
|
or words[0] & 0x3c or words[25] not in (0, 8)):
|
|
raise ValueError('Active Source liquid flags or parent extent cannot be declared dry')
|
|
seen.add(xy)
|
|
children = _adt_split_records(data[128:], maximum=128)
|
|
names = [t for t, payload, child_tail in children]
|
|
if len(set(names)) != len(names) or 'MCVT' not in names or 'MCNR' not in names:
|
|
raise ValueError('Dry-liquid absence requires the established split MCNK children')
|
|
retained = []
|
|
for child, payload, child_tail in children:
|
|
if child == 'MCLQ':
|
|
if payload or child_tail:
|
|
raise ValueError('Nonempty MCLQ cannot be removed as liquid absence')
|
|
removed += 1
|
|
continue
|
|
retained.append((child, payload, child_tail))
|
|
cells.append(_adt_split_chunk('MCNK', _adt_root_retained_liquid_children(data[:128], retained)))
|
|
if len(cells) != 256:
|
|
raise ValueError('Dry-liquid absence requires all256 unique ROOT cells')
|
|
header = bytearray(top[1][1])
|
|
encoded_extras = b''.join(_adt_split_chunk(tag, data) + tail for tag, data, tail in extras)
|
|
# Existing extras keep their original positions. MHDR offsets are relative
|
|
# to its payload at absolute20; the new MH2O follows the64B header/extras.
|
|
struct.pack_into('<I', header, 40, 64 + len(encoded_extras))
|
|
result = (_adt_split_chunk('MVER', top[0][1]) + _adt_split_chunk('MHDR', bytes(header))
|
|
+ encoded_extras + _adt_split_chunk('MH2O', bytes(256 * 12)) + b''.join(cells))
|
|
audit = dict(kind='private-70334-dry-liquid-absence-candidate', cells=256,
|
|
Source_liquid_header_mask=0x3c, Source_selected_blocks=0,
|
|
removed_empty_MCLQ_headers=removed, native_MH2O_zero_instance_rows=256,
|
|
native_MH2O_bytes=3072, active_liquid_or_material_authority=False,
|
|
publishable=False,
|
|
held=['Terrain material, flags, assets, neighboring/LOD and runtime rendering remain separately held'])
|
|
return result, audit
|
|
|
|
|
|
def _adt_edge_invariant_alpha8_layers(mcly, mcal, *, source_edge_repair=False,
|
|
source_alpha_presence_only=False,
|
|
native_plain_full64_authoritative=False):
|
|
"""Lossless4bit->8bit for the complete ordinary, edge-invariant category.
|
|
|
|
Source primary decoders agree on low-nibble-first/17 scaling. Invariance
|
|
makes the unresolved native last-row/column repair decision immaterial.
|
|
The default refuses extra flags and edge-changing maps. The separate
|
|
original Source profile authorizes63x63 border replication and unchanged
|
|
low-byte layer operands; compressed/high flags and irregular offsets stay
|
|
refused. Source6AFF80 uses only bit0x100 to register its alpha callback.
|
|
Captured native plain-full64 authority can preserve noninvariant Source
|
|
full64 edges explicitly; the default invariant-only policy is unchanged.
|
|
"""
|
|
if not isinstance(mcly, bytes) or not isinstance(mcal, bytes) or len(mcly)%16:
|
|
raise ValueError('Bounded MCLY/MCAL byte records required')
|
|
if type(source_edge_repair) is not bool:
|
|
raise ValueError('Explicit original Source alpha-edge policy required')
|
|
if type(source_alpha_presence_only) is not bool:
|
|
raise ValueError('Explicit original Source alpha-layer policy required')
|
|
if (type(native_plain_full64_authoritative) is not bool
|
|
or native_plain_full64_authoritative and not source_alpha_presence_only):
|
|
raise ValueError('Native full64 authority requires the original Source layer profile')
|
|
layers = list(struct.iter_unpack('<4I', mcly))
|
|
# Source6AFF80 registers alpha only for bit0x100; captured native
|
|
# CArgb635 tests only0x200 for compression. Under that explicit paired
|
|
# profile, unchanged low-byte base operands do not select alpha decoding.
|
|
# Keep the base offset/effect and all flags exact; empty layer lists and
|
|
# alpha/compression/high-bit base flags remain outside this family.
|
|
base_flag_mask = (0xff if source_alpha_presence_only
|
|
and native_plain_full64_authoritative else 0)
|
|
if (not 1 <= len(layers) <= 4
|
|
or layers[0][1] & ~base_flag_mask or layers[0][2] != 0):
|
|
raise ValueError('Ordinary opaque base alpha layer required')
|
|
if len(mcal) != 2048*(len(layers)-1):
|
|
raise ValueError('Complete ordinary2048-byte alpha intervals required')
|
|
if any(((row[1] & ~0xff) != 0x100 if source_alpha_presence_only else row[1] != 0x100)
|
|
or row[2] != 2048*i for i,row in enumerate(layers[1:])):
|
|
raise ValueError('Unreviewed alpha layer flags/offset relationship')
|
|
low = bytes((v & 15)*17 for v in range(256))
|
|
high = bytes((v >> 4)*17 for v in range(256))
|
|
result = []; layer_bytes = bytearray(mcly)
|
|
for i in range(len(layers)-1):
|
|
data = mcal[i*2048:(i+1)*2048]
|
|
if (not source_edge_repair and not native_plain_full64_authoritative
|
|
and (data[63*32:64*32] != data[62*32:63*32]
|
|
or any((data[y*32+31]&15) != (data[y*32+31]>>4) for y in range(64)))):
|
|
raise ValueError('Alpha boundary repair decision would change Source samples')
|
|
expanded = bytearray(4096)
|
|
expanded[0::2] = data.translate(low); expanded[1::2] = data.translate(high)
|
|
if source_edge_repair:
|
|
# Source5014 6B0A60 selects6B0BF0 when MCNK bit0x8000 is
|
|
# clear: decode63 columns/rows, repeat column62, then row62.
|
|
for y in range(63):
|
|
expanded[y * 64 + 63] = expanded[y * 64 + 62]
|
|
expanded[63 * 64:64 * 64] = expanded[62 * 64:63 * 64]
|
|
result.append(bytes(expanded)); struct.pack_into('<I',layer_bytes,(i+1)*16+8,i*4096)
|
|
return bytes(layer_bytes), b''.join(result), len(layers)-1
|
|
|
|
|
|
def adt_tex0_alpha8_candidate(source, *, source_mcnk_flags=None,
|
|
native_plain_full64_authoritative=False):
|
|
"""Private opt-in ordinary/invariant TEX0 conversion; no WDT-mode admission.
|
|
|
|
Targets the observed original outdoor0x100/uncompressed4096-byte profile.
|
|
MAMP, MDID, MHID, cell order, all layer operands except offsets, and opaque
|
|
cell children remain exact. Other material/scene holds are not cleared.
|
|
Optional original Source MCNK flags use the producer's y-major256-cell
|
|
order. Bit0x8000 clear authorizes the exact original63x63 repair before
|
|
expansion; set keeps the default invariant-edge requirement. The output
|
|
is invariant under either native last-row/column repair choice.
|
|
A separate captured native plain-CArgb full64-copy authority also admits
|
|
Source bit0x8000 set without changing any of its64x64 samples. Compressed
|
|
layers remain outside this profile.
|
|
"""
|
|
if not isinstance(source, bytes) or not 12 <= len(source) <= 67108864:
|
|
raise ValueError('Bounded existing TEX0 candidate required')
|
|
if (type(native_plain_full64_authoritative) is not bool
|
|
or native_plain_full64_authoritative and source_mcnk_flags is None):
|
|
raise ValueError('Native full64 authority requires exact original Source flags')
|
|
if source_mcnk_flags is not None and (
|
|
not isinstance(source_mcnk_flags, tuple) or len(source_mcnk_flags) != 256
|
|
or any(type(v) is not int or not 0 <= v <= 0xffffffff
|
|
for v in source_mcnk_flags)):
|
|
raise ValueError('Exact y-major256 original Source MCNK flag words required')
|
|
records = _adt_split_records(source)
|
|
names = [t for t,p,tail in records]
|
|
if names[:4] != ['MVER','MAMP','MDID','MHID'] or names[4:] != ['MCNK']*256:
|
|
raise ValueError('Reviewed TEX0 header/256-cell family required')
|
|
common = {t:p for t,p,tail in records[:4]}
|
|
if common['MVER'] != struct.pack('<I',18) or common['MAMP'] != bytes(4) or len(common['MDID'])%4 or len(common['MDID']) != len(common['MHID']) or any(common['MHID']):
|
|
raise ValueError('Reviewed TEX0 absent-height-map profile required')
|
|
out = []; maps = 0; cells_with_maps = 0; cell_index = 0; source_repair_cells = 0
|
|
all_edges_invariant = True
|
|
for tag,payload,tail in records:
|
|
if tag != 'MCNK': out.append(_adt_split_chunk(tag,payload)); continue
|
|
children = _adt_split_records(payload, maximum=128); parts = {}
|
|
for name,data,pad in children:
|
|
if name in parts: raise ValueError('Duplicate TEX0 alpha child')
|
|
parts[name] = data
|
|
repair = source_mcnk_flags is not None and not source_mcnk_flags[cell_index] & 0x8000
|
|
layers,alpha,count = _adt_edge_invariant_alpha8_layers(
|
|
parts.get('MCLY',b''),parts.get('MCAL',b''), source_edge_repair=repair,
|
|
source_alpha_presence_only=source_mcnk_flags is not None,
|
|
native_plain_full64_authoritative=native_plain_full64_authoritative)
|
|
if native_plain_full64_authoritative:
|
|
all_edges_invariant = all_edges_invariant and all(
|
|
alpha[at + 63 * 64:at + 64 * 64] == alpha[at + 62 * 64:at + 63 * 64]
|
|
and all(alpha[at + y * 64 + 63] == alpha[at + y * 64 + 62]
|
|
for y in range(64)) for at in range(0, len(alpha), 4096))
|
|
source_repair_cells += repair and count > 0
|
|
cell_index += 1
|
|
maps += count; cells_with_maps += count > 0
|
|
encoded = b''.join(_adt_split_chunk(name,layers if name=='MCLY' else alpha if name=='MCAL' else data) for name,data,pad in children)
|
|
out.append(_adt_split_chunk('MCNK',encoded))
|
|
audit = dict(kind='private-ordinary-edge-invariant-TEX0-alpha8',
|
|
status='ENCODING_CANDIDATE_HELD_UNPUBLISHED',cells=256,alpha_maps=maps,
|
|
cells_with_alpha=cells_with_maps,Source_bits=4,native_bits=8,
|
|
low_nibble_first_times17=True,edge_fix_decision_independent=True,
|
|
only_MCAL_payload_extent_and_MCLY_alpha_offsets_changed=True,
|
|
native_profile='Original70334 outdoor uncompressed4096 under0x100; WDT-mode/application remains separate',
|
|
Source_flags_or_effect_IDs_remapped=False,publishable=False,
|
|
held=['Native WDT/renderer mode and actual scene acceptance','Other Source flags/material/shadow/ground-effect/liquid/LOD/resource holds'])
|
|
if source_mcnk_flags is not None:
|
|
audit.update(Source_alpha_edge_policy='original5014-MCNK8000-clear-63x63-copy-v1',
|
|
Source_alpha_edge_consumer='6AFF80→6B1150→6B02D0→6B0A60→6B0BF0',
|
|
Source_63_edge_profile_applied_cells=source_repair_cells,
|
|
Source_effective_interior_alpha_samples_preserved=True,
|
|
Source_alpha_layer_presence_bit=0x100,
|
|
Source_layer_low_byte_operands_passed_through_unchanged=True,
|
|
compressed_or_unknown_high_layer_flags_admitted=False,
|
|
edge_fix_decision_independent=all_edges_invariant,
|
|
all_output_alpha_edges_invariant=all_edges_invariant,
|
|
native_edge_repair_choice_changes_output=not all_edges_invariant)
|
|
if native_plain_full64_authoritative:
|
|
audit.update(native_alpha_edge_policy='captured70334-plain-CArgb635-full64-copy-v1',
|
|
native_plain_full64_copy_verified=True,
|
|
Source_set_bit8000_effective_full64_samples_preserved=True,
|
|
Native_raw_MCNK8000_flag_projection_assumed=False)
|
|
return b''.join(out), audit
|
|
|
|
|
|
def global_tex_mip_cache_candidate(texture_blps, *, native_tail_policy):
|
|
"""Serialize the observed TXVR1/TXBT/TXMD compressed mip-cache family.
|
|
|
|
This explicit native presentation policy chooses the first mip whose area
|
|
is at most1024 and whose largest dimension is at most64. Only the four
|
|
original-witnessed BLP2 block formats are admitted. The selected complete
|
|
tail is copied byte-for-byte; no source artwork or selector is replaced.
|
|
"""
|
|
if native_tail_policy != 'native-tail-area1024-max64-v1':
|
|
raise ValueError('Explicit reviewed native TEX tail policy required')
|
|
if (not isinstance(texture_blps, dict) or not 1 <= len(texture_blps) <= 4096
|
|
or any(type(ident) is not int or not 0 < ident <= 0xffffffff
|
|
for ident in texture_blps)):
|
|
raise ValueError('Bounded nonempty positive FileDataID-to-BLP map required')
|
|
formats = {(0, 0): (0, 8), (1, 0): (16, 8),
|
|
(8, 1): (129, 16), (8, 7): (130, 16)}
|
|
rows = []; chunks = []; audit = []; cursor = 0
|
|
for ident in sorted(texture_blps):
|
|
raw = texture_blps[ident]
|
|
if (type(ident) is not int or not 0 < ident <= 0xffffffff
|
|
or not isinstance(raw, bytes) or not 148 <= len(raw) <= 64 * 1024 * 1024
|
|
or raw[:4] != b'BLP2'):
|
|
raise ValueError('Positive FileDataID and bounded BLP2 body required')
|
|
typ, = struct.unpack_from('<I', raw, 4)
|
|
encoding, alpha_depth, alpha_encoding, has_mips = struct.unpack_from('<4B', raw, 8)
|
|
width, height = struct.unpack_from('<II', raw, 12)
|
|
if typ != 1 or encoding != 2:
|
|
raise ValueError('Only observed BLP2 type1 block-compressed family admitted')
|
|
if (alpha_depth, alpha_encoding) not in formats:
|
|
raise ValueError('BLP2 alpha/block format lacks original TEX witness')
|
|
if not 1 <= width <= 32768 or not 1 <= height <= 32768:
|
|
raise ValueError('Bounded positive BLP2 dimensions required')
|
|
fmt, block_bytes = formats[alpha_depth, alpha_encoding]
|
|
first = 0
|
|
while ((max(1, width >> first) * max(1, height >> first) > 1024)
|
|
or max(max(1, width >> first), max(1, height >> first)) > 64):
|
|
first += 1
|
|
tw, th = max(1, width >> first), max(1, height >> first)
|
|
nominal = max(tw, th).bit_length()
|
|
if first + nominal > 16:
|
|
raise ValueError('Selected TEX tail exceeds BLP2 sixteen mip slots')
|
|
offsets = struct.unpack_from('<16I', raw, 20)
|
|
lengths = struct.unpack_from('<16I', raw, 84)
|
|
tail = []; expected_offset = None; mip_lengths = []
|
|
for level in range(first, first + nominal):
|
|
w, h = max(1, width >> level), max(1, height >> level)
|
|
expected_length = ((w + 3) // 4) * ((h + 3) // 4) * block_bytes
|
|
at, size = offsets[level], lengths[level]
|
|
if (at < 148 or size != expected_length or at > len(raw) - size
|
|
or expected_offset is not None and at != expected_offset):
|
|
raise ValueError('Complete contiguous in-bounds compressed BLP2 tail required')
|
|
tail.append(raw[at:at + size]); mip_lengths.append(size)
|
|
expected_offset = at + size
|
|
payload = b''.join(tail)
|
|
if cursor + 8 + len(payload) > 64 * 1024 * 1024:
|
|
raise ValueError('Bounded TEX cache output exceeded')
|
|
rows.append(struct.pack('<II4B', ident, cursor, tw, th, nominal, fmt))
|
|
chunks.append(_adt_split_chunk('TXMD', payload))
|
|
audit.append(dict(file_data_id=ident, source_dimensions=[width, height],
|
|
first_mip=first, selected_dimensions=[tw, th],
|
|
nominal_mip_count=nominal, format_byte=fmt,
|
|
mip_lengths=mip_lengths, TXMD_relative_header_offset=cursor,
|
|
compressed_bytes_preserved=True))
|
|
cursor += 8 + len(payload)
|
|
output = (_adt_split_chunk('TXVR', struct.pack('<I', 1))
|
|
+ _adt_split_chunk('TXBT', b''.join(rows)) + b''.join(chunks))
|
|
return output, dict(kind='native-global-TEX-compressed-mip-cache-v1',
|
|
policy=native_tail_policy, records=len(rows), rows=audit,
|
|
ascending_unique_FileDataIDs=True,
|
|
relative_TXMD_chunk_header_offsets=True,
|
|
source_artwork_recompressed=False,
|
|
default_texture_selector_changed=False,
|
|
native_presentation_policy=True,
|
|
Source_cosmetic_equivalence=False,
|
|
runtime_verified=False)
|
|
|
|
|
|
def rebind_global_tex_file_ids(raw, replacements):
|
|
"""Rebind the observed TXVR1/TXBT namespace without rebuilding mip data.
|
|
|
|
TXBT's 12-byte records own FileDataID and relative TXMD-header offsets.
|
|
Keep each record's offset/shape/format and every TXMD chunk unchanged;
|
|
require ascending unique IDs without changing record ordinals. The existing constructor
|
|
and its original mip-cache controls remain the format authority.
|
|
"""
|
|
if (not isinstance(raw, bytes) or not isinstance(replacements, dict)
|
|
or not replacements or any(type(a) is not int or type(b) is not int
|
|
or not 0 < a <= 0xffffffff or not 0 < b <= 0xffffffff or a == b
|
|
for a, b in replacements.items())):
|
|
raise ValueError('Explicit changed global TEX IDs required')
|
|
records = _adt_split_records(raw)
|
|
if (len(records) < 3 or records[0][0] != 'TXVR'
|
|
or records[0][1] != struct.pack('<I', 1) or records[0][2]
|
|
or records[1][0] != 'TXBT' or records[1][2]
|
|
or any(tag != 'TXMD' or tail for tag, payload, tail in records[2:])):
|
|
raise ValueError('Observed TXVR1/TXBT/TXMD layout required')
|
|
table = records[1][1]
|
|
if not table or len(table) % 12:
|
|
raise ValueError('Complete global TEX binding records required')
|
|
rows = [table[i:i + 12] for i in range(0, len(table), 12)]
|
|
old_ids = [struct.unpack_from('<I', row)[0] for row in rows]
|
|
if old_ids != sorted(set(old_ids)) or not all(old_ids):
|
|
raise ValueError('Ascending unique global TEX IDs required')
|
|
if not set(replacements) <= set(old_ids):
|
|
raise ValueError('Unrelated global TEX replacement')
|
|
offsets = set()
|
|
cursor = 0
|
|
for tag, payload, tail in records[2:]:
|
|
offsets.add(cursor)
|
|
cursor += 8 + len(payload)
|
|
if any(struct.unpack_from('<I', row, 4)[0] not in offsets for row in rows):
|
|
raise ValueError('Original global TEX chunk-header offsets required')
|
|
rebound = [(replacements.get(ident, ident), row[4:])
|
|
for ident, row in zip(old_ids, rows)]
|
|
if len({ident for ident, rest in rebound}) != len(rebound):
|
|
raise ValueError('Global TEX replacement ID collision')
|
|
if [ident for ident, rest in rebound] != sorted(ident for ident, rest in rebound):
|
|
raise ValueError('Global TEX namespace rebind would change record ordinals')
|
|
new_table = b''.join(struct.pack('<I', ident) + rest for ident, rest in rebound)
|
|
output = (_adt_split_chunk('TXVR', records[0][1])
|
|
+ _adt_split_chunk('TXBT', new_table)
|
|
+ b''.join(_adt_split_chunk(tag, payload)
|
|
for tag, payload, tail in records[2:]))
|
|
return output, dict(kind='owned-global-TEX-FileDataID-rebind-v1',
|
|
old_file_data_ids=old_ids,
|
|
new_file_data_ids=[ident for ident, rest in rebound],
|
|
changed_records=len(replacements),
|
|
TXMD_and_all_record_offset_shape_format_bytes_preserved=True,
|
|
original_record_ordinals_preserved=True,
|
|
ascending_unique_FileDataIDs=True,
|
|
mip_construction_or_pixel_decode_repeated=False)
|