// retroDE_ps2 — tb_top_psmct32_raster_demo_bram_swz4 (Ch298)
//
// TOP-LEVEL SWIZZLED PSMT4 INDEXED-TEXTURE + CLUT demo for the BRAM BOARD
// variant. Proves the real-PS2 PSMT4 BLOCK-layout texture path renders
// end-to-end through top_psmct32_raster_demo_bram with PSMT4_SWIZZLE=1:
//   - the texture UPLOAD (gif_image_xfer_stub) writes the 64x32 PSMT4 index
//     texture into VRAM at SWIZZLED block/column addresses, and
//   - the texture SAMPLER (gs_stub -> gs_texture_unit) reads it back through
//     the SAME swizzle, so the two VRAM views are CONSISTENT.
//
// The sampled sprite is 16 wide x 32 TALL — crossing the 16-px PSMT4 block
// ROW boundary (v=16) — so the bytes for v>=16 live in a DIFFERENT block than
// a linear layout would address. Reading them swizzled recovers the intended
// diagonal index ramp idx(x,y)=(x+2y)%16; reading the SAME bytes LINEARLY
// (PSMT4_SWIZZLE=0) would scramble across the block-row boundary.
//
// Fixture: payload_swz4.mem / bios_swz4.mem (NO new EE/BIOS scaffolding —
// GIF payload only, reuses the one-shot textured-demo bootlet).
//
// Expected (mirrors bake.py clut4_index + clut4_palette):
//   index(x,y) = (x + 2*y) mod 16 ; 16 boldly distinct PSMCT32 palette entries.

`timescale 1ns/1ps

module tb_top_psmct32_raster_demo_bram_swz4;

    localparam int H_ACTIVE = 16;
    localparam int V_ACTIVE = 32;
    localparam int TEXW = 16;     // sampled width (block column 0)
    localparam int TEXH = 32;     // sampled height (crosses block rows 0 & 1)

    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     (16 * 1024),   // texture lives at 0x2400..0x27FF
        .PSMCT32_SWIZZLE(1'b0),        // FB stays LINEAR PSMCT32
        .PSMT4_SWIZZLE  (1'b1)         // PSMT4 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 index + 16-entry palette (mirrors bake.py) -----
    function automatic int idx(input int x, input int y);
        return (x + 2*y) % 16;
    endfunction
    function automatic logic [7:0] pal_r(input int i);
        case (i)
            0:  return 8'h00; 1:  return 8'hFF; 2:  return 8'h00; 3:  return 8'h00;
            4:  return 8'hFF; 5:  return 8'hFF; 6:  return 8'h00; 7:  return 8'hFF;
            8:  return 8'h80; 9:  return 8'h00; 10: return 8'h00; 11: return 8'h80;
            12: return 8'h80; 13: return 8'h00; 14: return 8'hC0; default: return 8'h40;
        endcase
    endfunction
    function automatic logic [7:0] pal_g(input int i);
        case (i)
            0:  return 8'h00; 1:  return 8'h00; 2:  return 8'hFF; 3:  return 8'h00;
            4:  return 8'hFF; 5:  return 8'h00; 6:  return 8'hFF; 7:  return 8'hFF;
            8:  return 8'h00; 9:  return 8'h80; 10: return 8'h00; 11: return 8'h80;
            12: return 8'h00; 13: return 8'h80; 14: return 8'h60; default: return 8'h40;
        endcase
    endfunction
    function automatic logic [7:0] pal_b(input int i);
        case (i)
            0:  return 8'h00; 1:  return 8'h00; 2:  return 8'h00; 3:  return 8'hFF;
            4:  return 8'h00; 5:  return 8'hFF; 6:  return 8'hFF; 7:  return 8'hFF;
            8:  return 8'h00; 9:  return 8'h00; 10: return 8'h80; 11: return 8'h00;
            12: return 8'h80; 13: return 8'h80; 14: return 8'h20; default: return 8'h40;
        endcase
    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_row_ok;    // pixels in block-row-1 (y>=16) that matched
    initial begin errors = 0; tex_pixels_ok = 0; distinct_colors = 0; cross_row_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 PSMT4 indexed-textured region: each pixel is
        //     palette[index(x,y)] with index = (x+2y) mod 16. The sprite
        //     covers the WHOLE 16x32 window, crossing the v=16 block-row line. ---
        for (int y = 0; y < TEXH; y++) begin
            for (int x = 0; x < TEXW; x++) begin
                logic [7:0] er, eg, eb;
                int i;
                i  = idx(x, y);
                er = pal_r(i); eg = pal_g(i); eb = pal_b(i);
                if (!cap_de[y][x]) begin
                    $error("swz4 (%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("[swz4] (%0d,%0d) idx=%0d got (%02x,%02x,%02x) exp (%02x,%02x,%02x)",
                           x, y, i, 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 >= 16) cross_row_ok = cross_row_ok + 1;   // proves block-row-1 sampled OK
                end
            end
        end

        // --- the textured region must use MANY distinct palette colors
        //     (a stuck nibble or wrong-block swizzle collapses the ramp). ---
        begin
            logic [23:0] seen [0:15];
            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 < 16) begin seen[n] = key; n = n + 1; end
                end
            distinct_colors = n;
            if (distinct_colors < 12) begin
                $error("swz4 region shows only %0d distinct colors — nibble/CLUT/swizzle collapsed",
                       distinct_colors);
                errors = errors + 1;
            end
        end

        // The across-block-row proof: block row 1 (y in [16..31]) must have
        // sampled correctly — that's exactly where swizzle diverges from linear.
        if (cross_row_ok < 16*16) begin
            $error("swz4 block-row-1 (y>=16) only %0d/%0d pixels correct — across-block-boundary sampling failed",
                   cross_row_ok, 16*16);
            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_swz4] tex_ok=%0d/%0d cross_row_ok=%0d distinct_colors=%0d raster_emits=%0d errors=%0d",
                 tex_pixels_ok, TEXW*TEXH, cross_row_ok, distinct_colors,
                 dut.u_gs.raster_pixel_emit_count, errors);
        if (errors == 0)
            $display("[tb_top_psmct32_raster_demo_bram_swz4] PASS");
        else
            $display("[tb_top_psmct32_raster_demo_bram_swz4] FAIL");
        $finish;
    end

    initial begin
        #40000000;
        $error("[tb_top_psmct32_raster_demo_bram_swz4] TIMEOUT");
        $finish;
    end

endmodule : tb_top_psmct32_raster_demo_bram_swz4
