/*
 *  This source copes with all amiga-specific stuff as opening the screen, resizing
 *  it using user copper lists, etc.
 *
 *  Copper-based resizing is now implemented, although no aspect ratio is taken care of.
 *
 *  Michael Rausch  14-2-94  12:00:00
 */

#include <proto/exec.h>
#include <proto/intuition.h>
#include <proto/graphics.h>

#include <exec/memory.h>
#include <hardware/custom.h>
#include <graphics/copper.h>
#include <graphics/gfxbase.h>
#include <graphics/gfxmacros.h>
#include <graphics/videocontrol.h>
#include <graphics/displayinfo.h>

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

#include "video.h"
#include "proto.h"
extern int ditherType;

extern void HAM8_Init(struct RastPort *);	// kinda static
extern void HAM8_Init_lores(struct RastPort *);

void (*HAM8_draw)(void *, int, int);


#define custom ((*(volatile struct Custom *)(0xdff000)))


struct IntuitionBase *IntuitionBase;
struct GfxBase *GfxBase;
extern struct ExecBase *SysBase;
static struct Screen *screen;
static ULONG soerror = NULL;

int gfx40;
ULONG *kaiko = NULL;

int lores, sdbl;

int max_x, max_y;

static struct ColorSpec firstblack[2]={ {0,0,0,0}, {-1, 0,0,0} };	/* Color 0 is 0x000*/

/*static const ULONG colconv[4] = {0x0,0x55000000,0xaa000000,0xff000000};*/


static void Quit(char *why, int failcode)
{
	puts(why);
	exit(failcode);
}

static void output_term(void)
{
	if (screen)
	{
		FreeVPortCopLists(&(screen->ViewPort));
		RemakeDisplay();
		CloseScreen(screen);
	}
	if (IntuitionBase) CloseLibrary((struct Library *) IntuitionBase);
	if (GfxBase) CloseLibrary((struct Library *) GfxBase);
}


void InitColorDisplay(char *name)
{
	/*int i;
	ULONG base[1+64*3+1];*/

	atexit(output_term);

	if ((GfxBase=(struct GfxBase *) OpenLibrary("graphics.library",39))==NULL)
		Quit("graphics.library is too old, <V39",25);
	if ((IntuitionBase=(struct IntuitionBase *) OpenLibrary("intuition.library",39))==NULL)
		Quit("intuition.library is too old, <V39",25);

	gfx40 = GfxBase->LibNode.lib_Version >= 40;
	if(gfx40) kaiko = GfxBase->ChunkyToPlanarPtr;


	/*base[0] = 64 << 16;
	for(i=1, j=0; j<64; j++)
	{
		base[i++] = colconv[(j>>0)&3];
		base[i++] = colconv[(j>>4)&3];
		base[i++] = colconv[(j>>2)&3];
	}
	base[i] = 0;*/


	HAM8_draw = (void (*)(void *, int, int)) NoDitherImage;	// method casting ... argh!
	DoDitherImage = NoDitherImage;

}


/*
 *   Resize the display using a copper list. Nifty'n neat amiga feature.
 *
 *   Phew ... takes now 2 hours to fiddle the system-compliant custom modulo stuff.
 */
void ResizeDisplay(int w, int h)
{
	struct UCopList *ucoplist;
	static struct TagItem uCopTags[] = {
		{ VTAG_USERCLIP_SET, NULL },
		{ VTAG_END_CM, NULL }};
	int i,j,k, y, fp_each, locallores;
	struct CopList *dspins;
	struct CopIns *copins;
	short bpl1mod=0, bpl2mod=0, last1, last2, this1, this2;
	ULONG id;
	struct DimensionInfo dim_info;


	if (ditherType == NO_DITHER) return;

	id = BestModeID(TAG_END) & MONITOR_ID_MASK;	/* get default monitor */

	if (GetDisplayInfoData(FindDisplayInfo(id), (UBYTE *)&dim_info, sizeof(struct DimensionInfo), DTAG_DIMS, 0))
		max_y=dim_info.StdOScan.MaxY - dim_info.StdOScan.MinY + 1;
	else
		max_y=200;

	sdbl=TRUE;
	if(h>max_y)
		sdbl=FALSE, max_y<<=1;

	lores=TRUE;
	locallores = lores && (w<=160);

	switch(id)
	{
		case A2024_MONITOR_ID:
			Quit("Get some colors, dude.", 25);

		case PAL_MONITOR_ID:
		case NTSC_MONITOR_ID:
			if(gfx40 && sdbl)
				id = locallores ? LORESHAMSDBL_KEY: HIRESHAMSDBL_KEY;
			else
				sdbl=FALSE, id = locallores ? HAM_KEY : HIRESHAM_KEY;
			break;

		case EURO72_MONITOR_ID:
			if(sdbl)
				id = locallores ? EURO72LORESHAMDBL_KEY : EURO72PRODUCTHAMDBL_KEY;
			else
				id = locallores ? EURO72LORESHAM_KEY : EURO72PRODUCTHAM_KEY;
			break;

		default:
			if(sdbl)
				id = locallores ? VGALORESHAMDBL_KEY : VGAPRODUCTHAMDBL_KEY;
			else
				id = locallores ? VGALORESHAM_KEY : VGAPRODUCTHAM_KEY;
			break;
	}

	if(!(screen=OpenScreenTags(NULL,
		SA_DisplayID,	id,
		SA_Depth,	8,
		SA_Width,	max_x = (locallores ? 320 : 640),
//		SA_Colors32,	base,
		SA_Colors,	firstblack,
		SA_Type,	CUSTOMSCREEN,
		SA_Quiet, 	TRUE,
		SA_Interleaved,	TRUE,
		SA_Overscan,	OSCAN_STANDARD,
		SA_MinimizeISG,	TRUE,
		SA_ErrorCode,	&soerror,
		TAG_END))) Quit("Couldn't open screen.",25);

	if(lores) {
		HAM8_Init_lores(&(screen->RastPort));
		HAM8_draw = HAM8_draw_lores;
		DoDitherImage = ColorDitherImage_lores;	// lacks kaiko support, actually
		max_x >>=1;
	} else {
		HAM8_Init(&(screen->RastPort));
		HAM8_draw = HAM8_draw_hires;
		DoDitherImage = ColorDitherImage;	// kaiko
		max_x >>=2;
	}

	if(noDisplayFlag)
		HAM8_draw = (void (*)(void *, int, int)) NoDitherImage;	// method casting ... argh!


	/* the memory is freed upon exit in output_term via FreeVPortCopLists */
	if(!(ucoplist = AllocMem(sizeof(struct UCopList), MEMF_PUBLIC|MEMF_CLEAR)))
		Quit("No memory for copper list.",25);

	/* fiddle out some hardware values from this screen's init copper list */
	dspins=screen->ViewPort.DspIns;
	copins=dspins->CopIns;
	for(i=dspins->Count-1; i>=0; i--, copins++)
	{
		j = copins->DESTDATA;
		switch(copins->DESTADDR)
		{		
			case (int)&((*(struct Custom *)(0)).bpl1mod):
				last1=bpl1mod = j;
				break;
			case (int)&((*(struct Custom *)(0)).bpl2mod):
				last2=bpl2mod = j;
				break;
		}
	}

	if(bpl1mod==0 || bpl2mod==0)	return;	/* hmmm? */

	if((bpl1mod == bpl2mod) && sdbl) sdbl=FALSE;

	y = screen->Height;
	(void) CINIT(ucoplist, y*3);		/* ... instructions per line */

	if(sdbl)
	{
		/*
		 *  We abuse some of AGA's features here; double-scanning is implemented
		 *  by applying bpl1mod to ALL planes on one line, bpl2mod on the next.
		 *  Obviously, double-scanning enables some kind of internal chipmem cache.
		 *  At least, it's faster. And (because of?) less copper instructions.
		 */

		fp_each = ((y*2)<<8) / (short)h;
		for(k=fp_each, j=0; j<y; j++)				/* for each line in the display */
		{

			if((k-=0x100)>=0x100)				/* we still gotta double the line */
				this1=bpl1mod;
			else						/* finally, we are ready; next one */
				this1=bpl2mod, k=(k&0xff)+fp_each;

			if((k-=0x100)>=0x100)				/* we still gotta double the line */
				this2=bpl1mod;
			else						/* finally, we are ready; next one */
				this2=bpl2mod, k=(k&0xff)+fp_each;

			if(last1!=this1 || last2!=this2)
				CWAIT(ucoplist, j, 0);

			if(last1!=this1)
			{
				CMOVE(ucoplist, custom.bpl1mod, this1);
				last1=this1;
			}

			if(last2!=this2)
			{
				CMOVE(ucoplist, custom.bpl2mod, this2);
				last2=this2;
			}
		}
	} else {

		/*
		 *  No scan-doubling possible; most probably because of a pal/ntsc screen 
		 *  and no V40 graphics library available.
		 */

		bpl1mod -= screen->RastPort.BitMap->BytesPerRow;

		fp_each = (y<<8) / (short)h;
		for(k=fp_each, j=0; j<y; j++)				/* for each line in the display */
		{

			if((k-=0x100)>=0x100)				/* we still gotta double the line */
				this1=bpl1mod;
			else						/* finally, we are ready; next one */
				this1=bpl2mod, k=(k&0xff)+fp_each;

			if(last1!=this1)
			{
				CWAIT(ucoplist, j, 0);
				CMOVE(ucoplist, custom.bpl1mod, this1);
				CMOVE(ucoplist, custom.bpl2mod, this1);
				last1=this1;
			}
		}

	}

	/*
	 *  Pretty nifty, isn't it? Finally, even a little bit copper-list-optimizing is build in!
	 */

	CEND(ucoplist);

	/* Set the freshly created user copper list */
	Forbid();
	screen->ViewPort.UCopIns = ucoplist;
	Permit();

	/*  Enable user copper list clipping for this ViewPort.  */
	(void) VideoControl( screen->ViewPort.ColorMap, uCopTags );

	RethinkDisplay();
	WaitTOF();

}



/*
 *--------------------------------------------------------------
 *
 * InitGrayDisplay --
 *
 *	Initialized display for gray scale dither.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *--------------------------------------------------------------
 */

#define NUM_COLORS 128

void InitGrayDisplay(char *name)
{
	Quit("Not implemented, yet.\n", 0);

	DoDitherImage = GrayDitherImage;
}



