/*	Copyright Alex Hornby 1994/1995. All rights reserved.
 	See file README for details
*/

/* 2D starfield */

#include "starfield.h"
#include "rnd.h"

StarField::StarField()
{
	for(int f=0; f<NUMFIELD; f++)
	{
		for(int s=0; s<NUMSTAR; s++)
		{
		pos[s][f].x=rnd(getScreenWidth());
		pos[s][f].y=rnd(getScreenHeight());
		speed[s][f]=rnd(MAXSPEED)+1;
		}
	}
	color[7]=40;
	color[6]=40;
	color[5]=41;
	color[4]=41;
	color[3]=42;
	color[2]=42;
	color[1]=43;
	color[0]=43;
}

void 
StarField::getBack(void)
{
pixel *video;
	for(int f=0; f<NUMFIELD; f++)
	{
		for(int s=0; s<NUMSTAR; s++)
		{
		video= getGraphMem() + pos[s][f].x + pos[s][f].y * getScreenWidth();
		back[s][f]=*video;
		}
	}
}

void
StarField::replace(void)
{
	pixel *video;
	for(int f=0; f<NUMFIELD; f++)
	{
		for(int s=0; s<NUMSTAR; s++)
		{
		video= getGraphMem() + pos[s][f].x + pos[s][f].y * getScreenWidth();
		*video=back[s][f];
		}
	}
}

void
StarField::paste(void)
{
	pixel *video;
	for(int f=0; f<NUMFIELD; f++)
	{
		for(int s=0; s<NUMSTAR; s++)
		{
		video= getGraphMem() + pos[s][f].x + pos[s][f].y * getScreenWidth();
		*video=color[f];
		}
	}
}

void
StarField::update(void)
{
	replace();
	move();
	getBack();
	paste();
}

void
StarField::move(void)
{
	static int time;
	for(int f=0; f<NUMFIELD; f++)
	{
		if(time%(f+1)==0)
		{
			for(int s=0; s<NUMSTAR; s++)
			{
				pos[s][f].y+=speed[s][f];
				if(pos[s][f].y > getScreenHeight())
				{
					pos[s][f].x=rnd(getScreenWidth());
					pos[s][f].y=0;
					speed[s][f]=rnd(MAXSPEED)+1;
				}
			}
		}
	}
	time++;
}
