// retroDE_ps2 — tb_gs_raster_swizzle_psmt8 (Ch134)
//
// Third write-side wiring of the Ch131 PSMT8 swizzle math — this
// time into gs_stub's raster emit channel (the per-pixel store
// path that backs SPRITE/TRI primitives). With the new
// `PSMT8_SWIZZLE=1` parameter on gs_stub, the per-pixel VRAM byte
// address goes through `gs_swizzle_psmt8_stub` instead of the
// legacy linear formula `(FBW*64*y + x) * 1`. PSMCT32 is gated by
// PSMCT32_SWIZZLE (Ch122); PSMCT16 by PSMCT16_SWIZZLE (Ch128);
// PSMT4 raster emits always stay on the linear path. Default off
// → every existing PSMT8 raster TB (Ch105 etc.) is unaffected.
// Mirrors Ch128's PSMCT16 raster wiring shape but for the third
// PSM and uses Ch132's swizzled-pcrtc as the read-side cross-
// check.
//
// Topology — keeps the proof end-to-end (mirrors Ch128 / Ch133):
//
//   TB drives PRIM/FRAME_1/RGBAQ/XYZ2 via gif_reg_wr_*
//        →  gs_stub#(PSMT8_SWIZZLE=1)         (raster emit)
//        →  vram_stub                         (PSMT8 byte store)
//        →  gs_pcrtc_stub#(PSMT8_SWIZZLE=1)   (swizzled scanout)
//        →  r/g/b
//
// Phase 1 (write-side lock): drive a 16×8 SPRITE that fills the
// rect (0,0)..(15,7) — 128 PSMT8 pixels at 1 byte/pixel. PSMT8
// blocks are 16×16 pixels, so the rect lives in the upper half
// of block (0,0) of page (0,0). PSMT8 uses FBW=2 here (PCSX2
// asserts FBW must be even; 2 is the minimum even FBW). The
// within-block columnTable8 distributes those 128 bytes across
// xb=0..15 / yb=0..7 — covering yb rows 0..7 of the column
// table, which produces byte values 0..127. Single per-primitive
// RGBAQ.R = 0xA5 (the PSMT8 raster channel uses R as the index;
// Ch105) is enough to lock the address layout: every byte the
// swizzle says should be written is verified to hold 0xA5; bytes
// outside the swizzled write set stay 0 — proves the gate is
// live since a fall-through to linear addressing (PSMT8 stride =
// FBW*64 = 128) would put the sprite byte at byte 128 (linear
// y=1 row start), which is strictly outside the swizzled set
// [0..127].
//
// Phase 2 (end-to-end agreement): without redrawing, enable the
// Ch132 swizzled-pcrtc path, capture the full 16×8 frame, assert
// every visible pixel reads back as PCRTC's PSMT8 grayscale
// fallback (R=G=B=idx=0xA5). Both gs_stub (Ch134) and
// gs_pcrtc_stub (Ch132) instantiate the same gs_swizzle_psmt8_stub;
// a successful capture proves the two integrations agree at byte
// level — what raster wrote at swizzled addresses comes out on
// r/g/b at the same (x, y).
//
// Phase 3 (non-origin raster): re-arm gs_stub with FRAME_1 set to
// FBP=4, FBW=4 and draw an 8×4 SPRITE at (124, 4)..(131, 7).
// This pins three contracts Phase 1 can't:
//   (a) `ras_fbp` reaches the swizzle's `fbp` input (FBP=0 in
//       Phase 1 would have masked a tied-zero regression).
//   (b) `ras_fbw` reaches the swizzle's `fbw` input (FBW=2 would
//       have masked a tied-two regression).
//   (c) The swizzle gets the FULL absolute pixel coords (s2_x_q,
//       s2_y_q) rather than bbox-local — Phase 1's sprite started
//       at (0,0) so absolute and local were equal there. The
//       Phase-3 rect crosses the PAGE-x boundary at x=128 (page
//       (0,0) for x∈[124..127], page (1,0) for x∈[128..131]) so
//       page_index changes mid-row. PSMT8's page-x boundary is at
//       x=128 (different from CT32/CT16's x=64) — exercises the
//       PSMT8-specific x[7] wiring of the swizzle.
//
// Phase 3 strict separator: under linear the (124, 4) pixel lands
// at byte:
//   FBP*2048 + 4*FBW*64 + 124
//   = 8192 + 1024 + 124
//   = 9340.
// Under swizzled the Phase-3 write set lives in:
//   page (0,0) block (0,7) (blockTable8[0][7]=21) at base 13568
//   page (1,0) block (0,0) (blockTable8[0][0]=0)  at base 16384
// Byte 9340 sits between page 0's start (8192) and the block-
// (0,7) base (13568) — strictly outside the swizzled write set.
// If raster had fallen through to linear, byte 9340 would hold
// P3's byte. Assert it stays 0.

`timescale 1ns/1ps

module tb_gs_raster_swizzle_psmt8;

    localparam int PCRTC_H_ACTIVE = 16;
    localparam int PCRTC_V_ACTIVE = 8;

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

    // ------------------------------------------------------------
    // gs_stub I/O
    // ------------------------------------------------------------
    logic        gif_reg_wr_en;
    logic [7:0]  gif_reg_num;
    logic [63:0] gif_reg_data;

    logic        priv_reg_wr_en;
    logic [15:0] priv_reg_wr_addr;
    logic [63:0] priv_reg_wr_data;

    logic [7:0]          bg_r, bg_g, bg_b;
    logic [63:0]         pmode_q, dispfb1_q, display1_q;
    logic [63:0]         prim_q, rgbaq_q, xyz2_q, xyzf2_q, frame_1_q, zbuf_1_q;
    logic [63:0]         tex0_1_q;
    logic [13:0]         tex0_1_cbp_q;
    logic [3:0]          tex0_1_cpsm_q;
    logic                tex0_1_csm_q;
    logic [4:0]          tex0_1_csa_q;
    logic [2:0]          tex0_1_cld_q;
    logic                tex0_1_wr_q;
    logic [63:0]         bitbltbuf_q, trxpos_q, trxreg_q, trxdir_q;
    logic                trxdir_wr_q;
    logic                prim_complete;
    logic [31:0]         prim_complete_count;
    logic [63:0]         prim_v0_q, prim_v1_q, prim_v2_q;
    logic [63:0]         prim_color_q;
    logic [63:0]         prim_color_v0_q, prim_color_v1_q, prim_color_v2_q;
    trace_pkg::vertex_t  prim_v0_decoded_q, prim_v1_decoded_q, prim_v2_decoded_q;
    trace_pkg::color_t   prim_v0_color_decoded_q, prim_v1_color_decoded_q, prim_v2_color_decoded_q;
    logic                pixel_emit;
    logic [31:0]         pixel_emit_count;
    logic [11:0]         pixel_x_q, pixel_y_q;
    logic [63:0]         pixel_color_q;
    logic [8:0]          pixel_fbp_q;
    logic [5:0]          pixel_fbw_q, pixel_psm_q;
    logic [31:0]         pixel_fb_addr_q;
    logic                raster_pixel_emit;
    logic [31:0]         raster_pixel_emit_count;
    logic [11:0]         raster_pixel_x_q, raster_pixel_y_q;
    logic [63:0]         raster_pixel_color_q;
    logic [31:0]         raster_pixel_fb_addr_q;
    logic [3:0]          raster_pixel_be_q;
    logic [31:0]         raster_pixel_mask_q;
    logic [5:0]          raster_pixel_psm_q;
    logic                raster_active;
    logic                raster_overflow;
    logic                raster_degenerate;
    logic                gs_ev_valid;
    trace_pkg::subsys_e  gs_ev_subsys;
    trace_pkg::event_e   gs_ev_event;
    logic [63:0]         gs_ev_arg0, gs_ev_arg1, gs_ev_arg2, gs_ev_arg3;
    logic [31:0]         gs_ev_flags;

    gs_stub #(
        .PSMCT32_SWIZZLE(1'b0),
        .PSMCT16_SWIZZLE(1'b0),
        .PSMT8_SWIZZLE  (1'b1)
    ) u_gs (
        .clk(clk), .rst_n(rst_n),
        .reg_wr_en  (priv_reg_wr_en),
        .reg_wr_addr(priv_reg_wr_addr),
        .reg_wr_data(priv_reg_wr_data),
        .gif_reg_wr_en(gif_reg_wr_en),
        .gif_reg_num(gif_reg_num),
        .gif_reg_data(gif_reg_data),
        .bg_r(bg_r), .bg_g(bg_g), .bg_b(bg_b),
        .pmode_q(pmode_q), .dispfb1_q(dispfb1_q), .display1_q(display1_q),
        .prim_q(prim_q), .rgbaq_q(rgbaq_q),
        .xyz2_q(xyz2_q), .xyzf2_q(xyzf2_q),
        .frame_1_q(frame_1_q), .zbuf_1_q(zbuf_1_q),
        .tex0_1_q(tex0_1_q),
        .tex0_1_cbp_q(tex0_1_cbp_q),
        .tex0_1_cpsm_q(tex0_1_cpsm_q),
        .tex0_1_csm_q(tex0_1_csm_q),
        .tex0_1_csa_q(tex0_1_csa_q),
        .tex0_1_cld_q(tex0_1_cld_q),
        .tex0_1_wr_q(tex0_1_wr_q),
        .bitbltbuf_q(bitbltbuf_q),
        .trxpos_q(trxpos_q),
        .trxreg_q(trxreg_q),
        .trxdir_q(trxdir_q),
        .trxdir_wr_q(trxdir_wr_q),
        .prim_complete(prim_complete),
        .prim_complete_count(prim_complete_count),
        .prim_v0_q(prim_v0_q), .prim_v1_q(prim_v1_q), .prim_v2_q(prim_v2_q),
        .prim_color_q(prim_color_q),
        .prim_color_v0_q(prim_color_v0_q),
        .prim_color_v1_q(prim_color_v1_q),
        .prim_color_v2_q(prim_color_v2_q),
        .prim_v0_decoded_q(prim_v0_decoded_q),
        .prim_v1_decoded_q(prim_v1_decoded_q),
        .prim_v2_decoded_q(prim_v2_decoded_q),
        .prim_v0_color_decoded_q(prim_v0_color_decoded_q),
        .prim_v1_color_decoded_q(prim_v1_color_decoded_q),
        .prim_v2_color_decoded_q(prim_v2_color_decoded_q),
        .pixel_emit(pixel_emit),
        .pixel_emit_count(pixel_emit_count),
        .pixel_x_q(pixel_x_q), .pixel_y_q(pixel_y_q),
        .pixel_color_q(pixel_color_q),
        .pixel_fbp_q(pixel_fbp_q),
        .pixel_fbw_q(pixel_fbw_q),
        .pixel_psm_q(pixel_psm_q),
        .pixel_fb_addr_q(pixel_fb_addr_q),
        .raster_pixel_emit(raster_pixel_emit),
        .raster_pixel_emit_count(raster_pixel_emit_count),
        .raster_pixel_x_q(raster_pixel_x_q),
        .raster_pixel_y_q(raster_pixel_y_q),
        .raster_pixel_color_q(raster_pixel_color_q),
        .raster_pixel_fb_addr_q(raster_pixel_fb_addr_q),
        .raster_pixel_be_q(raster_pixel_be_q),
        .raster_pixel_mask_q(raster_pixel_mask_q),
        .raster_pixel_psm_q(raster_pixel_psm_q),
        .raster_active(raster_active),
        .raster_overflow(raster_overflow),
        .raster_degenerate(raster_degenerate),
        .ev_valid(gs_ev_valid),
        .ev_subsys(gs_ev_subsys),
        .ev_event(gs_ev_event),
        .ev_arg0(gs_ev_arg0), .ev_arg1(gs_ev_arg1),
        .ev_arg2(gs_ev_arg2), .ev_arg3(gs_ev_arg3),
        .ev_flags(gs_ev_flags)
    );

    // ------------------------------------------------------------
    // vram_stub. Two readers: pcrtc (Phase 2) + TB (Phase 1/3).
    // ------------------------------------------------------------
    logic [31:0] vram_read_addr;
    logic [31:0] vram_read_data;
    logic [31:0] vram_read2_addr;
    logic [31:0] vram_read2_data;

    vram_stub #(.BYTES(65536)) u_vram (
        .clk(clk), .rst_n(rst_n),
        .write_en  (raster_pixel_emit),
        .write_addr(raster_pixel_fb_addr_q),
        .write_data(raster_pixel_color_q[31:0]),
        .write_be  (raster_pixel_be_q),
        .write_mask(raster_pixel_mask_q),
        .read_addr (vram_read_addr),
        .read_data (vram_read_data),
        .read2_addr(vram_read2_addr),
        .read2_data(vram_read2_data)
    );

    // ------------------------------------------------------------
    // gs_pcrtc_stub with the Ch132 PSMT8_SWIZZLE gate ON (and the
    // Ch120/Ch126 gates explicitly OFF — this TB exercises only
    // the PSMT8 scanout path).
    // ------------------------------------------------------------
    logic       hsync_o, vsync_o, de_o;
    logic [7:0] r_o, g_o, b_o;
    logic                pcrtc_ev_valid;
    trace_pkg::subsys_e  pcrtc_ev_subsys;
    trace_pkg::event_e   pcrtc_ev_event;
    logic [63:0]         pcrtc_ev_arg0, pcrtc_ev_arg1;
    logic [63:0]         pcrtc_ev_arg2, pcrtc_ev_arg3;
    logic [31:0]         pcrtc_ev_flags;

    gs_pcrtc_stub #(
        .H_ACTIVE(PCRTC_H_ACTIVE), .H_FRONT(1), .H_SYNC(1), .H_BACK(1),
        .V_ACTIVE(PCRTC_V_ACTIVE), .V_FRONT(1), .V_SYNC(1), .V_BACK(1),
        .PSMCT32_SWIZZLE(1'b0),
        .PSMCT16_SWIZZLE(1'b0),
        .PSMT8_SWIZZLE  (1'b1)
    ) u_pcrtc (
        .clk(clk), .rst_n(rst_n),
        .pmode_q       (pmode_q),
        .dispfb1_q     (dispfb1_q),
        .display1_q    (display1_q),
        .vram_read_addr(vram_read_addr),
        .vram_read_data(vram_read_data),
        .clut_enable   (1'b0),
        .clut_csa      (5'd0),
        .clut_read_idx (),
        .clut_read_data(32'd0),
        .hsync(hsync_o), .vsync(vsync_o), .de(de_o),
        .r(r_o), .g(g_o), .b(b_o),
        .ev_valid(pcrtc_ev_valid),
        .ev_subsys(pcrtc_ev_subsys),
        .ev_event(pcrtc_ev_event),
        .ev_arg0(pcrtc_ev_arg0), .ev_arg1(pcrtc_ev_arg1),
        .ev_arg2(pcrtc_ev_arg2), .ev_arg3(pcrtc_ev_arg3),
        .ev_flags(pcrtc_ev_flags)
    );

    // ------------------------------------------------------------
    // Frame capture (Phase 2).
    // ------------------------------------------------------------
    logic [7:0] cap_r [0:PCRTC_V_ACTIVE-1][0:PCRTC_H_ACTIVE-1];
    logic [7:0] cap_g [0:PCRTC_V_ACTIVE-1][0:PCRTC_H_ACTIVE-1];
    logic [7:0] cap_b [0:PCRTC_V_ACTIVE-1][0:PCRTC_H_ACTIVE-1];
    logic       cap_de[0:PCRTC_V_ACTIVE-1][0:PCRTC_H_ACTIVE-1];

    int errors;
    bit capture_armed;

    initial begin
        for (int y = 0; y < PCRTC_V_ACTIVE; y++)
            for (int x = 0; x < PCRTC_H_ACTIVE; x++) begin
                cap_r[y][x]  = 8'd0;
                cap_g[y][x]  = 8'd0;
                cap_b[y][x]  = 8'd0;
                cap_de[y][x] = 1'b0;
            end
        errors        = 0;
        capture_armed = 1'b0;
    end

    // ------------------------------------------------------------
    // Per-emit PSMT8 lane-shape observer. Ties the address-gate
    // proof to the intended PSM packing: raster_pixel_psm_q must
    // be PSMT8 (=0x13), be must be 4'b0001 (1-byte commit), mask
    // must be 0xFFFFFFFF (no nibble RMW). Catches a regression
    // that flipped the swizzle gate but corrupted the lane shape.
    // ------------------------------------------------------------
    int raster_obs_seen;
    initial raster_obs_seen = 0;

    always_ff @(posedge clk) begin
        if (rst_n && raster_pixel_emit) begin
            raster_obs_seen <= raster_obs_seen + 1;
            if (raster_pixel_psm_q !== 6'h13) begin
                $error("emit %0d: psm=0x%02x (expected 0x13 PSMT8)",
                       raster_obs_seen, raster_pixel_psm_q);
                errors <= errors + 1;
            end
            if (raster_pixel_be_q !== 4'b0001) begin
                $error("emit %0d: be=%b (expected 4'b0001 for PSMT8)",
                       raster_obs_seen, raster_pixel_be_q);
                errors <= errors + 1;
            end
            if (raster_pixel_mask_q !== 32'hFFFF_FFFF) begin
                $error("emit %0d: mask=0x%08x (expected 0xFFFF_FFFF for PSMT8)",
                       raster_obs_seen, raster_pixel_mask_q);
                errors <= errors + 1;
            end
        end
    end

    always_ff @(posedge clk) begin
        if (rst_n && capture_armed && de_o
            && (u_pcrtc.vcnt < PCRTC_V_ACTIVE)
            && (u_pcrtc.hcnt < PCRTC_H_ACTIVE)) begin
            cap_r [u_pcrtc.vcnt][u_pcrtc.hcnt] <= r_o;
            cap_g [u_pcrtc.vcnt][u_pcrtc.hcnt] <= g_o;
            cap_b [u_pcrtc.vcnt][u_pcrtc.hcnt] <= b_o;
            cap_de[u_pcrtc.vcnt][u_pcrtc.hcnt] <= 1'b1;
        end
    end

    // ------------------------------------------------------------
    // GIF / priv reg drive helpers.
    // ------------------------------------------------------------
    task automatic step_drive(input logic        wr_en,
                              input logic [7:0]  num,
                              input logic [63:0] data);
        @(negedge clk);
        gif_reg_wr_en = wr_en;
        gif_reg_num   = num;
        gif_reg_data  = data;
        @(posedge clk);
    endtask

    task automatic drive_reg(input logic [7:0] num, input logic [63:0] data);
        step_drive(1'b1, num, data);
    endtask

    task automatic drive_idle();
        step_drive(1'b0, 8'd0, 64'd0);
    endtask

    task automatic drive_priv(input logic [15:0] addr,
                              input logic [63:0] data);
        @(negedge clk);
        priv_reg_wr_en   = 1'b1;
        priv_reg_wr_addr = addr;
        priv_reg_wr_data = data;
        @(posedge clk);
        @(negedge clk);
        priv_reg_wr_en   = 1'b0;
        priv_reg_wr_addr = 16'd0;
        priv_reg_wr_data = 64'd0;
    endtask

    function automatic logic [63:0] xyz2_data(input logic [11:0] x_int,
                                              input logic [11:0] y_int);
        return {32'd0, y_int, 4'd0, x_int, 4'd0};
    endfunction

    // ------------------------------------------------------------
    // PSMT8 swizzle reference — block + column tables verbatim
    // from PCSX2 (Ch131 source-locked).
    // ------------------------------------------------------------
    function automatic int ref_block_idx8(input int by, input int bx);
        case ({by[1:0], bx[2:0]})
            5'd0:  return  0;  5'd1:  return  1;  5'd2:  return  4;  5'd3:  return  5;
            5'd4:  return 16;  5'd5:  return 17;  5'd6:  return 20;  5'd7:  return 21;
            5'd8:  return  2;  5'd9:  return  3;  5'd10: return  6;  5'd11: return  7;
            5'd12: return 18;  5'd13: return 19;  5'd14: return 22;  5'd15: return 23;
            5'd16: return  8;  5'd17: return  9;  5'd18: return 12;  5'd19: return 13;
            5'd20: return 24;  5'd21: return 25;  5'd22: return 28;  5'd23: return 29;
            5'd24: return 10;  5'd25: return 11;  5'd26: return 14;  5'd27: return 15;
            5'd28: return 26;  5'd29: return 27;  5'd30: return 30;  default: return 31;
        endcase
    endfunction

    function automatic int ref_col_idx8(input int yb, input int xb);
        case ({yb[3:0], xb[3:0]})
            8'd0:   return   0; 8'd1:   return   4; 8'd2:   return  16; 8'd3:   return  20;
            8'd4:   return  32; 8'd5:   return  36; 8'd6:   return  48; 8'd7:   return  52;
            8'd8:   return   2; 8'd9:   return   6; 8'd10:  return  18; 8'd11:  return  22;
            8'd12:  return  34; 8'd13:  return  38; 8'd14:  return  50; 8'd15:  return  54;
            8'd16:  return   8; 8'd17:  return  12; 8'd18:  return  24; 8'd19:  return  28;
            8'd20:  return  40; 8'd21:  return  44; 8'd22:  return  56; 8'd23:  return  60;
            8'd24:  return  10; 8'd25:  return  14; 8'd26:  return  26; 8'd27:  return  30;
            8'd28:  return  42; 8'd29:  return  46; 8'd30:  return  58; 8'd31:  return  62;
            8'd32:  return  33; 8'd33:  return  37; 8'd34:  return  49; 8'd35:  return  53;
            8'd36:  return   1; 8'd37:  return   5; 8'd38:  return  17; 8'd39:  return  21;
            8'd40:  return  35; 8'd41:  return  39; 8'd42:  return  51; 8'd43:  return  55;
            8'd44:  return   3; 8'd45:  return   7; 8'd46:  return  19; 8'd47:  return  23;
            8'd48:  return  41; 8'd49:  return  45; 8'd50:  return  57; 8'd51:  return  61;
            8'd52:  return   9; 8'd53:  return  13; 8'd54:  return  25; 8'd55:  return  29;
            8'd56:  return  43; 8'd57:  return  47; 8'd58:  return  59; 8'd59:  return  63;
            8'd60:  return  11; 8'd61:  return  15; 8'd62:  return  27; 8'd63:  return  31;
            8'd64:  return  96; 8'd65:  return 100; 8'd66:  return 112; 8'd67:  return 116;
            8'd68:  return  64; 8'd69:  return  68; 8'd70:  return  80; 8'd71:  return  84;
            8'd72:  return  98; 8'd73:  return 102; 8'd74:  return 114; 8'd75:  return 118;
            8'd76:  return  66; 8'd77:  return  70; 8'd78:  return  82; 8'd79:  return  86;
            8'd80:  return 104; 8'd81:  return 108; 8'd82:  return 120; 8'd83:  return 124;
            8'd84:  return  72; 8'd85:  return  76; 8'd86:  return  88; 8'd87:  return  92;
            8'd88:  return 106; 8'd89:  return 110; 8'd90:  return 122; 8'd91:  return 126;
            8'd92:  return  74; 8'd93:  return  78; 8'd94:  return  90; 8'd95:  return  94;
            8'd96:  return  65; 8'd97:  return  69; 8'd98:  return  81; 8'd99:  return  85;
            8'd100: return  97; 8'd101: return 101; 8'd102: return 113; 8'd103: return 117;
            8'd104: return  67; 8'd105: return  71; 8'd106: return  83; 8'd107: return  87;
            8'd108: return  99; 8'd109: return 103; 8'd110: return 115; 8'd111: return 119;
            8'd112: return  73; 8'd113: return  77; 8'd114: return  89; 8'd115: return  93;
            8'd116: return 105; 8'd117: return 109; 8'd118: return 121; 8'd119: return 125;
            8'd120: return  75; 8'd121: return  79; 8'd122: return  91; 8'd123: return  95;
            8'd124: return 107; 8'd125: return 111; 8'd126: return 123; 8'd127: return 127;
            8'd128: return 128; 8'd129: return 132; 8'd130: return 144; 8'd131: return 148;
            8'd132: return 160; 8'd133: return 164; 8'd134: return 176; 8'd135: return 180;
            8'd136: return 130; 8'd137: return 134; 8'd138: return 146; 8'd139: return 150;
            8'd140: return 162; 8'd141: return 166; 8'd142: return 178; 8'd143: return 182;
            8'd144: return 136; 8'd145: return 140; 8'd146: return 152; 8'd147: return 156;
            8'd148: return 168; 8'd149: return 172; 8'd150: return 184; 8'd151: return 188;
            8'd152: return 138; 8'd153: return 142; 8'd154: return 154; 8'd155: return 158;
            8'd156: return 170; 8'd157: return 174; 8'd158: return 186; 8'd159: return 190;
            8'd160: return 161; 8'd161: return 165; 8'd162: return 177; 8'd163: return 181;
            8'd164: return 129; 8'd165: return 133; 8'd166: return 145; 8'd167: return 149;
            8'd168: return 163; 8'd169: return 167; 8'd170: return 179; 8'd171: return 183;
            8'd172: return 131; 8'd173: return 135; 8'd174: return 147; 8'd175: return 151;
            8'd176: return 169; 8'd177: return 173; 8'd178: return 185; 8'd179: return 189;
            8'd180: return 137; 8'd181: return 141; 8'd182: return 153; 8'd183: return 157;
            8'd184: return 171; 8'd185: return 175; 8'd186: return 187; 8'd187: return 191;
            8'd188: return 139; 8'd189: return 143; 8'd190: return 155; 8'd191: return 159;
            8'd192: return 224; 8'd193: return 228; 8'd194: return 240; 8'd195: return 244;
            8'd196: return 192; 8'd197: return 196; 8'd198: return 208; 8'd199: return 212;
            8'd200: return 226; 8'd201: return 230; 8'd202: return 242; 8'd203: return 246;
            8'd204: return 194; 8'd205: return 198; 8'd206: return 210; 8'd207: return 214;
            8'd208: return 232; 8'd209: return 236; 8'd210: return 248; 8'd211: return 252;
            8'd212: return 200; 8'd213: return 204; 8'd214: return 216; 8'd215: return 220;
            8'd216: return 234; 8'd217: return 238; 8'd218: return 250; 8'd219: return 254;
            8'd220: return 202; 8'd221: return 206; 8'd222: return 218; 8'd223: return 222;
            8'd224: return 193; 8'd225: return 197; 8'd226: return 209; 8'd227: return 213;
            8'd228: return 225; 8'd229: return 229; 8'd230: return 241; 8'd231: return 245;
            8'd232: return 195; 8'd233: return 199; 8'd234: return 211; 8'd235: return 215;
            8'd236: return 227; 8'd237: return 231; 8'd238: return 243; 8'd239: return 247;
            8'd240: return 201; 8'd241: return 205; 8'd242: return 217; 8'd243: return 221;
            8'd244: return 233; 8'd245: return 237; 8'd246: return 249; 8'd247: return 253;
            8'd248: return 203; 8'd249: return 207; 8'd250: return 219; 8'd251: return 223;
            8'd252: return 235; 8'd253: return 239; 8'd254: return 251; default: return 255;
        endcase
    endfunction

    function automatic logic [31:0] ref_addr8(
        input int fbp_v, input int fbw_v, input int x_v, input int y_v);
        int page_x, page_y, bw_pg_v, page_idx, page_base;
        int by, bx, blk_idx, xb, yb, byte_idx;
        int addr_v;
        page_x   = x_v / 128;
        page_y   = y_v / 64;
        bw_pg_v  = fbw_v / 2;
        page_idx = page_y * bw_pg_v + page_x;
        page_base = fbp_v * 2048 + page_idx * 8192;
        by  = (y_v % 64)  / 16;
        bx  = (x_v % 128) / 16;
        blk_idx = ref_block_idx8(by, bx);
        xb = x_v % 16;
        yb = y_v % 16;
        byte_idx = ref_col_idx8(yb, xb);
        addr_v = page_base + blk_idx * 256 + byte_idx;
        return addr_v[31:0];
    endfunction

    // ------------------------------------------------------------
    // Phase 1 / 2 constants. PSMT8 stride = FBW*64 = 128 (FBW=2).
    // ------------------------------------------------------------
    localparam logic [7:0]  R_PRIM     = 8'h00;
    localparam logic [7:0]  R_RGBAQ    = 8'h01;
    localparam logic [7:0]  R_XYZ2     = 8'h05;
    localparam logic [7:0]  R_FRAME_1  = 8'h4C;

    localparam logic [63:0] PRIM_SPRITE = 64'd6;
    // FRAME_1: FBP[8:0]=0, FBW[5:0]=2 (at bit 16), PSM=PSMT8(=0x13 at bit 24).
    //   FBW=2 → bits[21:16]=0x02 → 0x0002_0000.
    //   PSM=0x13 → bits[29:24]=0x13 → 0x1300_0000.
    localparam logic [63:0] FRAME_1_VAL = 64'h0000_0000_1302_0000;
    // RGBAQ: R=0xA5, G=0x00, B=0x00, A=0x00 → low 32 = 0x00_00_00_A5
    // (PSMT8 raster channel uses R as the byte index; G/B/A unused).
    localparam logic [63:0] RGBAQ_VAL   = 64'h0000_0000_0000_00A5;
    localparam logic [7:0]  PSMT8_IDX   = 8'hA5;

    localparam int IMG_W = 16;
    localparam int IMG_H = 8;

    // ------------------------------------------------------------
    // Phase 3 — non-origin PSMT8 SPRITE.
    //
    // FRAME_1: FBP=4 (= 8192-byte base), FBW=4 (= 256 px per row at
    // PSMT8, two PSMT8 pages wide so bw_pg = FBW/2 = 2),
    // PSM=PSMT8.
    //   FRAME_1 layout: FBP[8:0], FBW[5:0]@16, PSM[5:0]@24.
    //   FBP=4 → bits[8:0]=0x004; FBW=4 → bits[21:16]=0x04 →
    //   0x0004_0000; PSM=0x13 → 0x1300_0000.
    //
    // SPRITE rect: v1=(124, 4), v2=(131, 7) — 8×4 = 32 pixels.
    //   Crosses PSMT8 PAGE-x boundary at x=128 (page (0,0) for
    //   x∈[124..127], page (1,0) for x∈[128..131]) so page_index
    //   changes mid-row. Within block_x: x∈[124..127] is xb=12..15
    //   inside block (0,7) of page (0,0); x∈[128..131] is xb=0..3
    //   inside block (0,0) of page (1,0). Within-block columns
    //   yb=4..7 cover columnTable8 rows 4..7. Strict non-origin
    //   coords — makes ras_fbp, ras_fbw, AND absolute s2_x_q/s2_y_q
    //   all load-bearing in the swizzle's input mux.
    //
    // RGBAQ for Phase 3: distinct color from Phase 1's so any
    // wrong-byte commit can be told apart.
    //   R=0x5A → byte_idx=0x5A. PCRTC PSMT8 grayscale: R=G=B=0x5A.
    // ------------------------------------------------------------
    localparam logic [63:0] P3_FRAME_1_VAL = 64'h0000_0000_1304_0004;
    localparam logic [63:0] P3_RGBAQ_VAL   = 64'h0000_0000_0000_005A;
    localparam logic [7:0]  P3_IDX         = 8'h5A;
    localparam int P3_FBP = 4;
    localparam int P3_FBW = 4;
    localparam int P3_X0  = 124;
    localparam int P3_Y0  = 4;
    localparam int P3_X1  = 131;
    localparam int P3_Y1  = 7;
    localparam int P3_W   = (P3_X1 - P3_X0 + 1);  // 8
    localparam int P3_H   = (P3_Y1 - P3_Y0 + 1);  // 4
    localparam int P3_PIXELS = P3_W * P3_H;       // 32

    // Helper: read a byte at byte_addr from vram via read2.
    task automatic read_byte_at(input logic [31:0] byte_addr,
                                output logic [7:0] b);
        vram_read2_addr = byte_addr & ~32'd3;
        #1;
        case (byte_addr[1:0])
            2'b00: b = vram_read2_data[7:0];
            2'b01: b = vram_read2_data[15:8];
            2'b10: b = vram_read2_data[23:16];
            default: b = vram_read2_data[31:24];
        endcase
    endtask

    initial begin
        rst_n            = 1'b0;
        gif_reg_wr_en    = 1'b0;
        gif_reg_num      = 8'd0;
        gif_reg_data     = 64'd0;
        priv_reg_wr_en   = 1'b0;
        priv_reg_wr_addr = 16'd0;
        priv_reg_wr_data = 64'd0;
        vram_read2_addr  = 32'd0;

        repeat (4) @(posedge clk);
        rst_n = 1'b1;
        repeat (2) @(posedge clk);

        // ============================================================
        // Phase 1 — origin SPRITE (16×8 PSMT8 at FBP=0, FBW=2).
        // ============================================================
        drive_reg(R_PRIM,    PRIM_SPRITE);
        drive_reg(R_FRAME_1, FRAME_1_VAL);
        drive_reg(R_RGBAQ,   RGBAQ_VAL);
        drive_reg(R_XYZ2,    xyz2_data(12'd0, 12'd0));
        drive_reg(R_XYZ2,    xyz2_data(12'(IMG_W - 1),
                                       12'(IMG_H - 1)));
        drive_idle();

        wait (raster_active == 1'b1);
        wait (raster_active == 1'b0);
        repeat (10) @(posedge clk);

        if (raster_pixel_emit_count != 32'(IMG_W * IMG_H)) begin
            $error("expected %0d raster emits, got %0d",
                   IMG_W * IMG_H, raster_pixel_emit_count);
            errors = errors + 1;
        end

        // Phase 1 — write-side lock. Verify each sprite byte landed
        // at its SWIZZLED byte address.
        for (int yy = 0; yy < IMG_H; yy++) begin
            for (int xx = 0; xx < IMG_W; xx++) begin
                logic [31:0] addr;
                logic [7:0]  got;
                addr = ref_addr8(0, 2, xx, yy);
                read_byte_at(addr, got);
                if (got !== PSMT8_IDX) begin
                    $error("[swizzled-byte] (%0d,%0d) @addr 0x%08x got 0x%02x expected 0x%02x",
                           xx, yy, addr, got, PSMT8_IDX);
                    errors = errors + 1;
                end
            end
        end

        // Strict separators: PSMT8 stride at FBW=2 = 128, so linear
        // y=1 row starts at byte 128. Swizzled writes for yb=0..7
        // span bytes [0..127]. Byte 128 is strictly outside. Linear
        // y=2 starts at byte 256.
        vram_read2_addr = 32'd128;
        #1;
        if (vram_read2_data !== 32'd0) begin
            $error("[linear-y1-byte-still-zero] @byte 0x80 got 0x%08x expected 0",
                   vram_read2_data);
            errors = errors + 1;
        end
        vram_read2_addr = 32'd256;
        #1;
        if (vram_read2_data !== 32'd0) begin
            $error("[linear-y2-byte-still-zero] @byte 0x100 got 0x%08x expected 0",
                   vram_read2_data);
            errors = errors + 1;
        end

        // ============================================================
        // Phase 2 — end-to-end agreement: enable swizzled scanout,
        // capture frame, assert grayscale R=G=B=PSMT8_IDX.
        // ============================================================
        // DISPFB1: FBP=0, FBW=2, PSM=PSMT8 (=0x13).
        //   FBW [14:9]   = 2   → 0x0400
        //   PSM [19:15]  = 0x13 → 0x9_8000
        drive_priv(16'h0070, 64'h0000_0000_0009_8400);
        // DISPLAY1: DX=0, DY=0, DW=15, DH=7, MAGH=MAGV=0.
        drive_priv(16'h0080, 64'h0070_000F_0000_0000);
        // PMODE.EN1 = 1.
        drive_priv(16'h0000, 64'h0000_0000_0000_0001);

        repeat (40) @(posedge clk);
        capture_armed = 1'b1;
        repeat (500) @(posedge clk);

        for (int yy = 0; yy < PCRTC_V_ACTIVE; yy++) begin
            for (int xx = 0; xx < PCRTC_H_ACTIVE; xx++) begin
                if (!cap_de[yy][xx]) begin
                    $error("[scanout] (%0d,%0d) DE never asserted", xx, yy);
                    errors = errors + 1;
                end else if (cap_r[yy][xx] !== PSMT8_IDX
                          || cap_g[yy][xx] !== PSMT8_IDX
                          || cap_b[yy][xx] !== PSMT8_IDX) begin
                    $error("[scanout] (%0d,%0d) got R=%02x G=%02x B=%02x expected gray=%02x",
                           xx, yy,
                           cap_r[yy][xx], cap_g[yy][xx], cap_b[yy][xx], PSMT8_IDX);
                    errors = errors + 1;
                end
            end
        end

        // ============================================================
        // Phase 3 — non-origin SPRITE (8×4 at (124,4)..(131,7),
        // FBP=4, FBW=4). Crosses page-x boundary at x=128.
        // ============================================================
        drive_reg(R_PRIM,    PRIM_SPRITE);
        drive_reg(R_FRAME_1, P3_FRAME_1_VAL);
        drive_reg(R_RGBAQ,   P3_RGBAQ_VAL);
        drive_reg(R_XYZ2,    xyz2_data(12'(P3_X0), 12'(P3_Y0)));
        drive_reg(R_XYZ2,    xyz2_data(12'(P3_X1), 12'(P3_Y1)));
        drive_idle();

        wait (raster_active == 1'b1);
        wait (raster_active == 1'b0);
        repeat (10) @(posedge clk);

        // Total emit count after Phase 3: 128 (P1 16×8) + 32 (P3 8×4).
        if (raster_pixel_emit_count != 32'(IMG_W * IMG_H + P3_PIXELS)) begin
            $error("after P3: expected %0d raster emits, got %0d",
                   IMG_W * IMG_H + P3_PIXELS, raster_pixel_emit_count);
            errors = errors + 1;
        end

        // Phase 3 per-pixel byte readback at swizzled addresses.
        for (int yy = P3_Y0; yy <= P3_Y1; yy++) begin
            for (int xx = P3_X0; xx <= P3_X1; xx++) begin
                logic [31:0] addr;
                logic [7:0]  got;
                addr = ref_addr8(P3_FBP, P3_FBW, xx, yy);
                read_byte_at(addr, got);
                if (got !== P3_IDX) begin
                    $error("[p3-swizzled-byte] (%0d,%0d) @addr 0x%08x got 0x%02x expected 0x%02x",
                           xx, yy, addr, got, P3_IDX);
                    errors = errors + 1;
                end
            end
        end

        // P3 strict separator: linear formula for P3 places pixel
        // (124, 4) at byte:
        //   FBP*2048 + (FBW*64)*y + x
        //   = 4*2048 + 4*64*4 + 124
        //   = 8192 + 1024 + 124
        //   = 9340
        // The P3 swizzled set lives in:
        //   page (0,0) of FBP=4, block (0,7)
        //     (blockTable8[0][7]=21) → base 13568,
        //     bytes within [13568..13823] (col indices for
        //     xb=12..15, yb=4..7).
        //   page (1,0) of FBP=4, block (0,0) (idx=0) → base 16384,
        //     bytes within [16384..16639] (col indices for
        //     xb=0..3, yb=4..7).
        // Byte 9340 sits between page 0's start (8192) and the
        // block-(0,7) base (13568) — strictly outside the swizzled
        // write set. If raster had fallen through to linear, byte
        // 9340 would hold P3's byte. Assert it stays 0.
        vram_read2_addr = 32'd9340;
        #1;
        if (vram_read2_data !== 32'd0) begin
            $error("[p3-linear-byte-still-zero] @byte 0x%08x got 0x%08x expected 0",
                   32'd9340, vram_read2_data);
            errors = errors + 1;
        end

        $display("[tb_gs_raster_swizzle_psmt8] emits=%0d errors=%0d",
                 raster_pixel_emit_count, errors);
        if (errors == 0) $display("[tb_gs_raster_swizzle_psmt8] PASS");
        else             $display("[tb_gs_raster_swizzle_psmt8] FAIL");
        $finish;
    end

    initial begin
        #1000000;
        $error("[tb_gs_raster_swizzle_psmt8] timeout");
        $finish;
    end

endmodule : tb_gs_raster_swizzle_psmt8
