Files
amiga/BoingBall3D/generate.py
T

58 lines
2.6 KiB
Python

from pathlib import Path
import math
from PIL import Image, ImageDraw
root=Path(__file__).parent
out=root/'assets'
out.mkdir(exist_ok=True)
W,H,R,N=400,300,57,64
palette=[(170,170,170),(145,0,145),(75,75,75),(110,110,110),(215,215,215)]
palette += [(int(160+i*95/7),int(8+i*12/7),int(8+i*12/7)) for i in range(8)]
palette += [(int(160+i*95/7),)*3 for i in range(8)]
bg=Image.new('P',(W,H),0)
bg.putpalette(sum((list(c) for c in palette),[])+[0]*(768-len(palette)*3))
d=ImageDraw.Draw(bg)
# Perspective room: same camera and dimensions used by the C animation.
def project(x,y,z):
return (200+x*340/(260+z),100+(150-y)*340/(260+z))
def line(a,b): d.line((project(*a),project(*b)),fill=1)
def plane(points,color):d.polygon([project(*v) for v in points],fill=color)
plane([(-190,0,400),(190,0,400),(190,250,400),(-190,250,400)],4)
plane([(-190,0,0),(-190,0,400),(-190,250,400),(-190,250,0)],3)
plane([(190,0,0),(190,0,400),(190,250,400),(190,250,0)],3)
for x in range(-190,191,38):
line((x,0,0),(x,0,400))
line((x,0,400),(x,250,400))
for z in range(0,401,40):
line((-190,0,z),(190,0,z))
line((-190,0,z),(-190,250,z))
line((190,0,z),(190,250,z))
for y in range(0,251,50):
line((-190,y,400),(190,y,400))
line((-190,y,0),(-190,y,400))
line((190,y,0),(190,y,400))
(out/'background.bin').write_bytes(bg.tobytes())
sprites=bytearray()
for phase in range(N):
im=Image.new('P',(R*2,R*2),255); im.putpalette(bg.getpalette())
for y in range(R*2):
for x in range(R*2):
nx=(x+.5-R)/R; ny=(y+.5-R)/R; rr=nx*nx+ny*ny
if rr>=1: continue
nz=math.sqrt(1-rr)
# Tilt the rotation axis, as in the original red/white ball.
a=.24; xx=nx*math.cos(a)-ny*math.sin(a); yy=nx*math.sin(a)+ny*math.cos(a)
# The checker pattern repeats after two columns (45 degrees).
# Sample that period densely instead of aliasing a full turn.
lon=math.atan2(xx,nz)+phase*(math.pi/4)/N
lat=math.acos(max(-1,min(1,yy)))
red=(math.floor((lon+math.pi)*8/math.pi)+math.floor(lat*8/math.pi))%2
light=max(0,min(1,.45+.55*(nz*.8-nx*.35-ny*.35)))
shade=min(7,int(light*7))
im.putpixel((x,y),(5 if red else 13)+shade)
sprites.extend(im.tobytes())
if phase==3:
preview=bg.copy(); preview.paste(im,(120,65),im.point(lambda p:0 if p==255 else 255).convert('1'))
preview.convert('RGB').save(out/'preview.png')
(out/'sprites.bin').write_bytes(sprites)
(root/'palette.h').write_text('static unsigned char colors[][3] = {'+','.join('{%d,%d,%d}'%c for c in palette)+'};\n')