367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
886 lines
67 KiB
Python
886 lines
67 KiB
Python
#!/usr/bin/env python3
|
|
"""Inventory and stage source item artwork from authorized local Octo MPQs.
|
|
|
|
Default selection admits identical candidates. Explicit reference selection is
|
|
scoped to a reviewed source binary; runtime launcher equivalence stays unknown.
|
|
Owned-client installation is separately journaled. No account or network access.
|
|
"""
|
|
import argparse
|
|
import ctypes as C
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import struct
|
|
import io
|
|
import subprocess
|
|
|
|
from item_icon_preflight import normalize_icon,hash_value,selected_items
|
|
from item_package_preflight import read_public_json,bounded_digest
|
|
from octo_client_data import ROOT,build_reader,read_member,canonical_sha256,_publish_inventory
|
|
from turtle_data import DBC,spell_layout
|
|
|
|
MAX_TOKENS=128
|
|
MAX_ARCHIVES=128
|
|
MAX_ARCHIVE_BYTES=17179869184
|
|
MAX_SOURCE_BYTES=68719476736
|
|
MAX_MEMBER_BYTES=4194304
|
|
MAX_PAYLOAD_BYTES=67108864
|
|
MAX_CATALOGUE_TOKENS=4096
|
|
MAX_CATALOGUE_PAYLOAD_BYTES=268435456
|
|
|
|
def _sha(raw):return hashlib.sha256(raw).hexdigest()
|
|
def _compact(value):return (json.dumps(value,sort_keys=True,separators=(',',':'),ensure_ascii=False,allow_nan=False)+'\n').encode()
|
|
def _stat(path):
|
|
value=path.stat()
|
|
return (value.st_dev,value.st_ino,value.st_size,value.st_mtime_ns,value.st_ctime_ns)
|
|
|
|
def icon_requests(report):
|
|
"""Derive only exact-reference misses from the existing observed icon report."""
|
|
if (not isinstance(report,dict) or report.get('kind')!='blocked-item-icon-reference-preflight' or type(report.get('schema_version')) is not int or report['schema_version']!=1 or
|
|
report.get('source_observed_context_validated') is not True or report.get('installable') is not False or report.get('installed') is not False):
|
|
raise ValueError('Require the existing observed non-installable icon report')
|
|
source=report.get('observed_source_context');pins=report.get('input_sha256')
|
|
if (not isinstance(source,dict) or not isinstance(pins,dict) or source.get('provenance')!='selected-by-pinned-evidence' or
|
|
source.get('selection_scope')!='observed-file-content-only' or not isinstance(source.get('source_installation'),str) or
|
|
not Path(source['source_installation']).is_absolute() or not isinstance(source.get('client_identity'),dict)):
|
|
raise ValueError('Missing observed source context')
|
|
for key in ('scan_sha256','content_sha256','observation_sha256','loader_analysis_sha256'):
|
|
if not hash_value(source.get(key)):raise ValueError('Invalid observed source-context hash')
|
|
if not hash_value(source['client_identity'].get('client_sha256')) or not isinstance(source.get('dataset'),str) or not 1<=len(source['dataset'])<=256:raise ValueError('Incomplete observed client identity')
|
|
if any(not hash_value(pins.get(key)) for key in ('candidate','observed_inventory','source_dbc','source_dbd','target_listfile')) or pins['source_dbc']!=source['content_sha256'] or report.get('source_item_display_sha256')!=source['content_sha256']:
|
|
raise ValueError('Icon report input pins differ from observed content')
|
|
rows=report.get('rows')
|
|
if not isinstance(rows,list) or not 1<=len(rows)<=4096 or type(report.get('source_count')) is not int or report['source_count']!=len(rows):raise ValueError('Icon report item bound')
|
|
owned=report.get('scope')=='owned-equipment-missing-icon-references'
|
|
if owned:
|
|
candidate=report.get('candidate')
|
|
if (not isinstance(candidate,dict)or candidate.get('kind')!='blocked-owned-equipment-icon-candidate'
|
|
or pins['candidate']!=canonical_sha256(candidate)
|
|
or candidate.get('source_snapshot_identity')!=report.get('item_relationship_source')):
|
|
raise ValueError('Pinned owned icon candidate required')
|
|
fields=('entry','source_display_id','native_icon_file_data_id')
|
|
expected={tuple(r[k]for k in fields)for r in selected_items(candidate)}
|
|
if expected!={tuple(r.get(k)for k in fields)for r in rows}or len(expected)!=len(rows):
|
|
raise ValueError('Owned icon report/source relationship differs')
|
|
requests={};seen=set()
|
|
for row in rows:
|
|
if not isinstance(row,dict) or type(row.get('entry')) is not int or not 0<row['entry']<=0x7fffffff or row['entry'] in seen:raise ValueError('Ambiguous icon-report item identity')
|
|
seen.add(row['entry']);references=row.get('replacement_candidates')
|
|
if not isinstance(references,list) or len(references)>16:raise ValueError('Missing bounded exact-reference result')
|
|
if references:continue
|
|
missing_owned=owned and row.get('status')=='blocked-target-listfile-missing'and row.get('native_icon_file_data_id')==0
|
|
if (row.get('status')!='blocked-filename-mismatch'and not missing_owned) or row.get('replacement_candidate_resolution')!='no-exact-listfile-reference' or row.get('replacement_candidate_selection')!='none':
|
|
raise ValueError('Unresolved source icons require an explicit exact-reference miss')
|
|
icon=normalize_icon(row.get('source_icon'),source=True)
|
|
if row.get('normalized_source')!=icon:raise ValueError('Source icon token differs from reviewed normalization')
|
|
for key in ('source_display_id','native_icon_file_data_id'):
|
|
if type(row.get(key)) is not int or not 0<=row[key]<=0xffffffff:raise ValueError('Invalid icon-report source relationship')
|
|
value=requests.setdefault(icon['path'],dict(source_icon_path=icon['path'],source_extension=icon['extension'],items=[]))
|
|
value['items'].append({key:row[key] for key in ('entry','source_display_id','native_icon_file_data_id')})
|
|
if not 1<=len(requests)<=MAX_TOKENS:raise ValueError('Missing-icon token bound')
|
|
result=[]
|
|
for value in requests.values():
|
|
value['items'].sort(key=lambda row:row['entry'])
|
|
value['members']=[value['source_icon_path']] if value['source_extension'] else [value['source_icon_path']+ext for ext in ('.blp','.tga')]
|
|
value['lookup_scope']='exact-source-path' if value['source_extension'] else 'exact-source-stem-candidate-extensions-unverified'
|
|
result.append(value)
|
|
return sorted(result,key=lambda row:row['source_icon_path']),source
|
|
|
|
def archive_paths(client):
|
|
"""Bounded public Data tree only; no symlink traversal or account directories."""
|
|
data=client/'Data'
|
|
if data.is_symlink() or not data.is_dir():raise ValueError('Require a regular public Data directory')
|
|
paths=[];entries=0;directories=0
|
|
for directory,children,files in os.walk(data,followlinks=False):
|
|
here=Path(directory);relative=here.relative_to(data);directories+=1
|
|
if len(relative.parts)>4 or directories>256:raise ValueError('Public Data directory bound')
|
|
for name in children+files:
|
|
entries+=1
|
|
if entries>16384 or not re.fullmatch(r'[A-Za-z0-9_. -]{1,128}',name) or name in ('.','..'):raise ValueError('Public Data path/entry bound')
|
|
path=here/name
|
|
if path.is_symlink():raise ValueError('Linked public Data entries require a separate reviewed inventory')
|
|
children.sort()
|
|
for name in sorted(files):
|
|
path=here/name
|
|
if path.suffix.lower()!='.mpq':continue
|
|
if not path.is_file() or not 0<path.stat().st_size<=MAX_ARCHIVE_BYTES:raise ValueError('Public MPQ file bound')
|
|
paths.append(path)
|
|
if len(paths)>MAX_ARCHIVES:raise ValueError('Archive inventory bound')
|
|
if not paths or sum(path.stat().st_size for path in paths)>MAX_SOURCE_BYTES:raise ValueError('Source archive batch byte bound')
|
|
return sorted(paths,key=lambda path:path.relative_to(data).as_posix())
|
|
|
|
def cached_reader(source):
|
|
"""Require the established cache fingerprint, then reuse its API setup.
|
|
|
|
Missing/drifted caches are explicit preparation failures, not an implicit
|
|
compilation during an asset inventory operation.
|
|
"""
|
|
source=Path(source);names=('common','explode','extract','huffman','mpq','wave')
|
|
files=sorted(source.glob('*.h'))+[source/(name+'.c') for name in names]
|
|
if not files or len(files)>128 or any(path.is_symlink() or not path.is_file() or not 0<path.stat().st_size<=4194304 for path in files) or sum(path.stat().st_size for path in files)>16777216:raise ValueError('Missing bounded existing MPQ reader sources')
|
|
fingerprint=hashlib.sha256(b''.join(path.read_bytes() for path in files)).hexdigest()
|
|
directory=ROOT/'build/octo-data';library=directory/'libmpq-readonly.so';marker=directory/'source.sha256'
|
|
if library.is_symlink() or marker.is_symlink() or not library.is_file() or not marker.is_file() or marker.stat().st_size!=64 or marker.read_text()!=fingerprint:
|
|
raise ValueError('Prepare the existing fingerprint-matched octo_client_data reader cache first')
|
|
library_hash=bounded_digest(library)
|
|
api,actual=build_reader(source)
|
|
if actual!=fingerprint or bounded_digest(library)!=library_hash or marker.read_text()!=fingerprint:raise ValueError('MPQ reader cache changed')
|
|
return api,dict(source_sha256=fingerprint,library_sha256=library_hash,cached_build_reused=True)
|
|
|
|
class BoundedIconAPI:
|
|
"""Apply the smaller icon allocation budget to the existing member reader."""
|
|
def __init__(self,api,remaining):self.api=api;self.bound=min(MAX_MEMBER_BYTES,remaining)
|
|
def __getattr__(self,name):return getattr(self.api,name)
|
|
def libmpq__file_size_unpacked(self,handle,index,size):
|
|
result=self.api.libmpq__file_size_unpacked(handle,index,size)
|
|
if not result and not 20<=C.cast(size,C.POINTER(C.c_int64)).contents.value<=self.bound:raise ValueError('Icon member allocation/remaining-byte bound')
|
|
return result
|
|
|
|
def classify_asset(raw,extension):
|
|
"""Basic file shape only; no decoder, visual interpretation or conversion."""
|
|
if not isinstance(raw,bytes) or not 20<=len(raw)<=MAX_MEMBER_BYTES:raise ValueError('Icon payload byte bound')
|
|
if extension=='.blp':
|
|
magic=raw[:4]
|
|
if magic not in (b'BLP1',b'BLP2'):return dict(status='unrecognized-blp-magic',magic_hex=magic.hex(),valid_image_verified=False)
|
|
width,height=struct.unpack_from('<II',raw,12)
|
|
return dict(status='recognized-blp-magic' if 0<width<=4096 and 0<height<=4096 else 'invalid-blp-dimensions',
|
|
magic=magic.decode('ascii'),width=width,height=height,valid_image_verified=False)
|
|
if extension!='.tga':raise ValueError('Unreviewed icon candidate extension')
|
|
ident,cmap,kind=struct.unpack_from('<BBB',raw);width,height,bpp=struct.unpack_from('<HHB',raw,12)
|
|
valid=cmap in (0,1) and kind in (1,2,3,9,10,11) and 0<width<=4096 and 0<height<=4096 and bpp in (8,15,16,24,32) and 18+ident<=len(raw)
|
|
return dict(status='tga-header-shaped' if valid else 'unrecognized-tga-header',width=width,height=height,pixel_bits=bpp,valid_image_verified=False)
|
|
|
|
def catalogue_icon_requests(report,manifest,report_hash):
|
|
"""Use the complete catalogue's exact observed source names, not misses.
|
|
|
|
Item identity and observed ItemDisplayInfo were pinned by the existing bulk
|
|
converter. This changes selection scope, never archive/extension precedence.
|
|
"""
|
|
if (report.get('kind')!='source-catalogue-icon-requests' or report.get('schema_version')!=1
|
|
or report.get('source_artwork_required')is not True
|
|
or manifest.get('kind')!='source-item-catalogue-conversion'
|
|
or manifest.get('observed_source_context')!=report.get('source')
|
|
or manifest.get('source_snapshot_identity')!=report.get('source_snapshot_identity')
|
|
or len([f for f in manifest.get('files',[])if f.get('path')=='icon-requests.json' and f.get('sha256')==report_hash])!=1):
|
|
raise ValueError('Pinned complete-catalogue icon request manifest required')
|
|
source=report.get('source',{})
|
|
if (source.get('provenance')!='selected-by-pinned-evidence' or source.get('selection_scope')!='observed-file-content-only'
|
|
or not isinstance(source.get('source_installation'),str) or not Path(source['source_installation']).is_absolute()
|
|
or not hash_value(source.get('client_identity',{}).get('client_sha256'))
|
|
or any(not hash_value(source.get(k))for k in ('scan_sha256','content_sha256','observation_sha256','loader_analysis_sha256'))):
|
|
raise ValueError('Catalogue observed source identity missing')
|
|
requests=report.get('requests')
|
|
if not isinstance(requests,list) or not 1<=len(requests)<=MAX_CATALOGUE_TOKENS:raise ValueError('Catalogue icon count bound')
|
|
result=[];seen=set();total=0
|
|
for request in requests:
|
|
icon=normalize_icon(request.get('source_icon_path'),source=True);items=request.get('items')
|
|
if icon['path']in seen or icon['extension']!=request.get('source_extension'):raise ValueError('Ambiguous catalogue icon path')
|
|
seen.add(icon['path'])
|
|
if not isinstance(items,list)or not items:raise ValueError('Catalogue item references missing')
|
|
total+=len(items)
|
|
if total>100000:raise ValueError('Catalogue icon item count bound')
|
|
if any(set(r)!={'entry','source_display_id'} or any(type(v)is not int or not 0<=v<=0x7fffffff for v in r.values())for r in items):
|
|
raise ValueError('Catalogue source item/display identity differs')
|
|
result.append(dict(source_icon_path=icon['path'],source_extension=icon['extension'],items=items,
|
|
members=[icon['path']]if icon['extension']else[icon['path']+ext for ext in ('.blp','.tga')],
|
|
lookup_scope='exact-source-path'if icon['extension']else'exact-source-stem-candidate-extensions-unverified'))
|
|
return sorted(result,key=lambda r:r['source_icon_path']),source
|
|
|
|
|
|
def inventory_icons(report_path,client,output,reader_source,*,catalogue=False):
|
|
report_path=Path(report_path);client=Path(client);output=Path(output);reader_source=Path(reader_source)
|
|
if not report_path.resolve().is_relative_to(ROOT/'runtime'):raise ValueError('Require an existing public runtime icon report')
|
|
report,report_hash=read_public_json(report_path,16777216)
|
|
catalogue_manifest_hash=None
|
|
if catalogue:
|
|
manifest,catalogue_manifest_hash=read_public_json(report_path.parent/'manifest.json',16777216)
|
|
requests,source=catalogue_icon_requests(report,manifest,report_hash)
|
|
else:requests,source=icon_requests(report)
|
|
payload_limit=MAX_CATALOGUE_PAYLOAD_BYTES if catalogue else MAX_PAYLOAD_BYTES
|
|
selected=client.resolve();original=Path(source['source_installation']).resolve()
|
|
if selected!=original and not selected.is_relative_to(ROOT/'runtime'):raise ValueError('Explicit private client copies must remain under gateway runtime')
|
|
if client.is_symlink() or not client.is_dir():raise ValueError('Require an authorized regular client installation')
|
|
executables=[client/name for name in ('WoW.exe','Wow.exe') if (client/name).is_file()]
|
|
if len(executables)!=1 or executables[0].is_symlink():raise ValueError('Require one public original WoW executable')
|
|
executable=executables[0];exe_stat=_stat(executable);exe_hash=bounded_digest(executable)
|
|
if exe_hash!=source['client_identity']['client_sha256']:raise ValueError('Selected client differs from observed source identity')
|
|
destination=output.resolve();staging=output.with_name(output.name+'.partial')
|
|
if not destination.is_relative_to(ROOT/'runtime') or destination==ROOT/'runtime' or destination.is_relative_to(selected) or output.exists() or output.is_symlink() or staging.exists() or staging.is_symlink() or not output.parent.is_dir():raise ValueError('Require a new runtime directory outside the source client')
|
|
api,reader=cached_reader(reader_source);archives=archive_paths(client)
|
|
before={path:dict(stat=_stat(path),sha256=bounded_digest(path,MAX_ARCHIVE_BYTES)) for path in archives}
|
|
staging.mkdir(mode=0o700);archive_rows=[];matches=[];payload_bytes=0
|
|
try:
|
|
for archive_index,archive in enumerate(archives):
|
|
relative=archive.relative_to(client/'Data').as_posix();handle=C.c_void_p()
|
|
opened=api.libmpq__archive_open(C.byref(handle),os.fsencode(archive),0)
|
|
row=dict(file=relative,bytes=before[archive]['stat'][2],sha256=before[archive]['sha256'],open_result=int(opened),members_checked=0,found=0,member_errors=0)
|
|
archive_rows.append(row)
|
|
if opened:continue
|
|
try:
|
|
for request in requests:
|
|
for member in request['members']:
|
|
row['members_checked']+=1
|
|
lookup=member.replace('/','\\')
|
|
try:raw=read_member(BoundedIconAPI(api,payload_limit-payload_bytes),handle,lookup)
|
|
except ValueError as error:
|
|
row['member_errors']+=1;matches.append(dict(archive=relative,source_icon_path=request['source_icon_path'],member=member,status='blocked-member-read-error',error=str(error)[:240]));continue
|
|
if raw is None:continue
|
|
if not isinstance(raw,bytes) or len(raw)>min(MAX_MEMBER_BYTES,payload_limit-payload_bytes):raise ValueError('Icon payload batch bound')
|
|
extension=Path(member).suffix;shape=classify_asset(raw,extension);payload_bytes+=len(raw);row['found']+=1
|
|
file=Path(f'assets-{archive_index:03d}')/(_sha(member.encode('ascii'))+extension)
|
|
target=staging/file;target.parent.mkdir(mode=0o700,parents=True,exist_ok=True)
|
|
with target.open('xb') as stream:stream.write(raw)
|
|
target.chmod(0o600)
|
|
matches.append(dict(archive=relative,source_icon_path=request['source_icon_path'],member=member,status='candidate-content-retained',
|
|
file=file.as_posix(),bytes=len(raw),sha256=_sha(raw),classification=shape))
|
|
finally:
|
|
closed=api.libmpq__archive_close(handle);row['close_result']=int(closed)
|
|
if closed:raise ValueError('MPQ archive close failed')
|
|
if archive_paths(client)!=archives:raise ValueError('Source archive inventory changed')
|
|
for archive in archives:
|
|
if _stat(archive)!=before[archive]['stat'] or bounded_digest(archive,MAX_ARCHIVE_BYTES)!=before[archive]['sha256'] or _stat(archive)!=before[archive]['stat']:raise ValueError('Source archive changed during inventory')
|
|
if _stat(executable)!=exe_stat or bounded_digest(executable)!=exe_hash or bounded_digest(report_path,16777216)!=report_hash:raise ValueError('Source executable or icon report changed during inventory')
|
|
if catalogue and bounded_digest(report_path.parent/'manifest.json',16777216)!=catalogue_manifest_hash:raise ValueError('Catalogue manifest changed during inventory')
|
|
retained_tokens={row['source_icon_path'] for row in matches if row['status']=='candidate-content-retained'}
|
|
result=dict(kind='octo-independent-icon-asset-candidates',schema_version=1,input_icon_report_sha256=report_hash,input_icon_report_canonical_sha256=canonical_sha256(report),
|
|
observed_source_context=source,selected_source_installation=str(selected),source_client_sha256=exe_hash,reader=reader,
|
|
source_inventory_scope='all regular MPQ files in bounded public Data tree; no symlink traversal',archives=archive_rows,requests=requests,matches=matches,
|
|
token_count=len(requests),archive_count=len(archives),candidate_content_count=sum(row['found'] for row in archive_rows),payload_bytes=payload_bytes,
|
|
tokens_with_retained_candidate=len(retained_tokens),tokens_without_retained_candidate=len(requests)-len(retained_tokens),archive_open_error_count=sum(row['open_result']!=0 for row in archive_rows),
|
|
member_error_count=sum(row['member_errors'] for row in archive_rows),archives_rehashed_twice=True,source_snapshot_transactional=False,
|
|
source_stat_fields_compared=['device','inode','bytes','mtime_ns','ctime_ns'],source_stat_drift_detected=False,
|
|
effective_patch_order_verified=False,extension_selected=False,launcher_environment_equivalence_verified=False,postload_semantics_verified=False,
|
|
addon_effects_verified=False,asset_conversion_verified=False,engine_loaded=False,gameplay_verified=False,installable=False,installed=False,
|
|
catalogue_source_artwork=catalogue,catalogue_manifest_sha256=catalogue_manifest_hash,
|
|
limits=['Each archive and candidate extension is independent; ordering is presentation only and selects no winner.',
|
|
'Only exact source names from the validated icon report/catalogue are probed; no account files, fuzzy names or unrelated assets.',
|
|
'Magic/header classification is not complete image validation, asset equivalence, engine compatibility or conversion.',
|
|
'Pre/post hashes and metadata detect observed drift; they do not create an atomic source snapshot.',
|
|
'The original loader environment, addon effects and post-load data processing are not established by archive extraction.'])
|
|
with (staging/'manifest.json').open('xb') as stream:stream.write(_compact(result))
|
|
(staging/'manifest.json').chmod(0o600)
|
|
_publish_inventory(staging,output,[dict(path=row['file'],output_bytes=row['bytes'],output_sha256=row['sha256']) for row in matches if row['status']=='candidate-content-retained'])
|
|
return result
|
|
except Exception as error:
|
|
with (staging/'failure.json').open('xb') as stream:stream.write(_compact(dict(status='INCOMPLETE_NOT_PUBLISHED',error_type=type(error).__name__,error=str(error)[:500])))
|
|
(staging/'failure.json').chmod(0o600)
|
|
raise
|
|
|
|
def decode_blp(raw):
|
|
"""Bound and decode a real texture, separately from reference/engine proof."""
|
|
if not isinstance(raw,bytes) or not 148<=len(raw)<=MAX_MEMBER_BYTES or raw[:4] not in (b'BLP1',b'BLP2'):raise ValueError('Bounded BLP texture required')
|
|
from PIL import Image
|
|
if raw[:4]==b'BLP2' and raw[8]==3:
|
|
# Pillow names encoding3 UNCOMPRESSED_RAW_BGRA, but its decoder omits
|
|
# that branch. Reuse the local benilla-blp Raw3 contract: the palette
|
|
# prefix is retained, and each uncompressed texel is B,G,R,A. Validate
|
|
# every stored level before decoding; never reinterpret compressed data.
|
|
# Source: references/manila/crates/benilla-blp/src/lib.rs, parse_header
|
|
# and decode_raw3. The returned artwork remains the exact Source bytes.
|
|
if (len(raw)<1172 or struct.unpack_from('<I',raw,4)[0]!=1 or
|
|
raw[9]!=8 or raw[10]!=8 or raw[11] not in (0,1)):
|
|
raise ValueError('Unqualified raw BGRA8 BLP2 header')
|
|
width,height=struct.unpack_from('<II',raw,12)
|
|
if (not 0<width<=4096 or not 0<height<=4096 or
|
|
width&(width-1) or height&(height-1)):
|
|
raise ValueError('Bounded power-of-two raw BGRA8 dimensions required')
|
|
offsets=struct.unpack_from('<16I',raw,20);sizes=struct.unpack_from('<16I',raw,84)
|
|
cursor=1172;levels=0;ended=False
|
|
for level,(offset,size) in enumerate(zip(offsets,sizes)):
|
|
if size==0:
|
|
ended=True
|
|
if offset not in (0,len(raw)):
|
|
raise ValueError('Unexpected unused raw BGRA8 mip offset')
|
|
continue
|
|
expected=max(1,width>>level)*max(1,height>>level)*4
|
|
if (ended or offset!=cursor or size!=expected or
|
|
offset>len(raw)-size or (level and not raw[11])):
|
|
raise ValueError('Contiguous bounded raw BGRA8 mip levels required')
|
|
cursor+=size;levels+=1
|
|
if not levels or cursor!=len(raw):
|
|
raise ValueError('Complete raw BGRA8 BLP2 levels required')
|
|
image=Image.frombytes('RGBA',(width,height),raw[offsets[0]:offsets[0]+sizes[0]],'raw','BGRA')
|
|
image.load()
|
|
return dict(width=width,height=height,decoded=True,format='BLP',
|
|
decoder='pillow-raw-bgra8',mip_levels=levels,
|
|
rgba_sha256=hashlib.sha256(image.tobytes()).hexdigest())
|
|
try:
|
|
with Image.open(io.BytesIO(raw)) as image:
|
|
if not 0<image.width<=4096 or not 0<image.height<=4096:raise ValueError('Texture dimension bound')
|
|
image.load();return dict(width=image.width,height=image.height,decoded=True,format=image.format)
|
|
except OSError as error:
|
|
# Pillow's BLP2 decoder reads a 1 KiB palette even for DXT textures.
|
|
# The short Source overlays below contain one valid palette-free DXT3
|
|
# mip; reuse the same BCn decoder used by the existing mip repair path.
|
|
if (str(error)!='Truncated File Read' or raw[:4]!=b'BLP2' or
|
|
struct.unpack_from('<I',raw,4)[0]!=1 or tuple(raw[8:12])!=(2,8,1,0) or len(raw)>=1172):
|
|
raise
|
|
width,height=struct.unpack_from('<II',raw,12)
|
|
offset=struct.unpack_from('<I',raw,20)[0];size=struct.unpack_from('<I',raw,84)[0]
|
|
if (not 0<width<=4096 or not 0<height<=4096 or offset!=148 or
|
|
size!=((width+3)//4)*((height+3)//4)*16 or offset+size!=len(raw)):
|
|
raise ValueError('Unqualified short palette-free DXT3 BLP') from error
|
|
image=Image.frombytes('RGBA',(width,height),raw[offset:offset+size],'bcn',(2,'DXT3'))
|
|
image.load()
|
|
return dict(width=width,height=height,decoded=True,format='BLP',decoder='pillow-bcn-short-dxt3')
|
|
|
|
|
|
def normalize_source_block_rectangular_mips(raw, *, presentation_policy):
|
|
"""Repair undersized edge-block mips without changing authored valid levels.
|
|
|
|
This opt-in native presentation variant uses the existing Pillow block codecs.
|
|
Only rectangular levels with a sub-four-pixel side may be regenerated, from
|
|
the nearest preceding structurally valid authored mip. It does not replace
|
|
a registered texture, select a variant, or import an asset.
|
|
"""
|
|
policy='source-block-malformed-tail-from-valid-authored-mip-box-v1'
|
|
if presentation_policy!=policy:
|
|
raise ValueError('Explicit Source block mip normalization policy required')
|
|
if (not isinstance(raw,bytes) or not 148<=len(raw)<=MAX_MEMBER_BYTES
|
|
or raw[:4]!=b'BLP2' or struct.unpack_from('<I',raw,4)[0]!=1
|
|
or raw[8]!=2):
|
|
raise ValueError('Block-compressed Source BLP2 required')
|
|
formats={(0,0):('DXT1',1,8,'RGB'),(1,0):('DXT1',1,8,'RGBA'),
|
|
(8,1):('DXT3',2,16,'RGBA')}
|
|
if tuple(raw[9:11]) not in formats:
|
|
raise ValueError('Source block/alpha family lacks normalization contract')
|
|
pixel_format,codec,block_bytes,mode=formats[tuple(raw[9:11])]
|
|
width,height=struct.unpack_from('<II',raw,12)
|
|
if (not 1<=width<=4096 or not 1<=height<=4096
|
|
or width&(width-1) or height&(height-1)):
|
|
raise ValueError('Bounded power-of-two Source dimensions required')
|
|
count=max(width,height).bit_length()
|
|
offsets=struct.unpack_from('<16I',raw,20)
|
|
sizes=struct.unpack_from('<16I',raw,84)
|
|
if any(offsets[count:]) or any(sizes[count:]):
|
|
raise ValueError('Unexpected Source mip slots beyond one-pixel extent')
|
|
if offsets[0] not in (148,1172):
|
|
raise ValueError('Unqualified Source pre-mip prefix extent')
|
|
levels=[];cursor=offsets[0];last_valid=None;changed=[]
|
|
for level in range(count):
|
|
w,h=max(1,width>>level),max(1,height>>level)
|
|
expected=((w+3)//4)*((h+3)//4)*block_bytes
|
|
at,size=offsets[level],sizes[level]
|
|
if (at!=cursor or not 0<size<=expected or size%block_bytes
|
|
or at>len(raw)-size):
|
|
raise ValueError('Contiguous bounded whole Source compressed blocks required')
|
|
cursor=at+size;payload=raw[at:cursor]
|
|
valid=size==expected
|
|
if valid:
|
|
last_valid=level
|
|
elif (last_valid is None or w==h or min(w,h)>=4):
|
|
raise ValueError('Only undersized rectangular edge-block tail admitted')
|
|
else:
|
|
changed.append(level)
|
|
levels.append(dict(level=level,width=w,height=h,expected_bytes=expected,
|
|
payload=payload,valid=valid,source_level=last_valid))
|
|
if cursor!=len(raw):
|
|
raise ValueError('Unclaimed Source texture bytes require separate contract')
|
|
if changed:
|
|
from PIL import Image
|
|
decoded={}
|
|
for item in levels:
|
|
if item['valid']:continue
|
|
source=levels[item['source_level']]
|
|
if source['level'] not in decoded:
|
|
decoded[source['level']]=Image.frombytes(
|
|
'RGBA',(source['width'],source['height']),source['payload'],
|
|
'bcn',(codec,pixel_format)).convert(mode)
|
|
image=decoded[source['level']].resize(
|
|
(item['width'],item['height']),Image.Resampling.BOX)
|
|
encoded=io.BytesIO();image.save(encoded,format='DDS',pixel_format=pixel_format)
|
|
dds=encoded.getvalue()
|
|
if (dds[:4]!=b'DDS ' or dds[84:88]!=pixel_format.encode('ascii')
|
|
or len(dds)!=128+item['expected_bytes']):
|
|
raise ValueError('Existing block encoder output differs from native extent')
|
|
item['payload']=dds[128:]
|
|
header=bytearray(raw[:offsets[0]]);payloads=[];cursor=offsets[0]
|
|
for item in levels:
|
|
level=item['level'];payload=item['payload']
|
|
struct.pack_into('<I',header,20+4*level,cursor)
|
|
struct.pack_into('<I',header,84+4*level,len(payload))
|
|
payloads.append(payload);cursor+=len(payload)
|
|
output=bytes(header)+b''.join(payloads)
|
|
else:
|
|
output=raw
|
|
audit=dict(kind='Source-block-rectangular-mip-native-presentation-v1',
|
|
policy=policy,changed=bool(changed),regenerated_levels=changed,
|
|
highest_resolution_compressed_pixels_preserved=True,
|
|
all_structurally_valid_authored_mips_preserved=True,
|
|
rows=[dict(level=r['level'],width=r['width'],height=r['height'],
|
|
bytes=r['expected_bytes'],authored_preserved=r['valid'],
|
|
regenerated_from_authored_level=None if r['valid']else r['source_level'])
|
|
for r in levels],
|
|
resampling='BOX',encoder='existing-Pillow-DDS-'+pixel_format,
|
|
pre_mip_prefix_bytes_preserved=offsets[0]-148,
|
|
alpha_depth_preserved=raw[9],alpha_encoding_preserved=raw[10],
|
|
Source_cosmetic_equivalence=False,runtime_verified=False,
|
|
default_texture_selector_changed=False)
|
|
return output,audit
|
|
|
|
|
|
# This profile is scoped to the byte-identical shipped source executable.
|
|
# REA closes initializer -> priority insertion -> first matching archive lookup;
|
|
# see docs/evidence/data/octo-builtin-archive-selection.json. Runtime DLL hooks
|
|
# and launcher behavior are deliberately outside this reference policy.
|
|
REFERENCE_ARCHIVE_PROFILE=dict(policy='octo-5875-builtin-archive-priority-v1',
|
|
source_client_sha256='5014ca1cfedf860f10e93fe7d955c56c28eb11a2bb503030dbb9b1c777f00470',
|
|
search_flags=0,runtime_launcher_equivalence_verified=False)
|
|
REFERENCE_ARCHIVE_PRIORITIES={name:63-i for i,name in enumerate(
|
|
('model.mpq','texture.mpq','terrain.mpq','wmo.mpq','sound.mpq','misc.mpq','interface.mpq','fonts.mpq','speech.mpq','dbc.mpq'))}
|
|
REFERENCE_ARCHIVE_PRIORITIES.update({name:64+i for i,name in enumerate(
|
|
('patch.mpq','patch-1.mpq','patch-2.mpq','patch-3.mpq','patch-4.mpq','patch-5.mpq','patch-o.mpq'))})
|
|
|
|
def reference_archive_selection(manifest,matches):
|
|
"""Select a member by the reviewed binary's builtin archive search only.
|
|
|
|
Unknown archives and same-archive extension/locale ambiguities remain
|
|
unresolved. Filenames alone do not authorize this policy on another build.
|
|
"""
|
|
if manifest.get('source_client_sha256')!=REFERENCE_ARCHIVE_PROFILE['source_client_sha256']:
|
|
raise ValueError('Reference archive policy requires the reviewed source executable')
|
|
archives=manifest.get('archives',[])
|
|
inventory={r['file'].lower():r for r in archives}
|
|
if len(inventory)!=len(archives):raise ValueError('Duplicate source archive identity')
|
|
for match in matches:
|
|
name=match['archive'].lower();archive=inventory.get(name)
|
|
if name not in REFERENCE_ARCHIVE_PRIORITIES or not archive or not hash_value(archive.get('sha256')):
|
|
raise ValueError('Archive is outside the reviewed builtin load set')
|
|
if not matches:raise ValueError('No source archive member available')
|
|
priority=max(REFERENCE_ARCHIVE_PRIORITIES[r['archive'].lower()]for r in matches)
|
|
selected=[r for r in matches if REFERENCE_ARCHIVE_PRIORITIES[r['archive'].lower()]==priority]
|
|
if len(selected)!=1:raise ValueError('Same-priority source member/extension ambiguity')
|
|
return selected[0],priority
|
|
|
|
def verify_artwork_selection(manifest):
|
|
if manifest.get('candidate_contents_identical')is True:return
|
|
if (manifest.get('kind')!='source-icon-artwork-batch'
|
|
or manifest.get('reference_archive_profile')!=REFERENCE_ARCHIVE_PROFILE):
|
|
raise ValueError('Explicit reviewed source artwork selection required')
|
|
inventory,pin=read_public_json(Path(manifest['source_inventory'])/'manifest.json',16777216)
|
|
if pin!=manifest.get('input_inventory_sha256'):raise ValueError('Source artwork inventory changed')
|
|
by_token={}
|
|
for match in inventory.get('matches',[]):
|
|
if match.get('status')=='candidate-content-retained':by_token.setdefault(match['source_icon_path'],[]).append(match)
|
|
for source in manifest['source_icons']:
|
|
if source.get('identical_available_candidates')is True:continue
|
|
chosen,priority=reference_archive_selection(inventory,by_token.get(source['source_icon'],[]))
|
|
if (source.get('reference_builtin_selected')is not True or source.get('selected_archive')!=chosen['archive']
|
|
or source.get('selected_priority')!=priority or source.get('sha256')!=chosen['sha256']):
|
|
raise ValueError('Source archive selection differs from reviewed builtin search')
|
|
|
|
def stage_catalogue_artwork(inventory,output,*,reference_builtin_priority=False):
|
|
"""Stage all unambiguous source textures together, preserving conflicts.
|
|
|
|
Content-addressed private names avoid collisions with Forever's artwork.
|
|
The UI provider resolves these names with the original texture API in each
|
|
process; process-specific handles are never put in persistent DB2 records.
|
|
"""
|
|
if type(reference_builtin_priority)is not bool:raise ValueError('Explicit reference archive policy required')
|
|
inventory=Path(inventory);output=Path(output);manifest,pin=read_public_json(inventory/'manifest.json',16777216)
|
|
if (manifest.get('kind')!='octo-independent-icon-asset-candidates' or manifest.get('catalogue_source_artwork')is not True
|
|
or manifest.get('archive_open_error_count')!=0 or manifest.get('member_error_count')!=0
|
|
or manifest.get('archives_rehashed_twice')is not True):raise ValueError('Complete catalogue source icon inventory required')
|
|
if reference_builtin_priority:
|
|
if manifest.get('source_client_sha256')!=REFERENCE_ARCHIVE_PROFILE['source_client_sha256']:
|
|
raise ValueError('Reference archive policy requires the reviewed source executable')
|
|
executable=Path(manifest['selected_source_installation'])/'WoW.exe'
|
|
if bounded_digest(executable,16777216)!=REFERENCE_ARCHIVE_PROFILE['source_client_sha256']:
|
|
raise ValueError('Reviewed reference executable changed')
|
|
staging=output.with_name(output.name+'.partial')
|
|
if (not inventory.resolve().is_relative_to(ROOT/'runtime') or not output.resolve().is_relative_to(ROOT/'runtime')
|
|
or output==ROOT/'runtime' or output.exists() or output.is_symlink() or staging.exists()
|
|
or staging.is_symlink() or not output.parent.is_dir()):raise ValueError('New runtime artwork stage required')
|
|
by_token={}
|
|
for match in manifest.get('matches',[]):
|
|
if match.get('status')=='candidate-content-retained':by_token.setdefault(match['source_icon_path'],[]).append(match)
|
|
payloads={};assets={};items={};excluded=[];sources=[]
|
|
for request in manifest['requests']:
|
|
token=request['source_icon_path'];matches=by_token.get(token,[])
|
|
identical=bool(matches)and len({r['sha256']for r in matches})==1
|
|
selection={};active=matches
|
|
if not identical:
|
|
try:
|
|
if not reference_builtin_priority:raise ValueError('source-content-missing'if not matches else'source-archive-content-conflict')
|
|
chosen,priority=reference_archive_selection(manifest,matches)
|
|
active=[chosen];selection=dict(reference_builtin_selected=True,selected_archive=chosen['archive'],selected_priority=priority)
|
|
except ValueError as error:
|
|
excluded.append(dict(source_icon=token,reason=str(error),item_ids=[r['entry']for r in request['items']],
|
|
candidate_hashes=sorted({r['sha256']for r in matches})));continue
|
|
try:
|
|
for match in active:
|
|
file=Path(match['file']);path=inventory/file
|
|
if file.is_absolute() or '..'in file.parts or path.is_symlink() or not path.resolve().is_relative_to(inventory.resolve()):raise ValueError('Unsafe retained icon asset path')
|
|
raw=path.read_bytes()
|
|
if len(raw)!=match['bytes'] or _sha(raw)!=match['sha256']:raise ValueError('Retained source icon changed')
|
|
if file.suffix!='.blp':raise ValueError('Source icon requires non-BLP conversion')
|
|
image=decode_blp(raw)
|
|
except ValueError as error:
|
|
excluded.append(dict(source_icon=token,reason=str(error),item_ids=[r['entry']for r in request['items']]));continue
|
|
digest=_sha(raw);name='interface/icons/gwhybrid_'+digest+'.blp';file='assets/'+digest+'.blp'
|
|
payloads[file]=raw;assets[name]=dict(path=name,file=file,sha256=digest,bytes=len(raw),magic_hex=raw[:4].hex(),image=image)
|
|
for item in request['items']:
|
|
ident=item['entry']
|
|
if ident==0:continue
|
|
if ident in items:raise ValueError('Ambiguous catalogue item artwork identity')
|
|
items[ident]=name
|
|
sources.append(dict(source_icon=token,path=name,sha256=digest,candidate_archives=sorted({r['archive']for r in matches}),
|
|
identical_available_candidates=identical,effective_patch_order_verified=False,**selection))
|
|
if not items or len(assets)>MAX_CATALOGUE_TOKENS or sum(map(len,payloads.values()))>MAX_CATALOGUE_PAYLOAD_BYTES:raise ValueError('Artwork stage count/byte bound')
|
|
mapping=dict(kind='source-item-icon-map',schema_version=1,items={str(k):v for k,v in sorted(items.items())})
|
|
payloads['item-icons.json']=_compact(mapping)
|
|
payloads['SourceItemIconData.lua']=('GWSourceItemIconData = { version = 1, items = {\n'+''.join(
|
|
'[%d] = "%s",\n'%(ident,name)for ident,name in sorted(items.items()))+'} }\n').encode('ascii')
|
|
if bounded_digest(inventory/'manifest.json',16777216)!=pin:raise ValueError('Source artwork inventory changed')
|
|
result=dict(kind='source-icon-artwork-batch',schema_version=1,input_inventory_sha256=pin,
|
|
source_inventory=str(inventory),assets=sorted(assets.values(),key=lambda r:r['path']),source_icons=sources,
|
|
item_count=len(items),source_icon_count=len(sources),distinct_texture_payloads=len(assets),excluded=excluded,
|
|
candidate_contents_identical=all(r['identical_available_candidates']for r in sources),source_artwork_required=True,
|
|
reference_archive_profile=REFERENCE_ARCHIVE_PROFILE if reference_builtin_priority else None,
|
|
installed=False,engine_loaded=False,gameplay_verified=False,
|
|
effective_patch_order_verified=False,implementation_sha256=bounded_digest(Path(__file__),1048576),
|
|
files=[dict(path=name,bytes=len(raw),sha256=_sha(raw))for name,raw in sorted(payloads.items())],
|
|
limits=['Differing variants require explicit byte-identical source builtin archive policy; launcher/DLL equivalence remains unverified.'if reference_builtin_priority else'Only identical available archive candidates are admitted; differing variants stay unresolved.',
|
|
'Source artwork and source item identities only; no spell, stat, model or gameplay compatibility claim.',
|
|
'Private content-addressed paths require the original texture loader and UI-provider verification.'])
|
|
staging.mkdir(mode=0o700)
|
|
for name,raw in payloads.items():
|
|
path=staging/name;path.parent.mkdir(mode=0o700,exist_ok=True);path.write_bytes(raw)
|
|
(staging/'manifest.json').write_bytes(_compact(result))
|
|
_publish_inventory(staging,output,[dict(path=f['path'],output_bytes=f['bytes'],output_sha256=f['sha256'])for f in result['files']])
|
|
return result
|
|
|
|
def talent_icon_reference(profile_path,member):
|
|
"""Check the exact existing generated profile against its source DBCs."""
|
|
profile,pin=read_public_json(profile_path,16777216);icon=normalize_icon(member,source=True)
|
|
if icon['extension']!='blp' or profile.get('schema_version')!=1:raise ValueError('Exact BLP member and existing talent profile required')
|
|
tables={};pins={}
|
|
for name,width in (('Spell',173),('Talent',21),('SpellIcon',2)):
|
|
meta=profile.get('tables',{}).get(name,{})
|
|
path=Path(meta.get('source',''))
|
|
if path.name!=name+'.dbc' or path.is_symlink() or bounded_digest(path)!=meta.get('sha256'):raise ValueError('Talent source table pin differs')
|
|
with path.open('rb') as stream:raw=stream.read(67108865)
|
|
if len(raw)>67108864 or _sha(raw)!=meta['sha256']:raise ValueError('Talent source table changed')
|
|
class Frozen:
|
|
name=path.name
|
|
def read_bytes(self):return raw
|
|
table=DBC(Frozen(),width)
|
|
if table.count!=meta.get('rows') or table.digest()!=meta['sha256']:raise ValueError('Talent source table shape/hash differs')
|
|
tables[name]=table;pins[str(path)]=meta['sha256']
|
|
references=[];layout=spell_layout()
|
|
for talent in profile.get('talents',[]):
|
|
for index,rank in enumerate(talent.get('ranks',[])):
|
|
try:source=normalize_icon(rank.get('icon'),source=True)
|
|
except ValueError:continue
|
|
if source['stem']!=icon['stem'] or source['extension'] is not None and source['path']!=icon['path']:continue
|
|
original=tables['Talent'].by_id.get(talent.get('id'));spell=tables['Spell'].by_id.get(rank.get('id'))
|
|
if index>=5 or original is None or original[4+index]!=rank['id'] or spell is None:raise ValueError('Talent/rank source identity differs')
|
|
icon_id=spell[layout['SpellIconID']];record=tables['SpellIcon'].by_id.get(icon_id)
|
|
if record is None or normalize_icon(tables['SpellIcon'].string(record[1]),source=True)!=source:raise ValueError('Source spell/icon reference differs')
|
|
references.append(dict(talent_id=talent['id'],rank=index+1,spell_id=rank['id'],spell_icon_id=icon_id,source_icon=rank['icon']))
|
|
if not 1<=len(references)<=512:raise ValueError('No bounded genuine talent reference to this exact icon')
|
|
return icon,dict(profile=str(Path(profile_path)),sha256=pin,source_table_sha256=pins,references=references)
|
|
|
|
def stage_talent_icon(profile_path,client,member,output,reader_source):
|
|
"""Stage one exact source texture; differing archive contents fail closed."""
|
|
client=Path(client);output=Path(output);icon,reference=talent_icon_reference(profile_path,member)
|
|
if client.is_symlink() or (client.resolve()!=Path.home()/'Games/octo/drive_c/Octowow' and not client.resolve().is_relative_to(ROOT/'runtime')):raise ValueError('Require authorized installed Octo or private runtime source')
|
|
if not output.resolve().is_relative_to(ROOT/'runtime') or output.resolve()==ROOT/'runtime' or output.exists() or output.is_symlink() or output.with_name(output.name+'.partial').exists() or not output.parent.is_dir():raise ValueError('Require a new runtime icon stage')
|
|
executable=client/'WoW.exe';exe_hash=bounded_digest(executable);api,reader=cached_reader(reader_source);archives=archive_paths(client)
|
|
before={path:_stat(path) for path in archives};matches=[];lookup=icon['path'].replace('/','\\')
|
|
def read(path):
|
|
handle=C.c_void_p()
|
|
if api.libmpq__archive_open(C.byref(handle),os.fsencode(path),0):raise ValueError('Source archive open failed')
|
|
try:return read_member(BoundedIconAPI(api,MAX_MEMBER_BYTES),handle,lookup)
|
|
finally:
|
|
if api.libmpq__archive_close(handle):raise ValueError('Source archive close failed')
|
|
for path in archives:
|
|
raw=read(path)
|
|
if raw is not None:matches.append((path,raw))
|
|
if not matches or len({_sha(raw) for _,raw in matches})!=1:raise ValueError('Missing or differing exact icon candidates; no archive winner selected')
|
|
raw=matches[0][1];image=decode_blp(raw);sources=[]
|
|
for path,_ in matches:
|
|
digest=bounded_digest(path,MAX_ARCHIVE_BYTES)
|
|
if read(path)!=raw or bounded_digest(path,MAX_ARCHIVE_BYTES)!=digest:raise ValueError('Matching source archive/member changed')
|
|
sources.append(dict(archive=path.relative_to(client/'Data').as_posix(),bytes=path.stat().st_size,sha256=digest,member=icon['path']))
|
|
if archive_paths(client)!=archives or any(_stat(path)!=before[path] for path in archives):raise ValueError('Source archive inventory changed')
|
|
if bounded_digest(executable)!=exe_hash:raise ValueError('Source executable changed')
|
|
if talent_icon_reference(profile_path,member)[1]!=reference:raise ValueError('Talent reference changed')
|
|
asset=dict(path=icon['path'],file='assets/'+_sha(raw)+'.blp',bytes=len(raw),sha256=_sha(raw),magic_hex=raw[:4].hex(),image=image)
|
|
result=dict(kind='source-talent-icon-stage',schema_version=1,source_installation=str(client.resolve()),source_client_sha256=exe_hash,
|
|
source_client_build='1.12.1.5875' if exe_hash=='5014ca1cfedf860f10e93fe7d955c56c28eb11a2bb503030dbb9b1c777f00470' else None,
|
|
source_build_basis='existing-reviewed-executable-hash' if exe_hash=='5014ca1cfedf860f10e93fe7d955c56c28eb11a2bb503030dbb9b1c777f00470' else 'unknown',source_reference=reference,
|
|
reader=reader,source_archives=sources,archive_inventory=[dict(path=p.relative_to(client/'Data').as_posix(),stat=list(before[p])) for p in archives],
|
|
candidate_contents_identical=True,member=icon['path'],assets=[asset],implementation_sha256=bounded_digest(Path(__file__),1048576),
|
|
installed=False,engine_loaded=False,effective_patch_order_verified=False,launcher_environment_equivalence_verified=False,postload_semantics_verified=False,
|
|
limits=['Exact source reference and identical available archive bytes, not global precedence or engine-loading proof.',
|
|
'Matching archives are hashed twice; other bounded public archive identities are checked by stat and member lookup, not full archive hashes.'])
|
|
staging=output.with_name(output.name+'.partial');staging.mkdir(mode=0o700);target=staging/asset['file'];target.parent.mkdir(mode=0o700)
|
|
with target.open('xb') as stream:stream.write(raw)
|
|
target.chmod(0o600)
|
|
with (staging/'manifest.json').open('xb') as stream:stream.write(_compact(result))
|
|
_publish_inventory(staging,output,[dict(path=asset['file'],output_bytes=asset['bytes'],output_sha256=asset['sha256'])])
|
|
return result
|
|
|
|
def private_icon_client():
|
|
from client_installation import COPY,MARKER,inspect_installation,running_clients
|
|
if running_clients():raise ValueError('Close Forever normally before changing owned icon files')
|
|
if COPY.resolve()!=ROOT/'runtime/native-client' or COPY.is_symlink() or not (COPY/MARKER).is_file():raise ValueError('Journaled private client required')
|
|
identity=inspect_installation(COPY)
|
|
return COPY/'_classic_beta_',identity
|
|
|
|
def _icon_target(client,path):
|
|
name=normalize_icon(path)
|
|
if name['path']!=path or name['extension']!='blp':raise ValueError('Canonical exact Interface/Icons BLP path required')
|
|
target=client/'Interface'/'Icons'/path.removeprefix('interface/icons/')
|
|
if any(p.is_symlink() for p in (client,client/'Interface',target.parent,target)) or target.resolve()!=target:raise ValueError('Linked icon path preserved')
|
|
return target
|
|
|
|
def install_icon_stage(stage,output):
|
|
"""Install only new exact textures; an existing matching file stays unowned."""
|
|
stage=Path(stage);output=Path(output);client,identity=private_icon_client()
|
|
if not stage.resolve().is_relative_to(ROOT/'runtime') or stage.is_symlink():raise ValueError('Private runtime icon stage required')
|
|
stage=stage.resolve()
|
|
manifest,pin=read_public_json(stage/'manifest.json',16777216);assets=manifest.get('assets')
|
|
bound=MAX_CATALOGUE_TOKENS if manifest.get('kind')=='source-icon-artwork-batch' else 128
|
|
if manifest.get('kind')not in ('source-talent-icon-stage','source-icon-artwork-batch') or manifest.get('schema_version')!=1 or not isinstance(assets,list) or not 1<=len(assets)<=bound:raise ValueError('Bounded verified source icon stage required')
|
|
verify_artwork_selection(manifest)
|
|
if not output.resolve().is_relative_to(ROOT/'runtime') or output.exists() or output.is_symlink() or not output.parent.is_dir():raise ValueError('New runtime installation journal required')
|
|
plans=[];seen=set()
|
|
for asset in assets:
|
|
path=asset.get('path');target=_icon_target(client,path)
|
|
if path in seen:raise ValueError('Duplicate icon installation path')
|
|
seen.add(path)
|
|
if not hash_value(asset.get('sha256')) or asset.get('file')!='assets/'+asset['sha256']+'.blp':raise ValueError('Content-addressed staged icon file required')
|
|
source=stage/asset['file']
|
|
if source.is_symlink() or source.resolve()!=source or bounded_digest(source,MAX_MEMBER_BYTES)!=asset.get('sha256') or source.stat().st_size!=asset.get('bytes'):raise ValueError('Staged texture bytes differ')
|
|
with source.open('rb') as stream:raw=stream.read(MAX_MEMBER_BYTES+1)
|
|
if len(raw)!=asset['bytes'] or _sha(raw)!=asset['sha256']:raise ValueError('Staged texture changed while reading')
|
|
if raw[:4].hex()!=asset.get('magic_hex') or decode_blp(raw)!=asset.get('image'):raise ValueError('Staged texture image differs')
|
|
existed=target.exists()
|
|
if existed and (not target.is_file() or bounded_digest(target,MAX_MEMBER_BYTES)!=asset['sha256']):raise ValueError('Different existing icon preserved; no unowned overwrite')
|
|
plans.append(dict(path=path,file=asset['file'],sha256=asset['sha256'],bytes=asset['bytes'],existed=existed,created=False))
|
|
result=dict(kind='private-source-icon-installation',schema_version=1,status='PREPARED',client=str(client),client_identity=identity,
|
|
stage=str(stage),stage_manifest_sha256=pin,files=plans,engine_loaded=False,gameplay_verified=False,
|
|
rollback='Close the private client; run octo_icon_assets.py --rollback-manifest THIS_JSON. Only created files still matching their exact hashes are removed; preexisting files stay untouched.')
|
|
with output.open('x') as stream:stream.write(_compact(result).decode())
|
|
output.chmod(0o600)
|
|
for plan in plans:
|
|
if plan['existed']:continue
|
|
target=_icon_target(client,plan['path']);target.parent.mkdir(parents=True,exist_ok=True)
|
|
with (stage/plan['file']).open('rb') as source:raw=source.read(MAX_MEMBER_BYTES+1)
|
|
if len(raw)!=plan['bytes'] or _sha(raw)!=plan['sha256']:raise ValueError('Staged texture changed before install')
|
|
with target.open('xb') as stream:stream.write(raw)
|
|
target.chmod(0o600);plan['created']=True
|
|
output.write_bytes(_compact(result))
|
|
result['status']='INSTALLED_ENGINE_VERIFICATION_PENDING';output.write_bytes(_compact(result));return result
|
|
|
|
|
|
def install_artwork_provider(stage,output):
|
|
"""Install the source artwork and its removable original-UI data provider.
|
|
|
|
New module only; original Blizzard files and existing modules are untouched.
|
|
Existing differing files are preserved. Installation requires normal client
|
|
shutdown and journals both textures and the small provider independently.
|
|
"""
|
|
stage=Path(stage);output=Path(output);client,identity=private_icon_client()
|
|
manifest,pin=read_public_json(stage/'manifest.json',16777216)
|
|
if manifest.get('kind')!='source-icon-artwork-batch':raise ValueError('Complete source artwork batch required')
|
|
files={p.name:p.read_bytes()for p in (ROOT/'client_addons/WoWHybridContent').iterdir()if p.is_file()}
|
|
if set(files)!={'SourceItemIcons.lua','SourceItemIconData.lua','WoWHybridContent.toc'}:raise ValueError('Reviewed content provider source files required')
|
|
record=next((r for r in manifest['files']if r['path']=='SourceItemIconData.lua'),None)
|
|
raw=(stage/'SourceItemIconData.lua').read_bytes()
|
|
if not record or len(raw)!=record['bytes']or _sha(raw)!=record['sha256']:raise ValueError('Generated source artwork map changed')
|
|
files['SourceItemIconData.lua']=raw
|
|
for name,raw in files.items():
|
|
if name.endswith('.lua'):subprocess.run(['luac','-p','-'],input=raw,check=True,capture_output=True)
|
|
target=client/'Interface/AddOns/WoWHybridContent'
|
|
if target.is_symlink() or any(p.is_symlink()for p in (target.parent,target.parent.parent)):raise ValueError('Linked provider target preserved')
|
|
existed=target.exists()
|
|
if existed and ({p.name:_sha(p.read_bytes())for p in target.iterdir()if p.is_file()}!={k:_sha(v)for k,v in files.items()}
|
|
or any(not p.is_file()or p.is_symlink()for p in target.iterdir())):
|
|
raise ValueError('Different existing provider preserved; back it up before updating')
|
|
if not output.resolve().is_relative_to(ROOT/'runtime')or output.exists()or not output.parent.is_dir():raise ValueError('New runtime provider journal required')
|
|
assets_journal=output.with_name(output.stem+'-textures.json')
|
|
if assets_journal.exists():raise ValueError('Preserve previous texture journal')
|
|
report=dict(kind='source-item-artwork-provider-installation',schema_version=1,status='PREPARED',
|
|
client=str(client),client_identity=identity,target=str(target),stage=str(stage),stage_manifest_sha256=pin,
|
|
existed=existed,files={k:_sha(v)for k,v in files.items()},texture_journal=str(assets_journal),
|
|
item_count=manifest['item_count'],installed=False,engine_loaded=False,gameplay_verified=False,
|
|
rollback='Close private client. If existed=false, verify all provider file hashes, then move the owned WoWHybridContent folder into recovery. Run octo_icon_assets.py --rollback-manifest TEXTURE_JOURNAL. Original clients and all other modules stay untouched.')
|
|
with output.open('xb')as stream:stream.write(_compact(report))
|
|
install_icon_stage(stage,assets_journal)
|
|
if bounded_digest(stage/'manifest.json',16777216)!=pin:raise ValueError('Artwork package changed during install')
|
|
if not existed:
|
|
target.mkdir(mode=0o700)
|
|
# TOC last: a half-installed module is never a complete addon.
|
|
for name in ('SourceItemIconData.lua','SourceItemIcons.lua','WoWHybridContent.toc'):
|
|
with (target/name).open('xb')as stream:stream.write(files[name])
|
|
report.update(status='INSTALLED_ORIGINAL_UI_VERIFICATION_PENDING',installed=True)
|
|
output.write_bytes(_compact(report));return report
|
|
|
|
def update_artwork_code(previous,output,code_update=None):
|
|
"""Update only owned Lua code; preserve all source data and installed assets.
|
|
|
|
Ordinary /reload activates the new module. No client restart, texture
|
|
reinstall, database query or metadata conversion is needed for this path.
|
|
"""
|
|
import shutil
|
|
previous=Path(previous);output=Path(output)
|
|
if (not previous.resolve().is_relative_to(ROOT/'runtime')or
|
|
not output.resolve().is_relative_to(ROOT/'runtime')or output.exists()or
|
|
not output.parent.is_dir()):raise ValueError('Owned prior/new runtime journals required')
|
|
old,_=read_public_json(previous,4194304)
|
|
target=ROOT/'runtime/native-client/_classic_beta_/Interface/AddOns/WoWHybridContent'
|
|
if old.get('kind')!='source-item-artwork-provider-installation'or old.get('target')!=str(target):
|
|
raise ValueError('Owned source provider journal required')
|
|
if code_update is not None:
|
|
code_update=Path(code_update)
|
|
if not code_update.resolve().is_relative_to(ROOT/'recovery'):raise ValueError('Owned intervening code journal required')
|
|
change,_=read_public_json(code_update,1048576)
|
|
if (change.get('kind')!='source-merchant-icon-provider-update'or
|
|
change.get('target')!=str((target/'SourceItemIcons.lua').relative_to(ROOT))or
|
|
change.get('old_sha256')!=old.get('files',{}).get('SourceItemIcons.lua')or
|
|
not hash_value(change.get('new_sha256'))):raise ValueError('Intervening code ownership differs')
|
|
old['files']['SourceItemIcons.lua']=change['new_sha256']
|
|
files={p.name:p.read_bytes()for p in target.iterdir()if p.is_file()and not p.is_symlink()}
|
|
if target.is_symlink()or {k:_sha(v)for k,v in files.items()}!=old.get('files')or len(list(target.iterdir()))!=len(files):
|
|
raise ValueError('Changed provider preserved; review before update')
|
|
raw=(ROOT/'client_addons/WoWHybridContent/SourceItemIcons.lua').read_bytes()
|
|
subprocess.run(['luac','-p','-'],input=raw,check=True)
|
|
recovery=ROOT/'recovery'/output.stem
|
|
recovery.mkdir(mode=0o700)
|
|
shutil.copytree(target,recovery/'previous-addon');shutil.copyfile(previous,recovery/'previous-manifest.json')
|
|
report=dict(old,status='CODE_UPDATE_RELOAD_VERIFICATION_PENDING',engine_loaded=False,
|
|
previous_provider_backup=str(recovery.relative_to(ROOT)),provider_revision='source-item-icon-post-hooks',
|
|
rollback='Verify current files against this journal, then restore previous-addon from previous_provider_backup and reload UI.')
|
|
report['files']=dict(old['files'],**{'SourceItemIcons.lua':_sha(raw)})
|
|
output.write_bytes(_compact(dict(report,status='PREPARED')))
|
|
(target/'SourceItemIcons.lua').write_bytes(raw)
|
|
output.write_bytes(_compact(report))
|
|
return report
|
|
|
|
|
|
def provider_artwork_map(raw):
|
|
"""Read the generated data-only Lua grammar without executing Lua."""
|
|
text=raw.decode('ascii')
|
|
if not text.startswith('GWSourceItemIconData = { version = 1, items = {\n')or not text.endswith('} }\n'):
|
|
raise ValueError('Generated source artwork data grammar required')
|
|
rows=text.splitlines()[1:-1];result={}
|
|
for row in rows:
|
|
match=re.fullmatch(r'\[([1-9][0-9]*)\] = "(interface/icons/gwhybrid_[0-9a-f]{64}\.blp)",',row)
|
|
if not match or int(match[1])>=2**31 or int(match[1])in result:raise ValueError('Distinct generated source item/artwork identities required')
|
|
result[int(match[1])]=match[2]
|
|
if not result or len(result)>100000:raise ValueError('Bounded generated artwork map required')
|
|
return result
|
|
|
|
def additive_artwork_map(old_raw,new_raw):
|
|
old=provider_artwork_map(old_raw);new=provider_artwork_map(new_raw)
|
|
if any(new.get(k)!=v for k,v in old.items()):raise ValueError('Existing source artwork bindings must remain unchanged')
|
|
return sorted(set(new)-set(old)),len(new)
|
|
|
|
def update_artwork_data(previous,stage,output):
|
|
"""Add verified source bindings to the owned provider; retain its Lua code."""
|
|
import shutil
|
|
previous=Path(previous);stage=Path(stage);output=Path(output)
|
|
for path in (previous,stage,output):
|
|
if not path.resolve().is_relative_to(ROOT/'runtime')or path.is_symlink():raise ValueError('Owned runtime provider/artwork journals required')
|
|
if output.exists()or not output.parent.is_dir():raise ValueError('New runtime provider journal required')
|
|
client,identity=private_icon_client();target=client/'Interface/AddOns/WoWHybridContent'
|
|
old,_=read_public_json(previous,4194304)
|
|
if old.get('kind')!='source-item-artwork-provider-installation'or old.get('target')!=str(target):raise ValueError('Owned source provider journal required')
|
|
files={p.name:p.read_bytes()for p in target.iterdir()if p.is_file()and not p.is_symlink()}
|
|
if (target.is_symlink()or {k:_sha(v)for k,v in files.items()}!=old.get('files')
|
|
or len(list(target.iterdir()))!=len(files)):raise ValueError('Changed provider preserved; review before update')
|
|
manifest,pin=read_public_json(stage/'manifest.json',16777216)
|
|
if manifest.get('kind')!='source-icon-artwork-batch':raise ValueError('Complete source artwork stage required')
|
|
verify_artwork_selection(manifest)
|
|
raw=(stage/'SourceItemIconData.lua').read_bytes()
|
|
record=next((r for r in manifest['files']if r['path']=='SourceItemIconData.lua'),None)
|
|
if not record or record['bytes']!=len(raw)or record['sha256']!=_sha(raw):raise ValueError('Staged artwork data changed')
|
|
added,count=additive_artwork_map(files['SourceItemIconData.lua'],raw)
|
|
if count!=manifest['item_count']:raise ValueError('Generated artwork count differs')
|
|
subprocess.run(['luac','-p','-'],input=raw,check=True,capture_output=True)
|
|
recovery=ROOT/'recovery'/output.stem;recovery.mkdir(mode=0o700)
|
|
shutil.copytree(target,recovery/'previous-addon');shutil.copyfile(previous,recovery/'previous-manifest.json')
|
|
textures=output.with_name(output.stem+'-textures.json')
|
|
if textures.exists():raise ValueError('Preserve previous texture journal')
|
|
report=dict(old,client_identity=identity,status='PREPARED',stage=str(stage),stage_manifest_sha256=pin,
|
|
previous_provider_backup=str(recovery.relative_to(ROOT)),previous_texture_journal=old.get('texture_journal'),
|
|
texture_journal=str(textures),item_count=count,added_item_ids=added,engine_loaded=False,gameplay_verified=False,
|
|
rollback='Close owned client; verify provider hashes, restore previous-addon from previous_provider_backup, and roll back the new texture_journal.')
|
|
report['files']=dict(old['files'],**{'SourceItemIconData.lua':_sha(raw)})
|
|
output.write_bytes(_compact(report))
|
|
install_icon_stage(stage,textures)
|
|
if bounded_digest(stage/'manifest.json',16777216)!=pin:raise ValueError('Artwork stage changed during installation')
|
|
temporary=target/'SourceItemIconData.lua.partial'
|
|
with temporary.open('xb')as stream:stream.write(raw)
|
|
temporary.replace(target/'SourceItemIconData.lua')
|
|
report['status']='DATA_UPDATE_NATIVE_VERIFICATION_PENDING';output.write_bytes(_compact(report))
|
|
return report
|
|
|
|
def rollback_icons(path):
|
|
path=Path(path)
|
|
if path.is_symlink() or not path.resolve().is_relative_to(ROOT/'runtime'):raise ValueError('Private runtime installation journal required')
|
|
client,_=private_icon_client();record,_=read_public_json(path,4194304)
|
|
if record.get('kind')!='private-source-icon-installation' or record.get('client')!=str(client) or not isinstance(record.get('files'),list) or not 1<=len(record['files'])<=MAX_CATALOGUE_TOKENS:raise ValueError('Owned private icon installation journal required')
|
|
targets=[]
|
|
for row in record['files']:
|
|
if row.get('created') is not True:continue
|
|
target=_icon_target(client,row['path'])
|
|
if not target.is_file() or bounded_digest(target,MAX_MEMBER_BYTES)!=row.get('sha256'):raise ValueError('Changed/missing installed icon preserved for review')
|
|
targets.append(target)
|
|
for target in targets:target.unlink()
|
|
record['status']='ROLLED_BACK';path.write_bytes(_compact(record));return record
|
|
|
|
def main():
|
|
parser=argparse.ArgumentParser(description=__doc__)
|
|
mode=parser.add_mutually_exclusive_group(required=True)
|
|
mode.add_argument('--icon-report',type=Path)
|
|
mode.add_argument('--catalogue',type=Path,help='Complete catalogue icon-requests.json; extract source artwork even for names present in Forever')
|
|
mode.add_argument('--stage-catalogue-artwork',type=Path,help='Stage all unambiguous source textures from a complete catalogue extraction')
|
|
parser.add_argument('--reference-builtin-priority',action='store_true',help='Explicit reviewed Octo5875 builtin archive policy; runtime launcher equivalence is not claimed')
|
|
mode.add_argument('--talent-profile',type=Path)
|
|
mode.add_argument('--install-stage',type=Path)
|
|
mode.add_argument('--install-artwork-provider',type=Path)
|
|
mode.add_argument('--update-artwork-data',type=Path,help='Additive source artwork stage; preserve existing data bindings and provider code')
|
|
parser.add_argument('--previous-provider-journal',type=Path)
|
|
mode.add_argument('--update-artwork-code',type=Path,help='Prior owned provider journal; replace only Lua code and retain all artwork')
|
|
mode.add_argument('--rollback-manifest',type=Path)
|
|
parser.add_argument('--exact-member')
|
|
parser.add_argument('--previous-code-update',type=Path,help='Optional owned recovery journal for the intervening merchant-only code update')
|
|
parser.add_argument('--client',type=Path,default=Path.home()/'Games/octo/drive_c/Octowow')
|
|
parser.add_argument('--output',type=Path)
|
|
parser.add_argument('--libmpq-source',type=Path,default=Path.home()/'Servers/tortoise-wow/dep/libmpq/libmpq')
|
|
args=parser.parse_args()
|
|
if args.reference_builtin_priority and not args.stage_catalogue_artwork:parser.error('Reference archive selection applies only to catalogue artwork staging')
|
|
if args.previous_provider_journal and not args.update_artwork_data:parser.error('Prior provider journal applies only to additive artwork data updates')
|
|
if args.rollback_manifest:
|
|
if args.output or args.exact_member:parser.error('Rollback accepts only its owned journal')
|
|
result=rollback_icons(args.rollback_manifest);print(result['status']);return
|
|
if not args.output:parser.error('--output required for staging or installation')
|
|
if args.update_artwork_data:
|
|
if not args.previous_provider_journal:parser.error('Data update requires --previous-provider-journal')
|
|
result=update_artwork_data(args.previous_provider_journal,args.update_artwork_data,args.output);print(result['status'],len(result['added_item_ids']),'additional source item icons');return
|
|
if args.update_artwork_code:
|
|
result=update_artwork_code(args.update_artwork_code,args.output,args.previous_code_update);print(result['status']);return
|
|
if args.install_artwork_provider:
|
|
result=install_artwork_provider(args.install_artwork_provider,args.output);print(result['status'],result['item_count'],'source item icons');return
|
|
if args.stage_catalogue_artwork:
|
|
result=stage_catalogue_artwork(args.stage_catalogue_artwork,args.output,reference_builtin_priority=args.reference_builtin_priority)
|
|
print('Source artwork staged:',result['item_count'],'item identities;',result['source_icon_count'],'source names;',result['distinct_texture_payloads'],'texture payloads;',len(result['excluded']),'exceptions; NOT installed.');return
|
|
if args.install_stage:
|
|
if args.exact_member:parser.error('Install uses only manifest-declared paths')
|
|
result=install_icon_stage(args.install_stage,args.output);print(result['status']);return
|
|
if args.talent_profile:
|
|
if not args.exact_member:parser.error('Talent texture staging requires --exact-member')
|
|
result=stage_talent_icon(args.talent_profile,args.client,args.exact_member,args.output,args.libmpq_source)
|
|
print('Staged exact source texture:',result['member'],result['assets'][0]['bytes'],'bytes; engine loading unverified.');return
|
|
if args.exact_member:parser.error('--exact-member requires --talent-profile')
|
|
result=inventory_icons(args.catalogue or args.icon_report,args.client,args.output,args.libmpq_source,catalogue=bool(args.catalogue))
|
|
print('Independent source icon assets:',result['token_count'],'tokens;',result['archive_count'],'archives;',result['candidate_content_count'],'candidate contents;',result['member_error_count'],'member errors; no winner/install/engine claim.')
|
|
|
|
if __name__=='__main__':main()
|