"""
凸透镜成像演示（带光屏）
- 鼠标拖动红色箭头：改变物距 u
- 鼠标拖动光屏：改变像距（光屏位置）
- 鼠标滚轮 / ← →：调节焦距 f
- ↑ ↓：调节物体高度
- Esc：退出

依赖：pip install pygame
"""

import math
import os

import pygame

# ---------------------------------------------------------------- 初始化
pygame.init()

WIDTH, HEIGHT = 1280, 720
FPS = 60

# 颜色
BG = (18, 18, 26)
GRID = (28, 28, 40)
AXIS = (80, 80, 110)
WHITE = (240, 240, 240)
GRAY = (140, 140, 160)
DARK = (60, 60, 80)
LENS_FILL = (40, 100, 180)
LENS_EDGE = (100, 180, 255)
RAY1 = (255, 210, 80)    # 平行主轴 -> 过焦点
RAY2 = (120, 240, 140)   # 过光心
RAY3 = (255, 130, 200)   # 过焦点 -> 平行主轴
OBJ_C = (255, 100, 100)
IMG_C = (140, 190, 255)
SCREEN_C = (210, 210, 230)
SCREEN_EDGE = (120, 120, 150)
FOCAL_C = (255, 200, 80)
TEXT_C = (220, 220, 240)
ACCENT = (255, 180, 80)
DIM = (100, 100, 120)

screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("凸透镜成像演示")
clock = pygame.time.Clock()


# 关键：绕过 pygame 2.6.1 SysFont 在 Windows 上的崩溃
def load_font(size, bold=False):
    paths = []
    if bold:
        paths.append(r"C:\Windows\Fonts\msyhbd.ttc")
    paths += [
        r"C:\Windows\Fonts\msyh.ttc",
        r"C:\Windows\Fonts\simhei.ttf",
        r"C:\Windows\Fonts\simsun.ttc",
        r"C:\Windows\Fonts\Deng.ttf",
    ]
    for p in paths:
        if os.path.isfile(p):
            try:
                return pygame.font.Font(p, size)
            except Exception:
                pass
    return pygame.font.Font(None, size)


font_small = load_font(15)
font_mid = load_font(18)
font_big = load_font(22)
font_title = load_font(26, bold=True)

# 场景几何
LENS_X = 640
AXIS_Y = 380
LENS_HALF_H = 200
LENS_THICK = 28

F_MIN, F_MAX = 80.0, 280.0
U_MIN, U_MAX = 60.0, 560.0
D_MIN, D_MAX = 30.0, 600.0

# 状态
focus = 180.0
obj_u = 400.0
obj_h = 110.0
screen_d = 300.0

dragging = None
drag_grab_x = 0


# ---------------------------------------------------------------- 工具
def clamp(v, lo, hi):
    return max(lo, min(hi, v))


def lens_v(u, f):
    """薄透镜成像公式：1/u + 1/v = 1/f -> v = uf/(u-f)"""
    if abs(u - f) < 1e-6:
        return float("inf")
    return u * f / (u - f)


def extend_ray(start, direction, x_end):
    dx, dy = direction
    if abs(dx) < 1e-9:
        return start
    t = (x_end - start[0]) / dx
    if t <= 0:
        return start
    return (start[0] + t * dx, start[1] + t * dy)


def draw_dashed_line(surf, start, end, color, width=2, dash=8, gap=6):
    x1, y1 = start
    x2, y2 = end
    length = math.hypot(x2 - x1, y2 - y1)
    if length < 1:
        return
    n = int(length / (dash + gap)) + 1
    for i in range(n):
        t1 = i * (dash + gap) / length
        t2 = min(1.0, (i * (dash + gap) + dash) / length)
        if t1 >= 1:
            break
        p1 = (x1 + (x2 - x1) * t1, y1 + (y2 - y1) * t1)
        p2 = (x1 + (x2 - x1) * t2, y1 + (y2 - y1) * t2)
        pygame.draw.line(surf, color, p1, p2, width)


def draw_arrow(surf, base, height, color, width=4, dashed=False):
    """画一支竖直箭头，base 在轴上，height>0 向上。"""
    tip = (base[0], base[1] - height)
    if dashed:
        draw_dashed_line(surf, base, tip, color, width)
    else:
        pygame.draw.line(surf, color, base, tip, width)

    ah = 13
    if height > 0:
        pygame.draw.polygon(surf, color, [
            tip,
            (tip[0] - ah * 0.6, tip[1] + ah),
            (tip[0] + ah * 0.6, tip[1] + ah),
        ])
    elif height < 0:
        pygame.draw.polygon(surf, color, [
            tip,
            (tip[0] - ah * 0.6, tip[1] - ah),
            (tip[0] + ah * 0.6, tip[1] - ah),
        ])


def draw_lens(surf):
    left, right = [], []
    N = 30
    for i in range(N + 1):
        t = i / N
        y = AXIS_Y - LENS_HALF_H + 2 * LENS_HALF_H * t
        norm = (y - AXIS_Y) / LENS_HALF_H
        bulge = LENS_THICK * math.sqrt(max(0.0, 1 - norm * norm))
        left.append((LENS_X - bulge, y))
        right.append((LENS_X + bulge, y))
    pts = left + right[::-1]

    lens_surf = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
    pygame.draw.polygon(lens_surf, (*LENS_FILL, 120), pts)
    surf.blit(lens_surf, (0, 0))
    pygame.draw.polygon(surf, LENS_EDGE, pts, 2)


def draw_rays(surf):
    """画三条特征光线（都在折射后走到底）。"""
    P = (LENS_X - obj_u, AXIS_Y - obj_h)
    x_end = WIDTH - 30

    # 光线1：平行主轴 -> 折射后过 F'
    L1 = (LENS_X, AXIS_Y - obj_h)
    if abs(obj_h) <= LENS_HALF_H:
        pygame.draw.line(surf, RAY1, P, L1, 2)
        F2 = (LENS_X + focus, AXIS_Y)
        direction = (F2[0] - L1[0], F2[1] - L1[1])
        end = extend_ray(L1, direction, x_end)
        pygame.draw.line(surf, RAY1, L1, end, 2)

    # 光线2：过光心，方向不变
    C = (LENS_X, AXIS_Y)
    direction2 = (C[0] - P[0], C[1] - P[1])
    end2 = extend_ray(C, direction2, x_end)
    pygame.draw.line(surf, RAY2, P, end2, 2)

    # 光线3：入射光线延长线过 F -> 折射后平行主轴
    if abs(focus - obj_u) > 1.0:
        L3_y = AXIS_Y - obj_h * focus / (focus - obj_u)
        if abs(L3_y - AXIS_Y) <= LENS_HALF_H + 5:
            L3 = (LENS_X, L3_y)
            pygame.draw.line(surf, RAY3, P, L3, 2)
            pygame.draw.line(surf, RAY3, L3, (x_end, L3_y), 2)


def draw_light_screen(surf, x):
    top = AXIS_Y - LENS_HALF_H - 30
    bottom = AXIS_Y + LENS_HALF_H + 30
    rect = pygame.Rect(x - 6, top, 12, bottom - top)
    pygame.draw.rect(surf, SCREEN_C, rect)
    pygame.draw.rect(surf, SCREEN_EDGE, rect, 2)
    pygame.draw.rect(surf, SCREEN_EDGE, (x - 4, bottom, 8, 20))
    pygame.draw.rect(surf, SCREEN_EDGE, (x - 18, bottom + 18, 36, 4))


def draw_image_on_screen(surf, screen_x):
    """在光屏上描绘像（清晰 -> 亮条；失焦 -> 弥散圆）。"""
    v = lens_v(obj_u, focus)
    if v == float("inf") or v <= 0:
        return

    # 像的末端在光屏上的位置（主光线 —— 过光心那条）
    img_tip_y = AXIS_Y + obj_h * screen_d / obj_u
    height = img_tip_y - AXIS_Y
    blur = LENS_HALF_H * abs(screen_d - v) / v

    if abs(height) < 1:
        return

    if blur < 5:
        # 清晰像：亮条
        width = 10
        y_top = min(AXIS_Y, img_tip_y)
        h = abs(height)
        r = pygame.Rect(screen_x - width // 2, y_top, width, h)
        pygame.draw.rect(surf, IMG_C, r)
        glow_surf = pygame.Surface((width + 16, h + 16), pygame.SRCALPHA)
        glow_surf.fill((*IMG_C, 60))
        surf.blit(glow_surf, (screen_x - (width + 16) // 2, y_top - 8))
    else:
        # 失焦：模糊光斑（多层叠加模拟）
        layers = 5
        base_h = abs(height)
        for i in range(layers):
            t = i / (layers - 1)
            expand = blur * t * 1.2
            alpha = int(80 * (1 - t * 0.75))
            w = 14 + expand * 2
            h = base_h + expand * 2
            y_top = min(AXIS_Y, img_tip_y) - expand
            s = pygame.Surface((int(w), int(h)), pygame.SRCALPHA)
            s.fill((*IMG_C, alpha))
            surf.blit(s, (screen_x - w / 2, y_top))


def draw_hud():
    panel = pygame.Surface((360, 210), pygame.SRCALPHA)
    panel.fill((20, 20, 32, 210))
    pygame.draw.rect(panel, DARK, panel.get_rect(), 1)
    screen.blit(panel, (20, 20))

    v = lens_v(obj_u, focus)
    m = -v / obj_u if v != float("inf") else float("inf")

    title = font_big.render("凸透镜成像", True, ACCENT)
    screen.blit(title, (34, 30))

    lines = [f"焦距 f = {focus:.0f} px", f"物距 u = {obj_u:.0f} px"]
    if v == float("inf"):
        lines.append("像距 v = ∞  不成像（平行光）")
    else:
        lines.append(f"像距 v = {v:.1f} px")
        if v > 0:
            lines.append(f"放大率 m = {abs(m):.2f}   倒立实像")
        else:
            lines.append(f"放大率 m = {abs(m):.2f}   正立虚像")
    y = 66
    for line in lines:
        screen.blit(font_small.render(line, True, TEXT_C), (34, y))
        y += 22

    # 右侧状态
    lines_r = [f"光屏距离 d = {screen_d:.0f} px"]
    color = TEXT_C
    if v != float("inf") and v > 0:
        blur = LENS_HALF_H * abs(screen_d - v) / v
        if blur < 5:
            lines_r.append("状态：清晰实像 ✓")
            color = (120, 255, 150)
        else:
            lines_r.append(f"状态：模糊（弥散圆≈{blur * 2:.0f}px）")
            color = (255, 180, 120)
    elif v != float("inf") and v < 0:
        lines_r.append("状态：虚像，光屏无像")
        color = (255, 130, 130)
    else:
        lines_r.append("状态：不成像")

    y = 66
    for i, line in enumerate(lines_r):
        c = color if i > 0 else TEXT_C
        screen.blit(font_small.render(line, True, c), (200, y))
        y += 22

    # 底部操作提示
    hints = [
        "鼠标拖动红色箭头 → 改变物距 u",
        "鼠标拖动光屏     → 改变像距 d",
        "鼠标滚轮 / ← →   → 调节焦距 f",
        "↑ ↓              → 调节物体高度",
    ]
    y = HEIGHT - 100
    for line in hints:
        screen.blit(font_small.render(line, True, DIM), (20, y))
        y += 20


def draw_scene():
    screen.fill(BG)

    for x in range(0, WIDTH, 40):
        pygame.draw.line(screen, GRID, (x, 0), (x, HEIGHT))
    for y in range(0, HEIGHT, 40):
        pygame.draw.line(screen, GRID, (0, y), (WIDTH, y))

    pygame.draw.line(screen, AXIS, (30, AXIS_Y), (WIDTH - 30, AXIS_Y), 1)

    # 焦点
    F1 = (LENS_X - focus, AXIS_Y)
    F2 = (LENS_X + focus, AXIS_Y)
    pygame.draw.circle(screen, FOCAL_C, (int(F1[0]), int(F1[1])), 5)
    pygame.draw.circle(screen, FOCAL_C, (int(F2[0]), int(F2[1])), 5)
    screen.blit(font_small.render("F", True, FOCAL_C), (F1[0] - 6, F1[1] + 12))
    screen.blit(font_small.render("F'", True, FOCAL_C), (F2[0] - 8, F2[1] + 12))

    # 光线（先画，让物体/透镜盖住）
    draw_rays(screen)

    # 物体
    obj_x = LENS_X - obj_u
    draw_arrow(screen, (obj_x, AXIS_Y), obj_h, OBJ_C, 5)
    screen.blit(font_small.render("物体", True, OBJ_C),
                (obj_x - 18, AXIS_Y - obj_h - 30))

    # 光屏
    scr_x = LENS_X + screen_d
    draw_light_screen(screen, scr_x)
    screen.blit(font_small.render("光屏", True, SCREEN_C),
                (scr_x - 16, AXIS_Y - LENS_HALF_H - 55))

    # 透镜
    draw_lens(screen)

    # 像（虚线画在原位置）
    v = lens_v(obj_u, focus)
    if v != float("inf") and v > 0:
        h_img = -v / obj_u * obj_h
        img_x = LENS_X + v
        if img_x < WIDTH - 20:
            draw_arrow(screen, (img_x, AXIS_Y), h_img, IMG_C, 3, dashed=True)
            ty = AXIS_Y + 20 if h_img < 0 else AXIS_Y - 35
            screen.blit(font_small.render("实像", True, IMG_C), (img_x - 14, ty))

    # 光屏上的像
    draw_image_on_screen(screen, scr_x)

    # HUD
    draw_hud()


# ---------------------------------------------------------------- 鼠标
def handle_mouse_down(pos):
    global dragging, drag_grab_x
    mx, my = pos
    obj_x = LENS_X - obj_u
    scr_x = LENS_X + screen_d

    if abs(mx - obj_x) < 30 and (AXIS_Y - obj_h - 30) < my < (AXIS_Y + 20):
        dragging = "obj"
        drag_grab_x = mx - obj_x
        return

    if abs(mx - scr_x) < 25 and (AXIS_Y - LENS_HALF_H - 35) < my < (AXIS_Y + LENS_HALF_H + 40):
        dragging = "screen"
        drag_grab_x = mx - scr_x
        return


def handle_mouse_move(pos):
    global obj_u, screen_d
    mx = pos[0]
    if dragging == "obj":
        target_x = mx - drag_grab_x
        obj_u = clamp(LENS_X - target_x, U_MIN, U_MAX)
    elif dragging == "screen":
        target_x = mx - drag_grab_x
        screen_d = clamp(target_x - LENS_X, D_MIN, D_MAX)


def update_cursor():
    mx, my = pygame.mouse.get_pos()
    obj_x = LENS_X - obj_u
    scr_x = LENS_X + screen_d

    on_obj = abs(mx - obj_x) < 30 and (AXIS_Y - obj_h - 30) < my < (AXIS_Y + 20)
    on_scr = abs(mx - scr_x) < 25 and (AXIS_Y - LENS_HALF_H - 35) < my < (AXIS_Y + LENS_HALF_H + 40)

    if dragging or on_obj or on_scr:
        pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_HAND)
    else:
        pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_ARROW)


# ---------------------------------------------------------------- 主循环
def main():
    global focus, obj_h, dragging

    running = True
    while running:
        clock.tick(FPS)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
                elif event.key == pygame.K_LEFT:
                    focus = clamp(focus - 5, F_MIN, F_MAX)
                elif event.key == pygame.K_RIGHT:
                    focus = clamp(focus + 5, F_MIN, F_MAX)
                elif event.key == pygame.K_UP:
                    obj_h = clamp(obj_h + 5, 30, 180)
                elif event.key == pygame.K_DOWN:
                    obj_h = clamp(obj_h - 5, 30, 180)

            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    handle_mouse_down(event.pos)
                elif event.button == 4:
                    focus = clamp(focus + 5, F_MIN, F_MAX)
                elif event.button == 5:
                    focus = clamp(focus - 5, F_MIN, F_MAX)

            elif event.type == pygame.MOUSEBUTTONUP:
                if event.button == 1:
                    dragging = None

            elif event.type == pygame.MOUSEMOTION:
                handle_mouse_move(event.pos)

            elif event.type == pygame.MOUSEWHEEL:
                focus = clamp(focus + event.y * 5, F_MIN, F_MAX)

        update_cursor()
        draw_scene()
        pygame.display.flip()

    pygame.quit()


if __name__ == "__main__":
    main()