/*   EXTRAITS DE LA LICENCE
     Copyright CEA, contributeurs : Luc BILLARD et Damien
     CALISTE, laboratoire L_Sim, (2001-2006)
  
     Adresse mèl :
     BILLARD, non joignable par mèl ;
     CALISTE, damien P caliste AT cea P fr.

     Ce logiciel est un programme informatique servant à visualiser des
     structures atomiques dans un rendu pseudo-3D. 

     Ce logiciel est régi par la licence CeCILL soumise au droit français et
     respectant les principes de diffusion des logiciels libres. Vous pouvez
     utiliser, modifier et/ou redistribuer ce programme sous les conditions
     de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA 
     sur le site "http://www.cecill.info".

     Le fait que vous puissiez accéder à cet en-tête signifie que vous avez 
     pris connaissance de la licence CeCILL, et que vous en avez accepté les
     termes (cf. le fichier Documentation/licence.fr.txt fourni avec ce logiciel).
*/

/*   LICENCE SUM UP
     Copyright CEA, contributors : Luc BILLARD et Damien
     CALISTE, laboratoire L_Sim, (2001-2006)

     E-mail address:
     BILLARD, not reachable any more ;
     CALISTE, damien P caliste AT cea P fr.

     This software is a computer program whose purpose is to visualize atomic
     configurations in 3D.

     This software is governed by the CeCILL  license under French law and
     abiding by the rules of distribution of free software.  You can  use, 
     modify and/ or redistribute the software under the terms of the CeCILL
     license as circulated by CEA, CNRS and INRIA at the following URL
     "http://www.cecill.info". 

     The fact that you are presently reading this means that you have had
     knowledge of the CeCILL license and that you accept its terms. You can
     find a copy of this licence shipped with this software at Documentation/licence.en.txt.
*/
#include "visu_OSInterface.h"

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

#include <windows.h>

#include "visu_WIN32.h"
#include "visu_tools.h"

static HGLRC ctxDirect;
static HGLRC ctxPixmap;

static HDC storedDrawable;
static HGLRC storedContext;

struct DumpImage_struct
{
  /*   GLXPixmap glxPixmap; */
  /*   Pixmap pixmap; */
  HDC pixmapDC;
  HBITMAP pixmap;
  int width, height;
};

gboolean drawableIsPixmap;

void SetupPixelFormat(HDC hDC)
{
  /*      Pixel format index
   */
  int nPixelFormat;

  static PIXELFORMATDESCRIPTOR pfd = {
    sizeof(PIXELFORMATDESCRIPTOR),          /*size of structure*/
    1,                                      /*default version*/
    PFD_DRAW_TO_WINDOW |                    /*window drawing support*/
    PFD_SUPPORT_OPENGL |                    /*opengl support*/
    PFD_DOUBLEBUFFER,                       /*double buffering support*/
    PFD_TYPE_RGBA,                          /*RGBA color mode*/
    32,                                     /*32 bit color mode*/
    0, 0, 0, 0, 0, 0,                       /*ignore color bits*/
    0,                                      /*no alpha buffer*/
    0,                                      /*ignore shift bit*/
    0,                                      /*no accumulation buffer*/
    0, 0, 0, 0,                             /*ignore accumulation bits*/
    16,                                     /*16 bit z-buffer size*/
    0,                                      /*no stencil buffer*/
    0,                                      /*no aux buffer*/
    PFD_MAIN_PLANE,                         /*main drawing plane*/
    0,                                      /*reserved*/
    0, 0, 0 };                              /*layer masks ignored*/

  /*      Choose best matching format*/
  nPixelFormat = ChoosePixelFormat(hDC, &pfd);

  /*      Set the pixel format to the device context*/
  SetPixelFormat(hDC, nPixelFormat, &pfd);
}

void SetupPixelFormatPixmap(HDC hDC)
{
  /*      Pixel format index
   */
  int nPixelFormat;

  static PIXELFORMATDESCRIPTOR pfdPix = {
    sizeof(PIXELFORMATDESCRIPTOR),          /*size of structure*/
    1,                                      /*default version*/
    PFD_DRAW_TO_BITMAP |                    /*window drawing support*/
    PFD_SUPPORT_OPENGL,                     /*opengl support*/
    PFD_TYPE_RGBA,                          /*RGBA color mode*/
    32,                                     /*32 bit color mode*/
    0, 0, 0, 0, 0, 0,                       /*ignore color bits*/
    0,                                      /*no alpha buffer*/
    0,                                      /*ignore shift bit*/
    0,                                      /*no accumulation buffer*/
    0, 0, 0, 0,                             /*ignore accumulation bits*/
    16,                                     /*16 bit z-buffer size*/
    0,                                      /*no stencil buffer*/
    0,                                      /*no aux buffer*/
    PFD_MAIN_PLANE,                         /*main drawing plane*/
    0,                                      /*reserved*/
    0, 0, 0 };                              /*layer masks ignored*/

  /*      Choose best matching format*/
  nPixelFormat = ChoosePixelFormat(hDC, &pfdPix);

  /*      Set the pixel format to the device context*/
  SetPixelFormat(hDC, nPixelFormat, &pfdPix);
}



int initOpenGLContext()
{
  DBG_fprintf(stderr, "Visu WGL : init OpenGl context.\n");

  SetupPixelFormat(hdc);

  ctxDirect = wglCreateContext(hdc);

  drawableIsPixmap = FALSE;

  DBG_fprintf(stderr, "Visu WGL : OK.\n");

  return 1;
}

int setWindowHandler(gpointer windowHandler)
{
  window = (HWND*)windowHandler;
  return 1;
}

gboolean OpenGLIsPixmap()
{
  return drawableIsPixmap;
}


int attachOpenGlContext(gboolean isPixmap, gpointer windowDescriptor)
{
  if (isPixmap)
    {
      drawableIsPixmap = TRUE;
      wglMakeCurrent(NULL, NULL);
      wglMakeCurrent(*((HDC*)windowDescriptor), ctxPixmap);
    }
  else
    {
      drawableIsPixmap = FALSE;
      wglMakeCurrent(NULL, NULL);
      wglMakeCurrent(hdc, ctxDirect);
    }
  DBG_fprintf(stderr, "Visu WGL : Set the current context to pixmap(1)"
	      " or to window(0) : %d.\n", isPixmap);
  return 1;
}

DumpImage* dumpImageNew(int width, int height)
{
  DumpImage *image;

  DBG_fprintf(stderr, "Visu WGL : creating a off-screen buffer (%dx%d).\n", width, height);
  image = malloc(sizeof(DumpImage));
  if (!image)
    {
      allocationProblems();
      exit(1);
    }
  image->width = width;
  image->height = height;
  image->pixmap = CreateCompatibleBitmap(hdc, width, height);
  image->pixmapDC = CreateCompatibleDC(NULL);
  image->pixmap = SelectObject(image->pixmapDC, image->pixmap);
  SetupPixelFormatPixmap(image->pixmapDC);
  ctxPixmap = wglCreateContext(image->pixmapDC);
  return image;
}
void dumpImageFree(DumpImage *image)
{
  if (image)
    {
      wglDeleteContext(ctxPixmap);
      DeleteDC(image->pixmapDC);
      DeleteObject(SelectObject(image->pixmapDC, image->pixmap));
      free(image);
    }
}
gpointer dumpImageGet_buffer(DumpImage *image)
{
  if (image)
    return (gpointer)&image->pixmapDC;
  else
    return (gpointer)0;
}


void callSwapGLBuffer()
{
  if (!drawableIsPixmap)
    SwapBuffers(hdc);
}

int initOSinterface()
{
  window = (HWND *)0;
  return 1;
}


int initDisplay()
{
  if (window)
    hdc = GetDC(*window);
  else
    hdc = GetDC(NULL);
  if ( !hdc )
    {
      (void)fprintf(stderr, "FATAL ERROR! Cannot get HDC.\n");
      /* 		    "Is there an X server running and do you have" */
      /* 		    " access on it?\n", XDisplayName(0)); */
      return 0;
    }
  return 1;
}



void storeOpenGLContext()
{
  storedContext = wglGetCurrentContext();
  storedDrawable = wglGetCurrentDC();

  DBG_fprintf(stderr, "Visu WGL : store the current context and HDC.\n");
}
void restoreOpenGLContext()
{
  BOOL res;

  DBG_fprintf(stderr, "Visu WGL : restore old context and HDC.\n");
  res = wglMakeCurrent(storedDrawable, storedContext);
  if (storedDrawable == hdc)
    drawableIsPixmap = FALSE;
  if (!res)
    g_warning("Cannot restore WGL context to previous drawable.\n");
}

GLuint initOpenGLFontList()
{
  GLuint BASE;
  BOOL res;

  BASE = 0;
  
  return 0;

  DBG_fprintf(stderr, "Visu WGL : initialise fonts.\n");
  /* this creates display lists 1 to 256 (not checked) */
  if ( (BASE = glGenLists(256)) == 0 )
    {
      DBG_fprintf(stderr, "Visu WGL : Cannot create a list for font.\n");
      g_warning("Cannot build font display lists.\n");
      exit(1);
    }
  if (!drawableIsPixmap)
    res = wglUseFontBitmaps(hdc, 0, 255, BASE);
  /*  else
      res = wglUseFontBitmaps(hdcPixmap, 0, 255, BASE);*/
  /*if ( !res )
    {
    DBG_fprintf(stderr, "Visu WGL : wglUseFontBitmaps returns false (%d - %d).\n", res, drawableIsPixmap);
    (void)fprintf(stderr, _("INTERNAL ERROR! Cannot build font display lists.\n%d\n"), GetLastError());
    exit(1);
    }*/
 
  return BASE;
}
