/*   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_extension.h"
#include "extensions/externalOpenGLExtensions.h"

#include <stdlib.h>
#include <string.h>
#include <GL/gl.h>
#include <GL/glu.h> 


#include "visu_tools.h"

/* A GHashTable to store all the available OpenGL extensions
   in the system. The keys are the name of each extension. */
GList *availableOpenGLExtensions;

/* This flag is TRUE when some priorities are new or have changed, and 
   the list should be reordered. */
gboolean OpenGLExtension_reorderingNeeded;
/* Method used to compare the priority of two extensions. */
gint compareExtensionPriority(gconstpointer a, gconstpointer b);

void openGLSaveState();
void openGLRestoreState();
static void drawExtension(OpenGLExtension *extension, RenderingModeId renderingMode);

/***************/
/* Public part */
/***************/


/* Method used to create such structures. */
OpenGLExtension* OpenGLExtension_new(char* name, char* description,
				     int objectListId, rebuildObjectListFunc rebuild)
{
  OpenGLExtension *extension;

  extension = g_malloc(sizeof(OpenGLExtension));
  extension->name = (char*)0;
  extension->description = (char*)0;
  extension->name = g_strdup(name);
  if (description)
    extension->description = g_strdup(description);

  extension->objectListId = objectListId;
  extension->rebuild = rebuild;
  extension->priority = OPENGL_EXTENSION_PRIORITY_NORMAL;
  extension->saveState = FALSE;
  extension->isSensitiveToRenderingMode = FALSE;
  extension->preferedRenderingMode = -1; /* Follow global settings */

  extension->used = 0;

  return extension;
}

/* Free all the allocated attributes of the specified extension. */
void OpenGLExtension_free(OpenGLExtension* extension)
{
  if (!extension)
    return;
  if (extension->name)
    free(extension->name);
  if (extension->description)
    free(extension->description);
  free(extension);
}
/* Get if the extension is used or not. */
int OpenGLExtensionGet_active(OpenGLExtension* extension)
{
  if (extension)
    return extension->used;
  else
    return 0;
}
/* Set if an extension is actually used or not. */
void OpenGLExtensionSet_active(OpenGLExtension* extension, int value)
{
  if (!extension || extension->used == value)
    return;

  extension->used = value;
}
GList* OpenGLExtensionGet_list()
{
  if (OpenGLExtension_reorderingNeeded)
    {
      DBG_fprintf(stderr, "Visu Extension : sorting known extension depending on their priority.\n");
      availableOpenGLExtensions = g_list_sort(availableOpenGLExtensions, compareExtensionPriority);
      OpenGLExtension_reorderingNeeded = FALSE;
    }
  return availableOpenGLExtensions;
}

void OpenGLExtensionSet_priority(OpenGLExtension* extension, int priority)
{
  g_return_if_fail(extension);
  extension->priority = priority;
  OpenGLExtension_reorderingNeeded = TRUE;
}

void OpenGLExtensionSet_saveOpenGLState(OpenGLExtension *extension, gboolean saveState)
{
  g_return_if_fail(extension);
  extension->saveState = saveState;
}

void OpenGLExtensionSet_sensitiveToRenderingMode(OpenGLExtension* extension, gboolean status)
{
  g_return_if_fail(extension);
  extension->isSensitiveToRenderingMode = TRUE;
}
gboolean OpenGLExtensionSet_preferedRenderingMode(OpenGLExtension* extension,
						  gint value)
{
  g_return_val_if_fail(extension, FALSE);
  g_return_val_if_fail(value < nb_renderingModes, FALSE);

  if (extension->preferedRenderingMode == value)
    return FALSE;

  extension->preferedRenderingMode = value;

  return TRUE;
}



/* A method used by user to registered a new extension. */
void OpenGLExtensionRegister(OpenGLExtension *extension)
{
  DBG_fprintf(stderr, "Visu Extension : registering a new OpenGL extension ... ");
  g_return_if_fail(extension && extension->name && extension->name[0]);

  availableOpenGLExtensions = g_list_append(availableOpenGLExtensions,
					    (gpointer)extension);

  OpenGLExtension_reorderingNeeded = TRUE;
  DBG_fprintf(stderr, "'%s' (%p).\n", extension->name, (gpointer)extension);
}

/* A method used by user to remove a previously registered extension. */
void OpenGLExtensionRemove(OpenGLExtension *extension)
{
  DBG_fprintf(stderr, "Visu Extension : removing a registered OpenGL"
	      " extension (%p).\n", (gpointer)extension);
  g_return_if_fail(extension);

  availableOpenGLExtensions = g_list_remove(availableOpenGLExtensions,
					    (gpointer)extension);
}


/* For each extension that has a valid list (id > 1000) a glCallList is raised. */
void callAllExtensionsLists()
{
  GList *pnt;
  RenderingModeId renderingMode, globalRenderingMode;
  OpenGLExtension *ext;

  if (OpenGLExtension_reorderingNeeded)
    {
      DBG_fprintf(stderr, "Visu Extension : sorting known extension depending on their priority.\n");
      availableOpenGLExtensions = g_list_sort(availableOpenGLExtensions, compareExtensionPriority);
      OpenGLExtension_reorderingNeeded = FALSE;
    }
  globalRenderingMode = openGLGet_globalRenderingOption();
  renderingMode = globalRenderingMode;
  pnt = availableOpenGLExtensions;
  while (pnt)
    {
      ext = (OpenGLExtension*)pnt->data;
      if (ext->used &&
	  ext->objectListId > 1000)
	{
	  /* The extension needs its own rendering mode. */
	  if (ext->isSensitiveToRenderingMode && ext->preferedRenderingMode >= 0)
	    {
	      if ((unsigned int)ext->preferedRenderingMode != renderingMode)
		{
		  openGLApply_renderingMode((RenderingModeId)ext->preferedRenderingMode);
		  renderingMode = (unsigned int)ext->preferedRenderingMode;
		}
	    }
	  else
	    {
	      if (renderingMode != globalRenderingMode)
		{
		  openGLApply_renderingMode(globalRenderingMode);
		  renderingMode = globalRenderingMode;
		}
	    }
	  if (ext->saveState)
	    {
	      DBG_fprintf(stderr, "Visu Extension : save state.\n");
	      glPushAttrib(GL_ENABLE_BIT);
	    }

	  drawExtension(ext, renderingMode);

	  if (ext->saveState)
	    {
	      DBG_fprintf(stderr, "Visu Extension : restore state.\n");
	      glPopAttrib();
	    }
	}
      pnt = g_list_next(pnt);
    }
  if (renderingMode != globalRenderingMode)
    /* Return the rendering mode to normal. */
    openGLApply_renderingMode(globalRenderingMode);
}
void rebuildAllExtensionsLists(VisuData *dataObj)
{
  GList *pnt;

  DBG_fprintf(stderr, "Visu Extension : Rebuilding lists...\n");
  if (OpenGLExtension_reorderingNeeded)
    {
      DBG_fprintf(stderr, "Visu Extension : sorting known extension depending on their priority.\n");
      availableOpenGLExtensions = g_list_sort(availableOpenGLExtensions, compareExtensionPriority);
      OpenGLExtension_reorderingNeeded = FALSE;
    }
  pnt = availableOpenGLExtensions;
  while (pnt)
    {
      if (((OpenGLExtension*)pnt->data)->used &&
	  ((OpenGLExtension*)pnt->data)->rebuild)
	{
	  DBG_fprintf(stderr, "Visu Extension : rebuild extension %s (list %d).\n",
		      ((OpenGLExtension*)pnt->data)->name,
		      ((OpenGLExtension*)pnt->data)->objectListId);
	  ((OpenGLExtension*)pnt->data)->rebuild(dataObj);
	}
      pnt = g_list_next(pnt);
    }
}


/****************/
/* Private area */
/****************/

/* Initialise all the variable of this part. */
int initOpenGLExtensions()
{
  availableOpenGLExtensions = (GList*)0;
  OpenGLExtension_reorderingNeeded = FALSE;
  return 1;
}
void loadExtensions()
{
  OpenGLExtension *extension;
  int i, res;

  res = 1;
  for (i = 0; listInitExtensionFunc[i]; i++)
    {
      extension = listInitExtensionFunc[i]();
      if (!extension)
	res = 0;
      OpenGLExtensionRegister(extension);
    }
  
  if (!res)
    g_warning("Some OpenGL extensions can't initialse.\n");
}
static void drawExtension(OpenGLExtension *extension, RenderingModeId renderingMode)
{
  float mat[5] = {0., 0., 0., 0., 0.};
  float rgba[4] = {0., 0., 0., 0.};

  /* Call the compiled list. */
  DBG_fprintf(stderr, "Visu Extension : call list %d (%s).\n",
	      extension->objectListId, extension->name);
  glCallList(extension->objectListId);

  /* Add a wireframe draw if renderingMode is SmoothAndEdge. */
/*   if (extension->isSensitiveToRenderingMode && renderingMode == SmoothAndEdge) */
/*     { */
/*       glPushAttrib(GL_ENABLE_BIT); */
/*       glEnable(GL_BLEND); */
/*       glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_SRC_COLOR); */
/*       glColor4f(1., 1., 1., 0.); */
/*       setOpenGlMaterial(mat, rgba); */
/*       openGLApply_renderingMode(Wireframe); */
/*       glCallList(extension->objectListId); */
/*       openGLApply_renderingMode(Smooth); */
/*       glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); */
/*       glPopAttrib(); */
/*     } */
}

gint compareExtensionPriority(gconstpointer a, gconstpointer b)
{
  if (((OpenGLExtension*)a)->priority < ((OpenGLExtension*)b)->priority)
    return (gint)-1;
  else if (((OpenGLExtension*)a)->priority > ((OpenGLExtension*)b)->priority)
    return (gint)+1;
  else
    return (gint)0;
}
