367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
191 lines
11 KiB
Python
191 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Batch source creature-model references against the installed Forever index.
|
|
|
|
Reuses DBC ingestion and CASC's exported in-storage index. Independent patch
|
|
candidates stay independent: this neither selects archive precedence nor
|
|
equates path/index presence with rendering, animation or mount compatibility.
|
|
"""
|
|
import argparse
|
|
from collections import Counter, defaultdict
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
|
|
from turtle_data import DBC
|
|
|
|
|
|
def model_path(value):
|
|
path=value.replace('\\','/').lower()
|
|
if not re.fullmatch(r'[a-z0-9_ .&,/-]{1,256}\.(?:mdx|m2)',path) or any(
|
|
part in ('','.','..') for part in path.split('/')):
|
|
raise ValueError('Canonical relative source model path required')
|
|
# Legacy DBC refers to MDX names while the MPQ payload is an M2.
|
|
return path[:-4]+'.m2' if path.endswith('.mdx') else path
|
|
|
|
|
|
def compare(sources, native_index, native_models):
|
|
if not 1<=len(sources)<=64 or not 1<=len(native_index)<=200000:
|
|
raise ValueError('Bounded candidate tables and native model index required')
|
|
names=defaultdict(set);ids=set()
|
|
for row in native_index:
|
|
ident=row.get('fdid');size=row.get('size')
|
|
if (type(ident)is not int or not 0<ident<=0xffffffff or ident in ids or
|
|
type(size)is not int or size<0 or row.get('resolved')is not True):
|
|
raise ValueError('Distinct resolved in-storage model identities required')
|
|
ids.add(ident);names[model_path(row['name'])].add(ident)
|
|
if len(native_models)>100000:raise ValueError('Native model row bound')
|
|
models={};links=defaultdict(set)
|
|
for row in native_models:
|
|
ident=row.get('ID');file_id=row.get('FileDataID')
|
|
if type(ident)is not int or ident<=0 or ident in models or type(file_id)is not int or file_id<0:
|
|
raise ValueError('Distinct native model records required')
|
|
models[ident]=file_id;links[file_id].add(ident)
|
|
candidates=[];variants=defaultdict(set)
|
|
for source, dbc in sources:
|
|
if dbc.fields!=16:raise ValueError('Reviewed legacy CreatureModelData width16 required')
|
|
for row in dbc.rows:
|
|
value=dbc.string(row[2])
|
|
if not value:continue
|
|
path=model_path(value);variants[row[0]].add(path)
|
|
candidates.append((source,row[0],path))
|
|
groups=defaultdict(list)
|
|
for source,ident,path in candidates:groups[(ident,path)].append(source)
|
|
result=[]
|
|
for (ident,path),provenance in sorted(groups.items()):
|
|
file_ids=sorted(names.get(path,()))
|
|
bindings=sorted({m for f in file_ids for m in links.get(f,())})
|
|
status=('AMBIGUOUS_NATIVE_PATH' if len(file_ids)>1 else
|
|
'INDEXED_ASSET_WITH_MODEL_RECORD' if bindings else
|
|
'INDEXED_ASSET_MISSING_MODEL_RECORD' if file_ids else
|
|
'NO_EXACT_PATH_IN_INDEX')
|
|
result.append(dict(source_model_id=ident,path=path,source_candidates=sorted(provenance),
|
|
source_path_conflict=len(variants[ident])>1,native_file_data_ids=file_ids,
|
|
native_model_ids=bindings,native_same_id_file_data_id=models.get(ident),
|
|
status=status,bytes_extracted=False,rendering_verified=False,
|
|
dependencies_complete=False,animation_compatibility_verified=False))
|
|
return dict(kind='source-creature-native-asset-reference-preflight',target_build='1.60.1.70334',
|
|
counts=dict(source_candidate_rows=len(candidates),source_model_ids=len(variants),
|
|
source_id_path_variants=len(result),source_path_conflicts=sum(len(v)>1 for v in variants.values()),
|
|
native_indexed_models=len(native_index),native_model_records=len(models),
|
|
statuses=dict(sorted(Counter(r['status']for r in result).items()))),records=result,
|
|
effective_patch_precedence_verified=False,client_modified=False,installed=False,
|
|
limits=['CASC index membership is not byte extraction or actual rendering.',
|
|
'An exact path is a reuse candidate, not proof of identical geometry, textures, bones or animation.',
|
|
'No exact path does not establish that no differently named compatible asset exists.',
|
|
'Source IDs and native file/model IDs remain separate; equal IDs do not imply equivalence.',
|
|
'Patch candidates are compared independently; conflicting paths require effective-source evidence.'])
|
|
|
|
|
|
def read_json(path,limit):
|
|
if path.is_symlink() or not path.is_file() or not 0<path.stat().st_size<=limit:
|
|
raise ValueError('Bounded regular local JSON required')
|
|
return json.loads(path.read_text())
|
|
|
|
|
|
def main():
|
|
p=argparse.ArgumentParser(description=__doc__)
|
|
p.add_argument('--source-models',type=Path,nargs='+',required=True)
|
|
p.add_argument('--native-index',type=Path,required=True)
|
|
p.add_argument('--native-models',type=Path,required=True)
|
|
p.add_argument('--output',type=Path,required=True)
|
|
a=p.parse_args();root=Path(__file__).resolve().parents[1]
|
|
if a.output.exists() or not a.output.resolve().is_relative_to(root/'runtime'):
|
|
p.error('Fresh workspace runtime output required')
|
|
inputs=a.source_models+[a.native_index,a.native_models]
|
|
pins={str(f):hashlib.sha256(f.read_bytes()).hexdigest()for f in inputs}
|
|
sources=[(str(f),DBC(f,16))for f in a.source_models]
|
|
report=compare(sources,read_json(a.native_index,33554432),read_json(a.native_models,33554432))
|
|
if any(hashlib.sha256(f.read_bytes()).hexdigest()!=pins[str(f)]for f in inputs):
|
|
raise ValueError('Input changed during comparison')
|
|
report['input_sha256']=pins
|
|
a.output.mkdir(mode=0o700,parents=True)
|
|
(a.output/'manifest.json').write_text(json.dumps(report,indent=2)+'\n')
|
|
print(json.dumps(report['counts'],sort_keys=True))
|
|
|
|
|
|
def native_display_texture_corrections(source_rows, native_rows, model_relations, texture_relations, missing_native_ids):
|
|
"""Repair only witnessed material slots on complete original native rows.
|
|
|
|
The caller supplies one explicitly selected source-table snapshot and
|
|
owner-validated stored source aliases. Model paths/IDs must already have
|
|
exact reuse proof. Alpha, scale, gender, flags and all other native fields
|
|
remain byte-value identical; this grants no full source-template authority.
|
|
"""
|
|
from copy import deepcopy
|
|
native={r['ID']:r for r in native_rows};models=defaultdict(list)
|
|
for r in model_relations:models[r['source_model_id']].append(r)
|
|
corrections=[];held=[];unchanged=[]
|
|
for source in source_rows:
|
|
ident=source['ID'];target=native.get(ident);reason=None
|
|
links=models.get(source['ModelID'],[]);paths={r['path']for r in links};ids={i for r in links for i in r['native_model_ids']}
|
|
if source['ExtendedDisplayInfoID'] or target and target['ExtendedDisplayInfoID']:reason='extra-info-selector-outside-generic-material-authority'
|
|
elif target is None:reason='native-display-definition-missing'
|
|
elif len(paths)!=1 or len(ids)!=1 or any(r['source_path_conflict']for r in links):reason='model-reuse-not-unique'
|
|
elif target['ModelID']not in ids:reason='same-display-id-is-a-different-native-model'
|
|
if reason:held.append(dict(source_display_id=ident,reason=reason));continue
|
|
record=deepcopy(target);changes=[];directory=next(iter(paths)).rsplit('/',1)[0]
|
|
for slot,token in enumerate(source['TextureVariation']):
|
|
if not token:continue
|
|
path=token.replace('\\','/').lower();path=path if '/'in path else directory+'/'+path
|
|
if not path.endswith('.blp'):path+='.blp'
|
|
relation=texture_relations.get(path);current=target['TextureVariationFileDataID'][slot]
|
|
if relation is None or relation['native_exact_filename_candidates']!=[current]:reason='source-slot-to-existing-native-material-not-proven';break
|
|
if current not in missing_native_ids:continue
|
|
aliases=relation.get('stored_source_aliases',[])
|
|
if len(aliases)!=1:reason='missing-native-material-without-unique-stored-source-alias';break
|
|
replacement=aliases[0]
|
|
if type(replacement)is not int or not 0<replacement<2**31:raise ValueError('Positive native-width source texture FileDataID required')
|
|
record['TextureVariationFileDataID'][slot]=replacement;changes.append(dict(slot=slot,source_path=path,before=current,after=replacement))
|
|
if reason:held.append(dict(source_display_id=ident,reason=reason));continue
|
|
if changes:
|
|
assert all(record[k]==target[k]for k in record if k!='TextureVariationFileDataID')
|
|
corrections.append(dict(source_display_id=ident,source_model_id=source['ModelID'],native_model_id=target['ModelID'],record=record,original_native_record=target,changes=changes,authority='stored-source-material-slots-only-not-full-source-template'))
|
|
else:unchanged.append(ident)
|
|
return dict(corrections=corrections,held=held,unchanged=unchanged,source_scope=len(source_rows),all_nonmaterial_native_fields_preserved=True)
|
|
|
|
|
|
if __name__=='__main__':main()
|
|
|
|
|
|
def reconcile_native_texture_storage(relations, observations):
|
|
"""Correct legacy negative lookup labels without claiming payload absence.
|
|
|
|
FileID Root membership and SDK FullInfo are metadata, not a successful
|
|
decoded payload read. Preserve existing positive content proofs and aliases.
|
|
"""
|
|
legacy = {'NATIVE_ROOT_KNOWN_LOCAL_PAYLOAD_MISSING',
|
|
'REUSED_KNOWN_NATIVE_PAYLOAD_MISSING',
|
|
'REUSED_NATIVE_LOOKUP_UNSUPPORTED'}
|
|
indexed = {}
|
|
for observation in observations:
|
|
ident = observation['file_data_id']
|
|
if ident in indexed:
|
|
raise ValueError('Duplicate native texture metadata observation')
|
|
indexed[ident] = observation
|
|
rows = []
|
|
for original in relations:
|
|
row = dict(original)
|
|
if row.get('asset_state') not in legacy:
|
|
rows.append(row)
|
|
continue
|
|
ids = row.get('native_exact_filename_candidates', [])
|
|
evidence = [indexed.get(ident) for ident in ids]
|
|
supported = bool(evidence) and all(
|
|
r is not None and r.get('lookup_supported') is True and
|
|
type(r.get('root_features')) is int and r['root_features'] & 0x2
|
|
for r in evidence)
|
|
row['previous_asset_state'] = row['asset_state']
|
|
row['physical_payload_absence_proven'] = False
|
|
if not supported:
|
|
row['asset_state'] = 'NATIVE_FILEID_LOOKUP_UNSUPPORTED_OR_UNOBSERVED'
|
|
elif not all(r.get('known') is True for r in evidence):
|
|
row['asset_state'] = 'NATIVE_FILEID_UNRESOLVED'
|
|
elif all(r.get('full_info_available') is True for r in evidence):
|
|
row['asset_state'] = 'NATIVE_ROOT_METADATA_AVAILABLE_PAYLOAD_UNVERIFIED'
|
|
else:
|
|
row['asset_state'] = 'NATIVE_ROOT_KNOWN_PAYLOAD_AVAILABILITY_UNRESOLVED'
|
|
row['native_metadata_evidence'] = [dict(r) for r in evidence if r is not None]
|
|
rows.append(row)
|
|
return rows
|