program Tutorial1_Tiles;
/*

	In this first SNES tutorial, we set up the system to have 2 background (tiled) planes.
	On the first plane, we display a simple text string, while the other one is filled with
	all the available tiles. Background 2 is then scrolled using the hardware scroll registers. 

	First of all, we're using mode 1 here, which corresponds to 2 4bpp (16 colour) tiles. The tile
	graphics is located in "resources/gfx/tiles.flf", and was created with the 4bpp (16 colour) option. 

	NB: Make sure you NEVER copy data to VRAM while outside of vsync/the screen is turned on! This will
	result in corrupted data.
*/

// The unit "Screen" contains all the important methods for VRAM operations
@use "screen"
var
// Automatically export "tiles.flf", and export only 1 (128x128) bank	
@export "resources/gfx/tiles.flf" "resources/gfx/tiles.bin" 1

// Where we decide to put the charset in VRAM
	const charset1_addr : integer = $3000;

// The tile data. 
	tiles : incbin("resources/gfx/tiles.bin");
// "export" automatically exports the palette as well
	palette_tiles: incbin("resources/gfx/tiles.pal");
// Some random string	
	text : string="TRSE ON SNES";	
	
	
	i1:integer;
	i,j,val,col:byte;


begin
	// Initialses the SNES
	Screen::Init();
	// Copies the palette to VRAM
	Screen::SetPalette(#palette_tiles,0,$100);
	// Sets mode 1, points all background VRAM to the same address. 
	// If you want your backgrounds to use independent tile data, set this up here	
	Screen::SetGraphicsMode(1, #charset1_addr);
	// Copes all the tile data to VRAM
	Screen::CopyToVRAM(#tiles,#charset1_addr,128*128/2);
	// Sets up the background 0 and 1 to pointt to $1000 and $1400. Only works for 32x32 playfields, if
	// you are using 64x64, you need to set BG2 to be BG1+64*64
	Screen::SetBGScreenLocation(0,hi(#SCREEN_BG1) | Screen::BG_32X32);
	Screen::SetBGScreenLocation(1,hi(#SCREEN_BG2) | Screen::BG_32X32);
	
	// Fill background 1 with value 0 (all black) and attribute 0
	Screen::MoveToXY(0,0, #Screen::BG1);
	Screen::FillToVRAM(0, 0 , 32*32);
	
	// Fill background 2 with all the available tiles	
	Screen::MoveToXY(0,0, #Screen::BG2);
	for j:=0 to 32 do 
	begin
		for i:=0 to 32 do
		begin
			val:=(i) + (j)*16;			
			// Some random colour
			col:=(i+1)>>1;
			// 3-bit colour data starts at bit 2, so we need to SHL with 2
			Screen::PokeVRAM(val,(col&3)<<2);
		end;
	end;

	// Turn on background 1 and 2
	Screen::EnableGFX(Screen::ENABLE_BG1 | Screen::ENABLE_BG2);

	// Print the text, set priority high (so it will be displayed on top of everything)
	Screen::MoveToXY(10,20, #Screen::BG1);
	Screen::CopyToScreen(#text,length(text),Screen::TILE_PRIORITY);	

	 // Turn on the screen. 
	Screen::EnableDisplay();
	// Infinite loop		
 	while (true) offpage do
 	begin
	 	// wait for vsync
	 	Screen::WaitForVerticalBlank();
		// Scroll background 2 with some increasing value. 
		Screen::Scroll(i1,i1/2,2);
		i1+=1;
		
 	end;
 	
end.