# -*- coding: utf-8 -*-
# 凹凸透镜成像 2.5D 终极版 v5.0 - 无穿模单体透镜
# Python 3.8 兼容 | 单文件 | 无第三方库
import tkinter as tk
import math
import random

try:
    import winsound
    HAS_SOUND = True
except Exception:
    HAS_SOUND = False

W, H = 1500, 850
BG = "#0b0e14"
FG = "#e6edf3"
SUB = "#7d8590"

# ========== 音效 ==========
def beep(freq=800, dur=80):
    if HAS_SOUND:
        try:
            winsound.Beep(freq, dur)
        except Exception:
            pass

def beep_type(conv):
    if conv:
        beep(1200, 60)
        beep(1600, 40)
    else:
        beep(600, 60)
        beep(400, 40)

def beep_warn():
    beep(200, 120)

# ========== 3D 数学 ==========
def rot(p, ax, ay):
    x, y, z = p
    ca, sa = math.cos(ax), math.sin(ax)
    y, z = y * ca - z * sa, y * sa + z * ca
    cb, sb = math.cos(ay), math.sin(ay)
    x, z = x * cb + z * sb, -x * sb + z * cb
    return x, y, z

def proj(p, ax, ay, scale, d=6.0):
    x, y, z = rot(p, ax, ay)
    f = d / (d + z) if (d + z) > 0.1 else 0.1
    cx = W * 0.42
    return cx + x * scale * f, H / 2 - y * scale * f, z

def solve(u, f):
    if abs(u - f) < 1e-6:
        return None
    v = u * f / (u - f)
    m = -v / u
    return v, m

# ========== 球面透镜模型 ==========
def sag(rho, Rcur):
    c = 1.0 / Rcur
    d = 1.0 - (c * rho) ** 2
    if d < 0:
        d = 0.0
    return (c * rho * rho) / (1.0 + math.sqrt(d))

def lens_mesh(conv, R=1.5, tc=0.26, nseg=24, nring=6):
    if conv:
        R1, R2 = 3.0, -3.0
        tc = 0.26
    else:
        R1, R2 = -3.0, 3.0
        tc = 0.10

    pts = []
    a = R
    for side in (-1, 1):
        Rcur = R1 if side == -1 else R2
        zface = (-tc / 2.0) if side == -1 else (tc / 2.0)
        for i in range(nring + 1):
            rho = a * i / nring
            s = sag(rho, Rcur)
            z = zface + s if side == -1 else zface - s
            for j in range(nseg):
                th = 2 * math.pi * j / nseg
                x = rho * math.cos(th)
                y = rho * math.sin(th)
                pts.append((x, y, z, side, i, j))
    return pts, nseg, nring

# ========== 粒子 ==========
class Particle:
    def __init__(self, x, y, color):
        self.x = x
        self.y = y
        self.vx = random.uniform(-4, 4)
        self.vy = random.uniform(-5, -1)
        self.life = 35
        self.color = color
        self.size = random.uniform(2, 6)

    def update(self):
        self.x += self.vx
        self.y += self.vy
        self.vy += 0.18
        self.life -= 1
        return self.life > 0

# ========== 主程序 ==========
class App:
    def __init__(self, root):
        self.root = root
        root.title("凹凸透镜成像 2.5D 终极版 v5.0")
        root.geometry("%dx%d" % (W, H))
        root.configure(bg=BG)

        self.ax = -0.28
        self.ay = 0.55
        self.scale = 155
        self.drag = False
        self.lx = self.ly = 0

        self.shake = 0
        self.flash = 0
        self.particles = []
        self.last_conv = True

        self.ltype = tk.StringVar(value="conv")
        self.u = tk.DoubleVar(value=3.0)
        self.fabs = tk.DoubleVar(value=1.2)
        self.hobj = tk.DoubleVar(value=0.9)
        self.anim_t = 0
        self.playing = True

        # ---- UI ----
        top = tk.Frame(root, bg="#161b22", height=46)
        top.pack(fill=tk.X)
        top.pack_propagate(False)

        tk.Label(top, text="透镜:", bg="#161b22", fg=FG).pack(side=tk.LEFT, padx=(12, 2))
        tk.Radiobutton(top, text="凸", variable=self.ltype, value="conv",
                       bg="#161b22", fg=FG, selectcolor="#222",
                       command=self.on_type_change).pack(side=tk.LEFT)
        tk.Radiobutton(top, text="凹", variable=self.ltype, value="conc",
                       bg="#161b22", fg=FG, selectcolor="#222",
                       command=self.on_type_change).pack(side=tk.LEFT)

        tk.Label(top, text=" 物距u", bg="#161b22", fg=SUB).pack(side=tk.LEFT)
        tk.Scale(top, from_=0.4, to=6.0, resolution=0.05, orient=tk.HORIZONTAL,
                 variable=self.u, bg="#161b22", fg=FG, troughcolor="#222",
                 highlightthickness=0, length=150,
                 command=lambda _: self.on_slide()).pack(side=tk.LEFT)

        tk.Label(top, text=" |f|", bg="#161b22", fg=SUB).pack(side=tk.LEFT)
        tk.Scale(top, from_=0.5, to=2.5, resolution=0.05, orient=tk.HORIZONTAL,
                 variable=self.fabs, bg="#161b22", fg=FG, troughcolor="#222",
                 highlightthickness=0, length=120,
                 command=lambda _: self.redraw()).pack(side=tk.LEFT)

        tk.Label(top, text=" 物高", bg="#161b22", fg=SUB).pack(side=tk.LEFT)
        tk.Scale(top, from_=0.3, to=1.6, resolution=0.05, orient=tk.HORIZONTAL,
                 variable=self.hobj, bg="#161b22", fg=FG, troughcolor="#222",
                 highlightthickness=0, length=110,
                 command=lambda _: self.redraw()).pack(side=tk.LEFT)

        tk.Button(top, text="暂停", bg="#21262d", fg="#58a6ff", relief=tk.FLAT,
                  command=self.toggle).pack(side=tk.LEFT, padx=8)
        tk.Button(top, text="复位", bg="#21262d", fg=SUB, relief=tk.FLAT,
                  command=self.reset_view).pack(side=tk.LEFT)

        tk.Label(top, text="左键拖=旋转 | 滚轮=缩放 | 点击=爆粒子 | R=复位",
                 bg="#161b22", fg=SUB).pack(side=tk.RIGHT, padx=12)

        self.c = tk.Canvas(root, bg=BG, highlightthickness=0)
        self.c.pack(fill=tk.BOTH, expand=True)

        self.info = tk.Label(root, text="", bg="#161b22", fg="#ffa657", anchor="w")
        self.info.pack(fill=tk.X, side=tk.BOTTOM)

        self.c.bind("<Button-1>", self.down)
        self.c.bind("<B1-Motion>", self.move)
        self.c.bind("<MouseWheel>", self.wheel)
        self.c.bind("<ButtonRelease-1>", self.up)
        root.bind("r", lambda e: self.reset_view())
        root.bind("<Key>", self.on_key)

        self.redraw()
        self.tick()

    # ---- 事件 ----
    def on_key(self, e):
        if e.char == ' ':
            self.toggle()

    def on_type_change(self):
        conv = self.ltype.get() == "conv"
        if conv != self.last_conv:
            self.flash = 14
            beep_type(conv)
            self.last_conv = conv
        self.redraw()

    def on_slide(self):
        u = self.u.get()
        fa = self.fabs.get()
        if abs(u - fa) < 0.18:
            self.shake = 18
            beep_warn()
        self.redraw()

    def toggle(self):
        self.playing = not self.playing

    def reset_view(self):
        self.ax = -0.28
        self.ay = 0.55
        self.scale = 155
        self.redraw()

    def down(self, e):
        self.drag = True
        self.lx = e.x
        self.ly = e.y

    def up(self, e):
        self.drag = False
        for _ in range(22):
            self.particles.append(Particle(
                e.x, e.y,
                random.choice(["#ffd166", "#ff6b9b", "#58a6ff", "#7ee787", "#d2a8ff"])))

    def move(self, e):
        if self.drag:
            self.ay += (e.x - self.lx) * 0.008
            self.ax += (e.y - self.ly) * 0.008
            self.ax = max(-1.4, min(1.4, self.ax))
            self.lx = e.x
            self.ly = e.y
            self.redraw()

    def wheel(self, e):
        self.scale = max(80, min(320, self.scale + (1 if e.delta > 0 else -1) * 8))
        self.redraw()

    # ---- 绘图工具 ----
    def P(self, x, y, z=0):
        px, py, _ = proj((x, y, z), self.ax, self.ay, self.scale)
        if self.shake > 0:
            px += random.randint(-self.shake, self.shake)
            py += random.randint(-self.shake, self.shake)
        return px, py

    def line3(self, a, b, fill, w=2, dash=None, tag="s"):
        p1 = self.P(*a)
        p2 = self.P(*b)
        self.c.create_line(p1[0], p1[1], p2[0], p2[1],
                           fill=fill, width=w, dash=dash, tags=tag)

    def dot(self, p, color, r=3, tag="s"):
        x, y = self.P(*p)
        self.c.create_oval(x - r, y - r, x + r, y + r,
                           fill=color, outline="", tags=tag)

    # ---- 画透镜（无穿模 / 单体通透版）----
    def draw_lens(self, conv):
        mesh, nseg, nring = lens_mesh(conv)
        col = "#79c0ff" if conv else "#d2a8ff"
        edge_col = "#388bfd" if conv else "#a371f7"
        body_col = "#1e4a7a" if conv else "#4a2a7a"

        # 1) 仅画右面（正面）半透明封口填充 —— 消灭双面重影，无侧壁不穿模
        right_ring = []
        for p in mesh:
            if p[4] == nring and p[3] == 1:
                right_ring.append(self.P(p[0], p[1], p[2]))
        if len(right_ring) > 2:
            flat = []
            for pt in right_ring:
                flat.extend([pt[0], pt[1]])
            self.c.create_polygon(flat, fill=body_col, outline=edge_col, width=1, tags="s")

        # 2) 经线网格（纯线框，通透感，不填充）
        for j in range(0, nseg, 3):
            for side in (-1, 1):
                line = []
                for p in mesh:
                    if p[3] == side and p[5] == j:
                        line.append(self.P(p[0], p[1], p[2]))
                if len(line) > 1:
                    self.c.create_line(line, fill=col, width=1, smooth=True, tags="s")

        # 3) 边缘亮线（勾勒左右轮廓）
        for side in (-1, 1):
            ring = []
            for p in mesh:
                if p[3] == side and p[4] == nring:
                    ring.append(self.P(p[0], p[1], p[2]))
            if len(ring) > 1:
                ring.append(ring[0])
                self.c.create_line(ring, fill=edge_col, width=2, tags="s")

        # 4) 中间赤道线（增强立体感）
        eq = []
        for p in mesh:
            if p[4] == 0:
                eq.append(self.P(p[0], p[1], p[2]))
        if len(eq) > 1:
            self.c.create_line(eq, fill=col, width=1, dash=(2, 2), tags="s")

    # ---- 右侧对照图 ----
    def draw_sideview(self, sol, conv, u, f, h):
        sx = int(W * 0.72)
        sy = int(H * 0.15)
        c = self.c

        c.create_line(sx - 20, 10, sx - 20, H - 40, fill="#30363d", dash=(4, 3), tags="ref")
        c.create_text(sx + 130, 20, text="侧视对照图", fill=FG,
                      font=("Microsoft YaHei", 14, "bold"), tags="ref")

        ox, oy = sx + 40, sy + 250
        scale = 55

        c.create_line(ox, oy, ox + 380, oy, fill="#3a4250", width=1, dash=(4, 3), tags="ref")
        c.create_line(ox + 180, oy - 120, ox + 180, oy + 120,
                       fill="#79c0ff" if conv else "#d2a8ff", width=3, tags="ref")
        c.create_text(ox + 185, oy + 130, text="透镜", fill=SUB, tags="ref")

        ff = abs(f) * scale
        c.create_oval(ox + 180 - ff - 3, oy - 3, ox + 180 - ff + 3, oy + 3,
                       fill="#ff7b72", outline="", tags="ref")
        c.create_text(ox + 180 - ff, oy + 15, text="F", fill="#ff7b72", tags="ref")
        c.create_oval(ox + 180 + ff - 3, oy - 3, ox + 180 + ff + 3, oy + 3,
                       fill="#ff7b72", outline="", tags="ref")
        c.create_text(ox + 180 + ff, oy + 15, text="F'", fill="#ff7b72", tags="ref")

        obj_x = ox + 180 - u * scale
        c.create_line(obj_x, oy, obj_x, oy - h * scale, fill="#7ee787", width=3, tags="ref")
        c.create_text(obj_x, oy + 15, text="物", fill="#7ee787", tags="ref")

        if sol:
            v, m = sol
            hi = m * h
            img_x = ox + 180 + v * scale
            col = "#ffd166" if v > 0 else "#ff6b9b"
            dash = None if v > 0 else (5, 4)
            c.create_line(img_x, oy, img_x, oy - hi * scale, fill=col, width=3, dash=dash, tags="ref")
            c.create_text(img_x, oy + 15, text="像", fill=col, tags="ref")

            c.create_line(obj_x, oy - h * scale, ox + 180, oy - h * scale, fill="#58a6ff", width=1, tags="ref")
            if v > 0:
                c.create_line(ox + 180, oy - h * scale, img_x, oy - hi * scale, fill="#58a6ff", width=1, tags="ref")
            else:
                c.create_line(ox + 180, oy - h * scale, ox + 180 + v * scale, oy - hi * scale, fill="#58a6ff", width=1, dash=(4, 3), tags="ref")

            c.create_line(obj_x, oy - h * scale, img_x, oy - hi * scale, fill="#ff7b72", width=1, dash=(3, 3) if v < 0 else None, tags="ref")

            c.create_line(obj_x, oy - h * scale, ox + 180, oy, fill="#56d4dd", width=1, tags="ref")
            if v > 0:
                c.create_line(ox + 180, oy, img_x, oy - hi * scale, fill="#56d4dd", width=1, tags="ref")
            else:
                c.create_line(ox + 180, oy, ox + 350, oy, fill="#56d4dd", width=1, dash=(4, 3), tags="ref")
        else:
            c.create_text(ox + 180, oy - 140, text="u≈f 不成像", fill="#ff6b9b", tags="ref")
            c.create_line(obj_x, oy - h * scale, ox + 180, oy - h * scale, fill="#58a6ff", width=1, tags="ref")
            c.create_line(ox + 180, oy - h * scale, ox + 360, oy - h * scale, fill="#58a6ff", width=1, tags="ref")

    # ---- 主绘制 ----
    def redraw(self):
        self.c.delete("all")

        if self.flash > 0:
            self.c.create_rectangle(0, 0, W, H, fill="#ffffff", outline="", tags="fx")
            self.c.create_text(W / 2, H / 2, text="✨ LENS SWITCH ✨",
                               fill="#000", font=("Arial", 48, "bold"), tags="fx")
        if self.shake > 0:
            self.shake = max(0, self.shake - 1)
        if self.flash > 0:
            self.flash = max(0, self.flash - 1)

        u = self.u.get()
        fa = self.fabs.get()
        h = self.hobj.get()
        conv = self.ltype.get() == "conv"
        self.last_conv = conv
        f = fa if conv else -fa
        sol = solve(u, f)

        # 光轴
        self.line3((-4.2, 0, 0), (4.6, 0, 0), "#3a4250", 1, (4, 3))

        # F / 2F
        for s in (-1, 1):
            fp = s * fa
            self.dot((fp, 0, 0), "#ff7b72", 3)
            self.line3((fp, -0.12, 0), (fp, 0.12, 0), "#ff7b72", 1)
            self.dot((2 * fp, 0, 0), "#56d4dd", 3)

        # 透镜（无穿模版）
        self.draw_lens(conv)

        # 物体
        self.line3((-u, 0, 0), (-u, h, 0), "#7ee787", 3)
        self.dot((-u, h, 0), "#7ee787", 4)

        # 像 + 光路
        if sol:
            v, m = sol
            hi = m * h
            xi = v
            col = "#ffd166" if v > 0 else "#ff6b9b"
            dash = None if v > 0 else (5, 4)
            self.line3((xi, 0, 0), (xi, hi, 0), col, 3, dash)
            self.dot((xi, hi, 0), col, 4)

            if random.random() < 0.18:
                sx, sy = self.P(xi, hi, 0)
                for _ in range(6):
                    self.particles.append(Particle(sx, sy, col))

            top_obj = (-u, h, 0)
            top_img = (xi, hi, 0)
            self.line3(top_obj, (0, h, 0), "#58a6ff", 2)
            self.line3((0, h, 0), top_img, "#58a6ff", 2, (3, 2) if v < 0 else None)
            self.line3(top_obj, top_img, "#ff7b72", 2, (3, 2) if v < 0 else None)
            self.line3(top_obj, (0, 0, 0), "#56d4dd", 2)
            self.line3((0, 0, 0), top_img, "#56d4dd", 2, (3, 2) if v < 0 else None)

            nature = "实像" if v > 0 else "虚像"
            orient = "倒立" if m < 0 else "正立"
            size = "放大" if abs(m) > 1 else ("缩小" if abs(m) < 1 else "等大")
            self.info.config(
                text="u=%.2f  f=%.2f  v=%.2f  m=%.2f  → %s %s %s（像在透镜%s侧）"
                % (u, f, v, m, nature, orient, size, "右" if v > 0 else "左"))
        else:
            self.info.config(text="⚠ u≈f，不成像！出射平行光")
            top_obj = (-u, h, 0)
            self.line3(top_obj, (0, h, 0), "#58a6ff", 2)
            self.line3((0, h, 0), (4.5, h, 0), "#58a6ff", 2, (4, 3))

        # 右侧对照图
        self.draw_sideview(sol, conv, u, f, h)

        # 粒子
        for p in self.particles[:]:
            if p.update():
                self.c.create_oval(p.x - p.size, p.y - p.size,
                                    p.x + p.size, p.y + p.size,
                                    fill=p.color, outline="", tags="fx")
            else:
                self.particles.remove(p)

        self.c.create_text(14, 14, anchor="nw", fill=SUB,
                           text="ax=%.2f ay=%.2f scale=%d | 空格=暂停 R=复位"
                           % (self.ax, self.ay, int(self.scale)), tags="s")

    def tick(self):
        if self.playing:
            self.anim_t += 0.02
            self.ay += 0.001
            self.redraw()
        self.root.after(33, self.tick)

if __name__ == "__main__":
    root = tk.Tk()
    App(root)
    root.mainloop()