// retroDE_ps2 — tb_gs_tri_interp (Brick 3)
//
// White-box focused TB for the SYNTHESIZABLE non-axis-aligned triangle
// rasterizer: screen-space-affine interpolation of Gouraud COLOR and
// DEPTH (Z), with NO per-pixel divide and NO `// synthesis translate_off`
// on the live path.
//
// Two checks:
//
//   (1) COVERAGE + COLOR — a Gouraud triangle (3 distinct vertex colors)
//       with a NON-axis-aligned edge is drawn WITHOUT Z-test. The TB
//       captures every raster_pixel emit and asserts:
//         * pixels strictly inside the triangle (per an independent
//           reference edge-function + top-left fill rule) are emitted;
//         * pixels outside are NOT emitted (no spurious coverage);
//         * the emitted color at a handful of interior pixels matches
//           the expected AFFINE interpolation (and is within 1 LSB of
//           the exact barycentric ground truth — affine == barycentric
//           for affine attributes, modulo Q16.16 rounding).
//
//   (2) DEPTH (Z) — a second Gouraud triangle with 3 DISTINCT vertex Z
//       values is drawn with Z-test ALWAYS (z_rd_data tied to 0). The
//       TB probes the white-box s2_interp_z at a few interior pixels and
//       asserts it matches the expected affine Z plane (within 1 LSB of
//       the barycentric Z), proving per-pixel interpolated depth feeds
//       the Brick-2b Z path.
//
// The interpolation path is synthesizable: this TB exercises the exact
// same RTL functions (grad_dadx/grad_dady + interp_affine8/interp_affine_z)
// that synthesis sees — there is no translate_off fork.

`timescale 1ns/1ps

module tb_gs_tri_interp;

    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;

    // Outputs (most tied off — we watch raster_* + whitebox).
    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;

    gs_stub 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(32'd0),
        .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),  // Z buffer cleared
        .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

    function automatic logic [63:0] xyz2z(input int x, input int y, input int z);
        return {32'(z), 12'(y), 4'd0, 12'(x), 4'd0};
    endfunction
    function automatic logic [63:0] rgbaq(input int r, input int g, input int b);
        return {32'd0, 8'hFF, 8'(b), 8'(g), 8'(r)};
    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 [7:0] R_TEST_1  = 8'h47;
    localparam logic [7:0] R_ZBUF_1  = 8'h4E;
    localparam logic [63:0] PRIM_TRI    = 64'd3;
    localparam logic [63:0] FRAME_1_VAL = 64'h0000_0000_0001_0000;  // FBW=1, PSMCT32

    // ----- Independent reference: edge functions, fill rule, barycentric -----
    // Triangle vertices (set per primitive before reference calls).
    int vx0, vy0, vx1, vy1, vx2, vy2;
    int cr0, cg0, cb0, cr1, cg1, cb1, cr2, cg2, cb2;
    int vz0, vz1, vz2;
    int ref_det;

    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

    // Post-swap CCW reference (det>0). The DUT swaps v1<->v2 if the
    // signed area is negative; this reference computes the signed area
    // and mirrors that swap so L weights are interior-positive.
    int sx1, sy1, sx2, sy2;          // post-swap v1/v2 screen coords
    int scr1, scg1, scb1, scr2, scg2, scb2, sz1, sz2;
    task automatic setup_ref();
        int sa;
        sa = (vx1 - vx0) * (vy2 - vy0) - (vy1 - vy0) * (vx2 - vx0);
        if (sa < 0) begin
            sx1 = vx2; sy1 = vy2; sx2 = vx1; sy2 = vy1;
            scr1 = cr2; scg1 = cg2; scb1 = cb2; sz1 = vz2;
            scr2 = cr1; scg2 = cg1; scb2 = cb1; sz2 = vz1;
            ref_det = -sa;
        end else begin
            sx1 = vx1; sy1 = vy1; sx2 = vx2; sy2 = vy2;
            scr1 = cr1; scg1 = cg1; scb1 = cb1; sz1 = vz1;
            scr2 = cr2; scg2 = cg2; scb2 = cb2; sz2 = vz2;
            ref_det = sa;
        end
    endtask

    // top-or-left predicate (post-swap CCW)
    function automatic bit tol(input int ax, input int ay, input int bx, input int by);
        int dx, dy;
        dx = bx - ax; dy = by - ay;
        return (dy > 0) || ((dy == 0) && (dx > 0));
    endfunction

    // Inside test using the same biased edge functions the DUT uses.
    function automatic bit ref_inside(input int px, input int py);
        int e0, e1, e2;
        int b0, b1, b2;
        e0 = edge_f(px, py, vx0, vy0, sx1, sy1);
        e1 = edge_f(px, py, sx1, sy1, sx2, sy2);
        e2 = edge_f(px, py, sx2, sy2, vx0, vy0);
        b0 = tol(vx0, vy0, sx1, sy1) ? 0 : 1;
        b1 = tol(sx1, sy1, sx2, sy2) ? 0 : 1;
        b2 = tol(sx2, sy2, vx0, vy0) ? 0 : 1;
        return ((e0 + b0) <= 0) && ((e1 + b1) <= 0) && ((e2 + b2) <= 0);
    endfunction

    // Exact barycentric attribute (ground truth, rational/det) for an
    // attribute with post-swap vertex values a0/a1/a2.
    function automatic int ref_attr(input int px, input int py,
                                    input int a0, input int a1, input int a2);
        int L0, L1, L2;  // -e1, -e2, -e0 (interior-positive)
        int 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 * a0 + L1 * a1 + L2 * a2;
        if (ref_det == 0) return 0;
        return num / ref_det;        // integer trunc toward 0 (matches HW divide)
    endfunction

    int errors;
    int emit_inside_ok, emit_outside_bad, missing_inside;

    // Coverage map captured from raster_pixel emits for the current prim.
    bit covered [0:15][0:15];
    logic [7:0] cap_r [0:15][0:15];
    logic [7:0] cap_g [0:15][0:15];
    logic [7:0] cap_b [0:15][0:15];

    task automatic clear_cov();
        for (int y = 0; y < 16; y++)
            for (int x = 0; x < 16; x++) begin
                covered[y][x] = 1'b0;
                cap_r[y][x] = 8'd0; cap_g[y][x] = 8'd0; cap_b[y][x] = 8'd0;
            end
    endtask

    // Capture emits while armed.
    bit cap_armed;
    always_ff @(posedge clk) begin
        if (rst_n && cap_armed && raster_pixel_emit
            && raster_pixel_x_q < 16 && raster_pixel_y_q < 16) begin
            covered[raster_pixel_y_q][raster_pixel_x_q] <= 1'b1;
            cap_r[raster_pixel_y_q][raster_pixel_x_q] <= raster_pixel_color_q[7:0];
            cap_g[raster_pixel_y_q][raster_pixel_x_q] <= raster_pixel_color_q[15:8];
            cap_b[raster_pixel_y_q][raster_pixel_x_q] <= raster_pixel_color_q[23:16];
        end
    end

    initial begin
        errors = 0; emit_inside_ok = 0; emit_outside_bad = 0; missing_inside = 0;
        cap_armed = 1'b0;
        rst_n = 1'b0; gif_reg_wr_en = 1'b0; gif_reg_num = 8'd0; gif_reg_data = 64'd0;
        clear_cov();

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

        // =====================================================================
        // TEST 1 — Gouraud color, non-axis-aligned, no Z-test.
        //   v0=(2,1) RED, v1=(13,2) GREEN, v2=(5,7) BLUE.
        // =====================================================================
        vx0=2; vy0=1; cr0=8'hFF; cg0=0;    cb0=0;    vz0=0;
        vx1=13;vy1=2; cr1=0;     cg1=8'hFF; cb1=0;    vz1=0;
        vx2=5; vy2=7; cr2=0;     cg2=0;     cb2=8'hFF; vz2=0;
        setup_ref();

        cap_armed = 1'b1;
        drive_reg(R_PRIM,    PRIM_TRI);
        drive_reg(R_FRAME_1, FRAME_1_VAL);
        drive_reg(R_RGBAQ,   rgbaq(cr0,cg0,cb0));
        drive_reg(R_XYZ2,    xyz2z(vx0,vy0,vz0));
        drive_reg(R_RGBAQ,   rgbaq(cr1,cg1,cb1));
        drive_reg(R_XYZ2,    xyz2z(vx1,vy1,vz1));
        drive_reg(R_RGBAQ,   rgbaq(cr2,cg2,cb2));
        drive_reg(R_XYZ2,    xyz2z(vx2,vy2,vz2));  // closes
        drive_idle();
        repeat (260) @(posedge clk);
        cap_armed = 1'b0;
        @(posedge clk);

        // Coverage + color checks against the reference.
        for (int y = 0; y < 16; y++) begin
            for (int x = 0; x < 16; x++) begin
                bit want;
                want = ref_inside(x, y);
                if (want && !covered[y][x]) begin
                    $error("[T1 coverage] inside pixel (%0d,%0d) NOT drawn", x, y);
                    missing_inside = missing_inside + 1; errors = errors + 1;
                end else if (!want && covered[y][x]) begin
                    $error("[T1 coverage] outside pixel (%0d,%0d) WAS drawn", x, y);
                    emit_outside_bad = emit_outside_bad + 1; errors = errors + 1;
                end else if (want && covered[y][x]) begin
                    emit_inside_ok = emit_inside_ok + 1;
                end
            end
        end

        // Spot-check interpolated color at interior pixels vs barycentric
        // ground truth (affine == barycentric within 1 LSB).
        chk_color(7, 3);
        chk_color(5, 4);
        chk_color(9, 4);
        chk_color(6, 2);

        if (raster_overflow)   begin $error("[T1] raster_overflow"); errors=errors+1; end
        if (raster_degenerate) begin $error("[T1] raster_degenerate"); errors=errors+1; end

        // =====================================================================
        // TEST 2 — interpolated DEPTH. Gouraud triangle with distinct vertex
        //   Z, Z-test active (ALWAYS, cleared Z buffer). Probe s2_interp_z.
        //   v0=(2,1) z=0x100, v1=(13,2) z=0x700, v2=(5,7) z=0x400.
        // =====================================================================
        vx0=2; vy0=1; cr0=8'hFF; cg0=0;    cb0=0;    vz0=32'h100;
        vx1=13;vy1=2; cr1=0;     cg1=8'hFF; cb1=0;    vz1=32'h700;
        vx2=5; vy2=7; cr2=0;     cg2=0;     cb2=8'hFF; vz2=32'h400;
        setup_ref();

        // TEST_1.ZTE=1, ZTST=ALWAYS(1). ZBUF ZBP=2 PSMZ32 ZMSK=0.
        drive_reg(R_PRIM,    PRIM_TRI);
        drive_reg(R_FRAME_1, FRAME_1_VAL);
        drive_reg(R_TEST_1,  (64'd1 << 16) | (64'd1 << 17));  // ZTE=1, ALWAYS
        drive_reg(R_ZBUF_1,  64'd2);                          // ZBP=2, PSMZ32, ZMSK=0
        drive_reg(R_RGBAQ,   rgbaq(cr0,cg0,cb0));
        drive_reg(R_XYZ2,    xyz2z(vx0,vy0,vz0));
        drive_reg(R_RGBAQ,   rgbaq(cr1,cg1,cb1));
        drive_reg(R_XYZ2,    xyz2z(vx1,vy1,vz1));
        drive_reg(R_RGBAQ,   rgbaq(cr2,cg2,cb2));
        drive_reg(R_XYZ2,    xyz2z(vx2,vy2,vz2));  // closes
        drive_idle();
        // Probe s2_interp_z across the scan (collected by the monitor below).
        repeat (520) @(posedge clk);

        if (z_probe_checks == 0) begin
            $error("[T2] no interior Z pixels observed");
            errors = errors + 1;
        end

        $display("[tb_gs_tri_interp] T1 inside_ok=%0d missing=%0d outside_bad=%0d | T2 z_checks=%0d errors=%0d",
                 emit_inside_ok, missing_inside, emit_outside_bad, z_probe_checks, errors);
        if (errors == 0) $display("[tb_gs_tri_interp] PASS");
        else             $display("[tb_gs_tri_interp] FAIL");
        $finish;
    end

    // Color spot-check: compare DUT-captured color to barycentric ground
    // truth with 1-LSB tolerance.
    task automatic chk_color(input int x, input int y);
        int er, eg, eb;
        if (!ref_inside(x, y)) begin
            // outside the triangle — not a meaningful color spot
        end else if (!covered[y][x]) begin
            $error("[T1 color] (%0d,%0d) inside but not covered", x, y);
            errors = errors + 1;
        end else begin
            er = ref_attr(x, y, cr0, scr1, scr2);
            eg = ref_attr(x, y, cg0, scg1, scg2);
            eb = ref_attr(x, y, cb0, scb1, scb2);
            if (absdiff(cap_r[y][x], er) > 1 ||
                absdiff(cap_g[y][x], eg) > 1 ||
                absdiff(cap_b[y][x], eb) > 1) begin
                $error("[T1 color] (%0d,%0d) got (%0d,%0d,%0d) expected ~(%0d,%0d,%0d)",
                       x, y, cap_r[y][x], cap_g[y][x], cap_b[y][x], er, eg, eb);
                errors = errors + 1;
            end else begin
                $display("[T1 color] (%0d,%0d) got (%0d,%0d,%0d) ref (%0d,%0d,%0d) OK",
                         x, y, cap_r[y][x], cap_g[y][x], cap_b[y][x], er, eg, eb);
            end
        end
    endtask

    function automatic int absdiff(input int a, input int b);
        return (a > b) ? (a - b) : (b - a);
    endfunction

    // ----- Ch296 multiplier-resize guard: the per-pixel interp multiplier
    // operands dx/dy were narrowed to signed 16 bits. Assert at every live
    // S2 cycle that the white-box s2_dx/s2_dy actually stay inside signed
    // 16-bit range (true bound is ±4095 from 12-bit screen coords). If a
    // future change widens screen coords past this, the resize is no longer
    // lossless and this fires.
    always_ff @(posedge clk) begin
        if (rst_n && u_gs.s2_valid_q) begin
            if ($signed(u_gs.s2_dx) > 32767 || $signed(u_gs.s2_dx) < -32768) begin
                $error("[dx range] s2_dx=%0d out of signed-16 range", $signed(u_gs.s2_dx));
                errors = errors + 1;
            end
            if ($signed(u_gs.s2_dy) > 32767 || $signed(u_gs.s2_dy) < -32768) begin
                $error("[dy range] s2_dy=%0d out of signed-16 range", $signed(u_gs.s2_dy));
                errors = errors + 1;
            end
        end
    end

    // ----- T2 Z probe: watch the whitebox s2_interp_z at interior S2 pixels.
    int z_probe_checks;
    initial z_probe_checks = 0;
    bit z_probe_armed;
    always_ff @(posedge clk) begin
        if (rst_n && z_probe_armed
            && u_gs.s2_valid_q && u_gs.s2_inside_q
            && u_gs.ras_tri_active) begin
            int px, py;
            int ez;
            px = int'(u_gs.s2_x_q);
            py = int'(u_gs.s2_y_q);
            if (px < 16 && py < 16 && ref_inside(px, py)) begin
                ez = ref_attr(px, py, vz0, sz1, sz2);
                if (absdiff(int'(u_gs.s2_interp_z), ez) > 1) begin
                    $error("[T2 Z] (%0d,%0d) s2_interp_z=%0d expected ~%0d",
                           px, py, u_gs.s2_interp_z, ez);
                    errors = errors + 1;
                end else begin
                    z_probe_checks = z_probe_checks + 1;
                end
            end
        end
    end
    // Arm the Z probe only during TEST 2 (after T1 finishes). T1 has
    // vz*=0 so its s2_interp_z is trivially 0; gate on a nonzero vertex Z.
    always_comb z_probe_armed = (vz1 != 0);

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

endmodule : tb_gs_tri_interp
