Cotton code
238 lines · 11.7 KB · PythonRaw
#!/usr/bin/env python3"""Put the standing hardback's painted materials into the Loom package's catalogue.    python3 scripts/import-books-materials.py [<materials directory>]    python3 scripts/import-books-materials.py doors [<doors directory>]    python3 scripts/import-books-materials.py views [<view tiles directory>]    python3 scripts/import-books-materials.py list-ground    python3 scripts/import-books-materials.py layers [<books27 layers directory>]The layers were painted for Cotton Books (Round 8, 4 Nov 2026, after theheld-book picture the coordinator chose) and cut from one wordless hardbackmaster; the directory holds them with `layout.json`, which places each in an846 x 1260 book box (CottonFaces' `Cotton/BookHardbackFace.swift` lays them byit, its knobs `BookHardbackFaceKnobs` measured off it; the felt by`FaceGroundSurface`). No word, number or star is on any of them: the facedraws the title, the author, the band's and the slip's words and the starslive, and a book's cover is the record's own picture, laid behind theboards' cut-out.    book-boards         the standing hardback: spine, boards and page block,                        the front jacket's region a transparent aperture    book-shadow         its shadow on the felt, larger than the book    book-jacket-blank   the jacket's cream paper and double rule, laid in the                        aperture for a book kept without a cover    book-ribbon         the gold cloth ribbon, full length, its swallowtail                        the last 64 pixels    book-band           the paper belly band round the lower third    book-band-shadow    its contact shadow    books-felt          the dark navy felt, a seamless tile (JPEG)The page block is the boards' own (no `book-pages`), and a finished book'sdate and stars are the band's live type (no stamp).Each is at least 3x the most it is drawn at on a phone (the book is 846 pxwide, drawn at most 250 points), declared 3x (2x on the Mac) as the cardpaper is; the face sets the scale it draws each at."""import jsonimport pathlibimport sysHERE = pathlib.Path(__file__).resolve().parentCATALOGUE = HERE.parent / 'apps/loom/Sources/CottonPaper/Media.xcassets'NAMES = [    'book-boards', 'book-shadow', 'book-jacket-blank', 'book-ribbon', 'book-band', 'book-band-shadow',    'books-felt',]def imageset(name, extension):    folder = CATALOGUE / f'{name}.imageset'    folder.mkdir(exist_ok=True)    for old in folder.iterdir():        old.unlink()    contents = {        'images': [            {'filename': f'{name}.{extension}', 'idiom': 'universal', 'scale': '3x'},            {'filename': f'{name}.{extension}', 'idiom': 'mac', 'scale': '2x'},        ],        'info': {'author': 'xcode', 'version': 1},        'properties': {'preserves-vector-representation': False},    }    (folder / 'Contents.json').write_text(json.dumps(contents, indent=2) + '\n')    return folder / f'{name}.{extension}'def main(source):    source = pathlib.Path(source)    total = 0    for name in NAMES:        found = [source / f'{name}.{extension}' for extension in ('png', 'jpg') if (source / f'{name}.{extension}').exists()]        if len(found) != 1:            sys.exit(f'{source} holds {len(found)} pictures named {name}, not one')        picture = found[0]        target = imageset(name, picture.suffix[1:])        target.write_bytes(picture.read_bytes())        total += picture.stat().st_size        print(f'{picture.name} -> {name}')    print(f'{total // 1024} KB in all')# THE BOOKS DOORS' PICTURES (Round 15, 4 Nov 2026): Plus's three doors on# the Books deck, painted wordless — a cream catalogue card with red rules# (Find a book), a brown-paper parcel tied with string (Add a file), three# reading-record cards held by a rubber band (Bring Goodreads in). Each is# laid over its own separate shadow (`<name>-shadow.png`, 64 px larger on# every side, `layout.json`'s shadowOffset) and kept once, as an act picture# (`act-<object>`, one of the core's ACT_OBJECTS) at the act objects' size:# 360 px on its longer side, declared 3x (2x on the Mac), as# `import-act-objects.py` keeps the others. Requires Pillow.DOORS = {'book-find': 'catalogue', 'book-file': 'parcel', 'book-goodreads': 'stack'}ACT_SIDE = 360def doors(source):    from PIL import Image    source = pathlib.Path(source)    layout = json.loads((source / 'layout.json').read_text())['layers']    for painted, object_name in DOORS.items():        name = f'act-{object_name}'        if (CATALOGUE / f'{name}.imageset').exists():            sys.exit(f'{name} is in the catalogue already: nothing is imported twice')        shadowed = layout[f'{painted}-shadow.png']        dx, dy = (-offset for offset in shadowed['shadowOffset'])        with Image.open(source / f'{painted}-shadow.png') as shadow, Image.open(source / f'{painted}.png') as picture:            laid = shadow.convert('RGBA')            picture = picture.convert('RGBA')            if picture.getchannel('A').getextrema()[0] != 0:                sys.exit(f'{painted}: requires a transparent background')            laid.alpha_composite(picture, (dx, dy))        laid.thumbnail((ACT_SIDE, ACT_SIDE), Image.Resampling.LANCZOS)        target = imageset(name, 'png')        laid.save(target, optimize=True)        print(f'{painted} over its shadow -> {name} {laid.size[0]}x{laid.size[1]}')# THE BOOKS VIEWS' TILES (Round 17, variation b, 5 Nov 2026): the seven# views' fan tiles, each a cream card with one small painted object at its# head and nothing else, wordless — the fan types the view's name and count# live beneath the object. Each `tile-<view>.png` is cut at 474 x 696 with# its alpha (3x the fan's 158 x 232 pt tile) and kept once, as it is, as a# view picture (`view-<picture>`, one of the core's VIEW_PICTURES), declared# 3x (2x on the Mac). The originals stay where they are.VIEWS = {    'reading': 'open_book', 'want_to_read': 'ribbon', 'finished': 'banded_book', 'stopped': 'slipped_book',    'highlights': 'pencil', 'on_phone': 'keypad_phone', 'all': 'book_pile',}TILE = (474, 696)def png_size_with_alpha(path):    """A PNG's width and height, refused unless it is RGBA (colour type 6)."""    head = path.read_bytes()[:26]    if head[:8] != b'\x89PNG\r\n\x1a\n' or head[12:16] != b'IHDR':        sys.exit(f'{path.name}: not a PNG')    if head[25] != 6:        sys.exit(f'{path.name}: requires an alpha channel (RGBA)')    return int.from_bytes(head[16:20], 'big'), int.from_bytes(head[20:24], 'big')def views(source):    source = pathlib.Path(source)    for view, picture in VIEWS.items():        name = f'view-{picture}'        if (CATALOGUE / f'{name}.imageset').exists():            sys.exit(f'{name} is in the catalogue already: nothing is imported twice')        tile = source / f'tile-{view}.png'        if png_size_with_alpha(tile) != TILE:            sys.exit(f'{tile.name}: requires {TILE[0]} x {TILE[1]} pixels')        imageset(name, 'png').write_bytes(tile.read_bytes())        print(f'{tile.name} -> {name}')# THE LIST TILE'S GROUND (5 Nov 2026): a list's fan tile is made from what# it holds — its first members' covers, or the person's own picture, laid on# the card where a view tile's painted object stands. The card is the view# tiles' own worn cream card with no object on it, made from All's tile# (`scripts/list-ground.swift`: its blank lower half kept and mirrored over# its upper half), kept as `list-tile-ground`, 474 x 696, 3x.def list_ground():    import subprocess    tile = CATALOGUE / 'view-book_pile.imageset/view-book_pile.png'    out = imageset('list-tile-ground', 'png')    subprocess.run(['swift', str(HERE / 'list-ground.swift'), str(tile), str(out)], check=True)    if png_size_with_alpha(out) != TILE:        sys.exit(f'{out.name}: requires {TILE[0]} x {TILE[1]} pixels')    print(f'{tile.name} -> list-tile-ground')# THE BOOKS27 LAYERS (Codex, 14 Nov 2026, after the 4 Nov pictures# `books27`): painted wordless, each with real alpha, placed by the folder's# `layout.json` (the faces' knobs are measured off it).##   highlight-strip-top     a highlight's torn strip in three bands, 2400 px#   highlight-strip-middle  wide (`Cotton/HighlightPassageFace.swift`): the top#   highlight-strip-bottom  and the foot 250 rows each, the middle 400 rows and#                           vertically periodic, repeated (its last repeat#                           partial) to the height the words need#   highlight-strip-shadow  the strip's shadow, 60 px larger on every side,#                           sliced as the strip is#   highlight-curl          the curled lower right corner a note is#   highlight-curl-shadow   pencilled on, and its shadow, 40 px larger#   books-lamp              the felt's warm lamp from the upper left and its#                           faint pool lower right, one light-only overlay the#                           size of the screen (1290 x 2796, its opacity#                           baked in: `FaceGround.feltNavy.lamp`)#   book-lying-*            a stopped book lying on the felt, turned, in#                           three-quarter view (`stopped/`): the book (its#                           cover a hole the cover is warped into), its#                           shadow, the slip out of its fore-edge and the#                           slip's shadow, the cover's gloss and the ribbon;#                           all on one 1290 x 1600 canvas, each kept cut to#                           its alpha's bounds, which this prints for#                           `BookHardbackFaceKnobs.lying`## The strip's bands are kept at half their width (1200 px, more than 3x the# 340-point card), every other layer as painted; declared 3x (2x on the Mac).# Requires Pillow.STRIP = ['highlight-strip-top', 'highlight-strip-middle', 'highlight-strip-bottom', 'highlight-strip-shadow']LAYERS = ['highlight-curl', 'highlight-curl-shadow', 'books-lamp']LYING = ['book-lying', 'book-lying-shadow', 'book-lying-slip', 'book-lying-slip-shadow', 'book-lying-gloss', 'book-lying-ribbon']def layers(source):    from PIL import Image    source = pathlib.Path(source)    for name in STRIP + LAYERS:        with Image.open(source / f'{name}.png') as painted:            picture = painted.convert('RGBA')        if picture.getchannel('A').getextrema()[0] != 0:            sys.exit(f'{name}.png: requires a transparent alpha')        if name in STRIP:            picture = picture.resize((picture.width // 2, picture.height // 2), Image.Resampling.LANCZOS)        picture.save(imageset(name, 'png'), optimize=True)        print(f'{name}.png {picture.width}x{picture.height} -> {name}')    for name in LYING:        with Image.open(source / 'stopped' / f'{name}.png') as painted:            picture = painted.convert('RGBA')        if picture.size != (1290, 1600):            sys.exit(f'stopped/{name}.png: requires the 1290 x 1600 canvas, not {picture.size}')        box = picture.getchannel('A').getbbox()        picture.crop(box).save(imageset(name, 'png'), optimize=True)        print(f'stopped/{name}.png bounds x {box[0]} y {box[1]} w {box[2] - box[0]} h {box[3] - box[1]} -> {name}')if __name__ == '__main__':    if len(sys.argv) > 1 and sys.argv[1] == 'doors':        doors(sys.argv[2] if len(sys.argv) > 2 else '/Volumes/Cotton SSD/lanes/features/out/doors15')    elif len(sys.argv) > 1 and sys.argv[1] == 'list-ground':        list_ground()    elif len(sys.argv) > 1 and sys.argv[1] == 'layers':        layers(sys.argv[2] if len(sys.argv) > 2 else '/Volumes/Cotton SSD Mini/lanes/_refs/books27/layers')    elif len(sys.argv) > 1 and sys.argv[1] == 'views':        views(sys.argv[2] if len(sys.argv) > 2 else '/Volumes/Cotton SSD/lanes/features/out/books17-view-tiles')    else:        main(sys.argv[1] if len(sys.argv) > 1 else '/Volumes/Cotton SSD/lanes/features/out/books8-materials')