// retroDE_ps2 — tb_gs_textured_alpha_sprite (Brick 1)
//
// FIRST textured-sprite test: drives a PSMCT32 DECAL textured SPRITE
// through gs_stub's raster pipeline and verifies the framebuffer
// pixels equal the preloaded texture texels.
//
// Datapath under test (Brick 1):
//   PRIM.TME=1 + TEX0_1(texture-side) + UV per-vertex + SPRITE
//     -> per-pixel linear (u,v) interpolation
//     -> gs_texture_unit (gs_texel_addr + PSMCT32 DECAL sample)
//     -> texel REPLACES the flat sprite color at emit.
//
// To isolate the sampling datapath from the texture-UPLOAD path, the
// texture is PRELOADED DIRECTLY into vram_stub at the TBP0-derived
// base (TBP0*256, the convention gs_stub documents + the upload path
// uses). A follow-on chapter reconciles the BITBLT/TRX upload path.
//
// Geometry / mapping (chosen so the mapping is the identity texel(x,y)):
//   SPRITE endpoints (0,0)->(3,3)  => 4x4 fill.
//   UV endpoints (0,0)->(3,3)      => u=x, v=y across the sprite.
//   Framebuffer: FBP=0, FBW=1, PSM=PSMCT32. Stride = 64*4 = 256 B/row.
//   Texture: TBP0=8 (base 2048 B), TBW=1 (64 texels/row), PSM=PSMCT32.
//
// PASS criteria:
//   - 16 raster_pixel_emit pulses.
//   - Each framebuffer pixel (x,y) == preloaded texel(x,y).
//   - A NON-textured control SPRITE (TME=0) at a different FB region
//     still emits the FLAT color (proves the TME=0 path is unchanged).

`timescale 1ns/1ps

module tb_gs_textured_alpha_sprite;

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

    // gs_stub IO
    logic        gif_reg_wr_en;
    logic [7:0]  gif_reg_num;
    logic [63:0] gif_reg_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_fifo_full;
    logic                raster_degenerate;
    logic                tex_rd_en;
    logic [31:0]         tex_rd_addr;
    logic [31:0]         tex_rd_data;
    // Ch344 — alpha dest-read port (read2, muxed with texel below).
    logic                fb_rd_en;
    logic [31:0]         fb_rd_addr;
    logic [31:0]         fb_rd_data;
    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;

    // SPRITE_TEX_ALPHA targets the BOARD wrapper's read model: 1-cycle REGISTERED read2
    // (TEX/FB/Z_RD_REGISTERED=1, as top_psmct32_raster_demo_bram sets). The read2 below is registered.
    gs_stub #(.SPRITE_TEX_ALPHA(1'b1),
              .TEX_RD_REGISTERED(1'b1), .FB_RD_REGISTERED(1'b1), .Z_RD_REGISTERED(1'b1)) u_gs (
        .clk(clk), .rst_n(rst_n),
        .reg_wr_en(1'b0), .reg_wr_addr(16'd0), .reg_wr_data(64'd0),
        .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_fifo_full(raster_fifo_full),
        .raster_degenerate(raster_degenerate),
        .tex_rd_en(tex_rd_en),
        .tex_rd_addr(tex_rd_addr),
        .tex_rd_data(tex_rd_data),
        .fb_rd_en(fb_rd_en),
        .fb_rd_addr(fb_rd_addr),
        .fb_rd_data(fb_rd_data),
        .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. Port 0 = raster write + TB readback. Port 1 (read2) =
    // texel fetch. In a full integration read2 is muxed between
    // clut_loader_stub (CLUT load at TEX0 commit) and gs_stub's texel
    // fetch (during the scan); clut_loader is not instantiated here,
    // so read2 is dedicated to the texel port. The mux is documented
    // in gs_stub's tex_rd_* port comment.
    logic [31:0] vram_read_addr;
    logic [31:0] vram_read_data;

    localparam int VRAM_BYTES = 8192;

    vram_stub #(.BYTES(VRAM_BYTES)) 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(rd2_addr),
        .read2_data(rd2_data)
    );
    // Ch344 — read2 is the SINGLE 2nd read port shared by the texel fetch and the alpha
    // dest read (exactly as the real wrapper muxes them). gs_stub guarantees they are
    // time-exclusive; the no-overlap monitor below ASSERTS it. fb_rd_en wins the mux when
    // asserted (it never co-asserts with tex_rd_en).
    logic [31:0] rd2_addr, rd2_data;
    assign rd2_addr     = fb_rd_en ? fb_rd_addr : tex_rd_addr;
    // 1-cycle REGISTERED read2 (matches vram_bram_stub on the board): data lands the cycle AFTER addr.
    logic [31:0] rd2_data_reg;
    always_ff @(posedge clk) rd2_data_reg <= rd2_data;
    assign tex_rd_data  = rd2_data_reg;
    assign fb_rd_data   = rd2_data_reg;

    int errors;
    int textured_emit_seen;

    initial begin
        errors = 0;
        textured_emit_seen = 0;
    end

    // ----- GIF register numbers -----
    localparam logic [7:0] R_PRIM    = 8'h00;
    localparam logic [7:0] R_RGBAQ   = 8'h01;
    localparam logic [7:0] R_UV      = 8'h03;
    localparam logic [7:0] R_XYZ2    = 8'h05;
    localparam logic [7:0] R_TEX0_1  = 8'h06;
    localparam logic [7:0] R_ALPHA_1 = 8'h42;
    localparam logic [7:0] R_FRAME_1 = 8'h4C;

    // PRIM: SPRITE(6) + TME(bit4) + ABE(bit6) -> the textured-alpha path.
    localparam logic [63:0] PRIM_SPR_TEX_ABE = 64'd6 | (64'd1 << 4) | (64'd1 << 6);
    // ALPHA_1 canonical source-over: A=0(Cs) B=1(Cd) C=0(As) D=1(Cd) -> 0|1<<2|0<<4|1<<6 = 0x44.
    localparam logic [63:0] ALPHA_SRCOVER = 64'h0000_0000_0000_0044;

    // FRAME_1: FBP[8:0]=0, FBW[21:16]=1, PSM[29:24]=PSMCT32(0x00).
    localparam logic [63:0] FRAME_1_FB0 = 64'h0000_0000_0001_0000;

    // TEX0_1: TBP0=8, TBW=1, PSM=PSMCT32(0), TW[29:26]=2, TH[33:30]=2 (4x4), TCC[34]=1.
    localparam logic [63:0] TEX0_VAL = 64'd8 | (64'd1 << 14) | (64'd0 << 20)
                                     | (64'd2 << 26) | (64'd2 << 30) | (64'd1 << 34);
    localparam logic [31:0] TEX_BASE_BYTES = 32'd8 * 32'd256;         // 2048
    localparam int          TEX_ROW_TEXELS = 64;                     // TBW*64

    // Per-vertex RGBAQ TINT: {A=0x10, B=0xFF, G=0x80, R=0x40}.
    // TFX=MODULATE,TCC=1 modulates all four channels, including texture alpha.
    localparam logic [63:0] TINT_RGBAQ = 64'h0000_0000_10FF_8040;
    // Background (dest) PSMCT32 pixel pre-filled under the sprite: {A=FF,B=20,G=20,R=20}.
    localparam logic [31:0] BG_PIXEL = 32'hFF20_2020;

    localparam int SPRITE_W = 4;
    localparam int SPRITE_H = 4;
    localparam int FB0_STRIDE = 64 * 4;     // FBW=1 -> 64 px/row * 4 B

    // Authentic texel(x,y): fixed alpha 0x40 (DISTINCT from the vertex A=0x10), distinct RGB per (x,y)
    // so a UV/sampling error is caught. PSMCT32 word {A,B,G,R}.
    function automatic logic [31:0] texel(input int x, input int y);
        return {8'h40, 8'hC0, 8'(8'h40 + y*16), 8'(8'h80 + x*16)};
    endfunction

    // ----- software source-over reference (matches gs_stub ta_mod8 + gs_alpha_blend exactly) -----
    function automatic logic [7:0] sw_mod8(input logic [7:0] t, input logic [7:0] c);
        logic [15:0] p; begin p = ({8'd0,t} * {8'd0,c}) >> 7; sw_mod8 = (p > 16'd255) ? 8'hFF : p[7:0]; end
    endfunction
    function automatic logic [7:0] sw_blend(input logic [7:0] cs, input logic [7:0] cd, input logic [7:0] as);
        logic [7:0] ae; logic signed [17:0] d, pr, sh, su;
        begin
            ae = (as > 8'd128) ? 8'd128 : as;
            d  = $signed({2'b00, cs}) - $signed({2'b00, cd});
            pr = d * $signed({1'b0, ae});
            sh = pr >>> 7;
            su = sh + $signed({10'd0, cd});
            sw_blend = (su < 0) ? 8'd0 : (su > 18'sd255) ? 8'd255 : su[7:0];
        end
    endfunction
    function automatic logic [31:0] expected(input int x, input int y);
        logic [31:0] t; logic [7:0] cs_r, cs_g, cs_b, cs_a;
        begin
            t    = texel(x, y);
            cs_r = sw_mod8(t[7:0],   TINT_RGBAQ[7:0]);    // *0x40 -> half
            cs_g = sw_mod8(t[15:8],  TINT_RGBAQ[15:8]);   // *0x80 -> identity
            cs_b = sw_mod8(t[23:16], TINT_RGBAQ[23:16]);  // *0xFF -> ~double (clamps)
            cs_a = sw_mod8(t[31:24], TINT_RGBAQ[31:24]);
            expected = {cs_a,
                        sw_blend(cs_b, BG_PIXEL[23:16], cs_a),
                        sw_blend(cs_g, BG_PIXEL[15:8],  cs_a),
                        sw_blend(cs_r, BG_PIXEL[7:0],   cs_a)};
        end
    endfunction

    // ----- 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

    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

    // UV reg: U=[13:0], V=[27:14], 10.4 fixed-point. Integer u,v.
    function automatic logic [63:0] uv_data(input int ui, input int vi);
        logic [13:0] u_fp, v_fp;
        u_fp = 14'(ui) << 4;
        v_fp = 14'(vi) << 4;
        return {36'd0, v_fp, u_fp};
    endfunction

    // Read a 32-bit word from VRAM port 0 (combinational read). The
    // settle delay lives in the caller (a task), not in a function.
    task automatic vram_word(input  logic [31:0] byte_addr,
                             output logic [31:0] word);
        vram_read_addr = byte_addr;
        #1;
        word = vram_read_data;
    endtask

    // Preload a 32-bit little-endian word directly into the VRAM
    // backing store (raster is idle during preload, so a direct mem
    // poke is the simplest texture-upload bypass). Static task: a
    // hierarchical force/poke on automatic-task locals is illegal in
    // iverilog 12, and a direct mem write needs no force at all.
    task automatic force_word(input logic [31:0] addr, input logic [31:0] data);
        u_vram.mem[addr + 0] = data[7:0];
        u_vram.mem[addr + 1] = data[15:8];
        u_vram.mem[addr + 2] = data[23:16];
        u_vram.mem[addr + 3] = data[31:24];
    endtask

    // ----- observer: count textured-alpha emits -----
    always_ff @(posedge clk) begin
        if (rst_n && raster_pixel_emit && (raster_pixel_psm_q == 6'h00)) begin
            textured_emit_seen <= textured_emit_seen + 1;
        end
    end

    // ----- Ch344 CORE GATE: the texel read and the dest read must NEVER co-fire on read2. -----
    int overlap_count;
    initial overlap_count = 0;
    always_ff @(posedge clk) begin
        if (rst_n && tex_rd_en && fb_rd_en) begin
            $error("[tb_gs_textured_alpha_sprite] READ2 OVERLAP @%0t: tex_rd_en && fb_rd_en both HIGH (addr tex=0x%08x fb=0x%08x)",
                   $time, tex_rd_addr, fb_rd_addr);
            overlap_count <= overlap_count + 1;
        end
    end

    integer x, y;
    logic [31:0] got, exp;

    initial begin
        rst_n          = 1'b0;
        gif_reg_wr_en  = 1'b0;
        gif_reg_num    = 8'd0;
        gif_reg_data   = 64'd0;
        vram_read_addr = 32'd0;

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

        // --- Preload the texture (RGBA, with alpha) directly into VRAM at TBP0*256. ---
        for (y = 0; y < SPRITE_H; y++)
            for (x = 0; x < SPRITE_W; x++)
                force_word(TEX_BASE_BYTES + ((y * TEX_ROW_TEXELS + x) * 4), texel(x, y));

        // --- Preload the BACKGROUND (dest) under the sprite footprint in FB0. ---
        for (y = 0; y < SPRITE_H; y++)
            for (x = 0; x < SPRITE_W; x++)
                force_word((y * FB0_STRIDE) + (x * 4), BG_PIXEL);

        // ===========================================================
        // TEXTURED + source-over ALPHA SPRITE
        // ===========================================================
        drive_reg(R_PRIM,    PRIM_SPR_TEX_ABE);
        drive_reg(R_FRAME_1, FRAME_1_FB0);
        drive_reg(R_TEX0_1,  TEX0_VAL);
        drive_reg(R_ALPHA_1, ALPHA_SRCOVER);
        // vertex 0: RGBAQ tint, UV(0,0) at screen (0,0)
        drive_reg(R_RGBAQ,   TINT_RGBAQ);
        drive_reg(R_UV,      uv_data(0, 0));
        drive_reg(R_XYZ2,    xyz2_data(12'd0, 12'd0));
        // vertex 1 (closing): inclusive far corner (3,3) -> u=x, v=y across the 4x4 sprite (16 px)
        drive_reg(R_RGBAQ,   TINT_RGBAQ);
        drive_reg(R_UV,      uv_data(SPRITE_W - 1, SPRITE_H - 1));
        drive_reg(R_XYZ2,    xyz2_data(12'(SPRITE_W - 1), 12'(SPRITE_H - 1)));
        drive_idle();

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

        // PROOF 1 — emit count = the 16 sprite pixels.
        if (raster_pixel_emit_count != 32'(SPRITE_W * SPRITE_H)) begin
            $error("textured-alpha: expected %0d emits, got %0d", SPRITE_W*SPRITE_H, raster_pixel_emit_count);
            errors = errors + 1;
        end

        // PROOF 2 (CORE GATE) — the texel and dest reads never overlapped on read2.
        if (overlap_count != 0) begin
            $error("textured-alpha: %0d read2 OVERLAP cycles (tex_rd_en && fb_rd_en) — invariant VIOLATED", overlap_count);
            errors = errors + 1;
        end

        // PROOF 3 — every FB pixel == source-over(texel*tint, background), As from TEXEL.
        // (A pure-DECAL or As-from-vertex bug would diverge here against the independent reference.)
        for (y = 0; y < SPRITE_H; y++) begin
            for (x = 0; x < SPRITE_W; x++) begin
                logic [31:0] addr;
                addr = (y * FB0_STRIDE) + (x * 4);
                vram_word(addr, got);
                exp = expected(x, y);
                if (got !== exp) begin
                    $error("textured-alpha FB(%0d,%0d)@0x%08x got 0x%08x expected 0x%08x (texel=0x%08x bg=0x%08x)",
                           x, y, addr, got, exp, texel(x,y), BG_PIXEL);
                    errors = errors + 1;
                end
            end
        end

        $display("[tb_gs_textured_alpha_sprite] sprite=%0dx%0d emits=%0d textured=%0d read2_overlap=%0d errors=%0d",
                 SPRITE_W, SPRITE_H, raster_pixel_emit_count, textured_emit_seen, overlap_count, errors);

        if (errors == 0) begin $display("[tb_gs_textured_alpha_sprite] PASS"); $finish; end
        else             $fatal(1, "[tb_gs_textured_alpha_sprite] FAIL (%0d errors)", errors);
    end

    initial begin
        #5000000;
        $error("[tb_gs_textured_alpha_sprite] timeout");
        $finish;
    end

endmodule : tb_gs_textured_alpha_sprite
