/*
Copyright (c) 1998 Michael Haar, Ulrich Haar, Michael Thayer,
  Tobias Mueller, Tobias Lenz
All rights reserved.
Terroid Programming by Michael Haar, Michael Thayer, Ulrich Haar
Terroid Graphics by Ulrich Haar, Michael Haar
Terroid Music by Michael Thayer
Terroid Level design by Michael Haar, Ulrich Haar, Tobias Lenz
Terroid Beta testing by Tobias Mueller, Tobias Lenz

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice and credits, this unmodified list of conditions and the
   following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice and credits, this unmodified list of conditions and the
   following disclaimer in the documentation and/or other materials
   provided with the distribution.
3. Any credits displayed during programme execution must include the
   above or an equivalent credit list.
4. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.
5. The authors Michael Thayer and Michael Haar are to be informed,
   preferable by electronic mail, when this software is distributed
   commercially.  A single notification is required for any given
   distribution, and explicit copies of that distribution (e.g. for all
   resellers of a given Linux distribution).
6. If any modifications are made to the software, then a description of them
   must be included when the software is redistributed, or alternatively,
   the distributed binary or source code must be described as a product
   based on source code by Michael Haar, Michael Thayer and Ulrich Haar.

THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/********************************/
/* Bonusgame for TERROID        */
/* (C) Sep 1996 by Michael Haar */
/********************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dn.h>

#include "DEFS.H"
#include "VARS.H"
#include "FUNCS.H"

#define MAX_SAMMELBONI 50
#define MAX_HYPERWARPS 1000
#define ANZ_SAMMELPICS 6

#define STEUERFAC 1

#define BONUSGROESSE 20
#define BONUSSTREU 4
#define RINGSTREU 10

/* globale Variablen */
struct
{
	int x, y, z;
	int nr;
} sammelbonus[MAX_SAMMELBONI];

struct
{
	int x, y, z;
	int color;
} hyperwarp[MAX_HYPERWARPS];
OLDBLK sammelpix[ANZ_SAMMELPICS];
int cam_x, cam_y;
BOOLEAN show_lampe;
void *hinterbild;
OLDBLK shippix;
OLDBLK autolampepix;
int position, letzter_smily, ringe;
//BOOLEAN setpal_neu;

/* Funktionsprototypen */
void bonusgame(int level);

/* Funktionen */
void init_bonusgame(int level)
{
//	void *old_screen = screen_addr;
	OLDBLK leuchtepix[2];
	int i;

	srand(level);

	cls(0);
	copy_frame_buffer();
	ClearPalette(alt_rgb);
	SetPalette(alt_rgb);

/*	leuchtepix[0].mem = NULL;
	leuchtepix[1].mem = NULL;
*/	load_pic("BILDSCH2.PIX", screen_addr, alt_rgb);
	oldget(9, 58, 23, 70, &leuchtepix[1]);
	load_pic("BILDSCHI.PIX", screen_addr, alt_rgb);
	oldget(9, 58, 23, 70, &leuchtepix[0]);
	copy_frame_buffer();
	PaletteFadeIn(alt_rgb);

	ticker_text(&gamefont, 50, 40, "BONUSGAME!", FALSE);

	// Bonusbilder laden
	load_pic("BONUS2.PIX", screen_addr, alt_rgb);
	oldget(2, 2, 134, 110, &sammelpix[0]);	// Durchfliegetor
	oldget(2, 115, 76, 177, &sammelpix[3]); // Böser!
	oldget(81, 116, 167, 198,  &sammelpix[2]);	// Diamant
	oldget(178, 119, 263, 193, &sammelpix[1]); // Ring
	load_pic("BONUS1.PIX", screen_addr, alt_rgb);
	oldget(4, 78, 76, 138, &sammelpix[4]);	// Kugel
	oldget(3, 54, 38, 71, &sammelpix[5]);	// Pfeil

	ticker_text(&gamefont, 50, 50, "FLY TROUGH ALL SILVER", FALSE);

	// Hintergrund
	hinterbild = malloc(screen_width * screen_height);
	sprintf(txt, "BONUSH%d.PIX", level / 3 + 1);
	load_pic(txt, hinterbild, alt_rgb);

	ticker_text(&gamefont, 50, 60, "RINGS, AVOID MINES AND", FALSE);

	// Schiff und Anzeigen
	load_pic("BONUSSHI.PIX", screen_addr, alt_rgb);
	oldget(147, 72, 169, 90, &autolampepix);
	box(140, 70, 171, 92, 0, TRUE, FALSE);
	oldget(0, 0, 319, 199, &shippix);

	ticker_text(&gamefont, 50, 70, "COLLECT SOME BONUSES!", FALSE);

	// für Pause
	load_pic("LEISTE.PIX", screen_addr, alt_rgb);
	get(0, 47, 151, 102, &pausedpix);

	ticker_text(&gamefont, 50, 90, "LOADING ENERGY", FALSE);

//	memset(whitepal, 63, sizeof(RGB) * 256);

	ticker_text(&gamefont, 50, 100, "SYSTEM STARTUP", FALSE);

	load_pic("PAL.PIX", screen_addr, gamepal);

	ticker_text(&gamefont, 50, 110, "STARTING ENGINE", FALSE);
	ticker_text(&gamefont, 50, 120, "INIT NAVINFO", FALSE);

	ticker_text(&gamefont, 50, 140, "WAITING FOR LAUNCH!", FALSE);

	while(keyTest(KEY_ENTER) || keyTest(KEY_SPACE) || keyTest(KEY_ESC) || keyTest(KEY_RCTRL) || keyTest(KEY_LCTRL))
		;

//	screen_addr = (void *)0xA0000;
	i = 0;
	while(!keyTest(KEY_ENTER) && !keyTest(KEY_SPACE) && !keyTest(KEY_ESC) && !keyTest(KEY_RCTRL) && !keyTest(KEY_LCTRL))
	{
		i++;
		wait_retrace();
		oldput(9, 58, &leuchtepix[(i % 32) / 16]);
		copy_frame_buffer() ;
	}
	if (sounddevice != 4) start_sample(bloinksnd, md_numchn - 1);
	while(keyTest(KEY_ENTER) || keyTest(KEY_SPACE) || keyTest(KEY_ESC) || keyTest(KEY_RCTRL) || keyTest(KEY_LCTRL))
		;

//	screen_addr = old_screen;

	free(leuchtepix[0].mem);
	free(leuchtepix[1].mem);

	PaletteFadeOut(alt_rgb);
	cls(0);
	copy_frame_buffer();

	for(i = 0; i < MAX_SAMMELBONI; i++)
		sammelbonus[i].nr = 0;

	for(i = 0; i < MAX_HYPERWARPS; i++)
	{
		hyperwarp[i].x = (rand() % screen_width) - screen_width / 2;
		hyperwarp[i].y = (rand() % screen_height) - screen_height / 2;
		hyperwarp[i].z = rand() % 255 + 1;
		hyperwarp[i].color = (rand() % (256 / 32)) * 32;	// 'Bank' auswaehlen
	}

	cam_x = cam_y = 0;
	letzter_smily = 0;
	ringe = 0;
//	setpal_neu = FALSE;
}

void hyperwarps()
{
	int i, px, py;
	char *addr;

	for(i = 0; i < MAX_HYPERWARPS; i++)
	{
		px = (hyperwarp[i].x + cam_x / STEUERFAC) * 256 / hyperwarp[i].z + screen_width / 2;
		py = (hyperwarp[i].y + cam_y / STEUERFAC) * 256 / hyperwarp[i].z + screen_height / 2;
		if((px >= clip_x1) && (py >= clip_y1) && (px < clip_x2) && (py < clip_y2))
		{
			addr = (unsigned char *)((long)screen_addr + px + py * screen_width);
//			if(*addr == 0)
				*addr = /*hyperwarp[i].color + */ (31 - (hyperwarp[i].z * 31 / 256));
		}

		hyperwarp[i].z -= 2;
		if(hyperwarp[i].z <= 0)
		{
			hyperwarp[i].x = (rand() % screen_width) - screen_width / 2;
			hyperwarp[i].y = (rand() % screen_height) - screen_height / 2;
			hyperwarp[i].z = 256;
			hyperwarp[i].color = (rand() % (256 / 32)) * 32;	// 'Bank' auswaehlen
		}
	}
}

BOOLEAN bonus_nah(int x, int y)
{
	int i;

	for(i = 0; i < MAX_SAMMELBONI; i++)
		if(sammelbonus[i].nr > 0)
			if(sammelbonus[i].z > 220)
				if(abs(x - sammelbonus[i].x) < 10)
					if(abs(y - sammelbonus[i].y) < 10)
						return(TRUE);

	return(FALSE);
}

BOOLEAN sammelboni()
{
	int i, o, px, py, pw, ph, z;

	letzter_smily++;

	// Neue erzeugen
	if(rand() % 2 == 0)
	{
		px = (sintab[rand() % 360] * (rand() % screen_width / BONUSSTREU)) >> SINFAC; //(rand() % screen_width / 8) - screen_width / 16;
		py = (sintab[rand() % 360] * (rand() % screen_height / BONUSSTREU)) >> SINFAC;//(rand() % screen_height / 8) - screen_height / 16;
		if(!bonus_nah(px, py))
		{
			i = 0;
			while((i < MAX_SAMMELBONI) && (sammelbonus[i].nr > 0))
				i++;
			if(i < MAX_SAMMELBONI)
			{
				if((rand() % 7 == 0) && (letzter_smily > max(15, 100 - position / 250)) && (px > -screen_width / RINGSTREU) && (px < screen_width / RINGSTREU) && (py > -screen_height / RINGSTREU) && (py < screen_height / RINGSTREU))
				{
					sammelbonus[i].nr = 1;
					letzter_smily = 0;
	
					// Pfeil erzeugen
					o = 0;
					while((o < MAX_SAMMELBONI) && (sammelbonus[o].nr > 0))
						o++;
					if(o < MAX_SAMMELBONI)
					{
						sammelbonus[o].nr = ANZ_SAMMELPICS;
						sammelbonus[o].x = px;
						sammelbonus[o].y = py + 4;
						sammelbonus[o].z = 224;
					}
				}
				else if(rand() % (position / 1000 + 2) == 0)
				{
					sammelbonus[i].nr = (rand() % (ANZ_SAMMELPICS - 2)) + 2;	// keine Pfeile!
				}
				else
					sammelbonus[i].nr = 4; // Mine
				sammelbonus[i].x = px;
				sammelbonus[i].y = py;
				sammelbonus[i].z = 256;
			}
		}
	}

	for(z = 256; z > 0; z--)	// Sieht lahm aus - ist aber wegen z == z nicht!
		for(i = 0; i < MAX_SAMMELBONI; i++)
			if((sammelbonus[i].nr > 0) && (sammelbonus[i].z == z))
			{
				// Anzeigen
				px = (sammelbonus[i].x + cam_x / STEUERFAC) * 256 / sammelbonus[i].z + screen_width / 2;
				py = (sammelbonus[i].y + cam_y / STEUERFAC) * 256 / sammelbonus[i].z + screen_height / 2;
				pw = max(1, sammelpix[sammelbonus[i].nr - 1].w * BONUSGROESSE / sammelbonus[i].z);
				ph = max(1, sammelpix[sammelbonus[i].nr - 1].h * BONUSGROESSE / sammelbonus[i].z);
				if((px - pw / 2 >= 0) && (py - ph / 2 >= 0))
					oldzoom(px - pw / 2, py - ph / 2, pw, ph, &sammelpix[sammelbonus[i].nr - 1]);
			}

	for(i = 0; i < MAX_SAMMELBONI; i++)
		if(sammelbonus[i].nr > 0)
		{
			// Kollision abfragen
			px = (sammelbonus[i].x + cam_x / STEUERFAC) * 256 / sammelbonus[i].z + screen_width / 2;
			py = (sammelbonus[i].y + cam_y / STEUERFAC) * 256 / sammelbonus[i].z + screen_height / 2;
			pw = max(2, sammelpix[sammelbonus[i].nr - 1].w * BONUSGROESSE / sammelbonus[i].z);
			ph = max(2, sammelpix[sammelbonus[i].nr - 1].h * BONUSGROESSE / sammelbonus[i].z);
			if(sammelbonus[i].z < 5)
			{
				if((px > -BONUSGROESSE * 2) && (py > -BONUSGROESSE * 2) && (px < screen_width + BONUSGROESSE * 2) && (py < screen_height + BONUSGROESSE * 2))
				{
					switch(sammelbonus[i].nr)
					{
						case 1:
							spieler.punkte += 250;
							ringe++;
//							SetPalette(redpal);
//							setpal_neu = TRUE;
							if (sounddevice != 4) start_sample(ringsnd, md_numchn - 1);
							break;
						case 2:
							spieler.punkte += 1000;
//							SetPalette(whitepal);
//							setpal_neu = TRUE;
							if (sounddevice != 4) start_sample(extrasnd[8], md_numchn - 1);
							break;
						case 3:
							spieler.punkte += 2500;
//							SetPalette(whitepal);
//							setpal_neu = TRUE;
							if (sounddevice != 4) start_sample(extrasnd[8], md_numchn - 1);
							break;
						case 4:
							// Ende, wenn Boesen gesammelt!
							spieler.punkte += position;
							if (sounddevice != 4) start_sample(warningsnd, md_numchn - 1);
							return(TRUE);
						case 5:
							spieler.punkte += 500;
//							SetPalette(whitepal);
//							setpal_neu = TRUE;
							if (sounddevice != 4) start_sample(extrasnd[8], md_numchn - 1);
							break;
						case 6:
							// Nix bei Pfeil
							break;
					}
					sammelbonus[i].nr = 0;
				}
			}

			if(sammelbonus[i].nr > 0)
			{
				// und Bewegung
				sammelbonus[i].z -= 2;
				if(sammelbonus[i].z <= 0)
				{
					// Ende, wenn Smilie nicht gesammelt!
					if(sammelbonus[i].nr == 1)
					{
						if (sounddevice != 4)
							start_sample(warningsnd, md_numchn - 1);
						return(TRUE);
					}
					sammelbonus[i].nr = 0;
				}
			}
		}

	return(FALSE);
}

BOOLEAN game_tasten()
{
	if(keyTest(KEY_ESC))
	{
		// eventuell noch spieler.leben auf 0
		return(TRUE);
	}
	else if(keyTest(KEY_P))
	{
		// Pause
		while(keyTest(KEY_P))
			;
		paused_effect();
		objput(screen_width / 2 - pausedpix.w / 2, screen_height / 2 - pausedpix.h / 2, &pausedpix);
		copy_frame_buffer();
		while(!keyTest(KEY_P))
			;
		while(keyTest(KEY_P))
			;
	}

	if(keyTest(KEY_UP) || joy1_up())
	{
		if(cam_y < screen_height / 4)
			cam_y++;
		else
			show_lampe = TRUE;
	}
	if(keyTest(KEY_DOWN) || joy1_down())
	{
		if(cam_y > -screen_height / 4)
			cam_y--;
		else
			show_lampe = TRUE;
	}
	if(keyTest(KEY_LEFT) || joy1_left())
	{
		if(cam_x < screen_width / 4)
			cam_x++;
		else
			show_lampe = TRUE;
	}
	if(keyTest(KEY_RIGHT) || joy1_right())
	{
		if(cam_x > -screen_width / 4)
			cam_x--;
		else
			show_lampe = TRUE;
	}

	return(FALSE);
}

void displays()
{
	if(position < 10)
		sprintf(txt, "00000%d", position);
	else if(position < 100)
		sprintf(txt, "0000%d", position);
	else if(position < 1000)
		sprintf(txt, "000%d", position);
	else if(position < 10000)
		sprintf(txt, "00%d", position);
	else if(position < 100000)
		sprintf(txt, "0%d", position);
	else
		sprintf(txt, "%d", position);
	put_text(&digitalfnt, 150, 173, txt);

	if(spieler.punkte < 10)
		sprintf(txt, "00000%d", spieler.punkte);
	else if(spieler.punkte < 100)
		sprintf(txt, "0000%d", spieler.punkte);
	else if(spieler.punkte < 1000)
		sprintf(txt, "000%d", spieler.punkte);
	else if(spieler.punkte < 10000)
		sprintf(txt, "00%d", spieler.punkte);
	else if(spieler.punkte < 100000)
		sprintf(txt, "0%d", spieler.punkte);
	else
		sprintf(txt, "%d", spieler.punkte);

	put_text(&digitalfnt, 120, 157, txt);

	if(ringe < 10)
		sprintf(txt, "0%d", ringe);
	else if(ringe < 100)
		sprintf(txt, "%d", ringe);

	put_text(&digitalfnt, 210, 157, txt);
}

void bonusgame(int level)
{
	long t;
	BOOLEAN ende;

	init_bonusgame(level);

	SetPalette(gamepal);

	t = timer();
	ende = FALSE;
	position = 0;
	while(!ende)
	{
		if(timer() - t > 1)
		{
			t = timer();

			position++;
			show_lampe = FALSE;

			ende = game_tasten();

			putvollbild(hinterbild);
			hyperwarps();
			ende |= sammelboni();

			oldobjput(0, 0, &shippix);
			if(show_lampe || ende)
				oldput(72, 142, &autolampepix);

			displays();

			wait_retrace();
/*			if(setpal_neu)
			{
				setpal_neu = FALSE;
				SetPalette(gamepal);
			} */
			copy_frame_buffer();
		}
	}

	free(shippix.mem);
	free(autolampepix.mem);

	free(hinterbild);

	free(sammelpix[0].mem);
	free(sammelpix[1].mem);
	free(sammelpix[2].mem);
	free(sammelpix[3].mem);
	free(sammelpix[4].mem);
	free(sammelpix[5].mem);

	PaletteFadeOut(alt_rgb);
	cls(0);
	copy_frame_buffer();

	srand((int)timer());
}
