/*
 *                          The Art Of
 *                      D E M O M A K I N G
 *
 *                     by Alex J. Champandard
 *                          Base Sixteen
 *			
 *                      vga.cpp ported to SDL
 *                       by Michael Malsbury
 *
 *                http://www.flipcode.com/demomaking
 *
 *                This file is in the public domain.
 *                      Use at your own risk.
 */


#include <stdio.h>
#include "vga.h"

/*
 * initialize mode 320x200x8 and prepare the double buffering
 */
VGA::VGA()
{
  if( SDL_Init(SDL_INIT_VIDEO) < 0 ){
    fprintf(stderr, "Error: %s\n", SDL_GetError());
//    exit(1);
  }
 
//  atexit(SDL_Quit);
  
  SDL_ShowCursor(0);

  // ignore all events except SDL_KEY* and SDL_QUIT
  SDL_EventState(SDL_ACTIVEEVENT, SDL_IGNORE);
  SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
  SDL_EventState(SDL_MOUSEBUTTONDOWN, SDL_IGNORE);
  SDL_EventState(SDL_MOUSEBUTTONUP, SDL_IGNORE);
  SDL_EventState(SDL_SYSWMEVENT, SDL_IGNORE);
  
  screen = SDL_SetVideoMode(320, 200, 8, SDL_SWSURFACE |SDL_FULLSCREEN );
  if( screen == NULL ){
    fprintf(stderr, "Error: %s\n", SDL_GetError());
//    exit(1);
  }  
  
  page_draw = (Uint8 *)screen->pixels;

  {
    int i;
    for(i=0;i<256;i++)
    {
       colors[i].r = colors[i].g = colors[i].b = 0;
    }
  }

  dirty = 0;
};

/*
 * set a colour in the palette
 */
void VGA::SetColour( unsigned char i, unsigned char r, unsigned char g, unsigned char b )
{
  colors[i].r = r<<2;
  colors[i].g = g<<2;
  colors[i].b = b<<2;
  dirty = 1;
};

/*
 * return to text mode, and clean up
 */
VGA::~VGA()
{
	SDL_Quit();
};

/*
 * flip the double buffer to the screen
 */
void VGA::Update()
{
  if(dirty){
    SDL_SetColors(screen,colors,0,256);
    SDL_Flip(screen);
    dirty = 0;
  } else {
    SDL_Flip(screen);
  }
};

/*
 * draw a pixel in the temporary buffer
 */
void VGA::PutPixel( int x, int y, unsigned c )
{
  *((Uint8 *)screen->pixels + (((y)<<8)+((y)<<6)) + x) = c;
}

/*
 * clear the double buffer
 */
void VGA::Clear()
{
  SDL_FillRect(screen, NULL, 0);
}
