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

	E-mail addresses :
	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 "surfaces_points.h"

#include <string.h>

#include <visu_tools.h>
#include <coreTools/toolMatrix.h>

/**
 * SECTION:surfaces_points
 * @short_description: Define a structure to store a set of triangles
 * defining a surface.
 *
 * <para>This structure is used to store and draw polyedges as a set
 * of XYZ points and a set of link to them.</para>
 */

/**
 * VisuSurfacePoints:
 * @nsurf: number of surfaces encoded in this structure ;
 * @bufferSize: number of stored float in addition to coordinates and
 * normals ;
 * @num_polys: number of polygoins stored in this structure ;
 * @num_points: number of vertices stored in this structure ;
 * @num_polys_surf: number of visible polygons stored in this structure per surface ;
 * @poly_surf_index: gives the id of the surface for each polygon,
 *                   this value ranges from - nsurf to + nsurf. abs(id - 1) gives
 *                   the index of the surface the polygon is attached to. If values
 *                   are negative, then the polygon is currently not used ;
 * @poly_num_vertices: gives the number of vertices used by each polygons ;
 * @poly_vertices: returns the id j of the vertices of polygon i ;
 * @poly_points_data: vectors giving additional data of vertex i.
 *
 * This structure stores geometric description of surfaces.
 * Several surfaces are stored in a single structure for improved performances.
 */

/**
 * visu_surface_point_new:
 * @pt: (out caller-allocates): a location to a #VisuSurfacePoint structure.
 * @at: (array fixed-size=3): coordinates.
 * @normal: (array fixed-size=3): normal.
 *
 * Initialise @pt with @at and @normal.
 *
 * Since: 3.8
 **/
void visu_surface_point_new(VisuSurfacePoint *pt,
                            const double at[3], const double normal[3])
{
  pt->at[0] = at[0];
  pt->at[1] = at[1];
  pt->at[2] = at[2];
  pt->normal[0] = normal[0];
  pt->normal[1] = normal[1];
  pt->normal[2] = normal[2];
}

/**
 * visu_surface_points_check:
 * @points: a set of points.
 *
 * A debug routines to check that all pointers and size are
 * relevant. It should not be used outside a debug area because it can
 * be slow.
 */
void visu_surface_points_check(VisuSurfacePoints *points)
{
  guint i, j;
  guint *nbPolys;

  /* Check the surface index. */
  DBG_fprintf(stderr, " | check surface index for each polygons.\n");
  for (i = 0; i < points->num_polys; i++)
    g_return_if_fail(ABS(points->poly_surf_index[i]) > 0 &&
		     (guint)ABS(points->poly_surf_index[i]) <= points->nsurf);

  /* Check vertice index. */
  DBG_fprintf(stderr, " | check vertice index for each polygons.\n");
  for (i = 0; i < points->num_polys; i++)
    for (j = 0; j < points->poly_num_vertices[i]; j++)
      g_return_if_fail(points->poly_vertices[i][j] < points->num_points);

  /* Check the number of polygons. */
  nbPolys = g_malloc(sizeof(int) * points->nsurf);
  memset(nbPolys, 0, sizeof(int) * points->nsurf);
  for (i = 0; i < points->num_polys; i++)
    if (points->poly_surf_index[i] > 0)
      nbPolys[points->poly_surf_index[i] - 1] += 1;
  for (i = 0; i < points->nsurf; i++)
    {
      DBG_fprintf(stderr, " | %d counted %7d : stored %7d\n", i, 
		  nbPolys[i], points->num_polys_surf[i]);
      g_return_if_fail(nbPolys[i] == points->num_polys_surf[i]);
    }
  g_free(nbPolys);
}
/**
 * visu_surface_points_translate:
 * @points: a set of points.
 * @xyz: a given translation in cartesian coordinates.
 *
 * In devel...
 */
void visu_surface_points_translate(VisuSurfacePoints *points, float xyz[3])
{
  gboolean *verticeStatus, visibility, boundary;
  guint i, j;
  int *boundaryPolys, nBounadryPolys;

  g_return_if_fail(points);

  DBG_fprintf(stderr, "IsosurfacesPoints: translate points %p of %gx%gx%g.\n",
	      (gpointer)points, xyz[0], xyz[1], xyz[2]);

  /* As for surface hide: translate and reput in the box
     except if the triangle has some points that have been
     reput in the box. */
  verticeStatus = g_malloc(sizeof(gboolean) * points->num_points);
  /* Apply the translation and compute a translation
     flag for each vertice. */
  for (i = 0; i < points->num_points; i++)
    {
      /* Translations are given in cartesian coordinates. */
/*       points->poly_points_data[j] += xyz[j]; */
      
/*       verticeStatus[i] = visu_plane_class_getVisibility(planes, surf->basePoints.poly_points_data[i]); */
    }
  /* We store the id of boundary polygons. */
  boundaryPolys = g_malloc(sizeof(int) * points->num_polys);
  nBounadryPolys = 0;
  /* Hide polygons. */
  for (i = 0; i < points->num_polys; i++)
    {
      visibility = TRUE;
      boundary = FALSE;
/*       if (surf->resources[ABS(points->poly_surf_index[i]) - 1]->sensitiveToPlanes) */
	{
	  for (j = 0; j < points->poly_num_vertices[i]; j++)
	    {
	      visibility = visibility && verticeStatus[points->poly_vertices[i][j]];
	      boundary = boundary || verticeStatus[points->poly_vertices[i][j]];
	    }
	  boundary = !visibility && boundary;
	}
      if (!visibility && points->poly_surf_index[i] > 0)
	{
	  /* Hide this polygon. */
	  points->num_polys_surf[points->poly_surf_index[i] - 1] -= 1;
	  points->poly_surf_index[i] = -points->poly_surf_index[i];
	}
      else if (visibility && points->poly_surf_index[i] < 0)
	{
	  /* Show this polygon. */
	  points->poly_surf_index[i] = -points->poly_surf_index[i];
	  points->num_polys_surf[points->poly_surf_index[i] - 1] += 1;
	}
      if (boundary)
	boundaryPolys[nBounadryPolys++] = i;
    }
/*   if (DEBUG) */
/*     for (i = 0; i < surf->nsurf; i++) */
/*       fprintf(stderr, , " | surface %2d -> %7d polygons\n", i, points->num_polys_surf[i]); */
  /* We count the number of boundaries per surface and allocate
     accordingly the volatile. */
}
/**
 * visu_surface_points_transform:
 * @points: a set of points.
 * @trans: a matrix.
 *
 * Apply @trans matrix to all vertices coordinates stored by @points.
 *
 * Since: 3.7
 **/
void visu_surface_points_transform(VisuSurfacePoints *points, float trans[3][3])
{
  guint i;
  float old_poly_points[6];

  g_return_if_fail(points);

  DBG_fprintf(stderr, " | apply change to %d points.\n",
              points->num_points);
  for (i = 0; i < points->num_points; i++)
    {
      old_poly_points[0] = points->poly_points_data[i][0];
      old_poly_points[1] = points->poly_points_data[i][1];
      old_poly_points[2] = points->poly_points_data[i][2];
      old_poly_points[3] = points->poly_points_data[i][VISU_SURFACE_POINTS_OFFSET_NORMAL + 0];
      old_poly_points[4] = points->poly_points_data[i][VISU_SURFACE_POINTS_OFFSET_NORMAL + 1];
      old_poly_points[5] = points->poly_points_data[i][VISU_SURFACE_POINTS_OFFSET_NORMAL + 2];
      tool_matrix_productVector(points->poly_points_data[i],
                                trans, old_poly_points);
      tool_matrix_productVector(points->poly_points_data[i] + VISU_SURFACE_POINTS_OFFSET_NORMAL,
                                trans, old_poly_points + 3);
    }
}
static void _reallocate(VisuSurfacePoints *points,
                        const guint nPoints, const guint nPolys)
{
  gboolean alloc;
  guint i;

  points->num_points = nPoints;

  if (nPoints > 0)
    {
      alloc = (points->poly_points_data == (float**)0);
      points->poly_points_data = g_realloc(points->poly_points_data,
                                           points->num_points * sizeof(float *));
      if (alloc)
        points->poly_points_data[0] = (float*)0;
      points->poly_points_data[0] = g_realloc(points->poly_points_data[0],
                                              (VISU_SURFACE_POINTS_OFFSET_USER +
                                               points->bufferSize) *
                                              points->num_points * sizeof(float));  
      for(i = 1; i < points->num_points; i++)
        points->poly_points_data[i] = points->poly_points_data[0] +
          i * (VISU_SURFACE_POINTS_OFFSET_USER + points->bufferSize);
    }
  else
    {
      if (points->poly_points_data)
        g_free(points->poly_points_data[0]);
      g_free(points->poly_points_data);
      points->poly_points_data = (float**)0;
    }

  points->num_polys = nPolys;

  if (nPolys > 0)
    {
      /* for each of the num_polys polygons will contain the surf value
         to which it belongs */
      points->poly_surf_index = g_realloc(points->poly_surf_index,
                                          points->num_polys * sizeof(int));
      /* for each of the num_polys polygons will contain the number
         of vertices in it */
      points->poly_num_vertices = g_realloc(points->poly_num_vertices,
                                            points->num_polys * sizeof(guint));
      /* for each of the num_polys polygons will contain the indices
         of vertices in it */   
      points->poly_vertices = g_realloc(points->poly_vertices,
                                        points->num_polys * sizeof(int*));
    }
  else
    {
      g_free(points->poly_surf_index);
      g_free(points->poly_num_vertices);
      g_free(points->poly_vertices);
    }
}
/**
 * visu_surface_points_remove:
 * @points: a set of points ;
 * @pos: an integer between 0 and points->nsurf.
 *
 * Remove the points belonging to surface number @pos.
 */
void visu_surface_points_remove(VisuSurfacePoints *points, guint pos)
{
  int nPoly, nPoint;
  guint i, j;
  int iPoly, iPoint;
  VisuSurfacePoints tmpPoints;
  gboolean *usedPoints;
  int *switchArray;

  points->nsurf -= 1;

  if (!points->num_points)
    {
      points->num_polys_surf = g_realloc(points->num_polys_surf,
					 points->nsurf * sizeof(int));
      return;
    }

  DBG_fprintf(stderr, "IsosurfacesPoints: remove surface %d from points %p.\n",
              pos, (gpointer)points);
  g_return_if_fail(pos <= points->nsurf);
  
  /* Special case when there is only one remaining surface. */
  if (points->nsurf == 0)
    {
      visu_surface_points_free(points);
      return;
    }

  /* Simple implementation is to create a new VisuSurfacePoints object arrays, and to
     copy everything, except the polygons belonging to the given pos. */

  /* Count number of poly and points to remove. */
  usedPoints = g_malloc(sizeof(gboolean) * points->num_points);
  memset(usedPoints, 0, sizeof(gboolean) * points->num_points);
  /* We don't use num_polys_surf since it is restricted to visible surfaces. */
  nPoly = 0;
  for (i = 0; i < points->num_polys; i++)
    if ((guint)(ABS(points->poly_surf_index[i]) - 1) != pos)
      {
	nPoly += 1;
	for (j = 0; j < points->poly_num_vertices[i]; j++)
	  usedPoints[points->poly_vertices[i][j]] = TRUE;
      }
  nPoint = 0;
  for (i = 0; i < points->num_points; i++)
    if (usedPoints[i])
      nPoint += 1;
  DBG_fprintf(stderr, " | remove %d polygons and %d points.\n",
	      points->num_polys - nPoly,
	      points->num_points - nPoint);

  visu_surface_points_init(&tmpPoints, points->bufferSize);
  _reallocate(&tmpPoints, nPoly, nPoint);

  /* Copy from surf to tmpSurf. */
  switchArray = g_malloc(sizeof(int) * points->num_points);
  iPoint = 0;
  for (i = 0; i < points->num_points; i++)
    if (usedPoints[i])
      {
	memcpy(tmpPoints.poly_points_data[iPoint],
	       points->poly_points_data[i], sizeof(float) *
	       (VISU_SURFACE_POINTS_OFFSET_USER + points->bufferSize));
	switchArray[i] = iPoint;
	iPoint += 1;
	if (iPoint > nPoint)
	  {
	    g_error("Incorrect point checksum.");
	  }
      }
  iPoly = 0;
  for (i = 0; i < points->num_polys; i++)
    {
      if ((guint)(ABS(points->poly_surf_index[i]) - 1) != pos)
	{
	  if (points->poly_surf_index[i] > (int)pos + 1)
	    tmpPoints.poly_surf_index[iPoly] = points->poly_surf_index[i] - 1;
	  else if (points->poly_surf_index[i] < -(int)pos - 1)
	    tmpPoints.poly_surf_index[iPoly] = points->poly_surf_index[i] + 1;
	  else
	    tmpPoints.poly_surf_index[iPoly] = points->poly_surf_index[i];
	  tmpPoints.poly_num_vertices[iPoly] = points->poly_num_vertices[i];
	  tmpPoints.poly_vertices[iPoly]     =
	    g_malloc(sizeof(int) * tmpPoints.poly_num_vertices[iPoly]);
	  for (j = 0; j < tmpPoints.poly_num_vertices[iPoly]; j++)
	    tmpPoints.poly_vertices[iPoly][j] =
	      switchArray[points->poly_vertices[i][j]];
	  iPoly += 1;
	  if (iPoly > nPoly)
	    {
	      g_error("Incorrect polygon checksum.");
	    }
	}
    }
  g_free(usedPoints);
  g_free(switchArray);
  /* Check sum. */
  if (iPoly != nPoly || iPoint != nPoint)
    {
      g_error("Incorrect checksum (%d %d | %d %d).", iPoly, nPoly, iPoint, nPoint);
    }

  /* Move the number of polygons per surface. */
  for (i = pos; i < points->nsurf; i++)
    points->num_polys_surf[i] = points->num_polys_surf[i + 1];
  points->num_polys_surf = g_realloc(points->num_polys_surf,
				     sizeof(int) * points->nsurf);

  /* We replace the arrays between tmpSurf and surf. */
  DBG_fprintf(stderr, " | switch and free arrays.\n");
  g_free(points->poly_surf_index);
  points->poly_surf_index = tmpPoints.poly_surf_index;

  g_free(points->poly_num_vertices);
  points->poly_num_vertices = tmpPoints.poly_num_vertices;

  for (i = 0; i< points->num_polys; i++)
    g_free(points->poly_vertices[i]);
  g_free(points->poly_vertices);
  points->poly_vertices = tmpPoints.poly_vertices;

  g_free(points->poly_points_data[0]);
  g_free(points->poly_points_data);
  points->poly_points_data = tmpPoints.poly_points_data;

  /* additionnal tuning. */
  points->num_polys  = nPoly;
  points->num_points = nPoint;
}
/**
 * visu_surface_points_free:
 * @points: a set of points.
 *
 * Free all allocated arrays of the given set of points. The point
 * structure itself is not freed.
 */
void visu_surface_points_free(VisuSurfacePoints *points)
{
  guint i;

  if(points->num_polys == 0)
    return;

  if (points->num_polys_surf)
    g_free(points->num_polys_surf);
  if (points->poly_surf_index)
    g_free(points->poly_surf_index);
  if (points->poly_num_vertices)
    g_free(points->poly_num_vertices);
  if (points->poly_vertices)
    {
      for (i = 0; i < points->num_polys; i++)
	g_free(points->poly_vertices[i]);
      g_free(points->poly_vertices);
    }
  if (points->poly_points_data)
    {
      g_free(points->poly_points_data[0]);
      g_free(points->poly_points_data);
    }

  points->nsurf      = 0;
  points->num_polys  = 0;
  points->num_points = 0;
  points->num_polys_surf = (guint*)0;
  points->poly_surf_index = (int*)0;
  points->poly_num_vertices = (guint*)0;
  points->poly_vertices = (guint**)0;
  points->poly_points_data = (float **)0;
}
/**
 * visu_surface_points_init:
 * @points: a pointer on a set of points (not initialised) ;
 * @bufferSize: the number of additional data to coordinates and
 * normals.
 *
 * Initialise a VisuSurfacePoints structure. It must be done before any use.
 */
void visu_surface_points_init(VisuSurfacePoints *points, int bufferSize)
{
  g_return_if_fail(bufferSize >= 0 && points);
  DBG_fprintf(stderr, "Surfaces Points: initialise point definitions (%p-%d).\n",
	  (gpointer)points, bufferSize);

  points->nsurf      = 0;
  points->num_polys  = 0;
  points->num_points = 0;
  points->bufferSize = bufferSize;

  points->num_polys_surf = (guint*)0;
  points->poly_surf_index = (int*)0;
  points->poly_num_vertices = (guint*)0;
  points->poly_vertices = (guint**)0;
  points->poly_points_data = (float **)0;
}
/**
 * visu_surface_points_addPoly:
 * @points: a #VisuSurfacePoints object.
 * @vertices: (element-type VisuSurfacePoint): a set of #VisuSurfacePoint. 
 * @polys: (element-type VisuSurfacePoly): a set of #VisuSurfacePoly.
 *
 * Add a new surface in @points with the given definition of @vertices
 * and @polys.
 *
 * Since: 3.8
 **/
void visu_surface_points_addPoly(VisuSurfacePoints *points,
                                  const GArray *vertices, const GArray *polys)
{
  guint i, n, old_num_points, old_num_polys;
  float *fval;
  VisuSurfacePoint *point;
  VisuSurfacePoly *poly;

  g_return_if_fail(points);

  points->nsurf += 1;
  points->num_polys_surf = g_realloc(points->num_polys_surf,
                                     points->nsurf * sizeof(int));
  points->num_polys_surf[points->nsurf - 1] = (polys) ? polys->len : 0;

  if (!vertices || !vertices->len ||
      !polys || !polys->len)
    return;

  old_num_points = points->num_points;
  old_num_polys = points->num_polys;

  _reallocate(points, points->num_points + vertices->len, points->num_polys + polys->len);

  DBG_fprintf(stderr, " | copy vertices.\n");
  for (n = 0; n < vertices->len; n++)
    {
      fval = points->poly_points_data[old_num_points + n];
      point = &g_array_index(vertices, VisuSurfacePoint, n);
      fval[0] = point->at[0];
      fval[1] = point->at[1];
      fval[2] = point->at[2];
      fval[VISU_SURFACE_POINTS_OFFSET_NORMAL + 0] = -point->normal[0];
      fval[VISU_SURFACE_POINTS_OFFSET_NORMAL + 1] = -point->normal[1];
      fval[VISU_SURFACE_POINTS_OFFSET_NORMAL + 2] = -point->normal[2];
    }

  DBG_fprintf(stderr, " | copy poly.\n");
  for (n = 0; n < polys->len; n++)
    {
      poly = &g_array_index(polys, VisuSurfacePoly, n);
      points->poly_surf_index[old_num_polys + n] = points->nsurf;
      points->poly_num_vertices[old_num_polys + n] = poly->nvertices;
      points->poly_vertices[old_num_polys + n] =
        g_malloc(sizeof(int) * poly->nvertices);
      for (i = 0; i < poly->nvertices; i++)
        points->poly_vertices[old_num_polys + n][poly->nvertices - i - 1] =
          poly->indices[i] + old_num_points;
    }
}
/**
 * visu_surface_points_hide:
 * @points: a #VisuSurfacePoints object.
 * @resource: a #VisuSurfaceResource object.
 * @edges: (out caller-allocates): a #VisuSurfacePoints location.
 * @planes: a #VisuPlaneSet object.
 *
 * Apply the masking properties of @planes on @points, creating
 * additional vertices and polygons to smooth the edges of the cut
 * surface in @edges.
 *
 * Since: 3.8
 *
 * Returns: TRUE if some polygons of @points have changed visibility.
 **/
gboolean visu_surface_points_hide(VisuSurfacePoints *points,
                                  const VisuSurfaceResource *resource,
                                  VisuSurfacePoints *edges,
                                  const VisuPlaneSet *planes)
{
  guint i, j, iv;
  int k, iPoly, isurf, iVertice, n;
  gboolean *verticeStatus;
  gboolean visibility, redraw, boundary, valid;
  int *boundaryPolys;
  guint nBounadryPolys;
  int npolys, npoints;

  g_return_val_if_fail(points && edges, FALSE);

  if (!planes)
    {
      for (i = 0; i < points->num_polys; i++)
        points->poly_surf_index[i] = ABS(points->poly_surf_index[i]);
      points->num_polys_surf[0] = points->num_polys;
      return TRUE;
    }

  verticeStatus = g_malloc(sizeof(gboolean) * points->num_points);
  redraw = FALSE;
  /* Compute a visibility flag for each vertice. */
  for (i = 0; i < points->num_points; i++)
    verticeStatus[i] =
      visu_plane_set_getVisibility(planes, points->poly_points_data[i]);
  /* We store the id of boundary polygons. */
  boundaryPolys = g_malloc(sizeof(int) * points->num_polys);
  nBounadryPolys = 0;
  /* Hide polygons. */
  for (i = 0; i < points->num_polys; i++)
    {
      visibility = TRUE;
      boundary = FALSE;
      if (visu_surface_resource_getMaskable(resource))
	{
	  for (j = 0; j < points->poly_num_vertices[i]; j++)
	    {
	      visibility = visibility && verticeStatus[points->poly_vertices[i][j]];
	      boundary = boundary || verticeStatus[points->poly_vertices[i][j]];
	    }
	  boundary = !visibility && boundary;
	}
      if (!visibility && points->poly_surf_index[i] > 0)
	{
	  /* Hide this polygon. */
	  points->num_polys_surf[points->poly_surf_index[i] - 1] -= 1;
	  points->poly_surf_index[i] = -points->poly_surf_index[i];
	  redraw = TRUE;
	}
      else if (visibility && points->poly_surf_index[i] < 0)
	{
	  /* Show this polygon. */
	  points->poly_surf_index[i] = -points->poly_surf_index[i];
	  points->num_polys_surf[points->poly_surf_index[i] - 1] += 1;
	  redraw = TRUE;
	}
      if (boundary)
	boundaryPolys[nBounadryPolys++] = i;
    }
  if (DEBUG)
    for (i = 0; i < points->nsurf; i++)
      fprintf(stderr, " | surface %2d -> %7d polygons\n", i, points->num_polys_surf[i]);
  /* We count the number of boundaries per surface and allocate
     accordingly the volatile. */
  npolys  = nBounadryPolys;
  npoints = 0;
  for (i = 0; i < nBounadryPolys; i++)
    {
      /* The number of points to add is the number of visible points plus 2. */
      npoints += 2;
      for (j = 0; j < points->poly_num_vertices[boundaryPolys[i]]; j++)
	if (verticeStatus[points->poly_vertices[boundaryPolys[i]][j]])
	  npoints += 1;
    }
  DBG_fprintf(stderr, "Isosurfaces: volatile polygons.\n");
  DBG_fprintf(stderr, " | polys %d, points %d\n", npolys, npoints);
  _reallocate(edges, npoints, npolys);
  edges->nsurf = points->nsurf;
  edges->num_polys_surf = g_realloc(edges->num_polys_surf,
                                    edges->nsurf * sizeof(int));
  for (i = 0; i < edges->nsurf; i++)
    edges->num_polys_surf[i] = 0;
  edges->num_polys  = 0;
  edges->num_points = 0;
  /* We copy the polygons and the vertices in the volatile part. */
  for (i = 0; i < nBounadryPolys; i++)
    {
      isurf = -points->poly_surf_index[boundaryPolys[i]] - 1;
      iPoly = edges->num_polys;
      iVertice = edges->num_points;

      edges->num_polys_surf[isurf] += 1;
      edges->poly_surf_index[iPoly] = (int)isurf + 1;
      n = 2;
      for (j = 0; j < points->poly_num_vertices[boundaryPolys[i]]; j++)
	if (verticeStatus[points->poly_vertices[boundaryPolys[i]][j]])
	  n += 1;
      edges->poly_num_vertices[iPoly] = n;
      edges->poly_vertices[iPoly] = g_malloc(sizeof(int) * n);
      n = points->poly_num_vertices[boundaryPolys[i]];
      /* Compute new vertex. */
      iv = 0;
      for (k = 0; k < n; k++)
	{
	  /* If vertex is visible, we put it. */
	  if (verticeStatus[points->poly_vertices[boundaryPolys[i]][k]])
	    {
	      memcpy(edges->poly_points_data[iVertice],
		     points->poly_points_data[points->poly_vertices[boundaryPolys[i]][k]],
		     sizeof(float) * (VISU_SURFACE_POINTS_OFFSET_USER + edges->bufferSize));
	      g_return_val_if_fail(iv < edges->poly_num_vertices[iPoly], redraw);
	      edges->poly_vertices[iPoly][iv] = iVertice;
	      iVertice += 1;
	      iv += 1;
	    }
	  /* If next vertex brings a visibility change, we compute intersection. */
	  if ((!verticeStatus[points->poly_vertices[boundaryPolys[i]][k]] &&
	       verticeStatus[points->poly_vertices[boundaryPolys[i]][(k + 1)%n]]))
	    {
	      /* We take the previous and compute the intersection. */
	      valid = visu_plane_set_getIntersection
		(planes,
		 points->poly_points_data[points->poly_vertices[boundaryPolys[i]][(k + 1)%n]],
		 points->poly_points_data[points->poly_vertices[boundaryPolys[i]][k]],
		 edges->poly_points_data[iVertice], TRUE);
	      g_return_val_if_fail(valid, redraw);
	      /* Other values than coordinates are copied. */
	      memcpy(edges->poly_points_data[iVertice] + 3,
		     points->poly_points_data[points->poly_vertices[boundaryPolys[i]][(k + 1)%n]] + 3,
		     sizeof(float) * (VISU_SURFACE_POINTS_OFFSET_USER + edges->bufferSize - 3));
	      g_return_val_if_fail(iv < edges->poly_num_vertices[iPoly], redraw);
	      edges->poly_vertices[iPoly][iv] = iVertice;
	      iVertice += 1;
	      iv += 1;
	    }
	  if ((verticeStatus[points->poly_vertices[boundaryPolys[i]][k]] &&
	       !verticeStatus[points->poly_vertices[boundaryPolys[i]][(k + 1)%n]]))
	    {
	      /* We take the previous and compute the intersection. */
	      valid = visu_plane_set_getIntersection
		(planes, points->poly_points_data[points->poly_vertices[boundaryPolys[i]][k]],
		 points->poly_points_data[points->poly_vertices[boundaryPolys[i]][(k + 1)%n]],
		 edges->poly_points_data[iVertice], TRUE);
	      g_return_val_if_fail(valid, redraw);
	      memcpy(edges->poly_points_data[iVertice] + 3,
		     points->poly_points_data[points->poly_vertices[boundaryPolys[i]][k]] + 3,
		     sizeof(float) * (VISU_SURFACE_POINTS_OFFSET_USER + edges->bufferSize - 3));
	      g_return_val_if_fail(iv < edges->poly_num_vertices[iPoly], redraw);
	      edges->poly_vertices[iPoly][iv] = iVertice;
	      iVertice += 1;
	      iv += 1;
	    }
	}
      edges->num_polys += 1;
      edges->num_points = iVertice;
    }
  g_free(verticeStatus);
  g_free(boundaryPolys);

  return redraw;
}
