/*   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 "fogAndBGColor.h"

#include <opengl.h>
#include <visu_object.h>
#include <visu_tools.h>
#include <visu_configFile.h>
#include <renderingBackend/visu_windowInterface.h>

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


/* Parameters & resources*/
/* This is a boolean to control is the axes is render or not. */
#define FLAG_RESOURCE_FOG_USED   "fog_is_on"
#define DESC_RESOURCE_FOG_USED   "Control if the fog is used ; boolean (0 or 1)"
#define RESOURCE_FOG_USED_DEFAULT 0
gboolean readFogIsOn(gchar **lines, int nbLines,
		     int position, GString *errorMessage);
#define FLAG_RESOURCE_FOG_SPECIFIC   "fog_color_is_specific"
#define DESC_RESOURCE_FOG_SPECIFIC   "Control if the fog uses a specific color ; boolean (0 or 1)"
#define RESOURCE_FOG_SPECIFIC_DEFAULT 0
int fogColorSpecific;
gboolean readFogSpecific(gchar **lines, int nbLines,
			 int position, GString *errorMessage);
/* A resource to control the color used to render the lines of the axes. */
#define FLAG_RESOURCE_FOG_COLOR   "fog_specific_color"
#define DESC_RESOURCE_FOG_COLOR   "Define the color of the fog ; three floating point values (0. <= v <= 1.)"
float fogRGB[3];
gboolean readFogColor(gchar **lines, int nbLines,
		      int position, GString *errorMessage);
#define FLAG_RESOURCE_FOG_STARTEND "fog_start_end"
#define DESC_RESOURCE_FOG_STARTEND "Define the position of the fog ; two floating point values (0. <= v <= 1.)"
float fog_start, fog_end;
gboolean readFogStartEnd(gchar **lines, int nbLines,
			 int position, GString *errorMessage);
/* A resource to control the color of the background. */
#define FLAG_RESOURCE_BG_COLOR   "backgroundColor_color"
#define DESC_RESOURCE_BG_COLOR   "Set the background of the background ; three floating point values (0. <= v <= 1.)"
float bgRGB[3];
gboolean readBgColor(gchar **lines, int nbLines,
		     int position, GString *errorMessage);

/* Export function that is called by visu_module to write the
   values of resources to a file. */
gboolean exportResourcesFog(GString *data, int *nbLinesWritten);

static float fogRGBDefault[3] = {0., 0., 0.};
static float fogStartEndDefault[2] = {0.3, 0.7};
static float bgRGBDefault[3] = {0., 0., 0.};

static int fogIsOn;
static gboolean fogHasBeenBuilt;

/* Local callbacks */
static void rebuildOpenGLValues(VisuData *dataObj);
static void onDataReadySignal(GObject *visu, VisuData *dataObj, gpointer data);
static void onFogParameterChanged(VisuData *dataObj, OpenGLView *view, gpointer data);
static void rebuildFogOnResources(GObject *obj, gpointer data);

/* Local methods */
void refreshBgRGB();


OpenGLExtension* initExtensionFogAndBGColor()
{
  char *name = "Fog and background color";
  char *description = _("Draw a nice fog around the elements and set the color of the background.");
  VisuConfigFileEntry *resourceEntry;

  DBG_fprintf(stderr,"Initialising the fog & bg OpenGL extension...\n");
  extensionFog = OpenGLExtension_new(name, description, 0, rebuildOpenGLValues);

  resourceEntry = visuConfigFileAdd_entry(VISU_CONFIGFILE_RESOURCE,
					  FLAG_RESOURCE_FOG_USED,
					  DESC_RESOURCE_FOG_USED,
					  1, readFogIsOn);
  resourceEntry = visuConfigFileAdd_entry(VISU_CONFIGFILE_RESOURCE,
					  FLAG_RESOURCE_FOG_SPECIFIC,
					  DESC_RESOURCE_FOG_SPECIFIC,
					  1, readFogSpecific);
  resourceEntry = visuConfigFileAdd_entry(VISU_CONFIGFILE_RESOURCE,
					  FLAG_RESOURCE_FOG_COLOR,
					  DESC_RESOURCE_FOG_COLOR,
					  1, readFogColor);
  resourceEntry = visuConfigFileAdd_entry(VISU_CONFIGFILE_RESOURCE,
					  FLAG_RESOURCE_FOG_STARTEND,
					  DESC_RESOURCE_FOG_STARTEND,
					  1, readFogStartEnd);
  resourceEntry = visuConfigFileAdd_entry(VISU_CONFIGFILE_RESOURCE,
					  FLAG_RESOURCE_BG_COLOR,
					  DESC_RESOURCE_BG_COLOR,
					  1, readBgColor);
  visuConfigFileAdd_exportFunction(VISU_CONFIGFILE_RESOURCE,
				   exportResourcesFog);

  /* Initialisation des valeurs par défaut. */
  setFogRGBValues(fogRGBDefault, MASK_RGB_ALL);
  setBgRGBValues(bgRGBDefault, MASK_RGB_ALL);
  extensionFog->used = 1;
  fogIsOn = 0;
  fogHasBeenBuilt = FALSE;
  fogColorSpecific = -1;
  setFogColorSpecific(RESOURCE_FOG_SPECIFIC_DEFAULT);
  setFogStartEndValues(fogStartEndDefault, MASK_FOG_START | MASK_FOG_END);

  g_signal_connect(G_OBJECT(visu), "resourcesLoaded",
		   G_CALLBACK(rebuildFogOnResources), (gpointer)0);
  g_signal_connect(G_OBJECT(visu), "dataReadyForRendering",
		   G_CALLBACK(onDataReadySignal), (gpointer)0);

  return extensionFog;
}

/* Method used to change the value of the parameter fog. */
int setFogRGBValues(float rgb[3], int mask)
{
  int diff = 0;
  
  if (mask & MASK_RGB_R && fogRGB[0] != rgb[0])
    {
      fogRGB[0] = rgb[0];
      diff = 1;
    }
  if (mask & MASK_RGB_G && fogRGB[1] != rgb[1])
    {
      fogRGB[1] = rgb[1];
      diff = 1;
    }
  if (mask & MASK_RGB_B && fogRGB[2] != rgb[2])
    {
      fogRGB[2] = rgb[2];
      diff = 1;
    }
  if (!diff)
    return 0;

  /* The method which calls the set method should ask for redraw. */
  if (fogColorSpecific)
    glFogfv(GL_FOG_COLOR, fogRGB);

  return (fogColorSpecific && fogIsOn);
}

/* Get methods. */
float getFogRedValue()
{
  return fogRGB[0];
}
float getFogGreenValue()
{
  return fogRGB[1];
}
float getFogBlueValue()
{
  return fogRGB[2];
}
/* Method used to change the value of the parameter axes_is_on. */
int setFogIsOn(int value)
{
  if (value == fogIsOn)
    return 0;

  fogIsOn = value;
  if (value)
    {
      glEnable(GL_FOG);
      glFogi(GL_FOG_MODE, GL_LINEAR); 
    }
  else
    glDisable(GL_FOG);
    
  return (value && !fogHasBeenBuilt);
}
int isFogOn()
{
  return fogIsOn;
}
int setFogColorSpecific(int value)
{
  if (value == fogColorSpecific)
    return 0;

  fogColorSpecific = value;
  createFogColor();
    
  return fogIsOn;
}
int getFogColorSpecific()
{
  return fogColorSpecific;
}
int setFogStartEndValues(float startEnd[2], int mask)
{
  int diff = 0;
  
  if (mask & MASK_FOG_START && fog_start != startEnd[0])
    {
      fog_start = startEnd[0];
      if (fog_start < 0.)
	fog_start = 0.;
      if (fog_start > 1.)
	fog_start = 1.;
      if (mask & MASK_FOG_END)
	{
	  if (fog_start >= startEnd[1])
	    fog_start = startEnd[1] - 0.001;
	}
      else
	if (fog_start >= fog_end)
	  fog_start = fog_end - 0.001;
      diff = 1;
    }
  if (mask & MASK_FOG_END && fog_end != startEnd[1])
    {
      fog_end = startEnd[1];
      if (fog_end < 0.)
	fog_end = 0.;
      if (fog_end > 1.)
	fog_end = 1.;
      if (fog_end <= fog_start)
	fog_end = fog_start + 0.001;
      diff = 1;
    }
  if (!diff)
    return 0;
  
  /* The method which calls the set method should ask for redraw. */
/*   createFog((GObject*)0, (gpointer)0); */
  fogHasBeenBuilt = FALSE;
  
  return (fogIsOn);
}
float getFogStart()
{
  return fog_start;
}
float getFogEnd()
{
  return fog_end;
}

/* Method used to change the value of the parameter backgroundColor. */
int setBgRGBValues(float rgb[3], int mask)
{
  int diff = 0;
  
  if (mask & MASK_RGB_R && bgRGB[0] != rgb[0])
    {
      bgRGB[0] = rgb[0];
      diff = 1;
    }
  if (mask & MASK_RGB_G && bgRGB[1] != rgb[1])
    {
      bgRGB[1] = rgb[1];
      diff = 1;
    }
  if (mask & MASK_RGB_B && bgRGB[2] != rgb[2])
    {
      bgRGB[2] = rgb[2];
      diff = 1;
    }
  if (!diff)
    return 0;

  /* The method which calls the set method should ask for redraw. */
  glClearColor(bgRGB[0], bgRGB[1], bgRGB[2], 0.0f);

  /* Update the fog color */
  createFogColor();
  return 1;
}

/* Get methods. */
float getBgRedValue()
{
  return bgRGB[0];
}
float getBgGreenValue()
{
  return bgRGB[1];
}
float getBgBlueValue()
{
  return bgRGB[2];
}


/****************/
/* Private part */
/****************/

static void onDataReadySignal(GObject *visu, VisuData *dataObj, gpointer data)
{
  if (!dataObj)
    return;

  refreshBgRGB();
  g_signal_connect(G_OBJECT(dataObj), "OpenGLNearFar",
		   G_CALLBACK(onFogParameterChanged), (gpointer)0);
  
  createFog(dataObj);
}
static void onFogParameterChanged(VisuData *dataObj, OpenGLView *view, gpointer data)
{
  DBG_fprintf(stderr, "Extension Fog : caught the 'OpenGLNearFar' signal, rebuilding"
	      " fog.\n");
  createFog(dataObj);
}
static void rebuildFogOnResources(GObject *obj,gpointer data)
{
  GList *tmpLst;

  DBG_fprintf(stderr, "Extension Fog : caught the 'resourcesLoaded' signal, rebuilding"
	      " fog.\n");

  tmpLst = visuDataGet_allObjects();
  while (tmpLst)
    {
      createFog(VISU_DATA(tmpLst->data));
      tmpLst = g_list_next(tmpLst);
    }
}

void createFog(VisuData *data)
{
  float start, stop;
  OpenGLView *view;

  g_return_if_fail(data);

  fogHasBeenBuilt = TRUE;

  view = visuDataGet_openGLView(data);
  start = (float)(view->window->near +
		  (view->window->far - view->window->near) * fog_start);
  stop = (float)(view->window->near +
		 (view->window->far - view->window->near) * fog_end);

/*   start = visuBox->extens * visuCamera->d_red * (1. - fog_start); */
/*   stop = visuBox->extens * visuCamera->d_red * (1. + fog_end); */
/*   start = visuBox->extens * visuCamera->d_red * (1. - 1 / 1.1); */
/*   stop = visuBox->extens * visuCamera->d_red * (1. + 1 / 1.1); */
/*   fprintf(stderr, "----------> %f %f %f %f\n", (float)(view->window->near + */
/* 						       (view->window->far - view->window->near) * fog_start), (float)(view->window->near + */
/* 														  (view->window->far - view->window->near) * fog_end), start, stop); */
  glFogf(GL_FOG_START, start);
  glFogf(GL_FOG_END, stop);
}

void createFogColor()
{
  if (fogColorSpecific)
    glFogfv(GL_FOG_COLOR, fogRGB);
  else
    glFogfv(GL_FOG_COLOR, bgRGB);
}
void refreshBgRGB()
{
  DBG_fprintf(stderr, "Extension bg : set background color.\n");
  glClearColor(bgRGB[0], bgRGB[1], bgRGB[2], 0.0f);
}

void rebuildOpenGLValues(VisuData *dataObj)
{
  if (fogIsOn)
    {
      glEnable(GL_FOG);
      glFogi(GL_FOG_MODE, GL_LINEAR); 
      createFogColor();
      createFog(dataObj);
    }
  refreshBgRGB();
}

/* This is a boolean to control is the fog is render or not. */
gboolean readFogIsOn(gchar **lines, int nbLines,
		     int position, GString *errorMessage)
{
  int res, val;

  res = sscanf(lines[0],"%d", &val);
  if (res != 1)
    {
      if (errorMessage)
	g_string_append_printf(errorMessage, _("WARNING! Parse error at line %d,"
					       " 1 boolean value must appear"
					       " after the %s markup.\n"),
			       position, FLAG_RESOURCE_FOG_USED);
      setFogIsOn(RESOURCE_FOG_USED_DEFAULT);
      return FALSE;
    }

  setFogIsOn(val);
  return TRUE;
}
/* This is a boolean to control the color used by the fog : a
   specific one or the background color. */
gboolean readFogSpecific(gchar **lines, int nbLines,
			 int position, GString *errorMessage)
{
  int res, val;

  res = sscanf(lines[0],"%d", &val);
  if (res != 1)
    {
      if (errorMessage)
	g_string_append_printf(errorMessage, _("WARNING! Parse error at line %d, 1 boolean"
					       " value (1 or 0) must appear after the %s"
					       " markup.\n"),
			       position, FLAG_RESOURCE_FOG_SPECIFIC);
      setFogIsOn(RESOURCE_FOG_SPECIFIC_DEFAULT);
      return FALSE;
    }

  setFogColorSpecific(val);
  return TRUE;
}
/* A resource to control the color used for the background. */
gboolean readFogColor(gchar **lines, int nbLines,
		      int position, GString *errorMessage)
{
  int res;
  float rgb[3];
  
  res = sscanf(lines[0],"%f %f %f", &rgb[0], &rgb[1], &rgb[2]);
  if (res != 3 ||
      visuConfigFileSet_floatValue(&rgb[0], rgb[0], 0., 1.) ||
      visuConfigFileSet_floatValue(&rgb[1], rgb[1], 0., 1.) ||
      visuConfigFileSet_floatValue(&rgb[2], rgb[2], 0., 1.))
    {
      if (errorMessage)
	g_string_append_printf(errorMessage, _("WARNING! Parse error at line %d, 3 floating "
					       "point values (0 <= v <= 1) must appear after"
					       " the %s markup.\n"),
			       position, FLAG_RESOURCE_FOG_COLOR);
      setFogRGBValues(fogRGBDefault, MASK_RGB_ALL);
      return FALSE;
    }
  setFogRGBValues(rgb, MASK_RGB_ALL);

  return TRUE;
}
/* A resource to control the color used for the background. */
gboolean readFogStartEnd(gchar **lines, int nbLines,
			 int position, GString *errorMessage)
{
  int res;
  float val[2];
  
  res = sscanf(lines[0],"%f %f", &val[0], &val[1]);
  if (res != 2 ||
      visuConfigFileSet_floatValue(&val[0], val[0], 0., 1.) ||
      visuConfigFileSet_floatValue(&val[1], val[1], 0., 1.))
    {
      if (errorMessage)
	g_string_append_printf(errorMessage, _("WARNING! Parse error at line %d, 2 floating "
					       "point values (0 <= v <= 1) must appear after"
					       " the %s markup.\n"),
			       position, FLAG_RESOURCE_FOG_STARTEND);
      setFogStartEndValues(fogStartEndDefault, MASK_FOG_START | MASK_FOG_END);
      return FALSE;
    }
  setFogStartEndValues(val, MASK_FOG_START | MASK_FOG_END);

  return TRUE;
}
/* A resource to control the color used for the background. */
gboolean readBgColor(gchar **lines, int nbLines,
		     int position, GString *errorMessage)
{
  int res;
  float rgb[3];
  
  res = sscanf(lines[0],"%f %f %f", &rgb[0], &rgb[1], &rgb[2]);
  if (res != 3 ||
      visuConfigFileSet_floatValue(&rgb[0], rgb[0], 0., 1.) ||
      visuConfigFileSet_floatValue(&rgb[1], rgb[1], 0., 1.) ||
      visuConfigFileSet_floatValue(&rgb[2], rgb[2], 0., 1.))
    {
      if (errorMessage)
	g_string_append_printf(errorMessage, _("WARNING! Parse error at line %d, 3 floating "
					       "point values (0 <= v <= 1) must appear after"
					       " the %s markup.\n"),
			       position, FLAG_RESOURCE_BG_COLOR);
      setBgRGBValues(bgRGBDefault, MASK_RGB_ALL);
      return FALSE;
    }
  setBgRGBValues(rgb, MASK_RGB_ALL);

  return TRUE;
}

/* Export function that is called by visu_module to write the
   values of resources to a file. */
gboolean exportResourcesFog(GString *data, int *nbLinesWritten)
{
  g_string_append_printf(data, "# %s\n", DESC_RESOURCE_FOG_USED);
  g_string_append_printf(data, "%s:\n    %d\n", FLAG_RESOURCE_FOG_USED,
			 fogIsOn);
  g_string_append_printf(data, "# %s\n", DESC_RESOURCE_FOG_SPECIFIC);
  g_string_append_printf(data, "%s:\n    %d\n", FLAG_RESOURCE_FOG_SPECIFIC,
			 fogColorSpecific);
  *nbLinesWritten = 6;
  g_string_append_printf(data, "# %s\n", DESC_RESOURCE_FOG_COLOR);
  g_string_append_printf(data, "%s:\n", FLAG_RESOURCE_FOG_COLOR);
  g_string_append_printf(data, "    %4.3f %4.3f %4.3f\n",
			 fogRGB[0], fogRGB[1], fogRGB[2]);
  g_string_append_printf(data, "# %s\n", DESC_RESOURCE_FOG_STARTEND);
  g_string_append_printf(data, "%s:\n", FLAG_RESOURCE_FOG_STARTEND);
  g_string_append_printf(data, "    %4.3f %4.3f\n",
			 fog_start, fog_end);
  g_string_append_printf(data, "\n");
  *nbLinesWritten += 7;
  g_string_append_printf(data, "# %s\n", DESC_RESOURCE_BG_COLOR);
  g_string_append_printf(data, "%s:\n", FLAG_RESOURCE_BG_COLOR);
  g_string_append_printf(data, "    %4.3f %4.3f %4.3f\n",
			 bgRGB[0], bgRGB[1], bgRGB[2]);
  g_string_append_printf(data, "\n");
  *nbLinesWritten += 4;

  return TRUE;
}
