/* -*- mode: C; c-basic-offset: 2 -*- */
/*   EXTRAITS DE LA LICENCE
	Copyright CEA, contributeurs : Damien
	CALISTE, laboratoire L_Sim, (2015-2022)
  
	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-2022)

	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 <epoxy/gl.h>
#include <epoxy/egl.h>
#include <string.h>

#include "opengl.h"
#include "visu_tools.h"
#include "iface_boxed.h"
#include "coreTools/toolConfigFile.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>
 */

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;
  guint dirtyPending;

  /* GPU pointers for offscreen rendering. */
  GLuint frameBuf, renderBuf, depthBuf;

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

  /* Used for offscreen rendering. */
  EGLDisplay eglDpy;
};

static void visu_gl_ext_set_dispose     (GObject* obj);
static void visu_gl_ext_set_finalize    (GObject* obj);
static gboolean visu_gl_ext_set_initContext (VisuGl *gl, GError **error);
static void visu_gl_ext_set_freeContext     (VisuGl *gl);
static void visu_gl_ext_set_draw            (VisuGl *gl);
static void visu_gl_ext_set_render          (VisuGl *gl);

/* Local callbacks */
static void onCamera(VisuGlView *view, gpointer data);

static void _appendDirty(VisuGlExtSet *set);

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)
{
  g_debug("Visu Extension Set: creating the class of the object.");
  /* g_debug("                - adding new signals ;"); */

  /* Connect the overloading methods. */
  G_OBJECT_CLASS(klass)->dispose  = visu_gl_ext_set_dispose;
  G_OBJECT_CLASS(klass)->finalize = visu_gl_ext_set_finalize;
  VISU_GL_CLASS(klass)->initContext = visu_gl_ext_set_initContext;
  VISU_GL_CLASS(klass)->freeContext = visu_gl_ext_set_freeContext;
  VISU_GL_CLASS(klass)->draw = visu_gl_ext_set_draw;
  VISU_GL_CLASS(klass)->render = visu_gl_ext_set_render;
}

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

  ext->priv->eglDpy = EGL_NO_DISPLAY;
  ext->priv->set = g_array_new(FALSE, FALSE, sizeof(struct _GlExt));
  ext->priv->reorderingNeeded = FALSE;
  ext->priv->dirtyPending = 0;
  ext->priv->frameBuf = 0;
  ext->priv->renderBuf = 0;
  ext->priv->depthBuf = 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);
}

/* 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;

  g_debug("Visu Extension Set: dispose object %p.", (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);

  g_debug("Visu Extension Set: releasing %d extensions.", 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)
        {
          g_debug("Visu Extension Set: releasing extension %p.",
                      (gpointer)s->ext);
          g_object_get(s->ext, "name", &name, NULL);
          g_debug(" | %s (%d)", 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));
    }

  if (ext->priv->eglDpy != EGL_NO_DISPLAY)
    {
      eglMakeCurrent(ext->priv->eglDpy,
                     EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
      eglTerminate(ext->priv->eglDpy);
    }

  /* 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);

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

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

  /* Chain up to the parent class */
  g_debug("Visu Extension Set: chain to parent.");
  G_OBJECT_CLASS(visu_gl_ext_set_parent_class)->finalize(obj);
  g_debug("Visu Extension Set: freeing ... OK.");
}

static const EGLint configAttribs[] =
  {
    EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
    EGL_BLUE_SIZE, 8,
    EGL_GREEN_SIZE, 8,
    EGL_RED_SIZE, 8,
    EGL_DEPTH_SIZE, 8,
    EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
    EGL_NONE
  };

/**
 * visu_gl_ext_set_initOffscreenContext:
 * @gl: a #VisuGl object.
 * @error: an error location.
 *
 * Create an OpenGL context for offscreen rendering. After this call,
 * the context is set current.
 *
 * Since: 3.9
 *
 * Returns: %TRUE if a context is successfully created.
 */
gboolean visu_gl_ext_set_initOffscreenContext(VisuGlExtSet *gl, GError **error)
{
  g_return_val_if_fail(VISU_IS_GL_EXT_SET(gl), FALSE);

  gl->priv->eglDpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);

  EGLint major, minor;
  eglInitialize(gl->priv->eglDpy, &major, &minor);
  g_debug("Visu Extension Set: EGL version %d.%d", major, minor);

  EGLint numConfigs;
  EGLConfig eglCfg;
  eglChooseConfig(gl->priv->eglDpy, configAttribs, &eglCfg, 1, &numConfigs);

  eglBindAPI(EGL_OPENGL_API);
  EGLContext eglCtx = eglCreateContext(gl->priv->eglDpy, eglCfg, EGL_NO_CONTEXT, 
                                       NULL);

  eglMakeCurrent(gl->priv->eglDpy, EGL_NO_SURFACE, EGL_NO_SURFACE, eglCtx);

  return visu_gl_initContext(VISU_GL(gl), error);
}

static gboolean visu_gl_ext_set_initContext(VisuGl *gl, GError **error)
{
  VisuGlExtSet *self = VISU_GL_EXT_SET(gl);
  guint i;

  g_return_val_if_fail(VISU_IS_GL_EXT_SET(self), FALSE);
  
  if (VISU_GL_CLASS(visu_gl_ext_set_parent_class)->initContext &&
      !VISU_GL_CLASS(visu_gl_ext_set_parent_class)->initContext(gl, error))
    return FALSE;

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

  if (!self->priv->frameBuf)
    glGenFramebuffers(1, &self->priv->frameBuf);
  if (!self->priv->frameBuf)
    {
      g_set_error(error, TOOL_GL_ERROR, ERROR_CREATE_OBJECT,
                  "Cannot create framebuffer object");
      return FALSE;
    }
  if (!self->priv->renderBuf)
    glGenRenderbuffers(1, &self->priv->renderBuf);
  if (!self->priv->renderBuf)
    {
      g_set_error(error, TOOL_GL_ERROR, ERROR_CREATE_OBJECT,
                  "Cannot create renderbuffer object");
      return FALSE;
    }
  if (!self->priv->depthBuf)
    glGenRenderbuffers(1, &self->priv->depthBuf);
  if (!self->priv->depthBuf)
    {
      g_set_error(error, TOOL_GL_ERROR, ERROR_CREATE_OBJECT,
                  "Cannot create depthbuffer object");
      return FALSE;
    }

  return TRUE;
}
static void visu_gl_ext_set_freeContext(VisuGl *gl)
{
  VisuGlExtSet *self = VISU_GL_EXT_SET(gl);
  guint i;

  g_return_if_fail(VISU_IS_GL_EXT_SET(self));

  if (VISU_GL_CLASS(visu_gl_ext_set_parent_class)->freeContext)
    VISU_GL_CLASS(visu_gl_ext_set_parent_class)->freeContext(gl);

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

  if (self->priv->frameBuf)
    glDeleteFramebuffers(1, &self->priv->frameBuf);
  self->priv->frameBuf = 0;
  if (self->priv->renderBuf)
    glDeleteRenderbuffers(1, &self->priv->renderBuf);
  self->priv->renderBuf = 0;
  if (self->priv->depthBuf)
    glDeleteRenderbuffers(1, &self->priv->depthBuf);
  self->priv->depthBuf = 0;
}

/**
 * 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_signal_handler_disconnect(G_OBJECT(set->priv->view), set->priv->chg_signal);
      g_object_unref(G_OBJECT(set->priv->view));
    }
  if (view)
    {
      g_object_ref(G_OBJECT(view));
      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 (!g_strcmp0(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_signal_emit_by_name(G_OBJECT(data), "dirty");

  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); */
  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;
  g_debug("Visu Extension Set: extension '%s' is dirty.",
              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)
    {
      g_debug("Visu Extension Set: sorting known extension"
              " depending on their priority.");
      g_array_sort(set->priv->set, compareExtensionPriority);
      set->priv->reorderingNeeded = FALSE;
    }
}

static void visu_gl_ext_set_draw(VisuGl *gl)
{
  VisuGlExtSet *set = VISU_GL_EXT_SET(gl);
  guint i;

  g_return_if_fail(VISU_IS_GL_EXT_SET(set));

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

static void visu_gl_ext_set_render(VisuGl *gl)
{
  int i_stereo, stereo;
  guint i;
  static int stereo_buf[2] = {GL_BACK_LEFT, GL_BACK_RIGHT};
  GLboolean glStereo;
  VisuGlExtSet *set = VISU_GL_EXT_SET(gl);
  VisuGlExtGlobals globals;
#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);
  
  glGetBooleanv(GL_STEREO, &glStereo);
  stereo = (glStereo && visu_gl_getStereo(VISU_GL(set))) ? 1 : 0;
  g_debug("Visu ExtSet: rendering with camera zoom at %g.",
          set->priv->view->camera.gross);
  visu_gl_view_getModelViewProjection(set->priv->view, &globals.mvp);
  visu_gl_view_getModelView(set->priv->view, &globals.MV);
  globals.resolution[0] = visu_gl_view_getWidth(set->priv->view);
  globals.resolution[1] = visu_gl_view_getHeight(set->priv->view);
  globals.camPosition[0] = set->priv->view->camera.eye[0];
  globals.camPosition[1] = set->priv->view->camera.eye[1];
  globals.camPosition[2] = set->priv->view->camera.eye[2];
  visu_gl_getFogColor(gl, globals.fogColor);
  if (visu_gl_getFogActive(gl))
    {
      gfloat nearFar[2], startEnd[2];
      gfloat fog[4] = {0.f, 0.f, 0.f, 1.f}, v[4];
      ToolGlMatrix P;

      visu_gl_getFogStartFull(gl, startEnd);
      visu_gl_view_getProjection(set->priv->view, &P);
      tool_gl_camera_getNearFar(&set->priv->view->camera, nearFar);
      fog[2] = -nearFar[0] - startEnd[0] * (nearFar[1] - nearFar[0]);
      tool_gl_matrix_vectorProd(v, &P, fog);
      globals.fogStartEnd[0] = (v[2] / v[3] + 1.f) / 2.f;
      fog[2] = -nearFar[0] - startEnd[1] * (nearFar[1] - nearFar[0]);
      tool_gl_matrix_vectorProd(v, &P, fog);
      globals.fogStartEnd[1] = (v[2] / v[3] + 1.f) / 2.f;
    }
  else
    {
      globals.fogStartEnd[0] = 20.f;
      globals.fogStartEnd[1] = 30.f;
    }

  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]);
          g_debug("Visu Extension Set: draw on buffer %d.", i_stereo);
        }

      glClear(GL_DEPTH_BUFFER_BIT);
      glEnable(GL_DEPTH_TEST);

      g_debug("Visu Extension Set: first pass.");
      if (visu_gl_getTrueTransparency(VISU_GL(set)))
        {
          glEnable(GL_ALPHA_TEST);
          glAlphaFunc(GL_EQUAL, 1.);
        }
      for (i = 0; i < set->priv->set->len; i++)
        if (visu_gl_ext_getPriority(g_array_index(set->priv->set, struct _GlExt, i).ext) < VISU_GL_EXT_PRIORITY_LAST)
          visu_gl_ext_call(g_array_index(set->priv->set, struct _GlExt, i).ext, &globals);
      if (visu_gl_getTrueTransparency(VISU_GL(set)))
        {
          g_debug("Visu Extension Set: second pass for transparency.");
          glAlphaFunc(GL_LESS, 1.);
          glDepthMask(GL_FALSE);
          for (i = 0; i < set->priv->set->len; i++)
            if (visu_gl_ext_getPriority(g_array_index(set->priv->set, struct _GlExt, i).ext) < VISU_GL_EXT_PRIORITY_LAST)
              visu_gl_ext_call(g_array_index(set->priv->set, struct _GlExt, i).ext, &globals);
          glDepthMask(GL_TRUE);
          glDisable(GL_ALPHA_TEST);
        }
      g_debug("Visu Extension Set: calling text rendering.");
      for (i = 0; i < set->priv->set->len; i++)
        if (visu_gl_ext_getPriority(g_array_index(set->priv->set, struct _GlExt, i).ext) < VISU_GL_EXT_PRIORITY_LAST)
          visu_gl_ext_callText(g_array_index(set->priv->set, struct _GlExt, i).ext, &globals);
      g_debug("Visu Extension Set: calling priority last extensions.");
      for (i = 0; i < set->priv->set->len; i++)
        if (visu_gl_ext_getPriority(g_array_index(set->priv->set, struct _GlExt, i).ext) == VISU_GL_EXT_PRIORITY_LAST)
          {
            visu_gl_ext_call(g_array_index(set->priv->set, struct _GlExt, i).ext, &globals);
            visu_gl_ext_callText(g_array_index(set->priv->set, struct _GlExt, i).ext, &globals);
          }
    }

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

/**
 * 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;
  guint row_length;
  gint m, n1, n2;
  guchar *row_tab;
  guint oldW, oldH;
  GLenum status;

  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);
  g_return_val_if_fail(set->priv->frameBuf && set->priv->renderBuf, (GArray*)0);

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

  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);

  g_debug("Visu ExtSet: pixmap export using framebuffer %d on renderbuffer %d.",
          set->priv->frameBuf, set->priv->renderBuf);
  glBindRenderbuffer(GL_RENDERBUFFER, set->priv->renderBuf);
  glRenderbufferStorage(GL_RENDERBUFFER, hasAlpha ? GL_RGBA8 : GL_RGB8, width, height);
  glBindRenderbuffer(GL_RENDERBUFFER, set->priv->depthBuf);
  glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height);

  glBindFramebuffer(GL_FRAMEBUFFER, set->priv->frameBuf);
  glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                            GL_RENDERBUFFER, set->priv->renderBuf);
  glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
                            GL_RENDERBUFFER, set->priv->depthBuf);
  status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  if (status != GL_FRAMEBUFFER_COMPLETE)
    g_warning("Incomplete framebuffer, status: %d", status);

  glViewport(0, 0, width, height);
  visu_gl_paint(VISU_GL(set));

  /* Copy the image into our buffer */
  glReadBuffer(GL_COLOR_ATTACHMENT0);
  n2 = 0;
  for(m = height - 1; m >= 0; m--)
    {
      glReadPixels(0, m, width, 1, hasAlpha ? GL_RGBA : 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);

  g_debug(" | save to array %p.", (gpointer)image);

  glBindRenderbuffer(GL_RENDERBUFFER, 0);
  glBindFramebuffer(GL_FRAMEBUFFER, 0);

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

static void onCamera(VisuGlView *view _U_, gpointer data)
{
  _appendDirty(VISU_GL_EXT_SET(data));
}
