+`define XRES 640
+`define XFPORCH 16
+`define XSYNC 96
+`define XBPORCH 48
+`define YRES 480
+`define YFPORCH 10
+`define YSYNC 2
+`define YBPORCH 29
+
+`define XOFS ((640-160)/2)
+`define YOFS ((480-144)/2)
+
+module Framebuffer(
+ input lcdclk,
+ input lcdvs, lcdhs,
+ input [2:0] lcdr, lcdg, input [1:0] lcdb,
+
+ input vgaclk,
+ output reg vgavs, vgahs,
+ output wire [2:0] vgar, vgag, output wire [1:0] vgab);
+
+ reg [2:0] fb [23039:0];
+
+ reg [7:0] lcdx = 8'h00;
+ reg [7:0] lcdy = 8'h00;
+ reg [15:0] lcdfb = 16'h0000;
+
+ always @(posedge lcdclk)
+ begin
+ /* We use BLOCKING assigns here. */
+ if (lcdvs) begin
+ lcdx <= 0;
+ lcdy <= 0;
+ lcdfb <= 0;
+ end else if (lcdhs) begin
+ lcdx <= 0;
+ lcdy <= lcdy + 1;
+ end else if (lcdx < 160) begin
+ lcdx <= lcdx + 1;
+ lcdfb <= lcdfb + 1;
+ end
+ end
+
+ reg [11:0] vgax = 0, vgay = 0;
+ reg [15:0] vgafb = 16'h0000;
+
+ reg [2:0] failandloss;
+ assign {vgar, vgag, vgab} =
+ ((vgax > `XOFS) && (vgax < (`XOFS + 160)) && (vgay > `YOFS) && (vgay < (`YOFS + 144))) ? {failandloss[2],2'b0,failandloss[1],2'b0,failandloss[0],1'b0} :
+ ((vgax < 640) && (vgay < 480)) ? 8'b11100000 :
+ 8'b00000000;
+
+ always @(posedge vgaclk)
+ begin
+ if (vgax >= (`XRES + `XFPORCH + `XSYNC + `XBPORCH))
+ begin
+ if (vgay >= (`YRES + `YFPORCH + `YSYNC + `YBPORCH)) begin
+ vgafb <= 0;
+ vgay <= 0;
+ end else
+ vgay <= vgay + 1;
+ vgax <= 0;
+ end else
+ vgax <= vgax + 1;
+
+ vgahs <= (vgax >= (`XRES + `XFPORCH)) && (vgax < (`XRES + `XFPORCH + `XSYNC));
+ vgavs <= (vgay >= (`YRES + `YFPORCH)) && (vgay < (`YRES + `YFPORCH + `YSYNC));
+
+ if ((vgax > `XOFS) && (vgax < (`XOFS + 160)) && (vgay > `YOFS) && (vgay < (`YOFS + 144))) begin
+ vgafb <= vgafb + 1;
+ failandloss <= fb[vgafb + 1];
+ end
+
+ // Need thsi here; vgaclk >>> lcdclk
+ if ((lcdy < 144) && (lcdx < 160))
+ fb[lcdfb] <= {lcdr[2], lcdg[2], lcdb[1]};
+ end
+endmodule