Cotton code
100 lines · 3.9 KB · PythonRaw
#!/usr/bin/env python3"""Put the reader's papers into the Loom package's catalogue.    python3 scripts/import-reader-materials.py [layers directory]The day paper is MADE here (the owner chose the centred page on 29 Oct 2026,`reader-look/1-centred`, and said the book page "looks too much paper"): aplain warm cream, the picture's blank paper, with the faintest grain — a fineeven noise in its brightness alone, no mottle, no fibres, the same every run(a fixed seed). Fine noise has no seam, so a small tile repeats unseen.The night paper was painted with Codex (29 Oct 2026, after `reader-look/4-lamp`)and cut into a tile (the painting's slow light taken out, made seamless by acrossfade with itself rolled by half, its mean brought to the picture's paper,512 px); given a layers directory, it is taken from there as `reader-night`.The reader lays both (CottonUI's `Deck/Reader/ReadGround.swift`); the lamp'spool and every word are drawn live. No word or number is on either tile.    reader-paper   the page's plain cream, the faintest grain (PNG, made here)    reader-night   the lamp's warm near-black, the faintest tooth (JPEG)Each is declared 3x (2x on the Mac) as the notebook's linen is."""import jsonimport pathlibimport randomimport structimport sysimport zlibHERE = pathlib.Path(__file__).resolve().parentCATALOGUE = HERE.parent / 'apps/loom/Sources/CottonPaper/Media.xcassets'# The day paper: the centred picture's blank cream (`ReaderMaterial.paper`),# the grain's spread in levels of brightness (one standard deviation, the# picture's own is about 1.3 with its JPEG's noise in it), the tile's side.CREAM = (243.1, 235.6, 224.9)GRAIN = 1.0SIDE = 256SEED = 29102026def 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 png(width, height, rows):    """An 8-bit RGB PNG of `rows`, each a bytes of width * 3."""    def chunk(kind, data):        return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data) & 0xFFFFFFFF)    raw = b''.join(b'\x00' + row for row in rows)    header = struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)    return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', header) + chunk(b'IDAT', zlib.compress(raw, 9)) + chunk(b'IEND', b'')def cream():    """The day paper: the cream with a fine grain in its brightness."""    rng = random.Random(SEED)    rows = []    for _ in range(SIDE):        row = bytearray()        for _ in range(SIDE):            grain = max(-3.0, min(3.0, rng.gauss(0, GRAIN)))            row.extend(max(0, min(255, round(channel + grain))) for channel in CREAM)        rows.append(bytes(row))    return png(SIDE, SIDE, rows)def main(source):    made = cream()    imageset('reader-paper', 'png').write_bytes(made)    print(f'reader-paper made, {len(made) // 1024} KB')    if source is None:        return    source = pathlib.Path(source)    found = [source / f'reader-night.{extension}' for extension in ('png', 'jpg') if (source / f'reader-night.{extension}').exists()]    if len(found) != 1:        sys.exit(f'{source} holds {len(found)} pictures named reader-night, not one')    picture = found[0]    imageset('reader-night', picture.suffix[1:]).write_bytes(picture.read_bytes())    print(f'{picture.name} -> reader-night, {picture.stat().st_size // 1024} KB')if __name__ == '__main__':    if len(sys.argv) > 2:        sys.exit(__doc__)    main(sys.argv[1] if len(sys.argv) == 2 else None)