Add Bone Quest anatomy quiz for CoCo

This commit is contained in:
Brian Holman committed 2026-11-11 21:00:21 -07:00
commit 3cc37be5fb
50 files changed
+10146

No files matched your search

+80
View File
@@ -0,0 +1,80 @@
// autostart.c - Program to be run by the Disk Basic DOS command.
// By Pierre Sarrazin <http://sarrazip.com/>
// This file is in the public domain.
//
// Reference: Roger Schrag, "A Special Use For The DOS Command",
// The Rainbow, November 1984, p.140.
//
// To compile: cmoc --dos autostart.c
// To install on CoCo disk image: install-coco-boot-loader some-image.dsk autostart.bin
// To run on CoCo: type DOS and <Enter> to automatically run *.BAS.
//
// Version history:
// 0.1.0 2016-01-16 Use of legacy.h discontinued.
// 0.1.1 2018-04-03 Adapted to CMOC 0.1.51 (const).
// 0.1.2 2018-08-04 Basic line now forced to be uppercase.
#include <coco.h>
#define ENDFLG 0x00 // STOP/END FLAG: POSITIVE=STOP, NEG=END
#define CINBFL 0x70 // CONSOLE IN BUFFER FLAG: 00=NOT EMPTY, $FF=EMPTY
#define RVEC4 0x016a // RAM hook: CONSOLE IN
byte oldHookInstr;
word oldHookAddr;
const char *basicLineReader;
void feedKeyboard()
{
word preservedX;
asm("stx", preservedX);
* (byte *) CINBFL = 0; // console in buffer now not empty
char nextBasicByte = (char) toupper(*basicLineReader);
++basicLineReader;
if (nextBasicByte == 0) // if finished returning Basic line
{
* (byte *) RVEC4 = oldHookInstr;
* (word *) (RVEC4 + 1) = oldHookAddr;
nextBasicByte = '\r'; // return "Enter" to cause execution of Basic line
}
asm {
lda nextBasicByte
ldx preservedX
tfr u,s // discard stack frame
leas 4,s // discard previous stack frame ptr and return addr
rts // return to caller of CONSOLE IN
}
}
int main()
{
* (byte *) ENDFLG = - * (byte *) ENDFLG; // why?
basicLineReader =
#ifndef COMMAND
"LOADM\"BONEQ.BIN\":EXEC"
#else
COMMAND
#endif
;
// Install function feedKeyboard() as CONSOLE IN routine.
//
oldHookInstr = * (byte *) RVEC4;
oldHookAddr = * (word *) (RVEC4 + 1);
* (byte *) RVEC4 = 0x7e; // JMP instruction
* (void **) (RVEC4 + 1) = (void *) feedKeyboard;
* (word *) 0x2600 = 0; // overwrite "OS" marker with two null bytes
asm("jmp", "$ac7c"); // go interpret a Basic line (which is read from console)
return 0; // avoids compiler error
}
+242
View File
@@ -0,0 +1,242 @@
#!/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()
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env python3
"""Validate authored anatomy facts and regenerate the small CMOC question table."""
import argparse
import json
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
CODES=('CRANIUM','MANDIBLE','CLAVICLE','SCAPULA','STERNUM','RIBS','CERVICAL','THORACIC','LUMBAR','SACRUM','COCCYX','PELVIS','HUMERUS','RADIUS','ULNA','CARPALS','METACARPALS','FINGERS','FEMUR','PATELLA','TIBIA','FIBULA','TARSALS','METATARSALS','TOES')
def generated():
rows=json.loads((ROOT/'data/bones.json').read_text());assert tuple(r['code'] for r in rows)==CODES
seen=set()
for row in rows:
assert 0<len(row['name'])<=22 and 0<len(row['hint'])<=30
for value in [row['name']]+row['aliases']:
assert value.isascii() and len(value)<40 and '|' not in value
normalized=' '.join(value.lower().split());assert normalized and normalized not in seen
seen.add(normalized)
assert all(a==a.lower() and a==' '.join(a.split()) for a in row['aliases'])
out='/* Generated from data/bones.json; labels/codes remain in the authoring data. */\n#include "quiz.h"\nconst Bone bones[BONE_COUNT] = {\n'
for row in rows:out+=' {'+', '.join(json.dumps(value) for value in (row['name'],row['hint'],'|'.join(row['aliases'])))+'},\n'
return out+'};\n'
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--check',action='store_true');args=parser.parse_args();out=generated();path=ROOT/'src/bones.c'
if args.check:assert path.read_text()==out,'Regenerate src/bones.c';print('PASS 25 anatomy topics, unique aliases, bounds, and generated C identity.')
else:path.write_text(out);print('Generated src/bones.c')