/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Luc BILLARD et Damien
	CALISTE, laboratoire L_Sim, (2001-2005)
  
	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-2005)

	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 <stdio.h>
#include <stdlib.h>
#include <math.h>

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

#include "opengl.h"

#include "visu_extension.h"
#include "visu_tools.h"
#include "visu_configFile.h"
#include "openGLFunctions/interactive.h"
#include "openGLFunctions/objectList.h"
#include "coreTools/toolColor.h"

/**
 * SECTION:opengl
 * @short_description: This part is responsible for the pseudo3D
 * rendering through OpenGl and gives methods to adapt the view.
 *
 * <para>There is a last parameter which controls when render is
 * done. There are two states : whenever a changing occurs (in fact
 * when the OpenGLAskForReDraw signal is received) or only the
 * OpenGLForceReDraw is received.</para>
 *
 * <para>Except when high performances are required, this module never
 * makes a redraw by itself, even when parameters such as the camera
 * position are changed. The redraw must be asked by the client by
 * emitting the OpenGLAskForReDraw signal or the OpenGLForceReDraw
 * signal. This is to avoid situations when the client makes different
 * changes but want just only one redraw at the end. All set methods
 * return a boolean which informs the client of the opportunity to
 * redraw after the set occurs. For example, if the client call a set
 * change on theta or phi but the server returns FALSE, it means that
 * not emission of OpenGLAskForReDraw is needed (for example because
 * theta or phi had already these values).</para>
 */

/******************************************************************************/

struct _VisuGlPrivate
{
  /* static int stereo; */
  VisuGlLights *currentLights;
  gboolean antialias, immediate;
  gboolean trueTransparency, stereoStatus;
  float stereoAngle;
  VisuGlRenderingMode mode;
  guint hints;
};

#define FLAG_PARAMETER_OPENGL_IMMEDIATE   "opengl_immediateDrawing"
#define DESC_PARAMETER_OPENGL_IMMEDIATE   "If true, changes of parameters means immediate redrawing ; boolean 0 or 1"
static gboolean immediate = TRUE;

#define FLAG_PARAMETER_OPENGL_ANTIALIAS "opengl_antialias"
#define DESC_PARAMETER_OPENGL_ANTIALIAS "If true, lines are drawn smoother ; boolean 0 or 1"
static gboolean antialias = FALSE;

#define FLAG_PARAMETER_OPENGL_FAKEBS "opengl_fakeBackingStore"
#define DESC_PARAMETER_OPENGL_FAKEBS "If true, V_Sim catches the Expose event from the X server and calls a redraw ; boolean 0 or 1"
#define PARAMETER_OPENGL_FAKEBS_DEFAULT 0
static int fakeBackingStore;

#define FLAG_PARAMETER_OPENGL_TRANS "opengl_trueTransparency"
#define DESC_PARAMETER_OPENGL_TRANSS "If true, the transparency rendering is enhanced ; boolean 0 or 1"
static gboolean trueTransparency = FALSE;

#define FLAG_PARAMETER_OPENGL_ANGLE "opengl_stereoAngle"
#define DESC_PARAMETER_OPENGL_ANGLE "Give the angle of the two receivers in stereo output ; float positive"
static float stereoAngle = 5.f;

#define FLAG_PARAMETER_OPENGL_STEREO "opengl_stereo"
#define DESC_PARAMETER_OPENGL_STEREO "If true, try to draw in stereo ; boolean 0 or 1"
static gboolean stereoStatus = FALSE;

#define FLAG_PARAMETER_OPENGL_RENDERING "opengl_render"
#define DESC_PARAMETER_OPENGL_RENDERING "Rules the way OpenGl draws objects in general ; 4 possible strings : VISU_GL_RENDERING_WIREFRAME, VISU_GL_RENDERING_FLAT, VISU_GL_RENDERING_SMOOTH and VISU_GL_RENDERING_SMOOTH_AND_EDGE"
#define FLAG_RESOURCE_OPENGL_RENDERING "gl_render"
#define DESC_RESOURCE_OPENGL_RENDERING "Rules the way OpenGl draws objects in general ; 4 possible strings : VISU_GL_RENDERING_WIREFRAME, VISU_GL_RENDERING_FLAT, VISU_GL_RENDERING_SMOOTH and VISU_GL_RENDERING_SMOOTH_AND_EDGE"
static guint renderingOption = VISU_GL_RENDERING_SMOOTH;

enum
  {
    PROP_0,
    LIGHTS_PROP,
    ANTIALIAS_PROP,
    IMMEDIATE_PROP,
    TRANS_PROP,
    STEREO_PROP,
    ANGLE_PROP,
    MODE_PROP,
    N_PROP
  };
static GParamSpec* _properties[N_PROP];

static VisuGl *defaultGl = NULL;

static void visu_gl_get_property(GObject* obj, guint property_id,
                                         GValue *value, GParamSpec *pspec);
static void visu_gl_set_property(GObject* obj, guint property_id,
                                         const GValue *value, GParamSpec *pspec);
static void glInitContext(VisuGl *gl);

/* Local methods. */
static void onEntryAntialias(VisuGl *self, VisuConfigFileEntry *entry, VisuConfigFile *obj);
static void onEntryImmediate(VisuGl *self, VisuConfigFileEntry *entry, VisuConfigFile *obj);
static void onEntryTrans(VisuGl *self, VisuConfigFileEntry *entry, VisuConfigFile *obj);
static void onEntryStereo(VisuGl *self, VisuConfigFileEntry *entry, VisuConfigFile *obj);
static void onEntryAngle(VisuGl *self, VisuConfigFileEntry *entry, VisuConfigFile *obj);
static void onEntryMode(VisuGl *self, VisuConfigFileEntry *entry, VisuConfigFile *obj);
static void exportParametersOpenGL(GString *data, VisuData *dataObj);
static void exportOpenGL(GString *data, VisuData *dataObj);
static void glSetAntiAlias(VisuGlPrivate *gl);

/******************************************************************************/

G_DEFINE_TYPE_WITH_CODE(VisuGl, visu_gl, VISU_TYPE_OBJECT,
                        G_ADD_PRIVATE(VisuGl))

static void visu_gl_class_init(VisuGlClass *klass)
{
  float rgAngle[2] = {-45.f,45.f};
  VisuConfigFileEntry *resourceEntry, *oldEntry;

  DBG_fprintf(stderr, "Visu Gl: creating the class of the object.\n");
  /* DBG_fprintf(stderr, "                - adding new signals ;\n"); */

  /* Parameters */
  visu_config_file_addBooleanEntry(VISU_CONFIG_FILE_PARAMETER,
                                   FLAG_PARAMETER_OPENGL_ANTIALIAS,
                                   DESC_PARAMETER_OPENGL_ANTIALIAS,
                                   &antialias, FALSE);
  visu_config_file_addBooleanEntry(VISU_CONFIG_FILE_PARAMETER,
                                   FLAG_PARAMETER_OPENGL_IMMEDIATE,
                                   DESC_PARAMETER_OPENGL_IMMEDIATE,
                                   &immediate, FALSE);
  resourceEntry = visu_config_file_addBooleanEntry(VISU_CONFIG_FILE_PARAMETER,
                                                   FLAG_PARAMETER_OPENGL_TRANS,
                                                   DESC_PARAMETER_OPENGL_TRANSS,
                                                   &trueTransparency, FALSE);
  visu_config_file_entry_setVersion(resourceEntry, 3.4f);
  resourceEntry = visu_config_file_addFloatArrayEntry(VISU_CONFIG_FILE_PARAMETER,
                                                      FLAG_PARAMETER_OPENGL_ANGLE,
                                                      DESC_PARAMETER_OPENGL_ANGLE,
                                                      1, &stereoAngle, rgAngle, FALSE);
  visu_config_file_entry_setVersion(resourceEntry, 3.4f);
  resourceEntry = visu_config_file_addBooleanEntry(VISU_CONFIG_FILE_PARAMETER,
                                                   FLAG_PARAMETER_OPENGL_STEREO,
                                                   DESC_PARAMETER_OPENGL_STEREO,
                                                   &stereoStatus, FALSE);
  visu_config_file_entry_setVersion(resourceEntry, 3.4f);
  visu_config_file_addExportFunction(VISU_CONFIG_FILE_PARAMETER,
                                     exportParametersOpenGL);

  oldEntry = visu_config_file_addEntry(VISU_CONFIG_FILE_PARAMETER,
                                       FLAG_PARAMETER_OPENGL_RENDERING,
                                       DESC_PARAMETER_OPENGL_RENDERING,
                                       1, NULL);
  resourceEntry = visu_config_file_addEnumEntry(VISU_CONFIG_FILE_RESOURCE,
                                                FLAG_RESOURCE_OPENGL_RENDERING,
                                                DESC_RESOURCE_OPENGL_RENDERING,
                                                &renderingOption,
                                                visu_gl_rendering_getModeFromName, FALSE);
  visu_config_file_entry_setVersion(resourceEntry, 3.4f);
  visu_config_file_entry_setReplace(resourceEntry, oldEntry);
  visu_config_file_addExportFunction(VISU_CONFIG_FILE_RESOURCE,
                                     exportOpenGL);
  visu_gl_rendering_init();
  
  fakeBackingStore = PARAMETER_OPENGL_FAKEBS_DEFAULT;

  /* Connect the overloading methods. */
  G_OBJECT_CLASS(klass)->set_property = visu_gl_set_property;
  G_OBJECT_CLASS(klass)->get_property = visu_gl_get_property;
  VISU_GL_CLASS(klass)->initContext = glInitContext;

  /**
   * VisuGl::lights:
   *
   * Lights environment used for this context.
   *
   * Since: 3.8
   */
  _properties[LIGHTS_PROP] = g_param_spec_boxed("lights", "Lights",
                                                "light environment",
                                                VISU_TYPE_GL_LIGHTS, G_PARAM_READABLE |
                                                G_PARAM_STATIC_STRINGS);
  g_object_class_install_property
    (G_OBJECT_CLASS(klass), LIGHTS_PROP, _properties[LIGHTS_PROP]);
  /**
   * VisuGl::antialias:
   *
   * Antialias line drawing or not.
   *
   * Since: 3.8
   */
  _properties[ANTIALIAS_PROP] = g_param_spec_boolean("antialias", "Antialias",
                                                     "antialias line",
                                                     antialias, G_PARAM_READWRITE |
                                                     G_PARAM_STATIC_STRINGS);
  g_object_class_install_property
    (G_OBJECT_CLASS(klass), ANTIALIAS_PROP, _properties[ANTIALIAS_PROP]);
  /**
   * VisuGl::immediate:
   *
   * Redraw immediately after any change.
   *
   * Since: 3.8
   */
  _properties[IMMEDIATE_PROP] = g_param_spec_boolean("immediate", "Immediate",
                                                     "immediate redraw after change",
                                                     immediate, G_PARAM_READWRITE |
                                                     G_PARAM_STATIC_STRINGS);
  g_object_class_install_property
    (G_OBJECT_CLASS(klass), IMMEDIATE_PROP, _properties[IMMEDIATE_PROP]);
  /**
   * VisuGl::true-transparency:
   *
   * Draw the scene twice to improve transparency rendering.
   *
   * Since: 3.8
   */
  _properties[TRANS_PROP] = g_param_spec_boolean("true-transparency", "True-Transparency",
                                                 "draw in two passes to improve transparency",
                                                 trueTransparency, G_PARAM_READWRITE |
                                                 G_PARAM_STATIC_STRINGS);
  g_object_class_install_property
    (G_OBJECT_CLASS(klass), TRANS_PROP, _properties[TRANS_PROP]);
  /**
   * VisuGl::stereo:
   *
   * Draw the scene differently in the right and the left buffer to
   * simulate stereo rendering.
   *
   * Since: 3.8
   */
  _properties[STEREO_PROP] = g_param_spec_boolean("stereo", "Stereo",
                                                 "differenciate right and left buffer",
                                                 stereoStatus, G_PARAM_READWRITE |
                                                 G_PARAM_STATIC_STRINGS);
  g_object_class_install_property
    (G_OBJECT_CLASS(klass), STEREO_PROP, _properties[STEREO_PROP]);
  /**
   * VisuGl::stereo-angle:
   *
   * Angle used to separate the left and right buffers (in fact half).
   *
   * Since: 3.8
   */
  _properties[ANGLE_PROP] = g_param_spec_float("stereo-angle", "Stereo-angle",
                                               "angle between left and right buffers",
                                               -45.f, 45.f, stereoAngle,
                                               G_PARAM_READWRITE |
                                               G_PARAM_STATIC_STRINGS);
  g_object_class_install_property
    (G_OBJECT_CLASS(klass), ANGLE_PROP, _properties[ANGLE_PROP]);
  /**
   * VisuGl::mode:
   *
   * Global rendering mode.
   *
   * Since: 3.8
   */
  _properties[MODE_PROP] = g_param_spec_uint("mode", "Mode",
                                             "global rendering mode",
                                             0, VISU_GL_RENDERING_N_MODES - 1,
                                             VISU_GL_RENDERING_SMOOTH,
                                             G_PARAM_READWRITE |
                                             G_PARAM_STATIC_STRINGS);
  g_object_class_install_property
    (G_OBJECT_CLASS(klass), MODE_PROP, _properties[MODE_PROP]);
}

static void visu_gl_init(VisuGl *self)
{
  DBG_fprintf(stderr, "Visu Gl: initializing a new object (%p).\n",
	      (gpointer)self);
  self->priv = visu_gl_get_instance_private(self);

  self->priv->currentLights = (VisuGlLights*)0;
  self->priv->antialias     = antialias;
  self->priv->immediate     = immediate;
  self->priv->trueTransparency = trueTransparency;
  self->priv->stereoStatus  = stereoStatus;
  self->priv->stereoAngle   = stereoAngle;
  self->priv->mode          = renderingOption;
  self->priv->hints         = 0;

  g_signal_connect_object(VISU_CONFIG_FILE_PARAMETER, "parsed::" FLAG_PARAMETER_OPENGL_ANTIALIAS,
                          G_CALLBACK(onEntryAntialias), (gpointer)self, G_CONNECT_SWAPPED);
  g_signal_connect_object(VISU_CONFIG_FILE_PARAMETER, "parsed::" FLAG_PARAMETER_OPENGL_IMMEDIATE,
                          G_CALLBACK(onEntryImmediate), (gpointer)self, G_CONNECT_SWAPPED);
  g_signal_connect_object(VISU_CONFIG_FILE_PARAMETER, "parsed::" FLAG_PARAMETER_OPENGL_TRANS,
                          G_CALLBACK(onEntryTrans), (gpointer)self, G_CONNECT_SWAPPED);
  g_signal_connect_object(VISU_CONFIG_FILE_PARAMETER, "parsed::" FLAG_PARAMETER_OPENGL_STEREO,
                          G_CALLBACK(onEntryStereo), (gpointer)self, G_CONNECT_SWAPPED);
  g_signal_connect_object(VISU_CONFIG_FILE_PARAMETER, "parsed::" FLAG_PARAMETER_OPENGL_ANGLE,
                          G_CALLBACK(onEntryAngle), (gpointer)self, G_CONNECT_SWAPPED);
  g_signal_connect_object(VISU_CONFIG_FILE_PARAMETER, "parsed::" FLAG_PARAMETER_OPENGL_RENDERING,
                          G_CALLBACK(onEntryMode), (gpointer)self, G_CONNECT_SWAPPED);

  if (!defaultGl)
    defaultGl = self;
}

static void visu_gl_get_property(GObject* obj, guint property_id,
                                 GValue *value, GParamSpec *pspec)
{
  VisuGl *self = VISU_GL(obj);

  DBG_fprintf(stderr, "Visu Gl: get property '%s' -> ",
	      g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case LIGHTS_PROP:
      DBG_fprintf(stderr, "%p.\n", (gpointer)self->priv->currentLights);
      g_value_set_boxed(value, self->priv->currentLights);
      break;
    case ANTIALIAS_PROP:
      DBG_fprintf(stderr, "%d.\n", self->priv->antialias);
      g_value_set_boolean(value, self->priv->antialias);
      break;
    case IMMEDIATE_PROP:
      DBG_fprintf(stderr, "%d.\n", self->priv->immediate);
      g_value_set_boolean(value, self->priv->immediate);
      break;
    case TRANS_PROP:
      DBG_fprintf(stderr, "%d.\n", self->priv->trueTransparency);
      g_value_set_boolean(value, self->priv->trueTransparency);
      break;
    case STEREO_PROP:
      DBG_fprintf(stderr, "%d.\n", self->priv->stereoStatus);
      g_value_set_boolean(value, self->priv->stereoStatus);
      break;
    case ANGLE_PROP:
      DBG_fprintf(stderr, "%g.\n", self->priv->stereoAngle);
      g_value_set_float(value, self->priv->stereoAngle);
      break;
    case MODE_PROP:
      DBG_fprintf(stderr, "%d.\n", self->priv->mode);
      g_value_set_uint(value, self->priv->mode);
      break;
    default:
      /* We don't have any other property... */
      G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, property_id, pspec);
      break;
    }
}
static void visu_gl_set_property(GObject* obj, guint property_id,
                                 const GValue *value, GParamSpec *pspec)
{
  VisuGl *self = VISU_GL(obj);

  DBG_fprintf(stderr, "Visu Gl: set property '%s' -> ",
	      g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case ANTIALIAS_PROP:
      DBG_fprintf(stderr, "%d.\n", g_value_get_boolean(value));
      visu_gl_setAntialias(self, g_value_get_boolean(value));
      break;
    case IMMEDIATE_PROP:
      DBG_fprintf(stderr, "%d.\n", g_value_get_boolean(value));
      visu_gl_setImmediate(self, g_value_get_boolean(value));
      break;
    case TRANS_PROP:
      DBG_fprintf(stderr, "%d.\n", g_value_get_boolean(value));
      visu_gl_setTrueTransparency(self, g_value_get_boolean(value));
      break;
    case STEREO_PROP:
      DBG_fprintf(stderr, "%d.\n", g_value_get_boolean(value));
      visu_gl_setStereo(self, g_value_get_boolean(value));
      break;
    case ANGLE_PROP:
      DBG_fprintf(stderr, "%g.\n", g_value_get_float(value));
      visu_gl_setStereoAngle(self, g_value_get_float(value));
      break;
    case MODE_PROP:
      DBG_fprintf(stderr, "%d.\n", g_value_get_uint(value));
      visu_gl_setMode(self, g_value_get_uint(value));
      break;
    default:
      /* We don't have any other property... */
      G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, property_id, pspec);
      break;
    }
}

/**
 * visu_gl_getLights:
 * @gl: a #VisuGl object.
 *
 * V_Sim proposes a wrapper around the OpenGL light definitions.
 *
 * Returns: the set of current lights.
 */
VisuGlLights* visu_gl_getLights(VisuGl *gl)
{
  g_return_val_if_fail(VISU_IS_GL(gl), (VisuGlLights*)0);

  DBG_fprintf(stderr, "lights %p\n", (gpointer)gl->priv->currentLights);
  if (!gl->priv->currentLights)
    {
      /* Deals with lights. */
      gl->priv->currentLights = visu_gl_lights_new();
      visu_gl_lights_add(gl->priv->currentLights, visu_gl_light_newDefault());
    }

  return gl->priv->currentLights;
}

/**
 * visu_gl_applyLights:
 * @gl: a #VisuGl object.
 *
 * If @gl has some defined lights, it setup the OpenGL context with
 * them and notify the "lights" parameter.
 *
 * Since: 3.8
 **/
void visu_gl_applyLights(VisuGl *gl)
{
  g_return_if_fail(VISU_IS_GL(gl));

  if (gl->priv->currentLights)
    {
      visu_gl_lights_apply(gl->priv->currentLights);
      g_object_notify_by_pspec(G_OBJECT(gl), _properties[LIGHTS_PROP]);
    }
}

/******************************************************************************/

/**
 * visu_gl_setColor:
 * @gl: a #VisuGl object.
 * @material: (array fixed-size=5): a 5 elements array with the material properties ;
 * @rgba: (array fixed-size=4): a 4 elements array with the color values.
 *
 * This method call glMaterial to create the right shiningness, emission, diffuse...
 */
void visu_gl_setColor(VisuGl *gl _U_, const float* material, const float* rgba)
{
  float mm[4] = {0.0f, 0.0f, 0.0f, 0.0f};

  g_return_if_fail(material && rgba);
  DBG_fprintf(stderr, "OpenGL: set rgba colours %gx%gx%gx%g.\n",
              rgba[0], rgba[1], rgba[2], rgba[3]);
  glColor4fv(rgba);

  mm[3] = rgba[3];
  mm[0] = material[TOOL_MATERIAL_AMB] * rgba[0];
  mm[1] = material[TOOL_MATERIAL_AMB] * rgba[1];
  mm[2] = material[TOOL_MATERIAL_AMB] * rgba[2];
  glMaterialfv(GL_FRONT, GL_AMBIENT, mm);
  mm[0] = material[TOOL_MATERIAL_DIF] * rgba[0];
  mm[1] = material[TOOL_MATERIAL_DIF] * rgba[1];
  mm[2] = material[TOOL_MATERIAL_DIF] * rgba[2];
  glMaterialfv(GL_FRONT, GL_DIFFUSE, mm);
  glMaterialf(GL_FRONT, GL_SHININESS, material[TOOL_MATERIAL_SHI] * 128.0f);
  mm[0] = material[TOOL_MATERIAL_SPE];
  mm[1] = material[TOOL_MATERIAL_SPE];
  mm[2] = material[TOOL_MATERIAL_SPE];
  glMaterialfv(GL_FRONT, GL_SPECULAR, mm);
  mm[0] = material[TOOL_MATERIAL_EMI] * rgba[0];
  mm[1] = material[TOOL_MATERIAL_EMI] * rgba[1];
  mm[2] = material[TOOL_MATERIAL_EMI] * rgba[2];
  glMaterialfv(GL_FRONT, GL_EMISSION, mm);
}
/**
 * visu_gl_setHighlightColor:
 * @gl: a #VisuGl object.
 * @material: a 5 elements array with the material properties ;
 * @rgb: a 3 elements array with the color values.
 * @alpha: the alpha channel.
 *
 * This method try to set a colour that will contrast with @rgb.
 */
void visu_gl_setHighlightColor(VisuGl *gl, const float material[5],
                               const float rgb[3], float alpha)
{
  float rgba[4], hsl[3];
  
  tool_color_convertRGBtoHSL(hsl, rgb);
  hsl[0] = tool_modulo_float(0.5f + hsl[0], 1);
  hsl[1] = 1.f;
  hsl[2] = .5f;
  tool_color_convertHSLtoRGB(rgba, hsl);
  rgba[3] = alpha;
  visu_gl_setColor(gl, material, rgba);
}
/**
 * visu_gl_drawArrow:
 * @gl: a #VisuGl object.
 * @origin: (array fixed-size=3): Position of the centre of the arrow.
 * @vect: (array fixed-size=3): Vector coordinates.
 *
 * Draw an arrow defined by @vect centred at @origin. For a lower
 * level function, see visu_gl_drawSmoothArrow().
 *
 * Since: 3.8
 **/
void visu_gl_drawArrow(VisuGl *gl _U_, const gfloat origin[3], const gfloat vect[3])
{
  GLUquadricObj *obj;
  gfloat sph[3];

  obj = gluNewQuadric();

  tool_matrix_cartesianToSpherical(sph, vect);

  DBG_fprintf(stderr, "OpenGL: draw an arrow at (%g, %g, %g) of size (%g, %g, %g)\n",
              origin[0], origin[1], origin[2], vect[0], vect[1], vect[2]);

  glPushMatrix();
  glTranslatef(origin[0], origin[1], origin[2]);
  glRotated(sph[TOOL_MATRIX_SPHERICAL_PHI], 0, 0, 1);
  glRotated(sph[TOOL_MATRIX_SPHERICAL_THETA], 0, 1, 0);
  visu_gl_drawSmoothArrow(obj, VISU_GL_ARROW_CENTERED,
                          sph[TOOL_MATRIX_SPHERICAL_MODULUS] * 0.6,
                          sph[TOOL_MATRIX_SPHERICAL_MODULUS] * 0.1,
                          50, NULL,
                          sph[TOOL_MATRIX_SPHERICAL_MODULUS] * 0.4,
                          sph[TOOL_MATRIX_SPHERICAL_MODULUS] * 0.15,
                          50, NULL);
  glPopMatrix();

  gluDeleteQuadric(obj);
}

static void glInitContext(VisuGl *gl)
{
  g_return_if_fail(VISU_IS_GL(gl));

  /* Set the openGL flags. */
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);
  glDepthRange(0.0, 1.0);
  glClearDepth(1.0);

  glEnable(GL_CULL_FACE);
  glCullFace(GL_BACK);

  glEnable(GL_NORMALIZE);

  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  visu_gl_lights_apply(visu_gl_getLights(gl));
  visu_gl_rendering_applyMode(gl->priv->mode);

  glSetAntiAlias(gl->priv);
}

/**
 * visu_gl_initContext:
 * @gl: a #VisuGl object.
 *
 * This method is called when an OpenGL surface is created for the first time.
 * It sets basic OpenGL options and calls other OpenGLFunctions used in V_Sim.
 */
void visu_gl_initContext(VisuGl *gl)
{
  VisuGlClass *klass = VISU_GL_GET_CLASS(gl);
  g_return_if_fail(klass && klass->initContext);
  
  klass->initContext(gl);
}

/******************************************************************************/

/* To set the antialiasing on lines. */
static void glSetAntiAlias(VisuGlPrivate *gl)
{
  if (gl->antialias)
    {
      /* Set blend if not present */
      glEnable(GL_BLEND);
      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
/*       glBlendFunc(GL_SRC_ALPHA_SATURATE,GL_ONE); */

      /* Antialias */
      glEnable(GL_LINE_SMOOTH);
      glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
    }
  else
    {
      glDisable(GL_LINE_SMOOTH);
/*       glDisable(GL_BLEND); */
    }
}
/**
 * visu_gl_setAntialias:
 * @gl: a #VisuGl object.
 * @value: a boolean to activate or not the lines antialias.
 *
 * To set the antialiasing on lines.
 *
 * Returns: TRUE if value is actually changed.
 */
gboolean visu_gl_setAntialias(VisuGl *gl, gboolean value)
{
  g_return_val_if_fail(VISU_IS_GL(gl), FALSE);

  if (value == gl->priv->antialias)
    return FALSE;
  gl->priv->antialias = value;
  g_object_notify_by_pspec(G_OBJECT(gl), _properties[ANTIALIAS_PROP]);

  glSetAntiAlias(gl->priv);
  
  return TRUE;
}
/**
 * visu_gl_getAntialias:
 * @gl: a #VisuGl object.
 *
 * Get the value of the antialiasing parameter.
 *
 * Returns: wether or not the antialising for lines is activated.
 */
gboolean visu_gl_getAntialias(const VisuGl *gl)
{
  g_return_val_if_fail(VISU_IS_GL(gl), FALSE);
  return gl->priv->antialias;
}

/**
 * visu_gl_setImmediate:
 * @gl: a #VisuGl object.
 * @value: a boolean to set or not the immediateDrawing option.
 *
 * If true all changes are applied only when the refresh button
 * is pushed.
 *
 * Returns: TRUE if the value is changed.
 */
gboolean visu_gl_setImmediate(VisuGl *gl, gboolean value)
{
  g_return_val_if_fail(VISU_IS_GL(gl), FALSE);

  if (value == gl->priv->immediate)
    return FALSE;
  gl->priv->immediate = value;
  g_object_notify_by_pspec(G_OBJECT(gl), _properties[IMMEDIATE_PROP]);

  return TRUE;
}
/**
 * visu_gl_getImmediate:
 * @gl: a #VisuGl object.
 *
 * Get the value of the immediateDrawing option.
 *
 * Returns: the value of the immediateDrawing option.
 */
gboolean visu_gl_getImmediate(const VisuGl *gl)
{
  g_return_val_if_fail(VISU_IS_GL(gl), FALSE);
  return gl->priv->immediate;
}
/**
 * visu_gl_getStereoCapability:
 * @gl: a #VisuGl object.
 *
 * Retrieve if the OpenGL window can render in stereo or not.
 *
 * Returns: TRUE if the OpenGL surface can draw in stereo.
 */
gboolean visu_gl_getStereoCapability(const VisuGl *gl _U_)
{
  GLboolean glStereo;

  glGetBooleanv(GL_STEREO, &glStereo);

  return (gboolean)glStereo;
}
/**
 * visu_gl_setTrueTransparency:
 * @gl: a #VisuGl object.
 * @status: a boolean.
 *
 * If true the rendering is done twice to respect the transparency.
 *
 * Returns: TRUE if redraw should be done.
 */
gboolean visu_gl_setTrueTransparency(VisuGl *gl, gboolean status)
{
  g_return_val_if_fail(VISU_IS_GL(gl), FALSE);

  if (status == gl->priv->trueTransparency)
    return FALSE;
  gl->priv->trueTransparency = status;  
  g_object_notify_by_pspec(G_OBJECT(gl), _properties[TRANS_PROP]);

  return TRUE;
}
/**
 * visu_gl_getTrueTransparency:
 * @gl: a #VisuGl object.
 *
 * The drawing can be done in one pass or two to respect transparency.
 *
 * Returns: TRUE if the drawing is done twice.
 */
gboolean visu_gl_getTrueTransparency(const VisuGl *gl)
{
  g_return_val_if_fail(VISU_IS_GL(gl), FALSE);
  return gl->priv->trueTransparency;
}
/**
 * visu_gl_setStereoAngle:
 * @gl: a #VisuGl object.
 * @angle: a positive floating point value.
 *
 * Change the angle of the eyes in the stereo output.
 *
 * Returns: TRUE if redraw should be done.
 */
gboolean visu_gl_setStereoAngle(VisuGl *gl, float angle)
{
  g_return_val_if_fail(VISU_IS_GL(gl), FALSE);
  g_return_val_if_fail(angle > 0.f, FALSE);

  if (gl->priv->stereoAngle == angle)
    return FALSE;
  gl->priv->stereoAngle = angle;
  g_object_notify_by_pspec(G_OBJECT(gl), _properties[ANGLE_PROP]);

  return TRUE;
}
/**
 * visu_gl_getStereoAngle:
 * @gl: a #VisuGl object.
 *
 * Retrieve the angle of the eyes in the stereo output.
 *
 * Returns: the angle.
 */
float visu_gl_getStereoAngle(const VisuGl *gl)
{
  g_return_val_if_fail(VISU_IS_GL(gl), 0.f);
  return gl->priv->stereoAngle;
}
/**
 * visu_gl_setStereo:
 * @gl: a #VisuGl object.
 * @status: a boolean.
 *
 * Change the type of rendering. The surface can be switch to stereo,
 * only if the OpenGL has stereo capabilities (see
 * visu_gl_getStereoCapability()).
 */
gboolean visu_gl_setStereo(VisuGl *gl, gboolean status)
{
  g_return_val_if_fail(VISU_IS_GL(gl), FALSE);

  if (gl->priv->stereoStatus == status)
    return FALSE;
  gl->priv->stereoStatus = status;
  g_object_notify_by_pspec(G_OBJECT(gl), _properties[STEREO_PROP]);

  return TRUE;
}
/**
 * visu_gl_getStereo:
 * @gl: a #VisuGl object.
 *
 * Retrieve the status of the OpenGL surface.
 *
 * Returns: TRUE if the surface try to draw in stereo (may be TRUE,
 *          even if visu_gl_getStereoCapability() returns FALSE, in
 *          that case the stereo capability is not used).
 */
gboolean visu_gl_getStereo(const VisuGl *gl)
{
  g_return_val_if_fail(VISU_IS_GL(gl), FALSE);
  return gl->priv->stereoStatus;
}
/**
 * visu_gl_setMode:
 * @gl: a #VisuGl object.
 * @value: an integer to represent the method of rendering.
 *
 * This function change the value of the parameter renderingOption.
 * It controls how V_Sim renders objects, in wireframe for example.
 *
 * Returns: TRUE if value is actually changed.
 */
gboolean visu_gl_setMode(VisuGl *gl, VisuGlRenderingMode value)
{
  g_return_val_if_fail(VISU_IS_GL(gl), FALSE);
  g_return_val_if_fail(value < VISU_GL_RENDERING_N_MODES, FALSE);
  
  if (value == gl->priv->mode)
    return FALSE;

  gl->priv->mode = value;
  g_object_notify_by_pspec(G_OBJECT(gl), _properties[MODE_PROP]);
  visu_gl_rendering_applyMode(value);

  return TRUE;
}
/**
 * visu_gl_getMode:
 * @gl: a #VisuGl object.
 *
 * This function retrieve the value of the parameter renderingOption.
 *
 * Returns: the identifier of the current rendering option.
 */
VisuGlRenderingMode visu_gl_getMode(const VisuGl *gl)
{
  g_return_val_if_fail(VISU_IS_GL(gl), renderingOption);
  return gl->priv->mode;
}
/**
 * visu_gl_addHint:
 * @gl: a #VisuGl object.
 * @value: a mask of hints.
 *
 * Set some additional hints to @gl.
 *
 * Since: 3.8
 *
 * Returns: the mask of current hints.
 **/
guint visu_gl_addHint(VisuGl *gl, guint value)
{
  g_return_val_if_fail(VISU_IS_GL(gl), 0);
  
  return (gl->priv->hints |= value);
}
/**
 * visu_gl_getHint:
 * @gl: a #VisuGl object.
 *
 * Retrieve hints of @gl.
 *
 * Since: 3.8
 *
 * Returns: the mask of current hints.
 **/
guint visu_gl_getHint(VisuGl *gl)
{
  g_return_val_if_fail(VISU_IS_GL(gl), 0);
  
  return gl->priv->hints;
}

/***************************/
/* Dealing with parameters */
/***************************/
static void onEntryAntialias(VisuGl *self, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_setAntialias(self, antialias);
}
static void onEntryImmediate(VisuGl *self, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_setImmediate(self, immediate);
}
static void onEntryTrans(VisuGl *self, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_setTrueTransparency(self, trueTransparency);
}
static void onEntryStereo(VisuGl *self, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_setStereo(self, stereoStatus);
}
static void onEntryAngle(VisuGl *self, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_setStereoAngle(self, stereoAngle);
}
static void onEntryMode(VisuGl *self, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_setMode(self, renderingOption);
}
static void exportParametersOpenGL(GString *data,
                                   VisuData *dataObj _U_)
{
  g_string_append_printf(data, "# %s\n", DESC_PARAMETER_OPENGL_ANTIALIAS);
  g_string_append_printf(data, "%s: %d\n\n", FLAG_PARAMETER_OPENGL_ANTIALIAS,
	  defaultGl->priv->antialias);
  g_string_append_printf(data, "# %s\n", DESC_PARAMETER_OPENGL_IMMEDIATE);
  g_string_append_printf(data, "%s: %d\n\n", FLAG_PARAMETER_OPENGL_IMMEDIATE,
	  defaultGl->priv->immediate);
  g_string_append_printf(data, "# %s\n", DESC_PARAMETER_OPENGL_TRANSS);
  g_string_append_printf(data, "%s: %d\n\n", FLAG_PARAMETER_OPENGL_TRANS,
	  defaultGl->priv->trueTransparency);
  g_string_append_printf(data, "# %s\n", DESC_PARAMETER_OPENGL_STEREO);
  g_string_append_printf(data, "%s: %d\n\n", FLAG_PARAMETER_OPENGL_STEREO,
	  defaultGl->priv->stereoStatus);
  g_string_append_printf(data, "# %s\n", DESC_PARAMETER_OPENGL_ANGLE);
  g_string_append_printf(data, "%s: %f\n\n", FLAG_PARAMETER_OPENGL_ANGLE,
	  defaultGl->priv->stereoAngle);
}
static void exportOpenGL(GString *data, VisuData *dataObj _U_)
{
  visu_config_file_exportComment(data, DESC_RESOURCE_OPENGL_RENDERING);
  visu_config_file_exportEntry(data, FLAG_RESOURCE_OPENGL_RENDERING, NULL,
                               "%s", visu_gl_rendering_getAllModes()[defaultGl->priv->mode]);
  visu_config_file_exportComment(data, "");
}
