/* =============================================================================
 * Lecture 4 · 程序 08：内存布局：同样的数据，不同的摆法（讲义 §10）
 * =============================================================================
 *
 * 【这个程序要回答的问题】
 *   1. 一个结构体占多少字节？为什么有时比各字段之和还大？（对齐和填充）
 *   2. 同样一堆顶点，"结构体的数组"和"数组的结构体"差多少？（AoS vs SoA）
 *   3. 按行遍历和按列遍历一张图，差多少？随机访问呢？
 *
 * 【运行】make && ./out/08_data_layout        （约 3 秒）
 *
 * 【图形学联系】GPU 的顶点缓冲既可以交错存放（AoS），也可以分开存放（SoA）。
 *     移动 GPU 特别喜欢把位置单独放一个缓冲区：只需要位置的深度 pass 就不用读其他属性了。
 *     纹理在显存里也不是按行存放的，而是按小块（tiling），为的就是下面第 3 节的效果。
 * -------------------------------------------------------------------------- */
#include <cmath>
#include <cstddef>
#include <cstdio>
#include <numeric>
#include <vector>

#include "gfx_common.h"
#include "vec3.h"

using gfx::Vec3f;

/* ---- 第 1 节：对齐和填充 ----
 *
 * 【思路】CPU 读一个 double 时，希望它的地址是 8 的倍数（对齐），否则可能更慢甚至出错。
 * 所以编译器会在字段之间塞入看不见的"填充字节"。字段的顺序不同，结构体大小就可能不同。
 */
struct BadOrder {
    char a;
    double b;
    char c;
    double d;
    char e;
};
struct GoodOrder {
    double b;
    double d;
    char a;
    char c;
    char e;
};

/* GPU 的一个著名的坑：很多着色器语言的 uniform 缓冲（std140）要求 vec3 按 16 字节对齐，而 C++ 里 Vec3f 是 12 字节。
 * 两边的布局不一样，数据就全错位了。解决办法：要么用 alignas，要么干脆不用 vec3。 */
struct LightCpp {
    Vec3f position;
    float intensity;
    Vec3f color;
    float radius;
};
struct alignas(16) Vec3Gpu {
    float x, y, z;
};
struct LightWrong {
    Vec3Gpu position;
    Vec3Gpu color;
    float intensity;
};

/* ---- 第 2 节：AoS vs SoA ----
 *
 * 一个典型的顶点：位置、法线、切线、纹理坐标、颜色。AoS 把它们放在一起，总共 64 字节。
 */
struct VertexAoS {
    float px, py, pz;
    float nx, ny, nz;
    float tx, ty, tz, tw;
    float u, v;
    float r, g, b, a;
};

/* SoA：每个分量一个数组。这里只需要用到位置这 3 个数组，其余的略去（内存里本来就不挨着）。 */
struct PositionsSoA {
    std::vector<float> px, py, pz;
};

__attribute__((noinline)) static void transform_aos(VertexAoS* __restrict v, size_t n, const float* m) {
    for (size_t i = 0; i < n; i++) {
        float x = v[i].px, y = v[i].py, z = v[i].pz;
        v[i].px = m[0] * x + m[1] * y + m[2] * z + m[3];
        v[i].py = m[4] * x + m[5] * y + m[6] * z + m[7];
        v[i].pz = m[8] * x + m[9] * y + m[10] * z + m[11];
    }
}

__attribute__((noinline)) static void transform_soa(float* __restrict px, float* __restrict py, float* __restrict pz, size_t n, const float* m) {
    for (size_t i = 0; i < n; i++) {
        float x = px[i], y = py[i], z = pz[i];
        px[i] = m[0] * x + m[1] * y + m[2] * z + m[3];
        py[i] = m[4] * x + m[5] * y + m[6] * z + m[7];
        pz[i] = m[8] * x + m[9] * y + m[10] * z + m[11];
    }
}

/* 只算所有顶点的 x 坐标之和：SoA 只碰 4/64 的数据。 */
__attribute__((noinline)) static float sum_x_aos(const VertexAoS* v, size_t n) {
    float s = 0.0f;
    for (size_t i = 0; i < n; i++) s = s + v[i].px;
    return s;
}

__attribute__((noinline)) static float sum_x_soa(const float* px, size_t n) {
    float s = 0.0f;
    for (size_t i = 0; i < n; i++) s = s + px[i];
    return s;
}

static void section_aos_soa() {
    std::printf("\n=== 2. AoS vs SoA：变换所有顶点的位置（真实计时，每个顶点的纳秒数）===\n");
    std::printf("  sizeof(VertexAoS) = %zu 字节，其中位置只有 12 字节\n", sizeof(VertexAoS));
    std::printf("  %10s %12s %10s %10s %8s %10s %10s %8s\n", "顶点数", "数据量(AoS)", "AoS 变换", "SoA 变换", "AoS/SoA", "AoS 求和", "SoA 求和", "AoS/SoA");
    float m[12] = {0.8f, -0.6f, 0.0f, 0.001f, 0.6f, 0.8f, 0.0f, -0.002f, 0.0f, 0.0f, 1.0f, 0.0f};    // 旋转 + 微小平移，反复作用也不会爆炸
    for (size_t n : {size_t(1000), size_t(10000), size_t(100000), size_t(1000000), size_t(10000000)}) {
        std::vector<VertexAoS> aos(n);
        PositionsSoA soa;
        soa.px.resize(n);
        soa.py.resize(n);
        soa.pz.resize(n);
        gfx::Lcg rng(n);
        for (size_t i = 0; i < n; i++) {
            float x = rng.uniform(), y = rng.uniform(), z = rng.uniform();
            aos[i].px = soa.px[i] = x;
            aos[i].py = soa.py[i] = y;
            aos[i].pz = soa.pz[i] = z;
        }
        size_t passes = 8'000'000 / n + 1;
        double t_aos = gfx::best_of(5, [&] { for (size_t p = 0; p < passes; p++) transform_aos(aos.data(), n, m); }) / double(passes);
        double t_soa = gfx::best_of(5, [&] { for (size_t p = 0; p < passes; p++) transform_soa(soa.px.data(), soa.py.data(), soa.pz.data(), n, m); }) / double(passes);
        float s1 = 0.0f, s2 = 0.0f;
        double t_sa = gfx::best_of(5, [&] { for (size_t p = 0; p < passes; p++) { s1 = sum_x_aos(aos.data(), n); gfx::keep(s1); } }) / double(passes);
        double t_ss = gfx::best_of(5, [&] { for (size_t p = 0; p < passes; p++) { s2 = sum_x_soa(soa.px.data(), n); gfx::keep(s2); } }) / double(passes);
        double f = 1e9 / double(n);
        std::printf("  %10zu %9.2f MB %7.3f ns %7.3f ns %7.1f倍 %7.3f ns %7.3f ns %7.1f倍\n",
                    n, double(n * sizeof(VertexAoS)) / 1e6, t_aos * f, t_soa * f, t_aos / t_soa, t_sa * f, t_ss * f, t_sa / t_ss);
    }
    std::printf("  观察：变换这一列，SoA 快 3~5 倍。AoS 每处理一个顶点都要跳过 52 字节用不到的数据，而且相邻的 x 不挨着，没法向量化；\n");
    std::printf("        SoA 里相邻的 x 挨在一起，编译器可以一次算 4 个。\n");
    std::printf("        求和这一列却几乎没有差别，这和预想的不一样：硬件预取器跟得上这种有规律的跨步访问，\n");
    std::printf("        而严格的浮点求和不能向量化（改变加法顺序会改变结果），瓶颈其实是加法本身的延迟。\n");
    std::printf("        注意 AoS 并非一无是处：如果每次都要用一个顶点的所有属性，它们挨在一起反而好。选哪种取决于访问模式。\n");
}

/* ---- 第 3 节：遍历顺序 ---- */
static void section_traversal() {
    std::printf("\n=== 3. 遍历顺序：图像在内存里是一行接一行的（真实计时，每像素的纳秒数）===\n");
    std::printf("  %14s %10s %10s %10s %14s %14s\n", "图像大小", "数据量", "按行", "按列", "随机顺序", "随机 / 按行");
    for (size_t w : {size_t(512), size_t(2048), size_t(8192)}) {
        size_t h = w * 9 / 16;
        size_t n = w * h;
        std::vector<float> img(n, 1.0f);
        std::vector<uint32_t> order(n);
        std::iota(order.begin(), order.end(), 0u);
        gfx::Lcg rng(w);
        gfx::shuffle(order, n, rng);
        float s = 0.0f;
        double t_row = gfx::best_of(5, [&] {
            float a = 0.0f;
            for (size_t y = 0; y < h; y++)
                for (size_t x = 0; x < w; x++) a = a + img[y * w + x];
            s = a;
            gfx::keep(a);
        });
        double t_col = gfx::best_of(5, [&] {
            float a = 0.0f;
            for (size_t x = 0; x < w; x++)
                for (size_t y = 0; y < h; y++) a = a + img[y * w + x];
            s = a;
            gfx::keep(a);
        });
        double t_rand = gfx::best_of(3, [&] {
            float a = 0.0f;
            for (size_t i = 0; i < n; i++) a = a + img[order[i]];
            s = a;
            gfx::keep(a);
        });
        double f = 1e9 / double(n);
        std::printf("  %7zu×%-6zu %7.1f MB %7.3f ns %7.3f ns %11.3f ns %12.1f 倍\n", w, h, double(n * 4) / 1e6, t_row * f, t_col * f, t_rand * f, t_rand / t_row);
        gfx::keep(s);
    }
    std::printf("  观察：完全相同的像素、完全相同的加法，只是顺序不同。图小的时候都在缓存里，差别不大；\n");
    std::printf("        图大了之后，按列和随机访问都要频繁地取新的缓存行。这台机器的缓存行是 128 字节。\n");
    std::printf("        纹理在显存里按小块（tile）存放，就是为了让屏幕上相邻的采样也在内存里相邻（第 10、12 讲）。\n");
}

int main() {
    std::printf("\n=== 1. 对齐和填充 ===\n");
    std::printf("  字段完全相同（3 个 char + 2 个 double，共 19 字节）：\n");
    std::printf("    BadOrder（char, double, char, double, char）  sizeof = %zu\n", sizeof(BadOrder));
    std::printf("    GoodOrder（double, double, char, char, char） sizeof = %zu\n", sizeof(GoodOrder));
    std::printf("    BadOrder 里各字段的偏移：a=%zu, b=%zu, c=%zu, d=%zu, e=%zu（中间的空隙就是填充）\n",
                offsetof(BadOrder, a), offsetof(BadOrder, b), offsetof(BadOrder, c), offsetof(BadOrder, d), offsetof(BadOrder, e));
    std::printf("  CPU 和 GPU 布局不一致的坑（着色器的 std140 规则要求 vec3 按 16 字节对齐）：\n");
    std::printf("    C++ 的 LightCpp：position@%zu, intensity@%zu, color@%zu, radius@%zu，sizeof = %zu\n",
                offsetof(LightCpp, position), offsetof(LightCpp, intensity), offsetof(LightCpp, color), offsetof(LightCpp, radius), sizeof(LightCpp));
    std::printf("    Vec3 按 16 字节对齐的 LightWrong：position@%zu, color@%zu, intensity@%zu，sizeof = %zu\n",
                offsetof(LightWrong, position), offsetof(LightWrong, color), offsetof(LightWrong, intensity), sizeof(LightWrong));
    section_aos_soa();
    section_traversal();
    return 0;
}
