// retroDE_ps2 — tb_gs_fog_persp
//
// Focused white-box TB for GS per-vertex FOG on the PERSPECTIVE-textured emit
// path (persp_emit5). Forces PERSPECTIVE_CORRECT=1. The SH3 board scene runs
// this build (PERSPECTIVE_CORRECT=1, COMBINED_TAZ=0, TILE_LOCAL=0), so its
// geometry emits through persp_emit5 — the path round-1 left unfogged.
//
// A perspective-textured DECAL triangle (ST/Q supplied so ras_persp activates)
// samples a SOLID texture (tex_rd_data tied constant → s1_tex_color == TEXEL
// for every pixel), so the emitted color isolates the fog blend and its stage
// alignment without needing to model the perspective UV walk. F is affine /
// screen-linear per vertex (XYZF2[63:56]).
//
// Checks:
//   T1p — FGE=1, flat color, DISTINCT per-vertex F. At every persp_emit5:
//         (a) ALIGNMENT — the white-box +5-aligned s2_fog_f delay tap
//             (u_gs.persp_fog_f5) matches the barycentric (screen-linear) F at
//             the emitted pixel (persp_x5,persp_y5) within 1 LSB. A wrong delay
//             depth would 1-pixel-shift F and fail here.
//         (b) BLEND — the captured emitted RGB equals fog_blend(TEXEL,
//             persp_fog_f5) EXACTLY, alpha unchanged.
//   T2p — FGE=0, same geometry. Emitted color is BYTE-IDENTICAL to TEXEL (no
//         fog) — the non-negotiable invariant on the perspective path.

`timescale 1ns/1ps

module tb_gs_fog_persp;

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

    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]         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 [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                fb_rd_en;   logic [31:0] fb_rd_addr;
    logic                z_rd_en;    logic [31:0] z_rd_addr;
    logic                ev_valid;
    trace_pkg::subsys_e  ev_subsys;
    trace_pkg::event_e   ev_event;
    logic [63:0]         ev_arg0, ev_arg1, ev_arg2, ev_arg3;
    logic [31:0]         ev_flags;

    // Solid texture: any texel address returns this ABGR word.
    localparam logic [31:0] TEXEL = 32'hFF_B0_60_20;   // A=FF B=B0 G=60 R=20
    logic [31:0] tex_texel;
    assign tex_texel = TEXEL;

    gs_stub #(.PERSPECTIVE_CORRECT(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),
        .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_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_texel),
        .fb_rd_en(fb_rd_en), .fb_rd_addr(fb_rd_addr), .fb_rd_data(32'd0),
        .z_rd_en(z_rd_en), .z_rd_addr(z_rd_addr), .z_rd_data(32'd0),
        .ev_valid(ev_valid), .ev_subsys(ev_subsys), .ev_event(ev_event),
        .ev_arg0(ev_arg0), .ev_arg1(ev_arg1),
        .ev_arg2(ev_arg2), .ev_arg3(ev_arg3),
        .ev_flags(ev_flags)
    );

    // ----- Drive helpers -----
    task automatic drive_reg(input logic [7:0] num, input logic [63:0] data);
        @(negedge clk);
        gif_reg_wr_en = 1'b1; gif_reg_num = num; gif_reg_data = data;
        @(posedge clk);
    endtask
    task automatic drive_idle();
        @(negedge clk);
        gif_reg_wr_en = 1'b0; gif_reg_num = 8'd0; gif_reg_data = 64'd0;
        @(posedge clk);
    endtask

    // XYZF2 (reg 0x04): X=[15:0] (12.4), Y=[31:16] (12.4), Z=[55:32], F=[63:56].
    function automatic logic [63:0] xyzf2(input int x, input int y,
                                          input int z, input int f);
        return {8'(f), 24'(z), 12'(y), 4'd0, 12'(x), 4'd0};
    endfunction
    // RGBAQ with Q in [55:32] (24-bit, FRAC=12).
    function automatic logic [63:0] rgbaq_q_val(input int r, input int g, input int b,
                                                input int a, input int q_fp);
        return {8'd0, 24'(q_fp), 8'(a), 8'(b), 8'(g), 8'(r)};
    endfunction
    // ST (reg 0x02): S in [23:0], T in [55:32] (24-bit, FRAC=12).
    function automatic logic [63:0] st_val(input int s_fp, input int t_fp);
        return {8'd0, 24'(t_fp), 8'd0, 24'(s_fp)};
    endfunction

    localparam logic [7:0] R_PRIM    = 8'h00;
    localparam logic [7:0] R_RGBAQ   = 8'h01;
    localparam logic [7:0] R_ST      = 8'h02;
    localparam logic [7:0] R_XYZF2   = 8'h04;
    localparam logic [7:0] R_TEX0_1  = 8'h06;
    localparam logic [7:0] R_FOGCOL  = 8'h3D;
    localparam logic [7:0] R_FRAME_1 = 8'h4C;

    // PRIM: TRIANGLE(3) + TME(bit4) + FGE(bit5).
    localparam logic [63:0] PRIM_TRI_TEX_FGE = 64'd3 | (64'd1 << 4) | (64'd1 << 5);
    localparam logic [63:0] PRIM_TRI_TEX     = 64'd3 | (64'd1 << 4);      // FGE=0
    localparam logic [63:0] FRAME_1_VAL      = 64'h0000_0000_0001_0000;   // FBW=1, PSMCT32
    // TEX0_1: TBP0=8, TBW=1, PSM=PSMCT32(0), TW=TH=0, TCC=0, TFX=DECAL(1)@[36:35].
    localparam logic [63:0] TEX0_VAL = 64'd8 | (64'd1 << 14) | (64'd1 << 35);
    localparam int Q_ONE = 24'h001000;   // 1.0 in FRAC=12

    localparam int FOG_R = 8'h20, FOG_G = 8'h40, FOG_B = 8'h60;
    localparam logic [63:0] FOGCOL_VAL = {40'd0, 8'(FOG_B), 8'(FOG_G), 8'(FOG_R)};

    function automatic int fog_ch(input int c, input int f, input int fc);
        return (c * f + fc * (255 - f)) >> 8;
    endfunction
    function automatic int absdiff(input int a, input int b);
        return (a > b) ? (a - b) : (b - a);
    endfunction

    // ----- Triangle reference (edge fn + fill rule + barycentric for F) -----
    int vx0, vy0, vx1, vy1, vx2, vy2, vf0, vf1, vf2;
    int ref_det, sx1, sy1, sx2, sy2, sf1, sf2;

    function automatic int edge_f(input int px, input int py,
                                  input int ax, input int ay,
                                  input int bx, input int by);
        return (px - ax) * (by - ay) - (py - ay) * (bx - ax);
    endfunction
    task automatic setup_ref();
        int sa;
        sa = (vx1 - vx0) * (vy2 - vy0) - (vy1 - vy0) * (vx2 - vx0);
        if (sa < 0) begin
            sx1 = vx2; sy1 = vy2; sf1 = vf2;
            sx2 = vx1; sy2 = vy1; sf2 = vf1;
            ref_det = -sa;
        end else begin
            sx1 = vx1; sy1 = vy1; sf1 = vf1;
            sx2 = vx2; sy2 = vy2; sf2 = vf2;
            ref_det = sa;
        end
    endtask
    function automatic int ref_f(input int px, input int py);
        int L0, L1, L2, num;
        L0 = -edge_f(px, py, sx1, sy1, sx2, sy2);
        L1 = -edge_f(px, py, sx2, sy2, vx0, vy0);
        L2 = -edge_f(px, py, vx0, vy0, sx1, sy1);
        num = L0 * vf0 + L1 * sf1 + L2 * sf2;
        if (ref_det == 0) return 0;
        return num / ref_det;
    endfunction

    int errors, align_checks, blend_checks;

    // Emit capture: expected color computed at persp_emit5 from the RTL's own
    // +5-aligned F (persp_fog_f5), plus the alignment check vs barycentric F.
    logic [31:0] exp_c [0:31][0:31];
    bit          exp_set [0:31][0:31];
    bit          fge_on;

    task automatic clear_exp();
        for (int y = 0; y < 32; y++)
            for (int x = 0; x < 32; x++) begin
                exp_c[y][x] = 32'd0; exp_set[y][x] = 1'b0;
            end
    endtask

    // persp_emit5 monitor: alignment + record expected fogged color.
    always_ff @(posedge clk) begin
        if (rst_n && u_gs.ras_persp && u_gs.persp_emit5) begin
            int px, py, ef, af;
            logic [31:0] want;
            px = int'(u_gs.persp_x5);
            py = int'(u_gs.persp_y5);
            af = int'(u_gs.persp_fog_f5);
            if (px < 32 && py < 32) begin
                // (a) alignment: RTL +5-aligned F vs barycentric F at this pixel.
                ef = ref_f(px, py);
                if (absdiff(af, ef) > 1) begin
                    $error("[persp align] (%0d,%0d) persp_fog_f5=%0d expected ~%0d", px, py, af, ef);
                    errors = errors + 1;
                end else begin
                    align_checks = align_checks + 1;
                end
                // (b) expected emitted color = fog(TEXEL, af) if FGE, else TEXEL.
                if (fge_on)
                    want = {TEXEL[31:24],
                            8'(fog_ch(int'(TEXEL[23:16]), af, FOG_B)),
                            8'(fog_ch(int'(TEXEL[15:8]),  af, FOG_G)),
                            8'(fog_ch(int'(TEXEL[7:0]),   af, FOG_R))};
                else
                    want = TEXEL;
                exp_c[py][px]   <= want;
                exp_set[py][px] <= 1'b1;
            end
        end
    end

    // Capture the actual emitted pixel and compare to the expected recorded above.
    always_ff @(posedge clk) begin
        if (rst_n && raster_pixel_emit
            && raster_pixel_x_q < 32 && raster_pixel_y_q < 32) begin
            if (!exp_set[raster_pixel_y_q][raster_pixel_x_q]) begin
                $error("[persp emit] (%0d,%0d) emitted but no persp_emit5 expected color recorded",
                       raster_pixel_x_q, raster_pixel_y_q);
                errors = errors + 1;
            end else if (raster_pixel_color_q[31:0] !== exp_c[raster_pixel_y_q][raster_pixel_x_q]) begin
                $error("[persp emit] (%0d,%0d) got %08x expected %08x",
                       raster_pixel_x_q, raster_pixel_y_q,
                       raster_pixel_color_q[31:0], exp_c[raster_pixel_y_q][raster_pixel_x_q]);
                errors = errors + 1;
            end else begin
                blend_checks = blend_checks + 1;
            end
        end
    end

    task automatic drive_persp_tri(input logic [63:0] prim_word);
        drive_reg(R_FOGCOL,  FOGCOL_VAL);
        drive_reg(R_PRIM,    prim_word);
        drive_reg(R_FRAME_1, FRAME_1_VAL);
        drive_reg(R_TEX0_1,  TEX0_VAL);
        drive_reg(R_RGBAQ,   rgbaq_q_val(8'hFF, 8'hFF, 8'hFF, 8'hFF, Q_ONE));
        drive_reg(R_ST,      st_val(0, 0));
        drive_reg(R_XYZF2,   xyzf2(vx0, vy0, 0, vf0));
        drive_reg(R_RGBAQ,   rgbaq_q_val(8'hFF, 8'hFF, 8'hFF, 8'hFF, Q_ONE));
        drive_reg(R_ST,      st_val(0, 0));
        drive_reg(R_XYZF2,   xyzf2(vx1, vy1, 0, vf1));
        drive_reg(R_RGBAQ,   rgbaq_q_val(8'hFF, 8'hFF, 8'hFF, 8'hFF, Q_ONE));
        drive_reg(R_ST,      st_val(0, 0));
        drive_reg(R_XYZF2,   xyzf2(vx2, vy2, 0, vf2));   // closes
        drive_idle();
        repeat (900) @(posedge clk);
    endtask

    initial begin
        errors = 0; align_checks = 0; blend_checks = 0;
        rst_n = 1'b0; gif_reg_wr_en = 1'b0; gif_reg_num = 8'd0; gif_reg_data = 64'd0;
        clear_exp();

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

        // ============================================================
        // T1p — FGE=1, distinct per-vertex F, solid texel. Alignment + blend.
        // ============================================================
        vx0=2;  vy0=2;  vf0=8'h20;
        vx1=12; vy1=3;  vf1=8'hE0;
        vx2=4;  vy2=9;  vf2=8'h80;
        setup_ref();
        clear_exp(); fge_on = 1'b1;
        drive_persp_tri(PRIM_TRI_TEX_FGE);
        if (align_checks == 0) begin
            $error("[T1p] no persp_emit5 pixels observed (persp path did not fire)");
            errors = errors + 1;
        end
        if (raster_overflow || raster_degenerate) begin
            $error("[T1p] raster anomaly"); errors = errors + 1;
        end

        // ============================================================
        // T2p — FGE=0, same geometry. Emitted MUST be byte-identical to TEXEL.
        // ============================================================
        clear_exp(); fge_on = 1'b0;
        drive_persp_tri(PRIM_TRI_TEX);

        $display("[tb_gs_fog_persp] align_checks=%0d blend_checks=%0d errors=%0d",
                 align_checks, blend_checks, errors);
        if (errors == 0) $display("[tb_gs_fog_persp] PASS");
        else             $display("[tb_gs_fog_persp] FAIL");
        $finish;
    end

    initial begin
        #8000000;
        $error("[tb_gs_fog_persp] timeout");
        $finish;
    end

endmodule : tb_gs_fog_persp
