#include <vga.h>
#include <stdlib.h>

#include "sintab.h"

#define S() (srand48(getpid()))
#define R(x) (drand48()*x)

#define XSIZE (320/XMAG)
#define YSIZE (200/YMAG)
#define XMAG 8
#define YMAG 8
#define MOVE 4
#define SPOTS 4

int spots[3][2][SPOTS];
char line[XSIZE*XMAG*3];

int world[YSIZE][XSIZE][3][2];
#define W(x,y,z) (world[y][x][z][f])
#define O(x,y,z) (world[y][x][z][1-f])

frame() {
	static int f=0;
	int x,y,xx,yy,i,j,k,c[3];
	char *lp;


	f=1-f;
	yy=0;
	for(i=0;i<3;i++) for(j=0;j<SPOTS;j++) O(spots[i][0][j],spots[i][1][j],i)+=512;
	for(y=0;y<YSIZE;y++) {
		lp=line;
		for(x=0;x<XSIZE;x++) {
			for(i=0;i<3;i++) {
				if((y==0)||(x==0)||(y==(YSIZE-1))||(x==(XSIZE-1))) W(x,y,i)=0;
				else W(x,y,i)=(
#ifdef DIAG
					O(x-1,y-1,i)+O(x-1,y+1,i)+O(x+1,y-1,i)+O(x+1,y+1,i)+
#endif
					O(x,y+1,i)+O(x,y-1,i)+O(x-1,y,i)+O(x+1,y,i))
#ifdef DIAG
					/8-1;
#else
					/4-1;
#endif
				for(j=0;j<SPOTS;j++) if((spots[i][1][j])==y&&(spots[i][0][j]==x))
					W(x,y,i)+=512;
				if (W(x,y,i)<0) W(x,y,i)=0;
				j=W(x,y,i); if(j>255)j=255;
				c[i]=j;
			}
			for(xx=0;xx<XMAG;xx++) {
				*(lp++)=c[0];
				*(lp++)=c[1];
				*(lp++)=c[2];
			}
		}
		for(xx=0;xx<YMAG;xx++) vga_drawscansegment(line,0,yy++,3*XSIZE*XMAG); 
	}
	for(i=0;i<3;i++) for(j=0;j<SPOTS;j++) for(k=0;k<MOVE;k++) {
		spots[i][0][j]+=((int)R(3))-1; if(spots[i][0][j]<1)spots[i][0][j]=1; if(spots[i][0][j]>XSIZE-2)spots[i][0][j]=XSIZE-2;
		spots[i][1][j]+=((int)R(3))-1; if(spots[i][1][j]<1)spots[i][1][j]=1; if(spots[i][1][j]>YSIZE-2)spots[i][1][j]=YSIZE-2;
	}
}
	
main(int argc, char **argv[]) {
	int i,j;

	S();

	vga_setmode(G320x200x16M); 

	for(i=0;i<3;i++) for(j=0;j<SPOTS;j++) {spots[i][0][j]=R(XSIZE-2)+1; spots[i][1][j]=R(YSIZE-2)+1; }

 	while(1) frame();
}
