Exemplo n.º 1
0
int main() {
  Tr tr;            // 3D-Delaunay triangulation
  C2t3 c2t3 (tr);   // 2D-complex in 3D-Delaunay triangulation

  // defining the surface
  Surface_3 surface(moebius_function,             // pointer to function
                    Sphere_3(Point_3(0.0001, -0.0003, 0.), 2.)); // bounding sphere

  // defining meshing criteria
  CGAL::Surface_mesh_default_criteria_3<Tr> criteria(30.,  // angular bound
                                                     0.05,  // radius bound
                                                     0.05); // distance bound
  // meshing surface
  CGAL::make_surface_mesh(c2t3, surface, criteria, CGAL::Non_manifold_tag());

  std::ofstream out("out.off");

#ifndef NDEBUG
  const bool result = 
#endif
    CGAL::output_surface_facets_to_off(out, c2t3,
				       CGAL::Surface_mesher::IO_VERBOSE | 
				       CGAL::Surface_mesher::IO_ORIENT_SURFACE);

  assert(result == false);

  std::cout << "Final number of points: " << tr.number_of_vertices() << "\n";
}
void ImplicitMesher::ImpSurfToMeshJDBois(ImpPolyhedron& ImpPoly)
{
	//transfer data from inside of class to global
	RadialBasisFunc::CopyRadialBasisFunction(this->Weights,this->PolyNom,this->InterpoPoints);

	SMDT3 tr;            // 3D-Delaunay triangulation
	C2T3 c2t3 (tr);   // 2D-complex in 3D-Delaunay triangulation
	// defining the surface
	ImpSurface_3 surface(&RadialBasisFunc::RadialBasisFunction,// pointer to function
		SMDT3GTSphere_3(CGAL::ORIGIN, 2.)); // bounding sphere
	// Note that "2." above is the *squared* radius of the bounding sphere!

	// defining meshing criteria
	CGAL::Surface_mesh_default_criteria_3<SMDT3> criteria(30.,  // angular bound
		0.1,  // radius bound
		0.1); // distance bound
	// meshing surface
	CGAL::make_surface_mesh(c2t3, surface, criteria, CGAL::Non_manifold_tag());

	//std::cout << "Final number of points: " << tr.number_of_vertices() << "\n";

	CGAL::output_surface_facets_to_polyhedron(c2t3,ImpPoly);

	std::ofstream out("out.off");
	CGAL::output_surface_facets_to_off (out, c2t3);
}
Exemplo n.º 3
0
void ShereMesh() {
  Tr tr;            // 3D-Delaunay triangulation
  C2t3 c2t3 (tr);   // 2D-complex in 3D-Delaunay triangulation

  // defining the surface
  Surface_3 surface(sphere_function,             // pointer to function
                    Sphere_3(CGAL::ORIGIN, 2.)); // bounding sphere
  // Note that "2." above is the *squared* radius of the bounding sphere!

  // defining meshing criteria
  CGAL::Surface_mesh_default_criteria_3<Tr> criteria(30.,  // angular bound
                                                     0.1,  // radius bound
                                                     0.1); // distance bound
  // meshing surface
  CGAL::make_surface_mesh(c2t3, surface, criteria, CGAL::Non_manifold_tag());

  std::cout << "Final number of points: " << tr.number_of_vertices() << "\n";

  //Output mesh
  //Polyhedron polymesh;
  //bool result = CGAL::output_surface_facets_to_polyhedron(c2t3, polymesh);
  //std::cout << "output_surface_facets_to_polyhedron: " << result << "\n";

  //Scommentare per salvare mesh su file
  std::ofstream out("mesh_sphere_test_low.off");
  CGAL::output_surface_facets_to_off (out, c2t3);
  std::cout << "SAVED MESH\n";

  //std::list<TriangleGT> triangleMesh;
  //std::back_insert_iterator<std::list<TriangleGT> > bii(triangleMesh);
  //output_surface_facets_to_triangle_soup(c2t3, bii);
}
Exemplo n.º 4
0
int main(int , char** argv)
{
  Tr tr;
  C2T3 c2t3(tr);

  std::ifstream ifs(argv[1]);
  if( !ifs )
  {
    std::cerr << "Usage:\n"
              << "  " << argv[0] << " FILE\n"
              << "\n"
	      << "  FILE must be " << format_cgal_description
              << "\n";
    return EXIT_FAILURE;
  }

  std::cout << "  Reading " << argv[1] << std::endl;

  if( CGAL::Mesh_3::input_mesh(ifs, c2t3,
                               true,
                               &std::cerr) )
//   if( CGAL::input_pslg_from_medit(ifs,
//                                   c2t3,
//                                   true,         // debug
//                                   &std::cout) ) // debug to cout
  {
    display_faces_counts(tr, "    ", &std::cout);

    std::cout << "\n  Statistics:\n";

    std::cout << "(vertices)\n";
    display_vertices_by_surface_indices_statistics(tr, "    ", &std::cout);

    std::cout << "(facets)\n";
    display_facets_by_surface_indices_statistics(c2t3, "    ", &std::cout);

    Compute_min_angle<Tr> min_angle(tr);

    double min = 180;
    for(Tr::Finite_cells_iterator cit = tr.finite_cells_begin();
	cit != tr.finite_cells_end();
	++cit)
      if(cit->is_in_domain())
      {
	const double angle = min_angle(cit);
	if( angle < min ) min = angle;
      }
	
    std::cout << "\nmin angle: " << min << "\n";

    return EXIT_SUCCESS;
  }
  else
    return EXIT_FAILURE;
}
Exemplo n.º 5
0
int main() {
  Tr tr;            // 3D-Delaunay triangulation
  C2t3 c2t3 (tr);   // 2D-complex in 3D-Delaunay triangulation

  // defining the surface
  Surface_3 surface(sphere_function,             // pointer to function
                    Sphere_3(CGAL::ORIGIN, 2.)); // bounding sphere
  // Note that "2." above is the *squared* radius of the bounding sphere!

  // defining meshing criteria
  CGAL::Surface_mesh_default_criteria_3<Tr> criteria(30.,  // angular bound
                                                     0.1,  // radius bound
                                                     0.1); // distance bound
  // meshing surface
  CGAL::make_surface_mesh(c2t3, surface, criteria, CGAL::Non_manifold_tag());

  std::cout << "Final number of points: " << tr.number_of_vertices() << "\n";
}
Exemplo n.º 6
0
int main(int , char** argv)
{
  Tr tr;
  C2T3 c2t3(tr);

  std::ifstream ifs(argv[1]);
  std::ofstream ofs(argv[2]);
  if( !ifs || !ofs )
  {
    std::cerr << "Usage:\n"
              << "  " << argv[0] << " INPUT OUPUT\n" <<
"\n"
"  INPUT must be " << format_cgal_description <<
"\n"
"  OUTPUT will be a medit file.\n"
"\n";
    return EXIT_FAILURE;
  }

  std::cout << "  Reading " << argv[1] << std::endl;

  if( CGAL::Mesh_3::input_mesh(ifs, c2t3,
                               true,
                               &std::cerr) )
//   if( CGAL::input_pslg_from_medit(ifs,
//                                   c2t3,
//                                   true,         // debug
//                                   &std::cout) ) // debug to cout
  {
    std::cout << "  Writing " << argv[2] << std::endl;
    CGAL::output_to_medit(ofs, c2t3);
    return EXIT_SUCCESS;
  }
  else
    return EXIT_FAILURE;
}
Exemplo n.º 7
0
int main() {
  Tr tr;            // 3D-Delaunay triangulation
  C2t3 c2t3 (tr);   // 2D-complex in 3D-Delaunay triangulation

  // defining the surface
  std::ifstream file_input("data/triceratops.off");
  Polyhedral_surface surface(file_input);

  // defining meshing criteria
  CGAL::Surface_mesh_default_criteria_3<Tr> 
    facets_criteria(30.,  // angular bound
		    0.5,  // radius bound
		    0.5); // distance bound
  CGAL::Surface_mesh_default_edges_criteria_3<Tr>
    edges_criteria(0.5,  // radius bound
		   0.5); // distance bound

  // meshing surface
  CGAL::make_piecewise_smooth_surface_mesh(c2t3, surface,
					   facets_criteria, edges_criteria,
					   CGAL::Manifold_tag());

  std::cout << "Final number of points: " << tr.number_of_vertices() << "\n";
}
Exemplo n.º 8
0
// adapted from http://www.cgal.org/Manual/beta/examples/Surface_reconstruction_points_3/poisson_reconstruction_example.cpp
Mesh poissonSurface(const Mat ipoints, const Mat normals)
{
    // Poisson options
    FT sm_angle = 20.0; // Min triangle angle in degrees.
    FT sm_radius = 300; // Max triangle size w.r.t. point set average spacing.
    FT sm_distance = 0.375; // Surface Approximation error w.r.t. point set average spacing.

    PointList points;
    points.reserve(ipoints.rows);
    float min = 0, max = 0;
    for (int i=0; i<ipoints.rows; i++) {
        float const *p = ipoints.ptr<float const>(i), *n = normals.ptr<float const>(i);
        points.push_back(Point_with_normal(Point(p[0]/p[3], p[1]/p[3], p[2]/p[3]), Vector(n[0], n[1], n[2])));
        if (p[0]/p[3] > max) max = p[0]/p[3];
        if (p[0]/p[3] < min) min = p[0]/p[3];
    }

    // Creates implicit function from the read points using the default solver.

    // Note: this method requires an iterator over points
    // + property maps to access each point's position and normal.
    // The position property map can be omitted here as we use iterators over Point_3 elements.
    Poisson_reconstruction_function function(points.begin(), points.end(), CGAL::make_normal_of_point_with_normal_pmap(points.begin()) );

    // Computes the Poisson indicator function f() at each vertex of the triangulation.
    bool success = function.compute_implicit_function();
    assert(success);
#ifdef TEST_BUILD
    printf("implicit function ready. Meshing...\n");
#endif
    // Computes average spacing
    FT average_spacing = CGAL::compute_average_spacing(points.begin(), points.end(), 6 /* knn = 1 ring */);

    // Gets one point inside the implicit surface
    // and computes implicit function bounding sphere radius.
    Point inner_point = function.get_inner_point();
    Sphere bsphere = function.bounding_sphere();
    FT radius = std::sqrt(bsphere.squared_radius());

    // Defines the implicit surface: requires defining a
    // conservative bounding sphere centered at inner point.
    FT sm_sphere_radius = 5.0 * radius;
    FT sm_dichotomy_error = sm_distance*average_spacing/1000.0; // Dichotomy error must be << sm_distance
    Surface_3 surface(function, Sphere(inner_point,sm_sphere_radius*sm_sphere_radius), sm_dichotomy_error/sm_sphere_radius);

    // Defines surface mesh generation criteria
    // parameters: min triangle angle (degrees), max triangle size, approximation error
    CGAL::Surface_mesh_default_criteria_3<STr> criteria(sm_angle, sm_radius*average_spacing, sm_distance*average_spacing);

    // Generates surface mesh with manifold option
    STr tr; // 3D Delaunay triangulation for surface mesh generation
    C2t3 c2t3(tr); // 2D complex in 3D Delaunay triangulation
    // parameters: reconstructed mesh, implicit surface, meshing criteria, 'do not require manifold mesh'
    CGAL::make_surface_mesh(c2t3, surface, criteria, CGAL::Non_manifold_tag());

    assert(tr.number_of_vertices() > 0);

    // Search structure: index of the vertex at an exactly given position
    std::map<Point, int> vertexIndices;

    // Extract all vertices of the resulting mesh
    Mat vertices(tr.number_of_vertices(), 4, CV_32FC1), faces(c2t3.number_of_facets(), 3, CV_32SC1);
#ifdef TEST_BUILD
    printf("%i vertices, %i facets. Converting...\n", vertices.rows, faces.rows);
#endif
    {   int i=0;
        for (C2t3::Vertex_iterator it=c2t3.vertices_begin(); it!=c2t3.vertices_end(); it++, i++) {
            float *vertex = vertices.ptr<float>(i);
            Point p = it->point();
            vertex[0] = p.x();
            vertex[1] = p.y();
            vertex[2] = p.z();
            vertex[3] = 1;
            vertexIndices[p] = i;
        }
        vertices.resize(i);
    }

    // Extract all faces of the resulting mesh and calculate the index of each of their vertices
    {   int i=0;
        for (C2t3::Facet_iterator it=c2t3.facets_begin(); it!=c2t3.facets_end(); it++, i++) {
            Cell cell = *it->first;
            int vertex_excluded = it->second;
            int32_t* outfacet = faces.ptr<int32_t>(i);
            // a little magic so that face normals are oriented outside
            char sign = (function(cell.vertex(vertex_excluded)->point()) > 0) ? 1 : 2; // 2 = -1 (mod 3)
            for (char j = vertex_excluded + 1; j < vertex_excluded + 4; j++) {
                outfacet[(sign*j)%3] = vertexIndices[cell.vertex(j%4)->point()];
            }
        }
    }

    return Mesh(vertices, faces);
}
Exemplo n.º 9
0
int Reconstruccion3D::Delaunay()
{
    // Poisson options
    FT sm_angle = 20; // Min triangle angle in degrees.  10
    FT sm_radius = 1; // Max triangle size w.r.t. point set average spacing.   2
    FT sm_distance = 0.1; // Surface Approximation error w.r.t. point set average spacing.0.375

    // Reads the point set file in points[].
    // Note: read_xyz_points_and_normals() requires an iterator over points
    // + property maps to access each point's position and normal.
    // The position property map can be omitted here as we use iterators over Point_3 elements.
    PointList points;
    std::ifstream stream("puntosNormalizados.off");
    if (!stream ||
        !CGAL::read_xyz_points_and_normals(
                              stream,
                              std::back_inserter(points),
                              CGAL::make_normal_of_point_with_normal_pmap(std::back_inserter(points))))
    {
      std::cerr << "Error: cannot read file data/kitten.xyz" << std::endl;
      return EXIT_FAILURE;
    }

    // Creates implicit function from the read points.
    // Note: this method requires an iterator over points
    // + property maps to access each point's position and normal.
    // The position property map can be omitted here as we use iterators over Point_3 elements.
    Poisson_reconstruction_function function(
                              points.begin(), points.end(),
                              CGAL::make_normal_of_point_with_normal_pmap(points.begin()));

    // Computes the Poisson indicator function f()
    // at each vertex of the triangulation.
    if ( ! function.compute_implicit_function() )
      return EXIT_FAILURE;

    // Computes average spacing
    FT average_spacing = CGAL::compute_average_spacing(points.begin(), points.end(),
                                                       6 /* knn = 1 ring */);

    // Gets one point inside the implicit surface
    // and computes implicit function bounding sphere radius.
    Point inner_point = function.get_inner_point();
    Sphere bsphere = function.bounding_sphere();
    FT radius = std::sqrt(bsphere.squared_radius());

    // Defines the implicit surface: requires defining a
  	// conservative bounding sphere centered at inner point.
    FT sm_sphere_radius = 0.5 * radius;      //0.5
    FT sm_dichotomy_error = sm_distance*average_spacing/1000.0; // Dichotomy error must be << sm_distance
    Surface_3 surface(function,
                      Sphere(inner_point,sm_sphere_radius*sm_sphere_radius),
                      sm_dichotomy_error/sm_sphere_radius);

    // Defines surface mesh generation criteria
    CGAL::Surface_mesh_default_criteria_3<STr> criteria(sm_angle,  // Min triangle angle (degrees)
                                                        sm_radius*average_spacing,  // Max triangle size
                                                        sm_distance*average_spacing); // Approximation error

    // Generates surface mesh with manifold option
    STr tr; // 3D Delaunay triangulation for surface mesh generation
    C2t3 c2t3(tr); // 2D complex in 3D Delaunay triangulation
    CGAL::make_surface_mesh(c2t3,                                 // reconstructed mesh
                            surface,                              // implicit surface
                            criteria,                             // meshing criteria
                            CGAL::Manifold_with_boundary_tag());  // require manifold mesh

    if(tr.number_of_vertices() == 0)
      return EXIT_FAILURE;

    // saves reconstructed surface mesh
    std::ofstream out("kitten_poisson-20-30-0.375.off");
    Polyhedron output_mesh;
    CGAL::output_surface_facets_to_polyhedron(c2t3, output_mesh);
    out << output_mesh;

    return EXIT_SUCCESS;
}
Exemplo n.º 10
0
int main(int argc, char** argv) {
  QApplication app(argc, argv);

  Tr tr;            // 3D-Delaunay triangulation
  C2t3 c2t3 (tr);   // 2D-complex in 3D-Delaunay triangulation

  // the 'function' is a 3D gray level image
  Gray_level_image image("../../../examples/Surface_mesher/data/skull_2.9.inr", 2.9);

  // Carefully choosen bounding sphere: the center must be inside the
  // surface defined by 'image' and the radius must be high enough so that
  // the sphere actually bounds the whole image.
  GT::Point_3 bounding_sphere_center(122., 102., 117.);
  GT::FT bounding_sphere_squared_radius = 200.*200.*2.;
  GT::Sphere_3 bounding_sphere(bounding_sphere_center,
                                   bounding_sphere_squared_radius);

  // definition of the surface, with 10^-2 as relative precision
  Surface_3 surface(image, bounding_sphere, 1e-5);

  // defining meshing criteria
  CGAL::Surface_mesh_default_criteria_3<Tr> criteria(30.,
                                                     5.,
                                                     1.);

  // meshing surface, with the "manifold without boundary" algorithm
  CGAL::make_surface_mesh(c2t3, surface, criteria, CGAL::Manifold_tag());

  QVTKWidget widget;
  widget.resize(256,256);

//   vtkImageData* vtk_image = CGAL::vtk_image_sharing_same_data_pointer(image);

  vtkRenderer *aRenderer = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
    renWin->AddRenderer(aRenderer);

  widget.SetRenderWindow(renWin);

//   vtkContourFilter *skinExtractor = vtkContourFilter::New();
//     skinExtractor->SetInput(vtk_image);
//     skinExtractor->SetValue(0, isovalue);
//     skinExtractor->SetComputeNormals(0);
  vtkPolyDataNormals *skinNormals = vtkPolyDataNormals::New();
//     skinNormals->SetInputConnection(skinExtractor->GetOutputPort());
  vtkPolyData* polydata = CGAL::output_c2t3_to_vtk_polydata(c2t3);
  skinNormals->SetInput(polydata);
    skinNormals->SetFeatureAngle(60.0);
  vtkPolyDataMapper *skinMapper = vtkPolyDataMapper::New();
//     skinMapper->SetInputConnection(skinExtractor->GetOutputPort());
  skinMapper->SetInput(polydata);
    skinMapper->ScalarVisibilityOff();
  vtkActor *skin = vtkActor::New();
    skin->SetMapper(skinMapper);

  // An outline provides context around the data.
  //
//   vtkOutlineFilter *outlineData = vtkOutlineFilter::New();
//     outlineData->SetInput(vtk_image);
//   vtkPolyDataMapper *mapOutline = vtkPolyDataMapper::New();
//     mapOutline->SetInputConnection(outlineData->GetOutputPort());
//   vtkActor *outline = vtkActor::New();
//     outline->SetMapper(mapOutline);
//     outline->GetProperty()->SetColor(0,0,0);

  // It is convenient to create an initial view of the data. The FocalPoint
  // and Position form a vector direction. Later on (ResetCamera() method)
  // this vector is used to position the camera to look at the data in
  // this direction.
  vtkCamera *aCamera = vtkCamera::New();
    aCamera->SetViewUp (0, 0, -1);
    aCamera->SetPosition (0, 1, 0);
    aCamera->SetFocalPoint (0, 0, 0);
    aCamera->ComputeViewPlaneNormal();

  // Actors are added to the renderer. An initial camera view is created.
  // The Dolly() method moves the camera towards the FocalPoint,
  // thereby enlarging the image.
//   aRenderer->AddActor(outline);
  aRenderer->AddActor(skin);
  aRenderer->SetActiveCamera(aCamera);
  aRenderer->ResetCamera ();
  aCamera->Dolly(1.5);

  // Set a background color for the renderer and set the size of the
  // render window (expressed in pixels).
  aRenderer->SetBackground(1,1,1);
  renWin->SetSize(640, 480);

  // Note that when camera movement occurs (as it does in the Dolly()
  // method), the clipping planes often need adjusting. Clipping planes
  // consist of two planes: near and far along the view direction. The 
  // near plane clips out objects in front of the plane; the far plane
  // clips out objects behind the plane. This way only what is drawn
  // between the planes is actually rendered.
  aRenderer->ResetCameraClippingRange ();

  // Initialize the event loop and then start it.
//   iren->Initialize();
//   iren->Start(); 

  // It is important to delete all objects created previously to prevent
  // memory leaks. In this case, since the program is on its way to
  // exiting, it is not so important. But in applications it is
  // essential.
//   vtk_image->Delete();
//   skinExtractor->Delete();
  skinNormals->Delete();
  skinMapper->Delete();
  skin->Delete();
//   outlineData->Delete();
//   mapOutline->Delete();
//   outline->Delete();
  aCamera->Delete();
//   iren->Delete();
  renWin->Delete();
  aRenderer->Delete();
  polydata->Delete();

  widget.show();

  app.exec();
  
  return 0;
}
Exemplo n.º 11
0
int
main(int argc, char* argv[])
{
    // Process command line arguments
    CLI cli(argc, argv);

    // Load image
    std::cout << "Load image." << std::endl;
    const TIFF_image_reader_2 reader(cli.input);
    if (reader.bpp() != 16)
    {
        std::cerr << "Non 16 bit images are not supported.\n";
        return EXIT_FAILURE;
    }

    const Image* const image = reader.get_image<short, K::FT>();

    const LandscapeImage landscape(*image, cli.bottom, cli.z_scale);

    //
    // Surface
    //
    std::cout << "Create mesh surface." << std::endl;
    // Find bounding sphere.
    const K::FT image_center_value =
        *image->interpolate(image->x_size() / 2., image->y_size() / 2.)/cli.z_scale;
    std::cout << "value " << image_center_value << std::endl;

    K::Point_3 bounding_sphere_center(  // Center of the image
        image->x_size() / 2.,
        image->y_size() / 2.,
        (cli.bottom + image_center_value)/2.);
    K::FT bounding_sphere_squared_radius =  // (diagonal/2)^2 = diagonal^2 / 4;
        (POW2(image->x_size()) + POW2(image->y_size()))/4.
            + POW2(std::numeric_limits<short>::max()/cli.z_scale);
    K::Sphere_3 bounding_sphere(bounding_sphere_center,
        bounding_sphere_squared_radius);
    std::cout << "center " << bounding_sphere_center << " r "
        << CGAL::sqrt(bounding_sphere_squared_radius) << std::endl;

    std::cout << "landscape value in center "
        << landscape(bounding_sphere_center) << std::endl;

    Surface surface(landscape, bounding_sphere, 1e-3/CGAL::sqrt(bounding_sphere_squared_radius));

    CGAL::Surface_mesh_default_criteria_3<Tr> mesh_criteria(
        cli.angular_bound,
        cli.facet_size,
        cli.approximation);


    //
    // Mesh generation
    //
    std::cout << "Start mesh generation." << std::endl;
    Tr tr;
    C2t3 c2t3(tr);
    CGAL::make_surface_mesh(c2t3, surface, mesh_criteria, CGAL::Manifold_with_boundary_tag());

    delete image;

    std::ofstream out(cli.output);
    out << std::setprecision(17);
    CGAL::output_surface_facets_to_off(out, c2t3);
    return 0;
}
void PoissonSurfaceReconstruction::reconstruct(std::vector<Eigen::Vector3d> &points, std::vector<Eigen::Vector3d> &normals, TriangleMesh &mesh){

	assert(points.size() == normals.size());

  std::cout << "creating points with normal..." << std::endl;
  std::vector<Point_with_normal> points_with_normal;
  points_with_normal.resize((int)points.size());
  for(int i=0; i<(int)points.size(); i++){
    Vector vec(normals[i][0], normals[i][1], normals[i][2]);
    //Point_with_normal pwn(points[i][0], points[i][1], points[i][2], vec);
    //points_with_normal[i]  = pwn;
    points_with_normal[i] = Point_with_normal(points[i][0], points[i][1], points[i][2], vec);
  }

  std::cout << "constructing poisson reconstruction function..." << std::endl;
  Poisson_reconstruction_function function(points_with_normal.begin(), points_with_normal.end(),
                                           CGAL::make_normal_of_point_with_normal_pmap(PointList::value_type()));

  std::cout << "computing implicit function..." << std::endl;
  if( ! function.compute_implicit_function() ) {
  	std::cout << "compute implicit function is failure" << std::endl;
  	return;
  }
  	//return EXIT_FAILURE;

  // Computes average spacing
  std::cout << "compute average spacing..." << std::endl;
  FT average_spacing = CGAL::compute_average_spacing(points_with_normal.begin(), points_with_normal.end(),
                                                       6 /* knn = 1 ring */);
  // Gets one point inside the implicit surface
  // and computes implicit function bounding sphere radius.
  Point inner_point = function.get_inner_point();
  Sphere bsphere = function.bounding_sphere();
  FT radius = std::sqrt(bsphere.squared_radius());

  // Defines the implicit surface: requires defining a
  // conservative bounding sphere centered at inner point.
  FT sm_sphere_radius = 5.0 * radius;
  FT sm_dichotomy_error = distance_criteria*average_spacing/1000.0; // Dichotomy error must be << sm_distance
  //FT sm_dichotomy_error = distance_criteria*average_spacing/10.0; // Dichotomy error must be << sm_distance
  std::cout << "reconstructed surface" << std::endl;
  Surface_3 reconstructed_surface(function,
                    Sphere(inner_point,sm_sphere_radius*sm_sphere_radius),
                    sm_dichotomy_error/sm_sphere_radius);

  // Defines surface mesh generation criteria    
  CGAL::Surface_mesh_default_criteria_3<STr> criteria(angle_criteria,  // Min triangle angle (degrees)
                                                        radius_criteria*average_spacing,  // Max triangle size
                                                        distance_criteria*average_spacing); // Approximation error
  
  std::cout << "generating surface mesh..." << std::endl;
  // Generates surface mesh with manifold option
  STr tr; // 3D Delaunay triangulation for surface mesh generation
  C2t3 c2t3(tr); // 2D complex in 3D Delaunay triangulation
  CGAL::make_surface_mesh(c2t3,                                 // reconstructed mesh
                            reconstructed_surface,                              // implicit surface
                            criteria,                             // meshing criteria
                            CGAL::Manifold_tag());  // require manifold mesh

  if(tr.number_of_vertices() == 0){
  	std::cout << "surface mesh generation is failed" << std::endl;
  	return;
  }

  Polyhedron surface;
  CGAL::output_surface_facets_to_polyhedron(c2t3, surface);

  // convert CGAL::surface to TriangleMesh //
  std::cout << "converting CGA::surface to TriangleMesh..." << std::endl;
	std::vector<Eigen::Vector3d> pts;
	std::vector<std::vector<int> > faces;
	pts.resize(surface.size_of_vertices());
	faces.resize(surface.size_of_facets());

	Polyhedron::Point_iterator pit;
	int index = 0;
	for(pit=surface.points_begin(); pit!=surface.points_end(); ++pit){
		pts[index][0] = pit->x();
		pts[index][1] = pit->y();
		pts[index][2] = pit->z();				
		index ++;
	}
	index = 0;
	Polyhedron::Face_iterator fit;
	for(fit=surface.facets_begin(); fit!=surface.facets_end(); ++fit){
		std::vector<int > face(3);
		Halfedge_facet_circulator j = fit->facet_begin();
		int f_index = 0;
		do {
			face[f_index] = std::distance(surface.vertices_begin(), j->vertex());
			f_index++;
    } while ( ++j != fit->facet_begin());    

    faces[index] = face;
		index++;
	}

	mesh.createFromFaceVertex(pts, faces);  
}
// Poisson reconstruction method:
// Reconstructs a surface mesh from a point set and returns it as a polyhedron.
Polyhedron* poisson_reconstruct(const Point_set& points,
                                Kernel::FT sm_angle, // Min triangle angle (degrees).
                                Kernel::FT sm_radius, // Max triangle size w.r.t. point set average spacing.
                                Kernel::FT sm_distance, // Approximation error w.r.t. point set average spacing.
                                const QString& solver_name,
                                bool use_two_passes) // solver name
{
    CGAL::Timer task_timer; task_timer.start();

    //***************************************
    // Checks requirements
    //***************************************

    if (points.size() == 0)
    {
      std::cerr << "Error: empty point set" << std::endl;
      return NULL;
    }

    bool points_have_normals = (points.begin()->normal() != CGAL::NULL_VECTOR);
    if ( ! points_have_normals )
    {
      std::cerr << "Input point set not supported: this reconstruction method requires oriented normals" << std::endl;
      return NULL;
    }

    CGAL::Timer reconstruction_timer; reconstruction_timer.start();

    //***************************************
    // Computes implicit function
    //***************************************

 
    std::cerr << "Computes Poisson implicit function "
              << "using " << solver_name.toLatin1().data() << " solver...\n";
              
    
    // Creates implicit function from the point set.
    // Note: this method requires an iterator over points
    // + property maps to access each point's position and normal.
    // The position property map can be omitted here as we use iterators over Point_3 elements.
    Poisson_reconstruction_function function(
                              points.begin(), points.end(),
                              CGAL::make_normal_of_point_with_normal_pmap(Point_set::value_type()));

    bool ok = false;    
    #ifdef CGAL_EIGEN3_ENABLED
    if(solver_name=="Eigen - built-in simplicial LDLt")
    {
      CGAL::Eigen_solver_traits<Eigen::SimplicialCholesky<CGAL::Eigen_sparse_matrix<double>::EigenType> > solver;
      ok = function.compute_implicit_function(solver, use_two_passes);
    }
    if(solver_name=="Eigen - built-in CG")
    {
      CGAL::Eigen_solver_traits<Eigen::ConjugateGradient<CGAL::Eigen_sparse_matrix<double>::EigenType> > solver;
      solver.solver().setTolerance(1e-6);
      solver.solver().setMaxIterations(1000);
      ok = function.compute_implicit_function(solver, use_two_passes);
    }
    #endif

    // Computes the Poisson indicator function f()
    // at each vertex of the triangulation.
    if ( ! ok )
    {
      std::cerr << "Error: cannot compute implicit function" << std::endl;
      return NULL;
    }

    // Prints status
    std::cerr << "Total implicit function (triangulation+refinement+solver): " << task_timer.time() << " seconds\n";
    task_timer.reset();

    //***************************************
    // Surface mesh generation
    //***************************************

    std::cerr << "Surface meshing...\n";

    // Computes average spacing
    Kernel::FT average_spacing = CGAL::compute_average_spacing(points.begin(), points.end(),
                                                       6 /* knn = 1 ring */);

    // Gets one point inside the implicit surface
    Kernel::Point_3 inner_point = function.get_inner_point();
    Kernel::FT inner_point_value = function(inner_point);
    if(inner_point_value >= 0.0)
    {
      std::cerr << "Error: unable to seed (" << inner_point_value << " at inner_point)" << std::endl;
      return NULL;
    }

    // Gets implicit function's radius
    Kernel::Sphere_3 bsphere = function.bounding_sphere();
    Kernel::FT radius = std::sqrt(bsphere.squared_radius());

    // Defines the implicit surface: requires defining a
  	// conservative bounding sphere centered at inner point.
    Kernel::FT sm_sphere_radius = 5.0 * radius;
    Kernel::FT sm_dichotomy_error = sm_distance*average_spacing/1000.0; // Dichotomy error must be << sm_distance
    Surface_3 surface(function,
                      Kernel::Sphere_3(inner_point,sm_sphere_radius*sm_sphere_radius),
                      sm_dichotomy_error/sm_sphere_radius);

    // Defines surface mesh generation criteria
    CGAL::Surface_mesh_default_criteria_3<STr> criteria(sm_angle,  // Min triangle angle (degrees)
                                                        sm_radius*average_spacing,  // Max triangle size
                                                        sm_distance*average_spacing); // Approximation error

    CGAL_TRACE_STREAM << "  make_surface_mesh(sphere center=("<<inner_point << "),\n"
                      << "                    sphere radius="<<sm_sphere_radius<<",\n"
                      << "                    angle="<<sm_angle << " degrees,\n"
                      << "                    triangle size="<<sm_radius<<" * average spacing="<<sm_radius*average_spacing<<",\n"
                      << "                    distance="<<sm_distance<<" * average spacing="<<sm_distance*average_spacing<<",\n"
                      << "                    dichotomy error=distance/"<<sm_distance*average_spacing/sm_dichotomy_error<<",\n"
                      << "                    Manifold_with_boundary_tag)\n";

    // Generates surface mesh with manifold option
    STr tr; // 3D Delaunay triangulation for surface mesh generation
    C2t3 c2t3(tr); // 2D complex in 3D Delaunay triangulation
    CGAL::make_surface_mesh(c2t3,                                 // reconstructed mesh
                            surface,                              // implicit surface
                            criteria,                             // meshing criteria
                            CGAL::Manifold_with_boundary_tag());  // require manifold mesh

    // Prints status
    std::cerr << "Surface meshing: " << task_timer.time() << " seconds, "
                                     << tr.number_of_vertices() << " output vertices"
                                     << std::endl;
    task_timer.reset();

    if(tr.number_of_vertices() == 0)
      return NULL;

    // Converts to polyhedron
    Polyhedron* output_mesh = new Polyhedron;
    CGAL::output_surface_facets_to_polyhedron(c2t3, *output_mesh);

    // Prints total reconstruction duration
    std::cerr << "Total reconstruction (implicit function + meshing): " << reconstruction_timer.time() << " seconds\n";

    //***************************************
    // Computes reconstruction error
    //***************************************

    // Constructs AABB tree and computes internal KD-tree
    // data structure to accelerate distance queries
    AABB_tree tree(faces(*output_mesh).first, faces(*output_mesh).second, *output_mesh);
    tree.accelerate_distance_queries();

    // Computes distance from each input point to reconstructed mesh
    double max_distance = DBL_MIN;
    double avg_distance = 0;
    for (Point_set::const_iterator p=points.begin(); p!=points.end(); p++)
    {
      double distance = std::sqrt(tree.squared_distance(*p));

      max_distance = (std::max)(max_distance, distance);
      avg_distance += distance;
    }
    avg_distance /= double(points.size());

    std::cerr << "Reconstruction error:\n"
              << "  max = " << max_distance << " = " << max_distance/average_spacing << " * average spacing\n"
              << "  avg = " << avg_distance << " = " << avg_distance/average_spacing << " * average spacing\n";

    return output_mesh;
}
bool poisson_reconstruct(FaceGraph* graph,
                         Point_set& points,
                         typename Traits::FT sm_angle, // Min triangle angle (degrees).
                         typename Traits::FT sm_radius, // Max triangle size w.r.t. point set average spacing.
                         typename Traits::FT sm_distance, // Approximation error w.r.t. point set average spacing.
                         const QString& solver_name, // solver name
                         bool use_two_passes,
                         bool do_not_fill_holes)
{
  // Poisson implicit function
  typedef CGAL::Poisson_reconstruction_function<Traits> Poisson_reconstruction_function;

  // Surface mesher
  typedef CGAL::Surface_mesh_default_triangulation_3 STr;
  typedef CGAL::Surface_mesh_complex_2_in_triangulation_3<STr> C2t3;
  typedef CGAL::Implicit_surface_3<Traits, Poisson_reconstruction_function> Surface_3;

  // AABB tree
  typedef CGAL::AABB_face_graph_triangle_primitive<FaceGraph> Primitive;
  typedef CGAL::AABB_traits<Traits, Primitive> AABB_traits;
  typedef CGAL::AABB_tree<AABB_traits> AABB_tree;
    CGAL::Timer task_timer; task_timer.start();

    //***************************************
    // Checks requirements
    //***************************************

    if (points.size() == 0)
    {
      std::cerr << "Error: empty point set" << std::endl;
     return false;
    }

    bool points_have_normals = points.has_normal_map();
    if ( ! points_have_normals )
    {
      std::cerr << "Input point set not supported: this reconstruction method requires oriented normals" << std::endl;
     return false;
    }

    CGAL::Timer reconstruction_timer; reconstruction_timer.start();

    //***************************************
    // Computes implicit function
    //***************************************

 
    std::cerr << "Computes Poisson implicit function "
              << "using " << solver_name.toLatin1().data() << " solver...\n";
              
    
    // Creates implicit function from the point set.
    // Note: this method requires an iterator over points
    // + property maps to access each point's position and normal.
    Poisson_reconstruction_function function(points.begin_or_selection_begin(), points.end(),
                                             points.point_map(), points.normal_map());

    bool ok = false;    
    #ifdef CGAL_EIGEN3_ENABLED
    if(solver_name=="Eigen - built-in simplicial LDLt")
    {
      CGAL::Eigen_solver_traits<Eigen::SimplicialCholesky<CGAL::Eigen_sparse_matrix<double>::EigenType> > solver;
      ok = function.compute_implicit_function(solver, use_two_passes);
    }
    if(solver_name=="Eigen - built-in CG")
    {
      CGAL::Eigen_solver_traits<Eigen::ConjugateGradient<CGAL::Eigen_sparse_matrix<double>::EigenType> > solver;
      solver.solver().setTolerance(1e-6);
      solver.solver().setMaxIterations(1000);
      ok = function.compute_implicit_function(solver, use_two_passes);
    }
    #endif

    // Computes the Poisson indicator function f()
    // at each vertex of the triangulation.
    if ( ! ok )
    {
      std::cerr << "Error: cannot compute implicit function" << std::endl;
     return false;
    }

    // Prints status
    std::cerr << "Total implicit function (triangulation+refinement+solver): " << task_timer.time() << " seconds\n";
    task_timer.reset();

    //***************************************
    // Surface mesh generation
    //***************************************

    std::cerr << "Surface meshing...\n";

    // Computes average spacing
    Kernel::FT average_spacing = CGAL::compute_average_spacing<Concurrency_tag>(points.all_or_selection_if_not_empty(),
                                                                                6 /* knn = 1 ring */,
                                                                                points.parameters());

    // Gets one point inside the implicit surface
    Kernel::Point_3 inner_point = function.get_inner_point();
    Kernel::FT inner_point_value = function(inner_point);
    if(inner_point_value >= 0.0)
    {
      std::cerr << "Error: unable to seed (" << inner_point_value << " at inner_point)" << std::endl;
     return false;
    }

    // Gets implicit function's radius
    Kernel::Sphere_3 bsphere = function.bounding_sphere();
    Kernel::FT radius = std::sqrt(bsphere.squared_radius());

    // Defines the implicit surface: requires defining a
  	// conservative bounding sphere centered at inner point.
    Kernel::FT sm_sphere_radius = 5.0 * radius;
    Kernel::FT sm_dichotomy_error = sm_distance*average_spacing/1000.0; // Dichotomy error must be << sm_distance
    Surface_3 surface(function,
                      Kernel::Sphere_3(inner_point,sm_sphere_radius*sm_sphere_radius),
                      sm_dichotomy_error/sm_sphere_radius);

    // Defines surface mesh generation criteria
    CGAL::Surface_mesh_default_criteria_3<STr> criteria(sm_angle,  // Min triangle angle (degrees)
                                                        sm_radius*average_spacing,  // Max triangle size
                                                        sm_distance*average_spacing); // Approximation error

    CGAL_TRACE_STREAM << "  make_surface_mesh(sphere center=("<<inner_point << "),\n"
                      << "                    sphere radius="<<sm_sphere_radius<<",\n"
                      << "                    angle="<<sm_angle << " degrees,\n"
                      << "                    triangle size="<<sm_radius<<" * average spacing="<<sm_radius*average_spacing<<",\n"
                      << "                    distance="<<sm_distance<<" * average spacing="<<sm_distance*average_spacing<<",\n"
                      << "                    dichotomy error=distance/"<<sm_distance*average_spacing/sm_dichotomy_error<<",\n"
                      << "                    Manifold_with_boundary_tag)\n";

    // Generates surface mesh with manifold option
    STr tr; // 3D Delaunay triangulation for surface mesh generation
    C2t3 c2t3(tr); // 2D complex in 3D Delaunay triangulation
    CGAL::make_surface_mesh(c2t3,                                 // reconstructed mesh
                            surface,                              // implicit surface
                            criteria,                             // meshing criteria
                            CGAL::Manifold_with_boundary_tag());  // require manifold mesh

    // Prints status
    std::cerr << "Surface meshing: " << task_timer.time() << " seconds, "
                                     << tr.number_of_vertices() << " output vertices"
                                     << std::endl;
    task_timer.reset();

    if(tr.number_of_vertices() == 0)
     return false;

    // Converts to polyhedron
    CGAL::facets_in_complex_2_to_triangle_mesh(c2t3, *graph);

    // Prints total reconstruction duration
    std::cerr << "Total reconstruction (implicit function + meshing): " << reconstruction_timer.time() << " seconds\n";

    //***************************************
    // Computes reconstruction error
    //***************************************

    // Constructs AABB tree and computes internal KD-tree
    // data structure to accelerate distance queries
    AABB_tree tree(faces(*graph).first, faces(*graph).second, *graph);
    tree.accelerate_distance_queries();

    // Computes distance from each input point to reconstructed mesh
    double max_distance = DBL_MIN;
    double avg_distance = 0;

    std::set<typename boost::graph_traits<FaceGraph>::face_descriptor> faces_to_keep;
    
    for (Point_set::const_iterator p=points.begin_or_selection_begin(); p!=points.end(); p++)
    {
      typename AABB_traits::Point_and_primitive_id pap = tree.closest_point_and_primitive (points.point (*p));
      double distance = std::sqrt(CGAL::squared_distance (pap.first, points.point(*p)));
      
      max_distance = (std::max)(max_distance, distance);
      avg_distance += distance;

      typename boost::graph_traits<FaceGraph>::face_descriptor f = pap.second;
      faces_to_keep.insert (f);  
    }
    avg_distance /= double(points.size());

    std::cerr << "Reconstruction error:\n"
              << "  max = " << max_distance << " = " << max_distance/average_spacing << " * average spacing\n"
              << "  avg = " << avg_distance << " = " << avg_distance/average_spacing << " * average spacing\n";

    if (do_not_fill_holes)
      {
        typename boost::graph_traits<FaceGraph>::face_iterator it = faces(*graph).begin ();
        while (it != faces(*graph).end ())
	  {
            typename boost::graph_traits<FaceGraph>::face_iterator current = it ++;

            if (faces_to_keep.find (*current) == faces_to_keep.end ())
            {
              CGAL::Euler::remove_face(halfedge (*current, *graph), *graph);
            }

	  }

      }
    return true;
}