221 lines
11 KiB
Python
221 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Qualify the local 640x225 graphics driver on isolated VCC Plus machines.
|
|
|
|
Supply your own ROMs explicitly. This builds an independent fixture disk into a
|
|
fresh ignored run directory, never uses the normal emulator or the game disk,
|
|
and requires no Python packages beyond the standard library. Host arithmetic
|
|
checks additionally need a host C compiler; --skip-host records that skip.
|
|
"""
|
|
import argparse
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import plistlib
|
|
import re
|
|
import selectors
|
|
import shutil
|
|
import struct
|
|
import subprocess
|
|
import tempfile
|
|
import zlib
|
|
|
|
ROOT=Path(__file__).resolve().parents[1]
|
|
COLORS=((0,0,0),(255,255,255),(255,255,0),(255,85,85))
|
|
|
|
|
|
def sha(path):
|
|
return hashlib.sha256(path.read_bytes()).hexdigest()
|
|
|
|
|
|
def run(command,folder,log):
|
|
with log.open('ab') as stream:
|
|
subprocess.run([str(v) for v in command],cwd=folder,stdout=stream,
|
|
stderr=subprocess.STDOUT,check=True)
|
|
|
|
|
|
def host_arithmetic(folder,compiler):
|
|
source=(ROOT/'src/graphics.c').read_text()
|
|
start=source.index('void gfx_fill_rect(')
|
|
end=source.index('\nvoid gfx_plot(',start)
|
|
(folder/'graphics_fill_under_test.h').write_text(source[start:end]+'\n')
|
|
executable=folder/'graphics_arithmetic'
|
|
log=folder/'host-build.log'
|
|
run([compiler,'-std=c99','-O2','-Wall','-Wextra','-Werror','-I'+str(ROOT),
|
|
'-I'+str(folder),ROOT/'tests/graphics_arithmetic.c','-o',executable],folder,log)
|
|
run([executable],folder,log)
|
|
|
|
|
|
def build_fixture(app,folder):
|
|
tools=app/'Contents/Resources/Toolchain/bin'
|
|
compiler=tools/'cmoc'
|
|
log=folder/'guest-build.log'
|
|
for stem,source in (('fixture',ROOT/'tests/graphics_fixture.c'),
|
|
('graphics',ROOT/'src/graphics.c')):
|
|
run([compiler,'--coco','-O2','--intermediate','--intdir='+str(folder),
|
|
'-I'+str(ROOT),'-c','-o',folder/(stem+'.o'),source],folder,log)
|
|
run([compiler,'--coco','--org=2000','--limit=7800','--intermediate','-o',
|
|
folder/'BONEQ.BIN',folder/'fixture.o',folder/'graphics.o'],folder,log)
|
|
run([compiler,'--dos','-O0','--limit=2800','-o',folder/'boot.bin',
|
|
ROOT/'tools/boot.c'],folder,log)
|
|
disk=folder/'fixture.dsk'
|
|
disk.write_bytes(bytes([255])*(35*18*256))
|
|
run([tools/'install-coco-boot-loader',disk,folder/'boot.bin'],folder,log)
|
|
run([tools/'writecocofile',disk,folder/'BONEQ.BIN'],folder,log)
|
|
source=(folder/'BONEQ.map').read_text()
|
|
phase=int(re.search(r'Symbol: _phase .*?= ([0-9A-Fa-f]+)',source)[1],16)
|
|
return disk,phase
|
|
|
|
|
|
def png(path):
|
|
"""Decode the helper's 8-bit RGB/RGBA PNG without optional image modules."""
|
|
blob=path.read_bytes();position=8;compressed=b''
|
|
assert blob[:8]==b'\x89PNG\r\n\x1a\n'
|
|
while position<len(blob):
|
|
count=int.from_bytes(blob[position:position+4],'big')
|
|
kind=blob[position+4:position+8]
|
|
data=blob[position+8:position+8+count];position+=count+12
|
|
if kind==b'IHDR':width,height,depth,color,*_=struct.unpack('>IIBBBBB',data)
|
|
if kind==b'IDAT':compressed+=data
|
|
assert depth==8 and color in (2,6)
|
|
channels=3 if color==2 else 4;stride=width*channels
|
|
raw=zlib.decompress(compressed);prior=bytearray(stride);rows=[];position=0
|
|
for _ in range(height):
|
|
method=raw[position];position+=1
|
|
row=bytearray(raw[position:position+stride]);position+=stride
|
|
assert method in range(5)
|
|
for i in range(stride):
|
|
a=row[i-channels] if i>=channels else 0
|
|
b=prior[i];c=prior[i-channels] if i>=channels else 0
|
|
if method==1:prediction=a
|
|
elif method==2:prediction=b
|
|
elif method==3:prediction=(a+b)//2
|
|
elif method==4:
|
|
v=a+b-c;pa=abs(v-a);pb=abs(v-b);pc=abs(v-c)
|
|
prediction=a if pa<=pb and pa<=pc else b if pb<=pc else c
|
|
else:prediction=0
|
|
row[i]=(row[i]+prediction)&255
|
|
rows.append(row);prior=row
|
|
return width,height,channels,rows
|
|
|
|
|
|
def rectangle(image,x,y,width,height,color):
|
|
for yy in range(y,min(225,y+height)):
|
|
for xx in range(x,min(640,x+width)):
|
|
image[yy*640+xx]=color
|
|
|
|
|
|
def expected_page(page):
|
|
if page==1:
|
|
image=[1]*(640*225)
|
|
for i in range(1,5):
|
|
rectangle(image,(i*8192%160)*4-3,i*8192//160,9,1,2)
|
|
rectangle(image,638,223,9,9,0)
|
|
rectangle(image,639,0,1,1,3);rectangle(image,0,224,1,1,3)
|
|
else:
|
|
image=[2]*(640*225)
|
|
rectangle(image,0,0,640,1,1);rectangle(image,0,224,640,1,3)
|
|
rectangle(image,0,0,1,225,0);rectangle(image,639,0,1,225,0)
|
|
rectangle(image,17,51,619,154,3);rectangle(image,18,52,617,152,1)
|
|
if page==4:
|
|
rectangle(image,1,1,2,1,3);rectangle(image,639,224,1,1,1)
|
|
return image
|
|
|
|
|
|
def qualify_cpu(app,folder,disk,phase,cpu,system_rom,disk_rom):
|
|
stderr=(folder/(cpu+'-helper.log')).open('w')
|
|
process=subprocess.Popen([str(app/'Contents/Helpers/vcc-playtest')],
|
|
stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=stderr,text=True,bufsize=1)
|
|
selector=selectors.DefaultSelector();selector.register(process.stdout,selectors.EVENT_READ)
|
|
def call(op,**kwargs):
|
|
process.stdin.write(json.dumps(dict(op=op,**kwargs))+'\n');process.stdin.flush()
|
|
if not selector.select(timeout=60):raise TimeoutError('Playtest helper timed out: '+op)
|
|
line=process.stdout.readline()
|
|
if not line:raise RuntimeError('Playtest helper closed during '+op)
|
|
response=json.loads(line)
|
|
if 'error' in response:raise RuntimeError('Playtest helper rejected '+op+': '+str(response['error']))
|
|
return response['result']
|
|
def step():return call('input',steps=[dict(mask=0,fields=600)])
|
|
def key():return call('input',steps=[dict(mask=1<<31,fields=8),dict(mask=0,fields=600)])
|
|
def current_phase():return call('read_memory',address=phase,count=1)['bytes'][0]
|
|
def capture(name):
|
|
result=call('capture');path=folder/(cpu+'-'+name+'.png')
|
|
path.write_bytes(base64.b64decode(result.pop('png_base64')))
|
|
(folder/(cpu+'-'+name+'.json')).write_text(json.dumps(result,indent=2)+'\n')
|
|
return png(path)
|
|
encode=lambda data:base64.b64encode(data).decode()
|
|
try:
|
|
call('init',system_rom=encode(system_rom),disk_rom=encode(disk_rom),
|
|
disk=encode(disk.read_bytes()),cpu=cpu,boot_keys=[1<<b for b in (4,15,19,48)])
|
|
step();assert current_phase()==1,(cpu,'first page phase',current_phase())
|
|
top=None
|
|
for page in (1,2,3,4):
|
|
if page>1:key();assert current_phase()==page,(cpu,'page phase',page,current_phase())
|
|
width,height,channels,rows=capture('page'+str(page))
|
|
assert (width,height)==(640,480),(cpu,width,height)
|
|
def pixel(x,y):return tuple(rows[y][x*channels:x*channels+3])
|
|
if page==1:
|
|
visible=[y for y in range(height)
|
|
if sum(pixel(x,y)==COLORS[1] for x in range(width))>600]
|
|
assert len(visible)==450 and max(visible)==min(visible)+449,(cpu,'active height')
|
|
top=min(visible)
|
|
expected=expected_page(page)
|
|
for y in range(225):
|
|
for x in range(640):
|
|
value=COLORS[expected[y*640+x]]
|
|
for repeat in (0,1):
|
|
actual=pixel(x,top+y*2+repeat)
|
|
assert actual==value,(cpu,page,x,y,actual,value)
|
|
mmu=call('read_memory',address=0xffa0,count=8)['bytes']
|
|
assert [value&63 for value in mmu]==list(range(0x38,0x40)),(cpu,'MMU restoration')
|
|
key();assert current_phase()==5,(cpu,'exit phase',current_phase())
|
|
result=call('capture')
|
|
assert 'GRAPHICS TEST COMPLETE' in result.get('screen_text',''),(cpu,'BASIC return')
|
|
capture('exit')
|
|
final=call('stop')
|
|
assert final['disk_writes']==0 and final['disk_sha256']==sha(disk),(cpu,'disk changed')
|
|
process.wait(timeout=10)
|
|
return dict(cpu=cpu,ramKB=512,width=640,height=225,frameTop=top,pageFlips=3,frontCopied=True,noPrematurePresentation=True,
|
|
guestPixelsChecked=576000,clipping=True,partialByteEdges=True,
|
|
bankBoundaries=True,MMURestored=True,BASICReturned=True,diskWrites=0)
|
|
finally:
|
|
if process.poll() is None:process.kill();process.wait(timeout=10)
|
|
selector.close();stderr.close()
|
|
|
|
|
|
def main():
|
|
parser=argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--app',type=Path,default=Path('/Applications/VCC Plus.app'))
|
|
parser.add_argument('--rom',type=Path,required=True)
|
|
parser.add_argument('--disk-rom',type=Path,required=True)
|
|
parser.add_argument('--cpu',choices=('6809','6309','both'),default='both')
|
|
parser.add_argument('--evidence',type=Path,default=ROOT/'test-output/graphics')
|
|
parser.add_argument('--cc',default='cc',help='Host C compiler for the arithmetic check')
|
|
parser.add_argument('--skip-host',action='store_true',help='Skip and record the optional host-compiler check')
|
|
args=parser.parse_args()
|
|
args.app=args.app.resolve()
|
|
system_rom=args.rom.read_bytes();disk_rom=args.disk_rom.read_bytes()
|
|
evidence=args.evidence.resolve();evidence.mkdir(parents=True,exist_ok=True)
|
|
folder=Path(tempfile.mkdtemp(prefix='run-',dir=evidence))
|
|
sources=('src/graphics.c','graphics.h','tests/graphics_fixture.c','tests/graphics_arithmetic.c','tests/check_graphics.py','tools/boot.c')
|
|
identity={path:sha(ROOT/path) for path in sources}
|
|
if not args.skip_host:
|
|
compiler=shutil.which(args.cc)
|
|
if not compiler:parser.error('Host C compiler unavailable; supply --cc or record --skip-host.')
|
|
host_arithmetic(folder,compiler);print('PASS host graphics arithmetic',flush=True)
|
|
disk,phase=build_fixture(args.app,folder)
|
|
reports=[]
|
|
for cpu in (('6809','6309') if args.cpu=='both' else (args.cpu,)):
|
|
reports.append(qualify_cpu(args.app,folder,disk,phase,cpu,system_rom,disk_rom))
|
|
print('PASS',cpu,'640x225 pages, front copy, all pixels, clipping, bank seams, MMU and BASIC return',flush=True)
|
|
assert identity=={path:sha(ROOT/path) for path in sources},'Source changed during graphics checks; rerun.'
|
|
info=plistlib.loads((args.app/'Contents/Info.plist').read_bytes())
|
|
report=dict(sourceSHA256=identity,fixtureDiskSHA256=sha(disk),
|
|
emulatorVersion=info.get('CFBundleShortVersionString'),emulatorBuild=info.get('CFBundleVersion'),
|
|
hostArithmetic='skipped by explicit option' if args.skip_host else 'passed',tests=reports)
|
|
(folder/'verification.json').write_text(json.dumps(report,indent=2)+'\n')
|
|
print('Evidence:',folder)
|
|
|
|
|
|
if __name__=='__main__':main()
|