program Tutorial3_Levels;
@use levels
@use screens

// Export the level data
@export "images/level.flf" "images/level.bin" 256

// Export the metatile data (2x2 chunks of tiles)
@export "images/metatiles.flf" "images/metatiles.bin" 256

// Export the tile data
@export "images/tiles.flf" "images/tiles.bin" 256


var  
	// Bank to place sprites
	const levelBank : byte = 2;
	
	level_data : incbin("images/level.bin") bank(levelBank);
	tiles : incbin("images/tiles.bin") bank(levelBank);
	metatiles : incbin("images/metatiles.bin") bank(levelBank);


	time,x,y,curLevel  : byte;

	// Generate a sine table
    sine : array[256] of byte = BuildSineTable(127);


/*
	Renders the level and copies to the screen while turned off

*/

procedure RenderLevel(x,y : global byte);
begin
	current_bank := levelBank;
	Levels::lp := #level_data;
	Levels::RenderLevel2x2MetaTiles(x,y);
	// Remember to turn off LCD before copying to VRAM!
	Screens::StopLCD();
	memcpy(^$D000,screen0,$400);
	Screens::Set9800();
end;



procedure VBlank();
begin
	time:=time+1;
	scrollx:=sine[time]/2;
	scrolly:=sine[time+64]/2;
	
	if (time=0) then 
	begin
		curLevel:=(curLevel+1)&1;
		RenderLevel(0,curLevel);
	end;
end;




procedure InitLevelData();
begin
	current_bank := levelBank;
	// Set up tile data
	Screens::CopyFullCharset(#tiles);

	// Set TRU data to point to level & metatiles
	Levels::mt := #metatiles;
	Levels::ReadHeader(#level_data);
	// Set a nice palette
	background_palette:=%11010010;
	object0_palette:=%11010010;

end;


begin
	Screens::InitDefaultScreen();
	current_bank:=levelBank;

	InitLevelData();
	RenderLevel(0,0);

	time:=0;
	curLevel:=0;
	
	// must have Vertical blank in order to be able to display sprites
	InitVBlank(VBlank());
	EnableVBLank();
	Loop();	
end.
