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

#include <errno.h>
#include <string.h>

#include <pango/pango.h>

#include <visu_configFile.h>
#include "toolConfigFile.h"
#include "toolColor.h"

/**
 * SECTION:toolShade
 * @short_description: ToolShades are color gradients.
 *
 * <para>This module allow V_Sim to deal with color gradients. Such a
 * gradient is defined by a linear transformation of color space. This
 * space can be RBG or HSV (see the enum #ToolShadeColorMode). This linear
 * transformation can be written [resulting color vector] = [vectB] +
 * lambda.[vectA], where lambda denotes the input variable of the
 * gradient (ranging from 0 to 1). Resulting color vector are clamped
 * to [0;1] if needed.</para>
 * <para>Use tool_shade_new() to create a new shade, giving the arguments as
 * defined above.</para>
 * <para>To share color gradients between modules in V_Sim, you can
 * find a global list of stored shades with tool_shade_getStorage().
 * This is a #ToolPool object. Use tool_pool_add() to add a new shade
 * to it.</para>
 */


#define SHADE_LEGEND_WIDTH 0.05
#define SHADE_LEGEND_HEIGHT 0.3
#define SHADE_LEGEND_N_QUADS 20

#define FLAG_SHADE "shade_palette"
#define DESC_SHADE "Define a new shade by giving colours to points ; label (val [name|#rgb|#rrggbb|...], ...)"
static void exportParameters(GString *data, VisuData *dataObj);
static gboolean readShade(VisuConfigFileEntry *entry _U_, gchar **lines, int nbLines,int position,
                          GError **error);
static gboolean parseValue(gchar *line, float *index, float rgb[3], GError **error);
static void _buildPresetList(void);

struct _ToolShade
{
  gchar* labelUTF8;
  ToolShadeColorMode colorMode;
  ToolShadeMode mode;

  /* The linear storage. */
  float vectA[3], vectB[3];
  /* The array storage. */
  float *index;
  float *vectCh[3];
  guint nVals;

  /* Some user defined values. */
  gboolean userDefined;
  gchar *steps;
};

static ToolPool *shadePool = NULL;

/**
 * tool_shade_get_type:
 *
 * Create and retrieve a #GType for a #ToolShade object.
 *
 * Since: 3.7
 *
 * Returns: a new type for #ToolShade structures.
 */
GType tool_shade_get_type(void)
{
  static GType g_define_type_id = 0;
  VisuConfigFileEntry *entry;

  if (g_define_type_id == 0)
    {
      g_define_type_id = g_boxed_type_register_static("ToolShade", 
                                                      (GBoxedCopyFunc)tool_shade_copy,
                                                      (GBoxedFreeFunc)tool_shade_free);

      /* Set private variables. */
      entry = visu_config_file_addEntry(VISU_CONFIG_FILE_RESOURCE,
                                        FLAG_SHADE, DESC_SHADE,
                                        1, readShade);
      visu_config_file_entry_setVersion(entry, 3.7f);
      visu_config_file_addExportFunction(VISU_CONFIG_FILE_RESOURCE,
                                         exportParameters);
    }

  return g_define_type_id;
}

/**
 * tool_shade_getById:
 * @id: an id.
 *
 * Convenience function calling tool_pool_getById() on the default
 * #ToolShade storage.
 *
 * Since: 3.8
 *
 * Returns: a #ToolShade from the pool.
 **/
const ToolShade* tool_shade_getById(guint id)
{
  return tool_pool_getById(tool_shade_getStorage(), id);
}

/**
 * tool_shade_new:
 * @labelUTF8: a UTF8 string that shortly named this new shade ;
 * @vectA: an array of three floating point values ;
 * @vectB: an array of three floating point values ;
 * @colorMode: an integer that describes the color code (see #ToolShadeColorMode enumeration).
 *
 * Create a linear shade. Its profile is given by an AX+B formula,
 * dealing on three channels. These channels are defined by the
 * @colorMode parameter. All given values are copied when the new
 * shade is created.
 *
 * Returns: the newly created ToolShade.
 */
ToolShade* tool_shade_new(const gchar* labelUTF8, float vectA[3], float vectB[3],
                          ToolShadeColorMode colorMode)
{
  ToolShade *shade;
  int i;

  g_return_val_if_fail(labelUTF8 && vectA && vectB &&
		       colorMode < TOOL_SHADE_COLOR_MODE_N_VALUES, (ToolShade*)0);

  DBG_fprintf(stderr, "Tool ToolShade: create a new ToolShade object (linear):");
  shade = g_malloc(sizeof(ToolShade));
  shade->labelUTF8 = g_strdup(labelUTF8);
  for (i = 0; i < 3; i++)
    {
      shade->vectA[i] = vectA[i];
      shade->vectB[i] = vectB[i];
    }
  shade->index     = (float*)0;
  shade->vectCh[0] = (float*)0;
  shade->vectCh[1] = (float*)0;
  shade->vectCh[2] = (float*)0;
  shade->colorMode = colorMode;
  shade->mode      = TOOL_SHADE_MODE_LINEAR;
  shade->userDefined = TRUE;
  shade->steps     = (gchar*)0;

  DBG_fprintf(stderr, " %p.\n", (gpointer)shade);
  return shade;
}
/**
 * tool_shade_newFromData:
 * @labelUTF8: a UTF8 string that shortly named this new shade ;
 * @len: the size of arguments @vectCh1, @vectCh2 and @vectCh3 ;
 * @vectCh1: an array of floating point values for the first channel ;
 * @vectCh2: an array of floating point values for the second channel ;
 * @vectCh3: an array of floating point values for the third channel ;
 * @colorMode: an integer that describes the color code (see
 * #ToolShadeColorMode enumeration).
 *
 * Create a #ToolShade from direct data for three channels. These channels
 * are defined by the @colorMode parameter. All given values are
 * copied when the new shade is created.
 *
 * Returns: the newly created ToolShade.
 */ 
ToolShade* tool_shade_newFromData(const gchar* labelUTF8, guint len, float *vectCh1,
                                  float *vectCh2, float *vectCh3, ToolShadeColorMode colorMode)
{
  ToolShade *shade;
  guint i;

  g_return_val_if_fail(labelUTF8 && vectCh1 && vectCh2 && vectCh3 &&
		       colorMode < TOOL_SHADE_COLOR_MODE_N_VALUES && len > 0, (ToolShade*)0);

  DBG_fprintf(stderr, "Tool ToolShade: create a new ToolShade object (array):");
  shade = g_malloc(sizeof(ToolShade));
  shade->labelUTF8 = g_strdup(labelUTF8);
  shade->colorMode = colorMode;
  shade->mode      = TOOL_SHADE_MODE_ARRAY;
  shade->nVals     = len;
  shade->index     = g_malloc(sizeof(float) * len);
  shade->vectCh[0] = g_malloc(sizeof(float) * len);
  shade->vectCh[1] = g_malloc(sizeof(float) * len);
  shade->vectCh[2] = g_malloc(sizeof(float) * len);
  for (i = 0; i < len; i++)
    shade->index[i] = (float)i / (float)(len - 1);
  memcpy(shade->vectCh[0], vectCh1, sizeof(float) * len);
  memcpy(shade->vectCh[1], vectCh2, sizeof(float) * len);
  memcpy(shade->vectCh[2], vectCh3, sizeof(float) * len);
  shade->userDefined = TRUE;
  shade->steps     = (gchar*)0;

  DBG_fprintf(stderr, " %p.\n", (gpointer)shade);
  return shade;
}
/**
 * tool_shade_newFromSteps:
 * @labelUTF8: a UTF8 string that shortly named this new shade ;
 * @lst: (transfer none) (element-type ToolShadeStep*): a list of
 * color steps.
 * @colorMode: a #ToolShadeColorMode mode.
 *
 * Create a #ToolShade from a set of steps defining colours at given
 * indexes. These channels are defined by the @colorMode
 * parameter. All given values are copied when the new shade is
 * created. The values of indexes will be normalised by this call to
 * range in [0;1]. Colour channel values must be in [0;1] for each step.
 *
 * Since: 3.7
 *
 * Returns: (transfer full): the newly created ToolShade.
 */ 
ToolShade* tool_shade_newFromSteps(const gchar* labelUTF8, GList *lst,
                                   ToolShadeColorMode colorMode)
{
  ToolShade *shade;
  float minVal, maxVal, f;
  GList *tmp;
  ToolShadeStep *step;
  guint i;

  g_return_val_if_fail(labelUTF8 && lst && (g_list_length(lst) > 1), (ToolShade*)0);

  DBG_fprintf(stderr, "Tool ToolShade: create a new ToolShade object (array):\n");
  shade = g_malloc(sizeof(ToolShade));
  shade->labelUTF8 = g_strdup(labelUTF8);
  shade->nVals     = g_list_length(lst);
  shade->index     = g_malloc(sizeof(float) * shade->nVals);
  shade->vectCh[0] = g_malloc(sizeof(float) * shade->nVals);
  shade->vectCh[1] = g_malloc(sizeof(float) * shade->nVals);
  shade->vectCh[2] = g_malloc(sizeof(float) * shade->nVals);
  shade->colorMode = colorMode;
  shade->mode      = TOOL_SHADE_MODE_ARRAY;
  shade->userDefined = TRUE;
  shade->steps     = (gchar*)0;
  
  /* Normalise entry. */
  minVal =  G_MAXFLOAT;
  maxVal = -G_MAXFLOAT;
  for (tmp = lst; tmp; tmp = g_list_next(tmp))
    {
      minVal = MIN(minVal, ((ToolShadeStep*)tmp->data)->index);
      maxVal = MAX(maxVal, ((ToolShadeStep*)tmp->data)->index);
    }
  f = 1.f / (maxVal - minVal);
  DBG_fprintf(stderr, " | applying factor %g to index\n", f);
  
  for (tmp = lst, i = 0; tmp; tmp = g_list_next(tmp), i++)
    {
      step = (ToolShadeStep*)tmp->data;
      shade->index[i] = (step->index - minVal) * f;
      shade->vectCh[0][i] = CLAMP(step->channels[0], 0.f, 1.f);
      shade->vectCh[1][i] = CLAMP(step->channels[1], 0.f, 1.f);
      shade->vectCh[2][i] = CLAMP(step->channels[2], 0.f, 1.f);
    }

  DBG_fprintf(stderr, " | done %p.\n", (gpointer)shade);
  return shade;
}
/**
 * tool_shade_newFromString:
 * @labelUTF8: a UTF8 string that shortly named this new shade ;
 * @descr: a string with the shade description.
 * @colorMode: a #ToolShadeColorMode mode.
 * @error: (allow-none): a location for an error.
 *
 * As tool_shade_newFromSteps() routine, but it takes an unparsed
 * string describing the steps in @descr.
 *
 * Since: 3.7
 *
 * Returns: (transfer full): the newly created ToolShade.
 */ 
ToolShade* tool_shade_newFromString(const gchar* labelUTF8, const gchar *descr,
                                    ToolShadeColorMode colorMode, GError **error)
{
  ToolShade *shade;
  gchar **tokens;
  guint i;
  GList *lst;
  ToolShadeStep *step;
  
  g_return_val_if_fail(labelUTF8 && descr && error, (ToolShade*)0);

  DBG_fprintf(stderr, "Tool ToolShade: create a new ToolShade object (string): %s\n", descr);

  /* Read @size boolean values from @line. */
  lst = (GList*)0;
  tokens = g_strsplit_set(descr, ",", TOOL_MAX_LINE_LENGTH);
  for (i = 0; tokens[i]; i++)
    if (tokens[i][0])
      {
        step = g_malloc(sizeof(ToolShadeStep));
        lst = g_list_append(lst, step);
        if (!parseValue(tokens[i], &(step->index), step->channels, error))
          {
            g_strfreev(tokens);
            g_list_free_full(lst, g_free);
            return FALSE;
          }
      }
  
  shade = tool_shade_newFromSteps(labelUTF8, lst, colorMode);
  if (shade)
    shade->steps = g_strdup(descr);

  g_strfreev(tokens);
  g_list_free_full(lst, g_free);

  return shade;
}
/**
 * tool_shade_free:
 * @shade: a #ToolShade.
 *
 * Free all dynamic memory from @shade and free @shade itself.
 */
void tool_shade_free(ToolShade *shade)
{
  if (shade)
    {
      DBG_fprintf(stderr, "Tool Shade: freeing %p.\n", (gpointer)shade);
      g_free(shade->labelUTF8);
      g_free(shade->index);
      g_free(shade->vectCh[0]);
      g_free(shade->vectCh[1]);
      g_free(shade->vectCh[2]);
      g_free(shade->steps);
      g_free(shade);
    }
}
/**
 * tool_shade_copy:
 * @shade: a #ToolShade.
 *
 * Create a new shade deep copy of the first.
 *
 * Returns: a newly created shade.
 */
ToolShade* tool_shade_copy(const ToolShade *shade)
{
  ToolShade *out;

  if (!shade)
    return (ToolShade*)0;

  out = g_malloc(sizeof(ToolShade));
  out->labelUTF8 = g_strdup(shade->labelUTF8);
  out->colorMode = shade->colorMode;
  out->mode      = shade->mode;
  out->nVals     = shade->nVals;
  out->vectA[0]  = shade->vectA[0];
  out->vectA[1]  = shade->vectA[1];
  out->vectA[2]  = shade->vectA[2];
  out->vectB[0]  = shade->vectB[0];
  out->vectB[1]  = shade->vectB[1];
  out->vectB[2]  = shade->vectB[2];
  out->index     = g_memdup(shade->index,     sizeof(float) * out->nVals);
  out->vectCh[0] = g_memdup(shade->vectCh[0], sizeof(float) * out->nVals);
  out->vectCh[1] = g_memdup(shade->vectCh[1], sizeof(float) * out->nVals);
  out->vectCh[2] = g_memdup(shade->vectCh[2], sizeof(float) * out->nVals);
  out->userDefined = shade->userDefined;
  out->steps     = g_strdup(shade->steps);

  return out;
}
static gint _compare(const ToolShade* sh1, const ToolShade *sh2)
{
  guint i;
  gboolean equal;

  if (!sh1 && !sh2)
    return 0;
  if (!sh1)
    return -1;
  if (!sh2)
    return +1;

  if (sh1->mode != sh2->mode)
    return (sh2 - sh1);
  if (sh1->colorMode != sh2->colorMode)
    return (sh2 - sh1);

  if (sh1->mode == TOOL_SHADE_MODE_LINEAR)
    return (sh1->vectA[0] == sh2->vectA[0] &&
	    sh1->vectA[1] == sh2->vectA[1] &&
	    sh1->vectA[2] == sh2->vectA[2] &&
	    sh1->vectB[0] == sh2->vectB[0] &&
	    sh1->vectB[1] == sh2->vectB[1] &&
	    sh1->vectB[2] == sh2->vectB[2]) ? 0 : (sh2 - sh1);
  else
    {
      if (sh1->nVals != sh2->nVals)
	return (sh2 - sh1);
      equal = TRUE;
      for (i = 0; i < sh1->nVals && equal; i++)
	equal = equal && (sh1->index[i] == sh2->index[i]) &&
          (sh1->vectCh[0][i] == sh2->vectCh[0][i]) &&
	  (sh1->vectCh[1][i] == sh2->vectCh[1][i]) &&
	  (sh1->vectCh[2][i] == sh2->vectCh[2][i]);
      return equal ? 0 : (sh2 - sh1);
    }
}
/**
 * tool_shade_compare:
 * @sh1: a #ToolShade ;
 * @sh2: a #ToolShade.
 *
 * Compare if the two shade are identical (first, smae mode, then same
 * values).
 *
 * Returns: TRUE if @shade1 is equivalent to @shade2.
 */
gboolean tool_shade_compare(const ToolShade* sh1, const ToolShade *sh2)
{
  return (_compare(sh1, sh2) == 0);
}
/**
 * tool_shade_getLabel:
 * @shade: a valid #ToolShade object.
 *
 * Get the name (in UTF8) of the shade.
 *
 * Returns: a string naming the shade.
 */
gchar* tool_shade_getLabel(ToolShade *shade)
{
  g_return_val_if_fail(shade, (gchar*)0);
  return shade->labelUTF8;
}
/**
 * tool_shade_getColorMode:
 * @shade: a valid #ToolShade object.
 *
 * Get the color mode of the shade (RGB or HSV).
 *
 * Returns: the color mode.
 */
ToolShadeColorMode tool_shade_getColorMode(ToolShade *shade)
{
  g_return_val_if_fail(shade, (int)0);
  return shade->colorMode;
}
/**
 * tool_shade_getMode:
 * @shade: a valid #ToolShade object.
 *
 * Get the mode of the shade (linear, array...).
 *
 * Returns: the mode.
 */
ToolShadeMode tool_shade_getMode(const ToolShade *shade)
{
  g_return_val_if_fail(shade, (int)0);
  return shade->mode;
}
/**
 * tool_shade_setColorMode:
 * @shade: a #ToolShade ;
 * @mode: a new mode for the shade.
 * 
 * Change the mode of the shade, see #ToolShadeColorMode.
 *
 * Returns: TRUE if @mode is different from previous @shade mode.
 */
gboolean tool_shade_setColorMode(ToolShade *shade, ToolShadeColorMode mode)
{
  g_return_val_if_fail(shade, FALSE);

  if (shade->colorMode == mode)
    return FALSE;
  
  shade->colorMode = mode;
  return TRUE;
}
/**
 * tool_shade_getLinearCoeff:
 * @shade: a valid #ToolShade object ;
 * @vectA: a pointer to a floating point values array to store vect in AX+B ;
 * @vectB: a pointer to a floating point values array to store vect in AX+B.
 *
 * This methods can get the linear color transformation. The given
 * arrays (@vectA, @vectB) are read-only. This method return
 * FALSE if the @shade is not in a #TOOL_SHADE_MODE_LINEAR state.
 *
 * Returns: TRUE if @vectA, @vectB and @vectX have been set correctly.
 */
gboolean tool_shade_getLinearCoeff(const ToolShade *shade,
                                   const float **vectA, const float **vectB)
{
  g_return_val_if_fail(shade, FALSE);
  g_return_val_if_fail(shade->mode == TOOL_SHADE_MODE_LINEAR, FALSE);
  g_return_val_if_fail(vectA && vectB, FALSE);
  
  *vectA = shade->vectA;
  *vectB = shade->vectB;
  return TRUE;
}
/**
 * tool_shade_setLinearCoeff:
 * @shade: a #ToolShade ;
 * @coeff: a new value ;
 * @channel: either RGBA (from 0 to 3) ;
 * @order: the order in the linear approx (0 means constant and 1 is
 * the linear coeeficient).
 *
 * Change one value @coeff of the linear mode for the given @shade.
 *
 * Returns: TRUE if the new value changes anything.
 */
gboolean tool_shade_setLinearCoeff(ToolShade *shade, float coeff, int channel, int order)
{
  float *pt;

  g_return_val_if_fail(shade, FALSE);
  g_return_val_if_fail(channel >= 0 && channel < 3 && order >= 0 && order < 2, FALSE);

  if (order == 0)
    pt = shade->vectB + channel;
  else
    pt = shade->vectA + channel;

  DBG_fprintf(stderr, "Tool ToolShade: set the %d value of vect[%d]"
	      " to %f (previuosly %f).\n", channel, order, coeff, *pt);

  if (*pt == coeff)
    return FALSE;

  *pt = coeff;
  return TRUE;
}
/**
 * tool_shade_channelToRGB:
 * @shade: a #ToolShade ;
 * @rgba: a location to store the result of the colour transformation ;
 * @values: inout values.
 *
 * Like tool_shade_valueToRGB() but here, the three values
 * are applied respectivly for the Red, the Green and the Blue
 * channel.
 */
void tool_shade_channelToRGB(const ToolShade *shade, float rgba[4], float values[3])
{
  guint i;

  g_return_if_fail(shade);

  /* DBG_fprintf(stderr, "Tool Shade: get RGB from (%g ; %g ; %g).\n", */
  /*             values[0], values[1], values[2]); */
  if (shade->mode == TOOL_SHADE_MODE_LINEAR)
    {
      rgba[0] = CLAMP(shade->vectA[0] * values[0] + shade->vectB[0], 0.f, 1.f);
      rgba[1] = CLAMP(shade->vectA[1] * values[1] + shade->vectB[1], 0.f, 1.f);
      rgba[2] = CLAMP(shade->vectA[2] * values[2] + shade->vectB[2], 0.f, 1.f);
    }
  else
    {
      for (i = 1; i < shade->nVals - 1; i++)
        if (values[0] < shade->index[i])
          break;
      rgba[0] = CLAMP(shade->vectCh[0][i - 1] +
		      (shade->vectCh[0][i] - shade->vectCh[0][i - 1]) *
		      (values[0] - shade->index[i - 1]) /
                      (shade->index[i] - shade->index[i - 1]), 0.f, 1.f);
      for (i = 1; i < shade->nVals - 1; i++)
        if (values[1] < shade->index[i])
          break;
      rgba[1] = CLAMP(shade->vectCh[1][i - 1] +
		      (shade->vectCh[1][i] - shade->vectCh[1][i - 1]) *
		      (values[1] - shade->index[i - 1]) /
                      (shade->index[i] - shade->index[i - 1]), 0.f, 1.f);
      for (i = 1; i < shade->nVals - 1; i++)
        if (values[2] < shade->index[i])
          break;
      rgba[2] = CLAMP(shade->vectCh[2][i - 1] +
		      (shade->vectCh[2][i] - shade->vectCh[2][i - 1]) *
		      (values[2] - shade->index[i - 1]) /
                      (shade->index[i] - shade->index[i - 1]), 0.f, 1.f);
    }
  /* Don't use alpha channel at present time. */
  rgba[3] = 1.;
  /* Transform if required. */
  if (shade->colorMode == TOOL_SHADE_COLOR_MODE_HSV)
    tool_color_convertHSVtoRGB(rgba, rgba);
}
/**
 * tool_shade_valueToRGB:
 * @shade: a valid #ToolShade object ;
 * @rgba: an array of size [4] ;
 * @value: the value ranged in [0;1].
 *
 * Give a RGBA vector for the given value.
 */
void tool_shade_valueToRGB(const ToolShade *shade, float rgba[4], float value)
{
  float vals[3];

  vals[0] = value;
  vals[1] = value;
  vals[2] = value;
  tool_shade_channelToRGB(shade, rgba, vals);
}

/*********************************************/
/* Methods to deal with internal shade list. */
/*********************************************/
/**
 * tool_shade_getStorage:
 *
 * It returns a read-only pointer to the internal shade list. Use tool_shade_appendList()
 * to add new shades to this list.
 *
 * Since: 3.8
 *
 * Returns: (transfer none): a pointer to the internal shade list.
 */
ToolPool* tool_shade_getStorage(void)
{
  if (!shadePool)
    _buildPresetList();

  return shadePool;
}
static void _buildPresetList(void)
{
  ToolShade *shade;
  float vectA[3], vectB[3];

  /* Zero Centred Colored. */
  #define zccLn 3
  float zccH[zccLn] = {0.f, 0.333f, 0.667f};
  float zccS[zccLn] = {1.0f, 0.0f, 1.0f};
  float zccV[zccLn] = {1.f, 1.f, 1.f};

  /* Zero Centred Light. */
  #define zclLn 3
  float zclR[zclLn] = {1.f, 1.f, 0.f};
  float zclG[zclLn] = {0.0f, 1.0f, 0.0f};
  float zclB[zclLn] = {0.f, 1.f, 1.f};

  /* Jet colour shade. */
  #define jetn 9
  float jetR[jetn] = {0.f, 0.f, 0.f, 0.f, 0.5f, 1.f, 1.f, 1.f, 0.5f};
  float jetG[jetn] = {0.f, 0.f, 0.5f, 1.f, 1.f, 1.f, 0.5f, 0.f, 0.f};
  float jetB[jetn] = {0.5f, 1.f, 1.f, 1.f, 0.5f, 0.f, 0.f, 0.f, 0.f};

  shadePool = tool_pool_new(TOOL_TYPE_SHADE, (GCompareFunc)_compare);

  /* Create a blue to red color range. */
  vectA[0] = -0.66667;
  vectA[1] = 0.;
  vectA[2] = 0.;
  vectB[0] = 0.66667;
  vectB[1] = 1.;
  vectB[2] = 1.;
  shade = tool_shade_new(_("blue to red"), vectA, vectB, TOOL_SHADE_COLOR_MODE_HSV);
  shade->userDefined = FALSE;
  tool_pool_take(shadePool, shade);

  /* Create a black to white (through yellow and red) color range. */
  vectA[0] = 2.66667;
  vectA[1] = 2.66667;
  vectA[2] = 4.;
  vectB[0] = 0.;
  vectB[1] = -1.;
  vectB[2] = -3.;
  shade = tool_shade_new(_("hot color"), vectA, vectB, TOOL_SHADE_COLOR_MODE_RGB);
  shade->userDefined = FALSE;
  tool_pool_take(shadePool, shade);

  /* Create a blue to yellow (through dark purple) color range. */
  vectA[0] = 1.33333;
  vectA[1] = 2.;
  vectA[2] = -2;
  vectB[0] = 0.;
  vectB[1] = -1.;
  vectB[2] = 1.;
  shade = tool_shade_new(_("blue to yellow"), vectA, vectB, TOOL_SHADE_COLOR_MODE_RGB);
  shade->userDefined = FALSE;
  tool_pool_take(shadePool, shade);

  /* Create a blue and red shade with black zero centred. */
  vectA[0] = -2.;
  vectA[1] = 0.;
  vectA[2] = 2.;
  vectB[0] = 1.;
  vectB[1] = 0.;
  vectB[2] = -1.;
  shade = tool_shade_new(_("zero centred dark"), vectA, vectB, TOOL_SHADE_COLOR_MODE_RGB);
  shade->userDefined = FALSE;
  tool_pool_take(shadePool, shade);

  /* Create a blue and red shade with withe zero centred. */
  shade = tool_shade_newFromData(_("zero centred light"), zclLn,
                                 zclR, zclG, zclB, TOOL_SHADE_COLOR_MODE_RGB);
  shade->userDefined = FALSE;
  tool_pool_take(shadePool, shade);

  shade = tool_shade_newFromData(_("zero centred coloured"), zccLn,
			    zccH, zccS, zccV, TOOL_SHADE_COLOR_MODE_HSV);
  shade->userDefined = FALSE;
  tool_pool_take(shadePool, shade);

  /* Create a green to red color range. */
  vectA[0] = -.3333;
  vectA[1] = 0.;
  vectA[2] = 0.;
  vectB[0] = 0.3333;
  vectB[1] = 1.;
  vectB[2] = 1.;
  shade = tool_shade_new(_("green to red"), vectA, vectB, TOOL_SHADE_COLOR_MODE_HSV);
  shade->userDefined = FALSE;
  tool_pool_take(shadePool, shade);

  /* Create a white to red color range. */
  vectA[0] = -.3333;
  vectA[1] = 0.8;
  vectA[2] = 0.;
  vectB[0] = 0.3333;
  vectB[1] = 0.1;
  vectB[2] = 1.;
  shade = tool_shade_new(_("light green to red"), vectA, vectB, TOOL_SHADE_COLOR_MODE_HSV);
  shade->userDefined = FALSE;
  tool_pool_take(shadePool, shade);

  /* Create a black to white color range. */
  vectA[0] = 0.;
  vectA[1] = 0.;
  vectA[2] = 1.;
  vectB[0] = 0.;
  vectB[1] = 0.;
  vectB[2] = 0.;
  shade = tool_shade_new(_("black to white"), vectA, vectB, TOOL_SHADE_COLOR_MODE_HSV);
  shade->userDefined = FALSE;
  tool_pool_take(shadePool, shade);

  /* Create a black to white color range. */
  vectA[0] = 0.;
  vectA[1] = 0.;
  vectA[2] = -1.;
  vectB[0] = 0.;
  vectB[1] = 0.;
  vectB[2] = 1.;
  shade = tool_shade_new(_("white to black"), vectA, vectB, TOOL_SHADE_COLOR_MODE_HSV);
  shade->userDefined = FALSE;
  tool_pool_take(shadePool, shade);
  
  /* Create a black to red (through purple) color range. */
  vectA[0] = 1.;
  vectA[1] = 1.;
  vectA[2] = 1.;
  vectB[0] = 0.;
  vectB[1] = 0.;
  vectB[2] = 0.;
  shade = tool_shade_new(_("purple color"), vectA, vectB, TOOL_SHADE_COLOR_MODE_HSV);
  shade->userDefined = FALSE;
  tool_pool_take(shadePool, shade);

  /* Create the so-called Jet colour map. */
  shade = tool_shade_newFromData(_("Jet map"), jetn,
                                 jetR, jetG, jetB, TOOL_SHADE_COLOR_MODE_RGB);
  shade->userDefined = FALSE;
  tool_pool_take(shadePool, shade);
}

static gboolean parseValue(gchar *line, float *index, float rgb[3], GError **error)
{
  gchar *name;
  PangoColor color;
  double index_;
  
  DBG_fprintf(stderr, "Tool Shade: parse step from '%s'\n", line);
  index_ = g_ascii_strtod(line, &name);
  if (errno != 0 || name == line)
    {
      *error = g_error_new(TOOL_CONFIG_FILE_ERROR, TOOL_CONFIG_FILE_ERROR_READ,
                           _("1 floating point value should start a step '%s'.\n"), line);
      return FALSE;
    }
  *index = (float)index_;
  DBG_fprintf(stderr, " | index %g\n", *index);
  
  name += 1;
  g_strdelimit(name, "\"'", ' ');
  g_strstrip(name);
  if (!pango_color_parse(&color, name))
    {
      *error = g_error_new(TOOL_CONFIG_FILE_ERROR, TOOL_CONFIG_FILE_ERROR_READ,
                           _("cannot read a color from '%s' (name, #rgb, #rrggbb ... awaited).\n"),
                           name);
      return FALSE;
    }
  rgb[0] = (float)color.red   / (float)G_MAXUINT16;
  rgb[1] = (float)color.green / (float)G_MAXUINT16;
  rgb[2] = (float)color.blue  / (float)G_MAXUINT16;
  DBG_fprintf(stderr, " | color %fx%fx%f\n", rgb[0], rgb[1], rgb[2]);

  return TRUE;
}
static void exportParameters(GString *data, VisuData *dataObj _U_)
{
  GList *lst;
  ToolShade *shade;
  guint i;
  PangoColor pcolor;
  gchar *color;
  GString *buf;

  visu_config_file_exportComment(data, DESC_SHADE);
  for (lst = tool_pool_asList(shadePool); lst; lst = g_list_next(lst))
    if (((ToolShade*)lst->data)->userDefined)
      {
        shade = (ToolShade*)lst->data;
        buf = g_string_new("");
        if (shade->userDefined)
          g_string_append(buf, shade->steps);
        else
          for (i = 0; i < shade->nVals ; i++)
            {
              if (i != 0)
                g_string_append_printf(buf, ", ");
              pcolor.red   = (guint16)(shade->vectCh[0][i] * (gfloat)G_MAXUINT16);
              pcolor.green = (guint16)(shade->vectCh[1][i] * (gfloat)G_MAXUINT16);
              pcolor.blue  = (guint16)(shade->vectCh[2][i] * (gfloat)G_MAXUINT16);
              color = pango_color_to_string(&pcolor);
              g_string_append_printf(buf, "%g %s", shade->index[i], color);
              g_free(color);
            }
        visu_config_file_exportEntry(data, FLAG_SHADE, shade->labelUTF8,
                                     "%s", buf->str);
        g_string_free(buf, TRUE);
      }
  visu_config_file_exportComment(data, "");
}
static gboolean readShade(VisuConfigFileEntry *entry, gchar **lines, int nbLines _U_, int position _U_,
                          GError **error)
{
  gchar *name, *descr;
  char *startDef, *endDef;
  ToolShade *shade;
  ToolPool *pool;
  
  name = g_strdup(visu_config_file_entry_getLabel(entry));

  startDef = strchr(lines[0], '(');
  if (!startDef)
    startDef = lines[0];
  else
    startDef += 1;
  endDef = strchr(startDef, ')');
  if (endDef)
    descr = g_strndup(startDef, endDef - startDef);
  else
    descr = g_strdup(startDef);

  shade = tool_shade_newFromString(g_strstrip(name), descr,
                                   TOOL_SHADE_COLOR_MODE_RGB, error);
  g_free(name);
  g_free(descr);

  if (!shade)
    return FALSE;
  pool = tool_shade_getStorage();
  tool_pool_take(pool, shade);

  return TRUE;
}
