#!/usr/bin/env python3
"""Pure-Python 1990s 35mm cel-and-gouache field-camp dusk painting.

Depicts an instrumented high-Andean basecamp at 4,350 m in Peru's Cordillera
Vilcanota at twilight: a lantern-lit canvas command workstation tent with field
laptop, rock cores, and Starlink tripod outside; a stone-ringed camp stove,
Pelican equipment case, geological hammer, and smooth-lathed enamel mugs; and a
braided proglacial meltwater stream catching Fresnel alpenglow reflections.

Zero image models, zero external textures, zero font dependencies.
Run: python3 paint_scene.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


# ---------------------------------------------------------------------------
# Color, Noise, Camera, and 2x PyCairo Primitives (self-contained)
# ---------------------------------------------------------------------------

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:
    e0a = np.asarray(e0, dtype=np.float32)
    e1a = np.asarray(e1, dtype=np.float32)
    xa = np.asarray(x, dtype=np.float32)
    t = np.clip((xa - e0a) / np.maximum(e1a - e0a, 1e-8), 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)


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)
    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)
        acc += float(weight) * cv2.resize(grid, (w, h), interpolation=cv2.INTER_CUBIC)
        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 = 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.024,
    num_dabs: int = 92,
    tooth_weight: float = 0.016,
    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 = 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_stone_field(
    uv_h: int, uv_w: int, span_u: float, span_v: float, cell_size_m: float = 0.42, seed: int = 211
) -> tuple[np.ndarray, np.ndarray]:
    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(-0.38, 0.38, size=(ny, nx)).astype(np.float32)) * cell_size_m
    sy = (gy - 1.0 + 0.5 + rng.uniform(-0.38, 0.38, 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 + 0.03 * fbm_gouache(uv_h, uv_w, octaves=((36, 36, 1.0),), seed=seed + 3)
    vm = (vv / max(uv_h - 1, 1)) * span_v + 0.03 * 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


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 = 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, self.right, self.down = fwd, right, 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]
        self.horizon_y = float(self.project_direction(np.array([0.0, 1.0, 0.0]))[1])

    def project_points(self, pts_world: np.ndarray):
        pts = np.asarray(pts_world, dtype=np.float64)
        single = pts.ndim == 1
        if single:
            pts = pts[None, :]
        pc = (pts - self.eye[None, :]) @ 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 plane_homography(self, p0, e1, e2, 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):
        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 = 4.0,
        fog_density: float = 0.035,
    ):
        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)
        z_cam, dist, hx, hy, hz = self.ray_plane_hit(p0, np.cross(e1_u, e2_u))
        dx, dy, dz = hx - float(p0[0]), hy - float(p0[1]), 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.01) & (u_m <= span_u + 0.01) & (v_m >= -0.01) & (v_m <= span_v + 0.01)).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 = np.clip(1.0 - np.exp(-np.maximum(0.0, dist - fog_start) * fog_density), 0.0, 0.50)[:, :, None]
        rgb = rgb * (1.0 - fog_t) + fog_color[None, None, :] * fog_t
        return rgb, alpha, z_cam


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
    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]
        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:
    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_smooth_closed(self, pts_2d: np.ndarray, rgba: tuple[float, float, float, float], samples: int = 8) -> None:
        curve = eval_catmull_rom(pts_2d, samples_per_seg=samples, closed=True)
        self.fill_poly(curve, rgba)

    def fill_poly_linear(self, pts_2d: np.ndarray, p_start, p_end, stops) -> 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 stroke_straight_poly(
        self, pts_2d: np.ndarray, width_px: float, rgba: tuple[float, float, float, float], closed: bool = False
    ) -> None:
        if len(pts_2d) < 2:
            return
        ctx = self.ctx
        ctx.set_source_rgba(*rgba)
        ctx.set_line_width(float(width_px))
        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))
        if closed:
            ctx.close_path()
        ctx.stroke()

    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 = 4.0,
        taper_ends: float = 0.26,
        tremor: float = 0.22,
        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)
        ph1, ph2 = rng.uniform(0.0, 2.0 * math.pi, size=2)
        wobble = tremor * (0.65 * np.sin(2.0 * math.pi * 3.0 * s + ph1) + 0.35 * np.sin(2.0 * math.pi * 7.0 * s + ph2))
        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.28, 1.0)
        if closed:
            taper = 0.85 + 0.15 * np.sin(2.0 * math.pi * s + ph1)
        else:
            taper = 0.24 + 0.76 * smoothstep(0.0, max(taper_ends, 0.05), s) * (1.0 - smoothstep(1.0 - max(taper_ends, 0.05), 1.0, s))
        half_w = (base_width * persp * taper) * 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):
    th = np.linspace(0.0, 2.0 * 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, 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:
    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 = 40):
    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)
        rings.append(ring)
        left_edge.append(ring[int(np.argmin(ring[:, 0]))])
        right_edge.append(ring[int(np.argmax(ring[:, 0]))])
    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([np.array(left_edge)[::-1], bot_front[1:-1], np.array(right_edge), top_back[::-1][1:-1]])
    return contour, rings


def make_disc_kernel(radius: float = 8.0) -> np.ndarray:
    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.0, chroma_shift_px: float = 1.0) -> np.ndarray:
    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:
    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.70) / 0.30, 0.0, 1.0) ** 1.28
    if specular_glints is not None:
        bright = np.clip(bright + specular_glints * 0.90, 0.0, 1.38)
    hal_tint = np.array([1.00, 0.88, 0.70], dtype=np.float32)
    h_src = bright[:, :, None] * hal_tint[None, None, :]
    halation = (
        0.18 * cv2.GaussianBlur(h_src, (0, 0), 6.5)
        + 0.17 * 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.0008
    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.15 * np.clip(r2 - 0.16, 0.0, 2.0))[:, :, None]

    black_lift = np.array([0.020, 0.017, 0.024], 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.0145 * (0.58 * g_fine + 0.42 * g_clump)[:, :, None] + 0.0040 * 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.0, sigmaY=0.15, borderType=cv2.BORDER_REFLECT_101)
    q_soft = cv2.GaussianBlur(q_ch, (0, 0), sigmaX=1.1, 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.065 * (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.065, 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.006 * (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, crop_w: int = 600, crop_h: int = 450) -> None:
    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)


def project_poly_3d(cam: Camera3D, pts_3d: Sequence[Sequence[float]]) -> tuple[np.ndarray, np.ndarray]:
    u, v, zc = cam.project_points(np.asarray(pts_3d, dtype=np.float64))
    return np.column_stack([u, v]), zc


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)
    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


# ---------------------------------------------------------------------------
# Scene Painting: Cordillera Vilcanota Dusk Basecamp (2048 x 1152)
# ---------------------------------------------------------------------------

def render_scene(width: int = 2048, height: int = 1152):
    cam = Camera3D(
        eye=[0.78, -3.35, 1.32],
        target=[-0.42, 5.40, 1.06],
        up=[0.0, 0.0, 1.0],
        fov_deg=54.0,
        width=width,
        height=height,
    )
    sun_dir = np.array([0.82, 0.28, -0.34], dtype=np.float64)
    sun_dir /= np.linalg.norm(sun_dir)

    tooth = make_paper_tooth(height, width, seed=404)
    hy = cam.horizon_y

    # 1. Sky dome: Andean twilight gradient + cirrus wisps
    yy, xx = np.mgrid[0:height, 0:width].astype(np.float32)
    sky_t = np.clip((hy - yy) / max(hy, 1.0), 0.0, 1.0)
    zenith_c = hex_rgb("#223445")
    mid_c = hex_rgb("#486478")
    warm_band = hex_rgb("#E19D79")
    horiz_c = hex_rgb("#F2DEC7")

    sky = (
        horiz_c[None, None, :] * (1.0 - smoothstep(0.0, 0.28, sky_t))[:, :, None]
        + warm_band[None, None, :] * (smoothstep(0.02, 0.24, sky_t) * (1.0 - smoothstep(0.24, 0.56, sky_t)))[:, :, None]
        + mid_c[None, None, :] * (smoothstep(0.22, 0.58, sky_t) * (1.0 - smoothstep(0.62, 0.96, sky_t)))[:, :, None]
        + zenith_c[None, None, :] * smoothstep(0.55, 0.98, sky_t)[:, :, None]
    )
    sun_glow_r = np.sqrt(((xx - width * 0.16) / (width * 0.42)) ** 2 + ((yy - hy * 0.88) / (height * 0.34)) ** 2)
    sun_glow = np.exp(-sun_glow_r * sun_glow_r * 2.2)[:, :, None]
    sky = np.clip(sky + sun_glow * np.array([0.20, 0.11, 0.04], dtype=np.float32)[None, None, :], 0.0, 1.0)

    cloud_f = fbm_gouache(height, width, octaves=((180.0, 42.0, 0.55), (68.0, 18.0, 0.30), (24.0, 8.0, 0.15)), seed=313)
    cloud_band = smoothstep(0.18, 0.48, sky_t) * (1.0 - smoothstep(0.62, 0.92, sky_t)) * smoothstep(0.35, 1.45, cloud_f)
    cloud_col = hex_rgb("#E8B496") * 0.72 + hex_rgb("#7C8894") * 0.28
    sky = alpha_composite(sky, np.broadcast_to(cloud_col, sky.shape), cloud_band * 0.42)
    sky = paint_isotropic_gouache_dabs(sky, np.clip(sky_t * 1.4, 0.0, 1.0), tooth, dab_strength=0.028, num_dabs=84, seed=501)

    # 2. Cordillera Vilcanota mountain range (smooth multi-scale geological ridgelines, zero pixel jitter)
    xs = np.linspace(0, width - 1, 220)

    def make_ridge(base_y: float, amp: float, peaks_n: int, seed_r: int) -> np.ndarray:
        rr = np.random.default_rng(seed_r)
        ys = np.full_like(xs, base_y, dtype=np.float64)
        for _ in range(peaks_n):
            cx_p = rr.uniform(-0.08 * width, 1.08 * width)
            pw = rr.uniform(0.08 * width, 0.22 * width)
            ph = rr.uniform(0.35 * amp, amp)
            ys -= ph * np.maximum(0.0, 1.0 - np.abs(xs - cx_p) / pw) ** 1.35
        # Smooth multi-frequency ridge undulations (no high-frequency white noise)
        ys += 6.5 * np.sin(xs * 0.017 + seed_r) + 3.2 * np.cos(xs * 0.043 + seed_r * 1.7)
        return np.column_stack([xs, ys])

    far_layer = CairoLayer2x(width, height)
    far_ridge = make_ridge(hy + 12, 238, 8, 17)
    far_poly = np.vstack([far_ridge, [[width, hy + 220], [0, hy + 220]]])
    far_layer.fill_poly_linear(
        far_poly,
        (width * 0.2, hy - 210),
        (width * 0.8, hy + 20),
        [(0.0, (0.76, 0.53, 0.44, 1.0)), (0.45, (0.41, 0.49, 0.56, 1.0)), (1.0, (0.31, 0.38, 0.44, 1.0))],
    )
    for i in range(6, len(far_ridge) - 8, 10):
        if far_ridge[i + 2, 1] < far_ridge[i, 1] - 4.0:
            px, py = far_ridge[i + 2]
            snow = np.array([[px, py], [px - 44, py + 76], [px - 18, py + 82], [px + 10, py + 44]])
            far_layer.fill_poly(snow, (0.94, 0.77, 0.66, 0.72))
    far_rgb, far_a = far_layer.finish()
    far_rgb = paint_isotropic_gouache_dabs(far_rgb, far_a, tooth, dab_strength=0.042, num_dabs=88, seed=602)
    canvas = alpha_composite(sky, far_rgb, far_a)

    # Mid-distant moraine ridge extending deeply past horizon so ground never exposes a sky strip
    mid_layer = CairoLayer2x(width, height)
    mid_ridge = make_ridge(hy + 22, 122, 6, 29)
    mid_poly = np.vstack([mid_ridge, [[width, hy + 240], [0, hy + 240]]])
    mid_layer.fill_poly_linear(
        mid_poly,
        (0, hy - 95),
        (0, hy + 90),
        [(0.0, (0.29, 0.35, 0.40, 1.0)), (0.60, (0.24, 0.27, 0.24, 1.0)), (1.0, (0.21, 0.23, 0.20, 1.0))],
    )
    mid_layer.stroke_catmull_rom(mid_ridge[::6], 8.0, 1.8, (0.10, 0.11, 0.12, 0.55), seed=41, tremor=0.12)
    mid_rgb, mid_a = mid_layer.finish()
    mid_rgb = paint_isotropic_gouache_dabs(mid_rgb, mid_a, tooth, dab_strength=0.046, num_dabs=88, seed=603)
    canvas = alpha_composite(canvas, mid_rgb, mid_a)

    # 3. Ground Plane (Z = 0) covering wide horizon x in [-30, +30] m, y in [-0.5, 80.0] m
    uv_w, uv_h = 1400, 1400
    span_u, span_v = 60.0, 80.5
    p0_g = np.array([-30.0, -0.5, 0.0], dtype=np.float64)
    joint, stone_tone = voronoi_stone_field(uv_h, uv_w, span_u, span_v, cell_size_m=0.45, seed=711)
    vg, ug = np.mgrid[0:uv_h, 0:uv_w].astype(np.float32)
    wx_g = -30.0 + (ug / (uv_w - 1)) * span_u
    wy_g = -0.5 + (vg / (uv_h - 1)) * span_v

    # Braided proglacial meltwater channel winding toward the mountain valley
    stream_cx = -0.45 + 0.55 * np.sin(wy_g * 0.38 + 0.4) + 0.16 * (wy_g - 2.0)
    stream_half_w = 0.64 + 0.16 * np.sin(wy_g * 0.72)
    stream_dist = np.abs(wx_g - stream_cx)
    water_mask_uv = 1.0 - smoothstep(stream_half_w - 0.18, stream_half_w + 0.14, stream_dist)
    dry_pad = np.exp(-(((wx_g - 1.65) / 1.55) ** 2 + ((wy_g - 4.2) / 2.2) ** 2))
    water_mask_uv *= (1.0 - smoothstep(0.25, 0.65, dry_pad))

    turf_fbm = fbm_gouache(uv_h, uv_w, octaves=((52, 52, 0.55), (16, 16, 0.35), (6, 6, 0.10)), seed=812)
    turf_col = hex_rgb("#484E35") * (1.0 + 0.10 * turf_fbm[:, :, None])
    scree_col = hex_rgb("#5A554C") * (0.90 + 0.14 * stone_tone[:, :, None]) * (0.80 + 0.20 * smoothstep(0.010, 0.045, joint))[:, :, None]
    gravel_t = smoothstep(-0.2, 0.8, turf_fbm + 0.9 * (1.0 - smoothstep(0.3, 1.4, stream_dist)))
    ground_uv = turf_col * (1.0 - gravel_t[:, :, None]) + scree_col * gravel_t[:, :, None]

    lantern_pool = np.exp(-(((wx_g - 1.65) / 1.85) ** 2 + ((wy_g - 3.60) / 1.75) ** 2))
    stove_pool = np.exp(-(((wx_g + 1.15) / 0.95) ** 2 + ((wy_g - 2.45) / 0.90) ** 2))
    ground_uv += lantern_pool[:, :, None] * np.array([0.32, 0.22, 0.09], dtype=np.float32)[None, None, :]
    ground_uv += stove_pool[:, :, None] * np.array([0.24, 0.13, 0.05], dtype=np.float32)[None, None, :]

    fog_c = hex_rgb("#505B63")
    g_rgb, g_a, _ = cam.warp_plane_panel(
        np.clip(ground_uv, 0.0, 1.0),
        np.ones((uv_h, uv_w), dtype=np.float32),
        p0=p0_g,
        e1=np.array([1.0, 0.0, 0.0]),
        e2=np.array([0.0, 1.0, 0.0]),
        span_u=span_u,
        span_v=span_v,
        fog_color=fog_c,
        fog_start=7.5,
        fog_density=0.032,
    )
    water_screen, _, _ = cam.warp_plane_panel(
        np.repeat(water_mask_uv[:, :, None], 3, axis=2),
        np.ones((uv_h, uv_w), dtype=np.float32),
        p0=p0_g,
        e1=np.array([1.0, 0.0, 0.0]),
        e2=np.array([0.0, 1.0, 0.0]),
        span_u=span_u,
        span_v=span_v,
        fog_color=np.zeros(3, dtype=np.float32),
        fog_start=100.0,
        fog_density=0.0,
    )
    w_mask = np.clip(water_screen[:, :, 0] * g_a, 0.0, 1.0)
    g_rgb = paint_isotropic_gouache_dabs(g_rgb, g_a * (1.0 - w_mask * 0.7), tooth, dab_strength=0.050, num_dabs=96, seed=777)
    canvas = alpha_composite(canvas, g_rgb, g_a)

    # 4. Fresnel meltwater reflection
    y_src = np.clip(np.round(2.0 * hy - yy).astype(np.int32), 0, height - 1)
    rip = 3.0 * np.sin(yy * 0.24 + xx * 0.025) + 2.0 * np.sin(yy * 0.59 - xx * 0.041 + 1.4) + 1.2 * np.cos(yy * 1.12 + xx * 0.017)
    x_src = np.clip(np.round(xx + rip).astype(np.int32), 0, width - 1)
    refl_sky = canvas[y_src, x_src]
    dist_t = np.clip((yy - hy) / max(1.0, height - hy), 0.0, 1.0)
    fresnel = 0.26 + (0.88 - 0.26) * ((1.0 - dist_t) ** 1.4)
    water_base = hex_rgb("#1E282E") * 0.62 + refl_sky * 0.38
    water_col = water_base * (1.0 - fresnel[:, :, None]) + refl_sky * fresnel[:, :, None]
    wet_rim = smoothstep(0.08, 0.45, w_mask) * (1.0 - smoothstep(0.50, 0.92, w_mask))
    canvas = canvas * (1.0 - 0.28 * wet_rim[:, :, None])
    canvas = alpha_composite(canvas, np.clip(water_col, 0.0, 1.0), w_mask * 0.92)

    # 5. Unified SUN_DIR shadows on ground
    sh_layer = CairoLayer2x(width, height)
    tent_sh = shadow_xy_on_plane(np.array([[0.76, 2.95, 0.0], [2.80, 3.08, 0.0], [2.80, 5.18, 1.55], [0.76, 5.10, 1.55]]), sun_dir, 0.0)
    sh_pts, _ = project_poly_3d(cam, tent_sh)
    sh_layer.fill_poly(sh_pts, (0.07, 0.07, 0.09, 0.44))
    case_sh = shadow_xy_on_plane(np.array([[-1.85, 2.15, 0.34], [-1.25, 2.15, 0.34], [-1.25, 2.58, 0.0], [-1.85, 2.58, 0.0]]), sun_dir, 0.0)
    c_sh_2d, _ = project_poly_3d(cam, case_sh)
    sh_layer.fill_poly(c_sh_2d, (0.07, 0.07, 0.09, 0.38))
    sh_rgb, sh_a = sh_layer.finish()
    sh_a = cv2.GaussianBlur(sh_a, (0, 0), 5.5)
    canvas = alpha_composite(canvas, sh_rgb, sh_a)

    # 6. Central Command Workstation Tent (sealed canvas interior + groundsheet + warm lantern + table)
    tent_layer = CairoLayer2x(width, height)
    # Interior enclosure: dark warm floor sheet, left/right inner canvas walls, and back canvas wall
    in_floor, _ = project_poly_3d(cam, [[0.78, 2.96, 0.0], [2.78, 3.08, 0.0], [2.78, 5.12, 0.0], [0.78, 5.08, 0.0]])
    in_left, _ = project_poly_3d(cam, [[0.78, 2.96, 0.0], [0.78, 2.96, 0.90], [1.78, 2.96, 1.66], [1.78, 5.10, 1.66], [0.78, 5.08, 0.90], [0.78, 5.08, 0.0]])
    in_right, _ = project_poly_3d(cam, [[2.78, 3.08, 0.0], [2.78, 3.08, 0.90], [1.78, 2.96, 1.66], [1.78, 5.10, 1.66], [2.78, 5.14, 0.90], [2.78, 5.14, 0.0]])
    in_back, _ = project_poly_3d(cam, [[0.78, 5.08, 0.0], [0.78, 5.08, 0.90], [1.78, 5.10, 1.66], [2.78, 5.14, 0.90], [2.78, 5.14, 0.0]])

    tent_layer.fill_poly(in_floor, (0.20, 0.16, 0.12, 1.0))
    tent_layer.fill_poly(in_left, (0.58, 0.42, 0.25, 1.0))
    tent_layer.fill_poly(in_right, (0.44, 0.31, 0.19, 1.0))
    tent_layer.fill_poly_linear(
        in_back,
        (float(np.mean(in_back[:, 0])), float(np.min(in_back[:, 1]))),
        (float(np.mean(in_back[:, 0])), float(np.max(in_back[:, 1]))),
        [(0.0, (0.98, 0.85, 0.54, 1.0)), (0.48, (0.84, 0.59, 0.32, 1.0)), (1.0, (0.38, 0.25, 0.15, 1.0))],
    )

    # Interior folding camp table + instruments
    tbl_top, _ = project_poly_3d(cam, [[1.22, 3.55, 0.68], [2.28, 3.55, 0.68], [2.28, 4.35, 0.68], [1.22, 4.35, 0.68]])
    tbl_front, _ = project_poly_3d(cam, [[1.22, 3.55, 0.68], [2.28, 3.55, 0.68], [2.28, 3.55, 0.63], [1.22, 3.55, 0.63]])
    tent_layer.fill_poly(tbl_top, (0.78, 0.61, 0.41, 1.0))
    tent_layer.fill_poly(tbl_front, (0.42, 0.29, 0.18, 1.0))
    for lx, ly in ((1.26, 3.59), (2.24, 3.59), (1.26, 4.30), (2.24, 4.30)):
        leg_2d, _ = project_poly_3d(cam, [[lx, ly, 0.64], [lx, ly, 0.0]])
        tent_layer.stroke_straight_poly(leg_2d, 3.2, (0.18, 0.13, 0.10, 1.0))

    # Rugged workstation laptop + telemetry graph lines + specimen cores + open notebook
    lap_base, _ = project_poly_3d(cam, [[1.38, 3.74, 0.69], [1.72, 3.74, 0.69], [1.72, 3.96, 0.69], [1.38, 3.96, 0.69]])
    lap_lid, _ = project_poly_3d(cam, [[1.38, 3.96, 0.69], [1.72, 3.96, 0.69], [1.72, 4.02, 0.91], [1.38, 4.02, 0.91]])
    lap_scr, _ = project_poly_3d(cam, [[1.40, 3.95, 0.71], [1.70, 3.95, 0.71], [1.70, 4.00, 0.89], [1.40, 4.00, 0.89]])
    tent_layer.fill_poly(lap_base, (0.13, 0.14, 0.15, 1.0))
    tent_layer.fill_poly(lap_lid, (0.11, 0.12, 0.14, 1.0))
    tent_layer.fill_poly(lap_scr, (0.76, 0.92, 0.96, 1.0))
    # Tiny telemetry trace on screen
    trace_pts, _ = project_poly_3d(cam, [[1.43, 3.94, 0.78], [1.49, 3.94, 0.82], [1.56, 3.94, 0.76], [1.62, 3.94, 0.85], [1.67, 3.94, 0.80]])
    tent_layer.stroke_straight_poly(trace_pts, 1.8, (0.73, 0.32, 0.22, 0.92))

    # Specimen tray with three rock cores + open cream field notebook + brass compass
    tray_2d, _ = project_poly_3d(cam, [[1.80, 3.68, 0.69], [2.16, 3.68, 0.69], [2.16, 3.94, 0.69], [1.80, 3.94, 0.69]])
    tent_layer.fill_poly(tray_2d, (0.64, 0.34, 0.25, 1.0))
    for rx in (1.87, 1.97, 2.07):
        rock_2d, _ = project_poly_3d(cam, [[rx - 0.03, 3.74, 0.70], [rx + 0.03, 3.74, 0.70], [rx + 0.02, 3.86, 0.73], [rx - 0.02, 3.86, 0.73]])
        tent_layer.fill_poly(rock_2d, (0.34, 0.35, 0.38, 1.0))
    book_2d, _ = project_poly_3d(cam, [[1.84, 3.99, 0.695], [2.12, 3.99, 0.695], [2.12, 4.20, 0.695], [1.84, 4.20, 0.695]])
    tent_layer.fill_poly(book_2d, (0.97, 0.95, 0.90, 1.0))

    # Hanging lantern with brass cap & warm core
    lan_p, _ = project_poly_3d(cam, [[1.78, 3.85, 1.64], [1.78, 3.85, 1.38]])
    tent_layer.stroke_straight_poly(lan_p, 2.0, (0.14, 0.11, 0.09, 1.0))
    lan_cap, _ = project_poly_3d(cam, [[1.72, 3.85, 1.38], [1.84, 3.85, 1.38], [1.82, 3.85, 1.35], [1.74, 3.85, 1.35]])
    lan_glow, _ = project_poly_3d(cam, [[1.74, 3.85, 1.35], [1.82, 3.85, 1.35], [1.82, 3.85, 1.24], [1.74, 3.85, 1.24]])
    tent_layer.fill_poly(lan_cap, (0.20, 0.16, 0.12, 1.0))
    tent_layer.fill_poly(lan_glow, (1.0, 0.96, 0.78, 1.0))

    # Solid exterior tent shell panels (left wall, left roof, right roof) + doorway trim flaps
    lw_2d, _ = project_poly_3d(cam, [[0.76, 2.95, 0.0], [0.76, 2.95, 0.90], [0.76, 5.10, 0.90], [0.76, 5.10, 0.0]])
    lr_2d, _ = project_poly_3d(cam, [[0.76, 2.95, 0.90], [1.78, 2.95, 1.68], [1.78, 5.10, 1.68], [0.76, 5.10, 0.90]])
    rr_2d, _ = project_poly_3d(cam, [[1.78, 2.95, 1.68], [2.80, 3.08, 0.90], [2.80, 5.18, 0.90], [1.78, 5.10, 1.68]])
    rw_2d, _ = project_poly_3d(cam, [[2.80, 3.08, 0.0], [2.80, 3.08, 0.90], [2.80, 5.18, 0.90], [2.80, 5.18, 0.0]])
    tent_layer.fill_poly(lw_2d, (0.76, 0.72, 0.62, 1.0))
    tent_layer.fill_poly_linear(
        lr_2d,
        (float(lr_2d[0, 0]), float(lr_2d[1, 1])),
        (float(lr_2d[0, 0]), float(lr_2d[0, 1])),
        [(0.0, (0.91, 0.85, 0.74, 1.0)), (1.0, (0.80, 0.74, 0.62, 1.0))],
    )
    tent_layer.fill_poly(rr_2d, (0.58, 0.56, 0.50, 1.0))
    tent_layer.fill_poly(rw_2d, (0.48, 0.46, 0.42, 1.0))

    flap_l, _ = project_poly_3d(cam, [[0.76, 2.95, 0.0], [0.76, 2.95, 0.90], [1.78, 2.95, 1.68], [1.14, 2.95, 0.85], [0.98, 2.95, 0.0]])
    flap_r, _ = project_poly_3d(cam, [[2.80, 3.08, 0.0], [2.80, 3.08, 0.90], [1.78, 2.95, 1.68], [2.46, 3.04, 0.88], [2.58, 3.05, 0.0]])
    tent_layer.fill_poly(flap_l, (0.72, 0.42, 0.31, 0.98))
    tent_layer.fill_poly(flap_r, (0.64, 0.37, 0.28, 0.98))

    for seg_3d in (
        [[0.76, 2.95, 0.90], [1.78, 2.95, 1.68], [2.80, 3.08, 0.90]],
        [[1.78, 2.95, 1.68], [1.78, 5.10, 1.68]],
        [[0.76, 2.95, 0.0], [0.76, 2.95, 0.90], [0.76, 5.10, 0.90]],
        [[0.76, 2.95, 0.90], [0.18, 2.65, 0.0]],
        [[0.76, 4.10, 0.90], [0.22, 4.05, 0.0]],
    ):
        p2, _ = project_poly_3d(cam, seg_3d)
        tent_layer.stroke_straight_poly(p2, 2.2, (0.14, 0.11, 0.09, 0.86))

    tent_rgb, tent_a = tent_layer.finish()
    tent_rgb = paint_isotropic_gouache_dabs(tent_rgb, tent_a, tooth, dab_strength=0.044, num_dabs=90, seed=910)
    canvas = alpha_composite(canvas, tent_rgb, tent_a)

    # 7. Starlink Phased-Array Dish on Tripod beside Tent (crisp straight structural ink)
    dish_layer = CairoLayer2x(width, height)
    tripod_top = np.array([0.38, 2.65, 0.72])
    for lx, ly in ((0.18, 2.48), (0.55, 2.45), (0.38, 2.92)):
        leg2, _ = project_poly_3d(cam, [tripod_top, [lx, ly, 0.0]])
        dish_layer.stroke_straight_poly(leg2, 3.4, (0.14, 0.14, 0.15, 1.0))
    mast2, _ = project_poly_3d(cam, [tripod_top, [0.38, 2.65, 0.88]])
    dish_layer.stroke_straight_poly(mast2, 4.0, (0.18, 0.18, 0.20, 1.0))

    dish_pts = np.array([[0.14, 2.52, 0.86], [0.62, 2.52, 0.86], [0.62, 2.82, 1.08], [0.14, 2.82, 1.08]])
    d2d, _ = project_poly_3d(cam, dish_pts)
    dish_layer.fill_poly_linear(
        d2d,
        (float(d2d[2, 0]), float(d2d[2, 1])),
        (float(d2d[0, 0]), float(d2d[0, 1])),
        [(0.0, (0.95, 0.94, 0.90, 1.0)), (1.0, (0.76, 0.78, 0.80, 1.0))],
    )
    dish_layer.stroke_straight_poly(d2d, 2.2, (0.14, 0.13, 0.12, 0.88), closed=True)
    cable2, cablez = project_poly_3d(cam, [[0.38, 2.65, 0.70], [0.46, 2.75, 0.04], [0.85, 2.98, 0.02], [1.22, 3.55, 0.05]])
    dish_layer.stroke_catmull_rom(cable2, cablez, 2.2, (0.12, 0.11, 0.11, 0.90), seed=26)
    d_rgb, d_a = dish_layer.finish()
    canvas = alpha_composite(canvas, d_rgb, d_a)

    # 8. Left-Midground: Pelican Case (straight lines + latches), River-Cobble Hearth, Smooth-Lathed Pot & Mugs, & Two Seated/Crouching Explorers
    props_layer = CairoLayer2x(width, height)

    # Pelican case with crisp straight edges and dark latches
    p_top, _ = project_poly_3d(cam, [[-1.85, 2.15, 0.34], [-1.25, 2.15, 0.34], [-1.25, 2.58, 0.34], [-1.85, 2.58, 0.34]])
    p_front, _ = project_poly_3d(cam, [[-1.85, 2.15, 0.34], [-1.25, 2.15, 0.34], [-1.25, 2.15, 0.0], [-1.85, 2.15, 0.0]])
    p_side, _ = project_poly_3d(cam, [[-1.25, 2.15, 0.34], [-1.25, 2.58, 0.34], [-1.25, 2.58, 0.0], [-1.25, 2.15, 0.0]])
    props_layer.fill_poly(p_top, (0.78, 0.44, 0.32, 1.0))
    props_layer.fill_poly(p_front, (0.64, 0.33, 0.24, 1.0))
    props_layer.fill_poly(p_side, (0.48, 0.25, 0.19, 1.0))
    props_layer.stroke_straight_poly(p_top, 1.8, (0.14, 0.10, 0.08, 0.85), closed=True)
    props_layer.stroke_straight_poly(p_front, 1.8, (0.14, 0.10, 0.08, 0.85), closed=True)
    props_layer.stroke_straight_poly(p_side, 1.6, (0.14, 0.10, 0.08, 0.85), closed=True)
    for lx in (-1.70, -1.40):
        latch, _ = project_poly_3d(cam, [[lx - 0.03, 2.14, 0.31], [lx + 0.03, 2.14, 0.31], [lx + 0.03, 2.14, 0.24], [lx - 0.03, 2.14, 0.24]])
        props_layer.fill_poly(latch, (0.16, 0.15, 0.15, 1.0))

    # Rounded natural moraine stone slab & hearth stones (smoothed Catmull-Rom boulder contours)
    slab_raw, _ = project_poly_3d(cam, [[-1.16, 2.16, 0.22], [-0.82, 2.12, 0.22], [-0.50, 2.18, 0.22], [-0.48, 2.48, 0.22], [-0.75, 2.60, 0.22], [-1.14, 2.54, 0.22]])
    slab_side_raw, _ = project_poly_3d(cam, [[-1.18, 2.14, 0.21], [-0.82, 2.10, 0.21], [-0.49, 2.16, 0.21], [-0.46, 2.12, 0.0], [-0.82, 2.02, 0.0], [-1.21, 2.08, 0.0]])
    props_layer.fill_smooth_closed(slab_side_raw, (0.24, 0.24, 0.23, 1.0))
    props_layer.fill_smooth_closed(slab_raw, (0.39, 0.38, 0.36, 1.0))

    # Smooth-lathed stainless camp pot + handle + two smooth-lathed enamel mugs
    pot_c, pot_rings = build_smooth_lathe_silhouette(cam, np.array([-0.96, 2.34, 0.22]), [(0.085, 0.22), (0.095, 0.25), (0.096, 0.37), (0.102, 0.385)])
    props_layer.fill_poly_linear(
        pot_c,
        (float(np.min(pot_c[:, 0])), float(np.mean(pot_c[:, 1]))),
        (float(np.max(pot_c[:, 0])), float(np.mean(pot_c[:, 1]))),
        [(0.0, (0.76, 0.74, 0.70, 1.0)), (0.5, (0.52, 0.51, 0.50, 1.0)), (1.0, (0.30, 0.30, 0.32, 1.0))],
    )
    props_layer.stroke_catmull_rom(extract_front_or_back_arc(pot_rings[-1], want_front=True), 3.0, 1.8, (0.14, 0.12, 0.11, 0.9), seed=41)

    for m_pos, m_col, m_seed in (
        (np.array([-0.71, 2.28, 0.22]), (0.73, 0.39, 0.28, 1.0), 42),
        (np.array([-0.59, 2.40, 0.22]), (0.24, 0.35, 0.42, 1.0), 43),
    ):
        mc, mrings = build_smooth_lathe_silhouette(cam, m_pos, [(0.040, 0.22), (0.044, 0.23), (0.044, 0.305), (0.047, 0.312)])
        props_layer.fill_poly(mc, m_col)
        props_layer.stroke_catmull_rom(extract_front_or_back_arc(mrings[-1], want_front=True), 2.8, 1.8, (0.97, 0.96, 0.92, 0.92), seed=m_seed)
        props_layer.stroke_catmull_rom(extract_front_or_back_arc(mrings[0], want_front=True), 2.8, 1.4, (0.12, 0.10, 0.09, 0.75), seed=m_seed + 10)

    # Geological rock hammer resting on ground cloth beside Pelican case (x=-1.18, y=1.88)
    ham_h, _ = project_poly_3d(cam, [[-1.34, 1.88, 0.02], [-1.06, 1.98, 0.02]])
    ham_head, _ = project_poly_3d(cam, [[-1.08, 1.94, 0.03], [-1.02, 2.04, 0.03]])
    props_layer.stroke_straight_poly(ham_h, 4.0, (0.52, 0.34, 0.20, 1.0))
    props_layer.stroke_straight_poly(ham_head, 6.0, (0.26, 0.27, 0.29, 1.0))

    # Smooth Catmull-Rom explorer silhouettes seated warmly beside tent entrance (organic curves, never jagged polygons)
    au, av, _ = cam.project_points(np.array([0.82, 2.82, 0.0]))
    fs = height / 1152.0
    adult_parka = np.array([
        [au - 36 * fs, av - 2 * fs],
        [au - 40 * fs, av - 56 * fs],
        [au - 24 * fs, av - 110 * fs],
        [au + 8 * fs, av - 114 * fs],
        [au + 28 * fs, av - 68 * fs],
        [au + 32 * fs, av - 14 * fs],
        [au + 10 * fs, av + 4 * fs],
    ])
    props_layer.fill_smooth_closed(adult_parka, (0.20, 0.26, 0.32, 1.0))
    adult_head = np.array([
        [au - 14 * fs, av - 114 * fs],
        [au - 16 * fs, av - 138 * fs],
        [au - 2 * fs, av - 148 * fs],
        [au + 14 * fs, av - 138 * fs],
        [au + 13 * fs, av - 114 * fs],
    ])
    props_layer.fill_smooth_closed(adult_head, (0.86, 0.70, 0.58, 1.0))
    adult_hair = np.array([
        [au - 17 * fs, av - 128 * fs],
        [au - 17 * fs, av - 146 * fs],
        [au + 2 * fs, av - 151 * fs],
        [au + 15 * fs, av - 142 * fs],
        [au + 6 * fs, av - 135 * fs],
    ])
    props_layer.fill_smooth_closed(adult_hair, (0.14, 0.12, 0.11, 1.0))

    cu, cv, _ = cam.project_points(np.array([1.14, 2.75, 0.0]))
    child_coat = np.array([
        [cu - 24 * fs, cv - 2 * fs],
        [cu - 26 * fs, cv - 42 * fs],
        [cu - 14 * fs, cv - 78 * fs],
        [cu + 10 * fs, cv - 80 * fs],
        [cu + 24 * fs, cv - 44 * fs],
        [cu + 22 * fs, cv + 2 * fs],
    ])
    props_layer.fill_smooth_closed(child_coat, (0.45, 0.43, 0.37, 1.0))
    child_face = np.array([
        [cu - 11 * fs, cv - 79 * fs],
        [cu - 12 * fs, cv - 98 * fs],
        [cu + 10 * fs, cv - 98 * fs],
        [cu + 10 * fs, cv - 79 * fs],
    ])
    props_layer.fill_smooth_closed(child_face, (0.87, 0.72, 0.60, 1.0))
    child_beanie = np.array([
        [cu - 14 * fs, cv - 94 * fs],
        [cu - 11 * fs, cv - 113 * fs],
        [cu + 11 * fs, cv - 112 * fs],
        [cu + 13 * fs, cv - 94 * fs],
    ])
    props_layer.fill_smooth_closed(child_beanie, (0.73, 0.39, 0.28, 1.0))

    # Gossamer steam wisps rising from camp pot & mugs
    for sx_off, s_seed in ((-0.96, 71), (-0.71, 72)):
        wisp_3d = [[sx_off, 2.34, 0.39], [sx_off - 0.03, 2.34, 0.49], [sx_off + 0.02, 2.34, 0.59], [sx_off - 0.02, 2.34, 0.69]]
        w2, wz = project_poly_3d(cam, wisp_3d)
        props_layer.stroke_catmull_rom(w2, wz, 3.6, (0.98, 0.96, 0.92, 0.38), seed=s_seed)

    p_rgb, p_a = props_layer.finish()
    p_rgb = paint_isotropic_gouache_dabs(p_rgb, p_a, tooth, dab_strength=0.042, num_dabs=86, seed=940)
    canvas = alpha_composite(canvas, p_rgb, p_a)

    # 9. Lantern + Laptop Specular Glints
    glint = np.zeros((height, width), dtype=np.float32)
    lu, lv, _ = cam.project_points(np.array([1.78, 3.85, 1.30]))
    glint += np.exp(-(((xx - lu) ** 2 + (yy - lv) ** 2) / (2.0 * 32.0 ** 2))) * 0.95
    su, sv, _ = cam.project_points(np.array([1.55, 3.97, 0.80]))
    glint += np.exp(-(((xx - su) ** 2 + (yy - sv) ** 2) / (2.0 * 18.0 ** 2))) * 0.55

    # 10. Foreground Disc Bokeh: out-of-focus wind-bent ichu grass tufts framing corners
    fg_layer = CairoLayer2x(width, height)
    fg_rng = np.random.default_rng(1999)
    for base_x, count, side_dir in ((0.05 * width, 11, 1.0), (0.95 * width, 9, -1.0)):
        for idx in range(count):
            bx = base_x + fg_rng.uniform(-75, 75)
            by = height + 12
            tip_x = bx + side_dir * fg_rng.uniform(45, 155)
            tip_y = height - fg_rng.uniform(110, 275)
            mid_x = 0.5 * (bx + tip_x) + side_dir * fg_rng.uniform(12, 42)
            mid_y = 0.5 * (by + tip_y)
            pts = np.array([[bx, by], [mid_x, mid_y], [tip_x, tip_y]])
            col = (0.18, 0.16, 0.11, 0.92) if idx % 2 == 0 else (0.28, 0.23, 0.14, 0.88)
            fg_layer.stroke_catmull_rom(pts, 0.5, fg_rng.uniform(5.5, 10.0), col, seed=800 + idx + int(base_x))
    fg_rgb, fg_a = fg_layer.finish()
    canvas = apply_foreground_disc_bokeh(canvas, fg_rgb, fg_a, radius=8.0, chroma_shift_px=1.0)

    # 11. 35mm Cinema Optics Finish
    final = finish_35mm_optics(canvas, specular_glints=glint, seed=1994)

    c1 = cam.project_points(np.array([0.38, 2.65, 1.05]))[:2]
    c2 = cam.project_points(np.array([1.72, 3.85, 0.88]))[:2]
    c3 = cam.project_points(np.array([-0.82, 2.34, 0.24]))[:2]
    crops = [
        ("crop1-peaks-starlink.png", (float(c1[0]), float(c1[1]) - 90.0)),
        ("crop2-command-tent.png", (float(c2[0]), float(c2[1]))),
        ("crop3-camp-mugs-water.png", (float(c3[0]), float(c3[1]) + 25.0)),
    ]
    return final, crops


def main() -> None:
    parser = argparse.ArgumentParser(description="Paint high-Andean dusk basecamp still in pure Python.")
    parser.add_argument("--out", required=True, type=Path, help="Output WebP or PNG path.")
    parser.add_argument("--crops-dir", type=Path, default=None, help="Optional directory for 600x450 1:1 audit crops.")
    args = parser.parse_args()

    final, crops = render_scene(2048, 1152)
    save_image(final, args.out)
    if args.crops_dir is not None:
        save_crop_boxes(final, args.crops_dir, crops)
    print(f"Saved {args.out} (2048x1152)")


if __name__ == "__main__":
    main()
