# -*- coding: utf-8 -*-
import tkinter as tk
import math

# ================= 参数 =================
W, H = 1200, 760
AXIS_Y = 430
LENS_X = 620
F0 = 130.0
OBJ_H = 110.0
MIN_U, MAX_U = 80.0, 520.0

# ================= 配色 =================
BG_TOP  = (16, 24, 40)
BG_BOT  = (6, 8, 16)
GRID    = '#141c2c'
AXIS    = '#3a4d68'
TICK    = '#5a7a9c'
LENS_FILL = '#0e2a44'
LENS_EDGE = '#5ac8ff'
RAY1    = '#ffc450'
RAY2    = '#54daff'
RAY1_DIM = '#8a6a28'
RAY2_DIM = '#2a6a80'
OBJ_BODY = '#ffda98'
OBJ_HI   = '#fff4d0'
OBJ_DARK = '#b8864a'
FLAME1, FLAME2, FLAME3 = '#ff8a2e', '#ffc65c', '#fff8d8'
VIR_BODY = '#5a90c8'
VIR_HI   = '#b0d8f8'
VIR_DARK = '#2a4a6a'
VFLAME1, VFLAME2, VFLAME3 = '#4a9adf', '#7ac0ef', '#d0eaff'
SCREEN_BG = '#141c2c'
SCREEN_EDGE = '#8a9cc0'
TEXT = '#e0e8f4'
SUB  = '#8a9cb8'
MEAS = '#4a6a8c'

FONT_T = ('Microsoft YaHei', 20, 'bold')
FONT_N = ('Microsoft YaHei', 16)
FONT_S = ('Microsoft YaHei', 14)
FONT_B = ('Microsoft YaHei', 17, 'bold')


def lerp_color(c1, c2, t):
    r = int(c1[0] + (c2[0] - c1[0]) * t)
    g = int(c1[1] + (c2[1] - c1[1]) * t)
    b = int(c1[2] + (c2[2] - c1[2]) * t)
    return '#%02x%02x%02x' % (r, g, b)


def bezier(p0, p1, p2, n=24):
    pts = []
    for i in range(n + 1):
        t = i / n
        mt = 1 - t
        x = mt * mt * p0[0] + 2 * mt * t * p1[0] + t * t * p2[0]
        y = mt * mt * p0[1] + 2 * mt * t * p1[1] + t * t * p2[1]
        pts.append((x, y))
    return pts


class App:
    def __init__(self, root):
        self.root = root
        root.title('透镜成像 · 光路演示')
        root.configure(bg='#060810')
        root.resizable(False, False)

        self.canvas = tk.Canvas(root, width=W, height=H,
                                bg='#060810', highlightthickness=0)
        self.canvas.pack()

        self.lens_type = 'convex'   # convex 凸透镜 / concave 凹透镜
        self.u = 340.0
        self.screen_x = LENS_X + 400
        self.drag = None

        self.canvas.bind('<Button-1>', self.on_press)
        self.canvas.bind('<B1-Motion>', self.on_drag)
        self.canvas.bind('<ButtonRelease-1>', self.on_release)
        self.canvas.bind('<Motion>', self.on_move)
        root.bind_all('<Key>', self.on_key)

        self.draw()

    # ================= 交互 =================
    def on_press(self, e):
        ox = LENS_X - self.u
        if abs(e.x - ox) < 40 and AXIS_Y - OBJ_H - 50 < e.y < AXIS_Y + 35:
            self.drag = 'obj'
        elif abs(e.x - self.screen_x) < 30 and abs(e.y - AXIS_Y) < 200:
            self.drag = 'screen'

    def on_drag(self, e):
        if self.drag == 'obj':
            self.u = max(MIN_U, min(MAX_U, LENS_X - e.x))
            self.draw()
        elif self.drag == 'screen':
            self.screen_x = max(LENS_X + 100, min(W - 40, e.x))
            self.draw()

    def on_release(self, e):
        self.drag = None
        self.canvas.config(cursor='')

    def on_move(self, e):
        if self.drag:
            return
        ox = LENS_X - self.u
        over_obj = abs(e.x - ox) < 40 and AXIS_Y - OBJ_H - 50 < e.y < AXIS_Y + 35
        over_scr = abs(e.x - self.screen_x) < 30 and abs(e.y - AXIS_Y) < 200
        self.canvas.config(cursor='hand2' if (over_obj or over_scr) else '')

    def on_key(self, e):
        k = e.keysym
        if k in ('c', 'C'):
            self.lens_type = 'concave' if self.lens_type == 'convex' else 'convex'
            self.draw()
        elif k == '1':
            self.u = 420.0
            self.draw()
        elif k == '2':
            self.u = 190.0
            self.draw()
        elif k == '3':
            self.u = 90.0
            self.draw()

    # ================= 工具 =================
    def dashed(self, x1, y1, x2, y2, color, width=1, dash=10, gap=7):
        length = math.hypot(x2 - x1, y2 - y1)
        if length < 1:
            return
        ux = (x2 - x1) / length
        uy = (y2 - y1) / length
        pos = 0
        while pos < length:
            end = min(pos + dash, length)
            self.canvas.create_line(x1 + ux * pos, y1 + uy * pos,
                                    x1 + ux * end, y1 + uy * end,
                                    fill=color, width=width)
            pos += dash + gap

    # ================= 绘制 =================
    def draw(self):
        c = self.canvas
        c.delete('all')

        # 背景渐变
        steps = 40
        for i in range(steps):
            col = lerp_color(BG_TOP, BG_BOT, i / (steps - 1))
            y1 = H * i / steps
            y2 = H * (i + 1) / steps + 1
            c.create_rectangle(0, y1, W, y2, fill=col, outline='')

        # 网格
        for x in range(0, W, 40):
            c.create_line(x, 0, x, H, fill=GRID)
        for y in range(0, H, 40):
            c.create_line(0, y, W, y, fill=GRID)

        # 主光轴
        self.dashed(20, AXIS_Y, W - 20, AXIS_Y, AXIS, 1, 14, 10)

        # 焦点刻度
        for k in (-2, -1, 1, 2):
            fx = LENS_X + k * F0
            c.create_line(fx, AXIS_Y - 8, fx, AXIS_Y + 8, fill=TICK, width=2)
            name = ('2F' if abs(k) == 2 else 'F') + ("'" if k > 0 else '')
            c.create_text(fx, AXIS_Y + 20, text=name, fill=TICK, font=FONT_S)

        # 光心
        c.create_oval(LENS_X - 4, AXIS_Y - 4, LENS_X + 4, AXIS_Y + 4,
                      fill='#7ad4ff', outline='')

        # 透镜
        self.draw_lens()

        # 物理计算
        f = F0 if self.lens_type == 'convex' else -F0
        u = self.u
        Px, Py = LENS_X - u, AXIS_Y - OBJ_H
        Ax, Ay = LENS_X, AXIS_Y - OBJ_H
        Ox, Oy = LENS_X, AXIS_Y

        xi = yi = None
        if abs(u - f) > 6:
            xi = u * f / (u - f)
            yi = -OBJ_H * f / (u - f)
            if abs(xi) > 5000 or abs(yi) > 2500:
                xi = yi = None

        # 光线 1：平行主光轴
        slope1 = OBJ_H / f
        end_x = W + 80
        c.create_line(Px, Py, Ax, Ay, fill=RAY1, width=2)
        c.create_line(Ax, Ay, end_x, Ay + slope1 * (end_x - Ax),
                      fill=RAY1, width=2)

        # 光线 2：过光心
        dx, dy = Ox - Px, Oy - Py
        L = math.hypot(dx, dy)
        if L > 0.5:
            ux, uy = dx / L, dy / L
            c.create_line(Px, Py, Ox, Oy, fill=RAY2, width=2)
            c.create_line(Ox, Oy, Ox + ux * 2000, Oy + uy * 2000,
                          fill=RAY2, width=2)

        # 虚像时反向延长
        if xi is not None and xi < 0:
            ix = LENS_X + xi
            need = Ax - ix + 40
            if need > 0:
                self.dashed(Ax, Ay, Ax - need, Ay - slope1 * need,
                            RAY1_DIM, 1, 8, 6)
            need2 = Ox - ix + 40
            if need2 > 0 and L > 0.5:
                self.dashed(Ox, Oy, Ox - ux * need2, Oy - uy * need2,
                            RAY2_DIM, 1, 8, 6)

        # 光屏
        self.draw_screen()

        # 实像落在光屏上的光斑
        if xi is not None and xi > 0 and abs(LENS_X + xi - self.screen_x) < 30:
            cyi = AXIS_Y - yi / 2
            rh = abs(yi) / 2 + 10
            for i in range(4, 0, -1):
                rr = rh * i / 4
                t = (5 - i) / 4 * 0.4
                col = lerp_color((30, 24, 8), (255, 200, 100), t)
                c.create_oval(self.screen_x - rr * 0.6, cyi - rr,
                              self.screen_x + rr * 0.6, cyi + rr,
                              fill=col, outline='')

        # 物蜡烛
        self.draw_candle(Px, AXIS_Y, OBJ_H, False)

        # 像
        if xi is not None:
            ix_s = LENS_X + xi
            if abs(yi) < 2000:
                self.draw_candle(ix_s, AXIS_Y, yi, xi < 0)
                tag = '虚像' if xi < 0 else '实像'
                tag_col = '#82c8ff' if xi < 0 else '#ffc864'
                ty = AXIS_Y - yi
                ty = ty - 42 if yi > 0 else ty + 36
                c.create_rectangle(ix_s - 28, ty - 13, ix_s + 28, ty + 13,
                                   fill='#0e1626', outline=tag_col)
                c.create_text(ix_s, ty, text=tag, fill=tag_col, font=FONT_S)

        # 物距标注
        self.draw_measure()

        # HUD
        self.draw_hud(xi, yi)

        # 底部提示
        c.create_text(24, H - 24, anchor='w',
                      text='拖动蜡烛改变物距  ·  拖动光屏  ·  C 切换凸/凹透镜  ·  1/2/3 预设物距',
                      fill=SUB, font=FONT_S)

    def draw_lens(self):
        c = self.canvas
        hh, w = 145, 10
        cx, cy = LENS_X, AXIS_Y
        if self.lens_type == 'convex':
            bulge = 40
            left  = bezier((cx - w, cy - hh), (cx - w - bulge, cy), (cx - w, cy + hh))
            right = bezier((cx + w, cy + hh), (cx + w + bulge, cy), (cx + w, cy - hh))
        else:
            bulge = 22
            left  = bezier((cx - w, cy - hh), (cx - w + bulge, cy), (cx - w, cy + hh))
            right = bezier((cx + w, cy + hh), (cx + w - bulge, cy), (cx + w, cy - hh))
        flat = []
        for p in left + right:
            flat.extend(p)
        c.create_polygon(flat, fill=LENS_FILL, outline=LENS_EDGE, width=2)
        c.create_line(cx, cy - hh + 12, cx, cy + hh - 12,
                      fill='#4a9ac0', dash=(4, 6), width=1)

    def draw_screen(self):
        c = self.canvas
        x, cy, h, w = self.screen_x, AXIS_Y, 320, 14
        c.create_line(x, cy + h / 2, x, cy + h / 2 + 30, fill='#6a7a9a', width=3)
        c.create_line(x - 26, cy + h / 2 + 30, x + 26, cy + h / 2 + 30,
                      fill='#6a7a9a', width=3)
        c.create_rectangle(x - w / 2, cy - h / 2, x + w / 2, cy + h / 2,
                           fill=SCREEN_BG, outline=SCREEN_EDGE, width=2)
        for i in range(1, 6):
            yy = cy - h / 2 + h * i / 6
            c.create_line(x - w / 2 + 2, yy, x + w / 2 - 2, yy, fill='#1c2838')

    def draw_candle(self, cx, base_y, h, is_virtual):
        c = self.canvas
        if is_virtual:
            body, hi, dark = VIR_BODY, VIR_HI, VIR_DARK
            f1, f2, f3 = VFLAME1, VFLAME2, VFLAME3
        else:
            body, hi, dark = OBJ_BODY, OBJ_HI, OBJ_DARK
            f1, f2, f3 = FLAME1, FLAME2, FLAME3

        sign = 1 if h >= 0 else -1
        Hh = abs(h)
        if Hh < 8:
            c.create_oval(cx - 5, base_y - 5, cx + 5, base_y + 5,
                          fill=body, outline='')
            return

        w = max(8, min(26, Hh * 0.20))
        body_h = Hh * 0.68
        flame_h = Hh * 0.32
        top_y = base_y - sign * body_h
        x1, x2 = cx - w / 2, cx + w / 2
        y1, y2 = min(base_y, top_y), max(base_y, top_y)

        # 烛身
        c.create_rectangle(x1, y1, x2, y2, fill=body, outline=dark, width=1)
        hw = max(2, w * 0.22)
        c.create_rectangle(x1 + 2, y1 + 3, x1 + 2 + hw, y2 - 3, fill=hi, outline='')
        c.create_rectangle(x2 - 2 - hw, y1 + 3, x2 - 2, y2 - 3, fill=dark, outline='')

        # 顶面
        if sign == 1:
            c.create_oval(x1, y1 - 3, x2, y1 + 3, fill=hi, outline=dark)
        else:
            c.create_oval(x1, y2 - 3, x2, y2 + 3, fill=dark, outline=dark)

        # 烛芯
        wick_h = flame_h * 0.18
        wick_top = top_y - sign * wick_h
        c.create_line(cx, top_y, cx, wick_top, fill='#3a2a1a', width=2)

        # 火焰
        fw = max(6, w * 0.85)
        fcy = top_y - sign * (wick_h + flame_h * 0.5)
        c.create_oval(cx - fw / 2, fcy - flame_h / 2,
                      cx + fw / 2, fcy + flame_h / 2, fill=f1, outline='')
        c.create_oval(cx - fw * 0.32, fcy - flame_h * 0.32,
                      cx + fw * 0.32, fcy + flame_h * 0.32, fill=f2, outline='')
        c.create_oval(cx - fw * 0.15, fcy - flame_h * 0.15,
                      cx + fw * 0.15, fcy + flame_h * 0.15, fill=f3, outline='')

    def draw_measure(self):
        c = self.canvas
        y = 640
        x1, x2 = LENS_X - self.u, LENS_X
        c.create_line(x1, y, x2, y, fill=MEAS, width=1)
        c.create_line(x1, y - 7, x1, y + 7, fill=MEAS, width=1)
        c.create_line(x2, y - 7, x2, y + 7, fill=MEAS, width=1)
        c.create_polygon(x1, y, x1 + 8, y - 4, x1 + 8, y + 4, fill=MEAS, outline='')
        c.create_polygon(x2, y, x2 - 8, y - 4, x2 - 8, y + 4, fill=MEAS, outline='')
        mid = (x1 + x2) / 2
        c.create_rectangle(mid - 50, y + 10, mid + 50, y + 32,
                           fill='#0e1626', outline='#3a5070')
        c.create_text(mid, y + 21, text='u = %.0f px' % self.u,
                      fill='#8aa8c8', font=FONT_S)

    def draw_hud(self, xi, yi):
        c = self.canvas
        x0, y0, pw, ph = 24, 20, 440, 186
        c.create_rectangle(x0, y0, x0 + pw, y0 + ph,
                           fill='#0c1422', outline='#2a4060', width=1)

        title = '凸透镜 · 会聚' if self.lens_type == 'convex' else '凹透镜 · 发散'
        dot_col = '#6ecdff' if self.lens_type == 'convex' else '#c494ff'
        c.create_oval(x0 + 18, y0 + 18, x0 + 30, y0 + 30, fill=dot_col, outline='')
        c.create_text(x0 + 40, y0 + 24, anchor='w',
                      text=title, fill=TEXT, font=FONT_T)
        c.create_line(x0 + 16, y0 + 44, x0 + pw - 16, y0 + 44, fill='#223450')

        y = y0 + 58
        c.create_text(x0 + 18, y, anchor='w',
                      text='物距  u = %.0f px   ( %.2f f )' % (self.u, self.u / F0),
                      fill=SUB, font=FONT_N)
        y += 30

        if xi is not None:
            m = abs(yi) / OBJ_H
            c.create_text(x0 + 18, y, anchor='w',
                          text='像距  v = %+.0f px    放大率 |m| = %.2f' % (xi, m),
                          fill=SUB, font=FONT_N)
            y += 30

            if self.lens_type == 'concave':
                nature, ncol = '正立 · 缩小 · 虚像（物同侧）', '#c494ff'
            elif abs(self.u - 2 * F0) < 5:
                nature, ncol = '倒立 · 等大 · 实像', '#ffc864'
            elif self.u > 2 * F0:
                nature, ncol = '倒立 · 缩小 · 实像', '#ffc864'
            elif self.u > F0:
                nature, ncol = '倒立 · 放大 · 实像', '#ffc864'
            else:
                nature, ncol = '正立 · 放大 · 虚像（物同侧）', '#c494ff'

            c.create_text(x0 + 18, y, anchor='w',
                          text=nature, fill=ncol, font=FONT_B)
        else:
            c.create_text(x0 + 18, y, anchor='w',
                          text='u = f ：折射光平行射出，不成像',
                          fill='#ff966e', font=FONT_B)

    def run(self):
        self.root.mainloop()


if __name__ == '__main__':
    root = tk.Tk()
    App(root).run()