/*
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.
*/

/****************************************/
/* ballerspiel-Initialisierungsroutinen */
/* (C) April 1996 by Michael Haar       */
/****************************************/

/* Änderungen: */

#include <time.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dn.h>
#include "DEFS.H"
#include "FUNCS.H"
#include "VARS.H"

/* globale Variablen */
char txt[1024], str[33];
RGB gamepal[256];
int game_scrollpos;
int anz_ketten;
int game_level;
GAMEDIFFICULTY game_difficulty;
KETTENSTART startkette[ANZ_LEVELKETTEN];
int level_over;
SAMPLE *explo1snd, *scratchsnd;
SAMPLE *warningsnd, *bloinksnd, *lasersnd;
SAMPLE *donnersnd, *beepsnd, *ringsnd;
SAMPLE *extrasnd[10];
FONT digitalfnt;
FONT gamefont, greenfont, redfont, endetickerfont;
char level_name[][30] =
{
	"ORBIT ENTRANCE", "ORBITAL DEFENSE", "LUNAR LIFE", "PLANETARY DEFENSE", "WATERWORLD", "PLANET TOURS", "JUNGLE STRIKE", "DESTRUCTION", "FREEDOM!!!"
};
ATTACK_WAVE attack;
void * pic_buffer ;

/* Funktionsprototypen */
BOOLEAN init_game(void);
void exit_game(void);
void start_game(unsigned char level);
void naechstes_level();

/* Funktionen */
BOOLEAN init_game(void)
{
	init_joy1();

	if(sounddevice != 4)
	{
		if(!init_mod("TERROID.XM", sounddevice, 4))
		{
			puts("Error during soundsystem-initialisation - running without sound!");
			no_music = TRUE;
			sounddevice = 4;	// nosound
		}
		else
		{
			init_sample("EXPLODE.WAV", &explo1snd, 0, 0);
			init_sample("SCRATCH.WAV", &scratchsnd, 0, 0);
			init_sample("WARNING.WAV", &warningsnd, 0, 0);
			init_sample("BUTTON.WAV", &bloinksnd, 0, 0);
			init_sample("LASER.WAV", &lasersnd, 0, 0);
			init_sample("DONNER.WAV", &donnersnd, 0, 0);
			init_sample("BEEP.WAV", &beepsnd, 0, 0);
			init_sample("RING.WAV", &ringsnd, 0, 0);
			init_sample("GOTBONUS.WAV", &extrasnd[8], 0, 0);
		}
	}

	if(!init_gfx(GFXMODE))
	{
		if(sounddevice != 4)
			exit_sound();
		if (error_text) printf("%s\n\n", error_text) ;
		else puts("GFX-InitError!\n");
		return(FALSE);
	}

	load_font("FONT.PIX", 20, ' ', 10, 10, &gamefont);
	load_font("FONT.PIX", 60, ' ', 10, 10, &greenfont);
	load_font("FONT.PIX", 80, ' ', 10, 10, &redfont);
	load_font("FONT.PIX", 100, ' ', 10, 10, &endetickerfont);
	load_font("SCHRIFT.PIX", 0, ' ', 8, 8, &schrift);
	load_font("LEISTE.PIX", 29, ' ', 6, 9, &digitalfnt);

	ende = FALSE;
	game_difficulty = NORMAL;

	keyInstall();

	srand(timer());

	return(TRUE);
}

void exit_game(void)
{
/*	for(i = 0; i < ANZ_EXPLOS; i++)
		free_blk(& explopix[i]);

	for(i = 0; i < ANZ_OBJPICS; i++)
		if(objpix[i].mem != NULL)
			free_blk(& objpix[i]);

	for(i = 0; i < ANZ_SPIELERPICS; i++)
		free_blk(& spielerpix[i]);

//	for(i = 0; i < ANZ_HINTERGRUENDE; i++)
//		free(hintergrundpix[i]); */

	keyRemove();

	if(sounddevice != 4)
	{
		stop_sound();
		exit_sound();
	}

	exit_gfx();
}

void start_game(unsigned char level)
{
	int i, c;
	char txt[80];
//	void *old_screen = screen_addr;
	GFXBLK leuchtepix[3];

	pic_buffer = malloc(64000) ;
	// erstmal so
	if(!no_music)
	{
		stop_sound();
		free_mod();
		md_numchn = 4;
		if(game_difficulty == TRAINING)
			sprintf(txt, "LEVEL%d.XM", (rand() % 2) * 2 + 1);
		else
			sprintf(txt, "LEVEL%d.XM", (level % ANZ_MODS) + 1);
		if((mymod = ML_LoadFN(txt)))
		{
			md_numchn += mymod->numchn;
			start_mod(TRUE, 0, 5);
		}
		else
			puts("\7");
	}

	level_over = 100;
	endmonster.energie_max = 0;
	endmonster.art_da = 0;
	endmonster.start_x = 0;

	attack.nr = 1;
	attack.wait = ATTACK_WAIT_LEN;
	attack.dauer = 0;

/*	cls(0);
	Copy2Screen(); */

	load_pic("BILDSCHI.PIX", screen_addr, alt_rgb);
	get(0, 0, screen_width, screen_height, & leuchtepix[2]) ;
	put(0, 0, & leuchtepix[2]) ;
	SetPalette(alt_rgb);
	Copy2Screen();

	ticker_text(&gamefont, 50, 40, "RECEIVING NAVDATA FOR", FALSE);

	if(game_difficulty == TRAINING)
		ticker_text(&gamefont, 50, 50, "TRAINING COURSE", FALSE);
	else
		ticker_text(&gamefont, 50, 50, level_name[level], FALSE);

	memcpy(pic_buffer, screen_addr, 64000) ;
//	leuchtepix[0].mem = NULL;
//	leuchtepix[1].mem = NULL;
	get(9, 58, 23, 70, &leuchtepix[0]);
	load_pic("BILDSCH2.PIX", screen_addr, alt_rgb);
	get(9, 58, 23, 70, &leuchtepix[1]);

	for(i = 0; i < ANZ_LEVELKETTEN; i++)
		startkette[i].start_x = 0;

	if(!init_bg(level)
		|| !init_platforms(level))
		puts("\7");

	memcpy(screen_addr, pic_buffer, 64000) ;
	ticker_text(&gamefont, 50, 70, "LOADING ENERGY", FALSE);
	memcpy(pic_buffer, screen_addr, 64000) ;

	if(!init_spieler(level))
		puts("\7");

	memcpy(screen_addr, pic_buffer, 64000) ;
	ticker_text(&gamefont, 50, 80, "SYSTEM STARTUP", FALSE);
	memcpy(pic_buffer, screen_addr, 64000) ;

	if(!init_objekte(level))
		puts("\7");

	memcpy(screen_addr, pic_buffer, 64000) ;
	ticker_text(&gamefont, 50, 90, "STARTING ENGINE", FALSE);
	memcpy(pic_buffer, screen_addr, 64000) ;

	if(!extras_init(level))
		puts("\7");

	memcpy(screen_addr, pic_buffer, 64000) ;
	ticker_text(&gamefont, 50, 100, "LOADING WEAPONS", FALSE);
	memcpy(pic_buffer, screen_addr, 64000) ;

	if(!init_explos(level))
		puts("\7");

	memcpy(screen_addr, pic_buffer, 64000) ;
	ticker_text(&gamefont, 50, 110, "INIT TERRAININFOS", FALSE);
	memcpy(pic_buffer, screen_addr, 64000) ;

	if(!load_level(level))
	{
		// Spiel geschafft!!! oder im Editor neues Level
		puts("\7");
	}

	load_pic("PAL.PIX", screen_addr, gamepal);
	game_scrollpos = 0;
	game_scrollgeschw = 1;
	// Palette für Treffer generieren
	for(i = 0; i < 4; i++)
	{
		memmove(redpal[i], gamepal, 256 * sizeof(RGB));
		for(c = 0; c < 256; c++)
			if(redpal[i][c].r < 63)
			{
				redpal[i][c].r += (i + 1) * 5;
				if(redpal[i][c].r > 63)
					redpal[i][c].r = 63;
			}
	}

	init_sterne();

	memcpy(screen_addr, pic_buffer, 64000) ;
	ticker_text(&gamefont, 50, 120, "RECEIVING TARGETS", FALSE);
	memcpy(pic_buffer, screen_addr, 64000) ;

	if(game_mode == PLAY)
	{
		wait_retrace();

		memcpy(screen_addr, pic_buffer, 64000) ;
		ticker_text(&gamefont, 50, 140, "WAITING FOR LAUNCH!", FALSE);

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

//		screen_addr = old_screen;
		free(pic_buffer) ;
	}

	free_blk(& leuchtepix[0]);
	free_blk(& leuchtepix[1]);
	free_blk(& leuchtepix[2]) ;

	cls(0);
	Copy2Screen();
	SetPalette(gamepal);
}

void naechstes_level()
{
	memcpy(alt_rgb, gamepal, sizeof(RGB) * 256);
	PaletteFadeOut(alt_rgb);
	cls(0);
	Copy2Screen();

	game_level++;
	start_game(game_level);
}
