plugins/network/resource-pack/central/generator/vanilla_materials.py

312 lines
19 KiB
Python

"""Code-native Dune materials for vanilla UV surfaces; no model/gameplay changes.
Extends this pack's procedural artwork system. Vanilla silhouettes, UV shading,
colour-coded details and animation poses are retained; this is a material retexture,
not a claim that thousands of independent illustrations were hand drawn.
"""
import hashlib
import io
import json
import math
from pathlib import Path
import re
import numpy as np
from PIL import Image, ImageDraw
import future_metals
from plugin_vanilla_art import PREFIX,PROTECTED,selected,compatibility_inputs
WOOD={
'oak':(160,115,64),'spruce':(107,72,43),'birch':(204,185,132),
'jungle':(159,106,69),'acacia':(183,99,55),'dark_oak':(72,49,36),
'mangrove':(136,58,49),'cherry':(202,147,140),'pale_oak':(208,199,172),
'bamboo':(168,157,79),'crimson':(118,49,70),'warped':(42,116,111)}
COLORS={'white':(216,210,184),'orange':(216,129,52),'magenta':(167,68,149),
'light_blue':(97,171,194),'yellow':(221,180,71),'lime':(130,169,68),
'pink':(215,138,151),'gray':(81,91,88),'light_gray':(157,163,148),
'cyan':(49,140,149),'purple':(116,73,157),'blue':(54,94,170),
'brown':(125,86,55),'green':(63,113,79),'red':(177,60,48),'black':(29,36,35)}
def seed(key):return int.from_bytes(hashlib.sha256(key.encode()).digest()[:4],'big')
def png(image):
out=io.BytesIO();image.save(out,format='PNG',compress_level=9);return out.getvalue()
def species(name):
return next((k for k in sorted(WOOD,key=len,reverse=True) if re.search(r'(^|_)'+k+r'(_|$)',name)),None)
def colour(name):return next((k for k in sorted(COLORS,key=len,reverse=True) if name.startswith(k+'_')),None)
def family(key):
name=Path(key).stem
if '/entity/' in key:return 'uv-equipment' if '/equipment/' in key else 'uv-furniture'
if '/item/' in key:return 'item'
if name.startswith('furnace_'):return 'furnace'
if name.endswith('_ore'):return 'ore'
if any(w in name for w in ('stonecutter','lodestone','redstone_lamp','redstone_block','glowstone','bulb','lantern','lightning_rod','piston','observer','dispenser','dropper','enchanting','brewing','beacon','command','structure','jigsaw','respawn_anchor','spawner','vault','repeater','comparator','target','crafter','crafting','cartography','fletching','smithing','loom','grindstone','blast_furnace','smoker','barrel','bookshelf','note_block','jukebox','tnt','daylight','lectern')):return 'crafted-surface'
if name.endswith('_planks'):return 'planks'
if any(name.endswith('_'+x) for x in ('log','wood','stem','hyphae','log_top','stem_top','hyphae_top','wood_top')):return 'timber'
if any(w in name for w in ('glass','leaves','flower','sapling','grass','fern','vine','seagrass','torch','rail','door','bars','chain','wire','roots','crop','wheat','fire','portal','water','lava','overlay')):return 'masked-surface'
if name in ('red_sand','soul_sand'):return 'ground'
if re.fullmatch(r'(?:'+'|'.join(COLORS)+r')_(?:wool|concrete|concrete_powder|terracotta|glazed_terracotta)',name) or name in ('terracotta','bricks','brick','resin_bricks'):return 'coloured-building'
if any(w in name for w in ('copper','iron_block','gold_block','netherite_block')):return 'metal'
if any(w in name for w in ('stone','andesite','diorite','granite','basalt','tuff','calcite','quartz','prismarine','purpur','bedrock')):return 'masonry'
if any(w in name for w in ('sand','dirt','gravel','mud','farmland','podzol','mycelium','netherrack','nylium','snow')):return 'ground'
return 'crafted-surface'
def base_for(name):
if name=='bricks':return np.array((155,87,63),float)
if 'resin' in name:return np.array((183,103,42),float)
if 'deepslate' in name:return np.array((70,72,77),float)
if 'bedrock' in name:return np.array((67,69,60),float)
if 'andesite' in name:return np.array((132,137,130),float)
if 'blackstone' in name or 'basalt' in name:return np.array((56,57,61),float)
if 'diorite' in name or 'calcite' in name or 'quartz' in name:return np.array((209,201,180),float)
if 'granite' in name:return np.array((153,111,87),float)
if 'prismarine' in name:return np.array((66,126,119),float)
if 'purpur' in name:return np.array((149,113,147),float)
if 'end_stone' in name:return np.array((200,188,124),float)
if 'sandstone' in name:return np.array((190,154,94) if 'red_' not in name else (184,106,56),float)
if 'tuff' in name:return np.array((115,117,102),float)
return np.array((132,125,110),float)
def periodic(w,h,key):
# Periodic interpolated value noise, rather than conspicuous diagonal sine bands.
yy,xx=np.mgrid[0:h,0:w];rng=np.random.default_rng(seed(key));field=np.zeros((h,w),float)
for frequency,amplitude in ((3,.23),(7,.15),(16,.08)):
grid=rng.uniform(-1,1,(frequency,frequency));gx=xx*frequency/w;gy=yy*frequency/h
ix=gx.astype(int)%frequency;iy=gy.astype(int)%frequency;tx=gx%1;ty=gy%1
tx=tx*tx*(3-2*tx);ty=ty*ty*(3-2*ty)
top=grid[iy,ix]*(1-tx)+grid[iy,(ix+1)%frequency]*tx
bottom=grid[(iy+1)%frequency,ix]*(1-tx)+grid[(iy+1)%frequency,(ix+1)%frequency]*tx
field+=amplitude*(top*(1-ty)+bottom*ty)
return field
def masonry(name,w,h,key):
yy,xx=np.mgrid[0:h,0:w];v=periodic(w,h,key);base=base_for(name)
if any(t in name for t in ('brick','tile','chiseled')):
row=yy//8;bx=(xx+(row%2)*8)%16;by=yy%8
mortar=(bx==0)|(by==0);edge=(bx==1)|(by==1)
v=np.where(mortar,-.31,np.where(edge,.13,v*.6))
if 'chiseled' in name:
d=np.abs(xx-w/2)+np.abs(yy-h/2);v=np.where((d>=7)&(d<9),-.25,v)
elif 'cobble' in name:
rng=np.random.default_rng(seed(key));points=rng.uniform(0,1,(14,2));ds=[]
for px,py in points:
dx=np.minimum(np.abs(xx/w-px),1-np.abs(xx/w-px));dy=np.minimum(np.abs(yy/h-py),1-np.abs(yy/h-py));ds.append(dx*dx+dy*dy)
d=np.sort(np.array(ds),axis=0);gap=d[1]-d[0]
v=np.where(gap<.006,-.28,v*.55+.04)
else:
strata=np.sin(2*math.pi*(yy/h*4+.12*np.sin(xx/w*2*math.pi)))
v+=strata*.028
arr=np.clip(base[None,None,:]*(1+v[...,None]),0,255).astype('uint8')
if 'mossy' in name:
mask=periodic(w,h,key+'moss')>.10;arr[mask]=(64,100,66)
if 'cracked' in name:
crack=((xx+yy//3)%19==0)&(yy%16>5);arr[crack]=(70,65,52)
return Image.fromarray(arr,'RGB').convert('RGBA')
def planks(name,w,h,key):
kind=species(name) or 'oak';base=np.array(WOOD[kind],float)
yy,xx=np.mgrid[0:h,0:w];row=yy//8;seams=(yy%8==0)|((xx+(row%2)*11)%32==0)
v=.06*np.sin(2*math.pi*(yy/h*9+.12*np.sin(xx/w*2*math.pi)))+periodic(w,h,key)*.30
v=np.where(seams,-.29,np.where(yy%8==1,.12,v))
arr=np.clip(base[None,None,:]*(1+v[...,None]),0,255).astype('uint8')
# Grain knots repeat inside the tile, without turning every plank into a framed panel.
for x,y in ((w//4,h//4),(3*w//4,3*h//4)):
mask=((xx-x)**2/5+(yy-y)**2/2<1);arr[mask]=(base*.60).astype('uint8')
return Image.fromarray(arr,'RGB').convert('RGBA')
def timber(name,w,h,key):
kind=species(name) or 'oak';base=np.array(WOOD[kind],float);yy,xx=np.mgrid[0:h,0:w]
if name.endswith('_top'):
d=np.maximum(np.abs(xx-(w-1)/2),np.abs(yy-(h-1)/2));v=np.where((d.astype(int)%4)==0,-.19,.045)+periodic(w,h,key)*.2
else:v=.11*np.sin(2*math.pi*(xx/w*7+.14*np.sin(yy/h*2*math.pi)))+periodic(w,h,key)*.3
if name.startswith('stripped_'):base=base*.9+np.array((194,160,102))*.1;v*=.45
else:base*=.73
return Image.fromarray(np.clip(base[None,None,:]*(1+v[...,None]),0,255).astype('uint8'),'RGB').convert('RGBA')
def furnace(name,w,h,key):
im=masonry('deepslate_tiles',w,h,key);d=ImageDraw.Draw(im)
# Sand-worn ceramic furnace body with bronze castings and a readable fuel opening.
def rect(box,c):d.rectangle(tuple(int(x*w/32) if i%2==0 else int(x*h/32) for i,x in enumerate(box)),fill=c)
rect((0,0,31,1),(119,107,76));rect((0,30,31,31),(39,43,40))
if 'front' in name:
rect((4,5,27,11),(30,40,36));rect((5,5,26,5),(159,127,70))
for x in (8,14,20):rect((x,6,x+1,10),(89,95,77))
rect((4,16,27,27),(21,30,27));rect((3,15,28,16),(141,112,63))
if name.endswith('_on'):
rect((7,22,24,26),(205,101,35));rect((10,20,13,25),(246,173,63));rect((18,19,21,25),(244,164,51))
else:rect((7,25,24,26),(58,57,42))
elif 'top' in name:
for x in (6,12,18,24):rect((x,6,x+1,25),(25,36,31))
else:
rect((5,6,26,25),(64,75,64));rect((6,7,25,8),(104,113,89))
for y in (13,18):rect((8,y,23,y+1),(31,45,38))
return im
def ground(name,w,h,key):
yy,xx=np.mgrid[0:h,0:w];v=periodic(w,h,key)
if 'soul' in name:base=np.array((92,72,50))
elif 'snow' in name:base=np.array((220,226,214))
elif 'red_sand' in name:base=np.array((185,111,57))
elif 'sand' in name:base=np.array((203,179,122))
elif 'gravel' in name:base=np.array((135,131,113))
elif 'mud' in name:base=np.array((79,79,64))
elif 'netherrack' in name:base=np.array((113,53,45))
elif 'mycelium' in name:base=np.array((115,102,122))
else:base=np.array((126,92,56))
if 'farmland' in name:
v=np.where(xx%8<2,-.30,v*.45)
if 'moist' in name:base=base*.69
elif 'mud' in name:
v=np.where(np.sin(xx*.39+np.sin(yy*.41))>.94,-.19,v*.40)
elif 'gravel' in name:
rng=np.random.default_rng(seed(key));points=rng.uniform(0,1,(48,2));dist=[]
for px,py in points:
dx=np.minimum(np.abs(xx/w-px),1-np.abs(xx/w-px));dy=np.minimum(np.abs(yy/h-py),1-np.abs(yy/h-py));dist.append(dx*dx+dy*dy)
distances=np.array(dist);order=np.argsort(distances,axis=0);nearest=np.take_along_axis(distances,order[:2],axis=0)
shades=rng.uniform(-.10,.14,48);v=shades[order[0]]
v=np.where(nearest[1]-nearest[0]<.0013,-.26,v)
else:v=v*.5+.025*np.sin(xx*.97+yy*1.69)
return Image.fromarray(np.clip(base[None,None,:]*(1+v[...,None]),0,255).astype('uint8'),'RGB').convert('RGBA')
def metal_tile(name,w,h,key):
if 'copper' in name:
base=(76,128,110) if 'oxidized' in name else (96,134,109) if 'weathered' in name else (158,128,84) if 'exposed' in name else (182,116,69)
elif 'gold' in name:base=(194,158,76)
elif 'netherite' in name:base=(67,62,72)
else:base=(151,166,151)
yy,xx=np.mgrid[0:h,0:w];v=periodic(w,h,key)*.32
edge=(xx%16==0)|(yy%16==0);highlight=(xx%16==1)|(yy%16==1)
v=np.where(edge,-.30,np.where(highlight,.13,v))
arr=np.clip(np.array(base)[None,None,:]*(1+v[...,None]),0,255).astype('uint8')
# Small cast rivets, not a bright border around every surface.
for x in (3,w-4):
for y in (3,h-4):arr[y,x]=np.minimum(255,np.array(base)+35)
if 'chiseled' in name:
diamond=np.abs(xx-w//2)+np.abs(yy-h//2);arr[(diamond==8)|(diamond==9)]=(62,74,59)
return Image.fromarray(arr,'RGB').convert('RGBA')
def building(name,w,h,key):
if name in ('bricks','brick','resin_bricks'):return masonry(name,w,h,key)
col=colour(name);base=np.array(COLORS[col] if col else (167,116,77),float)
yy,xx=np.mgrid[0:h,0:w];v=periodic(w,h,key)*.24
if 'wool' in name:v+=np.where((xx+yy)%4==0,.07,-.015)
elif 'glazed' in name:
diamond=np.abs(xx-w/2)+np.abs(yy-h/2);v=np.where(diamond.astype(int)%8<2,-.22,v)
elif 'terracotta' in name:base=base*.82+np.array((149,103,70))*.18
elif 'concrete' in name:v*=.4
return Image.fromarray(np.clip(base[None,None,:]*(1+v[...,None]),0,255).astype('uint8'),'RGB').convert('RGBA')
def ore(name,w,h,key):
im=ground('netherrack',w,h,key) if name.startswith('nether_') else masonry('deepslate' if name.startswith('deepslate') else 'stone',w,h,key)
d=ImageDraw.Draw(im);rng=np.random.default_rng(seed(name.replace('deepslate_','')))
mineral=next((x for x in ('diamond','emerald','redstone','lapis','copper','gold','iron','coal','quartz') if x in name),'iron')
c={'diamond':(80,200,208),'emerald':(67,180,111),'redstone':(204,52,39),'lapis':(58,103,196),'copper':(192,118,64),'gold':(225,181,65),'iron':(183,167,139),'coal':(32,37,34),'quartz':(224,213,182)}[mineral]
deposits=[]
for i in range(8):
x=int(rng.integers(2,w-4));y=int(rng.integers(2,h-4))
deposits.append((x+2,y+2))
d.polygon([(x,y+2),(x+2,y),(x+4,y+1),(x+3,y+4),(x,y+3)],fill=c)
d.point((x+2,y+1),fill=tuple(min(255,v+32) for v in c))
# Angular embedded conduits and mineral nodes: the explicit futuristic exception.
for a,b in zip(deposits[::2],deposits[1::2]):
route=[a,(b[0],a[1]),b]
d.line(route,fill=(29,43,36),width=3)
d.line(route,fill=tuple(min(255,v+20) for v in c),width=1)
for x,y in deposits:
d.rectangle((x-1,y-1,x+1,y+1),fill=c)
d.point((x,y),fill=tuple(min(255,v+42) for v in c))
return im
def finish_uv(source,key):
"""Apply newly authored Dune material ramps while retaining shape/state information."""
rgba=np.asarray(source.convert('RGBA'),dtype=np.uint8);rgb=rgba[...,:3].astype(float)/255
hi=rgb.max(axis=2);lo=rgb.min(axis=2);sat=hi-lo;lum=rgb@np.array((.2126,.7152,.0722))
# Preserve colour-coded surfaces, signal brightness, potion/armour tint masks and animated poses.
# Ramp endpoints add dusty bronze to neutrals and mineral character to coloured materials.
warm=np.array((.84,.76,.60));cold=np.array((.49,.69,.70))
neutral=np.stack((lum,lum,lum),axis=-1)
tint=neutral*warm
name=Path(key).stem
if any(x in name for x in ('ice','snow','diamond','iron','water','quartz','light_blue')):tint=neutral*np.array((.85,.94,.94))
if any(x in name for x in ('netherite','obsidian','purpur','amethyst')):tint=neutral*np.array((.85,.80,.96))
if 'copper' in name:tint=neutral*np.array((.98,.72,.46))
# Keep hue identities. The material drawing uses existing tonal boundaries as UV relief.
coloured=rgb*.76+rgb*warm*.24
result=np.where((sat<.11)[...,None],neutral*.43+tint*.57,coloured)
if '/entity/chest/' in key and name.startswith(('normal','trapped')):
wood=(rgb[...,0]>rgb[...,2]*1.35)&(rgb[...,0]>rgb[...,1]*1.15)&(lum>.09)
red_warning=(rgb[...,0]>rgb[...,1]*2.6)&(rgb[...,0]>rgb[...,2]*2)&(rgb[...,0]>.4)
green=lum[...,None]*np.array((.42,.78,.58))
result=np.where((wood&~red_warning)[...,None],green,result)
clasp=(sat<.12)&(lum>.3)
result=np.where(clasp[...,None],lum[...,None]*np.array((1.08,.87,.49)),result)
yy,xx=np.mgrid[0:source.height,0:source.width]
if '/item/' in key:
hardware=any(part in name for part in ('sword','pickaxe','axe','shovel','hoe','helmet','chestplate','leggings','boots','bow','fishing_rod','bucket','shears','flint_and_steel','compass','clock','spyglass','brush'))
if hardware:
neutral_metal=(sat<.11)&(lum>.18)
plasteel=lum[...,None]*np.array((.83,.93,.88))
result=np.where(neutral_metal[...,None],plasteel,result)
# Bind the familiar grip, without changing its silhouette or material head.
grip=(rgb[...,0]>rgb[...,1]*1.15)&(rgb[...,1]>rgb[...,2]*1.15)&(xx<source.width*.57)&(yy>source.height*.45)
leather=lum[...,None]*np.array((.54,.70,.49))
binding=(xx-yy)%8<2
brass=lum[...,None]*np.array((1.12,.88,.46))
result=np.where(grip[...,None],np.where(binding[...,None],brass,leather),result)
if name in ('book','writable_book','written_book'):
cover=(rgb[...,0]>rgb[...,1]*1.1)&(rgb[...,1]>rgb[...,2]*1.1)
coated=lum[...,None]*np.array((.50,.80,.61))
result=np.where(cover[...,None],coated,result)
stable_key=re.sub(r'((?:recovery_)?compass|clock)_\d+\.png$',r'\1.png',key)
# A fixed local-frame finish avoids inventing flicker in animated strips/pose sequences.
grain=(np.sin((xx*13+(yy%source.width)*7+seed(stable_key)%67)*.73)*.011)[...,None]
result=np.clip(result+grain*(rgba[...,3:4]>0),0,1)
# Biome-tinted sprites and runtime tint overlays must stay exactly neutral before the game tints them.
visible=rgba[...,3]>0
grayscale=bool(np.all((rgba[...,:3].max(axis=2)-rgba[...,:3].min(axis=2))[visible]<=6))
tint_mask=any(x in name for x in ('grass','leaves','fern','vine','wire','overlay','stem','lily','sugar_cane','leather','tipped_arrow_head')) or '/entity/banner/' in key or '/entity/shield/' in key or name.startswith('shield_base')
biome_leaf=bool(re.fullmatch(r'(oak|spruce|birch|jungle|acacia|dark_oak|mangrove|pale_oak)_leaves',name))
biome_plant=name in ('grass_block_top','grass_block_side_overlay','short_grass','tall_grass_top','tall_grass_bottom','fern','large_fern_top','large_fern_bottom','vine','sugar_cane','lily_pad')
runtime_tint=key.startswith(PREFIX+'block/') and (name.startswith(('redstone_dust_','water_')) or biome_leaf or biome_plant)
if runtime_tint or grayscale and tint_mask:
grey=np.clip(lum+grain[...,0],0,1);result=np.repeat(grey[...,None],3,axis=2)
out=np.concatenate(((result*255).astype('uint8'),rgba[...,3:4]),axis=2)
out[~visible,:3]=0
return Image.fromarray(out,'RGBA')
def render(payload,key,scale=2):
source=Image.open(io.BytesIO(payload)).convert('RGBA')
if '/item/' in key and Path(key).stem in future_metals.NAMES:return future_metals.draw(Path(key).stem),'future-metal-item'
source=source.resize((source.width*scale,source.height*scale),Image.Resampling.NEAREST)
group=family(key);name=Path(key).stem
opaque=source.getextrema()[3]==(255,255)
# Whole tile redraws only on ordinary opaque tile UVs. Special/animated UV sheets retain their layout.
if opaque and source.width==source.height and group in ('masonry','planks','timber','furnace','ground','metal','coloured-building','ore'):
draw={'masonry':masonry,'planks':planks,'timber':timber,'furnace':furnace,'ground':ground,'metal':metal_tile,'coloured-building':building,'ore':ore}[group]
image=draw(name,source.width,source.height,key)
else:image=finish_uv(source,key)
# Alpha, including semitransparent pixels, is an exact gameplay/UV invariant.
image.putalpha(source.getchannel('A'))
return image,group
def build(vanilla,output,source_sha1,scale=2):
output=Path(output);output.mkdir(parents=True,exist_ok=True);entries=[];counts={}
compat,compat_meta=compatibility_inputs(output.parent)
vanilla=dict(vanilla)
for key in compat_meta['rootOnly']:
if key in vanilla:raise ValueError('Legacy source replaces current source')
vanilla[key]=compat[key]
for key in sorted(k for k in vanilla if selected(k)):
if key in PROTECTED:
entries.append({'path':key,'status':'preserved-central-spice-art'});continue
image,group=render(vanilla[key],key,scale);data=png(image);target=output/key;target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(data)
entry={'path':key,'status':'material-retexture','family':group,'width':image.width,'height':image.height,'sha256':hashlib.sha256(data).hexdigest()}
if key+'.mcmeta' in vanilla:
meta=json.loads(vanilla[key+'.mcmeta']);animation=meta.get('animation',{})
for dim in ('width','height'):
if dim in animation:animation[dim]*=scale
saved=(json.dumps(meta,sort_keys=True,separators=(',',':'))+'\n').encode();(output/(key+'.mcmeta')).write_bytes(saved);entry['metadataSha256']=hashlib.sha256(saved).hexdigest()
entries.append(entry);counts[group]=counts.get(group,0)+1
report={'schemaVersion':2,'sourceClientSha1':source_sha1,'compatibilityClientSha1':compat_meta['client']['sha1'],'scale':scale,'description':'Dune material retexture with futuristic ore/ingot artwork and Dune-II-inspired masonry/timber/furnace materials. Ordinary vanilla item silhouettes, UV relief and semantic colours retained. Procedural artwork, not independent hand-drawn illustrations for every asset.','generated':sum(counts.values()),'preservedCentral':len(PROTECTED),'families':counts,'entries':entries,'limits':['Player skins and mob/head identity textures are retained, not replaced.','The shulker-box shell uses the same native sheet as the mob shell; that material finish is shared. Worn armour, general mob/vehicle skins and copper-golem/statue skins are retained.','Connected-client rendering must be reviewed before deployment.']}
(output.parent/'material-manifest.json').write_text(json.dumps(report,indent=2)+'\n',encoding='utf-8')
return report