/*  :ts=8 bk=0
 * 3dstars.c:  Spacing out taken a step further
 * by Leo L. Schwab   8607.1
 */

#include <exec/types.h>
#include <intuition/intuition.h>

#define NSTARS		32

extern void *OpenLibrary(), *OpenScreen(), *OpenWindow(), *GetMsg();
extern short rnd();

long *IntuitionBase, *GfxBase;

struct NewScreen scrdef = {
	0, 0, 320, 200,
	4,		/*  # planes  */
	-1, -1,
	NULL,
	CUSTOMSCREEN,
	NULL, NULL, NULL, NULL
};

struct NewWindow windef = {
	0, 0, 320, 200,
	-1, -1,
	CLOSEWINDOW,
	WINDOWCLOSE,
	NULL, NULL, NULL, NULL, NULL,
	0, 0, 0, 0,
	CUSTOMSCREEN
};

struct Window *win;
struct Screen *scr;
struct RastPort *rp;
short x[NSTARS], y[NSTARS], z[NSTARS];
short xlo[NSTARS], xro[NSTARS], yo[NSTARS];


main (ac, av)
char *av[];
int ac;
{
	long xls, xrs, ys;
	long *msg;
	short magic, inc;
	register short i, fz;

	if (ac > 1)
		magic = atoi (av[1]);
	else
		magic = 128;

	if (ac > 2)
		inc = atoi (av[2]);
	else
		inc = 3;

	openstuff ();
	rnd (-5286);
	SetRast (rp, 0L);
	for (i=0, xls=1; i<8; i++, xls += 2) {
		SetRGB4 (&(scr -> ViewPort), (long) i, xls, 0L, 0L);
		SetRGB4 (&(scr -> ViewPort), (long) i+8, 0L, 0L, xls);
	}

	for (i=0; i<NSTARS; i++)
		mkpoint (i);

	FOREVER {
		for (i=0; i<NSTARS; i++) {
			if ((z[i] -= inc) <= 0)
				mkpoint (i);
			fz = z[i];
			xls = (x[i] - (fz >> 4)) * magic / fz + 160;
			xrs = (x[i] + (fz >> 4)) * magic / fz + 160;
			ys = y[i] * magic / fz + 100;
			SetAPen (rp, 0L);
			WritePixel (rp, (long) xlo[i], (long) yo[i]);
			WritePixel (rp, (long) xro[i], (long) yo[i]);
			if (xls < 0 || xls > 319 || xrs < 0 || xrs > 319 ||
			    ys < 0 || ys > 199)
				mkpoint (i);
			else {
				SetAPen (rp, (long) (256-fz >> 5));
				WritePixel (rp, xls, ys);
				SetAPen (rp, (long) 8+(256-fz >> 5));
				WritePixel (rp, xrs, ys);
				xlo[i] = xls;  xro[i] = xrs;  yo[i] = ys;
			}
		}
		if (msg = GetMsg (win -> UserPort)) {
			ReplyMsg (msg);
			break;
		}
	}

	closestuff ();
}

mkpoint (i)
register short i;
{
	x[i] = rnd (256) - 128;
	y[i] = rnd (150) - 75;
	z[i] = 255;
}

openstuff ()
{
	if (!(IntuitionBase = OpenLibrary ("intuition.library", 0L))) {
		printf ("Intuition open failed.\n");
		die ();
	}

	if (!(GfxBase = OpenLibrary ("graphics.library", 0L))) {
		printf ("graphics open failed.\n");
		die ();
	}

	if (!(scr = OpenScreen (&scrdef))) {
		printf ("Can't open screen.\n");
		die ();
	}

	windef.Screen = scr;
	if (!(win = OpenWindow (&windef))) {
		printf ("Window painted shut.\n");
		die ();
	}
	rp = &(scr -> RastPort);
}

closestuff ()
{
	if (win)		CloseWindow  (win);
	if (scr)		CloseScreen  (scr);
	if (GfxBase)		CloseLibrary (GfxBase);
	if (IntuitionBase)	CloseLibrary (IntuitionBase);
}

die ()
{
	closestuff ();
	exit (-1);
}
