"""
=============================================================================
CMU 15-462/662 · 第 2 讲共享模块：plot2d.py —— 从零画示意图（线、箭头、多边形、文字）
=============================================================================

【这个模块在回答什么问题】
    讲线性代数、微积分时，要画很多带箭头、曲线、标注的示意图。这里不用 matplotlib，
    而是用第 1 讲学到的东西自己画：这既是一个好用的工具，也是光栅化的又一次练习。

【用到的思想】
    - 第 1 讲 §5.4：线其实没有面积，要给它一个宽度，再算每个像素的覆盖比例（反走样）。
      这里用的是"到线段的距离"来估计覆盖：距离小于半宽的像素全亮，边界上平滑过渡 1 个像素。
      这种用距离函数算形状的办法，第 13 讲（隐式几何）还会再见到。
    - 第 2 讲 §2：世界坐标 → 像素坐标是一个仿射映射（缩放 + 平移）。
    - 文字也是图形：每个字母是一张 5×7 的小位图。

【主要接口 API】
    Canvas2D(xlim, ylim, width, height=None)   建一块画布（xlim、ylim 是世界坐标范围，y 向上）
        .line(p, q, color, width)              线段
        .polyline(points, color, width, closed) 折线
        .arrow(p, q, color, width)             箭头
        .dot(p, color, radius)                 圆点
        .polygon(points, color, alpha)         实心多边形（可以是凹的）
        .grid(step, color) / .axes(color)      网格、坐标轴
        .heatmap(values, ...)                  二维标量场画成背景色（第 3 讲）
        .contour(xs, ys, values, level, ...)   等值线（marching squares，第 3 讲）
        .text(p, s, color, scale)              文字（只支持 ASCII）
        .image()                               返回 H×W×3 的浮点图
    label(img, s, scale)                       给一张图左上角加上标题（返回新图）
    COLORS                                     统一的配色表

【边界】
    - 这是教学用的小工具，每条线都在包围盒里算一遍距离，几千条线没问题，几十万条线会慢；
    - 文字只支持 ASCII（字符码 32~126），中文请写在讲义的图注里。
"""

import numpy as np

import course_path
course_path.use("lecture01")
import image_io


COLORS = {
    "black": (0.10, 0.10, 0.12), "gray": (0.55, 0.55, 0.58), "light": (0.86, 0.86, 0.88),
    "red": (0.80, 0.16, 0.14), "blue": (0.12, 0.30, 0.68), "green": (0.10, 0.55, 0.25),
    "orange": (0.90, 0.50, 0.08), "purple": (0.50, 0.22, 0.65), "teal": (0.05, 0.55, 0.60),
}

# 5×7 位图字体：ASCII 32~126 每个字符 5 列，每列 1 个字节（2 个十六进制数字），最低位是最上面一行。
_FONT = (
    "0000000000" "00005F0000" "0007000700" "147F147F14" "242A7F2A12" "2313086462" "3649552250" "0005030000"
    "001C224100" "0041221C00" "14083E0814" "08083E0808" "0050300000" "0808080808" "0060600000" "2010080402"
    "3E5149453E" "00427F4000" "4261514946" "2141454B31" "1814127F10" "2745454539" "3C4A494930" "0171090503"
    "3649494936" "064949291E" "0036360000" "0056360000" "0814224100" "1414141414" "0041221408" "0201510906"
    "324979413E" "7E1111117E" "7F49494936" "3E41414122" "7F4141221C" "7F49494941" "7F09090901" "3E4149497A"
    "7F0808087F" "00417F4100" "2040413F01" "7F08142241" "7F40404040" "7F020C027F" "7F0408107F" "3E4141413E"
    "7F09090906" "3E4151215E" "7F09192946" "4649494931" "01017F0101" "3F4040403F" "1F2040201F" "3F4038403F"
    "6314081463" "0708700807" "6151494543" "007F414100" "0204081020" "0041417F00" "0402010204" "4040404040"
    "0001020400" "2054545478" "7F48444438" "3844444420" "384444487F" "3854545418" "087E090102" "0C5252523E"
    "7F08040478" "00447D4000" "2040443D00" "7F10284400" "00417F4000" "7C04180478" "7C08040478" "3844444438"
    "7C14141408" "081414187C" "7C08040408" "4854545420" "043F444020" "3C4040207C" "1C2040201C" "3C4030403C"
    "4428102844" "0C5050503C" "4464544C44" "0008364100" "00007F0000" "0041360800" "1008081008"
)


def _glyph(ch):
    """
    取一个字符的 7×5 布尔位图。

    【参数】ch：一个字符
    【返回】(7, 5) 的布尔数组，第 0 行在最上面
    【边界】ASCII 32~126 以外的字符显示成问号。
    """
    code = ord(ch)
    index = code - 32 if 32 <= code <= 126 else ord("?") - 32
    columns = bytes.fromhex(_FONT[index * 10:index * 10 + 10])
    return np.array([[(c >> row) & 1 for c in columns] for row in range(7)], dtype=bool)


class Canvas2D:
    """
    一块用世界坐标绘图的画布。

    【思路】构造时算好"世界坐标 → 像素坐标"的仿射映射：x 方向缩放 + 平移，y 方向缩放 + 平移 + 翻转。
    【参数】
        xlim、ylim：世界坐标的范围，如 (-2, 2)
        width：画布宽度（像素）
        height：高度；默认按 xlim、ylim 的比例算，保证一个单位在两个方向一样长（圆不会变成椭圆）
        bg：背景色（线性值 0~1）
    【边界】xlim 或 ylim 的范围为 0 时抛出 ValueError。
    """

    def __init__(self, xlim, ylim, width, height=None, bg=(1.0, 1.0, 1.0)):
        if xlim[1] <= xlim[0] or ylim[1] <= ylim[0]:
            raise ValueError(f"坐标范围必须从小到大，收到 xlim={xlim}, ylim={ylim}")
        self.xlim, self.ylim = tuple(xlim), tuple(ylim)
        self.width = int(width)
        aspect = (ylim[1] - ylim[0]) / (xlim[1] - xlim[0])
        self.height = int(round(width * aspect)) if height is None else int(height)
        self.img = np.empty((self.height, self.width, 3), dtype=np.float64)
        self.img[:] = bg
        self.sx = self.width / (xlim[1] - xlim[0])      # 每个世界单位多少像素
        self.sy = self.height / (ylim[1] - ylim[0])

    def to_px(self, p):
        """
        世界坐标 → 像素坐标。

        【参数】p：(x, y) 或 N×2 数组
        【返回】同形状的浮点数组。注意 y 被翻转：世界坐标 y 向上，图像的行号向下
        """
        p = np.asarray(p, dtype=np.float64)
        out = np.empty_like(p)
        out[..., 0] = (p[..., 0] - self.xlim[0]) * self.sx
        out[..., 1] = (self.ylim[1] - p[..., 1]) * self.sy
        return out

    def _blend(self, x0, x1, y0, y1, alpha, color):
        """把颜色按覆盖比例 alpha 叠到画布的一个矩形区域上：结果 = 原色·(1−α) + 新色·α（第 11 讲的 over 运算）。"""
        region = self.img[y0:y1, x0:x1]
        region += alpha[..., None] * (np.asarray(color, dtype=np.float64) - region)

    def _capsule(self, a, b, color, width):
        """
        画一条有宽度的线段（两端是半圆，形状叫胶囊 capsule）。

        【思路】算每个像素中心到线段的距离 d。d ≤ 半宽 − 0.5 的像素全部被盖住，d ≥ 半宽 + 0.5 的完全没盖住，
            中间线性过渡。这是对真实覆盖比例很好的近似，比超采样快得多。
        【参数】a、b：像素坐标；color；width：线宽（像素）
        【边界】a、b 重合时退化成一个圆点。包围盒和画布不相交时直接返回。
        """
        r = width / 2.0
        x0 = max(int(np.floor(min(a[0], b[0]) - r - 1)), 0)
        x1 = min(int(np.ceil(max(a[0], b[0]) + r + 1)), self.width)
        y0 = max(int(np.floor(min(a[1], b[1]) - r - 1)), 0)
        y1 = min(int(np.ceil(max(a[1], b[1]) + r + 1)), self.height)
        if x1 <= x0 or y1 <= y0:
            return
        px, py = np.meshgrid(np.arange(x0, x1) + 0.5, np.arange(y0, y1) + 0.5)
        ab = np.asarray(b, dtype=np.float64) - np.asarray(a, dtype=np.float64)
        denom = float(ab @ ab)
        if denom == 0.0:
            t = np.zeros_like(px)
        else:
            t = np.clip(((px - a[0]) * ab[0] + (py - a[1]) * ab[1]) / denom, 0.0, 1.0)
        d = np.hypot(px - (a[0] + t * ab[0]), py - (a[1] + t * ab[1]))
        self._blend(x0, x1, y0, y1, np.clip(r + 0.5 - d, 0.0, 1.0), color)

    def line(self, p, q, color=COLORS["black"], width=1.5):
        """画一条线段。【参数】p、q：世界坐标；color：颜色；width：线宽（像素）。"""
        self._capsule(self.to_px(p), self.to_px(q), color, width)

    def polyline(self, points, color=COLORS["black"], width=1.5, closed=False):
        """
        画折线（曲线就是足够密的折线）。

        【参数】points：N×2 的世界坐标；closed：是否首尾相连
        【边界】含 NaN 的点会把折线断开，可以用来表示不连续。
        """
        pts = self.to_px(points)
        count = len(pts)
        for i in range(count if closed else count - 1):
            a, b = pts[i], pts[(i + 1) % count]
            if np.isfinite(a).all() and np.isfinite(b).all():
                self._capsule(a, b, color, width)

    def arrow(self, p, q, color=COLORS["blue"], width=2.0, head=9.0):
        """
        画箭头：一条线加两条短边。

        【参数】p、q：起点、终点（世界坐标）；head：箭头两翼的长度（像素）
        【边界】p、q 重合时只画一个点。
        """
        a, b = self.to_px(p), self.to_px(q)
        d = b - a
        length = float(np.hypot(*d))
        self._capsule(a, b, color, width)
        if length == 0.0:
            return
        u = d / length
        n = np.array([-u[1], u[0]])
        h = min(head, 0.5 * length)
        self._capsule(b, b - h * u + 0.45 * h * n, color, width)
        self._capsule(b, b - h * u - 0.45 * h * n, color, width)

    def dot(self, p, color=COLORS["red"], radius=3.0):
        """画一个圆点。【参数】p：世界坐标；radius：半径（像素）。"""
        a = self.to_px(p)
        self._capsule(a, a, color, 2.0 * radius)

    def polygon(self, points, color=COLORS["blue"], alpha=1.0, samples=4):
        """
        画实心多边形（可以是凹的）。

        【思路】奇偶规则：从一点向右发一条射线，和边相交奇数次就在内部。每个像素放 samples² 个子采样点。
        【参数】points：N×2 的世界坐标；alpha：不透明度；samples：每方向子采样数
        【边界】边数太少（< 3）时什么也不画。
        """
        pts = self.to_px(points)
        if len(pts) < 3:
            return
        x0 = max(int(np.floor(pts[:, 0].min())), 0)
        x1 = min(int(np.ceil(pts[:, 0].max())), self.width)
        y0 = max(int(np.floor(pts[:, 1].min())), 0)
        y1 = min(int(np.ceil(pts[:, 1].max())), self.height)
        if x1 <= x0 or y1 <= y0:
            return
        offsets = (np.arange(samples) + 0.5) / samples
        xs = (np.arange(x0, x1)[:, None] + offsets[None, :]).ravel()
        ys = (np.arange(y0, y1)[:, None] + offsets[None, :]).ravel()
        px, py = np.meshgrid(xs, ys)
        inside = np.zeros_like(px, dtype=bool)
        for i in range(len(pts)):
            a, b = pts[i], pts[(i + 1) % len(pts)]
            if a[1] == b[1]:
                continue                         # 水平的边不和向右的射线相交
            crosses = ((a[1] > py) != (b[1] > py)) & (px < a[0] + (py - a[1]) * (b[0] - a[0]) / (b[1] - a[1]))
            inside ^= crosses                    # ^= 异或：每穿过一条边，内外翻转一次
        cover = inside.reshape(y1 - y0, samples, x1 - x0, samples).mean(axis=(1, 3))
        self._blend(x0, x1, y0, y1, alpha * cover, color)

    def grid(self, step=1.0, color=COLORS["light"], width=1.0):
        """画网格线。【参数】step：网格间距（世界单位）。"""
        for x in np.arange(np.ceil(self.xlim[0] / step) * step, self.xlim[1] + 1e-9, step):
            self.line((x, self.ylim[0]), (x, self.ylim[1]), color, width)
        for y in np.arange(np.ceil(self.ylim[0] / step) * step, self.ylim[1] + 1e-9, step):
            self.line((self.xlim[0], y), (self.xlim[1], y), color, width)

    def axes(self, color=COLORS["gray"], width=1.5):
        """画过原点的两条坐标轴。【边界】原点不在范围内时，线会被裁掉，看不到。"""
        self.line((self.xlim[0], 0.0), (self.xlim[1], 0.0), color, width)
        self.line((0.0, self.ylim[0]), (0.0, self.ylim[1]), color, width)

    def heatmap(self, values, vmin=None, vmax=None, diverging=False):
        """
        把一个二维标量场画成背景颜色。

        【思路】values 的每个元素对应世界坐标范围内一个均匀的小格子。用最近邻重采样到画布大小。
        【参数】
            values：Ny×Nx 数组，第 0 行对应**世界坐标 y 最小**的一行（和数学习惯一致，不是图像习惯）
            vmin、vmax：颜色范围；默认用数据的最小、最大值
            diverging：True 时用蓝-白-红（0 对应白色，适合有正有负的量）；False 时用灰度（暗到亮）
        【边界】vmax == vmin 时整张图是同一种颜色，不会除零。
        """
        v = np.asarray(values, dtype=np.float64)
        ny, nx = v.shape
        jj = np.minimum((np.arange(self.height) + 0.5) / self.height * ny, ny - 1e-9).astype(int)[::-1]
        ii = np.minimum((np.arange(self.width) + 0.5) / self.width * nx, nx - 1e-9).astype(int)
        grid = v[np.ix_(jj, ii)]
        if diverging:
            limit = max(abs(np.nanmin(v)), abs(np.nanmax(v))) if vmax is None else vmax
            t = np.clip(grid / max(limit, 1e-300), -1.0, 1.0)[..., None]
            pos = np.array([0.80, 0.16, 0.14])
            neg = np.array([0.12, 0.30, 0.68])
            self.img[:] = np.where(t >= 0, (1.0 - t) * 1.0 + t * pos, (1.0 + t) * 1.0 - t * neg)
        else:
            lo = np.nanmin(v) if vmin is None else vmin
            hi = np.nanmax(v) if vmax is None else vmax
            t = np.clip((grid - lo) / max(hi - lo, 1e-300), 0.0, 1.0)[..., None]
            self.img[:] = 0.15 + 0.8 * t

    def contour(self, xs, ys, values, level=0.0, color=COLORS["black"], width=1.2):
        """
        画等值线：marching squares（走格子法）。

        【思路】对每个小方格，看四个角的值在 level 的哪一边。如果一条边的两端在两侧，这条边上一定有一个
            等值点（线性插值找到它）。把同一个方格里的等值点两两连起来，就得到等值线的一小段。
            第 18 讲的 Marching Cubes 就是这个算法在三维的版本。
        【参数】
            xs、ys：长度 Nx、Ny 的坐标
            values：Ny×Nx 数组，values[j, i] 对应 (xs[i], ys[j])
            level：等值线的高度
        【边界】同一方格四个交点（鞍点情形）时随意配对，图上可能有细微差别，这里不做特殊处理。
        """
        v = np.asarray(values, dtype=np.float64) - level
        for j in range(len(ys) - 1):
            for i in range(len(xs) - 1):
                corners = [(xs[i], ys[j], v[j, i]), (xs[i + 1], ys[j], v[j, i + 1]),
                           (xs[i + 1], ys[j + 1], v[j + 1, i + 1]), (xs[i], ys[j + 1], v[j + 1, i])]
                crossings = []
                for k in range(4):
                    x0, y0, a = corners[k]
                    x1, y1, b = corners[(k + 1) % 4]
                    if (a < 0.0) != (b < 0.0):
                        t = a / (a - b)
                        crossings.append((x0 + t * (x1 - x0), y0 + t * (y1 - y0)))
                for k in range(0, len(crossings) - 1, 2):
                    self.line(crossings[k], crossings[k + 1], color, width)

    def text(self, p, s, color=COLORS["black"], scale=2):
        """
        写文字。

        【参数】p：文字左下角（世界坐标）；s：字符串（ASCII）；color；scale：每个字体像素放大几倍
        【边界】超出画布的部分被裁掉。
        """
        x, y = self.to_px(p)
        self.text_px(int(x), int(y) - 7 * scale, s, color, scale)

    def text_px(self, x, y, s, color=COLORS["black"], scale=2):
        """在像素坐标 (x, y)（文字左上角）写文字。【参数】同 text。"""
        col = np.asarray(color, dtype=np.float64)
        for ch in s:
            glyph = np.repeat(np.repeat(_glyph(ch), scale, axis=0), scale, axis=1)
            for r, c in zip(*np.nonzero(glyph)):
                if 0 <= y + r < self.height and 0 <= x + c < self.width:
                    self.img[y + r, x + c] = col
            x += 6 * scale                       # 5 列字形 + 1 列间隔

    def image(self):
        """返回当前画面（H×W×3 浮点图）的副本。"""
        return self.img.copy()


def label(img, s, scale=2, color=COLORS["black"], bg=(1.0, 1.0, 1.0)):
    """
    给一张图在上方加一条标题栏。

    【参数】img：灰度或 RGB 图（uint8 或 float）；s：标题（ASCII）；scale：字号；color、bg：文字色和背景色
    【返回】新的浮点 RGB 图（高度增加）
    【用途】多联图里说明每一格是什么。
    """
    a = image_io.to_uint8(np.asarray(img)).astype(np.float64) / 255.0
    if a.ndim == 2:
        a = np.repeat(a[:, :, None], 3, axis=2)
    a = a[:, :, :3]
    bar_h = 7 * scale + 8
    canvas = Canvas2D((0, 1), (0, 1), a.shape[1], bar_h, bg=bg)
    canvas.text_px(4, 4, s, color, scale)
    return np.vstack([canvas.image(), a])


if __name__ == "__main__":
    # 自检：画一张带所有元素的小图，确认不崩溃，并检查颜色确实写到了预期的位置
    c = Canvas2D((-1, 1), (-1, 1), 100)
    c.line((-1, 0), (1, 0), (1, 0, 0), 3.0)
    assert np.allclose(c.img[50, 50], (1, 0, 0))             # 线经过中心
    assert np.allclose(c.img[5, 5], (1, 1, 1))               # 角落没被碰到
    c.polygon([(-0.5, 0.2), (0.5, 0.2), (0, 0.8)], (0, 0, 1))
    assert np.allclose(c.img[35, 50], (0, 0, 1))             # 三角形内部
    assert _glyph("A").shape == (7, 5) and _glyph("A").any() and not _glyph(" ").any()
    assert len(_FONT) == 95 * 10
    c2 = Canvas2D((-1, 1), (-1, 1), 60)
    xs = np.linspace(-1, 1, 21)
    field = xs[None, :] ** 2 + xs[:, None] ** 2
    c2.heatmap(field)
    c2.contour(xs, xs, field, 0.25, (1, 0, 0), 2.0)
    assert np.allclose(c2.img[30, 45], (1, 0, 0), atol=0.3)   # 半径 0.5 的圆经过这里
    print("plot2d 自检通过")
