#!/usr/bin/env python3 """Paint Cotton Calling's desk telephone as wordless layers into the Loom package's catalogue, procedurally, so it is reproducible from the repo. python3 scripts/paint-telephone.py [--out ] [--icon ] [--picture ] [--glyph] [--quick] The telephone is a heavy cream key telephone of the sixties standing bare on the calling desk's oxblood leather (`FaceGround.leatherDesk`): a wedge of glossy cream plastic on a dark plinth, its handset lying across the cradle's two horns on top, the coiled cord looping from the handset's mouthpiece down to the desk and into the body's side, twelve push keys on the sloping front and under them a row of four broad line keys, the last of them red. It is modelled as solids (signed distance fields) and ray-marched under the desk lamp, so one model gives every view the faces need. Each layer is a 3x PNG, its shadow on the desk painted into its alpha (black, so it darkens whatever leather it is laid on): telephone three-quarter view from the front right, the handset on its cradle (a contact's card, the fan's picture) telephone-front nearly from the front and above, larger, the handset on its cradle: the in-call telephone when the call is over telephone-lifted the same view with the handset lifted away, its cord running off the foot of the picture to the hand that holds it: the in-call telephone during the call The line keys are the in-call telephone's controls (mute, speaker, camera, and the red key that ends the call); their glyphs and the glow of a key that is on are drawn live over the paint, so each layer's keys are bare. The places of the keys and the handset in each layer are the faces' knobs (`CallTelephoneKnobs`, `PersonTelephoneKnobs`), printed when the layers are written; a repainted telephone owes new knobs. `--icon` paints the app's icon instead: the telephone on the leather under the lamp (1024 px, opaque). `--picture` paints the Calling tool's picture: the telephone cut out on nothing (600 px, RGBA), named by its own SHA-256 under the tool's `pictures/`. `--glyph` paints CallKit's template glyph (`CallKitIcon` in the calling flavour's catalogue, 120 px, white on nothing, the keys cut through: only its alpha counts). No word, figure or letter is on any layer. """ from __future__ import annotations import hashlib import importlib.util import json import sys from pathlib import Path import numpy as np from PIL import Image, ImageFilter ROOT = Path(__file__).resolve().parent.parent CATALOGUE = ROOT / "apps/loom/Sources/CottonPaper/Media.xcassets" # MARK: The model, in centimetres: x to the right, y up, z towards the front. HALF_X = 11.0 # the body's half width BODY = [(11.0, 0.7), (11.0, 3.6), (0.5, 9.8), (-11.0, 9.8), (-11.0, 0.7)] # its side, (z, y) BODY_R = 1.4 SLOPE_O = np.array([0.0, 3.6, 11.0]) # the sloping front's lower edge, middle SLOPE_D = np.array([0.0, 9.8 - 3.6, 0.5 - 11.0]) SLOPE_D = SLOPE_D / np.linalg.norm(SLOPE_D) # up the slope SLOPE_N = np.array([0.0, -SLOPE_D[2], SLOPE_D[1]]) # out of it SLOPE_LENGTH = float(np.hypot(9.8 - 3.6, 11.0 - 0.5)) # The line keys across the slope's foot: mute, speaker, camera, end (red). LINE_KEYS = [(-6.6, 1.85), (-2.2, 1.85), (2.2, 1.85), (6.6, 1.85)] # (u, v) LINE_HALF = (1.85, 0.95, 0.42) # The twelve push keys above them, four rows of three. PAD_KEYS = [(u, v) for v in (4.9, 6.75, 8.6, 10.45) for u in (-2.55, 0.0, 2.55)] PAD_HALF = (1.0, 0.68, 0.38) KEY_LIFT = 0.18 # how far a key's middle stands above the slope HORNS = [(-6.4, -5.2), (6.4, -5.2)] # (x, z) of the cradle's two horns HANDSET_Y = 14.3 HANDSET_Z = -5.2 CREAM = "#E9DCBF" KEYS = "#F1E8D2" LINE = "#F4F0E6" RED = "#B3261C" PLINTH = "#2A1D18" CORD = "#E2D3B3" LAMP = np.array([-30.0, 62.0, 34.0]) # the desk lamp, above and left, in front LAMP_COLOUR = np.array([1.0, 0.86, 0.68]) * 1.25 SKY = np.array([0.32, 0.27, 0.24]) # the room's dim warm fill from above BOUNCE = np.array([0.30, 0.09, 0.07]) # the leather's red thrown back up FAR = 400.0 def srgb_to_linear(h: str) -> np.ndarray: c = np.array([int(h.lstrip("#")[i : i + 2], 16) for i in (0, 2, 4)], dtype=float) / 255 return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4) def linear_to_srgb(c: np.ndarray) -> np.ndarray: c = np.clip(c, 0, 1) return np.where(c <= 0.0031308, c * 12.92, 1.055 * c ** (1 / 2.4) - 0.055) def length(v: np.ndarray) -> np.ndarray: return np.sqrt((v * v).sum(-1)) def round_box(p: np.ndarray, centre, half, r: float) -> np.ndarray: q = np.abs(p - np.asarray(centre)) - np.asarray(half) + r return length(np.maximum(q, 0)) + np.minimum(q.max(-1), 0) - r def smin(a: np.ndarray, b: np.ndarray, k: float) -> np.ndarray: h = np.clip(0.5 + 0.5 * (b - a) / k, 0, 1) return b * (1 - h) + a * h - k * h * (1 - h) def polygon(z: np.ndarray, y: np.ndarray, points) -> np.ndarray: """The exact signed distance to a closed polygon in (z, y) (Quilez).""" pts = np.asarray(points, dtype=float) d = (z - pts[0, 0]) ** 2 + (y - pts[0, 1]) ** 2 s = np.ones_like(z) j = len(pts) - 1 for i in range(len(pts)): ez, ey = pts[j] - pts[i] wz, wy = z - pts[i, 0], y - pts[i, 1] t = np.clip((wz * ez + wy * ey) / (ez * ez + ey * ey), 0, 1) bz, by = wz - ez * t, wy - ey * t d = np.minimum(d, bz * bz + by * by) c1 = y >= pts[i, 1] c2 = y < pts[j, 1] c3 = ez * wy > ey * wz flip = (c1 & c2 & c3) | (~c1 & ~c2 & ~c3) s = np.where(flip, -s, s) j = i return s * np.sqrt(d) def inset(points, r: float): """The polygon pulled in by `r` on every side (a convex one), so rounding it by `r` lays its surface back where the polygon was.""" pts = np.asarray(points, dtype=float) n = len(pts) area = sum(pts[i, 0] * pts[(i + 1) % n, 1] - pts[(i + 1) % n, 0] * pts[i, 1] for i in range(n)) sign = 1 if area > 0 else -1 lines = [] for i in range(n): a, b = pts[i], pts[(i + 1) % n] e = (b - a) / np.linalg.norm(b - a) normal = np.array([-e[1], e[0]]) * sign # inward lines.append((a + normal * r, e)) out = [] for i in range(n): (p1, d1), (p2, d2) = lines[i - 1], lines[i] m = np.array([[d1[0], -d2[0]], [d1[1], -d2[1]]]) t = np.linalg.solve(m, p2 - p1) out.append(tuple(p1 + d1 * t[0])) return out BODY_IN = inset(BODY, BODY_R) def cord_points(lifted: bool) -> np.ndarray: """The coiled cord's middle line: out of the body's left side, and to the handset's mouthpiece on the cradle, or, lifted, off towards the hand.""" if lifted: knots = [(-10.9, 3.2, -6.5), (-13.2, 1.3, -4.0), (-14.6, 0.85, 2.0), (-14.4, 0.85, 9.0), (-12.6, 0.9, 16.0), (-10.0, 1.4, 24.0), (-7.5, 2.6, 34.0)] else: knots = [(-10.9, 3.2, -6.5), (-13.0, 1.2, -5.5), (-15.2, 0.85, -2.5), (-15.8, 1.0, 1.5), (-14.6, 3.5, -1.0), (-12.9, 8.0, -3.5), (-11.6, 11.0, -4.8)] knots = np.array(knots) # a Catmull-Rom curve through the knots, finely sampled pts = [] ext = np.vstack([knots[0], knots, knots[-1]]) for i in range(1, len(ext) - 2): p0, p1, p2, p3 = ext[i - 1], ext[i], ext[i + 1], ext[i + 2] for t in np.linspace(0, 1, 14, endpoint=False): t2, t3 = t * t, t * t * t pts.append(0.5 * ((2 * p1) + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 + (-p0 + 3 * p1 - 3 * p2 + p3) * t3)) pts.append(knots[-1]) return np.array(pts) class Scene: """The telephone's solids; `part` says which each point is nearest.""" MATERIALS = ["body", "plinth", "key", "line", "red", "handset", "cord", "desk"] def __init__(self, handset: bool, lifted_cord: bool, desk: bool = True, cord: bool = True): self.handset = handset self.desk = desk self.corded = cord self.cord = cord_points(lifted_cord) seg = np.diff(self.cord, axis=0) self.cord_len = np.concatenate([[0], np.cumsum(length(seg))]) lo, hi = self.cord.min(0) - 1.2, self.cord.max(0) + 1.2 self.cord_box = (lo, hi) # each solid's distance def body(self, p): w = np.stack([polygon(p[:, 2], p[:, 1], BODY_IN), np.abs(p[:, 0]) - (HALF_X - BODY_R)], -1) d = np.minimum(w.max(-1), 0) + length(np.maximum(w, 0)) - BODY_R # the horns stand up out of the top, joined to it softly for x, z in HORNS: d = smin(d, round_box(p, (x, 11.4, z), (1.25, 1.7, 2.3), 0.9), 0.9) # the cradle's well between the horns, a shallow dish well = round_box(p, (0, 10.4, HANDSET_Z), (4.6, 0.9, 2.6), 0.9) d = np.maximum(d, -well) return d def plinth(self, p): return round_box(p, (0, 0.42, 0.2), (HALF_X - 0.25, 0.42, 11.0 - 0.25), 0.35) def slope_frame(self, p): q = p - SLOPE_O return p[:, 0], q @ SLOPE_D, q @ SLOPE_N def keys(self, p, which): u, v, h = self.slope_frame(p) local = np.stack([u, v, h], -1) d = np.full(len(p), FAR) if which == "pad": for ku, kv in PAD_KEYS: d = np.minimum(d, round_box(local, (ku, kv, KEY_LIFT - PAD_HALF[2] + 0.4), PAD_HALF, 0.3)) else: for i, (ku, kv) in enumerate(LINE_KEYS): if (which == "red") != (i == 3): continue d = np.minimum(d, round_box(local, (ku, kv, KEY_LIFT - LINE_HALF[2] + 0.5), LINE_HALF, 0.34)) return d def handset_d(self, p): bar = round_box(p, (0, HANDSET_Y + 0.55, HANDSET_Z), (8.6, 0.95, 1.55), 0.9) d = bar for x in (-9.0, 9.0): # each cup: a short round drum hanging under the bar's end c = p - np.array([x, HANDSET_Y - 0.6, HANDSET_Z]) radial = np.sqrt(c[:, 0] ** 2 + c[:, 2] ** 2) w = np.stack([radial - 2.6, np.abs(c[:, 1]) - 1.5], -1) cup = np.minimum(w.max(-1), 0) + length(np.maximum(w, 0)) - 0.7 d = smin(d, cup, 1.2) return d def cord_d(self, p, ribbed: bool = True): lo, hi = self.cord_box outside = np.maximum(np.maximum(lo - p, p - hi), 0) box = length(outside) d = box.copy() near = box < 1.0 if near.any(): q = p[near] best = np.full(len(q), FAR) along = np.zeros(len(q)) a = self.cord[:-1] e = np.diff(self.cord, axis=0) for i in range(len(a)): w = q - a[i] t = np.clip((w @ e[i]) / (e[i] @ e[i]), 0, 1) dist = length(w - t[:, None] * e[i]) closer = dist < best best = np.where(closer, dist, best) along = np.where(closer, self.cord_len[i] + t * np.sqrt(e[i] @ e[i]), along) # the coil: a tube ribbed at the coil's pitch d[near] = best - 0.52 - (0.09 * np.sin(2 * np.pi * along / 0.46) if ribbed else 0) return d def parts(self, p, ribbed: bool = True): out = { "body": self.body(p), "plinth": self.plinth(p), "key": self.keys(p, "pad"), "line": self.keys(p, "line"), "red": self.keys(p, "red"), } if self.corded: out["cord"] = self.cord_d(p, ribbed) if self.handset: out["handset"] = self.handset_d(p) if self.desk: out["desk"] = p[:, 1] return out def distance(self, p): return np.min(np.stack(list(self.parts(p).values()), -1), -1) def object_distance(self, p): parts = self.parts(p, ribbed=False) parts.pop("desk", None) return np.min(np.stack(list(parts.values()), -1), -1) def material(self, p): parts = self.parts(p) names = list(parts) idx = np.argmin(np.stack([parts[n] for n in names], -1), -1) return np.array([self.MATERIALS.index(n) for n in names])[idx] # MARK: The camera class Camera: def __init__(self, target, direction, distance: float, lens: float): self.target = np.asarray(target, dtype=float) d = np.asarray(direction, dtype=float) d = d / np.linalg.norm(d) self.eye = self.target + d * distance self.fwd = -d self.right = np.cross(self.fwd, [0, 1, 0]) self.right /= np.linalg.norm(self.right) self.up = np.cross(self.right, self.fwd) self.lens = lens # the image plane's half height at one unit def project(self, pts: np.ndarray) -> np.ndarray: v = pts - self.eye z = v @ self.fwd return np.stack([(v @ self.right) / z, (v @ self.up) / z], -1) def frame_points() -> np.ndarray: """What every view must hold: the body, the handset on its cradle, the cord's loop on the desk, and room for the shadow behind and right.""" xs, ys, zs = np.meshgrid([-16.5, 12.0], [0, 16.5], [-12.5, 12.0]) box = np.stack([xs.ravel(), ys.ravel(), zs.ravel()], -1) shadow = np.array([[17.0, 0, -14.0], [17.0, 0, 6.0], [-4.0, 0, -18.0]]) return np.vstack([box, shadow]) def window(camera: Camera, pad: float = 0.04): s = camera.project(frame_points()) lo, hi = s.min(0), s.max(0) span = hi - lo return lo - span * pad, hi + span * pad # MARK: Marching and shading def march(scene: Scene, origin: np.ndarray, dirs: np.ndarray, near: float, far: float, distance) -> tuple[np.ndarray, np.ndarray]: n = len(dirs) t = np.full(n, near) hit = np.zeros(n, bool) live = np.arange(n) for _ in range(220): if len(live) == 0: break p = origin[live] + dirs[live] * t[live, None] d = distance(p) done = d < 0.002 * np.maximum(t[live], 1) hit[live[done]] = True t[live] += np.where(done, 0, d * 0.92) gone = t[live] > far live = live[~done & ~gone] return t, hit def normals(scene: Scene, p: np.ndarray) -> np.ndarray: e = 0.004 k = np.array([[1, -1, -1], [-1, -1, 1], [-1, 1, -1], [1, 1, 1]], dtype=float) n = sum(k[i][None, :] * scene.distance(p + k[i] * e)[:, None] for i in range(4)) return n / np.maximum(length(n)[:, None], 1e-9) def soft_shadow(scene: Scene, p: np.ndarray, towards: np.ndarray, reach: np.ndarray) -> np.ndarray: res = np.ones(len(p)) t = np.full(len(p), 0.06) live = np.arange(len(p)) for _ in range(90): if len(live) == 0: break q = p[live] + towards[live] * t[live, None] d = scene.object_distance(q) res[live] = np.minimum(res[live], 10 * d / t[live]) t[live] += np.clip(d, 0.03, 1.5) live = live[(res[live] > 0.002) & (t[live] < reach[live])] res = np.clip(res, 0, 1) return res * res * (3 - 2 * res) def occlusion(scene: Scene, p: np.ndarray, n: np.ndarray, distance) -> np.ndarray: total = np.zeros(len(p)) weight = 1.0 for i in range(1, 6): h = 0.25 * i total += weight * (h - distance(p + n * h)) weight *= 0.7 return np.clip(1 - 0.55 * total, 0, 1) ALBEDO = { "body": srgb_to_linear(CREAM), "plinth": srgb_to_linear(PLINTH), "key": srgb_to_linear(KEYS), "line": srgb_to_linear(LINE), "red": srgb_to_linear(RED), "handset": srgb_to_linear(CREAM), "cord": srgb_to_linear(CORD), } GLOSS = {"body": (70, 0.55), "plinth": (20, 0.15), "key": (60, 0.45), "line": (90, 0.6), "red": (90, 0.55), "handset": (70, 0.55), "cord": (30, 0.25)} def render(scene: Scene, camera: Camera, width: int, lo, hi, supersample: int = 2) -> np.ndarray: """The view as linear RGB with an alpha: the telephone opaque, the desk transparent but for the shadow and the contact darkness laid on it.""" aspect = (hi[1] - lo[1]) / (hi[0] - lo[0]) W = width * supersample H = int(round(width * aspect)) * supersample xs = lo[0] + (np.arange(W) + 0.5) / W * (hi[0] - lo[0]) ys = hi[1] - (np.arange(H) + 0.5) / H * (hi[1] - lo[1]) sx, sy = np.meshgrid(xs, ys) dirs = camera.fwd[None, :] + sx.reshape(-1, 1) * camera.right[None, :] + sy.reshape(-1, 1) * camera.up[None, :] dirs /= length(dirs)[:, None] origin = np.broadcast_to(camera.eye, dirs.shape) t, hit = march(scene, origin, dirs, 1.0, FAR, scene.distance) rgba = np.zeros((len(dirs), 4)) idx = np.nonzero(hit)[0] p = origin[idx] + dirs[idx] * t[idx, None] mat = scene.material(p) desk = mat == Scene.MATERIALS.index("desk") # The telephone obj = idx[~desk] po = p[~desk] mo = mat[~desk] n = normals(scene, po) to_lamp = LAMP - po reach = length(to_lamp) l = to_lamp / reach[:, None] sh = soft_shadow(scene, po + n * 0.02, l, reach) ao = occlusion(scene, po, n, scene.distance) view = -dirs[obj] h = l + view h /= length(h)[:, None] ndl = np.clip((n * l).sum(-1), 0, 1) ndh = np.clip((n * h).sum(-1), 0, 1) fres = 0.04 + 0.96 * (1 - np.clip((n * view).sum(-1), 0, 1)) ** 5 albedo = np.zeros((len(po), 3)) spec = np.zeros(len(po)) for name, colour in ALBEDO.items(): m = mo == Scene.MATERIALS.index(name) albedo[m] = colour shine, strength = GLOSS[name] spec[m] = strength * (ndh[m] ** shine) * (shine + 8) / 40 spec *= (0.25 + 0.75 * fres) * sh * ndl up = np.clip(n[:, 1] * 0.5 + 0.5, 0, 1)[:, None] down = np.clip(-n[:, 1], 0, 1)[:, None] ambient = ao[:, None] * (SKY * up + BOUNCE * (0.4 + down)) # a soft sheen of the room's light glancing off the gloss at the edges rim = (fres * ao * 0.35)[:, None] * SKY colour = albedo * (LAMP_COLOUR * (ndl * sh)[:, None] + ambient) + spec[:, None] * LAMP_COLOUR + rim rgba[obj, :3] = colour rgba[obj, 3] = 1 # The desk: the shadow, and the darkness where the telephone meets it dk = idx[desk] pd = p[desk] near = (np.abs(pd[:, 0]) < 40) & (np.abs(pd[:, 2]) < 40) shade = np.zeros(len(pd)) if near.any(): q = pd[near] to_lamp = LAMP - q reach = length(to_lamp) lit = soft_shadow(scene, q + np.array([0, 0.01, 0]), to_lamp / reach[:, None], reach) up_n = np.tile([0.0, 1.0, 0.0], (len(q), 1)) contact = occlusion(scene, q, up_n, scene.object_distance) shade[near] = np.clip(0.72 * (1 - lit) + 0.9 * (1 - contact), 0, 0.88) rgba[dk, 3] = shade img = rgba.reshape(H, W, 4) if supersample > 1: img = img.reshape(H // supersample, supersample, W // supersample, supersample, 4).mean((1, 3)) return img def to_png(img: np.ndarray) -> Image.Image: """Linear premultiplied-by-coverage pixels to an sRGB RGBA picture.""" alpha = img[..., 3] # the telephone's pixels were averaged with transparent desk at its edge: # unpremultiply its colour by its coverage (desk pixels carry no colour) rgb = img[..., :3] / np.maximum(alpha, 1e-6)[..., None] out = np.dstack([linear_to_srgb(rgb) * 255, alpha * 255]) return Image.fromarray(np.clip(out + 0.5, 0, 255).astype(np.uint8)) # MARK: The views THREE_QUARTER = Camera(target=(-1.0, 6.5, 0.0), direction=(0.55, 0.62, 0.86), distance=120, lens=1) FRONT = Camera(target=(0.0, 6.0, 0.0), direction=(0.12, 0.92, 0.95), distance=120, lens=1) def knobs(camera: Camera, lo, hi, scene_handset: bool = True) -> dict: """Where the line keys' faces and the handset lie in the picture, as shares of its width and height (y down): each key's four top corners, clockwise from its upper left, and the handset's bounds.""" def share(pts): s = camera.project(np.asarray(pts, dtype=float)) x = (s[:, 0] - lo[0]) / (hi[0] - lo[0]) y = (hi[1] - s[:, 1]) / (hi[1] - lo[1]) return np.stack([x, y], -1) keys = [] top = KEY_LIFT + 0.5 + 0.08 for ku, kv in LINE_KEYS: hu, hv = LINE_HALF[0] - 0.25, LINE_HALF[1] - 0.25 corners = [(ku - hu, kv + hv), (ku + hu, kv + hv), (ku + hu, kv - hv), (ku - hu, kv - hv)] pts = [SLOPE_O + np.array([u, 0, 0]) + SLOPE_D * v + SLOPE_N * top for u, v in corners] keys.append([[round(float(a), 4), round(float(b), 4)] for a, b in share(pts)]) xs, ys, zs = np.meshgrid([-11.6, 11.6], [HANDSET_Y - 2.9, HANDSET_Y + 1.6], [HANDSET_Z - 3.4, HANDSET_Z + 3.4]) hand = share(np.stack([xs.ravel(), ys.ravel(), zs.ravel()], -1)) handset = [round(float(v), 4) for v in (*hand.min(0), *(hand.max(0) - hand.min(0)))] return {"aspect": round(float((hi[0] - lo[0]) / (hi[1] - lo[1])), 4), "lineKeys": keys, "handset": handset} def layers(quick: bool) -> dict[str, tuple[Image.Image, dict]]: ss = 1 if quick else 2 out = {} lo, hi = window(THREE_QUARTER) out["telephone"] = (to_png(render(Scene(handset=True, lifted_cord=False), THREE_QUARTER, 900 if not quick else 300, lo, hi, ss)), knobs(THREE_QUARTER, lo, hi)) lo, hi = window(FRONT, pad=0.03) width = 1170 if not quick else 390 out["telephone-front"] = (to_png(render(Scene(handset=True, lifted_cord=False), FRONT, width, lo, hi, ss)), knobs(FRONT, lo, hi)) out["telephone-lifted"] = (to_png(render(Scene(handset=False, lifted_cord=True), FRONT, width, lo, hi, ss)), knobs(FRONT, lo, hi)) return out # MARK: The icon and the picture def grounds(): spec = importlib.util.spec_from_file_location("grounds", ROOT / "scripts/paint-ground-tiles.py") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def paint_icon(quick: bool) -> Image.Image: n = 1024 g = grounds() leather = g.calling_desk()[:n, :n] yy, xx = np.mgrid[0:n, 0:n].astype(float) pool = np.clip(1 - np.hypot(xx - n * 0.42, yy - n * 0.36) / (n * 0.78), 0, 1) ** 1.5 desk = leather * (0.55 + 0.75 * pool[..., None]) camera = Camera(target=(-1.5, 6.8, 0.5), direction=(0.55, 0.62, 0.86), distance=120, lens=1) lo, hi = window(camera, pad=0.0) # square the window round the telephone, a little room all round c = (lo + hi) / 2 half = (hi - lo).max() / 2 * 1.02 lo, hi = c - half, c + half img = render(Scene(handset=True, lifted_cord=False), camera, 512 if quick else n, lo, hi, 1 if quick else 2) if quick: img = np.asarray(Image.fromarray((np.clip(img, 0, 1) * 255).astype(np.uint8), "RGBA").resize((n, n)), dtype=float) / 255 a = img[..., 3:4] rgb = linear_to_srgb(img[..., :3] / np.maximum(a, 1e-6)) * 255 # the shadow is black over the leather; the telephone its own colour obj = (img[..., :3].sum(-1) > 0)[..., None] shadowed = desk * (1 - a) out = np.where(obj, desk * (1 - a) + rgb * a, shadowed) return Image.fromarray(np.clip(out, 0, 255).astype(np.uint8)) def paint_picture(quick: bool) -> Image.Image: lo, hi = window(THREE_QUARTER, pad=0.0) c = (lo + hi) / 2 half = (hi - lo).max() / 2 * 1.01 img = render(Scene(handset=True, lifted_cord=False), THREE_QUARTER, 300 if quick else 600, c - half, c + half, 1 if quick else 2) # the fan's tile lays its own shadow: keep only the telephone and its # contact darkness, softened a = img[..., 3] obj = img[..., :3].sum(-1) > 0 img[..., 3] = np.where(obj, a, a * 0.55) return to_png(img) def paint_glyph(side: int = 120) -> Image.Image: """CallKit's template glyph: the telephone seen from the front and a little above, flat white on nothing, its keys cut through so it reads as a telephone at forty points; only its alpha counts.""" camera = Camera(target=(0.0, 7.0, 0.0), direction=(0.0, 0.42, 1.0), distance=160, lens=1) scene = Scene(handset=True, lifted_cord=False, desk=False, cord=False) xs, ys, zs = np.meshgrid([-12.0, 12.0], [0, 16.2], [-12.0, 12.0]) s = camera.project(np.stack([xs.ravel(), ys.ravel(), zs.ravel()], -1)) c = (s.min(0) + s.max(0)) / 2 half = (s.max(0) - s.min(0)).max() / 2 * 1.06 lo, hi = c - half, c + half ss = 6 n = side * ss xs = lo[0] + (np.arange(n) + 0.5) / n * (hi[0] - lo[0]) ys = hi[1] - (np.arange(n) + 0.5) / n * (hi[1] - lo[1]) sx, sy = np.meshgrid(xs, ys) dirs = camera.fwd[None, :] + sx.reshape(-1, 1) * camera.right[None, :] + sy.reshape(-1, 1) * camera.up[None, :] dirs /= length(dirs)[:, None] origin = np.broadcast_to(camera.eye, dirs.shape) t, hit = march(scene, origin, dirs, 1.0, FAR, scene.distance) alpha = np.zeros(len(dirs)) idx = np.nonzero(hit)[0] mat = scene.material(origin[idx] + dirs[idx] * t[idx, None]) keys = np.isin(mat, [Scene.MATERIALS.index(m) for m in ("key", "line", "red")]) alpha[idx[~keys]] = 1 # the handset stands clear of the body by a hair's gap, so its shape reads handset = np.zeros(len(dirs)) handset[idx[mat == Scene.MATERIALS.index("handset")]] = 1 held = Image.fromarray((handset.reshape(n, n) * 255).astype(np.uint8)) for _ in range(3): held = held.filter(ImageFilter.MaxFilter(5)) gap = np.asarray(held, dtype=float).ravel() / 255 alpha = np.where(handset > 0, 1, alpha * (1 - gap)) a = alpha.reshape(n, n).reshape(side, ss, side, ss).mean((1, 3)) out = np.zeros((side, side, 4)) out[..., :3] = 255 out[..., 3] = a * 255 return Image.fromarray(np.clip(out + 0.5, 0, 255).astype(np.uint8)) def write_glyph(folder: Path) -> None: folder.mkdir(parents=True, exist_ok=True) for old in folder.iterdir(): old.unlink() paint_glyph().save(folder / "CallKitIcon.png", optimize=True) contents = {"images": [{"filename": "CallKitIcon.png", "idiom": "universal"}], "info": {"author": "xcode", "version": 1}} (folder / "Contents.json").write_text(json.dumps(contents, indent=2) + "\n") print(f"glyph: {folder}") # MARK: Writing def write(name: str, image: Image.Image, out: Path) -> None: folder = out / f"{name}.imageset" folder.mkdir(parents=True, exist_ok=True) for old in folder.iterdir(): old.unlink() image.save(folder / f"{name}.png", optimize=True) contents = { "images": [ {"filename": f"{name}.png", "idiom": "universal", "scale": "3x"}, {"filename": f"{name}.png", "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") print(f"{name}: {image.width} x {image.height}") def main() -> None: np.seterr(all="ignore") # rays that leave the scene run to infinity args = sys.argv[1:] quick = "--quick" in args if quick: args.remove("--quick") out = CATALOGUE if "--out" in args: k = args.index("--out") out = Path(args[k + 1]) del args[k : k + 2] if "--glyph" in args: write_glyph(ROOT / "apps/cotton/App/Flavours/messages/Assets.xcassets/CallKitIcon.imageset") return if "--icon" in args: k = args.index("--icon") paint_icon(quick).save(args[k + 1]) print(f"icon: {args[k + 1]}") return if "--picture" in args: k = args.index("--picture") picture = paint_picture(quick) target = Path(args[k + 1]) picture.save(target, optimize=True) digest = hashlib.sha256(target.read_bytes()).hexdigest() print(f"picture: {target} sha256 {digest}") return for name, (image, places) in layers(quick).items(): write(name, image, out) if places: print(name, json.dumps(places)) if __name__ == "__main__": main()