"""
=============================================================================
Lecture 4 · 脚本：性能阶梯总表（讲义 §1）
=============================================================================

【这个脚本要回答的问题】
    同一段着色计算，从 Python 循环一路走到 GPU，每一级快多少？提升来自哪里？
    为什么答案取决于着色器本身？（内存受限 vs 计算受限）

【运行】python3 ladder.py        （约 25 秒，会先调用 make 编译 C++）
【输出】两张表：简单着色器和重计算着色器。

【边界】
    - 这是这台机器上的真实计时，你的结果会不同；
    - Python 和 numpy 用 64 位浮点，C++ 和 GPU 用 32 位浮点，这里只看数量级；
    - 没有 swiftc（不是 macOS）时跳过 GPU 这一行。
"""

import importlib.util
import os
import re
import shutil
import subprocess
import time

import numpy as np

import course_path
course_path.use("lecture01", "lecture02")
import console
import image_io
import plot2d

HERE = os.path.dirname(os.path.abspath(__file__))
L1 = os.path.join(os.path.dirname(HERE), "lecture01")
WIDTH, HEIGHT = 3840, 2160


def load_l1_shaders():
    """
    载入第 1 讲脚本 06 里的两个着色函数。

    【为什么这么麻烦】文件名以数字开头（06_cpu_vs_gpu.py），不能用普通的 import 语句，
        所以用 importlib 按路径加载。
    【返回】那个模块对象
    """
    spec = importlib.util.spec_from_file_location("cpu_vs_gpu", os.path.join(L1, "06_cpu_vs_gpu.py"))
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def run_binary(name, *args):
    """
    运行一个 C++ 版本，解析它打印的每片元耗时和校验和。

    【参数】name：out/ 下的可执行文件名；args：命令行参数
    【返回】(ns, checksum)
    """
    path = os.path.join(course_path.out_dir(), name)
    out = subprocess.run([path, *map(str, args)], capture_output=True, text=True, check=True).stdout
    return float(re.search(r"ns_per_fragment ([\d.]+)", out).group(1)), float(re.search(r"checksum ([\d.]+)", out).group(1))


def run_gpu():
    """
    编译并运行 01b_ladder_gpu.swift。

    【返回】字典 {"gpu_light": ns, "gpu_heavy": ns, ...}；不可用时返回空字典
    【边界】没有 swiftc 或者运行失败都返回空字典，不影响其他结果。
    """
    if shutil.which("swiftc") is None:
        return {}
    binary = os.path.join(course_path.out_dir(), "ladder_gpu")
    build = subprocess.run(["swiftc", "-O", os.path.join(HERE, "01b_ladder_gpu.swift"), "-o", binary], capture_output=True, text=True)
    if build.returncode != 0:
        print("  （swiftc 编译失败，跳过 GPU）\n" + build.stderr[:400])
        return {}
    out = subprocess.run([binary], capture_output=True, text=True).stdout
    os.remove(binary)
    result = {}
    for line in out.splitlines():
        parts = line.split()
        if len(parts) == 2 and parts[0].startswith("gpu_") and parts[0] != "gpu_name":
            result[parts[0]] = float(parts[1])
    return result


def heavy_python(count):
    """
    重计算着色器的纯 Python 版本。

    【参数】count：处理多少个片元（纯 Python 很慢，只算一小部分再除）
    【返回】结果列表
    """
    out = []
    for i in range(count):
        cx = (i % WIDTH) / WIDTH * 3.0 - 2.2
        cy = (i // WIDTH) / HEIGHT * 2.4 - 1.2
        zr = zi = 0.0
        for _ in range(128):
            t = zr * zr - zi * zi + cx
            v = 2.0 * zr * zi + cy
            zr = -4.0 if t < -4.0 else (4.0 if t > 4.0 else t)
            zi = -4.0 if v < -4.0 else (4.0 if v > 4.0 else v)
        out.append(zr * zr + zi * zi)
    return out


def heavy_numpy(count):
    """
    重计算着色器的 numpy 版本（批量，单线程，float32，和 C++ 相同的精度）。

    【参数】count：片元数
    【返回】结果数组
    """
    ids = np.arange(count)
    cx = ((ids % WIDTH) / WIDTH * 3.0 - 2.2).astype(np.float32)
    cy = ((ids // WIDTH) / HEIGHT * 2.4 - 1.2).astype(np.float32)
    zr, zi = np.zeros(count, dtype=np.float32), np.zeros(count, dtype=np.float32)
    for _ in range(128):
        t = zr * zr - zi * zi + cx
        v = 2.0 * zr * zi + cy
        zr, zi = np.clip(t, -4.0, 4.0), np.clip(v, -4.0, 4.0)
    return zr * zr + zi * zi


def best_ns(fn, count, reps):
    """跑 fn(count) 若干次，返回最快一次的每片元纳秒数。"""
    best = float("inf")
    for _ in range(reps):
        t0 = time.perf_counter()
        fn(count)
        best = min(best, time.perf_counter() - t0)
    return best / count * 1e9


def print_ladder(title, entries):
    """
    打印一张阶梯表。

    【参数】title：标题；entries：[(写法, 每片元纳秒, 说明), ...]
    """
    console.print_header(title)
    rows, previous = [], None
    first = entries[0][1]
    for label, ns, why in entries:
        rows.append([label, f"{ns:.3f} ns", f"{first / ns:,.0f} 倍", "" if previous is None else f"{previous / ns:.2f} 倍",
                     f"{1e9 / (ns * WIDTH * HEIGHT):,.1f} fps", why])
        previous = ns
    console.print_table(["写法", "每片元", "比 Python 快", "比上一级快", "4K 全屏", "这一级多了什么"], rows, align=["<", ">", ">", ">", ">", "<"])


def draw_chart(light, heavy):
    """
    把两张表画成对数坐标的横向柱状图。

    【为什么用对数坐标】最快和最慢差了几千倍，线性坐标下除了 Python 什么都看不见。
    【参数】light、heavy：print_ladder 用的 entries
    【输出】out/01_ladder.png
    """
    panels = []
    names = {"Python 循环": "Python", "numpy（批量，单线程）": "numpy", "C++ -O0（不优化）": "C++ -O0",
             "C++ -O2，禁止向量化": "C++ -O2 scalar", "C++ -O2（自动向量化）": "C++ -O2 SIMD", "C++ -O2，8 线程": "C++ 8 threads", "GPU（Metal）": "GPU"}
    for title, entries in [("simple shader: ns per fragment", light), ("heavy shader: ns per fragment", heavy)]:
        # 横轴是 log10(纳秒)，从 0.1 ns 画起；柱子左边留出写名字的位置
        c = plot2d.Canvas2D((-3.2, 4.8), (0.0, len(entries) + 0.3), 500, 240)
        for tick in range(-1, 4):
            c.line((tick, 0.0), (tick, len(entries) - 0.1), plot2d.COLORS["light"], 1.0)
            c.text((tick + 0.03, 0.02), f"{10.0 ** tick:g}", plot2d.COLORS["gray"], 1)
        for k, (label, ns, _) in enumerate(entries):
            y = len(entries) - k - 0.15
            x = float(np.log10(ns))
            c.polygon([(-1.2, y - 0.62), (x, y - 0.62), (x, y - 0.12), (-1.2, y - 0.12)], plot2d.COLORS["teal"] if "GPU" not in label else plot2d.COLORS["orange"], 0.75)
            c.text((-3.15, y - 0.5), names.get(label, label), plot2d.COLORS["black"], 1)
            c.text((x + 0.05, y - 0.5), f"{ns:.3g}", plot2d.COLORS["black"], 1)
        panels.append(plot2d.label(c.image(), title))
    image_io.save_png(os.path.join(course_path.out_dir(), "01_ladder.png"), image_io.image_grid(panels, gap=8))


def main():
    subprocess.run(["make", "-s", "ladder"], cwd=HERE, check=True)
    module = load_l1_shaders()
    gpu = run_gpu()
    threads = 8

    n = 300_000
    normals, positions = module.make_fragments(n)
    t_python = min(module._timed(module.shade_python, normals, positions) for _ in range(3)) / n * 1e9
    t_numpy = min(module._timed(module.shade_batch, normals, positions) for _ in range(10)) / n * 1e9
    light = [("Python 循环", t_python, "解释执行，每个数字都是一个对象"), ("numpy（批量，单线程）", t_numpy, "编译好的循环")]
    checks = []
    for label, name, args, why in [
        ("C++ -O0（不优化）", "01_ladder_O0", (1,), "编译了，但每个变量都老老实实进内存"),
        ("C++ -O2，禁止向量化", "01_ladder_novec", (1,), "优化器：内联、寄存器分配"),
        ("C++ -O2（自动向量化）", "01_ladder_O2", (1,), "再加上 SIMD：一次算 4 个 float"),
        (f"C++ -O2，{threads} 线程", "01_ladder_O2", (threads,), "再加上多核"),
    ]:
        ns, checksum = run_binary(name, *args)
        light.append((label, ns, why))
        checks.append(checksum)
    if "gpu_light" in gpu:
        light.append(("GPU（Metal）", gpu["gpu_light"], "几千个执行单元"))
    print_ladder("简单着色器（Lambert × 棋盘格）：每片元读 20~24 字节，写 4 字节", light)
    print(f"\n  校验：4 个 C++ 版本结果的校验和 = {[round(c, 3) for c in checks]}（相同，说明算的是同一件事）")
    # C++ 版本每个片元读 5 个 float（法线 3 个、位置 2 个）写 1 个，共 24 字节；GPU 版本读两个 packed_float3 写 1 个，共 28 字节
    for label, ns, _ in light[-2:]:
        amount = 28 if "GPU" in label else 24
        print(f"  {label}：每片元读写 {amount} 字节，相当于每秒读写 {amount / ns:.0f} GB 内存")

    heavy = [("Python 循环", best_ns(heavy_python, 5_000, 2), "解释执行"), ("numpy（批量，单线程）", best_ns(heavy_numpy, 300_000, 3), "编译好的循环")]
    heavy_checks = []
    for label, name, args, why in [
        ("C++ -O0（不优化）", "01_ladder_O0", (1, "heavy"), "每个变量都进内存"),
        ("C++ -O2，禁止向量化", "01_ladder_novec", (1, "heavy"), "优化器"),
        ("C++ -O2（自动向量化）", "01_ladder_O2", (1, "heavy"), "SIMD：一次算 4 个"),
        (f"C++ -O2，{threads} 线程", "01_ladder_O2", (threads, "heavy"), "多核"),
    ]:
        ns, checksum = run_binary(name, *args)
        heavy.append((label, ns, why))
        heavy_checks.append(checksum)
    if "gpu_heavy" in gpu:
        heavy.append(("GPU（Metal）", gpu["gpu_heavy"], "几千个执行单元"))
    print()
    print_ladder("重计算着色器（128 次迭代）：几乎不读内存，每片元只写 4 字节", heavy)
    print(f"\n  校验：C++ 版本结果的校验和 = {[round(c, 3) for c in heavy_checks]}", end="")
    if "gpu_heavy_checksum" in gpu:
        print(f"；GPU = {gpu['gpu_heavy_checksum']:.3f}（差 {abs(gpu['gpu_heavy_checksum'] / heavy_checks[0] - 1.0) * 100:.2f}%：GPU 可能用融合乘加，这个迭代又会放大舍入差异）")
    else:
        print()
    draw_chart(light, heavy)
    print("\n  观察：")
    print("    1. 同一份代码，-O0 和 -O2 可以差十倍。C++ -O0 甚至可能比 numpy 还慢。**永远不要用 -O0 的结果谈性能。**")
    print("    2. 简单着色器上，8 线程 C++ 和 GPU 差不多快，看读写速率就知道：它们都撞上了内存带宽的上限（这台机器标称约 273 GB/s）。")
    print("    3. 多核的加速比也说明了这一点：简单着色器 8 线程只快 2 倍，重计算着色器能快 7 倍左右。")
    print("    4. 重计算着色器上 GPU 才显出真正的优势：这才是在比计算能力。一个基准测出来的可能根本不是你以为的东西。")
    print("  输出 out/01_ladder.png")

if __name__ == "__main__":
    main()
