"""
=============================================================================
Lecture 1 · 脚本 03：画一条线为什么不简单（讲义 §5）
=============================================================================

【这个脚本要回答的问题】
    1. 最直觉的算法 y = m·x + b 错在哪？（陡线断开、竖线除零）
    2. DDA 怎样修好它？代价是什么？（浮点累加的误差）
    3. Bresenham 只用整数，凭什么和"每列取最近的像素"完全一样？（穷举验证，不靠相信）
    4. 只亮或不亮的像素为什么一定有锯齿？（线其实没有面积，要给它定义宽度，再算覆盖比例）

【运行】python3 03_rasterize_lines.py        （约 1 秒）
【输出】out/03_line_fan.png、out/03_antialias.png
"""

import math
import os
import time

import numpy as np

import console
import course_path
import image_io
import raster2d


def is_connected(pixels):
    """
    判断像素序列是否 8-连通：相邻两个像素在 x、y 上都最多差 1。

    【参数】pixels：[(x, y), ...]，按走线顺序
    【返回】bool
    【边界】空列表和单个像素都算连通。
    """
    return all(abs(a[0] - b[0]) <= 1 and abs(a[1] - b[1]) <= 1 for a, b in zip(pixels, pixels[1:]))


def max_deviation(pixels, x0, y0, x1, y1):
    """
    像素中心到真实直线的最大偏差，沿"副轴"方向度量（比如缓坡线就看 y 方向差多少）。

    【参数】pixels：像素列表；x0, y0, x1, y1：端点
    【返回】浮点数；一个"每列取最近像素"的算法，这个值不会超过 0.5
    【边界】两端点相同时返回 0。
    """
    dx, dy = x1 - x0, y1 - y0
    if dx == 0 and dy == 0:
        return 0.0
    worst = 0.0
    if abs(dx) >= abs(dy):
        for x, y in pixels:
            worst = max(worst, abs(y - (y0 + dy * (x - x0) / dx)))
    else:
        for x, y in pixels:
            worst = max(worst, abs(x - (x0 + dx * (y - y0) / dy)))
    return worst


def section_naive():
    """第 1 节：不同斜率下，三种算法的像素数和连通性。"""
    console.print_header("1. 同样的端点，三种算法：像素数和有没有断开")
    cases = [("缓坡", 0, 0, 20, 7), ("45°", 0, 0, 12, 12), ("陡坡", 0, 0, 7, 20), ("竖线", 5, 0, 5, 15)]
    rows = []
    for name, x0, y0, x1, y1 in cases:
        for label, fn in [("naive", raster2d.line_naive), ("DDA", raster2d.line_dda), ("Bresenham", raster2d.line_bresenham)]:
            p = fn(x0, y0, x1, y1)
            rows.append([name, f"({x0},{y0})→({x1},{y1})", label, len(p), "连续" if is_connected(p) else "断开"])
    console.print_table(["情形", "端点", "算法", "像素数", "连通性"], rows, align=["<", "<", "<", ">", "<"])
    print("\n  观察：naive 在陡线上每列只点一个像素，竖线更是只剩两端的点。陡线需要的像素数是 |dy|+1，不是 |dx|+1。")
    print("        修法只有一句话：哪个方向变化快，就沿哪个方向走。")

    # 用一小块字符画直观比较
    print("\n  陡线 (0,0)→(4,12) 的两种画法（# 是亮的像素）：")
    a, b = raster2d.line_naive(0, 0, 4, 12), raster2d.line_bresenham(0, 0, 4, 12)
    print("   naive   Bresenham")
    for y in range(13):
        la = "".join("#" if (x, y) in a else "." for x in range(5))
        lb = "".join("#" if (x, y) in b else "." for x in range(5))
        print(f"   {la}   {lb}")


def section_exhaustive():
    """
    第 2 节：不靠相信，穷举验证 Bresenham 的所有性质。

    【思路】枚举 0~14 的所有整数端点组合（15^4 = 50625 条线），逐条检查：
        端点正确、8-连通、主轴上每格恰好一个像素、到真实直线的偏差 ≤ 1/2、A→B 和 B→A 亮同一组像素。
        这是"证书式"的验证：只要有一条线违反，就会被数出来。
    """
    console.print_header("2. 穷举验证：所有 50,625 条线（端点坐标 0~14）")
    n = 15
    algos = [("naive", raster2d.line_naive), ("DDA", raster2d.line_dda), ("Bresenham", raster2d.line_bresenham)]
    rows = []
    for label, fn in algos:
        total = wrong_ends = broken = too_far = asymmetric = 0
        worst = 0.0
        for x0 in range(n):
            for y0 in range(n):
                for x1 in range(n):
                    for y1 in range(n):
                        total += 1
                        p = fn(x0, y0, x1, y1)
                        if {p[0], p[-1]} != {(x0, y0), (x1, y1)}:
                            wrong_ends += 1
                        if not is_connected(p):
                            broken += 1
                        d = max_deviation(p, x0, y0, x1, y1)
                        worst = max(worst, d)
                        if d > 0.5 + 1e-9:
                            too_far += 1
                        if set(p) != set(fn(x1, y1, x0, y0)):
                            asymmetric += 1
        rows.append([label, f"{total:,}", wrong_ends, f"{broken:,}", too_far, f"{asymmetric:,}", f"{worst:.3f}"])
    console.print_table(["算法", "线条总数", "端点不对", "断开", "偏差>½", "A→B≠B→A", "最大偏差"], rows)
    print("\n  观察：Bresenham 全部通过：只用整数加减，却和'每列取最近的像素'一样好，而且正反画亮同一组像素。")
    print("        DDA 的像素也不差，但正反画可能不同（平局时取整方向跟着走线方向变）：")
    print("        一条线从两头画结果不一样，意味着相邻多边形共用的边可能出现缝隙或重影。")


def section_float_drift():
    """
    第 3 节：浮点累加的误差：DDA 用 float32 画长线时，末端偏离多少。

    【思路】1/3 这样的增量无法被有限位二进制精确表示，每步累加都积累一点误差。
        GPU 着色器里常用 float32，而且 1962 年的绘图仪根本没有浮点硬件。
    【边界】线长不超过 8000 像素（4K~8K 屏幕的尺度），float32 下还不至于面目全非；这里只看偏差的大小。
    """
    console.print_header("3. 浮点累加的误差：用 float32 的 DDA 画长线")
    rows = []
    for x1, y1 in [(300, 100), (2000, 667), (8000, 2667), (8000, 7999)]:
        dx, dy = x1, y1
        steps = max(dx, dy)
        inc = np.float32(dy) / np.float32(steps)
        y = np.float32(0.0)
        for _ in range(steps):
            y = np.float32(y + inc)
        p32 = raster2d.line_dda(0, 0, x1, y1, dtype=np.float32)
        p64 = raster2d.line_dda(0, 0, x1, y1)
        pb = raster2d.line_bresenham(0, 0, x1, y1)
        diff32 = sum(a != b for a, b in zip(p32, pb))
        diff64 = sum(a != b for a, b in zip(p64, pb))
        rows.append([f"(0,0)→({x1},{y1})", steps, f"{float(y):.4f}", y1, f"{abs(float(y) - y1):.4f}", diff32, diff64])
    console.print_table(["线段", "步数", "累加终点 y", "真实 y", "累积误差", "float32 不同像素", "float64 不同像素"], rows)
    print("\n  观察：float32 累加 8000 步后，误差到了约 0.2 个像素，已经有成百上千个像素选得和理想结果不一样。")
    print("        float64 在这些例子里和 Bresenham 逐像素相同：精度足够高时，累积误差不显著。")
    print("        Bresenham 只用整数，没有任何累积误差：走多少步都精确到达终点。")


def section_speed():
    """
    第 4 节：纯 Python 下，三种算法的实际耗时（真实计时，每次运行略有不同）。

    【边界】这张表测的主要是 Python 解释器的开销，不是算法在硬件上的差别：
        DDA 慢，主要是因为每步要调用两次取整函数（Python 的函数调用很贵），而不是因为浮点运算慢。
        所以它提醒我们：**性能要在目标环境上测**，换一种语言或硬件，结论可能完全不同。
    """
    console.print_header("4. 真实计时：画 2000 条长度约 1000 像素的线（每次运行结果略有不同）")
    rng = np.random.default_rng(3)
    ends = rng.integers(0, 1000, size=(2000, 4)).tolist()
    rows = []
    for label, fn in [("naive", raster2d.line_naive), ("DDA", raster2d.line_dda), ("Bresenham", raster2d.line_bresenham)]:
        t0 = time.perf_counter()
        count = 0
        for x0, y0, x1, y1 in ends:
            count += len(fn(x0, y0, x1, y1))
        dt = time.perf_counter() - t0
        rows.append([label, f"{count:,}", f"{dt * 1000:.0f} ms", f"{dt / count * 1e9:.0f} ns"])
    console.print_table(["算法", "总像素数", "总耗时", "每像素耗时"], rows)
    print("\n  观察：naive 的总耗时看起来不错，只是因为它在陡线上少画了像素（也就是断开了）。比较快慢之前先看结果对不对。")
    print("        DDA 每像素比 Bresenham 慢，主要是每步两次取整函数调用的开销：这里测的是 Python，不是硬件。")


def section_fan_image():
    """第 5 节：扇形线束：把三种算法的结果放大显示。输出 out/03_line_fan.png。"""
    size, k = 41, 6
    center = size // 2
    panels = []
    for fn in (raster2d.line_naive, raster2d.line_dda, raster2d.line_bresenham):
        img = image_io.new_image(size, size, (250, 250, 250))
        for i in range(24):
            angle = i * 2 * math.pi / 24
            x1 = int(round(center + 19 * math.cos(angle)))
            y1 = int(round(center + 19 * math.sin(angle)))
            for x, y in fn(center, center, x1, y1):
                img[y, x] = (25, 50, 110)
        panels.append(image_io.upscale(img, k))
    image_io.save_png(os.path.join(course_path.out_dir(), "03_line_fan.png"), image_io.image_grid(panels, gap=10))


def thick_line_coverage(x0, y0, x1, y1, width, height, line_width=1.0, n=8):
    """
    把线段当作一个有宽度的长方形，算每个像素的覆盖比例（反走样的线）。

    【思路】数学上的线没有面积，"覆盖多少"无从谈起。给它一个宽度 line_width，它就成了一个长方形，
        和三角形一样可以用 n×n 个子采样点估计覆盖比例。
    【参数】端点（连续坐标）；width、height：画面大小；line_width：线宽；n：每方向子采样数
    【返回】(height, width) 的浮点数组，取值 [0,1]
    【边界】两端点相同时返回全 0；端点处是平头，不延长。
    """
    length = math.hypot(x1 - x0, y1 - y0)
    if length == 0:
        return np.zeros((height, width))
    ux, uy = (x1 - x0) / length, (y1 - y0) / length
    offsets = (np.arange(n) + 0.5) / n
    xs = (np.arange(width)[:, None] + offsets[None, :]).ravel()
    ys = (np.arange(height)[:, None] + offsets[None, :]).ravel()
    px, py = np.meshgrid(xs, ys)
    along = (px - x0) * ux + (py - y0) * uy              # 沿线方向的投影
    across = -(px - x0) * uy + (py - y0) * ux            # 垂直于线方向的距离
    inside = (along >= 0) & (along <= length) & (np.abs(across) <= line_width / 2.0)
    return inside.reshape(height, n, width, n).mean(axis=(1, 3))


def section_antialias():
    """
    第 6 节：只有亮和不亮两种选择，锯齿就无法避免；允许像素取中间值，边缘才显得光滑。

    【输出】out/03_antialias.png：左边 Bresenham，右边 8×8 超采样的覆盖比例。
    """
    console.print_header("5. 为什么有锯齿：线其实没有面积")
    w, h = 40, 24
    hard = np.ones((h, w))
    for x, y in raster2d.line_bresenham(2, 3, 37, 19):
        hard[y, x] = 0.0
    soft = 1.0 - thick_line_coverage(2.5, 3.5, 37.5, 19.5, w, h, 1.0, 8)
    image_io.save_png(os.path.join(course_path.out_dir(), "03_antialias.png"),
                      image_io.image_grid([image_io.upscale(hard, 8), image_io.upscale(soft, 8)], gap=10))
    levels = len(np.unique(np.round(soft, 4)))
    print(f"  Bresenham 的结果只有 2 种灰度；8×8 超采样后有 {levels} 种灰度（0~1 之间的覆盖比例）。")
    print(f"  覆盖比例之和 = {(1 - soft).sum():.2f}，线段面积 = 长 × 宽 = {math.hypot(35, 16):.2f}：'亮度总量'等于几何面积。")
    print("  输出 out/03_antialias.png：左边硬边，右边反走样。第 8 讲从信号处理的角度解释为什么这样有效。")


def main():
    section_naive()
    section_exhaustive()
    section_float_drift()
    section_speed()
    section_fan_image()
    section_antialias()


if __name__ == "__main__":
    main()
