"""Precompute a rotating cube for petcube: src/cubedata.h. 256 frames of one seamless rotation (X turns once, Y twice, Z once per loop), perspective-projected onto the 80x46 quarter-block grid (2x2 "pixels" per character, rows 0-22). Per frame: 8 vertices as (x, y) bytes. The cube is see-through, so every edge is drawn and no visibility data is needed. python projects/petcube/tools/gen_cube.py """ import math import os FRAMES = 256 W, H = 80, 46 # pixel grid used by the cube CX, CY = 39.5, 22.5 # centre of that grid DIST = 3.6 # camera distance (cube spans -1..1) V = [(x, y, z) for x in (-1, 1) for y in (-1, 1) for z in (-1, 1)] # faces as vertex loops (used only to list the 12 edges) FACES = [ (0, 1, 3, 2), # x = -1 (4, 6, 7, 5), # x = +1 (0, 4, 5, 1), # y = -1 (2, 3, 7, 6), # y = +1 (0, 2, 6, 4), # z = -1 (1, 5, 7, 3), # z = +1 ] EDGES = sorted({tuple(sorted((f[i], f[(i + 1) % 4]))) for f in FACES for i in range(4)}) assert len(EDGES) == 12 def rotate(p, ax, ay, az): x, y, z = p y, z = y * math.cos(ax) - z * math.sin(ax), y * math.sin(ax) + z * math.cos(ax) x, z = x * math.cos(ay) + z * math.sin(ay), -x * math.sin(ay) + z * math.cos(ay) x, y = x * math.cos(az) - y * math.sin(az), x * math.sin(az) + y * math.cos(az) return x, y, z def project(frames_scale): out = [] for t in range(FRAMES): a = 2 * math.pi * t / FRAMES pts = [] for p in V: x, y, z = rotate(p, a, 2 * a, a) k = frames_scale / (z + DIST) pts.append((CX + x * k, CY + y * k)) out.append(pts) return out # scale so the largest extent just fits the grid raw = project(1.0) ext = max(max(abs(x - CX) / (W / 2 - 0.6), abs(y - CY) / (H / 2 - 0.6)) for f in raw for x, y in f) frames = project(1.0 / ext) xy = [] for pts in frames: for x, y in pts: xi, yi = int(round(x)), int(round(y)) assert 0 <= xi < W and 0 <= yi < H, (xi, yi) xy += [xi, yi] src = os.path.join(os.path.dirname(__file__), '..', 'src', 'cubedata.h') with open(src, 'w', newline='\n') as fh: fh.write('/* Generated by tools/gen_cube.py: do not edit. */\n') fh.write('#define CUBE_FRAMES %d\n' % FRAMES) fh.write('static const unsigned char edge_a[12] = { %s };\n' % ', '.join(str(a) for a, b in EDGES)) fh.write('static const unsigned char edge_b[12] = { %s };\n' % ', '.join(str(b) for a, b in EDGES)) fh.write('/* per frame: x0, y0, ... x7, y7 on the 80x46 grid */\n') fh.write('static const unsigned char cube_xy[%d] = {\n' % len(xy)) for i in range(0, len(xy), 16): fh.write(' ' + ','.join(str(v) for v in xy[i:i + 16]) + ',\n') fh.write('};\n') print('wrote', os.path.normpath(src))