Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

5.6 KB
Raw Blame
#!/usr/bin/env python3
"""Build only the confirmed ASCII octopus into the connected firmware.

The gallery JSON remains the source of truth. Frames are unmodified printable
ASCII, not a runtime GIF. A small registration table follows the eyes as the
head moves, so touch/voice expressions stay attached to the original creature.
"""
import json
import itertools
import sys
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont

root = Path(__file__).resolve().parents[1]
check = '--check' in sys.argv
def emit(path, text):
    if check:
        assert path.read_text() == text, f'{path.name} is stale; run gen_octopus.py'
    else:
        path.write_text(text)

clip = json.loads((root.parent / 'prototype/habitat/assets/creature-references/clips.json').read_text())[0]
assert clip['name'] == 'Octopus / ASCII' and (clip['cols'], clip['rows']) == (54, 27)
assert len(clip['frames']) == len(clip['holds']) == 63
out = ['// Generated by scripts/gen_octopus.py. Do not edit.',
       '// Adapted from ferrebarrat/brrtfetch, gifs/defaults/brrt.gif.',
       '// Exact approved gallery text frames; see prototype/habitat/CREATURE_GALLERY_02.md.',
       '// Shared rows, lossless nibble RLE. No images or runtime conversion.']
rows = [row for frame in clip['frames'] for row in frame]
unique = list(dict.fromkeys(rows))
row_keys = {row: i for i, row in enumerate(unique)}
alphabet = ''.join(sorted(set(''.join(rows))))
assert 1 <= len(alphabet) <= 16 and all(32 <= ord(ch) <= 126 for ch in alphabet)
encoded = []
offsets = [0]
for row in unique:
    for ch, group in itertools.groupby(row):
        count = len(list(group))
        while count:
            take = min(count, 16)
            encoded.append(((take - 1) << 4) | alphabet.index(ch))
            count -= take
    offsets.append(len(encoded))
assert len(encoded) <= 65535 and len(unique) <= 65535
for key, row in enumerate(unique):
    assert ''.join(alphabet[b & 15] * ((b >> 4) + 1)
                   for b in encoded[offsets[key]:offsets[key + 1]]) == row
def array(name, ctype, values):
    out.append(f'static const {ctype} {name}[] = {{')
    out.extend('    ' + ','.join(map(str, values[i:i+24])) + ',' for i in range(0, len(values), 24))
    out.append('};')
array('octopus_data', 'uint8_t', encoded)
array('octopus_row_offsets', 'uint16_t', offsets)
array('octopus_frame_rows', 'uint16_t', [row_keys[row] for row in rows])
out += [f'static const char octopus_alphabet[] = {json.dumps(alphabet)};',
        'static const ht_ascii_clip_t octopus_clip = {',
        f'    .cols=54, .rows=27, .symbols={len(alphabet)}, .frames=63,',
        f'    .unique_rows={len(unique)}, .data_bytes=sizeof octopus_data,',
        '    .alphabet=octopus_alphabet, .frame_rows=octopus_frame_rows,',
        '    .row_offsets=octopus_row_offsets, .data=octopus_data,',
        '};']
eyes = []
ends = []
elapsed = 0
for frame, hold in zip(clip['frames'], clip['holds']):
    assert len(frame) == 27 and all(len(row) == 54 for row in frame)
    assert all(32 <= ord(ch) <= 126 for row in frame for ch in row)
    # The first opening in both solid forehead columns is the upper eyelid.
    row = next(y for y in range(6, 11)
               if sum(ch in ' .,:;xo' for ch in frame[y][19:22]) >= 2
               and sum(ch in ' .,:;xo' for ch in frame[y][30:33]) >= 2) + 1
    assert 8 <= row <= 11
    eyes.append(row)
    elapsed += hold
    ends.append(elapsed)
out += ['static const uint8_t octopus_eyes[] = {' + ','.join(map(str, eyes)) + '};',
        'static const uint16_t octopus_ends[] = {' + ','.join(map(str, ends)) + '};']
emit(root / 'main/ui/habitat/octopus_art.inc', '\n'.join(out) + '\n')

out = ['// Generated by scripts/gen_octopus.py. Habitat Octopus ASCII atlas.',
       '// Derived from Jgs7, (c) 2022 Adel Faure, Velvetyne; SIL OFL 1.1.',
       '// This atlas remains OFL-licensed; see fonts/Jgs-OFL.txt.', '#include "octopus.h"']
# THE ATLAS LADDER. The number is the CELL HEIGHT and the advance is half of it, so a 54 x 27 clip drawn
# in font_N measures 27N tall by 27N wide — font_4 is the 108 px portrait octopus.h talks about and
# font_6 is its 162 px brief one.
#
# 14 and 16 are the Pro's. A 720 px face has room for 27*16 = 432 px of companion where the dial's
# largest is 270, and 14 is the rung the carrying state drops to. They are guarded to the P4 so the
# dial's habitat image does not carry two atlases it can never draw.
PRO_ONLY = (14, 16)
for height in (2, 4, 6, 8, 10, 14, 16):
    width = height // 2
    font = ImageFont.truetype(str(root / 'fonts/jgs7.ttf'), height)
    data = []
    for cp in range(32, 127):
        im = Image.new('L', (width, height))
        ImageDraw.Draw(im).text((0, round(height * 22 / 28)), chr(cp), font=font, fill=255, anchor='ls')
        values = [min(3, (v + 42) // 85) for v in im.get_flattened_data()]
        values += [0] * (-len(values) % 4)
        data.extend(sum(values[j+k] << (6-2*k) for k in range(4)) for j in range(0, len(values), 4))
    if height in PRO_ONLY:
        out.append('#if HT_FACE_PX >= 720')
    out.append(f'static const uint8_t octopus_{height}_pixels[] = {{')
    out.extend('    ' + ','.join(map(str, data[i:i+24])) + ',' for i in range(0, len(data), 24))
    out.append(f'}};\nconst ht_font_t ht_octopus_font_{height} = {{32,126,{width},{height},octopus_{height}_pixels}};')
    if height in PRO_ONLY:
        out.append('#endif')
    print(f'Octopus font: {width}x{height}, {len(data)} bytes')
emit(root / 'main/ui/habitat/octopus_font.c', '\n'.join(out) + '\n')
packed = len(encoded) + 2 * (len(offsets) + len(rows)) + len(alphabet) + 1
print(f'Octopus: {len(eyes)} ASCII poses, {elapsed} ms loop, {63*27*55} -> {packed} frame bytes')