#!/usr/bin/env python3
"""Pure-Python 1990s 35mm cel-and-gouache studio still (`2048 x 1152`):
An off-axis drafting desk at dusk holding a freshly printed broadsheet halftone
proof sheet, a brass-and-paper terrestrial globe, a stoneware mug with rising
steam, and a specimen vial beside a mullioned twilight window.

Zero image models, zero external textures, zero fonts.
Run:
  uv run --with numpy --with opencv-python-headless --with pycairo --with scipy --with Pillow \
    python3 paint_studio_desk.py --out still.webp
"""

from __future__ import annotations

import argparse
import math
from pathlib import Path
from typing import Sequence

import cairo
import cv2
import numpy as np
from PIL import Image


def hex_rgb(code: str) -> np.ndarray:
    code = code.lstrip("#")
    return np.array([int(code[0:2], 16), int(code[2:4], 16), int(code[4:6], 16)], dtype=np.float32) / 255.0


def smoothstep(e0: np.ndarray | float, e1: np.ndarray | float, x: np.ndarray | float) -> np.ndarray:
    t = np.clip((np.asarray(x, dtype=np.float32) - np.float32(e0)) / max(float(e1) - float(e0), 1e-8), 0.0, 1.0)
    return (t * t * (3.0 - 2.0 * t)).astype(np.float32)


def alpha_composite(dst: np.ndarray, src: np.ndarray, alpha: np.ndarray) -> np.ndarray:
    a = np.clip(alpha, 0.0, 1.0)[..., None]
    return dst * (1.0 - a) + src * a


def screen_blend(dst: np.ndarray, add: np.ndarray, strength: float = 1.0) -> np.ndarray:
    return 1.0 - (1.0 - dst) * (1.0 - np.clip(add * strength, 0.0, 1.0))


def fbm_gouache(
    h: int,
    w: int,
    octaves: Sequence[tuple[float, float, float]] = ((72.0, 68.0, 0.45), (26.0, 29.0, 0.32), (10.5, 9.5, 0.16), (4.5, 4.8, 0.07)),
    seed: int = 101,
) -> np.ndarray:
    rng = np.random.default_rng(seed)
    acc = np.zeros((h, w), dtype=np.float32)
    wsum = 0.0
    for sx, sy, wt in octaves:
        gh, gw = max(4, int(round(h / sy))), max(4, int(round(w / sx)))
        grid = rng.standard_normal((gh, gw)).astype(np.float32)
        acc += float(wt) * cv2.resize(grid, (w, h), interpolation=cv2.INTER_CUBIC)
        wsum += float(wt)
    acc /= max(wsum, 1e-6)
    std = float(np.std(acc))
    if std > 1e-6:
        acc = (acc - float(np.mean(acc))) / std
    return acc.astype(np.float32)


def make_paper_tooth(h: int, w: int, seed: int = 707) -> np.ndarray:
    fine = fbm_gouache(h, w, octaves=((3.6, 3.8, 0.55), (1.9, 2.0, 0.45)), seed=seed)
    med = fbm_gouache(h, w, octaves=((11.0, 10.5, 1.0),), seed=seed + 19)
    return np.clip(0.72 * fine + 0.28 * med, -2.5, 2.5).astype(np.float32)


def paint_isotropic_gouache_dabs(
    rgb: np.ndarray,
    mask: np.ndarray,
    paper_tooth: np.ndarray,
    dab_strength: float = 0.045,
    warm_bounce_in_shadow: float = 0.024,
    num_dabs: int = 86,
    tooth_weight: float = 0.015,
    seed: int = 123,
) -> np.ndarray:
    h, w, _ = rgb.shape
    m = np.clip(mask.astype(np.float32), 0.0, 1.0)
    if float(np.max(m)) < 1e-4:
        return rgb.copy()
    mottle = fbm_gouache(h, w, seed=seed)
    sh, sw = max(64, h // 4), max(64, w // 4)
    rng = np.random.default_rng(seed + 41)
    dab_val = np.zeros((sh, sw), dtype=np.float32)
    dab_tmp = np.zeros((sh, sw), dtype=np.float32)
    for _ in range(num_dabs):
        ang = float(rng.uniform(0.0, math.pi))
        hx, hy = float(rng.uniform(14.0, 42.0)), float(rng.uniform(5.0, 14.0))
        cx, cy = float(rng.uniform(0.0, sw)), float(rng.uniform(0.0, sh))
        ca, sa = math.cos(ang), math.sin(ang)
        j0, j1 = float(rng.uniform(0.86, 1.12)), float(rng.uniform(0.86, 1.12))
        corners = np.array([
            [cx - hx * ca + hy * j0 * sa, cy - hx * sa - hy * j0 * ca],
            [cx + hx * ca + hy * j1 * sa, cy + hx * sa - hy * j1 * ca],
            [cx + hx * ca - hy * j0 * sa, cy + hx * sa + hy * j0 * ca],
            [cx - hx * ca - hy * j1 * sa, cy - hx * sa + hy * j1 * ca],
        ], dtype=np.float32)
        sig = float(rng.uniform(1.3, 2.7))
        pad = int(math.ceil(sig * 3.0)) + 2
        x0 = max(0, int(math.floor(corners[:, 0].min())) - pad)
        y0 = max(0, int(math.floor(corners[:, 1].min())) - pad)
        x1 = min(sw, int(math.ceil(corners[:, 0].max())) + pad)
        y1 = min(sh, int(math.ceil(corners[:, 1].max())) + pad)
        if x1 <= x0 or y1 <= y0:
            continue
        dab = np.zeros((y1 - y0, x1 - x0), dtype=np.float32)
        cv2.fillConvexPoly(dab, np.round(corners - [[x0, y0]]).astype(np.int32), 1.0, cv2.LINE_AA)
        a = cv2.GaussianBlur(dab, (0, 0), sig) * float(rng.uniform(0.18, 0.34))
        dab_val[y0:y1, x0:x1] = dab_val[y0:y1, x0:x1] * (1.0 - a) + float(rng.normal(0.0, 0.42)) * a
        dab_tmp[y0:y1, x0:x1] = dab_tmp[y0:y1, x0:x1] * (1.0 - a) + float(rng.normal(0.0, 0.52)) * a
    dv = cv2.resize(dab_val, (w, h), interpolation=cv2.INTER_LINEAR)
    dt = cv2.resize(dab_tmp, (w, h), interpolation=cv2.INTER_LINEAR)
    out = rgb.copy()
    delta = dab_strength * (0.52 * mottle + 0.48 * dv) + tooth_weight * paper_tooth
    wshift = (dab_strength * 0.36) * (0.48 * mottle + 0.52 * dt)
    out[:, :, 0] += m * (delta + wshift)
    out[:, :, 1] += m * (delta + 0.30 * wshift)
    out[:, :, 2] += m * (delta - wshift)
    lum = 0.2126 * out[:, :, 0] + 0.7152 * out[:, :, 1] + 0.0722 * out[:, :, 2]
    sh_w = np.clip((0.28 - lum) / 0.28, 0.0, 1.0) * m * np.clip(0.5 + 0.5 * dt, 0.0, 1.0)
    out[:, :, 0] += sh_w * warm_bounce_in_shadow * 1.15
    out[:, :, 1] += sh_w * warm_bounce_in_shadow * 0.72
    out[:, :, 2] += sh_w * warm_bounce_in_shadow * 0.32
    return np.clip(out, 0.0, 1.0)


class Camera3D:
    def __init__(self, eye, target, up, fov_deg: float, width: int = 2048, height: int = 1152) -> None:
        self.eye = np.asarray(eye, dtype=np.float64)
        self.target = np.asarray(target, dtype=np.float64)
        self.up = np.asarray(up, dtype=np.float64)
        self.width, self.height = int(width), int(height)
        fwd = self.target - self.eye
        fwd /= np.linalg.norm(fwd)
        right = np.cross(fwd, self.up)
        right /= np.linalg.norm(right)
        down = np.cross(fwd, right)
        down /= np.linalg.norm(down)
        self.R = np.vstack([right, down, fwd])
        self.f = (self.width * 0.5) / math.tan(math.radians(fov_deg) * 0.5)
        self.cx, self.cy = self.width * 0.5, self.height * 0.5
        self.K = np.array([[self.f, 0.0, self.cx], [0.0, self.f, self.cy], [0.0, 0.0, 1.0]], dtype=np.float64)
        yy, xx = np.mgrid[0:self.height, 0:self.width].astype(np.float32)
        dx_c, dy_c = (xx - self.cx) / self.f, (yy - self.cy) / self.f
        self.ray_len = np.sqrt(dx_c * dx_c + dy_c * dy_c + 1.0).astype(np.float32)
        rt = self.R.T.astype(np.float32)
        self.rx = rt[0, 0] * dx_c + rt[0, 1] * dy_c + rt[0, 2]
        self.ry = rt[1, 0] * dx_c + rt[1, 1] * dy_c + rt[1, 2]
        self.rz = rt[2, 0] * dx_c + rt[2, 1] * dy_c + rt[2, 2]

    def project_points(self, pts: np.ndarray):
        arr = np.asarray(pts, dtype=np.float64)
        single = arr.ndim == 1
        if single:
            arr = arr[None, :]
        pc = (arr - self.eye[None, :]) @ self.R.T
        zc = pc[:, 2]
        sz = np.where(np.abs(zc) < 1e-6, 1e-6, zc)
        u = self.f * (pc[:, 0] / sz) + self.cx
        v = self.f * (pc[:, 1] / sz) + self.cy
        if single:
            return float(u[0]), float(v[0]), float(zc[0])
        return u, v, zc

    def warp_plane_panel(self, panel_rgb, panel_a, p0, e1, e2, span_u, span_v, fog_col, fog_start=1.8, fog_density=0.05):
        uv_h, uv_w = panel_a.shape
        e1u, e2u = np.asarray(e1, np.float64), np.asarray(e2, np.float64)
        e1u /= np.linalg.norm(e1u)
        e2u /= np.linalg.norm(e2u)
        basis = np.column_stack([self.R @ e1u, self.R @ e2u, self.R @ (p0 - self.eye)])
        h_uv = np.array([[span_u / uv_w, 0.0, 0.0], [0.0, span_v / uv_h, 0.0], [0.0, 0.0, 1.0]], dtype=np.float64)
        H = self.K @ basis @ h_uv
        pre = np.empty((uv_h, uv_w, 4), dtype=np.float32)
        ac = np.clip(panel_a.astype(np.float32), 0.0, 1.0)
        pre[:, :, :3] = panel_rgb.astype(np.float32) * ac[:, :, None]
        pre[:, :, 3] = ac
        warped = cv2.warpPerspective(pre, H, (self.width, self.height), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)
        n = np.cross(e1u, e2u)
        n /= np.linalg.norm(n)
        num = float(np.dot(p0 - self.eye, n))
        den = self.rx * float(n[0]) + self.ry * float(n[1]) + self.rz * float(n[2])
        zc = (num / np.where(np.abs(den) < 1e-6, 1e-6, den)).astype(np.float32)
        dist = zc * self.ray_len
        hx = float(self.eye[0]) + zc * self.rx
        hy = float(self.eye[1]) + zc * self.ry
        hz = float(self.eye[2]) + zc * self.rz
        um = (hx - p0[0]) * e1u[0] + (hy - p0[1]) * e1u[1] + (hz - p0[2]) * e1u[2]
        vm = (hx - p0[0]) * e2u[0] + (hy - p0[1]) * e2u[1] + (hz - p0[2]) * e2u[2]
        valid = ((zc > 0.05) & (um >= -0.004) & (um <= span_u + 0.004) & (vm >= -0.004) & (vm <= span_v + 0.004)).astype(np.float32)
        alpha = np.clip(warped[:, :, 3] * valid, 0.0, 1.0)
        rgb = np.clip(warped[:, :, :3] / np.maximum(alpha, 1e-5)[:, :, None], 0.0, 1.0)
        ft = np.clip(1.0 - np.exp(-np.maximum(0.0, dist - fog_start) * fog_density), 0.0, 0.45)[:, :, None]
        return rgb * (1.0 - ft) + fog_col[None, None, :] * ft, alpha


def shadow_xy_on_plane(pts_3d: np.ndarray, sun_dir: np.ndarray, z_plane: float = 0.0) -> np.ndarray:
    pts = np.asarray(pts_3d, dtype=np.float64)
    t = np.maximum(pts[..., 2] - z_plane, 0.0) / max(-float(sun_dir[2]), 1e-6)
    out = np.empty_like(pts)
    out[..., 0] = pts[..., 0] + t * float(sun_dir[0])
    out[..., 1] = pts[..., 1] + t * float(sun_dir[1])
    out[..., 2] = z_plane
    return out


def eval_catmull_rom(pts: np.ndarray, samples_per_seg: int = 8, closed: bool = False) -> np.ndarray:
    pts = np.asarray(pts, dtype=np.float64)
    n = len(pts)
    if n < 2:
        return pts
    ext = np.vstack([pts[-1:], pts, pts[:2]]) if closed else np.vstack([pts[:1] * 2 - pts[1:2], pts, pts[-1:] * 2 - pts[-2:-1]])
    segs = n if closed else n - 1
    ts = np.linspace(0.0, 1.0, samples_per_seg, endpoint=False)
    t2, t3 = ts * ts, ts * ts * ts
    out = []
    for i in range(segs):
        p0, p1, p2, p3 = ext[i], ext[i + 1], ext[i + 2], ext[i + 3]
        out.append(0.5 * ((2 * p1)[None] + (-p0 + p2)[None] * ts[:, None] + (2 * p0 - 5 * p1 + 4 * p2 - p3)[None] * t2[:, None] + (-p0 + 3 * p1 - 3 * p2 + p3)[None] * t3[:, None]))
    out.append(pts[:1] if closed else pts[-1:])
    return np.vstack(out)


class CairoLayer2x:
    def __init__(self, width: int = 2048, height: int = 1152) -> None:
        self.width, self.height = width, height
        self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width * 2, height * 2)
        self.ctx = cairo.Context(self.surface)
        self.ctx.scale(2.0, 2.0)
        self.ctx.set_antialias(cairo.ANTIALIAS_BEST)
        self.ctx.set_line_cap(cairo.LINE_CAP_ROUND)
        self.ctx.set_line_join(cairo.LINE_JOIN_ROUND)

    def fill_poly(self, pts_2d, rgba):
        if len(pts_2d) < 3:
            return
        self.ctx.set_source_rgba(*rgba)
        self.ctx.new_path()
        self.ctx.move_to(float(pts_2d[0, 0]), float(pts_2d[0, 1]))
        for x, y in pts_2d[1:]:
            self.ctx.line_to(float(x), float(y))
        self.ctx.close_path()
        self.ctx.fill()

    def stroke_tapered(self, pts_2d, base_w: float, rgba, seed: int = 1, closed: bool = False, tremor: float = 0.25):
        curve = eval_catmull_rom(pts_2d, samples_per_seg=8, closed=closed)
        n = len(curve)
        d = np.gradient(curve, axis=0)
        dl = np.maximum(np.linalg.norm(d, axis=1, keepdims=True), 1e-6)
        norm = np.column_stack([-d[:, 1] / dl[:, 0], d[:, 0] / dl[:, 0]])
        rng = np.random.default_rng(seed)
        s = np.linspace(0.0, 1.0, n)
        p1, p2 = rng.uniform(0.0, 2 * math.pi, size=2)
        wob = tremor * (0.65 * np.sin(2 * math.pi * 3 * s + p1) + 0.35 * np.sin(2 * math.pi * 7 * s + p2))
        if closed:
            wob *= np.sin(math.pi * s)
        curve = curve + norm * wob[:, None]
        taper = (0.85 + 0.15 * np.sin(2 * math.pi * s + p1)) if closed else (0.25 + 0.75 * np.sin(math.pi * s) ** 0.55)
        hw = (base_w * taper) * 0.5
        rib = np.vstack([curve + norm * hw[:, None], (curve - norm * hw[:, None])[::-1]])
        self.fill_poly(rib, rgba)

    def finish(self):
        buf = np.frombuffer(self.surface.get_data(), dtype=np.uint8).reshape(self.height * 2, self.width * 2, 4)
        pil = Image.fromarray(buf[:, :, [2, 1, 0, 3]], mode="RGBA").resize((self.width, self.height), Image.Resampling.LANCZOS)
        arr = np.asarray(pil, dtype=np.float32) / 255.0
        a = np.clip(arr[:, :, 3], 0.0, 1.0)
        return np.clip(arr[:, :, :3] / np.maximum(a, 1e-5)[:, :, None], 0.0, 1.0), a


def ring_2d(cam: Camera3D, center, rx: float, ry: float, z: float, n: int = 72) -> np.ndarray:
    th = np.linspace(0.0, 2 * math.pi, n, endpoint=False)
    pts = np.column_stack([center[0] + rx * np.cos(th), center[1] + ry * np.sin(th), np.full_like(th, z)])
    u, v, _ = cam.project_points(pts)
    return np.column_stack([u, v])


def front_arc(ring: np.ndarray, want_front: bool = True) -> np.ndarray:
    il, ir = int(np.argmin(ring[:, 0])), int(np.argmax(ring[:, 0]))
    rolled = np.roll(ring, -il, axis=0)
    span = (ir - il) % len(ring)
    a, b = rolled[:span + 1], np.vstack([rolled[0:1], rolled[span:][::-1]])
    c = a if (float(a[:, 1].mean()) >= float(b[:, 1].mean())) == want_front else b
    return c if c[0, 0] <= c[-1, 0] else c[::-1]


def lathe_silhouette(cam: Camera3D, center, profile_rz) -> tuple[np.ndarray, list[np.ndarray]]:
    dense = eval_catmull_rom(np.asarray(profile_rz, np.float64), samples_per_seg=8, closed=False)
    le, re, rings = [], [], []
    for r, z in dense:
        rg = ring_2d(cam, center, float(r), float(r), float(z), n=80)
        rings.append(rg)
        le.append(rg[int(np.argmin(rg[:, 0]))])
        re.append(rg[int(np.argmax(rg[:, 0]))])
    bf = front_arc(rings[0], True)
    tb = front_arc(rings[-1], False)
    return np.vstack([np.array(le)[::-1], bf[1:-1], np.array(re), tb[::-1][1:-1]]), rings


def finish_35mm_optics(rgb: np.ndarray, seed: int = 909) -> np.ndarray:
    img = np.clip(rgb.astype(np.float32), 0.0, 1.0)
    h, w, _ = img.shape
    lum = 0.2126 * img[:, :, 0] + 0.7152 * img[:, :, 1] + 0.0722 * img[:, :, 2]
    bright = np.clip((lum - 0.72) / 0.28, 0.0, 1.0) ** 1.3
    ht = bright[:, :, None] * np.array([1.0, 0.90, 0.75], np.float32)[None, None, :]
    img = screen_blend(img, 0.16 * cv2.GaussianBlur(ht, (0, 0), 6.5) + 0.15 * cv2.GaussianBlur(ht, (0, 0), 24.0) + 0.12 * cv2.GaussianBlur(ht, (0, 0), 68.0))
    yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
    r2 = ((xx - w * 0.5) / (w * 0.5)) ** 2 + ((yy - h * 0.5) / (h * 0.5)) ** 2
    img *= (1.0 - 0.145 * np.clip(r2 - 0.16, 0.0, 2.0))[:, :, None]
    rng = np.random.default_rng(seed)
    grain = rng.standard_normal((h, w)).astype(np.float32) * 0.013
    img = np.clip(img + grain[:, :, None], 0.0, 1.0)
    return np.clip(0.016 + img * 0.968, 0.0, 1.0)


def render_studio_desk(w: int = 2048, h: int = 1152, crops_dir: Path | None = None) -> np.ndarray:
    cam = Camera3D([-0.38, -0.56, 0.62], [0.16, 1.32, 0.18], [0.0, 0.0, 1.0], 48.0, w, h)
    sun_dir = np.array([-0.54, 0.42, -0.73], np.float64)
    sun_dir /= np.linalg.norm(sun_dir)
    tooth = make_paper_tooth(h, w, seed=42)

    # Band 1: Dusk exterior gradient + misty ridge behind mullioned window
    yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
    sky_t = np.clip(yy / (h * 0.62), 0.0, 1.0)
    canvas = (
        hex_rgb("#354756")[None, None, :] * (1.0 - sky_t[:, :, None])
        + hex_rgb("#D69C72")[None, None, :] * (sky_t ** 1.15)[:, :, None]
    )
    ridge_y = h * 0.43 - 38.0 * np.sin(xx * 0.0032) - 18.0 * np.cos(xx * 0.0085)
    ridge_m = (yy >= ridge_y).astype(np.float32)
    canvas = alpha_composite(canvas, np.broadcast_to(hex_rgb("#3F4952"), (h, w, 3)), ridge_m * 0.92)
    canvas = paint_isotropic_gouache_dabs(canvas, np.ones((h, w), np.float32), tooth, dab_strength=0.036, seed=11)

    # Studio wall & left/upper window casing (leaving open twilight glass [0.18..1.25] x [0.16..0.95] in X-Z wall plane)
    wall = CairoLayer2x(w, h)
    # Wall quads surrounding the window
    w_left = cam.project_points([[-1.5, 1.85, -0.2], [0.16, 1.85, -0.2], [0.16, 1.85, 1.4], [-1.5, 1.85, 1.4]])[:2]
    w_right = cam.project_points([[1.12, 1.85, -0.2], [2.4, 1.85, -0.2], [2.4, 1.85, 1.4], [1.12, 1.85, 1.4]])[:2]
    w_bot = cam.project_points([[0.10, 1.85, -0.2], [1.18, 1.85, -0.2], [1.18, 1.85, 0.14], [0.10, 1.85, 0.14]])[:2]
    w_top = cam.project_points([[0.10, 1.85, 0.88], [1.18, 1.85, 0.88], [1.18, 1.85, 1.4], [0.10, 1.85, 1.4]])[:2]
    for xs, ys in (w_left, w_right, w_bot, w_top):
        wall.fill_poly(np.column_stack([xs, ys]), (0.87, 0.84, 0.78, 1.0))
    # Window wood mullions
    for xbar in (0.16, 0.64, 1.12):
        bu, bv, _ = cam.project_points([[xbar - 0.018, 1.83, 0.14], [xbar + 0.018, 1.83, 0.14], [xbar + 0.018, 1.83, 0.88], [xbar - 0.018, 1.83, 0.88]])
        wall.fill_poly(np.column_stack([bu, bv]), (0.28, 0.21, 0.17, 1.0))
    for zbar in (0.14, 0.51, 0.88):
        bu, bv, _ = cam.project_points([[0.15, 1.83, zbar - 0.016], [1.13, 1.83, zbar - 0.016], [1.13, 1.83, zbar + 0.016], [0.15, 1.83, zbar + 0.016]])
        wall.fill_poly(np.column_stack([bu, bv]), (0.28, 0.21, 0.17, 1.0))
    wall_rgb, wall_a = wall.finish()
    wall_rgb = paint_isotropic_gouache_dabs(wall_rgb, wall_a, tooth, dab_strength=0.04, seed=29)
    canvas = alpha_composite(canvas, wall_rgb, wall_a)

    # Band 2: Warm cedar tabletop via exact Camera3D homography
    tw, th = 1024, 768
    tbl_uv = np.broadcast_to(hex_rgb("#8F5B3C"), (th, tw, 3)).copy()
    grain_v = fbm_gouache(th, tw, octaves=((12.0, 140.0, 0.65), (5.0, 48.0, 0.35)), seed=77)
    tbl_uv = np.clip(tbl_uv + 0.042 * grain_v[:, :, None], 0.0, 1.0)
    # Sunlit diagonal patch on desk aligned with window mullion glow
    uv_y, uv_x = np.mgrid[0:th, 0:tw].astype(np.float32)
    uv_y /= float(th)
    uv_x /= float(tw)
    warm_spot = np.exp(-((uv_x - 0.56) ** 2 / 0.12 + (uv_y - 0.48) ** 2 / 0.18))
    tbl_uv = np.clip(tbl_uv + warm_spot[:, :, None] * np.array([0.14, 0.10, 0.05], np.float32), 0.0, 1.0)
    tbl_rgb, tbl_a = cam.warp_plane_panel(
        tbl_uv, np.ones((th, tw), np.float32),
        p0=np.array([-1.05, 0.15, 0.0]), e1=np.array([1.0, 0.0, 0.0]), e2=np.array([0.0, 1.0, 0.0]),
        span_u=2.6, span_v=1.7, fog_col=hex_rgb("#D69C72"),
    )
    tbl_rgb = paint_isotropic_gouache_dabs(tbl_rgb, tbl_a, tooth, dab_strength=0.032, seed=55)
    canvas = alpha_composite(canvas, tbl_rgb, tbl_a)

    # Broadsheet halftone proof sheet in UV plane over the cedar tabletop
    sw, sh = 720, 520
    sheet_uv = np.broadcast_to(hex_rgb("#FAF9F5"), (sh, sw, 3)).copy()
    # Draw halftone terracotta dots & ink curve directly on sheet UV!
    for rr in range(18, sh - 32, 18):
        for cc in range(28, sw - 28, 18):
            intens = max(0.0, 1.0 - rr / (sh * 0.85)) ** 1.2
            # Clear SDF channel near diagonal curve
            curve_y = sh * (0.82 - 0.62 * ((cc / sw) ** 1.45))
            dist = abs(rr - curve_y)
            carve = smoothstep(14.0, 44.0, dist)
            rad = intens * carve * 5.2
            if rad > 0.7:
                cv2.circle(sheet_uv, (cc, rr), int(round(rad)), (186 / 255.0, 99 / 255.0, 72 / 255.0), -1, cv2.LINE_AA)
    pts_curve = np.array([[int(28 + t * (sw - 56)), int(sh * (0.82 - 0.62 * (t ** 1.45)))] for t in np.linspace(0, 1, 48)], np.int32)
    cv2.polylines(sheet_uv, [pts_curve], False, (20 / 255.0, 20 / 255.0, 19 / 255.0), 4, cv2.LINE_AA)
    cv2.rectangle(sheet_uv, (4, 4), (sw - 5, sh - 5), (20 / 255.0, 20 / 255.0, 19 / 255.0), 3)

    # Slight 6-degree sheet rotation on desk
    ang_s = math.radians(7.0)
    e1_s = np.array([math.cos(ang_s), math.sin(ang_s), 0.0])
    e2_s = np.array([-math.sin(ang_s), math.cos(ang_s), 0.0])
    sh_rgb, sh_a = cam.warp_plane_panel(
        sheet_uv, np.ones((sh, sw), np.float32),
        p0=np.array([-0.28, 0.62, 0.003]), e1=e1_s, e2=e2_s, span_u=0.68, span_v=0.49, fog_col=hex_rgb("#D69C72"),
    )
    sh_rgb = paint_isotropic_gouache_dabs(sh_rgb, sh_a, tooth, dab_strength=0.022, seed=64)
    canvas = alpha_composite(canvas, sh_rgb, sh_a)

    # Ray-cast 3D shadows from mug, miniature globe stand, and specimen vial
    shad = CairoLayer2x(w, h)
    for center, r_base, z_h in (([0.52, 0.88, 0.0], 0.075, 0.24), ([0.14, 1.06, 0.0], 0.06, 0.14), ([-0.36, 0.84, 0.0], 0.032, 0.15)):
        ang_th = np.linspace(0, 2 * math.pi, 32, endpoint=False)
        base_pts = np.column_stack([center[0] + r_base * np.cos(ang_th), center[1] + r_base * np.sin(ang_th), np.full_like(ang_th, 0.004)])
        top_pts = np.column_stack([center[0] + r_base * np.cos(ang_th), center[1] + r_base * np.sin(ang_th), np.full_like(ang_th, z_h)])
        s_pts = shadow_xy_on_plane(top_pts, sun_dir, 0.004)
        su, sv, _ = cam.project_points(np.vstack([base_pts, s_pts]))
        hull = cv2.convexHull(np.column_stack([su, sv]).astype(np.float32)).reshape(-1, 2)
        shad.fill_poly(hull, (0.14, 0.08, 0.06, 0.34))
    sh2_rgb, sh2_a = shad.finish()
    canvas = alpha_composite(canvas, sh2_rgb, sh2_a)

    # Band 3: 2x PyCairo Hero Props (Lathe Globe + Mug + Glass Vial + Fountain Pen)
    hero = CairoLayer2x(w, h)
    ink = (0.08, 0.08, 0.07, 0.92)

    # 3a. Turned wood base + brass meridian cradle + engraved paper globe at [0.52, 0.88, 0.0]
    g_base, _ = lathe_silhouette(cam, [0.52, 0.88, 0.0], [(0.066, 0.0), (0.070, 0.014), (0.036, 0.026), (0.024, 0.056), (0.034, 0.072)])
    hero.fill_poly(g_base, (0.28, 0.19, 0.14, 1.0))
    hero.stroke_tapered(g_base, 2.2, ink, seed=101, closed=True)
    # Clean projected circular globe outline (eliminates lathe pole pinching)
    gc_u, gc_v, _ = cam.project_points([0.52, 0.88, 0.185])
    gr_u, _, _ = cam.project_points([0.52 + 0.118, 0.88, 0.185])
    g_rad_px = abs(gr_u - gc_u)
    ang_g = np.linspace(0, 2 * math.pi, 96, endpoint=False)
    g_orb = np.column_stack([gc_u + g_rad_px * np.cos(ang_g), gc_v + g_rad_px * np.sin(ang_g)])
    hero.fill_poly(g_orb, (0.97, 0.96, 0.93, 1.0))
    # Clip latitude hairlines, continent contours, and pin strictly inside sphere circle!
    hero.ctx.save()
    hero.ctx.new_path()
    hero.ctx.arc(float(gc_u), float(gc_v), float(g_rad_px - 1.2), 0.0, 2.0 * math.pi)
    hero.ctx.clip()
    for lat_z in (0.135, 0.185, 0.235):
        r_lat = math.sqrt(max(0.01, 0.118 ** 2 - (lat_z - 0.185) ** 2))
        rg = ring_2d(cam, [0.52, 0.88, 0.0], r_lat, r_lat, lat_z, n=48)
        hero.stroke_tapered(front_arc(rg, True), 1.2, (0.08, 0.08, 0.07, 0.36), seed=int(lat_z * 100), closed=False, tremor=0.25)
    am_n = np.array([[0.45, 0.81, 0.25], [0.48, 0.785, 0.255], [0.51, 0.775, 0.235], [0.495, 0.785, 0.205], [0.52, 0.775, 0.185], [0.545, 0.79, 0.15], [0.525, 0.805, 0.125], [0.50, 0.80, 0.155], [0.49, 0.785, 0.19], [0.46, 0.80, 0.22]])
    au, av, _ = cam.project_points(am_n)
    hero.fill_poly(np.column_stack([au, av]), (0.90, 0.88, 0.82, 0.85))
    hero.stroke_tapered(np.column_stack([au, av]), 1.8, ink, seed=108, closed=True, tremor=0.35)
    pu, pv, _ = cam.project_points([[0.515, 0.78, 0.17]])
    hero.ctx.set_source_rgba(0.73, 0.39, 0.28, 1.0)
    hero.ctx.arc(float(pu[0]), float(pv[0]), 6.0, 0, 2 * math.pi)
    hero.ctx.fill()
    hero.ctx.restore()
    hero.stroke_tapered(g_orb, 2.6, ink, seed=102, closed=True)
    # Brass half-meridian arc cradling globe from base
    cradle = np.column_stack([gc_u - (g_rad_px + 7) * np.sin(np.linspace(-0.25, math.pi + 0.15, 36)), gc_v - (g_rad_px + 7) * np.cos(np.linspace(-0.25, math.pi + 0.15, 36))])
    hero.stroke_tapered(cradle, 4.0, (0.62, 0.46, 0.24, 0.95), seed=109, closed=False, tremor=0.1)

    # 3b. Fluted stoneware mug at [0.14, 1.06, 0.0] with terracotta glaze & rising steam
    mug_sil, mug_rings = lathe_silhouette(cam, [0.14, 1.06, 0.0], [(0.055, 0.0), (0.059, 0.025), (0.062, 0.075), (0.060, 0.115)])
    hero.fill_poly(mug_sil, (0.73, 0.39, 0.28, 1.0))
    hero.fill_poly(mug_rings[-1], (0.24, 0.14, 0.09, 1.0))
    hero.stroke_tapered(mug_rings[-1], 2.0, ink, seed=201, closed=True)
    hero.stroke_tapered(mug_sil, 2.4, ink, seed=202, closed=True)
    # Seeded Bezier steam wisps
    for k, sx_off in enumerate((-0.015, 0.012)):
        sw_pts = [[0.14 + sx_off, 1.06, 0.12 + z_step * 0.05] for z_step in range(7)]
        for j in range(len(sw_pts)):
            sw_pts[j][0] += 0.016 * math.sin(j * 1.1 + k)
        su, sv, _ = cam.project_points(sw_pts)
        hero.stroke_tapered(np.column_stack([su, sv]), 4.2, (0.98, 0.96, 0.92, 0.24), seed=210 + k, closed=False, tremor=1.4)

    # 3c. Glass specimen vial with ochre sediment + brass-nib pen resting on desk margin
    vial_sil, vial_rings = lathe_silhouette(cam, [-0.36, 0.84, 0.0], [(0.030, 0.0), (0.031, 0.09), (0.022, 0.12), (0.025, 0.14)])
    hero.fill_poly(vial_sil, (0.82, 0.88, 0.89, 0.56))
    sed_sil, _ = lathe_silhouette(cam, [-0.36, 0.84, 0.0], [(0.028, 0.004), (0.029, 0.052)])
    hero.fill_poly(sed_sil, (0.64, 0.44, 0.28, 0.82))
    hero.stroke_tapered(vial_rings[-1], 1.6, ink, seed=303, closed=True)
    hero.stroke_tapered(vial_sil, 2.0, ink, seed=301, closed=True)
    # Pen along left edge of sheet
    pen_u, pen_v, _ = cam.project_points([[-0.35, 0.56, 0.008], [-0.14, 0.63, 0.008]])
    hero.stroke_tapered(np.column_stack([pen_u, pen_v]), 7.5, (0.12, 0.12, 0.11, 1.0), seed=302, closed=False, tremor=0.1)

    h_rgb, h_a = hero.finish()
    h_rgb = paint_isotropic_gouache_dabs(h_rgb, h_a, tooth, dab_strength=0.036, seed=88)
    canvas = alpha_composite(canvas, h_rgb, h_a)

    # Band 4: Foreground bokeh frame corner & 35mm optical finish
    fg = CairoLayer2x(w, h)
    fg.fill_poly(np.array([[0.0, h], [w * 0.11, h * 0.72], [0.0, h * 0.64]]), (0.16, 0.12, 0.10, 0.92))
    fg_rgb, fg_a = fg.finish()
    fg_blur_a = cv2.GaussianBlur(fg_a, (0, 0), 9.0)
    canvas = alpha_composite(canvas, fg_rgb, fg_blur_a)

    final = finish_35mm_optics(canvas, seed=909)
    if crops_dir is not None:
        crops_dir.mkdir(parents=True, exist_ok=True)
        for cname, (cx, cy) in (("crop-sheet.png", (w * 0.43, h * 0.68)), ("crop-globe.png", (w * 0.74, h * 0.50)), ("crop-window.png", (w * 0.66, h * 0.28))):
            x0 = int(np.clip(round(cx - 300), 0, w - 600))
            y0 = int(np.clip(round(cy - 225), 0, h - 450))
            Image.fromarray(np.round(final[y0:y0 + 450, x0:x0 + 600] * 255).astype(np.uint8)).save(crops_dir / cname)
    return final


def main() -> None:
    parser = argparse.ArgumentParser(description="Paint the Broadsheet Visual Suite studio desk still.")
    parser.add_argument("--out", type=Path, required=True)
    parser.add_argument("--crops-dir", type=Path, default=None)
    args = parser.parse_args()
    rgb = render_studio_desk(crops_dir=args.crops_dir)
    args.out.parent.mkdir(parents=True, exist_ok=True)
    u8 = np.round(np.clip(rgb, 0.0, 1.0) * 255.0).astype(np.uint8)
    img = Image.fromarray(u8, mode="RGB")
    if args.out.suffix.lower() == ".webp":
        img.save(args.out, format="WEBP", quality=90, method=6)
    else:
        img.save(args.out, format="PNG", compress_level=6)
    print("Saved", args.out, img.size)


if __name__ == "__main__":
    main()
