// Copyright (c) 2007-09  INRIA Sophia-Antipolis (France).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org); you may redistribute point_it under
// the terms of the Q Public License version 1.0.
// See the file LICENSE.QPL distributed with CGAL.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL: svn+ssh://scm.gforge.inria.fr/svn/cgal/branches/CGAL-3.5-branch/Point_set_processing_3/include/CGAL/grid_simplify_point_set.h $
// $Id: grid_simplify_point_set.h 49943 2009-06-17 07:49:35Z lsaboret $
//
// Author(s) : Laurent Saboret and Nader Salman

#ifndef CGAL_GRID_SIMPLIFY_POINT_SET_H
#define CGAL_GRID_SIMPLIFY_POINT_SET_H

#include <CGAL/property_map.h>
#include <CGAL/point_set_processing_assertions.h>

#include <iterator>
#include <set>
#include <deque>
#include <algorithm>
#include <cmath>

CGAL_BEGIN_NAMESPACE


// ----------------------------------------------------------------------------
// Private section
// ----------------------------------------------------------------------------
namespace CGALi {


/// Utility class for grid_simplify_point_set():
/// Less_epsilon_points_3 defines a 3D points order / 2 points are equal
/// iff they belong to the same cell of a grid of cell size = epsilon.
template <class Point_3>
struct Less_epsilon_points_3
{
private:

    double m_epsilon;

public:

    Less_epsilon_points_3 (double epsilon)
        : m_epsilon (epsilon)
    {
        CGAL_point_set_processing_precondition(epsilon > 0);
    }

    bool operator() (const Point_3& a, const Point_3& b) const
    {
        // Round points to multiples of m_epsilon, then compare.
        Point_3 rounded_a(round_epsilon(a.x(), m_epsilon),
                          round_epsilon(a.y(), m_epsilon),
                          round_epsilon(a.z(), m_epsilon));
        Point_3 rounded_b(round_epsilon(b.x(), m_epsilon),
                          round_epsilon(b.y(), m_epsilon),
                          round_epsilon(b.z(), m_epsilon));
        return (rounded_a < rounded_b);
    }

private:

    // Round number to multiples of epsilon
    static inline double round_epsilon(double value, double epsilon)
    {
        return std::floor(value/epsilon) * epsilon;
    }
};


} /* namespace CGALi */


// ----------------------------------------------------------------------------
// Public section
// ----------------------------------------------------------------------------


/// Utility class for grid_simplify_point_set():
/// 3D points set which allows at most 1 point per cell
/// of a grid of cell size = epsilon.
///
/// Warning:
/// This class is a container sorted wrt points position
/// => you should not modify directly the order or the position of points.

template <class Point_3>
class Epsilon_point_set_3
  : public std::set<Point_3, CGALi::Less_epsilon_points_3<Point_3> >
{
private:

    // superclass
    typedef std::set<Point_3, CGALi::Less_epsilon_points_3<Point_3> > Base;

public:

    Epsilon_point_set_3 (double epsilon)
        : Base( CGALi::Less_epsilon_points_3<Point_3>(epsilon) )
    {
        CGAL_point_set_processing_precondition(epsilon > 0);
    }

    // default copy constructor, operator =() and destructor are fine.
};


/// Merges points which belong to the same cell of a grid of cell size = epsilon.
///
/// This method modifies the order of input points so as to pack all remaining points first,
/// and returns an iterator over the first point to remove (see erase-remove idiom).
/// For this reason it should not be called on sorted containers.
///
/// @commentheading Precondition: epsilon > 0.
///
/// @commentheading Template Parameters:
/// @param ForwardIterator iterator over input points.
/// @param PointPMap is a model of boost::ReadablePropertyMap with a value_type = Point_3<Kernel>.
///        It can be omitted if ForwardIterator value_type is convertible to Point_3<Kernel>.
/// @param Kernel Geometric traits class.
///        It can be omitted and deduced automatically from PointPMap value_type.
///
/// @return iterator over the first point to remove.

// This variant requires all parameters.
template <typename ForwardIterator,
          typename PointPMap,
          typename Kernel
>
ForwardIterator
grid_simplify_point_set(
  ForwardIterator first,  ///< iterator over the first input point.
  ForwardIterator beyond, ///< past-the-end iterator over the input points.
  PointPMap point_pmap, ///< property map ForwardIterator -> Point_3
  double epsilon, ///< tolerance value when merging 3D points.
  const Kernel& kernel) ///< geometric traits.
{
  // actual type of input points
  typedef typename std::iterator_traits<ForwardIterator>::value_type Enriched_point;

  CGAL_point_set_processing_precondition(epsilon > 0);

  // Merges points which belong to the same cell of a grid of cell size = epsilon.
  // points_to_keep[] will contain 1 point per cell; the others will be in points_to_remove[].
  Epsilon_point_set_3<Enriched_point> points_to_keep(epsilon);
  std::deque<Enriched_point> points_to_remove;
  for (ForwardIterator it=first ; it != beyond ; it++)
  {
      std::pair<typename Epsilon_point_set_3<Enriched_point>::iterator,bool> result;
      result = points_to_keep.insert(*it);
      if (!result.second) // if not inserted
        points_to_remove.push_back(*it);
  }

  // Replaces [first, beyond) range by the content of points_to_keep, then points_to_remove.
  ForwardIterator first_point_to_remove =
    std::copy(points_to_keep.begin(), points_to_keep.end(), first);
  std::copy(points_to_remove.begin(), points_to_remove.end(), first_point_to_remove);

  return first_point_to_remove;
}

/// @cond SKIP_IN_MANUAL
// This variant deduces the kernel from the iterator type.
template <typename ForwardIterator,
          typename PointPMap
>
ForwardIterator
grid_simplify_point_set(
  ForwardIterator first, ///< iterator over the first input point
  ForwardIterator beyond, ///< past-the-end iterator
  PointPMap point_pmap, ///< property map ForwardIterator -> Point_3
  double epsilon) ///< tolerance value when merging 3D points
{
  typedef typename boost::property_traits<PointPMap>::value_type Point;
  typedef typename Kernel_traits<Point>::Kernel Kernel;
  return grid_simplify_point_set(
    first,beyond,
    point_pmap,
    epsilon,
    Kernel());
}
/// @endcond

/// @cond SKIP_IN_MANUAL
// This variant creates a default point property map = Dereference_property_map.
template <typename ForwardIterator
>
ForwardIterator
grid_simplify_point_set(
  ForwardIterator first, ///< iterator over the first input point
  ForwardIterator beyond, ///< past-the-end iterator
  double epsilon) ///< tolerance value when merging 3D points
{
  return grid_simplify_point_set(
    first,beyond,
    make_dereference_property_map(first),
    epsilon);
}
/// @endcond


CGAL_END_NAMESPACE

#endif // CGAL_GRID_SIMPLIFY_POINT_SET_H

