#!/usr/bin/env python3 """Cut `paper-grain` — the ONE seamless paper fibre tile — out of the cream card. python3 scripts/gen-cards/export_grain.py The paper kit draws paper rather than photographing it (`Sources/CottonUI/Paper/`): a dye paint, this tile MULTIPLIED over it, a hairline vignette. So the tile has to carry the master's fibre and NOTHING else — no dye, no shadow, no lighting gradient, or every sheet in the app wears the same blotch. What this does, in order: 1. crops a square out of the centre of `card-cream`'s imageset PNG, well inside the baked-in shadow, at the master's native resolution; 2. takes its LUMINANCE and divides out a blurred copy of itself — the high-pass that leaves the fibre and throws away the lighting; 3. 4-way mirrors it (the trick `scripts/gen-caps/export_caps.py::tile` uses), so every edge meets its own reflection and the tile is seamless; 4. normalises the mean to `MEAN` and clamps the swing, so the dye paints in `PaperDye.fill` can be the measured card colours divided by that one number; 5. writes a neutral-grey PNG at 3x, because a 3x tile puts the fibre on screen at very nearly the frequency the 720 px card photograph shows it at (a card is ~170 pt wide and its master 720 px: 4.2 px/pt). PNG, not JPEG: the tile is multiplied, and JPEG ringing around a fibre is visible as a halo once fifty sheets wear it. Needs Pillow (`python3 -m pip install pillow`). """ import json import math import pathlib from PIL import Image, ImageFilter ROOT = pathlib.Path(__file__).resolve().parents[2] CATALOGUE = ROOT / "apps/loom/Sources/CottonPaper/Media.xcassets" SOURCE = CATALOGUE / "card-cream.imageset/card-cream.png" NAME = "paper-grain" # The crop, in the master's own pixels, taken from its centre. CROP = 380 # The tile as written. 512 px at 3x is a 170.67 pt tile: one sheet of paper on # the phone is narrower than that, so no sheet ever shows the repeat. SIDE = 512 SCALE = 3 # The mean luminance the tile is normalised to. `PaperDye.fill` divides the # measured card colours by this, so paint × tile lands back on the photograph. MEAN = 0.96 # How far a fibre may swing either side of the mean. It is exactly `1/MEAN - 1` # on purpose: any more and the bright side of the tile would clip at 1.0, which # drags the tile's own mean below `MEAN` and makes the dyes' divisor a lie. SWING = 1 / MEAN - 1 # 1.0 as an 8-bit level while the tile is being worked on. Well under 255, so a # fibre brighter than the mean has somewhere to go. UNIT = 200 # The fibre is lifted before it is compressed: a tile cut straight out of the # master reads flatter on screen than the master does, because the master is # always shown magnified and this tile is not. # # 2.6 rather than the 1.5 this shipped with first: the design review compared a # 360pt drawn card against the photograph and read the drawing as having less # fibre. The lift cannot make the tile SWING further — `SWING` is the ceiling # and it is what keeps `MEAN` honest — but it pushes far more of the fibre up # against that ceiling through the soft knee, which is what "more fibre" looks # like at a size where the tile is not magnified. GAIN = 2.6 def high_pass(grey: Image.Image) -> Image.Image: """The fibre, with the lighting divided out.""" blurred = grey.filter(ImageFilter.GaussianBlur(radius=grey.width / 55)) flat = Image.new("F", grey.size) grey_px = grey.convert("F").load() blur_px = blurred.convert("F").load() flat_px = flat.load() for y in range(grey.height): for x in range(grey.width): base = blur_px[x, y] flat_px[x, y] = grey_px[x, y] / base if base > 1 else 1.0 return flat def flattened(tile: Image.Image) -> Image.Image: """The tile's own low frequency, divided out — WITHOUT breaking the seam. The mirror makes the edges meet, and then leaves one more artifact behind: a crease that ran across the crop becomes a line straight across the finished tile, and a tile laid fifty times over a screen shows that line fifty times. So the mirrored tile is high-passed a second time, and the blur is taken over a 3x3 lay-up of the tile so it WRAPS — a blur of the tile alone would darken its own edges and put the seam back. """ width, height = tile.size field = Image.new("L", (width * 3, height * 3)) for row in range(3): for column in range(3): field.paste(tile, (column * width, row * height)) blurred = field.filter(ImageFilter.GaussianBlur(radius=width / 6)) centre = blurred.crop((width, height, width * 2, height * 2)) tile_px = tile.load() blur_px = centre.load() out = Image.new("L", (width, height)) out_px = out.load() for y in range(height): for x in range(width): base = blur_px[x, y] ratio = tile_px[x, y] / base if base > 0 else 1.0 out_px[x, y] = int(round(max(0.0, min(1.0, ratio * UNIT / 255)) * 255)) return out def mirrored(tile: Image.Image) -> Image.Image: """4-way mirror: every edge meets its own reflection, so the tile is seamless.""" width, height = tile.size out = Image.new(tile.mode, (width * 2, height * 2)) out.paste(tile, (0, 0)) out.paste(tile.transpose(Image.FLIP_LEFT_RIGHT), (width, 0)) out.paste(tile.transpose(Image.FLIP_TOP_BOTTOM), (0, height)) out.paste(tile.transpose(Image.ROTATE_180), (width, height)) return out def main() -> None: master = Image.open(SOURCE).convert("RGB") width, height = master.size left = (width - CROP) // 2 top = (height - CROP) // 2 crop = master.crop((left, top, left + CROP, top + CROP)).convert("L") flat = high_pass(crop) values = list(flat.getdata()) mean = sum(values) / len(values) # Lift, then compress with a soft knee rather than a hard clamp: a clamp # flattens every speck that reaches it into one flat tone, and a sheet of # paper is specks. `tanh` keeps them, ordered, inside the swing. lifted = [] for value in values: unit = (value / mean - 1.0) * GAIN lifted.append(1.0 + SWING * math.tanh(unit / SWING)) centre = sum(lifted) / len(lifted) # 8-bit from here on, at `UNIT` for 1.0, because Pillow's blur — which the # seam pass below needs — does not run on a float image. grain = Image.new("L", flat.size) grain.putdata( [int(round(max(0.0, min(1.0, value / centre * UNIT / 255)) * 255)) for value in lifted] ) # Mirror, then flatten the mirror's own artifacts, then re-centre and write. seamless = flattened(mirrored(grain)) seamless = seamless.resize((SIDE, SIDE), Image.LANCZOS) final = list(seamless.getdata()) mid = sum(final) / len(final) tile = Image.new("L", (SIDE, SIDE)) tile.putdata( [int(round(max(0.0, min(1.0, MEAN * value / mid)) * 255)) for value in final] ) tile = tile.convert("RGB") folder = CATALOGUE / f"{NAME}.imageset" folder.mkdir(parents=True, exist_ok=True) tile.save(folder / f"{NAME}.png", "PNG", optimize=True) (folder / "Contents.json").write_text( json.dumps( { "images": [ {"filename": f"{NAME}.png", "idiom": "universal", "scale": f"{SCALE}x"} ], "info": {"author": "xcode", "version": 1}, }, indent=2, ) + "\n" ) final = list(tile.convert("L").getdata()) print( f"{NAME}: {SIDE}x{SIDE} @{SCALE}x mean={sum(final) / len(final) / 255:.4f} " f"min={min(final) / 255:.3f} max={max(final) / 255:.3f}" ) if __name__ == "__main__": main()