// retroDE_ps2 — tb_top_psmct32_raster_demo_bram_swz32 (Ch300)
//
// TOP-LEVEL SWIZZLED PSMCT32 (direct-color) texture demo for the BRAM BOARD
// variant — the CLOSURE rung of the swizzle layout family (after Ch298 swz4 +
// Ch299 swz8). PSMCT32 is DIRECT color (4 bytes/texel, NO CLUT), so the path is
// simpler than the indexed siblings. Proves the real-PS2 PSMCT32 page/block
// layout renders end-to-end through top_psmct32_raster_demo_bram with
// PSMCT32_SWIZZLE=1:
//   - the texture UPLOAD (gif_image_xfer_stub) writes the 16x48 PSMCT32 texture
//     into VRAM at SWIZZLED page/block addresses, and
//   - the texture SAMPLER (gs_stub -> gs_texture_unit) reads it back through the
//     SAME swizzle, so the two VRAM views are CONSISTENT.
// Because PSMCT32_SWIZZLE is a single per-format gate, the FRAMEBUFFER itself is
// ALSO swizzled here — proven coherent by the scanout, which de-swizzles back to
// raster order (this TB captures scanout pixels at raster (x,y), so a swizzled
// FB needs no change to the verify side).
//
// The sampled sprite is 16 wide x 40 TALL (a sub-window of a 22-wide texture —
// see the bake.py "heartbeat-splicer dodge" note for why the texture is wider
// than sampled) — crossing the 8-px PSMCT32 block ROW boundaries (y=8,16,24,32)
// AND — UNIQUELY for PSMCT32 vs the taller PSMT8 page — the 32-px PAGE-ROW
// boundary at v=32 (pixels v>=32 live in PAGE 1). Reading them swizzled recovers
// the intended coordinate-encoded gradient; reading the SAME bytes LINEARLY
// (PSMCT32_SWIZZLE=0) would scramble the bottom rows.
//
// Fixture: payload_swz32.mem / bios_swz32.mem (NO new EE/BIOS scaffolding —
// GIF payload only, reuses the one-shot textured-demo bootlet).
//
// Expected (mirrors bake.py swz32_texel):
//   color(x,y): R = x<<4, G = y*5, B = (x+y)<<2  (A dropped by scanout).

`timescale 1ns/1ps

module tb_top_psmct32_raster_demo_bram_swz32;

    localparam int H_ACTIVE = 16; // sampled sprite width (texture is 22 wide; cols 16..21 unsampled)
    localparam int V_ACTIVE = 40;
    localparam int TEXW = 16;     // sampled width  (crosses block col at x=8)
    localparam int TEXH = 40;     // sampled height (crosses block rows 8,16,24,32 + PAGE row y=32)

    logic clk;
    logic rst_n;
    initial clk = 1'b0;
    always #5 clk = ~clk;

    logic        core_go;
    logic [7:0]  r, g, b;
    logic        hsync, vsync, de;
    logic        core_halt;
    logic        dma_done_seen;
    logic        frame_seen;
    logic        raster_overflow;
    logic        frame_toggle;
    logic        dma_done_toggle;

    top_psmct32_raster_demo_bram #(
        .H_ACTIVE       (H_ACTIVE),
        .V_ACTIVE       (V_ACTIVE),
        .VRAM_BYTES     (32 * 1024),   // swizzled FB (pages 0..1) + texture at 0x3000..
        .PSMCT32_SWIZZLE(1'b1)         // PSMCT32 FB + texture upload + sample SWIZZLED
    ) dut (
        .clk(clk), .rst_n(rst_n),
        .core_go(core_go),
        .r(r), .g(g), .b(b),
        .hsync(hsync), .vsync(vsync), .de(de),
        .core_halt(core_halt),
        .dma_done_seen(dma_done_seen),
        .frame_seen(frame_seen),
        .raster_overflow(raster_overflow),
        .frame_toggle(frame_toggle),
        .dma_done_toggle(dma_done_toggle),
        .joy_a_pressed_i(1'b0),
        .joy_b_pressed_i(1'b0)
    );

    // ----- expected direct-color texel (mirrors bake.py swz32_texel) -----
    function automatic logic [7:0] exp_r(input int x, input int y); return 8'((x << 4)      & 8'hFF); endfunction
    function automatic logic [7:0] exp_g(input int x, input int y); return 8'((y * 5)        & 8'hFF); endfunction
    function automatic logic [7:0] exp_b(input int x, input int y); return 8'(((x + y) << 2) & 8'hFF); endfunction

    // ----- frame capture (VRAM_SYNC_READ=1 -> delayed counters) -----
    logic [7:0] cap_r [0:V_ACTIVE-1][0:H_ACTIVE-1];
    logic [7:0] cap_g [0:V_ACTIVE-1][0:H_ACTIVE-1];
    logic [7:0] cap_b [0:V_ACTIVE-1][0:H_ACTIVE-1];
    logic       cap_de[0:V_ACTIVE-1][0:H_ACTIVE-1];
    bit         capture_armed;

    initial begin
        for (int y = 0; y < V_ACTIVE; y++)
            for (int x = 0; x < H_ACTIVE; x++) begin
                cap_r[y][x] = 0; cap_g[y][x] = 0; cap_b[y][x] = 0; cap_de[y][x] = 0;
            end
        capture_armed = 1'b0;
    end

    logic [31:0] hcnt_d, vcnt_d;
    always_ff @(posedge clk) begin
        if (!rst_n) begin hcnt_d <= 0; vcnt_d <= 0; end
        else        begin hcnt_d <= 32'(dut.u_pcrtc.hcnt); vcnt_d <= 32'(dut.u_pcrtc.vcnt); end
    end
    always_ff @(posedge clk) begin
        if (rst_n && capture_armed && de && (vcnt_d < V_ACTIVE) && (hcnt_d < H_ACTIVE)) begin
            cap_r [vcnt_d][hcnt_d] <= r;
            cap_g [vcnt_d][hcnt_d] <= g;
            cap_b [vcnt_d][hcnt_d] <= b;
            cap_de[vcnt_d][hcnt_d] <= 1'b1;
        end
    end

    int errors;
    int tex_pixels_ok;
    int distinct_colors;
    int cross_page_ok;   // pixels in PAGE row 1 (y>=32) that matched
    initial begin errors = 0; tex_pixels_ok = 0; distinct_colors = 0; cross_page_ok = 0; end

    initial begin
        rst_n   = 1'b0;
        core_go = 1'b0;
        repeat (4) @(posedge clk);
        rst_n = 1'b1;
        repeat (8) @(posedge clk);

        @(negedge clk); core_go = 1'b1;
        @(negedge clk); core_go = 1'b0;

        wait (core_halt == 1'b1);
        repeat (4) @(posedge clk);
        wait (dma_done_seen == 1'b1);
        repeat (10) @(posedge clk);
        if (dut.xfer_busy == 1'b1)            wait (dut.xfer_busy == 1'b0);
        if (dut.clut_ld_busy == 1'b1)         wait (dut.clut_ld_busy == 1'b0);
        if (dut.u_gs.raster_active == 1'b1)   wait (dut.u_gs.raster_active == 1'b0);
        repeat (10) @(posedge clk);

        @(posedge dut.u_pcrtc.end_of_frame);
        @(posedge clk);
        capture_armed = 1'b1;
        @(posedge dut.u_pcrtc.end_of_frame);
        @(posedge clk);
        capture_armed = 1'b0;

        // --- swizzled PSMCT32 direct-color region: each pixel is the
        //     coordinate-encoded texel color. The sprite covers the WHOLE 16x48
        //     window, crossing the 8-px block rows AND the 32-px page row at v=32. ---
        for (int y = 0; y < TEXH; y++) begin
            for (int x = 0; x < TEXW; x++) begin
                logic [7:0] er, eg, eb;
                er = exp_r(x, y); eg = exp_g(x, y); eb = exp_b(x, y);
                if (!cap_de[y][x]) begin
                    $error("swz32 (%0d,%0d) DE never asserted", x, y);
                    errors = errors + 1;
                end else if (cap_r[y][x] !== er || cap_g[y][x] !== eg || cap_b[y][x] !== eb) begin
                    $error("[swz32] (%0d,%0d) got (%02x,%02x,%02x) exp (%02x,%02x,%02x)",
                           x, y, cap_r[y][x], cap_g[y][x], cap_b[y][x], er, eg, eb);
                    errors = errors + 1;
                end else begin
                    tex_pixels_ok = tex_pixels_ok + 1;
                    if (y >= 32) cross_page_ok = cross_page_ok + 1;  // proves PAGE 1 sampled OK
                end
            end
        end

        // --- the textured region must use MANY distinct colors (a stuck channel
        //     or wrong-block/page swizzle collapses the gradient). ---
        begin
            logic [23:0] seen [0:255];
            int n;
            n = 0;
            for (int y = 0; y < TEXH; y++)
                for (int x = 0; x < TEXW; x++) begin
                    logic [23:0] key;
                    bit found;
                    key = {cap_b[y][x], cap_g[y][x], cap_r[y][x]};
                    found = 1'b0;
                    for (int k = 0; k < n; k++) if (seen[k] === key) found = 1'b1;
                    if (!found && n < 256) begin seen[n] = key; n = n + 1; end
                end
            distinct_colors = n;
            if (distinct_colors < 64) begin
                $error("swz32 region shows only %0d distinct colors — channel/swizzle collapsed",
                       distinct_colors);
                errors = errors + 1;
            end
        end

        // The across-PAGE proof: PAGE row 1 (y in [32..39]) must have sampled
        // correctly — that's exactly where the PSMCT32 swizzle diverges hardest
        // from linear (a whole 8 KiB page hop).
        if (cross_page_ok < 16*8) begin
            $error("swz32 page-row 1 (y>=32) only %0d/%0d pixels correct — across-PAGE sampling failed",
                   cross_page_ok, 16*8);
            errors = errors + 1;
        end

        if (!core_halt)      begin $error("core_halt low at end");        errors = errors + 1; end
        if (!dma_done_seen)  begin $error("dma_done_seen never latched"); errors = errors + 1; end
        if (!frame_seen)     begin $error("frame_seen never latched");    errors = errors + 1; end
        if (raster_overflow) begin $error("raster_overflow set");         errors = errors + 1; end

        $display("[tb_top_psmct32_raster_demo_bram_swz32] tex_ok=%0d/%0d cross_page_ok=%0d distinct_colors=%0d raster_emits=%0d errors=%0d",
                 tex_pixels_ok, TEXW*TEXH, cross_page_ok, distinct_colors,
                 dut.u_gs.raster_pixel_emit_count, errors);
        if (errors == 0)
            $display("[tb_top_psmct32_raster_demo_bram_swz32] PASS");
        else
            $display("[tb_top_psmct32_raster_demo_bram_swz32] FAIL");
        $finish;
    end

    initial begin
        #60000000;
        $error("[tb_top_psmct32_raster_demo_bram_swz32] TIMEOUT");
        $finish;
    end

endmodule : tb_top_psmct32_raster_demo_bram_swz32
