243 lines
12 KiB
Python
243 lines
12 KiB
Python
#!/usr/bin/env python3
|
|
"""Prepare Bone Quest's compact masks from the retained public-domain SVG.
|
|
|
|
Optional authoring dependencies: Python 3, Pillow and rsvg-convert. Normal game
|
|
builds use the generated C files and do not run this converter. The SVG remains
|
|
unchanged; labels/background are omitted and source bone silhouettes are reduced
|
|
into a 25-owner pixel mask. All coordinates below refer to a 436x842 render of the
|
|
source's nominal 435.687x841.89 viewBox. No SVG is parsed on the CoCo.
|
|
"""
|
|
import argparse
|
|
import copy
|
|
import hashlib
|
|
import io
|
|
import json
|
|
from pathlib import Path
|
|
import shutil
|
|
import subprocess
|
|
import xml.etree.ElementTree as ET
|
|
from PIL import Image, ImageChops
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
TOPICS = [
|
|
('CRANIUM', ['Cranium', 'g1297']),
|
|
('MANDIBLE', ['Mandible']),
|
|
('CLAVICLE', ['ClavicleLeft', 'ClavicleRight']),
|
|
('SCAPULA', ['Scapula']),
|
|
('STERNUM', ['Sternum', 'Manubrium']),
|
|
('RIBS', ['g845', 'g1609']),
|
|
('CERVICAL', ['CervicalVertebrae']),
|
|
('THORACIC', ['ThoracicVertebrae']),
|
|
('LUMBAR', ['LumbarVertebrae']),
|
|
('SACRUM', ['Sacrum']),
|
|
('COCCYX', ['Coccyx']),
|
|
('PELVIS', ['PelvicGirdle', 'g447']),
|
|
('HUMERUS', ['HumerusLeft', 'HumerusRight']),
|
|
('RADIUS', ['RadiusLeft', 'RadiusRight']),
|
|
('ULNA', ['UlnaLeft', 'UlnaRight']),
|
|
('CARPALS', ['CarpalsLeft', 'CarpalsRight']),
|
|
('METACARPALS', ['MetacarpalsLeft', 'MetacarpalsRight']),
|
|
('FINGERS', ['PhalangesLeft', 'PhalangesRight']),
|
|
('FEMUR', ['g3760', 'FemurLeft', 'path479', 'path481', 'path513', 'path499']),
|
|
('PATELLA', ['PatellaLeft', 'PatellaRight']),
|
|
('TIBIA', ['TibiaLeft', 'TibiaRight']),
|
|
('FIBULA', ['FibulaLeft', 'FibulaRight']),
|
|
('TARSALS', ['TarsalsLeft', 'TarsalsRight']),
|
|
('METATARSALS', ['MetatarsalsLeft', 'MetatarsalsRight']),
|
|
('TOES', ['PhalangesFootLeft', 'PhalangesFootRight']),
|
|
]
|
|
# Front-view occlusion: scapulae/spine are behind chest and limbs; sternum,
|
|
# clavicles and knees remain visible. Both sides share each topic identity.
|
|
PAINT_ORDER = [15,16,17,22,23,24,21,20,18,11,3,10,9,8,5,7,6,0,1,4,2,12,14,13,19]
|
|
DETAIL_VIEW = [1,1,5,5,5,5,1,5,4,4,4,4,0,0,0,2,2,2,0,0,0,0,3,3,3]
|
|
VIEWS = [
|
|
('overview', None, 64, 149),
|
|
('head', (163,17,243,154), 38,65),
|
|
('hand', (313,397,410,500),61,65),
|
|
('foot', (199,747,275,825),63,65),
|
|
('spine', (169,274,235,400),34,65),
|
|
('chest', (107,132,300,308),68,62),
|
|
]
|
|
|
|
|
|
def selected_svg(source, elements, selected):
|
|
root = ET.Element(source.tag, {k:v for k,v in source.attrib.items()
|
|
if k in ('version','width','height','viewBox')})
|
|
root.append(copy.deepcopy(elements['defs3096']))
|
|
def prune(element, active=False):
|
|
active = active or element.get('id') in selected
|
|
result = ET.Element(element.tag, element.attrib)
|
|
for child in element:
|
|
kept = prune(child, active)
|
|
if kept is not None:
|
|
result.append(kept)
|
|
return result if active or len(result) else None
|
|
skeleton = prune(elements['layer3'])
|
|
if skeleton is None:
|
|
raise ValueError('No skeleton source groups selected')
|
|
root.append(skeleton)
|
|
return ET.tostring(root)
|
|
|
|
|
|
def runs(pixels, width, height):
|
|
result, offsets = [], [0]
|
|
for topic in range(1,26):
|
|
for y in range(height):
|
|
x = 0
|
|
while x < width:
|
|
if pixels[y*width+x] != topic:
|
|
x += 1
|
|
continue
|
|
start = x
|
|
while x < width and pixels[y*width+x] == topic:
|
|
x += 1
|
|
result.extend((y,start,x-start))
|
|
offsets.append(len(result))
|
|
return result, offsets
|
|
|
|
|
|
def c_array(name, values, kind='unsigned char', static=False):
|
|
lines = ['static ' if static else '']
|
|
prefix = ('static ' if static else '') + 'const '+kind+' '+name+'[] = {\n'
|
|
return prefix + ''.join(' '+','.join(map(str,values[n:n+24]))+',\n'
|
|
for n in range(0,len(values),24)) + '};\n\n'
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--rsvg-convert', default=shutil.which('rsvg-convert'))
|
|
args = parser.parse_args()
|
|
if not args.rsvg_convert:
|
|
parser.error('Install rsvg-convert for optional asset authoring, or use generated C unchanged.')
|
|
source_path = ROOT/'assets/skeleton-source.svg'
|
|
source = ET.parse(source_path).getroot()
|
|
elements = {e.get('id'):e for e in source.iter() if e.get('id')}
|
|
images, masks = [], []
|
|
for code, ids in TOPICS:
|
|
if any(name not in elements for name in ids):
|
|
raise ValueError('Missing source bone group: '+code)
|
|
rendered = subprocess.run([args.rsvg_convert,'-w','436','-h','842'],
|
|
input=selected_svg(source,elements,set(ids)),capture_output=True,check=True)
|
|
image = Image.open(io.BytesIO(rendered.stdout)).convert('RGBA')
|
|
images.append(image)
|
|
masks.append(image.getchannel('A'))
|
|
combined = masks[0]
|
|
for mask in masks[1:]:
|
|
combined = ImageChops.lighter(combined,mask)
|
|
overall_bounds = combined.getbbox()
|
|
if overall_bounds != (59,20,405,822):
|
|
raise ValueError('Source geometry bounds changed; review bone mapping before regenerating.')
|
|
# Keep actual shaded facial recesses from the original illustration visible
|
|
# after flattening its colors. No new anatomical shapes are drawn here.
|
|
recess = Image.new('L',(436,842),0)
|
|
original = images[0]
|
|
for y in range(55,103):
|
|
for x in range(175,232):
|
|
r,g,b,a = original.getpixel((x,y))
|
|
eye = ((177<=x<198 or 207<=x<231) and 58<=y<80)
|
|
nose = 195<=x<212 and 75<=y<101
|
|
luminance = (299*r+587*g+114*b)//1000
|
|
if a>128 and ((eye and luminance<213) or (nose and luminance<130)):
|
|
recess.putpixel((x,y),255)
|
|
generated = ROOT/'assets/generated'; generated.mkdir(parents=True,exist_ok=True)
|
|
view_data, overview_pixels = [], None
|
|
code = ['/* Generated by tools/prepare_assets.py from LadyofHats public-domain SVG. */\n',
|
|
'#include "map_data.h"\n\n']
|
|
manifest = dict(schemaVersion=1,source=dict(file='assets/skeleton-source.svg',
|
|
sha256=hashlib.sha256(source_path.read_bytes()).hexdigest(),
|
|
author='Mariana Ruiz Villarreal (LadyofHats)',license='Public domain dedication',
|
|
page='https://commons.wikimedia.org/wiki/File:Human_skeleton_front_en.svg'),
|
|
coordinateRender=[436,842],overviewSourceBounds=list(overall_bounds),
|
|
topics=[dict(id=i,code=topic,sourceElements=ids) for i,(topic,ids) in enumerate(TOPICS)],
|
|
paintOrder=PAINT_ORDER,facialRecesses='Original source shading thresholds, eyes and nasal recess only',
|
|
pairedSides='Both sides use one bone-family identity; no left/right questions',views=[])
|
|
sizes = 0
|
|
for view_index,(name,box,width,height) in enumerate(VIEWS):
|
|
box = box or overall_bounds
|
|
pixels = bytearray(width*height)
|
|
for topic in PAINT_ORDER:
|
|
alpha = masks[topic].crop(box).resize((width,height),Image.Resampling.LANCZOS)
|
|
for pos,value in enumerate(alpha.tobytes()):
|
|
if value>=64:
|
|
pixels[pos]=topic+1
|
|
if name in ('overview','head'):
|
|
holes = recess.crop(box).resize((width,height),Image.Resampling.LANCZOS)
|
|
for pos,value in enumerate(holes.tobytes()):
|
|
if pixels[pos]==1 and value>=64:
|
|
pixels[pos]=0
|
|
data,offsets=runs(pixels,width,height)
|
|
counts=[pixels.count(i+1) for i in range(25)]
|
|
if view_index==0:
|
|
overview_pixels=pixels
|
|
if not all(counts):
|
|
raise ValueError('A bone family disappeared from overview: '+str(counts))
|
|
stem='bone'
|
|
else:
|
|
stem=name
|
|
code.append(c_array(stem+'_spans',data,static=view_index!=0))
|
|
code.append(c_array(stem+'_offsets',offsets,'unsigned',static=view_index!=0))
|
|
sizes += len(data)+len(offsets)*2
|
|
view_data.append((stem,width,height))
|
|
manifest['views'].append(dict(id=view_index,name=name,sourceBounds=list(box),
|
|
width=width,height=height,spanBytes=len(data),offsetBytes=len(offsets)*2,
|
|
pixels={TOPICS[i][0]:counts[i] for i in range(25)}))
|
|
# A developer preview uses the runtime's palette; it is not a native
|
|
# emulator capture. The selected sample topic is yellow.
|
|
sample = next(i for i,value in enumerate(DETAIL_VIEW) if value==view_index) if view_index else 0
|
|
colors=[(0,0,85)] + [(255,255,0) if i==sample else (85,170,170) for i in range(25)]
|
|
preview=Image.new('RGB',(width,height));preview.putdata([colors[value] for value in pixels])
|
|
preview.save(generated/(name+'-preview.png'))
|
|
debug=Image.new('RGB',(width,height));palette=[(0,0,85)]+[((i*73+80)%220+35,(i*41)%220+35,(i*109)%220+35) for i in range(25)];debug.putdata([palette[value] for value in pixels]);debug.save(generated/(name+'-regions.png'))
|
|
# Independently decode all authored runs to prove disjoint bounds and
|
|
# exact reconstruction of every generated view.
|
|
decoded=bytearray(width*height)
|
|
for topic in range(25):
|
|
for p in range(offsets[topic],offsets[topic+1],3):
|
|
y,x,length=data[p:p+3]
|
|
assert 0<=y<height and 0<=x<x+length<=width
|
|
for xx in range(x,x+length):
|
|
pos=y*width+xx;assert decoded[pos]==0;decoded[pos]=topic+1
|
|
assert decoded==pixels
|
|
boxes=[]
|
|
for topic in range(1,26):
|
|
points=[(i%64,i//64) for i,value in enumerate(overview_pixels) if value==topic]
|
|
xmin=min(x for x,y in points);ymin=min(y for x,y in points)
|
|
boxes.extend((xmin,ymin,max(x for x,y in points)-xmin+1,max(y for x,y in points)-ymin+1))
|
|
code.append('const unsigned char bone_boxes[25][4] = {'+','.join('{'+','.join(map(str,boxes[i:i+4]))+'}' for i in range(0,100,4))+'};\n')
|
|
code.append(c_array('bone_detail_view',DETAIL_VIEW))
|
|
code.append(c_array('bone_view_widths',[v[1] for v in view_data]))
|
|
code.append(c_array('bone_view_heights',[v[2] for v in view_data]))
|
|
code.append('const unsigned char * const bone_view_spans[BONE_VIEW_COUNT] = {'+','.join(v[0]+'_spans' for v in view_data)+'};\n')
|
|
code.append('const unsigned * const bone_view_offsets[BONE_VIEW_COUNT] = {'+','.join(v[0]+'_offsets' for v in view_data)+'};\n')
|
|
sizes+=len(boxes)+len(DETAIL_VIEW)+len(view_data)*2+len(view_data)*4
|
|
if sizes>6000:
|
|
raise ValueError('Geometry exceeds 6000-byte ROM budget: '+str(sizes))
|
|
(ROOT/'src/map_data.c').write_text(''.join(code))
|
|
(ROOT/'map_data.h').write_text('''#ifndef BONE_MAP_DATA_H
|
|
#define BONE_MAP_DATA_H
|
|
#define BONE_MAP_WIDTH 64
|
|
#define BONE_MAP_HEIGHT 149
|
|
#define BONE_VIEW_COUNT 6
|
|
/* Spans are (y,x,length) triples. Offsets index bytes, 26 entries per view.
|
|
bone_boxes is [25][4]: xmin,ymin,width,height in overview pixels.
|
|
View IDs: 0 overview,1 head/neck,2 hand,3 foot,4 lower spine/pelvis,5 chest.
|
|
A zero detail-view selector asks the UI to magnify the current overview crop. */
|
|
extern const unsigned char bone_spans[];
|
|
extern const unsigned bone_offsets[26];
|
|
extern const unsigned char bone_boxes[25][4];
|
|
extern const unsigned char bone_detail_view[25];
|
|
extern const unsigned char bone_view_widths[6],bone_view_heights[6];
|
|
extern const unsigned char * const bone_view_spans[BONE_VIEW_COUNT];
|
|
extern const unsigned * const bone_view_offsets[BONE_VIEW_COUNT];
|
|
#endif
|
|
''')
|
|
manifest['geometryROMBytes']=sizes
|
|
manifest['detailSelector']=DETAIL_VIEW
|
|
manifest['overviewBoxes']={TOPICS[i][0]:boxes[4*i:4*i+4] for i in range(25)}
|
|
(ROOT/'data/geometry-manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
|
|
print('PASS25 source-group masks; six disjoint bounded views; geometry ROM bytes:',sizes)
|
|
|
|
|
|
if __name__=='__main__':
|
|
main()
|