"""
=============================================================================
Lecture 1 · 脚本 07：看见世界的两种方式：光栅化 vs 光线投射（讲义 §9）
=============================================================================

【这个脚本要回答的问题】
    渲染的核心问题之一是**可见性（visibility）**：每个像素里，看到的是哪个物体？有两种思路：
        光栅化（对象顺序）：for 每个三角形：它盖住了哪些像素？
        光线投射（图像顺序）：for 每个像素：沿着这条视线，最先碰到哪个三角形？
    1. 这两个循环只是交换了内外层，算出来的是同一个答案吗？（逐像素比较）
    2. 开销差多少？三角形变多时怎样增长？（数基本运算的次数，并真实计时）
    3. 既然开销差这么多，为什么离线渲染和新的 GPU 还要用光线？（下一步：每个交点可以继续发射光线）

【运行】python3 07_two_ways_to_see.py        （约 3 秒）
【输出】out/07_raster_vs_ray.png
"""

import os
import time

import numpy as np

import console
import course_path
import image_io
import mini_pipeline as mp

WIDTH, HEIGHT = 200, 125


def world_triangles(draws):
    """
    把场景里所有三角形变到世界坐标，拼成一个大数组。

    【参数】draws：Draw 列表
    【返回】(tris, draw_of_tri)
        tris：T×3×3 数组，第 i 个三角形的三个顶点（编号顺序和管线的图元编号相同）
        draw_of_tri：长度 T 的数组，每个三角形属于第几个 Draw
    """
    tris, owner = [], []
    for k, d in enumerate(draws):
        homogeneous = np.hstack([d.mesh.positions, np.ones((len(d.mesh.positions), 1))])
        world = (homogeneous @ d.model.T)[:, :3]
        tris.append(world[d.mesh.faces])
        owner.append(np.full(len(d.mesh.faces), k))
    return np.concatenate(tris), np.concatenate(owner)


def camera_rays(camera, width, height):
    """
    为每个像素中心生成一条从相机出发的光线。

    【思路】在相机坐标里，画面放在 z = −1 处，x、y 的范围由视场角决定；再把方向转回世界坐标。
        要和光栅化比较，这里必须和管线用**完全相同**的像素中心 (i+0.5, j+0.5) 和投影参数。
    【参数】camera：Camera；width、height：画面大小
    【返回】(origin, directions)：origin 是长度 3 的数组；directions 是 (width·height)×3 的数组（按行展开，未归一化）
    """
    half_h = np.tan(np.radians(camera.fovy_deg) / 2.0)
    half_w = half_h * width / height
    xs = ((np.arange(width) + 0.5) / width * 2.0 - 1.0) * half_w
    ys = (1.0 - (np.arange(height) + 0.5) / height * 2.0) * half_h
    px, py = np.meshgrid(xs, ys)
    view = camera.view()
    rotation = view[:3, :3].T                   # 旋转矩阵的逆等于它的转置
    d = np.stack([px.ravel(), py.ravel(), -np.ones(px.size)], axis=1)
    return np.asarray(camera.eye, dtype=np.float64), d @ rotation.T


def ray_cast(tris, origin, directions, near_t=1e-9, chunk=4000):
    """
    Möller–Trumbore 光线-三角形求交：每条光线和每个三角形都测一次（暴力）。

    【思路】把"光线上的点 = 三角形上的点"写成一个 3×3 线性方程组，用克莱姆法则解出 (t, b1, b2)。
        t > 0、b1 ≥ 0、b2 ≥ 0、b1 + b2 ≤ 1 时相交。每条光线记录最小的 t。（第 16 讲详细推导）
    【参数】
        tris：T×3×3；origin：长度 3；directions：R×3
        near_t：t 必须大于它才算相交
        chunk：每次处理多少条光线（控制内存）
    【返回】(ids, depth_t)：每条光线命中的三角形编号（−1 表示没命中）和对应的 t
    【边界】光线和三角形平行（行列式 ≈ 0）时当作不相交。恰好擦着边的情况也算相交（≥ 0）。
    """
    a = tris[:, 0]
    e1 = tris[:, 1] - a
    e2 = tris[:, 2] - a
    r = len(directions)
    ids = np.full(r, -1, dtype=np.int64)
    best = np.full(r, np.inf)
    s_all = origin - a                                     # T×3：所有光线同一个起点，只需算一次
    q_all = np.cross(s_all, e1)                            # T×3
    t_numerator = (q_all * e2).sum(axis=1)                 # 长度 T：t 的分子只和三角形有关
    for start in range(0, r, chunk):
        batch = directions[start:start + chunk]            # C×3
        p = np.cross(batch[:, None, :], e2[None, :, :])    # C×T×3（广播：每条光线配每个三角形）
        det = (p * e1).sum(axis=2)                         # C×T，克莱姆法则的分母
        ok = np.abs(det) > 1e-14
        inv = np.divide(1.0, det, out=np.zeros_like(det), where=ok)
        b1 = (p * s_all).sum(axis=2) * inv                 # 重心坐标 1
        b2 = (batch @ q_all.T) * inv                       # 重心坐标 2
        t = t_numerator[None, :] * inv                     # 沿光线的距离
        hit = ok & (b1 >= 0) & (b2 >= 0) & (b1 + b2 <= 1) & (t > near_t)
        t = np.where(hit, t, np.inf)
        k = t.argmin(axis=1)
        tmin = t[np.arange(len(k)), k]
        found = np.isfinite(tmin)
        slice_ids = np.full(len(k), -1, dtype=np.int64)
        slice_ids[found] = k[found]
        ids[start:start + chunk] = slice_ids
        best[start:start + chunk] = tmin
    return ids, best


def section_same_answer():
    """第 1 节：同一个场景两种算法算一遍，逐像素比较"每个像素看到的是谁"。"""
    console.print_header("1. 交换内外两层循环：答案一样吗？")
    draws, camera = mp.demo_scene(0.5)
    tris, owner = world_triangles(draws)
    t0 = time.perf_counter()
    fb, st = mp.render(draws, camera, WIDTH, HEIGHT, cull_backface=False, clear_color=(0.55, 0.7, 0.86))
    t_raster = time.perf_counter() - t0
    origin, directions = camera_rays(camera, WIDTH, HEIGHT)
    t0 = time.perf_counter()
    ids, ray_t = ray_cast(tris, origin, directions)
    t_ray = time.perf_counter() - t0
    ids = ids.reshape(HEIGHT, WIDTH)

    same_tri = ids == fb.ids
    print(f"  场景 {len(tris):,} 个三角形，画面 {WIDTH}×{HEIGHT} = {WIDTH * HEIGHT:,} 个像素")
    print(f"  每个像素看到的三角形编号完全相同的比例：{same_tri.mean() * 100:.3f}%（{int((~same_tri).sum())} 个像素不同）")
    owner_r = np.where(fb.ids >= 0, owner[np.maximum(fb.ids, 0)], -1)
    owner_c = np.where(ids >= 0, owner[np.maximum(ids, 0)], -1)
    print(f"  每个像素看到的物体相同的比例：{(owner_r == owner_c).mean() * 100:.3f}%")
    print("  观察：两种算法回答的是同一个数学问题：每个像素中心沿视线最先碰到谁。这里连编号都逐像素一致。")
    print("        （如果某个像素中心恰好落在两个三角形的公共边上，两种算法可能选不同的一边，那样也都算对。）")

    # 把 ID 图画出来，确认视觉上相同
    palette = np.random.default_rng(1).uniform(0.2, 1.0, size=(len(tris) + 1, 3))
    a = palette[fb.ids]
    b = palette[ids]
    a[fb.ids < 0] = 1.0
    b[ids < 0] = 1.0
    diff = np.ones((HEIGHT, WIDTH, 3))
    diff[~same_tri] = (0.8, 0.0, 0.0)
    image_io.save_png(os.path.join(course_path.out_dir(), "07_raster_vs_ray.png"), image_io.image_grid(
        [image_io.upscale(a, 2), image_io.upscale(b, 2), image_io.upscale(diff, 2)], cols=3, gap=6))
    print("  输出 out/07_raster_vs_ray.png：左光栅化、中光线投射（颜色表示三角形编号）、右差异（红点）")
    return t_raster, t_ray, st


def section_scaling():
    """
    第 2 节：开销怎样随三角形数增长。

    【思路】光栅化的基本操作是"包围盒内每个像素测一次"，总量约等于各三角形的覆盖面积之和，和三角形数关系不大；
        暴力光线投射是"每条光线 × 每个三角形"，和三角形数成正比。
    """
    console.print_header("2. 开销：三角形越多，差距越大（数基本操作，并真实计时）")
    rows, counts = [], []
    for detail in (0.125, 0.25, 0.5, 1.0):
        draws, camera = mp.demo_scene(detail)
        tris, _ = world_triangles(draws)
        t0 = time.perf_counter()
        _, st = mp.render(draws, camera, WIDTH, HEIGHT, cull_backface=False)
        t_raster = time.perf_counter() - t0
        origin, directions = camera_rays(camera, WIDTH, HEIGHT)
        t0 = time.perf_counter()
        ray_cast(tris, origin, directions)
        t_ray = time.perf_counter() - t0
        ray_tests = WIDTH * HEIGHT * len(tris)
        counts.append((len(tris), st.edge_tests, ray_tests))
        rows.append([f"{len(tris):,}", f"{st.edge_tests:,}", f"{ray_tests:,}", f"{ray_tests / st.edge_tests:.0f} 倍",
                     f"{t_raster * 1000:.0f} ms", f"{t_ray * 1000:.0f} ms"])
    console.print_table(["三角形数", "光栅化：覆盖测试次数", "光线投射：求交次数", "次数之比", "光栅化耗时", "光线投射耗时"], rows)
    low, high = counts[0], counts[-1]
    print(f"\n  观察：三角形数增加到 {high[0] / low[0]:.0f} 倍，光栅化的测试次数只增加到 {high[1] / low[1]:.2f} 倍，暴力光线投射的次数也增加到 {high[2] / low[2]:.0f} 倍。")
    print("        注意耗时之比比次数之比小：光栅化里每个三角形都有 Python 循环的固定开销，光线投射则是一口气批量算的。")
    print("        所以暴力光线投射并不实用，必须用空间数据结构（第 17 讲的 BVH）把 O(像素×三角形) 变成约 O(像素×log 三角形)。")


def section_why_rays():
    """
    第 3 节：光线的优势：从交点可以继续发射光线，轻松回答"这一点能看见光源吗"。

    【思路】光栅化每次只回答"从一个视点（投影中心）看，谁最近"。
        而阴影、反射需要从**场景中的任意点**朝**任意方向**提问。用光线投射直接算阴影，
        然后和没有阴影的光栅化结果比较。
    【输出】打印被阴影覆盖的像素比例，并把这张带阴影的图存到 out/07_shadow.png。
    """
    console.print_header("3. 光线的超能力：从任意点朝任意方向提问（比如算阴影）")
    draws, camera = mp.demo_scene(0.25)
    tris, _ = world_triangles(draws)
    w, h = 200, 125
    origin, directions = camera_rays(camera, w, h)
    ids, t = ray_cast(tris, origin, directions)
    hit = ids >= 0
    points = origin + directions[hit] * t[hit, None]
    light = np.array(mp.SCENE_LIGHT)
    light = light / np.linalg.norm(light)
    # 关键的一步：从每个可见点朝光源方向再发一条光线，碰到任何东西就是在阴影里
    a = tris[:, 0]
    e1, e2 = tris[:, 1] - a, tris[:, 2] - a
    in_shadow = np.zeros(len(points), dtype=bool)
    d = np.broadcast_to(light, (len(tris), 3))
    p = np.cross(d, e2)
    det = (p * e1).sum(axis=1)
    ok = np.abs(det) > 1e-14
    inv = np.divide(1.0, det, out=np.zeros_like(det), where=ok)
    for i, o in enumerate(points):
        s = o - a
        q = np.cross(s, e1)
        b1 = (p * s).sum(axis=1) * inv
        b2 = (q @ light) * inv
        tt = (q * e2).sum(axis=1) * inv
        in_shadow[i] = bool((ok & (b1 >= 0) & (b2 >= 0) & (b1 + b2 <= 1) & (tt > 1e-4)).any())
    fb, _ = mp.render(draws, camera, w, h, clear_color=(0.55, 0.70, 0.86))
    shaded = fb.color.copy()
    mask = np.zeros(w * h, dtype=bool)
    mask[np.flatnonzero(hit)[in_shadow]] = True
    shaded[mask.reshape(h, w)] *= 0.35
    image_io.save_png(os.path.join(course_path.out_dir(), "07_shadow.png"), image_io.image_grid(
        [image_io.upscale(image_io.to_uint8(image_io.srgb_encode(fb.color)), 2),
         image_io.upscale(image_io.to_uint8(image_io.srgb_encode(shaded)), 2)], cols=2, gap=6))
    shadow_rays = len(points)
    print(f"  可见点 {shadow_rays:,} 个，每个点朝光源再发一条阴影光线，{int(in_shadow.sum()):,} 个点在阴影里（{in_shadow.mean() * 100:.1f}%）")
    print("  输出 out/07_shadow.png：左边光栅化（物体悬浮在地面上一样），右边加了阴影（物体'落地'了）")
    print("  观察：只多写了几行就有了物理上正确的硬阴影。光栅化要做到同样的事，得先从光源的视角渲染一张深度图（阴影贴图，第 12 讲）。")
    print("        把这个想法推到底：从交点继续朝随机方向发射光线，就是路径追踪（第 21–24 讲，脚本 08 先预览）。")


def main():
    section_same_answer()
    section_scaling()
    section_why_rays()


if __name__ == "__main__":
    main()
