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

	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 "finder.h"

#include <math.h>

/**
 * SECTION:finder
 * @short_description: provide a node lookup based on coordinates.
 *
 * <para>This object can be used to find nodes based on coordinates in
 * a linear scaling complexity.</para>
 */

/**
 * VisuNodeFinderClass:
 * @parent: the parent class;
 *
 * A short way to identify #_VisuNodeFinderClass structure.
 *
 * Since: 3.8
 */
/**
 * VisuNodeFinder:
 *
 * An opaque structure.
 *
 * Since: 3.8
 */
/**
 * VisuNodeFinderPrivate:
 *
 * Private fields for #VisuNodeFinder objects.
 *
 * Since: 3.8
 */
struct _VisuNodeFinderPrivate
{
  gboolean dispose_has_run;

  gfloat size;

  guint mesh[3];
  GList **table;

  VisuData *data;
  gulong popDec_sig, popInc_sig, popPos_sig, popVis_sig;
};

static void visu_node_finder_finalize(GObject* obj);
static void visu_node_finder_dispose(GObject* obj);

G_DEFINE_TYPE_WITH_CODE(VisuNodeFinder, visu_node_finder, VISU_TYPE_OBJECT,
                        G_ADD_PRIVATE(VisuNodeFinder))

static void visu_node_finder_class_init(VisuNodeFinderClass *klass)
{
  DBG_fprintf(stderr, "Visu Finder: creating the class of the object.\n");
  /* DBG_fprintf(stderr, "                - adding new signals ;\n"); */

  /* Connect the overloading methods. */
  G_OBJECT_CLASS(klass)->dispose  = visu_node_finder_dispose;
  G_OBJECT_CLASS(klass)->finalize = visu_node_finder_finalize;
}

static void visu_node_finder_init(VisuNodeFinder *obj)
{
  DBG_fprintf(stderr, "Visu Finder: initializing a new object (%p).\n",
	      (gpointer)obj);
  
  obj->priv = visu_node_finder_get_instance_private(obj);
  obj->priv->dispose_has_run = FALSE;

  obj->priv->size  = 4.f;
  obj->priv->mesh[0] = 0;
  obj->priv->mesh[1] = 0;
  obj->priv->mesh[2] = 0;
  obj->priv->table   = (GList**)0;

  obj->priv->data = (VisuData*)0;
}
static void visu_node_finder_dispose(GObject* obj)
{
  VisuNodeFinder *finder;

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

  finder = VISU_NODE_FINDER(obj);
  if (finder->priv->dispose_has_run)
    return;
  finder->priv->dispose_has_run = TRUE;

  /* Disconnect signals. */
  if (G_LIKELY(finder->priv->data))
    {
      g_signal_handler_disconnect(G_OBJECT(finder->priv->data), finder->priv->popDec_sig);
      g_signal_handler_disconnect(G_OBJECT(finder->priv->data), finder->priv->popInc_sig);
      g_signal_handler_disconnect(G_OBJECT(finder->priv->data), finder->priv->popPos_sig);
      g_signal_handler_disconnect(G_OBJECT(finder->priv->data), finder->priv->popVis_sig);
      g_object_unref(finder->priv->data);
    }

  /* Chain up to the parent class */
  G_OBJECT_CLASS(visu_node_finder_parent_class)->dispose(obj);
}
static void visu_node_finder_finalize(GObject* obj)
{
  VisuNodeFinder *finder;

  g_return_if_fail(obj);

  DBG_fprintf(stderr, "Visu Finder: finalize object %p.\n", (gpointer)obj);

  finder = VISU_NODE_FINDER(obj);

  /* Free privs elements. */
  if (finder->priv)
    {
      DBG_fprintf(stderr, "Visu Finder: free private.\n");
      g_free(finder->priv->table);
    }

  /* Chain up to the parent class */
  DBG_fprintf(stderr, "Visu Finder: chain to parent.\n");
  G_OBJECT_CLASS(visu_node_finder_parent_class)->finalize(obj);
  DBG_fprintf(stderr, "Visu Finder: freeing ... OK.\n");
}

static void onChange(VisuNodeFinder *finder)
{
  finder->priv->mesh[0] = 0;
  finder->priv->mesh[1] = 0;
  finder->priv->mesh[2] = 0;
}
/**
 * visu_node_finder_new:
 * @data: a #VisuData object.
 *
 * Creates a new #VisuNodeFinder to look for node from coordinates.
 *
 * Since: 3.8
 *
 * Returns: a pointer to the #VisuNodeFinder it created or
 * NULL otherwise.
 */
VisuNodeFinder* visu_node_finder_new(VisuData *data)
{
  VisuNodeFinder *finder;

  DBG_fprintf(stderr,"Visu Finder: new object.\n");
  finder = VISU_NODE_FINDER(g_object_new(VISU_TYPE_NODE_FINDER, NULL));
  
  g_return_val_if_fail(data, finder);

  g_object_ref(data);
  finder->priv->data = data;
  finder->priv->popDec_sig =
    g_signal_connect_object(G_OBJECT(data), "PopulationDecrease",
                            G_CALLBACK(onChange), finder, G_CONNECT_SWAPPED);
  finder->priv->popInc_sig =
    g_signal_connect_object(G_OBJECT(data), "PopulationIncrease",
                            G_CALLBACK(onChange), finder, G_CONNECT_SWAPPED);
  finder->priv->popPos_sig =
    g_signal_connect_object(G_OBJECT(data), "position-changed",
                            G_CALLBACK(onChange), finder, G_CONNECT_SWAPPED);
  finder->priv->popVis_sig =
    g_signal_connect_object(data, "visibility-changed",
                            G_CALLBACK(onChange), finder, G_CONNECT_SWAPPED);

  return finder;
}

/**
 * visu_node_finder_getData:
 * @finder: a #VisuNodeFinder object.
 *
 * Get the #VisuData object the @finder is working on. 
 *
 * Since: 3.8
 *
 * Returns: (transfer full): the corresponding #VisuData the finder
 * work on.
 **/
VisuData* visu_node_finder_getData(VisuNodeFinder *finder)
{
  g_return_val_if_fail(VISU_IS_NODE_FINDER(finder), (VisuData*)0);

  g_object_ref(finder->priv->data);
  return finder->priv->data;
}

static void _generate_mesh(VisuNodeFinder *finder)
{
  float bsize[3], xyz[3], f;
  VisuNodeArrayIter iter;
  guint i, j, k, id;

  /* Mesh cubes will have roughly priv->size. */
  visu_box_getCentre(visu_boxed_getBox(VISU_BOXED(finder->priv->data)), bsize);
  bsize[0] *= 2.f;
  bsize[1] *= 2.f;
  bsize[2] *= 2.f;

  f = 1.f / finder->priv->size;
  finder->priv->mesh[0] = MAX((int)(bsize[0] * f), 1);
  finder->priv->mesh[1] = MAX((int)(bsize[1] * f), 1);
  finder->priv->mesh[2] = MAX((int)(bsize[2] * f), 1);
  DBG_fprintf(stderr, "Visu Finder: generate a mesh of %dx%dx%d.\n",
              finder->priv->mesh[0], finder->priv->mesh[1], finder->priv->mesh[2]);

  if (finder->priv->table)
    g_free(finder->priv->table);
  finder->priv->table = g_malloc0(sizeof(GList*) * finder->priv->mesh[0] *
                                  finder->priv->mesh[1] * finder->priv->mesh[2]);

  /* Distribute nodes inside table, according to their coordinates. */
  visu_node_array_iter_new(VISU_NODE_ARRAY(finder->priv->data), &iter);
  for (visu_node_array_iterStart(VISU_NODE_ARRAY(finder->priv->data), &iter);
       iter.node;
       visu_node_array_iterNext(VISU_NODE_ARRAY(finder->priv->data), &iter))
    {
      visu_data_getNodePosition(finder->priv->data, iter.node, xyz);
      i = CLAMP((int)(xyz[0] * f), 0, (int)finder->priv->mesh[0] - 1);
      j = CLAMP((int)(xyz[1] * f), 0, (int)finder->priv->mesh[1] - 1);
      k = CLAMP((int)(xyz[2] * f), 0, (int)finder->priv->mesh[2] - 1);
      id = k * finder->priv->mesh[0] * finder->priv->mesh[1] + j * finder->priv->mesh[0] + i;
      finder->priv->table[id] = g_list_prepend(finder->priv->table[id],
                                               GINT_TO_POINTER(iter.node->number));
    }
}

static gint _mesh_lookup(VisuNodeFinder *finder, guint id, const gfloat at[3], gfloat *d)
{
  VisuNodeArrayIter iter;
  gint res;
  gfloat dist, xyz[3], d2;
  
  dist = G_MAXFLOAT;
  res = -1;
  visu_node_array_iter_new(VISU_NODE_ARRAY(finder->priv->data), &iter);
  for (visu_node_array_iterStartList(VISU_NODE_ARRAY(finder->priv->data), &iter,
                                     finder->priv->table[id]);
       iter.node;
       visu_node_array_iterNextList(VISU_NODE_ARRAY(finder->priv->data), &iter))
    {
      /* Currently, we don't take into account the periodicity. */
      visu_data_getNodePosition(finder->priv->data, iter.node, xyz);
      xyz[0] -= at[0];
      xyz[1] -= at[1];
      xyz[2] -= at[2];
      d2 = xyz[0] * xyz[0] + xyz[1] * xyz[1] + xyz[2] * xyz[2];
      if (d2 < dist)
        {
          dist = d2;
          res = iter.node->number;
        }
    }
  if (d)
    *d = dist;
  return res;
}

/**
 * visu_node_finder_lookup:
 * @finder: a #VisuNodeFinder object.
 * @at: (array fixed-size=3): 
 * @tol: a float.
 *
 * Giving the cartesian coordinates @at, this method lookup for the closest
 * #VisuNode within a radius of @tol.
 *
 * Since: 3.8
 *
 * Returns: the id of the closest node to @at (within a maximum radius
 * of @tol). If none is found, returns -1.
 **/
gint visu_node_finder_lookup(VisuNodeFinder *finder, const gfloat at[3], gfloat tol)
{
  guint i, j, k;
  gint s;
  guint i0, j0, k0;
  gint res, res2;
  gfloat f, dist, d2;

  GTimer *timer;
  gulong fractionTimer;

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

  g_return_val_if_fail(VISU_IS_NODE_FINDER(finder), -1);
  g_return_val_if_fail(finder->priv->data, -1);

  if (!finder->priv->mesh[0] ||
      !finder->priv->mesh[1] ||
      !finder->priv->mesh[2])
    _generate_mesh(finder);

  f = 1.f / finder->priv->size;
  i0 = CLAMP((int)(at[0] * f), 0, (int)finder->priv->mesh[0] - 1);
  j0 = CLAMP((int)(at[1] * f), 0, (int)finder->priv->mesh[1] - 1);
  k0 = CLAMP((int)(at[2] * f), 0, (int)finder->priv->mesh[2] - 1);

  DBG_fprintf(stderr, "Visu Finder: testing (%gx%gx%g) in mesh:\n", at[0], at[1], at[2]);
  res = -1;
  dist = G_MAXFLOAT;
  s = (int)(tol / finder->priv->size) + 1;
  for (i = MAX(0, (int)i0 - s); i < MIN(finder->priv->mesh[0], i0 + s + 1); i++)
    for (j = MAX(0, (int)j0 - s); j < MIN(finder->priv->mesh[1], j0 + s + 1); j++)
      for (k = MAX(0, (int)k0 - s); k < MIN(finder->priv->mesh[2], k0 + s + 1); k++)
        {
          DBG_fprintf(stderr, " | %dx%dx%d\n", i, j, k);
          res2 = _mesh_lookup(finder, k * finder->priv->mesh[0] * finder->priv->mesh[1] +
                              j * finder->priv->mesh[0] + i, at, &d2);
          DBG_fprintf(stderr, " | found %d at %g.\n", res2, sqrt(d2));
          if (d2 < dist)
            {
              dist = d2;
              res = res2;
            }
          DBG_fprintf(stderr, " | at %g micro-s.\n",
                      g_timer_elapsed(timer, &fractionTimer)*1e6);
        }

#if DEBUG == 1
  g_timer_stop(timer);
  g_timer_destroy(timer);
#endif

  if (sqrt(dist) < tol)
    return res;
  else
    return -1;
}

/**
 * visu_node_finder_lookupArray:
 * @finder: a #VisuNodeFinder object.
 * @ids: (type gint64): an allocated array of size @np.
 * @at: (type gint64): an allocated array of size 3 * @np, with
 * coordinates to be tested.
 * @np: the number of coordinates to be tested.
 * @tol: a radius to find the nodes in.
 *
 * Apply visu_node_finder_lookup() on the array @at. It's used mainly
 * for bindings.
 *
 * Since: 3.8
 **/
void visu_node_finder_lookupArray(VisuNodeFinder *finder, gint *ids, const gfloat *at,
                                  guint np, gfloat tol)
{
  guint i;

  for (i = 0; i < np; i++)
    ids[i] = visu_node_finder_lookup(finder, at + 3 * i, tol);
}
