plugins/tools/plugin_resource_pack.py
unimatrixgit 0a341290b5
All checks were successful
DuneRealms Plugin CI / plugins (push) Successful in 2m7s
feat: merge owner vanilla item art while preserving jerboa and runtime bytes
2026-11-29 20:43:42 +01:00

211 lines
13 KiB
Python

"""Deterministic resource-pack assembly and dependency closure; never runs plugin/game code."""
import hashlib
import json
from pathlib import Path
import re
import struct
import urllib.request
import zipfile
import plugin_vanilla_art
ROOT = Path(__file__).resolve().parents[1]
SOURCE = ROOT / 'network/resource-pack/central'
PACK_ID = 'c24c7cf5-a292-539d-971f-a96d8b838162'
VALID = re.compile(r'[a-z0-9_.-]+:[a-z0-9_./-]+\Z')
def encoded(value): return (json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'))+'\n').encode()
def resource(value):
value = value if ':' in value else 'minecraft:'+value
if not VALID.fullmatch(value) or '..' in value.split(':')[1].split('/'): raise ValueError('Invalid resource ID: '+value)
return value.split(':', 1)
def path_for(value, kind, suffix='.json'):
ns, path = resource(value); return f'assets/{ns}/{kind}/{path}{suffix}'
def read_zip(path):
files = {}
with zipfile.ZipFile(path) as archive:
for item in archive.infolist():
name = item.filename
if item.is_dir(): continue
if name in files or name.startswith('/') or '\\' in name or '..' in name.split('/'):
raise ValueError('Unsafe/duplicate archive entry: '+name)
files[name] = archive.read(item)
return files
def client_assets(cache, supplied=None):
lock = json.loads((SOURCE/'inputs.lock.json').read_text(encoding='utf-8'))['client']
path = Path(supplied) if supplied else Path(cache)/'minecraft-26.3-client.jar'
if not path.exists():
path.parent.mkdir(parents=True, exist_ok=True)
with urllib.request.urlopen(lock['url'], timeout=60) as response: payload=response.read(lock['size']+1)
if len(payload)!=lock['size'] or hashlib.sha1(payload).hexdigest()!=lock['sha1']: raise ValueError('Official client download differs')
path.write_bytes(payload)
if path.stat().st_size!=lock['size'] or hashlib.sha1(path.read_bytes()).hexdigest()!=lock['sha1']: raise ValueError('Pinned client assets differ')
return {key:value for key,value in read_zip(path).items() if key.startswith('assets/')}
def strings_named(value, name):
if isinstance(value, dict):
for key, child in value.items():
if key==name and isinstance(child, str): yield child
else: yield from strings_named(child, name)
elif isinstance(value, list):
for child in value: yield from strings_named(child, name)
class Closure:
def __init__(self, pack, vanilla):
self.pack=pack; self.files=dict(vanilla, **pack); self.cache={}
def model(self, key, chain=()):
if key in chain: raise ValueError('Model parent cycle: '+key)
if key not in self.files: raise ValueError('Missing model: '+key)
obj=json.loads(self.files[key]); textures={}; elements=[]
parent=obj.get('parent')
if parent and not parent.split(':')[-1].startswith('builtin/'):
inherited, elements=self.model(path_for(parent,'models'),chain+(key,)); textures.update(inherited)
textures.update(obj.get('textures',{})); elements=obj.get('elements',elements)
if chain:return textures,elements
def resolve(ref, seen=()):
if isinstance(ref,dict): ref=ref['sprite']
if ref.startswith('#'):
name=ref[1:]
if name in seen or name not in textures: raise ValueError('Unresolved model texture variable: '+key+' '+ref)
return resolve(textures[name],seen+(name,))
target=path_for(ref,'textures','.png')
if target not in self.files: raise ValueError('Missing texture: '+target+' in '+key)
png=self.files[target]
if not png.startswith(b'\x89PNG\r\n\x1a\n') or len(png)<24: raise ValueError('Invalid PNG: '+target)
return ref
for ref in textures.values(): resolve(ref)
for ref in strings_named(elements,'texture'): resolve(ref)
return textures,elements
def font(self,key,chain=()):
if key in chain: raise ValueError('Font reference cycle: '+key)
if key not in self.files: raise ValueError('Missing font: '+key)
for provider in json.loads(self.files[key]).get('providers',[]):
kind=provider['type'].split(':')[-1]
if kind=='reference': self.font(path_for(provider['id'],'font'),chain+(key,))
elif 'file' in provider:
target=path_for(provider['file'],'textures' if kind=='bitmap' else 'font','')
if target not in self.files: raise ValueError('Missing font file: '+target)
if kind=='bitmap' and not self.files[target].startswith(b'\x89PNG\r\n\x1a\n'): raise ValueError('Invalid font bitmap: '+target)
def validate(self):
counts={'models':0,'fonts':0,'items':0,'blockstates':0}
for key,payload in self.pack.items():
if key.startswith('assets/') and not re.fullmatch(r'assets/[a-z0-9_./-]+',key): raise ValueError('Invalid asset path: '+key)
if key.endswith('.png') and not payload.startswith(b'\x89PNG\r\n\x1a\n'): raise ValueError('Invalid PNG: '+key)
if not key.endswith('.json'): continue
value=json.loads(payload)
if '/models/' in key: self.model(key); counts['models']+=1
elif '/font/' in key: self.font(key); counts['fonts']+=1
elif '/items/' in key or '/blockstates/' in key:
for ref in strings_named(value,'model'): self.model(path_for(ref,'models'))
counts['items' if '/items/' in key else 'blockstates']+=1
elif '/atlases/' in key:
seen=set()
for source in value.get('sources',[]):
if source['type'].split(':')[-1]=='single':
ref=source.get('sprite',source['resource'])
if ref in seen: raise ValueError('Duplicate atlas sprite: '+ref)
seen.add(ref)
if path_for(source['resource'],'textures','.png') not in self.files: raise ValueError('Missing atlas texture: '+ref)
return counts
def vanilla_catalog(files,vanilla):
"""Prove coverage of every concrete static texture referenced by vanilla item models.
Trim sprites are generated by the native paletted atlas, not separate PNG files.
Native special renderers/player-head skins retain their original model definitions.
"""
audit=Closure(files,vanilla);generated=set();static=set();definitions=0;references=0
atlas=json.loads(vanilla['assets/minecraft/atlases/items.json'])
for source in atlas['sources']:
if source['type'].split(':')[-1]!='paletted_permutations':continue
for base in source['textures']:
template=path_for(base,'textures','.png')
if template not in vanilla or template in files:raise ValueError('Native trim template must be preserved: '+template)
for suffix in source['permutations']:generated.add(path_for(base+'_'+suffix,'textures','.png'))
for ref in [source['palette_key'],*source['permutations'].values()]:
ns,path=resource(ref)
if f'assets/{ns}/textures/palettes/{path}.png' not in vanilla:raise ValueError('Missing native trim palette')
for key,payload in vanilla.items():
if not key.startswith('assets/minecraft/items/') or not key.endswith('.json'):continue
definitions+=1;value=json.loads(payload)
for ref in [*strings_named(value,'model'),*strings_named(value,'base')]:
references+=1;textures,_=audit.model(path_for(ref,'models'),('vanilla-catalog',))
for texture in textures.values():
if isinstance(texture,dict):texture=texture['sprite']
if texture.startswith('#'):continue
target=path_for(texture,'textures','.png')
if target in generated or target=='assets/minecraft/textures/missingno.png':continue
if target not in files:raise ValueError('Uncovered vanilla item texture: '+target)
static.add(target)
return {'definitions':definitions,'modelReferences':references,'staticTextureReferences':len(static),'nativeGeneratedTrimSprites':len(generated),'specialRendererModels':'preserved'}
def required_item_sprites(files, vanilla):
"""Modern item definitions may point at models/entity or any other model directory."""
sprites=set(); audit=Closure(files,vanilla)
for key,payload in files.items():
if '/items/' not in key or not key.endswith('.json'): continue
definition=json.loads(payload)
for model in [*strings_named(definition,'model'), *strings_named(definition,'base')]:
textures,_=audit.model(path_for(model,'models'))
for ref in textures.values():
if isinstance(ref,dict):ref=ref['sprite']
if not ref.startswith('#'):
ns,leaf=resource(ref)
if ns!='minecraft' and not leaf.startswith(('item/','block/')):sprites.add(ns+':'+leaf)
return sprites
def validate_item_atlas(files, vanilla):
sources=json.loads(files.get('assets/minecraft/atlases/items.json',b'{"sources":[]}'))['sources']
published={source.get('sprite',source['resource']) for source in sources if source['type'].split(':')[-1]=='single'}
missing=required_item_sprites(files,vanilla)-published
if missing:raise ValueError('Item atlas missing custom sprites: '+', '.join(sorted(missing)))
def build(output, source_commit, vanilla, source_root=SOURCE):
if not re.fullmatch('[a-f0-9]{40}',source_commit):raise ValueError('Exact source SHA required')
lock=json.loads((source_root/'inputs.lock.json').read_text(encoding='utf-8'))
files,vanilla_art=plugin_vanilla_art.load(vanilla)
owner_root=ROOT/'network/resource-pack/owner-items'
if (owner_root/'inputs.json').is_file():
approved=json.loads((owner_root/'inputs.json').read_text(encoding='utf-8'))['entries']
expected={r['path']:r['sha256'] for r in approved}
actual={p.relative_to(owner_root/'overlay').as_posix():hashlib.sha256(p.read_bytes()).hexdigest() for p in (owner_root/'overlay').rglob('*') if p.is_file()}
if actual!=expected or any(not n.startswith('assets/minecraft/textures/item/') or '..' in Path(n).parts or not n.endswith(('.png','.png.mcmeta')) for n in actual):raise ValueError('Owner item overlay differs from its reviewed boundary')
replacements=[]
for directory in (ROOT/'network/resource-pack/owner-items/overlay',source_root/'legacy',ROOT/'network/resource-pack/shared',source_root/'overlay'):
for path in sorted(directory.rglob('*')):
if path.is_file():
key=path.relative_to(directory).as_posix();payload=path.read_bytes()
if key in files and files[key]!=payload:replacements.append(key)
files[key]=payload
# Compatibility alias removes the historical dangling default-font reference without replacing source artwork.
files['assets/dunerealms/font/imperial_menus.json']=encoded({'providers':[{'type':'reference','id':'dunerealms:card_art'},{'type':'reference','id':'dunerealms:lore_panels'}]})
# Item-only sprites outside the vanilla item directory need explicit registration; register in ONE atlas.
sprites=required_item_sprites(files,vanilla)
files['assets/minecraft/atlases/items.json']=encoded({'sources':[{'type':'minecraft:single','resource':ref,'sprite':ref} for ref in sorted(sprites)]})
transport_path=ROOT/'network/resource-pack/mcgui/transport-0.8.6.zip'
if hashlib.sha256(transport_path.read_bytes()).hexdigest()!=lock['transportSha256']:raise ValueError('Transport input differs')
transport=read_zip(transport_path)
for key,value in transport.items():
if key=='pack.mcmeta':continue
if key in files and files[key]!=value:raise ValueError('Unexpected GUI transport collision: '+key)
files[key]=value
meta=json.loads(transport['pack.mcmeta']);meta['pack']={'description':'DuneRealms | One central network resource pack','min_format':88,'max_format':97}
files['pack.mcmeta']=encoded(meta)
files['CREDITS-DuneRealms.txt']=b'DuneRealms central artwork: owner-supplied procedural source and assets. Vanilla material layer extends that generator, retaining Minecraft/Mojang silhouettes and UV relief where noted; futuristic ore/metal icons and masonry/furniture materials by DuneRealms. Existing custom card atlases, legacy custom item/entity artwork and MCGUI transport preserved. No Xeindom/XAE assets.\n'
counts=Closure(files,vanilla).validate()
validate_item_atlas(files,vanilla)
vanilla_art['itemCatalog']=vanilla_catalog(files,vanilla)
output=Path(output);output.parent.mkdir(parents=True,exist_ok=True)
with zipfile.ZipFile(output,'w',compression=zipfile.ZIP_DEFLATED,compresslevel=9) as zipout:
for key,value in sorted(files.items()):
info=zipfile.ZipInfo(key,(2026,11,29,0,0,0));info.create_system=0;info.compress_type=zipfile.ZIP_DEFLATED;zipout.writestr(info,value,compresslevel=9)
if read_zip(output)!=files:raise ValueError('Built ZIP differs from source assembly')
data=output.read_bytes();manifest={'filename':output.name,'sourceCommit':source_commit,'packId':PACK_ID,'delivery':'server','unified':True,'bytes':len(data),'sha1':hashlib.sha1(data).hexdigest(),'sha256':hashlib.sha256(data).hexdigest(),'entries':len(files),'validation':counts,'vanillaArtwork':vanilla_art,'inputs':lock,'replacedAssetPaths':sorted(set(replacements))}
output.with_suffix('.manifest.json').write_bytes(encoded(manifest));return manifest