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

	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 "renderingAtomic.h"
#include "renderingAtomic_ascii.h"
#include "renderingAtomic_d3.h"
#include "atomic_xyz.h"
#include <visu_elements.h>
#include <visu_configFile.h>
#include <coreTools/toolFileFormat.h>
#include <renderingBackend/visu_windowInterface.h>
#include <openGLFunctions/view.h>
#include <openGLFunctions/objectList.h>
#include <opengl.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* The OpenGL identifier to store the glObjectLists that
   describe the spheres. */
int identifierSpheres;

#define RADIUS_DEFAULT 1.
#define SHAPE_DEFAULT shapeSphere
/* Dealing with the radius resource. */
#define FLAG_RESOURCE_RADIUS_SHAPE "atomic_radius_shape"
#define DESC_RESOURCE_RADIUS_SHAPE "The radius of the element and its shape, a real > 0. & [Sphere Cube]"
gboolean renderingAtomicRead_atomicRadiusShape(gchar **lines, int nbLines,
					       int position, GString *errorMessage);
/* These functions write all the element list to export there associated resources. */
gboolean renderingAtomicExport_atomicRadiusShape(GString *data, int *nbLinesWritten);

const char* shapeName[3] = {"Sphere", "Cube", (const char*)0};
const char* shapeNameI18n[3];
struct atomicResources_struct
{
  float radius;
  int shape;
};

/* The files methods. */
int loadAtomic(VisuData *data, GString **errormessage);
int tryDifferentAtomicFormats(VisuData* data, const char* fileName, VisuIO *io);

void freeAtomicStruct(gpointer data);

RenderingMethod* initAtomic()
{
  RenderingMethod *atom;
  char *name = _("Atom visualisation");
  char *descr = _("It draws spheres at specified positions to represent atoms."
		  " The radius of the sphere can vary.");
  char *typeD3[] = {"*.d3", (char*)0};
  char *descrD3 = _("Binary format");
  char *typeASCII[] = {"*.ascii", (char*)0};
  char *descrASCII = _("'x y z Element' format");
  char *typeXYZ[] = {"*.xyz", (char*)0};
  char *descrXYZ = _("'Element x y z' format");
  FileFormat *fmt;
  GList *formatList;
  gchar *iconPath;

  VisuConfigFileEntry *resourceEntry;

  DBG_fprintf(stderr,"Initialising the atomic rendering method...\n");
  formatList = (GList*)0;
  fmt = fileFormatNew(descrD3, typeD3);
  if (!fmt)
    g_error("Can't initialize the rendering atomic method, aborting...\n");

  formatList = g_list_append(formatList, (gpointer)fmt);
  fmt = fileFormatNew(descrASCII, typeASCII);
  if (!fmt)
    g_error("Can't initialize the rendering atomic method, aborting...\n");

  formatList = g_list_append(formatList, (gpointer)fmt);
  fmt = fileFormatNew(descrXYZ, typeXYZ);
  if (!fmt)
    g_error("Can't initialize the rendering atomic method, aborting...\n");

  formatList = g_list_append(formatList, (gpointer)fmt);
  atom = renderingMethod_new("Atom visualisation", name, descr, 1, loadAtomic);
  renderingMethodSet_fileType(atom, formatList, 0, _("Position files"));
  iconPath = g_build_filename(v_sim_pixmaps_dir, "stock-atomic.png", NULL);
  renderingMethodSet_icon(atom, iconPath);
  g_free(iconPath);
  setOpenGLMethods(atom, renderingAtomic_createShape,
		   renderingAtomic_positionShape,
		   renderingAtomicGet_radius);

  resourceEntry = visuConfigFileAdd_entry(VISU_CONFIGFILE_RESOURCE,
					  FLAG_RESOURCE_RADIUS_SHAPE,
					  DESC_RESOURCE_RADIUS_SHAPE,
					  1,
					  renderingAtomicRead_atomicRadiusShape);
  visuConfigFileAdd_exportFunction(VISU_CONFIGFILE_RESOURCE,
				   renderingAtomicExport_atomicRadiusShape);
					  

  /* Initialise the OpenGl part. */
  identifierSpheres = openGLObjectList_new(NMAX_TP);

  /* Set the general pointer to retrieve easily this method. */
  pointerOnRenderingAtomicMethod = atom;

  shapeNameI18n[0] = _("Sphere");
  shapeNameI18n[1] = _("Cube");
  shapeNameI18n[2] = (const char*)0;

  return atom;
}

int loadAtomic(VisuData *data, GString **errormessage)
{
  gchar *file, *fileUTF8;
  VisuIO io;
  int nbLine;
  int res;

  if (errormessage)
    *errormessage = (GString*)0;

  if (!data)
    return 0;
  
  io.informations = g_string_new("");

  file = visuDataGet_file(data, 0);
  if (!file)
    {
      g_string_append_printf(io.informations, "No file name available.");
      if (errormessage)
	*errormessage = io.informations;
      return 0;
    }
  
  fileUTF8 = getStringInUTF8(file);
  g_string_append_printf(io.informations, "Loading data file '%s'...\n\n", file);
  g_free(fileUTF8);

  nbLine = 0;
  io.nbLine = &nbLine;

  if (g_file_test(file, G_FILE_TEST_IS_DIR))
    {
      g_string_append_printf(io.informations, _("WARNING! The specified file is"
						" a directory indeed. Can't load"
						" a directory!\n"));
      if (errormessage)
	*errormessage = io.informations;
      return 0;
    }
  res = tryDifferentAtomicFormats(data, (char*)file, &io);
  if (!res)
    {
      if (errormessage)
	*errormessage = io.informations;
      return 0;
    }
  else
    {
      if (errormessage)
	*errormessage = io.informations;
    }

  return 1;
}

int tryDifferentAtomicFormats(VisuData* data, const char* fileName, VisuIO *io)
{
  int res;
  GString *tmp;
  FILE *readFrom;

  tmp = g_string_new(io->informations->str);

  if (!data)
    return 0;

  DBG_fprintf(stderr,"Rendering Atomic : testing '%s' as a d3 file.\n", fileName);
  readFrom = fopen(fileName, "r");
  if (!readFrom)
    {
      g_string_append_printf(io->informations, _("WARNING : impossible to open this file.\n"));
      return 0;
    }
  io->flux = &readFrom;
  res = read_d3_file(data, io);
  fclose(*io->flux);
  if (res < 0)
    {
      DBG_fprintf(stderr,"Rendering Atomic : it is not a d3 file, trying as ascii file.\n");
      /* We don't have a D3 file.
	 We test with a ascii one. */
      g_string_free(io->informations, TRUE);
      io->informations = tmp;
      tmp = g_string_new(io->informations->str);

      readFrom = fopen(fileName, "r");
      if (!readFrom)
	{
	  g_string_append_printf(io->informations, _("WARNING : impossible to open this file.\n"));
	  return 0;
	}
      io->flux = &readFrom;
      res = read_ascii_file(data, io);
      fclose(*io->flux);
      if(res < 0)
	{
	  DBG_fprintf(stderr,"Rendering Atomic : it is not an ascii file,"
		      " trying as xyz file.\n");
	  g_string_free(io->informations, TRUE);
	  io->informations = tmp;
	  tmp = g_string_new(io->informations->str);

	  readFrom = fopen(fileName, "r");
	  if (!readFrom)
	    {
	      g_string_append_printf(io->informations,
				     _("WARNING : impossible to open this file.\n"));
	      return 0;
	    }
	  io->flux = &readFrom;
	  res = read_xyz_file(data, io);
	  fclose(*io->flux);
	  if (res)
	    return 0;
	}
      else if (res > 0)
	return 0;
    }
  else if (res > 0)
    return 0;

  g_string_free(tmp, TRUE);
  DBG_fprintf(stderr,"Rendering Atomic : loading OK.\n");

  return 1;
}

void freeAtomicStruct(gpointer data)
{
  if (data)
    free(data);
}

struct atomicResources_struct* createDefaultAtomicStruct()
{
  struct atomicResources_struct *str;

  str = malloc(sizeof(struct atomicResources_struct));
  if (!str)
    {
      allocationProblems();
      exit(1);
    }
  str->radius = RADIUS_DEFAULT;
  str->shape = SHAPE_DEFAULT;

  return str;
}

float renderingAtomicGet_radius(VisuElement *ele)
{
  struct atomicResources_struct *str;

  if (!ele)
    return RADIUS_DEFAULT;

  str = (struct atomicResources_struct*)visuElementGet_property(ele, "radiusAndShape");
  /* g_hash_table_lookup(shapeAndRadiusResource, (gpointer)ele); */
  if (!str)
    {
      str = createDefaultAtomicStruct();
      visuElementSet_property(ele, "radiusAndShape", (gpointer)str);
/*       g_hash_table_insert(shapeAndRadiusResource, (gpointer)ele, (gpointer)str); */
    }
  return str->radius;
}
float renderingAtomicGet_radiusDefault()
{
  return RADIUS_DEFAULT;
}
int renderingAtomicSet_radius(VisuElement* ele, float value)
{
  struct atomicResources_struct *str;

  if (!ele)
    return 0;
  
  str = (struct atomicResources_struct*)visuElementGet_property(ele, "radiusAndShape");
/*   str = g_hash_table_lookup(shapeAndRadiusResource, (gpointer)ele); */
  if (!str)
    {
      str = createDefaultAtomicStruct();
      visuElementSet_property(ele, "radiusAndShape", (gpointer)str);
/*       g_hash_table_insert(shapeAndRadiusResource, (gpointer)ele, (gpointer)str); */
    }
  if (value <= 0.)
    {
      fprintf(stderr, "WARNING! Trying to set a negative value (%f)"
	      " for the radius of VisuElement '%s'.\n", value, ele->name);
      str->radius = 1.;
    }
  else if (value == str->radius)
    return 0;
  else
    str->radius = value;

  /* Ask for reDraw if needed. */
  return 1;
}

int renderingAtomicGet_shape(VisuElement *ele)
{
  struct atomicResources_struct *str;

  str = (struct atomicResources_struct*)visuElementGet_property(ele, "radiusAndShape");
/*   str = g_hash_table_lookup(shapeAndRadiusResource, (gpointer)ele); */
  if (!str)
    return -1;
  else
    return str->shape;
}
const char* renderingAtomicGet_shapeName(int shape)
{
  if (shape < 0 || shape >= nbShapes)
    return (char*)0;
  else
    return shapeName[shape];
}
const char* renderingAtomicGet_shapeNameDefault()
{
  return shapeName[SHAPE_DEFAULT];
}
int renderingAtomicGet_shapeDefault()
{
  return SHAPE_DEFAULT;
}
int renderingAtomicSet_shape(VisuElement *ele, int shape)
{
  struct atomicResources_struct *str;

  if (!ele || shape < 0 || shape >= nbShapes)
    {
      fprintf(stderr, "WARNING! Wrong parameters to the call of renderingAtomicSet_shape.\n");
      return 0;
    }
  
  str = (struct atomicResources_struct*)visuElementGet_property(ele, "radiusAndShape");
/*   str = g_hash_table_lookup(shapeAndRadiusResource, (gpointer)ele); */
  if (!str)
    {
      str = createDefaultAtomicStruct();
      visuElementSet_property(ele, "radiusAndShape", (gpointer)str);
/*       g_hash_table_insert(shapeAndRadiusResource, (gpointer)ele, (gpointer)str); */
    }
  if (shape == str->shape)
    return 0;
  else
    str->shape = shape;

  return 1;
}
int renderingAtomicSet_shapeFromName(VisuElement *ele, char* shape)
{
  int res, i;

  res = -1;
  for (i = 0; shapeName[i] && res < 0; i++)
    {
      if (!strcmp(shapeName[i], shape))
	res = i;
    }
  if (res < 0)
    {
      fprintf(stderr, "WARNING! Unknown shape name in the call of renderingAtomicSet_shapeFromName.\n");
      return 0;
    }
  else
    return renderingAtomicSet_shape(ele, res);
}
const char** renderingAtomicGet_allShapes()
{
  return shapeName;
}
const char** renderingAtomicGet_allShapesI18n()
{
  return shapeNameI18n;
}


gboolean renderingAtomicRead_atomicRadiusShape(gchar **lines, int nbLines,
					       int position, GString *errorMessage)
{
  VisuElement* ele;
  char *cursor;
  int res, shapeNum, errorFlag, i;
  float radius;
  char shape[MAX_LINE_LENGTH];
  GenericRenderingWindow window;

  cursor = lines[0];
  ele = visuElementGet_fromValueLine(&cursor, -1, &errorFlag);
  if (!ele)
    {
      if (errorMessage)
	visuElementPrint_errorFromValueLine(errorMessage, position, errorFlag);
      return FALSE;
    }
  res = sscanf(cursor, "%f %s", &radius, shape);
  if (res != 2 || radius <=0.)
    {
      if (errorMessage)
	g_string_append_printf(errorMessage, _("WARNING! Parse error at line %d,"
					       " 1 floating point value (v > 0.) and a shape name "
					       "must appear after the %s markup.\n"),
			       position, FLAG_RESOURCE_RADIUS_SHAPE);
      return FALSE;
    }
  shapeNum = -1;
  for (i = 0; shapeName[i] && shapeNum < 0; i++)
    {
      if (!strcmp(shapeName[i], shape))
	shapeNum = i;
    }
  if (shapeNum < 0)
    {
      if (errorMessage)
	g_string_append_printf(errorMessage, _("WARNING! Parse error at line %d,"
					       " the shape '%s' is unknown.\n"),
			       position, shape);
      return 1;
    }
  res = renderingAtomicSet_radius(ele, radius);
  res = renderingAtomicSet_shape(ele, shapeNum) || res;

  window = visuRenderingWindowGet_current();
  if (res && window && visuRenderingWindowGet_visuData(window))
    renderingAtomic_createShape(visuDataGet_openGLView(visuRenderingWindowGet_visuData(window)),
				ele);
  
  return TRUE;
}

/* These functions write all the element list to export there associated resources. */
gboolean renderingAtomicExport_atomicRadiusShape(GString *data, int *nbLinesWritten)
{
  GList *pos;
  struct atomicResources_struct *str;

  g_string_append_printf(data, "# %s\n", DESC_RESOURCE_RADIUS_SHAPE);
  *nbLinesWritten = 1;
  pos = visuElementGet_allElements();
  while(pos)
    {
      str = (struct atomicResources_struct*)visuElementGet_property((VisuElement*)pos->data,
								    "radiusAndShape");
      if (str)
	{
	  g_string_append_printf(data, "%s:\n", FLAG_RESOURCE_RADIUS_SHAPE);
	  g_string_append_printf(data, "    %s %10.3f %s\n", ((VisuElement*)pos->data)->name,
				 str->radius, shapeName[str->shape]);
	  *nbLinesWritten += 2;
	}
      pos = g_list_next(pos);
    }
  g_string_append_printf(data, "\n");
  *nbLinesWritten += 1;

  return TRUE;
}


/***************/
/* OpenGL part */
/***************/

void renderingAtomic_positionShape(VisuData *visuData, VisuNode *node, VisuElement* ele)
{
  float rgba[4];
  float xyz[3];
  OpenGLView *view;

  visuDataGet_nodePosition(visuData, node, xyz);
  view = visuDataGet_openGLView(visuData);
  g_return_if_fail(view);

  glPushMatrix();
  glTranslated(xyz[0] - view->box->dxxs2,
	       xyz[1] - view->box->dyys2,
	       xyz[2] - view->box->dzzs2);
  if (visuData->setColor)
    {
      visuData->setColor(visuData, rgba, ele, node);
      setOpenGlMaterial(ele->material, rgba);
    }
  glCallList(ele->openGLIdentifier);
  glPopMatrix();
}

void renderingAtomic_createShape(OpenGLView *view, VisuElement* ele)
{
  struct atomicResources_struct *str;
  int nlat;
/*   int i, j; */
/*   float alpha, beta; */
/*   float alpha1, beta1; */

  g_return_if_fail(view && ele);

  str = (struct atomicResources_struct*)visuElementGet_property(ele, "radiusAndShape");
/*   str = g_hash_table_lookup(shapeAndRadiusResource, (gpointer)ele); */
  if (!str)
    {
      str = createDefaultAtomicStruct();
      visuElementSet_property(ele, "radiusAndShape", (gpointer)str);
/*       g_hash_table_insert(shapeAndRadiusResource, (gpointer)ele, (gpointer)str); */
    }

  nlat = OpenGLViewGet_numberOfFacettes(view, str->radius);

  DBG_fprintf(stderr, "Rendering Atomic : creating '%s' for %s (%d - OpenGL id"
	      " %d - fac %d)\n", shapeName[str->shape],
	      ele->name, ele->typeNumber, identifierSpheres + ele->typeNumber,
	      nlat);
  if (nlat < 0)
    return;
   
  glNewList(identifierSpheres + ele->typeNumber, GL_COMPILE);
  switch (str->shape)
    {
    case shapeSphere:
      gluSphere(obj, (double)str->radius, nlat, nlat);
      break;
    case shapeCube:
      glBegin(GL_QUADS);

      glNormal3f(0., 0., 1.);
      glVertex3f(str->radius / 2., str->radius / 2., str->radius / 2.);
      glVertex3f(-str->radius / 2., str->radius / 2., str->radius / 2.);
      glVertex3f(-str->radius / 2., -str->radius / 2., str->radius / 2.);
      glVertex3f(str->radius / 2., -str->radius / 2., str->radius / 2.);
/*       for (i = 0; i < nlat / 2; i++) */
/* 	{ */
/* 	  alpha = (float)i / (float)(nlat / 2) - 0.5; */
/* 	  alpha1 = alpha + 1. / (float)(nlat / 2); */
/* 	  for (j = 0; j < nlat / 2; j++) */
/* 	    { */
/* 	      beta = (float)j / (float)(nlat / 2) - 0.5; */
/* 	      beta1 = beta + 1. / (float)(nlat / 2); */
/* 	      glVertex3f(str->radius * alpha1, str->radius * beta1, str->radius / 2.); */
/* 	      glVertex3f(str->radius * alpha, str->radius * beta1, str->radius / 2.); */
/* 	      glVertex3f(str->radius * alpha, str->radius * beta, str->radius / 2.); */
/* 	      glVertex3f(str->radius * alpha1, str->radius * beta, str->radius / 2.); */
/* 	    } */
/* 	} */

      glNormal3f(0., 0., -1.);
      glVertex3f(str->radius / 2.,str->radius / 2.,-str->radius / 2.);
      glVertex3f(str->radius / 2.,-str->radius / 2.,-str->radius / 2.);
      glVertex3f(-str->radius / 2.,-str->radius / 2.,-str->radius / 2.);
      glVertex3f(-str->radius / 2.,str->radius / 2.,-str->radius / 2.);

      glNormal3f(1., 0., 0.);
      glVertex3f(str->radius / 2.,str->radius / 2.,str->radius / 2.);
      glVertex3f(str->radius / 2.,-str->radius / 2.,str->radius / 2.);
      glVertex3f(str->radius / 2.,-str->radius / 2.,-str->radius / 2.);
      glVertex3f(str->radius / 2.,str->radius / 2.,-str->radius / 2.);

      glNormal3f(-1., 0., 0.);
      glVertex3f(-str->radius / 2.,str->radius / 2.,str->radius / 2.);
      glVertex3f(-str->radius / 2.,str->radius / 2.,-str->radius / 2.);
      glVertex3f(-str->radius / 2.,-str->radius / 2.,-str->radius / 2.);
      glVertex3f(-str->radius / 2.,-str->radius / 2.,str->radius / 2.);

      glNormal3f(0., 1., 0.);
      glVertex3f(-str->radius / 2.,str->radius / 2.,-str->radius / 2.);
      glVertex3f(-str->radius / 2.,str->radius / 2.,str->radius / 2.);
      glVertex3f(str->radius / 2.,str->radius / 2.,str->radius / 2.);
      glVertex3f(str->radius / 2.,str->radius / 2.,-str->radius / 2.);

      glNormal3f(0., -1., 0.);
      glVertex3f(-str->radius / 2.,-str->radius / 2.,-str->radius / 2.);
      glVertex3f(str->radius / 2.,-str->radius / 2.,-str->radius / 2.);
      glVertex3f(str->radius / 2.,-str->radius / 2.,str->radius / 2.);
      glVertex3f(-str->radius / 2.,-str->radius / 2.,str->radius / 2.);

      glEnd();
      break;
    }
  glEndList();
   
  ele->openGLIdentifier = identifierSpheres + ele->typeNumber;
}
