// =============================================================================
// Lecture 1 · 脚本 06b（可选，仅 macOS）：用真正的 GPU 跑一次同样的着色计算（讲义 §8.3）
// =============================================================================
//
// 【这个脚本要回答的问题】
//     06_cpu_vs_gpu.py 里，Python 循环和 numpy 都到不了 4K 实时。那 GPU 呢？
//     这里把同一个"Lambert × 棋盘格"着色器写成 Metal 计算着色器（compute shader），
//     对 3840×2160 = 829 万个片元运行，测真实耗时。
//
// 【为什么用计算着色器，而不是真的画三角形】
//     要比较的只是"同一段着色代码对一大批数据运行有多快"。计算着色器去掉了光栅化，
//     也就没有其他固定功能硬件的干扰。课件讲的 GPGPU 就是这种用法。
//
// 【运行】（macOS，需要 Xcode 命令行工具）
//     swiftc -O 06b_real_gpu.swift -o out/real_gpu
//     ./out/real_gpu
//
// 【边界】
//     - 机器上没有 Metal 设备时打印提示并退出；
//     - 这里用 32 位浮点，numpy 脚本用 64 位，所以这不是一场严格的基准比较，只看数量级；
//     - 第一次运行有编译着色器的时间，所以跳过前几次，取最快的一次；
//     - 用 waitUntilCompleted 等待每一帧，包含了提交、同步的开销。
//
// 【Swift 小知识】
//     - let 声明常量，var 声明变量；guard ... else { 退出 } 用来提前处理失败的情况；
//     - """ ... """ 是多行字符串，这里面就是运行在 GPU 上的着色器源码（Metal Shading Language，长得很像 C++）。

import Foundation
import Metal

// ---- 运行在 GPU 上的代码：对每个片元执行一次，thread_position_in_grid 告诉它自己是第几个 ----
let shaderSource = """
#include <metal_stdlib>
using namespace metal;

kernel void shade(device const packed_float3 *normals   [[buffer(0)]],
                  device const packed_float3 *positions [[buffer(1)]],
                  device float               *out       [[buffer(2)]],
                  uint id [[thread_position_in_grid]])
{
    const float3 light = normalize(float3(0.45, 0.8, 0.4));
    float3 n = normals[id];
    float3 p = positions[id];
    float diffuse = max(dot(n, light), 0.0f);
    float parity = fmod(floor(p.x) + floor(p.z) + 2000.0f, 2.0f);
    float checker = parity < 0.5f ? 0.85f : 0.25f;
    out[id] = (0.12f + 0.88f * diffuse) * checker;
}
"""

guard let device = MTLCreateSystemDefaultDevice() else {
    print("这台机器没有可用的 Metal 设备，跳过。")
    exit(0)
}

let fragmentCount = 3840 * 2160
print("GPU：\(device.name)")
print("片元数：\(fragmentCount)（相当于 4K 全屏着色一次）")

// ---- 准备数据：可复现的伪随机法线和位置（线性同余发生器，避免依赖系统随机数）----
// 【思路】CPU 和 GPU 在 Apple 芯片上共用内存（.storageModeShared），写进缓冲区后 GPU 直接能读，不用复制。
var seed: UInt64 = 12345
func nextUniform() -> Float {
    seed = seed &* 6364136223846793005 &+ 1442695040888963407   // &* 和 &+ 是允许溢出的乘法、加法
    return Float((seed >> 40) & 0xFFFFFF) / Float(1 << 24)
}

let stride3 = MemoryLayout<Float>.stride * 3
guard
    let normalBuffer = device.makeBuffer(length: fragmentCount * stride3, options: .storageModeShared),
    let positionBuffer = device.makeBuffer(length: fragmentCount * stride3, options: .storageModeShared),
    let outBuffer = device.makeBuffer(length: fragmentCount * MemoryLayout<Float>.stride, options: .storageModeShared)
else {
    print("分配 GPU 缓冲区失败（内存不够？）")
    exit(1)
}
let normals = normalBuffer.contents().bindMemory(to: Float.self, capacity: fragmentCount * 3)
let positions = positionBuffer.contents().bindMemory(to: Float.self, capacity: fragmentCount * 3)
for i in 0..<fragmentCount {
    // 单位球面上的随机方向：z 均匀分布，方位角均匀分布
    let z = 2.0 * nextUniform() - 1.0
    let phi = 2.0 * Float.pi * nextUniform()
    let r = (1.0 - z * z).squareRoot()
    normals[3 * i] = r * cos(phi)
    normals[3 * i + 1] = r * sin(phi)
    normals[3 * i + 2] = z
    positions[3 * i] = 10.0 * nextUniform() - 5.0
    positions[3 * i + 1] = 10.0 * nextUniform() - 5.0
    positions[3 * i + 2] = 10.0 * nextUniform() - 5.0
}

// ---- 编译着色器：把源码字符串翻译成这块 GPU 的机器码（课件说的"着色器要在运行时编译"就是这一步）----
let compileStart = Date()
let library: MTLLibrary
let pipeline: MTLComputePipelineState
do {
    library = try device.makeLibrary(source: shaderSource, options: nil)
    pipeline = try device.makeComputePipelineState(function: library.makeFunction(name: "shade")!)
} catch {
    print("着色器编译失败：\(error)")
    exit(1)
}
print(String(format: "着色器编译耗时：%.1f ms（这就是游戏第一次运行时'正在编译着色器'的原因）",
             Date().timeIntervalSince(compileStart) * 1000))
print("SIMD 组宽度（thread execution width）：\(pipeline.threadExecutionWidth)")

guard let queue = device.makeCommandQueue() else { exit(1) }

// ---- 运行若干帧，取最快的一帧 ----
var best = Double.infinity
for frame in 0..<12 {
    guard let commands = queue.makeCommandBuffer(),
          let encoder = commands.makeComputeCommandEncoder() else { exit(1) }
    encoder.setComputePipelineState(pipeline)
    encoder.setBuffer(normalBuffer, offset: 0, index: 0)
    encoder.setBuffer(positionBuffer, offset: 0, index: 1)
    encoder.setBuffer(outBuffer, offset: 0, index: 2)
    let group = MTLSize(width: pipeline.threadExecutionWidth, height: 1, depth: 1)
    encoder.dispatchThreads(MTLSize(width: fragmentCount, height: 1, depth: 1), threadsPerThreadgroup: group)
    encoder.endEncoding()
    let start = Date()
    commands.commit()
    commands.waitUntilCompleted()
    let elapsed = Date().timeIntervalSince(start)
    if frame >= 2 { best = min(best, elapsed) }      // 跳过最开始的两帧（缓存、频率都还没稳定）
}

let ns = best / Double(fragmentCount) * 1e9
print(String(format: "最快一帧：%.2f ms；每片元 %.3f ns；相当于 4K 全屏 %.0f fps", best * 1000, ns, 1.0 / best))

// ---- 核对：挑一个片元，用 CPU 算一遍同样的公式，确认 GPU 真的算对了 ----
let results = outBuffer.contents().bindMemory(to: Float.self, capacity: fragmentCount)
let lx: Float = 0.45, ly: Float = 0.8, lz: Float = 0.4
let lengthL = (lx * lx + ly * ly + lz * lz).squareRoot()
var maxError: Float = 0
for i in stride(from: 0, to: fragmentCount, by: 100_003) {
    let d = normals[3 * i] * lx / lengthL + normals[3 * i + 1] * ly / lengthL + normals[3 * i + 2] * lz / lengthL
    let parity = fmod(floor(positions[3 * i]) + floor(positions[3 * i + 2]) + 2000.0, 2.0)
    let checker: Float = parity < 0.5 ? 0.85 : 0.25
    let expected = (0.12 + 0.88 * max(d, 0)) * checker
    maxError = max(maxError, abs(expected - results[i]))
}
print(String(format: "抽查 %d 个片元，CPU 和 GPU 结果的最大差：%.2e", fragmentCount / 100_003 + 1, maxError))
