program Tutorial_7_80col;
var  
   	i,j,k, x,y,dx,dy, time,xx,add: byte; 
	int : integer;
	zp1,zp2 : pointer;
	perlin : incbin("resources/data/perlin16.dat");
	@export "resources/charsets/charset.flf" "resources/charsets/charset.bin" 256
	charset : incbin("resources/charsets/charset.bin", $3000);


@define c1pos $4000
@define l1pos $4800


procedure PreCalculate();
begin
	zp1:=@c1pos;
	zp2:=@l1pos;
	xx:=255;
	for y:=0 to 25 do begin
		for x:=0 to 80 do begin
			dx:=abs(40-x);
			dx:=dx/3;
		
			dy:=abs(12-y);
			int := dx*dx + dy*dy;
			int:=int/7;
			i:=sqrt(int);
			i:=i+5;
			zp1[x]:=64/i;

			j:=atan2(40,x,24,y*2);

			zp2[x]:=j/5;

		end;
		zp1:=zp1+80;
		zp2:=zp2+80;
	end;

end;




procedure Render();
begin
	vdcinit(31);
	zp1:=@c1pos;
	zp2:=@l1pos;
	for y:=0 to 25 do begin
//		for x:=0 to 80 do begin
			asm("
				ldy #0
				
;				ldy x
iLoop:
				lda (zp1),y
				adc time	
				adc (zp2),y
				tax
				lda perlin,x
				adc add	
				sta $D601				

				iny
				cpy #80
				bne iLoop
			");
		zp1:=zp1+80;
		zp2:=zp2+80;

	end;


end;



procedure CopyCharset();
begin
	zp1:=#charset;
	vdcwrite(18,$20);
	vdcwrite(19,$00);
	vdcinit(31);
	for i:=0 to 256 do begin
		for j:=0 to 8 do begin
			k:=zp1[j];
			poke(^$D601,0,k);			
		end;
		// Shadow 8 bytes wasted because the VDC needs 16 bytes per &%(¤/% char
		for j:=0 to 8 do
			poke(^$D601,0,k);			

		zp1:=zp1+8;
	end;

end;

procedure SetupTables();
begin
	for i:=0 to 0 do begin
		k:=peek(#perlin,i);
		k:=k/28;
		poke(#perlin,i,k);
	end;

end;


begin
	Go80Columns();
	// Set 2 mhz mode
	Set2MhzMode();
	// Enable $4K-$8K
	SetMemoryConfig(0,1,1,1,0);	
	PreCalculate();
	SetupTables();
	MoveTo80(0,0,$08);
	// Copy charset data from ram to VDC ($2000)
	CopyCharset();	
	for i:=0 to 25 do 
		fill80(7, 80);
	
	// Move to x=20, y=10 at memory address $0000 on the VDC (text matrix)
	
	while (1=1) do begin
		inc(time);
		// Move to matrix ram
		MoveTo80(0,0,0);
		add:=64; // Base character
		Render(); // Render text
		// Move to color (attribute) ram
		MoveTo80(0,0,$08);
		add:=7; // base color = 7
		Render(); // Render color
	end;

	Loop();
end.
