# -*- coding: utf-8 -*-
"""水循环 3D 精美版（黑线上移版） —— Pygame
运行：python water_cycle_3d.py
"""
import pygame, math, random, sys, os

pygame.init()
W, H = 1024, 680
FPS = 60
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("水循环 · 3D 精美版")
clock = pygame.time.Clock()

# ---------- 字体（带描边） ----------
def get_font(size, bold=False):
    cands = [
        "C:/Windows/Fonts/msyhbd.ttc" if bold else "C:/Windows/Fonts/msyh.ttc",
        "C:/Windows/Fonts/simhei.ttf",
        "C:/Windows/Fonts/simsun.ttc",
        "/System/Library/Fonts/PingFang.ttc",
        "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
    ]
    for p in cands:
        if p and os.path.exists(p):
            try: return pygame.font.Font(p, size)
            except Exception: pass
    return pygame.font.Font(None, size)

F_TITLE = get_font(34, True)
F_LABEL = get_font(18, True)
F_SMALL = get_font(14)

def draw_text(surf, text, x, y, color, font, outline=(0,0,0,180), center=False):
    base = font.render(text, True, color)
    ol = font.render(text, True, outline[:3])
    rect = base.get_rect()
    if center: rect.center = (x, y)
    else: rect.topleft = (x, y)
    ox, oy = rect.x, rect.y
    for dx, dy in [(-1,0),(1,0),(0,-1),(0,1),(-1,-1),(1,1),(-1,1),(1,-1)]:
        surf.blit(ol, (ox+dx, oy+dy))
    surf.blit(base, (ox, oy))

# ---------- 颜色 ----------
SKY_TOP    = (85, 155, 225)
SKY_MID    = (150, 200, 245)
SKY_BOT    = (235, 220, 200)
SUN        = (255, 235, 130)
CLOUD_HI   = (255, 255, 255)
CLOUD_MID  = (235, 242, 252)
CLOUD_LO   = (190, 205, 225)
SEA_TOP    = (90, 180, 240)
SEA_MID    = (45, 120, 195)
SEA_BOT    = (20, 70, 140)
GROUND_TOP = (125, 185, 100)
GROUND_MID = (95, 150, 80)
SOIL_TOP   = (150, 105, 70)
SOIL_MID   = (115, 80, 52)
SOIL_BOT   = (75, 50, 32)
MOUNT_FAR  = (150, 165, 175)
MOUNT_NEAR = (105, 130, 125)
MOUNT_SNOW = (240, 245, 250)
RIVER_TOP  = (105, 195, 245)
RIVER_SIDE = (35, 100, 170)
RAIN       = (165, 210, 255)
VAPOR      = (235, 245, 255)
GW         = (110, 195, 245)
TEXT_DARK  = (30, 40, 55)
TEXT_LIGHT = (255, 255, 255)
ARROW_W    = (220, 240, 255)
ARROW_GW   = (140, 210, 255)

# ---------- 3D 投影 ----------
FOV = 340
CAM_Y = 130

def project(x, y, z):
    if z <= 1: z = 1
    s = FOV / z
    return W/2 + x * s, H/2 - (y - CAM_Y) * s, s

# ---------- 地形参数 ----------
GROUND_Y = -60
SEA_Y    = -95
SOIL_TOP_Y = SEA_Y
SOIL_BOT_Y = -280
X_MIN, X_MAX = -480, 480
Z_MIN, Z_MAX = 240, 1300

def build_terrain():
    cells = []
    step_x = 64
    step_z = 76
    z = Z_MIN
    while z < Z_MAX:
        x = X_MIN
        while x < X_MAX:
            x2, z2 = x + step_x, z + step_z
            cx, cz = (x+x2)/2, (z+z2)/2
            is_sea = (cx > 150 and cz > 650) or (cz > 1000) or (cx > 300)
            is_river = (abs(cx) < 34 and cz < 720 and not is_sea)
            is_mountain = (cz > 950 and not is_sea and not is_river)
            cells.append({'x':x,'x2':x2,'z':z,'z2':z2,'cx':cx,'cz':cz,
                          'kind':'sea' if is_sea else ('river' if is_river else 'ground'),
                          'mountain':is_mountain})
            x += step_x
        z += step_z
    return cells

TERRAIN = build_terrain()

# ---------- 天空预渲染 ----------
def make_sky():
    sky = pygame.Surface((W, H))
    horizon = int(H * 0.55)
    for y in range(horizon):
        f = y / horizon
        if f < 0.6:
            t = f / 0.6
            c = tuple(int(SKY_TOP[i] + (SKY_MID[i]-SKY_TOP[i])*t) for i in range(3))
        else:
            t = (f - 0.6) / 0.4
            c = tuple(int(SKY_MID[i] + (SKY_BOT[i]-SKY_MID[i])*t) for i in range(3))
        pygame.draw.line(sky, c, (0, y), (W, y))
    for _ in range(40):
        x = random.randint(0, W)
        y = random.randint(0, int(horizon*0.4))
        b = random.randint(160, 220)
        sky.set_at((x, y), (b, b, b+10))
    return sky
SKY = make_sky()

# ---------- 地形绘制 ----------
def draw_terrain(surf, t):
    cells_sorted = sorted(TERRAIN, key=lambda c: -c['cz'])
    for c in cells_sorted:
        x, x2, z, z2 = c['x'], c['x2'], c['z'], c['z2']
        cx, cz = c['cx'], c['cz']
        fog = max(0.25, 1 - cz / 1800)

        if c['kind'] == 'sea':
            top_y = SEA_Y + math.sin(cx*0.018 + cz*0.022 + t*1.4) * 5
            f = (top_y - SEA_Y + 5) / 10
            base = tuple(int(SEA_TOP[i]*(1-f) + SEA_MID[i]*f) for i in range(3))
            color = tuple(int(base[i]*fog + 60*(1-fog)) for i in range(3))
        elif c['kind'] == 'river':
            top_y = GROUND_Y - 5
            color = tuple(int(RIVER_TOP[i]*fog + 80*(1-fog)) for i in range(3))
        else:
            top_y = GROUND_Y + (4 if c['mountain'] else 0)
            if c['mountain']:
                base = MOUNT_NEAR
                if cz > 1100:
                    base = MOUNT_SNOW
            else:
                base = GROUND_TOP
            color = tuple(int(base[i]*fog + 90*(1-fog)) for i in range(3))

        p1 = project(x,  top_y, z)
        p2 = project(x2, top_y, z)
        p3 = project(x2, top_y, z2)
        p4 = project(x,  top_y, z2)
        pygame.draw.polygon(surf, color, [p1[:2], p2[:2], p3[:2], p4[:2]])

        if z == Z_MIN:
            if c['kind'] == 'sea':
                side = tuple(int(SEA_BOT[i]*fog) for i in range(3))
            elif c['kind'] == 'river':
                side = tuple(int(RIVER_SIDE[i]*fog) for i in range(3))
            else:
                side = tuple(int(GROUND_MID[i]*fog) for i in range(3))
            b1 = project(x, SOIL_TOP_Y, z)
            b2 = project(x2, SOIL_TOP_Y, z)
            pygame.draw.polygon(surf, side, [p4[:2], p1[:2], b1[:2], b2[:2]])

        # 最前土层剖面 + 黑线（已上移）
        if z < Z_MIN + 150:
            s1 = project(x, SOIL_TOP_Y, z)
            s2 = project(x2, SOIL_TOP_Y, z)
            s3 = project(x2, SOIL_BOT_Y, z)
            s4 = project(x, SOIL_BOT_Y, z)
            for i in range(1, 4):
                f = i / 4
                y_mid = SOIL_TOP_Y + (SOIL_BOT_Y - SOIL_TOP_Y) * f
                m1 = project(x, y_mid, z); m2 = project(x2, y_mid, z)
                sc = tuple(int(SOIL_TOP[j]*(1-f) + SOIL_BOT[j]*f) for j in range(3))
                pygame.draw.polygon(surf, sc, [m1[:2], m2[:2], s3[:2], s4[:2]])
            # 黑线上移 8 单位
            ln1 = project(x, SOIL_TOP_Y + 8, z)
            ln2 = project(x2, SOIL_TOP_Y + 8, z)
            pygame.draw.line(surf, (50, 35, 25), ln1[:2], ln2[:2], 2)

# ---------- 3D 云 ----------
class Cloud3D:
    def __init__(self, x, y, z, scale=1.0):
        self.x, self.y, self.z = x, y, z
        self.scale = scale
        self.puffs = [(random.uniform(-55,55), random.uniform(-16,16),
                       random.uniform(24,42)) for _ in range(8)]
        self.rain_timer = random.randint(200, 500)
        self.raining = False
    def update(self):
        self.x += 0.28
        if self.x > 600: self.x = -600
        self.rain_timer -= 1
        if self.rain_timer <= 0:
            self.raining = not self.raining
            self.rain_timer = random.randint(280, 560) if self.raining else random.randint(200, 400)
    def draw(self, surf):
        for dx, dy, r in self.puffs:
            sx, sy, s = project(self.x + dx*self.scale, self.y + dy*self.scale - 6, self.z)
            rr = int(r * s * self.scale)
            if rr < 2: continue
            pygame.draw.circle(surf, CLOUD_LO, (int(sx+3), int(sy+5)), rr)
        for dx, dy, r in self.puffs:
            sx, sy, s = project(self.x + dx*self.scale, self.y + dy*self.scale, self.z)
            rr = int(r * s * self.scale)
            if rr < 2: continue
            pygame.draw.circle(surf, CLOUD_MID, (int(sx), int(sy)), rr)
        for dx, dy, r in self.puffs:
            sx, sy, s = project(self.x + dx*self.scale - 4, self.y + dy*self.scale - 6, self.z)
            rr = int(r * s * self.scale * 0.55)
            if rr < 1: continue
            pygame.draw.circle(surf, CLOUD_HI, (int(sx), int(sy)), rr)

# ---------- 3D 粒子 ----------
class Particle3D:
    def __init__(self, x, y, z, vx, vy, vz, r, color, life, glow=False):
        self.x, self.y, self.z = x, y, z
        self.vx, self.vy, self.vz = vx, vy, vz
        self.r = r; self.color = color
        self.life = life; self.max_life = life
        self.glow = glow
    def update(self):
        self.x += self.vx; self.y += self.vy; self.z += self.vz
        self.life -= 1
        return self.life > 0
    def draw(self, surf):
        t = self.life / self.max_life
        sx, sy, s = project(self.x, self.y, self.z)
        rr = max(1, int(self.r * s))
        if self.glow:
            for k in range(2, 0, -1):
                a = int(80 * t / k)
                gr = rr + k*2
                tmp = pygame.Surface((gr*2, gr*2), pygame.SRCALPHA)
                pygame.draw.circle(tmp, (*self.color, a), (gr, gr), gr)
                surf.blit(tmp, (int(sx-gr), int(sy-gr)))
        a = int(230 * t)
        tmp = pygame.Surface((rr*2, rr*2), pygame.SRCALPHA)
        pygame.draw.circle(tmp, (*self.color, a), (rr, rr), rr)
        surf.blit(tmp, (int(sx-rr), int(sy-rr)))

# ---------- 太阳 ----------
def draw_sun(surf, t):
    sx, sy, _ = project(-350, 200, 700)
    for i in range(10, 0, -1):
        r = 55 + i*11 + math.sin(t*1.8+i)*5
        a = int(22*(1-i/11))
        tmp = pygame.Surface((int(r*2),int(r*2)),pygame.SRCALPHA)
        pygame.draw.circle(tmp,(255,230,150,a),(int(r),int(r)),int(r))
        surf.blit(tmp,(int(sx-r),int(sy-r)))
    pygame.draw.circle(surf, SUN, (int(sx), int(sy)), 46)
    pygame.draw.circle(surf, (255,250,220), (int(sx-12), int(sy-12)), 20)

# ---------- 3D 箭头 ----------
def draw_arrow_3d(surf, x, y, z, dx, dy, dz, length, color, width=3):
    x2, y2, z2 = x + dx*length, y + dy*length, z + dz*length
    p1 = project(x, y, z); p2 = project(x2, y2, z2)
    if p1[2] <= 0 or p2[2] <= 0: return
    lw = max(1, int(width * p2[2] * 0.35))
    pygame.draw.line(surf, color, p1[:2], p2[:2], lw)
    ang = math.atan2(p2[1]-p1[1], p2[0]-p1[0])
    head = 12 * p2[2] * 0.4
    for da in (math.pi*0.78, -math.pi*0.78):
        hx = p2[0] + math.cos(ang+da)*head
        hy = p2[1] + math.sin(ang+da)*head
        pygame.draw.line(surf, color, p2[:2], (hx, hy), max(1, lw-1))

# ---------- 标签 ----------
def label_3d(surf, text, x, y, z, color=TEXT_DARK, font=F_SMALL):
    sx, sy, s = project(x, y, z)
    if s <= 0.05: return
    draw_text(surf, text, int(sx), int(sy), color, font, center=True)

# ---------- 主循环 ----------
def main():
    t = 0.0
    clouds = [
        Cloud3D(-280, 140, 900, 1.15),
        Cloud3D(220, 160, 1150, 1.0),
        Cloud3D(-60, 190, 1350, 0.9),
        Cloud3D(400, 130, 800, 1.1),
    ]
    particles = []

    while True:
        for e in pygame.event.get():
            if e.type == pygame.QUIT or (e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE):
                pygame.quit(); sys.exit()

        t += 1/FPS

        # 蒸发
        if random.random() < 0.5:
            particles.append(Particle3D(
                random.uniform(180, 420), SEA_Y + 5, random.uniform(700, 1100),
                random.uniform(-0.2, 0.2), random.uniform(0.5, 1.1), random.uniform(-0.3, 0.3),
                random.uniform(3, 6), VAPOR, random.randint(90, 160), glow=True
            ))
        # 降水
        for c in clouds:
            if c.raining and random.random() < 0.8:
                particles.append(Particle3D(
                    c.x + random.uniform(-55, 55), c.y - 25, c.z + random.uniform(-30, 30),
                    random.uniform(-0.3, 0.3), random.uniform(-7, -4.5), 0,
                    random.uniform(1.8, 2.8), RAIN, 55, glow=False
                ))
        # 下渗
        if random.random() < 0.6:
            particles.append(Particle3D(
                random.uniform(-380, 380), GROUND_Y, random.uniform(Z_MIN, Z_MIN+220),
                0, random.uniform(-2.2, -1.2), 0,
                random.uniform(2, 3.5), (70, 150, 230), random.randint(55, 100), glow=True
            ))
        # 地下径流
        if random.random() < 0.6:
            particles.append(Particle3D(
                random.uniform(-400, -220), SOIL_TOP_Y - random.uniform(25, 170),
                random.uniform(Z_MIN, Z_MIN+200),
                random.uniform(1.2, 2.4), 0, 0,
                random.uniform(2.5, 4.5), GW, random.randint(90, 170), glow=True
            ))
        # 水汽输送
        if random.random() < 0.08:
            particles.append(Particle3D(
                -450, random.uniform(90, 180), random.uniform(650, 1100),
                random.uniform(1.2, 2.2), 0, 0,
                4.5, VAPOR, 240, glow=True
            ))

        # 绘制
        screen.blit(SKY, (0, 0))
        draw_sun(screen, t)

        for c in sorted(clouds, key=lambda c: -c.z):
            c.update()
            c.draw(screen)

        draw_terrain(screen, t)

        particles.sort(key=lambda p: -p.z)
        alive = []
        for p in particles:
            if p.update():
                alive.append(p)
                p.draw(screen)
        particles = alive

        # 水汽输送箭头
        for i in range(4):
            z = 720 + i * 90
            x_off = -380 + ((t*55 + i*70) % 760)
            draw_arrow_3d(screen, x_off, 150, z, 1, 0, 0, 160, ARROW_W, 2)
        label_3d(screen, "水汽输送", -240, 200, 820, (235, 245, 255), F_SMALL)

        # 地下径流箭头
        for i in range(3):
            z = Z_MIN + 50 + i * 60
            x_off = -300 + ((t*40 + i*60) % 320)
            draw_arrow_3d(screen, x_off, SOIL_TOP_Y - 90, z, 1, 0, 0, 130, ARROW_GW, 3)
        label_3d(screen, "地下径流", 80, SOIL_TOP_Y - 150, Z_MIN + 110, (190, 225, 255), F_SMALL)

        # 河川径流箭头
        for i in range(5):
            z = 320 + i * 90
            draw_arrow_3d(screen, -14, GROUND_Y + 5, z, 0, 0, 1, 70, (215, 240, 255), 2)
        label_3d(screen, "河川径流", 0, GROUND_Y + 48, 600, TEXT_DARK, F_SMALL)

        label_3d(screen, "下渗", -200, GROUND_Y - 32, Z_MIN + 40, TEXT_DARK, F_SMALL)

        # 2D 标签
        draw_text(screen, "太阳", 120, 120, TEXT_LIGHT, F_SMALL, center=True)
        draw_text(screen, "蒸发", W//2 - 60, 380, TEXT_LIGHT, F_SMALL, center=True)
        draw_text(screen, "凝结成云", W//2 + 140, 100, TEXT_DARK, F_SMALL, center=True)
        draw_text(screen, "降水", W//2 + 240, 280, TEXT_DARK, F_SMALL, center=True)
        draw_text(screen, "河流 / 海洋", W//2, H - 80, TEXT_LIGHT, F_SMALL, center=True)
        draw_text(screen, "下渗", W//2 - 260, H - 130, TEXT_DARK, F_SMALL, center=True)
        draw_text(screen, "地下径流", W//2 + 230, H - 140, TEXT_LIGHT, F_SMALL, center=True)
        draw_text(screen, "水汽输送", W//2 + 60, 165, TEXT_LIGHT, F_SMALL, center=True)

        draw_text(screen, "水循环 · 3D 精美版", W//2, 32, TEXT_LIGHT, F_TITLE, center=True)
        draw_text(screen, "ESC 退出", W - 70, H - 26, TEXT_DARK, F_SMALL)

        pygame.display.flip()
        clock.tick(FPS)

if __name__ == "__main__":
    main()