// ************************************************************************************************
//
//  Direct Video
//
//
// ************************************** (c) Pedro Díez López ************************************

#include <malloc.h>
#include "DXVideo.h"
//
// Inicio
//
BOOL CDXVideo::Inicio(HWND hwnd,int Ancho,int Alto,int BPP)
{
  char          buf[256];
  
  ddrval = DirectDrawCreate(NULL, &lpDD, NULL);
	
  if(ddrval == DD_OK)
  {
    ddrval = lpDD->SetCooperativeLevel(hwnd, DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN);
    if(ddrval == DD_OK)
	{
	  ddrval = lpDD->SetDisplayMode(Ancho,Alto,BPP);
	  if(ddrval == DD_OK)
      {
        ddsd.dwSize = sizeof(ddsd);
		ddsd.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;
		ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE | DDSCAPS_FLIP | DDSCAPS_COMPLEX;
		ddsd.dwBackBufferCount = 1;
		ddrval = lpDD->CreateSurface(&ddsd, &lpDDSView, NULL);
		if(ddrval == DD_OK)
		{					
		  ddscaps.dwCaps = DDSCAPS_BACKBUFFER;
		  ddrval = lpDDSView->GetAttachedSurface(&ddscaps, &lpDDSBack);
		  if(ddrval == DD_OK)
          {
            hres        = Ancho;
            vres        = Alto;
            bpp         = BPP;
            ElmBuffer   = hres*vres;
            DimBuffer   = hres*vres*(bpp/8);
            pBuffer.bpp = malloc (DimBuffer);
            if(pBuffer.bpp==NULL)
            {
              hres      = 0;
              vres      = 0;
              bpp       = 0;
              ElmBuffer = 0;
              DimBuffer = 0;
              Fin();
              return FALSE;
            }
            return TRUE;
          }
		}
      }
	}
  }
  wsprintf(buf, "Fallo %08lX al iniciliazr DirectDraw\n",ddrval);
  MessageBox(hwnd, buf, "ERROR DirectX", MB_OK);
  Fin();
  return FALSE;    
}

//
// Cursor
//
void CDXVideo::Cursor(HCURSOR nCursor)
{
	mDDCursorShape = nCursor;
}

//
// Pinta
//
void CDXVideo::Pinta ()
{
  // Copia el buffer de trabajo al BackBuffer.
  while (TRUE)
  {
    ddrval=lpDDSBack->Lock(NULL,&ddsd,0,NULL);
	if(ddrval == DD_OK) break;
	if (ddrval != DDERR_WASSTILLDRAWING) return;
  }
  lpDXBuffer = (void *)ddsd.lpSurface;
  memcpy(lpDXBuffer,pBuffer.bpp,DimBuffer);
  lpDDSBack->Unlock(NULL);
  // Cambia el buffer.
  while (TRUE)
  {
    ddrval=lpDDSView->Flip(NULL, 0);
    if (ddrval == DD_OK) return;
    if (ddrval == DDERR_SURFACELOST)
    {
      ddrval=lpDDSView->Restore();
      if (ddrval!=DD_OK) return;
    }
    if (ddrval!=DDERR_WASSTILLDRAWING) return;
  }
}

//
// Fin
//
void CDXVideo::Fin()
{
  if (pBuffer.bpp != NULL) free (pBuffer.bpp);
  if(lpDD != NULL)
  {
    if(lpDDSView!=NULL)
	{
	  lpDDSView->Release();
	  lpDDSView = NULL;
	}
	lpDD->Release();
	lpDD = NULL;
  }
}
