"""
=============================================================================
Lecture 4 · 脚本：C++ 版管线和 Python 版管线逐项比较（讲义 §11）
=============================================================================

【这个脚本要回答的问题】
    同一个场景、同一个算法，两种语言写的管线结果一样吗？差多快？

【运行】python3 compare_render.py        （约 5 秒）
【输出】out/09_cpp_render.png：C++ 渲染的结果；打印每个阶段的统计和逐像素差异。

【边界】
    - Python 版本批量着色，C++ 版本逐片元调用虚函数，算法相同但执行方式不同；
    - 两边的计算顺序已经尽量一致，但浮点运算顺序略有不同时，个别像素可能差 1 级（满量程 255）。
"""

import os
import re
import subprocess
import time

import numpy as np

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

HERE = os.path.dirname(os.path.abspath(__file__))
CLEAR = (0.62, 0.74, 0.86)


def run_cpp(width, height, repeat=1, out="out/09_cpp_render.png"):
    """
    运行 C++ 渲染器，解析打印出的统计。

    【参数】width、height：画面大小；repeat：重复渲染几次（取最快）；out：输出路径（相对本目录）
    【返回】字典 {统计名: 数值}
    """
    result = subprocess.run([os.path.join("out", "09_mini_rasterizer"), str(width), str(height), f"repeat={repeat}", f"out={out}"],
                            capture_output=True, text=True, check=True, cwd=HERE)
    return {k: float(v) for k, v in re.findall(r"(\w+) ([\d.]+)", result.stdout)}


def render_python(width, height):
    """
    运行第 1 讲的 Python 管线（和 C++ 版本一样，提前深度测试、背面剔除都打开）。

    【返回】(Framebuffer, Stats, 秒数)
    """
    draws, camera = mp.demo_scene()
    best, fb, st = float("inf"), None, None
    for _ in range(3):
        t0 = time.perf_counter()
        fb, st = mp.render(draws, camera, width, height, clear_color=CLEAR)
        best = min(best, time.perf_counter() - t0)
    return fb, st, best


def main():
    subprocess.run(["make", "-s", "out/09_mini_rasterizer"], cwd=HERE, check=True)
    w, h = 640, 400
    cpp = run_cpp(w, h, repeat=20)
    fb, st, t_python = render_python(w, h)

    console.print_header("1. 每个阶段的统计：两种语言写的管线数字一样吗？")
    rows = []
    mismatch = 0
    pairs = [("vertices", st.vertices), ("primitives", st.primitives), ("rejected", st.rejected), ("near_clipped", st.near_clipped),
             ("backfacing", st.backfacing), ("rasterized", st.rasterized), ("edge_tests", st.edge_tests), ("fragments", st.fragments),
             ("shaded", st.shaded), ("pixels", st.pixels)]
    for name, value in pairs:
        same = int(cpp[name]) == value
        mismatch += not same
        rows.append([name, f"{value:,}", f"{int(cpp[name]):,}", "相同" if same else f"差 {int(cpp[name]) - value:+,}"])
    console.print_table(["阶段", "Python", "C++", "比较"], rows, align=["<", ">", ">", "<"])

    console.print_header("2. 最终图像：逐像素比较")
    cpp_img = image_io.load_png(os.path.join(HERE, "out", "09_cpp_render.png"))
    py_img = image_io.to_uint8(image_io.srgb_encode(fb.color))
    diff = np.abs(cpp_img.astype(np.int64) - py_img.astype(np.int64)).max(axis=2)
    print(f"  {w}×{h} = {w * h:,} 个像素。完全相同：{int((diff == 0).sum()):,}；差 1 级：{int((diff == 1).sum()):,}；差超过 1 级：{int((diff > 1).sum()):,}（最大差 {int(diff.max())} 级）")
    image_io.save_png(os.path.join(course_path.out_dir(), "09_compare.png"), image_io.image_grid(
        [plot2d.label(py_img, "Python"), plot2d.label(cpp_img, "C++"), plot2d.label(np.clip(diff * 60, 0, 255).astype(np.uint8), "difference x60")], gap=6))

    console.print_header("3. 同一条管线差多快（这台机器上的真实计时）")
    rows = []
    t_cpp = cpp["seconds"]
    rows.append(["Python + numpy（逐三角形循环，批量着色）", f"{t_python * 1000:.1f} ms", f"{1 / t_python:.0f} fps", ""])
    rows.append(["C++ -O2（逐片元，每个片元一次虚函数调用）", f"{t_cpp * 1000:.2f} ms", f"{1 / t_cpp:.0f} fps", f"{t_python / t_cpp:.0f} 倍"])
    console.print_table(["写法", "一帧", "帧率", "快了"], rows, align=["<", ">", ">", ">"])
    print("\n  C++ 版本在不同分辨率下：")
    rows = []
    for rw, rh in [(320, 200), (640, 400), (1280, 800), (1920, 1200), (3840, 2400)]:
        r = run_cpp(rw, rh, repeat=8, out="out/_tmp.png")
        rows.append([f"{rw}×{rh}", f"{int(r['fragments']):,}", f"{r['seconds'] * 1000:.2f} ms", f"{1 / r['seconds']:.0f} fps", f"{r['seconds'] / r['fragments'] * 1e9:.1f} ns"])
    os.remove(os.path.join(HERE, "out", "_tmp.png"))
    console.print_table(["分辨率", "片元数", "一帧", "帧率", "每片元"], rows)
    print("\n  观察：C++ 版本和 Python 版本的每个阶段统计完全一致，8 位图像也逐像素相同，说明这确实是同一个算法。")
    print(f"        换一门语言，同样的算法快了约 {t_python / t_cpp:.0f} 倍，单线程就能实时渲染这个小场景。每片元约 10 纳秒，和分辨率无关。")
    print("        可是这个场景只有 3000 多个三角形，而且 4K 下只剩十几 fps。真实的游戏有几百万个三角形，这才是为什么还需要 GPU。")
    print("  输出 out/09_compare.png：Python、C++、差异（放大 60 倍）")
    # C++ 写的 PNG 没有压缩，这里用第 1 讲的编码器压缩一下，免得目录里留一个很大的文件
    image_io.save_png(os.path.join(HERE, "out", "09_cpp_render.png"), cpp_img, filter_kind=1)


if __name__ == "__main__":
    main()
