#!/usr/bin/env python3
"""Reusable 3D-grounded 1990s 35mm cel-and-gouache scene painting primitives.

Zero image models, zero external textures, zero font dependencies.
Requires: numpy, opencv-python-headless (or opencv-python), pycairo, scipy, Pillow.

Import these helpers when prototyping a scene, or inline the needed functions
into a standalone `paint_scene.py` when publishing a single-file script.
"""

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


# ---------------------------------------------------------------------------
# 1. Color & Compositing Primitives
# ---------------------------------------------------------------------------

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(
    edge0: np.ndarray | float, edge1: np.ndarray | float, x: np.ndarray | float
) -> np.ndarray:
    e0 = np.asarray(edge0, dtype=np.float32)
    e1 = np.asarray(edge1, dtype=np.float32)
    xv = np.asarray(x, dtype=np.float32)
    denom = np.maximum(e1 - e0, 1e-8)
    t = np.clip((xv - e0) / denom, 0.0, 1.0)
    return (t * t * (3.0 - 2.0 * t)).astype(np.float32)


def alpha_composite(
    dst_rgb: np.ndarray, src_rgb: np.ndarray, src_a: np.ndarray
) -> np.ndarray:
    a = np.clip(src_a, 0.0, 1.0)[..., None]
    return dst_rgb * (1.0 - a) + src_rgb * a


def screen_blend(
    dst_rgb: np.ndarray, add_rgb: np.ndarray, strength: float = 1.0
) -> np.ndarray:
    b = np.clip(add_rgb * strength, 0.0, 1.0)
    return 1.0 - (1.0 - dst_rgb) * (1.0 - b)


# ---------------------------------------------------------------------------
# 2. Isotropic Gouache Brushwork, Paper Tooth & Voronoi Masonry
# ---------------------------------------------------------------------------

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:
    """Multi-octave bicubic-upsampled zero-mean unit-variance Gaussian mottling
    at balanced square scales (never stretched row/column striping on fills)."""
    rng = np.random.default_rng(seed)
    acc = np.zeros((h, w), dtype=np.float32)
    w_sum = 0.0
    for sx, sy, weight in octaves:
        gh = max(4, int(round(h / float(sy))))
        gw = max(4, int(round(w / float(sx))))
        grid = rng.standard_normal((gh, gw)).astype(np.float32)
        up = cv2.resize(grid, (w, h), interpolation=cv2.INTER_CUBIC)
        acc += float(weight) * up
        w_sum += float(weight)
    acc /= max(w_sum, 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 isotropic cold-press paperboard tooth."""
    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.048,
    warm_bounce_in_shadow: float = 0.022,
    num_dabs: int = 92,
    tooth_weight: float = 0.016,
    seed: int = 123,
) -> np.ndarray:
    """Modulate flat fills with balanced square-scale mottling, randomly rotated
    1/4-res soft convex-polygon brush dabs, paper tooth, opposite red/blue warm-cool
    shifts, and warm bounce light inside deep shadows (lum < 0.28)."""
    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 = float(rng.uniform(13.0, 40.0))
        hy = float(rng.uniform(5.0, 15.0))
        cx = float(rng.uniform(0.0, sw))
        cy = 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.8))
        pad = int(math.ceil(sig * 3.0)) + 2
        x0 = max(0, int(math.floor(np.min(corners[:, 0]))) - pad)
        y0 = max(0, int(math.floor(np.min(corners[:, 1]))) - pad)
        x1 = min(sw, int(math.ceil(np.max(corners[:, 0]))) + pad)
        y1 = min(sh, int(math.ceil(np.max(corners[:, 1]))) + pad)
        if x1 <= x0 or y1 <= y0:
            continue

        roi_pts = np.round(corners - np.array([[x0, y0]], dtype=np.float32)).astype(np.int32)
        dab = np.zeros((y1 - y0, x1 - x0), dtype=np.float32)
        cv2.fillConvexPoly(dab, roi_pts, 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)


def voronoi_mortar_field(
    uv_h: int,
    uv_w: int,
    span_u: float,
    span_v: float,
    cell_size_m: float = 0.42,
    jitter: float = 0.36,
    warp_amp_m: float = 0.035,
    seed: int = 211,
) -> tuple[np.ndarray, np.ndarray]:
    """Vectorized 3x3 cell-neighborhood Voronoi distance difference (d2 - d1) in
    physical meters for organic flagstones/masonry, plus per-stone random IDs."""
    rng = np.random.default_rng(seed)
    nx = max(3, int(math.ceil(span_u / cell_size_m)) + 3)
    ny = max(3, int(math.ceil(span_v / cell_size_m)) + 3)

    gx, gy = np.meshgrid(np.arange(nx, dtype=np.float32), np.arange(ny, dtype=np.float32))
    sx = (gx - 1.0 + 0.5 + rng.uniform(-jitter, jitter, size=(ny, nx)).astype(np.float32)) * cell_size_m
    sy = (gy - 1.0 + 0.5 + rng.uniform(-jitter, jitter, size=(ny, nx)).astype(np.float32)) * cell_size_m
    tone = rng.uniform(-1.0, 1.0, size=(ny, nx)).astype(np.float32)

    vv, uu = np.mgrid[0:uv_h, 0:uv_w].astype(np.float32)
    um = (uu / max(uv_w - 1, 1)) * span_u + warp_amp_m * fbm_gouache(uv_h, uv_w, octaves=((36, 36, 1.0),), seed=seed + 3)
    vm = (vv / max(uv_h - 1, 1)) * span_v + warp_amp_m * fbm_gouache(uv_h, uv_w, octaves=((36, 36, 1.0),), seed=seed + 7)

    ix = np.clip(np.floor(um / cell_size_m).astype(np.int32) + 1, 1, nx - 2)
    iy = np.clip(np.floor(vm / cell_size_m).astype(np.int32) + 1, 1, ny - 2)

    d1 = np.full((uv_h, uv_w), 1e9, dtype=np.float32)
    d2 = np.full((uv_h, uv_w), 1e9, dtype=np.float32)
    best_tone = np.zeros((uv_h, uv_w), dtype=np.float32)

    for dy in (-1, 0, 1):
        for dx in (-1, 0, 1):
            cx = sx[iy + dy, ix + dx]
            cy = sy[iy + dy, ix + dx]
            ct = tone[iy + dy, ix + dx]
            dist = np.sqrt((um - cx) ** 2 + (vm - cy) ** 2)
            closer = dist < d1
            d2 = np.where(closer, d1, np.minimum(d2, dist))
            best_tone = np.where(closer, ct, best_tone)
            d1 = np.where(closer, dist, d1)

    return (d2 - d1).astype(np.float32), best_tone


# ---------------------------------------------------------------------------
# 3. Metric 3D Pinhole Camera & Exact Plane-Basis UV Homography
# ---------------------------------------------------------------------------

class Camera3D:
    def __init__(
        self,
        eye: Sequence[float] | np.ndarray,
        target: Sequence[float] | np.ndarray,
        up: Sequence[float] | np.ndarray,
        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 = int(width)
        self.height = 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.fwd = fwd
        self.right = right
        self.down = 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.width * 0.5
        self.cy = 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_cam = (xx - self.cx) / self.f
        dy_cam = (yy - self.cy) / self.f
        self.ray_len_scale = np.sqrt(dx_cam * dx_cam + dy_cam * dy_cam + 1.0).astype(np.float32)
        rt = self.R.T.astype(np.float32)
        self.ray_world_x = rt[0, 0] * dx_cam + rt[0, 1] * dy_cam + rt[0, 2]
        self.ray_world_y = rt[1, 0] * dx_cam + rt[1, 1] * dy_cam + rt[1, 2]
        self.ray_world_z = rt[2, 0] * dx_cam + rt[2, 1] * dy_cam + rt[2, 2]

        vp_y = self.project_direction(np.array([0.0, 1.0, 0.0]))
        self.horizon_y = float(vp_y[1])

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

    def project_direction(self, d_world: np.ndarray) -> tuple[float, float]:
        pc = self.R @ np.asarray(d_world, dtype=np.float64)
        return (
            float(self.f * (pc[0] / max(pc[2], 1e-6)) + self.cx),
            float(self.f * (pc[1] / max(pc[2], 1e-6)) + self.cy),
        )

    def clip_segment_near(
        self, p0: np.ndarray, p1: np.ndarray, z_min: float = 0.05
    ) -> tuple[np.ndarray, np.ndarray] | None:
        c0 = self.R @ (p0 - self.eye)
        c1 = self.R @ (p1 - self.eye)
        if c0[2] < z_min and c1[2] < z_min:
            return None
        q0, q1 = p0.copy(), p1.copy()
        if c0[2] < z_min:
            t = (z_min - c0[2]) / max(c1[2] - c0[2], 1e-9)
            q0 = p0 + t * (p1 - p0)
        elif c1[2] < z_min:
            t = (z_min - c1[2]) / max(c0[2] - c1[2], 1e-9)
            q1 = p1 + t * (p0 - p1)
        return q0, q1

    def plane_homography(
        self,
        p0: np.ndarray,
        e1: np.ndarray,
        e2: np.ndarray,
        span_u: float,
        span_v: float,
        uv_w: int,
        uv_h: int,
    ) -> np.ndarray:
        e1_u = np.asarray(e1, dtype=np.float64)
        e2_u = np.asarray(e2, dtype=np.float64)
        e1_u /= np.linalg.norm(e1_u)
        e2_u /= np.linalg.norm(e2_u)
        basis = np.column_stack([self.R @ e1_u, self.R @ e2_u, self.R @ (p0 - self.eye)])
        h_uv = np.array(
            [[span_u / float(uv_w), 0.0, 0.0], [0.0, span_v / float(uv_h), 0.0], [0.0, 0.0, 1.0]],
            dtype=np.float64,
        )
        return self.K @ basis @ h_uv

    def ray_plane_hit(
        self, p0: np.ndarray, normal: np.ndarray
    ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
        n = np.asarray(normal, dtype=np.float64)
        n /= np.linalg.norm(n)
        num = float(np.dot(p0 - self.eye, n))
        den = (
            self.ray_world_x * float(n[0])
            + self.ray_world_y * float(n[1])
            + self.ray_world_z * float(n[2])
        )
        safe_den = np.where(np.abs(den) < 1e-6, 1e-6, den)
        z_cam = (num / safe_den).astype(np.float32)
        dist = z_cam * self.ray_len_scale
        hx = float(self.eye[0]) + z_cam * self.ray_world_x
        hy = float(self.eye[1]) + z_cam * self.ray_world_y
        hz = float(self.eye[2]) + z_cam * self.ray_world_z
        return z_cam, dist, hx, hy, hz

    def warp_plane_panel(
        self,
        panel_rgb: np.ndarray,
        panel_alpha: np.ndarray,
        p0: np.ndarray,
        e1: np.ndarray,
        e2: np.ndarray,
        span_u: float,
        span_v: float,
        fog_color: np.ndarray,
        fog_start: float = 1.6,
        fog_density: float = 0.06,
    ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
        uv_h, uv_w = panel_alpha.shape
        h_mat = self.plane_homography(p0, e1, e2, span_u, span_v, uv_w, uv_h)

        premul = np.empty((uv_h, uv_w, 4), dtype=np.float32)
        a_clamped = np.clip(panel_alpha.astype(np.float32), 0.0, 1.0)
        premul[:, :, :3] = panel_rgb.astype(np.float32) * a_clamped[:, :, None]
        premul[:, :, 3] = a_clamped

        warped = cv2.warpPerspective(
            premul,
            h_mat,
            (self.width, self.height),
            flags=cv2.INTER_LINEAR,
            borderMode=cv2.BORDER_CONSTANT,
            borderValue=(0.0, 0.0, 0.0, 0.0),
        )

        e1_u = np.asarray(e1, dtype=np.float64)
        e2_u = np.asarray(e2, dtype=np.float64)
        e1_u /= np.linalg.norm(e1_u)
        e2_u /= np.linalg.norm(e2_u)
        normal = np.cross(e1_u, e2_u)
        z_cam, dist, hx, hy, hz = self.ray_plane_hit(p0, normal)

        dx = hx - float(p0[0])
        dy = hy - float(p0[1])
        dz = hz - float(p0[2])
        u_m = dx * float(e1_u[0]) + dy * float(e1_u[1]) + dz * float(e1_u[2])
        v_m = dx * float(e2_u[0]) + dy * float(e2_u[1]) + dz * float(e2_u[2])
        valid = (
            (z_cam > 0.05)
            & (u_m >= -0.004)
            & (u_m <= span_u + 0.004)
            & (v_m >= -0.004)
            & (v_m <= span_v + 0.004)
        ).astype(np.float32)

        alpha = np.clip(warped[:, :, 3] * valid, 0.0, 1.0)
        safe_a = np.maximum(alpha, 1e-5)
        rgb = np.clip(warped[:, :, :3] / safe_a[:, :, None], 0.0, 1.0)

        fog_t = 1.0 - np.exp(-np.maximum(0.0, dist - float(fog_start)) * float(fog_density))
        fog_t = np.clip(fog_t, 0.0, 0.55)[:, :, None]
        rgb = rgb * (1.0 - fog_t) + fog_color[None, None, :] * fog_t
        return rgb, alpha, z_cam


def shadow_xy_on_plane(
    pts_3d: np.ndarray, sun_dir: np.ndarray, z_plane: float = 0.0
) -> np.ndarray:
    """Cast 3D points along normalized `sun_dir` (sun_dir[2] < 0) onto Z = z_plane."""
    pts = np.asarray(pts_3d, dtype=np.float64)
    dz = np.maximum(pts[..., 2] - z_plane, 0.0)
    t = dz / 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 mirror_points_across_plane(
    pts_3d: np.ndarray, plane_p0: np.ndarray, plane_normal: np.ndarray
) -> np.ndarray:
    """Mirror 3D points across a reflective plane `(p0, n)` for puddle/tea reflections."""
    pts = np.asarray(pts_3d, dtype=np.float64)
    n = np.asarray(plane_normal, dtype=np.float64)
    n = n / np.linalg.norm(n)
    d = np.sum((pts - plane_p0) * n, axis=-1, keepdims=True)
    return pts - 2.0 * d * n


# ---------------------------------------------------------------------------
# 4. 2x Supersampled PyCairo Ink & Smooth 3D Lathe Silhouettes
# ---------------------------------------------------------------------------

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


class CairoLayer2x:
    """2x supersampled PyCairo drawing surface downsampled with Lanczos."""

    def __init__(self, width: int = 2048, height: int = 1152) -> None:
        self.width = int(width)
        self.height = int(height)
        self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.width * 2, self.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: np.ndarray, rgba: tuple[float, float, float, float]) -> None:
        if len(pts_2d) < 3:
            return
        ctx = self.ctx
        ctx.new_path()
        ctx.move_to(float(pts_2d[0, 0]), float(pts_2d[0, 1]))
        for x, y in pts_2d[1:]:
            ctx.line_to(float(x), float(y))
        ctx.close_path()
        ctx.set_source_rgba(*rgba)
        ctx.fill()

    def fill_poly_linear(
        self,
        pts_2d: np.ndarray,
        p_start: tuple[float, float],
        p_end: tuple[float, float],
        stops: Sequence[tuple[float, tuple[float, float, float, float]]],
    ) -> None:
        if len(pts_2d) < 3:
            return
        ctx = self.ctx
        pat = cairo.LinearGradient(p_start[0], p_start[1], p_end[0], p_end[1])
        for offset, rgba in stops:
            pat.add_color_stop_rgba(offset, *rgba)
        ctx.new_path()
        ctx.move_to(float(pts_2d[0, 0]), float(pts_2d[0, 1]))
        for x, y in pts_2d[1:]:
            ctx.line_to(float(x), float(y))
        ctx.close_path()
        ctx.set_source(pat)
        ctx.fill()

    def fill_poly_radial(
        self,
        pts_2d: np.ndarray,
        c0: tuple[float, float, float],
        c1: tuple[float, float, float],
        stops: Sequence[tuple[float, tuple[float, float, float, float]]],
    ) -> None:
        if len(pts_2d) < 3:
            return
        ctx = self.ctx
        pat = cairo.RadialGradient(c0[0], c0[1], c0[2], c1[0], c1[1], c1[2])
        for offset, rgba in stops:
            pat.add_color_stop_rgba(offset, *rgba)
        ctx.new_path()
        ctx.move_to(float(pts_2d[0, 0]), float(pts_2d[0, 1]))
        for x, y in pts_2d[1:]:
            ctx.line_to(float(x), float(y))
        ctx.close_path()
        ctx.set_source(pat)
        ctx.fill()

    def stroke_catmull_rom(
        self,
        pts_2d: np.ndarray,
        z_depths: np.ndarray | float,
        base_width: float,
        rgba: tuple[float, float, float, float],
        seed: int = 1,
        closed: bool = False,
        fade_dist: float = 2.4,
        taper_ends: float = 0.28,
        tremor: float = 0.28,
        samples_per_seg: int = 8,
    ) -> None:
        pts = np.asarray(pts_2d, dtype=np.float64)
        if len(pts) < 2:
            return
        curve = eval_catmull_rom(pts, samples_per_seg=samples_per_seg, closed=closed)
        n = len(curve)
        if np.ndim(z_depths) == 0:
            zs = np.full(n, float(z_depths), dtype=np.float64)
        else:
            z_arr = np.asarray(z_depths, dtype=np.float64)
            zs = np.interp(np.linspace(0.0, len(z_arr) - 1, n), np.arange(len(z_arr)), z_arr)

        d = np.gradient(curve, axis=0)
        dlen = np.maximum(np.linalg.norm(d, axis=1, keepdims=True), 1e-6)
        norm = np.column_stack([-d[:, 1] / dlen[:, 0], d[:, 0] / dlen[:, 0]])

        rng = np.random.default_rng(seed)
        s = np.linspace(0.0, 1.0, n)
        phase1, phase2 = rng.uniform(0.0, 2.0 * math.pi, size=2)
        wobble = tremor * (
            0.65 * np.sin(2.0 * math.pi * (3.0 * s) + phase1)
            + 0.35 * np.sin(2.0 * math.pi * (7.0 * s) + phase2)
        )
        if closed:
            wobble *= np.sin(math.pi * s)
        curve = curve + norm * wobble[:, None]

        persp = np.clip(1.0 / (1.0 + np.maximum(zs, 0.05) / (fade_dist * 0.45)), 0.25, 1.0)
        if closed:
            taper = 0.84 + 0.16 * np.sin(2.0 * math.pi * s + phase1)
        else:
            taper = smoothstep(0.0, max(taper_ends, 0.05), s) * (
                1.0 - smoothstep(1.0 - max(taper_ends, 0.05), 1.0, s)
            )
            taper = 0.22 + 0.78 * taper
        widths = base_width * persp * taper

        half_w = widths * 0.5
        ribbon = np.vstack([curve + norm * half_w[:, None], (curve - norm * half_w[:, None])[::-1]])
        ctx = self.ctx
        ctx.set_source_rgba(*rgba)
        ctx.new_path()
        ctx.move_to(float(ribbon[0, 0]), float(ribbon[0, 1]))
        for x, y in ribbon[1:]:
            ctx.line_to(float(x), float(y))
        ctx.close_path()
        ctx.fill()

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


def project_3d_ring(
    cam: Camera3D,
    center: np.ndarray,
    rx: float,
    ry: float,
    z: float,
    n: int = 96,
    wobble_amp: float = 0.0,
    seed: int = 1,
) -> tuple[np.ndarray, np.ndarray]:
    th = np.linspace(0.0, 2.0 * math.pi, n, endpoint=False)
    wob = np.zeros_like(th)
    if wobble_amp > 0.0:
        rng = np.random.default_rng(seed)
        ph = rng.uniform(0.0, 2.0 * math.pi, size=3)
        wob = wobble_amp * (
            0.55 * np.sin(2.0 * th + ph[0])
            + 0.30 * np.sin(3.0 * th + ph[1])
            + 0.15 * np.sin(5.0 * th + ph[2])
        )
    pts = np.column_stack(
        [
            center[0] + (rx + wob) * np.cos(th),
            center[1] + (ry + wob) * np.sin(th),
            np.full_like(th, z),
        ]
    )
    u, v, zc = cam.project_points(pts)
    return np.column_stack([u, v]), zc


def extract_front_or_back_arc(ring_2d: np.ndarray, want_front: bool = True) -> np.ndarray:
    """Return the viewer-facing front arc (U-curved, lower on screen) or back arc."""
    idx_l = int(np.argmin(ring_2d[:, 0]))
    idx_r = int(np.argmax(ring_2d[:, 0]))
    n = len(ring_2d)
    rolled = np.roll(ring_2d, -idx_l, axis=0)
    span = (idx_r - idx_l) % n
    arc_a = rolled[: span + 1]
    arc_b = np.vstack([rolled[0:1], rolled[span:][::-1]])
    a_is_front = float(np.mean(arc_a[:, 1])) >= float(np.mean(arc_b[:, 1]))
    chosen = arc_a if (a_is_front == want_front) else arc_b
    if chosen[0, 0] > chosen[-1, 0]:
        chosen = chosen[::-1]
    return chosen


def build_smooth_lathe_silhouette(
    cam: Camera3D,
    center: np.ndarray,
    profile_rz: Sequence[tuple[float, float]],
    n_slices: int = 36,
    wobble_amp: float = 0.0,
    seed: int = 1,
) -> tuple[np.ndarray, list[np.ndarray]]:
    """Build a smooth, non-faceted 2D vessel silhouette from `(radius, z)` profile points."""
    prof = np.asarray(profile_rz, dtype=np.float64)
    dense = eval_catmull_rom(
        prof, samples_per_seg=max(6, n_slices // max(1, len(prof) - 1)), closed=False
    )
    left_edge, right_edge, rings = [], [], []
    for r_val, z_val in dense:
        ring, _ = project_3d_ring(
            cam, center, float(r_val), float(r_val), float(z_val), n=96, wobble_amp=wobble_amp, seed=seed
        )
        rings.append(ring)
        left_edge.append(ring[int(np.argmin(ring[:, 0]))])
        right_edge.append(ring[int(np.argmax(ring[:, 0]))])

    left_arr = np.array(left_edge)
    right_arr = np.array(right_edge)
    bot_front = extract_front_or_back_arc(rings[0], want_front=True)
    top_back = extract_front_or_back_arc(rings[-1], want_front=False)
    contour = np.vstack([left_arr[::-1], bot_front[1:-1], right_arr, top_back[::-1][1:-1]])
    return contour, rings


# ---------------------------------------------------------------------------
# 5. Foreground Circular Disc Bokeh & Float32 35mm Film Optics
# ---------------------------------------------------------------------------

def make_disc_kernel(radius: float = 8.0) -> np.ndarray:
    """Normalized circular iris PSF kernel with subtle spherical-aberration rim."""
    rad = max(1, int(round(float(radius))))
    ky, kx = np.mgrid[-rad : rad + 1, -rad : rad + 1].astype(np.float32)
    kr = np.sqrt(kx * kx + ky * ky) / max(float(radius), 1.0)
    rim = 0.86 + 0.24 * np.exp(-((kr - 0.84) ** 2) / 0.016)
    disc = np.clip((1.04 - kr) / 0.16, 0.0, 1.0) * rim
    return (disc / max(float(np.sum(disc)), 1e-6)).astype(np.float32)


def apply_foreground_disc_bokeh(
    canvas: np.ndarray,
    fg_rgb: np.ndarray,
    fg_alpha: np.ndarray,
    radius: float = 8.2,
    chroma_shift_px: float = 1.0,
) -> np.ndarray:
    """Blur a foreground RGBA silhouette with `make_disc_kernel` in premultiplied
    space plus ~1 px opposite red/blue lateral shift, then composite over canvas."""
    h, w, _ = canvas.shape
    kernel = make_disc_kernel(radius=radius)
    premul = np.empty((h, w, 4), dtype=np.float32)
    premul[:, :, :3] = fg_rgb * fg_alpha[:, :, None]
    premul[:, :, 3] = fg_alpha

    blurred = np.empty_like(premul)
    for c in range(4):
        blurred[:, :, c] = cv2.filter2D(premul[:, :, c], -1, kernel, borderType=cv2.BORDER_CONSTANT)

    m_red = np.array([[1.0, 0.0, chroma_shift_px], [0.0, 1.0, -0.35 * chroma_shift_px]], dtype=np.float32)
    m_blue = np.array([[1.0, 0.0, -chroma_shift_px], [0.0, 1.0, 0.35 * chroma_shift_px]], dtype=np.float32)
    blurred[:, :, 0] = cv2.warpAffine(blurred[:, :, 0], m_red, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)
    blurred[:, :, 2] = cv2.warpAffine(blurred[:, :, 2], m_blue, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)

    out_a = np.clip(blurred[:, :, 3], 0.0, 1.0)[:, :, None]
    return np.clip(canvas * (1.0 - out_a) + np.clip(blurred[:, :, :3], 0.0, 1.0), 0.0, 1.0)


def finish_35mm_optics(
    rgb: np.ndarray,
    specular_glints: np.ndarray | None = None,
    seed: int = 909,
) -> np.ndarray:
    """Float32 35mm cinema optics + restrained analog transfer finish."""
    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.30
    if specular_glints is not None:
        bright = np.clip(bright + specular_glints * 0.88, 0.0, 1.38)

    hal_tint = np.array([1.00, 0.90, 0.74], dtype=np.float32)
    h_src = bright[:, :, None] * hal_tint[None, None, :]
    halation = (
        0.17 * cv2.GaussianBlur(h_src, (0, 0), 6.5)
        + 0.16 * cv2.GaussianBlur(h_src, (0, 0), 24.0)
        + 0.14 * cv2.GaussianBlur(h_src, (0, 0), 72.0)
    )
    img = screen_blend(img, halation, strength=1.0)

    yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
    nx = (xx - w * 0.5) / (w * 0.5)
    ny = (yy - h * 0.5) / (h * 0.5)
    r2 = nx * nx + ny * ny

    ca_scale = 0.00085
    img[:, :, 0] = cv2.remap(
        img[:, :, 0],
        (xx + (xx - w * 0.5) * r2 * ca_scale).astype(np.float32),
        (yy + (yy - h * 0.5) * r2 * ca_scale).astype(np.float32),
        interpolation=cv2.INTER_LINEAR,
        borderMode=cv2.BORDER_REFLECT_101,
    )
    img[:, :, 2] = cv2.remap(
        img[:, :, 2],
        (xx - (xx - w * 0.5) * r2 * ca_scale).astype(np.float32),
        (yy - (yy - h * 0.5) * r2 * ca_scale).astype(np.float32),
        interpolation=cv2.INTER_LINEAR,
        borderMode=cv2.BORDER_REFLECT_101,
    )
    img *= (1.0 - 0.155 * np.clip(r2 - 0.16, 0.0, 2.0))[:, :, None]

    black_lift = np.array([0.018, 0.016, 0.022], dtype=np.float32)
    img = black_lift[None, None, :] + img * (1.0 - black_lift[None, None, :])
    knee, ceiling = 0.80, 0.965
    span = ceiling - knee
    above = np.maximum(img - knee, 0.0)
    img = np.where(img > knee, knee + span * np.tanh(above / span), img)

    rng = np.random.default_rng(seed)
    lum2 = 0.2126 * img[:, :, 0] + 0.7152 * img[:, :, 1] + 0.0722 * img[:, :, 2]
    env = np.clip(1.12 - 0.95 * (np.clip(lum2, 0.0, 1.0) ** 1.55), 0.12, 1.12)
    g_fine = rng.standard_normal((h, w)).astype(np.float32)
    g_clump = cv2.resize(
        rng.standard_normal((max(2, h // 2), max(2, w // 2))).astype(np.float32),
        (w, h),
        interpolation=cv2.INTER_LINEAR,
    )
    g_chroma = cv2.resize(
        rng.standard_normal((max(2, h // 2), max(2, w // 2), 3)).astype(np.float32),
        (w, h),
        interpolation=cv2.INTER_LINEAR,
    )
    img = np.clip(
        img + (0.0150 * (0.58 * g_fine + 0.42 * g_clump)[:, :, None] + 0.0042 * g_chroma) * env[:, :, None],
        0.0,
        1.0,
    )

    r_ch, g_ch, b_ch = img[:, :, 0], img[:, :, 1], img[:, :, 2]
    y_ch = 0.299 * r_ch + 0.587 * g_ch + 0.114 * b_ch
    i_ch = 0.596 * r_ch - 0.274 * g_ch - 0.322 * b_ch
    q_ch = 0.211 * r_ch - 0.523 * g_ch + 0.312 * b_ch

    i_soft = cv2.GaussianBlur(i_ch, (0, 0), sigmaX=1.05, sigmaY=0.15, borderType=cv2.BORDER_REFLECT_101)
    q_soft = cv2.GaussianBlur(q_ch, (0, 0), sigmaX=1.15, sigmaY=0.15, borderType=cv2.BORDER_REFLECT_101)
    y_blur = cv2.GaussianBlur(y_ch, (0, 0), sigmaX=0.85, sigmaY=0.05, borderType=cv2.BORDER_REFLECT_101)
    y_out = np.clip(y_ch + 0.07 * (y_ch - y_blur), 0.0, 1.0)

    out = np.empty_like(img)
    out[:, :, 0] = y_out + 0.956 * i_soft + 0.621 * q_soft
    out[:, :, 1] = y_out - 0.272 * i_soft - 0.647 * q_soft
    out[:, :, 2] = y_out - 1.106 * i_soft + 1.703 * q_soft
    out = np.clip(out, 0.0, 1.0)

    row_shift = rng.normal(0.0, 0.072, size=h).astype(np.float32)
    row_shift = cv2.GaussianBlur(row_shift[:, None], (1, 5), 0.9)[:, 0]
    out = cv2.remap(
        out,
        (xx + row_shift[:, None]).astype(np.float32),
        yy,
        interpolation=cv2.INTER_LINEAR,
        borderMode=cv2.BORDER_REFLECT_101,
    )
    scan = 1.0 - 0.0065 * (0.5 - 0.5 * np.cos(math.pi * yy))
    return np.clip(out * scan[:, :, None], 0.0, 1.0)


def save_image(rgb_float: np.ndarray, out_path: Path) -> None:
    out_path.parent.mkdir(parents=True, exist_ok=True)
    u8 = np.round(np.clip(rgb_float, 0.0, 1.0) * 255.0).astype(np.uint8)
    img = Image.fromarray(u8, mode="RGB")
    if out_path.suffix.lower() == ".webp":
        img.save(out_path, format="WEBP", quality=90, method=6)
    else:
        img.save(out_path, format="PNG", compress_level=6)


def save_crop_boxes(
    rgb_float: np.ndarray,
    crops_dir: Path,
    centers_px: Sequence[tuple[str, tuple[float, float]]],
    crop_w: int = 600,
    crop_h: int = 450,
) -> None:
    """Export 1:1 actual-pixel macro crops (`600 x 450` default) clamped inside the frame."""
    h, w, _ = rgb_float.shape
    crops_dir.mkdir(parents=True, exist_ok=True)
    cw, ch = min(crop_w, w), min(crop_h, h)
    for name, (cx, cy) in centers_px:
        x0 = int(np.clip(round(cx - cw * 0.5), 0, w - cw))
        y0 = int(np.clip(round(cy - ch * 0.5), 0, h - ch))
        save_image(rgb_float[y0 : y0 + ch, x0 : x0 + cw], crops_dir / name)


# ---------------------------------------------------------------------------
# 6. Dusk Study Desk Scene: Projecting Thoughts into Sentences
# ---------------------------------------------------------------------------

WIDTH = 2048
HEIGHT = 1152

# Off-axis metric camera (+X right, +Y forward, +Z up; desk surface Z = 0.0)
CAM_EYE = np.array([0.28, -0.34, 0.50], dtype=np.float64)
CAM_TARGET = np.array([-0.04, 1.38, 0.11], dtype=np.float64)
CAM_UP = np.array([0.0, 0.0, 1.0], dtype=np.float64)
CAM_FOV_DEG = 49.0

# Unified 3D evening sun/dusk window light travel vector (from upper-right window)
_SUN_RAW = np.array([-0.54, -0.74, -0.40], dtype=np.float64)
SUN_DIR = _SUN_RAW / np.linalg.norm(_SUN_RAW)

Y_BACK_WALL = 2.68
X_LEFT_WALL = -1.04
WIN_X0, WIN_X1 = -0.34, 1.98
WIN_Z0, WIN_Z1 = 0.02, 1.52
WIN_V_MULLIONS = (0.18, 0.72, 1.26)
WIN_H_MULLIONS = (0.48, 0.98)
WIN_MULLION_W = 0.042


def trace_window_light(wx: np.ndarray, wy: np.ndarray, wz: np.ndarray) -> np.ndarray:
    t = (Y_BACK_WALL - wy) / (-float(SUN_DIR[1]))
    xh = wx - t * float(SUN_DIR[0])
    zh = wz - t * float(SUN_DIR[2])
    pen = np.clip(0.010 + 0.009 * np.maximum(t, 0.0), 0.008, 0.038)
    in_x = smoothstep(WIN_X0 - pen, WIN_X0 + pen, xh) * (1.0 - smoothstep(WIN_X1 - pen, WIN_X1 + pen, xh))
    in_z = smoothstep(WIN_Z0 - pen, WIN_Z0 + pen, zh) * (1.0 - smoothstep(WIN_Z1 - pen, WIN_Z1 + pen, zh))
    pane = in_x * in_z
    half_m = WIN_MULLION_W * 0.5
    mull = np.ones_like(pane, dtype=np.float32)
    for mx in WIN_V_MULLIONS:
        mull *= smoothstep(half_m - pen * 0.5, half_m + pen * 0.9, np.abs(xh - mx))
    for mz in WIN_H_MULLIONS:
        mull *= smoothstep(half_m - pen * 0.5, half_m + pen * 0.9, np.abs(zh - mz))
    valid = (t > 0.0).astype(np.float32)
    return np.clip(pane * mull * valid, 0.0, 1.0).astype(np.float32)


def stroke_sharp_poly(layer: CairoLayer2x, pts: np.ndarray, z_depth: float, width: float, rgba: tuple[float, float, float, float], tremor: float = 0.2, seed: int = 1) -> None:
    n = len(pts)
    for i in range(n):
        p0, p1 = pts[i], pts[(i + 1) % n]
        mid = 0.5 * (p0 + p1)
        layer.stroke_catmull_rom(np.vstack([p0, mid, p1]), z_depth, width, rgba, closed=False, tremor=tremor, taper_ends=0.04, seed=seed + i)


def project_quad(cam: Camera3D, pts_3d: np.ndarray) -> np.ndarray:
    u, v, _ = cam.project_points(pts_3d)
    return np.column_stack([u, v])


def render_sky_and_architecture(cam: Camera3D, tooth: np.ndarray) -> np.ndarray:
    h, w = cam.height, cam.width
    yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
    yn = yy / float(h)
    xn = xx / float(w)

    # Warm dusk exterior sky gradient behind window
    top_sky = hex_rgb("#486074")
    mid_sky = hex_rgb("#B99B7F")
    low_sky = hex_rgb("#F4DEC0")
    t1 = smoothstep(0.04, 0.44, yn)[..., None]
    t2 = smoothstep(0.36, 0.72, yn)[..., None]
    sky = top_sky * (1.0 - t1) + mid_sky * t1
    sky = sky * (1.0 - t2) + low_sky * t2
    # Soft dusk cloud wisps
    cloud = fbm_gouache(h, w, octaves=((120.0, 44.0, 0.55), (46.0, 22.0, 0.30), (18.0, 10.0, 0.15)), seed=31)
    cloud_m = smoothstep(0.15, 1.15, cloud) * (1.0 - smoothstep(0.45, 0.75, yn))
    sky = np.clip(sky + cloud_m[..., None] * np.array([0.14, 0.10, 0.06], dtype=np.float32), 0.0, 1.0)
    # Distant dark slate treeline silhouette near bottom of window
    tree_line = 0.54 + 0.032 * np.sin(xn * 11.0 + 0.4) + 0.018 * np.sin(xn * 27.0)
    tree_m = smoothstep(tree_line - 0.012, tree_line + 0.010, yn)
    sky = alpha_composite(sky, np.broadcast_to(hex_rgb("#354148"), (h, w, 3)), tree_m * 0.88)

    fog_col = hex_rgb("#E9DFCE")
    canvas = sky.copy()

    # Back plaster wall with rectangular window cutout
    bw_h, bw_w = 512, 768
    p0_bw = np.array([X_LEFT_WALL, Y_BACK_WALL, -0.55], dtype=np.float64)
    span_u_bw, span_v_bw = 3.45, 2.55
    u_g = np.linspace(0.0, span_u_bw, bw_w, dtype=np.float32)[None, :]
    v_g = np.linspace(0.0, span_v_bw, bw_h, dtype=np.float32)[:, None]
    wx_bw = float(p0_bw[0]) + u_g
    wz_bw = float(p0_bw[2]) + span_v_bw - v_g
    in_win = (wx_bw >= WIN_X0) & (wx_bw <= WIN_X1) & (wz_bw >= WIN_Z0) & (wz_bw <= WIN_Z1)
    bw_rgb = np.broadcast_to(hex_rgb("#D8CFC0"), (bw_h, bw_w, 3)).copy()
    # Vertical dusk falloff across plaster wall
    grad_bw = smoothstep(-0.3, 1.8, wz_bw)[..., None]
    bw_rgb = bw_rgb * (0.72 + 0.28 * grad_bw)
    bw_mottle = fbm_gouache(bw_h, bw_w, seed=55)
    bw_rgb = np.clip(bw_rgb + 0.025 * bw_mottle[..., None], 0.0, 1.0)
    bw_a = (~in_win).astype(np.float32)
    w_rgb, w_a, _ = cam.warp_plane_panel(
        bw_rgb, bw_a,
        p0=np.array([X_LEFT_WALL, Y_BACK_WALL, float(p0_bw[2]) + span_v_bw]),
        e1=np.array([1.0, 0.0, 0.0]),
        e2=np.array([0.0, 0.0, -1.0]),
        span_u=span_u_bw, span_v=span_v_bw,
        fog_color=fog_col, fog_start=1.8, fog_density=0.05,
    )
    canvas = alpha_composite(canvas, w_rgb, w_a)

    # Cedar window frame and mullions in 2x PyCairo
    win_layer = CairoLayer2x(w, h)
    cedar_dark = (0.20, 0.15, 0.12, 1.0)
    cedar_lit = (0.36, 0.26, 0.19, 1.0)
    fw = 0.055
    frame_bars = [
        (WIN_X0 - fw, WIN_X1 + fw, WIN_Z1, WIN_Z1 + fw),
        (WIN_X0 - fw, WIN_X1 + fw, WIN_Z0 - fw, WIN_Z0),
        (WIN_X0 - fw, WIN_X0, WIN_Z0 - fw, WIN_Z1 + fw),
        (WIN_X1, WIN_X1 + fw, WIN_Z0 - fw, WIN_Z1 + fw),
    ]
    for mx in WIN_V_MULLIONS:
        frame_bars.append((mx - WIN_MULLION_W * 0.5, mx + WIN_MULLION_W * 0.5, WIN_Z0, WIN_Z1))
    for mz in WIN_H_MULLIONS:
        frame_bars.append((WIN_X0, WIN_X1, mz - WIN_MULLION_W * 0.5, mz + WIN_MULLION_W * 0.5))
    for x0, x1, z0, z1 in frame_bars:
        q = project_quad(cam, np.array([[x0, Y_BACK_WALL, z0], [x1, Y_BACK_WALL, z0], [x1, Y_BACK_WALL, z1], [x0, Y_BACK_WALL, z1]]))
        win_layer.fill_poly(q, cedar_dark)
        # Warm rim highlight on sun-facing edge
        edge = project_quad(cam, np.array([[x0, Y_BACK_WALL - 0.015, z0], [x0, Y_BACK_WALL - 0.015, z1]]))
        win_layer.stroke_catmull_rom(edge, 2.6, 1.5, cedar_lit, tremor=0.25, seed=9)
    wf_rgb, wf_a = win_layer.finish()
    canvas = alpha_composite(canvas, wf_rgb, wf_a)

    # Left cream plaster wall with diagonal sunlight patch from the back window
    lw_h, lw_w = 512, 768
    span_u_lw, span_v_lw = 3.25, 2.40
    p0_lw = np.array([X_LEFT_WALL, -0.45, 1.85], dtype=np.float64)
    uy = np.linspace(0.0, span_u_lw, lw_w, dtype=np.float32)[None, :]
    vz = np.linspace(0.0, span_v_lw, lw_h, dtype=np.float32)[:, None]
    wy_lw = float(p0_lw[1]) + uy
    wz_lw = float(p0_lw[2]) - vz
    wx_lw = np.full_like(wy_lw, X_LEFT_WALL)
    sun_lw = trace_window_light(wx_lw, wy_lw, wz_lw)
    lw_shade = hex_rgb("#B9B1A2")
    lw_lit = hex_rgb("#F7E6CA")
    lw_rgb = lw_shade[None, None, :] * (1.0 - sun_lw[..., None]) + lw_lit[None, None, :] * sun_lw[..., None]
    lw_rgb = np.clip(lw_rgb + 0.022 * fbm_gouache(lw_h, lw_w, seed=71)[..., None], 0.0, 1.0)
    lw_a = np.ones((lw_h, lw_w), dtype=np.float32)
    l_rgb, l_a, _ = cam.warp_plane_panel(
        lw_rgb, lw_a, p0=p0_lw,
        e1=np.array([0.0, 1.0, 0.0]), e2=np.array([0.0, 0.0, -1.0]),
        span_u=span_u_lw, span_v=span_v_lw,
        fog_color=fog_col, fog_start=1.6, fog_density=0.05,
    )
    canvas = alpha_composite(canvas, l_rgb, l_a)

    # Warm walnut / oak study desk plane (Z = 0.0)
    dt_h, dt_w = 768, 768
    desk_x0, desk_x1 = -0.92, 0.96
    desk_y0, desk_y1 = 0.04, 2.24
    span_u_dt = desk_x1 - desk_x0
    span_v_dt = desk_y1 - desk_y0
    ux = np.linspace(0.0, span_u_dt, dt_w, dtype=np.float32)[None, :]
    vy = np.linspace(0.0, span_v_dt, dt_h, dtype=np.float32)[:, None]
    wx_dt = desk_x0 + ux
    wy_dt = desk_y0 + vy
    wz_dt = np.zeros_like(wx_dt)
    sun_dt = trace_window_light(wx_dt, wy_dt, wz_dt)

    # Subtle plank joints and isotropic timber mottling
    grain_broad = fbm_gouache(dt_h, dt_w, octaves=((90.0, 38.0, 0.55), (34.0, 18.0, 0.30), (14.0, 9.0, 0.15)), seed=83)
    plank_seam = np.exp(-((np.abs(((wx_dt + 0.12) % 0.28) - 0.14) - 0.14) ** 2) / 0.000018)
    wood_shade = hex_rgb("#5A4535")
    wood_lit = hex_rgb("#B6885E")
    dt_rgb = wood_shade[None, None, :] * (1.0 - sun_dt[..., None]) + wood_lit[None, None, :] * sun_dt[..., None]
    dt_rgb = np.clip(dt_rgb + 0.035 * grain_broad[..., None] - 0.08 * plank_seam[..., None], 0.0, 1.0)
    # Soft table apron shadow near far edge
    dt_rgb *= (0.84 + 0.16 * smoothstep(2.24, 1.50, wy_dt))[..., None]
    dt_a = np.ones((dt_h, dt_w), dtype=np.float32)

    d_rgb, d_a, _ = cam.warp_plane_panel(
        dt_rgb, dt_a,
        p0=np.array([desk_x0, desk_y0, 0.0]),
        e1=np.array([1.0, 0.0, 0.0]),
        e2=np.array([0.0, 1.0, 0.0]),
        span_u=span_u_dt, span_v=span_v_dt,
        fog_color=fog_col, fog_start=1.9, fog_density=0.04,
    )
    canvas = alpha_composite(canvas, d_rgb, d_a)
    canvas = paint_isotropic_gouache_dabs(canvas, np.ones((h, w), dtype=np.float32), tooth, dab_strength=0.036, num_dabs=88, seed=107)
    return canvas


def draw_desk_props(cam: Camera3D, canvas: np.ndarray, tooth: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    h, w = cam.height, cam.width
    specular = np.zeros((h, w), dtype=np.float32)

    # 1. Rear props layer: closed dark laptop (right) + stacked cloth notebooks (rear-left)
    rear = CairoLayer2x(w, h)
    # Closed laptop in cool shade on upper-right desk
    lap_pts = np.array([
        [0.24, 1.24, 0.0], [0.56, 1.28, 0.0], [0.52, 1.54, 0.0], [0.20, 1.50, 0.0]
    ])
    lap_top = lap_pts + np.array([0.0, 0.0, 0.018])
    lap_sh = shadow_xy_on_plane(lap_top, SUN_DIR, 0.0)
    rear.fill_poly(project_quad(cam, lap_sh), (0.09, 0.08, 0.09, 0.42))
    # Front bevel & lid
    rear.fill_poly(project_quad(cam, np.array([lap_pts[0], lap_pts[1], lap_top[1], lap_top[0]])), (0.14, 0.16, 0.19, 1.0))
    rear.fill_poly(project_quad(cam, np.array([lap_pts[3], lap_pts[0], lap_top[0], lap_top[3]])), (0.11, 0.13, 0.16, 1.0))
    lid_2d = project_quad(cam, lap_top)
    rear.fill_poly_linear(
        lid_2d, tuple(lid_2d[0]), tuple(lid_2d[2]),
        [(0.0, (0.21, 0.24, 0.28, 1.0)), (0.55, (0.27, 0.30, 0.34, 1.0)), (1.0, (0.18, 0.20, 0.24, 1.0))]
    )
    stroke_sharp_poly(rear, lid_2d, 1.4, 1.5, (0.09, 0.09, 0.11, 0.85), tremor=0.18, seed=12)

    # Stacked cloth notebooks (rear-left)
    for idx, (z0, z1, col_top, col_side) in enumerate([
        (0.0, 0.024, (0.24, 0.35, 0.42, 1.0), (0.18, 0.27, 0.33, 1.0)),
        (0.024, 0.044, (0.72, 0.39, 0.28, 1.0), (0.55, 0.29, 0.20, 1.0)),
    ]):
        dx = -0.012 * idx
        dy = 0.008 * idx
        base = np.array([
            [-0.56 + dx, 1.32 + dy, z0], [-0.30 + dx, 1.35 + dy, z0],
            [-0.33 + dx, 1.56 + dy, z0], [-0.59 + dx, 1.53 + dy, z0],
        ])
        top = base.copy()
        top[:, 2] = z1
        if idx == 0:
            rear.fill_poly(project_quad(cam, shadow_xy_on_plane(top, SUN_DIR, 0.0)), (0.10, 0.08, 0.07, 0.40))
        rear.fill_poly(project_quad(cam, np.array([base[0], base[1], top[1], top[0]])), (0.91, 0.88, 0.81, 1.0))
        rear.fill_poly(project_quad(cam, np.array([base[1], base[2], top[2], top[1]])), col_side)
        top_2d = project_quad(cam, top)
        rear.fill_poly(top_2d, col_top)
        stroke_sharp_poly(rear, top_2d, 1.4, 1.4, (0.12, 0.10, 0.09, 0.78), tremor=0.2, seed=21 + idx)

    r_rgb, r_a = rear.finish()
    r_rgb = paint_isotropic_gouache_dabs(r_rgb, r_a, tooth, dab_strength=0.042, num_dabs=70, seed=131)
    canvas = alpha_composite(canvas, r_rgb, r_a)

    # 2. Hero open cream notebook (center-left) + crossed-out ink draft + fountain pen
    hero = CairoLayer2x(w, h)
    # Slight organic desk rotation angle (-8 deg)
    ang = math.radians(-8.0)
    ca, sa = math.cos(ang), math.sin(ang)
    nb_c = np.array([-0.12, 0.86, 0.0])

    def nb_pt(lx: float, ly: float, lz: float = 0.0) -> np.ndarray:
        return np.array([nb_c[0] + lx * ca - ly * sa, nb_c[1] + lx * sa + ly * ca, lz], dtype=np.float64)

    # Cover backing + cast shadow
    cov_b = np.array([nb_pt(-0.225, -0.150, 0.0), nb_pt(0.225, -0.150, 0.0), nb_pt(0.225, 0.150, 0.0), nb_pt(-0.225, 0.150, 0.0)])
    cov_t = np.array([nb_pt(-0.225, -0.150, 0.012), nb_pt(0.225, -0.150, 0.012), nb_pt(0.225, 0.150, 0.012), nb_pt(-0.225, 0.150, 0.012)])
    hero.fill_poly(project_quad(cam, shadow_xy_on_plane(cov_t, SUN_DIR, 0.0)), (0.10, 0.07, 0.05, 0.44))
    hero.fill_poly(project_quad(cam, cov_b), (0.16, 0.15, 0.14, 1.0))

    # Page block thickness along front edge
    pg_fl = np.array([nb_pt(-0.214, -0.140, 0.004), nb_pt(0.0, -0.140, 0.003), nb_pt(0.0, -0.140, 0.015), nb_pt(-0.214, -0.140, 0.016)])
    pg_fr = np.array([nb_pt(0.0, -0.140, 0.003), nb_pt(0.214, -0.140, 0.004), nb_pt(0.214, -0.140, 0.016), nb_pt(0.0, -0.140, 0.015)])
    hero.fill_poly(project_quad(cam, pg_fl), (0.85, 0.82, 0.75, 1.0))
    hero.fill_poly(project_quad(cam, pg_fr), (0.89, 0.86, 0.79, 1.0))

    # Left & right open pages with gentle gutter arch
    def page_poly(side: float) -> np.ndarray:
        xs = np.linspace(0.0, 0.214 * side, 9)
        front = [nb_pt(x, -0.140, 0.014 + 0.007 * math.sin(math.pi * abs(x) / 0.214)) for x in xs]
        back = [nb_pt(x, 0.140, 0.014 + 0.007 * math.sin(math.pi * abs(x) / 0.214)) for x in xs[::-1]]
        return project_quad(cam, np.array(front + back))

    lp_2d = page_poly(-1.0)
    rp_2d = page_poly(1.0)
    hero.fill_poly_linear(
        lp_2d, tuple(lp_2d[0]), tuple(lp_2d[8]),
        [(0.0, (0.86, 0.83, 0.77, 1.0)), (0.28, (0.96, 0.94, 0.89, 1.0)), (1.0, (0.95, 0.92, 0.86, 1.0))]
    )
    hero.fill_poly_linear(
        rp_2d, tuple(rp_2d[0]), tuple(rp_2d[8]),
        [(0.0, (0.88, 0.84, 0.77, 1.0)), (0.22, (0.98, 0.96, 0.91, 1.0)), (1.0, (0.97, 0.94, 0.88, 1.0))]
    )
    hero.stroke_catmull_rom(lp_2d[:9], 0.9, 1.35, (0.22, 0.19, 0.16, 0.78), closed=False, tremor=0.2, seed=31)
    hero.stroke_catmull_rom(lp_2d[9:], 0.9, 1.35, (0.22, 0.19, 0.16, 0.78), closed=False, tremor=0.2, seed=32)
    stroke_sharp_poly(hero, np.vstack([lp_2d[0], lp_2d[-1]]), 0.9, 1.35, (0.22, 0.19, 0.16, 0.72), tremor=0.15, seed=33)
    stroke_sharp_poly(hero, np.vstack([lp_2d[8], lp_2d[9]]), 0.9, 1.35, (0.22, 0.19, 0.16, 0.72), tremor=0.15, seed=34)
    hero.stroke_catmull_rom(rp_2d[:9], 0.9, 1.35, (0.22, 0.19, 0.16, 0.78), closed=False, tremor=0.2, seed=35)
    hero.stroke_catmull_rom(rp_2d[9:], 0.9, 1.35, (0.22, 0.19, 0.16, 0.78), closed=False, tremor=0.2, seed=36)
    stroke_sharp_poly(hero, np.vstack([rp_2d[8], rp_2d[9]]), 0.9, 1.35, (0.22, 0.19, 0.16, 0.72), tremor=0.15, seed=37)

    # Ruled lines + handwritten ink strokes + clay-terracotta revisions & arrows on pages
    rng = np.random.default_rng(404)
    for side in (-1.0, 1.0):
        x_a = 0.024 * side
        x_b = 0.192 * side
        if x_a > x_b:
            x_a, x_b = x_b, x_a
        for row in range(9):
            ly = 0.105 - row * 0.024
            rule_pts = np.array([nb_pt(x, ly, 0.015 + 0.007 * math.sin(math.pi * abs(x) / 0.214)) for x in np.linspace(x_a, x_b, 6)])
            hero.stroke_catmull_rom(project_quad(cam, rule_pts), 0.9, 0.55, (0.42, 0.41, 0.38, 0.25), tremor=0.1, seed=50 + row)
            # Handwritten ink word dashes
            if side < 0 and row < 7:
                end_x = x_b - (0.04 if row in (2, 6) else 0.008)
                xs_w = np.linspace(x_a + 0.006, end_x, 10)
                w_pts = np.array([nb_pt(x, ly + float(rng.uniform(-0.0025, 0.0025)), 0.016 + 0.007 * math.sin(math.pi * abs(x) / 0.214)) for x in xs_w])
                hero.stroke_catmull_rom(project_quad(cam, w_pts), 0.85, 1.45, (0.11, 0.11, 0.12, 0.78), tremor=0.7, seed=100 + row)
            if side > 0 and row < 5:
                end_x = x_b - (0.05 if row == 4 else 0.012)
                xs_w = np.linspace(x_a + 0.006, end_x, 10)
                w_pts = np.array([nb_pt(x, ly + float(rng.uniform(-0.0025, 0.0025)), 0.016 + 0.007 * math.sin(math.pi * abs(x) / 0.214)) for x in xs_w])
                hero.stroke_catmull_rom(project_quad(cam, w_pts), 0.85, 1.45, (0.11, 0.11, 0.12, 0.76), tremor=0.7, seed=140 + row)

    # Terracotta-clay editorial strikethrough + curved marginal revision arrow on right page
    strike_pts = np.array([nb_pt(x, 0.057, 0.022) for x in np.linspace(0.032, 0.158, 7)])
    hero.stroke_catmull_rom(project_quad(cam, strike_pts), 0.85, 2.2, (0.73, 0.39, 0.28, 0.90), tremor=0.55, seed=201)
    arc_pts = np.array([nb_pt(0.155 + 0.028 * math.sin(t * math.pi), 0.055 - 0.068 * t, 0.022) for t in np.linspace(0.0, 1.0, 9)])
    hero.stroke_catmull_rom(project_quad(cam, arc_pts), 0.85, 1.9, (0.73, 0.39, 0.28, 0.88), tremor=0.4, seed=202)
    # Small circle diagram sketch at bottom-right of open page
    for k in range(3):
        cx_s = 0.065 + 0.042 * k
        cy_s = -0.062 + (0.018 if k == 1 else -0.008)
        th = np.linspace(0, 2 * math.pi, 16)
        circ = np.array([nb_pt(cx_s + 0.012 * math.cos(t), cy_s + 0.012 * math.sin(t), 0.021) for t in th])
        hero.stroke_catmull_rom(project_quad(cam, circ), 0.85, 1.2, (0.24, 0.35, 0.42, 0.72), closed=True, tremor=0.3, seed=210 + k)

    # Uncapped fountain pen resting diagonally across right page
    pen_p0 = nb_pt(-0.045, -0.095, 0.026)  # nib tip
    pen_p1 = nb_pt(0.155, 0.028, 0.027)    # tail end
    pen_vec = pen_p1 - pen_p0
    pen_dir = pen_vec / np.linalg.norm(pen_vec)
    pen_side = np.array([-pen_dir[1], pen_dir[0], 0.0])
    # Pen shadow on paper
    p_sh0 = shadow_xy_on_plane(pen_p0[None, :], SUN_DIR, 0.018)[0]
    p_sh1 = shadow_xy_on_plane(pen_p1[None, :], SUN_DIR, 0.018)[0]
    sh_quad = project_quad(cam, np.array([p_sh0 - pen_side * 0.005, p_sh1 - pen_side * 0.007, p_sh1 + pen_side * 0.007, p_sh0 + pen_side * 0.005]))
    hero.fill_poly(sh_quad, (0.14, 0.11, 0.09, 0.34))
    # Brass-gold nib + dark lacquer barrel
    nib_base = pen_p0 + pen_vec * 0.13
    nib_quad = project_quad(cam, np.array([pen_p0, nib_base - pen_side * 0.0055, nib_base + pen_side * 0.0055]))
    hero.fill_poly(nib_quad, (0.80, 0.64, 0.33, 1.0))
    stroke_sharp_poly(hero, nib_quad, 0.85, 1.1, (0.18, 0.14, 0.09, 0.85), tremor=0.1, seed=230)
    bar_quad = project_quad(cam, np.array([
        nib_base - pen_side * 0.0075, pen_p1 - pen_side * 0.0065,
        pen_p1 + pen_side * 0.0065, nib_base + pen_side * 0.0075
    ]))
    hero.fill_poly_linear(
        bar_quad, tuple(bar_quad[0]), tuple(bar_quad[3]),
        [(0.0, (0.09, 0.09, 0.10, 1.0)), (0.35, (0.25, 0.25, 0.27, 1.0)), (1.0, (0.08, 0.08, 0.09, 1.0))]
    )
    # Brass collar ring & specular glint
    ring_a = pen_p0 + pen_vec * 0.30
    ring_b = pen_p0 + pen_vec * 0.33
    hero.fill_poly(project_quad(cam, np.array([
        ring_a - pen_side * 0.0078, ring_b - pen_side * 0.0078,
        ring_b + pen_side * 0.0078, ring_a + pen_side * 0.0078
    ])), (0.85, 0.69, 0.36, 1.0))
    stroke_sharp_poly(hero, bar_quad, 0.85, 1.25, (0.06, 0.06, 0.07, 0.90), tremor=0.12, seed=231)

    h_rgb, h_a = hero.finish()
    h_rgb = paint_isotropic_gouache_dabs(h_rgb, h_a, tooth, dab_strength=0.028, num_dabs=64, seed=151)
    canvas = alpha_composite(canvas, h_rgb, h_a)

    # 3. Glazed stoneware teacup with warm amber tea + grazing Fresnel sky reflection (right-mid)
    cup = CairoLayer2x(w, h)
    cup_c = np.array([0.23, 0.93, 0.0], dtype=np.float64)
    cup_prof = [
        (0.028, 0.000), (0.031, 0.008), (0.041, 0.032),
        (0.044, 0.062), (0.043, 0.076), (0.041, 0.082),
    ]
    # Cast cup shadow seamlessly connecting foot base to projected top rim along SUN_DIR
    th_s = np.linspace(0, 2 * math.pi, 36, endpoint=False)
    base_3d = np.column_stack([cup_c[0] + 0.029 * np.cos(th_s), cup_c[1] + 0.029 * np.sin(th_s), np.zeros(36)])
    top_sh = shadow_xy_on_plane(
        np.column_stack([cup_c[0] + 0.042 * np.cos(th_s), cup_c[1] + 0.042 * np.sin(th_s), np.full(36, 0.080)]),
        SUN_DIR, 0.0
    )
    sh_2d_all = project_quad(cam, np.vstack([base_3d, top_sh])).astype(np.float32)
    hull = cv2.convexHull(sh_2d_all)[:, 0, :]
    cup.fill_poly(hull, (0.10, 0.07, 0.05, 0.36))

    cup_contour, cup_rings = build_smooth_lathe_silhouette(cam, cup_c, cup_prof, n_slices=40, wobble_amp=0.0004, seed=7)
    c_l = cup_contour[int(np.argmin(cup_contour[:, 0]))]
    c_r = cup_contour[int(np.argmax(cup_contour[:, 0]))]
    cup.fill_poly_linear(
        cup_contour, (float(c_l[0]), float(c_l[1])), (float(c_r[0]), float(c_r[1])),
        [(0.0, (0.48, 0.37, 0.30, 1.0)), (0.38, (0.77, 0.56, 0.44, 1.0)), (0.78, (0.93, 0.87, 0.78, 1.0)), (1.0, (0.76, 0.66, 0.56, 1.0))]
    )
    # Foot band accent (terracotta unglazed clay base)
    foot_bot = extract_front_or_back_arc(cup_rings[0], want_front=True)
    foot_top = extract_front_or_back_arc(cup_rings[4], want_front=True)
    cup.fill_poly(np.vstack([foot_bot, foot_top[::-1]]), (0.58, 0.33, 0.24, 0.92))

    # Ceramic lip, deep glazed interior cavity, and clipped warm amber tea surface
    rim_out, _ = project_3d_ring(cam, cup_c, 0.041, 0.041, 0.082, n=72)
    rim_in, _ = project_3d_ring(cam, cup_c, 0.037, 0.037, 0.081, n=72)
    tea_ring, _ = project_3d_ring(cam, cup_c, 0.0365, 0.0365, 0.072, n=72)
    cup.fill_poly(rim_out, (0.90, 0.84, 0.76, 1.0))
    cup.fill_poly(rim_in, (0.42, 0.31, 0.23, 1.0))
    # Clip amber tea cleanly inside inner rim opening
    ctx_c = cup.ctx
    ctx_c.save()
    ctx_c.new_path()
    ctx_c.move_to(float(rim_in[0, 0]), float(rim_in[0, 1]))
    for rx_p, ry_p in rim_in[1:]:
        ctx_c.line_to(float(rx_p), float(ry_p))
    ctx_c.close_path()
    ctx_c.clip()
    t_top = tea_ring[int(np.argmin(tea_ring[:, 1]))]
    t_bot = tea_ring[int(np.argmax(tea_ring[:, 1]))]
    cup.fill_poly_linear(
        tea_ring, (float(t_top[0]), float(t_top[1])), (float(t_bot[0]), float(t_bot[1])),
        [(0.0, (0.94, 0.87, 0.75, 0.96)), (0.38, (0.63, 0.36, 0.17, 0.98)), (1.0, (0.28, 0.14, 0.07, 1.0))]
    )
    ctx_c.restore()
    cup.stroke_catmull_rom(cup_contour[::3], 0.95, 1.6, (0.14, 0.11, 0.09, 0.84), closed=True, tremor=0.25, seed=71)
    cup.stroke_catmull_rom(rim_out[::2], 0.95, 1.4, (0.96, 0.91, 0.82, 0.85), closed=True, tremor=0.15, seed=72)

    # Specular glint on tea & rim
    u_g, v_g, _ = cam.project_points(cup_c + np.array([0.015, -0.008, 0.072]))
    yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
    specular += np.exp(-(((xx - u_g) ** 2) / 140.0 + ((yy - v_g) ** 2) / 48.0)).astype(np.float32) * 0.75

    cu_rgb, cu_a = cup.finish()
    cu_rgb = paint_isotropic_gouache_dabs(cu_rgb, cu_a, tooth, dab_strength=0.032, num_dabs=50, seed=173)
    canvas = alpha_composite(canvas, cu_rgb, cu_a)

    # 4. Soft volumetric dusk light shaft from back window
    shaft_pts = project_quad(cam, np.array([
        [0.05, Y_BACK_WALL, 1.38], [1.45, Y_BACK_WALL, 1.38],
        [0.10, 0.45, 0.0], [-0.72, 0.45, 0.0]
    ]))
    shaft_mask = np.zeros((h, w), dtype=np.float32)
    cv2.fillConvexPoly(shaft_mask, np.round(shaft_pts).astype(np.int32), 1.0, cv2.LINE_AA)
    shaft_mask = cv2.GaussianBlur(shaft_mask, (0, 0), 54.0) * 0.11
    canvas = screen_blend(canvas, shaft_mask[..., None] * hex_rgb("#F7DFB6")[None, None, :], strength=1.0)

    # 5. Out-of-focus foreground olive sprig in bottom-left corner via disc bokeh
    fg = CairoLayer2x(w, h)
    stem = np.array([[0.0, h * 1.03], [w * 0.05, h * 0.88], [w * 0.12, h * 0.76], [w * 0.18, h * 0.70]])
    fg.stroke_catmull_rom(stem, 0.3, 6.0, (0.14, 0.17, 0.13, 1.0), tremor=0.6, seed=801)
    for (lx, ly, ang_l, rx_l, ry_l) in [
        (w * 0.05, h * 0.89, -0.7, 58, 20),
        (w * 0.09, h * 0.83, 0.35, 64, 22),
        (w * 0.12, h * 0.77, -0.5, 52, 18),
        (w * 0.16, h * 0.72, 0.15, 48, 17),
    ]:
        th = np.linspace(0, 2 * math.pi, 24)
        ca_l, sa_l = math.cos(ang_l), math.sin(ang_l)
        pts_l = np.column_stack([
            lx + rx_l * np.cos(th) * ca_l - ry_l * np.sin(th) * sa_l,
            ly + rx_l * np.cos(th) * sa_l + ry_l * np.sin(th) * ca_l,
        ])
        fg.fill_poly(pts_l, (0.16, 0.21, 0.15, 0.96))
    fg_rgb, fg_a = fg.finish()
    canvas = apply_foreground_disc_bokeh(canvas, fg_rgb, fg_a, radius=8.2, chroma_shift_px=1.0)

    return canvas, specular


def main() -> None:
    parser = argparse.ArgumentParser(description="Render 35mm cel-and-gouache study desk plate.")
    parser.add_argument("--out", type=Path, required=True, help="Output image path (.webp or .png)")
    parser.add_argument("--crops-dir", type=Path, default=None, help="Optional directory for 600x450 1:1 audit crops")
    args = parser.parse_args()

    cam = Camera3D(CAM_EYE, CAM_TARGET, CAM_UP, CAM_FOV_DEG, WIDTH, HEIGHT)
    tooth = make_paper_tooth(HEIGHT, WIDTH, seed=707)

    canvas = render_sky_and_architecture(cam, tooth)
    canvas, spec = draw_desk_props(cam, canvas, tooth)
    final = finish_35mm_optics(canvas, specular_glints=spec, seed=919)

    save_image(final, args.out)
    if args.crops_dir is not None:
        nb_u, nb_v, _ = cam.project_points(np.array([-0.08, 0.86, 0.02]))
        cup_u, cup_v, _ = cam.project_points(np.array([0.23, 0.95, 0.05]))
        win_u, win_v, _ = cam.project_points(np.array([0.55, Y_BACK_WALL, 0.72]))
        save_crop_boxes(
            final,
            args.crops_dir,
            [
                ("crop1_window.png", (win_u, win_v)),
                ("crop2_notebook_pen.png", (nb_u, nb_v)),
                ("crop3_cup_laptop.png", (cup_u, cup_v)),
            ],
        )


if __name__ == "__main__":
    main()
