Files
WoW-Hybrid-gateway/tests/item_appearance_preflight_test.py
praxisandClaude Fable 5.2 7f2139d8d0 Offline test fixtures
883 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

544 lines
45 KiB
Python

#!/usr/bin/env python3
"""Pure dependency fixtures; matching numbers/names never prove asset support."""
import copy,hashlib,json,struct,sys,tempfile,unittest
from pathlib import Path
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'ops'))
import item_appearance_preflight as appearance
from turtle_data import DBC,_canonical
class AppearanceTest(unittest.TestCase):
def test_source_asset_batch_includes_unpublished_items_and_deduplicates(self):
items=[dict(entry=i,display_id=100,inventory_type=13,subclass=4,**{'class':2})for i in(58214,600130)]
before=copy.deepcopy(items);r=appearance.source_equipment_asset_requests(items,self.dbc)
self.assertEqual(items,before);self.assertEqual(len(r['records']),2);self.assertEqual(len(r['requests']),3)
model=next(q for q in r['requests']if q['kind']=='model');self.assertEqual(model['paths'],['item/objectcomponents/weapon/blade.m2'])
self.assertEqual([u['item_id']for u in model['users']],[58214,600130]);self.assertFalse(r['published_metadata_required']);self.assertFalse(r['converted'])
self.assertEqual(r,appearance.source_equipment_asset_requests(list(reversed(items)),self.dbc))
with self.assertRaises(ValueError):appearance.source_equipment_asset_requests(items+[items[0]],self.dbc)
def test_catalogue_chunks_deduplicate_and_retain_all_users(self):
rows=[dict(raw_fields=dict(entry=i+1,display_id=100,inventory_type=13,subclass=4,**{'class':2})) for i in range(4100)]
source=dict(records=rows)
result=appearance.catalogue_equipment_asset_requests(source,self.dbc)
zero=appearance.catalogue_equipment_asset_requests(dict(records=rows+[dict(raw_fields=dict(rows[0]['raw_fields'],entry=0))]),self.dbc)
self.assertEqual(zero['blocked_nonwire_source_item_ids'],[0])
self.assertEqual(len(result['records']),4100)
self.assertEqual(len(result['requests']),3)
self.assertEqual(len(result['requests'][0]['users']),4100)
self.assertEqual(result,appearance.catalogue_equipment_asset_requests(dict(records=list(reversed(rows))),self.dbc))
with self.assertRaises(ValueError):appearance.catalogue_equipment_asset_requests(dict(records=rows+[rows[0]]),self.dbc)
def test_body_model_context_is_not_guessed_and_layers_keep_gender_choices(self):
item=dict(entry=600130,display_id=100,inventory_type=19,subclass=0,**{'class':4})
r=appearance.source_equipment_asset_requests([item],self.dbc)
self.assertTrue(r['records'][0]['unresolved_attached_models']);self.assertEqual(len(r['requests']),1)
q=r['requests'][0];self.assertEqual(q['kind'],'body-material');self.assertEqual(q['paths'],['item/texturecomponents/armuppertexture/armlayer'+s+'.blp'for s in('_f','_m','_u','')])
def test_native_asset_names_match_exact_paths_and_head_families_only(self):
import io
req=[dict(kind='model',paths=['item/objectcomponents/weapon/blade.m2']),dict(kind='model-family',paths=['item/objectcomponents/head/helm_test']),dict(kind='material',paths=['item/objectcomponents/head/blue.blp'])]
data=b'1;item/objectcomponents/weapon/blade.m2\n2;item/objectcomponents/head/helm_test_tam.m2\n3;item/objectcomponents/head/helm_test_huf.m2\n4;item/objectcomponents/head/helm_test_similar_hum.m2\n5;item/objectcomponents/head/blue_other.blp\n'
r=appearance.native_equipment_asset_names(req,io.BytesIO(data));self.assertEqual([len(q['native_references'])for q in r['requests']],[1,2,0]);self.assertFalse(r['engine_loaded'])
bad=copy.deepcopy(req);bad[0]['paths']=['item/objectcomponents/weapon/../bad.m2']
with self.assertRaises(ValueError):appearance.native_equipment_asset_names(bad,io.BytesIO(data))
with self.assertRaises(ValueError):appearance.native_equipment_asset_names(req,io.BytesIO(b'0;item/objectcomponents/weapon/blade.m2\n'))
def test_shared_source_display_links_preserve_item_identity_and_existing_variants(self):
from item_sparse_compat import encode
def raw(i,display):
r=dict(entry=i,display_id=display,inventory_type=21,**{'class':2})
return dict(identity=['Item',i],raw_fields=r,raw_sha256=hashlib.sha256(_canonical(r)).hexdigest())
source=dict(snapshot_verification=dict(content_and_schema_and_ids_verified=True),records=[raw(1,100),raw(2,100),raw(3,999),raw(4,100)])
target=dict(ItemAppearance=[dict(ID=10,ItemDisplayInfoID=100,TransmogPlayerConditionID=0)],ItemDisplayInfo=[dict(ID=100)],ItemModifiedAppearance=[dict(ID=5,ItemID=1,ItemAppearanceModifierID=0,ItemAppearanceID=10),dict(ID=6,ItemID=4,ItemAppearanceModifierID=3,ItemAppearanceID=10)])
package=[dict(table_name=t,id=i,record=dict(ClassID=2,InventoryType=21)if t=='Item'else{})for i in(2,3,4)for t in('Item','ItemSparse')]
registry=dict(version=1,slots={});before=copy.deepcopy((source,target,package,registry))
r=appearance.missing_weapon_links(source,target,package,registry,100)
self.assertEqual((source,target,package,registry),before)
self.assertEqual(len(r['records']),1);row=r['records'][0]
self.assertEqual((row['id'],row['record']['ItemID'],row['record']['ItemAppearanceID']),(101,2,10))
self.assertEqual(bytes.fromhex(row['wire_hex']),encode(row['record'],appearance.MODIFIED_SCHEMA))
self.assertEqual(r['bindings'][0]['source_witness_item_ids'],[1])
self.assertEqual(r['blocked'][0]['item_id'],3);self.assertFalse(r['installable'])
self.assertEqual(r,appearance.missing_weapon_links(source,target,package,r['registry'],100))
scoped=appearance.missing_weapon_links(source,target,package,registry,100,selected_items={2})
self.assertEqual(scoped['records'],r['records'])
self.assertFalse(scoped['blocked'])
self.assertEqual(scoped['bindings'][0]['source_witness_item_ids'],[1]) # Unowned donor remains evidence, never an import target.
self.assertFalse(appearance.missing_weapon_links(source,target,package,registry,100,selected_items={3})['records'])
with self.assertRaises(ValueError):appearance.missing_weapon_links(source,target,package,registry,100,selected_items={True})
parent=dict(build='1.60.1.70334',rows=[])
combined=appearance.compose_weapon_links(parent,r)
self.assertEqual(combined['rows'],r['records']);self.assertEqual(parent['rows'],[])
bad=copy.deepcopy(r);bad['records'][0]['record']['ItemID']=999
with self.assertRaisesRegex(ValueError,'contract'):appearance.compose_weapon_links(parent,bad)
source['records'][1]['raw_fields']['display_id']=999
with self.assertRaisesRegex(ValueError,'hash'):appearance.missing_weapon_links(source,target,package,registry,100)
def test_new_parent_requires_exact_native_geometry_texture_and_schema(self):
source=copy.deepcopy(self.source);target=copy.deepcopy(self.target)
raw=list(self.dbc.by_id[100]);raw[6]=0;raw[14]=0;self.dbc.by_id[100]=tuple(raw)
display=dict(ID=100,ModelResourcesID=[30,0],ModelMaterialResourcesID=[40,0],GeosetGroup=[0]*6,AttachmentGeosetGroup=[0]*6,HelmetGeosetVis=[0,0],ModelType=[0,0])
target['ItemDisplayInfo']=[dict(display,ID=20),display]
target['ItemAppearance']=[dict(ID=10,ItemDisplayInfoID=20,TransmogPlayerConditionID=0,DisplayType=11)]
target['ItemModifiedAppearance']=[]
package=[dict(table_name=t,id=500001,record=dict(ClassID=2,InventoryType=13,IconFileDataID=777)if t=='Item'else{})for t in('Item','ItemSparse')]
names={1234:['item/objectcomponents/weapon/blade.m2'],2345:['item/objectcomponents/weapon/red.blp']}
target['ModelFileData']=target['ModelFileData'][:1]
c,b=appearance.native_weapon_parent_candidates(source,self.dbc,target,package,names)
self.assertEqual(list(c),[500001]);self.assertEqual(c[500001]['display_type'],11)
result=appearance.missing_weapon_links(source,target,package,dict(version=1,slots={}),100,parent_candidates=c,parent_native_max=200)
self.assertEqual([r['table_name']for r in result['records']],['ItemAppearance','ItemModifiedAppearance'])
parent=result['records'][0];self.assertEqual(parent['id'],201);self.assertEqual(parent['record']['ItemDisplayInfoID'],100)
self.assertEqual(parent['wire_hex'],struct.pack('<b4i',11,100,777,0,0).hex())
combined=appearance.compose_weapon_links(dict(build='1.60.1.70334',rows=[]),result)
self.assertEqual(len(combined['rows']),2)
names[2345]=['item/objectcomponents/weapon/blue.blp']
rejected,_=appearance.native_weapon_parent_candidates(source,self.dbc,target,package,names)
self.assertFalse(rejected) # A different recolor must not pass by geometry alone.
def test_visible_armor_uses_same_class_source_display_witness_not_weapon_alias(self):
source=copy.deepcopy(self.source);target=copy.deepcopy(self.target)
for r in source['records']:
r['raw_fields'].update(**{'class':4},inventory_type=5,display_id=100)
r['raw_sha256']=hashlib.sha256(_canonical(r['raw_fields'])).hexdigest()
target['ItemAppearance']=[dict(ID=10,ItemDisplayInfoID=100,TransmogPlayerConditionID=0)]
target['ItemDisplayInfo']=[dict(ID=100)]
target['ItemModifiedAppearance']=[dict(ID=1,ItemID=500001,ItemAppearanceModifierID=0,ItemAppearanceID=10)]
package=[dict(table_name=t,id=500002,record=dict(ClassID=4,InventoryType=5)if t=='Item'else{})for t in('Item','ItemSparse')]
args=(source,target,package,dict(version=1,slots={}),100)
self.assertFalse(appearance.missing_weapon_links(*args)['records'])
result=appearance.missing_weapon_links(*args,visible_armor=True)
self.assertEqual(len(result['records']),1);self.assertEqual(result['records'][0]['record']['ItemID'],500002)
target['ItemAppearance'][0]['ItemDisplayInfoID']=200
target['ItemDisplayInfo'].append(dict(ID=200))
self.assertFalse(appearance.missing_weapon_links(*args,visible_armor=True)['records'])
baseline={500001:dict(ID=500001,ClassID=4,SubclassID=2,InventoryType=5)}
for r in source['records']:
r['raw_fields']['subclass']=2;r['raw_sha256']=hashlib.sha256(_canonical(r['raw_fields'])).hexdigest()
modern=appearance.missing_weapon_links(*args,visible_armor=True,modern_basics=baseline,selected_items={500002})
self.assertEqual(modern['bindings'][0]['native_display_info_id'],200)
self.assertEqual(modern['bindings'][0]['witness_policy'],'source-shared-display-preserve-modern-native-item')
self.assertEqual(modern['bindings'][0]['source_witness_item_ids'],[500001])
for field in('ClassID','SubclassID','InventoryType'):
bad=copy.deepcopy(baseline);bad[500001][field]=99
self.assertFalse(appearance.missing_weapon_links(*args,visible_armor=True,modern_basics=bad)['records'])
# Nonvisual jewelry is not a missing worn model, even with metadata.
source['records'][1]['raw_fields']['inventory_type']=11
source['records'][1]['raw_sha256']=hashlib.sha256(_canonical(source['records'][1]['raw_fields'])).hexdigest()
self.assertFalse(appearance.missing_weapon_links(*args,visible_armor=True)['records'])
def test_existing_shield_recolor_requires_both_exact_resource_paths(self):
source=copy.deepcopy(self.source);source['records']=source['records'][:1]
item=source['records'][0]['raw_fields'];item.update(**{'class':4},subclass=6,inventory_type=14)
source['records'][0]['raw_sha256']=hashlib.sha256(_canonical(item)).hexdigest()
raw=list(self.dbc.by_id[100]);raw[6]=0;raw[14]=0;self.dbc.by_id[100]=tuple(raw)
target=copy.deepcopy(self.target)
target['ItemDisplayInfo']=[dict(ID=200,ModelResourcesID=[30,0],ModelMaterialResourcesID=[40,0],GeosetGroup=[0]*6,AttachmentGeosetGroup=[0]*6,HelmetGeosetVis=[0,0],ModelType=[0,-1])]
target['ItemAppearance']=[dict(ID=10,ItemDisplayInfoID=200,DisplayType=13,TransmogPlayerConditionID=0)]
target['ItemModifiedAppearance']=[];target['ModelFileData']=target['ModelFileData'][:1]
package=[dict(table_name=t,id=item['entry'],record=dict(ClassID=4,SubclassID=6,InventoryType=14)if t=='Item'else{})for t in('Item','ItemSparse')]
names={1234:['item/objectcomponents/shield/blade.m2'],2345:['item/objectcomponents/shield/red.blp']}
selected={item['entry']}
variants,blocked=appearance.native_equipment_variant_candidates(source,self.dbc,target,package,names,selected)
self.assertFalse(blocked);self.assertEqual(variants[item['entry']]['native_display_info_id'],200)
self.assertFalse(appearance.native_equipment_variant_candidates(source,self.dbc,target,[],names,selected)[0])
references,failed=appearance.native_equipment_variant_candidates(source,self.dbc,target,[],names,selected,allow_unpublished_references=True)
self.assertFalse(failed);self.assertEqual(references,variants)
with self.assertRaises(ValueError):appearance.native_equipment_variant_candidates(source,self.dbc,target,[],names,selected,allow_unpublished_references=True,unparented_candidates={})
result=appearance.missing_weapon_links(source,target,package,dict(version=1,slots={}),100,visible_armor=True,selected_items=selected,resource_variants=variants)
self.assertEqual(len(result['records']),1);self.assertEqual(result['records'][0]['record']['ItemAppearanceID'],10)
self.assertEqual(result['bindings'][0]['witness_policy'],'exact-source-model-and-material-existing-native-variant')
composed=appearance.compose_weapon_links(dict(build='1.60.1.70334',rows=[]),result)
self.assertEqual(composed['rows'],result['records'])
invalid=copy.deepcopy(result);invalid['bindings'][0]['native_resource_reference']['policy']='geometry-only'
with self.assertRaises(ValueError):appearance.compose_weapon_links(dict(build='1.60.1.70334',rows=[]),invalid)
bad=copy.deepcopy(variants);bad[item['entry']]['native_display_info_id']=201
with self.assertRaises(ValueError):appearance.missing_weapon_links(source,target,package,dict(version=1,slots={}),100,visible_armor=True,resource_variants=bad)
names[2345]=['item/objectcomponents/shield/blue.blp']
self.assertFalse(appearance.native_equipment_variant_candidates(source,self.dbc,target,package,names,selected)[0])
names[2345]=['item/objectcomponents/shield/red.blp'];target['ItemAppearance'].append(dict(target['ItemAppearance'][0],ID=11))
self.assertFalse(appearance.native_equipment_variant_candidates(source,self.dbc,target,package,names,selected)[0])
target['ItemAppearance'].pop();target['ItemDisplayInfo'][0]['ItemVisual']=42
self.assertFalse(appearance.native_equipment_variant_candidates(source,self.dbc,target,package,names,selected)[0])
def test_helmet_variant_preserves_all_native_model_races_and_visibility(self):
source=copy.deepcopy(self.source);source['records']=source['records'][:1]
item=source['records'][0]['raw_fields'];item.update(**{'class':4},subclass=4,inventory_type=1)
raw=list(self.dbc.by_id[100]);raw[6]=0;raw[14]=0;raw[12:14]=[248,306];self.dbc.by_id[100]=tuple(raw)
source['records'][0]['raw_sha256']=hashlib.sha256(_canonical(item)).hexdigest()
target=copy.deepcopy(self.target)
target['ItemDisplayInfo']=[dict(ID=200,ModelResourcesID=[30,0],ModelMaterialResourcesID=[40,0],GeosetGroup=[0]*6,AttachmentGeosetGroup=[0]*6,HelmetGeosetVis=[248,306],ModelType=[0,0])]
target['ItemAppearance']=[dict(ID=10,ItemDisplayInfoID=200,DisplayType=0,TransmogPlayerConditionID=0)]
target['ModelFileData']=[dict(ID=i,FileDataID=i,ModelResourcesID=30)for i in (1234,1235,1236)]
package=[dict(table_name=t,id=item['entry'],record=dict(ClassID=4,InventoryType=1)if t=='Item'else{})for t in('Item','ItemSparse')]
names={1234:['item/objectcomponents/head/blade_hum.m2'],1235:['item/objectcomponents/head/blade_taf.m2'],1236:['item/objectcomponents/head/blade_za_m.m2'],2345:['item/objectcomponents/head/red.blp']}
variants,blocked=appearance.native_equipment_variant_candidates(source,self.dbc,target,package,names,{item['entry']})
self.assertFalse(blocked);ref=variants[item['entry']]['resources'][0]
self.assertEqual(ref['model_file_ids'],[1234,1235,1236]);self.assertEqual(ref['helmet_visibility'],[248,306])
target['ItemDisplayInfo'].append(dict(target['ItemDisplayInfo'][0],ID=100))
target['ItemAppearance'].append(dict(target['ItemAppearance'][0],ID=11,ItemDisplayInfoID=100))
exact,_=appearance.native_equipment_variant_candidates(source,self.dbc,target,package,names,{item['entry']})
self.assertEqual(exact[item['entry']]['native_appearance_id'],11)
target['ItemDisplayInfo'].pop();target['ItemAppearance'].pop()
names[1235]=['item/objectcomponents/head/unrelated_taf.m2']
self.assertFalse(appearance.native_equipment_variant_candidates(source,self.dbc,target,package,names,{item['entry']})[0])
names[1235]=['item/objectcomponents/head/blade_taf.m2'];target['ItemDisplayInfo'][0]['HelmetGeosetVis']=[0,0]
self.assertFalse(appearance.native_equipment_variant_candidates(source,self.dbc,target,package,names,{item['entry']})[0])
target['ItemDisplayInfo'][0]['HelmetGeosetVis']=[248,306]
donor=copy.deepcopy(source['records'][0]);donor['identity']=['Item',500002]
donor['raw_fields'].update(entry=500002,display_id=200)
donor['raw_sha256']=hashlib.sha256(_canonical(donor['raw_fields'])).hexdigest()
source['records'].append(donor);self.dbc.by_id[200]=self.dbc.by_id[100]
target['ItemModifiedAppearance']=[dict(ID=1,ItemID=500002,ItemAppearanceModifierID=0,ItemAppearanceID=10)]
candidate=copy.deepcopy(target['ItemDisplayInfo'][0]);candidate['ID']=201
target['ItemDisplayInfo'].append(candidate);target['ItemDisplayInfo'][0]['ModelMaterialResourcesID']=[41,0]
target['TextureFileData'].append(dict(ID=2346,FileDataID=2346,MaterialResourcesID=41))
names[2346]=['item/objectcomponents/head/blue.blp'];package[0]['record']['IconFileDataID']=777
args=(source,self.dbc,target,package,names,{item['entry']})
pending={};variants,blocked=appearance.native_equipment_variant_candidates(*args,unparented_candidates=pending)
self.assertFalse(variants);self.assertFalse(blocked)
self.assertEqual(pending[item['entry']]['display_type'],0)
self.assertEqual(pending[item['entry']]['resources'][0]['model_file_ids'],[1234,1235,1236])
self.assertEqual(pending[item['entry']]['resources'][-1]['source_geometry_witness_item_ids'],[500002])
result=appearance.missing_weapon_links(source,target,package,dict(version=1,slots={}),100,
visible_armor=True,selected_items={item['entry']},parent_candidates=pending,parent_native_max=200)
self.assertEqual(result['records'][0]['record']['ItemDisplayInfoID'],201)
self.assertEqual(len(appearance.compose_weapon_links(dict(build='1.60.1.70334',rows=[]),result)['rows']),2)
target['ItemDisplayInfo'][1]['HelmetGeosetVis']=[0,0]
pending={};appearance.native_equipment_variant_candidates(*args,unparented_candidates=pending)
self.assertFalse(pending)
def test_neutral_layered_armor_requires_exact_regions_and_unisex_materials(self):
source=copy.deepcopy(self.source);source['records']=source['records'][:1]
item=source['records'][0]['raw_fields'];item.update(**{'class':4},subclass=4,inventory_type=7)
source['records'][0]['raw_sha256']=hashlib.sha256(_canonical(item)).hexdigest()
raw=[0]*23;raw[0]=100;raw[19]=20;raw[20]=20;self.dbc.by_id[100]=tuple(raw)
target=copy.deepcopy(self.target)
target['ItemDisplayInfo']=[dict(ID=200,ModelResourcesID=[0,0],ModelMaterialResourcesID=[0,0],GeosetGroup=[0]*6,AttachmentGeosetGroup=[0]*6,HelmetGeosetVis=[0,0],ModelType=[-1,-1])]
target['ItemAppearance']=[dict(ID=10,ItemDisplayInfoID=200,DisplayType=5,TransmogPlayerConditionID=0)]
target['ItemDisplayInfoMaterialRes']=[dict(ID=1,ItemDisplayInfoID=200,ComponentSection=5,MaterialResourcesID=40),dict(ID=2,ItemDisplayInfoID=200,ComponentSection=6,MaterialResourcesID=41)]
package=[dict(table_name=t,id=item['entry'],record=dict(ClassID=4,InventoryType=7)if t=='Item'else{})for t in('Item','ItemSparse')]
names={2345:['item/texturecomponents/leguppertexture/armlayer_u.blp'],2346:['item/texturecomponents/leglowertexture/armlayer_u.blp']}
args=(source,self.dbc,target,package,names,{item['entry']})
variants,blocked=appearance.native_equipment_variant_candidates(*args)
self.assertFalse(blocked);self.assertEqual(variants[item['entry']]['native_display_info_id'],200)
self.assertEqual([r['component_section']for r in variants[item['entry']]['resources']],[5,6])
bad=copy.deepcopy(names);bad[2345]=['item/texturecomponents/leguppertexture/blue_u.blp']
self.assertFalse(appearance.native_equipment_variant_candidates(source,self.dbc,target,package,bad,{item['entry']})[0])
target['ItemDisplayInfoMaterialRes'][1]['ComponentSection']=5
self.assertFalse(appearance.native_equipment_variant_candidates(*args)[0])
target['ItemDisplayInfoMaterialRes'][1]['ComponentSection']=6
target['ItemDisplayInfo'][0]['GeosetGroup'][0]=1
self.assertFalse(appearance.native_equipment_variant_candidates(*args)[0])
target['ItemDisplayInfo'][0]['GeosetGroup'][0]=0
# Preserve both genuine native sex variants, including their selectors.
target['TextureFileData']=[dict(ID=i,FileDataID=i,MaterialResourcesID=40)for i in(2345,2347)]+[dict(ID=2346,FileDataID=2346,MaterialResourcesID=41)]
target['ComponentTextureFileData']=[dict(ID=i,GenderIndex=g,ClassID=0,RaceID=0)for i,g in((2345,0),(2347,1))]
names[2345]=['item/texturecomponents/leguppertexture/armlayer_m.blp'];names[2347]=['item/texturecomponents/leguppertexture/armlayer_f.blp']
variants,_=appearance.native_equipment_variant_candidates(*args)
family=variants[item['entry']]['resources'][0]['texture_family']
self.assertEqual({r['gender_index']for r in family},{0,1})
target['ComponentTextureFileData'][1]['GenderIndex']=0
self.assertFalse(appearance.native_equipment_variant_candidates(*args)[0])
target['ComponentTextureFileData'][1]['GenderIndex']=1
# Nonzero Classic glove/boot geosets need a real default native witness.
item['inventory_type']=10;raw[6]=3;self.dbc.by_id[100]=tuple(raw)
source['records'][0]['raw_sha256']=hashlib.sha256(_canonical(item)).hexdigest()
target['ItemDisplayInfo'][0]['GeosetGroup'][0]=3
self.assertFalse(appearance.native_equipment_variant_candidates(*args)[0])
witness=dict(item,entry=500002,display_id=101)
source['records'].append(dict(identity=['Item',500002],raw_fields=witness,raw_sha256=hashlib.sha256(_canonical(witness)).hexdigest()))
self.dbc.by_id[101]=tuple([101]+raw[1:])
target['ItemDisplayInfo'].append(dict(target['ItemDisplayInfo'][0],ID=101))
target['ItemAppearance'].append(dict(ID=11,ItemDisplayInfoID=101,DisplayType=8,TransmogPlayerConditionID=0))
target['ItemModifiedAppearance']=[dict(ID=1,ItemID=500002,ItemAppearanceModifierID=0,ItemAppearanceID=11)]
self.assertFalse(appearance.native_equipment_variant_candidates(*args)[0]) # Wrong native slot/display type.
target['ItemAppearance'][0]['DisplayType']=8
variants,_=appearance.native_equipment_variant_candidates(*args)
self.assertEqual(variants[item['entry']]['resources'][-1]['source_display_witness_item_ids'],[500002])
# Same witness rule applies to real miscellaneous shirts and tabards;
# never infer a body geoset merely from its number or matching color.
for slot,display_type in((4,2),(19,10)):
item.update(subclass=0,inventory_type=slot);witness.update(subclass=0,inventory_type=slot)
for r in source['records']:r['raw_sha256']=hashlib.sha256(_canonical(r['raw_fields'])).hexdigest()
target['ItemAppearance'][0]['DisplayType']=display_type
target['ItemAppearance'][1]['DisplayType']=display_type
variants,_=appearance.native_equipment_variant_candidates(*args)
self.assertEqual(variants[item['entry']]['resources'][-1]['source_display_witness_item_ids'],[500002])
target['ItemModifiedAppearance'][0]['ItemAppearanceModifierID']=1
self.assertFalse(appearance.native_equipment_variant_candidates(*args)[0])
target['ItemModifiedAppearance'][0]['ItemAppearanceModifierID']=0
# Complete native material resources without an appearance parent can
# receive a new internal parent; keep the real source display separate.
target['ItemAppearance']=target['ItemAppearance'][1:]
package[0]['record'].update(ClassID=4,SubclassID=0,InventoryType=19,IconFileDataID=777)
pending={};variants,blocked=appearance.native_equipment_variant_candidates(*args,unparented_candidates=pending)
self.assertFalse(variants);self.assertFalse(blocked)
self.assertEqual(pending[item['entry']]['native_display_info_id'],200)
self.assertEqual(pending[item['entry']]['source_display_id'],100)
result=appearance.missing_weapon_links(source,target,package,dict(version=1,slots={}),100,
visible_armor=True,selected_items={item['entry']},parent_candidates=pending,parent_native_max=200)
self.assertEqual([r['table_name']for r in result['records']],['ItemAppearance','ItemModifiedAppearance'])
parent=result['records'][0];self.assertEqual(parent['record']['ItemDisplayInfoID'],200)
self.assertEqual(parent['record']['DisplayType'],10)
composed=appearance.compose_weapon_links(dict(build='1.60.1.70334',rows=[]),result)
self.assertEqual(composed['rows'],result['records'])
altered=copy.deepcopy(result);altered['bindings'][0]['native_resource_reference']['native_display_info_id']=101
with self.assertRaisesRegex(ValueError,'parent identity'):appearance.compose_weapon_links(dict(build='1.60.1.70334',rows=[]),altered)
target['ItemDisplayInfoMaterialRes'].pop()
pending={};self.assertFalse(appearance.native_equipment_variant_candidates(*args,unparented_candidates=pending)[0]);self.assertFalse(pending)
def test_native_shoulder_family_requires_correct_left_and_right_selectors(self):
source=copy.deepcopy(self.source);source['records']=source['records'][:1]
item=source['records'][0]['raw_fields'];item.update(**{'class':4},subclass=4,inventory_type=3)
source['records'][0]['raw_sha256']=hashlib.sha256(_canonical(item)).hexdigest()
raw=list(self.dbc.by_id[100]);raw[1]=len(self.dbc.strings);raw[2]=raw[1]+len(b'LBlade.mdx\0')
self.dbc.strings+=b'LBlade.mdx\0RBlade.mdx\0'
raw[4]=raw[3];raw[6]=0;raw[14]=0;self.dbc.by_id[100]=tuple(raw)
target=copy.deepcopy(self.target)
target['ItemDisplayInfo']=[dict(ID=200,ModelResourcesID=[30,30],ModelMaterialResourcesID=[40,40],GeosetGroup=[0]*6,AttachmentGeosetGroup=[0]*6,HelmetGeosetVis=[0,0],ModelType=[0,0])]
target['ItemAppearance']=[dict(ID=10,ItemDisplayInfoID=200,DisplayType=1,TransmogPlayerConditionID=0)]
target['ComponentModelFileData']=[dict(ID=i,PositionIndex=p,GenderIndex=2,ClassID=0,RaceID=0)for i,p in((1234,0),(1235,1))]
target['ItemDisplayInfoMaterialRes']=[]
package=[dict(table_name=t,id=item['entry'],record=dict(ClassID=4,InventoryType=3)if t=='Item'else{})for t in('Item','ItemSparse')]
names={1234:['item/objectcomponents/shoulder/lblade.m2'],1235:['item/objectcomponents/shoulder/rblade.m2'],2345:['item/objectcomponents/shoulder/red.blp']}
args=(source,self.dbc,target,package,names,{item['entry']})
variants,blocked=appearance.native_equipment_variant_candidates(*args)
self.assertFalse(blocked);self.assertEqual(len(variants[item['entry']]['resources']),2)
# A recolor can have complete native resources but no appearance
# parent. Reuse the paired geometry; the source donor establishes the
# shoulder display type, never the recolor's material or item identity.
donor=copy.deepcopy(source['records'][0]);donor['identity']=['Item',500002]
donor['raw_fields'].update(entry=500002,display_id=200)
donor['raw_sha256']=hashlib.sha256(_canonical(donor['raw_fields'])).hexdigest()
source['records'].append(donor)
self.dbc.by_id[200]=self.dbc.by_id[100]
target['ItemModifiedAppearance']=[dict(ID=1,ItemID=500002,ItemAppearanceModifierID=0,ItemAppearanceID=10)]
candidate=copy.deepcopy(target['ItemDisplayInfo'][0]);candidate['ID']=201
target['ItemDisplayInfo'].append(candidate)
target['ItemDisplayInfo'][0]['ModelMaterialResourcesID']=[41,41]
target['TextureFileData'].append(dict(ID=2346,FileDataID=2346,MaterialResourcesID=41))
names[2346]=['item/objectcomponents/shoulder/blue.blp']
package[0]['record']['IconFileDataID']=777
pending={};variants,blocked=appearance.native_equipment_variant_candidates(*args,unparented_candidates=pending)
self.assertFalse(variants);self.assertFalse(blocked)
self.assertEqual(pending[item['entry']]['native_display_info_id'],201)
self.assertEqual(pending[item['entry']]['resources'][-1]['source_geometry_witness_item_ids'],[500002])
result=appearance.missing_weapon_links(source,target,package,dict(version=1,slots={}),100,
visible_armor=True,selected_items={item['entry']},parent_candidates=pending,parent_native_max=200)
self.assertEqual([r['table_name']for r in result['records']],['ItemAppearance','ItemModifiedAppearance'])
self.assertEqual(result['records'][0]['record']['ItemDisplayInfoID'],201)
self.assertEqual(appearance.compose_weapon_links(dict(build='1.60.1.70334',rows=[]),result)['rows'],result['records'])
links=target['ItemModifiedAppearance'];target['ItemModifiedAppearance']=[]
missing={};appearance.native_equipment_variant_candidates(*args,unparented_candidates=missing)
self.assertFalse(missing)
target['ItemModifiedAppearance']=links
target['ComponentModelFileData'][1]['PositionIndex']=0
self.assertFalse(appearance.native_equipment_variant_candidates(*args)[0])
missing={};appearance.native_equipment_variant_candidates(*args,unparented_candidates=missing)
self.assertFalse(missing)
target['ComponentModelFileData'][0]['PositionIndex']=1;target['ComponentModelFileData'][1]['PositionIndex']=0
self.assertFalse(appearance.native_equipment_variant_candidates(*args)[0])
target['ComponentModelFileData'][0]['PositionIndex']=0;target['ComponentModelFileData'][1]['PositionIndex']=1
names[1235]=['item/objectcomponents/shoulder/unrelated.m2']
self.assertFalse(appearance.native_equipment_variant_candidates(*args)[0])
def test_plain_pants_parent_uses_source_slot_witness_and_keeps_gender_layers(self):
source=copy.deepcopy(self.source);source['records']=source['records'][:2]
for record in source['records']:
record['raw_fields'].update(**{'class':4},subclass=4,inventory_type=7)
record['raw_sha256']=hashlib.sha256(_canonical(record['raw_fields'])).hexdigest()
for ident,token in((100,20),(101,11)):
raw=[0]*23;raw[0]=ident;raw[19]=raw[20]=token;self.dbc.by_id[ident]=tuple(raw)
target={name:[]for name in appearance.TARGET_TABLES}
display=dict(ID=200,ModelResourcesID=[0,0],ModelMaterialResourcesID=[0,0],GeosetGroup=[0]*6,AttachmentGeosetGroup=[0]*6,HelmetGeosetVis=[0,0],ModelType=[0,0])
target['ItemDisplayInfo']=[display,dict(display,ID=101)]
target['ItemAppearance']=[dict(ID=11,ItemDisplayInfoID=101,DisplayType=5,TransmogPlayerConditionID=0)]
target['ItemModifiedAppearance']=[dict(ID=1,ItemID=500002,ItemAppearanceModifierID=0,ItemAppearanceID=11)]
names={};next_file=2400
for did,stem in((200,'armlayer'),(101,'red')):
for section,directory in((5,'leguppertexture'),(6,'leglowertexture')):
group=did*10+section
target['ItemDisplayInfoMaterialRes'].append(dict(ID=did*10+section,ItemDisplayInfoID=did,ComponentSection=section,MaterialResourcesID=group))
for gender,suffix in((0,'m'),(1,'f')):
next_file+=1;target['TextureFileData'].append(dict(ID=next_file,FileDataID=next_file,MaterialResourcesID=group))
target['ComponentTextureFileData'].append(dict(ID=next_file,GenderIndex=gender,ClassID=0,RaceID=0))
names[next_file]=[f'item/texturecomponents/{directory}/{stem}_{suffix}.blp']
package=[dict(table_name=t,id=500001,record=dict(ClassID=4,SubclassID=4,InventoryType=7,IconFileDataID=777)if t=='Item'else{})for t in('Item','ItemSparse')]
args=(source,self.dbc,target,package,names,{500001});pending={}
variants,blocked=appearance.native_equipment_variant_candidates(*args,unparented_candidates=pending)
self.assertFalse(variants);self.assertFalse(blocked)
self.assertEqual(pending[500001]['display_type'],5)
self.assertEqual(pending[500001]['resources'][-1]['source_display_witness_item_ids'],[500002])
self.assertEqual({r['gender_index']for r in pending[500001]['resources'][0]['texture_family']},{0,1})
target['ItemModifiedAppearance'][0]['ItemAppearanceModifierID']=1
pending={};appearance.native_equipment_variant_candidates(*args,unparented_candidates=pending)
self.assertFalse(pending)
def setUp(self):
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
strings=b'\0Blade.mdx\0Red\0Blue\0ArmLayer\0'
rows=[]
for ident,texture in ((100,11),(101,15)):
row=[0]*23;row[0]=ident;row[1]=1;row[3]=texture;row[6]=2;row[14]=20;rows.append(row)
path=Path(self.tmp.name)/'ItemDisplayInfo.dbc'
path.write_bytes(struct.pack('<4s4I',b'WDBC',2,23,92,len(strings))+b''.join(struct.pack('<23I',*r)for r in rows)+strings)
self.dbc=DBC(path,23)
self.source=dict(kind='source-item-dependency-inventory',source_identity=dict(dataset='fixture'),
snapshot_verification=dict(content_and_schema_and_ids_verified=True),records=[])
for item,display in ((500001,100),(500002,101),(500003,999)):
raw=dict(entry=item,display_id=display,inventory_type=13,**{'class':2})
self.source['records'].append(dict(identity=['Item',item],raw_fields=raw,raw_sha256=hashlib.sha256(_canonical(raw)).hexdigest()))
self.target={name:[]for name in appearance.TARGET_TABLES}
self.target.update(ItemModifiedAppearance=[dict(ID=1,ItemID=500001,ItemAppearanceID=10,ItemAppearanceModifierID=0),
dict(ID=2,ItemID=500001,ItemAppearanceID=11,ItemAppearanceModifierID=3)],
ItemAppearance=[dict(ID=10,ItemDisplayInfoID=20),dict(ID=11,ItemDisplayInfoID=20)],
ItemDisplayInfo=[dict(ID=20,ModelResourcesID=[30,0],ModelMaterialResourcesID=[40,0],GeosetGroup=[2,0,0,0,0,0])],
ItemDisplayInfoMaterialRes=[dict(ID=50,ItemDisplayInfoID=20,MaterialResourcesID=41,ComponentSection=6)],
ModelFileData=[dict(ID=60,ModelResourcesID=30,FileDataID=1234),dict(ID=61,ModelResourcesID=30,FileDataID=1235)],
TextureFileData=[dict(ID=70,MaterialResourcesID=40,FileDataID=2345),dict(ID=71,MaterialResourcesID=41,FileDataID=2346)])
def test_exact_context_variants_not_claimed_shared_geometry(self):
before=copy.deepcopy((self.source,self.target))
result=appearance.compare_appearances(self.source,self.dbc,self.target)
self.assertEqual(result['counts']['source_context_texture_variant_groups'],1)
group=result['source_reference_variant_candidates'][0]
self.assertEqual(group['texture_variant_count'],2)
self.assertFalse(group['verified_shared_geometry']);self.assertFalse(group['recolor_conversion_ready'])
self.assertEqual(group['geometry_context']['ModelName'],['Blade.mdx',''])
self.assertEqual(group['source_displays'][0]['texture_tokens']['Texture'][0],'ArmLayer')
self.assertEqual(result['counts']['classifications'],{'unresolved-dependencies':3})
self.assertFalse(result['installable']);self.assertFalse(result['engine_loaded'])
self.assertEqual((self.source,self.target),before)
self.assertEqual(_canonical(result),_canonical(appearance.compare_appearances(self.source,self.dbc,self.target)))
def test_target_chain_preserves_modifiers_and_all_resource_choices(self):
result=appearance.compare_appearances(self.source,self.dbc,self.target)
first=result['items'][0]
self.assertEqual([row['modifier']for row in first['target_candidates']],[0,3])
resolved=result['target_compositions']['20']
self.assertEqual(resolved['model_file_ids_by_slot'],[[1234,1235],[]])
self.assertEqual(resolved['material_file_ids_by_slot'],[[2345],[]])
self.assertEqual(resolved['body_materials'][0]['record']['ComponentSection'],6)
self.assertEqual(resolved['body_materials'][0]['file_data_ids'],[2346])
self.assertFalse(resolved['asset_bytes_verified']);self.assertFalse(resolved['source_equivalence_verified'])
self.assertIn('source-display-missing',result['items'][2]['blockers'])
self.assertEqual(result['counts']['missing_target_item_chains'],2)
def test_missing_resource_and_table_edges_are_explicit(self):
self.target['TextureFileData']=[]
self.target['ItemAppearance'].pop()
result=appearance.compare_appearances(self.source,self.dbc,self.target)
missing={(row['namespace'],row['id'])for row in result['missing_target_table_references']}
self.assertEqual(missing,{('ItemAppearance',11),('MaterialResourcesID',40),('MaterialResourcesID',41)})
self.assertIn('target-appearance-chain-incomplete',result['items'][0]['blockers'])
def test_context_flags_prevent_grouping_even_with_identical_model_name(self):
self.dbc.by_id[101]=tuple(list(self.dbc.by_id[101][:9])+[1]+list(self.dbc.by_id[101][10:]))
result=appearance.compare_appearances(self.source,self.dbc,self.target)
self.assertEqual(result['source_reference_variant_candidates'],[])
def test_zero_snapshot_sentinel_is_retained_as_blocked_not_a_wire_item(self):
raw=dict(entry=0,display_id=100,inventory_type=13,**{'class':2})
self.source['records'].append(dict(identity=['Item',0],raw_fields=raw,raw_sha256=hashlib.sha256(_canonical(raw)).hexdigest()))
result=appearance.compare_appearances(self.source,self.dbc,self.target)
self.assertEqual(result['blocked_nonwire_source_item_ids'],[0])
self.assertEqual(result['counts']['source_items'],4)
self.assertEqual(result['counts']['wearable_weapon_armor_items'],3)
def test_unverified_changed_or_ambiguous_inputs_fail_closed(self):
cases=[lambda s,t:s['snapshot_verification'].update(content_and_schema_and_ids_verified=False),
lambda s,t:s['records'][0]['raw_fields'].update(display_id=555),
lambda s,t:t['ItemDisplayInfo'].append(copy.deepcopy(t['ItemDisplayInfo'][0])),
lambda s,t:t['ItemDisplayInfo'][0].update(ModelResourcesID=[30]),
lambda s,t:t['ItemAppearance'][0].update(ItemDisplayInfoID=-1),
lambda s,t:t.pop('ComponentTextureFileData')]
for mutate in cases:
source,target=copy.deepcopy((self.source,self.target));mutate(source,target)
with self.assertRaises(ValueError):appearance.compare_appearances(source,self.dbc,target)
class ModelDependencyTest(unittest.TestCase):
def container(self,*chunks):
return b''.join(tag+struct.pack('<I',len(raw))+raw for tag,raw in chunks)
def test_real_chunk_structures_preserve_slot_and_animation_identity(self):
body=b'MD20'+struct.pack('<I',274)
raw=self.container((b'MD21',body),(b'SFID',struct.pack('<III',1234,0,5678)),
(b'AFID',struct.pack('<HHI',17,2,9012)),(b'TXID',struct.pack('<II',0,3456)),(b'JUNK',b'opaque'))
row=appearance.model_dependency_chunks(raw)
self.assertEqual(row['md20_version'],274)
self.assertEqual(row['skin_file_ids'],[1234,0,5678])
self.assertEqual(row['animation_files'],[dict(animation_id=17,variation=2,file_data_id=9012)])
self.assertEqual(row['texture_file_ids'],[0,3456])
self.assertEqual(row['opaque_chunks'],[dict(tag_hex=b'JUNK'.hex(),bytes=6)])
self.assertFalse(row['dependency_complete']);self.assertFalse(row['skin_path_fallback_unreviewed'])
def test_invalid_or_duplicate_chunks_fail_without_partial_success(self):
body=self.container((b'MD21',b'MD20'+struct.pack('<I',274)))
cases=[b'MD20'+struct.pack('<I',256),body[:-1],body+b'x',body+body,
body+self.container((b'SFID',b'123')),body+self.container((b'AFID',b'1234')),body+self.container((b'TXID',b'123')),
self.container((b'MD21',b'bad body')),
body+b'JUNK'+struct.pack('<I',0xffffffff)]
for raw in cases:
with self.assertRaises(ValueError):appearance.model_dependency_chunks(raw)
def test_batch_keeps_blocked_models_and_never_requests_zero(self):
with tempfile.TemporaryDirectory()as folder:
root=Path(folder)
(root/'one.m2').write_bytes(self.container((b'MD21',b'MD20'+struct.pack('<I',274)),(b'SFID',struct.pack('<II',0,123))))
(root/'bad.m2').write_bytes(b'MD21'+struct.pack('<I',100))
row=appearance.scan_model_files(root)
self.assertEqual(row['counts']['parsed_models'],1);self.assertEqual(row['counts']['blocked_models'],1)
self.assertEqual(row['declared_file_ids'],[123]);self.assertFalse(row['dependency_complete'])
self.assertEqual(_canonical(row),_canonical(appearance.scan_model_files(root)))
class ModelVertexTest(unittest.TestCase):
def body(self,version=256):
raw=bytearray(324 if version==256 else 304)
raw[:8]=b'MD20'+struct.pack('<I',version)
vertices=(1.,2.,3.,0.,0.,1.,.25,.75,0.,0.)
vertex=struct.pack('<3f4B4B7f',*vertices[:3],255,0,0,0,1,0,0,0,*vertices[3:])
struct.pack_into('<II',raw,68 if version==256 else 60,1,len(raw));raw.extend(vertex)
at=len(raw);raw.extend(bytes(16));name=b'Item\\ObjectComponents\\Weapon\\Blue.blp\0'
struct.pack_into('<II',raw,92 if version==256 else 80,1,at)
struct.pack_into('<4I',raw,at,0,3,len(name),len(raw));raw.extend(name)
return bytes(raw)
def test_version_specific_offsets_compare_ordered_vertex_content(self):
source=appearance.model_vertex_stream(self.body())
target_body=self.body(274);target=appearance.model_vertex_stream(b'MD21'+struct.pack('<I',len(target_body))+target_body)
self.assertEqual(source['vertex_count'],1)
self.assertEqual(source['ordered_geometry_sha256'],target['ordered_geometry_sha256'])
self.assertEqual(source['ordered_skinning_sha256'],target['ordered_skinning_sha256'])
self.assertEqual(source['ordered_attribute_sha256'],target['ordered_attribute_sha256'])
self.assertEqual(source['declared_textures'][0]['name'],'Item\\ObjectComponents\\Weapon\\Blue.blp')
self.assertFalse(source['full_model_equivalence_verified']);self.assertFalse(target['source_precedence_verified'])
changed=bytearray(self.body(272));changed[304+16]=9
other=appearance.model_vertex_stream(bytes(changed))
self.assertEqual(source['ordered_geometry_sha256'],other['ordered_geometry_sha256'])
self.assertNotEqual(source['ordered_skinning_sha256'],other['ordered_skinning_sha256'])
struct.pack_into('<f',changed,304,5.)
altered=appearance.model_vertex_stream(bytes(changed))
self.assertNotEqual(source['ordered_geometry_sha256'],altered['ordered_geometry_sha256'])
self.assertNotEqual(source['ordered_attribute_sha256']['position'],altered['ordered_attribute_sha256']['position'])
self.assertEqual(source['ordered_attribute_sha256']['normal'],altered['ordered_attribute_sha256']['normal'])
def test_bad_extents_floats_paths_and_unreviewed_versions_are_blocked(self):
good=self.body()
cases=[good[:100],b'bad!'+good[4:],good[:4]+struct.pack('<I',260)+good[8:]]
for offset,value in ((68,0xffffffff),(72,4),(324,0x7fc00000),(92,4097)):
changed=bytearray(good);struct.pack_into('<I',changed,offset,value);cases.append(bytes(changed))
cases.extend((good[:-1]+b'x',good.replace(b'Item\\Object',b'..\\.\\Object')))
for raw in cases:
with self.assertRaises(ValueError):appearance.model_vertex_stream(raw)
def test_replaceable_empty_names_do_not_dereference_inactive_offsets(self):
raw=bytearray(self.body(274));_,at=struct.unpack_from('<II',raw,80)
struct.pack_into('<4I',raw,at,2,0,0,0xffffffff)
row=appearance.model_vertex_stream(bytes(raw))['declared_textures'][0]
self.assertIsNone(row['name']);self.assertFalse(row['external_name_declared'])
self.assertEqual(row['unused_name_offset'],0xffffffff)
struct.pack_into('<4I',raw,at,2,0,1,len(raw)-1)
row=appearance.model_vertex_stream(bytes(raw))['declared_textures'][0]
self.assertIsNone(row['name']);self.assertFalse(row['external_name_declared'])
if __name__=='__main__':unittest.main()