// retroDE_ps2 — tb_gs_scanout_dbx_dby (Ch91 audit-medium)
//
// Codex flagged that gs_pcrtc_stub decoded DISPFB1.FBP/FBW/PSM
// but ignored DISPFB1.DBX/DBY. Address generation was just
// `vcnt * row + hcnt`, so a real driver using a non-zero
// display-buffer origin would scan from the wrong VRAM offset.
//
// Fix: pcrtc now computes
//   pixel_index = (vcnt + DBY) * pixels_per_row + (hcnt + DBX)
// This TB locks the contract: render a sprite at VRAM (4,2)..(7,5),
// configure DISPFB1 with DBX=4 / DBY=2, and verify the sprite
// appears at scanout (0..3, 0..3). With the bug, it would appear
// at (4..7, 2..5) and (0..3, 0..3) would be black.
//
// To strengthen the proof, we also assert the per-pixel scanout
// at (0,0) reads the SAME VRAM byte that gs_stub wrote at v(4,2),
// not the byte at VRAM (0,0).

`timescale 1ns/1ps

module tb_gs_scanout_dbx_dby;

    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 IO
    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                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 [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 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),
        .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_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)
    );

    logic [31:0] vram_read_addr;
    logic [31:0] vram_read_data;

    vram_stub #(.BYTES(4096)) 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(32'hFFFF_FFFF),
        .read_addr (vram_read_addr),
        .read_data (vram_read_data),
        .read2_addr(32'd0),
        .read2_data()
    );

    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)
    ) 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)
    );

    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

    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

    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

    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 [15:0] PMODE_OFF    = 16'h0000;
    localparam logic [15:0] DISPFB1_OFF  = 16'h0070;
    localparam logic [15:0] DISPLAY1_OFF = 16'h0080;

    localparam logic [63:0] PRIM_SPRITE = 64'd6;
    localparam logic [63:0] FRAME_1_VAL = 64'h0000_0000_0001_0000;
    localparam logic [63:0] RGBAQ_VAL   = 64'h0000_0000_0000_FF30;

    // DISPFB1 layout: FBP=0[8:0], FBW=1[14:9], PSM=0[19:15],
    // DBX=4[42:32], DBY=2[53:43].
    //   FBW=1 → bit 9            = 0x0000_0000_0000_0200
    //   DBX=4 → bits [34:32]=100 = 0x0000_0004_0000_0000
    //   DBY=2 → bits [44:43]=10  = 0x0000_1000_0000_0000
    localparam logic [63:0] DISPFB1_VAL =
        64'h0000_0000_0000_0200
      | (64'(11'd4) << 32)   // DBX=4
      | (64'(11'd2) << 43);  // DBY=2

    localparam logic [63:0] PMODE_EN1   = 64'h0000_0000_0000_0001;
    // DISPLAY1: full active area (DX=0, DY=0, DW=H_ACTIVE-1, DH=V_ACTIVE-1).
    localparam logic [63:0] DISPLAY1_VAL =
          (64'(PCRTC_H_ACTIVE - 1) << 32)
        | (64'(PCRTC_V_ACTIVE - 1) << 44);

    localparam logic [7:0] EXP_R = 8'h30;
    localparam logic [7:0] EXP_G = 8'hFF;
    localparam logic [7:0] EXP_B = 8'h00;

    // Sprite is rendered at VRAM (4,2)..(7,5) — 4×4 pixels in
    // VRAM coords matching DBX/DBY. After scanout shift, this
    // sprite occupies the FIRST 4×4 of the displayed frame.
    localparam int SPRITE_VRAM_X = 4;
    localparam int SPRITE_VRAM_Y = 2;
    localparam int SPRITE_W      = 4;
    localparam int SPRITE_H      = 4;

    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;

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

        // Configure DISPFB1 with non-zero DBX/DBY, and DISPLAY1
        // covering the full active area so the DBX/DBY shift is
        // the only variable under test.
        drive_priv(DISPFB1_OFF,  DISPFB1_VAL);
        drive_priv(DISPLAY1_OFF, DISPLAY1_VAL);

        // Render sprite at VRAM (4,2)..(7,5).
        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'(SPRITE_VRAM_X),
                                    12'(SPRITE_VRAM_Y)));
        drive_reg(R_XYZ2, xyz2_data(12'(SPRITE_VRAM_X + SPRITE_W - 1),
                                    12'(SPRITE_VRAM_Y + SPRITE_H - 1)));
        drive_idle();

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

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

        // Confirm DISPFB1 latched the DBX/DBY we wrote.
        if (dispfb1_q[42:32] !== 11'd4) begin
            $error("DISPFB1.DBX latched as %0d (expected 4)", dispfb1_q[42:32]);
            errors = errors + 1;
        end
        if (dispfb1_q[53:43] !== 11'd2) begin
            $error("DISPFB1.DBY latched as %0d (expected 2)", dispfb1_q[53:43]);
            errors = errors + 1;
        end

        // Enable scanout.
        drive_priv(PMODE_OFF, PMODE_EN1);

        @(posedge u_pcrtc.end_of_frame);
        @(posedge clk);

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

        // The shifted scanout means VRAM (DBX, DBY) appears at
        // displayed (0, 0). Sprite is at VRAM (4..7, 2..5), so
        // displayed coords (0..3, 0..3) should be the sprite
        // color, and ALL OTHER displayed pixels should be 0
        // (assuming the surrounding VRAM bytes are still
        // zero-initialized, which is true since vram_stub uses an
        // initial-block zero-init and gs_stub only wrote inside
        // the sprite bbox).
        for (int y = 0; y < PCRTC_V_ACTIVE; y++) begin
            for (int x = 0; x < PCRTC_H_ACTIVE; x++) begin
                logic [7:0] er, eg, eb;
                if (x < SPRITE_W && y < SPRITE_H) begin
                    er = EXP_R; eg = EXP_G; eb = EXP_B;
                end else begin
                    er = 8'd0; eg = 8'd0; eb = 8'd0;
                end
                if (!cap_de[y][x]) begin
                    $error("(%0d,%0d) DE never asserted", x, y);
                    errors = errors + 1;
                end
                if (cap_r[y][x] !== er || cap_g[y][x] !== eg || cap_b[y][x] !== eb) begin
                    $error("(%0d,%0d) got (%02x,%02x,%02x) expected (%02x,%02x,%02x)",
                           x, y, cap_r[y][x], cap_g[y][x], cap_b[y][x], er, eg, eb);
                    errors = errors + 1;
                end
            end
        end

        $display("[tb_gs_scanout_dbx_dby] sprite=%0dx%0d at VRAM(%0d,%0d) DBX=%0d DBY=%0d",
                 SPRITE_W, SPRITE_H, SPRITE_VRAM_X, SPRITE_VRAM_Y,
                 11'(dispfb1_q[42:32]), 11'(dispfb1_q[53:43]));

        if (errors == 0) $display("[tb_gs_scanout_dbx_dby] PASS");
        else             $display("[tb_gs_scanout_dbx_dby] FAIL");
        $finish;
    end

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

endmodule : tb_gs_scanout_dbx_dby
