Cotton code
162 lines · 7.4 KB · PythonRaw
#!/usr/bin/env python3"""Put the cinema's painted materials into the Loom package's catalogue.    python3 scripts/import-cinemas-materials.py <object> [<materials directory>]    python3 scripts/import-cinemas-materials.py all [<materials directory>]The layers were painted with Codex (4 Nov 2026, Round 14, after the PictureHouse pictures, `cinemas13-house`) and cut out of wordless masters; thedirectory (`cinemas14-materials`) holds them with `layout.json`, which placeseach in its object's box, in its pixels. No word, numeral, poster or still ison any of them: the faces draw those live, and a film's poster is the record'sown picture laid behind the frame's aperture. One function per object, so eachCinemas face job imports the objects it draws, and a layer two faces share(the progress strip and the stub, under the poster and on the lobby card) isimported once, by the first.    ground   the Picture House every Cinemas face stands in             (`FaceGround.velvet`, laid by `FaceGroundSurface`)        velvet          the curtain-red velvet, a seamless tile (JPEG)        house-light     the warm pool of the one house light, laid once                        upper left    poster   the one-sheet in its brass-cornered lobby frame             (CottonFaces' `Cotton/FilmPosterFace.swift`)        frame           the black frame and its brass corners, the poster's                        aperture cut through it, the cream marquee blank        frame-shadow    its shadow, larger than the frame        progress-strip  the red enamel strip, a 9-slice (its caps                        `layout.json`'s `nineSliceInsets`)        stub            the blank ticket stub, its stamp box and date rule                        printed red, baked at its tilt        stub-shadow     its shadow, larger than the stub        season-card     one blank cream season card, laid up to three times                        behind a series' frame    lobby    the episode's landscape lobby card             (CottonFaces' `Cotton/EpisodeLobbyFace.swift`; it lays the             poster's progress strip and stub, imported once, above)        lobby-card      the slim cream card and its brass corners, the                        still's aperture cut through it, the caption blank        lobby-card-shadow  its shadow, larger than the card    doors    the three doors of an empty Films deck, as act pictures: each             door laid over its own shadow (64 pixels past it on every             side, `layout.json`'s doors' `shadow`) and kept once as             `act-<object>`, one of the core's ACT_OBJECTS, at the act             objects' size (360 pixels on its longer side, as             `import-act-objects.py` keeps them). Requires Pillow.        door-files      the cream string-tie envelope (Add files)                        -> act-pouch        door-folder     the red cloth folder, a cream page peeking                        (Add a folder) -> act-portfolio        door-find       the small brass-cornered lobby frame, its backing                        blank (Find a film) -> act-frame    marquee  the plate the Films player lays the episode's caption on             (CottonFaces' `Cotton/CinemaMarquee.swift`)        marquee-plate   the charcoal plate under one worn brass ruleEach is at least 3x the most it is drawn at on a phone, declared 3x (2x onthe Mac) as the card paper is; the faces set the frame they draw each at.The places the faces read off `layout.json` (the aperture, the marquee's andthe strip's rects, the stub's tuck and its stamp, the season cards' offsetsand angles, the house light's rect and strength) are their knobs(`FilmPosterFaceKnobs`, `EpisodeLobbyFaceKnobs`, `CinemaMarqueeKnobs`,`FaceGroundLamp`): a repainted layer owes new ones."""import jsonimport pathlibimport sysHERE = pathlib.Path(__file__).resolve().parentCATALOGUE = HERE.parent / 'apps/loom/Sources/CottonPaper/Media.xcassets'DEFAULT = pathlib.Path('/Volumes/Cotton SSD/lanes/features/out/cinemas14-materials')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 put(source, names):    """Each of `names`, the one picture of that name in `source`, into the catalogue; its size."""    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]        imageset(name, picture.suffix[1:]).write_bytes(picture.read_bytes())        total += picture.stat().st_size        print(f'{picture.name} -> {name}')    return totaldef ground(source):    return put(source, ['velvet', 'house-light'])def poster(source):    return put(source, ['frame', 'frame-shadow', 'progress-strip', 'stub', 'stub-shadow', 'season-card'])def lobby(source):    return put(source, ['lobby-card', 'lobby-card-shadow'])DOORS = {'door-files': 'pouch', 'door-folder': 'portfolio', 'door-find': 'frame'}DOOR_SHADOW_REACH = 64ACT_SIDE = 360def doors(source):    from PIL import Image    total = 0    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')        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')            if laid.size != (picture.width + 2 * DOOR_SHADOW_REACH, picture.height + 2 * DOOR_SHADOW_REACH):                sys.exit(f'{painted}-shadow is not {DOOR_SHADOW_REACH} pixels past {painted} on every side')            laid.alpha_composite(picture, (DOOR_SHADOW_REACH, DOOR_SHADOW_REACH))        laid.thumbnail((ACT_SIDE, ACT_SIDE), Image.Resampling.LANCZOS)        target = imageset(name, 'png')        laid.save(target, optimize=True)        total += target.stat().st_size        print(f'{painted} over its shadow -> {name} {laid.size[0]}x{laid.size[1]}')    return totaldef marquee(source):    return put(source, ['marquee-plate'])OBJECTS = {'ground': ground, 'poster': poster, 'lobby': lobby, 'doors': doors, 'marquee': marquee}def main(argv):    if not argv or argv[0] not in [*OBJECTS, 'all']:        sys.exit(f'import-cinemas-materials: name an object ({", ".join(OBJECTS)}) or all')    source = pathlib.Path(argv[1]) if len(argv) > 1 else DEFAULT    chosen = OBJECTS.values() if argv[0] == 'all' else [OBJECTS[argv[0]]]    total = sum(object_(source) for object_ in chosen)    print(f'{total // 1024} KB in all')if __name__ == '__main__':    main(sys.argv[1:])