/****************************************************************************************

	Invader's Revenge (MisfitMAME version)

	October, 2008 by Robbbert

	No diagram available, so I threw this together


	Invader's Revenge was made by the English company, Zenitone-Microsec Ltd.
	Distributed in Germany by Dutchford.
	Also distributed in America by Americade Amusement, Inc., of New Jersey.

	It's basically a hardware hack of the normal Taito Space Invaders machine.

	Changes (start with a Space Invaders with a colour CRT):

	1. The sound board is replaced with another that makes different sounds.

	2. A sardine-can-shaped potted black epoxy block containing a 4mhz crystal,
	   two large 40-pin ICs, at least 2 roms, and a number of TTL-shaped chips.
	   My assumption is that one of the big chips is a (slave sound) CPU.

	3. New main roms

	4. A small card contains a colour PROM. There's no RAM for this, so the colours
	   must be quite simplistic.

	The main CPU communicates to the slave by sending sound codes via port 3,
	while port 5 controls various aspects of the screen display.

	The method of enabling cocktail mode is the same as for Space Invaders, that is,
	changing the positions of SW5,6,7; cutting a track; and adding some jumpers.
	Obviously this is a once-off change for the table model.

	Known bugs in the original roms:

	1. If you turn on the machine, start a 1-player game and just let it run to the
	   end, it will congratulate player 2 for getting a high score. Of course, zero
	   points is not a high score, and there wasn't a player 2.

	2. If you die just after killing the last enemy in the 8th level, the docking
	   stage uses the wrong colour map. I've added a fix for this.

	Todo:

	1. Find the colour prom and hook it up, and get rid of the MAME overlay.
	2. Identify the slave CPU and make it work.
	3. Get schematic diagrams, and design a discrete sound board.

	Changes for MisfitMAME:

	1. Created this one-off driver
	2. Moved subroutines that are only called once, into the calling routine
	3. Added watchdog
	4. Added above documentation (MAME doesn't have any)
	5. Identified all inputs and outputs.
	6. Identified all sound codes. (We only need good samples now)

*******************************************************************************************/

#include "driver.h"
#include "machine/mb14241.h"
#include "sound/samples.h"
#include "invrvnge.lh"

#define NUM_PENS	(8)
#define INVRVNGE_MASTER_CLOCK				(19968000)
#define INVRVNGE_CPU_CLOCK					(INVRVNGE_MASTER_CLOCK / 10)
#define INVRVNGE_PIXEL_CLOCK				(INVRVNGE_MASTER_CLOCK / 4)
#define INVRVNGE_HTOTAL						(0x140)
#define INVRVNGE_HBEND						(0x000)
#define INVRVNGE_HBSTART					(0x100)
#define INVRVNGE_VTOTAL						(0x106)
#define INVRVNGE_VBEND						(0x000)
#define INVRVNGE_VBSTART					(0x0e0)
#define INVRVNGE_VCOUNTER_START_NO_VBLANK	(0x020)
#define INVRVNGE_VCOUNTER_START_VBLANK		(0x0da)
#define INVRVNGE_INT_TRIGGER_COUNT_1		(0x080)
#define INVRVNGE_INT_TRIGGER_VBLANK_1		(0)
#define INVRVNGE_INT_TRIGGER_COUNT_2		INVRVNGE_VCOUNTER_START_VBLANK
#define INVRVNGE_INT_TRIGGER_VBLANK_2		(1)

/* +4 is added to HBSTART because the hardware displays that many pixels after
   setting HBLANK */
#define INVRVNGE_HPIXCOUNT		(INVRVNGE_HBSTART + 4)

static UINT8 invrvnge_flip_screen;
static UINT8 invrvnge_screen_red;
static UINT8 *invrvnge_ram;
static size_t invrvnge_ram_size;


/*************************************
 *
 *  Interrupt generation
 *
 *************************************/

static emu_timer *interrupt_timer;


static UINT8 vpos_to_vysnc_chain_counter(int vpos)
{
	/* convert from a vertical position to the actual values on the vertical sync counters */
	UINT8 counter;
	int vblank = (vpos >= INVRVNGE_VBSTART);

	if (vblank)
		counter = vpos - INVRVNGE_VBSTART + INVRVNGE_VCOUNTER_START_VBLANK;
	else
		counter = vpos + INVRVNGE_VCOUNTER_START_NO_VBLANK;

	return counter;
}


static int vysnc_chain_counter_to_vpos(UINT8 counter, int vblank)
{
	/* convert from the vertical sync counters to an actual vertical position */
	int vpos;

	if (vblank)
		vpos = counter - INVRVNGE_VCOUNTER_START_VBLANK + INVRVNGE_VBSTART;
	else
		vpos = counter - INVRVNGE_VCOUNTER_START_NO_VBLANK;

	return vpos;
}


static TIMER_CALLBACK( invrvnge_interrupt_callback )
{
	UINT8 next_counter;
	int next_vpos;
	int next_vblank;

	/* compute vector and set the interrupt line */
	int vpos = video_screen_get_vpos(machine->primary_screen);
	UINT8 counter = vpos_to_vysnc_chain_counter(vpos);
	UINT8 vector = 0xc7 | ((counter & 0x40) >> 2) | ((~counter & 0x40) >> 3);
	cpunum_set_input_line_and_vector(machine, 0, 0, HOLD_LINE, vector);

	/* set up for next interrupt */
	if (counter == INVRVNGE_INT_TRIGGER_COUNT_1)
	{
		next_counter = INVRVNGE_INT_TRIGGER_COUNT_2;
		next_vblank = INVRVNGE_INT_TRIGGER_VBLANK_2;
	}
	else
	{
		next_counter = INVRVNGE_INT_TRIGGER_COUNT_1;
		next_vblank = INVRVNGE_INT_TRIGGER_VBLANK_1;
	}

	next_vpos = vysnc_chain_counter_to_vpos(next_counter, next_vblank);
	timer_adjust_oneshot(interrupt_timer, video_screen_get_time_until_pos(machine->primary_screen, next_vpos, 0), 0);
}


static void invrvnge_create_interrupt_timer(void)
{
	interrupt_timer = timer_alloc(invrvnge_interrupt_callback, NULL);
}


static void invrvnge_start_interrupt_timer(running_machine *machine)
{
	int vpos = vysnc_chain_counter_to_vpos(INVRVNGE_INT_TRIGGER_COUNT_1, INVRVNGE_INT_TRIGGER_VBLANK_1);
	timer_adjust_oneshot(interrupt_timer, video_screen_get_time_until_pos(machine->primary_screen, vpos, 0), 0);
}

/*************************************
 *
 *  Video Routines
 *
 *************************************/

INLINE void set_pixel(bitmap_t *bitmap, UINT8 y, UINT8 x, pen_t *pens, UINT8 color)
{
	if (y >= INVRVNGE_VCOUNTER_START_NO_VBLANK)
	{
		if (invrvnge_flip_screen)
			*BITMAP_ADDR32(bitmap, INVRVNGE_VBSTART - 1 - (y - INVRVNGE_VCOUNTER_START_NO_VBLANK), INVRVNGE_HPIXCOUNT - 1 - x) = pens[color];
		else
			*BITMAP_ADDR32(bitmap, y - INVRVNGE_VCOUNTER_START_NO_VBLANK, x) = pens[color];
	}
}

static VIDEO_UPDATE( invrvnge )
{
	int i;
	pen_t pens[NUM_PENS];
	offs_t offs;

	for (i = 0; i < NUM_PENS; i++)
		pens[i] = MAKE_RGB(pal1bit(i >> 0), pal1bit(i >> 2), pal1bit(i >> 1));

	for (offs = 0; offs < invrvnge_ram_size; offs++)
	{
		UINT8 y = offs >> 5;
		UINT8 x = offs << 3;

		UINT8 data = invrvnge_ram[offs];
	/* Add the colour coding, when missing rom is found */
	//	UINT8 fore_color = ~invrvnge_colorram[offs & 0x1f1f] & 0x07;
		UINT8 fore_color = 7;

		for (i = 0; i < 8; i++)
		{
			set_pixel(bitmap, y, x, pens, (data & 1) ? fore_color : 0);
			x++;
			data = data >> 1;
		}
	}

	return 0;
}

/**********************************************************************************
 *
 *  Special Input Handler
 *	if in upright mode, we need to read players 1's controls for both players
 *
 **********************************************************************************/

static READ8_HANDLER( invrvnge_in2_r )
{
	if (input_port_read(machine, "CAB"))
		return input_port_read(machine, "IN2");
	else
		return (input_port_read(machine, "IN2") & 0x8F) | (input_port_read(machine, "IN1") & 0x70);
}

/*************************************
 *
 *  Sound
 *
 *************************************/

static const char *const invrvnge_sample_names[] =
{
	"*invrvnge",
	"02.wav",		/* insert coin */
	"06.wav",		/* you shoot */
	"14.wav",		/* hit alien */
	"16.wav",		/* hit asteroid */
	"18.wav",		/* low fuel */
	"1a.wav",		/* successful docking */
	"1e.wav",		/* die */
	"22.wav",		/* start game */
	"24.wav",		/* alien diving */
	"26.wav",		/* alien steals fuel */
	"28.wav",		/* background sound 1 */
	"2a.wav",		/* background sound 2 */
	"2c.wav",		/* background sound 3 */
	"2e.wav",		/* background sound 4 */
	"30.wav",		/* build up fuel */
	"32.wav",		/* ufo fires */
	"34.wav",		/* high score */
	"36.wav",		/* docking stage */
	"38.wav",		/* bonus ship */
	"3a.wav",		/* thrust */
	0
};


static const samples_interface invrvnge_samples_interface =
{
	9,	/* 9 channels */
	invrvnge_sample_names
};

/*************************************************************************************/
/* Notes:                                                                            */
/* Init sequence: 0x01 (20 times), 0x40 (20 times), 0x4c, 0x40, 0x44, 0x40 (9 times).*/
/* Player 1 start sequence: 0x0c, 0x20, 0x22.                                        */
/* Unknown codes: 0x0A, 0x0c                                                         */
/*************************************************************************************/

static WRITE8_HANDLER( invrvnge_port_03_w )
{
	switch (data)
	{
		case 0x02:						/* Coin */
			sound_global_enable(1);				/* enable sound so we can hear coin drop */
			sample_start(0, 0, 0);
			break;

		case 0x04:						/* Attract Mode */
			sound_global_enable(0);				/* disable sound */
			break;

		case 0x06:
			sample_start(1, 1, 0);				/* Shoot */
			break;

		case 0x14:
			sample_start(2, 2, 0);				/* Hit Alien (0x0a happens at the same time) */
			break;

		case 0x16:
			sample_start(2, 3, 0);				/* Hit Asteroid */
			break;

		case 0x18:						/* Fuel Low */
			sample_start(5, 4, 0);
			break;

		case 0x1a:						/* Successful docking */
			sample_start(0, 5, 0);
			break;

		case 0x1c:						/* Finished fuelling */
			sample_stop(0);
			break;

		case 0x1e:
			sample_start(0, 6, 0);				/* Death */
			break;

		case 0x20:
			sound_global_enable(1);				/* enable sound for game start */
		case 0x22:
			sample_start(0, 7, 0);				/* Start Game */
			break;

		case 0x24:						/* Alien dropping to steal fuel */
			sample_start(3, 8, 0);
			break;

		case 0x26:						/* Alien lifting with fuel */
			sample_start(4, 9, 0);
			break;

		case 0x28:						/* background sound level 1 */
		case 0x2a:						/* background sound level 2 */
		case 0x2c:						/* background sound level 3 */
		case 0x2e:						/* background sound level 4 */
			sample_start(0, data/2-10, 1);
			break;

		case 0x30:						/* Fuel bar filling up */
			sample_start(0, 14, 0);
			break;

		case 0x32:						/* UFO drops a bomb */
			sample_start(6, 15, 0);
			break;

		case 0x34:						/* You got the highest score */
			sample_start(0, 16, 0);
			break;

		case 0x36:						/* Docking stage */
			invrvnge_screen_red = 0;			/* fix bug (2) in documentation */
			sample_start(0, 17, 1);
			break;

		case 0x38:						/* Bonus ship */
			sample_start(8, 18, 0);
			break;

		case 0x3a:						/* Thrust */
			sample_start(7, 19, 0);
			break;

		case 0x4c:
			sample_stop(0);	// using this to stop sound if game tilted
		case 0x01:						/* These play at boot time */
		case 0x40:						/* no idea if they are actual sounds */
		case 0x44:

		case 0x0a:						/* with 0x14 */
		case 0x0c:						/* used a lot but for what? */
			break;

		default:
			if (data) printf("Undefined sound code: %X\n",data);
	}
}

static WRITE8_HANDLER( invrvnge_port_05_w )
{
	/*
	00 - normal play
	01 - briefly at boot time
	10 - different colour map when you die
	20 - flip screen */
 
	invrvnge_screen_red = data & 0x10;
	invrvnge_flip_screen = data & 0x20 & input_port_read(machine, "CAB");
}

/*************************************
 *
 *  Machine setup
 *
 *************************************/

static MACHINE_START( invrvnge )
{
	invrvnge_create_interrupt_timer();
	mb14241_init(0);
}

static MACHINE_RESET( invrvnge )
{
	invrvnge_start_interrupt_timer(machine);
}

/*************************************
 *
 *  Address Maps
 *
 *************************************/

static ADDRESS_MAP_START( main_map, ADDRESS_SPACE_PROGRAM, 8 )
	ADDRESS_MAP_GLOBAL_MASK(0x7fff)
	AM_RANGE(0x0000, 0x1fff) AM_ROM
	AM_RANGE(0x2000, 0x3fff) AM_MIRROR(0x4000) AM_RAM AM_BASE(&invrvnge_ram) AM_SIZE(&invrvnge_ram_size)
ADDRESS_MAP_END

static ADDRESS_MAP_START( invrvnge_io_map, ADDRESS_SPACE_IO, 8 )
	AM_RANGE(0x00, 0x00) AM_READ_PORT("IN0")
	AM_RANGE(0x01, 0x01) AM_READ_PORT("IN1")
	AM_RANGE(0x02, 0x02) AM_READ(invrvnge_in2_r) AM_WRITE(mb14241_0_shift_count_w)
	AM_RANGE(0x03, 0x03) AM_READWRITE(mb14241_0_shift_result_r, invrvnge_port_03_w)
	AM_RANGE(0x04, 0x04) AM_WRITE(mb14241_0_shift_data_w)
	AM_RANGE(0x05, 0x05) AM_WRITE(invrvnge_port_05_w)
	AM_RANGE(0x06, 0x06) AM_WRITE(watchdog_reset_w)
ADDRESS_MAP_END

/*************************************
 *
 *  Inputs
 *
 *************************************/

static INPUT_PORTS_START( invrvnge )
	PORT_START("IN0")
	PORT_BIT( 0x71, IP_ACTIVE_HIGH, IPT_UNKNOWN )	// unused
	PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_UNKNOWN )	// must be low or game won't boot [code: 0x1a9-1af]
	PORT_DIPNAME( 0x06, 0x00, DEF_STR( Difficulty ) )
	PORT_DIPSETTING(    0x00, "1 (Easiest)" )	// [code: 0x3b1-3b5]
	PORT_DIPSETTING(    0x02, "2" )
	PORT_DIPSETTING(    0x04, "3" )
	PORT_DIPSETTING(    0x06, "4 (Hardest)" )
	PORT_DIPNAME( 0x80, 0x00, "Fuel Usage" )	// [code: 0x1cb0-1cb6]
	PORT_DIPSETTING(    0x80, "Fast" )
	PORT_DIPSETTING(    0x00, "Slow" )

	PORT_START("IN1")
	PORT_BIT( 0x01, IP_ACTIVE_LOW,  IPT_COIN1 )
	PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_START2 )
	PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_START1 )
	PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_UNKNOWN )	// unused
	PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 )	// hold down, to start flying
	PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_2WAY
	PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_2WAY
	PORT_BIT( 0x80, IP_ACTIVE_LOW,  IPT_UNKNOWN )	// [code: 0x750-75B] causes this switch to be ineffective

	PORT_START("IN2")
	PORT_DIPNAME( 0x03, 0x00, DEF_STR( Lives ) )		PORT_DIPLOCATION("SW1:1,2")
	PORT_DIPSETTING(    0x00, "3" )
	PORT_DIPSETTING(    0x01, "4" )
	PORT_DIPSETTING(    0x02, "5" )
	PORT_DIPSETTING(    0x03, "6" )
	PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_TILT )		PORT_DIPLOCATION("SW1:3")
	PORT_DIPNAME( 0x08, 0x00, DEF_STR( Bonus_Life ) )	PORT_DIPLOCATION("SW1:4")	// [code: 0x3b9-3c9]
	PORT_DIPSETTING(    0x00, "1500" )
	PORT_DIPSETTING(    0x08, "2000" )
	PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_PLAYER(2)			PORT_DIPLOCATION("SW1:5")
	PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_2WAY PORT_PLAYER(2)	PORT_DIPLOCATION("SW1:6")
	PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_2WAY PORT_PLAYER(2)	PORT_DIPLOCATION("SW1:7")
	PORT_DIPNAME( 0x80, 0x00, DEF_STR( Coinage ) )					PORT_DIPLOCATION("SW1:8")
	PORT_DIPSETTING(    0x80, DEF_STR( 2C_1C ) )
	PORT_DIPSETTING(    0x00, DEF_STR( 1C_1C ) )

	/* Dummy port for cocktail mode - equivalent of the jumpers etc on the real machine */
	PORT_START("CAB")
	PORT_CONFNAME( 0x20, 0x00, DEF_STR( Cabinet ) )
	PORT_CONFSETTING(    0x00, DEF_STR( Upright ) )
	PORT_CONFSETTING(    0x20, DEF_STR( Cocktail ) )
INPUT_PORTS_END

/*************************************
 *
 *  Machine Drivers
 *
 *************************************/

static MACHINE_DRIVER_START( invrvnge )

	/* basic machine hardware */
	MDRV_CPU_ADD("main",8080,INVRVNGE_CPU_CLOCK)
	MDRV_CPU_PROGRAM_MAP(main_map,0)
	MDRV_CPU_IO_MAP(invrvnge_io_map,0)
	MDRV_WATCHDOG_VBLANK_INIT(255)
	MDRV_MACHINE_START(invrvnge)
	MDRV_MACHINE_RESET(invrvnge)

	/* video hardware */
	MDRV_VIDEO_UPDATE(invrvnge)

	MDRV_SCREEN_ADD("main", RASTER)
	MDRV_SCREEN_FORMAT(BITMAP_FORMAT_RGB32)
	MDRV_SCREEN_RAW_PARAMS(INVRVNGE_PIXEL_CLOCK, INVRVNGE_HTOTAL, INVRVNGE_HBEND, INVRVNGE_HPIXCOUNT, INVRVNGE_VTOTAL, INVRVNGE_VBEND, INVRVNGE_VBSTART)

	/* sound hardware */
	MDRV_SPEAKER_STANDARD_MONO("mono")

	MDRV_SOUND_ADD("samples", SAMPLES, 0)
	MDRV_SOUND_CONFIG(invrvnge_samples_interface)
	MDRV_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.0)
MACHINE_DRIVER_END

/*************************************
 *
 *  Roms
 *
 *************************************/

ROM_START( invrvnge )
	ROM_REGION( 0x10000, "main", 0 )
	ROM_LOAD( "invrvnge.h",   0x0000, 0x0800, CRC(aca41bbb) SHA1(ca71f792abd6d9a44d15b19d2ccf678e82ccba4f) )
	ROM_LOAD( "invrvnge.g",   0x0800, 0x0800, CRC(cfe89dad) SHA1(218b6a0b636c49c4cdc3667e8b1387ef0e257115) )
	ROM_LOAD( "invrvnge.f",   0x1000, 0x0800, CRC(e350de2c) SHA1(e845565e2f96f9dec3242ec5ab75910a515428c9) )
	ROM_LOAD( "invrvnge.e",   0x1800, 0x0800, CRC(1ec8dfc8) SHA1(fc8fbe1161958f57c9f4ccbcab8a769184b1c562) )
ROM_END

/* Set 2 from Zenitone. This one has the "For Amusement Only" sign at the top of the screen.
	Dumped by Andy Welburn. */
ROM_START( invrvng2 )
	ROM_REGION( 0x10000, "main", 0 )
	ROM_LOAD( "invrvng2.h",   0x0000, 0x0800, CRC(0e229b9f) SHA1(617197bf94e9700cbbb2f32487dc47b318d4f2af) )
	ROM_LOAD( "invrvng2.g",   0x0800, 0x0800, CRC(26b38aa4) SHA1(f281c7ec47ce6ab61bfda2e7aa6a5b8a01f2c11e) )
	ROM_LOAD( "invrvng2.f",   0x1000, 0x0800, CRC(b3b2749e) SHA1(4f854f981396e2d6a959dd48cff12234074fb69b) )
	ROM_LOAD( "invrvng2.e",   0x1800, 0x0800, CRC(d8e75102) SHA1(86d5618944265947e3ce60fdf048d8fff4a55744) )
ROM_END

/* Dutchford variant. This also has the sign at the top. Unlike the others, you die almost immediately
	in attract mode. */
ROM_START( invrvnga )
	ROM_REGION( 0x10000, "main", 0 )
	ROM_LOAD( "5m.bin",       0x0000, 0x0800, CRC(b145cb71) SHA1(127eb11de7ab9835f06510fb12838c0b728c0d42) )
	ROM_LOAD( "5n.bin",       0x0800, 0x0800, CRC(660e8af3) SHA1(bd52eadf4ee3d717fd5bd7206e1e87d729250c92) )
	ROM_LOAD( "5p.bin",       0x1000, 0x0800, CRC(6ec5a9ad) SHA1(d1e84d2d60c6128c092f2cd20a2b87216df3034b) )
	ROM_LOAD( "5r.bin",       0x1800, 0x0800, CRC(74516811) SHA1(0f595c7b0fae5f3f83fdd1ffed5a408ee77c9438) )
ROM_END

/*************************************
 *
 *  Game Drivers
 *
 *************************************/

/* board #  rom       parent    machine   inp */

GAMEL(1979, invrvng2, 0,        invrvnge, invrvnge, 0, ROT270, "Zenitone-Microsec Ltd.", "Invader's Revenge (set 2)",  GAME_IMPERFECT_COLORS, layout_invrvnge )
GAMEL(1979, invrvnge, 0,        invrvnge, invrvnge, 0, ROT270, "Zenitone-Microsec Ltd.", "Invader's Revenge",  GAME_IMPERFECT_COLORS, layout_invrvnge )
GAMEL(1979, invrvnga, invrvnge, invrvnge, invrvnge, 0, ROT270, "Zenitone-Microsec Ltd. (Dutchford license)", "Invader's Revenge (Dutchford)", GAME_IMPERFECT_COLORS, layout_invrvnge )
