// retroDE_ps2 — tb_top_psmct32_tile_wrap_demo (Ch307)
//
// GS texture WRAP MODES (REPEAT + CLAMP) in the tiled renderer. Two textured
// combined prims sample the SAME striped 4x4 texture (columns u=0,1 WHITE,
// u=2,3 BLUE; opaque A=0x80) with UV running u:0->8 (2x the texture width):
//   REPEAT prim (top band, CLAMP_1 WMS=WMT=0): white stripe REPEATS at u=0 and
//     u=4 -> TWO white stripes (texture tiles).
//   CLAMP  prim (bottom band, WMS=WMT=1): white at u=0..1 only; u>=2 sticks to
//     the blue edge -> ONE white stripe.
// Both cross the x=16 tile seam. Distinguishing region u in [4,6): REPEAT=WHITE,
// CLAMP=BLUE. Opaque texels (As=0x80 -> Cv=Cs), so expected color == texel RGB.
//
// PROOFS:
//   REPEAT-TILES : >=N pixels in the u-in-[4,6) band of the REPEAT prim are WHITE.
//   CLAMP-STICKS : the SAME band of the CLAMP prim is BLUE (0 white there).
//   FIRST-STRIPE : both prims show the u-in-[0,2) white stripe (texture sampled).
//   IMAGE        : whole 32x32 matches the wrap/clamp software reference.
//   GRID         : 4 tiles cleared (256 each) + 1024 flush; prim list = 2.

`timescale 1ns/1ps

module tb_top_psmct32_tile_wrap_demo;

    localparam int H_ACTIVE = 32, V_ACTIVE = 32;
    localparam int TP_CLEAR = 1;
    localparam real MARG = 0.10;   // triangle-edge barycentric margin
    localparam real UFRAC = 0.30;  // skip pixels whose interp-u is near a texel boundary
    localparam int TWIDTH = 4;     // 2^TW

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

    logic        core_go;
    logic [7:0]  r, g, b;
    logic        hsync, vsync, de;
    logic        core_halt, dma_done_seen, frame_seen, raster_overflow;
    logic        frame_toggle, dma_done_toggle;

    top_psmct32_raster_demo_bram #(
        .H_ACTIVE(H_ACTIVE), .V_ACTIVE(V_ACTIVE),
        .VRAM_BYTES(16*1024), .PSMCT32_SWIZZLE(1'b0),
        .COMBINED_TAZ(1'b1), .TILE_LOCAL(1'b1), .TILE_COLS(2), .TILE_ROWS(2),
        .TILE_MULTIPRIM(1'b1), .TILE_PRIM_COUNT(2), .TEX_WRAP_ENABLE(1'b1)
    ) dut (
        .clk(clk), .rst_n(rst_n), .core_go(core_go),
        .r(r), .g(g), .b(b), .hsync(hsync), .vsync(vsync), .de(de),
        .core_halt(core_halt), .dma_done_seen(dma_done_seen),
        .frame_seen(frame_seen), .raster_overflow(raster_overflow),
        .frame_toggle(frame_toggle), .dma_done_toggle(dma_done_toggle),
        .joy_a_pressed_i(1'b0), .joy_b_pressed_i(1'b0)
    );

    // barycentric weights wb (of vertex b) for a triangle — used for the affine u.
    function automatic int tri_cls(input real px, input real py,
                                   input real ax, input real ay,
                                   input real bx, input real by,
                                   input real cx, input real cy);
        real d, wa, wb, wc;
        begin
            d  = (by-cy)*(ax-cx) + (cx-bx)*(ay-cy);
            wa = ((by-cy)*(px-cx) + (cx-bx)*(py-cy)) / d;
            wb = ((cy-ay)*(px-cx) + (ax-cx)*(py-cy)) / d;
            wc = 1.0 - wa - wb;
            if (wa>MARG && wb>MARG && wc>MARG)            tri_cls = 1;
            else if (wa<-MARG || wb<-MARG || wc<-MARG)    tri_cls = 0;
            else                                          tri_cls = 2;
        end
    endfunction
    function automatic real tri_wb(input real px, input real py,
                                   input real ax, input real ay,
                                   input real bx, input real by,
                                   input real cx, input real cy);
        real d;
        begin
            d  = (by-cy)*(ax-cx) + (cx-bx)*(ay-cy);
            tri_wb = ((cy-ay)*(px-cx) + (ax-cx)*(py-cy)) / d;
        end
    endfunction

    // ---- grid tracers ----
    int  clear_cw_tile [0:1][0:1];
    int  flush_emits;
    bit  saw_prim_count_2;
    initial begin
        for (int rr=0;rr<2;rr++) for (int cc=0;cc<2;cc++) clear_cw_tile[rr][cc]=0;
        flush_emits=0; saw_prim_count_2=1'b0;
    end
    always_ff @(posedge clk) if (rst_n) begin
        if (dut.u_gs.tile_phase==TP_CLEAR && dut.u_gs.tile_color_we) begin
            int cc, rr; cc=int'(dut.u_gs.tile_col_r); rr=int'(dut.u_gs.tile_row_r);
            if (cc<2 && rr<2) clear_cw_tile[rr][cc] <= clear_cw_tile[rr][cc] + 1;
        end
        if (dut.u_gs.raster_pixel_emit) flush_emits <= flush_emits + 1;
        if (dut.u_gs.raster_active && (int'(dut.u_gs.prim_count_r)==2)) saw_prim_count_2 <= 1'b1;
    end

    // ---- scanout capture (32x32) ----
    logic [7:0] cap_r[0:V_ACTIVE-1][0:H_ACTIVE-1], cap_g[0:V_ACTIVE-1][0:H_ACTIVE-1], cap_b[0:V_ACTIVE-1][0:H_ACTIVE-1];
    logic       cap_de[0:V_ACTIVE-1][0:H_ACTIVE-1];
    bit capture_armed;
    initial begin
        for (int y=0;y<V_ACTIVE;y++) for (int x=0;x<H_ACTIVE;x++) begin cap_r[y][x]=0;cap_g[y][x]=0;cap_b[y][x]=0;cap_de[y][x]=0; end
        capture_armed=1'b0;
    end
    logic [31:0] hcnt_d, vcnt_d;
    always_ff @(posedge clk) begin
        if (!rst_n) begin hcnt_d<=0; vcnt_d<=0; end
        else begin hcnt_d<=32'(dut.u_pcrtc.hcnt); vcnt_d<=32'(dut.u_pcrtc.vcnt); end
    end
    always_ff @(posedge clk) begin
        if (rst_n && capture_armed && de && (vcnt_d<V_ACTIVE) && (hcnt_d<H_ACTIVE)) begin
            cap_r[vcnt_d][hcnt_d]<=r; cap_g[vcnt_d][hcnt_d]<=g; cap_b[vcnt_d][hcnt_d]<=b; cap_de[vcnt_d][hcnt_d]<=1'b1;
        end
    end

    int errors, n_match, n_check, n_seam;
    int n_rep2_white, n_clamp2_blue, n_first_white;

    initial begin
        errors=0; n_match=0; n_check=0; n_seam=0;
        n_rep2_white=0; n_clamp2_blue=0; n_first_white=0;
        rst_n=1'b0; core_go=1'b0;
        repeat(4) @(posedge clk); rst_n=1'b1; repeat(8) @(posedge clk);
        @(negedge clk); core_go=1'b1; @(negedge clk); core_go=1'b0;
        wait (core_halt==1'b1); repeat(4) @(posedge clk);
        wait (dma_done_seen==1'b1); repeat(10) @(posedge clk);
        if (dut.xfer_busy==1'b1) wait (dut.xfer_busy==1'b0);
        @(posedge dut.u_gs.raster_active);
        @(negedge dut.u_gs.raster_active);
        repeat(10) @(posedge clk);
        @(posedge dut.u_pcrtc.end_of_frame); @(posedge clk); capture_armed=1'b1;
        @(posedge dut.u_pcrtc.end_of_frame); @(posedge clk); capture_armed=1'b0;

        // PROOF GRID
        for (int rr=0;rr<2;rr++) for (int cc=0;cc<2;cc++)
            if (clear_cw_tile[rr][cc] != 256) begin
                $error("[twr] tile(col=%0d,row=%0d) cleared %0d (want 256)", cc, rr, clear_cw_tile[rr][cc]); errors++;
            end
        if (flush_emits != 4*256) begin $error("[twr] flush emitted %0d (want %0d)", flush_emits, 4*256); errors++; end
        if (!saw_prim_count_2)     begin $error("[twr] prim_count_r never == 2"); errors++; end

        // PROOF IMAGE — whole 32x32 vs the wrap/clamp reference.
        for (int py=0; py<V_ACTIVE; py++) begin
            for (int px=0; px<H_ACTIVE; px++) begin
                int crep, cclmp, tu, te, mode;
                real uf, fr;
                logic [7:0] er, eg, eb;
                bit skip_u;
                crep  = tri_cls(real'(px),real'(py),  2,4, 29,4, 2,15);   // REPEAT tri (top)
                cclmp = tri_cls(real'(px),real'(py),  2,17,29,17,2,28);   // CLAMP  tri (bottom)
                er=8'hxx; eg=8'hxx; eb=8'hxx; mode=-1; uf=0.0;
                if (crep==2 || cclmp==2) begin
                    // near a triangle edge -> skip
                end else if (crep==1) begin
                    mode=0; uf = 8.0 * tri_wb(real'(px),real'(py), 2,4, 29,4, 2,15);
                end else if (cclmp==1) begin
                    mode=1; uf = 8.0 * tri_wb(real'(px),real'(py), 2,17,29,17,2,28);
                end else begin
                    er=8'h00; eg=8'h80; eb=8'h00;   // outside both -> clear green
                end

                if (mode>=0) begin
                    fr = uf - $floor(uf);
                    skip_u = (fr < UFRAC) || (fr > 1.0-UFRAC);   // near texel boundary -> ambiguous
                    if (!skip_u) begin
                        tu = int'($floor(uf));
                        te = (mode==0) ? (tu & (TWIDTH-1)) : ((tu < TWIDTH) ? tu : TWIDTH-1);
                        // striped texture: columns 0,1 white; 2,3 blue (opaque -> texel RGB)
                        if (te <= 1) begin er=8'hFF; eg=8'hFF; eb=8'hFF; end
                        else         begin er=8'h00; eg=8'h00; eb=8'hFF; end
                    end
                end

                if (er!==8'hxx && cap_de[py][px]) begin
                    n_check++;
                    // distinguishing tallies (u in [4,6))
                    if (mode>=0 && uf>=4.0 && uf<6.0 && !( (uf-$floor(uf))<UFRAC || (uf-$floor(uf))>1.0-UFRAC )) begin
                        if (mode==0 && er==8'hFF) n_rep2_white++;
                        if (mode==1 && eb==8'hFF && er==8'h00) n_clamp2_blue++;
                    end
                    if (mode>=0 && uf>=0.0 && uf<2.0 && er==8'hFF) n_first_white++;
                    if (cap_r[py][px]===er && cap_g[py][px]===eg && cap_b[py][px]===eb) begin
                        n_match++;
                        if (px==15||px==16) n_seam++;
                    end else begin
                        if (errors<14) $error("[twr] (%0d,%0d) mode=%0d uf=%0.2f got(%02x,%02x,%02x) exp(%02x,%02x,%02x)",
                                              px,py,mode,uf,cap_r[py][px],cap_g[py][px],cap_b[py][px],er,eg,eb);
                        errors++;
                    end
                end
            end
        end

        if (n_check < 150)      begin $error("[twr] too few checkable pixels (%0d)", n_check); errors++; end
        if (n_match != n_check) begin $error("[twr] image match %0d/%0d (wrap/clamp error)", n_match, n_check); errors++; end
        if (n_first_white < 8)  begin $error("[twr] first white stripe thin (%0d) — texture not sampled", n_first_white); errors++; end
        if (n_rep2_white < 4)   begin $error("[twr] REPEAT 2nd stripe thin (%0d) — repeat not proven", n_rep2_white); errors++; end
        if (n_clamp2_blue < 4)  begin $error("[twr] CLAMP region not blue enough (%0d) — clamp not proven", n_clamp2_blue); errors++; end
        if (n_seam < 8)         begin $error("[twr] too few SEAM matches (%0d)", n_seam); errors++; end
        if (!core_halt)         begin $error("core_halt low"); errors++; end
        if (raster_overflow)    begin $error("raster_overflow"); errors++; end

        $display("[tb_top_psmct32_tile_wrap_demo] clears=[%0d %0d %0d %0d] flush=%0d prim2=%0b match=%0d/%0d seam=%0d | firstW=%0d rep2W=%0d clamp2B=%0d errors=%0d",
                 clear_cw_tile[0][0],clear_cw_tile[0][1],clear_cw_tile[1][0],clear_cw_tile[1][1],
                 flush_emits, saw_prim_count_2, n_match, n_check, n_seam,
                 n_first_white, n_rep2_white, n_clamp2_blue, errors);
        if (errors==0) $display("[tb_top_psmct32_tile_wrap_demo] PASS");
        else           $display("[tb_top_psmct32_tile_wrap_demo] FAIL");
        $finish;
    end

    initial begin #300000000; $error("[tb_top_psmct32_tile_wrap_demo] TIMEOUT"); $finish; end
endmodule : tb_top_psmct32_tile_wrap_demo
