program part6_RenderLevel;
@use "gfx/Levels"

var

/*
In this tutorial, we use actual level data to render a screen with 
our character set
*/

// Memory position where we include the level data
@define levelPosition $5000
// Memory position (on VIC 0) for character data
@define charsetPosition $2000
// Don't use kernal
@define useKernal 0
@define @levelpointer levelp

// Automatically export sprites on each build, so you don't have to manually export
@export "sprites/Sprites.flf" "sprites/sprites.bin" 256
// Automatically export charsets 
@export "charsets/charset1.flf" "charsets/charset1.bin" 256

   	charset1: incbin("charsets/charset1.bin", @charsetPosition);
	levels: incbin("levels/level1.flf", @levelPosition);
	colors : incbin("charsets/charset1_color.bin", @charsetPosition+$800);
	// Define some pointers
	i,j:byte = 0;
	// Current level screen x,y
	curLevel_x, curLevel_y : byte=0;

// Include RasLib level renderer
@define colorpointer colormemory

// Initializes charsets etc
procedure Initialize();
begin
	clearscreen(light_blue, screen_col_loc);
	clearscreen(key_space, screen_char_loc);
	screen_fg_col:=black;
	screen_bg_col:=black;

	multicolor_char_col[1]:=grey;
	multicolor_char_col[2]:=brown;

	setmulticolormode();

	setcharsetlocation(@charsetPosition);
	// Make sure that the level pointer points to level data location
	// Read header data
	Levels::ReadHeader(@levelPosition);
	Levels::starty:=2;
end;


/*
	Main raster function that mainly just does nothing except when the joystick is moved. If so,
	a new level screen is rendered.

*/
interrupt RasterRenderLevels();
begin
	StartIRQ(@useKernal);
	if (i=0) then begin
		joystick(2);
		if (joystickdown=1) then begin inc(curLevel_y); i:=10; end;
		if (joystickup=1) then begin dec(curLevel_y); i:=10; end;
		if (joystickleft=1) then begin dec(curLevel_x); i:=10; end;
		if (joystickright=1) then begin inc(curLevel_x); i:=10; end;
	end;

	if (i=10) then begin
		screenoff();
		Levels::RenderCharsetColorLevel(curLevel_x,curLevel_y,$04);
		screenon();
	end;
	if (i) then dec(i); // i acts as a counter

	CloseIRQ();
end;

// Main block
begin
	Initialize();
	// Remember to set level location!
	Levels::lp:=@levelPosition;
	Levels::cdp := #colors;
	// Render the level to $0400
	Levels::RenderCharsetColorLevel(curLevel_x,curLevel_y,hi(screen_char_loc));

	DisableCIAInterrupts();
	SetMemoryConfig(1,@useKernal,0);
	RasterIRQ(RasterRenderLevels(),$00,@useKernal);
	EnableRasterIRQ();
	enableirq();
	Loop(); 
end.
