/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Damien
	CALISTE, laboratoire L_Sim, (2015)
  
	Adresse 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 : Damien
	CALISTE, laboratoire L_Sim, (2015)

	E-mail address:
	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_extset.h"

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

#include "opengl.h"
#include "visu_tools.h"
#include "iface_boxed.h"
#include "visu_configFile.h"
#include "openGLFunctions/objectList.h"
#include "coreTools/toolConfigFile.h"
#include "OSOpenGL/visu_openGL.h"

#include "extensions/mapset.h"

/**
 * SECTION:visu_extset
 * @short_description: Defines a storage object to handle a bunch of
 * #VisuGlExt objects.
 *
 * <para>A storage to display several #VisuGlExt objects. It takes
 * care of ordering display, following priority of each object.</para>
 */

/* Parameters & resources*/
/* 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 ; four floating point values (0. <= v <= 1.)"
static float bgRGBDefault[4] = {0., 0., 0., 1.};

/* 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)"
static gboolean fogActiveDefault = TRUE;

#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)"
static gboolean fogSpecificDefault = FALSE;

#define FLAG_RESOURCE_FOG_COLOR   "fog_specific_color"
#define DESC_RESOURCE_FOG_COLOR   "Define the color of the fog ; four floating point values (0. <= v <= 1.)"
static float fogRGBDefault[4] = {0.f, 0.f, 0.f, 1.f};

#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.)"
static float fogStartEndDefault[2] = {0.3f, 0.7f};

struct _GlExt {
  VisuGlExt *ext;
  gulong priority_sig, dirty_sig, active_sig;
};

struct _VisuGlExtSetPrivate
{
  gboolean dispose_has_run;

  /* A list to store all the available OpenGL extensions. */
  GArray *set;
  gboolean reorderingNeeded, dirty;
  guint dirtyPending;

  /* The view extensions are rendered on. */
  VisuGlView *view;
  gulong widthHeight_signal, chg_signal;

  /* Handling the background color and the fog. */
  float bgRGB[4];
  int chessList;
  gboolean bgDirty;
  gboolean fogActive;
  float fogStartEnd[2];
  gboolean fogFollowsBg;
  float fogRGB[4];
};

enum
  {
    PROP_0,
    BG_R_PROP,
    BG_G_PROP,
    BG_B_PROP,
    BG_A_PROP,
    FOG_ACTIVE_PROP,
    FOG_START_PROP,
    FOG_FULL_PROP,
    FOG_FOLLOWS_PROP,
    FOG_R_PROP,
    FOG_G_PROP,
    FOG_B_PROP,
    FOG_A_PROP,
    DIRTY_PROP,
    N_PROP
  };
static GParamSpec *properties[N_PROP];

static VisuGlExtSet *defaultSet = NULL;
static GLuint texName = 0;

static void visu_gl_ext_set_dispose     (GObject* obj);
static void visu_gl_ext_set_finalize    (GObject* obj);
static void visu_gl_ext_set_get_property(GObject* obj, guint property_id,
                                         GValue *value, GParamSpec *pspec);
static void visu_gl_ext_set_set_property(GObject* obj, guint property_id,
                                         const GValue *value, GParamSpec *pspec);
static void visu_gl_ext_initContext     (VisuGl *gl);

/* Local callbacks */
static void onWidthHeight(VisuGlView *view, gpointer data);
static void onCamera(VisuGlView *view, gpointer data);
static void onEntryBgColor(VisuGlExtSet *set, VisuConfigFileEntry *entry, VisuConfigFile *obj);
static void onEntryFogActive(VisuGlExtSet *set, VisuConfigFileEntry *entry, VisuConfigFile *obj);
static void onEntryFogSpecific(VisuGlExtSet *set, VisuConfigFileEntry *entry, VisuConfigFile *obj);
static void onEntryFogColor(VisuGlExtSet *set, VisuConfigFileEntry *entry, VisuConfigFile *obj);
static void onEntryFogStartEnd(VisuGlExtSet *set, VisuConfigFileEntry *entry, VisuConfigFile *obj);

static void _appendDirty(VisuGlExtSet *set);
static void _chessDraw(VisuGlExtSet *set);
static void exportResources(GString *data, VisuData *dataObj);

G_DEFINE_TYPE_WITH_CODE(VisuGlExtSet, visu_gl_ext_set, VISU_TYPE_GL,
                        G_ADD_PRIVATE(VisuGlExtSet))

static void visu_gl_ext_set_class_init(VisuGlExtSetClass *klass)
{
  float rgColor[2] = {0.f, 1.f};

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

  /* Parameters */
  visu_config_file_addFloatArrayEntry(VISU_CONFIG_FILE_RESOURCE,
                                      FLAG_RESOURCE_BG_COLOR,
                                      DESC_RESOURCE_BG_COLOR,
                                      4, bgRGBDefault, rgColor, FALSE);
  visu_config_file_addBooleanEntry(VISU_CONFIG_FILE_RESOURCE,
                                   FLAG_RESOURCE_FOG_USED,
                                   DESC_RESOURCE_FOG_USED,
                                   &fogActiveDefault, FALSE);
  visu_config_file_addBooleanEntry(VISU_CONFIG_FILE_RESOURCE,
                                   FLAG_RESOURCE_FOG_SPECIFIC,
                                   DESC_RESOURCE_FOG_SPECIFIC,
                                   &fogSpecificDefault, FALSE);
  visu_config_file_addFloatArrayEntry(VISU_CONFIG_FILE_RESOURCE,
                                      FLAG_RESOURCE_FOG_COLOR,
                                      DESC_RESOURCE_FOG_COLOR,
                                      4, fogRGBDefault, rgColor, FALSE);
  visu_config_file_addFloatArrayEntry(VISU_CONFIG_FILE_RESOURCE,
                                      FLAG_RESOURCE_FOG_STARTEND,
                                      DESC_RESOURCE_FOG_STARTEND,
                                      2, fogStartEndDefault, rgColor, FALSE);
  visu_config_file_addExportFunction(VISU_CONFIG_FILE_RESOURCE, exportResources);

  /* Connect the overloading methods. */
  G_OBJECT_CLASS(klass)->dispose  = visu_gl_ext_set_dispose;
  G_OBJECT_CLASS(klass)->finalize = visu_gl_ext_set_finalize;
  G_OBJECT_CLASS(klass)->set_property = visu_gl_ext_set_set_property;
  G_OBJECT_CLASS(klass)->get_property = visu_gl_ext_set_get_property;
  VISU_GL_CLASS(klass)->initContext = visu_gl_ext_initContext;
  
  /**
   * VisuGlExtSet::dirty:
   *
   * TRUE when at least one of the active #VisuGlExt gets dirty.
   *
   * Since: 3.8
   */
  properties[DIRTY_PROP] = g_param_spec_boolean("dirty", "Dirty",
                                                "one of the object rendering is out of date",
                                                FALSE, G_PARAM_READABLE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), DIRTY_PROP, properties[DIRTY_PROP]);
  /**
   * VisuGlExtSet::bg-red:
   *
   * Store the red channel of the background color.
   *
   * Since: 3.8
   */
  properties[BG_R_PROP] = g_param_spec_float("bg-red", "red channel",
                                             "background red channel",
                                             0., 1., 0., G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), BG_R_PROP,
				  properties[BG_R_PROP]);
  /**
   * VisuGlExtSet::bg-green:
   *
   * Store the green channel of the background color.
   *
   * Since: 3.8
   */
  properties[BG_G_PROP] = g_param_spec_float("bg-green", "green channel",
                                             "background green channel",
                                             0., 1., 0., G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), BG_G_PROP,
				  properties[BG_G_PROP]);
  /**
   * VisuGlExtSet::bg-blue:
   *
   * Store the blue channel of the background color.
   *
   * Since: 3.8
   */
  properties[BG_B_PROP] = g_param_spec_float("bg-blue", "blue channel",
                                             "background blue channel",
                                             0., 1., 0., G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), BG_B_PROP,
				  properties[BG_B_PROP]);
  /**
   * VisuGlExtSet::bg-alpha:
   *
   * Store the alpha channel of the background color.
   *
   * Since: 3.8
   */
  properties[BG_A_PROP] = g_param_spec_float("bg-alpha", "alpha channel",
                                             "background alpha channel",
                                             0., 1., 0., G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), BG_A_PROP,
				  properties[BG_A_PROP]);
  /**
   * VisuGlExtSet::fog-active:
   *
   * Store if the fog is used.
   *
   * Since: 3.8
   */
  properties[FOG_ACTIVE_PROP] = g_param_spec_boolean("fog-active", "Fog active",
                                                      "Fog is used",
                                                      TRUE, G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), FOG_ACTIVE_PROP,
				  properties[FOG_ACTIVE_PROP]);
  /**
   * VisuGlExtSet::fog-start:
   *
   * Store the starting depth of the fog.
   *
   * Since: 3.8
   */
  properties[FOG_START_PROP] = g_param_spec_float("fog-start", "Fog start",
                                                  "starting fog depth",
                                                  0., 1., 0.3, G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), FOG_START_PROP,
				  properties[FOG_START_PROP]);
  /**
   * VisuGlExtSet::fog-full:
   *
   * Store the depth where the fog hides all.
   *
   * Since: 3.8
   */
  properties[FOG_FULL_PROP] = g_param_spec_float("fog-full", "Fog full",
                                                  "depth where fog hides all",
                                                  0., 1., 0.7, G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), FOG_FULL_PROP,
				  properties[FOG_FULL_PROP]);
  /**
   * VisuGlExtSet::fog-follows-bg:
   *
   * Store if the fog follows the background color.
   *
   * Since: 3.8
   */
  properties[FOG_FOLLOWS_PROP] = g_param_spec_boolean("fog-follows-bg", "Fog follows bg",
                                                      "Fog color is the bg color",
                                                      TRUE, G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), FOG_FOLLOWS_PROP,
				  properties[FOG_FOLLOWS_PROP]);
  /**
   * VisuGlExtSet::fog-red:
   *
   * Store the red channel of the specific fog color.
   *
   * Since: 3.8
   */
  properties[FOG_R_PROP] = g_param_spec_float("fog-red", "red channel",
                                              "specific fog red channel",
                                              0., 1., 0., G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), FOG_R_PROP,
				  properties[FOG_R_PROP]);
  /**
   * VisuGlExtSet::fog-green:
   *
   * Store the green channel of the specific fog color.
   *
   * Since: 3.8
   */
  properties[FOG_G_PROP] = g_param_spec_float("fog-green", "green channel",
                                              "specific fog green channel",
                                              0., 1., 0., G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), FOG_G_PROP,
				  properties[FOG_G_PROP]);
  /**
   * VisuGlExtSet::fog-blue:
   *
   * Store the blue channel of the specific fog color.
   *
   * Since: 3.8
   */
  properties[FOG_B_PROP] = g_param_spec_float("fog-blue", "blue channel",
                                              "specific fog blue channel",
                                              0., 1., 0., G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), FOG_B_PROP,
				  properties[FOG_B_PROP]);
  /**
   * VisuGlExtSet::fog-alpha:
   *
   * Store the alpha channel of the specific fog color.
   *
   * Since: 3.8
   */
  properties[FOG_A_PROP] = g_param_spec_float("fog-alpha", "alpha channel",
                                              "specific fog alpha channel",
                                              0., 1., 1., G_PARAM_READWRITE);
  g_object_class_install_property(G_OBJECT_CLASS(klass), FOG_A_PROP,
				  properties[FOG_A_PROP]);

  visu_gl_objectlist_init();
}

static void visu_gl_ext_set_init(VisuGlExtSet *ext)
{
  DBG_fprintf(stderr, "Visu Extension Set: initializing a new object (%p).\n",
	      (gpointer)ext);
  ext->priv = visu_gl_ext_set_get_instance_private(ext);
  ext->priv->dispose_has_run = FALSE;

  ext->priv->set = g_array_new(FALSE, FALSE, sizeof(struct _GlExt));
  ext->priv->reorderingNeeded = FALSE;
  ext->priv->dirty = FALSE;
  ext->priv->dirtyPending = 0;
  ext->priv->view = (VisuGlView*)0;
  g_signal_connect(G_OBJECT(ext), "notify::lights",
                   G_CALLBACK(_appendDirty), (gpointer)0);
  g_signal_connect(G_OBJECT(ext), "notify::antialias",
                   G_CALLBACK(_appendDirty), (gpointer)0);
  g_signal_connect(G_OBJECT(ext), "notify::immediate",
                   G_CALLBACK(_appendDirty), (gpointer)0);
  g_signal_connect(G_OBJECT(ext), "notify::true-transparency",
                   G_CALLBACK(_appendDirty), (gpointer)0);
  g_signal_connect(G_OBJECT(ext), "notify::stereo",
                   G_CALLBACK(_appendDirty), (gpointer)0);
  g_signal_connect(G_OBJECT(ext), "notify::stereo-angle",
                   G_CALLBACK(_appendDirty), (gpointer)0);
  g_signal_connect(G_OBJECT(ext), "notify::mode",
                   G_CALLBACK(_appendDirty), (gpointer)0);

  ext->priv->bgRGB[0] = bgRGBDefault[0];
  ext->priv->bgRGB[1] = bgRGBDefault[1];
  ext->priv->bgRGB[2] = bgRGBDefault[2];
  ext->priv->bgRGB[3] = bgRGBDefault[3];
  g_signal_connect_object(VISU_CONFIG_FILE_RESOURCE, "parsed::" FLAG_RESOURCE_BG_COLOR,
                          G_CALLBACK(onEntryBgColor), (gpointer)ext, G_CONNECT_SWAPPED);
  ext->priv->chessList = visu_gl_objectlist_new(1);
  ext->priv->bgDirty = FALSE;

  ext->priv->fogActive      = fogActiveDefault;
  ext->priv->fogStartEnd[0] = fogStartEndDefault[0];
  ext->priv->fogStartEnd[1] = fogStartEndDefault[1];
  ext->priv->fogFollowsBg   = !fogSpecificDefault;
  ext->priv->fogRGB[0]      = fogRGBDefault[0];
  ext->priv->fogRGB[1]      = fogRGBDefault[1];
  ext->priv->fogRGB[2]      = fogRGBDefault[2];
  ext->priv->fogRGB[3]      = fogRGBDefault[3];
  g_signal_connect_object(VISU_CONFIG_FILE_RESOURCE, "parsed::" FLAG_RESOURCE_FOG_USED,
                          G_CALLBACK(onEntryFogActive), (gpointer)ext, G_CONNECT_SWAPPED);
  g_signal_connect_object(VISU_CONFIG_FILE_RESOURCE, "parsed::" FLAG_RESOURCE_FOG_SPECIFIC,
                          G_CALLBACK(onEntryFogSpecific), (gpointer)ext, G_CONNECT_SWAPPED);
  g_signal_connect_object(VISU_CONFIG_FILE_RESOURCE, "parsed::" FLAG_RESOURCE_FOG_COLOR,
                          G_CALLBACK(onEntryFogColor), (gpointer)ext, G_CONNECT_SWAPPED);
  g_signal_connect_object(VISU_CONFIG_FILE_RESOURCE, "parsed::" FLAG_RESOURCE_FOG_STARTEND,
                          G_CALLBACK(onEntryFogStartEnd), (gpointer)ext, G_CONNECT_SWAPPED);

  if (!defaultSet)
    defaultSet = ext;
}

/* This method can be called several times.
   It should unref all of its reference to
   GObjects. */
static void visu_gl_ext_set_dispose(GObject* obj)
{
  VisuGlExtSet *ext;
  guint i;
  struct _GlExt *s;
  gchar *name;

  DBG_fprintf(stderr, "Visu Extension Set: dispose object %p.\n", (gpointer)obj);

  ext = VISU_GL_EXT_SET(obj);
  if (ext->priv->dispose_has_run)
    return;
  ext->priv->dispose_has_run = TRUE;

  visu_gl_ext_set_setGlView(ext, (VisuGlView*)0);

  DBG_fprintf(stderr, "Visu Extension Set: releasing %d extensions.\n", ext->priv->set->len);
  for (i = 0; i < ext->priv->set->len; i++)
    {
      s = &g_array_index(ext->priv->set, struct _GlExt, i);
      if (DEBUG)
        {
          DBG_fprintf(stderr, "Visu Extension Set: releasing extension %p.\n",
                      (gpointer)s->ext);
          g_object_get(s->ext, "name", &name, NULL);
          DBG_fprintf(stderr, " | %s (%d)\n", name, G_OBJECT(s->ext)->ref_count);
          g_free(name);
        }
      g_signal_handler_disconnect(G_OBJECT(s->ext), s->priority_sig);
      g_signal_handler_disconnect(G_OBJECT(s->ext), s->dirty_sig);
      g_signal_handler_disconnect(G_OBJECT(s->ext), s->active_sig);
      g_object_unref(G_OBJECT(s->ext));
    }

  /* Chain up to the parent class */
  G_OBJECT_CLASS(visu_gl_ext_set_parent_class)->dispose(obj);
}
/* This method is called once only. */
static void visu_gl_ext_set_finalize(GObject* obj)
{
  VisuGlExtSetPrivate *ext;

  g_return_if_fail(obj);

  DBG_fprintf(stderr, "Visu Extension Set: finalize object %p.\n", (gpointer)obj);
  ext = VISU_GL_EXT_SET(obj)->priv;

  if (ext->dirtyPending)
    g_source_remove(ext->dirtyPending);
  g_array_free(ext->set, TRUE);
  glDeleteLists(ext->chessList, 1);

  /* Chain up to the parent class */
  DBG_fprintf(stderr, "Visu Extension Set: chain to parent.\n");
  G_OBJECT_CLASS(visu_gl_ext_set_parent_class)->finalize(obj);
  DBG_fprintf(stderr, "Visu Extension Set: freeing ... OK.\n");
}
static void visu_gl_ext_set_get_property(GObject* obj, guint property_id,
                                         GValue *value, GParamSpec *pspec)
{
  VisuGlExtSet *self = VISU_GL_EXT_SET(obj);

  DBG_fprintf(stderr, "Visu Extension Set: get property '%s' -> ",
	      g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case DIRTY_PROP:
      g_value_set_boolean(value, (self->priv->dirtyPending > 0));
      DBG_fprintf(stderr, "%d.\n", (self->priv->dirtyPending > 0));
      break;
    case BG_R_PROP:
      g_value_set_float(value, self->priv->bgRGB[0]);
      DBG_fprintf(stderr, "%g.\n", self->priv->bgRGB[0]);
      break;
    case BG_G_PROP:
      g_value_set_float(value, self->priv->bgRGB[1]);
      DBG_fprintf(stderr, "%g.\n", self->priv->bgRGB[1]);
      break;
    case BG_B_PROP:
      g_value_set_float(value, self->priv->bgRGB[2]);
      DBG_fprintf(stderr, "%g.\n", self->priv->bgRGB[2]);
      break;
    case BG_A_PROP:
      g_value_set_float(value, self->priv->bgRGB[3]);
      DBG_fprintf(stderr, "%g.\n", self->priv->bgRGB[3]);
      break;
    case FOG_ACTIVE_PROP:
      g_value_set_boolean(value, self->priv->fogActive);
      DBG_fprintf(stderr, "%d.\n", self->priv->fogActive);
      break;
    case FOG_START_PROP:
      g_value_set_float(value, self->priv->fogStartEnd[0]);
      DBG_fprintf(stderr, "%g.\n", self->priv->fogStartEnd[0]);
      break;
    case FOG_FULL_PROP:
      g_value_set_float(value, self->priv->fogStartEnd[1]);
      DBG_fprintf(stderr, "%g.\n", self->priv->fogStartEnd[1]);
      break;
    case FOG_FOLLOWS_PROP:
      g_value_set_boolean(value, self->priv->fogFollowsBg);
      DBG_fprintf(stderr, "%d.\n", self->priv->fogFollowsBg);
      break;
    case FOG_R_PROP:
      g_value_set_float(value, self->priv->fogRGB[0]);
      DBG_fprintf(stderr, "%g.\n", self->priv->fogRGB[0]);
      break;
    case FOG_G_PROP:
      g_value_set_float(value, self->priv->fogRGB[1]);
      DBG_fprintf(stderr, "%g.\n", self->priv->fogRGB[1]);
      break;
    case FOG_B_PROP:
      g_value_set_float(value, self->priv->fogRGB[2]);
      DBG_fprintf(stderr, "%g.\n", self->priv->fogRGB[2]);
      break;
    case FOG_A_PROP:
      g_value_set_float(value, self->priv->fogRGB[3]);
      DBG_fprintf(stderr, "%g.\n", self->priv->fogRGB[3]);
      break;
    default:
      /* We don't have any other property... */
      G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, property_id, pspec);
      break;
    }
}
static void visu_gl_ext_set_set_property(GObject* obj, guint property_id,
                                         const GValue *value, GParamSpec *pspec)
{
  VisuGlExtSet *self = VISU_GL_EXT_SET(obj);
  float rgba[4], startEnd[2];

  DBG_fprintf(stderr, "Visu Extension Set: set property '%s' -> ",
	      g_param_spec_get_name(pspec));
  switch (property_id)
    {
    case BG_R_PROP:
      rgba[0] = g_value_get_float(value);
      visu_gl_ext_set_setBgColor(self, rgba, TOOL_COLOR_MASK_R);
      DBG_fprintf(stderr, "%g.\n", self->priv->bgRGB[0]);
      break;
    case BG_G_PROP:
      rgba[1] = g_value_get_float(value);
      visu_gl_ext_set_setBgColor(self, rgba, TOOL_COLOR_MASK_G);
      DBG_fprintf(stderr, "%g.\n", self->priv->bgRGB[1]);
      break;
    case BG_B_PROP:
      rgba[2] = g_value_get_float(value);
      visu_gl_ext_set_setBgColor(self, rgba, TOOL_COLOR_MASK_B);
      DBG_fprintf(stderr, "%g.\n", self->priv->bgRGB[2]);
      break;
    case BG_A_PROP:
      rgba[3] = g_value_get_float(value);
      visu_gl_ext_set_setBgColor(self, rgba, TOOL_COLOR_MASK_A);
      DBG_fprintf(stderr, "%g.\n", self->priv->bgRGB[3]);
      break;
    case FOG_ACTIVE_PROP:
      visu_gl_ext_set_setFogActive(self, g_value_get_boolean(value));
      DBG_fprintf(stderr, "%d.\n", self->priv->fogActive);
      break;
    case FOG_START_PROP:
      startEnd[0] = g_value_get_float(value);
      visu_gl_ext_set_setFogStartFull(self, startEnd, VISU_GL_EXT_SET_FOG_MASK_START);
      DBG_fprintf(stderr, "%g.\n", self->priv->fogStartEnd[0]);
      break;
    case FOG_FULL_PROP:
      startEnd[1] = g_value_get_float(value);
      visu_gl_ext_set_setFogStartFull(self, startEnd, VISU_GL_EXT_SET_FOG_MASK_FULL);
      DBG_fprintf(stderr, "%g.\n", self->priv->fogStartEnd[1]);
      break;
    case FOG_FOLLOWS_PROP:
      visu_gl_ext_set_setFogFollowsBg(self, g_value_get_boolean(value));
      DBG_fprintf(stderr, "%d.\n", self->priv->fogFollowsBg);
      break;
    case FOG_R_PROP:
      rgba[0] = g_value_get_float(value);
      visu_gl_ext_set_setFogColor(self, rgba, TOOL_COLOR_MASK_R);
      DBG_fprintf(stderr, "%g.\n", self->priv->fogRGB[0]);
      break;
    case FOG_G_PROP:
      rgba[1] = g_value_get_float(value);
      visu_gl_ext_set_setFogColor(self, rgba, TOOL_COLOR_MASK_G);
      DBG_fprintf(stderr, "%g.\n", self->priv->fogRGB[1]);
      break;
    case FOG_B_PROP:
      rgba[2] = g_value_get_float(value);
      visu_gl_ext_set_setFogColor(self, rgba, TOOL_COLOR_MASK_B);
      DBG_fprintf(stderr, "%g.\n", self->priv->fogRGB[2]);
      break;
    case FOG_A_PROP:
      rgba[3] = g_value_get_float(value);
      visu_gl_ext_set_setFogColor(self, rgba, TOOL_COLOR_MASK_A);
      DBG_fprintf(stderr, "%g.\n", self->priv->fogRGB[3]);
      break;
    default:
      /* We don't have any other property... */
      G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, property_id, pspec);
      break;
    }
}
static void visu_gl_ext_initContext(VisuGl *gl)
{
  VisuGlExtSet *self = VISU_GL_EXT_SET(gl);
  guint i;

  g_return_if_fail(VISU_IS_GL_EXT_SET(self));
  
  VISU_GL_CLASS(visu_gl_ext_set_parent_class)->initContext(gl);

  if (self->priv->view)
    visu_gl_view_initContext(self->priv->view);
  for (i = 0; i < self->priv->set->len; i++)
    visu_gl_ext_rebuild(g_array_index(self->priv->set, struct _GlExt, i).ext);
}

/**
 * visu_gl_ext_set_new:
 *
 * Create an object to handle a set of #VisuGlExt objects and draw
 * them together.
 *
 * Since: 3.8
 *
 * Returns: (transfer full): a newly created #VisuGlExtSet object.
 **/
VisuGlExtSet* visu_gl_ext_set_new()
{
  VisuGlExtSet *set;

  set = VISU_GL_EXT_SET(g_object_new(VISU_TYPE_GL_EXT_SET, NULL));
  return set;
}

/**
 * visu_gl_ext_set_setGlView:
 * @set: a #VisuGlExtSet object.
 * @view: a #VisuGlView object.
 *
 * Apply the given @view on all #VisuGlExt objects stored in @set.
 *
 * Since: 3.8
 *
 * Returns: TRUE if the @view actually change.
 **/
gboolean visu_gl_ext_set_setGlView(VisuGlExtSet *set, VisuGlView *view)
{
  guint i;

  g_return_val_if_fail(VISU_IS_GL_EXT_SET(set), FALSE);

  if (set->priv->view == view)
    return FALSE;

  if (set->priv->view)
    {
      g_object_unref(G_OBJECT(set->priv->view));
      g_signal_handler_disconnect(G_OBJECT(set->priv->view), set->priv->widthHeight_signal);
      g_signal_handler_disconnect(G_OBJECT(set->priv->view), set->priv->chg_signal);
    }
  if (view)
    {
      g_object_ref(G_OBJECT(view));
      set->priv->widthHeight_signal =
        g_signal_connect(G_OBJECT(view), "WidthHeightChanged",
                         G_CALLBACK(onWidthHeight), (gpointer)set);
      set->priv->chg_signal =
        g_signal_connect(G_OBJECT(view), "changed",
                         G_CALLBACK(onCamera), (gpointer)set);
    }
  set->priv->view = view;

  for (i = 0; i < set->priv->set->len; i++)
    visu_gl_ext_setGlView(g_array_index(set->priv->set, struct _GlExt, i).ext, view);

  return TRUE;
}

/**
 * visu_gl_ext_set_getAll:
 * @set: a #VisuGlExtSet object.
 *
 * Retrieve as a #GList all the #VisuGlExt objects drawn by @set.
 *
 * Since: 3.8
 *
 * Returns: (transfer container) (element-type VisuGlExt*): only the
 * container list should be freed after.
 **/
GList* visu_gl_ext_set_getAll(VisuGlExtSet *set)
{
  GList *lst;
  guint i;

  g_return_val_if_fail(VISU_IS_GL_EXT_SET(set), (GList*)0);

  lst = (GList*)0;
  for (i = 0; i < set->priv->set->len; i++)
    lst = g_list_append(lst, g_array_index(set->priv->set, struct _GlExt, i).ext);
  return lst;
}

/**
 * visu_gl_ext_set_getByName:
 * @set: a #VisuGlExtSet object.
 * @name: a name to look for.
 *
 * Retrieve the #VisuGlExt object with @name that is stored in
 * @set. If several #VisuGlExt objects have the same name, the first
 * one is returned.
 *
 * Since: 3.8
 *
 * Returns: (transfer none): a #VisuGlExt with @name.
 **/
VisuGlExt* visu_gl_ext_set_getByName(const VisuGlExtSet *set, const gchar *name)
{
  guint i;

  g_return_val_if_fail(VISU_IS_GL_EXT_SET(set), (VisuGlExt*)0);

  for (i = 0; i < set->priv->set->len; i++)
    if (!strcmp(visu_gl_ext_getName(g_array_index(set->priv->set, struct _GlExt, i).ext), name))
      return g_array_index(set->priv->set, struct _GlExt, i).ext;
  return (VisuGlExt*)0;
}

static gboolean _emitDirty(gpointer data)
{
  /* if (!VISU_GL_EXT_SET(data)->priv->dirty) */
  /*   return FALSE; */
  g_object_notify_by_pspec(G_OBJECT(data), properties[DIRTY_PROP]);

  VISU_GL_EXT_SET(data)->priv->dirtyPending = 0;
  return FALSE;
}
static void _appendDirty(VisuGlExtSet *set)
{
  /* if (set->priv->dirtyPending) */
  /*   g_source_remove(set->priv->dirtyPending); */
  set->priv->dirty = TRUE;
  if (!set->priv->dirtyPending)
    set->priv->dirtyPending =
      g_idle_add_full(G_PRIORITY_HIGH_IDLE, _emitDirty, (gpointer)set, (GDestroyNotify)0);
}
static void onExtPriority(VisuGlExtSet *set)
{
  set->priv->reorderingNeeded = TRUE;
}
static void onExtDirty(VisuGlExtSet *set, GParamSpec *pspec _U_, VisuGlExt *ext)
{
  if (!visu_gl_ext_getActive(ext))
    return;
  DBG_fprintf(stderr, "Visu Extension Set: extension '%s' is dirty.\n",
              visu_gl_ext_getName(ext));
  _appendDirty(set);
}

/**
 * visu_gl_ext_set_add:
 * @set: a #VisuGlExtSet object.
 * @ext: a #VisuGlExt object.
 *
 * Add @ext in the list of drawn #VisuGlExt by @set.
 *
 * Since: 3.8
 *
 * Returns: TRUE if not already existing.
 **/
gboolean visu_gl_ext_set_add(VisuGlExtSet *set, VisuGlExt *ext)
{
  struct _GlExt s;
  guint i;

  g_return_val_if_fail(VISU_IS_GL_EXT_SET(set), FALSE);

  /* Lookup first for ext in the set. */
  for (i = 0; i < set->priv->set->len; i++)
    if (g_array_index(set->priv->set, struct _GlExt, i).ext == ext)
      return FALSE;

  g_object_ref(G_OBJECT(ext));
  s.ext = ext;
  s.priority_sig = g_signal_connect_swapped(G_OBJECT(ext), "notify::priority",
                                            G_CALLBACK(onExtPriority), set);
  s.dirty_sig = g_signal_connect_swapped(G_OBJECT(ext), "notify::dirty",
                                         G_CALLBACK(onExtDirty), set);
  s.active_sig = g_signal_connect_swapped(G_OBJECT(ext), "notify::active",
                                          G_CALLBACK(_appendDirty), set);
  if (set->priv->view)
    visu_gl_ext_setGlView(ext, set->priv->view);
  visu_gl_ext_setGlContext(ext, VISU_GL(set));

  set->priv->reorderingNeeded = TRUE;

  g_array_append_val(set->priv->set, s);

  if (VISU_GL_EXT_SET_GET_CLASS(set)->added)
    VISU_GL_EXT_SET_GET_CLASS(set)->added(set, ext);

  onExtDirty(set, NULL, ext);

  return TRUE;
}

/**
 * visu_gl_ext_set_remove:
 * @set: a #VisuGlExtSet object.
 * @ext: a #VisuGlExt object.
 *
 * Remove @ext in the list of drawn #VisuGlExt by @set.
 *
 * Since: 3.8
 *
 * Returns: TRUE if successfully removed.
 **/
gboolean visu_gl_ext_set_remove(VisuGlExtSet *set, VisuGlExt *ext)
{
  struct _GlExt *s;
  guint i;
  gboolean dirty;

  g_return_val_if_fail(VISU_IS_GL_EXT_SET(set), FALSE);

  for (i = 0; i < set->priv->set->len; i++)
    {
      s = &g_array_index(set->priv->set, struct _GlExt, i);
      if (s->ext == ext)
        {
          dirty = visu_gl_ext_getActive(s->ext);
          g_signal_handler_disconnect(G_OBJECT(s->ext), s->priority_sig);
          g_signal_handler_disconnect(G_OBJECT(s->ext), s->dirty_sig);
          g_signal_handler_disconnect(G_OBJECT(s->ext), s->active_sig);
          g_object_unref(s->ext);
          g_array_remove_index(set->priv->set, i);
          if (dirty)
            _appendDirty(set);
          if (VISU_GL_EXT_SET_GET_CLASS(set)->removed)
            VISU_GL_EXT_SET_GET_CLASS(set)->removed(set, ext);
          return TRUE;
        }
    }
  return FALSE;
}

static gint compareExtensionPriority(gconstpointer a, gconstpointer b)
{
  guint pa = visu_gl_ext_getPriority(((struct _GlExt*)a)->ext);
  guint pb = visu_gl_ext_getPriority(((struct _GlExt*)b)->ext);

  if (pa < pb)
    return (gint)-1;
  else if (pa > pb)
    return (gint)+1;
  else
    return (gint)0;
}

static void mayReorder(VisuGlExtSet *set)
{
  if (set->priv->reorderingNeeded)
    {
      DBG_fprintf(stderr, "Visu Extension Set: sorting known extension"
                  " depending on their priority.\n");
      g_array_sort(set->priv->set, compareExtensionPriority);
      set->priv->reorderingNeeded = FALSE;
    }
}

/**
 * visu_gl_ext_set_draw:
 * @set: a #VisuGlExtSet object.
 *
 * Basic drawing method : it clears the OpenGL area and call all lists
 * stored in @set.
 *
 * Since: 3.8
 */
void visu_gl_ext_set_draw(VisuGlExtSet *set)
{
  int i_stereo, stereo;
  guint i;
  static int stereo_buf[2] = {GL_BACK_LEFT, GL_BACK_RIGHT};
  GLboolean glStereo;
  float centre[3];
  VisuBox *box;
  float start, stop, bSize, fogCentre;
#if DEBUG == 1
  GTimer *timer;
  gulong fractionTimer;
#endif

  g_return_if_fail(VISU_IS_GL_EXT_SET(set) && set->priv->view);

#if DEBUG == 1
  timer = g_timer_new();
  g_timer_start(timer);
#endif

  mayReorder(set);
  
  box = visu_boxed_getBox(VISU_BOXED(set->priv->view));
  if (box)
    visu_box_getCentre(box, centre);
  else
    {
      centre[0] = 0.f;
      centre[1] = 0.f;
      centre[2] = 0.f;
    }

  _chessDraw(set);

  glClearColor(set->priv->bgRGB[0], set->priv->bgRGB[1],
               set->priv->bgRGB[2], set->priv->bgRGB[3]);
  if (set->priv->fogActive && set->priv->view &&
      visu_boxed_getBox(VISU_BOXED(set->priv->view)))
    {
      glEnable(GL_FOG);
      glFogi(GL_FOG_MODE, GL_LINEAR);
/*       glFogi(GL_FOG_MODE, GL_EXP);  */
/*       glFogf(GL_FOG_DENSITY, 0.03f);  */
      if (set->priv->fogFollowsBg)
        glFogfv(GL_FOG_COLOR, set->priv->bgRGB);
      else
        glFogfv(GL_FOG_COLOR, set->priv->fogRGB);

      bSize = visu_box_getGlobalSize(visu_boxed_getBox(VISU_BOXED(set->priv->view)), FALSE);
      fogCentre = ((set->priv->view->camera.d_red > 100.f) ?
                   100.f : set->priv->view->camera.d_red) * set->priv->view->camera.length0;

      start = fogCentre - bSize + 2.f * bSize * set->priv->fogStartEnd[0];
      stop  = fogCentre - bSize + 2.f * bSize * set->priv->fogStartEnd[1];
/*   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);
    }
  else
    glDisable(GL_FOG);

  glGetBooleanv(GL_STEREO, &glStereo);
  stereo = (set->priv->view && glStereo && visu_gl_getStereo(VISU_GL(set))) ? 1 : 0;
  for(i_stereo = 0; i_stereo <= stereo; i_stereo++)
    {
      if (stereo == 1)
        {
          glRotatef(visu_gl_getStereoAngle(VISU_GL(set)) * (2.f * i_stereo - 1.f),
        	    set->priv->view->camera.up[0],
        	    set->priv->view->camera.up[1],
        	    set->priv->view->camera.up[2]);
          glDrawBuffer(stereo_buf[i_stereo]);
          DBG_fprintf(stderr, "Visu Extension Set: draw on buffer %d.\n", i_stereo);
        }
      else
        glDrawBuffer(GL_BACK);

      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

      glPushAttrib(GL_ENABLE_BIT);
      glCallList(set->priv->chessList);
      glPopAttrib();

      glPushMatrix();
      glTranslated(-centre[0], -centre[1], -centre[2]);

      glEnable(GL_DEPTH_TEST);

      /* if (!lists && !trueTransparency) */
      /*   { */
      /*     visu_gl_ext_callAll(FALSE); */
      /*     visu_gl_ext_callAll(TRUE); */
      /*   } */
      /* else if (!lists && trueTransparency) */
      /*   { */
      /*     glDepthMask(1); */
      /*     glEnable(GL_ALPHA_TEST); */
      /*     glAlphaFunc(GL_EQUAL, 1.); */
      /*     visu_gl_ext_callAll(FALSE); */
      /*     DBG_fprintf(stderr, "OpenGL: second pass for transparency.\n"); */
      /*     glAlphaFunc(GL_LESS, 1.); */
      /*     glDepthMask(0); */
      /*     visu_gl_ext_callAll(FALSE); */
      /*     glDepthMask(1); */
      /*     glAlphaFunc(GL_ALWAYS, 1.); */
      /*     glDisable(GL_ALPHA_TEST); */
      /*     visu_gl_ext_callAll(TRUE); */
      /*   } */
      /* else */ if (!visu_gl_getTrueTransparency(VISU_GL(set)))
        for (i = 0; i < set->priv->set->len; i++)
          visu_gl_ext_call(g_array_index(set->priv->set, struct _GlExt, i).ext, FALSE);
      else
        {
          glDepthMask(1);
          glEnable(GL_ALPHA_TEST);
          glAlphaFunc(GL_EQUAL, 1.);
          for (i = 0; i < set->priv->set->len; i++)
            visu_gl_ext_call(g_array_index(set->priv->set, struct _GlExt, i).ext, FALSE);
          DBG_fprintf(stderr, "Visu Extension Set: second pass for transparency.\n");
          glAlphaFunc(GL_LESS, 1.);
          glDepthMask(0);
          for (i = 0; i < set->priv->set->len; i++)
            visu_gl_ext_call(g_array_index(set->priv->set, struct _GlExt, i).ext, FALSE);
          glDepthMask(1);
          glAlphaFunc(GL_ALWAYS, 1.);
          glDisable(GL_ALPHA_TEST);
        }
      for (i = 0; i < set->priv->set->len; i++)
        visu_gl_ext_call(g_array_index(set->priv->set, struct _GlExt, i).ext, TRUE);

      glPopMatrix();
    }
  set->priv->dirty = FALSE;

#if DEBUG == 1
  glFlush();
  g_timer_stop(timer);
  fprintf(stderr, "Visu Extension Set: lists drawn in %g micro-s.\n",
          g_timer_elapsed(timer, &fractionTimer)*1e6);
  g_timer_destroy(timer);
#endif
}

/**
 * visu_gl_ext_set_setBgColor:
 * @set: a #VisuGlExtSet object.
 * @rgba: (in) (array fixed-size=4): a three floats array with values
 * (0 <= values <= 1) for the red, the green and the blue color. Only
 * values specified by the mask are really relevant.
 * @mask: use #TOOL_COLOR_MASK_R, #TOOL_COLOR_MASK_G,
 * #TOOL_COLOR_MASK_B, #TOOL_COLOR_MASK_RGBA or a combinaison to
 * indicate what values in the rgb array must be taken into account.
 *
 * Method used to change the value of the parameter background_color.
 *
 * Since: 3.8
 *
 * Returns: TRUE if changed.
 */
gboolean visu_gl_ext_set_setBgColor(VisuGlExtSet *set, float rgba[4], int mask)
{
  g_return_val_if_fail(VISU_IS_GL_EXT_SET(set), FALSE);

  g_object_freeze_notify(G_OBJECT(set));
  if (mask & TOOL_COLOR_MASK_R && set->priv->bgRGB[0] != rgba[0])
    {
      set->priv->bgRGB[0] = CLAMP(rgba[0], 0.f, 1.f);
      g_object_notify_by_pspec(G_OBJECT(set), properties[BG_R_PROP]);
      set->priv->bgDirty = TRUE;
    }
  if (mask & TOOL_COLOR_MASK_G && set->priv->bgRGB[1] != rgba[1])
    {
      set->priv->bgRGB[1] = CLAMP(rgba[1], 0.f, 1.f);
      g_object_notify_by_pspec(G_OBJECT(set), properties[BG_G_PROP]);
      set->priv->bgDirty = TRUE;
    }
  if (mask & TOOL_COLOR_MASK_B && set->priv->bgRGB[2] != rgba[2])
    {
      set->priv->bgRGB[2] = CLAMP(rgba[2], 0.f, 1.f);
      g_object_notify_by_pspec(G_OBJECT(set), properties[BG_B_PROP]);
      set->priv->bgDirty = TRUE;
    }
  if (mask & TOOL_COLOR_MASK_A && set->priv->bgRGB[3] != rgba[3])
    {
      set->priv->bgRGB[3] = CLAMP(rgba[3], 0.f, 1.f);
      g_object_notify_by_pspec(G_OBJECT(set), properties[BG_A_PROP]);
      set->priv->bgDirty = TRUE;
    }
  g_object_thaw_notify(G_OBJECT(set));
  if (set->priv->bgDirty)
    _appendDirty(set);
  return set->priv->bgDirty;
}

/**
 * visu_gl_ext_set_getBgColor:
 * @set: a #VisuGlExtSet object.
 * @rgba: (array fixed-size=4) (out): a storage for four values.
 *
 * Read the RGBA value of the specific background colour (in [0;1]).
 *
 * Since: 3.8
 */
void visu_gl_ext_set_getBgColor(const VisuGlExtSet *set, float rgba[4])
{
  g_return_if_fail(VISU_IS_GL_EXT_SET(set));

  memcpy(rgba, set->priv->bgRGB, sizeof(float) * 4);
}

static void _chessDraw(VisuGlExtSet *set)
{
  GLubyte chessboard[32][32][3];
  int viewport[4];
  int i, j, c;

  if (!set->priv->bgDirty)
    return;

  if (set->priv->bgRGB[3] < 1.f && !(visu_gl_getHint(VISU_GL(set)) & VISU_GL_OFFSCREEN))
    {
      DBG_fprintf(stderr, "Visu Extension Set: set background chess board (alpha = %g).\n",
                  set->priv->bgRGB[3]);

      if (texName == 0)
        glGenTextures(1, &texName);

      /* We create the chessboard texture with the right colour. */
      for (i = 0; i < 32; i++)
        for (j = 0; j < 32; j++)
          {
            c = 128 + ( ((i&0x10)==0) ^ ((j&0x10) == 0) ) * 64;
            chessboard[i][j][0] =
              (GLubyte)(255.f * set->priv->bgRGB[0] * set->priv->bgRGB[3] +
                        (1.f - set->priv->bgRGB[3]) * c);
            chessboard[i][j][1] =
              (GLubyte)(255.f * set->priv->bgRGB[1] * set->priv->bgRGB[3] +
                        (1.f - set->priv->bgRGB[3]) * c);
            chessboard[i][j][2] =
              (GLubyte)(255.f * set->priv->bgRGB[2] * set->priv->bgRGB[3] +
                        (1.f - set->priv->bgRGB[3]) * c);
          }
      /* We bind the texture. */
      glBindTexture(GL_TEXTURE_2D, texName);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

      glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
      glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 32, 32, 0,
                   GL_RGB, GL_UNSIGNED_BYTE, chessboard);

      glGetIntegerv(GL_VIEWPORT, viewport);

      glNewList(set->priv->chessList, GL_COMPILE);
      glDisable(GL_CULL_FACE);
      glDisable(GL_LIGHTING);

      glEnable(GL_TEXTURE_2D);
      glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
      glBindTexture(GL_TEXTURE_2D, texName);

      glMatrixMode(GL_PROJECTION);
      glPushMatrix();
      glLoadIdentity();
      gluOrtho2D(0., (float)viewport[2], 0., (float)viewport[3]);   
      glMatrixMode(GL_MODELVIEW);
      glPushMatrix();
      glLoadIdentity();

      glDepthMask(0);
      glBegin(GL_QUADS);
      glTexCoord2f(0.0, 0.0);
      glVertex3f(0.0, 0.0, 0.0);
      glTexCoord2f(0.0, (float)viewport[3] / 32.f);
      glVertex3f(0.0, (float)viewport[3], 0.0);
      glTexCoord2f((float)viewport[2] / 32.f, (float)viewport[3] / 32.f);
      glVertex3f((float)viewport[2], (float)viewport[3], 0.0);
      glTexCoord2f((float)viewport[2] / 32.f, 0.0);
      glVertex3f((float)viewport[2], 0.0, 0.0);
      glEnd();
      glDepthMask(1);

      glPopMatrix();
      glMatrixMode(GL_PROJECTION);
      glPopMatrix();
      glMatrixMode(GL_MODELVIEW);

      glDisable(GL_TEXTURE_2D);
      glEndList();
    }
  else
    glDeleteLists(set->priv->chessList, 1);  
  set->priv->bgDirty = FALSE;
}

/**
 * visu_gl_ext_set_setFogColor:
 * @set: a #VisuGlExtSet object.
 * @rgba: (array fixed-size=4): four [0;1] float values.
 * @mask: a mask, see %TOOL_COLOR_MASK_R for instance.
 *
 * Change the fog specific colour. Activate it with
 * visu_gl_ext_set_setFogFollowsBg().
 *
 * Since: 3.8
 *
 * Returns: TRUE if value is actually changed.
 **/
gboolean visu_gl_ext_set_setFogColor(VisuGlExtSet *set, float rgba[4], int mask)
{
  gboolean diff;

  g_return_val_if_fail(VISU_IS_GL_EXT_SET(set), FALSE);

  diff = FALSE;
  g_object_freeze_notify(G_OBJECT(set));
  if (mask & TOOL_COLOR_MASK_R && set->priv->fogRGB[0] != rgba[0])
    {
      set->priv->fogRGB[0] = CLAMP(rgba[0], 0.f, 1.f);
      g_object_notify_by_pspec(G_OBJECT(set), properties[FOG_R_PROP]);
      diff = TRUE;
    }
  if (mask & TOOL_COLOR_MASK_G && set->priv->fogRGB[1] != rgba[1])
    {
      set->priv->fogRGB[1] = CLAMP(rgba[1], 0.f, 1.f);
      g_object_notify_by_pspec(G_OBJECT(set), properties[FOG_G_PROP]);
      diff = TRUE;
    }
  if (mask & TOOL_COLOR_MASK_B && set->priv->fogRGB[2] != rgba[2])
    {
      set->priv->fogRGB[2] = CLAMP(rgba[2], 0.f, 1.f);
      g_object_notify_by_pspec(G_OBJECT(set), properties[FOG_B_PROP]);
      diff = TRUE;
    }
  if (mask & TOOL_COLOR_MASK_A && set->priv->fogRGB[3] != rgba[3])
    {
      set->priv->fogRGB[3] = CLAMP(rgba[3], 0.f, 1.f);
      g_object_notify_by_pspec(G_OBJECT(set), properties[FOG_A_PROP]);
      diff = TRUE;
    }
  g_object_thaw_notify(G_OBJECT(set));
  if (diff && set->priv->fogActive)
    _appendDirty(set);
  return diff;
}
/**
 * visu_gl_ext_set_setFogActive:
 * @set: a #VisuGlExtSet object.
 * @value: a boolean.
 *
 * Activates the fog rendering, or not.
 *
 * Since: 3.8
 *
 * Returns: TRUE if value is actually changed.
 **/
gboolean visu_gl_ext_set_setFogActive(VisuGlExtSet *set, gboolean value)
{
  g_return_val_if_fail(VISU_IS_GL_EXT_SET(set), FALSE);

  if (set->priv->fogActive == value)
    return FALSE;

  set->priv->fogActive = value;
  g_object_notify_by_pspec(G_OBJECT(set), properties[FOG_ACTIVE_PROP]);
  _appendDirty(set);
  return TRUE;
}
/**
 * visu_gl_ext_set_setFogFollowsBg:
 * @set: a #VisuGlExtSet object.
 * @value: a boolean.
 *
 * Specifies if the fog is coloured with the background colour or with
 * its own colour, see visu_gl_ext_set_setFogColor().
 *
 * Since: 3.8
 *
 * Returns: TRUE if value is actually changed.
 **/
gboolean visu_gl_ext_set_setFogFollowsBg(VisuGlExtSet *set, gboolean value)
{
  g_return_val_if_fail(VISU_IS_GL_EXT_SET(set), FALSE);

  if (set->priv->fogFollowsBg == value)
    return FALSE;

  set->priv->fogFollowsBg = value;
  g_object_notify_by_pspec(G_OBJECT(set), properties[FOG_FOLLOWS_PROP]);
  if (set->priv->fogActive)
    _appendDirty(set);
  return TRUE;
}
/**
 * visu_gl_ext_set_setFogStartFull:
 * @set: a #VisuGlExtSet object.
 * @startEnd: (array fixed-size=2): two [0;1] floating point values.
 * @mask: a mask, see %VISU_GL_EXT_SET_FOG_MASK_START and
 * %VISU_GL_EXT_SET_FOG_MASK_FULL.
 *
 * Change the starting and ending point of fog.
 *
 * Since: 3.8
 *
 * Returns: TRUE if values are actually changed.
 **/
gboolean visu_gl_ext_set_setFogStartFull(VisuGlExtSet *set, float startEnd[2], int mask)
{
  gboolean diff;

  g_return_val_if_fail(VISU_IS_GL_EXT_SET(set), FALSE);

  diff = FALSE;
  g_object_freeze_notify(G_OBJECT(set));
  if (mask & VISU_GL_EXT_SET_FOG_MASK_START && set->priv->fogStartEnd[0] != startEnd[0])
    {
      set->priv->fogStartEnd[0] = CLAMP(startEnd[0], 0.f, 1.f);
      if (mask & VISU_GL_EXT_SET_FOG_MASK_FULL)
	{
	  if (set->priv->fogStartEnd[0] >= startEnd[1])
	    set->priv->fogStartEnd[0] = startEnd[1] - 0.001;
	}
      else
	if (set->priv->fogStartEnd[0] >= set->priv->fogStartEnd[1])
	  set->priv->fogStartEnd[0] = set->priv->fogStartEnd[1] - 0.001;
      g_object_notify_by_pspec(G_OBJECT(set), properties[FOG_START_PROP]);
      diff = TRUE;
    }
  if (mask & VISU_GL_EXT_SET_FOG_MASK_FULL && set->priv->fogStartEnd[1] != startEnd[1])
    {
      set->priv->fogStartEnd[1] = CLAMP(startEnd[1], 0.f, 1.f);
      if (set->priv->fogStartEnd[1] <= set->priv->fogStartEnd[0])
	set->priv->fogStartEnd[1] = set->priv->fogStartEnd[0] + 0.001;
      g_object_notify_by_pspec(G_OBJECT(set), properties[FOG_FULL_PROP]);
      diff = TRUE;
    }
  g_object_thaw_notify(G_OBJECT(set));
  if (diff && set->priv->fogActive)
    _appendDirty(set);
  return diff;
}

/**
 * visu_gl_ext_set_getFogColor:
 * @set: a #VisuGlExtSet object.
 * @rgba: (out) (array fixed-size=4): a storage for three values.
 *
 * Gives the actual fog color, for the specific color, use
 * visu_gl_ext_set_getFogSpecificColor().
 *
 * Since: 3.8
 */
void visu_gl_ext_set_getFogColor(VisuGlExtSet *set, float rgba[4])
{
  g_return_if_fail(VISU_IS_GL_EXT_SET(set));
  if (set->priv->fogFollowsBg)
    memcpy(rgba, set->priv->bgRGB, sizeof(float) * 4);
  else
    memcpy(rgba, set->priv->fogRGB, sizeof(float) * 4);
}
/**
 * visu_gl_ext_set_getFogSpecificColor:
 * @set: a #VisuGlExtSet object.
 * @rgba: (out) (array fixed-size=4): a storage for three values.
 *
 * Gives the specific fog color, for the actual color, use
 * visu_gl_ext_set_getFogColor().
 *
 * Since: 3.8
 */
void visu_gl_ext_set_getFogSpecificColor(VisuGlExtSet *set, float rgba[4])
{
  g_return_if_fail(VISU_IS_GL_EXT_SET(set));
  memcpy(rgba, set->priv->fogRGB, sizeof(float) * 4);
}
/**
 * visu_gl_ext_set_getFogActive:
 * @set: a #VisuGlExtSet object.
 *
 * Read if fog is used or not.
 *
 * Since: 3.8
 *
 * Returns: TRUE if the fog is rendered, FALSE otherwise.
 */
gboolean visu_gl_ext_set_getFogActive(VisuGlExtSet *set)
{
  g_return_val_if_fail(VISU_IS_GL_EXT_SET(set), FALSE);
  return set->priv->fogActive;
}
/**
 * visu_gl_ext_set_getFogFollowsBg:
 * @set: a #VisuGlExtSet object.
 *
 * Read if fog uses a specific colour or not.
 *
 * Since: 3.8
 *
 * Returns: TRUE if the fog uses its own color or FALSE if it uses
 * the color of the background.
 */
gboolean visu_gl_ext_set_getFogFollowsBg(VisuGlExtSet *set)
{
  g_return_val_if_fail(VISU_IS_GL_EXT_SET(set), FALSE);
  return set->priv->fogFollowsBg;
}
/**
 * visu_gl_ext_set_getFogStartFull:
 * @set: a #VisuGlExtSet object.
 * @startFull: (out caller-allocates) (array fixed-size=2): two float
 * location.
 *
 * Retrieves the starting and ending value (reduced) of fog extension.
 *
 * Since: 3.8
 **/
void visu_gl_ext_set_getFogStartFull(VisuGlExtSet *set, float startFull[2])
{
  g_return_if_fail(VISU_IS_GL_EXT_SET(set));
  memcpy(startFull, set->priv->fogStartEnd, sizeof(float) * 2);
}

/**
 * visu_gl_ext_set_getPixmapData:
 * @set: a #VisuGlExtSet object ;
 * @width: the desired width or 0 for current ;
 * @height: the desired height or 0 for current ;
 * @hasAlpha: if TRUE, the returned data is RGBA, else only RGB.
 *
 * Create an image from the OpenGL area. The size can be changed, using @width and
 * @height. If these pointers contains positive values, then they are used to set the
 * size for the image. If not, the size of the current #VisuGlView is used and
 * stored in these pointers.
 *
 * Since: 3.8
 *
 * Returns: (transfer full) (element-type int): image data, row by row.
 */
GArray* visu_gl_ext_set_getPixmapData(VisuGlExtSet *set, guint width,
                                      guint height, gboolean hasAlpha)
{
  GArray *image;
  VisuPixmapContext *dumpData;
  guint row_length;
  gint m, n1, n2;
  guchar *row_tab;
  guint oldW, oldH;

  g_return_val_if_fail(VISU_IS_GL_EXT_SET(set), (GArray*)0);
  g_return_val_if_fail(VISU_IS_GL_VIEW(set->priv->view), (GArray*)0);

  /* We may change the actual drawing size. */
  width  = (width > 0)  ? width  : set->priv->view->window.width;
  height = (height > 0) ? height : set->priv->view->window.height;
  oldW = set->priv->view->window.width;
  oldH = set->priv->view->window.height;
  visu_gl_view_setViewport(set->priv->view, width, height);

  /* We create a pixmap context and make this context current. */
  dumpData = visu_pixmap_context_new(width, height);
  if (!dumpData)
    {
      g_warning("can't create off-screen pixmap.");
      return (GArray*)0;
    }
  /* We set the glViewport of this new context. */
  visu_gl_initContext(VISU_GL(set));
  /* We call the given draw method. */
  visu_gl_ext_set_draw(set);
  /* We copy the pixmap into generic data. */
  if (hasAlpha)
    row_length = 4 * width;
  else
    row_length = 3 * width;
  row_tab = g_malloc(sizeof(guchar) * row_length);

  image = g_array_sized_new(FALSE, FALSE, sizeof(guchar), row_length * height);

  glPixelStorei(GL_PACK_ALIGNMENT, 1); /* just in case */

  /* Copy the image into our buffer */
  n2 = 0;
  for(m = height - 1; m >= 0; m--)
    {
      if (hasAlpha)
	glReadPixels(0, m, width, 1, GL_RGBA, GL_UNSIGNED_BYTE, row_tab);
      else
	glReadPixels(0, m, width, 1, GL_RGB, GL_UNSIGNED_BYTE, row_tab);
      n1 = n2;
      n2 = n1 + row_length;
      image = g_array_insert_vals(image, n1, row_tab, n2 - n1);
    }
  g_free(row_tab);

  DBG_fprintf(stderr, " | save to array %p.\n", (gpointer)image);
  /* We free the pixmap context. */
  visu_pixmap_context_free(dumpData);

  /* We put back the viewport. */
  visu_gl_view_setViewport(set->priv->view, oldW, oldH);

  return image;
}

/***************************/
/* Dealing with parameters */
/***************************/
static void onEntryBgColor(VisuGlExtSet *set, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_ext_set_setBgColor(set, bgRGBDefault, TOOL_COLOR_MASK_RGBA);
}
static void onEntryFogActive(VisuGlExtSet *set, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_ext_set_setFogActive(set, fogActiveDefault);
}
static void onEntryFogSpecific(VisuGlExtSet *set, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_ext_set_setFogFollowsBg(set, !fogSpecificDefault);
}
static void onEntryFogColor(VisuGlExtSet *set, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_ext_set_setFogColor(set, fogRGBDefault, TOOL_COLOR_MASK_RGBA);
}
static void onEntryFogStartEnd(VisuGlExtSet *set, VisuConfigFileEntry *entry _U_, VisuConfigFile *obj _U_)
{
  visu_gl_ext_set_setFogStartFull(set, fogStartEndDefault,
                                  VISU_GL_EXT_SET_FOG_MASK_START |
                                  VISU_GL_EXT_SET_FOG_MASK_FULL);
}
static void onWidthHeight(VisuGlView *view _U_, gpointer data)
{
  VisuGlExtSetPrivate *priv = VISU_GL_EXT_SET(data)->priv;

  DBG_fprintf(stderr, "Visu Extension Set: caught the 'WidthHeightChanged' signal.\n");

  if (priv->bgRGB[3] < 1.f)
    priv->bgDirty = TRUE;
}
static void onCamera(VisuGlView *view _U_, gpointer data)
{
  _appendDirty(VISU_GL_EXT_SET(data));
}

static void exportResources(GString *data, VisuData *dataObj _U_)
{
  if (!defaultSet)
    return;

  visu_config_file_exportComment(data, DESC_RESOURCE_BG_COLOR);
  visu_config_file_exportEntry(data, FLAG_RESOURCE_BG_COLOR, NULL,
                               "%4.3f %4.3f %4.3f %4.3f",
                               defaultSet->priv->bgRGB[0], defaultSet->priv->bgRGB[1],
                               defaultSet->priv->bgRGB[2], defaultSet->priv->bgRGB[3]);

  visu_config_file_exportComment(data, DESC_RESOURCE_FOG_USED);
  visu_config_file_exportEntry(data, FLAG_RESOURCE_FOG_USED, NULL,
                               "%d", defaultSet->priv->fogActive);
  visu_config_file_exportComment(data, DESC_RESOURCE_FOG_SPECIFIC);
  visu_config_file_exportEntry(data, FLAG_RESOURCE_FOG_SPECIFIC, NULL,
                               "%d", !defaultSet->priv->fogFollowsBg);
  visu_config_file_exportComment(data, DESC_RESOURCE_FOG_COLOR);
  visu_config_file_exportEntry(data, FLAG_RESOURCE_FOG_COLOR, NULL,
                               "%4.3f %4.3f %4.3f %4.3f",
                               defaultSet->priv->fogRGB[0], defaultSet->priv->fogRGB[1],
                               defaultSet->priv->fogRGB[2], defaultSet->priv->fogRGB[3]);
  visu_config_file_exportComment(data, DESC_RESOURCE_FOG_STARTEND);
  visu_config_file_exportEntry(data, FLAG_RESOURCE_FOG_STARTEND, NULL,
                               "%4.3f %4.3f", defaultSet->priv->fogStartEnd[0],
                               defaultSet->priv->fogStartEnd[1]);

  visu_config_file_exportComment(data, "");
}
