# -*- coding: utf-8 -*-
"""
暮光岩馆 —— 实机演示视频原型渲染器
动画方案（与游戏内实现一致，可直接移植到 Unity/Godot）：
  1. 接触点驱动：NPC 的动作只描述“哪只手/脚去哪个岩点”，四肢用两段式 IK 求解肘/膝。
  2. 重心求解：髋部位置由已接触的手脚自动约束求解（臂长/腿长约束松弛迭代），保证不穿帮。
  3. 平滑：关键帧之间用 Hermite 样条（速度连续）；肢体移动带弧线；落下用抛物线；
     动态（dyno）前有下沉预备，接住后双脚做阻尼摆荡；待机有呼吸，新手有颤抖。
  4. 像素：背景按 384x216 逻辑像素绘制，角色在 3 倍子像素画布绘制，运动不抖动。
"""
import math, random, subprocess, sys, os
from PIL import Image, ImageDraw, ImageFont
import imageio_ffmpeg

W, H = 384, 216          # 逻辑分辨率
K = 3                    # 世界画布倍率
CW, CH = W * K, H * K
OW, OH = 1920, 1080
UW, UH = 960, 540        # UI 层
FPS = 30
DUR = 78.0
TR = 58.5   # 回放开始（运行时重算）
TS = 68.0   # 结算开始（运行时重算）

def hx(s): return tuple(int(s[i:i+2], 16) for i in (1, 3, 5))
PAL = dict(sky=hx('#c23a34'), sky2=hx('#7a2440'), sun=hx('#fd812b'), frame=hx('#261030'),
           city=hx('#2f1738'), teal=hx('#446b77'), mid=hx('#3b5274'), light=hx('#53688e'),
           walltop=hx('#6a80a6'), hold=hx('#ed8724'), holdsh=hx('#9a4a22'), cream=hx('#f1deba'),
           pants=hx('#ea8c31'), red=hx('#c23a34'), floor=hx('#271130'), floorline=hx('#3d1f47'),
           mat=hx('#43284f'), mattop=hx('#5a3868'), desk=hx('#e17b26'), pole=hx('#426978'),
           dark=hx('#261030'), dog=hx('#e0822e'))

FONT_PX = 'C:/Windows/Fonts/simsun.ttc'
FONT_B = 'C:/Windows/Fonts/msyhbd.ttc'
def F(sz, bold=False): return ImageFont.truetype(FONT_B if bold else FONT_PX, sz)
F12, F16, F24, F32 = F(12), F(16), F(24), F(32)
FB20, FB28, FB40 = F(20, True), F(28, True), F(40, True)

# ------------------------------------------------------------------ 工具
def lerp(a, b, u): return a + (b - a) * u
def lerp2(a, b, u): return (lerp(a[0], b[0], u), lerp(a[1], b[1], u))
def lerpc(a, b, u): return tuple(int(round(lerp(a[i], b[i], u))) for i in range(3))
def clamp(x, a, b): return max(a, min(b, x))
def smooth(u): u = clamp(u, 0, 1); return u * u * (3 - 2 * u)
def eio(u): u = clamp(u, 0, 1); return 4*u*u*u if u < .5 else 1 - (-2*u + 2)**3 / 2
def eout(u): u = clamp(u, 0, 1); return 1 - (1 - u)**3
def ein(u): u = clamp(u, 0, 1); return u * u * u
def eback(u):
    u = clamp(u, 0, 1); c1 = 1.70158; c3 = c1 + 1
    return 1 + c3 * (u - 1)**3 + c1 * (u - 1)**2
def dist(a, b): return math.hypot(a[0]-b[0], a[1]-b[1])
def add(a, b): return (a[0]+b[0], a[1]+b[1])
def sub(a, b): return (a[0]-b[0], a[1]-b[1])
def mul(a, s): return (a[0]*s, a[1]*s)
def norm(a):
    d = math.hypot(*a)
    return (a[0]/d, a[1]/d) if d > 1e-6 else (0.0, -1.0)
def rot(v, ang):
    c, s = math.cos(ang), math.sin(ang)
    return (v[0]*c - v[1]*s, v[0]*s + v[1]*c)
def noise1(t, seed=0):
    # 平滑噪声：几组正弦叠加
    return (math.sin(t*7.3+seed*1.7)*.5 + math.sin(t*11.9+seed*3.1)*.3 + math.sin(t*17.1+seed*5.3)*.2)

# ------------------------------------------------------------------ 岩点
class Hold:
    def __init__(self, name, x, y, kind, w=10, t_on=-1.0):
        self.name, self.x, self.y, self.kind, self.w, self.t_on = name, x, y, kind, w, t_on
    def hand(self, dx=0):
        if self.kind == 'volume': return (self.x + dx, self.y - 1)
        if self.kind == 'sloper': return (self.x + dx, self.y - 3)
        return (self.x + dx, self.y - 1.5)
    def foot(self, dx=0):
        hx_, hy = self.hand(dx)
        return (hx_, hy - 1.5)

# 路线岩点（玩家在设计阶段放置）
ROUTE = {}
def R(name, x, y, kind, w=10, t=-1): ROUTE[name] = Hold(name, x, y, kind, w, t)
R('S', 171, 150, 'jug', 13, 4.2)      # 起步大把手
R('f1', 165, 176, 'chip', 4, 5.3)
R('f2', 181, 176, 'chip', 4, 5.6)
R('L', 158, 136, 'sloper', 9, 6.6)    # 斜面点（新手陷阱）
R('V', 0, 0, 'volume', 0, 7.9)        # 三角块（特殊绘制）
R('J2', 192, 127, 'jug', 10, 9.0)
R('f3', 163, 163, 'chip', 4, 9.7)
R('f4', 185, 137, 'chip', 4, 10.2)
R('Cr', 178, 112, 'crimp', 6, 10.9)
R('T', 205, 99, 'jug', 15, 11.8)      # 终点
VOL = [(184, 152), (202, 152), (202, 135)]   # 三角块（直角在右下）
def vol_y(x): return 152 - (x - 184) / 18 * 17
DECOR = [Hold('d1', 72, 160, 'round', 5), Hold('d2', 80, 160, 'round', 5), Hold('d3', 118, 140, 'jug', 10),
         Hold('d4', 104, 112, 'sloper', 8), Hold('d5', 300, 104, 'crimp', 8), Hold('d6', 336, 130, 'jug', 18),
         Hold('d7', 352, 160, 'sloper', 9), Hold('d8', 270, 150, 'crimp', 6), Hold('d9', 244, 116, 'round', 6)]

# ------------------------------------------------------------------ 角色与动画时间线
UA, FA, TOR, TH, SH = 9.0, 8.5, 12.0, 9.5, 9.0
LIMBS = ('lh', 'rh', 'lf', 'rf')

class Look:
    def __init__(self, name, s=1.0, tw=5, pants=None, shirt=None, band=False, hair=True, cap=False):
        self.name, self.s, self.tw = name, s, tw
        self.pants = pants or PAL['pants']; self.shirt = shirt or PAL['cream']
        self.band, self.hair, self.cap = band, hair, cap

def hip_y(s): return 182.0 - (TH + SH) * s * 0.93
def stand_state(x, facing=1, s=1.0):
    hy = hip_y(s)
    return dict(hip=(x, hy), lh=(x-4, hy-1.5), rh=(x+4, hy-1.5), lf=(x-3, 182.0), rf=(x+3, 182.0),
                att=dict(lh=False, rh=False, lf=True, rf=True), shake=0.0, kd=None, ed=None,
                face=facing, breathe=1.0, lean=None)

class Timeline:
    """关键帧时间线。每个关键帧是完整姿态；采样时髋部与自由肢体用 Hermite 样条，
    抓握/踩点的肢体用缓入缓出 + 抬起弧线。"""
    def __init__(self, actor, t0, state):
        self.actor = actor
        self.t = t0
        self.keys = [(t0, dict(state), 'io')]
        self.cur = dict(state)
        self.labels = []   # (t, 动作名)

    def to(self, dur, ease='io', auto=True, hip_bias=(0, 0), **ch):
        st = dict(self.cur)
        st['att'] = dict(self.cur['att'])
        for k, v in ch.items():
            if k in LIMBS:
                if isinstance(v, tuple) and len(v) == 3 and v[2] == 'free':
                    st[k] = (v[0], v[1]); st['att'][k] = False
                elif v is None:
                    st['att'][k] = False
                else:
                    st[k] = v; st['att'][k] = True
            else:
                st[k] = v
        if auto and 'hip' not in ch:
            st['hip'] = solve_hip(st, self.actor.look, hip_bias)
        st['hip'] = fix_hip(st, self.actor.look)
        self.t += dur
        self.keys.append((self.t, st, ease))
        self.cur = st
        return self

    def wait(self, dur):
        st = dict(self.cur); st['att'] = dict(self.cur['att'])
        self.t += dur; self.keys.append((self.t, st, 'io')); self.cur = st
        return self

    def label(self, text): self.labels.append((self.t, text)); return self
    def ev(self, kind, dt=0.0, **kw):
        EVENTS.append(dict(t=self.t + dt, kind=kind, actor=self.actor, **kw)); return self

    # ---- 复合动作
    def walk(self, x1, speed=34.0, end_stand=True):
        x0 = self.cur['hip'][0]
        hy = hip_y(self.actor.look.s)
        d = 1 if x1 > x0 else -1
        n = max(2, int(round(abs(x1 - x0) / 6.0)))
        step = (x1 - x0) / n
        dt = abs(step) / speed
        for i in range(n):
            x = x0 + step * (i + 1)
            lead = 'lf' if i % 2 == 0 else 'rf'
            other = 'rf' if lead == 'lf' else 'lf'
            ch = {lead: (x + d * 3.5, 182.0), other: self.cur[other]}
            sw = 3.0 if i % 2 == 0 else -3.0
            ch['lh'] = (x - 3 + sw * d * .6, hy - 1.5, 'free')
            ch['rh'] = (x + 3 - sw * d * .6, hy - 1.5, 'free')
            ch['hip'] = (x + d * 1.0, hy - 0.6 if i % 2 else hy + 0.3)
            ch['kd'] = {'lf': (d, -.3), 'rf': (d, -.3)}
            self.to(dt, 'lin', **ch)
        if end_stand:
            self.to(0.25, 'io', hip=(x1, hy), lf=(x1 - 3, 182.0), rf=(x1 + 3, 182.0),
                    lh=(x1 - 4, hy - 1.5, 'free'), rh=(x1 + 4, hy - 1.5, 'free'), kd=None)
        return self

    def fall(self, land_hip, land, g=330.0, flail=True, ease='lin'):
        """抛物线下落：髋部按重力积分，四肢甩开，着地后下蹲缓冲。"""
        h0 = self.cur['hip']
        dy = land_hip[1] - h0[1]
        T = math.sqrt(max(2 * dy / g, 0.04))
        n = 7
        for i in range(1, n + 1):
            u = i / n
            tt = T * u
            y = h0[1] + 0.5 * g * tt * tt
            x = lerp(h0[0], land_hip[0], u)
            ch = dict(hip=(x, y))
            if not flail:
                ch['lh'] = (x - 5, y - 26, 'free'); ch['rh'] = (x + 5, y - 26, 'free')
                ch['lf'] = (x - 3, y + 15, 'free'); ch['rf'] = (x + 3, y + 15, 'free')
            if flail:
                a = math.sin(u * 3.0) * 3
                ch['lh'] = (x - 7 - a, y - 18 + u * 8, 'free')
                ch['rh'] = (x + 7 + a, y - 19 + u * 9, 'free')
                ch['lf'] = (x - 4, y + 15 - u * 4, 'free')
                ch['rf'] = (x + 5, y + 14 - u * 3, 'free')
            if i == n:
                ch.update({k: v for k, v in land.items()})
            self.to(T / n, 'lin', auto=False, **ch)
        return self

    def sample(self, t):
        ks = self.keys
        if t <= ks[0][0]: return dict(ks[0][1])
        if t >= ks[-1][0]: return dict(ks[-1][1])
        i = 1
        while ks[i][0] < t: i += 1
        t0, s0, _ = ks[i-1]; t1, s1, ease = ks[i]
        dt = max(t1 - t0, 1e-4)
        u = (t - t0) / dt
        out = dict(s1); out['att'] = s1['att']
        # 髋部：Hermite 样条（速度连续）
        out['hip'] = self._herm('hip', i, u, ease)
        for L in LIMBS:
            a, b = s0[L], s1[L]
            moving = dist(a, b) > 0.3
            if not moving:
                out[L] = b; continue
            if s1['att'][L] and ease != 'lin':
                e = eio(u) if ease == 'io' else (eout(u) if ease == 'out' else (eback(u) if ease == 'back' else ein(u)))
                p = lerp2(a, b, e)
                d = dist(a, b)
                lift = min(3.5, d * 0.22) * math.sin(math.pi * clamp(u, 0, 1))
                if L in ('lf', 'rf'):
                    p = (p[0], p[1] - lift)          # 脚抬起越过
                else:
                    n_ = norm(sub(b, a))
                    p = add(p, mul((n_[1], -n_[0]) if n_[0] > 0 else (-n_[1], n_[0]), lift * .5))
                out[L] = p
            else:
                out[L] = self._herm(L, i, u, ease)
        limb_keep_out(out, self.actor.look)
        out['kd0'], out['ed0'], out['kdu'] = s0.get('kd'), s0.get('ed'), u
        out['shake'] = lerp(s0.get('shake', 0), s1.get('shake', 0), u)
        out['breathe'] = lerp(s0.get('breathe', 1), s1.get('breathe', 1), u)
        return out

    def _herm(self, ch, i, u, ease):
        ks = self.keys
        t0, s0, _ = ks[i-1]; t1, s1, _ = ks[i]
        p0, p1 = s0[ch], s1[ch]
        dt = t1 - t0
        if ease == 'lin' and ch == 'hip':
            return lerp2(p0, p1, u)
        def tangent(j):
            if j <= 0 or j >= len(ks) - 1: return (0.0, 0.0)
            ta, sa, _ = ks[j-1]; tb, sb, _ = ks[j+1]; tc, sc, ec = ks[j]
            pa, pb, pc = sa[ch], sb[ch], sc[ch]
            # 一侧静止 → 该关键帧速度为 0（自然停住，不漂移）
            if dist(pa, pc) < 0.3 or dist(pc, pb) < 0.3: return (0.0, 0.0)
            # 方向折返 → 速度为 0
            v1, v2 = sub(pc, pa), sub(pb, pc)
            if v1[0]*v2[0] + v1[1]*v2[1] < 0: return (0.0, 0.0)
            return mul(sub(pb, pa), 0.85 / max(tb - ta, 1e-4))
        m0, m1 = tangent(i-1), tangent(i)
        if ks[i][2] == 'lin': m1 = mul(sub(p1, p0), 1/dt) if ch == 'hip' else m1
        u2, u3 = u*u, u*u*u
        h00 = 2*u3 - 3*u2 + 1; h10 = u3 - 2*u2 + u; h01 = -2*u3 + 3*u2; h11 = u3 - u2
        return (h00*p0[0] + h10*dt*m0[0] + h01*p1[0] + h11*dt*m1[0],
                h00*p0[1] + h10*dt*m0[1] + h01*p1[1] + h11*dt*m1[1])

def keep_out(p, root, lmin, u):
    """轨迹绕开身体：若 p 进入关节根部 lmin 半径内，沿固定方向 u 推到圆周上（随 p 连续变化）。"""
    w = sub(p, root)
    if w[0]*w[0] + w[1]*w[1] >= lmin * lmin: return p
    wu = w[0]*u[0] + w[1]*u[1]
    t = -wu + math.sqrt(max(wu*wu - (w[0]*w[0] + w[1]*w[1]) + lmin*lmin, 0))
    return (p[0] + u[0]*t, p[1] + u[1]*t)

def limb_keep_out(st, look):
    s = look.s
    hip = st['hip']
    for L, side in (('lh', -1), ('rh', 1)):
        root = (hip[0] + side * 2.3 * s, hip[1] - TOR * s)
        st[L] = keep_out(st[L], root, (UA + FA) * s * 0.45, (side * 0.8, 0.6))
    for L, side in (('lf', -1), ('rf', 1)):
        st[L] = keep_out(st[L], hip, (TH + SH) * s * 0.3, (side * 0.9, -0.44))

def fix_hip(st, look):
    """人体工学约束：抓点的手离肩 ≥ 50% 臂长，踩点的脚离髋 ≥ 35% 腿长（防止肢体被压扁折叠）。"""
    s = look.s
    hip = list(st['hip'])
    amin = (UA + FA) * s * 0.5; lmin = (TH + SH) * s * 0.35
    for _ in range(20):
        for L, side in (('lh', -1), ('rh', 1)):
            if not st['att'][L]: continue
            sh = (hip[0] + side * 2.3 * s, hip[1] - TOR * s)
            v = sub(sh, st[L]); d = math.hypot(*v)
            if d < amin:
                n_ = norm(v) if d > 1e-3 else (0.0, 1.0)
                hip[0] += n_[0] * (amin - d) * .6; hip[1] += n_[1] * (amin - d) * .6
        for L in ('lf', 'rf'):
            if not st['att'][L]: continue
            v = sub(hip, st[L]); d = math.hypot(*v)
            if d < lmin:
                n_ = norm(v) if d > 1e-3 else (0.0, -1.0)
                hip[0] += n_[0] * (lmin - d) * .6; hip[1] += n_[1] * (lmin - d) * .6
    return (hip[0], hip[1])

def solve_hip(st, look, bias=(0, 0)):
    """重心求解：根据已接触的手脚求髋部位置（臂长/腿长约束的松弛迭代）。"""
    s = look.s
    hands = [st[k] for k in ('lh', 'rh') if st['att'][k]]
    feet = [st[k] for k in ('lf', 'rf') if st['att'][k]]
    pts = hands + feet
    if not pts: return st['hip']
    px = sum(p[0] for p in pts) / len(pts)
    if hands and feet:
        hy = min(p[1] for p in hands); fy = max(p[1] for p in feet)
        py = lerp(hy, fy, 0.55)
    elif hands:
        py = max(p[1] for p in hands) + (TOR + UA + FA - 2) * s
    else:
        py = min(p[1] for p in feet) - (TH + SH - 1.5) * s
    hip = [px + bias[0], py + bias[1]]
    LA = (UA + FA) * s * 0.96; LL = (TH + SH) * s * 0.96
    for _ in range(60):
        for p in hands:
            sh = (hip[0] + (-2.3 if p is st['lh'] else 2.3) * s, hip[1] - TOR * s)
            v = sub(p, sh); d = math.hypot(*v)
            if d > LA: hip[0] += v[0]*(d-LA)/d*.5; hip[1] += v[1]*(d-LA)/d*.5
        for p in feet:
            v = sub(p, hip); d = math.hypot(*v)
            if d > LL: hip[0] += v[0]*(d-LL)/d*.5; hip[1] += v[1]*(d-LL)/d*.5
            if d < 5*s: hip[1] -= 0.3
    return (hip[0], hip[1])

class Actor:
    def __init__(self, look, t_in, t_out):
        self.look, self.t_in, self.t_out = look, t_in, t_out
        self.tl = None
        self.seed = random.random() * 10
    def state(self, t):
        if t < self.t_in or t > self.t_out or self.tl is None: return None
        return self.tl.sample(t)
    def move_label(self, t):
        lab = None
        for tt, txt in self.tl.labels:
            if tt <= t: lab = txt
        return lab

# ------------------------------------------------------------------ IK & 绘制
def ik(a, b, l1, l2, pref):
    v = sub(b, a); d = math.hypot(*v)
    dirv = norm(v)
    if d >= l1 + l2 - 0.05:
        j = add(a, mul(dirv, l1)); e = add(a, mul(dirv, l1 + l2))
        return j, e
    d = max(d, abs(l1 - l2) + 0.1)
    x = (l1*l1 - l2*l2 + d*d) / (2*d)
    h = math.sqrt(max(l1*l1 - x*x, 0))
    base = add(a, mul(dirv, x))
    perp = (-dirv[1], dirv[0])
    if perp[0]*pref[0] + perp[1]*pref[1] < 0: perp = (-perp[0], -perp[1])
    return add(base, mul(perp, h)), b

def build_pose(st, look, t, seed):
    s = look.s
    hip = st['hip']
    # 待机呼吸 + 颤抖（新手/力竭）
    br = st.get('breathe', 1.0)
    hip = (hip[0], hip[1] + math.sin(t * 2.6 + seed) * 0.35 * br)
    sk = st.get('shake', 0)
    if sk > 0:
        hip = (hip[0] + noise1(t*3.2, seed) * sk * .8, hip[1] + noise1(t*2.9, seed+4) * sk * .5)
    # 躯干倾斜：朝向已抓的手
    hands = [st[k] for k in ('lh', 'rh')]
    hc = ((hands[0][0]+hands[1][0])/2, (hands[0][1]+hands[1][1])/2)
    lean = st.get('lean')
    if lean is None:
        lean = clamp((hc[0] - hip[0]) * 0.03, -0.35, 0.35) if (st['att']['lh'] or st['att']['rh']) else 0.0
    sh = add(hip, rot((0, -TOR * s), lean))
    ax = norm(sub(sh, hip)); perp = (-ax[1], ax[0])
    tk = look.tw / 5.0
    sw = 2.3 * s * tk
    head = add(sh, mul(ax, 4.6 * s))
    ed = st.get('ed') or {}
    kd = st.get('kd') or {}
    P = dict(hip=hip, sh=sh, head=head, lean=lean, ax=ax, perp=perp)
    kd0 = st.get('kd0', st.get('kd')) or {}
    ed0 = st.get('ed0', st.get('ed')) or {}
    ku = smooth(st.get('kdu', 1.0))
    def pref_of(L, root, tgt, table):
        if L in ('lh', 'rh'):
            return table.get(L, (-.6, 1) if L == 'lh' else (.6, 1))
        p_ = table.get(L)
        if p_ is None:
            # 膝关节 = 铰链：只能朝一个旋转方向弯（右腿顺时针侧、左腿逆时针侧），
            # 站立时膝盖朝外、抬脚时膝盖朝上，任何脚位都不会反折，也不会突然翻面。
            dv = norm(sub(tgt, root))
            p_ = (dv[1], -dv[0]) if L == 'rf' else (-dv[1], dv[0])
        return p_
    for L, root, l1, l2 in (('lh', sub(sh, mul(perp, sw)), UA*s, FA*s),
                            ('rh', add(sh, mul(perp, sw)), UA*s, FA*s),
                            ('lf', sub(hip, mul(perp, 1.3*s)), TH*s, SH*s),
                            ('rf', add(hip, mul(perp, 1.3*s)), TH*s, SH*s)):
        tgt = st[L]
        if sk > 0 and L in ('lh', 'rh') and not st['att'][L]:
            tgt = (tgt[0] + noise1(t*4, seed+7) * sk, tgt[1] + noise1(t*4.4, seed+9) * sk)
        cur_t, prev_t = (ed, ed0) if L in ('lh', 'rh') else (kd, kd0)
        def joint(table):
            pole = pref_of(L, root, tgt, table)
            j_, e_ = ik(root, tgt, l1, l2, pole)
            if L in ('lh', 'rh'):
                # 极点目标（pole target）：肘部总是靠向肩部外下方的一个固定点，
                # 两个 IK 解按到极点的距离连续加权 → 手经过肩附近也不会甩肘/翻面
                pn = norm(pole)
                P_ = add(root, mul(pn, l1 * 1.2))
                dv = norm(sub(tgt, root)); pp = (-dv[1], dv[0])
                ja, _ = ik(root, tgt, l1, l2, pp)
                jb_, _ = ik(root, tgt, l1, l2, (-pp[0], -pp[1]))
                w = smooth(0.5 + 0.5 * clamp((dist(jb_, P_) - dist(ja, P_)) / (l1 * 0.8), -1, 1))
                jm = lerp2(jb_, ja, w)
                if dist(jm, root) > 1e-3:
                    j_ = add(root, mul(norm(sub(jm, root)), l1))
            return j_, e_
        j, e = joint(cur_t)
        if ku < 1.0:
            # 姿态风格切换时（如走路→站立、落地→坐下）两套关节解平滑过渡，
            # 相当于髋/肩关节旋转把膝盖“转”过去，而不是一帧翻面。
            j0, _ = joint(prev_t)
            if dist(j0, j) > 0.05:
                jb = lerp2(j0, j, ku)
                j = add(root, mul(norm(sub(jb, root)), l1))
                pass
        P[L + '_root'] = root; P[L + '_j'] = j; P[L] = e
    return P

def C(p): return (p[0] * K, p[1] * K)

def thick_line(d, pts, w, col):
    pts = [C(p) for p in pts]
    d.line(pts, fill=col, width=int(round(w * K)), joint='curve')
    r = w * K / 2
    for p in pts:
        d.ellipse((p[0]-r, p[1]-r, p[0]+r, p[1]+r), fill=col)

def rect(d, x0, y0, x1, y1, col):
    X0, Y0, X1, Y1 = round(min(x0, x1)*K), round(min(y0, y1)*K), round(max(x0, x1)*K)-1, round(max(y0, y1)*K)-1
    d.rectangle((X0, Y0, max(X0, X1), max(Y0, Y1)), fill=col)

def draw_person(d, P, look):
    s = look.s
    cream, pants = look.shirt, look.pants
    # 腿
    for L in ('lf', 'rf'):
        thick_line(d, [P[L+'_root'], P[L+'_j'], P[L]], 3.0*s, pants)
    for L in ('lf', 'rf'):
        fx, fy = P[L]
        rect(d, fx - 1.6*s, fy - 0.5, fx + 1.8*s, fy + 2.0*s, cream)
    hip, sh, ax, pp = P['hip'], P['sh'], P['ax'], P['perp']
    tk = look.tw / 5.0
    ww, sw = 2.0 * s * tk, 3.3 * s * tk
    # 躯干（肩宽腰窄的梯形）
    top = add(sh, mul(ax, 0.6))
    poly = [sub(add(hip, mul(ax, 1.0)), mul(pp, ww)), add(add(hip, mul(ax, 1.0)), mul(pp, ww)),
            add(top, mul(pp, sw)), sub(top, mul(pp, sw))]
    d.polygon([C(p) for p in poly], fill=cream)
    for sgn in (-1, 1):
        c = add(sh, mul(pp, sgn * (sw - 1.0)))
        r = 1.1 * K * s
        d.ellipse((c[0]*K - r, c[1]*K - r, c[0]*K + r, c[1]*K + r), fill=cream)
    # 胯（裤腰）
    poly = [sub(add(hip, mul(ax, 1.6)), mul(pp, ww + .3)), add(add(hip, mul(ax, 1.6)), mul(pp, ww + .3)),
            add(sub(hip, mul(ax, 1.8)), mul(pp, ww + .5)), sub(sub(hip, mul(ax, 1.8)), mul(pp, ww + .5))]
    d.polygon([C(p) for p in poly], fill=pants)
    # 手臂
    for L in ('lh', 'rh'):
        thick_line(d, [P[L+'_root'], P[L+'_j'], P[L]], 2.0*s, cream)
        x, y = P[L]
        rect(d, x - 1.2*s, y - 1.2*s, x + 1.2*s, y + 1.2*s, cream)
    # 头
    cx, cy = P['head']
    hw, hh = 2.6*s, 3.0*s
    rect(d, cx - hw, cy - hh, cx + hw, cy + hh, cream)
    if look.hair:
        rect(d, cx - hw, cy - hh, cx + hw, cy - hh + 1.4*s, PAL['dark'])
    if look.band:
        rect(d, cx - hw, cy - hh + 1.6*s, cx + hw, cy - hh + 2.6*s, PAL['dark'])
    if look.cap:
        rect(d, cx - hw - .6, cy - hh - .6, cx + hw + .6, cy - hh + 1.4*s, PAL['red'])

# ------------------------------------------------------------------ 背景
_bg_cache = {}
def sky_at(t):
    u = smooth((t - (TR + 1)) / (DUR - TR - 1))
    return lerpc(PAL['sky'], PAL['sky2'], u * 0.8)

def make_bg(t):
    sun_y = round(40 + t * 0.45)
    skyc = sky_at(t)
    key = (sun_y, skyc)
    if key in _bg_cache: return _bg_cache[key]
    im = Image.new('RGB', (W, H), PAL['frame'])
    d = ImageDraw.Draw(im)
    glass = Image.new('RGB', (W, H), skyc)
    g = ImageDraw.Draw(glass)
    g.ellipse((128 - 22, sun_y - 22, 128 + 22, sun_y + 22), fill=PAL['sun'])
    city = [(60, 70, 24), (84, 76, 30), (110, 66, 18), (140, 78, 26), (168, 72, 20), (196, 60, 10),
            (208, 74, 36), (246, 58, 14), (262, 68, 22), (286, 76, 30), (318, 64, 12), (332, 72, 30)]
    for x, y, w in city:
        g.rectangle((x, y, x + w, 100), fill=PAL['city'])
    g.rectangle((0, 82, W, 100), fill=PAL['city'])
    mask = Image.new('L', (W, H), 0)
    m = ImageDraw.Draw(mask)
    m.ellipse((22, -40, 362, 176), fill=255)
    m.rectangle((0, 88, W, H), fill=0)
    m.polygon([(0, 0), (60, 0), (0, 52)], fill=255)
    m.polygon([(W, 0), (W - 60, 0), (W, 52)], fill=255)
    im.paste(glass, (0, 0), mask)
    # 窗格
    for x in range(56, 340, 34):
        d.rectangle((x, 0, x + 1, 88), fill=PAL['frame'])
    for y in (30, 58):
        d.rectangle((0, y, W, y + 1), fill=PAL['frame'])
    d.ellipse((22, -40, 362, 176), outline=PAL['frame'], width=7)
    d.line((0, 56, 64, 0), fill=PAL['frame'], width=5)
    d.line((W, 56, W - 64, 0), fill=PAL['frame'], width=5)
    # 吊灯
    for lx in (42, 342):
        d.rectangle((lx, 0, lx + 1, 60), fill=PAL['pole'])
        d.polygon([(lx - 6, 66), (lx + 7, 66), (lx + 3, 61), (lx - 2, 61)], fill=PAL['cream'])
    # 岩壁
    top = [(50, 184), (50, 168), (54, 158), (60, 150), (70, 140), (82, 128), (96, 116), (110, 106), (124, 100),
           (140, 96), (170, 94), (200, 92), (240, 91), (280, 90), (320, 91), (350, 93), (384, 95), (384, 184)]
    d.polygon(top, fill=PAL['mid'])
    d.polygon([(50, 184), (50, 168), (54, 158), (60, 150), (70, 140), (82, 128), (96, 116), (110, 106), (124, 100),
               (146, 96), (104, 184)], fill=PAL['teal'])
    d.polygon([(318, 91), (350, 93), (384, 95), (384, 184), (290, 184)], fill=PAL['light'])
    d.line(top[1:-1], fill=PAL['walltop'], width=2)
    # 地面、垫子、前台、门
    d.rectangle((0, 184, W, H), fill=PAL['floor'])
    d.rectangle((0, 184, W, 185), fill=PAL['floorline'])
    d.rectangle((126, 181, 262, 186), fill=PAL['mat'])
    d.rectangle((126, 181, 262, 181), fill=PAL['mattop'])
    d.rectangle((3, 140, 13, 184), fill=PAL['cream'])
    d.rectangle((13, 138, 15, 184), fill=hx('#4a2a55'))
    d.rectangle((20, 168, 46, 184), fill=PAL['desk'])
    d.rectangle((18, 165, 48, 168), fill=PAL['cream'])
    d.rectangle((26, 160, 34, 165), fill=PAL['cream'])
    big = im.resize((CW, CH), Image.NEAREST)
    _bg_cache[key] = big
    if len(_bg_cache) > 40: _bg_cache.pop(next(iter(_bg_cache)))
    return big

def draw_hold(d, h, t, highlight=False):
    if h.t_on >= 0 and t < h.t_on: return
    k = 1.0
    if h.t_on >= 0 and t < h.t_on + 0.35:
        k = eback((t - h.t_on) / 0.35)
    if h.kind == 'volume':
        cx, cy = 196, 147
        pts = [(cx + (x - cx) * k, cy + (y - cy) * k) for x, y in VOL]
        d.polygon([(p[0]*K + K, p[1]*K + K) for p in pts], fill=PAL['dark'])
        d.polygon([C(p) for p in pts], fill=PAL['cream'])
        return
    x, y, w = h.x, h.y, h.w * k
    if h.kind in ('jug', 'crimp', 'chip'):
        th = {'jug': 3, 'crimp': 2, 'chip': 1.5}[h.kind] * k
        rect(d, x - w/2, y - th/2 + 1, x + w/2, y + th/2 + 1, PAL['holdsh'])
        rect(d, x - w/2, y - th/2, x + w/2, y + th/2, PAL['hold'])
    else:
        rw, rh_ = w / 2, (3.0 if h.kind == 'sloper' else 2.6) * k
        d.ellipse(((x - rw)*K, (y - rh_ + 1)*K, (x + rw)*K, (y + rh_ + 1)*K), fill=PAL['holdsh'])
        d.ellipse(((x - rw)*K, (y - rh_)*K, (x + rw)*K, (y + rh_)*K), fill=PAL['hold'])

GLYPH = {
    '!': ["..#..", "..#..", "..#..", ".....", "..#.."],
    '?': [".###.", "...#.", "..#..", ".....", "..#.."],
    'heart': [".#.#.", "#####", "#####", ".###.", "..#.."],
    '...': [".....", ".....", "#.#.#", ".....", "....."],
    'star': ["..#..", ".###.", "#####", ".###.", ".#.#."],
    'swirl': [".###.", "#...#", "#.#.#", "#..#.", ".##.."],
    'note': ["..##.", "..#.#", "..#..", "###..", "##..."],
}
def draw_emote(d, pos, glyph, age):
    x, y = pos
    pop = eback(min(age / 0.25, 1))
    bw = 9 * pop
    x0, y0 = x - bw/2, y - 11 * pop
    rect(d, x0, y0, x0 + bw, y0 + bw, PAL['cream'])
    rect(d, x - 1, y0 + bw, x + 1, y0 + bw + 1.5, PAL['cream'])
    if pop > 0.9:
        g = GLYPH[glyph]
        col = PAL['red'] if glyph in ('!', 'heart') else PAL['dark']
        for j, row in enumerate(g):
            for i, c in enumerate(row):
                if c == '#': rect(d, x0 + 2 + i, y0 + 2 + j, x0 + 3 + i, y0 + 3 + j, col)

def draw_dog(d, x, t, walking, facing=1):
    y = 184
    leg = int(t * 8) % 2 if walking else 0
    col = PAL['dog']
    def px(i, j, w=1, h=1): rect(d, x + i*facing - (w if facing < 0 else 0), y + j, x + i*facing + (w if facing > 0 else 0) * 1 - (0 if facing > 0 else 0) + (0), y + j + h, col) if False else None
    body = [(-5, -7, 9, 3)]
    # 简单像素小狗
    f = facing
    def r(i, j, w, h):
        xa = x + (i if f > 0 else -i - w)
        rect(d, xa, y + j, xa + w, y + j + h, col)
    col = PAL['dark']
    def r2(i, j, w, h): r(i - .4, j - .4, w + .8, h + .8)
    for args in ((-5, -7, 9, 3), (3, -10, 4, 4), (3, -12, 1, 2), (6, -12, 1, 2), (7, -9, 2, 2), (-7, -9, 2, 2)):
        r2(*args)
    col = hx('#f2a046')
    r(-5, -7, 9, 3)                 # 身体
    r(3, -10, 4, 4)                 # 头
    r(3, -12, 1, 2); r(6, -12, 1, 2)  # 耳朵
    r(7, -9, 2, 2)                  # 嘴
    r(-7, -9 + (1 if walking and leg else 0), 2, 2)  # 尾巴
    for i, lx in enumerate((-5, -3, 1, 3)):
        off = (1 if (i + leg) % 2 else 0) if walking else 0
        r(lx + off, -4, 1, 4)
    sit_ = None

# ------------------------------------------------------------------ 事件 / 粒子
EVENTS = []
def draw_particles(d, t, actor_time=None):
    for i, e in enumerate(EVENTS):
        te = e['t'] if actor_time is None else e['t']
        tt = t if actor_time is None else actor_time.get(e.get('actor'), None)
        if tt is None: continue
        age = tt - te
        if e['kind'] == 'puff' and 0 <= age < 0.9:
            rnd = random.Random(i * 31)
            for k in range(14):
                a = rnd.uniform(0, 2*math.pi); sp = rnd.uniform(4, 14)
                if rnd.random() < age / 0.9: continue
                x = e['pos'][0] + math.cos(a) * sp * eout(age / 0.9)
                y = e['pos'][1] + math.sin(a) * sp * eout(age / 0.9) * .6 - age * 4
                rect(d, x, y, x + 1, y + 1, PAL['cream'])
        if e['kind'] == 'dust' and 0 <= age < 0.8:
            rnd = random.Random(i * 17)
            for k in range(18):
                side = -1 if k % 2 else 1
                sp = rnd.uniform(5, 18)
                if rnd.random() < age / 0.8: continue
                x = e['pos'][0] + side * sp * eout(age / 0.8)
                y = e['pos'][1] - rnd.uniform(0, 5) * math.sin(math.pi * age / 0.8) - 1
                rect(d, x, y, x + 1.3, y + 1.3, PAL['mattop'])
        if e['kind'] == 'sweat' and 0 <= age < 0.7:
            a = e['actor']; st = a.state(tt)
            if st:
                hp = st['hip']
                x = hp[0] + 5 + age * 6; y = hp[1] - 20 + age * age * 30
                rect(d, x, y, x + 1, y + 2, hx('#9fd3e0'))

def draw_emotes(d, t, actor_time=None):
    for e in EVENTS:
        if e['kind'] != 'emote': continue
        a = e['actor']
        tt = t if actor_time is None else actor_time.get(a)
        if tt is None: continue
        age = tt - e['t']
        if 0 <= age < e.get('dur', 1.2):
            st = a.state(tt)
            if not st: continue
            P = build_pose(st, a.look, tt, a.seed)
            hx_, hy = P['head']
            draw_emote(d, (hx_ + 6, hy - 4), e['glyph'], age)

# ------------------------------------------------------------------ 角色剧本
ACTORS = []
LOOK_A = Look('阿岩', 1.0, 5, band=True)
LOOK_B = Look('小橙', 0.92, 5, hair=True, cap=True)
LOOK_C = Look('大壮', 1.1, 7, pants=PAL['red'])
LOOK_S1 = Look('观众1', 0.95, 5)
LOOK_S2 = Look('观众2', 1.0, 5, band=True, pants=hx('#c96a28'))
LOOK_S3 = Look('观众3', 0.97, 5, hair=False)

S, f1, f2, L_, J2, f3, f4, Cr, T_ = (ROUTE[k] for k in ('S', 'f1', 'f2', 'L', 'J2', 'f3', 'f4', 'Cr', 'T'))

def sit_start(tl):
    return tl.to(0.7, 'io', lh=S.hand(-3.5), rh=S.hand(3.5), hip=(171, 167), lean=0.0,
                 kd=None, auto=False, breathe=0.6) \
             .to(0.5, 'io', lf=f1.foot(), auto=False, hip=(171, 168)) \
             .to(0.45, 'io', rf=f2.foot(), auto=False, hip=(172, 167.5))

# ---- A：技术流老手
def script_A(t0):
    a = Actor(LOOK_A, t0, 999); ACTORS.append(a)
    tl = Timeline(a, t0, stand_state(8, 1, LOOK_A.s)); a.tl = tl; HY = hip_y(LOOK_A.s)
    tl.walk(172, speed=58)
    tl.label('擦镁粉').to(0.35, lh=(170, 166, 'free'), rh=(174, 166, 'free'), auto=False) \
      .ev('puff', pos=(172, 164)).to(0.35, lh=(168, 162, 'free'), rh=(176, 162, 'free'), auto=False) \
      .to(0.3, lh=(166, 155, 'free'), rh=(177, 155, 'free'), auto=False)
    tl.label('坐式起步'); sit_start(tl)
    tl.wait(0.25).label('换脚上三角块')
    tl.to(0.55, 'io', hip=(175, 163), auto=False, lean=None, kd=None, breathe=0.4)
    tl.to(0.6, 'io', rf=(188, vol_y(188) - 2))
    tl.label('压上三角块 Rock-over').to(0.7, 'io', lf=f3.foot(), hip_bias=(2, -2))
    tl.label('伸手抓高点').to(0.55, 'io', rh=J2.hand(1)).ev('puff', pos=J2.hand(1), dt=0.0)
    tl.to(0.55, 'io', lf=S.foot(-2))
    tl.label('交叉手 Cross').to(0.6, 'io', lh=Cr.hand(-1)).ev('puff', pos=Cr.hand(-1))
    tl.label('高抬脚 High-step').to(0.6, 'io', rf=(199, vol_y(199) - 1.5))
    tl.to(0.55, 'io', lf=f4.foot())
    tl.label('死点 Deadpoint').to(0.18, 'io', hip_bias=(1, 2)) \
      .to(0.42, 'out', rh=T_.hand(3)).ev('puff', pos=T_.hand(3)).ev('emote', glyph='note', dur=1.0)
    tl.label('完攀！').to(0.5, 'io', lh=T_.hand(-3)).ev('pop', text='完攀 TOP!', pos=(205, 86), col='cream')
    tl.to(0.7, 'io', lf=(194, 126, 'free'), rf=(208, 126, 'free'), kd=None)
    tl.label('跳下').to(0.3, 'io', auto=False, hip=(205, 115)).wait(0.15)
    tl.fall((205, 173.5), dict(lf=(200, 182.0), rf=(210, 182.0), lh=(198, 168, 'free'), rh=(212, 168, 'free'),
                               kd=None), flail=False)
    tl.ev('dust', pos=(205, 183)).ev('shake', amp=0.8, dur=0.25)
    tl.to(0.5, 'out', hip=(205, HY), auto=False, kd=None, lh=(199, 146, 'free'), rh=(212, HY - 1.5, 'free')) \
      .ev('emote', glyph='heart', dur=1.4).label('庆祝')
    tl.to(0.6, 'io', auto=False, hip=(205, HY), lh=(198, 144, 'free'))
    tl.ev('say', text='三角块踩得好舒服！', dur=2.6)
    tl.wait(0.6).walk(400, speed=50)
    return a

# ---- B：新手（抓斜面点脱落）
def script_B(t0):
    a = Actor(LOOK_B, t0, 999); ACTORS.append(a)
    tl = Timeline(a, t0, stand_state(8, 1, LOOK_B.s)); a.tl = tl; HY = hip_y(LOOK_B.s)
    tl.walk(168, speed=48)
    tl.ev('emote', glyph='?', dur=1.3).label('观察路线').to(1.0, 'io', auto=False, hip=(168, HY + 0.4),
        rh=(178, 144, 'free'))
    tl.label('擦镁粉').to(0.35, lh=(166, 166, 'free'), rh=(170, 166, 'free'), auto=False).ev('puff', pos=(168, 164))
    tl.label('坐式起步'); sit_start(tl)
    tl.to(0.6, 'io', shake=0.5).ev('emote', glyph='...', dur=1.4).wait(0.6)
    tl.label('抬脚').to(0.8, 'io', lf=f3.foot(), shake=0.7)
    tl.label('抓斜面点 Sloper').to(0.9, 'io', lh=L_.hand(1), shake=0.9, hip_bias=(-3, 0)).wait(0.5)
    tl.label('手在打滑…').to(0.5, 'in', lh=(155, 137.5), shake=1.4).ev('emote', glyph='!', dur=0.9)
    tl.to(0.35, 'in', lh=(152, 140), rh=S.hand(3.5), shake=1.8)
    tl.label('脱落！').ev('shake', amp=0.5, dur=0.2)
    tl.fall((160, 178.0), dict(lf=(167, 182.0), rf=(170, 182.0), lh=(153, 179, 'free'), rh=(164, 179, 'free'),
                               kd={'lf': (0.4, -1), 'rf': (0.4, -1)}, shake=0.0), g=300)
    tl.ev('dust', pos=(160, 183)).ev('shake', amp=1.6, dur=0.35).ev('emote', glyph='swirl', dur=1.4)
    # 落垫回弹
    tl.to(0.14, 'out', auto=False, hip=(160, 175.2)).to(0.22, 'io', auto=False, hip=(160, 178.0))
    tl.wait(0.7).ev('sweat')
    tl.label('揉脑袋').to(0.5, 'io', auto=False, rh=(163, 155, 'free'), ed={'rh': (1, -.5)}) \
      .to(0.25, auto=False, rh=(161, 154, 'free')).to(0.25, auto=False, rh=(163, 155, 'free'))
    tl.ev('say', text='那个圆圆的点太滑了…', dur=2.8)
    tl.to(0.6, 'io', auto=False, hip=(160, HY), lf=(157, 182.0), rf=(163, 182.0), kd=None, ed=None,
          lh=(156, HY - 1.5, 'free'), rh=(164, HY - 1.5, 'free'))
    tl.wait(0.4).walk(-20, speed=40)
    return a

# ---- C：力量型（动态 + 挂脚跟 + 单手挂）
def script_C(t0):
    a = Actor(LOOK_C, t0, 999); ACTORS.append(a)
    tl = Timeline(a, t0, stand_state(400, -1, LOOK_C.s)); a.tl = tl; HY = hip_y(LOOK_C.s)
    tl.walk(174, speed=62)
    tl.label('拍粉').to(0.25, auto=False, lh=(170, 160, 'free'), rh=(178, 160, 'free')) \
      .to(0.15, auto=False, lh=(173, 160, 'free'), rh=(175, 160, 'free')).ev('puff', pos=(174, 158))
    tl.label('坐式起步'); sit_start(tl)
    tl.label('换脚上三角块').to(0.55, 'io', hip=(175, 163), auto=False, lean=None, kd=None, breathe=0.5) \
      .to(0.5, 'io', rf=(189, vol_y(189) - 2))
    tl.label('大跨度').to(0.55, 'io', rh=J2.hand(0), hip_bias=(2, -3)).ev('puff', pos=J2.hand(0))
    tl.label('挂脚跟 Heel hook').to(0.65, 'io', rf=(201, 134.5), kd=None, lf=f3.foot())
    tl.to(0.55, 'io', lh=Cr.hand(0)).ev('puff', pos=Cr.hand(0))
    tl.to(0.5, 'io', lf=S.foot(-3))
    # 动态：预备下沉 → 爆发 → 空中 → 单手接住
    tl.label('预备下沉').to(0.45, 'io', hip_bias=(0, 4), kd=None)
    sink = tl.cur['hip']
    s_ = LOOK_C.s
    hand = T_.hand(2)
    hang_y = hand[1] + (UA + FA) * s_ * 0.9 + TOR * s_      # 直臂悬挂时的髋高
    tl.label('动态 DYNO!').to(0.24, 'out', auto=False, hip=(197, hang_y - 9), lf=(190, hang_y + 8, 'free'),
                           rf=(201, hang_y + 6, 'free'), lh=(188, hang_y - 20, 'free'), rh=(205, hand[1] - 2, 'free'), lean=0.12)
    tl.to(0.12, 'out', auto=False, hip=(202, hang_y - 7), rh=hand, lh=(192, hang_y - 16, 'free'),
          lf=(197, hang_y + 11, 'free'), rf=(206, hang_y + 10, 'free'))
    tl.ev('puff', pos=hand).ev('shake', amp=1.4, dur=0.3).ev('pop', text='DYNO!', pos=(205, 84), col='orange')
    # 接住后身体下坠到直臂（跟随动作），再做阻尼钟摆
    px = hand[0]
    tl.to(0.22, 'out', auto=False, hip=(px + 4, hang_y + 0.5), lean=None,
          lf=(px + 2, hang_y + 16, 'free'), rf=(px + 9, hang_y + 15, 'free'), lh=(px - 5, hang_y - 4, 'free'))
    for i, amp in enumerate((5, -3.6, 2.4, -1.4, 0.6)):
        hipx = px + amp * 0.8
        tl.to(0.36, 'io', auto=False, hip=(hipx, hang_y - abs(amp) * 0.12), lean=None,
              lf=(hipx - 2.5 + amp * 1.3, hang_y + 16.5 - abs(amp) * .3, 'free'),
              rf=(hipx + 3.5 + amp * 1.4, hang_y + 16 - abs(amp) * .3, 'free'),
              lh=(hipx - 6 - amp * .4, hang_y - 3, 'free'))
    tl.label('单手挂 秀一下').to(0.5, 'io', auto=False, lh=(px - 13, hang_y - 14, 'free'), ed={'lh': (-1, 1)}) \
      .ev('emote', glyph='star', dur=1.3)
    tl.to(0.5, 'io', auto=False, lh=(px - 12, hang_y - 16, 'free')).to(0.45, 'io', lh=T_.hand(-3), ed=None)
    tl.label('跳下').fall((203, 173.0), dict(lf=(198, 182.0), rf=(208, 182.0), lh=(196, 168, 'free'),
                                            rh=(210, 168, 'free'), kd=None), flail=False)
    tl.ev('dust', pos=(203, 183)).ev('shake', amp=1.2, dur=0.3)
    tl.to(0.55, 'out', auto=False, hip=(203, HY), kd=None, lh=(193, 150, 'free'), rh=(213, 150, 'free'),
          ed={'lh': (-1, -1), 'rh': (1, -1)}).label('秀肌肉')
    tl.ev('say', text='最后那下动态太爽了！', dur=2.6)
    tl.wait(0.9).to(0.3, auto=False, ed=None, lh=(199, HY - 1.5, 'free'), rh=(207, HY - 1.5, 'free')).walk(400, speed=55)
    return a

# ---- 观众：根据场上情况做反应（指、欢呼、捂脸、坐着看）
class Spectator(Actor):
    def __init__(self, look, x, base, reacts):
        super().__init__(look, -1, 999)
        self.x, self.base, self.reacts = x, base, reacts
        self.tl = None
    def mode(self, t):
        m = self.base
        for t0, t1, mm in self.reacts:
            if t0 <= t < t1: return mm, (t - t0), (t1 - t)
        return m, 99, 99
    def state(self, t):
        x = self.x
        st = stand_state(x, 1, self.look.s)
        st['breathe'] = 1.0
        m, age, left = self.mode(t)
        blend = min(eout(age / 0.35), eout(left / 0.35)) if age < 99 else 1.0
        base = self._pose(self.base, x, t)
        if m == self.base: return base
        tgt = self._pose(m, x, t)
        out = dict(tgt)
        for k in ('hip', 'lh', 'rh', 'lf', 'rf'):
            out[k] = lerp2(base[k], tgt[k], blend)
        out['kd0'], out['ed0'], out['kdu'] = base.get('kd'), base.get('ed'), blend
        limb_keep_out(out, self.look)
        return out
    def _pose(self, m, x, t):
        st = stand_state(x, 1, self.look.s)
        if m == 'sit':
            st.update(hip=(x, 179.5), lf=(x + 8, 182.0), rf=(x + 10, 182.0), lh=(x + 7, 172, 'f'), rh=(x + 9, 172.5, 'f'),
                      kd={'lf': (.3, -1), 'rf': (.3, -1)})
        elif m == 'hips':
            st.update(lh=(x - 4, 165.5), rh=(x + 4, 165.5), ed={'lh': (-1, -.2), 'rh': (1, -.2)})
        elif m == 'point':
            tgt = climber_hip(t) or (200, 130)
            sh = (x, 153)
            v = norm(sub(tgt, sh))
            st.update(rh=add(sh, mul(v, 14.5)), lh=(x - 4, 163.5), ed={'rh': (1, 1)})
        elif m == 'cheer':
            b = math.sin(t * 12) * 1.5
            st.update(lh=(x - 6, 140 + b), rh=(x + 6, 140 - b), hip=(x, 164 - abs(b) * .5), ed={'lh': (-1, 0), 'rh': (1, 0)})
        elif m == 'clap':
            c = abs(math.sin(t * 10)) * 3
            st.update(lh=(x - 1 - c, 155), rh=(x + 1 + c, 155), ed={'lh': (-1, .5), 'rh': (1, .5)})
            if self.base == 'sit':
                st.update(hip=(x, 179.5), lf=(x + 8, 182.0), rf=(x + 10, 182.0), kd={'lf': (.3, -1), 'rf': (.3, -1)},
                          lh=(x + 4 - c, 166), rh=(x + 6 + c, 166))
        elif m == 'gasp':
            if self.base == 'sit':
                st.update(hip=(x, 179.5), lf=(x + 8, 182.0), rf=(x + 10, 182.0), kd={'lf': (.3, -1), 'rf': (.3, -1)},
                          lh=(x - 1, 163), rh=(x + 2, 163), ed={'lh': (-1, .3), 'rh': (1, .3)})
            else:
                st.update(lh=(x - 2, 148), rh=(x + 2, 148), ed={'lh': (-1, .3), 'rh': (1, .3)})
        for k in ('lh', 'rh', 'lf', 'rf'):
            if len(st[k]) == 3: st[k] = (st[k][0], st[k][1])
        return st

def climber_hip(t):
    for a in ACTORS[:3]:
        st = a.state(t)
        if st and st['hip'][1] < 160: return st['hip']
    return None

# ------------------------------------------------------------------ 镜头
CAM = []  # (t, cx, cy, zoom)
def cam_key(t, cx, cy, z): CAM.append((t, cx, cy, z))
FOLLOW = []   # 攀爬者（自动跟随）
def follow_target(t):
    best = None
    for a in FOLLOW:
        w = min(smooth((t - a.t_in - 1.5) / 1.2), smooth((a.active_end - t) / 1.2))
        if w <= 0 or (best and best[0] >= w): continue
        xs = ys = n = 0
        for k in range(-6, 7):   # 前后各 0.6s 的平均（离线可前瞻 → 镜头非常稳）
            st = a.state(t + k * 0.1)
            if st is None: continue
            xs += st['hip'][0]; ys += st['hip'][1]; n += 1
        if n == 0: continue
        cx, cy = xs / n, ys / n
        z = lerp(1.35, 1.75, smooth((162 - cy) / 25))
        best = (w, cx + 6, cy - 6, z)
    return best

def camera(t):
    base = camera_keys(t)
    f = follow_target(t)
    if not f: return base
    w = f[0]
    return (lerp(base[0], f[1], w), lerp(base[1], f[2], w), math.exp(lerp(math.log(base[2]), math.log(f[3]), w)))

def camera_keys(t):
    ks = CAM
    if t <= ks[0][0]: return ks[0][1:]
    for i in range(1, len(ks)):
        if ks[i][0] >= t:
            t0, *a = ks[i-1]; t1, *b = ks[i]
            u = eio((t - t0) / max(t1 - t0, 1e-4))
            z = math.exp(lerp(math.log(a[2]), math.log(b[2]), u))
            return (lerp(a[0], b[0], u), lerp(a[1], b[1], u), z)
    return ks[-1][1:]

# ------------------------------------------------------------------ UI
class UI:
    def __init__(self):
        self.money = 1280
def box(d, x0, y0, x1, y1, fill=(38, 16, 48, 230), border=PAL['cream'], bw=2):
    d.rectangle((x0, y0, x1, y1), fill=fill)
    d.rectangle((x0, y0, x1, y1), outline=border + (255,), width=bw)
def star(d, cx, cy, r, filled, col):
    pts = []
    for i in range(10):
        a = -math.pi/2 + i * math.pi / 5
        rr = r if i % 2 == 0 else r * 0.45
        pts.append((cx + math.cos(a) * rr, cy + math.sin(a) * rr))
    if filled: d.polygon(pts, fill=col)
    else: d.polygon(pts, outline=col)
def text(d, xy, s, font, col=PAL['cream'], anchor='la'):
    d.text(xy, s, font=font, fill=col + (255,) if len(col) == 3 else col, anchor=anchor)

REVIEWS = [  # t（运行时按事件重算）, 名字, 标签, 星, 评语, 收入
    (28.6, '阿岩', '技术流 · 常客', 5, '三角块踩得很舒服，节奏流畅！', 45),
    (41.6, '小橙', '新手 · 第一次来', 2, '左边那个斜面点太滑了…有点受挫', 20),
    (56.2, '大壮', '力量型', 4, '最后一下动态过瘾！脚点有点多', 35),
]
def money_at(t):
    m = 1280.0
    for rt, _, _, _, _, inc in REVIEWS:
        if t > rt + 0.8: m += inc * eout((t - rt - 0.8) / 0.8)
    return m

def world_to_ui(p, crop):
    x0, y0, x1, y1 = crop  # 逻辑坐标
    sx = UW / (x1 - x0)
    return ((p[0] - x0) * sx, (p[1] - y0) * sx)

def draw_ui(t, crop, phase):
    ui = Image.new('RGBA', (UW, UH), (0, 0, 0, 0))
    d = ImageDraw.Draw(ui)
    d.fontmode = '1'
    if phase in ('replay',): return ui, d
    # 顶部 HUD
    box(d, 10, 8, 250, 40)
    text(d, (20, 16), '暮光岩馆', F16)
    text(d, (110, 16), '¥ %s' % format(int(money_at(t)), ','), F16, PAL['hold'])
    star(d, 205, 24, 7, True, PAL['hold'])
    rating = 4.2 if t < 42 else (4.1 if t < 56.5 else 4.2)
    text(d, (215, 16), '%.1f' % rating, F16)
    clock = 18 * 60 + 30 + int(t * 1.2)
    box(d, UW - 130, 8, UW - 10, 40)
    text(d, (UW - 120, 16), '第12天 %02d:%02d' % (clock // 60, clock % 60), F16)
    return ui, d

def draw_banner(d, t, t0, t1, title, sub=None):
    if not (t0 <= t < t1): return
    a = min(eout((t - t0) / 0.4), eout((t1 - t) / 0.4))
    y = -40 + 92 * a
    w = 300
    box(d, UW/2 - w/2, y, UW/2 + w/2, y + 44, fill=(38, 16, 48, 235), border=PAL['hold'], bw=3)
    text(d, (UW/2, y + 22), title, F24, anchor='mm')
    if sub:
        text(d, (UW/2, y + 58), sub, F16, PAL['cream'], anchor='mm')

def draw_climber_card(d, t, a, stam_curve):
    if not (a.t_in + 0.5 < t < a.active_end): return
    in_a = min(eout((t - a.t_in - 0.5) / 0.4), eout((a.active_end - t) / 0.4))
    x = -260 + 270 * in_a
    y = UH - 104
    box(d, x, y, x + 250, y + 92)
    text(d, (x + 12, y + 10), a.look.name, F24, PAL['hold'])
    tag = {'阿岩': '技术流 · 常客', '小橙': '新手 · 第一次来', '大壮': '力量型'}[a.look.name]
    text(d, (x + 80, y + 14), tag, F16)
    text(d, (x + 12, y + 44), '体力', F16)
    st = stam_curve(t)
    d.rectangle((x + 56, y + 46, x + 236, y + 58), outline=PAL['cream'] + (255,), width=1)
    col = PAL['hold'] if st > 0.35 else PAL['red']
    d.rectangle((x + 58, y + 48, x + 58 + 176 * st, y + 56), fill=col + (255,))
    lab = a.move_label(t) or '—'
    text(d, (x + 12, y + 68), '动作：' + lab, F16)

def draw_review(d, t, rv):
    rt, name, tag, stars, cmt, inc = rv
    if not (rt <= t < rt + 4.2): return
    a = min(eout((t - rt) / 0.45), eout((rt + 4.2 - t) / 0.4))
    x = UW + 10 - 330 * a
    y = 120
    box(d, x, y, x + 310, y + 132, border=PAL['hold'], bw=3)
    text(d, (x + 14, y + 12), '顾客评价', F16, PAL['hold'])
    text(d, (x + 100, y + 12), name + ' · ' + tag, F16)
    for i in range(5):
        k = clamp((t - rt - 0.4 - i * 0.12) / 0.2, 0, 1)
        r = 11 * (eback(k) if i < stars else 1)
        star(d, x + 28 + i * 30, y + 54, max(r, 0.1) if i < stars else 11, i < stars, PAL['hold'])
    text(d, (x + 14, y + 78), '“' + cmt + '”', F16)
    text(d, (x + 14, y + 104), '门票+小费', F16)
    text(d, (x + 110, y + 104), '+¥%d' % inc, F16, PAL['hold'])

def draw_says(d, t, crop):
    for e in EVENTS:
        if e['kind'] != 'say': continue
        age = t - e['t']
        if not (0 <= age < e['dur']): continue
        st = e['actor'].state(t)
        if not st: continue
        P = build_pose(st, e['actor'].look, t, e['actor'].seed)
        px, py = world_to_ui((P['head'][0], P['head'][1] - 7), crop)
        a = min(eback(min(age / 0.3, 1)), eout((e['dur'] - age) / 0.25))
        tw = d.textlength(e['text'], font=F16)
        w = (tw + 24) * a; h = 30 * a
        x0 = clamp(px - w / 2, 4, UW - w - 4); y0 = py - h - 10
        d.rectangle((x0, y0, x0 + w, y0 + h), fill=PAL['cream'] + (255,))
        d.polygon([(px - 6, y0 + h), (px + 6, y0 + h), (px, y0 + h + 9)], fill=PAL['cream'] + (255,))
        if a > 0.95:
            text(d, (x0 + 12, y0 + 7), e['text'], F16, PAL['dark'])

def draw_pops(d, t, crop):
    for e in EVENTS:
        if e['kind'] != 'pop': continue
        age = t - e['t']
        if not (0 <= age < 1.3): continue
        px, py = world_to_ui(e['pos'], crop)
        s = eback(min(age / 0.25, 1))
        col = PAL['hold'] if e['col'] == 'orange' else PAL['cream']
        y = py - age * 18
        if age > 1.0 and int(age * 20) % 2: continue
        f = FB28 if s > 0.98 else F(max(8, int(28 * s)), True)
        d.text((px + 2, y + 2), e['text'], font=f, fill=PAL['dark'] + (255,), anchor='mm')
        d.text((px, y), e['text'], font=f, fill=col + (255,), anchor='mm')
    for rt, name, tag, stars, cmt, inc in REVIEWS:
        age = t - rt - 0.8
        if 0 <= age < 1.4:
            d.text((UW - 260, 52 - age * 10), '+¥%d' % inc, font=FB20, fill=PAL['hold'] + (255,))

# ------------------------------------------------------------------ 设计阶段（光标放置岩点）
TOOLBAR = [('jug', 150), ('volume', 192), ('play', 234)]
def design_cursor(t):
    """返回 (x, y, 是否按下, 拖拽中的岩点类型)"""
    order = ['S', 'f1', 'f2', 'L', 'V', 'J2', 'f3', 'f4', 'Cr', 'T']
    tool = {'jug': 150, 'chip': 150, 'crimp': 150, 'sloper': 150, 'volume': 192}
    seq = []
    for k in order:
        h = ROUTE[k]
        tx, ty = (196, 145) if k == 'V' else (h.x, h.y)
        seq.append((h.t_on, (tool[h.kind], 202), (tx, ty), h.kind))
    for i, (ton, src, dst, kind) in enumerate(seq):
        tp = ton - 0.75  # 从工具栏拖出
        if tp - 0.4 <= t < ton + 0.1:
            prev = seq[i-1][2] if i else (300, 150)
            if t < tp:
                u = eio((t - (tp - 0.4)) / 0.4); return (*lerp2(prev, src, u), False, None)
            u = eio((t - tp) / 0.75)
            p = lerp2(src, dst, u)
            return (p[0], p[1], True, kind)
        if ton + 0.1 <= t < (seq[i+1][0] - 1.15 if i + 1 < len(seq) else 13.2):
            return (dst[0], dst[1], False, None)
    if 12.6 <= t < 13.6:
        u = eio((t - 12.6) / 0.6); p = lerp2(seq[-1][2], (234, 202), u)
        return (p[0], p[1], 13.2 < t < 13.4, None)
    return None

CURSOR = ["#.......", "##......", "#c#.....", "#cc#....", "#ccc#...", "#cccc#..", "#ccccc#.", "#cc####.",
          "#c#.....", "##......", "#......."]
def draw_cursor(d, x, y, down):
    for j, row in enumerate(CURSOR):
        for i, c in enumerate(row):
            if c == '#': rect(d, x + i * .8, y + j * .8, x + i * .8 + .8, y + j * .8 + .8, PAL['dark'])
            elif c == 'c': rect(d, x + i * .8, y + j * .8, x + i * .8 + .8, y + j * .8 + .8, PAL['cream'] if not down else PAL['hold'])

def draw_design_layer(d, t):
    if not (3.0 <= t < 14.2): return
    a = min(eout((t - 3.0) / 0.5), eout((14.2 - t) / 0.4))
    yoff = (1 - a) * 30
    # 工具栏
    rect(d, 120, 192 + yoff, 264, 212 + yoff, hx('#1c0b24'))
    rect(d, 141, 201 + yoff, 159, 205 + yoff, PAL['hold'])
    d.polygon([C((184, 208 + yoff)), C((198, 208 + yoff)), C((198, 196 + yoff))], fill=PAL['cream'])
    d.polygon([C((230, 196 + yoff)), C((230, 208 + yoff)), C((240, 202 + yoff))],
              fill=PAL['hold'] if 13.2 < t < 13.6 else PAL['cream'])
    cur = design_cursor(t)
    if cur:
        x, y, down, kind = cur
        if down and kind:
            if kind == 'volume':
                pts = [(x - 12, y + 7), (x + 6, y + 7), (x + 6, y - 10)]
                d.polygon([C(p) for p in pts], outline=PAL['cream'])
            else:
                for i in range(int(x - 6), int(x + 6), 2):
                    rect(d, i, y - 2, i + 1, y - 1, PAL['cream']); rect(d, i, y + 2, i + 1, y + 3, PAL['cream'])
        # 选中框
        for k in ROUTE:
            h = ROUTE[k]
            if 0 <= t - h.t_on < 0.9:
                cx, cy = (196, 145) if k == 'V' else (h.x, h.y)
                r = 9 if k == 'V' else max(5, h.w / 2 + 3)
                for sx in (-1, 1):
                    for sy in (-1, 1):
                        rect(d, cx + sx * r - (2 if sx > 0 else 0), cy + sy * r - (0 if sy < 0 else 0.6), cx + sx * r + (0 if sx > 0 else 2) , cy + sy * r + (0.6 if sy < 0 else 0), PAL['cream'])
                        rect(d, cx + sx * r - (0.6 if sx > 0 else 0), cy + sy * r - (2 if sy > 0 else 0), cx + sx * r + (0 if sx > 0 else 0.6), cy + sy * r + (0 if sy > 0 else 2), PAL['cream'])
        draw_cursor(d, x, y, down)

# ------------------------------------------------------------------ 场景构建
SPECS = []
def build():
    global TR, TS, DUR
    def say_t(a): return next(e['t'] for e in EVENTS if e['kind'] == 'say' and e['actor'] is a)
    A = script_A(14.0); A.t_out = A.tl.t
    B = script_B(say_t(A) + 0.8); B.t_out = B.tl.t
    Cc = script_C(say_t(B) + 0.8); Cc.t_out = Cc.tl.t
    TR = say_t(Cc) + 5.4; TS = TR + 9.5; DUR = TS + 10.0
    for a in (A, B, Cc): a.active_end = say_t(a) + 1.2
    FOLLOW.extend([A, B, Cc])
    # 评价卡在 NPC 说完感想后弹出（与动画事件对齐）
    says = [e['t'] for e in EVENTS if e['kind'] == 'say']
    for i, st_ in enumerate(sorted(says)):
        REVIEWS[i] = (st_ + 0.6,) + REVIEWS[i][1:]
    # 观众反应由攀爬者的动作事件驱动（游戏内同理：广播“完攀/脱落/动态”事件给围观 NPC）
    L = lambda a, n: label_t(a, n)
    tA_top, tB_fall, tC_dyno = L(A, '完攀！'), L(B, '脱落！'), L(Cc, '动态 DYNO!')
    s1 = Spectator(LOOK_S1, 112, 'sit', [(tA_top + .2, tA_top + 3, 'clap'), (tB_fall + .1, tB_fall + 1.8, 'gasp'),
                                         (tC_dyno + .5, tC_dyno + 3.2, 'clap')])
    s2 = Spectator(LOOK_S2, 262, 'stand', [(L(A, '伸手抓高点'), tA_top - .3, 'point'), (tA_top, tA_top + 2.4, 'cheer'),
                                           (L(B, '抓斜面点 Sloper'), tB_fall - .1, 'point'), (tB_fall, tB_fall + 1.8, 'gasp'),
                                           (L(Cc, '挂脚跟 Heel hook'), tC_dyno - .1, 'point'), (tC_dyno + .2, tC_dyno + 3, 'cheer')])
    s3 = Spectator(LOOK_S3, 300, 'hips', [(tA_top + .3, tA_top + 2.2, 'clap'), (tB_fall + .15, tB_fall + 2.1, 'gasp'),
                                          (tC_dyno + .3, tC_dyno + 2.8, 'cheer')])
    SPECS.extend([s1, s2, s3])
    for s, dt in ((s2, .1), (s3, .2), (s1, .3)):
        EVENTS.append(dict(t=tB_fall + dt, kind='emote', actor=s, glyph='!', dur=1.0))
    EVENTS.append(dict(t=tC_dyno + .4, kind='emote', actor=s2, glyph='heart', dur=1.2))
    EVENTS.append(dict(t=tA_top + .3, kind='emote', actor=s3, glyph='star', dur=1.2))
    # 镜头（基础关键帧；攀爬期间由自动跟随接管）
    cam_key(0, 192, 108, 1.0); cam_key(3.0, 192, 108, 1.0); cam_key(4.0, 190, 132, 1.25)
    cam_key(13.0, 190, 132, 1.25); cam_key(15.0, 165, 140, 1.25)
    cam_key(30.0, 185, 140, 1.25); cam_key(TR - 2.0, 185, 140, 1.25); cam_key(TR, 192, 120, 1.0)
    cam_key(TS, 192, 120, 1.0); cam_key(DUR, 175, 125, 1.15)
    return A, B, Cc

def stamina_fn(a, drain):
    def f(t):
        # 上墙后体力下降，落地恢复
        st = a.state(t)
        on_wall = t - a.t_in
        if st and st['hip'][1] < 160:
            return clamp(1 - (on_wall - 4) * drain, 0.08, 1)
        return clamp(1 - max(on_wall - 4, 0) * drain * 0.8, 0.1, 1)
    return f

# ------------------------------------------------------------------ 渲染
def render_world(t, actor_list, ev_time=None, holds_t=None, dog=None):
    ht = t if holds_t is None else holds_t
    img = make_bg(min(t, 78)).copy()
    d = ImageDraw.Draw(img)
    for h in DECOR: draw_hold(d, h, ht)
    for k, h in ROUTE.items(): draw_hold(d, h, ht)
    # 前景人物：先观众后攀爬者
    for a, ta in actor_list:
        st = a.state(ta)
        if st is None: continue
        P = build_pose(st, a.look, ta, a.seed)
        draw_person(d, P, a.look)
    if dog: draw_dog(d, *dog)
    draw_particles(d, t, ev_time)
    draw_emotes(d, t, ev_time)
    return img, d

def crop_box(cx, cy, z, shake=(0, 0)):
    cw, ch = W / z, H / z
    cx = clamp(cx + shake[0], cw / 2, W - cw / 2); cy = clamp(cy + shake[1], ch / 2, H - ch / 2)
    return (cx - cw / 2, cy - ch / 2, cx + cw / 2, cy + ch / 2)

def shake_at(t):
    sx = sy = 0.0
    for i, e in enumerate(EVENTS):
        if e['kind'] == 'shake':
            age = t - e['t']
            if 0 <= age < e['dur']:
                k = (1 - age / e['dur']) * e['amp']
                sx += math.sin(age * 90 + i) * k; sy += math.cos(age * 77 + i) * k
    return (sx, sy)

def frame(t, A, B, Cc):
    # ---- 回放对比段
    if TR <= t < TS:
        return frame_replay(t, A, B)
    cx, cy, z = camera(t)
    cb = crop_box(cx, cy, z, shake_at(t))
    actors = [(s, t) for s in SPECS] + [(a, t) for a in (A, B, Cc)]
    dog = None
    if t >= TS:
        dx = 9 + min(t - TS - 1.0, 7.0) * 12 if t > TS + 1.0 else -30
        dog = (dx, t, TS + 1.0 < t < TS + 8.0, 1)
    img, d = render_world(t, actors, dog=dog)
    draw_design_layer(d, t)
    out = img.resize((OW, OH), Image.NEAREST, box=tuple(v * K for v in cb))
    ui, ud = draw_ui(t, cb, 'play')
    phase_banners(ud, t)
    for a, drain in ((A, 0.05), (B, 0.09), (Cc, 0.06)):
        draw_climber_card(ud, t, a, stamina_fn(a, drain))
    for rv in REVIEWS: draw_review(ud, t, rv)
    draw_says(ud, t, cb)
    draw_pops(ud, t, cb)
    if 3.0 < t < 14.0: design_panel(ud, t)
    if t >= TS + 0.5: summary_panel(ud, t - TS + 68.0)
    out = composite(out, ui)
    return fade(out, t)

def phase_banners(d, t):
    draw_banner(d, t, 0.6, 3.2, '暮光岩馆 · 实机演示', '概念原型 / 程序化攀爬动画')
    draw_banner(d, t, 3.3, 6.0, '路线设计', '拖拽岩点到墙上')
    draw_banner(d, t, 14.0, 16.4, '开放攀爬', '顾客陆续到馆')

def design_panel(d, t):
    a = min(eout((t - 3.0) / 0.5), eout((14.0 - t) / 0.4))
    x = UW + 10 - 230 * a
    box(d, x, 120, x + 210, 268)
    text(d, (x + 12, 132), '新路线：落日', F16, PAL['hold'])
    placed = sum(1 for h in ROUTE.values() if t >= h.t_on)
    text(d, (x + 12, 158), '岩点 %d / 10' % placed, F16)
    diff = ['—', 'V0', 'V1', 'V1', 'V2', 'V2', 'V3', 'V3', 'V3', 'V3', 'V3'][placed]
    text(d, (x + 12, 182), '预估难度  ' + diff, F16)
    text(d, (x + 12, 206), '适合：中级 / 力量型', F16)
    text(d, (x + 12, 236), '▶ 开放路线', F16, PAL['hold'] if t > 13.2 else PAL['cream'])

def summary_panel(d, t):
    a = eout((t - 68.5) / 0.6)
    x = UW + 10 - 380 * a
    box(d, x, 90, x + 360, 400, border=PAL['hold'], bw=3)
    text(d, (x + 18, 104), '今日结算 · 路线「落日」', F24, PAL['hold'])
    rows = [('到访顾客', '3 人'), ('完攀率', '2 / 3'), ('平均评价', '3.7 ★'), ('今日收入', '+¥100')]
    for i, (k, v) in enumerate(rows):
        if t > 69.0 + i * 0.35:
            text(d, (x + 22, 150 + i * 32), k, F16)
            text(d, (x + 200, 150 + i * 32), v, F16, PAL['hold'] if i == 3 else PAL['cream'])
    if t > 70.6:
        text(d, (x + 22, 290), '玩家反馈', F16, PAL['hold'])
        tags = [('三角块好评', PAL['teal']), ('动态够爽', PAL['teal']), ('斜面点太滑', PAL['red'])]
        xx = x + 22
        for i, (tg, col) in enumerate(tags):
            if t > 71.0 + i * 0.3:
                w = d.textlength(tg, font=F16) + 16
                d.rectangle((xx, 316, xx + w, 340), fill=col + (255,))
                text(d, (xx + 8, 320), tg, F16)
                xx += w + 8
    if t > 72.4:
        text(d, (x + 22, 356), '建议：斜面点旁加一个过渡脚点', F16, PAL['cream'])

def label_t(a, name):
    return next(tt for tt, x in a.tl.labels if x == name)

def frame_replay(t, A, B):
    u = t - TR
    a_in = min(eout(u / 0.5), eout((TS - t) / 0.5))
    # 同一段动作慢放对比：阿岩换脚上三角块 vs 小橙去抓斜面点
    rate = 0.75
    ta = label_t(A, '换脚上三角块') - 0.2 + u * rate
    tb = label_t(B, '抬脚') - 0.4 + u * rate
    halves = []
    for a, ta_ in ((A, ta), (B, tb)):
        img, d = render_world(t, [(a, ta_)], ev_time={a: ta_}, holds_t=99)
        hw_, hh_ = OW // 2 - 4, OH - 140
        lh_ = 92.0; lw_ = lh_ * hw_ / hh_
        cx, cy = 176, 138
        bx = (cx - lw_ / 2, cy - lh_ / 2, cx + lw_ / 2, cy + lh_ / 2)
        halves.append(img.resize((hw_, hh_), Image.NEAREST, box=tuple(v * K for v in bx)))
    out = make_bg(t).resize((OW, OH), Image.NEAREST, box=(0, 0, CW, CH * 0.45)).copy()
    out.paste(halves[0], (0, 0)); out.paste(halves[1], (OW // 2 + 4, 0))
    dd = ImageDraw.Draw(out)
    dd.rectangle((OW // 2 - 4, 0, OW // 2 + 4, OH - 140), fill=PAL['dark'])
    dd.rectangle((0, OH - 140, OW, OH), fill=PAL['dark'])
    ui = Image.new('RGBA', (UW, UH), (0, 0, 0, 0)); d = ImageDraw.Draw(ui); d.fontmode = '1'
    # 播放条（参考效果图3）
    d.polygon([(24, UH - 44), (24, UH - 22), (42, UH - 33)], fill=PAL['cream'] + (255,))
    prog = clamp(u / 9.5, 0, 1)
    d.rectangle((58, UH - 34, UW - 30, UH - 32), fill=hx('#6a5a8a') + (255,))
    d.rectangle((58, UH - 34, 58 + (UW - 88) * prog, UH - 32), fill=PAL['cream'] + (255,))
    d.rectangle((54 + (UW - 88) * prog, UH - 40, 64 + (UW - 88) * prog, UH - 26), fill=PAL['hold'] + (255,))
    text(d, (UW - 30, UH - 60), '0.75x 慢放', F16, anchor='ra')
    ly = UH - 116
    box(d, 12, ly, 260, ly + 32); text(d, (24, ly + 8), '阿岩 · 踩三角块上移', F16, PAL['hold'])
    box(d, UW // 2 + 12, ly, UW // 2 + 280, ly + 32); text(d, (UW // 2 + 24, ly + 8), '小橙 · 伸手去抓斜面点', F16, PAL['hold'])
    draw_banner(d, t, TR + 0.2, TR + 3.1, '回放对比', '同一条路线 · 不同顾客的选择')
    if u > 4.0:
        k = eout((u - 4.0) / 0.5)
        box(d, UW / 2 - 300, 14, UW / 2 + 300, 60, border=PAL['hold'], bw=2)
        text(d, (UW / 2, 37), '设计洞察：斜面点在新手视线里“看起来最近” → 诱导脱落', F16, anchor='mm')
    out = composite(out, ui)
    if a_in < 1:
        out = Image.blend(Image.new('RGB', out.size, PAL['dark']), out, a_in)
    return out

def composite(base, ui):
    big = ui.resize((OW, OH), Image.NEAREST)
    base = base.convert('RGBA')
    base.alpha_composite(big)
    return base.convert('RGB')

def fade(img, t):
    a = 1.0
    if t < 0.6: a = t / 0.6
    if t > DUR - 1.5: a = max(0, (DUR - t) / 1.5)
    if a < 1: img = Image.blend(Image.new('RGB', img.size, (0, 0, 0)), img, a)
    return img

def main():
    A, B, Cc = build()
    args = sys.argv[1:]
    outdir = os.path.dirname(os.path.abspath(__file__))
    if args and args[0] == 'stills':
        for ts in args[1:]:
            tt = float(ts)
            frame(tt, A, B, Cc).save(os.path.join(outdir, 'still_%05.1f.png' % tt))
        return
    if args and args[0] == 'check':
        check(A, B, Cc); return
    out = os.path.join(os.path.dirname(outdir), '暮光岩馆_实机演示.mp4')
    ff = imageio_ffmpeg.get_ffmpeg_exe()
    p = subprocess.Popen([ff, '-y', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-s', '%dx%d' % (OW, OH), '-r', str(FPS),
                          '-i', '-', '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', '-pix_fmt', 'yuv420p',
                          '-movflags', '+faststart', out], stdin=subprocess.PIPE, stderr=subprocess.DEVNULL)
    n = int(DUR * FPS)
    for i in range(n):
        t = i / FPS
        p.stdin.write(frame(t, A, B, Cc).tobytes())
        if i % 150 == 0: print('frame', i, '/', n, flush=True)
    p.stdin.close(); p.wait()
    print('done', out)

def check_smooth(actors, dt=1/30):
    """逐帧检查：关节（肘/膝）相对末端的突变 = 翻面/抽搐。"""
    worst = []
    for a in actors:
        t, prev = a.t_in, None
        while t < a.t_out:
            st = a.state(t)
            if st:
                P = build_pose(st, a.look, t, a.seed)
                if prev:
                    for L in LIMBS:
                        jm = dist(P[L+'_j'], prev[L+'_j']); em = dist(P[L], prev[L]); rm = dist(P[L+'_root'], prev[L+'_root'])
                        excess = jm - max(em, rm)
                        if excess > 1.2: worst.append((excess, a.look.name, round(t, 2), L))
                prev = P
            t += dt
    worst.sort(reverse=True)
    print('关节突变帧数:', len(worst)); [print(w) for w in worst[:15]]

def check(A, B, Cc):
    check_smooth([A, B, Cc] + SPECS)
    """检查：已接触的手脚是否都够得着（防止穿帮）。"""
    for a in (A, B, Cc):
        s = a.look.s
        bad = 0
        for t, st, _ in a.tl.keys:
            P = build_pose(dict(st, shake=0, breathe=0), a.look, t, 0)
            for L in LIMBS:
                if st['att'][L]:
                    miss = dist(P[L], st[L])
                    if miss > 0.8:
                        bad += 1
                        lab = [x for tt, x in a.tl.labels if tt <= t + 1e-6]
                        print('%s t=%.2f %s miss %.1f hip=(%.1f,%.1f) tgt=%s [%s]' % (a.look.name, t, L, miss, st['hip'][0], st['hip'][1], tuple(round(v,1) for v in st[L]), lab[-1] if lab else ''))
        print(a.look.name, 'keys', len(a.tl.keys), 'violations', bad)

if __name__ == '__main__':
    main()
