diff --git a/.travis.yml b/.travis.yml index 61a6efa477a..82227701898 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,5 @@ language: cpp -dist: trusty +dist: xenial sudo: required git: depth: 3 @@ -52,19 +52,19 @@ env: - PACKAGE='Triangulation Triangulation_2 Triangulation_3 ' - PACKAGE='Union_find Visibility_2 Voronoi_diagram_2 ' - PACKAGE='wininst ' -compiler: clang-3.6 +compiler: clang install: - echo "$PWD" - if [ -n "$TRAVIS_PULL_REQUEST" ] && [ "$PACKAGE" != CHECK ]; then DO_IGNORE=FALSE; for ARG in $(echo "$PACKAGE");do if [ "$ARG" = "Maintenance" ]; then continue; fi; . $PWD/.travis/test_package.sh "$PWD" "$ARG"; echo "DO_IGNORE is $DO_IGNORE"; if [ "$DO_IGNORE" = "FALSE" ]; then break; fi; done; if [ "$DO_IGNORE" = "TRUE" ]; then travis_terminate 0; fi;fi - bash .travis/install.sh - - export CXX=clang++-3.6 CC=clang-3.6; + - export CXX=clang++ CC=clang; before_script: - wget -O doxygen_exe https://cgal.geometryfactory.com/~mgimeno/doxygen_exe - sudo mv doxygen_exe /usr/bin/doxygen - sudo chmod +x /usr/bin/doxygen - mkdir -p build - cd build -- cmake -DCMAKE_CXX_FLAGS="-std=c++11" -DCGAL_HEADER_ONLY=ON -DQt5_DIR="/opt/qt55/lib/cmake/Qt5" -DQt5Svg_DIR="/opt/qt55/lib/cmake/Qt5Svg" -DQt5OpenGL_DIR="/opt/qt55/lib/cmake/Qt5OpenGL" -DCMAKE_CXX_FLAGS_RELEASE=-DCGAL_NDEBUG -DWITH_examples=ON -DWITH_demos=ON -DWITH_tests=ON .. +- cmake -DCMAKE_CXX_FLAGS="-std=c++11" -DCGAL_HEADER_ONLY=ON -DCMAKE_CXX_FLAGS_RELEASE=-DCGAL_NDEBUG -DWITH_examples=ON -DWITH_demos=ON -DWITH_tests=ON .. - make - sudo make install &>/dev/null - cd .. diff --git a/.travis/build_package.sh b/.travis/build_package.sh index c47cd822c21..adfc3bda083 100755 --- a/.travis/build_package.sh +++ b/.travis/build_package.sh @@ -18,40 +18,18 @@ function build_tests { function build_demo { mkdir -p build-travis cd build-travis - if [ $NEED_3D = 1 ]; then - #install libqglviewer - git clone --depth=4 -b v2.6.3 --single-branch https://github.com/GillesDebunne/libQGLViewer.git ./qglviewer - pushd ./qglviewer/QGLViewer - #use qt5 instead of qt4 -# export QT_SELECT=5 - qmake NO_QT_VERSION_SUFFIX=yes - make -j2 - if [ ! -f libQGLViewer.so ]; then - echo "libQGLViewer.so not made" - exit 1 - else - echo "QGLViewer built successfully" - fi - #end install qglviewer - popd - fi EXTRA_CXX_FLAGS= case "$CC" in clang*) EXTRA_CXX_FLAGS="-Werror=inconsistent-missing-override" ;; esac - if [ $NEED_3D = 1 ]; then - QGLVIEWERROOT=$PWD/qglviewer - export QGLVIEWERROOT - fi - cmake -DCGAL_DIR="/usr/local/lib/cmake/CGAL" -DQt5_DIR="/opt/qt55/lib/cmake/Qt5" -DQt5Svg_DIR="/opt/qt55/lib/cmake/Qt5Svg" -DQt5OpenGL_DIR="/opt/qt55/lib/cmake/Qt5OpenGL" -DCGAL_DONT_OVERRIDE_CMAKE_FLAGS:BOOL=ON -DCMAKE_CXX_FLAGS="${CXX_FLAGS} ${EXTRA_CXX_FLAGS}" .. + cmake -DCGAL_DIR="/usr/local/lib/cmake/CGAL" -DCGAL_DONT_OVERRIDE_CMAKE_FLAGS:BOOL=ON -DCMAKE_CXX_FLAGS="${CXX_FLAGS} ${EXTRA_CXX_FLAGS}" .. make -j2 } old_IFS=$IFS IFS=$' ' ROOT="$PWD/.." -NEED_3D=0 for ARG in $(echo "$@") do #skip package maintenance @@ -146,12 +124,6 @@ cd $ROOT EXAMPLES="$ARG/examples/$ARG" TEST="$ARG/test/$ARG" DEMOS=$ROOT/$ARG/demo/* - if [ "$ARG" = AABB_tree ] || [ "$ARG" = Alpha_shapes_3 ] ||\ - [ "$ARG" = Circular_kernel_3 ] || [ "$ARG" = Linear_cell_complex ] ||\ - [ "$ARG" = Periodic_3_triangulation_3 ] || [ "$ARG" = Principal_component_analysis ] ||\ - [ "$ARG" = Surface_mesher ] || [ "$ARG" = Triangulation_3 ]; then - NEED_3D=1 - fi if [ -d "$ROOT/$EXAMPLES" ] then @@ -206,10 +178,9 @@ cd $ROOT done if [ "$ARG" = Polyhedron_demo ]; then DEMO=Polyhedron/demo/Polyhedron - NEED_3D=1 cd "$ROOT/$DEMO" build_demo - fi + fi done IFS=$old_IFS # Local Variables: diff --git a/.travis/generate_travis.sh b/.travis/generate_travis.sh index 5e6c46889d4..63a5e1f3705 100755 --- a/.travis/generate_travis.sh +++ b/.travis/generate_travis.sh @@ -60,7 +60,7 @@ done COPY=0 for LINE in $(cat "$PWD/.travis/template.txt") do - if [ "$LINE" = "compiler: clang-3.6" ] + if [ "$LINE" = "compiler: clang" ] then COPY=1 fi diff --git a/.travis/install.sh b/.travis/install.sh index 4d78446fc74..11e94f59b1d 100644 --- a/.travis/install.sh +++ b/.travis/install.sh @@ -2,23 +2,13 @@ [ -n "$CGAL_DEBUG_TRAVIS" ] && set -x DONE=0 +sudo apt-get update while [ $DONE = 0 ] do - DONE=1 && sudo -E apt-add-repository -y "ppa:ppsspp/cmake" || DONE=0 && sleep 5 -done -DONE=0 -while [ $DONE = 0 ] -do - DONE=1 && sudo -E apt-add-repository -y "ppa:hedges/qt5.5" || DONE=0 && sleep 5 -done - -DONE=0 -while [ $DONE = 0 ] -do - DONE=1 && sudo -E apt-get -yq --no-install-suggests --no-install-recommends --force-yes install clang-3.6 zsh \ -flex bison cmake graphviz libgmp-dev libmpfr-dev libmpfi-dev zlib1g-dev libeigen3-dev libboost1.55-dev \ -libboost-system1.55-dev libboost-program-options1.55-dev libboost-thread1.55-dev libboost-iostreams1.55-dev \ -qt55base qt55script qt55svg qt55tools qt55graphicaleffects libopencv-dev mesa-common-dev libmetis-dev libglu1-mesa-dev \ + DONE=1 && sudo -E apt-get -yq --no-install-suggests --no-install-recommends --force-yes install clang zsh \ +flex bison cmake graphviz libgmp-dev libmpfr-dev libmpfi-dev zlib1g-dev libeigen3-dev libboost-dev \ +libboost-system-dev libboost-program-options-dev libboost-thread-dev libboost-iostreams-dev \ +qtbase5-dev libqt5opengl5-dev qtscript5-dev libqt5svg5-dev qttools5-dev qttools5-dev-tools qml-module-qtgraphicaleffects libopencv-dev mesa-common-dev libmetis-dev libglu1-mesa-dev \ || DONE=0 && sudo apt-get update done exit 0 diff --git a/.travis/template.txt b/.travis/template.txt index 1632aa16cbf..97662bb5b89 100644 --- a/.travis/template.txt +++ b/.travis/template.txt @@ -1,5 +1,5 @@ language: cpp -dist: trusty +dist: xenial sudo: required git: depth: 3 @@ -7,19 +7,19 @@ env: matrix: PACKAGES_MATRIX -compiler: clang-3.6 +compiler: clang install: - echo "$PWD" - if [ -n "$TRAVIS_PULL_REQUEST" ] && [ "$PACKAGE" != CHECK ]; then DO_IGNORE=FALSE; for ARG in $(echo "$PACKAGE");do if [ "$ARG" = "Maintenance" ]; then continue; fi; . $PWD/.travis/test_package.sh "$PWD" "$ARG"; echo "DO_IGNORE is $DO_IGNORE"; if [ "$DO_IGNORE" = "FALSE" ]; then break; fi; done; if [ "$DO_IGNORE" = "TRUE" ]; then travis_terminate 0; fi;fi - bash .travis/install.sh - - export CXX=clang++-3.6 CC=clang-3.6; + - export CXX=clang++ CC=clang; before_script: - wget -O doxygen_exe https://cgal.geometryfactory.com/~mgimeno/doxygen_exe - sudo mv doxygen_exe /usr/bin/doxygen - sudo chmod +x /usr/bin/doxygen - mkdir -p build - cd build -- cmake -DCMAKE_CXX_FLAGS="-std=c++11" -DCGAL_HEADER_ONLY=ON -DQt5_DIR="/opt/qt55/lib/cmake/Qt5" -DQt5Svg_DIR="/opt/qt55/lib/cmake/Qt5Svg" -DQt5OpenGL_DIR="/opt/qt55/lib/cmake/Qt5OpenGL" -DCMAKE_CXX_FLAGS_RELEASE=-DCGAL_NDEBUG -DWITH_examples=ON -DWITH_demos=ON -DWITH_tests=ON .. +- cmake -DCMAKE_CXX_FLAGS="-std=c++11" -DCGAL_HEADER_ONLY=ON -DCMAKE_CXX_FLAGS_RELEASE=-DCGAL_NDEBUG -DWITH_examples=ON -DWITH_demos=ON -DWITH_tests=ON .. - make - sudo make install &>/dev/null - cd .. diff --git a/AABB_tree/examples/AABB_tree/AABB_custom_indexed_triangle_set_example.cpp b/AABB_tree/examples/AABB_tree/AABB_custom_indexed_triangle_set_example.cpp index b6c9d360951..4311d1cbbf8 100644 --- a/AABB_tree/examples/AABB_tree/AABB_custom_indexed_triangle_set_example.cpp +++ b/AABB_tree/examples/AABB_tree/AABB_custom_indexed_triangle_set_example.cpp @@ -3,7 +3,7 @@ #include #include -#include +#include #include #include diff --git a/AABB_tree/examples/AABB_tree/AABB_custom_triangle_soup_example.cpp b/AABB_tree/examples/AABB_tree/AABB_custom_triangle_soup_example.cpp index 0bcfbb6ca9a..590c5c0c7ba 100644 --- a/AABB_tree/examples/AABB_tree/AABB_custom_triangle_soup_example.cpp +++ b/AABB_tree/examples/AABB_tree/AABB_custom_triangle_soup_example.cpp @@ -1,10 +1,11 @@ + // Author(s) : Camille Wormser, Pierre Alliez // Example of an AABB tree used with a simple list of // triangles (a triangle soup) stored into an array of points. #include #include -#include +#include #include #include diff --git a/BGL/doc/BGL/Doxyfile.in b/BGL/doc/BGL/Doxyfile.in index 6948a31cf43..9681886835a 100644 --- a/BGL/doc/BGL/Doxyfile.in +++ b/BGL/doc/BGL/Doxyfile.in @@ -16,6 +16,7 @@ INPUT += ${CGAL_PACKAGE_INCLUDE_DIR}/CGAL/boost/graph/Euler_operations.h \ ${CGAL_PACKAGE_INCLUDE_DIR}/CGAL/boost/graph/METIS/partition_graph.h \ ${CGAL_PACKAGE_INCLUDE_DIR}/CGAL/boost/graph/METIS/partition_dual_graph.h + EXAMPLE_PATH = ${CGAL_Surface_mesh_skeletonization_EXAMPLE_DIR} \ ${CGAL_Surface_mesh_segmentation_EXAMPLE_DIR} \ ${CGAL_Polygon_mesh_processing_EXAMPLE_DIR} \ diff --git a/BGL/doc/BGL/NamedParameters.txt b/BGL/doc/BGL/NamedParameters.txt index f775e26ce48..ce3be60f8f4 100644 --- a/BGL/doc/BGL/NamedParameters.txt +++ b/BGL/doc/BGL/NamedParameters.txt @@ -81,6 +81,13 @@ being marked or not.\n Default: a default property map where no edge is constrained \cgalNPEnd +\cgalNPBegin{use_binary_mode} \anchor BGL_use_binary_mode +is a Boolean indicating whether the binary mode or the ASCII mode should be used +when writing data into a stream.\n +Type: `bool`\n +Default: Function specific. +\cgalNPEnd + \cgalNPBegin{METIS_options} \anchor BGL_METIS_options is a parameter used in `partition_graph()` and `partition_dual_graph()` to pass options to the METIS graph partitioner. The many options of METIS diff --git a/BGL/doc/BGL/PackageDescription.txt b/BGL/doc/BGL/PackageDescription.txt index d069c70ee55..a3b67ca990c 100644 --- a/BGL/doc/BGL/PackageDescription.txt +++ b/BGL/doc/BGL/PackageDescription.txt @@ -709,6 +709,7 @@ user might encounter. - \link PkgBGLIOFct CGAL::read_off() \endlink - \link PkgBGLIOFct CGAL::write_off() \endlink - \link PkgBGLIOFct CGAL::write_wrl() \endlink +- `CGAL::write_vtp()` */ diff --git a/BGL/include/CGAL/boost/graph/io.h b/BGL/include/CGAL/boost/graph/io.h index 60dcfca72ad..cb5c8082b21 100644 --- a/BGL/include/CGAL/boost/graph/io.h +++ b/BGL/include/CGAL/boost/graph/io.h @@ -34,6 +34,7 @@ #include #include #include +#include namespace CGAL { /*! @@ -401,6 +402,278 @@ bool write_inp(std::ostream& os, { return write_inp(os, g, name, type, parameters::all_default()); } + +namespace internal { + namespace write_vtp { + +// writes the polys appended data at the end of the .vtp file +template +void +write_polys(std::ostream& os, + const Mesh & mesh, + const NamedParameters& np) +{ + typedef typename boost::graph_traits::vertex_descriptor vertex_descriptor; + typedef typename boost::graph_traits::face_iterator face_iterator; + typedef typename CGAL::Polygon_mesh_processing::GetVertexIndexMap::type Vimap; + Vimap V = choose_param(get_param(np, CGAL::internal_np::vertex_index), + get_const_property_map(CGAL::internal_np::vertex_index, mesh)); + + std::vector connectivity_table; + std::vector offsets; + std::vector cell_type(num_faces(mesh),5); // triangle == 5 + + std::size_t off = 0; + for( face_iterator fit = faces(mesh).begin() ; + fit != faces(mesh).end() ; + ++fit ) + { + off += 3; + offsets.push_back(off); + BOOST_FOREACH(vertex_descriptor v, + vertices_around_face(halfedge(*fit, mesh), mesh)) + connectivity_table.push_back(V[v]); + } + write_vector(os,connectivity_table); + write_vector(os,offsets); + write_vector(os,cell_type); +} +//todo use named params for maps +template +void +write_polys_tag(std::ostream& os, + const Mesh & mesh, + bool binary, + std::size_t& offset, + const NamedParameters& np) +{ + typedef typename boost::graph_traits::vertex_descriptor vertex_descriptor; + typedef typename boost::graph_traits::face_iterator face_iterator; + typedef typename CGAL::Polygon_mesh_processing::GetVertexIndexMap::type Vimap; + Vimap V = choose_param(get_param(np, CGAL::internal_np::vertex_index), + get_const_property_map(CGAL::internal_np::vertex_index, mesh)); + + std::string formatattribute = + binary ? " format=\"appended\"" : " format=\"ascii\""; + + std::string typeattribute; + switch(sizeof(std::size_t)) { + case 8: typeattribute = " type=\"UInt64\""; break; + case 4: typeattribute = " type=\"UInt32\""; break; + default: CGAL_error_msg("Unknown size of std::size_t"); + } + + // Write connectivity table + os << " \n" + << " \n"; + offset += (3 * num_faces(mesh)+ 1) * sizeof(std::size_t); + // 3 indices (size_t) per triangle + length of the encoded data (size_t) + } + else { + os << "\">\n"; + for( face_iterator fit = faces(mesh).begin() ; + fit != faces(mesh).end() ; + ++fit ) + { + BOOST_FOREACH(vertex_descriptor v, + vertices_around_face(halfedge(*fit, mesh), mesh)) + os << V[v] << " "; + } + os << " \n"; + } + + // Write offsets + os << " \n"; + offset += (num_faces(mesh) + 1) * sizeof(std::size_t); + // 1 offset (size_t) per triangle + length of the encoded data (size_t) + } + else { + os << "\">\n"; + std::size_t polys_offset = 0; + for( face_iterator fit = faces(mesh).begin() ; + fit != faces(mesh).end() ; + ++fit ) + { + polys_offset += 3; + os << polys_offset << " "; + } + os << " \n"; + } + + // Write cell type (triangle == 5) + os << " \n"; + offset += num_faces(mesh) + sizeof(std::size_t); + // 1 unsigned char per cell + length of the encoded data (size_t) + } + else { + os << "\">\n"; + for(std::size_t i = 0; i< num_faces(mesh); ++i) + os << "5 "; + os << " \n"; + } + os << " \n"; +} + +//todo : use namedparams for points and ids +//overload for facegraph +template +void +write_points_tag(std::ostream& os, + const Mesh & mesh, + bool binary, + std::size_t& offset, + const NamedParameters& np) +{ + typedef typename boost::graph_traits::vertex_iterator vertex_iterator; + typedef typename CGAL::Polygon_mesh_processing::GetVertexPointMap::const_type Vpmap; + Vpmap vpm = choose_param(get_param(np, CGAL::vertex_point), + get_const_property_map(CGAL::vertex_point, mesh)); + typedef typename boost::property_traits::value_type Point_t; + typedef typename CGAL::Kernel_traits::Kernel Gt; + typedef typename Gt::FT FT; + + std::string format = binary ? "appended" : "ascii"; + std::string type = (sizeof(FT) == 8) ? "Float64" : "Float32"; + + os << " \n" + << " \n"; + offset += 3 * num_vertices(mesh) * sizeof(FT) + sizeof(std::size_t); + // 3 coords per points + length of the encoded data (size_t) + } + else { + os << "\">\n"; + for( vertex_iterator vit = vertices(mesh).begin(); + vit != vertices(mesh).end(); + ++vit) + { + os << get(vpm, *vit).x() << " " << get(vpm, *vit).y() << " " + << get(vpm, *vit).z() << " "; + } + os << " \n"; + } + os << " \n"; +} + + +// writes the points appended data at the end of the .vtp file +template +void +write_polys_points(std::ostream& os, + const Mesh & mesh, + const NamedParameters& np) +{ + typedef typename boost::graph_traits::vertex_iterator vertex_iterator; + typedef typename CGAL::Polygon_mesh_processing::GetVertexPointMap::const_type Vpmap; + Vpmap vpm = choose_param(get_param(np, CGAL::vertex_point), + get_const_property_map(CGAL::vertex_point, mesh)); + typedef typename boost::property_traits::value_type Point_t; + typedef typename CGAL::Kernel_traits::Kernel Gt; + typedef typename Gt::FT FT; + std::vector coordinates; + for( vertex_iterator vit = vertices(mesh).begin(); + vit != vertices(mesh).end(); + ++vit) + { + coordinates.push_back(get(vpm, *vit).x()); + coordinates.push_back(get(vpm, *vit).y()); + coordinates.push_back(get(vpm, *vit).z()); + } + write_vector(os,coordinates); +} + + } // end namespace CGAL::internal::write_vtp +} // end namespace CGAL::internal + +/*!\ingroup PkgBGLIOFct + * + * \brief writes a triangulated surface mesh in the `PolyData` XML format. + * + * \tparam TriangleMesh a model of `FaceListGraph` with only triangle faces. + * \tparam NamedParameters a sequence of \ref pmp_namedparameters "Named Parameters" + * + * \param os the stream used for writing. + * \param mesh the triangle mesh to be written. + * \param np optional sequence of \ref pmp_namedparameters "Named Parameters" among the + * ones listed below + * + * \cgalNamedParamsBegin + * \cgalParamBegin{use_binary_mode} a Boolean indicating if the + * data should be written in binary (`true`, the default) or in ASCII (`false`). + * \cgalParamEnd + * \cgalParamBegin{vertex_point_map} the property map with the points associated to + * the vertices of `mesh`. If this parameter is omitted, an internal property map for + * `CGAL::vertex_point_t` must be available in `TriangleMesh`. + * \cgalParamEnd + * \cgalParamBegin{vertex_index_map} the property map with the indices associated to + * the vertices of `mesh`. If this parameter is omitted, an internal property map for + * `CGAL::vertex_index_t` must be available in `TriangleMesh`. + * \cgalParamEnd + * \cgalNamedParamsEnd + */ +template +void write_vtp(std::ostream& os, + const TriangleMesh& mesh, + const NamedParameters& np) +{ + os << "\n" + << "\n" + << " " << "\n"; + + os << " \n"; + std::size_t offset = 0; + const bool binary = boost::choose_param(boost::get_param(np, internal_np::use_binary_mode), true); + internal::write_vtp::write_points_tag(os,mesh,binary,offset, np); + internal::write_vtp::write_polys_tag(os,mesh,binary,offset, np); + os << " \n" + << " \n"; + if (binary) { + os << "\n_"; + internal::write_vtp::write_polys_points(os,mesh, np); + internal::write_vtp::write_polys(os,mesh, np); + } + os << "\n"; +} + +template +void write_vtp(std::ostream& os, + const TriangleMesh& mesh) +{ + write_vtp(os, mesh, CGAL::parameters::all_default()); +} + } // namespace CGAL #endif // CGAL_BOOST_GRAPH_IO_H diff --git a/BGL/include/CGAL/boost/graph/parameters_interface.h b/BGL/include/CGAL/boost/graph/parameters_interface.h index 5c4c5ceb3b5..bd4f15d8e23 100644 --- a/BGL/include/CGAL/boost/graph/parameters_interface.h +++ b/BGL/include/CGAL/boost/graph/parameters_interface.h @@ -28,6 +28,7 @@ CGAL_add_named_parameter(edge_is_constrained_t, edge_is_constrained, edge_is_con CGAL_add_named_parameter(first_index_t, first_index, first_index) CGAL_add_named_parameter(number_of_iterations_t, number_of_iterations, number_of_iterations) CGAL_add_named_parameter(verbosity_level_t, verbosity_level, verbosity_level) +CGAL_add_named_parameter(use_binary_mode_t, use_binary_mode, use_binary_mode) CGAL_add_named_parameter(metis_options_t, METIS_options, METIS_options) CGAL_add_named_parameter(vertex_partition_id_t, vertex_partition_id, vertex_partition_id_map) diff --git a/BGL/test/BGL/test_cgal_bgl_named_params.cpp b/BGL/test/BGL/test_cgal_bgl_named_params.cpp index 71cf1369565..346043ff037 100644 --- a/BGL/test/BGL/test_cgal_bgl_named_params.cpp +++ b/BGL/test/BGL/test_cgal_bgl_named_params.cpp @@ -102,6 +102,7 @@ void test(const NamedParameters& np) assert(get_param(np, CGAL::internal_np::weight_calculator).v == 39); assert(get_param(np, CGAL::internal_np::preserve_genus).v == 40); assert(get_param(np, CGAL::internal_np::verbosity_level).v == 41); + assert(get_param(np, CGAL::internal_np::use_binary_mode).v == 51); assert(get_param(np, CGAL::internal_np::projection_functor).v == 42); assert(get_param(np, CGAL::internal_np::apply_per_connected_component).v == 46); assert(get_param(np, CGAL::internal_np::output_iterator).v == 47); @@ -182,6 +183,7 @@ void test(const NamedParameters& np) check_same_type<39>(get_param(np, CGAL::internal_np::weight_calculator)); check_same_type<40>(get_param(np, CGAL::internal_np::preserve_genus)); check_same_type<41>(get_param(np, CGAL::internal_np::verbosity_level)); + check_same_type<51>(get_param(np, CGAL::internal_np::use_binary_mode)); check_same_type<42>(get_param(np, CGAL::internal_np::projection_functor)); check_same_type<46>(get_param(np, CGAL::internal_np::apply_per_connected_component)); check_same_type<47>(get_param(np, CGAL::internal_np::output_iterator)); @@ -241,6 +243,7 @@ int main() .weight_calculator(A<39>(39)) .preserve_genus(A<40>(40)) .verbosity_level(A<41>(41)) + .use_binary_mode(A<51>(51)) .projection_functor(A<42>(42)) .throw_on_self_intersection(A<43>(43)) .clip_volume(A<44>(44)) diff --git a/CGAL_Core/include/CGAL/CORE/CoreDefs.h b/CGAL_Core/include/CGAL/CORE/CoreDefs.h index 1d136ab43d1..c9851e6c09c 100644 --- a/CGAL_Core/include/CGAL/CORE/CoreDefs.h +++ b/CGAL_Core/include/CGAL/CORE/CoreDefs.h @@ -322,7 +322,6 @@ inline bool setRationalReduceFlag(bool f) { inline void CORE_init(long d) { get_static_defAbsPrec() = CORE_posInfty; get_static_defOutputDigits() = d; - std::setprecision(get_static_defOutputDigits()); } /// change to scientific output format diff --git a/CMakeLists.txt b/CMakeLists.txt index 4c884132d3e..216f1c2829f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -37,11 +37,13 @@ message( "== CMake setup (DONE) ==\n" ) # Enable testing with BUILD_TESTING option(BUILD_TESTING "Build the testing tree." OFF) -include(CTest) if(BUILD_TESTING AND NOT POLICY CMP0064) message(FATAL_ERROR "CGAL support of CTest requires CMake version 3.4 or later. The variable BUILD_TESTING must be set of OFF.") endif() +if(BUILD_TESTING) + enable_testing() +endif() # and finally start actual build add_subdirectory( Installation ) diff --git a/Classification/doc/Classification/Classification.txt b/Classification/doc/Classification/Classification.txt index a0cd4c9650f..2138985acd5 100644 --- a/Classification/doc/Classification/Classification.txt +++ b/Classification/doc/Classification/Classification.txt @@ -87,7 +87,10 @@ The following code snippet shows how to instantiate such data structures from an - [Distance_to_plane](@ref CGAL::Classification::Feature::Distance_to_plane) measures how far away a point is from a locally estimated plane; - [Eigenvalue](@ref CGAL::Classification::Feature::Eigenvalue) measures one of the three local eigenvalues; - [Elevation](@ref CGAL::Classification::Feature::Elevation) computes the local distance to an estimation of the ground; +- [Height_above](@ref CGAL::Classification::Feature::Elevation) computes the distance between the local highest point and the point; +- [Height_below](@ref CGAL::Classification::Feature::Elevation) computes the distance between the point and the local lowest point; - [Vertical_dispersion](@ref CGAL::Classification::Feature::Vertical_dispersion) computes how noisy the point set is on a local Z-cylinder; +- [Vertical_range](@ref CGAL::Classification::Feature::Elevation) computes the distance between the local highest and lowest points; - [Verticality](@ref CGAL::Classification::Feature::Verticality) compares the local normal vector to the vertical vector. These features are designed for point sets but can easily be used with surface meshes as well (see \ref Classification_meshes). For more details about how these different features can help to identify one label or the other, please refer to their associated reference manual pages. @@ -108,6 +111,8 @@ Multiple scales that are sequentially larger can be used to increase the quality Note that using this class in order to generate features is not mandatory, as features and data structures can all be handled by hand. It is mainly provided to make the specific case of point sets simpler to handle. Users can still add their own features within their feature set. +Some data structure instantiated by the generator will be used by feature: for this reason, the generator should be instantiated _within the same scope_ as the feature set and should not be deleted before the feature set. + The following snippet shows how to use the point set feature generator: \snippet Classification/example_generation_and_training.cpp Generator @@ -196,13 +201,17 @@ Example of cluster classification mesh (left: input, middle: clusters computed f %Classification relies on a classifier: this classifier is an object that, from the set of values taken by the features at an input item, computes the probability that an input item belongs to one label or another. A model of the concept `CGAL::Classification::Classifier` must take the index of an input item and store the probability associated to each label in a vector. If a classifier returns the value 1 for a pair of label and input item, it means that this item belongs to this label with certainty; values close to 0 mean that this item is not likely to belong to this label. -\cgal provides three models for this concept, [ETHZ_random_forest_classifier](@ref CGAL::Classification::ETHZ_random_forest_classifier), [OpenCV_random_forest_classifier](@ref CGAL::Classification::OpenCV_random_forest_classifier) and [Sum_of_weighted_features_classifier](@ref CGAL::Classification::Sum_of_weighted_features_classifier). +\cgal provides four models for this concept, [ETHZ::Random_forest_classifier](@ref CGAL::Classification::ETHZ::Random_forest_classifier), [OpenCV::Random_forest_classifier](@ref CGAL::Classification::OpenCV::Random_forest_classifier), [TensorFlow::Neural_network_classifier](@ref CGAL::Classification::TensorFlow::Neural_network_classifier) and [Sum_of_weighted_features_classifier](@ref CGAL::Classification::Sum_of_weighted_features_classifier). -To perform classification based on these classifiers, please refer to \ref Classification_classification_functions. +\note Currently, [ETHZ::Random_forest_classifier](@ref CGAL::Classification::ETHZ::Random_forest_classifier) +is the best classifier available in \cgal and we strongly advise users +to use it. + +To perform classification based on four classifiers, please refer to \ref Classification_classification_functions. \subsection Classification_ETHZ_random_forest ETHZ Random Forest -\cgal provides [ETHZ_random_forest_classifier](@ref CGAL::Classification::ETHZ_random_forest_classifier), +\cgal provides [ETHZ::Random_forest_classifier](@ref CGAL::Classification::ETHZ::Random_forest_classifier), a classifier based on the Random Forest Template Library developed by Stefan Walk at ETH Zurich \cgalCite{cgal:w-erftl-14} (the library is distributed under the MIT license and is included with the \cgal release, @@ -210,9 +219,6 @@ the user does not have to install anything more). This classifier uses a ground truth training set to construct several decision trees that are then used to assign a label to each input item. -__This classifier is currently the best available in \cgal and we -strongly advise users to use it.__ - This classifier cannot be set up by hand and requires a ground truth training set. The training algorithm is fast but usually requires a high number of inliers. The training algorithm uses more memory at @@ -227,14 +233,13 @@ to README provided in the [ETH Zurich's code archive](https://www.ethz.ch/conten \subsection Classification_OpenCV_random_forest OpenCV Random Forest -The second classifier is [OpenCV_random_forest_classifier](@ref CGAL::Classification::OpenCV_random_forest_classifier). +The second classifier is [OpenCV::Random_forest_classifier](@ref CGAL::Classification::OpenCV::Random_forest_classifier). It uses the \ref thirdpartyOpenCV library, more specifically the [Random Trees](http://docs.opencv.org/2.4/modules/ml/doc/random_trees.html) package. Note that this classifier usually produces results with a lower -quality than [ETHZ_random_forest_classifier](@ref CGAL::Classification::ETHZ_random_forest_classifier). - +quality than [ETHZ::Random_forest_classifier](@ref CGAL::Classification::ETHZ::Random_forest_classifier). It is provided for the sake of completeness and for testing purposes, but if you are not sure what to use, we advise using the ETHZ Random Forest instead. @@ -244,6 +249,31 @@ use this classifier. For more details about the algorithm, please refer to [the official documentation](http://docs.opencv.org/2.4/modules/ml/doc/random_trees.html) of OpenCV. +\subsection Classification_TensorFlow_neural_network TensorFlow Neural Network + +\cgal provides [TensorFlow::Neural_network_classifier](@ref CGAL::Classification::TensorFlow::Neural_network_classifier). + +It uses the C++ API of the \ref thirdpartyTensorFlow library. + +\warning This feature is still experimental: it may not be stable +and is likely to undergo substantial changes in future releases of +\cgal. The API changes will be announced in the release notes. + +The provided interface is a feature-based neural network: a set of +features is used as an input layer followed by a user-specified number +of hidden layers with a user-specified activation function. The output +layer is a softmax layer providing, for each label, the probability +that an input item belongs to it. + +This classifier cannot be set up by hand and requires a ground truth +training set. The training algorithm usually requires a higher number +of inliers than random forest. The quality of the results, so far, is +comparable to random forest. + +An [example](\ref Classification_example_tensorflow_neural_network) shows how to +use this classifier. For more details about the algorithm, please refer +to [the TensorFlow tutorials](https://www.tensorflow.org/tutorials/). + \subsection Classification_sowf Sum of Weighted Features This latest classifier defines the following attributes: @@ -334,7 +364,7 @@ Top-Left: input point set. Top-Right: raw output classification represented by a Mathematical details are provided hereafter. -\subsection Classification_classify Raw classification +\subsection Classification_classify Raw Classification - `CGAL::Classification::classify()`: this is the fastest method that provides acceptable but usually noisy results (see Figure @@ -478,23 +508,31 @@ The following example: \subsection Classification_example_ethz_random_forest ETHZ Random Forest -The following example shows how to use the classifier [ETHZ_random_forest_classifier](@ref CGAL::Classification::ETHZ_random_forest_classifier) using an input training set. +The following example shows how to use the classifier [ETHZ::Random_forest_classifier](@ref CGAL::Classification::ETHZ::Random_forest_classifier) using an input training set. \cgalExample{Classification/example_ethz_random_forest.cpp} \subsection Classification_example_opencv_random_forest OpenCV Random Forest -The following example shows how to use the classifier [OpenCV_random_forest_classifier](@ref CGAL::Classification::OpenCV_random_forest_classifier) using an input training set. +The following example shows how to use the classifier [OpenCV::Random_forest_classifier](@ref CGAL::Classification::OpenCV::Random_forest_classifier) using an input training set. \cgalExample{Classification/example_opencv_random_forest.cpp} +\subsection Classification_example_tensorflow_neural_network TensorFlow Neural Network + +The following example shows how to use the classifier +[TensorFlow::Neural_network_classifier](@ref CGAL::Classification::TensorFlow::Neural_network_classifier) +using an input training set. + +\cgalExample{Classification/example_tensorflow_neural_network.cpp} + \subsection Classification_example_mesh Mesh Classification The following example: - reads a mesh in OFF format; - automatically generates features on 5 scales; -- loads a configuration file for classifier [ETHZ_random_forest_classifier](@ref CGAL::Classification::ETHZ_random_forest_classifier); +- loads a configuration file for classifier [ETHZ::Random_forest_classifier](@ref CGAL::Classification::ETHZ::Random_forest_classifier); - runs the algorithm using the graphcut regularization. \cgalExample{Classification/example_mesh_classification.cpp} @@ -509,7 +547,7 @@ The following example: - detects plane using the algorithm `CGAL::Shape_detection_3::Region_growing`; - creates [Cluster](@ref CGAL::Classification::Cluster) objects from these detected planes; - computes cluster features from the pointwise features; -- loads a configuration file for classifier [ETHZ_random_forest_classifier](@ref CGAL::Classification::ETHZ_random_forest_classifier); +- loads a configuration file for classifier [ETHZ::Random_forest_classifier](@ref CGAL::Classification::ETHZ::Random_forest_classifier); - runs the algorithm using the raw algorithm. \cgalExample{Classification/example_cluster_classification.cpp} @@ -517,7 +555,7 @@ The following example: \section Classification_history History -This package is based on a research code by [Florent Lafarge](https://www-sop.inria.fr/members/Florent.Lafarge/) that was generalized, extended and packaged by [Simon Giraudot](http://geometryfactory.com/who-we-are/) in \cgal 4.12. %Classification of surface meshes and of clusters were introduced in \cgal 4.13. +This package is based on a research code by [Florent Lafarge](https://www-sop.inria.fr/members/Florent.Lafarge/) that was generalized, extended and packaged by [Simon Giraudot](http://geometryfactory.com/who-we-are/) in \cgal 4.12. %Classification of surface meshes and of clusters were introduced in \cgal 4.13. The Neural Network classifier was introduced in \cgal 4.14. diff --git a/Classification/doc/Classification/Concepts/Classifier.h b/Classification/doc/Classification/Concepts/Classifier.h index 1702fba0cb9..5f0059a7519 100644 --- a/Classification/doc/Classification/Concepts/Classifier.h +++ b/Classification/doc/Classification/Concepts/Classifier.h @@ -13,8 +13,9 @@ Concept describing a classifier used by classification functions (see `CGAL::Classification::classify_with_graphcut()`). \cgalHasModel `CGAL::Classification::Sum_of_weighted_features_classifier` -\cgalHasModel `CGAL::Classification::ETHZ_random_forest_classifier` -\cgalHasModel `CGAL::Classification::OpenCV_random_forest_classifier` +\cgalHasModel `CGAL::Classification::ETHZ::Random_forest_classifier` +\cgalHasModel `CGAL::Classification::OpenCV::Random_forest_classifier` +\cgalHasModel `CGAL::Classification::TensorFlow::Neural_network_classifier` */ class Classifier diff --git a/Classification/doc/Classification/PackageDescription.txt b/Classification/doc/Classification/PackageDescription.txt index 6452aa25b39..ab3ce14e173 100644 --- a/Classification/doc/Classification/PackageDescription.txt +++ b/Classification/doc/Classification/PackageDescription.txt @@ -14,6 +14,21 @@ Functions that perform classification based on a set of labels and a classifier, Classifiers are functors that, given a label set and an input item, associate this input item with an energy for each label. This energy measures the likelihood of the item to belong to this label. +\defgroup PkgClassificationClassifiersETHZ ETHZ +\ingroup PkgClassificationClassifiers + +Classifiers that use the ETHZ library. + +\defgroup PkgClassificationClassifiersOpenCV OpenCV +\ingroup PkgClassificationClassifiers + +Classifiers that use the \ref thirdpartyOpenCV library. + +\defgroup PkgClassificationClassifiersTensorFlow TensorFlow +\ingroup PkgClassificationClassifiers + +Classifiers that use the \ref thirdpartyTensorFlow library. + \defgroup PkgClassificationDataStructures Common Data Structures \ingroup PkgClassificationRef @@ -86,9 +101,10 @@ Data structures specialized to classify clusters. ## Classifiers ## +- `CGAL::Classification::ETHZ::Random_forest_classifier` +- `CGAL::Classification::OpenCV::Random_forest_classifier` +- `CGAL::Classification::TensorFlow::Neural_network_classifier` - `CGAL::Classification::Sum_of_weighted_features_classifier` -- `CGAL::Classification::ETHZ_random_forest_classifier` -- `CGAL::Classification::OpenCV_random_forest_classifier` ## Common Data Structures ## @@ -115,8 +131,11 @@ Data structures specialized to classify clusters. - `CGAL::Classification::Feature::Echo_scatter` - `CGAL::Classification::Feature::Eigenvalue` - `CGAL::Classification::Feature::Elevation` +- `CGAL::Classification::Feature::Height_above` +- `CGAL::Classification::Feature::Height_below` - `CGAL::Classification::Feature::Simple_feature` - `CGAL::Classification::Feature::Vertical_dispersion` +- `CGAL::Classification::Feature::Vertical_range` - `CGAL::Classification::Feature::Verticality` ## Point Set Classification ## diff --git a/Classification/doc/Classification/examples.txt b/Classification/doc/Classification/examples.txt index f3598bb82a9..90fde632cce 100644 --- a/Classification/doc/Classification/examples.txt +++ b/Classification/doc/Classification/examples.txt @@ -4,6 +4,7 @@ \example Classification/example_generation_and_training.cpp \example Classification/example_ethz_random_forest.cpp \example Classification/example_opencv_random_forest.cpp +\example Classification/example_tensorflow_neural_network.cpp \example Classification/example_mesh_classification.cpp \example Classification/example_cluster_classification.cpp */ diff --git a/Classification/examples/Classification/CMakeLists.txt b/Classification/examples/Classification/CMakeLists.txt index 392d1708e5c..4ec061b3991 100644 --- a/Classification/examples/Classification/CMakeLists.txt +++ b/Classification/examples/Classification/CMakeLists.txt @@ -94,7 +94,6 @@ if( WIN32 ) endif() endif() -find_package(OpenCV QUIET) if (OpenCV_FOUND) message(STATUS "Found OpenCV ${OpenCV_VERSION}") include_directories(${OpenCV_INCLUDE_DIRS}) @@ -108,6 +107,21 @@ else() message(STATUS "NOTICE: OpenCV was not found. OpenCV random forest predicate for classification won't be available.") endif() +find_package(TensorFlow QUIET) +if (TensorFlow_FOUND) + message(STATUS "Found TensorFlow") + include_directories( ${TensorFlow_INCLUDE_DIR} ) + set(classification_linked_libraries ${classification_linked_libraries} + ${TensorFlow_LIBRARY}) + set(classification_compile_definitions ${classification_compile_definitions} + "-DCGAL_LINKED_WITH_TENSORFLOW") + + set(targets ${targets} example_tensorflow_neural_network) +else() + message(STATUS "NOTICE: TensorFlow not found, Neural Network predicate for classification won't be available.") +endif() + + # Creating targets with correct libraries and flags foreach(target ${targets}) create_single_source_cgal_program( "${target}.cpp" CXX_FEATURES ${needed_cxx_features} ) diff --git a/Classification/examples/Classification/example_classification.cpp b/Classification/examples/Classification/example_classification.cpp index 4ed9caccabd..665fb17f064 100644 --- a/Classification/examples/Classification/example_classification.cpp +++ b/Classification/examples/Classification/example_classification.cpp @@ -146,7 +146,7 @@ int main (int argc, char** argv) /////////////////////////////////////////////////////////////////// //! [Classify] - std::vector label_indices; + std::vector label_indices (pts.size(), -1); CGAL::Real_timer t; t.start(); @@ -200,7 +200,7 @@ int main (int argc, char** argv) { f << pts[i] << " "; - Label_handle label = labels[label_indices[i]]; + Label_handle label = labels[std::size_t(label_indices[i])]; if (label == ground) f << "245 180 0" << std::endl; else if (label == vegetation) diff --git a/Classification/examples/Classification/example_cluster_classification.cpp b/Classification/examples/Classification/example_cluster_classification.cpp index 5774336d484..3012b5c62f0 100644 --- a/Classification/examples/Classification/example_cluster_classification.cpp +++ b/Classification/examples/Classification/example_cluster_classification.cpp @@ -191,7 +191,7 @@ int main (int argc, char** argv) std::vector label_indices(clusters.size(), -1); std::cerr << "Using ETHZ Random Forest Classifier" << std::endl; - Classification::ETHZ_random_forest_classifier classifier (labels, features); + Classification::ETHZ::Random_forest_classifier classifier (labels, features); std::cerr << "Loading configuration" << std::endl; std::ifstream in_config (filename_config, std::ios_base::in | std::ios_base::binary); diff --git a/Classification/examples/Classification/example_ethz_random_forest.cpp b/Classification/examples/Classification/example_ethz_random_forest.cpp index 202c1b5d9fb..f4cca8960b8 100644 --- a/Classification/examples/Classification/example_ethz_random_forest.cpp +++ b/Classification/examples/Classification/example_ethz_random_forest.cpp @@ -91,7 +91,7 @@ int main (int argc, char** argv) std::vector label_indices(pts.size(), -1); std::cerr << "Using ETHZ Random Forest Classifier" << std::endl; - Classification::ETHZ_random_forest_classifier classifier (labels, features); + Classification::ETHZ::Random_forest_classifier classifier (labels, features); std::cerr << "Training" << std::endl; t.reset(); diff --git a/Classification/examples/Classification/example_feature.cpp b/Classification/examples/Classification/example_feature.cpp index d1ce94e8fee..4cce763be1a 100644 --- a/Classification/examples/Classification/example_feature.cpp +++ b/Classification/examples/Classification/example_feature.cpp @@ -114,7 +114,7 @@ int main (int argc, char** argv) classifier.set_effect (b, my_feature, Classifier::PENALIZING); std::cerr << "Classifying" << std::endl; - std::vector label_indices(pts.size(), -1); + std::vector label_indices(pts.size(), -1); Classification::classify_with_graphcut (pts, Pmap(), labels, classifier, neighborhood.k_neighbor_query(12), diff --git a/Classification/examples/Classification/example_mesh_classification.cpp b/Classification/examples/Classification/example_mesh_classification.cpp index da76248ed7d..f6ac64f60c2 100644 --- a/Classification/examples/Classification/example_mesh_classification.cpp +++ b/Classification/examples/Classification/example_mesh_classification.cpp @@ -85,7 +85,7 @@ int main (int argc, char** argv) std::vector label_indices(mesh.number_of_faces(), -1); std::cerr << "Using ETHZ Random Forest Classifier" << std::endl; - Classification::ETHZ_random_forest_classifier classifier (labels, features); + Classification::ETHZ::Random_forest_classifier classifier (labels, features); std::cerr << "Loading configuration" << std::endl; std::ifstream in_config (filename_config, std::ios_base::in | std::ios_base::binary); diff --git a/Classification/examples/Classification/example_opencv_random_forest.cpp b/Classification/examples/Classification/example_opencv_random_forest.cpp index 4b97032d65d..4ada5c5182a 100644 --- a/Classification/examples/Classification/example_opencv_random_forest.cpp +++ b/Classification/examples/Classification/example_opencv_random_forest.cpp @@ -90,7 +90,7 @@ int main (int argc, char** argv) std::vector label_indices(pts.size(), -1); std::cerr << "Using OpenCV Random Forest Classifier" << std::endl; - Classification::OpenCV_random_forest_classifier classifier (labels, features); + Classification::OpenCV::Random_forest_classifier classifier (labels, features); std::cerr << "Training" << std::endl; t.reset(); diff --git a/Classification/examples/Classification/example_tensorflow_neural_network.cpp b/Classification/examples/Classification/example_tensorflow_neural_network.cpp new file mode 100644 index 00000000000..d86650de182 --- /dev/null +++ b/Classification/examples/Classification/example_tensorflow_neural_network.cpp @@ -0,0 +1,164 @@ +#if defined (_MSC_VER) && !defined (_WIN64) +#pragma warning(disable:4244) // boost::number_distance::distance() + // converts 64 to 32 bits integers +#endif + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +typedef CGAL::Simple_cartesian Kernel; +typedef Kernel::Point_3 Point; +typedef CGAL::Point_set_3 Point_set; +typedef Kernel::Iso_cuboid_3 Iso_cuboid_3; + +typedef Point_set::Point_map Pmap; +typedef Point_set::Property_map Imap; +typedef Point_set::Property_map UCmap; + +namespace Classification = CGAL::Classification; + +typedef Classification::Label_handle Label_handle; +typedef Classification::Feature_handle Feature_handle; +typedef Classification::Label_set Label_set; +typedef Classification::Feature_set Feature_set; + +typedef Classification::Point_set_feature_generator Feature_generator; + + +int main (int argc, char** argv) +{ + std::string filename = "data/b9_training.ply"; + + if (argc > 1) + filename = argv[1]; + + std::ifstream in (filename.c_str(), std::ios::binary); + Point_set pts; + + std::cerr << "Reading input" << std::endl; + in >> pts; + + Imap label_map; + bool lm_found = false; + boost::tie (label_map, lm_found) = pts.property_map ("label"); + if (!lm_found) + { + std::cerr << "Error: \"label\" property not found in input file." << std::endl; + return EXIT_FAILURE; + } + + std::vector ground_truth; + ground_truth.reserve (pts.size()); + std::copy (pts.range(label_map).begin(), pts.range(label_map).end(), + std::back_inserter (ground_truth)); + + Feature_set features; + + std::cerr << "Generating features" << std::endl; + CGAL::Real_timer t; + t.start(); + Feature_generator generator (pts, pts.point_map(), + 5); // using 5 scales + +#ifdef CGAL_LINKED_WITH_TBB + features.begin_parallel_additions(); +#endif + + generator.generate_point_based_features (features); + +#ifdef CGAL_LINKED_WITH_TBB + features.end_parallel_additions(); +#endif + + t.stop(); + std::cerr << "Done in " << t.time() << " second(s)" << std::endl; + + // Add types + Label_set labels; + Label_handle ground = labels.add ("ground"); + Label_handle vegetation = labels.add ("vegetation"); + Label_handle roof = labels.add ("roof"); + + std::vector label_indices(pts.size(), -1); + + std::cerr << "Using TensorFlow neural network Classifier" << std::endl; + Classification::TensorFlow::Neural_network_classifier<> classifier (labels, features); + + std::cerr << "Training" << std::endl; + t.reset(); + t.start(); + classifier.train (ground_truth, + true, // restart from scratch + 100); // 100 iterations + t.stop(); + std::cerr << "Done in " << t.time() << " second(s)" << std::endl; + + t.reset(); + t.start(); + Classification::classify_with_graphcut + (pts, pts.point_map(), labels, classifier, + generator.neighborhood().k_neighbor_query(12), + 0.2f, 1, label_indices); + t.stop(); + + std::cerr << "Classification with graphcut done in " << t.time() << " second(s)" << std::endl; + + std::cerr << "Precision, recall, F1 scores and IoU:" << std::endl; + Classification::Evaluation evaluation (labels, ground_truth, label_indices); + + for (std::size_t i = 0; i < labels.size(); ++ i) + { + std::cerr << " * " << labels[i]->name() << ": " + << evaluation.precision(labels[i]) << " ; " + << evaluation.recall(labels[i]) << " ; " + << evaluation.f1_score(labels[i]) << " ; " + << evaluation.intersection_over_union(labels[i]) << std::endl; + } + + std::cerr << "Accuracy = " << evaluation.accuracy() << std::endl + << "Mean F1 score = " << evaluation.mean_f1_score() << std::endl + << "Mean IoU = " << evaluation.mean_intersection_over_union() << std::endl; + + // Color point set according to class + UCmap red = pts.add_property_map("red", 0).first; + UCmap green = pts.add_property_map("green", 0).first; + UCmap blue = pts.add_property_map("blue", 0).first; + + for (std::size_t i = 0; i < label_indices.size(); ++ i) + { + label_map[i] = label_indices[i]; // update label map with computed classification + + Label_handle label = labels[label_indices[i]]; + + if (label == ground) + { + red[i] = 245; green[i] = 180; blue[i] = 0; + } + else if (label == vegetation) + { + red[i] = 0; green[i] = 255; blue[i] = 27; + } + else if (label == roof) + { + red[i] = 255; green[i] = 0; blue[i] = 170; + } + } + + // Write result + std::ofstream f ("classification.ply"); + f.precision(18); + f << pts; + + std::cerr << "All done" << std::endl; + + return EXIT_SUCCESS; +} diff --git a/Classification/include/CGAL/Classification.h b/Classification/include/CGAL/Classification.h index 654aa185cd3..6be192f22b8 100644 --- a/Classification/include/CGAL/Classification.h +++ b/Classification/include/CGAL/Classification.h @@ -25,10 +25,14 @@ #include #include -#include +#include #ifdef CGAL_LINKED_WITH_OPENCV -#include +#include +#endif + +#ifdef CGAL_LINKED_WITH_TENSORFLOW +#include #endif #include diff --git a/Classification/include/CGAL/Classification/ETHZ_random_forest_classifier.h b/Classification/include/CGAL/Classification/ETHZ/Random_forest_classifier.h similarity index 64% rename from Classification/include/CGAL/Classification/ETHZ_random_forest_classifier.h rename to Classification/include/CGAL/Classification/ETHZ/Random_forest_classifier.h index 1587baf4b9b..e0910e57275 100644 --- a/Classification/include/CGAL/Classification/ETHZ_random_forest_classifier.h +++ b/Classification/include/CGAL/Classification/ETHZ/Random_forest_classifier.h @@ -25,6 +25,7 @@ #include #include +#include #ifdef CGAL_CLASSIFICATION_VERBOSE #define VERBOSE_TREE_PROGRESS 1 @@ -41,8 +42,10 @@ # pragma warning(disable:4996) #endif -#include -#include +#include +#include + +#include #include #include @@ -58,16 +61,18 @@ namespace CGAL { namespace Classification { -/*! - \ingroup PkgClassificationClassifiers +namespace ETHZ { - \brief %Classifier based on the ETH Zurich version of random forest algorithm \cgalCite{cgal:w-erftl-14}. +/*! + \ingroup PkgClassificationClassifiersETHZ + + \brief %Classifier based on the ETH Zurich version of the random forest algorithm \cgalCite{cgal:w-erftl-14}. \note This classifier is distributed under the MIT license. \cgalModels `CGAL::Classification::Classifier` */ -class ETHZ_random_forest_classifier +class Random_forest_classifier { typedef CGAL::internal::liblearning::RandomForest::RandomForest < CGAL::internal::liblearning::RandomForest::NodeGini @@ -83,16 +88,36 @@ public: /// @{ /*! - \brief Instantiate the classifier using the sets of `labels` and `features`. + \brief Instantiates the classifier using the sets of `labels` and `features`. */ - ETHZ_random_forest_classifier (const Label_set& labels, - const Feature_set& features) + Random_forest_classifier (const Label_set& labels, + const Feature_set& features) : m_labels (labels), m_features (features), m_rfc (NULL) { } + /*! + \brief Copies the `other` classifier's configuration using another + set of `features`. + + This constructor can be used to apply a trained random forest to + another data set. + + \warning The feature set should be composed of the same features + than the ones used by `other`, and in the same order. + + */ + Random_forest_classifier (const Random_forest_classifier& other, + const Feature_set& features) + : m_labels (other.m_labels), m_features (features), m_rfc (NULL) + { + std::stringstream stream; + other.save_configuration(stream); + this->load_configuration(stream); + } + /// \cond SKIP_IN_MANUAL - ~ETHZ_random_forest_classifier () + ~Random_forest_classifier () { if (m_rfc != NULL) delete m_rfc; @@ -102,8 +127,23 @@ public: /// @} /// \name Training - /// @{ + + /// \cond SKIP_IN_MANUAL + template + void train (const LabelIndexRange& ground_truth, + bool reset_trees = true, + std::size_t num_trees = 25, + std::size_t max_depth = 20) + { +#ifdef CGAL_LINKED_WITH_TBB + train(ground_truth, reset_trees, num_trees, max_depth); +#else + train(ground_truth, reset_trees, num_trees, max_depth); +#endif + } + /// \endcond + /*! \brief Runs the training algorithm. @@ -114,6 +154,11 @@ public: \pre At least one ground truth item should be assigned to each label. + \tparam ConcurrencyTag enables sequential versus parallel + algorithm. Possible values are `Parallel_tag` (default value is + %CGAL is linked with TBB) or `Sequential_tag` (default value + otherwise). + \param ground_truth vector of label indices. It should contain for each input item, in the same order as the input set, the index of the corresponding label in the `Label_set` provided in the @@ -135,7 +180,7 @@ public: will underfit the test data and conversely an overly high value will likely overfit. */ - template + template void train (const LabelIndexRange& ground_truth, bool reset_trees = true, std::size_t num_trees = 25, @@ -159,7 +204,7 @@ public: } } - std::cerr << "Using " << gt.size() << " inliers" << std::endl; + CGAL_CLASSIFICATION_CERR << "Using " << gt.size() << " inliers" << std::endl; CGAL::internal::liblearning::DataView2D label_vector (&(gt[0]), gt.size(), 1); CGAL::internal::liblearning::DataView2D feature_vector(&(ft[0]), gt.size(), ft.size() / gt.size()); @@ -175,7 +220,8 @@ public: CGAL::internal::liblearning::RandomForest::AxisAlignedRandomSplitGenerator generator; - m_rfc->train(feature_vector, label_vector, CGAL::internal::liblearning::DataView2D(), generator, 0, false, reset_trees); + m_rfc->train + (feature_vector, label_vector, CGAL::internal::liblearning::DataView2D(), generator, 0, reset_trees, m_labels.size()); } /// \cond SKIP_IN_MANUAL @@ -195,10 +241,46 @@ public: for (std::size_t i = 0; i < out.size(); ++ i) out[i] = (std::min) (1.f, (std::max) (0.f, prob[i])); } + /// \endcond /// @} + /// \name Miscellaneous + /// @{ + + /*! + \brief Computes, for each feature, how many nodes in the forest + uses it as a split criterion. + + Each tree of the random forest recursively splits the training + data set using at each node one of the input features. This method + counts, for each feature, how many times it was selected by the + training algorithm as a split criterion. + + This method allows to evaluate how useful a feature was with + respect to a training set: if a feature is used a lot, that means + that it has a strong discriminative power with respect to how the + labels are represented by the feature set; on the contrary, if a + feature is not used very often, its discriminative power is + probably low; if a feature is _never_ used, it likely has no + interest at all and is completely uncorrelated to the label + segmentation of the training set. + + \param count vector where the result is stored. After running the + method, it contains, for each feature, the number of nodes in the + forest that use it as a split criterion, in the same order as the + feature set order. + */ + void get_feature_usage (std::vector& count) const + { + count.clear(); + count.resize(m_features.size(), 0); + return m_rfc->get_feature_usage(count); + } + + /// @} + /// \name Input/Output /// @{ @@ -211,7 +293,7 @@ public: The output file is written in an GZIP container that is readable by the `load_configuration()` method. */ - void save_configuration (std::ostream& output) + void save_configuration (std::ostream& output) const { boost::iostreams::filtering_ostream outs; outs.push(boost::iostreams::gzip_compressor()); @@ -247,6 +329,13 @@ public: } +/// \cond SKIP_IN_MANUAL +// Backward compatibility +typedef ETHZ::Random_forest_classifier ETHZ_random_forest_classifier; +/// \endcond + +} + } #endif // CGAL_CLASSIFICATION_ETHZ_RANDOM_FOREST_CLASSIFIER_H diff --git a/Classification/include/CGAL/Classification/internal/auxiliary/dataview.h b/Classification/include/CGAL/Classification/ETHZ/internal/dataview.h similarity index 100% rename from Classification/include/CGAL/Classification/internal/auxiliary/dataview.h rename to Classification/include/CGAL/Classification/ETHZ/internal/dataview.h diff --git a/Classification/include/CGAL/Classification/internal/auxiliary/random-forest/common-libraries.hpp b/Classification/include/CGAL/Classification/ETHZ/internal/random-forest/common-libraries.hpp similarity index 88% rename from Classification/include/CGAL/Classification/internal/auxiliary/random-forest/common-libraries.hpp rename to Classification/include/CGAL/Classification/ETHZ/internal/random-forest/common-libraries.hpp index 3d9b9a60553..ec70abfdada 100644 --- a/Classification/include/CGAL/Classification/internal/auxiliary/random-forest/common-libraries.hpp +++ b/Classification/include/CGAL/Classification/ETHZ/internal/random-forest/common-libraries.hpp @@ -27,6 +27,16 @@ // Modifications from original library: // * changed inclusion protection tag // * moved to namespace CGAL::internal:: +// * init_feature_class_data() does not resize anymore (it's done +// later directly in the splitter). WARNING: all splitters other +// than the default won't be working correctly (but experimentally +// they are less good and we don't use them - we keep them just in +// case) +// * sample reduction is now 36.8% (to account for the correction of +// the randomization of the input which used to implicitly ignore +// this proportion of items) +// * map_points() in axis aligned splitter now only uses a subset of +// the points for evaluation (for timing optimization= #ifndef CGAL_INTERNAL_LIBLEARNING_RANDOMFOREST_COMMON_LIBRARIES_H #define CGAL_INTERNAL_LIBLEARNING_RANDOMFOREST_COMMON_LIBRARIES_H @@ -62,9 +72,9 @@ namespace liblearning { namespace RandomForest { typedef std::vector< std::pair > FeatureClassDataFloat; -inline void init_feature_class_data(FeatureClassDataFloat& data, int /*n_classes*/, int n_samples) +inline void init_feature_class_data(FeatureClassDataFloat& /*data*/, int /*n_classes*/, int /* n_samples */) { - data.resize(n_samples); +// data.resize(n_samples); } typedef boost::unordered_set FeatureSet; @@ -97,7 +107,7 @@ struct ForestParams { max_depth(42), n_trees(100), min_samples_per_node(5), - sample_reduction(0) + sample_reduction(0.368f) {} template void serialize(Archive& ar, unsigned /*version*/) @@ -222,15 +232,21 @@ struct AxisAlignedSplitter { int n_samples, FeatureClassData& data_points) const { - for (int i_sample = 0; i_sample < n_samples; ++i_sample) { - // determine index of this sample ... - int sample_idx = sample_idxes[i_sample]; - // determine class ... - int sample_class = labels(sample_idx, 0); - // determine value of the selected feature for this sample - FeatureType sample_fval = samples(sample_idx, feature); - data_points[i_sample] = std::make_pair(sample_fval, sample_class); - } + std::size_t size = (std::min)(std::size_t(5000), std::size_t(n_samples)); + data_points.clear(); + data_points.reserve(size); + + std::size_t step = n_samples / size; + + for (int i_sample = 0; i_sample < n_samples; i_sample += step) { + // determine index of this sample ... + int sample_idx = sample_idxes[i_sample]; + // determine class ... + int sample_class = labels(sample_idx, 0); + // determine value of the selected feature for this sample + FeatureType sample_fval = samples(sample_idx, feature); + data_points.push_back(std::make_pair(sample_fval, sample_class)); + } } template void serialize(Archive& ar, unsigned /*version*/) diff --git a/Classification/include/CGAL/Classification/internal/auxiliary/random-forest/forest.hpp b/Classification/include/CGAL/Classification/ETHZ/internal/random-forest/forest.hpp similarity index 58% rename from Classification/include/CGAL/Classification/internal/auxiliary/random-forest/forest.hpp rename to Classification/include/CGAL/Classification/ETHZ/internal/random-forest/forest.hpp index 4d22c2bb36b..02d326f8c76 100644 --- a/Classification/include/CGAL/Classification/internal/auxiliary/random-forest/forest.hpp +++ b/Classification/include/CGAL/Classification/ETHZ/internal/random-forest/forest.hpp @@ -29,6 +29,12 @@ // * moved to namespace CGAL::internal:: // * add parameter "reset_trees" to train() to be able to construct // forest with several iterations +// * training algorithm has been parallelized with Intel TBB +// * remove the unused feature "register_obb" +// * add option to not count labels (if it's know before) +// * fix the randomization of input (which was implicitly losing +// samples) +// * add method to get feature usage #ifndef CGAL_INTERNAL_LIBLEARNING_RANDOMFOREST_FOREST_H #define CGAL_INTERNAL_LIBLEARNING_RANDOMFOREST_FOREST_H @@ -39,11 +45,80 @@ #include #endif +#include + +#ifdef CGAL_LINKED_WITH_TBB +#include +#include +#include +#include +#endif // CGAL_LINKED_WITH_TBB + + namespace CGAL { namespace internal { + + namespace liblearning { namespace RandomForest { +template +class Tree_training_functor +{ + typedef typename NodeT::ParamType ParamType; + typedef typename NodeT::FeatureType FeatureType; + typedef Tree TreeType; + + std::size_t seed_start; + const std::vector& sample_idxes; + boost::ptr_vector >& trees; + DataView2D samples; + DataView2D labels; + std::size_t n_in_bag_samples; + const SplitGenerator& split_generator; + +public: + + Tree_training_functor(std::size_t seed_start, + const std::vector& sample_idxes, + boost::ptr_vector >& trees, + DataView2D samples, + DataView2D labels, + std::size_t n_in_bag_samples, + const SplitGenerator& split_generator) + : seed_start (seed_start) + , sample_idxes (sample_idxes) + , trees (trees) + , samples (samples) + , labels (labels) + , n_in_bag_samples(n_in_bag_samples) + , split_generator(split_generator) + { } + +#ifdef CGAL_LINKED_WITH_TBB + void operator()(const tbb::blocked_range& r) const + { + for (std::size_t s = r.begin(); s != r.end(); ++ s) + apply(s); + } +#endif // CGAL_LINKED_WITH_TBB + + inline void apply (std::size_t i_tree) const + { + // initialize random generator with sequential seeds (one for each + // tree) + RandomGen gen(seed_start + i_tree); + std::vector in_bag_samples = sample_idxes; + + // Bagging: draw random sample indexes used for this tree + std::random_shuffle (in_bag_samples.begin(),in_bag_samples.end()); + + // Train the tree + trees[i_tree].train(samples, labels, &in_bag_samples[0], n_in_bag_samples, split_generator, gen); + } + +}; + template class RandomForest { public: @@ -52,28 +127,29 @@ public: typedef Tree TreeType; ParamType params; - std::vector was_oob_data; - DataView2D was_oob; - boost::ptr_vector< Tree > trees; RandomForest() {} RandomForest(ParamType const& params) : params(params) {} - template + template void train(DataView2D samples, DataView2D labels, DataView2D train_sample_idxes, SplitGenerator const& split_generator, size_t seed_start = 1, - bool register_oob = true, - bool reset_trees = true + bool reset_trees = true, + std::size_t n_classes = std::size_t(-1) ) { if (reset_trees) trees.clear(); - params.n_classes = *std::max_element(&labels(0,0), &labels(0,0)+labels.num_elements()) + 1; + if (n_classes == std::size_t(-1)) + params.n_classes = *std::max_element(&labels(0,0), &labels(0,0)+labels.num_elements()) + 1; + else + params.n_classes = n_classes; + params.n_features = samples.cols; params.n_samples = samples.rows; @@ -93,42 +169,31 @@ public: size_t n_idxes = sample_idxes.size(); params.n_in_bag_samples = n_idxes * (1 - params.sample_reduction); - // Random distribution over indexes - UniformIntDist dist(0, n_idxes - 1); - - // Store for each sample and each tree if sample was used for tree - if (register_oob) { - was_oob_data.assign(n_idxes*params.n_trees, 1); - was_oob = DataView2D(&was_oob_data[0], n_idxes, params.n_trees); - } - std::size_t nb_trees = trees.size(); - for (size_t i_tree = nb_trees; i_tree < nb_trees + params.n_trees; ++i_tree) { + for (std::size_t i_tree = nb_trees; i_tree < nb_trees + params.n_trees; ++ i_tree) + trees.push_back (new TreeType(¶ms)); + + Tree_training_functor + f (seed_start, sample_idxes, trees, samples, labels, params.n_in_bag_samples, split_generator); + +#ifndef CGAL_LINKED_WITH_TBB + CGAL_static_assertion_msg (!(boost::is_convertible::value), + "Parallel_tag is enabled but TBB is unavailable."); +#else + if (boost::is_convertible::value) + { + tbb::parallel_for(tbb::blocked_range(nb_trees, nb_trees + params.n_trees), f); + } + else +#endif + { + for (size_t i_tree = nb_trees; i_tree < nb_trees + params.n_trees; ++i_tree) + { #if VERBOSE_TREE_PROGRESS std::printf("Training tree %zu/%zu, max depth %zu\n", i_tree+1, nb_trees + params.n_trees, params.max_depth); #endif - // new tree - trees.push_back(new TreeType(¶ms)); - // initialize random generator with sequential seeds (one for each - // tree) - RandomGen gen(seed_start + i_tree); - // Bagging: draw random sample indexes used for this tree - std::vector in_bag_samples(params.n_in_bag_samples); - for (size_t i_sample = 0; i_sample < in_bag_samples.size(); ++i_sample) { - int random_idx = dist(gen); - in_bag_samples[i_sample] = sample_idxes[random_idx]; - if (register_oob && was_oob(random_idx, i_tree)) { - was_oob(random_idx, i_tree) = 0; - } - } -#ifdef TREE_GRAPHVIZ_STREAM - TREE_GRAPHVIZ_STREAM << "digraph Tree {" << std::endl; -#endif - // Train the tree - trees.back().train(samples, labels, &in_bag_samples[0], in_bag_samples.size(), split_generator, gen); -#ifdef TREE_GRAPHVIZ_STREAM - TREE_GRAPHVIZ_STREAM << "}" << std::endl << std::endl; -#endif + f.apply(i_tree); + } } } int evaluate(FeatureType const* sample, float* results) { @@ -177,6 +242,12 @@ public: ar & BOOST_SERIALIZATION_NVP(params); ar & BOOST_SERIALIZATION_NVP(trees); } + + void get_feature_usage (std::vector& count) const + { + for (std::size_t i_tree = 0; i_tree < trees.size(); ++i_tree) + trees[i_tree].get_feature_usage(count); + } }; } diff --git a/Classification/include/CGAL/Classification/internal/auxiliary/random-forest/node-gini.hpp b/Classification/include/CGAL/Classification/ETHZ/internal/random-forest/node-gini.hpp similarity index 92% rename from Classification/include/CGAL/Classification/internal/auxiliary/random-forest/node-gini.hpp rename to Classification/include/CGAL/Classification/ETHZ/internal/random-forest/node-gini.hpp index 1b3c6ec89c8..2b42b35843b 100644 --- a/Classification/include/CGAL/Classification/internal/auxiliary/random-forest/node-gini.hpp +++ b/Classification/include/CGAL/Classification/ETHZ/internal/random-forest/node-gini.hpp @@ -28,6 +28,11 @@ // * changed inclusion protection tag // * moved to namespace CGAL::internal:: +// * improve sorting algorithm by only comparing the first of pair +// (second is useless) + + + #ifndef CGAL_INTERNAL_LIBLEARNING_RANDOMFOREST_NODE_GINI_H #define CGAL_INTERNAL_LIBLEARNING_RANDOMFOREST_NODE_GINI_H #include "node.hpp" @@ -79,7 +84,13 @@ public: n_r += 1; } // sort data so thresholding is easy based on position in array - std::sort(data_points.begin(), data_points.end()); + std::sort(data_points.begin(), data_points.end(), + [&](const std::pair& a, + const std::pair& b) -> bool + { + return a.first < b.first; + }); + // loop over data, update class distributions left&right for (size_t i_point = 1; i_point < data_points.size(); ++i_point) { int cls = data_points[i_point-1].second; diff --git a/Classification/include/CGAL/Classification/internal/auxiliary/random-forest/node.hpp b/Classification/include/CGAL/Classification/ETHZ/internal/random-forest/node.hpp similarity index 97% rename from Classification/include/CGAL/Classification/internal/auxiliary/random-forest/node.hpp rename to Classification/include/CGAL/Classification/ETHZ/internal/random-forest/node.hpp index 9e02ed11400..6d5ef03bafc 100644 --- a/Classification/include/CGAL/Classification/internal/auxiliary/random-forest/node.hpp +++ b/Classification/include/CGAL/Classification/ETHZ/internal/random-forest/node.hpp @@ -30,6 +30,7 @@ // * fix computation of node_dist[label] so that results are always <= 1.0 // * change serialization functions to avoid a bug with boost and some // compilers (that leads to dereferencing a null pointer) +// * add a method to get feature usage #ifndef CGAL_INTERNAL_LIBLEARNING_RANDOMFORESTS_NODE_H #define CGAL_INTERNAL_LIBLEARNING_RANDOMFORESTS_NODE_H @@ -257,6 +258,16 @@ public: ar & BOOST_SERIALIZATION_NVP(right); } } + + void get_feature_usage (std::vector& count) const + { + if (!is_leaf) + { + count[std::size_t(splitter.feature)] ++; + left->get_feature_usage(count); + right->get_feature_usage(count); + } + } }; } diff --git a/Classification/include/CGAL/Classification/internal/auxiliary/random-forest/tree.hpp b/Classification/include/CGAL/Classification/ETHZ/internal/random-forest/tree.hpp similarity index 96% rename from Classification/include/CGAL/Classification/internal/auxiliary/random-forest/tree.hpp rename to Classification/include/CGAL/Classification/ETHZ/internal/random-forest/tree.hpp index 6c426f75141..08ddb45aa5b 100644 --- a/Classification/include/CGAL/Classification/internal/auxiliary/random-forest/tree.hpp +++ b/Classification/include/CGAL/Classification/ETHZ/internal/random-forest/tree.hpp @@ -27,6 +27,7 @@ // Modifications from original library: // * changed inclusion protection tag // * moved to namespace CGAL::internal:: +// * add a method to get feature usage #ifndef CGAL_INTERNAL_LIBLEARNING_RANDOMFOREST_TREE_H #define CGAL_INTERNAL_LIBLEARNING_RANDOMFOREST_TREE_H @@ -135,6 +136,10 @@ public: ar & BOOST_SERIALIZATION_NVP(params); ar & BOOST_SERIALIZATION_NVP(root_node); } + void get_feature_usage (std::vector& count) const + { + root_node->get_feature_usage(count); + } }; } diff --git a/Classification/include/CGAL/Classification/Feature/Echo_scatter.h b/Classification/include/CGAL/Classification/Feature/Echo_scatter.h index 85e3b9942b4..dd90d7b86f8 100644 --- a/Classification/include/CGAL/Classification/Feature/Echo_scatter.h +++ b/Classification/include/CGAL/Classification/Feature/Echo_scatter.h @@ -85,6 +85,8 @@ public: : grid (grid) { this->set_name ("echo_scatter"); + if (radius_neighbors < 0.) + radius_neighbors = 3.f * grid.resolution(); if (grid.width() * grid.height() > input.size()) echo_scatter.resize(input.size(), compressed_float(0)); diff --git a/Classification/include/CGAL/Classification/Feature/Elevation.h b/Classification/include/CGAL/Classification/Feature/Elevation.h index 14750ba905f..1af70565840 100644 --- a/Classification/include/CGAL/Classification/Feature/Elevation.h +++ b/Classification/include/CGAL/Classification/Feature/Elevation.h @@ -91,7 +91,7 @@ public: { this->set_name ("elevation"); if (radius_dtm < 0.) - radius_dtm = 100.f * grid.resolution(); + radius_dtm = 10.f * grid.resolution(); //DEM Image_float dem(grid.width(),grid.height()); diff --git a/Classification/include/CGAL/Classification/Feature/Height_above.h b/Classification/include/CGAL/Classification/Feature/Height_above.h new file mode 100644 index 00000000000..0696541b610 --- /dev/null +++ b/Classification/include/CGAL/Classification/Feature/Height_above.h @@ -0,0 +1,142 @@ +// Copyright (c) 2012 INRIA Sophia-Antipolis (France). +// Copyright (c) 2017 GeometryFactory Sarl (France). +// All rights reserved. +// +// This file is part of CGAL (www.cgal.org). +// You can redistribute it and/or modify it under the terms of the GNU +// General Public License as published by the Free Software Foundation, +// either version 3 of the License, or (at your option) any later version. +// +// 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$ +// $Id$ +// SPDX-License-Identifier: GPL-3.0+ +// +// Author(s) : Florent Lafarge, Simon Giraudot + +#ifndef CGAL_CLASSIFICATION_FEATURE_HEIGHT_ABOVE_H +#define CGAL_CLASSIFICATION_FEATURE_HEIGHT_ABOVE_H + +#include + +#include + +#include +#include +#include +#include + +namespace CGAL { + +namespace Classification { + +namespace Feature { + + /*! + \ingroup PkgClassificationFeatures + + %Feature based on local height distribution This feature computes + the distance between the maximum height on the local cell of the + planimetric grid and a point's height. + + Its default name is "height_above". + + \tparam GeomTraits model of \cgal Kernel. + \tparam PointRange model of `ConstRange`. Its iterator type + is `RandomAccessIterator` and its value type is the key type of + `PointMap`. + \tparam PointMap model of `ReadablePropertyMap` whose key + type is the value type of the iterator of `PointRange` and value type + is `GeomTraits::Point_3`. + + */ +template +class Height_above : public Feature_base +{ + typedef typename GeomTraits::Iso_cuboid_3 Iso_cuboid_3; + + typedef Image Image_float; + typedef Planimetric_grid Grid; + + const PointRange& input; + PointMap point_map; + const Grid& grid; + Image_float dtm; + std::vector values; + +public: + /*! + \brief Constructs the feature. + + \param input point range. + \param point_map property map to access the input points. + \param grid precomputed `Planimetric_grid`. + */ + Height_above (const PointRange& input, + PointMap point_map, + const Grid& grid) + : input(input), point_map(point_map), grid(grid) + { + this->set_name ("height_above"); + + dtm = Image_float(grid.width(),grid.height()); + + for (std::size_t j = 0; j < grid.height(); ++ j) + for (std::size_t i = 0; i < grid.width(); ++ i) + if (grid.has_points(i,j)) + { + float z_max = -std::numeric_limits::max(); + + typename Grid::iterator end = grid.indices_end(i,j); + for (typename Grid::iterator it = grid.indices_begin(i,j); it != end; ++ it) + { + float z = float(get(point_map, *(input.begin()+(*it))).z()); + z_max = (std::max(z_max, z)); + } + + dtm(i,j) = z_max; + } + + if (grid.width() * grid.height() > input.size()) + { + values.resize (input.size(), 0.f); + for (std::size_t i = 0; i < input.size(); ++ i) + { + std::size_t I = grid.x(i); + std::size_t J = grid.y(i); + values[i] = float(dtm(I,J) - get (point_map, *(input.begin() + i)).z()); + } + dtm.free(); + } + + } + + /// \cond SKIP_IN_MANUAL + virtual float value (std::size_t pt_index) + { + if (values.empty()) + { + std::size_t I = grid.x(pt_index); + std::size_t J = grid.y(pt_index); + return dtm(I,J) - float(get (point_map, *(input.begin() + pt_index)).z()); + } + + return values[pt_index]; + } + + /// \endcond +}; + +} // namespace Feature + +} // namespace Classification + + +} // namespace CGAL + +#endif // CGAL_CLASSIFICATION_FEATURE_HEIGHT_ABOVE_H diff --git a/Classification/include/CGAL/Classification/Feature/Height_below.h b/Classification/include/CGAL/Classification/Feature/Height_below.h new file mode 100644 index 00000000000..c63f890f20c --- /dev/null +++ b/Classification/include/CGAL/Classification/Feature/Height_below.h @@ -0,0 +1,142 @@ +// Copyright (c) 2012 INRIA Sophia-Antipolis (France). +// Copyright (c) 2017 GeometryFactory Sarl (France). +// All rights reserved. +// +// This file is part of CGAL (www.cgal.org). +// You can redistribute it and/or modify it under the terms of the GNU +// General Public License as published by the Free Software Foundation, +// either version 3 of the License, or (at your option) any later version. +// +// 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$ +// $Id$ +// SPDX-License-Identifier: GPL-3.0+ +// +// Author(s) : Florent Lafarge, Simon Giraudot + +#ifndef CGAL_CLASSIFICATION_FEATURE_HEIGHT_BELOW_H +#define CGAL_CLASSIFICATION_FEATURE_HEIGHT_BELOW_H + +#include + +#include + +#include +#include +#include +#include + +namespace CGAL { + +namespace Classification { + +namespace Feature { + + /*! + \ingroup PkgClassificationFeatures + + %Feature based on local height distribution This feature computes + the distance between a point's height and the minimum height on + the local cell of the planimetric grid. + + Its default name is "height_below". + + \tparam GeomTraits model of \cgal Kernel. + \tparam PointRange model of `ConstRange`. Its iterator type + is `RandomAccessIterator` and its value type is the key type of + `PointMap`. + \tparam PointMap model of `ReadablePropertyMap` whose key + type is the value type of the iterator of `PointRange` and value type + is `GeomTraits::Point_3`. + + */ +template +class Height_below : public Feature_base +{ + typedef typename GeomTraits::Iso_cuboid_3 Iso_cuboid_3; + + typedef Image Image_float; + typedef Planimetric_grid Grid; + + const PointRange& input; + PointMap point_map; + const Grid& grid; + Image_float dtm; + std::vector values; + +public: + /*! + \brief Constructs the feature. + + \param input point range. + \param point_map property map to access the input points. + \param grid precomputed `Planimetric_grid`. + */ + Height_below (const PointRange& input, + PointMap point_map, + const Grid& grid) + : input(input), point_map(point_map), grid(grid) + { + this->set_name ("height_below"); + + dtm = Image_float(grid.width(),grid.height()); + + for (std::size_t j = 0; j < grid.height(); ++ j) + for (std::size_t i = 0; i < grid.width(); ++ i) + if (grid.has_points(i,j)) + { + float z_min = std::numeric_limits::max(); + + typename Grid::iterator end = grid.indices_end(i,j); + for (typename Grid::iterator it = grid.indices_begin(i,j); it != end; ++ it) + { + float z = float(get(point_map, *(input.begin()+(*it))).z()); + z_min = (std::min(z_min, z)); + } + + dtm(i,j) = z_min; + } + + if (grid.width() * grid.height() > input.size()) + { + values.resize (input.size(), 0.f); + for (std::size_t i = 0; i < input.size(); ++ i) + { + std::size_t I = grid.x(i); + std::size_t J = grid.y(i); + values[i] = float(get (point_map, *(input.begin() + i)).z() - dtm(I,J)); + } + dtm.free(); + } + + } + + /// \cond SKIP_IN_MANUAL + virtual float value (std::size_t pt_index) + { + if (values.empty()) + { + std::size_t I = grid.x(pt_index); + std::size_t J = grid.y(pt_index); + return float(get (point_map, *(input.begin() + pt_index)).z() - dtm(I,J)); + } + + return values[pt_index]; + } + + /// \endcond +}; + +} // namespace Feature + +} // namespace Classification + + +} // namespace CGAL + +#endif // CGAL_CLASSIFICATION_FEATURE_HEIGHT_BELOW_H diff --git a/Classification/include/CGAL/Classification/Feature/Vertical_range.h b/Classification/include/CGAL/Classification/Feature/Vertical_range.h new file mode 100644 index 00000000000..6a475786eef --- /dev/null +++ b/Classification/include/CGAL/Classification/Feature/Vertical_range.h @@ -0,0 +1,144 @@ +// Copyright (c) 2012 INRIA Sophia-Antipolis (France). +// Copyright (c) 2017 GeometryFactory Sarl (France). +// All rights reserved. +// +// This file is part of CGAL (www.cgal.org). +// You can redistribute it and/or modify it under the terms of the GNU +// General Public License as published by the Free Software Foundation, +// either version 3 of the License, or (at your option) any later version. +// +// 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$ +// $Id$ +// SPDX-License-Identifier: GPL-3.0+ +// +// Author(s) : Florent Lafarge, Simon Giraudot + +#ifndef CGAL_CLASSIFICATION_FEATURE_VERTICAL_RANGE_H +#define CGAL_CLASSIFICATION_FEATURE_VERTICAL_RANGE_H + +#include + +#include + +#include +#include +#include +#include + +namespace CGAL { + +namespace Classification { + +namespace Feature { + + /*! + \ingroup PkgClassificationFeatures + + %Feature based on local height distribution. This feature computes + the distance between the maximum and the minimum height on the + local cell of the planimetric grid. + + Its default name is "vertical_range". + + \tparam GeomTraits model of \cgal Kernel. + \tparam PointRange model of `ConstRange`. Its iterator type + is `RandomAccessIterator` and its value type is the key type of + `PointMap`. + \tparam PointMap model of `ReadablePropertyMap` whose key + type is the value type of the iterator of `PointRange` and value type + is `GeomTraits::Point_3`. + + */ +template +class Vertical_range : public Feature_base +{ + typedef typename GeomTraits::Iso_cuboid_3 Iso_cuboid_3; + + typedef Image Image_float; + typedef Planimetric_grid Grid; + + const PointRange& input; + PointMap point_map; + const Grid& grid; + Image_float dtm; + std::vector values; + +public: + /*! + \brief Constructs the feature. + + \param input point range. + \param point_map property map to access the input points. + \param grid precomputed `Planimetric_grid`. + */ + Vertical_range (const PointRange& input, + PointMap point_map, + const Grid& grid) + : input(input), point_map(point_map), grid(grid) + { + this->set_name ("vertical_range"); + + dtm = Image_float(grid.width(),grid.height()); + + for (std::size_t j = 0; j < grid.height(); ++ j) + for (std::size_t i = 0; i < grid.width(); ++ i) + if (grid.has_points(i,j)) + { + float z_max = -std::numeric_limits::max(); + float z_min = std::numeric_limits::max(); + + typename Grid::iterator end = grid.indices_end(i,j); + for (typename Grid::iterator it = grid.indices_begin(i,j); it != end; ++ it) + { + float z = float(get(point_map, *(input.begin()+(*it))).z()); + z_max = (std::max(z_max, z)); + z_min = (std::min(z_min, z)); + } + + dtm(i,j) = z_max - z_min; + } + + if (grid.width() * grid.height() > input.size()) + { + values.resize (input.size(), 0.f); + for (std::size_t i = 0; i < input.size(); ++ i) + { + std::size_t I = grid.x(i); + std::size_t J = grid.y(i); + values[i] = dtm(I,J); + } + dtm.free(); + } + + } + + /// \cond SKIP_IN_MANUAL + virtual float value (std::size_t pt_index) + { + if (values.empty()) + { + std::size_t I = grid.x(pt_index); + std::size_t J = grid.y(pt_index); + return dtm(I,J); + } + + return values[pt_index]; + } + + /// \endcond +}; + +} // namespace Feature + +} // namespace Classification + + +} // namespace CGAL + +#endif // CGAL_CLASSIFICATION_FEATURE_VERTICAL_RANGE_H diff --git a/Classification/include/CGAL/Classification/Image.h b/Classification/include/CGAL/Classification/Image.h index 6f2f0ed297a..ffaf0796081 100644 --- a/Classification/include/CGAL/Classification/Image.h +++ b/Classification/include/CGAL/Classification/Image.h @@ -41,6 +41,8 @@ class Image std::size_t m_width; std::size_t m_height; + std::size_t m_depth; + boost::shared_ptr m_raw; boost::shared_ptr m_sparse; Type m_default; @@ -52,18 +54,19 @@ class Image public: - Image () : m_width(0), m_height(0), m_raw (NULL) + Image () : m_width(0), m_height(0), m_depth(0), m_raw (NULL) { } - Image (std::size_t width, std::size_t height) - : m_width (width), - m_height (height) + Image (std::size_t width, std::size_t height, std::size_t depth = 1) + : m_width (width) + , m_height (height) + , m_depth (depth) { - if (m_width * m_height > 0) + if (m_width * m_height * m_depth > 0) { - if (m_width * m_height < CGAL_CLASSIFICATION_IMAGE_SIZE_LIMIT) - m_raw = boost::shared_ptr (new Vector(m_width * m_height)); + if (m_width * m_height * m_depth < CGAL_CLASSIFICATION_IMAGE_SIZE_LIMIT) + m_raw = boost::shared_ptr (new Vector(m_width * m_height * m_depth)); else m_sparse = boost::shared_ptr (new Map()); } @@ -85,33 +88,41 @@ public: m_sparse = other.m_sparse; m_width = other.width(); m_height = other.height(); + m_depth = other.depth(); return *this; } std::size_t width() const { return m_width; } std::size_t height() const { return m_height; } + std::size_t depth() const { return m_depth; } - Type& operator() (const std::size_t& x, const std::size_t& y) + inline std::size_t coord (const std::size_t& x, const std::size_t& y, const std::size_t& z) const + { + return z + (m_depth * y) + (m_depth * m_height * x); + } + + Type& operator() (const std::size_t& x, const std::size_t& y, const std::size_t& z = 0) { if (m_raw == boost::shared_ptr()) // sparse case { - typename Map::iterator inserted = m_sparse->insert (std::make_pair (x * m_height + y, Type())).first; + typename Map::iterator inserted = m_sparse->insert + (std::make_pair (coord(x,y,z), Type())).first; return inserted->second; } - return (*m_raw)[x * m_height + y]; + return (*m_raw)[coord(x,y,z)]; } - const Type& operator() (const std::size_t& x, const std::size_t& y) const + const Type& operator() (const std::size_t& x, const std::size_t& y, const std::size_t& z = 0) const { if (m_raw == boost::shared_ptr()) // sparse case { - typename Map::iterator found = m_sparse->find (x * m_height + y); + typename Map::iterator found = m_sparse->find (coord(x,y,z)); if (found != m_sparse->end()) return found->second; return m_default; } - return (*m_raw)[x * m_height + y]; + return (*m_raw)[coord(x,y,z)]; } diff --git a/Classification/include/CGAL/Classification/Label.h b/Classification/include/CGAL/Classification/Label.h index 910a3498add..6c06eb96a49 100644 --- a/Classification/include/CGAL/Classification/Label.h +++ b/Classification/include/CGAL/Classification/Label.h @@ -50,6 +50,10 @@ public: Label (std::string name) : m_name (name) { } const std::string& name() const { return m_name; } + + /// \cond SKIP_IN_MANUAL + void set_name (const std::string& name) { m_name = name; } + /// \endcond }; #ifdef DOXYGEN_RUNNING diff --git a/Classification/include/CGAL/Classification/Mesh_feature_generator.h b/Classification/include/CGAL/Classification/Mesh_feature_generator.h index 935abc76a1e..d15b139cb3e 100644 --- a/Classification/include/CGAL/Classification/Mesh_feature_generator.h +++ b/Classification/include/CGAL/Classification/Mesh_feature_generator.h @@ -36,6 +36,9 @@ #include #include #include +#include +#include +#include #include #include @@ -65,15 +68,20 @@ namespace Classification { \brief Generates a set of generic features for surface mesh classification. - This class takes care of computing all necessary data structures and - of generating a set of generic features at multiple scales to - increase the reliability of the classification. + This class takes care of computing and storing all necessary data + structures and of generating a set of generic features at multiple + scales to increase the reliability of the classification. A `PointMap` is required: this map should associate each face of the mesh to a representative point (for example, the center of mass of the face). It is used to generate point set features by considering the mesh as a point set. + \warning The generated features use data structures that are stored + inside the generator. For this reason, the generator should be + instantiated _within the same scope_ as the feature set and should + not be deleted before the feature set. + \tparam GeomTraits model of \cgal Kernel. \tparam FaceListGraph model of `FaceListGraph`. \tparam PointMap model of `ReadablePropertyMap` whose key type is @@ -134,6 +142,12 @@ public: Distance_to_plane; typedef Classification::Feature::Elevation Elevation; + typedef Classification::Feature::Height_below + Height_below; + typedef Classification::Feature::Height_above + Height_above; + typedef Classification::Feature::Vertical_range + Vertical_range; typedef Classification::Feature::Vertical_dispersion Dispersion; typedef Classification::Feature::Verticality @@ -212,8 +226,8 @@ private: } float grid_resolution() const { return voxel_size; } - float radius_neighbors() const { return voxel_size * 5; } - float radius_dtm() const { return voxel_size * 100; } + float radius_neighbors() const { return voxel_size * 3; } + float radius_dtm() const { return voxel_size * 10; } }; @@ -327,7 +341,10 @@ public: - `CGAL::Classification::Feature::Distance_to_plane` - `CGAL::Classification::Feature::Elevation` + - `CGAL::Classification::Feature::Height_above` + - `CGAL::Classification::Feature::Height_below` - `CGAL::Classification::Feature::Vertical_dispersion` + - `CGAL::Classification::Feature::Vertical_range` \param features the feature set where the features are instantiated. */ @@ -339,6 +356,12 @@ public: features.add_with_scale_id (i, m_range, m_point_map, grid(i), radius_neighbors(i)); for (std::size_t i = 0; i < m_scales.size(); ++ i) features.add_with_scale_id (i, m_range, m_point_map, grid(i), radius_dtm(i)); + for (std::size_t i = 0; i < m_scales.size(); ++ i) + features.add_with_scale_id (i, m_range, m_point_map, grid(i)); + for (std::size_t i = 0; i < m_scales.size(); ++ i) + features.add_with_scale_id (i, m_range, m_point_map, grid(i)); + for (std::size_t i = 0; i < m_scales.size(); ++ i) + features.add_with_scale_id (i, m_range, m_point_map, grid(i)); } /// @} diff --git a/Classification/include/CGAL/Classification/OpenCV_random_forest_classifier.h b/Classification/include/CGAL/Classification/OpenCV/Random_forest_classifier.h similarity index 92% rename from Classification/include/CGAL/Classification/OpenCV_random_forest_classifier.h rename to Classification/include/CGAL/Classification/OpenCV/Random_forest_classifier.h index 091396b1b14..8b04c5d0b8d 100644 --- a/Classification/include/CGAL/Classification/OpenCV_random_forest_classifier.h +++ b/Classification/include/CGAL/Classification/OpenCV/Random_forest_classifier.h @@ -37,16 +37,18 @@ namespace CGAL { namespace Classification { -/*! - \ingroup PkgClassificationClassifiers +namespace OpenCV { - \brief %Classifier based on the OpenCV version of random forest algorithm. +/*! + \ingroup PkgClassificationClassifiersOpenCV + + \brief %Classifier based on the OpenCV version of the random forest algorithm. \note This class requires the \ref thirdpartyOpenCV library. \cgalModels `CGAL::Classification::Classifier` */ -class OpenCV_random_forest_classifier +class Random_forest_classifier { const Label_set& m_labels; const Feature_set& m_features; @@ -68,7 +70,7 @@ public: /// @{ /*! - \brief Instantiate the classifier using the sets of `labels` and `features`. + \brief Instantiates the classifier using the sets of `labels` and `features`. Parameters documentation is copy-pasted from [the official documentation of OpenCV](http://docs.opencv.org/2.4/modules/ml/doc/random_trees.html). For more details on this method, please refer to it. @@ -80,13 +82,13 @@ public: \param max_number_of_trees_in_the_forest The maximum number of trees in the forest (surprise, surprise). Typically the more trees you have the better the accuracy. However, the improvement in accuracy generally diminishes and asymptotes pass a certain number of trees. Also to keep in mind, the number of tree increases the prediction time linearly. \param forest_accuracy Sufficient accuracy (OOB error). */ - OpenCV_random_forest_classifier (const Label_set& labels, - const Feature_set& features, - int max_depth = 20, - int min_sample_count = 5, - int max_categories = 15, - int max_number_of_trees_in_the_forest = 100, - float forest_accuracy = 0.01f) + Random_forest_classifier (const Label_set& labels, + const Feature_set& features, + int max_depth = 20, + int min_sample_count = 5, + int max_categories = 15, + int max_number_of_trees_in_the_forest = 100, + float forest_accuracy = 0.01f) : m_labels (labels), m_features (features), m_max_depth (max_depth), m_min_sample_count (min_sample_count), m_max_categories (max_categories), @@ -98,7 +100,7 @@ public: { } /// \cond SKIP_IN_MANUAL - ~OpenCV_random_forest_classifier () + ~Random_forest_classifier () { #if (CV_MAJOR_VERSION < 3) if (rtree != NULL) @@ -298,6 +300,13 @@ public: } +/// \cond SKIP_IN_MANUAL +// Backward compatibility +typedef OpenCV::Random_forest_classifier OpenCV_random_forest_classifier; +/// \endcond + +} + } #endif // CGAL_CLASSIFICATION_OPENCV_RANDOM_FOREST_CLASSIFIER_H diff --git a/Classification/include/CGAL/Classification/Point_set_feature_generator.h b/Classification/include/CGAL/Classification/Point_set_feature_generator.h index 9063d094afb..b017ebe427c 100644 --- a/Classification/include/CGAL/Classification/Point_set_feature_generator.h +++ b/Classification/include/CGAL/Classification/Point_set_feature_generator.h @@ -35,6 +35,9 @@ #include #include #include +#include +#include +#include // Experimental feature, not used officially #ifdef CGAL_CLASSIFICATION_USE_GRADIENT_OF_FEATURE @@ -67,9 +70,14 @@ namespace Classification { \brief Generates a set of generic features for point set classification. - This class takes care of computing all necessary data structures and - of generating a set of generic features at multiple scales to - increase the reliability of the classification. + This class takes care of computing and storing all necessary data + structures and of generating a set of generic features at multiple + scales to increase the reliability of the classification. + + \warning The generated features use data structures that are stored + inside the generator. For this reason, the generator should be + instantiated _within the same scope_ as the feature set and should + not be deleted before the feature set. \tparam GeomTraits model of \cgal Kernel. \tparam PointRange model of `ConstRange`. Its iterator type is @@ -128,6 +136,12 @@ public: Distance_to_plane; typedef Classification::Feature::Elevation Elevation; + typedef Classification::Feature::Height_below + Height_below; + typedef Classification::Feature::Height_above + Height_above; + typedef Classification::Feature::Vertical_range + Vertical_range; typedef Classification::Feature::Vertical_dispersion Dispersion; typedef Classification::Feature::Verticality @@ -166,7 +180,7 @@ private: neighborhood = new Neighborhood (input, point_map, voxel_size); t.stop(); - if (voxel_size < 0.) + if (lower_grid == NULL) CGAL_CLASSIFICATION_CERR << "Neighborhood computed in " << t.time() << " second(s)" << std::endl; else CGAL_CLASSIFICATION_CERR << "Neighborhood with voxel size " << voxel_size @@ -216,8 +230,8 @@ private: } float grid_resolution() const { return voxel_size; } - float radius_neighbors() const { return voxel_size * 5; } - float radius_dtm() const { return voxel_size * 100; } + float radius_neighbors() const { return voxel_size * 3; } + float radius_dtm() const { return voxel_size * 10; } }; @@ -365,7 +379,10 @@ public: - `CGAL::Classification::Feature::Eigenvalue` with indices 0, 1 and 2 - `CGAL::Classification::Feature::Distance_to_plane` - `CGAL::Classification::Feature::Elevation` + - `CGAL::Classification::Feature::Height_above` + - `CGAL::Classification::Feature::Height_below` - `CGAL::Classification::Feature::Vertical_dispersion` + - `CGAL::Classification::Feature::Vertical_range` - The version of `CGAL::Classification::Feature::Verticality` based on eigenvalues \param features the feature set where the features are instantiated. @@ -381,6 +398,12 @@ public: features.add_with_scale_id (i, m_input, m_point_map, grid(i), radius_neighbors(i)); for (std::size_t i = 0; i < m_scales.size(); ++ i) features.add_with_scale_id (i, m_input, m_point_map, grid(i), radius_dtm(i)); + for (std::size_t i = 0; i < m_scales.size(); ++ i) + features.add_with_scale_id (i, m_input, m_point_map, grid(i)); + for (std::size_t i = 0; i < m_scales.size(); ++ i) + features.add_with_scale_id (i, m_input, m_point_map, grid(i)); + for (std::size_t i = 0; i < m_scales.size(); ++ i) + features.add_with_scale_id (i, m_input, m_point_map, grid(i)); for (std::size_t i = 0; i < m_scales.size(); ++ i) features.add_with_scale_id (i, m_input, eigen(i)); } diff --git a/Classification/include/CGAL/Classification/Sum_of_weighted_features_classifier.h b/Classification/include/CGAL/Classification/Sum_of_weighted_features_classifier.h index 2b159e27934..7426f275899 100644 --- a/Classification/include/CGAL/Classification/Sum_of_weighted_features_classifier.h +++ b/Classification/include/CGAL/Classification/Sum_of_weighted_features_classifier.h @@ -173,7 +173,7 @@ public: /*! - \brief Instantiate the classifier using the sets of `labels` and `features`. + \brief Instantiates the classifier using the sets of `labels` and `features`. \note If the label set of the feature set are modified after instantiating this object (addition of removal of a label and/or of diff --git a/Classification/include/CGAL/Classification/TensorFlow/Neural_network_classifier.h b/Classification/include/CGAL/Classification/TensorFlow/Neural_network_classifier.h new file mode 100644 index 00000000000..b3df48bb72b --- /dev/null +++ b/Classification/include/CGAL/Classification/TensorFlow/Neural_network_classifier.h @@ -0,0 +1,1123 @@ +// Copyright (c) 2018 GeometryFactory Sarl (France). +// All rights reserved. +// +// This file is part of CGAL (www.cgal.org). +// You can redistribute it and/or modify it under the terms of the GNU +// General Public License as published by the Free Software Foundation, +// either version 3 of the License, or (at your option) any later version. +// +// 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$ +// $Id$ +// SPDX-License-Identifier: GPL-3.0+ +// +// Author(s) : Simon Giraudot + +#ifndef CGAL_CLASSIFICATION_TENSORFLOW_NEURAL_NETWORK_CLASSIFIER_H +#define CGAL_CLASSIFICATION_TENSORFLOW_NEURAL_NETWORK_CLASSIFIER_H + +#include + +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +#define CGAL_NEURAL_NETWORK_VERSION "0.1" + +namespace CGAL { + +namespace Classification { + +namespace TensorFlow { + +namespace TF = tensorflow; +namespace TFops = tensorflow::ops; + +/*! + \ingroup PkgClassificationClassifiersTensorFlow + + \brief %Classifier based on the TensorFlow version of the neural + network algorithm. + + This class provides an interface to a feature-based neural network: + a set of features is used as an input layer followed by a + user-specified number of hidden layers with a user-specified + activation function. The output layer is a softmax layer providing, + for each label, the probability that an input item belongs to it. + + \warning This feature is still experimental: it may not be stable + and is likely to undergo substantial changes in future releases of + \cgal. The API changes will be announced in the release notes. + + \note This class requires the \ref thirdpartyTensorFlow library. + + \tparam ActivationFunction Chosen activation function for the hidden + layers. `Relu` is used as default. The following functions can be + used (please refer to the documentation of \ref thirdpartyTensorFlow + for more information): + - `tensorflow::ops::Elu` + - `tensorflow::ops::Relu6` + - `tensorflow::ops::Relu` + - `tensorflow::ops::Selu` + - `tensorflow::ops::Sigmoid` + - `tensorflow::ops::Tanh` + + \cgalModels `CGAL::Classification::Classifier` +*/ +template +class Neural_network_classifier +{ + bool m_verbose; + + const Label_set& m_labels; + const Feature_set& m_features; + std::vector m_feature_means; + std::vector m_feature_sd; + + TF::Scope* m_root; + TFops::Placeholder* m_ph_ft; + TFops::Placeholder* m_ph_gt; + + TFops::ReduceMean* m_loss; + + std::vector > m_weights; + std::vector > m_bias; + float m_learning_rate; + std::vector m_layers; + +#define CGAL_CLASSIFICATION_TENSORFLOW_USE_ADAM +#ifdef CGAL_CLASSIFICATION_TENSORFLOW_USE_ADAM + std::vector m_optimizer; +#else + std::vector m_optimizer; +#endif + + TF::ClientSession* m_session; + +public: + + /// \cond SKIP_IN_MANUAL + const Feature_set& features() const { return m_features; } + /// \endcond + + /// \name Constructor + /// @{ + + /*! + \brief Instantiates the classifier using the sets of `labels` and `features`. + + */ + Neural_network_classifier (const Label_set& labels, + const Feature_set& features) + : m_verbose (true), m_labels (labels), m_features (features) + , m_root (NULL), m_ph_ft (NULL), m_ph_gt (NULL), m_loss(NULL), m_session (NULL) + { } + + /// \cond SKIP_IN_MANUAL + ~Neural_network_classifier () + { + clear(); + } + + bool initialized() const { return (m_root != NULL); } + + bool& verbose() { return m_verbose; } + + void clear() + { + clear (m_ph_gt); + clear (m_ph_ft); + clear (m_loss); + clear (m_session); + clear (m_root); + m_weights.clear(); + m_bias.clear(); + m_optimizer.clear(); + m_layers.clear(); + } + + template + void clear (T* t) + { + if (t != NULL) + delete t; + t = NULL; + } + + void compute_normalization_coefficients (const std::vector& indices) + { +//#define DO_NOT_NORMALIZE_FEATURES +#ifdef DO_NOT_NORMALIZE_FEATURES + m_feature_means.clear(); + m_feature_means.resize (m_features.size(), 0.f); + m_feature_sd.clear(); + m_feature_sd.resize (m_features.size(), 1.f); +#else + m_feature_means.clear(); + m_feature_means.resize (m_features.size(), 0.f); + + for (std::size_t i = 0; i < indices.size(); ++ i) + for (std::size_t f = 0; f < m_features.size(); ++ f) + m_feature_means[f] += m_features[f]->value(indices[i]); + for (std::size_t f = 0; f < m_features.size(); ++ f) + m_feature_means[f] /= indices.size(); + + m_feature_sd.clear(); + m_feature_sd.resize (m_features.size(), 0.f); + + for (std::size_t i = 0; i < indices.size(); ++ i) + for (std::size_t f = 0; f < m_features.size(); ++ f) + m_feature_sd[f] += + (m_features[f]->value(indices[i]) - m_feature_means[f]) * + (m_features[f]->value(indices[i]) - m_feature_means[f]); + for (std::size_t f = 0; f < m_features.size(); ++ f) + { + m_feature_sd[f] = std::sqrt (m_feature_sd[f] / indices.size()); + if (m_feature_sd[f] == 0.f) + m_feature_sd[f] = 1.f; + + if (std::isnan(m_feature_means[f])) + m_feature_means[f] = 0.f; + if (std::isnan(m_feature_sd[f])) + m_feature_sd[f] = 1.f; + + // if (m_verbose) + // std::cerr << "#" << f << ": " << m_features[f]->name() << " = " + // << m_feature_means[f] << " +/- " << m_feature_sd[f] << std::endl; + } +#endif + } + /// \endcond + + /// @} + + /// \name Training + + /// @{ + /*! + \brief Runs the training algorithm. + + From the set of provided ground truth, this algorithm constructs a + neural network and applies an Adam optimizer to set up the weights + and bias that produce the most accurate result with respect to + this ground truth. + + \pre At least one ground truth item should be assigned to each + label. + + \param ground_truth vector of label indices. It should contain for + each input item, in the same order as the input set, the index of + the corresponding label in the `Label_set` provided in the + constructor. Input items that do not have a ground truth + information should be given the value `-1`. + + \param restart_from_scratch should be set to `false` if the user + wants to continue adjusting weights and bias based, and set to + `true` if the neural network should be re-created from scratch + (discarding all previous training results). + + \param number_of_iterations number of times the optimizer is + called. + + \param learning_rate describes the rate at which the optimizer + changes the weights and bias. + + \param batch_size size of the random subset of inliers used for + optimizing at each iteration. + + \param hidden_layers vector containing the consecutive sizes + (number of neurons) of the hidden layers of the network. If no + vector is given, the behavior used is the following: 2 hidden + layers are used. The first layer has as many neurons as the number + of features; the second layer has a number of neurons equal to the + average value between the number of features and the number of + labels. + */ + template + void train (const LabelIndexRange& ground_truth, + bool restart_from_scratch = true, + std::size_t number_of_iterations = 5000, + float learning_rate = 0.01, + std::size_t batch_size = 1000, + const std::vector& hidden_layers + = std::vector()) + { + if (restart_from_scratch) + clear(); + + std::vector > random_indices (m_labels.size()); + + std::vector indices; + std::vector raw_gt; + for (std::size_t i = 0; i < ground_truth.size(); ++ i) + { + int gc = int(ground_truth[i]); + if (gc != -1) + { + indices.push_back (i); + raw_gt.push_back (gc); + random_indices[std::size_t(gc)].push_back (indices.size() - 1); + } + } + + if (!initialized()) + { + m_learning_rate = learning_rate; + build_architecture (hidden_layers); + if (m_verbose) std::cerr << "II - NORMALIZING FEATURES" << std::endl; + compute_normalization_coefficients (indices); + } + + if (m_verbose) std::cerr << "III - TRAINING NEURAL NETWORK" << std::endl; + + std::vector operations; + for (std::size_t i = 0; i < m_optimizer.size(); ++ i) + operations.push_back (m_optimizer[i]); + operations.push_back (m_layers.back()); + + std::vector outputs; + + m_weights.clear(); + m_bias.clear(); + // std::ofstream log ("loss.log"); + // log.precision(18); + + for (std::size_t i = 0; i < number_of_iterations; ++ i) + { + std::size_t total_batch_size = 0; + for (std::size_t j = 0; j < random_indices.size(); ++ j) + { + if (random_indices[j].empty()) + continue; + std::size_t local_batch_size = std::min (std::size_t(batch_size / m_labels.size()), + random_indices[j].size()); + random_unique (random_indices[j].begin(), random_indices[j].end(), local_batch_size); + total_batch_size += local_batch_size; + + if (i == 0) + { + if (m_verbose) std::cerr << " * Size of batch for " << m_labels[j]->name() << ": " + << local_batch_size << std::endl; + } + } + + TF::Tensor ft + (TF::DataTypeToEnum::v(), + TF::TensorShape {(long long)(total_batch_size), (long long)(m_features.size())}); + TF::Tensor gt + (TF::DataTypeToEnum::v(), + TF::TensorShape {(long long)(total_batch_size), (long long)(m_labels.size())}); + + float* ft_data = ft.flat().data(); + float* gt_data = gt.flat().data(); + + // Fill input tensors + std::size_t current_i = 0; + for (std::size_t j = 0; j < random_indices.size(); ++ j) + { + if (random_indices[j].empty()) + continue; + std::size_t local_batch_size = std::min (std::size_t(batch_size / m_labels.size()), + random_indices[j].size()); + for (std::size_t k = 0; k < local_batch_size; ++ k) + { + std::size_t idx = indices[random_indices[j][k]]; + int g = raw_gt[random_indices[j][k]]; + + for (std::size_t f = 0; f < m_features.size(); ++ f) + ft_data[current_i * m_features.size() + f] + = (m_features[f]->value(idx) - m_feature_means[f]) / m_feature_sd[f]; + + for (std::size_t l = 0; l < m_labels.size(); ++ l) + if (std::size_t(g) == l) + gt_data[current_i * m_labels.size() + l] = 1.f; + else + gt_data[current_i * m_labels.size() + l] = 0.f; + + ++ current_i; + } + } + + TF_CHECK_OK (m_session->Run ({{*m_ph_ft, ft}, {*m_ph_gt, gt}}, {*m_loss}, &outputs)); + + if ((i+1) % (number_of_iterations / 20) == 0) + { + if (m_verbose) std::cerr << " * Step " << i+1 << "/" << number_of_iterations << ": loss = " + << outputs[0].scalar() << std::endl; + } + if (!std::isfinite(*outputs[0].scalar().data())) + { + if (m_verbose) + std::cerr << "Loss is " << outputs[0].scalar() << ", aborting" << std::endl; + return; + } + + if (i == number_of_iterations - 1) + { + TF_CHECK_OK(m_session->Run({{*m_ph_ft, ft}, {*m_ph_gt, gt}}, operations, &outputs)); + for (std::size_t o = 0; o < outputs.size() - 1; ++ o) + { + std::size_t size = outputs[o].dim_size(0) * outputs[o].dim_size(1); + if (o < outputs.size() / 2) + { + m_weights.push_back (std::vector(size)); + float* weights_data = outputs[o].flat().data(); + std::copy_n (weights_data, size, m_weights.back().begin()); + } + else + { + m_bias.push_back (std::vector(size)); + float* bias_data = outputs[o].flat().data(); + std::copy_n (bias_data, size, m_bias.back().begin()); + } + } + } + else + TF_CHECK_OK(m_session->Run({{*m_ph_ft, ft}, {*m_ph_gt, gt}}, operations, nullptr)); + } + + } + + /// \cond SKIP_IN_MANUAL + void operator() (std::size_t item_index, std::vector& out) const + { + out.resize (m_labels.size(), 0.); + + TF::Tensor ft + (TF::DataTypeToEnum::v(), + TF::TensorShape {(long long)(1), (long long)(m_features.size())}); + + float* ft_data = ft.flat().data(); + + // Fill input tensor + for (std::size_t f = 0; f < m_features.size(); ++ f) + ft_data[f] = (m_features[f]->value(item_index) - m_feature_means[f]) / m_feature_sd[f]; + + std::vector outputs; + TF_CHECK_OK(m_session->Run({{*m_ph_ft, ft}}, {m_layers.back()}, &outputs)); + + float* output_data = outputs[0].flat().data(); + + for (std::size_t i = 0; i < m_labels.size(); ++ i) + out[i] = output_data[i]; + } + + + void operator() (const std::vector& item_indices, + std::vector >& out) const + { + out.resize (item_indices.size(), std::vector(m_labels.size(), 0.)); + + TF::Tensor ft + (TF::DataTypeToEnum::v(), + TF::TensorShape {(long long)(item_indices.size()), (long long)(m_features.size())}); + + float* ft_data = ft.flat().data(); + + // Fill input tensor + for (std::size_t i = 0; i < item_indices.size(); ++ i) + for (std::size_t f = 0; f < m_features.size(); ++ f) + ft_data[i * m_features.size() + f] + = (m_features[f]->value(item_indices[i]) - m_feature_means[f]) / m_feature_sd[f]; + + std::vector outputs; + TF_CHECK_OK(m_session->Run({{*m_ph_ft, ft}}, {m_layers.back()}, &outputs)); + + float* output_data = outputs[0].flat().data(); + + for (std::size_t i = 0; i < item_indices.size(); ++ i) + for (std::size_t l = 0; l < m_labels.size(); ++ l) + out[i][l] = output_data[i * m_labels.size() + l]; + } + /// \endcond + + /// @} + + /// \name Input/Output + /// @{ + + /*! + \brief Saves the current configuration in the stream `output`. + + This allows to easily save and recover a specific classification + configuration, that is to say: + + - The statistics of features (mean and standard deviation) + - The number of hiddens layers and their respectives sizes + - The weights and bias of the neurons + + The output file is written in an XML format that is readable by + the `load_configuration()` method. + */ + void save_configuration (std::ostream& output) + { + boost::property_tree::ptree tree; + + { + boost::property_tree::ptree ptr; + ptr.put("classifier_version", CGAL_NEURAL_NETWORK_VERSION); + ptr.put("number_of_features", m_features.size()); + ptr.put("number_of_labels", m_labels.size()); + ptr.put("number_of_hidden_layers", m_layers.size() - 1); + ptr.put("learning_rate", m_learning_rate); + tree.add_child("classification.metadata", ptr); + } + + for (std::size_t i = 0; i < m_features.size(); ++ i) + { + boost::property_tree::ptree ptr; + ptr.put("name", m_features[i]->name()); + ptr.put("mean", m_feature_means[i]); + ptr.put("standard_deviation", m_feature_sd[i]); + tree.add_child("classification.features.feature", ptr); + } + + for (std::size_t i = 0; i < m_labels.size(); ++ i) + { + boost::property_tree::ptree ptr; + ptr.put("name", m_labels[i]->name()); + tree.add_child("classification.labels.label", ptr); + } + + for (std::size_t i = 0; i < m_weights.size(); ++ i) + { + boost::property_tree::ptree ptr; + ptr.put("height", (m_weights[i].size() / m_bias[i].size())); + ptr.put("width", m_bias[i].size()); + + std::ostringstream oss; + oss.precision(std::numeric_limits::digits10 + 2); + for (std::size_t j = 0; j < m_weights[i].size(); ++ j) + { + oss << m_weights[i][j]; + if (j != m_weights[i].size() - 1) + oss << " "; + } + ptr.put("weights", oss.str()); + + oss = std::ostringstream(); + oss.precision(std::numeric_limits::digits10 + 2); + for (std::size_t j = 0; j < m_bias[i].size(); ++ j) + { + oss << m_bias[i][j]; + if (j != m_bias[i].size() - 1) + oss << " "; + } + ptr.put("bias", oss.str()); + + tree.add_child("classification.layers.layer", ptr); + } + + // Write property tree to XML file + boost::property_tree::write_xml(output, tree, +#if BOOST_VERSION >= 105600 + boost::property_tree::xml_writer_make_settings(' ', 3)); +#else + boost::property_tree::xml_writer_make_settings(' ', 3)); +#endif + } + + /*! + \brief Loads a configuration from the stream `input`. + + The input file should be in the XML format written by the + `save_configuration()` method. The feature set of the classifier + should contain the exact same features in the exact same order as + the ones present when the file was generated using + `save_configuration()`. + */ + bool load_configuration (std::istream& input, bool verbose = false) + { + clear(); + + bool out = true; + + boost::property_tree::ptree tree; + boost::property_tree::read_xml(input, tree); + + std::string version = tree.get("classification.metadata.classifier_version"); + if (version != CGAL_NEURAL_NETWORK_VERSION) + { + if (verbose) + std::cerr << "Error: CGAL Neural Network version mismatch " << version << "/" << CGAL_NEURAL_NETWORK_VERSION << std::endl; + return false; + } + std::size_t nb_features = std::size_t(tree.get("classification.metadata.number_of_features")); + if (nb_features != m_features.size()) + { + if (verbose) + std::cerr << "Error: number of features mismatch " << nb_features << "/" << m_features.size() << std::endl; + return false; + } + + std::size_t nb_labels = std::size_t(tree.get("classification.metadata.number_of_labels")); + if (nb_labels != m_labels.size()) + { + if (verbose) + std::cerr << "Error: number of labels mismatch " << nb_labels << "/" << m_labels.size() << std::endl; + return false; + } + + std::size_t nb_layers = std::size_t(tree.get("classification.metadata.number_of_hidden_layers")) + 1; + m_learning_rate = tree.get("classification.metadata.learning_rate"); + + std::size_t idx = 0; + BOOST_FOREACH(boost::property_tree::ptree::value_type &v, tree.get_child("classification.features")) + { + std::string name = v.second.get("name"); + + if (name != m_features[idx]->name()) + { + if (verbose) + std::cerr << "Warning: feature mismatch " << name << "/" << m_features[idx]->name() << std::endl; + out = false; + } + + m_feature_means.push_back(v.second.get("mean")); + m_feature_sd.push_back(v.second.get("standard_deviation")); + + ++ idx; + } + + if (idx != nb_features) + { + if (verbose) + std::cerr << "Error: number of features mismatch " << nb_features << "/" << idx << std::endl; + return false; + } + + idx = 0; + BOOST_FOREACH(boost::property_tree::ptree::value_type &v, tree.get_child("classification.labels")) + { + std::string name = v.second.get("name"); + if (name != m_labels[idx]->name()) + { + if (verbose) + std::cerr << "Warning: label mismatch " << name << "/" << m_labels[idx]->name() << std::endl; + out = false; + } + ++ idx; + } + + if (idx != nb_labels) + { + if (verbose) + std::cerr << "Error: number of labels mismatch " << nb_labels << "/" << idx << std::endl; + return false; + } + + idx = 0; + m_weights.resize (nb_layers); + m_bias.resize (nb_layers); + + std::vector hidden_layers; + BOOST_FOREACH(boost::property_tree::ptree::value_type &v, tree.get_child("classification.layers")) + { + if (idx >= nb_layers) + { + if (verbose) + std::cerr << "Error: number of layers mismatch " << nb_layers << "/" << idx << std::endl; + return false; + } + std::size_t height = std::size_t(v.second.get("height")); + std::size_t width = std::size_t(v.second.get("width")); + std::size_t size = height * width; + m_weights[idx].reserve (size); + m_bias[idx].reserve (width); + + std::string weights = v.second.get("weights"); + std::istringstream iss (weights); + float f; + while (iss >> f) + m_weights[idx].push_back (f); + + std::string bias = v.second.get("bias"); + iss = std::istringstream (bias); + while (iss >> f) + m_bias[idx].push_back (f); + + if (idx != nb_layers - 1) + hidden_layers.push_back (width); + + ++ idx; + } + + if (idx != nb_layers) + { + if (verbose) + std::cerr << "Error: number of layers mismatch " << nb_layers << "/" << idx << std::endl; + return false; + } + + build_architecture(hidden_layers); + + return out; + } + +private: + + template + BidiIter random_unique(BidiIter begin, BidiIter end, size_t num_random) { + size_t left = std::distance(begin, end); + while (num_random--) { + BidiIter r = begin; + std::advance(r, rand()%left); + std::swap(*begin, *r); + ++begin; + --left; + } + return begin; + } + + void build_architecture (const std::vector& hidden_layers) + { + m_root = new TF::Scope (TF::Scope::NewRootScope()); + + + if (m_verbose) std::cerr << "I - BUILDING NEURAL NETWORK ARCHITECTURE" << std::endl; + + // Get layers and sizes or init with default values + std::vector hl = hidden_layers; + if (hl.empty()) + { + hl.push_back (m_features.size()); + hl.push_back ((m_features.size() + m_labels.size()) / 2); + } + + if (m_verbose) std::cerr << " 1) Initializing architecture:" << std::endl + << " * Layer 0: " << m_features.size() << " neuron(s) (input features)" << std::endl; + + if (m_verbose) + for (std::size_t i = 0; i < hl.size(); ++ i) + std::cerr << " * Layer " << i+1 << ": " << hl[i] << " neuron(s)" << std::endl; + + if (m_verbose) std::cerr << " * Layer " << hl.size() + 1 << ": " + << m_labels.size() << " neuron(s) (output labels)" << std::endl; + + + + m_ph_ft = new TFops::Placeholder (*m_root, TF::DT_FLOAT); + m_ph_gt = new TFops::Placeholder (*m_root, TF::DT_FLOAT); + + if (m_verbose) std::cerr << " 2) Creating weight matrices and bias" << std::endl; + + // create weight matrices and bias for each layer transition + std::vector weights; + std::vector bias; + std::vector assign_weights; + std::vector assign_bias; + + for (std::size_t i = 0; i <= hl.size(); ++ i) + { + long long size_from = 0; + long long size_to = 0; + if (i == 0) + { + size_from = m_features.size(); + size_to = hl[0]; + } + else if (i == hl.size()) + { + size_from = hl.back(); + size_to = m_labels.size(); + } + else + { + size_from = hl[i-1]; + size_to = hl[i]; + } + + if (m_verbose) std::cerr << " * Weight matrix " << i << " [" << size_from << ";" << size_to << "]" << std::endl; + weights.push_back (TFops::Variable (*m_root, { size_from, size_to }, TF::DT_FLOAT)); + + if (m_weights.empty()) + { + if (boost::is_same::value) // Weights initialized by Xavier method + assign_weights.push_back (TFops::Assign (*m_root, weights.back(), + TFops::Mul (*m_root, TFops::Const(*m_root, + std::sqrt (1.f / (float)(size_from))), + TFops::RandomNormal (*m_root, { size_from, size_to}, TF::DT_FLOAT)))); + else if (boost::is_same::value || + boost::is_same::value) // Weights initialized by He method + assign_weights.push_back (TFops::Assign (*m_root, weights.back(), + TFops::Mul (*m_root, TFops::Const(*m_root, + std::sqrt (2.f / (float)(size_from))), + TFops::RandomNormal (*m_root, { size_from, size_to}, TF::DT_FLOAT)))); + else // Default: weights truncated normal + assign_weights.push_back (TFops::Assign (*m_root, weights.back(), + TFops::TruncatedNormal (*m_root, { size_from, size_to}, TF::DT_FLOAT))); + } + else + { + TF::Tensor init_weight + (TF::DataTypeToEnum::v(), + TF::TensorShape {(long long)(size_from), (long long)(size_to)}); + float* init_weight_data = init_weight.flat().data(); + std::copy_n (m_weights[i].begin(), size_from * size_to, init_weight_data); + + assign_weights.push_back (TFops::Assign (*m_root, weights.back(), init_weight)); + } + + if (m_verbose) std::cerr << " * Bias " << i << " [" << size_to << "]" << std::endl; + bias.push_back (TFops::Variable (*m_root, { (long long)(1), size_to }, TF::DT_FLOAT)); + + TF::Tensor init_bias + (TF::DataTypeToEnum::v(), + TF::TensorShape {(long long)(1), (long long)(size_to)}); + float* init_bias_data = init_bias.flat().data(); + if (m_bias.empty()) + for (std::size_t s = 0; s < size_to; ++ s) + init_bias_data[s] = 0.f; + else + std::copy_n (m_bias[i].begin(), size_to, init_bias_data); + + assign_bias.push_back (TFops::Assign (*m_root, bias.back(), init_bias)); + } + + if (!m_root->status().ok()) + { + if (m_verbose) std::cerr << "Error: " << m_root->status().ToString() << std::endl; + return; + } + + if (m_verbose) std::cerr << " 3) Creating layers" << std::endl; + + for (std::size_t i = 0; i < weights.size(); ++ i) + { + if (i == 0) + m_layers.push_back (ActivationFunction (*m_root, TFops::Add + (*m_root, TFops::MatMul (*m_root, *m_ph_ft, weights[0]), + bias[0]))); + else if (i == weights.size() - 1) + m_layers.push_back (TFops::Softmax (*m_root, TFops::Add + (*m_root, TFops::MatMul (*m_root, m_layers.back(), weights[i]), + bias[i]))); + else + m_layers.push_back (ActivationFunction (*m_root, TFops::Add + (*m_root, TFops::MatMul (*m_root, m_layers.back(), weights[i]), + bias[i]))); + } + + if (!m_root->status().ok()) + { + if (m_verbose) std::cerr << "Error: " << m_root->status().ToString() << std::endl; + return; + } + + if (m_verbose) std::cerr << " 4) Setting up loss calculation" << std::endl; + + // loss calculation based on cross-entropy + TFops::Maximum truncated_ypred = TFops::Maximum (*m_root, TFops::Const(*m_root, 0.0001f), m_layers.back()); + TFops::Log log_ypred = TFops::Log (*m_root, truncated_ypred); + TFops::Mul ygt_times_log_ypred = TFops::Mul (*m_root, *m_ph_gt, log_ypred); + TFops::ReduceSum sum_ygt_times_log_ypred = TFops::ReduceSum(*m_root, ygt_times_log_ypred, {1}); + TFops::Mul minus_sum_ygt_times_log_ypred = TFops::Mul (*m_root, TFops::Const(*m_root, -1.f), sum_ygt_times_log_ypred); + + m_loss = new TFops::ReduceMean (*m_root, minus_sum_ygt_times_log_ypred, {0}); + + if (!m_root->status().ok()) + { + if (m_verbose) std::cerr << "Error: " << m_root->status().ToString() << std::endl; + return; + } + + if (m_verbose) std::cerr << " 5) Setting up gradient descent" << std::endl; + + std::vector weights_and_bias; + for (std::size_t i = 0; i < weights.size(); ++ i) + weights_and_bias.push_back (TF::Output(weights[i])); + for (std::size_t i = 0; i < bias.size(); ++ i) + weights_and_bias.push_back (TF::Output(bias[i])); + + std::vector gradients; + + TF_CHECK_OK(TF::AddSymbolicGradients(*m_root, {*m_loss}, + weights_and_bias, + &gradients)); + + if (!m_root->status().ok()) + { + if (m_verbose) std::cerr << "Error: " << m_root->status().ToString() << std::endl; + return; + } + + std::vector assigners; + +#ifdef CGAL_CLASSIFICATION_TENSORFLOW_USE_ADAM + for (std::size_t i = 0; i < weights.size(); ++ i) + { + long long size_from = 0; + long long size_to = 0; + if (i == 0) + { + size_from = m_features.size(); + size_to = hl[0]; + } + else if (i == weights.size() - 1) + { + size_from = hl.back(); + size_to = m_labels.size(); + } + else + { + size_from = hl[i-1]; + size_to = hl[i]; + } + + TFops::Variable m (*m_root, { size_from, size_to}, TF::DT_FLOAT); + TF::Tensor init_m + (TF::DataTypeToEnum::v(), + TF::TensorShape {(long long)(size_from), (long long)(size_to)}); + float* init_m_data = init_m.flat().data(); + for (std::size_t s = 0; s < size_from; ++ s) + for (std::size_t ss = 0; ss < size_to; ++ ss) + init_m_data[ss * size_from + s] = 0.f; + assigners.push_back (TFops::Assign (*m_root, m, init_m)); + + TFops::Variable v (*m_root, { size_from, size_to}, TF::DT_FLOAT); + TF::Tensor init_v + (TF::DataTypeToEnum::v(), + TF::TensorShape {(long long)(size_from), (long long)(size_to)}); + float* init_v_data = init_v.flat().data(); + for (std::size_t s = 0; s < size_from; ++ s) + for (std::size_t ss = 0; ss < size_to; ++ ss) + init_v_data[ss * size_from + s] = 0.f; + assigners.push_back (TFops::Assign (*m_root, v, init_v)); + + m_optimizer.push_back (TFops::ApplyAdam + (*m_root, + weights[i], + m, + v, + TFops::Cast(*m_root, 0.9, TF::DT_FLOAT), + TFops::Cast(*m_root, 0.999, TF::DT_FLOAT), + TFops::Cast(*m_root, m_learning_rate, TF::DT_FLOAT), + TFops::Cast(*m_root, 0.9, TF::DT_FLOAT), + TFops::Cast(*m_root, 0.999, TF::DT_FLOAT), + TFops::Cast(*m_root, 1e-8, TF::DT_FLOAT), + {gradients[i]})); + } + + for (std::size_t i = 0; i < bias.size(); ++ i) + { + long long size_from = 0; + long long size_to = 0; + if (i == 0) + size_to = hl[0]; + else if (i == bias.size() - 1) + size_to = m_labels.size(); + else + size_to = hl[i]; + + TFops::Variable m (*m_root, { 1, size_to}, TF::DT_FLOAT); + TF::Tensor init_m + (TF::DataTypeToEnum::v(), + TF::TensorShape {(long long)(1), (long long)(size_to)}); + float* init_m_data = init_m.flat().data(); + for (std::size_t s = 0; s < size_to; ++ s) + init_m_data[s] = 0.f; + assigners.push_back (TFops::Assign (*m_root, m, init_m)); + + TFops::Variable v (*m_root, { 1, size_to}, TF::DT_FLOAT); + TF::Tensor init_v + (TF::DataTypeToEnum::v(), + TF::TensorShape {(long long)(1), (long long)(size_to)}); + float* init_v_data = init_v.flat().data(); + for (std::size_t s = 0; s < size_to; ++ s) + init_v_data[s] = 0.f; + assigners.push_back (TFops::Assign (*m_root, v, init_v)); + + m_optimizer.push_back (TFops::ApplyAdam + (*m_root, + bias[i], + m, + v, + TFops::Cast(*m_root, 0.9, TF::DT_FLOAT), + TFops::Cast(*m_root, 0.999, TF::DT_FLOAT), + TFops::Cast(*m_root, m_learning_rate, TF::DT_FLOAT), + TFops::Cast(*m_root, 0.9, TF::DT_FLOAT), + TFops::Cast(*m_root, 0.999, TF::DT_FLOAT), + TFops::Cast(*m_root, 1e-8, TF::DT_FLOAT), + {gradients[weights.size() + i]})); + } + +#else + for (std::size_t i = 0; i < weights.size(); ++ i) + m_optimizer.push_back (TFops::ApplyGradientDescent + (*m_root, weights[i], + TFops::Cast(*m_root, m_learning_rate, TF::DT_FLOAT), {gradients[i]})); + for (std::size_t i = 0; i < bias.size(); ++ i) + m_optimizer.push_back (TFops::ApplyGradientDescent + (*m_root, bias[i], + TFops::Cast(*m_root, m_learning_rate, TF::DT_FLOAT), {gradients[weights.size() + i]})); +#endif + if (!m_root->status().ok()) + { + if (m_verbose) std::cerr << "Error: " << m_root->status().ToString() << std::endl; + return; + } + + if (m_verbose) std::cerr << " 6) Starting session" << std::endl; + + TF::SessionOptions options = TF::SessionOptions(); + + options.config.mutable_gpu_options()->set_allow_growth(true); + options.config.mutable_gpu_options()->set_per_process_gpu_memory_fraction(0.8); + options.config.mutable_gpu_options()->set_force_gpu_compatible(true); + + m_session = new TF::ClientSession (*m_root, options); + if (!m_root->status().ok()) + { + if (m_verbose) std::cerr << "Error: " << m_root->status().ToString() << std::endl; + return; + } + + std::vector outputs; + + for (std::size_t i = 0; i < assign_weights.size(); ++ i) + assigners.push_back (TF::Output(assign_weights[i])); + for (std::size_t i = 0; i < assign_bias.size(); ++ i) + assigners.push_back (TF::Output(assign_bias[i])); + TF_CHECK_OK (m_session->Run(assigners, nullptr)); + + if (!m_root->status().ok()) + { + if (m_verbose) std::cerr << "Error: " << m_root->status().ToString() << std::endl; + return; + } + } +}; + + +/// \cond SKIP_IN_MANUAL +#ifdef CGAL_CLASSIFICATION_TENSORFLOW_ENABLE_GPU_SPECIALIZATION +// Specialization to use GPU parallelization +template +void classify (const ItemRange& input, + const Label_set& labels, + const TensorFlow::Neural_network_classifier& classifier, + LabelIndexRange& output, + ProbabilitiesRanges& probabilities) +{ + std::cerr << "Classify with TensorFlow classifier" << std::endl; + + output.resize(input.size()); + probabilities.resize (labels.size()); + for (std::size_t i = 0; i < probabilities.size(); ++ i) + probabilities[i].resize (input.size()); + + const std::size_t mem_allocated = sizeof(float) * input.size() * (labels.size() + classifier.features().size()); + const std::size_t size_max = 512 * 1024 * 1024; + const std::size_t nb_subdivisions = (mem_allocated / size_max) + 1; + std::cerr << nb_subdivisions << " subdivision(s) for GPU processing" << std::endl; + + std::size_t idx = 0; + for (std::size_t n = 0; n < nb_subdivisions; ++ n) + { + std::vector indices; + indices.reserve (input.size() / nb_subdivisions); + for (std::size_t i = 0; i < input.size() / nb_subdivisions && idx < input.size(); ++ i) + indices.push_back(idx ++); + + std::vector > values; + classifier (indices, values); + for(std::size_t i = 0; i < indices.size(); ++ i) + { + std::size_t nb_class_best = 0; + float val_class_best = 0.f; + + for (std::size_t j = 0; j < labels.size(); ++ j) + { + probabilities[j][indices[i]] = values[i][j]; + + if(val_class_best < values[i][j]) + { + val_class_best = values[i][j]; + nb_class_best = j; + } + } + + output[indices[i]] = nb_class_best; + } + } +} + +// Specialization to use GPU parallelization +template +void classify (const ItemRange& input, + const Label_set& labels, + const TensorFlow::Neural_network_classifier& classifier, + LabelIndexRange& output) +{ + std::cerr << "Classify with TensorFlow classifier" << std::endl; + + output.resize(input.size()); + + const std::size_t mem_allocated = sizeof(float) * input.size() * (labels.size() + classifier.features().size()); + const std::size_t size_max = 512 * 1024 * 1024; + const std::size_t nb_subdivisions = (mem_allocated / size_max) + 1; + std::cerr << nb_subdivisions << " subdivision(s) for GPU processing" << std::endl; + + std::size_t idx = 0; + for (std::size_t n = 0; n < nb_subdivisions; ++ n) + { + std::vector indices; + indices.reserve (input.size() / nb_subdivisions); + for (std::size_t i = 0; i < input.size() / nb_subdivisions && idx < input.size(); ++ i) + indices.push_back(idx ++); + + std::vector > values; + classifier (indices, values); + + for(std::size_t i = 0; i < indices.size(); ++ i) + { + std::size_t nb_class_best = 0; + float val_class_best = 0.f; + + for (std::size_t j = 0; j < labels.size(); ++ j) + { + if(val_class_best < values[i][j]) + { + val_class_best = values[i][j]; + nb_class_best = j; + } + } + + output[indices[i]] = nb_class_best; + } + } +} +#endif +/// \endcond + +} + +} + +} + +#endif // CGAL_CLASSIFICATION_TENSORFLOW_NEURAL_NETWORK_CLASSIFIER_H diff --git a/Classification/include/CGAL/Classification/classify.h b/Classification/include/CGAL/Classification/classify.h index bf491b89c71..492d1855237 100644 --- a/Classification/include/CGAL/Classification/classify.h +++ b/Classification/include/CGAL/Classification/classify.h @@ -87,6 +87,53 @@ namespace internal { }; + template + class Classify_detailed_output_functor + { + const Label_set& m_labels; + const Classifier& m_classifier; + LabelIndexRange& m_out; + ProbabilitiesRanges& m_prob; + + public: + + Classify_detailed_output_functor (const Label_set& labels, + const Classifier& classifier, + LabelIndexRange& out, + ProbabilitiesRanges& prob) + : m_labels (labels), m_classifier (classifier), m_out (out), m_prob (prob) + { } + +#ifdef CGAL_LINKED_WITH_TBB + void operator()(const tbb::blocked_range& r) const + { + for (std::size_t s = r.begin(); s != r.end(); ++ s) + apply(s); + } +#endif // CGAL_LINKED_WITH_TBB + + inline void apply (std::size_t s) const + { + std::size_t nb_class_best=0; + std::vector values; + m_classifier (s, values); + + float val_class_best = 0.f; + for(std::size_t k = 0; k < m_labels.size(); ++ k) + { + m_prob[k][s] = values[k]; + if(val_class_best < values[k]) + { + val_class_best = values[k]; + nb_class_best = k; + } + } + + m_out[s] = static_cast(nb_class_best); + } + + }; + template class Classify_functor_local_smoothing_preprocessing { @@ -323,8 +370,6 @@ namespace internal { const Classifier& classifier, LabelIndexRange& output) { - output.resize(input.size()); - internal::Classify_functor f (labels, classifier, output); @@ -344,6 +389,39 @@ namespace internal { } } + /// \cond SKIP_IN_MANUAL + // variant to get a detailed output (not documented yet) + template + void classify (const ItemRange& input, + const Label_set& labels, + const Classifier& classifier, + LabelIndexRange& output, + ProbabilitiesRanges& probabilities) + { + internal::Classify_detailed_output_functor + f (labels, classifier, output, probabilities); + +#ifndef CGAL_LINKED_WITH_TBB + CGAL_static_assertion_msg (!(boost::is_convertible::value), + "Parallel_tag is enabled but TBB is unavailable."); +#else + if (boost::is_convertible::value) + { + tbb::parallel_for(tbb::blocked_range(0, input.size ()), f); + } + else +#endif + { + for (std::size_t i = 0; i < input.size(); ++ i) + f.apply(i); + } + } + /// \endcond + /*! \ingroup PkgClassificationMain @@ -388,8 +466,6 @@ namespace internal { const NeighborQuery& neighbor_query, LabelIndexRange& output) { - output.resize(input.size()); - std::vector > values (labels.size(), std::vector (input.size(), -1.)); internal::Classify_functor_local_smoothing_preprocessing diff --git a/Classification/test/Classification/deprecated_test_classification_point_set.cpp b/Classification/test/Classification/deprecated_test_classification_point_set.cpp index 45f5a92fdc3..46dc85b46a5 100644 --- a/Classification/test/Classification/deprecated_test_classification_point_set.cpp +++ b/Classification/test/Classification/deprecated_test_classification_point_set.cpp @@ -77,7 +77,7 @@ int main (int, char**) color_map, echo_map); assert (generator.number_of_scales() == 5); - assert (features.size() == 44); + assert (features.size() == 59); Label_set labels; diff --git a/Classification/test/Classification/test_classification_io.cpp b/Classification/test/Classification/test_classification_io.cpp index cc05ccfb110..83e782eb09d 100644 --- a/Classification/test/Classification/test_classification_io.cpp +++ b/Classification/test/Classification/test_classification_io.cpp @@ -28,7 +28,7 @@ typedef Classification::Feature_handle typedef Classification::Label_set Label_set; typedef Classification::Feature_set Feature_set; -typedef Classification::ETHZ_random_forest_classifier Classifier; +typedef Classification::ETHZ::Random_forest_classifier Classifier; typedef Classification::Planimetric_grid Planimetric_grid; typedef Classification::Point_set_neighborhood Neighborhood; @@ -87,13 +87,18 @@ int main (int, char**) std::ifstream inf ("output_config.gz", std::ios::binary); classifier2.load_configuration(inf); - std::vector label_indices; - std::vector label_indices_2; + Classifier classifier3 (classifier, features); + + std::vector label_indices (points.size()); + std::vector label_indices_2 (points.size()); + std::vector label_indices_3 (points.size()); Classification::classify (points, labels, classifier, label_indices); Classification::classify (points, labels, classifier2, label_indices_2); + Classification::classify (points, labels, classifier3, label_indices_3); assert (label_indices == label_indices_2); - + assert (label_indices == label_indices_3); + return EXIT_SUCCESS; } diff --git a/Classification/test/Classification/test_classification_point_set.cpp b/Classification/test/Classification/test_classification_point_set.cpp index f7092478a70..c60fe69b17d 100644 --- a/Classification/test/Classification/test_classification_point_set.cpp +++ b/Classification/test/Classification/test_classification_point_set.cpp @@ -91,7 +91,7 @@ int main (int, char**) #endif assert (generator.number_of_scales() == 5); - assert (features.size() == 44); + assert (features.size() == 59); Label_set labels; diff --git a/Documentation/doc/Documentation/Installation.txt b/Documentation/doc/Documentation/Installation.txt index b5ba993f4f5..59923355807 100644 --- a/Documentation/doc/Documentation/Installation.txt +++ b/Documentation/doc/Documentation/Installation.txt @@ -593,6 +593,22 @@ In \cgal, \sc{OpenCV} is used by the \ref PkgClassificationRef package. The \sc{OpenCV} web site is `http://opencv.org/`. +\subsection thirdpartyTensorFlow TensorFlow + +\sc{TensorFlow} is a library designed for machine learning and deep learning. + +In \cgal, the C++ API of \sc{TensorFlow} is used by the \ref +PkgClassificationRef package for neural network. The C++ API can be +compiled using CMake: it is distributed as part of the official +package and is located in `tensorflow/contrib/cmake`. Be sure to +enable and compile the following targets: + +- `tensorflow_BUILD_ALL_KERNELS` +- `tensorflow_BUILD_PYTHON_BINDINGS` +- `tensorflow_BUILD_SHARED_LIB`. + +The \sc{TensorFlow} web site is `https://www.tensorflow.org/`. + \subsection thirdpartyMETIS METIS \sc{METIS} is a library developed by the Karypis Lab diff --git a/GraphicsView/demo/Triangulation_2/Constrained_Delaunay_triangulation_2.cpp b/GraphicsView/demo/Triangulation_2/Constrained_Delaunay_triangulation_2.cpp index 818d9f04c69..3285004ecb1 100644 --- a/GraphicsView/demo/Triangulation_2/Constrained_Delaunay_triangulation_2.cpp +++ b/GraphicsView/demo/Triangulation_2/Constrained_Delaunay_triangulation_2.cpp @@ -22,6 +22,7 @@ #include #include #include +#include // Qt headers #include @@ -84,12 +85,12 @@ discoverInfiniteComponent(const CDT & ct) Face_handle fh = queue.front(); queue.pop_front(); fh->set_in_domain(false); - + for(int i = 0; i < 3; i++) { Face_handle fi = fh->neighbor(i); if(fi->is_in_domain() - && !ct.is_constrained(CDT::Edge(fh,i))) + && !ct.is_constrained(CDT::Edge(fh,i))) queue.push_back(fi); } } @@ -269,7 +270,7 @@ MainWindow::MainWindow() dgi->setFacesInDomainBrush(facesColor); QObject::connect(this, SIGNAL(changed()), - dgi, SLOT(modelChanged())); + dgi, SLOT(modelChanged())); dgi->setVerticesPen( QPen(Qt::red, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); dgi->setVoronoiPen( @@ -285,8 +286,8 @@ MainWindow::MainWindow() // the signal/slot mechanism pi = new CGAL::Qt::GraphicsViewPolylineInput(this, &scene, 0, true); // inputs polylines which are not closed QObject::connect(pi, SIGNAL(generate(CGAL::Object)), - this, SLOT(processInput(CGAL::Object))); - + this, SLOT(processInput(CGAL::Object))); + tcc = new CGAL::Qt::TriangulationCircumcircle(&scene, &cdt, this); tcc->setPen(QPen(Qt::red, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); @@ -298,8 +299,8 @@ MainWindow::MainWindow() // Manual handling of actions // QObject::connect(this->actionQuit, SIGNAL(triggered()), - this, SLOT(close())); - + this, SLOT(close())); + // We put mutually exclusive actions in an QActionGroup QActionGroup* ag = new QActionGroup(this); ag->addAction(this->actionInsertPolyline); @@ -338,7 +339,7 @@ MainWindow::MainWindow() this->addRecentFiles(this->menuFile, this->actionQuit); connect(this, SIGNAL(openRecentFile(QString)), - this, SLOT(open(QString))); + this, SLOT(open(QString))); } @@ -534,11 +535,11 @@ void MainWindow::on_actionLoadConstraints_triggered() { QString fileName = QFileDialog::getOpenFileName(this, - tr("Open Constraint File"), - ".", - tr("Edge files (*.edg);;" + tr("Open Constraint File"), + ".", + tr("Edge files (*.edg);;" "Plg files (*.plg);;" - "Poly files (*.poly)")); + "Poly files (*.poly)")); open(fileName); } @@ -655,12 +656,13 @@ void MainWindow::on_actionSaveConstraints_triggered() { QString fileName = QFileDialog::getSaveFileName(this, - tr("Save Constraints"), - ".", - tr("Poly files (*.poly)\n" - "Edge files (*.edg)")); + tr("Save Constraints"), + ".", + tr("Poly files (*.poly)\n" + "Edge files (*.edg)\n" + "VTU files (*.vtu)")); if(! fileName.isEmpty()){ - saveConstraints(fileName); + saveConstraints(fileName); } } @@ -669,7 +671,13 @@ void MainWindow::saveConstraints(QString fileName) { std::ofstream output(qPrintable(fileName)); - if (output) output << cdt; + + if(!fileName.endsWith("vtu") && output) + output << cdt; + else if (output) + { + CGAL::write_vtu(output, cdt); + } } @@ -796,15 +804,15 @@ MainWindow::on_actionInsertRandomPoints_triggered() bool ok = false; const int number_of_points = - QInputDialog::getInt(this, - tr("Number of random points"), - tr("Enter number of random points"), - 100, - 0, - (std::numeric_limits::max)(), - 1, - &ok); - + QInputDialog::getInt(this, + tr("Number of random points"), + tr("Enter number of random points"), + 100, + 0, + (std::numeric_limits::max)(), + 1, + &ok); + if(!ok) { return; } diff --git a/Installation/CHANGES.md b/Installation/CHANGES.md index 742d68f89e2..97f29df9e86 100644 --- a/Installation/CHANGES.md +++ b/Installation/CHANGES.md @@ -64,6 +64,24 @@ Release date: March 2019 original behavior (using one unique and automatically selected seed) is kept if this parameter is not used. +### Classification + +- Added a new experimental classifier + `TensorFlow::Neural_network_classifier`. + +- For uniformity, `ETHZ_random_forest_classifier` is renamed + `ETHZ::Random_forest_classifier` and `OpenCV_random_forest_classifier` + is renamed `OpenCV::Random_forest_classifier`. + +- The training algorithm of `ETHZ::Random_forest_classifier` was + parallelized. + +- Added a constructor to copy a `ETHZ::Random_forest_classifier` using a + different data set as input. + +- Added 3 new geometric features, `Height_above`, `Height_below` and + `Vertical_range`. + ### 3D Fast Intersection and Distance Computation - The primitives `AABB_face_graph_triangle_primitive` and @@ -86,6 +104,12 @@ Release date: March 2019 `Arr_polyline_traits_2`, `Arr_polycurve_traits_2`, and `Arr_polycurve_basic_traits_2`. +### 2D and 3D Mesh Generation + +- Added two functions for writing in XML VTK formats: + - `CGAL::write_vtu()`, that writes a 2D mesh in a `.vtu` file, + - `CGAL::output_to_vtu()`, that writes a 3D mesh in a `.vtu` file. + ### 2D Minkowski Sums - Fixed a bug in the function that computed the Minkowski sum using the @@ -94,7 +118,10 @@ Release date: March 2019 ### CGAL and the Boost Graph Library (BGL) -- Add function `write_wrl()` for writing into VRML 2.0 format. +- Added function `write_wrl()` for writing into VRML 2.0 format. +- Added functions `CGAL::write_vtp()` for writing a triangulated + face graph in a `.vtp` file (XML VTK format). + Release 4.13 diff --git a/Installation/CMakeLists.txt b/Installation/CMakeLists.txt index 88e41c1c455..f40f327b608 100644 --- a/Installation/CMakeLists.txt +++ b/Installation/CMakeLists.txt @@ -108,11 +108,13 @@ else ( CGAL_BRANCH_BUILD ) # Enable testing with BUILD_TESTING option(BUILD_TESTING "Build the testing tree." OFF) - include(CTest) if(BUILD_TESTING AND NOT POLICY CMP0064) message(FATAL_ERROR "CGAL support of CTest requires CMake version 3.4 or later. The variable BUILD_TESTING must be set of OFF.") endif() + if(BUILD_TESTING) + enable_testing() + endif() endif (CGAL_BRANCH_BUILD ) #message(STATUS "Packages found: ${CGAL_CONFIGURED_PACKAGES}") diff --git a/Installation/cmake/modules/CGAL_SetupCGAL_CoreDependencies.cmake b/Installation/cmake/modules/CGAL_SetupCGAL_CoreDependencies.cmake index e22308e0025..66e7007f3d1 100644 --- a/Installation/cmake/modules/CGAL_SetupCGAL_CoreDependencies.cmake +++ b/Installation/cmake/modules/CGAL_SetupCGAL_CoreDependencies.cmake @@ -56,7 +56,7 @@ endif() # See the release notes of CGAL-4.10: CGAL_Core now requires # Boost.Thread, with all compilers but MSVC. if (NOT MSVC) - find_package( Boost 1.48 REQUIRED thread system ) + find_package( Boost 1.48 REQUIRED COMPONENTS thread system ) endif() function(CGAL_setup_CGAL_Core_dependencies target) diff --git a/Installation/cmake/modules/CGAL_add_test.cmake b/Installation/cmake/modules/CGAL_add_test.cmake index 2f0aec7163a..adf2430ff66 100644 --- a/Installation/cmake/modules/CGAL_add_test.cmake +++ b/Installation/cmake/modules/CGAL_add_test.cmake @@ -3,6 +3,8 @@ if(CGAL_add_test_included) endif(CGAL_add_test_included) set(CGAL_add_test_included TRUE) +option(BUILD_TESTING "Build the testing tree." OFF) + if(NOT POLICY CMP0064) # CMake <= 3.3 if(BUILD_TESTING) @@ -19,7 +21,9 @@ if(NOT POLICY CMP0064) return() endif() -include(CTest) +if(BUILD_TESTING) + enable_testing() +endif() cmake_policy(SET CMP0064 NEW) diff --git a/Installation/cmake/modules/FindTensorFlow.cmake b/Installation/cmake/modules/FindTensorFlow.cmake new file mode 100644 index 00000000000..2d63a0ea237 --- /dev/null +++ b/Installation/cmake/modules/FindTensorFlow.cmake @@ -0,0 +1,25 @@ +include(FindPackageHandleStandardArgs) + +unset(TENSORFLOW_FOUND) + +find_path(TensorFlow_INCLUDE_DIR + NAMES + tensorflow/core + tensorflow/cc + third_party + HINTS + /usr/include/ + /usr/local/include/) + +find_library(TensorFlow_LIBRARY NAMES tensorflow_all + HINTS + /usr/lib + /usr/local/lib) + +find_package_handle_standard_args(TensorFlow DEFAULT_MSG TensorFlow_INCLUDE_DIR TensorFlow_LIBRARY) + +if(TENSORFLOW_FOUND) + set(TensorFlow_LIBRARIES ${TensorFlow_LIBRARY}) + set(TensorFlow_INCLUDE_DIRS ${TensorFlow_INCLUDE_DIR}) +endif() + diff --git a/Installation/cmake/modules/list_of_whitelisted_headers.cmake b/Installation/cmake/modules/list_of_whitelisted_headers.cmake index c6bfe0e3adb..c9a2155e50f 100644 --- a/Installation/cmake/modules/list_of_whitelisted_headers.cmake +++ b/Installation/cmake/modules/list_of_whitelisted_headers.cmake @@ -1,4 +1,5 @@ set(list_of_whitelisted_headers_txt [=[ + CGAL/Classification/TensorFlow/Neural_network_classifier.h CGAL/Linear_cell_complex_constructors.h CGAL/CGAL_Ipelet_base.h CGAL/IO/read_las_points.h diff --git a/Mesh_2/doc/Mesh_2/CGAL/IO/write_vtu.h b/Mesh_2/doc/Mesh_2/CGAL/IO/write_vtu.h new file mode 100644 index 00000000000..146cb6bb785 --- /dev/null +++ b/Mesh_2/doc/Mesh_2/CGAL/IO/write_vtu.h @@ -0,0 +1,19 @@ +namespace CGAL{ +//!\ingroup PkgMesh2IO +//! \brief writes the faces of a domain and its constrained edges embedded in +//! a 2D constrained Delaunay triangulation using the `PolyData` XML format. +//! +//! The faces output are those for which `DelaunayMeshFaceBase_2::is_in_domain()` returns `true`, +//! the edges are those for which `ConstrainedTriangulationFaceBase_2::is_constrained()` returns `true`. +//! \tparam CDT a `Constrained_Delaunay_triangulation_2` with face type model of `DelaunayMeshFaceBase_2`. +//! +//! \param os the stream used for writing. +//! \param tr the triangulated domain to be written. +//! \param mode decides if the data should be written in binary (`IO::BINARY`) +//! or in ASCII (`IO::ASCII`). +//! +template +void write_vtu(std::ostream& os, + const CDT& tr, + IO::Mode mode = IO::BINARY); +} diff --git a/Mesh_2/doc/Mesh_2/PackageDescription.txt b/Mesh_2/doc/Mesh_2/PackageDescription.txt index 96c93298c8b..313f3901185 100644 --- a/Mesh_2/doc/Mesh_2/PackageDescription.txt +++ b/Mesh_2/doc/Mesh_2/PackageDescription.txt @@ -11,6 +11,11 @@ /// \defgroup PkgMesh2Enum Enumerations /// \ingroup PkgMesh2Ref +/// \defgroup PkgMesh2IO I/O Functions +/// \ingroup PkgMesh2Ref +/// In addition to the stream extraction and insertion operators for +/// %CGAL 2D triangulations, the following functions can be used. + /*! \addtogroup PkgMesh2Ref \cgalPkgDescriptionBegin{2D Conforming Triangulations and Meshes,PkgMesh2} @@ -58,6 +63,9 @@ The package can handle intersecting input constraints and set no restriction on - `CGAL::refine_Delaunay_mesh_2` - `CGAL::lloyd_optimize_mesh_2` +## I/O Functions ## +- `CGAL::write_vtu()` + ## Enumerations ## - `CGAL::Mesh_optimization_return_code` diff --git a/Mesh_2/include/CGAL/IO/write_vtu.h b/Mesh_2/include/CGAL/IO/write_vtu.h new file mode 100644 index 00000000000..bab5d5b4c11 --- /dev/null +++ b/Mesh_2/include/CGAL/IO/write_vtu.h @@ -0,0 +1,387 @@ +// Copyright (c) 2018 GeometryFactory (France). +// Copyright (c) 2004-2006 INRIA Sophia-Antipolis (France). +// Copyright (c) 2009 INRIA Sophia-Antipolis (France). +// All rights reserved. +// +// This file is part of CGAL (www.cgal.org). +// You can redistribute it and/or modify it under the terms of the GNU +// General Public License as published by the Free Software Foundation, +// either version 3 of the License, or (at your option) any later version. +// +// 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$ +// $Id$ +// SPDX-License-Identifier: GPL-3.0+ +// +// +// Author(s) : Laurent RINEAU, Stephane Tayeb, Maxime Gimeno + +#ifndef CGAL_WRITE_VTU_H +#define CGAL_WRITE_VTU_H + +#include + +#include +#include +#include +#include +#include +#include + +//todo try to factorize with functors +namespace CGAL{ +// writes the appended data into the .vtu file +template +void +write_vector(std::ostream& os, + const std::vector& vect) +{ + const char* buffer = reinterpret_cast(&(vect[0])); + std::size_t size = vect.size()*sizeof(FT); + + os.write(reinterpret_cast(&size), sizeof(std::size_t)); // number of bytes encoded + os.write(buffer, vect.size()*sizeof(FT)); // encoded data +} + +// writes the cells tags before binary data is appended + +template +void +write_cells_tag_2(std::ostream& os, + const CDT & tr, + std::size_t number_of_triangles, + std::map & V, + bool binary, + std::size_t& offset) +{ + std::string formatattribute = + binary ? " format=\"appended\"" : " format=\"ascii\""; + + std::string typeattribute; + switch(sizeof(std::size_t)) { + case 8: typeattribute = " type=\"UInt64\""; break; + case 4: typeattribute = " type=\"UInt32\""; break; + default: CGAL_error_msg("Unknown size of std::size_t"); + } + + // Write connectivity table + os << " \n" + << " \n"; + // 3 indices (size_t) per triangle + length of the encoded data (size_t) + offset += (3 * number_of_triangles + 1) * sizeof(std::size_t); + // 2 indices (size_t) per edge (size_t) + offset += (2 * std::distance(tr.constrained_edges_begin(), + tr.constrained_edges_end())) * sizeof(std::size_t); + } + else { + os << "\">\n"; + for(typename CDT::Finite_faces_iterator + fit = tr.finite_faces_begin(), + end = tr.finite_faces_end(); + fit != end; ++fit) + { + if(fit->is_in_domain()) + { + os << V[fit->vertex(0)] << " "; + os << V[fit->vertex(2)] << " "; + os << V[fit->vertex(1)] << " "; + } + } + os << " \n"; + } + + // Write offsets + os << " \n"; + offset += (number_of_triangles +std::distance(tr.constrained_edges_begin(), + tr.constrained_edges_end()) + 1) + * sizeof(std::size_t); + // 1 offset (size_t) per cell + length of the encoded data (size_t) + } + else { + os << "\">\n"; + std::size_t cells_offset = 0; + for(typename CDT::Finite_faces_iterator fit = + tr.finite_faces_begin() ; + fit != tr.finite_faces_end() ; + ++fit ) + { + if(fit->is_in_domain()) + { + cells_offset += 3; + os << cells_offset << " "; + } + } + os << " \n"; + } + + // Write cell type (triangles == 5) + os << " \n"; + offset += number_of_triangles + + std::distance(tr.constrained_edges_begin(), + tr.constrained_edges_end()) + + sizeof(std::size_t); + // 1 unsigned char per cell + length of the encoded data (size_t) + } + else { + os << "\">\n"; + for(typename CDT::Finite_faces_iterator fit = + tr.finite_faces_begin() ; + fit != tr.finite_faces_end() ; + ++fit ) + { + if(fit->is_in_domain()) + { + os << "5 "; + } + } + os << " \n"; + } + os << " \n"; +} + +// writes the cells appended data at the end of the .vtu file +template +void +write_cells_2(std::ostream& os, + const CDT & tr, + std::size_t number_of_triangles, + std::map & V) +{ + std::vector connectivity_table; + std::vector offsets; + std::vector cell_type(number_of_triangles,5); // triangles == 5 + cell_type.resize(cell_type.size() + std::distance(tr.constrained_edges_begin(), + tr.constrained_edges_end()), 3); // line == 3 + + std::size_t off = 0; + for(typename CDT::Finite_faces_iterator + fit = tr.finite_faces_begin(), + end = tr.finite_faces_end(); + fit != end; ++fit) + { + if(fit->is_in_domain()) + { + off += 3; + offsets.push_back(off); + connectivity_table.push_back(V[fit->vertex(0)]); + connectivity_table.push_back(V[fit->vertex(2)]); + connectivity_table.push_back(V[fit->vertex(1)]); + } + } + for(typename CDT::Constrained_edges_iterator + cei = tr.constrained_edges_begin(), + end = tr.constrained_edges_end(); + cei != end; ++cei) + { + off += 2; + offsets.push_back(off); + for(int i=0; i<3; ++i) + { + if(i != cei->second) + connectivity_table.push_back(V[cei->first->vertex(i)]); + } + } + write_vector(os,connectivity_table); + write_vector(os,offsets); + write_vector(os,cell_type); +} + +// writes the points tags before binary data is appended +template +void +write_cdt_points_tag(std::ostream& os, + const Tr & tr, + std::map & V, + bool binary, + std::size_t& offset) +{ + std::size_t dim = 2; + typedef typename Tr::Finite_vertices_iterator Finite_vertices_iterator; + typedef typename Tr::Geom_traits Gt; + typedef typename Gt::FT FT; + + std::size_t inum = 0; + std::string format = binary ? "appended" : "ascii"; + std::string type = (sizeof(FT) == 8) ? "Float64" : "Float32"; + + os << " \n" + << " \n"; + offset += 3 * tr.number_of_vertices() * sizeof(FT) + sizeof(std::size_t); + // dim coords per points + length of the encoded data (size_t) + } + else { + os << "\">\n"; + for( Finite_vertices_iterator vit = tr.finite_vertices_begin(); + vit != tr.finite_vertices_end(); + ++vit) + { + V[vit] = inum++; + os << vit->point()[0] << " "; + os << vit->point()[1] << " "; + if(dim == 3) + os << vit->point()[2] << " "; + else + os << 0.0 << " "; + } + os << " \n"; + } + os << " \n"; +} + +// writes the points appended data at the end of the .vtu file +template +void +write_cdt_points(std::ostream& os, + const Tr & tr, + std::map & V) +{ + std::size_t dim = 2; + typedef typename Tr::Finite_vertices_iterator Finite_vertices_iterator; + typedef typename Tr::Geom_traits Gt; + typedef typename Gt::FT FT; + + std::size_t inum = 0; + std::vector coordinates; + for( Finite_vertices_iterator vit = tr.finite_vertices_begin(); + vit != tr.finite_vertices_end(); + ++vit) + { + V[vit] = inum++; // binary output => the map has not been filled yet + coordinates.push_back(vit->point()[0]); + coordinates.push_back(vit->point()[1]); + coordinates.push_back(dim == 3 ? vit->point()[2] : 0.0); + } + write_vector(os,coordinates); +} + +// writes the attribute tags before binary data is appended +template +void +write_attribute_tag_2 (std::ostream& os, + const std::string& attr_name, + const std::vector& attribute, + bool binary, + std::size_t& offset) +{ + std::string format = binary ? "appended" : "ascii"; + std::string type = (sizeof(T) == 8) ? "Float64" : "Float32"; + os << " \n"; + offset += attribute.size() * sizeof(T) + sizeof(std::size_t); + } + else { + typedef typename std::vector::const_iterator Iterator; + os << "\">\n"; + for (Iterator it = attribute.begin(); + it != attribute.end(); + ++it ) + os << *it << " "; + os << " \n"; + } +} + +// writes the attributes appended data at the end of the .vtu file +template +void +write_attributes_2(std::ostream& os, + const std::vector& att) +{ + write_vector(os,att); +} + +template +void write_vtu_with_attributes(std::ostream& os, + const CDT& tr, + std::vector*> >& attributes, + IO::Mode mode = IO::BINARY) +{ + typedef typename CDT::Vertex_handle Vertex_handle; + std::map V; + //write header + os << "\n" + << "\n" + << " " << "\n"; + + int number_of_triangles = 0; + for(typename CDT::Finite_faces_iterator + fit = tr.finite_faces_begin(), + end = tr.finite_faces_end(); + fit != end; ++fit) + { + if(fit->is_in_domain()) ++number_of_triangles; + } + os << " \n"; + std::size_t offset = 0; + const bool binary = (mode == IO::BINARY); + write_cdt_points_tag(os,tr,V,binary,offset); + write_cells_tag_2(os,tr,number_of_triangles, V,binary,offset); + if(attributes.empty()) + os << " \n"; + else + os << " \n"; + for(std::size_t i = 0; i< attributes.size(); ++i) + { + write_attribute_tag_2(os,attributes[i].first, *attributes[i].second, binary,offset); + } + os << " \n"; + os << " \n" + << " \n"; + if (binary) { + os << "\n_"; + write_cdt_points(os,tr,V); // write points before cells to fill the std::map V + write_cells_2(os,tr, number_of_triangles, V); + for(std::size_t i = 0; i< attributes.size(); ++i) + write_attributes_2(os, *attributes[i].second); + } + os << "\n"; +} + + +template +void write_vtu(std::ostream& os, + const CDT& tr, + IO::Mode mode = IO::BINARY) +{ + std::vector*> > dummy_atts; + write_vtu_with_attributes(os, tr, dummy_atts, mode); +} + +} //end CGAL +#endif // CGAL_WRITE_VTU_H diff --git a/Mesh_3/doc/Mesh_3/CGAL/IO/output_to_vtu.h b/Mesh_3/doc/Mesh_3/CGAL/IO/output_to_vtu.h new file mode 100644 index 00000000000..70a64f586c7 --- /dev/null +++ b/Mesh_3/doc/Mesh_3/CGAL/IO/output_to_vtu.h @@ -0,0 +1,17 @@ +namespace CGAL{ +//! \ingroup PkgMesh3IOFunctions +//! +//! \brief writes a tetrahedron mesh using the `UnstructuredGrid` XML format. +//! +//! \tparam C3T3 a model of `MeshComplexWithFeatures_3InTriangulation_3`. +//! +//! \param os the stream used for writing. +//! \param c3t3 the instance of `C3T3` to be written. +//! \param mode decides if the data should be written in binary (`IO::BINARY`) +//! or in ASCII (`IO::ASCII`). +//! +template +void output_to_vtu(std::ostream& os, + const C3T3& c3t3, + IO::Mode mode = IO::BINARY); +} diff --git a/Mesh_3/doc/Mesh_3/Doxyfile.in b/Mesh_3/doc/Mesh_3/Doxyfile.in index 0a6229c8c69..eafd3c94e7a 100644 --- a/Mesh_3/doc/Mesh_3/Doxyfile.in +++ b/Mesh_3/doc/Mesh_3/Doxyfile.in @@ -1,5 +1,19 @@ @INCLUDE = ${CGAL_DOC_PACKAGE_DEFAULTS} +# macros to be used inside the code +ALIASES += "cgalNamedParamsBegin=
Named Parameters
" +ALIASES += "cgalNamedParamsEnd=
" +ALIASES += "cgalParamBegin{1}=\ref PMP_\1 \"\1\"" +ALIASES += "cgalParamEnd=" +ALIASES += "cgalDescribePolylineType=A polyline is defined as a sequence of points, each pair of contiguous points defines a segment of the polyline. If the first and last points of the polyline are identical, the polyline is closed." + +#macros for NamedParameters.txt +ALIASES += "cgalNPTableBegin=
" +ALIASES += "cgalNPTableEnd=
" +ALIASES += "cgalNPBegin{1}=\1 " +ALIASES += "cgalNPEnd=" + + INPUT += \ ${CGAL_PACKAGE_INCLUDE_DIR}/CGAL/Polyhedral_complex_mesh_domain_3.h \ ${CGAL_PACKAGE_INCLUDE_DIR}/CGAL/Mesh_domain_with_polyline_features_3.h diff --git a/Mesh_3/doc/Mesh_3/PackageDescription.txt b/Mesh_3/doc/Mesh_3/PackageDescription.txt index 92b9dc3711f..d67297572cd 100644 --- a/Mesh_3/doc/Mesh_3/PackageDescription.txt +++ b/Mesh_3/doc/Mesh_3/PackageDescription.txt @@ -139,6 +139,6 @@ and their associated classes: ## Input/Output Functions ## - `CGAL::output_to_medit()` - +- `CGAL::output_to_vtu()` */ diff --git a/Mesh_3/include/CGAL/IO/Complex_3_in_triangulation_3_to_vtk.h b/Mesh_3/include/CGAL/IO/Complex_3_in_triangulation_3_to_vtk.h index 8b9cd7e7520..8370bab261f 100644 --- a/Mesh_3/include/CGAL/IO/Complex_3_in_triangulation_3_to_vtk.h +++ b/Mesh_3/include/CGAL/IO/Complex_3_in_triangulation_3_to_vtk.h @@ -50,7 +50,7 @@ output_c3t3_to_vtk_unstructured_grid(const C3T3& c3t3, vtkCellArray* const vtk_facets = vtkCellArray::New(); vtkCellArray* const vtk_cells = vtkCellArray::New(); - vtk_points->Allocate(c3t3.triangulation().number_of_vertices()); + vtk_points->Allocate(c3t3.triangulation().number_of_vertices()- c3t3.number_of_far_points()); vtk_facets->Allocate(c3t3.number_of_facets_in_complex()); vtk_cells->Allocate(c3t3.number_of_cells_in_complex()); @@ -64,11 +64,14 @@ output_c3t3_to_vtk_unstructured_grid(const C3T3& c3t3, ++vit) { typedef typename Triangulation::Weighted_point Weighted_point; - const Weighted_point& p = tr.point(vit); - vtk_points->InsertNextPoint(CGAL::to_double(p.x()), - CGAL::to_double(p.y()), - CGAL::to_double(p.z())); - V[vit] = inum++; + if(vit->in_dimension() > -1) + { + const Weighted_point& p = tr.point(vit); + vtk_points->InsertNextPoint(CGAL::to_double(p.x()), + CGAL::to_double(p.y()), + CGAL::to_double(p.z())); + V[vit] = inum++; + } } for(typename C3T3::Facets_in_complex_iterator fit = c3t3.facets_in_complex_begin(), diff --git a/Mesh_3/include/CGAL/IO/output_to_vtu.h b/Mesh_3/include/CGAL/IO/output_to_vtu.h new file mode 100644 index 00000000000..5c9583ba272 --- /dev/null +++ b/Mesh_3/include/CGAL/IO/output_to_vtu.h @@ -0,0 +1,336 @@ +// Copyright (c) 2018 GeometryFactory (France). +// Copyright (c) 2004-2006 INRIA Sophia-Antipolis (France). +// Copyright (c) 2009 INRIA Sophia-Antipolis (France). +// All rights reserved. +// +// This file is part of CGAL (www.cgal.org). +// You can redistribute it and/or modify it under the terms of the GNU +// General Public License as published by the Free Software Foundation, +// either version 3 of the License, or (at your option) any later version. +// +// 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$ +// $Id$ +// SPDX-License-Identifier: GPL-3.0+ +// +// Author(s) : Laurent RINEAU, Stephane Tayeb, Maxime Gimeno + +#ifndef CGAL_OUTPUT_TO_VTU_H +#define CGAL_OUTPUT_TO_VTU_H + +#include + + +#include +#include +#include +#include +#include +#include + +//todo try to factorize with functors +namespace CGAL{ + +template +void +write_cells_tag(std::ostream& os, + const C3T3 & c3t3, + std::map & V, + bool binary, + std::size_t& offset) +{ + typedef typename C3T3::Cells_in_complex_iterator Cell_iterator; + std::string formatattribute = + binary ? " format=\"appended\"" : " format=\"ascii\""; + + std::string typeattribute; + switch(sizeof(std::size_t)) { + case 8: typeattribute = " type=\"UInt64\""; break; + case 4: typeattribute = " type=\"UInt32\""; break; + default: CGAL_error_msg("Unknown size of std::size_t"); + } + + // Write connectivity table + os << " \n" + << " \n"; + offset += (4 * c3t3.number_of_cells() + 1) * sizeof(std::size_t); + // 4 indices (size_t) per cell + length of the encoded data (size_t) + } + else { + os << "\">\n"; + for( Cell_iterator cit = c3t3.cells_in_complex_begin() ; + cit != c3t3.cells_in_complex_end() ; + ++cit ) + { + for (int i=0; i<4; i++) + os << V[cit->vertex(i)] << " "; + } + os << " \n"; + } + + // Write offsets + os << " \n"; + offset += (c3t3.number_of_cells() + 1) * sizeof(std::size_t); + // 1 offset (size_t) per cell + length of the encoded data (size_t) + } + else { + os << "\">\n"; + std::size_t cells_offset = 0; + for( Cell_iterator cit = c3t3.cells_in_complex_begin() ; + cit != c3t3.cells_in_complex_end() ; + ++cit ) + { + cells_offset += 4; + os << cells_offset << " "; + } + os << " \n"; + } + + // Write cell type (tetrahedra == 10) + os << " \n"; + offset += c3t3.number_of_cells() + sizeof(std::size_t); + // 1 unsigned char per cell + length of the encoded data (size_t) + } + else { + os << "\">\n"; + for( Cell_iterator cit = c3t3.cells_in_complex_begin() ; + cit != c3t3.cells_in_complex_end() ; + ++cit ) + os << "10 "; + os << " \n"; + } + os << " \n"; +} + + +template +void +write_cells(std::ostream& os, + const C3T3 & c3t3, + std::map & V) +{ + typedef typename C3T3::Cells_in_complex_iterator Cell_iterator; + std::vector connectivity_table; + std::vector offsets; + std::vector cell_type(c3t3.number_of_cells(),10); // tetrahedra == 10 + std::size_t off = 0; + for( Cell_iterator cit = c3t3.cells_in_complex_begin() ; + cit != c3t3.cells_in_complex_end() ; + ++cit ) + { + off += 4; + offsets.push_back(off); + for (int i=0; i<4; i++) + connectivity_table.push_back(V[cit->vertex(i)]); + } + write_vector(os,connectivity_table); + write_vector(os,offsets); + write_vector(os,cell_type); +} + + +template +void +write_c3t3_points_tag(std::ostream& os, + const Tr & tr, + std::size_t size_of_vertices, + std::map & V, + bool binary, + std::size_t& offset) +{ + std::size_t dim = 3; + typedef typename Tr::Finite_vertices_iterator Finite_vertices_iterator; + typedef typename Tr::Geom_traits Gt; + typedef typename Gt::FT FT; + + std::size_t inum = 0; + std::string format = binary ? "appended" : "ascii"; + std::string type = (sizeof(FT) == 8) ? "Float64" : "Float32"; + + os << " \n" + << " \n"; + offset += 3 * size_of_vertices * sizeof(FT) + sizeof(std::size_t); + // dim coords per points + length of the encoded data (size_t) + } + else { + os << "\">\n"; + for( Finite_vertices_iterator vit = tr.finite_vertices_begin(); + vit != tr.finite_vertices_end(); + ++vit) + { + if(vit->in_dimension() <= -1) continue; + V[vit] = inum++; + os << vit->point()[0] << " "; + os << vit->point()[1] << " "; + if(dim == 3) + os << vit->point()[2] << " "; + else + os << 0.0 << " "; + } + os << " \n"; + } + os << " \n"; +} + +// writes the points appended data at the end of the .vtu file +template +void +write_c3t3_points(std::ostream& os, + const Tr & tr, + std::map & V) +{ + std::size_t dim = 3; + typedef typename Tr::Finite_vertices_iterator Finite_vertices_iterator; + typedef typename Tr::Geom_traits Gt; + typedef typename Gt::FT FT; + + std::size_t inum = 0; + std::vector coordinates; + for( Finite_vertices_iterator vit = tr.finite_vertices_begin(); + vit != tr.finite_vertices_end(); + ++vit) + { + if(vit->in_dimension() <= -1) continue; + V[vit] = inum++; // binary output => the map has not been filled yet + coordinates.push_back(vit->point()[0]); + coordinates.push_back(vit->point()[1]); + coordinates.push_back(dim == 3 ? vit->point()[2] : 0.0); + } + write_vector(os,coordinates); +} + +// writes the attribute tags before binary data is appended +template +void +write_attribute_tag(std::ostream& os, + const std::string& attr_name, + const std::vector& attribute, + bool binary, + std::size_t& offset) +{ + std::string format = binary ? "appended" : "ascii"; + std::string type = (sizeof(T) == 8) ? "Float64" : "Float32"; + os << " \n"; + offset += attribute.size() * sizeof(T) + sizeof(std::size_t); + } + else { + typedef typename std::vector::const_iterator Iterator; + os << "\">\n"; + for (Iterator it = attribute.begin(); + it != attribute.end(); + ++it ) + os << *it << " "; + os << " \n"; + } +} + +// writes the attributes appended data at the end of the .vtu file +template +void +write_attributes(std::ostream& os, + const std::vector& att) +{ + write_vector(os,att); +} + +template +void output_to_vtu_with_attributes(std::ostream& os, + const C3T3& c3t3, + std::vector*> >& attributes, + IO::Mode mode = IO::BINARY) +{ + typedef typename C3T3::Triangulation Tr; + typedef typename Tr::Vertex_handle Vertex_handle; + const Tr& tr = c3t3.triangulation(); + std::map V; + //write header + os << "\n" + << "\n" + << " " << "\n"; + const std::size_t number_of_vertices = + tr.number_of_vertices() - c3t3.number_of_far_points(); + os << " \n"; + std::size_t offset = 0; + + const bool binary = (mode == IO::BINARY); + write_c3t3_points_tag(os,tr,number_of_vertices,V,binary,offset); + write_cells_tag(os,c3t3,V,binary,offset); // fills V if the mode is ASCII + os << " \n"; + for(std::size_t i = 0; i< attributes.size(); ++i) + { + write_attribute_tag(os,attributes[i].first, *attributes[i].second, binary,offset); + } + os << " \n"; + os << " \n" + << " \n"; + if (binary) { + os << "\n_"; + write_c3t3_points(os,tr,V); // fills V if the mode is BINARY + write_cells(os,c3t3,V); + for(std::size_t i = 0; i< attributes.size(); ++i) + write_attributes(os, *attributes[i].second); + } + os << "\n"; +} + + + +//public API +template +void output_to_vtu(std::ostream& os, + const C3T3& c3t3, + IO::Mode mode = IO::BINARY) +{ + typedef typename C3T3::Cells_in_complex_iterator Cell_iterator; + std::vector mids; + for( Cell_iterator cit = c3t3.cells_in_complex_begin() ; + cit != c3t3.cells_in_complex_end() ; + ++cit ) + { + mids.push_back(cit->subdomain_index()); + } + std::vector* > > atts; + atts.push_back(std::make_pair("MeshDomain", &mids)); + output_to_vtu_with_attributes(os, c3t3, atts, mode); +} + +} //end CGAL +#endif // CGAL_VTK_IO_H diff --git a/Nef_2/include/CGAL/Nef_2/HDS_items.h b/Nef_2/include/CGAL/Nef_2/HDS_items.h index 1265cb2eb87..25b7da232d1 100644 --- a/Nef_2/include/CGAL/Nef_2/HDS_items.h +++ b/Nef_2/include/CGAL/Nef_2/HDS_items.h @@ -389,7 +389,9 @@ public: hit->reset_fcit(); for (Isolated_vertex_iterator vit = iv_begin(); vit!=iv_end(); ++vit) vit->reset_ivit(); - FC.clear(); IV.clear(); } + FC.clear(); IV.clear(); + _e=Halfedge_handle(); + } /*{\Mtext There are the same iterator ranges defined for the const iterators |Hole_const_iterator|, |Isolated_vertex_const_iterator|. diff --git a/Nef_2/include/CGAL/Nef_2/PM_const_decorator.h b/Nef_2/include/CGAL/Nef_2/PM_const_decorator.h index 2e0f62cb940..5f4b92ef5d2 100644 --- a/Nef_2/include/CGAL/Nef_2/PM_const_decorator.h +++ b/Nef_2/include/CGAL/Nef_2/PM_const_decorator.h @@ -473,7 +473,7 @@ check_integrity_and_topological_planarity(bool faces) const int fc_num(0),iv_num(0); Face_const_iterator fit; for (fit = faces_begin(); fit != faces_end(); ++fit) { - if (!first) { + if (!first && halfedge(fit)!=Halfedge_const_handle()) { CGAL_assertion( face(halfedge(fit))==fit ); ++fc_num; } Hole_const_iterator fcit; diff --git a/Number_types/include/CGAL/boost_mp.h b/Number_types/include/CGAL/boost_mp.h index cae81077612..edaa005a8e7 100644 --- a/Number_types/include/CGAL/boost_mp.h +++ b/Number_types/include/CGAL/boost_mp.h @@ -57,6 +57,9 @@ # include #endif +#ifdef CGAL_USE_MPFR +# include +#endif // TODO: work on the coercions (end of the file) @@ -136,6 +139,13 @@ struct AST_boost_mp +struct Algebraic_structure_traits > +: AST_boost_mp > {}; +template +struct Algebraic_structure_traits > +: Algebraic_structure_traits::result_type > {}; + // Real_embeddable_traits template @@ -193,11 +203,22 @@ struct RET_boost_mp_base : public CGAL::cpp98::unary_function< Type, std::pair< double, double > > { std::pair operator()(const Type& x) const { + // See if https://github.com/boostorg/multiprecision/issues/108 suggests anything better // assume the conversion is within 1 ulp // adding IA::smallest() doesn't work because inf-e=inf, even rounded down. - double d = x.template convert_to(); + double i = x.template convert_to(); + double s = i; double inf = std::numeric_limits::infinity(); - return std::pair (nextafter (d, -inf), nextafter (d, inf)); + int cmp = x.compare(i); + if (cmp > 0) { + s = nextafter(s, +inf); + CGAL_assertion(x.compare(s) < 0); + } + else if (cmp < 0) { + i = nextafter(i, -inf); + CGAL_assertion(x.compare(i) > 0); + } + return std::pair (i, s); } }; }; @@ -211,26 +232,93 @@ struct RET_boost_mp struct RET_boost_mp > - : RET_boost_mp_base { -#if BOOST_VERSION < 105700 - typedef NT Type; + : RET_boost_mp_base {}; + +#ifdef CGAL_USE_MPFR +// Because of these full specializations, things get instantiated more eagerly. Make them artificially partial if necessary. +template <> +struct RET_boost_mp + : RET_boost_mp_base { + typedef boost::multiprecision::mpz_int Type; struct To_interval : public CGAL::cpp98::unary_function< Type, std::pair< double, double > > { std::pair operator()(const Type& x) const { - std::pair p_num = CGAL::to_interval (numerator (x)); - std::pair p_den = CGAL::to_interval (denominator (x)); - typedef Interval_nt IA; - IA::Protector P; - // assume the conversion is within 1 ulp for integers, but the conversion from rational may be unsafe, see boost trac #10085 - IA i_num (p_num.first, p_num.second); - IA i_den (p_den.first, p_den.second); - IA i = i_num / i_den; - return std::pair(i.inf(), i.sup()); +#if MPFR_VERSION_MAJOR >= 3 + MPFR_DECL_INIT (y, 53); /* Assume IEEE-754 */ + int r = mpfr_set_z (y, x.backend().data(), MPFR_RNDA); + double i = mpfr_get_d (y, MPFR_RNDA); /* EXACT but can overflow */ + if (r == 0 && is_finite (i)) + return std::pair(i, i); + else + { + double s = nextafter (i, 0); + if (i < 0) + return std::pair(i, s); + else + return std::pair(s, i); + } +#else + mpfr_t y; + mpfr_init2 (y, 53); /* Assume IEEE-754 */ + mpfr_set_z (y, x.backend().data(), GMP_RNDD); + double i = mpfr_get_d (y, GMP_RNDD); /* EXACT but can overflow */ + mpfr_set_z (y, x.backend().data(), GMP_RNDU); + double s = mpfr_get_d (y, GMP_RNDU); /* EXACT but can overflow */ + mpfr_clear (y); + return std::pair(i, s); +#endif } }; -#endif }; +template <> +struct RET_boost_mp + : RET_boost_mp_base { + typedef boost::multiprecision::mpq_rational Type; + struct To_interval + : public CGAL::cpp98::unary_function< Type, std::pair< double, double > > { + std::pair + operator()(const Type& x) const { +# if MPFR_VERSION_MAJOR >= 3 + mpfr_exp_t emin = mpfr_get_emin(); + mpfr_set_emin(-1073); + MPFR_DECL_INIT (y, 53); /* Assume IEEE-754 */ + int r = mpfr_set_q (y, x.backend().data(), MPFR_RNDA); + r = mpfr_subnormalize (y, r, MPFR_RNDA); /* Round subnormals */ + double i = mpfr_get_d (y, MPFR_RNDA); /* EXACT but can overflow */ + mpfr_set_emin(emin); /* Restore old value, users may care */ + // With mpfr_set_emax(1024) we could drop the is_finite test + if (r == 0 && is_finite (i)) + return std::pair(i, i); + else + { + double s = nextafter (i, 0); + if (i < 0) + return std::pair(i, s); + else + return std::pair(s, i); + } +# else + mpfr_t y; + mpfr_init2 (y, 53); /* Assume IEEE-754 */ + mpfr_set_q (y, x.backend().data(), GMP_RNDD); + double i = mpfr_get_d (y, GMP_RNDD); /* EXACT but can overflow */ + mpfr_set_q (y, x.backend().data(), GMP_RNDU); + double s = mpfr_get_d (y, GMP_RNDU); /* EXACT but can overflow */ + mpfr_clear (y); + return std::pair(i, s); +# endif + } + }; +}; +#endif + +template +struct Real_embeddable_traits > +: RET_boost_mp > {}; +template +struct Real_embeddable_traits > +: Real_embeddable_traits::result_type > {}; // Modular_traits @@ -262,6 +350,13 @@ struct MT_boost_mp +struct Modular_traits > +: MT_boost_mp > {}; +template +struct Modular_traits > +: Modular_traits::result_type > {}; + // Split_double template ::value> > @@ -284,6 +379,13 @@ struct SD_boost_mp +struct Split_double > +: SD_boost_mp > {}; +template +struct Split_double > +: Split_double::result_type > {}; + // Fraction_traits @@ -335,27 +437,6 @@ struct FT_boost_mp -struct Algebraic_structure_traits > -: AST_boost_mp > {}; -template -struct Algebraic_structure_traits > -: Algebraic_structure_traits::result_type > {}; - -template -struct Real_embeddable_traits > -: RET_boost_mp > {}; -template -struct Real_embeddable_traits > -: Real_embeddable_traits::result_type > {}; - -template -struct Modular_traits > -: MT_boost_mp > {}; -template -struct Modular_traits > -: Modular_traits::result_type > {}; - template struct Fraction_traits > : FT_boost_mp > {}; @@ -363,13 +444,6 @@ template struct Fraction_traits > : Fraction_traits::result_type > {}; -template -struct Split_double > -: SD_boost_mp > {}; -template -struct Split_double > -: Split_double::result_type > {}; - // Coercions @@ -440,7 +514,7 @@ typename boost::multiprecision::detail::expression::result_type, boost::multiprecision::number > { }; -// TODO: coercion with expressions, fix existing coercions +// TODO: fix existing coercions // (double -> rational is implicit only for 1.56+, see ticket #10082) // The real solution would be to avoid specializing Coercion_traits for all pairs of number types and let it auto-detect what works, so only broken types need an explicit specialization. @@ -458,7 +532,13 @@ struct Coercion_traits, int> { \ }; \ template \ struct Coercion_traits > \ -: Coercion_traits, int> {} +: Coercion_traits, int> {}; \ +template \ +struct Coercion_traits, int> \ +: Coercion_traits::result_type, int>{}; \ +template \ +struct Coercion_traits > \ +: Coercion_traits::result_type, int>{} CGAL_COERCE_INT(short); CGAL_COERCE_INT(int); @@ -479,7 +559,13 @@ struct Coercion_traits, float> { \ }; \ template \ struct Coercion_traits > \ -: Coercion_traits, float> {} +: Coercion_traits, float> {}; \ +template \ +struct Coercion_traits, float> \ +: Coercion_traits::result_type, float>{}; \ +template \ +struct Coercion_traits > \ +: Coercion_traits::result_type, float>{} CGAL_COERCE_FLOAT(float); CGAL_COERCE_FLOAT(double); diff --git a/Number_types/include/CGAL/internal/Exact_type_selector.h b/Number_types/include/CGAL/internal/Exact_type_selector.h index f98f2ace0d6..a0c64f326fd 100644 --- a/Number_types/include/CGAL/internal/Exact_type_selector.h +++ b/Number_types/include/CGAL/internal/Exact_type_selector.h @@ -73,8 +73,10 @@ struct Exact_field_selector # endif #elif defined(CGAL_USE_LEDA) { typedef leda_rational Type; }; -#elif defined(CGAL_USE_BOOST_MP) -{ typedef boost::multiprecision::cpp_rational Type; }; +#elif 0 && defined(CGAL_USE_BOOST_MP) +// See the discussion in https://github.com/CGAL/cgal/pull/3614 +// This is disabled for now because cpp_rational is even slower than Quotient. Quotient will be a good candidate after some polishing. +{ typedef BOOST_cpp_arithmetic_kernel::Rational Type; }; #else { typedef Quotient Type; }; #endif diff --git a/Number_types/test/Number_types/utilities.cpp b/Number_types/test/Number_types/utilities.cpp index b29517bfd82..53a132e5b16 100644 --- a/Number_types/test/Number_types/utilities.cpp +++ b/Number_types/test/Number_types/utilities.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #ifdef CGAL_USE_GMP #include @@ -82,6 +83,12 @@ int main() TESTIT(CGAL::Lazy_exact_nt, "Lazy_exact_nt >") TESTIT(CGAL::Interval_nt<>, "Interval_nt<>") + // Boost.Multiprecision +#ifdef CGAL_USE_BOOST_MP + TESTIT(boost::multiprecision::cpp_int, "cpp_int") + TESTIT(boost::multiprecision::cpp_rational, "cpp_rational") +#endif + // GMP based NTs #ifdef CGAL_USE_GMP TESTIT(CGAL::Gmpz, "Gmpz") @@ -90,6 +97,10 @@ int main() TESTIT(CGAL::Mpzf, "Mpzf") # endif TESTIT(CGAL::Gmpq, "Gmpq") +# ifdef CGAL_USE_BOOST_MP + TESTIT(boost::multiprecision::mpz_int, "mpz_int") + TESTIT(boost::multiprecision::mpq_rational, "mpq_rational") +# endif #endif // CGAL_USE_GMP #ifdef CGAL_USE_GMPXX TESTIT(mpz_class, "mpz_class") diff --git a/Periodic_2_triangulation_2/examples/Periodic_2_triangulation_2/p2t2_info_insert_with_pair_iterator_2.cpp b/Periodic_2_triangulation_2/examples/Periodic_2_triangulation_2/p2t2_info_insert_with_pair_iterator_2.cpp index 3788ffaa3d6..921afdc0bd1 100644 --- a/Periodic_2_triangulation_2/examples/Periodic_2_triangulation_2/p2t2_info_insert_with_pair_iterator_2.cpp +++ b/Periodic_2_triangulation_2/examples/Periodic_2_triangulation_2/p2t2_info_insert_with_pair_iterator_2.cpp @@ -2,18 +2,21 @@ #include #include +#include +#include #include #include #include -typedef CGAL::Exact_predicates_inexact_constructions_kernel K; -typedef CGAL::Periodic_2_Delaunay_triangulation_traits_2 Gt; -typedef CGAL::Triangulation_vertex_base_with_info_2 Vb; -typedef CGAL::Periodic_2_triangulation_face_base_2 Fb; -typedef CGAL::Triangulation_data_structure_2 Tds; -typedef CGAL::Periodic_2_Delaunay_triangulation_2 Delaunay; -typedef Delaunay::Point Point; +typedef CGAL::Exact_predicates_inexact_constructions_kernel K; +typedef CGAL::Periodic_2_Delaunay_triangulation_traits_2 Gt; +typedef CGAL::Periodic_2_triangulation_vertex_base_2 Vbb; +typedef CGAL::Triangulation_vertex_base_with_info_2 Vb; +typedef CGAL::Periodic_2_triangulation_face_base_2 Fb; +typedef CGAL::Triangulation_data_structure_2 Tds; +typedef CGAL::Periodic_2_Delaunay_triangulation_2 Delaunay; +typedef Delaunay::Point Point; int main() { diff --git a/Periodic_2_triangulation_2/examples/Periodic_2_triangulation_2/p2t2_info_insert_with_transform_iterator_2.cpp b/Periodic_2_triangulation_2/examples/Periodic_2_triangulation_2/p2t2_info_insert_with_transform_iterator_2.cpp index 79097940a19..c67bf9f324c 100644 --- a/Periodic_2_triangulation_2/examples/Periodic_2_triangulation_2/p2t2_info_insert_with_transform_iterator_2.cpp +++ b/Periodic_2_triangulation_2/examples/Periodic_2_triangulation_2/p2t2_info_insert_with_transform_iterator_2.cpp @@ -2,18 +2,21 @@ #include #include +#include +#include #include #include #include -typedef CGAL::Exact_predicates_inexact_constructions_kernel K; -typedef CGAL::Periodic_2_Delaunay_triangulation_traits_2 Gt; -typedef CGAL::Triangulation_vertex_base_with_info_2 Vb; -typedef CGAL::Periodic_2_triangulation_face_base_2 Fb; -typedef CGAL::Triangulation_data_structure_2 Tds; -typedef CGAL::Periodic_2_Delaunay_triangulation_2 Delaunay; -typedef Delaunay::Point Point; +typedef CGAL::Exact_predicates_inexact_constructions_kernel K; +typedef CGAL::Periodic_2_Delaunay_triangulation_traits_2 Gt; +typedef CGAL::Periodic_2_triangulation_vertex_base_2 Vbb; +typedef CGAL::Triangulation_vertex_base_with_info_2 Vb; +typedef CGAL::Periodic_2_triangulation_face_base_2 Fb; +typedef CGAL::Triangulation_data_structure_2 Tds; +typedef CGAL::Periodic_2_Delaunay_triangulation_2 Delaunay; +typedef Delaunay::Point Point; //a functor that returns a std::pair. //the unsigned integer is incremented at each call to diff --git a/Periodic_2_triangulation_2/examples/Periodic_2_triangulation_2/p2t2_info_insert_with_zip_iterator_2.cpp b/Periodic_2_triangulation_2/examples/Periodic_2_triangulation_2/p2t2_info_insert_with_zip_iterator_2.cpp index a5a844ec2c8..7862f102373 100644 --- a/Periodic_2_triangulation_2/examples/Periodic_2_triangulation_2/p2t2_info_insert_with_zip_iterator_2.cpp +++ b/Periodic_2_triangulation_2/examples/Periodic_2_triangulation_2/p2t2_info_insert_with_zip_iterator_2.cpp @@ -2,18 +2,21 @@ #include #include +#include +#include #include #include #include -typedef CGAL::Exact_predicates_inexact_constructions_kernel K; -typedef CGAL::Periodic_2_Delaunay_triangulation_traits_2 Gt; -typedef CGAL::Triangulation_vertex_base_with_info_2 Vb; -typedef CGAL::Periodic_2_triangulation_face_base_2 Fb; -typedef CGAL::Triangulation_data_structure_2 Tds; -typedef CGAL::Periodic_2_Delaunay_triangulation_2 Delaunay; -typedef Delaunay::Point Point; +typedef CGAL::Exact_predicates_inexact_constructions_kernel K; +typedef CGAL::Periodic_2_Delaunay_triangulation_traits_2 Gt; +typedef CGAL::Periodic_2_triangulation_vertex_base_2 Vbb; +typedef CGAL::Triangulation_vertex_base_with_info_2 Vb; +typedef CGAL::Periodic_2_triangulation_face_base_2 Fb; +typedef CGAL::Triangulation_data_structure_2 Tds; +typedef CGAL::Periodic_2_Delaunay_triangulation_2 Delaunay; +typedef Delaunay::Point Point; int main() { diff --git a/Periodic_3_mesh_3/examples/Periodic_3_mesh_3/CMakeLists.txt b/Periodic_3_mesh_3/examples/Periodic_3_mesh_3/CMakeLists.txt index ef572651d9f..4c3efde1ded 100644 --- a/Periodic_3_mesh_3/examples/Periodic_3_mesh_3/CMakeLists.txt +++ b/Periodic_3_mesh_3/examples/Periodic_3_mesh_3/CMakeLists.txt @@ -5,10 +5,16 @@ project( Periodic_3_mesh_3_Examples ) cmake_minimum_required(VERSION 3.1) -# CGAL and its components -find_package( CGAL QUIET ) +if(POLICY CMP0074) + cmake_policy(SET CMP0074 NEW) +endif() -if ( NOT CGAL_FOUND ) +# CGAL and its components +find_package( CGAL QUIET COMPONENTS ImageIO ) + +if ( CGAL_FOUND ) + include( ${CGAL_USE_FILE} ) +else() message(STATUS "This project requires the CGAL library, and will not be compiled.") return() endif() diff --git a/Periodic_3_mesh_3/test/Periodic_3_mesh_3/CMakeLists.txt b/Periodic_3_mesh_3/test/Periodic_3_mesh_3/CMakeLists.txt index 7097e37e4fe..68ab382ea9f 100644 --- a/Periodic_3_mesh_3/test/Periodic_3_mesh_3/CMakeLists.txt +++ b/Periodic_3_mesh_3/test/Periodic_3_mesh_3/CMakeLists.txt @@ -5,9 +5,14 @@ project( Periodic_3_mesh_3_Tests ) cmake_minimum_required(VERSION 3.1) -find_package( CGAL QUIET ) +if(POLICY CMP0074) + cmake_policy(SET CMP0074 NEW) +endif() + +find_package( CGAL QUIET COMPONENTS ImageIO ) if ( CGAL_FOUND ) + include( ${CGAL_USE_FILE} ) # Use Eigen find_package(Eigen3 3.1.0 REQUIRED) #(3.1.0 or greater) diff --git a/Periodic_3_triangulation_3/demo/Periodic_3_triangulation_3/CMakeLists.txt b/Periodic_3_triangulation_3/demo/Periodic_3_triangulation_3/CMakeLists.txt index b3b8b63f561..b71c45d5da3 100644 --- a/Periodic_3_triangulation_3/demo/Periodic_3_triangulation_3/CMakeLists.txt +++ b/Periodic_3_triangulation_3/demo/Periodic_3_triangulation_3/CMakeLists.txt @@ -26,7 +26,13 @@ if(Qt5_FOUND) set(CMAKE_INCLUDE_CURRENT_DIR ON) endif(Qt5_FOUND) -if (CGAL_FOUND AND CGAL_Qt5_FOUND AND Qt5_FOUND AND TARGET Qt5::qcollectiongenerator) +if( Qt5Help_VERSION VERSION_LESS 5.12 ) + set(CGAL_QCOLLECTIONGENERATOR_TARGET Qt5::qcollectiongenerator) +else() + set(CGAL_QCOLLECTIONGENERATOR_TARGET Qt5::qhelpgenerator) +endif() + +if (CGAL_FOUND AND CGAL_Qt5_FOUND AND Qt5_FOUND AND TARGET ${CGAL_QCOLLECTIONGENERATOR_TARGET}) # UI files (Qt Designer files) qt5_wrap_ui ( UI_FILES MainWindow.ui ) @@ -39,15 +45,10 @@ if (CGAL_FOUND AND CGAL_Qt5_FOUND AND Qt5_FOUND AND TARGET Qt5::qcollectiongener qt5_generate_moc( "MainWindow.h" "${CMAKE_CURRENT_BINARY_DIR}/moc_MainWindow.cpp" ) qt5_generate_moc( "Viewer.h" "${CMAKE_CURRENT_BINARY_DIR}/moc_Viewer.cpp" ) - if(DEFINED QT_QCOLLECTIONGENERATOR_EXECUTABLE) - else() - set(QT_QCOLLECTIONGENERATOR_EXECUTABLE qcollectiongenerator) - endif() - # generate QtAssistant collection file add_custom_command ( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/Periodic_3_triangulation_3.qhc DEPENDS Periodic_3_triangulation_3.qhp Periodic_3_triangulation_3.qhcp - COMMAND Qt5::qcollectiongenerator + COMMAND ${CGAL_QCOLLECTIONGENERATOR_TARGET} ${CMAKE_CURRENT_SOURCE_DIR}/Periodic_3_triangulation_3.qhcp -o ${CMAKE_CURRENT_BINARY_DIR}/Periodic_3_triangulation_3.qhc ) @@ -83,8 +84,8 @@ else () set(PERIODIC_TRIANGULATION_MISSING_DEPS "Qt5, ${PERIODIC_TRIANGULATION_MISSING_DEPS}") endif() - if (NOT TARGET Qt5::qcollectiongenerator) - set(PERIODIC_TRIANGULATION_MISSING_DEPS "qcollectiongenerator, ${PERIODIC_TRIANGULATION_MISSING_DEPS}") + if (NOT TARGET ${CGAL_QCOLLECTIONGENERATOR_TARGET}) + set(PERIODIC_TRIANGULATION_MISSING_DEPS "${CGAL_QCOLLECTIONGENERATOR_TARGET}, ${PERIODIC_TRIANGULATION_MISSING_DEPS}") endif() message(STATUS "NOTICE: This demo requires ${PERIODIC_TRIANGULATION_MISSING_DEPS}and will not be compiled.") diff --git a/Periodic_3_triangulation_3/demo/Periodic_Lloyd_3/CMakeLists.txt b/Periodic_3_triangulation_3/demo/Periodic_Lloyd_3/CMakeLists.txt index ffd9b3d7e2e..151d1e3afc1 100644 --- a/Periodic_3_triangulation_3/demo/Periodic_Lloyd_3/CMakeLists.txt +++ b/Periodic_3_triangulation_3/demo/Periodic_Lloyd_3/CMakeLists.txt @@ -21,8 +21,13 @@ find_package(CGAL COMPONENTS Qt5) find_package(Qt5 QUIET COMPONENTS Xml Script Help OpenGL Svg) +if( Qt5Help_VERSION VERSION_LESS 5.12 ) + set(CGAL_QCOLLECTIONGENERATOR_TARGET Qt5::qcollectiongenerator) +else() + set(CGAL_QCOLLECTIONGENERATOR_TARGET Qt5::qhelpgenerator) +endif() -if ( CGAL_FOUND AND CGAL_Qt5_FOUND AND Qt5_FOUND AND TARGET Qt5::qcollectiongenerator ) +if ( CGAL_FOUND AND CGAL_Qt5_FOUND AND Qt5_FOUND AND TARGET ${CGAL_QCOLLECTIONGENERATOR_TARGET} ) include_directories (BEFORE ./ ) @@ -41,7 +46,7 @@ if ( CGAL_FOUND AND CGAL_Qt5_FOUND AND Qt5_FOUND AND TARGET Qt5::qcollectiongene # generate QtAssistant collection file add_custom_command ( OUTPUT Periodic_Lloyd_3.qhc DEPENDS Periodic_Lloyd_3.qhp Periodic_Lloyd_3.qhcp - COMMAND Qt5::qcollectiongenerator + COMMAND ${CGAL_QCOLLECTIONGENERATOR_TARGET} ${CMAKE_CURRENT_SOURCE_DIR}/Periodic_Lloyd_3.qhcp -o ${CMAKE_CURRENT_BINARY_DIR}/Periodic_Lloyd_3.qhc WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} @@ -69,7 +74,7 @@ else( CGAL_FOUND AND CGAL_Qt5_FOUND AND Qt5_FOUND AND QT_QCOLLECTIONGENERATOR_EX endif() if(NOT QT_QCOLLECTIONGENERATOR_EXECUTABLE) - set(PERIODIC_LLOYD_MISSING_DEPS "qcollectiongenerator, ${PERIODIC_LLOYD_MISSING_DEPS}") + set(PERIODIC_LLOYD_MISSING_DEPS "${CGAL_QCOLLECTIONGENERATOR_TARGET}, ${PERIODIC_LLOYD_MISSING_DEPS}") endif() diff --git a/Point_set_processing_3/include/CGAL/mst_orient_normals.h b/Point_set_processing_3/include/CGAL/mst_orient_normals.h index 72cd4e3b48f..8dd0bd69d92 100644 --- a/Point_set_processing_3/include/CGAL/mst_orient_normals.h +++ b/Point_set_processing_3/include/CGAL/mst_orient_normals.h @@ -488,6 +488,7 @@ create_mst_graph( CGAL_USE(point_map); CGAL_USE(k); CGAL_USE(kernel); + CGAL_USE(index_map); // Bring private stuff to scope using namespace internal; diff --git a/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/border.h b/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/border.h index 1c6d870c28f..6e7c905b64d 100644 --- a/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/border.h +++ b/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/border.h @@ -258,7 +258,7 @@ namespace Polygon_mesh_processing { return border_counter; } - /// @ingroup PkgPolygonMeshProcessing + /// @ingroup PkgPolygonMeshProcessingRef /// extracts boundary cycles as a list of halfedges, with one halfedge per border. /// /// @tparam PolygonMesh a model of `HalfedgeListGraph` diff --git a/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/intersection.h b/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/intersection.h index a36b14d8803..916cb5a1377 100644 --- a/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/intersection.h +++ b/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/intersection.h @@ -411,6 +411,14 @@ compute_face_face_intersection(const FaceRange& face_range1, typedef TriangleMesh TM; typedef typename boost::graph_traits::face_descriptor face_descriptor; typedef typename CGAL::Box_intersection_d::Box_with_info_d Box; + + CGAL::Bbox_3 b1 = CGAL::Polygon_mesh_processing::bbox(tm1, np1), + b2 = CGAL::Polygon_mesh_processing::bbox(tm2, np2); + + if(!CGAL::do_overlap(b1, b2)) + { + return out; + } // make one box per facet std::vector boxes1; @@ -525,6 +533,11 @@ compute_face_polyline_intersection( const FaceRange& face_range, CGAL_precondition(CGAL::is_triangle_mesh(tm)); + CGAL::Bbox_3 b1 = CGAL::Polygon_mesh_processing::bbox(tm, np), + b2 = CGAL::bbox_3(polyline.begin(), polyline.end()); + + if(!CGAL::do_overlap(b1,b2)) + return out; typedef TriangleMesh TM; typedef typename boost::graph_traits::face_descriptor face_descriptor; typedef typename GetVertexPointMap::const_type VertexPointMap; @@ -648,7 +661,18 @@ compute_face_polylines_intersection(const FaceRange& face_range, using boost::get_param; CGAL_precondition(CGAL::is_triangle_mesh(tm)); - + + CGAL::Bbox_3 b1,b2; + b1 = CGAL::Polygon_mesh_processing::bbox(tm, np); + for(std::size_t i =0; i< polyline_range.size(); ++i) + { + b2 += CGAL::bbox_3(polyline_range[i].begin(), + polyline_range[i].end()); + } + + if(!CGAL::do_overlap(b1,b2)) + return out; + typedef TriangleMesh TM; typedef typename boost::graph_traits::face_descriptor face_descriptor; typedef typename GetVertexPointMap::const_type VertexPointMap; @@ -849,18 +873,23 @@ compute_polylines_polylines_intersection(const PolylineRange& polylines1, std::vector boxes1; std::vector boxes2; std::size_t polylines_size = 0; + CGAL::Bbox_3 b1, b2; BOOST_FOREACH(Polyline poly, polylines1) { polylines_size += std::distance( boost::begin(poly), boost::end(poly) ) -1; + b1 += CGAL::bbox_3(poly.begin(), poly.end()); } boxes1.reserve( polylines_size ); polylines_size = 0; BOOST_FOREACH(Polyline poly, polylines2) { polylines_size += std::distance( boost::begin(poly), boost::end(poly) ) -1; + b2 += CGAL::bbox_3(poly.begin(), poly.end()); } boxes2.reserve(polylines_size); - + + if(!CGAL::do_overlap(b1,b2)) + return out; std::size_t range_size = std::distance( boost::begin(polylines1), boost::end(polylines1) ); for(std::size_t j = 0; j < range_size; ++j) { @@ -1207,7 +1236,6 @@ bool do_intersect(const TriangleMesh& tm1, { using boost::choose_param; using boost::get_param; - bool test_overlap = choose_param(get_param(np1, internal_np::overlap_test),false) || choose_param(get_param(np2, internal_np::overlap_test),false); @@ -1298,7 +1326,6 @@ bool do_intersect(const TriangleMesh& tm, ) { CGAL_precondition(CGAL::is_triangle_mesh(tm)); - try { typedef boost::function_output_iterator OutputIterator; @@ -1354,7 +1381,6 @@ bool do_intersect(const TriangleMesh& tm, ) { CGAL_precondition(CGAL::is_triangle_mesh(tm)); - try { typedef boost::function_output_iterator OutputIterator; @@ -1381,7 +1407,6 @@ bool do_intersect(const TriangleMesh& tm, >::type* = 0) { CGAL_precondition(CGAL::is_triangle_mesh(tm)); - return CGAL::Polygon_mesh_processing::do_intersect(tm, polylines, parameters::all_default()); } @@ -1404,7 +1429,6 @@ bool do_intersect(const TriangleMesh& tm, >::type* = 0) { CGAL_precondition(CGAL::is_triangle_mesh(tm)); - return CGAL::Polygon_mesh_processing::do_intersect(tm, polyline, parameters::all_default()); } diff --git a/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/repair.h b/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/repair.h index 59d7b0c26ad..a28f70960ce 100644 --- a/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/repair.h +++ b/Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/repair.h @@ -1649,7 +1649,7 @@ bool remove_degenerate_faces( TriangleMesh& tmesh, } template -std::size_t remove_degenerate_faces(TriangleMesh& tmesh) +bool remove_degenerate_faces(TriangleMesh& tmesh) { return remove_degenerate_faces(tmesh, CGAL::Polygon_mesh_processing::parameters::all_default()); diff --git a/Polyhedron/demo/Polyhedron/CMakeLists.txt b/Polyhedron/demo/Polyhedron/CMakeLists.txt index 857b3622def..9090f621866 100644 --- a/Polyhedron/demo/Polyhedron/CMakeLists.txt +++ b/Polyhedron/demo/Polyhedron/CMakeLists.txt @@ -359,6 +359,11 @@ add_executable ( CGAL_Mesh_3 Mesh_3.cpp ) add_dependencies(CGAL_Mesh_3 Mesh_3) target_link_libraries( CGAL_Mesh_3 PRIVATE polyhedron_demo ) add_to_cached_list( CGAL_EXECUTABLE_TARGETS CGAL_Mesh_3 ) + +add_executable ( CGAL_Classification Classification.cpp ) +add_dependencies(CGAL_Classification Classification) +target_link_libraries( CGAL_Classification PRIVATE polyhedron_demo ) +add_to_cached_list( CGAL_EXECUTABLE_TARGETS CGAL_Classification ) # # Exporting # diff --git a/Polyhedron/demo/Polyhedron/Classification.cpp b/Polyhedron/demo/Polyhedron/Classification.cpp new file mode 100644 index 00000000000..acbb39eb536 --- /dev/null +++ b/Polyhedron/demo/Polyhedron/Classification.cpp @@ -0,0 +1,29 @@ +#include "Polyhedron_demo.h" +#include +#include +#include + + +/*! + * \brief Defines the entry point of the demo. + * Creates the application and sets a main window. + */ +int main(int argc, char **argv) +{ + QSurfaceFormat fmt; + + fmt.setVersion(4, 3); + fmt.setRenderableType(QSurfaceFormat::OpenGL); + fmt.setProfile(QSurfaceFormat::CoreProfile); + fmt.setOption(QSurfaceFormat::DebugContext); + QSurfaceFormat::setDefaultFormat(fmt); + QStringList keywords; + keywords << "Classification"; + Polyhedron_demo app(argc, argv, + "Classification demo", + "CGAL Classification Demo", + keywords); + //We set the locale to avoid any trouble with VTK + std::setlocale(LC_ALL, "C"); + return app.try_exec(); +} diff --git a/Polyhedron/demo/Polyhedron/MainWindow.cpp b/Polyhedron/demo/Polyhedron/MainWindow.cpp index b45aca5ac1b..ebb3182ed2a 100644 --- a/Polyhedron/demo/Polyhedron/MainWindow.cpp +++ b/Polyhedron/demo/Polyhedron/MainWindow.cpp @@ -261,8 +261,10 @@ MainWindow::MainWindow(const QStringList &keywords, bool verbose, QWidget* paren connect(viewer, SIGNAL(requestContextMenu(QPoint)), this, SLOT(contextMenuRequested(QPoint))); - connect(viewer, SIGNAL(sendMessage(QString)), - this, SLOT(information(QString))); + connect(viewer, &Viewer::sendMessage, + this, [](QString s){ + information(s); + }); // The contextMenuPolicy of infoLabel is now the default one, so that one // can easily copy-paste its text. @@ -402,45 +404,70 @@ MainWindow::MainWindow(const QStringList &keywords, bool verbose, QWidget* paren } //Recursive function that do a pass over a menu and its sub-menus(etc.) and hide them when they are empty -void filterMenuOperations(QMenu* menu, bool showFullMenu) +void filterMenuOperations(QMenu* menu, QString filter, bool keep_from_here) { - Q_FOREACH(QAction* action, menu->actions()) { - if(QMenu* menu = action->menu()) - { - filterMenuOperations(menu, showFullMenu); - action->setVisible(showFullMenu && !(menu->isEmpty())); + QList buffer; + Q_FOREACH(QAction* action, menu->actions()) + buffer.append(action); + while(!buffer.isEmpty()){ + + Q_FOREACH(QAction* action, buffer) { + if(QMenu* submenu = action->menu()) + { + bool keep = true; + if(!keep_from_here){ + keep = submenu->menuAction()->text().contains(filter, Qt::CaseInsensitive); + if(!keep) + { + Q_FOREACH(QAction* subaction, submenu->actions()) + { + submenu->removeAction(subaction); + buffer.append(subaction); + } + } + else + { + menu->addAction(submenu->menuAction()); + } + } + filterMenuOperations(submenu, filter, keep); + action->setVisible(!(submenu->isEmpty())); + } + else if(action->text().contains(filter, Qt::CaseInsensitive)){ + menu->addAction(action); + } + buffer.removeAll(action); } } - } void MainWindow::filterOperations() { - static QVector to_remove; - Q_FOREACH(QAction* action, to_remove) - ui->menuOperations->removeAction(action); - QString filter=operationSearchBar.text(); - if(!filter.isEmpty()) - Q_FOREACH(const PluginNamePair& p, plugins) { - Q_FOREACH(QAction* action, p.first->actions()) { - action->setVisible( p.first->applicable(action) - && action->text().contains(filter, Qt::CaseInsensitive)); - if(action->menu() != ui->menuOperations){ - ui->menuOperations->addAction(action); - to_remove.push_back(action); - } - } + //return actions to their true menu + Q_FOREACH(QMenu* menu, action_menu_map.values()) + { + Q_FOREACH(QAction* action, menu->actions()) + { + if(action != searchAction) + menu->removeAction(action); } - else{ - Q_FOREACH(const PluginNamePair& p, plugins) { - Q_FOREACH(QAction* action, p.first->actions()) { - action->setVisible( p.first->applicable(action) - && action->text().contains(filter, Qt::CaseInsensitive)); - } - } - // do a pass over all menus in Operations and their sub-menus(etc.) and hide them when they are empty } - filterMenuOperations(ui->menuOperations, filter.isEmpty()); + Q_FOREACH(QAction* action, action_menu_map.keys()) + { + action_menu_map[action]->addAction(action); + } + QString filter=operationSearchBar.text(); + Q_FOREACH(const PluginNamePair& p, plugins) { + Q_FOREACH(QAction* action, p.first->actions()) { + action->setVisible( p.first->applicable(action) + && (action->text().contains(filter, Qt::CaseInsensitive) + || action->property("subMenuName") + .toString().contains(filter, Qt::CaseInsensitive))); + } + } + // do a pass over all menus in Operations and their sub-menus(etc.) and hide them when they are empty + filterMenuOperations(ui->menuOperations, filter, false); + operationSearchBar.setFocus(); } #include @@ -549,12 +576,14 @@ void MainWindow::setMenus(QString name, QString parentName, QAction* a ) menu_map[parentName] = new QMenu(parentName, this); // add the submenu in the menu menu_map[parentName]->addMenu(menu_map[menuName]); + action_menu_map[menu_map[menuName]->menuAction()] = menu_map[parentName]; // only add the action in the last submenu if(slash_index==-1) { ui->menuOperations->removeAction(a); menu_map[menuName]->addAction(a); + action_menu_map[a] = menu_map[menuName]; } } @@ -765,6 +794,7 @@ bool MainWindow::initPlugin(QObject* obj) // If action does not belong to the menus, add it to "Operations" menu if(!childs.contains(action)) { ui->menuOperations->addAction(action); + action_menu_map[action] = ui->menuOperations; } // Show and enable menu item addAction(action); @@ -893,17 +923,17 @@ void MainWindow::message(QString message, QString colorName, QString font) { ui->consoleTextEdit->verticalScrollBar()->setValue(ui->consoleTextEdit->verticalScrollBar()->maximum()); } -void MainWindow::information(QString text) { +void MainWindow::message_information(QString text) { statusBar()->setStyleSheet("color: blue"); this->message("INFO: " + text, "blue"); } -void MainWindow::warning(QString text) { +void MainWindow::message_warning(QString text) { statusBar()->setStyleSheet("color: orange"); this->message("WARNING: " + text, "orange"); } -void MainWindow::error(QString text) { +void MainWindow::message_error(QString text) { statusBar()->setStyleSheet("color: red"); this->message("ERROR: " + text, "red"); } @@ -968,6 +998,8 @@ void MainWindow::reloadItem() { Q_FOREACH(Scene::Item_id id, scene->selectionIndices()) { item = scene->item(id); + if(!item)//secure items like selection items that get deleted when their "parent" item is reloaded. + continue; QString filename = item->property("source filename").toString(); QString loader_name = item->property("loader_name").toString(); if(filename.isEmpty() || loader_name.isEmpty()) { @@ -986,9 +1018,9 @@ void MainWindow::reloadItem() { new_item->setRenderingMode(item->renderingMode()); new_item->setVisible(item->visible()); Scene_item_with_properties *property_item = dynamic_cast(new_item); + scene->replaceItem(scene->item_id(item), new_item, true); if(property_item) property_item->copyProperties(item); - scene->replaceItem(scene->item_id(item), new_item, true); new_item->invalidateOpenGLBuffers(); item->deleteLater(); } @@ -1169,22 +1201,19 @@ bool MainWindow::open(QString filename, QString loader_name) { CGAL::Three::Scene_item* MainWindow::loadItem(QFileInfo fileinfo, CGAL::Three::Polyhedron_demo_io_plugin_interface* loader) { CGAL::Three::Scene_item* item = NULL; if(!fileinfo.isFile() || !fileinfo.isReadable()) { - throw std::invalid_argument(QString("File %1 is not a readable file.") - .arg(fileinfo.absoluteFilePath()).toStdString()); - } - //test if the file is empty. - if(fileinfo.size() == 0) { QMessageBox::warning(this, tr("Error"), - tr("The file you are trying to load is empty.\n")); - return 0; + QString("File %1 is not a readable file.") + .arg(fileinfo.absoluteFilePath())); } QApplication::setOverrideCursor(Qt::WaitCursor); item = loader->load(fileinfo); QApplication::restoreOverrideCursor(); if(!item) { - throw std::logic_error(QString("Could not load item from file %1 using plugin %2") - .arg(fileinfo.absoluteFilePath()).arg(loader->name()).toStdString()); + QMessageBox::warning(this, tr("Error"), + QString("Could not load item from file %1 using plugin %2") + .arg(fileinfo.absoluteFilePath()).arg(loader->name())); + return 0; } item->setProperty("source filename", fileinfo.absoluteFilePath()); @@ -1207,11 +1236,13 @@ void MainWindow::selectSceneItem(int i) } else { QItemSelection s = - proxyModel->mapSelectionFromSource(scene->createSelection(i)); - + proxyModel->mapSelectionFromSource(scene->createSelection(i)); + QModelIndex mi = proxyModel->mapFromSource(scene->getModelIndexFromId(i).first()); + sceneView->setCurrentIndex(mi); sceneView->selectionModel()->select(s, QItemSelectionModel::ClearAndSelect); sceneView->scrollTo(s.indexes().first()); + sceneView->setCurrentIndex(sceneView->selectionModel()->selectedIndexes().first()); } } @@ -1226,6 +1257,8 @@ void MainWindow::selectSceneItems(QList is) QItemSelection s = proxyModel->mapSelectionFromSource(scene->createSelection(is)); + QModelIndex i = proxyModel->mapFromSource(scene->getModelIndexFromId(is.first()).first()); + sceneView->setCurrentIndex(i); sceneView->selectionModel()->select(s, QItemSelectionModel::ClearAndSelect); sceneView->scrollTo(s.indexes().first()); @@ -1409,6 +1442,15 @@ void MainWindow::showSceneContextMenu(const QPoint& p) { QMap menu_actions; QVector slider_menus; bool has_stats = false; + bool has_reload = false; + Q_FOREACH(Scene::Item_id id, scene->selectionIndices()) + { + if(!scene->item(id)->property("source filename").toString().isEmpty()) + { + has_reload = true; + break; + } + } Q_FOREACH(QAction* action, scene->item(main_index)->contextMenu()->actions()) { if(action->property("is_groupable").toBool()) @@ -1571,10 +1613,13 @@ void MainWindow::showSceneContextMenu(const QPoint& p) { connect(actionStatistics, SIGNAL(triggered()), this, SLOT(statisticsOnItem())); } + if(has_reload) + { QAction* reload = menu.addAction(tr("&Reload Item from File")); reload->setProperty("is_groupable", true); connect(reload, SIGNAL(triggered()), this, SLOT(reloadItem())); + } QAction* saveas = menu.addAction(tr("&Save as...")); connect(saveas, SIGNAL(triggered()), this, SLOT(on_actionSaveAs_triggered())); @@ -1963,9 +2008,11 @@ bool MainWindow::on_actionErase_triggered() void MainWindow::on_actionEraseAll_triggered() { - scene->setSelectedItem(0); - while(on_actionErase_triggered()) { - } + QList all_ids; + for(int i = 0; i < scene->numberOfEntries(); ++i) + all_ids.push_back(i); + scene->setSelectedItemsList(all_ids); + on_actionErase_triggered(); } void MainWindow::on_actionDuplicate_triggered() @@ -2202,6 +2249,8 @@ void MainWindow::on_actionLookAt_triggered() if( i == QDialog::Accepted && dialog.has_correct_coordinates() ) { + if(viewer->camera()->frame()->isSpinning()) + viewer->camera()->frame()->stopSpinning(); viewerShow((float)dialog.get_x()+viewer->offset().x, (float)dialog.get_y()+viewer->offset().y, (float)dialog.get_z()+viewer->offset().z); @@ -2722,3 +2771,20 @@ void MainWindow::invalidate_bbox(bool do_recenter) updateViewerBBox(true); } + +void MainWindow::on_action_Save_triggered() +{ + if(QMessageBox::question(this, "Save", "Are you sure you want to override these files ?") + == QMessageBox::No) + return; + Scene_item* item = nullptr; + Q_FOREACH(Scene::Item_id id, scene->selectionIndices()) + { + item = scene->item(id); + if(!item->property("source filename").toString().isEmpty()) + { + QString filename = item->property("source filename").toString(); + save(filename, item); + } + } +} diff --git a/Polyhedron/demo/Polyhedron/MainWindow.h b/Polyhedron/demo/Polyhedron/MainWindow.h index 7a23e664b61..0689df3183e 100644 --- a/Polyhedron/demo/Polyhedron/MainWindow.h +++ b/Polyhedron/demo/Polyhedron/MainWindow.h @@ -102,7 +102,7 @@ public Q_SLOTS: //! If `b` is true, recenters the scene. void updateViewerBBox(bool b); //! Opens a script or a file with the default loader if there is. - void open(QString); + void open(QString) Q_DECL_OVERRIDE; //! Is called when the up button is pressed. void on_upButton_pressed(); //! Is called when the down button is pressed. @@ -220,15 +220,15 @@ public Q_SLOTS: /*! * Displays a text preceded by the mention "INFO :". */ - void information(QString); + void message_information(QString) Q_DECL_OVERRIDE; /*! * Displays a blue text preceded by the mention "WARNING :". */ - void warning(QString); + void message_warning(QString) Q_DECL_OVERRIDE; /*! * Displays a red text preceded by the mention "ERROR :". */ - void error(QString); + void message_error(QString) Q_DECL_OVERRIDE; //!Displays a text in the chosen html color with the chosen html font. @@ -327,6 +327,8 @@ protected Q_SLOTS: //Preferences edition //!Opens the Preferences dialog. void on_actionPreferences_triggered(); + //!Save selected items if able. + void on_action_Save_triggered(); // save as... //!Opens a dialog to save selected item if able. void on_actionSaveAs_triggered(); @@ -384,7 +386,7 @@ protected: * Calls writeSettings() and set the flag accepted for the event. * @see writeSettings() */ - void closeEvent(QCloseEvent *event); + void closeEvent(QCloseEvent *event)Q_DECL_OVERRIDE; /*! Returns the currently selected item in the Geometric Objects view. Returns -1 * if none is selected. */ @@ -418,7 +420,7 @@ private: QAction* actionAddToGroup; QAction* actionResetDefaultLoaders; CGAL::Three::Three* three; - void print_message(QString message) { messages->information(message); } + void print_message(QString message) { messages->message_information(message); } Messages_interface* messages; QDialog *statistics_dlg; @@ -453,6 +455,9 @@ private: QMap >plugin_metadata_map; QMap ignored_map; const QStringList& accepted_keywords; + +private: + QMap action_menu_map; }; #endif // ifndef MAINWINDOW_H diff --git a/Polyhedron/demo/Polyhedron/MainWindow.ui b/Polyhedron/demo/Polyhedron/MainWindow.ui index c5057750dcf..5329803091d 100644 --- a/Polyhedron/demo/Polyhedron/MainWindow.ui +++ b/Polyhedron/demo/Polyhedron/MainWindow.ui @@ -48,6 +48,7 @@ + @@ -498,6 +499,11 @@ Sa&ve the Scene as a Script File... + + + &Save + + diff --git a/Polyhedron/demo/Polyhedron/Messages_interface.h b/Polyhedron/demo/Polyhedron/Messages_interface.h index 3c8e8dc51e9..cec5ef3f655 100644 --- a/Polyhedron/demo/Polyhedron/Messages_interface.h +++ b/Polyhedron/demo/Polyhedron/Messages_interface.h @@ -7,9 +7,9 @@ class Messages_interface { public: virtual ~Messages_interface() {} - virtual void warning(QString) = 0; - virtual void error(QString) = 0; - virtual void information(QString) = 0; + virtual void message_warning(QString) = 0; + virtual void message_error(QString) = 0; + virtual void message_information(QString) = 0; }; Q_DECLARE_INTERFACE(Messages_interface, diff --git a/Polyhedron/demo/Polyhedron/Plugins/AABB_tree/Cut_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/AABB_tree/Cut_plugin.cpp index 71dd2874115..7b46387398b 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/AABB_tree/Cut_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/AABB_tree/Cut_plugin.cpp @@ -47,7 +47,7 @@ std::size_t last; }; #endif // CGAL_LINKED_WITH_TBB - +#include typedef CGAL::Simple_cartesian Simple_kernel; typedef Simple_kernel::FT FT; typedef Simple_kernel::Point_3 Point; @@ -253,7 +253,7 @@ public: { } - bool isFinite() const { return true; } + bool isFinite() const { return false; } bool isEmpty() const { return is_tree_empty; } //computed in constructor void compute_bbox() const {} @@ -1193,12 +1193,12 @@ void Polyhedron_demo_cut_plugin::apply(Item* item, QMap< QObject*, Facets_tree*> const Mesh& mesh = *item->polyhedron(); if(!CGAL::is_triangle_mesh(mesh)) { - messages->warning(QString("%1 ignored (not a triangulated mesh)").arg(item->name())); + CGAL::Three::Three::warning(QString("%1 ignored (not a triangulated mesh)").arg(item->name())); return; } if(!CGAL::is_closed(mesh)) { - messages->warning(QString("%1 is not closed. Signed function will not be displayed.").arg(item->name())); + CGAL::Three::Three::warning(QString("%1 is not closed. Signed function will not be displayed.").arg(item->name())); } if(f_trees.find(item) == f_trees.end()) { PPMAP pmap(item->polyhedron()); @@ -1392,7 +1392,7 @@ void Polyhedron_demo_cut_plugin::computeIntersection() } } if(does_intersect) - messages->information(QString("cut (%1 ms). %2 edges.").arg(time.elapsed()).arg(edges_item->edges.size())); + CGAL::Three::Three::information(QString("cut (%1 ms). %2 edges.").arg(time.elapsed()).arg(edges_item->edges.size())); edges_item->invalidateOpenGLBuffers(); edges_item->itemChanged(); ready_to_cut = false; diff --git a/Polyhedron/demo/Polyhedron/Plugins/AABB_tree/Do_trees_intersect_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/AABB_tree/Do_trees_intersect_plugin.cpp index 91cef460b95..cae964740a6 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/AABB_tree/Do_trees_intersect_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/AABB_tree/Do_trees_intersect_plugin.cpp @@ -140,7 +140,7 @@ private Q_SLOTS: static_cast( CGAL::QGLViewer::QGLViewerPool().first())->installEventFilter(this); QApplication::restoreOverrideCursor(); - messageInterface->information("Press `W` to switch between Wireframe and Transparency mode."); + CGAL::Three::Three::information("Press `W` to switch between Wireframe and Transparency mode."); } public Q_SLOTS: diff --git a/Polyhedron/demo/Polyhedron/Plugins/Classification/CMakeLists.txt b/Polyhedron/demo/Polyhedron/Plugins/Classification/CMakeLists.txt index 48ce9e655d1..c3e48ffcd9b 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Classification/CMakeLists.txt +++ b/Polyhedron/demo/Polyhedron/Plugins/Classification/CMakeLists.txt @@ -20,7 +20,7 @@ if(EIGEN3_FOUND) if (Boost_SERIALIZATION_FOUND AND Boost_IOSTREAMS_FOUND AND (NOT WIN32 OR Boost_ZLIB_FOUND)) qt5_wrap_ui( classificationUI_FILES Classification_widget.ui Classification_advanced_widget.ui ) - polyhedron_demo_plugin(classification_plugin Classification_plugin Point_set_item_classification Cluster_classification Surface_mesh_item_classification ${classificationUI_FILES}) + polyhedron_demo_plugin(classification_plugin Classification_plugin Point_set_item_classification Cluster_classification Surface_mesh_item_classification ${classificationUI_FILES} KEYWORDS Classification) set(classification_linked_libraries ${classification_linked_libraries} ${Boost_SERIALIZATION_LIBRARY} @@ -37,9 +37,22 @@ if(EIGEN3_FOUND) else() message(STATUS "NOTICE: OpenCV was not found. OpenCV random forest predicate for classification won't be available.") endif() + + find_package(TensorFlow QUIET) + if (TensorFlow_FOUND) + message(STATUS "Found TensorFlow") + set(classification_linked_libraries ${classification_linked_libraries} + ${TensorFlow_LIBRARY}) + set(classification_compile_definitions ${classification_compile_definitions} + "-DCGAL_LINKED_WITH_TENSORFLOW") + include_directories( ${TensorFlow_INCLUDE_DIR} ) + else() + message(STATUS "NOTICE: TensorFlow not found, Neural Network predicate for classification won't be available.") + endif() target_link_libraries(classification_plugin PUBLIC scene_points_with_normal_item scene_polylines_item scene_polygon_soup_item scene_surface_mesh_item scene_selection_item scene_color_ramp ${classification_linked_libraries}) + add_dependencies(classification_plugin point_set_selection_plugin selection_plugin) target_compile_definitions(classification_plugin PUBLIC ${classification_compile_definitions}) else() message(STATUS "NOTICE: Boost Serialization or IO Streams or ZLIB not found. Classification plugin won't be available.") diff --git a/Polyhedron/demo/Polyhedron/Plugins/Classification/Classification_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/Classification/Classification_plugin.cpp index 45e5fdfaf87..64e33d2d3a2 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Classification/Classification_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/Classification/Classification_plugin.cpp @@ -19,6 +19,7 @@ #include #include +#include #include #include @@ -32,6 +33,7 @@ #include #include #include +#include #include #include #include @@ -43,6 +45,11 @@ #include #include +#define CGAL_CLASSIFICATION_ETHZ_ID "Random Forest (ETHZ)" +#define CGAL_CLASSIFICATION_TENSORFLOW_ID "Neural Network (TensorFlow)" +#define CGAL_CLASSIFICATION_OPENCV_ID "Random Forest (OpenCV)" +#define CGAL_CLASSIFICATION_SOWF_ID "Sum of Weighted Features" + using namespace CGAL::Three; class Polyhedron_demo_classification_plugin : @@ -120,6 +127,7 @@ class Polyhedron_demo_classification_plugin : color_button->setStyleSheet(s); color_button->update(); } + }; @@ -129,7 +137,7 @@ public: qobject_cast(scene->item(scene->mainSelectionIndex())) || qobject_cast(scene->item(scene->mainSelectionIndex())); } - void print_message(QString message) { messages->information(message); } + void print_message(QString message) { CGAL::Three::Three::information(message); } QList actions() const { return QList() << actionClassification; } using Polyhedron_demo_plugin_helper::init; @@ -185,82 +193,87 @@ public: addDockWidget(dock_widget); addDockWidget(dock_widget_adv); -#ifdef CGAL_LINKED_WITH_OPENCV - ui_widget.classifier->addItem (tr("Random Forest (OpenCV %1.%2)") - .arg(CV_MAJOR_VERSION) - .arg(CV_MINOR_VERSION)); -#endif - color_att = QColor (75, 75, 77); - ui_widget.menu->setMenu (new QMenu("Classification Menu", ui_widget.menu)); - - connect(ui_widget.classifier, SIGNAL(currentIndexChanged(int)), this, - SLOT(on_classifier_changed(int))); - - QAction* compute_features = ui_widget.menu->menu()->addAction ("Compute features"); + QAction* compute_features = ui_widget.features_menu->addAction ("Compute features..."); connect(compute_features, SIGNAL(triggered()), this, SLOT(on_compute_features_button_clicked())); - ui_widget.menu->menu()->addSection ("Training"); + action_statistics = ui_widget.features_menu->addAction ("Show feature statistics"); + connect(action_statistics, SIGNAL(triggered()), this, + SLOT(on_statistics_clicked())); - action_train = ui_widget.menu->menu()->addAction ("Train classifier"); - action_train->setShortcut(Qt::SHIFT | Qt::Key_T); - connect(action_train, SIGNAL(triggered()), this, - SLOT(on_train_clicked())); - - action_reset_local = ui_widget.menu->menu()->addAction ("Reset training set of selection"); + action_reset_local = ui_widget.training_menu->addAction ("Reset training set of selection"); connect(action_reset_local, SIGNAL(triggered()), this, SLOT(on_reset_training_set_of_selection_clicked())); - action_reset = ui_widget.menu->menu()->addAction ("Reset all training sets"); + action_reset = ui_widget.training_menu->addAction ("Reset all training sets"); connect(action_reset, SIGNAL(triggered()), this, SLOT(on_reset_training_sets_clicked())); - action_random_region = ui_widget.menu->menu()->addAction ("Select random region"); + action_random_region = ui_widget.training_menu->addAction ("Select random region"); action_random_region->setShortcut(Qt::SHIFT | Qt::Key_S); connect(action_random_region, SIGNAL(triggered()), this, SLOT(on_select_random_region_clicked())); - action_validate = ui_widget.menu->menu()->addAction ("Validate labels of current selection as training sets"); + action_validate = ui_widget.training_menu->addAction ("Validate labels of current selection as training sets"); connect(action_validate, SIGNAL(triggered()), this, SLOT(on_validate_selection_clicked())); - action_save_config = ui_widget.menu->menu()->addAction ("Save classifier's current configuration"); - action_load_config = ui_widget.menu->menu()->addAction ("Load configuration for classifier"); + classifier = ui_widget.classifier_menu->addSection (CGAL_CLASSIFICATION_ETHZ_ID); + + action_train = ui_widget.classifier_menu->addAction ("Train..."); + action_train->setShortcut(Qt::SHIFT | Qt::Key_T); + connect(action_train, SIGNAL(triggered()), this, + SLOT(on_train_clicked())); + + ui_widget.classifier_menu->addSeparator(); + + action_run = ui_widget.classifier_menu->addAction ("Classify"); + connect(action_run, SIGNAL(triggered()), this, + SLOT(on_run_button_clicked())); + + action_run_smoothed = ui_widget.classifier_menu->addAction ("Classify with local smoothing..."); + connect(action_run_smoothed, SIGNAL(triggered()), this, + SLOT(on_run_smoothed_button_clicked())); + + action_run_graphcut = ui_widget.classifier_menu->addAction ("Classify with Graph Cut..."); + connect(action_run_graphcut, SIGNAL(triggered()), this, + SLOT(on_run_graphcut_button_clicked())); + + ui_widget.classifier_menu->addSeparator(); + + action_save_config = ui_widget.classifier_menu->addAction ("Save current configuration..."); + action_load_config = ui_widget.classifier_menu->addAction ("Load configuration..."); connect(action_save_config, SIGNAL(triggered()), this, SLOT(on_save_config_button_clicked())); connect(action_load_config, SIGNAL(triggered()), this, SLOT(on_load_config_button_clicked())); - ui_widget.menu->menu()->addSection ("Algorithms"); - - action_run = ui_widget.menu->menu()->addAction ("Classification"); - connect(action_run, SIGNAL(triggered()), this, - SLOT(on_run_button_clicked())); - - action_run_smoothed = ui_widget.menu->menu()->addAction ("Classification with local smoothing"); - connect(action_run_smoothed, SIGNAL(triggered()), this, - SLOT(on_run_smoothed_button_clicked())); - - action_run_graphcut = ui_widget.menu->menu()->addAction ("Classification with Graph Cut"); - connect(action_run_graphcut, SIGNAL(triggered()), this, - SLOT(on_run_graphcut_button_clicked())); - - ui_widget.menu->menu()->addSeparator(); - - QAction* close = ui_widget.menu->menu()->addAction ("Close"); - connect(close, SIGNAL(triggered()), this, - SLOT(ask_for_closing())); - + ui_widget.classifier_menu->addSeparator(); + + QAction* switch_classifier = ui_widget.classifier_menu->addAction ("Switch to another classifier..."); + connect(switch_classifier, SIGNAL(triggered()), this, + SLOT(on_switch_classifier_clicked())); + connect(ui_widget.display, SIGNAL(currentIndexChanged(int)), this, SLOT(on_display_button_clicked(int))); + connect(ui_widget.minDisplay, SIGNAL(released()), this, + SLOT(on_min_display_button_clicked())); + connect(ui_widget.maxDisplay, SIGNAL(released()), this, + SLOT(on_max_display_button_clicked())); + connect(ui_widget_adv.selected_feature, SIGNAL(currentIndexChanged(int)), this, SLOT(on_selected_feature_changed(int))); connect(ui_widget_adv.feature_weight, SIGNAL(valueChanged(int)), this, SLOT(on_feature_weight_changed(int))); + connect(ui_widget.help, SIGNAL(clicked()), this, + SLOT(on_help_clicked())); + connect(ui_widget.close, SIGNAL(clicked()), this, + SLOT(ask_for_closing())); + QObject* scene_obj = dynamic_cast(scene_interface); if(scene_obj) { @@ -296,10 +309,26 @@ public Q_SLOTS: dock_widget->raise(); if (Scene_points_with_normal_item* points_item = qobject_cast(scene->item(scene->mainSelectionIndex()))) + { create_from_item(points_item); + QAction* ps_selection = mw->findChild("actionPointSetSelection"); + if (ps_selection) + ps_selection->trigger(); + else + print_message("Warning: can't find Point Set Selection plugin"); + } else if (Scene_surface_mesh_item* mesh_item = qobject_cast(scene->item(scene->mainSelectionIndex()))) + { create_from_item(mesh_item); + QAction* sm_selection = mw->findChild("actionSelection"); + if (sm_selection) + sm_selection->trigger(); + else + print_message("Warning: can't find Surface Mesh Selection plugin"); + } + + on_help_clicked(); } @@ -342,31 +371,39 @@ public Q_SLOTS: void disable_everything () { - ui_widget.menu->setEnabled(false); - ui_widget.display->setEnabled(false); - ui_widget.classifier->setEnabled(false); + ui_widget.features_menu->setEnabled(false); + ui_widget.training_menu->setEnabled(false); + ui_widget.classifier_menu->setEnabled(false); + ui_widget.view->setEnabled(false); ui_widget.frame->setEnabled(false); } void enable_computation() { - ui_widget.menu->setEnabled(true); + ui_widget.features_menu->setEnabled(true); + ui_widget.training_menu->setEnabled(true); + ui_widget.classifier_menu->setEnabled(false); + action_statistics->setEnabled(false); action_train->setEnabled(false); - action_reset_local->setEnabled(false); - action_reset->setEnabled(false); - action_random_region->setEnabled(false); - action_validate->setEnabled(false); + action_reset_local->setEnabled(true); + action_reset->setEnabled(true); + action_random_region->setEnabled(true); + action_validate->setEnabled(true); action_save_config->setEnabled(false); action_load_config->setEnabled(false); action_run->setEnabled(false); action_run_smoothed->setEnabled(false); action_run_graphcut->setEnabled(false); - ui_widget.display->setEnabled(true); - ui_widget.classifier->setEnabled(true); + ui_widget.view->setEnabled(true); + ui_widget.frame->setEnabled(true); } void enable_classif() { + ui_widget.features_menu->setEnabled(true); + ui_widget.training_menu->setEnabled(true); + ui_widget.classifier_menu->setEnabled(true); + action_statistics->setEnabled(true); action_train->setEnabled(true); action_reset_local->setEnabled(true); action_reset->setEnabled(true); @@ -420,9 +457,15 @@ public Q_SLOTS: ui_widget_adv.selected_feature->clear(); classif->fill_display_combo_box(ui_widget.display, ui_widget_adv.selected_feature); if (index >= ui_widget.display->count()) + { ui_widget.display->setCurrentIndex(1); + change_color (classif, 1); + } else + { ui_widget.display->setCurrentIndex(index); + change_color (classif, index); + } ui_widget_adv.selected_feature->setCurrentIndex(0); } } @@ -448,12 +491,6 @@ public Q_SLOTS: dynamic_cast(it->second)->set_selection_item(selection_item); return it->second; } - else if (Scene_points_with_normal_item* points_item - = qobject_cast(item)) - return create_from_item(points_item); - else if (Scene_surface_mesh_item* mesh_item - = qobject_cast(item)) - return create_from_item(mesh_item); return NULL; } @@ -504,25 +541,68 @@ public Q_SLOTS: update_plugin_from_item(classif); return classif; } + + int get_classifier () + { + if (classifier->text() == QString(CGAL_CLASSIFICATION_ETHZ_ID)) + return 1; + if (classifier->text() == QString(CGAL_CLASSIFICATION_TENSORFLOW_ID)) + return 3; + if (classifier->text() == QString(CGAL_CLASSIFICATION_OPENCV_ID)) + return 2; + if (classifier->text() == QString(CGAL_CLASSIFICATION_SOWF_ID)) + return 0; + + std::cerr << "Error: unknown classifier" << std::endl; + return -1; + } void run (Item_classification_base* classif, int method, std::size_t subdivisions = 1, double smoothing = 0.5) { - classif->run (method, ui_widget.classifier->currentIndex(), subdivisions, smoothing); + classif->run (method, get_classifier(), subdivisions, smoothing); } - void on_classifier_changed (int index) + void on_help_clicked() { - if (index == 0) - { - dock_widget_adv->show(); - dock_widget_adv->raise(); - } - else - dock_widget_adv->hide(); + QMessageBox::information(dock_widget, QString("Classification"), + QString("Classification\n" + "\n" + "Welcome to CGAL Classification! Please read carefully this notice\n" + "before using the plugin.\n" + "\n" + "[QUICK INTRODUCTION]\n" + "\n" + "In order to classify, you need to perform the following steps:\n" + "\n" + "1. Compute the features\n" + "2. Set up the labels (ground, vegetation, etc.) that you need\n" + "3. Select a training set for each of these labels\n" + "4. Train the classifier\n" + "\n" + "You can then either select more inliers for training and train again\n" + "to improve the results, classify with or without regularization or\n" + "save the classifier's configuration.\n" + "\n" + "When loading a classifier's configuration, the computed features\n" + "should be the same (same number of scales, etc.) and the labels should\n" + "be the same as when the classifier's configuration was saved.\n" + "\n" + "For more information, please refer to the CGAL manual.\n" + "\n" + "[IMPORTANT NOTICE ON SAVING CLASSIFIED ITEMS]\n" + "\n" + "If you intend to save the file after classifying, PLEASE CLOSE THE\n" + "CLASSIFICATION PLUGIN FIRST: for visualization, colors are saved in\n" + "the point set. If you do not close the classification plugin, colors\n" + "will be saved and might overwrite existing colors of the point cloud.\n" + "\n" + "Classification results will be saved if you use the PLY or LAS\n" + "formats. Training will be saved if you use the PLY format.\n")); + } - + void on_compute_features_button_clicked() { Item_classification_base* classif @@ -533,17 +613,26 @@ public Q_SLOTS: return; } - bool ok = false; - int nb_scales = QInputDialog::getInt((QWidget*)mw, - tr("Compute Features"), // dialog title - tr("Number of scales:"), // field label - 5, 1, 99, 1, &ok); - if (!ok) + QMultipleInputDialog dialog ("Compute Features", mw); + QSpinBox* scales = dialog.add ("Number of scales:"); + scales->setRange (1, 99); + scales->setValue (5); + + QDoubleSpinBox* voxel_size = dialog.add ("Voxel size (0 for automatic):"); + voxel_size->setRange (0.0, 10000.0); + voxel_size->setValue (0.0); + voxel_size->setSingleStep (0.01); + + if (dialog.exec() != QDialog::Accepted) return; QApplication::setOverrideCursor(Qt::WaitCursor); - classif->compute_features (std::size_t(nb_scales)); + float vsize = float(voxel_size->value()); + if (vsize == 0.f) + vsize = -1.f; // auto value + + classif->compute_features (std::size_t(scales->value()), vsize); update_plugin_from_item(classif); QApplication::restoreOverrideCursor(); @@ -562,18 +651,19 @@ public Q_SLOTS: QString filename; - if (ui_widget.classifier->currentIndex() == 0) + int classifier = get_classifier(); + if (classifier == 0) // Sum of Weighted Featuers filename = QFileDialog::getSaveFileName(mw, tr("Save classification configuration"), tr("%1 (CGAL classif config).xml").arg(classif->item()->name()), "CGAL classification configuration (*.xml);;"); - else if (ui_widget.classifier->currentIndex() == 1) + else if (classifier == 1) // Random Forest (ETHZ) filename = QFileDialog::getSaveFileName(mw, tr("Save classification configuration"), tr("%1 (ETHZ random forest config).gz").arg(classif->item()->name()), "Compressed ETHZ random forest configuration (*.gz);;"); #ifdef CGAL_LINKED_WITH_OPENCV - else if (ui_widget.classifier->currentIndex() == 2) + else if (classifier == 2) // Random Forest (OpenCV) filename = QFileDialog::getSaveFileName(mw, tr("Save classification configuration"), tr("%1 (OpenCV %2.%3 random forest config).xml") @@ -584,6 +674,13 @@ public Q_SLOTS: .arg(CV_MAJOR_VERSION) .arg(CV_MINOR_VERSION)); #endif +#ifdef CGAL_LINKED_WITH_TENSORFLOW + else if (classifier == 3) // Neural Network (TensorFlow) + filename = QFileDialog::getSaveFileName(mw, + tr("Save classification configuration"), + tr("%1 (CGAL Neural Network config).xml").arg(classif->item()->name()), + "CGAL TensorFlow Neural Network classification configuration (*.xml);;"); +#endif if (filename == QString()) return; @@ -591,8 +688,7 @@ public Q_SLOTS: QApplication::setOverrideCursor(Qt::WaitCursor); - classif->save_config (filename.toStdString().c_str(), - ui_widget.classifier->currentIndex()); + classif->save_config (filename.toStdString().c_str(), classifier); QApplication::restoreOverrideCursor(); @@ -609,18 +705,19 @@ public Q_SLOTS: } QString filename; - if (ui_widget.classifier->currentIndex() == 0) + int classifier = get_classifier(); + if (classifier == 0) // SOWF filename = QFileDialog::getOpenFileName(mw, tr("Open CGAL classification configuration"), ".", "CGAL classification configuration (*.xml);;All Files (*)"); - else if (ui_widget.classifier->currentIndex() == 1) + else if (classifier == 1) // ETHZ filename = QFileDialog::getOpenFileName(mw, tr("Open ETHZ random forest configuration"), ".", "Compressed ETHZ random forest configuration (*.gz);;All Files (*)"); #ifdef CGAL_LINKED_WITH_OPENCV - else if (ui_widget.classifier->currentIndex() == 2) + else if (classifier == 2) // OpenCV filename = QFileDialog::getOpenFileName(mw, tr("Open OpenCV %2.%3 random forest configuration") .arg(CV_MAJOR_VERSION) @@ -630,14 +727,21 @@ public Q_SLOTS: .arg(CV_MAJOR_VERSION) .arg(CV_MINOR_VERSION)); #endif +#ifdef CGAL_LINKED_WITH_TENSORFLOW + else if (classifier == 3) // TensorFlow + filename = QFileDialog::getOpenFileName(mw, + tr("Open CGAL Neural Network classification configuration"), + ".", + tr("CGAL Neural Network classification configuration (*.xml);;All Files (*)")); +#endif if (filename == QString()) return; QApplication::setOverrideCursor(Qt::WaitCursor); - classif->load_config (filename.toStdString().c_str(), - ui_widget.classifier->currentIndex()); + classif->load_config (filename.toStdString().c_str(), classifier); + update_plugin_from_item(classif); run (classif, 0); @@ -645,7 +749,32 @@ public Q_SLOTS: item_changed(classif->item()); } + void change_color (Item_classification_base* classif, int index) + { + float vmin = std::numeric_limits::infinity(); + float vmax = std::numeric_limits::infinity(); + + classif->change_color (index, &vmin, &vmax); + if (vmin == std::numeric_limits::infinity() || vmax == std::numeric_limits::infinity()) + { + ui_widget.minDisplay->setEnabled(false); + ui_widget.minDisplay->setText("Min"); + ui_widget.maxDisplay->setEnabled(false); + ui_widget.maxDisplay->setText("Max"); + } + else + { + ui_widget.minDisplay->setEnabled(true); + ui_widget.minDisplay->setText(tr("Min (%1)").arg(vmin)); + ui_widget.maxDisplay->setEnabled(true); + ui_widget.maxDisplay->setText(tr("Max (%1)").arg(vmax)); + } + + item_changed(classif->item()); + } + + void on_display_button_clicked(int index) { Item_classification_base* classif @@ -653,7 +782,87 @@ public Q_SLOTS: if(!classif) return; - classif->change_color (index); + change_color (classif, index); + } + + float display_button_value (QPushButton* button) + { + std::string text = button->text().toStdString(); + + std::size_t pos1 = text.find('('); + if (pos1 == std::string::npos) + return std::numeric_limits::infinity(); + std::size_t pos2 = text.find(')'); + if (pos2 == std::string::npos) + return std::numeric_limits::infinity(); + + std::string fstring (text.begin() + pos1 + 1, + text.begin() + pos2); + + return float (std::atof(fstring.c_str())); + } + + void on_min_display_button_clicked() + { + Item_classification_base* classif + = get_classification(); + if(!classif) + return; + + float vmin = display_button_value (ui_widget.minDisplay); + float vmax = display_button_value (ui_widget.maxDisplay); + + if (vmin == std::numeric_limits::infinity() + || vmax == std::numeric_limits::infinity()) + return; + + bool ok = false; + vmin = float(QInputDialog::getDouble((QWidget*)mw, + tr("Set display ramp minimum value (saturate under):"), + tr("Minimum value (pale blue):"), + double(vmin), + -10000000.0, + double(vmax), 5, &ok)); + if (!ok) + return; + + int index = ui_widget.display->currentIndex(); + + classif->change_color (index, &vmin, &vmax); + ui_widget.minDisplay->setText(tr("Min* (%1)").arg(vmin)); + + item_changed(classif->item()); + } + + void on_max_display_button_clicked() + { + Item_classification_base* classif + = get_classification(); + if(!classif) + return; + + float vmin = display_button_value (ui_widget.minDisplay); + float vmax = display_button_value (ui_widget.maxDisplay); + + if (vmin == std::numeric_limits::infinity() + || vmax == std::numeric_limits::infinity()) + return; + + bool ok = false; + vmax = float(QInputDialog::getDouble((QWidget*)mw, + tr("Set display ramp maximum value (saturate over):"), + tr("Maximum value (dark red):"), + double(vmax), + double(vmin), + 10000000.0, 5, &ok)); + if (!ok) + return; + + int index = ui_widget.display->currentIndex(); + + classif->change_color (index, &vmin, &vmax); + ui_widget.maxDisplay->setText(tr("Max* (%1)").arg(vmax)); + item_changed(classif->item()); } @@ -845,6 +1054,7 @@ public Q_SLOTS: add_new_label (classif, n); add_label_button(); + update_plugin_from_item(classif); } void on_use_config_building_clicked() @@ -1065,6 +1275,68 @@ public Q_SLOTS: (bbox.zmin() + bbox.zmax()) / 2.) + offset); } + void on_statistics_clicked() + { + Item_classification_base* classif + = get_classification(); + if(!classif) + { + print_message("Error: there is no point set classification item!"); + return; + } + + QApplication::setOverrideCursor(Qt::WaitCursor); + std::string str = classif->feature_statistics(); + QApplication::restoreOverrideCursor(); + + QMultipleInputDialog dialog ("Feature Statistics", mw); + QLabel* text = dialog.add (""); + text->setText(str.c_str()); + dialog.exec_no_cancel(); + } + + void on_switch_classifier_clicked() + { + QMultipleInputDialog dialog ("Which classifier do you want to use?", mw); + + QRadioButton* ethz = dialog.add (CGAL_CLASSIFICATION_ETHZ_ID); + ethz->setChecked(true); + + QRadioButton* sowf = dialog.add (CGAL_CLASSIFICATION_SOWF_ID); + +#ifdef CGAL_LINKED_WITH_TENSORFLOW + QRadioButton* tensorflow = dialog.add (CGAL_CLASSIFICATION_TENSORFLOW_ID); +#endif + +#ifdef CGAL_LINKED_WITH_OPENCV + QRadioButton* opencv = dialog.add (CGAL_CLASSIFICATION_OPENCV_ID); +#endif + + if (dialog.exec() != QDialog::Accepted) + return; + + if (ethz->isChecked()) + classifier->setText(CGAL_CLASSIFICATION_ETHZ_ID); + else if (sowf->isChecked()) + classifier->setText(CGAL_CLASSIFICATION_SOWF_ID); +#ifdef CGAL_LINKED_WITH_TENSORFLOW + else if (tensorflow->isChecked()) + classifier->setText(CGAL_CLASSIFICATION_TENSORFLOW_ID); +#endif +#ifdef CGAL_LINKED_WITH_OPENCV + else if (opencv->isChecked()) + classifier->setText(CGAL_CLASSIFICATION_OPENCV_ID); +#endif + + if (sowf->isChecked()) + { + dock_widget_adv->show(); + dock_widget_adv->raise(); + } + else + dock_widget_adv->hide(); + } + void on_train_clicked() { Item_classification_base* classif @@ -1075,41 +1347,48 @@ public Q_SLOTS: return; } - int nb_trials = 0; - int num_trees = 0; - int max_depth = 0; - - if (ui_widget.classifier->currentIndex() == 0) + QMultipleInputDialog dialog ("Train Classifier", mw); + + int classifier = get_classifier(); + if (classifier == 0) // SOWF { - bool ok = false; - nb_trials = QInputDialog::getInt((QWidget*)mw, - tr("Train Classifier"), // dialog title - tr("Number of trials:"), // field label - 800, 1, 99999, 50, &ok); - if (!ok) - return; + QSpinBox* trials = dialog.add ("Number of trials: ", "trials"); + trials->setRange (1, 99999); + trials->setValue (800); } - else + else if (classifier == 1 || classifier == 2) // random forest { - QMultipleInputDialog dialog ("Train Random Forest Classifier", mw); - QSpinBox* trees = dialog.add ("Number of trees: "); + QSpinBox* trees = dialog.add ("Number of trees: ", "num_trees"); trees->setRange (1, 9999); trees->setValue (25); - QSpinBox* depth = dialog.add ("Maximum depth of tree: "); + QSpinBox* depth = dialog.add ("Maximum depth of tree: ", "max_depth"); depth->setRange (1, 9999); depth->setValue (20); - - if (dialog.exec() != QDialog::Accepted) - return; - num_trees = trees->value(); - max_depth = depth->value(); } + else if (classifier == 3) // neural network + { + QSpinBox* trials = dialog.add ("Number of trials: ", "trials"); + trials->setRange (1, 99999); + trials->setValue (500); + QDoubleSpinBox* rate = dialog.add ("Learning rate: ", "learning_rate"); + rate->setRange (0.00001, 10000.0); + rate->setValue (0.001); + rate->setDecimals (5); + QSpinBox* batch = dialog.add ("Batch size: ", "batch_size"); + batch->setRange (1, 2000000000); + batch->setValue (1000); + dialog.add ("Hidden layer size(s): ", "hidden_layers"); + QCheckBox* restart = dialog.add ("Restart from scratch: ", "restart"); + restart->setChecked (false); + } + + if (dialog.exec() != QDialog::Accepted) + return; QApplication::setOverrideCursor(Qt::WaitCursor); CGAL::Real_timer t; t.start(); - classif->train(ui_widget.classifier->currentIndex(), nb_trials, - num_trees, max_depth); + classif->train(classifier, dialog); t.stop(); std::cerr << "Done in " << t.time() << " second(s)" << std::endl; QApplication::restoreOverrideCursor(); @@ -1170,6 +1449,10 @@ public Q_SLOTS: connect(change_color, SIGNAL(triggered()), this, SLOT(on_color_changed_clicked())); + QAction* change_name = label_buttons.back().menu->addAction ("Change name"); + connect(change_name, SIGNAL(triggered()), this, + SLOT(on_name_changed_clicked())); + QAction* create = label_buttons.back().menu->addAction ("Create point set item from labeled points"); connect(create, SIGNAL(triggered()), this, SLOT(on_create_point_set_item())); @@ -1244,7 +1527,7 @@ public Q_SLOTS: label_buttons.erase (label_buttons.begin() + position); add_label_button(); } - + update_plugin_from_item(classif); item_changed(classif->item()); } @@ -1270,7 +1553,11 @@ public Q_SLOTS: int position = row_index * 3 + column_index; QColor color = label_buttons[position].color; - color = QColorDialog::getColor(color, (QWidget*)mw, "Change of color of label"); + color = QColorDialog::getColor(color, (QWidget*)mw, "Change color of label"); + + if (!color.isValid()) + return; + label_buttons[position].change_color (color); classif->change_label_color (position, color); @@ -1279,6 +1566,47 @@ public Q_SLOTS: item_changed(classif->item()); } + void on_name_changed_clicked() + { + Item_classification_base* classif + = get_classification(); + if(!classif) + { + print_message("Error: there is no point set classification item!"); + return; + } + + QPushButton* label_clicked = qobject_cast(QObject::sender()->parent()->parent()); + if (label_clicked == NULL) + std::cerr << "Error" << std::endl; + else + { + int index = ui_widget.labelGrid->indexOf(label_clicked); + int row_index, column_index, row_span, column_span; + ui_widget.labelGrid->getItemPosition(index, &row_index, &column_index, &row_span, &column_span); + + int position = row_index * 3 + column_index; + + bool ok; + QString name = + QInputDialog::getText((QWidget*)mw, + tr("Change name of label"), // dialog title + tr("New name:"), // field label + QLineEdit::Normal, + classif->label(position)->name().c_str(), + &ok); + + if (!ok) + return; + + classif->change_label_name (position, name.toStdString()); + } + + update_plugin_from_item(classif); + classif->update_color (); + item_changed(classif->item()); + } + void on_add_selection_to_training_set_clicked() { Item_classification_base* classif @@ -1311,10 +1639,7 @@ public Q_SLOTS: Item_classification_base* classif = get_classification(); if(!classif) - { - print_message("Error: there is no point set classification item!"); return; - } if (classif->number_of_features() <= (std::size_t)v) return; @@ -1407,16 +1732,19 @@ private: QDockWidget* dock_widget; QDockWidget* dock_widget_adv; - QAction* action_train; + QAction* action_statistics; QAction* action_reset_local; QAction* action_reset; QAction* action_random_region; QAction* action_validate; - QAction* action_save_config; - QAction* action_load_config; + + QAction* classifier; + QAction* action_train; QAction* action_run; QAction* action_run_smoothed; QAction* action_run_graphcut; + QAction* action_save_config; + QAction* action_load_config; std::vector label_buttons; QPushButton* label_button; diff --git a/Polyhedron/demo/Polyhedron/Plugins/Classification/Classification_widget.ui b/Polyhedron/demo/Polyhedron/Plugins/Classification/Classification_widget.ui index 486e4a6d516..e96efa5c7d3 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Classification/Classification_widget.ui +++ b/Polyhedron/demo/Polyhedron/Plugins/Classification/Classification_widget.ui @@ -6,8 +6,8 @@ 0 0 - 289 - 154 + 411 + 194 @@ -21,112 +21,151 @@ - - - - - - - 75 - true - - - - Classification - - - - - - - Qt::Vertical - - - - - - - - 0 - 0 - - - - View: - - - - - - - 0 - - - - Real colors - - - - - Classification - - - - - Training sets - - - - - - - - - - 0 - 0 - + + + + Features + + + + + Training Sets + + + + + Classifier + + + + + + + + + + + Qt::Horizontal + + + 40 + 20 + + + + + + - Classifier: + + + + + :/cgal/icons/resources/help_button.png:/cgal/icons/resources/help_button.png - - - 1 + + + + + + + :/cgal/icons/check-off.png:/cgal/icons/check-off.png - - - Sum of Weighted Features - - - - - Random Forest (ETHZ) - - - + + + View + + + + + + 0 + + + + Real colors + + + + + Classification + + + + + Training sets + + + + + + + + Qt::Vertical + + + + + + + false + + + Min + + + false + + + + + + + Qt::Horizontal + + + + 65 + 20 + + + + + + + + false + + + Max + + + + + + + + 0 0 - - QFrame::StyledPanel - - - QFrame::Raised + + Labels @@ -155,6 +194,8 @@ - + + + diff --git a/Polyhedron/demo/Polyhedron/Plugins/Classification/Cluster_classification.cpp b/Polyhedron/demo/Polyhedron/Plugins/Classification/Cluster_classification.cpp index d8e20fd778f..a8ed8358285 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Classification/Cluster_classification.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/Classification/Cluster_classification.cpp @@ -12,6 +12,8 @@ #include #include +#include + #include #include @@ -21,6 +23,7 @@ Cluster_classification::Cluster_classification(Scene_points_with_normal_item* points) : m_points (points) + , m_input_is_las (false) { m_index_color = 1; @@ -59,6 +62,7 @@ Cluster_classification::Cluster_classification(Scene_points_with_normal_item* po boost::tie (las_classif, las_found) = m_points->point_set()->property_map("classification"); if (las_found) { + m_input_is_las = true; for (Point_set::const_iterator it = m_points->point_set()->begin(); it != m_points->point_set()->first_selected(); ++ it) { @@ -126,20 +130,26 @@ Cluster_classification::Cluster_classification(Scene_points_with_normal_item* po if (training_found) { - if (las_found && (m_training[*it] == 0 || m_training[*it] == 1)) // Unclassified class in LAS - m_training[*it] = -1; - else if (m_training[*it] != -1) - m_training[*it] = used_indices[std::size_t(m_training[*it])]; - if (c != -1) + if (std::size_t(current_idx) != used_indices.size()) // Empty indices -> reorder indices in point set + { + if (las_found && (m_training[*it] == 0 || m_training[*it] == 1)) // Unclassified class in LAS + m_training[*it] = -1; + else if (m_training[*it] != -1) + m_training[*it] = used_indices[std::size_t(m_training[*it])]; + } + if (c != -1 && m_training[*it] != -1) m_clusters[c].training() = m_training[*it]; } if (classif_found) { - if (las_found && (m_classif[*it] == 0 || m_classif[*it] == 1)) // Unclassified class in LAS - m_classif[*it] = -1; - else if (m_classif[*it] != -1) - m_classif[*it] = used_indices[std::size_t(m_classif[*it])]; - if (c != -1) + if (std::size_t(current_idx) != used_indices.size()) // Empty indices -> reorder indices in point set + { + if (las_found && (m_classif[*it] == 0 || m_classif[*it] == 1)) // Unclassified class in LAS + m_classif[*it] = -1; + else if (m_classif[*it] != -1) + m_classif[*it] = used_indices[std::size_t(m_classif[*it])]; + } + if (c != -1 && m_classif[*it] != -1) m_clusters[c].label() = m_classif[*it]; } } @@ -221,9 +231,12 @@ Cluster_classification::Cluster_classification(Scene_points_with_normal_item* po update_comments_of_point_set_item(); m_sowf = new Sum_of_weighted_features (m_labels, m_features); - m_ethz = new ETHZ_random_forest (m_labels, m_features); + m_ethz = NULL; #ifdef CGAL_LINKED_WITH_OPENCV - m_random_forest = new Random_forest (m_labels, m_features); + m_random_forest = NULL; +#endif +#ifdef CGAL_LINKED_WITH_TENSORFLOW + m_neural_network = NULL; #endif // Compute neighborhood @@ -272,17 +285,6 @@ Cluster_classification::Cluster_classification(Scene_points_with_normal_item* po Cluster_classification::~Cluster_classification() { - for (Point_set::const_iterator it = m_points->point_set()->begin(); - it != m_points->point_set()->first_selected(); ++ it) - { - int c = m_cluster_id[*it]; - if (c != -1) - { - m_training[*it] = m_clusters[c].training(); - m_classif[*it] = m_clusters[c].label(); - } - } - if (m_sowf != NULL) delete m_sowf; if (m_ethz != NULL) @@ -290,9 +292,100 @@ Cluster_classification::~Cluster_classification() #ifdef CGAL_LINKED_WITH_OPENCV if (m_random_forest != NULL) delete m_random_forest; +#endif +#ifdef CGAL_LINKED_WITH_TENSORFLOW + if (m_neural_network != NULL) + delete m_neural_network; #endif if (m_points != NULL) { + for (Point_set::const_iterator it = m_points->point_set()->begin(); + it != m_points->point_set()->first_selected(); ++ it) + { + int c = m_cluster_id[*it]; + if (c != -1) + { + m_training[*it] = m_clusters[c].training(); + m_classif[*it] = m_clusters[c].label(); + } + else + { + m_training[*it] = -1; + m_classif[*it] = -1; + } + } + + // For LAS saving, convert classification info in the LAS standard +// if (m_input_is_las) + { + Point_set::Property_map las_classif + = m_points->point_set()->add_property_map("classification", 0).first; + + std::vector label_indices; + + unsigned char custom = 19; + for (std::size_t i = 0; i < m_labels.size(); ++ i) + { + if (m_labels[i]->name() == "ground") + label_indices.push_back (2); + else if (m_labels[i]->name() == "low_veget") + label_indices.push_back (3); + else if (m_labels[i]->name() == "med_veget" || m_labels[i]->name() == "vegetation") + label_indices.push_back (4); + else if (m_labels[i]->name() == "high_veget") + label_indices.push_back (5); + else if (m_labels[i]->name() == "building" || m_labels[i]->name() == "roof") + label_indices.push_back (6); + else if (m_labels[i]->name() == "noise") + label_indices.push_back (7); + else if (m_labels[i]->name() == "reserved" || m_labels[i]->name() == "facade") + label_indices.push_back (8); + else if (m_labels[i]->name() == "water") + label_indices.push_back (9); + else if (m_labels[i]->name() == "rail") + label_indices.push_back (10); + else if (m_labels[i]->name() == "road_surface") + label_indices.push_back (11); + else if (m_labels[i]->name() == "reserved_2") + label_indices.push_back (12); + else if (m_labels[i]->name() == "wire_guard") + label_indices.push_back (13); + else if (m_labels[i]->name() == "wire_conduct") + label_indices.push_back (14); + else if (m_labels[i]->name() == "trans_tower") + label_indices.push_back (15); + else if (m_labels[i]->name() == "wire_connect") + label_indices.push_back (16); + else if (m_labels[i]->name() == "bridge_deck") + label_indices.push_back (17); + else if (m_labels[i]->name() == "high_noise") + label_indices.push_back (18); + else + label_indices.push_back (custom ++); + } + + for (Point_set::const_iterator it = m_points->point_set()->begin(); + it != m_points->point_set()->end(); ++ it) + { + int c = m_classif[*it]; + unsigned char lc = 1; // unclassified in LAS standard + if (c != -1) + lc = label_indices[std::size_t(c)]; + + las_classif[*it] = lc; + + int t = m_training[*it]; + unsigned char lt = 1; // unclassified in LAS standard + if (t != -1) + lt = label_indices[std::size_t(t)]; + + m_training[*it] = int(lt); + } + + m_points->point_set()->remove_property_map (m_classif); + } + + reset_colors(); erase_item(); } @@ -313,17 +406,7 @@ void Cluster_classification::backup_existing_colors_and_add_new() m_points->point_set()->remove_colors(); } - m_red = m_points->point_set()->add_property_map("red").first; - m_green = m_points->point_set()->add_property_map("green").first; - m_blue = m_points->point_set()->add_property_map("blue").first; - for (Point_set::const_iterator it = m_points->point_set()->begin(); - it != m_points->point_set()->first_selected(); ++ it) - { - m_red[*it] = 0; - m_green[*it] = 0; - m_blue[*it] = 0; - } - m_points->point_set()->check_colors(); + m_points->point_set()->add_colors(); } void Cluster_classification::reset_colors() @@ -334,40 +417,13 @@ void Cluster_classification::reset_colors() { for (Point_set::const_iterator it = m_points->point_set()->begin(); it != m_points->point_set()->first_selected(); ++ it) - { - m_red[*it] = m_color[*it][0]; - m_green[*it] = m_color[*it][1]; - m_blue[*it] = m_color[*it][2]; - } + m_points->point_set()->set_color(*it, m_color[*it]); + m_points->point_set()->remove_property_map(m_color); } } -// Write point set to .PLY file -bool Cluster_classification::write_output(std::ostream& stream) -{ - if (m_features.size() == 0) - return false; - - reset_indices(); - - stream.precision (std::numeric_limits::digits10 + 2); - - // std::vector colors; - // for (std::size_t i = 0; i < m_labels.size(); ++ i) - // { - // Color c = {{ (unsigned char)(m_labels[i].second.red()), - // (unsigned char)(m_labels[i].second.green()), - // (unsigned char)(m_labels[i].second.blue()) }}; - // colors.push_back (c); - // } - - // m_psc->write_classification_to_ply (stream); - return true; -} - - -void Cluster_classification::change_color (int index) +void Cluster_classification::change_color (int index, float* vmin, float* vmax) { m_index_color = index; @@ -377,138 +433,173 @@ void Cluster_classification::change_color (int index) static Color_ramp ramp; ramp.build_rainbow(); reset_indices(); + if (index_color == -1) // item color - { - for (Point_set::const_iterator it = m_points->point_set()->begin(); - it != m_points->point_set()->first_selected(); ++ it) - { - m_red[*it] = 0; - m_green[*it] = 0; - m_blue[*it] = 0; - } - } - else if (index_color == 0) // real colors - { - - for (Point_set::const_iterator it = m_points->point_set()->begin(); - it != m_points->point_set()->first_selected(); ++ it) - { - m_red[*it] = m_color[*it][0]; - m_green[*it] = m_color[*it][1]; - m_blue[*it] = m_color[*it][2]; - } - } - else if (index_color == 1) // classif - { - for (Point_set::const_iterator it = m_points->point_set()->begin(); - it != m_points->point_set()->first_selected(); ++ it) - { - QColor color (0, 0, 0); - int cid = m_cluster_id[*it]; - if (cid != -1) - { - std::size_t c = m_clusters[cid].label(); - - if (c != std::size_t(-1)) - color = m_label_colors[c]; - } - - m_red[*it] = color.red(); - m_green[*it] = color.green(); - m_blue[*it] = color.blue(); - } - } - else if (index_color == 2) // training - { - for (Point_set::const_iterator it = m_points->point_set()->begin(); - it != m_points->point_set()->first_selected(); ++ it) - { - QColor color (0, 0, 0); - int cid = m_cluster_id[*it]; - float div = 1; - - if (cid != -1) - { - int c = m_clusters[cid].training(); - int c2 = m_clusters[cid].label(); - - if (c != -1) - color = m_label_colors[std::size_t(c)]; - - if (c != c2) - div = 2; - } - m_red[*it] = (color.red() / div); - m_green[*it] = (color.green() / div); - m_blue[*it] = (color.blue() / div); - } - } - else if (index_color == 3) // clusters - { - for (Point_set::const_iterator it = m_points->point_set()->begin(); - it != m_points->point_set()->first_selected(); ++ it) - { - int cid = m_cluster_id[*it]; - - if (cid != -1) - { - srand(cid); - m_red[*it] = 64 + rand() % 192; - m_green[*it] = 64 + rand() % 192; - m_blue[*it] = 64 + rand() % 192; - } - else - { - m_red[*it] = 0; - m_green[*it] = 0; - m_blue[*it] = 0; - } - } - } + m_points->point_set()->remove_colors(); else { - Feature_handle feature = m_features[index_color - 4]; - - float max = 0.; - for (Point_set::const_iterator it = m_points->point_set()->begin(); - it != m_points->point_set()->first_selected(); ++ it) + if (!m_points->point_set()->has_colors()) + m_points->point_set()->add_colors(); + + if (index_color == 0) // real colors { - int cid = m_cluster_id[*it]; - if (cid != -1) + + for (Point_set::const_iterator it = m_points->point_set()->begin(); + it != m_points->point_set()->first_selected(); ++ it) + m_points->point_set()->set_color(*it, m_color[*it]); + } + else if (index_color == 1) // classif + { + for (Point_set::const_iterator it = m_points->point_set()->begin(); + it != m_points->point_set()->first_selected(); ++ it) { - if (feature->value(cid) > max) - max = feature->value(cid); + QColor color (0, 0, 0); + int cid = m_cluster_id[*it]; + if (cid != -1) + { + std::size_t c = m_clusters[cid].label(); + + if (c != std::size_t(-1)) + color = m_label_colors[c]; + } + + m_points->point_set()->set_color(*it, color); } } - - for (Point_set::const_iterator it = m_points->point_set()->begin(); - it != m_points->point_set()->first_selected(); ++ it) + else if (index_color == 2) // training { - int cid = m_cluster_id[*it]; - if (cid != -1) + for (Point_set::const_iterator it = m_points->point_set()->begin(); + it != m_points->point_set()->first_selected(); ++ it) { - float v = std::max (0.f, feature->value(cid) / max); - m_red[*it] = (unsigned char)(ramp.r(v) * 255); - m_green[*it] = (unsigned char)(ramp.g(v) * 255); - m_blue[*it] = (unsigned char)(ramp.b(v) * 255); + QColor color (0, 0, 0); + int cid = m_cluster_id[*it]; + float div = 1; + + if (cid != -1) + { + int c = m_clusters[cid].training(); + int c2 = m_clusters[cid].label(); + + if (c != -1) + color = m_label_colors[std::size_t(c)]; + + if (c != c2) + div = 2; + } + m_points->point_set()->set_color(*it, color.red() / div, color.green() / div, color.blue() / div); + } + } + else if (index_color == 3) // clusters + { + for (Point_set::const_iterator it = m_points->point_set()->begin(); + it != m_points->point_set()->first_selected(); ++ it) + { + int cid = m_cluster_id[*it]; + + if (cid != -1) + { + srand(cid); + m_points->point_set()->set_color(*it, 64 + rand() % 192, 64 + rand() % 192, 64 + rand() % 192); + } + else + { + m_points->point_set()->set_color(*it); + } + } + } + else + { + std::size_t corrected_index = index_color - 4; + if (corrected_index < m_labels.size()) // Display label probabilities + { + if (m_label_probabilities.size() <= corrected_index || + m_label_probabilities[corrected_index].size() != m_clusters.size()) + { + for (Point_set::const_iterator it = m_points->point_set()->begin(); + it != m_points->point_set()->first_selected(); ++ it) + m_points->point_set()->set_color(*it); + } + else + { + for (Point_set::const_iterator it = m_points->point_set()->begin(); + it != m_points->point_set()->first_selected(); ++ it) + { + int cid = m_cluster_id[*it]; + if (cid != -1) + { + float v = std::max (0.f, std::min(1.f, m_label_probabilities[corrected_index][cid])); + m_points->point_set()->set_color(*it, ramp.r(v) * 255, ramp.g(v) * 255, ramp.b(v) * 255); + } + else + m_points->point_set()->set_color(*it); + } + } } else { - m_red[*it] = 0; - m_green[*it] = 0; - m_blue[*it] = 0; + corrected_index -= m_labels.size(); + if (corrected_index >= m_features.size()) + { + std::cerr << "Error: trying to access feature " << corrected_index << " out of " << m_features.size() << std::endl; + return; + } + + Feature_handle feature = m_features[corrected_index]; + + float min = std::numeric_limits::max(); + float max = -std::numeric_limits::max(); + + if (vmin != NULL && vmax != NULL + && *vmin != std::numeric_limits::infinity() + && *vmax != std::numeric_limits::infinity()) + { + min = *vmin; + max = *vmax; + } + else + { + for (Point_set::const_iterator it = m_points->point_set()->begin(); + it != m_points->point_set()->first_selected(); ++ it) + { + int cid = m_cluster_id[*it]; + if (cid != -1) + { + if (feature->value(cid) > max) + max = feature->value(cid); + if (feature->value(cid) < min) + min = feature->value(cid); + } + } + } + + for (Point_set::const_iterator it = m_points->point_set()->begin(); + it != m_points->point_set()->first_selected(); ++ it) + { + int cid = m_cluster_id[*it]; + if (cid != -1) + { + float v = (feature->value(cid) - min) / (max - min); + if (v < 0.f) v = 0.f; + if (v > 1.f) v = 1.f; + + m_points->point_set()->set_color(*it, ramp.r(v) * 255, ramp.g(v) * 255, ramp.b(v) * 255); + } + else + m_points->point_set()->set_color(*it); + } + + if (vmin != NULL && vmax != NULL) + { + *vmin = min; + *vmax = max; + } } } } - + for (Point_set::const_iterator it = m_points->point_set()->first_selected(); it != m_points->point_set()->end(); ++ it) - { - m_red[*it] = 255; - m_green[*it] = 0; - m_blue[*it] = 0; - } - + m_points->point_set()->set_color(*it, 255, 0, 0); } int Cluster_classification::real_index_color() const @@ -532,13 +623,18 @@ void Cluster_classification::reset_indices () *(indices.begin() + i) = idx ++; } -void Cluster_classification::compute_features (std::size_t nb_scales) +void Cluster_classification::compute_features (std::size_t nb_scales, float voxel_size) { CGAL_assertion (!(m_points->point_set()->empty())); reset_indices(); - std::cerr << "Computing pointwise features with " << nb_scales << " scale(s)" << std::endl; + std::cerr << "Computing pointwise features with " << nb_scales << " scale(s) and "; + if (voxel_size == -1) + std::cerr << "automatic voxel size" << std::endl; + else + std::cerr << "voxel size = " << voxel_size << std::endl; + m_features.clear(); Point_set::Vector_map normal_map; @@ -556,7 +652,7 @@ void Cluster_classification::compute_features (std::size_t nb_scales) Feature_set pointwise_features; - Generator generator (*(m_points->point_set()), m_points->point_set()->point_map(), nb_scales); + Generator generator (*(m_points->point_set()), m_points->point_set()->point_map(), nb_scales, voxel_size); CGAL::Real_timer t; t.start(); @@ -620,11 +716,24 @@ void Cluster_classification::compute_features (std::size_t nb_scales) delete m_sowf; m_sowf = new Sum_of_weighted_features (m_labels, m_features); - delete m_ethz; - m_ethz = new ETHZ_random_forest (m_labels, m_features); + if (m_ethz != NULL) + { + delete m_ethz; + m_ethz = NULL; + } #ifdef CGAL_LINKED_WITH_OPENCV - delete m_random_forest; - m_random_forest = new Random_forest (m_labels, m_features); + if (m_random_forest != NULL) + { + delete m_random_forest; + m_random_forest = NULL; + } +#endif +#ifdef CGAL_LINKED_WITH_TENSORFLOW + if (m_neural_network != NULL) + { + delete m_neural_network; + m_neural_network = NULL; + } #endif std::cerr << "Features = " << m_features.size() << std::endl; @@ -696,8 +805,7 @@ void Cluster_classification::add_remaining_point_set_properties_as_features(Feat } } -void Cluster_classification::train(int classifier, unsigned int nb_trials, - std::size_t num_trees, std::size_t max_depth) +void Cluster_classification::train(int classifier, const QMultipleInputDialog& dialog) { if (m_features.size() == 0) { @@ -706,6 +814,11 @@ void Cluster_classification::train(int classifier, unsigned int nb_trials, } reset_indices(); + m_label_probabilities.clear(); + m_label_probabilities.resize (m_labels.size()); + for (std::size_t i = 0; i < m_label_probabilities.size(); ++ i) + m_label_probabilities[i].resize (m_clusters.size(), -1); + std::vector nb_label (m_labels.size(), 0); std::size_t nb_total = 0; @@ -730,30 +843,80 @@ void Cluster_classification::train(int classifier, unsigned int nb_trials, if (classifier == 0) { - m_sowf->train(training, nb_trials); + m_sowf->train(training, dialog.get("trials")->value()); CGAL::Classification::classify (m_clusters, m_labels, *m_sowf, - indices); + indices, m_label_probabilities); } else if (classifier == 1) { - m_ethz->train(training, true, num_trees, max_depth); + if (m_ethz != NULL) + delete m_ethz; + m_ethz = new ETHZ_random_forest (m_labels, m_features); + m_ethz->train(training, true, + dialog.get("num_trees")->value(), + dialog.get("max_depth")->value()); CGAL::Classification::classify (m_clusters, m_labels, *m_ethz, - indices); + indices, m_label_probabilities); } - else + else if (classifier == 2) { #ifdef CGAL_LINKED_WITH_OPENCV if (m_random_forest != NULL) delete m_random_forest; m_random_forest = new Random_forest (m_labels, m_features, - int(max_depth), 5, 15, - int(num_trees)); + dialog.get("max_depth")->value(), 5, 15, + dialog.get("num_trees")->value()); m_random_forest->train (training); CGAL::Classification::classify (m_clusters, m_labels, *m_random_forest, - indices); + indices, m_label_probabilities); +#endif + } + else if (classifier == 3) + { +#ifdef CGAL_LINKED_WITH_TENSORFLOW + if (m_neural_network != NULL) + { + if (m_neural_network->initialized()) + { + if (dialog.get("restart")->isChecked()) + { + delete m_neural_network; + m_neural_network = new Neural_network (m_labels, m_features); + } + } + else + { + delete m_neural_network; + m_neural_network = new Neural_network (m_labels, m_features); + } + } + else + m_neural_network = new Neural_network (m_labels, m_features); + + std::vector hidden_layers; + + std::string hl_input = dialog.get("hidden_layers")->text().toStdString(); + if (hl_input != "") + { + std::istringstream iss(hl_input); + int s; + while (iss >> s) + hidden_layers.push_back (std::size_t(s)); + } + + m_neural_network->train (training, + dialog.get("restart")->isChecked(), + dialog.get("trials")->value(), + dialog.get("learning_rate")->value(), + dialog.get("batch_size")->value(), + hidden_layers); + + CGAL::Classification::classify (m_clusters, + m_labels, *m_neural_network, + indices, m_label_probabilities); #endif } @@ -778,11 +941,36 @@ bool Cluster_classification::run (int method, int classifier, if (classifier == 0) run (method, *m_sowf, subdivisions, smoothing); else if (classifier == 1) + { + if (m_ethz == NULL) + { + std::cerr << "Error: ETHZ Random Forest must be trained or have a configuration loaded first" << std::endl; + return false; + } run (method, *m_ethz, subdivisions, smoothing); + } + else if (classifier == 2) + { #ifdef CGAL_LINKED_WITH_OPENCV - else + if (m_random_forest == NULL) + { + std::cerr << "Error: OpenCV Random Forest must be trained or have a configuration loaded first" << std::endl; + return false; + } run (method, *m_random_forest, subdivisions, smoothing); #endif + } + else if (classifier == 3) + { +#ifdef CGAL_LINKED_WITH_TENSORFLOW + if (m_neural_network == NULL) + { + std::cerr << "Error: TensorFlow Neural Network must be trained or have a configuration loaded first" << std::endl; + return false; + } + run (method, *m_neural_network, subdivisions, smoothing); +#endif + } return true; } diff --git a/Polyhedron/demo/Polyhedron/Plugins/Classification/Cluster_classification.h b/Polyhedron/demo/Polyhedron/Plugins/Classification/Cluster_classification.h index 190692f07c4..53753e7cbbb 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Classification/Cluster_classification.h +++ b/Polyhedron/demo/Polyhedron/Plugins/Classification/Cluster_classification.h @@ -97,7 +97,7 @@ class Cluster_classification : public Item_classification_base xcenter + dx, ycenter + dy, zcenter + dz); } - void compute_features (std::size_t nb_scales); + void compute_features (std::size_t nb_scales, float voxel_size); void add_remaining_point_set_properties_as_features(Feature_set& feature_set); void select_random_region(); @@ -202,12 +202,11 @@ class Cluster_classification : public Item_classification_base if (m_index_color == 1 || m_index_color == 2) change_color (m_index_color); } - void train(int classifier, unsigned int nb_trials, - std::size_t num_trees, std::size_t max_depth); + void train(int classifier, const QMultipleInputDialog& dialog); bool run (int method, int classifier, std::size_t subdivisions, double smoothing); void update_color () { change_color (m_index_color); } - void change_color (int index); + void change_color (int index, float* vmin = NULL, float* vmax = NULL); CGAL::Three::Scene_item* generate_one_item (const char* name, int label) const { @@ -255,8 +254,6 @@ class Cluster_classification : public Item_classification_base } - bool write_output(std::ostream& out); - QColor add_new_label (const char* name) { QColor out = Item_classification_base::add_new_label (name); @@ -287,13 +284,7 @@ class Cluster_classification : public Item_classification_base void fill_display_combo_box (QComboBox* cb, QComboBox* cb1) const { cb->addItem ("Clusters"); - for (std::size_t i = 0; i < m_features.size(); ++ i) - { - std::ostringstream oss; - oss << "Feature " << m_features[i]->name(); - cb->addItem (oss.str().c_str()); - cb1->addItem (oss.str().c_str()); - } + Item_classification_base::fill_display_combo_box(cb, cb1); } int real_index_color() const; @@ -391,17 +382,18 @@ class Cluster_classification : public Item_classification_base std::vector m_clusters; - Point_set::Property_map m_red; - Point_set::Property_map m_green; - Point_set::Property_map m_blue; Point_set::Property_map m_color; Point_set::Property_map m_cluster_id; Point_set::Property_map m_training; Point_set::Property_map m_classif; + std::vector > m_label_probabilities; + int m_index_color; boost::shared_ptr m_eigen; + + bool m_input_is_las; }; // end class Cluster_classification diff --git a/Polyhedron/demo/Polyhedron/Plugins/Classification/Item_classification_base.h b/Polyhedron/demo/Polyhedron/Plugins/Classification/Item_classification_base.h index 111b75a3f9e..6aa645c828a 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Classification/Item_classification_base.h +++ b/Polyhedron/demo/Polyhedron/Plugins/Classification/Item_classification_base.h @@ -4,14 +4,20 @@ #include #include +#include +#include +#include #include #include #include -#include +#include #ifdef CGAL_LINKED_WITH_OPENCV -#include +#include +#endif +#ifdef CGAL_LINKED_WITH_TENSORFLOW +#include #endif class Item_classification_base @@ -22,10 +28,13 @@ public: typedef CGAL::Classification::Label_set Label_set; typedef CGAL::Classification::Feature_set Feature_set; typedef CGAL::Classification::Sum_of_weighted_features_classifier Sum_of_weighted_features; - typedef CGAL::Classification::ETHZ_random_forest_classifier ETHZ_random_forest; + typedef CGAL::Classification::ETHZ::Random_forest_classifier ETHZ_random_forest; #ifdef CGAL_LINKED_WITH_OPENCV - typedef CGAL::Classification::OpenCV_random_forest_classifier Random_forest; + typedef CGAL::Classification::OpenCV::Random_forest_classifier Random_forest; +#endif +#ifdef CGAL_LINKED_WITH_TENSORFLOW + typedef CGAL::Classification::TensorFlow::Neural_network_classifier<> Neural_network; #endif public: @@ -38,8 +47,10 @@ public: virtual CGAL::Bbox_3 bbox() { return item()->bbox(); } - virtual void compute_features (std::size_t nb_scales) = 0; + virtual void compute_features (std::size_t nb_scales, float voxel_size) = 0; + virtual std::string feature_statistics () const { return std::string(); } + virtual void add_selection_to_training_set (std::size_t label) = 0; virtual void reset_training_set (std::size_t label) = 0; virtual void reset_training_set_of_selection() = 0; @@ -47,19 +58,16 @@ public: virtual void select_random_region() = 0; virtual void validate_selection () = 0; - virtual void train(int classifier, unsigned int nb_trials, - std::size_t num_trees, std::size_t max_depth) = 0; + virtual void train(int classifier, const QMultipleInputDialog&) = 0; virtual bool run (int method, int classifier, std::size_t subdivisions, double smoothing) = 0; virtual void update_color () = 0; - virtual void change_color (int index) = 0; + virtual void change_color (int index, float* vmin = NULL, float* vmax = NULL) = 0; virtual CGAL::Three::Scene_item* generate_one_item (const char* name, int label) const = 0; virtual void generate_one_item_per_label(std::vector& items, const char* name) const = 0; - virtual bool write_output(std::ostream& out) = 0; - bool features_computed() const { return (m_features.size() != 0); } std::size_t number_of_features() const { return m_features.size(); } Feature_handle feature(std::size_t i) { return m_features[i]; } @@ -84,6 +92,11 @@ public: delete m_random_forest; m_random_forest = new Random_forest (m_labels, m_features); #endif + +#ifdef CGAL_LINKED_WITH_TENSORFLOW + delete m_neural_network; + m_neural_network = new Neural_network (m_labels, m_features); +#endif return m_label_colors.back(); } @@ -102,7 +115,13 @@ public: delete m_random_forest; m_random_forest = new Random_forest (m_labels, m_features); #endif + +#ifdef CGAL_LINKED_WITH_TENSORFLOW + delete m_neural_network; + m_neural_network = new Neural_network (m_labels, m_features); +#endif } + virtual void clear_labels () { m_labels.clear(); @@ -118,12 +137,24 @@ public: delete m_random_forest; m_random_forest = new Random_forest (m_labels, m_features); #endif + +#ifdef CGAL_LINKED_WITH_TENSORFLOW + delete m_neural_network; + m_neural_network = new Neural_network (m_labels, m_features); +#endif } std::size_t number_of_labels() const { return m_labels.size(); } Label_handle label(std::size_t i) { return m_labels[i]; } virtual void fill_display_combo_box (QComboBox* cb, QComboBox* cb1) const { + for (std::size_t i = 0; i < m_labels.size(); ++ i) + { + std::ostringstream oss; + oss << "Label " << m_labels[i]->name(); + cb->addItem (oss.str().c_str()); + cb1->addItem (oss.str().c_str()); + } for (std::size_t i = 0; i < m_features.size(); ++ i) { std::ostringstream oss; @@ -151,10 +182,17 @@ public: std::ofstream f (filename, std::ios_base::out | std::ios_base::binary); m_ethz->save_configuration (f); } - else + else if (classifier == 2) { #ifdef CGAL_LINKED_WITH_OPENCV m_random_forest->save_configuration (filename); +#endif + } + else if (classifier == 3) + { +#ifdef CGAL_LINKED_WITH_TENSORFLOW + std::ofstream f (filename); + m_neural_network->save_configuration (f); #endif } } @@ -173,13 +211,24 @@ public: } else if (classifier == 1) { + if (m_ethz == NULL) + m_ethz = new ETHZ_random_forest (m_labels, m_features); std::ifstream f (filename, std::ios_base::in | std::ios_base::binary); m_ethz->load_configuration (f); } - else + else if (classifier == 2) { #ifdef CGAL_LINKED_WITH_OPENCV m_random_forest->load_configuration (filename); +#endif + } + else if (classifier == 3) + { +#ifdef CGAL_LINKED_WITH_TENSORFLOW + if (m_neural_network == NULL) + m_neural_network = new Neural_network (m_labels, m_features); + std::ifstream f (filename); + m_neural_network->load_configuration (f, true); #endif } } @@ -189,6 +238,10 @@ public: { m_label_colors[position] = color; } + void change_label_name (std::size_t position, const std::string& name) + { + m_labels[position]->set_name (name); + } QColor get_new_label_color (const std::string& name) { @@ -248,6 +301,9 @@ protected: #ifdef CGAL_LINKED_WITH_OPENCV Random_forest* m_random_forest; #endif +#ifdef CGAL_LINKED_WITH_TENSORFLOW + Neural_network* m_neural_network; +#endif }; diff --git a/Polyhedron/demo/Polyhedron/Plugins/Classification/Point_set_item_classification.cpp b/Polyhedron/demo/Polyhedron/Plugins/Classification/Point_set_item_classification.cpp index 1096fe5d067..2b64ea7349a 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Classification/Point_set_item_classification.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/Classification/Point_set_item_classification.cpp @@ -17,8 +17,9 @@ #include Point_set_item_classification::Point_set_item_classification(Scene_points_with_normal_item* points) - : m_points (points), - m_generator (NULL) + : m_points (points) + , m_generator (NULL) + , m_input_is_las (false) { m_index_color = 1; @@ -58,6 +59,7 @@ Point_set_item_classification::Point_set_item_classification(Scene_points_with_n boost::tie (las_classif, las_found) = m_points->point_set()->property_map("classification"); if (las_found) { + m_input_is_las = true; for (Point_set::const_iterator it = m_points->point_set()->begin(); it != m_points->point_set()->first_selected(); ++ it) { @@ -216,9 +218,12 @@ Point_set_item_classification::Point_set_item_classification(Scene_points_with_n update_comments_of_point_set_item(); m_sowf = new Sum_of_weighted_features (m_labels, m_features); - m_ethz = new ETHZ_random_forest (m_labels, m_features); + m_ethz = NULL; #ifdef CGAL_LINKED_WITH_OPENCV - m_random_forest = new Random_forest (m_labels, m_features); + m_random_forest = NULL; +#endif +#ifdef CGAL_LINKED_WITH_TENSORFLOW + m_neural_network = NULL; #endif } @@ -232,14 +237,89 @@ Point_set_item_classification::~Point_set_item_classification() #ifdef CGAL_LINKED_WITH_OPENCV if (m_random_forest != NULL) delete m_random_forest; +#endif +#ifdef CGAL_LINKED_WITH_TENSORFLOW + if (m_neural_network != NULL) + delete m_neural_network; #endif if (m_generator != NULL) delete m_generator; if (m_points != NULL) + { + // For LAS saving, convert classification info in the LAS standard + if (m_input_is_las) { - reset_colors(); - erase_item(); + Point_set::Property_map las_classif + = m_points->point_set()->add_property_map("classification", 0).first; + + std::vector label_indices; + + unsigned char custom = 19; + for (std::size_t i = 0; i < m_labels.size(); ++ i) + { + if (m_labels[i]->name() == "ground") + label_indices.push_back (2); + else if (m_labels[i]->name() == "low_veget") + label_indices.push_back (3); + else if (m_labels[i]->name() == "med_veget" || m_labels[i]->name() == "vegetation") + label_indices.push_back (4); + else if (m_labels[i]->name() == "high_veget") + label_indices.push_back (5); + else if (m_labels[i]->name() == "building" || m_labels[i]->name() == "roof") + label_indices.push_back (6); + else if (m_labels[i]->name() == "noise") + label_indices.push_back (7); + else if (m_labels[i]->name() == "reserved" || m_labels[i]->name() == "facade") + label_indices.push_back (8); + else if (m_labels[i]->name() == "water") + label_indices.push_back (9); + else if (m_labels[i]->name() == "rail") + label_indices.push_back (10); + else if (m_labels[i]->name() == "road_surface") + label_indices.push_back (11); + else if (m_labels[i]->name() == "reserved_2") + label_indices.push_back (12); + else if (m_labels[i]->name() == "wire_guard") + label_indices.push_back (13); + else if (m_labels[i]->name() == "wire_conduct") + label_indices.push_back (14); + else if (m_labels[i]->name() == "trans_tower") + label_indices.push_back (15); + else if (m_labels[i]->name() == "wire_connect") + label_indices.push_back (16); + else if (m_labels[i]->name() == "bridge_deck") + label_indices.push_back (17); + else if (m_labels[i]->name() == "high_noise") + label_indices.push_back (18); + else + label_indices.push_back (custom ++); + } + + for (Point_set::const_iterator it = m_points->point_set()->begin(); + it != m_points->point_set()->end(); ++ it) + { + int c = m_classif[*it]; + unsigned char lc = 1; // unclassified in LAS standard + if (c != -1) + lc = label_indices[std::size_t(c)]; + + las_classif[*it] = lc; + + int t = m_training[*it]; + unsigned char lt = 1; // unclassified in LAS standard + if (t != -1) + lt = label_indices[std::size_t(t)]; + + m_training[*it] = int(lt); + } + + m_points->point_set()->remove_property_map (m_classif); } + + reset_colors(); + erase_item(); + } + } @@ -256,18 +336,8 @@ void Point_set_item_classification::backup_existing_colors_and_add_new() m_points->point_set()->remove_colors(); } - - m_red = m_points->point_set()->add_property_map("red").first; - m_green = m_points->point_set()->add_property_map("green").first; - m_blue = m_points->point_set()->add_property_map("blue").first; - for (Point_set::const_iterator it = m_points->point_set()->begin(); - it != m_points->point_set()->first_selected(); ++ it) - { - m_red[*it] = 0; - m_green[*it] = 0; - m_blue[*it] = 0; - } - m_points->point_set()->check_colors(); + + m_points->point_set()->add_colors(); } void Point_set_item_classification::reset_colors() @@ -278,40 +348,13 @@ void Point_set_item_classification::reset_colors() { for (Point_set::const_iterator it = m_points->point_set()->begin(); it != m_points->point_set()->first_selected(); ++ it) - { - m_red[*it] = m_color[*it][0]; - m_green[*it] = m_color[*it][1]; - m_blue[*it] = m_color[*it][2]; - } + m_points->point_set()->set_color(*it, m_color[*it]); + m_points->point_set()->remove_property_map(m_color); } } -// Write point set to .PLY file -bool Point_set_item_classification::write_output(std::ostream& stream) -{ - if (m_features.size() == 0) - return false; - - reset_indices(); - - stream.precision (std::numeric_limits::digits10 + 2); - - // std::vector colors; - // for (std::size_t i = 0; i < m_labels.size(); ++ i) - // { - // Color c = {{ (unsigned char)(m_labels[i].second.red()), - // (unsigned char)(m_labels[i].second.green()), - // (unsigned char)(m_labels[i].second.blue()) }}; - // colors.push_back (c); - // } - - // m_psc->write_classification_to_ply (stream); - return true; -} - - -void Point_set_item_classification::change_color (int index) +void Point_set_item_classification::change_color (int index, float* vmin, float* vmax) { m_index_color = index; @@ -321,92 +364,129 @@ void Point_set_item_classification::change_color (int index) static Color_ramp ramp; ramp.build_rainbow(); reset_indices(); + if (index_color == -1) // item color - { - for (Point_set::const_iterator it = m_points->point_set()->begin(); - it != m_points->point_set()->first_selected(); ++ it) - { - m_red[*it] = 0; - m_green[*it] = 0; - m_blue[*it] = 0; - } - } - else if (index_color == 0) // real colors - { - - for (Point_set::const_iterator it = m_points->point_set()->begin(); - it != m_points->point_set()->first_selected(); ++ it) - { - m_red[*it] = m_color[*it][0]; - m_green[*it] = m_color[*it][1]; - m_blue[*it] = m_color[*it][2]; - } - } - else if (index_color == 1) // classif - { - for (Point_set::const_iterator it = m_points->point_set()->begin(); - it != m_points->point_set()->first_selected(); ++ it) - { - QColor color (0, 0, 0); - std::size_t c = m_classif[*it]; - - if (c != std::size_t(-1)) - color = m_label_colors[c]; - - m_red[*it] = color.red(); - m_green[*it] = color.green(); - m_blue[*it] = color.blue(); - } - } - else if (index_color == 2) // training - { - for (Point_set::const_iterator it = m_points->point_set()->begin(); - it != m_points->point_set()->first_selected(); ++ it) - { - QColor color (0, 0, 0); - int c = m_training[*it]; - int c2 = m_classif[*it]; - - if (c != -1) - color = m_label_colors[std::size_t(c)]; - - float div = 1; - if (c != c2) - div = 2; - - m_red[*it] = (color.red() / div); - m_green[*it] = (color.green() / div); - m_blue[*it] = (color.blue() / div); - } - } + m_points->point_set()->remove_colors(); else + { + if (!m_points->point_set()->has_colors()) + m_points->point_set()->add_colors(); + + if (index_color == 0) // real colors { - Feature_handle feature = m_features[index_color - 3]; - - float max = 0.; - for (Point_set::const_iterator it = m_points->point_set()->begin(); - it != m_points->point_set()->first_selected(); ++ it) - if (feature->value(*it) > max) - max = feature->value(*it); for (Point_set::const_iterator it = m_points->point_set()->begin(); it != m_points->point_set()->first_selected(); ++ it) - { - float v = std::max (0.f, feature->value(*it) / max); - m_red[*it] = (unsigned char)(ramp.r(v) * 255); - m_green[*it] = (unsigned char)(ramp.g(v) * 255); - m_blue[*it] = (unsigned char)(ramp.b(v) * 255); - } + m_points->point_set()->set_color(*it, m_color[*it]); } + else if (index_color == 1) // classif + { + for (Point_set::const_iterator it = m_points->point_set()->begin(); + it != m_points->point_set()->first_selected(); ++ it) + { + QColor color (0, 0, 0); + std::size_t c = m_classif[*it]; + + if (c != std::size_t(-1)) + color = m_label_colors[c]; + m_points->point_set()->set_color(*it, color); + } + } + else if (index_color == 2) // training + { + for (Point_set::const_iterator it = m_points->point_set()->begin(); + it != m_points->point_set()->first_selected(); ++ it) + { + QColor color (0, 0, 0); + int c = m_training[*it]; + int c2 = m_classif[*it]; + + if (c != -1) + color = m_label_colors[std::size_t(c)]; + + float div = 1; + if (c != c2) + div = 2; + + m_points->point_set()->set_color(*it, color.red() / div, color.green() / div, color.blue() / div); + } + } + else + { + std::size_t corrected_index = index_color - 3; + if (corrected_index < m_labels.size()) // Display label probabilities + { + if (m_label_probabilities.size() <= corrected_index || + m_label_probabilities[corrected_index].size() != m_points->point_set()->size()) + { + for (Point_set::const_iterator it = m_points->point_set()->begin(); + it != m_points->point_set()->first_selected(); ++ it) + m_points->point_set()->set_color(*it); + } + else + { + for (Point_set::const_iterator it = m_points->point_set()->begin(); + it != m_points->point_set()->first_selected(); ++ it) + { + float v = std::max (0.f, std::min(1.f, m_label_probabilities[corrected_index][*it])); + m_points->point_set()->set_color(*it, ramp.r(v) * 255, ramp.g(v) * 255, ramp.b(v) * 255); + } + } + } + else + { + corrected_index -= m_labels.size(); + if (corrected_index >= m_features.size()) + { + std::cerr << "Error: trying to access feature " << corrected_index << " out of " << m_features.size() << std::endl; + return; + } + Feature_handle feature = m_features[corrected_index]; + + float min = std::numeric_limits::max(); + float max = -std::numeric_limits::max(); + + if (vmin != NULL && vmax != NULL + && *vmin != std::numeric_limits::infinity() + && *vmax != std::numeric_limits::infinity()) + { + min = *vmin; + max = *vmax; + } + else + { + for (Point_set::const_iterator it = m_points->point_set()->begin(); + it != m_points->point_set()->end(); ++ it) + { + float v = feature->value(*it); + min = (std::min) (min, v); + max = (std::max) (max, v); + } + } + + for (Point_set::const_iterator it = m_points->point_set()->begin(); + it != m_points->point_set()->first_selected(); ++ it) + { + float v = (feature->value(*it) - min) / (max - min); + if (v < 0.f) v = 0.f; + if (v > 1.f) v = 1.f; + + m_points->point_set()->set_color(*it, ramp.r(v) * 255, ramp.g(v) * 255, ramp.b(v) * 255); + } + + if (vmin != NULL && vmax != NULL) + { + *vmin = min; + *vmax = max; + } + } + } + } + for (Point_set::const_iterator it = m_points->point_set()->first_selected(); it != m_points->point_set()->end(); ++ it) - { - m_red[*it] = 255; - m_green[*it] = 0; - m_blue[*it] = 0; - } - + m_points->point_set()->set_color(*it, 255, 0, 0); } int Point_set_item_classification::real_index_color() const @@ -430,7 +510,7 @@ void Point_set_item_classification::reset_indices () *(indices.begin() + i) = idx ++; } -void Point_set_item_classification::compute_features (std::size_t nb_scales) +void Point_set_item_classification::compute_features (std::size_t nb_scales, float voxel_size) { CGAL_assertion (!(m_points->point_set()->empty())); @@ -439,7 +519,12 @@ void Point_set_item_classification::compute_features (std::size_t nb_scales) reset_indices(); - std::cerr << "Computing features with " << nb_scales << " scale(s)" << std::endl; + std::cerr << "Computing features with " << nb_scales << " scale(s) and "; + if (voxel_size == -1) + std::cerr << "automatic voxel size" << std::endl; + else + std::cerr << "voxel size = " << voxel_size << std::endl; + m_features.clear(); Point_set::Vector_map normal_map; @@ -455,7 +540,7 @@ void Point_set_item_classification::compute_features (std::size_t nb_scales) if (!echo) boost::tie (echo_map, echo) = m_points->point_set()->template property_map("number_of_returns"); - m_generator = new Generator (*(m_points->point_set()), m_points->point_set()->point_map(), nb_scales); + m_generator = new Generator (*(m_points->point_set()), m_points->point_set()->point_map(), nb_scales, voxel_size); CGAL::Real_timer t; t.start(); @@ -480,12 +565,24 @@ void Point_set_item_classification::compute_features (std::size_t nb_scales) delete m_sowf; m_sowf = new Sum_of_weighted_features (m_labels, m_features); - delete m_ethz; - m_ethz = new ETHZ_random_forest (m_labels, m_features); - + if (m_ethz != NULL) + { + delete m_ethz; + m_ethz = NULL; + } #ifdef CGAL_LINKED_WITH_OPENCV - delete m_random_forest; - m_random_forest = new Random_forest (m_labels, m_features); + if (m_random_forest != NULL) + { + delete m_random_forest; + m_random_forest = NULL; + } +#endif +#ifdef CGAL_LINKED_WITH_TENSORFLOW + if (m_neural_network != NULL) + { + delete m_neural_network; + m_neural_network = NULL; + } #endif t.stop(); @@ -598,8 +695,7 @@ void Point_set_item_classification::add_remaining_point_set_properties_as_featur } } -void Point_set_item_classification::train(int classifier, unsigned int nb_trials, - std::size_t num_trees, std::size_t max_depth) +void Point_set_item_classification::train(int classifier, const QMultipleInputDialog& dialog) { if (m_features.size() == 0) { @@ -608,6 +704,11 @@ void Point_set_item_classification::train(int classifier, unsigned int nb_trials } reset_indices(); + m_label_probabilities.clear(); + m_label_probabilities.resize (m_labels.size()); + for (std::size_t i = 0; i < m_label_probabilities.size(); ++ i) + m_label_probabilities[i].resize (m_points->point_set()->size(), -1); + std::vector training (m_points->point_set()->size(), -1); std::vector indices (m_points->point_set()->size(), -1); @@ -632,32 +733,83 @@ void Point_set_item_classification::train(int classifier, unsigned int nb_trials if (classifier == 0) { - m_sowf->train(training, nb_trials); + m_sowf->train(training, dialog.get("trials")->value()); CGAL::Classification::classify (*(m_points->point_set()), m_labels, *m_sowf, - indices); + indices, m_label_probabilities); } else if (classifier == 1) { - m_ethz->train(training, true, num_trees, max_depth); + if (m_ethz != NULL) + delete m_ethz; + m_ethz = new ETHZ_random_forest (m_labels, m_features); + m_ethz->train(training, true, + dialog.get("num_trees")->value(), + dialog.get("max_depth")->value()); CGAL::Classification::classify (*(m_points->point_set()), m_labels, *m_ethz, - indices); + indices, m_label_probabilities); } - else - { + else if (classifier == 2) + { #ifdef CGAL_LINKED_WITH_OPENCV - if (m_random_forest != NULL) - delete m_random_forest; - m_random_forest = new Random_forest (m_labels, m_features, - int(max_depth), 5, 15, - int(num_trees)); - m_random_forest->train (training); - CGAL::Classification::classify (*(m_points->point_set()), - m_labels, *m_random_forest, - indices); + if (m_random_forest != NULL) + delete m_random_forest; + m_random_forest = new Random_forest (m_labels, m_features, + dialog.get("max_depth")->value(), 5, 15, + dialog.get("num_trees")->value()); + m_random_forest->train (training); + CGAL::Classification::classify (*(m_points->point_set()), + m_labels, *m_random_forest, + indices, m_label_probabilities); #endif + } + else if (classifier == 3) + { +#ifdef CGAL_LINKED_WITH_TENSORFLOW + if (m_neural_network != NULL) + { + if (m_neural_network->initialized()) + { + if (dialog.get("restart")->isChecked()) + { + delete m_neural_network; + m_neural_network = new Neural_network (m_labels, m_features); + } + } + else + { + delete m_neural_network; + m_neural_network = new Neural_network (m_labels, m_features); + } } + else + m_neural_network = new Neural_network (m_labels, m_features); + + std::vector hidden_layers; + + std::string hl_input = dialog.get("hidden_layers")->text().toStdString(); + if (hl_input != "") + { + std::istringstream iss(hl_input); + int s; + while (iss >> s) + hidden_layers.push_back (std::size_t(s)); + } + + m_neural_network->train (training, + dialog.get("restart")->isChecked(), + dialog.get("trials")->value(), + dialog.get("learning_rate")->value(), + dialog.get("batch_size")->value(), + hidden_layers); + + CGAL::Classification::classify (*(m_points->point_set()), + m_labels, *m_neural_network, + indices, m_label_probabilities); +#endif + } + for (Point_set::const_iterator it = m_points->point_set()->begin(); it != m_points->point_set()->first_selected(); ++ it) m_classif[*it] = indices[*it]; @@ -680,11 +832,36 @@ bool Point_set_item_classification::run (int method, int classifier, if (classifier == 0) run (method, *m_sowf, subdivisions, smoothing); else if (classifier == 1) + { + if (m_ethz == NULL) + { + std::cerr << "Error: ETHZ Random Forest must be trained or have a configuration loaded first" << std::endl; + return false; + } run (method, *m_ethz, subdivisions, smoothing); + } + else if (classifier == 2) + { #ifdef CGAL_LINKED_WITH_OPENCV - else + if (m_random_forest == NULL) + { + std::cerr << "Error: OpenCV Random Forest must be trained or have a configuration loaded first" << std::endl; + return false; + } run (method, *m_random_forest, subdivisions, smoothing); #endif + } + else if (classifier == 3) + { +#ifdef CGAL_LINKED_WITH_TENSORFLOW + if (m_neural_network == NULL) + { + std::cerr << "Error: TensorFlow Neural Network must be trained or have a configuration loaded first" << std::endl; + return false; + } + run (method, *m_neural_network, subdivisions, smoothing); +#endif + } return true; } diff --git a/Polyhedron/demo/Polyhedron/Plugins/Classification/Point_set_item_classification.h b/Polyhedron/demo/Polyhedron/Plugins/Classification/Point_set_item_classification.h index 7390bd3a8e3..3dc0ba57af9 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Classification/Point_set_item_classification.h +++ b/Polyhedron/demo/Polyhedron/Plugins/Classification/Point_set_item_classification.h @@ -3,6 +3,7 @@ //#define CGAL_DO_NOT_USE_BOYKOV_KOLMOGOROV_MAXFLOW_SOFTWARE #define CGAL_CLASSIFICATION_VERBOSE +#define CGAL_CLASSTRAINING_VERBOSE #include @@ -116,7 +117,35 @@ class Point_set_item_classification : public Item_classification_base xcenter + dx, ycenter + dy, zcenter + dz); } - void compute_features (std::size_t nb_scales); + void compute_features (std::size_t nb_scales, float voxel_size); + + std::string feature_statistics() const + { + std::ostringstream oss; + + for (std::size_t i = 0; i < m_features.size(); ++ i) + { + float vmin = std::numeric_limits::max(); + float vmax = -std::numeric_limits::max(); + float vmean = 0.f; + std::size_t nb = 0; + + for (Point_set::const_iterator it = m_points->point_set()->begin_or_selection_begin(); + it != m_points->point_set()->end(); ++ it) + { + float v = m_features[i]->value(std::size_t(it - m_points->point_set()->begin())); + vmin = (std::min) (vmin, v); + vmax = (std::max) (vmax, v); + vmean += v; + ++ nb; + } + + oss << m_features[i]->name() << " in [ " << vmin << " ; " << vmax << " ], mean = " << vmean / nb << std::endl; + } + + return oss.str(); + } + void add_remaining_point_set_properties_as_features(); void select_random_region(); @@ -129,8 +158,12 @@ class Point_set_item_classification : public Item_classification_base Pmap pmap; boost::tie (pmap, okay) = m_points->point_set()->template property_map(name.c_str()); if (okay) + { + std::cerr << "Adding property<" << CGAL::demangle(typeid(Type).name()) << ">(" + << name << ") as feature" << std::endl; m_features.template add > (*(m_points->point_set()), pmap, name.c_str()); + } return okay; } @@ -186,12 +219,11 @@ class Point_set_item_classification : public Item_classification_base if (m_index_color == 1 || m_index_color == 2) change_color (m_index_color); } - void train(int classifier, unsigned int nb_trials, - std::size_t num_trees, std::size_t max_depth); + void train(int classifier, const QMultipleInputDialog& dialog); bool run (int method, int classifier, std::size_t subdivisions, double smoothing); void update_color () { change_color (m_index_color); } - void change_color (int index); + void change_color (int index, float* vmin = NULL, float* vmax = NULL); CGAL::Three::Scene_item* generate_one_item (const char* name, int label) const { @@ -231,8 +263,6 @@ class Point_set_item_classification : public Item_classification_base } } - bool write_output(std::ostream& out); - QColor add_new_label (const char* name) { QColor out = Item_classification_base::add_new_label (name); @@ -301,10 +331,11 @@ class Point_set_item_classification : public Item_classification_base { std::vector indices (m_points->point_set()->size(), -1); + m_label_probabilities.clear(); if (method == 0) CGAL::Classification::classify (*(m_points->point_set()), m_labels, classifier, - indices); + indices, m_label_probabilities); else if (method == 1) { if (m_clusters.empty()) // Use real local smoothing @@ -367,9 +398,8 @@ class Point_set_item_classification : public Item_classification_base std::vector m_clusters; - Point_set::Property_map m_red; - Point_set::Property_map m_green; - Point_set::Property_map m_blue; + std::vector > m_label_probabilities; + Point_set::Property_map m_color; Point_set::Property_map m_training; Point_set::Property_map m_classif; @@ -377,6 +407,8 @@ class Point_set_item_classification : public Item_classification_base Generator* m_generator; int m_index_color; + + bool m_input_is_las; }; // end class Point_set_item_classification diff --git a/Polyhedron/demo/Polyhedron/Plugins/Classification/Surface_mesh_item_classification.cpp b/Polyhedron/demo/Polyhedron/Plugins/Classification/Surface_mesh_item_classification.cpp index 8c778bc3c58..eb0ce9b3bc5 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Classification/Surface_mesh_item_classification.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/Classification/Surface_mesh_item_classification.cpp @@ -6,6 +6,8 @@ #include +#include + #include #include #include @@ -31,9 +33,12 @@ Surface_mesh_item_classification::Surface_mesh_item_classification(Scene_surface m_label_colors.push_back (this->get_new_label_color (m_labels[i]->name())); m_sowf = new Sum_of_weighted_features (m_labels, m_features); - m_ethz = new ETHZ_random_forest (m_labels, m_features); + m_ethz = NULL; #ifdef CGAL_LINKED_WITH_OPENCV - m_random_forest = new Random_forest (m_labels, m_features); + m_random_forest = NULL; +#endif +#ifdef CGAL_LINKED_WITH_TENSORFLOW + m_neural_network = NULL; #endif } @@ -47,6 +52,10 @@ Surface_mesh_item_classification::~Surface_mesh_item_classification() #ifdef CGAL_LINKED_WITH_OPENCV if (m_random_forest != NULL) delete m_random_forest; +#endif +#ifdef CGAL_LINKED_WITH_TENSORFLOW + if (m_neural_network != NULL) + delete m_neural_network; #endif if (m_generator != NULL) delete m_generator; @@ -71,14 +80,7 @@ void Surface_mesh_item_classification::backup_existing_colors_and_add_new() m_mesh->polyhedron()->add_property_map("f:color", CGAL::Color(128,128,128)).first; } -bool Surface_mesh_item_classification::write_output(std::ostream& ) -{ - // TODO - return true; -} - - -void Surface_mesh_item_classification::change_color (int index) +void Surface_mesh_item_classification::change_color (int index, float* vmin, float* vmax) { m_index_color = index; int index_color = index; @@ -132,28 +134,90 @@ void Surface_mesh_item_classification::change_color (int index) } else { - Feature_handle feature = m_features[index_color - 3]; - - float max = 0.; - BOOST_FOREACH(face_descriptor fd, faces(*(m_mesh->polyhedron()))) + std::size_t corrected_index = index_color - 3; + if (corrected_index < m_labels.size()) // Display label probabilities { - if (feature->value(fd) > max) - max = feature->value(fd); + if (m_label_probabilities.size() <= corrected_index || + m_label_probabilities[corrected_index].size() != num_faces(*(m_mesh->polyhedron()))) + { + BOOST_FOREACH(face_descriptor fd, faces(*(m_mesh->polyhedron()))) + { + m_color[fd] = CGAL::Color((unsigned char)(128), + (unsigned char)(128), + (unsigned char)(128)); + } + } + else + { + BOOST_FOREACH(face_descriptor fd, faces(*(m_mesh->polyhedron()))) + { + float v = std::max (0.f, std::min(1.f, m_label_probabilities[corrected_index][fd])); + m_color[fd] = CGAL::Color((unsigned char)(ramp.r(v) * 255), + (unsigned char)(ramp.g(v) * 255), + (unsigned char)(ramp.b(v) * 255)); + } + } } - - BOOST_FOREACH(face_descriptor fd, faces(*(m_mesh->polyhedron()))) + else { - float v = std::max (0.f, feature->value(fd) / max); - m_color[fd] = CGAL::Color((unsigned char)(ramp.r(v) * 255), - (unsigned char)(ramp.g(v) * 255), - (unsigned char)(ramp.b(v) * 255)); + corrected_index -= m_labels.size(); + if (corrected_index >= m_features.size()) + { + std::cerr << "Error: trying to access feature " << corrected_index << " out of " << m_features.size() << std::endl; + return; + } + + Feature_handle feature = m_features[corrected_index]; + + float min = std::numeric_limits::max(); + float max = -std::numeric_limits::max(); + + if (vmin != NULL && vmax != NULL + && *vmin != std::numeric_limits::infinity() + && *vmax != std::numeric_limits::infinity()) + { + min = *vmin; + max = *vmax; + } + else + { + BOOST_FOREACH(face_descriptor fd, faces(*(m_mesh->polyhedron()))) + { + if (feature->value(fd) > max) + max = feature->value(fd); + if (feature->value(fd) < min) + min = feature->value(fd); + } + } + + BOOST_FOREACH(face_descriptor fd, faces(*(m_mesh->polyhedron()))) + { + float v = (feature->value(fd) - min) / (max - min); + if (v < 0.f) v = 0.f; + if (v > 1.f) v = 1.f; + + m_color[fd] = CGAL::Color((unsigned char)(ramp.r(v) * 255), + (unsigned char)(ramp.g(v) * 255), + (unsigned char)(ramp.b(v) * 255)); + } + + if (vmin != NULL && vmax != NULL) + { + *vmin = min; + *vmax = max; + } } } } -void Surface_mesh_item_classification::compute_features (std::size_t nb_scales) +void Surface_mesh_item_classification::compute_features (std::size_t nb_scales, float voxel_size) { - std::cerr << "Computing features with " << nb_scales << " scale(s)" << std::endl; + std::cerr << "Computing features with " << nb_scales << " scale(s) and "; + if (voxel_size == -1) + std::cerr << "automatic voxel size" << std::endl; + else + std::cerr << "voxel size = " << voxel_size << std::endl; + m_features.clear(); if (m_generator != NULL) @@ -161,7 +225,7 @@ void Surface_mesh_item_classification::compute_features (std::size_t nb_scales) Face_center_map fc_map (m_mesh->polyhedron()); - m_generator = new Generator (*(m_mesh->polyhedron()), fc_map, nb_scales); + m_generator = new Generator (*(m_mesh->polyhedron()), fc_map, nb_scales, voxel_size); #ifdef CGAL_LINKED_WITH_TBB m_features.begin_parallel_additions(); @@ -176,16 +240,29 @@ void Surface_mesh_item_classification::compute_features (std::size_t nb_scales) delete m_sowf; m_sowf = new Sum_of_weighted_features (m_labels, m_features); + if (m_ethz != NULL) + { + delete m_ethz; + m_ethz = NULL; + } #ifdef CGAL_LINKED_WITH_OPENCV - delete m_random_forest; - m_random_forest = new Random_forest (m_labels, m_features); + if (m_random_forest != NULL) + { + delete m_random_forest; + m_random_forest = NULL; + } +#endif +#ifdef CGAL_LINKED_WITH_TENSORFLOW + if (m_neural_network != NULL) + { + delete m_neural_network; + m_neural_network = NULL; + } #endif std::cerr << "Features = " << m_features.size() << std::endl; } -void Surface_mesh_item_classification::train -(int classifier, unsigned int nb_trials, - std::size_t num_trees, std::size_t max_depth) +void Surface_mesh_item_classification::train (int classifier, const QMultipleInputDialog& dialog) { if (m_features.size() == 0) { @@ -193,6 +270,11 @@ void Surface_mesh_item_classification::train return; } + m_label_probabilities.clear(); + m_label_probabilities.resize (m_labels.size()); + for (std::size_t i = 0; i < m_label_probabilities.size(); ++ i) + m_label_probabilities[i].resize (num_faces(*(m_mesh->polyhedron()))); + std::vector training (num_faces(*(m_mesh->polyhedron())), std::size_t(-1)); std::vector indices (num_faces(*(m_mesh->polyhedron())), std::size_t(-1)); @@ -216,31 +298,81 @@ void Surface_mesh_item_classification::train if (classifier == 0) { - m_sowf->train(training, nb_trials); + m_sowf->train(training, dialog.get("trials")->value()); CGAL::Classification::classify (m_mesh->polyhedron()->faces(), m_labels, *m_sowf, - indices); + indices, m_label_probabilities); } else if (classifier == 1) { - m_ethz->train(training, true, num_trees, max_depth); + if (m_ethz != NULL) + delete m_ethz; + m_ethz = new ETHZ_random_forest (m_labels, m_features); + m_ethz->train(training, true, + dialog.get("num_trees")->value(), + dialog.get("max_depth")->value()); CGAL::Classification::classify (m_mesh->polyhedron()->faces(), m_labels, *m_ethz, - indices); + indices, m_label_probabilities); } - else + else if (classifier == 2) { #ifdef CGAL_LINKED_WITH_OPENCV if (m_random_forest != NULL) delete m_random_forest; m_random_forest = new Random_forest (m_labels, m_features, - int(max_depth), 5, 15, - int(num_trees)); + dialog.get("max_depth")->value(), 5, 15, + dialog.get("num_trees")->value()); m_random_forest->train (training); CGAL::Classification::classify (m_mesh->polyhedron()->faces(), m_labels, *m_random_forest, - indices); + indices, m_label_probabilities); +#endif + } + else if (classifier == 3) + { +#ifdef CGAL_LINKED_WITH_TENSORFLOW + if (m_neural_network != NULL) + { + if (m_neural_network->initialized()) + { + if (dialog.get("restart")->isChecked()) + { + delete m_neural_network; + m_neural_network = new Neural_network (m_labels, m_features); + } + } + else + { + delete m_neural_network; + m_neural_network = new Neural_network (m_labels, m_features); + } + } + else + m_neural_network = new Neural_network (m_labels, m_features); + + std::vector hidden_layers; + + std::string hl_input = dialog.get("hidden_layers")->text().toStdString(); + if (hl_input != "") + { + std::istringstream iss(hl_input); + int s; + while (iss >> s) + hidden_layers.push_back (std::size_t(s)); + } + + m_neural_network->train (training, + dialog.get("restart")->isChecked(), + dialog.get("trials")->value(), + dialog.get("learning_rate")->value(), + dialog.get("batch_size")->value(), + hidden_layers); + + CGAL::Classification::classify (m_mesh->polyhedron()->faces(), + m_labels, *m_neural_network, + indices, m_label_probabilities); #endif } @@ -263,11 +395,36 @@ bool Surface_mesh_item_classification::run (int method, int classifier, if (classifier == 0) run (method, *m_sowf, subdivisions, smoothing); else if (classifier == 1) + { + if (m_ethz == NULL) + { + std::cerr << "Error: ETHZ Random Forest must be trained or have a configuration loaded first" << std::endl; + return false; + } run (method, *m_ethz, subdivisions, smoothing); + } + else if (classifier == 2) + { #ifdef CGAL_LINKED_WITH_OPENCV - else + if (m_random_forest == NULL) + { + std::cerr << "Error: OpenCV Random Forest must be trained or have a configuration loaded first" << std::endl; + return false; + } run (method, *m_random_forest, subdivisions, smoothing); #endif + } + else if (classifier == 3) + { +#ifdef CGAL_LINKED_WITH_TENSORFLOW + if (m_neural_network == NULL) + { + std::cerr << "Error: TensorFlow Neural Network must be trained or have a configuration loaded first" << std::endl; + return false; + } + run (method, *m_neural_network, subdivisions, smoothing); +#endif + } return true; } diff --git a/Polyhedron/demo/Polyhedron/Plugins/Classification/Surface_mesh_item_classification.h b/Polyhedron/demo/Polyhedron/Plugins/Classification/Surface_mesh_item_classification.h index 238d160c2eb..90d53ae3151 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Classification/Surface_mesh_item_classification.h +++ b/Polyhedron/demo/Polyhedron/Plugins/Classification/Surface_mesh_item_classification.h @@ -50,7 +50,7 @@ public: CGAL::Three::Scene_item* item() { return m_mesh; } void erase_item() { m_mesh = NULL; } - void compute_features (std::size_t nb_scales); + void compute_features (std::size_t nb_scales, float voxel_size); void add_selection_to_training_set (std::size_t label) { @@ -116,12 +116,11 @@ public: if (m_index_color == 1 || m_index_color == 2) change_color (m_index_color); } - void train(int classifier, unsigned int nb_trials, - std::size_t num_trees, std::size_t max_depth); + void train(int classifier, const QMultipleInputDialog& dialog); bool run (int method, int classifier, std::size_t subdivisions, double smoothing); void update_color() { change_color (m_index_color); } - void change_color (int index); + void change_color (int index, float* vmin = NULL, float* vmax = NULL); CGAL::Three::Scene_item* generate_one_item (const char* /* name */, int /* label */) const { @@ -136,8 +135,6 @@ public: std::cerr << "Warning: operation not yet available for meshes." << std::endl; } - bool write_output(std::ostream& out); - void set_selection_item (Scene_polyhedron_selection_item* selection) { m_selection = selection; @@ -210,6 +207,8 @@ protected: Mesh::Property_map m_color; Mesh::Property_map m_real_color; + std::vector > m_label_probabilities; + Generator* m_generator; int m_index_color; }; diff --git a/Polyhedron/demo/Polyhedron/Plugins/Convex_hull/CMakeLists.txt b/Polyhedron/demo/Polyhedron/Plugins/Convex_hull/CMakeLists.txt index 900441b871b..f5c8d0c766d 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Convex_hull/CMakeLists.txt +++ b/Polyhedron/demo/Polyhedron/Plugins/Convex_hull/CMakeLists.txt @@ -1,6 +1,6 @@ include( polyhedron_demo_macros ) -polyhedron_demo_plugin(convex_hull_plugin Convex_hull_plugin) +polyhedron_demo_plugin(convex_hull_plugin Convex_hull_plugin KEYWORDS PointSetProcessing) target_link_libraries(convex_hull_plugin PUBLIC scene_points_with_normal_item scene_polylines_item scene_selection_item scene_surface_mesh_item) polyhedron_demo_plugin(kernel_plugin Kernel_plugin) diff --git a/Polyhedron/demo/Polyhedron/Plugins/IO/CMakeLists.txt b/Polyhedron/demo/Polyhedron/Plugins/IO/CMakeLists.txt index 4a642daba09..e5d500cc9db 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/IO/CMakeLists.txt +++ b/Polyhedron/demo/Polyhedron/Plugins/IO/CMakeLists.txt @@ -10,7 +10,7 @@ target_link_libraries(io_implicit_function_plugin PUBLIC scene_implicit_function polyhedron_demo_plugin(nef_io_plugin Nef_io_plugin KEYWORDS IO) target_link_libraries(nef_io_plugin PUBLIC scene_nef_polyhedron_item) -polyhedron_demo_plugin(off_plugin OFF_io_plugin KEYWORDS IO Mesh_3) +polyhedron_demo_plugin(off_plugin OFF_io_plugin KEYWORDS IO Mesh_3 PointSetProcessing Classification) target_link_libraries(off_plugin PUBLIC scene_polygon_soup_item scene_points_with_normal_item scene_surface_mesh_item) polyhedron_demo_plugin(off_to_nef_plugin OFF_to_nef_io_plugin KEYWORDS IO) @@ -48,7 +48,7 @@ if (VTK_FOUND) else() message(STATUS "NOTICE : the vtk IO plugin needs VTK 6.0 or greater and will not be compiled.") endif() -polyhedron_demo_plugin(xyz_plugin XYZ_io_plugin KEYWORDS IO) +polyhedron_demo_plugin(xyz_plugin XYZ_io_plugin KEYWORDS IO PointSetProcessing Classification) target_link_libraries(xyz_plugin PUBLIC scene_points_with_normal_item) list(FIND CMAKE_CXX_COMPILE_FEATURES cxx_rvalue_references has_cxx_rvalues) @@ -59,12 +59,12 @@ if(has_cxx_rvalues LESS 0 OR has_cxx_variadic LESS 0) else() set(needed_cxx_features cxx_rvalue_references cxx_variadic_templates) - polyhedron_demo_plugin(ply_plugin PLY_io_plugin KEYWORDS IO) + polyhedron_demo_plugin(ply_plugin PLY_io_plugin KEYWORDS IO PointSetProcessing Classification) target_link_libraries(ply_plugin PUBLIC scene_points_with_normal_item scene_polygon_soup_item scene_surface_mesh_item scene_polygon_soup_item) target_compile_features(ply_plugin PRIVATE ${needed_cxx_features}) if (LASLIB_FOUND) - polyhedron_demo_plugin(las_plugin LAS_io_plugin KEYWORDS IO) + polyhedron_demo_plugin(las_plugin LAS_io_plugin KEYWORDS IO PointSetProcessing Classification) target_link_libraries(las_plugin PUBLIC scene_points_with_normal_item ${LASLIB_LIBRARIES}) target_compile_features(las_plugin PRIVATE ${needed_cxx_features}) else() diff --git a/Polyhedron/demo/Polyhedron/Plugins/IO/GOCAD_io_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/IO/GOCAD_io_plugin.cpp index d5316ad04f6..caae0705b5c 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/IO/GOCAD_io_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/IO/GOCAD_io_plugin.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -57,19 +58,24 @@ bool Polyhedron_demo_gocad_plugin::canLoad() const { CGAL::Three::Scene_item* Polyhedron_demo_gocad_plugin::load(QFileInfo fileinfo) { - + // Open file std::ifstream in(fileinfo.filePath().toUtf8()); if(!in) { std::cerr << "Error! Cannot open file " << (const char*)fileinfo.filePath().toUtf8() << std::endl; return NULL; } - - + + CGAL::Timer t; t.start(); // Try to read GOCAD file in a surface_mesh Scene_surface_mesh_item* item = new Scene_surface_mesh_item(new SMesh()); + if(fileinfo.size() == 0) + { + CGAL::Three::Three::warning( tr("The file you are trying to load is empty.")); + return item; + } SMesh& P = * const_cast(item->polyhedron()); std::string name, color; @@ -90,11 +96,9 @@ Polyhedron_demo_gocad_plugin::load(QFileInfo fileinfo) { if(qcolor.isValid()) { item->setColor(qcolor); - item->invalidateOpenGLBuffers(); } + item->invalidateOpenGLBuffers(); return item; - -return NULL; } bool Polyhedron_demo_gocad_plugin::canSave(const CGAL::Three::Scene_item* item) diff --git a/Polyhedron/demo/Polyhedron/Plugins/IO/Nef_io_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/IO/Nef_io_plugin.cpp index 499b2f7db4b..11265427374 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/IO/Nef_io_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/IO/Nef_io_plugin.cpp @@ -1,6 +1,7 @@ #include "Scene_nef_polyhedron_item.h" #include +#include #include #include @@ -47,6 +48,11 @@ Polyhedron_demo_io_nef_plugin::load(QFileInfo fileinfo) { // Try to read .nef3 in a polyhedron Scene_nef_polyhedron_item* item = new Scene_nef_polyhedron_item(); item->setName(fileinfo.baseName()); + if(fileinfo.size() == 0) + { + CGAL::Three::Three::warning( tr("The file you are trying to load is empty.")); + return item; + } if(!item->load(in)) { delete item; diff --git a/Polyhedron/demo/Polyhedron/Plugins/IO/OFF_io_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/IO/OFF_io_plugin.cpp index c2cbb3c5684..c0e57fe50e2 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/IO/OFF_io_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/IO/OFF_io_plugin.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include @@ -49,6 +50,15 @@ bool Polyhedron_demo_off_plugin::canLoad() const { CGAL::Three::Scene_item* Polyhedron_demo_off_plugin::load(QFileInfo fileinfo) { + + if(fileinfo.size() == 0) + { + CGAL::Three::Three::warning( tr("The file you are trying to load is empty.")); + Scene_surface_mesh_item* item = + new Scene_surface_mesh_item(SMesh()); + item->setName(fileinfo.completeBaseName()); + return item; + } if(fileinfo.suffix().toLower() == "off"){ return load_off(fileinfo); } else if(fileinfo.suffix().toLower() == "obj"){ diff --git a/Polyhedron/demo/Polyhedron/Plugins/IO/OFF_to_nef_io_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/IO/OFF_to_nef_io_plugin.cpp index cd557823bd8..5d142129b4c 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/IO/OFF_to_nef_io_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/IO/OFF_to_nef_io_plugin.cpp @@ -2,6 +2,7 @@ #include "Nef_type.h" #include +#include #include using namespace CGAL::Three; class Polyhedron_demo_off_to_nef_plugin : @@ -33,7 +34,12 @@ Polyhedron_demo_off_to_nef_plugin::load(QFileInfo fileinfo) { if(!in) std::cerr << "Error!\n"; Scene_nef_polyhedron_item* item = new Scene_nef_polyhedron_item(); - + if(fileinfo.size() == 0) + { + CGAL::Three::Three::warning( tr("The file you are trying to load is empty.")); + item->setName(fileinfo.completeBaseName()); + return item; + } if(!item->load_from_off(in)) { delete item; diff --git a/Polyhedron/demo/Polyhedron/Plugins/IO/PLY_io_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/IO/PLY_io_plugin.cpp index 0a57fac8fee..3725e3e93df 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/IO/PLY_io_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/IO/PLY_io_plugin.cpp @@ -79,6 +79,12 @@ Polyhedron_demo_ply_plugin::load(QFileInfo fileinfo) { QApplication::setOverrideCursor(Qt::WaitCursor); + if(fileinfo.size() == 0) + { + CGAL::Three::Three::warning( tr("The file you are trying to load is empty.")); + return 0; + } + // Test if input is mesh or point set bool input_is_mesh = false; std::string line; diff --git a/Polyhedron/demo/Polyhedron/Plugins/IO/Polylines_io_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/IO/Polylines_io_plugin.cpp index 0c4a3308503..6cd47d92aa8 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/IO/Polylines_io_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/IO/Polylines_io_plugin.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -100,6 +101,14 @@ Polyhedron_demo_polylines_io_plugin::load(QFileInfo fileinfo) { return NULL; } + if(fileinfo.size() == 0) + { + CGAL::Three::Three::warning( tr("The file you are trying to load is empty.")); + Scene_polylines_item* item = new Scene_polylines_item; + item->setName(fileinfo.completeBaseName()); + return item; + } + std::list > polylines; QStringList polylines_metadata; diff --git a/Polyhedron/demo/Polyhedron/Plugins/IO/STL_io_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/IO/STL_io_plugin.cpp index 4591567722f..18749766763 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/IO/STL_io_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/IO/STL_io_plugin.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -71,7 +72,13 @@ Polyhedron_demo_stl_plugin::load(QFileInfo fileinfo) { std::cerr << "Error! Cannot open file " << (const char*)fileinfo.filePath().toUtf8() << std::endl; return NULL; } - + if(fileinfo.size() == 0) + { + CGAL::Three::Three::warning( tr("The file you are trying to load is empty.")); + Scene_surface_mesh_item* item = new Scene_surface_mesh_item(); + item->setName(fileinfo.completeBaseName()); + return item; + } std::vector > points; std::vector > triangles; if (!CGAL::read_STL(in, points, triangles)) diff --git a/Polyhedron/demo/Polyhedron/Plugins/IO/Surf_io_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/IO/Surf_io_plugin.cpp index 87b7e5c5a4e..2302cfe4182 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/IO/Surf_io_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/IO/Surf_io_plugin.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include @@ -69,6 +70,13 @@ CGAL::Three::Scene_item* Surf_io_plugin::actual_load(QFileInfo fileinfo) return NULL; } + if(fileinfo.size() == 0) + { + CGAL::Three::Three::warning( tr("The file you are trying to load is empty.")); + Scene_group_item* item = + new Scene_group_item(fileinfo.completeBaseName()); + return item; + } std::vector patches; std::vector material_data; CGAL::Bbox_3 grid_box; diff --git a/Polyhedron/demo/Polyhedron/Plugins/IO/VTK_io_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/IO/VTK_io_plugin.cpp index 2cc6a37fdb7..c340b70aa24 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/IO/VTK_io_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/IO/VTK_io_plugin.cpp @@ -28,6 +28,7 @@ #include #include +#include #include #include @@ -44,6 +45,8 @@ #include #include #include +#include +#include #include #include @@ -51,6 +54,7 @@ #include #include #include +#include #include #include #include @@ -70,10 +74,16 @@ #include #include - +#include +#include typedef Scene_surface_mesh_item Scene_facegraph_item; typedef Scene_facegraph_item::Face_graph FaceGraph; -typedef boost::property_traits::type>::value_type Point; +typedef boost::property_traits::type>::value_type Point; + + + + namespace CGAL{ class ErrorObserverVtk : public vtkCommand @@ -236,13 +246,13 @@ namespace CGAL{ cell->Delete(); } - vtkSmartPointer polydata = - vtkSmartPointer::New(); + vtkSmartPointer usg = + vtkSmartPointer::New(); - polydata->SetPoints(vtk_points); + usg->SetPoints(vtk_points); vtk_points->Delete(); - polydata->SetPolys(vtk_cells); + usg->SetCells(5,vtk_cells); vtk_cells->Delete(); // Combine the two data sets @@ -259,7 +269,7 @@ namespace CGAL{ vtkSmartPointer writer = vtkSmartPointer::New(); writer->SetFileName(filename); - writer->SetInputData(polydata); + writer->SetInputData(usg); writer->Write(); } }//end namespace CGAL @@ -286,6 +296,8 @@ public: return (qobject_cast(item) || qobject_cast(item)); } + + bool save(const CGAL::Three::Scene_item* item, QFileInfo fileinfo) { std::string extension = fileinfo.suffix().toLower().toStdString(); @@ -300,13 +312,26 @@ public: if (poly_item) { if (extension != "vtp") - CGAL::polygon_mesh_to_vtkUnstructured( + { + if(!CGAL::is_triangle_mesh(*poly_item->polyhedron())) + { + QMessageBox::warning(0, "Error", + "Cannot save a mesh in vtu format if " + "it is not pure triangle."); + return false; + } + CGAL::polygon_mesh_to_vtkUnstructured( *poly_item->polyhedron(), output_filename.data()); + } else - CGAL::polygon_mesh_to_vtkUnstructured( - *poly_item->polyhedron(), - output_filename.data()); + { + const FaceGraph* mesh = poly_item->face_graph(); + std::ofstream os(output_filename.data()); + os << std::setprecision(16); + //write header + CGAL::write_vtp(os, *mesh); + } } else { @@ -314,12 +339,12 @@ public: qobject_cast(item); if(!c3t3_item || extension != "vtu") return false; - - vtkSmartPointer writer = - vtkSmartPointer::New(); - writer->SetFileName( output_filename.data()); - writer->SetInputData(CGAL::output_c3t3_to_vtk_unstructured_grid(c3t3_item->c3t3())); - writer->Write(); + + std::ofstream os(output_filename.data()); + os << std::setprecision(16); + const C3t3& c3t3 = c3t3_item->c3t3(); + + CGAL::output_to_vtu(os, c3t3); } return true; } @@ -349,6 +374,15 @@ public: FaceGraph* poly = new FaceGraph(); // Try to read .vtk in a facegraph + + if(fileinfo.size() == 0) + { + CGAL::Three::Three::warning( tr("The file you are trying to load is empty.")); + Scene_facegraph_item* item = + new Scene_facegraph_item(poly); + item->setName(fileinfo.completeBaseName()); + return item; + } vtkSmartPointer data; vtkSmartPointer obs = vtkSmartPointer::New(); diff --git a/Polyhedron/demo/Polyhedron/Plugins/IO/XYZ_io_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/IO/XYZ_io_plugin.cpp index 17873a0081f..7bed8af9e55 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/IO/XYZ_io_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/IO/XYZ_io_plugin.cpp @@ -43,6 +43,15 @@ Polyhedron_demo_xyz_plugin::load(QFileInfo fileinfo) return NULL; } + + if(fileinfo.size() == 0) + { + CGAL::Three::Three::warning( tr("The file you are trying to load is empty.")); + Scene_points_with_normal_item* item = + new Scene_points_with_normal_item(); + item->setName(fileinfo.completeBaseName()); + return item; + } // Read .xyz in a point set Scene_points_with_normal_item* point_set_item = new Scene_points_with_normal_item; point_set_item->setName(fileinfo.completeBaseName()); diff --git a/Polyhedron/demo/Polyhedron/Plugins/Mesh_3/C3t3_io_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/Mesh_3/C3t3_io_plugin.cpp index b3009ddef89..29aa230dfd9 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Mesh_3/C3t3_io_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/Mesh_3/C3t3_io_plugin.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -66,6 +67,13 @@ Polyhedron_demo_c3t3_binary_io_plugin::load(QFileInfo fileinfo) { return NULL; } Scene_c3t3_item* item = new Scene_c3t3_item(); + + if(fileinfo.size() == 0) + { + CGAL::Three::Three::warning( tr("The file you are trying to load is empty.")); + item->setName(fileinfo.completeBaseName()); + return item; + } if(fileinfo.suffix().toLower() == "cgal") { item->setName(fileinfo.baseName()); diff --git a/Polyhedron/demo/Polyhedron/Plugins/Mesh_3/Io_image_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/Mesh_3/Io_image_plugin.cpp index a5ad227b637..907085acdd0 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Mesh_3/Io_image_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/Mesh_3/Io_image_plugin.cpp @@ -65,6 +65,7 @@ #include #include #endif +#include // Covariant return types don't work for scalar types and we cannot // have templates here, hence this unfortunate hack. @@ -366,7 +367,7 @@ public Q_SLOTS: } } if(group_map.keys().contains(seg_img)) - this->message_interface->warning("This item already has volume planes."); + CGAL::Three::Three::warning("This item already has volume planes."); else { // Opens a modal Dialog to prevent the user from manipulating things that could mess with the planes creation and cause a segfault. @@ -1148,7 +1149,7 @@ bool Io_image_plugin::loadDCM(QString dirname) { QMessageBox::warning(mw, mw->windowTitle(), tr("Cannot read directory %1!").arg(dirname)); - message_interface->warning(tr("Opening of directory %1 failed!").arg(dirname)); + CGAL::Three::Three::warning(tr("Opening of directory %1 failed!").arg(dirname)); result = false; } else @@ -1199,12 +1200,12 @@ bool Io_image_plugin::loadDCM(QString dirname) { QMessageBox::warning(mw, mw->windowTitle(), tr("Error with file %1/:\nunknown file format!").arg(dirname)); - message_interface->warning(tr("Opening of file %1/ failed!").arg(dirname)); + CGAL::Three::Three::warning(tr("Opening of file %1/ failed!").arg(dirname)); result = false; } else { - message_interface->information(tr("File %1/ successfully opened.").arg(dirname)); + CGAL::Three::Three::information(tr("File %1/ successfully opened.").arg(dirname)); } if(result) { @@ -1225,12 +1226,12 @@ bool Io_image_plugin::loadDCM(QString dirname) { QMessageBox::warning(mw, mw->windowTitle(), tr("Error with file %1/:\nunknown file format!").arg(dirname)); - message_interface->warning(tr("Opening of file %1/ failed!").arg(dirname)); + CGAL::Three::Three::warning(tr("Opening of file %1/ failed!").arg(dirname)); result = false; } else { - message_interface->information(tr("File %1/ successfully opened.").arg(dirname)); + CGAL::Three::Three::information(tr("File %1/ successfully opened.").arg(dirname)); } if(result) { @@ -1242,7 +1243,7 @@ bool Io_image_plugin::loadDCM(QString dirname) } return result; #else - message_interface->warning("You need VTK to read a DCM file"); + CGAL::Three::Three::warning("You need VTK to read a DCM file"); CGAL_USE(dirname); return false; #endif @@ -1270,7 +1271,7 @@ Image* Io_image_plugin::createDCMImage(QString dirname) image = new Image; *image = CGAL::read_vtk_image_data(vtk_image); // copy the image data #else - message_interface->warning("You need VTK to read a DCM file"); + CGAL::Three::Three::warning("You need VTK to read a DCM file"); CGAL_USE(dirname); #endif return image; diff --git a/Polyhedron/demo/Polyhedron/Plugins/Mesh_3/Mesh_3_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/Mesh_3/Mesh_3_plugin.cpp index c4320a49e8d..ecf2f4bc889 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Mesh_3/Mesh_3_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/Mesh_3/Mesh_3_plugin.cpp @@ -3,6 +3,7 @@ #ifdef CGAL_POLYHEDRON_DEMO_USE_SURFACE_MESHER #include +#include #include "Messages_interface.h" #include @@ -623,7 +624,7 @@ meshing_done(Meshing_thread* thread) .arg(bbox.zmin()) .arg(bbox.zmax())); - msg->information(qPrintable(str)); + CGAL::Three::Three::information(qPrintable(str)); // Treat new c3t3 item treat_result(*source_item_, result_item); diff --git a/Polyhedron/demo/Polyhedron/Plugins/Mesh_3/Optimization_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/Mesh_3/Optimization_plugin.cpp index 344ab89ad0d..303e38fd5cc 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Mesh_3/Optimization_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/Mesh_3/Optimization_plugin.cpp @@ -9,6 +9,7 @@ #ifdef CGAL_POLYHEDRON_DEMO_USE_SURFACE_MESHER #include +#include #include "Messages_interface.h" #include "ui_Smoother_dialog.h" @@ -562,7 +563,7 @@ optimization_done(Optimizer_thread* thread) str.append(QString("( %1 )
").arg(param)); } - msg->information(qPrintable(str)); + CGAL::Three::Three::information(qPrintable(str)); // Treat new c3t3 item Scene_c3t3_item* result_item = thread->item(); diff --git a/Polyhedron/demo/Polyhedron/Plugins/Operations_on_polyhedra/Clip_polyhedron_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/Operations_on_polyhedra/Clip_polyhedron_plugin.cpp index ea133fe6bdf..d6cf4c57458 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Operations_on_polyhedra/Clip_polyhedron_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/Operations_on_polyhedra/Clip_polyhedron_plugin.cpp @@ -7,6 +7,7 @@ #include "Scene_plane_item.h" #include #include +#include #include #include "ui_Clip_polyhedron_plugin.h" @@ -168,7 +169,7 @@ public : } catch(CGAL::Polygon_mesh_processing::Corefinement::Self_intersection_exception) { - messages->warning(tr("The requested operation is not possible due to the presence of self-intersections in the region handled.")); + CGAL::Three::Three::warning(tr("The requested operation is not possible due to the presence of self-intersections in the region handled.")); } } public Q_SLOTS: @@ -242,7 +243,7 @@ public Q_SLOTS: } catch(CGAL::Polygon_mesh_processing::Corefinement::Self_intersection_exception) { - messages->warning(tr("The requested operation is not possible due to the presence of self-intersections in the region handled.")); + CGAL::Three::Three::warning(tr("The requested operation is not possible due to the presence of self-intersections in the region handled.")); } item->invalidateOpenGLBuffers(); viewer->update(); diff --git a/Polyhedron/demo/Polyhedron/Plugins/PCA/CMakeLists.txt b/Polyhedron/demo/Polyhedron/Plugins/PCA/CMakeLists.txt index ee9332ff8bd..f86989e9000 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PCA/CMakeLists.txt +++ b/Polyhedron/demo/Polyhedron/Plugins/PCA/CMakeLists.txt @@ -1,10 +1,10 @@ include( polyhedron_demo_macros ) -polyhedron_demo_plugin(pca_plugin Pca_plugin) +polyhedron_demo_plugin(pca_plugin Pca_plugin KEYWORDS PointSetProcessing) target_link_libraries(pca_plugin PUBLIC scene_surface_mesh_item scene_points_with_normal_item scene_basic_objects) qt5_wrap_ui( transformUI_FILES Transformation_widget.ui MeshOnGrid_dialog.ui) -polyhedron_demo_plugin(affine_transform_plugin Affine_transform_plugin ${transformUI_FILES}) +polyhedron_demo_plugin(affine_transform_plugin Affine_transform_plugin ${transformUI_FILES} KEYWORDS PointSetProcessing) target_link_libraries(affine_transform_plugin PUBLIC scene_surface_mesh_item scene_transform_item scene_points_with_normal_item) polyhedron_demo_plugin(edit_box_plugin Edit_box_plugin) @@ -18,5 +18,5 @@ polyhedron_demo_plugin(create_bbox_mesh_plugin Create_bbox_mesh_plugin) target_link_libraries(create_bbox_mesh_plugin PUBLIC scene_surface_mesh_item) qt5_wrap_ui( volumesUI_FILES Basic_generator_widget.ui) -polyhedron_demo_plugin(basic_generator_plugin Basic_generator_plugin ${volumesUI_FILES} KEYWORDS PolygonMesh) +polyhedron_demo_plugin(basic_generator_plugin Basic_generator_plugin ${volumesUI_FILES} KEYWORDS PolygonMesh PointSetProcessing) target_link_libraries(basic_generator_plugin PUBLIC scene_surface_mesh_item scene_points_with_normal_item scene_polylines_item) diff --git a/Polyhedron/demo/Polyhedron/Plugins/PCA/Pca_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/PCA/Pca_plugin.cpp index e56af0979ad..9f3ea5b8477 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PCA/Pca_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/PCA/Pca_plugin.cpp @@ -13,6 +13,7 @@ #include #include "Kernel_type.h" +#include typedef Kernel::Plane_3 Plane; typedef Kernel::Iso_cuboid_3 Iso_cuboid; typedef Kernel::Triangle_3 Triangle; @@ -99,148 +100,150 @@ void Polyhedron_demo_pca_plugin::on_actionFitPlane_triggered() Scene_surface_mesh_item* sm_item = qobject_cast(scene->item(index)); - QApplication::setOverrideCursor(Qt::WaitCursor); - - std::list triangles; - - SMesh* pMesh = sm_item->polyhedron(); - ::triangles(*pMesh,std::back_inserter(triangles)); - - if(! triangles.empty()){ - QString item_name = sm_item->name(); - // fit plane to triangles - Plane plane; - std::cout << "Fit plane..."; - CGAL::linear_least_squares_fitting_3(triangles.begin(),triangles.end(),plane,CGAL::Dimension_tag<2>()); - std::cout << "ok" << std::endl; - - // compute centroid - Point center_of_mass = CGAL::centroid(triangles.begin(),triangles.end()); - Scene_plane_item* new_item = new Scene_plane_item(this->scene); - new_item->setPosition(center_of_mass.x(), - center_of_mass.y(), - center_of_mass.z()); - const Vector& normal = plane.orthogonal_vector(); - new_item->setNormal(normal.x(), normal.y(), normal.z()); - new_item->setName(tr("%1 (plane fit)").arg(item_name)); - new_item->setColor(Qt::magenta); - new_item->setRenderingMode(sm_item->renderingMode()); - scene->addItem(new_item); - - } - else - { - Scene_points_with_normal_item* item = - qobject_cast(scene->item(index)); - - if (item) - { - Point_set* points = item->point_set(); - - // fit plane to triangles - Plane plane; - Point center_of_mass; - std::cout << "Fit plane..."; - CGAL::linear_least_squares_fitting_3 - (points->points().begin(),points->points().end(),plane, center_of_mass, - CGAL::Dimension_tag<0>()); - std::cout << "ok" << std::endl; - - // compute centroid - Scene_plane_item* new_item = new Scene_plane_item(this->scene); - new_item->setPosition(center_of_mass.x(), - center_of_mass.y(), - center_of_mass.z()); - const Vector& normal = plane.orthogonal_vector(); - new_item->setNormal(normal.x(), normal.y(), normal.z()); - new_item->setName(tr("%1 (plane fit)").arg(item->name())); - new_item->setColor(Qt::magenta); - new_item->setRenderingMode(item->renderingMode()); - scene->addItem(new_item); - - } + Three::CursorScopeGuard scope(Qt::WaitCursor); + if(sm_item){ + std::list triangles; + + SMesh* pMesh = sm_item->polyhedron(); + ::triangles(*pMesh,std::back_inserter(triangles)); + + if(! triangles.empty()){ + QString item_name = sm_item->name(); + // fit plane to triangles + Plane plane; + std::cout << "Fit plane..."; + CGAL::linear_least_squares_fitting_3(triangles.begin(),triangles.end(),plane,CGAL::Dimension_tag<2>()); + std::cout << "ok" << std::endl; + + // compute centroid + Point center_of_mass = CGAL::centroid(triangles.begin(),triangles.end()); + Scene_plane_item* new_item = new Scene_plane_item(this->scene); + new_item->setPosition(center_of_mass.x(), + center_of_mass.y(), + center_of_mass.z()); + const Vector& normal = plane.orthogonal_vector(); + new_item->setNormal(normal.x(), normal.y(), normal.z()); + new_item->setName(tr("%1 (plane fit)").arg(item_name)); + new_item->setColor(Qt::magenta); + new_item->setRenderingMode(sm_item->renderingMode()); + scene->addItem(new_item); + return; + } + } + Scene_points_with_normal_item* item = + qobject_cast(scene->item(index)); + + if (item) + { + Point_set* points = item->point_set(); + + // fit plane to triangles + Plane plane; + Point center_of_mass; + std::cout << "Fit plane..."; + CGAL::linear_least_squares_fitting_3 + (points->points().begin(),points->points().end(),plane, center_of_mass, + CGAL::Dimension_tag<0>()); + std::cout << "ok" << std::endl; + + // compute centroid + Scene_plane_item* new_item = new Scene_plane_item(this->scene); + new_item->setPosition(center_of_mass.x(), + center_of_mass.y(), + center_of_mass.z()); + const Vector& normal = plane.orthogonal_vector(); + new_item->setNormal(normal.x(), normal.y(), normal.z()); + new_item->setName(tr("%1 (plane fit)").arg(item->name())); + new_item->setColor(Qt::magenta); + new_item->setRenderingMode(item->renderingMode()); + scene->addItem(new_item); } - QApplication::restoreOverrideCursor(); } void Polyhedron_demo_pca_plugin::on_actionFitLine_triggered() { const CGAL::Three::Scene_interface::Item_id index = scene->mainSelectionIndex(); + Three::CursorScopeGuard sg(Qt::WaitCursor); + Scene_surface_mesh_item* sm_item = - qobject_cast(scene->item(index)); - - QApplication::setOverrideCursor(Qt::WaitCursor); - - CGAL::Bbox_3 bb; + qobject_cast(scene->item(index)); - std::list triangles; - SMesh* pMesh = sm_item->polyhedron(); - bb = ::triangles(*pMesh,std::back_inserter(triangles)); - - if(! triangles.empty()){ - QString item_name = sm_item->name(); - // fit line to triangles - Line line; - std::cout << "Fit line..."; - CGAL::linear_least_squares_fitting_3(triangles.begin(),triangles.end(),line,CGAL::Dimension_tag<2>()); - std::cout << "ok" << std::endl; - - // compute centroid - Point center_of_mass = CGAL::centroid(triangles.begin(),triangles.end()); - - // compute bounding box diagonal - Iso_cuboid bbox(bb); - - // compute scale for rendering using diagonal of bbox - Point cmin = (bbox.min)(); - Point cmax = (bbox.max)(); - FT diag = std::sqrt(CGAL::squared_distance(cmin,cmax)); - - // construct a 3D bar - Vector u = line.to_vector(); - u = u / std::sqrt(u*u); - - Point a = center_of_mass + u * diag; - Point b = center_of_mass - u * diag; - - Plane plane_a = line.perpendicular_plane(a); - - Vector u1 = plane_a.base1(); - u1 = u1 / std::sqrt(u1*u1); - u1 = u1 * 0.01 * diag; - Vector u2 = plane_a.base2(); - u2 = u2 / std::sqrt(u2*u2); - u2 = u2 * 0.01 * diag; - - Point points[8]; - - points[0] = a + u1; - points[1] = a + u2; - points[2] = a - u1; - points[3] = a - u2; - - points[4] = b + u1; - points[5] = b + u2; - points[6] = b - u1; - points[7] = b - u2; - - // add best fit line as new polyhedron bar - SMesh* pFit = new SMesh; - CGAL::make_hexahedron(points[0], - points[1], - points[2], - points[3], - points[4], - points[5], - points[6], - points[7], - *pFit); - Scene_surface_mesh_item* new_item = new Scene_surface_mesh_item(pFit); - new_item->setName(tr("%1 (line fit)").arg(item_name)); - new_item->setColor(Qt::magenta); - new_item->setRenderingMode( sm_item->renderingMode()); - scene->addItem(new_item); + if(sm_item) + { + CGAL::Bbox_3 bb; + + SMesh* pMesh = sm_item->polyhedron(); + std::list triangles; + + bb = ::triangles(*pMesh,std::back_inserter(triangles)); + + if(! triangles.empty()){ + QString item_name = sm_item->name(); + // fit line to triangles + Line line; + std::cout << "Fit line..."; + CGAL::linear_least_squares_fitting_3(triangles.begin(),triangles.end(),line,CGAL::Dimension_tag<2>()); + std::cout << "ok" << std::endl; + + // compute centroid + Point center_of_mass = CGAL::centroid(triangles.begin(),triangles.end()); + + // compute bounding box diagonal + Iso_cuboid bbox(bb); + + // compute scale for rendering using diagonal of bbox + Point cmin = (bbox.min)(); + Point cmax = (bbox.max)(); + FT diag = std::sqrt(CGAL::squared_distance(cmin,cmax)); + + // construct a 3D bar + Vector u = line.to_vector(); + u = u / std::sqrt(u*u); + + Point a = center_of_mass + u * diag; + Point b = center_of_mass - u * diag; + + Plane plane_a = line.perpendicular_plane(a); + + Vector u1 = plane_a.base1(); + u1 = u1 / std::sqrt(u1*u1); + u1 = u1 * 0.01 * diag; + Vector u2 = plane_a.base2(); + u2 = u2 / std::sqrt(u2*u2); + u2 = u2 * 0.01 * diag; + + Point points[8]; + + points[0] = a + u1; + points[1] = a + u2; + points[2] = a - u1; + points[3] = a - u2; + + points[4] = b + u1; + points[5] = b + u2; + points[6] = b - u1; + points[7] = b - u2; + + // add best fit line as new polyhedron bar + SMesh* pFit = new SMesh; + CGAL::make_hexahedron( + points[0], + points[3], + points[2], + points[1], + points[5], + points[4], + points[7], + points[6], + *pFit); + Scene_surface_mesh_item* new_item = new Scene_surface_mesh_item(pFit); + new_item->setName(tr("%1 (line fit)").arg(item_name)); + new_item->setColor(Qt::magenta); + new_item->setRenderingMode( sm_item->renderingMode()); + scene->addItem(new_item); + } + return; } else { @@ -297,15 +300,16 @@ void Polyhedron_demo_pca_plugin::on_actionFitLine_triggered() points[7] = b - u2; SMesh* pFit = new SMesh; - CGAL::make_hexahedron(points[0], - points[1], - points[2], - points[3], - points[4], - points[5], - points[6], - points[7], - *pFit); + CGAL::make_hexahedron( + points[0], + points[3], + points[2], + points[1], + points[5], + points[4], + points[7], + points[6], + *pFit); Scene_surface_mesh_item* new_item = new Scene_surface_mesh_item(pFit); new_item->setName(tr("%1 (line fit)").arg(item->name())); new_item->setColor(Qt::magenta); @@ -313,8 +317,6 @@ void Polyhedron_demo_pca_plugin::on_actionFitLine_triggered() scene->addItem(new_item); } } - - QApplication::restoreOverrideCursor(); } #include "Pca_plugin.moc" diff --git a/Polyhedron/demo/Polyhedron/Plugins/PCA/Scene_edit_box_item.cpp b/Polyhedron/demo/Polyhedron/Plugins/PCA/Scene_edit_box_item.cpp index baffa4ebf55..4846d60a13d 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PCA/Scene_edit_box_item.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/PCA/Scene_edit_box_item.cpp @@ -203,13 +203,13 @@ struct Scene_edit_box_item_priv{ if(QOpenGLContext::currentContext()->format().majorVersion() >= 3) { - pick_sphere_program.addShaderFromSourceFile(QOpenGLShader::Vertex,":/cgal/Polyhedron_3/resources/shader_spheres.v"); - pick_sphere_program.addShaderFromSourceFile(QOpenGLShader::Fragment,":/cgal/Polyhedron_3/resources/shader_without_light.f"); + pick_sphere_program.addShaderFromSourceFile(QOpenGLShader::Vertex,":/cgal/Polyhedron_3/resources/shader_spheres.vert"); + pick_sphere_program.addShaderFromSourceFile(QOpenGLShader::Fragment,":/cgal/Polyhedron_3/resources/shader_without_light.frag"); } else { - pick_sphere_program.addShaderFromSourceFile(QOpenGLShader::Vertex,":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_spheres.v"); - pick_sphere_program.addShaderFromSourceFile(QOpenGLShader::Fragment,":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_without_light.f"); + pick_sphere_program.addShaderFromSourceFile(QOpenGLShader::Vertex,":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_spheres.vert"); + pick_sphere_program.addShaderFromSourceFile(QOpenGLShader::Fragment,":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_without_light.frag"); } pick_sphere_program.bindAttributeLocation("colors", 1); pick_sphere_program.link(); diff --git a/Polyhedron/demo/Polyhedron/Plugins/PMP/CMakeLists.txt b/Polyhedron/demo/Polyhedron/Plugins/PMP/CMakeLists.txt index f7d3860eac6..9af3a6ebe11 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PMP/CMakeLists.txt +++ b/Polyhedron/demo/Polyhedron/Plugins/PMP/CMakeLists.txt @@ -39,7 +39,7 @@ else() endif() -polyhedron_demo_plugin(orient_soup_plugin Orient_soup_plugin) +polyhedron_demo_plugin(orient_soup_plugin Orient_soup_plugin KEYWORDS Classification) target_link_libraries(orient_soup_plugin PUBLIC scene_polygon_soup_item scene_surface_mesh_item scene_polylines_item scene_points_with_normal_item) @@ -64,7 +64,7 @@ polyhedron_demo_plugin(polyhedron_stitching_plugin Polyhedron_stitching_plugin) target_link_libraries(polyhedron_stitching_plugin PUBLIC scene_surface_mesh_item scene_polylines_item) qt5_wrap_ui( selectionUI_FILES Selection_widget.ui) -polyhedron_demo_plugin(selection_plugin Selection_plugin ${selectionUI_FILES} KEYWORDS PolygonMesh IO) +polyhedron_demo_plugin(selection_plugin Selection_plugin ${selectionUI_FILES} KEYWORDS PolygonMesh IO Classification) target_link_libraries(selection_plugin PUBLIC scene_selection_item scene_points_with_normal_item scene_polylines_item) polyhedron_demo_plugin(self_intersection_plugin Self_intersection_plugin) diff --git a/Polyhedron/demo/Polyhedron/Plugins/PMP/Corefinement_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/PMP/Corefinement_plugin.cpp index ce83faa6f5b..bb6c5ece3fd 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PMP/Corefinement_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/PMP/Corefinement_plugin.cpp @@ -3,6 +3,7 @@ #include #include "Messages_interface.h" #include +#include #include "Scene_surface_mesh_item.h" #include @@ -138,12 +139,12 @@ private: void apply_corefine(Item* item1, Item* item2) { if(! CGAL::is_triangle_mesh(*item1->face_graph())) { - messages->warning(tr("The face graph \"%1\" is not triangulated.") + CGAL::Three::Three::warning(tr("The face graph \"%1\" is not triangulated.") .arg(item1->name())); return; } if(! CGAL::is_triangle_mesh(*item2->face_graph())) { - messages->warning(tr("The face graph \"%1\" is not triangulated.") + CGAL::Three::Three::warning(tr("The face graph \"%1\" is not triangulated.") .arg(item2->name())); return; } @@ -151,6 +152,8 @@ private: QApplication::setOverrideCursor(Qt::WaitCursor); try{ PMP::corefine(*item1->face_graph(), *item2->face_graph(), params::throw_on_self_intersection(true)); + item1->resetColors(); + item2->resetColors(); item1->invalidateOpenGLBuffers(); item2->invalidateOpenGLBuffers(); scene->itemChanged(item2); @@ -158,7 +161,7 @@ private: } catch(CGAL::Polygon_mesh_processing::Corefinement::Self_intersection_exception) { - messages->warning(tr("The requested operation is not possible due to the presence of self-intersections in the neighborhood of the intersection.")); + CGAL::Three::Three::warning(tr("The requested operation is not possible due to the presence of self-intersections in the neighborhood of the intersection.")); } // default cursor QApplication::restoreOverrideCursor(); @@ -169,12 +172,12 @@ private: { typedef typename Item::Face_graph FaceGraph; if(! CGAL::is_triangle_mesh(*first_item->face_graph())) { - messages->warning(tr("The polyhedron \"%1\" is not triangulated.") + CGAL::Three::Three::warning(tr("The polyhedron \"%1\" is not triangulated.") .arg(first_item->name())); return; } if(! CGAL::is_triangle_mesh(*item->face_graph())) { - messages->warning(tr("The polyhedron \"%1\" is not triangulated.") + CGAL::Three::Three::warning(tr("The polyhedron \"%1\" is not triangulated.") .arg(item->name())); return; } @@ -191,7 +194,7 @@ private: if (! PMP::corefine_and_compute_union(P, Q, *new_poly, params::throw_on_self_intersection(true)) ) { delete new_poly; - messages->warning(tr("The result of the requested operation is not manifold and has not been computed.")); + CGAL::Three::Three::warning(tr("The result of the requested operation is not manifold and has not been computed.")); // default cursor QApplication::restoreOverrideCursor(); return; @@ -203,7 +206,7 @@ private: if (! PMP::corefine_and_compute_intersection(P, Q, *new_poly, params::throw_on_self_intersection(true)) ) { delete new_poly; - messages->warning(tr("The result of the requested operation is not manifold and has not been computed.")); + CGAL::Three::Three::warning(tr("The result of the requested operation is not manifold and has not been computed.")); // default cursor QApplication::restoreOverrideCursor(); return; @@ -218,7 +221,7 @@ private: if (! PMP::corefine_and_compute_difference(P, Q, *new_poly, params::throw_on_self_intersection(true)) ) { delete new_poly; - messages->warning(tr("The result of the requested operation is not manifold and has not been computed.")); + CGAL::Three::Three::warning(tr("The result of the requested operation is not manifold and has not been computed.")); // default cursor QApplication::restoreOverrideCursor(); return; @@ -228,7 +231,7 @@ private: } catch(CGAL::Polygon_mesh_processing::Corefinement::Self_intersection_exception) { - messages->warning(tr("The requested operation is not possible due to the presence of self-intersections in the neighborhood of the intersection.")); + CGAL::Three::Three::warning(tr("The requested operation is not possible due to the presence of self-intersections in the neighborhood of the intersection.")); QApplication::restoreOverrideCursor(); } diff --git a/Polyhedron/demo/Polyhedron/Plugins/PMP/Distance_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/PMP/Distance_plugin.cpp index 77506ecf4a7..48e8f51e082 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PMP/Distance_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/PMP/Distance_plugin.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -426,7 +427,7 @@ public Q_SLOTS: Scene_face_graph_item* itemB = qobject_cast(scene->item(scene->selectionIndices().last())); if(! CGAL::is_triangle_mesh(*itemA->polyhedron()) || !CGAL::is_triangle_mesh(*itemB->polyhedron()) ){ - messageInterface->error(QString("Distance not computed. (Both polyhedra must be triangulated)")); + CGAL::Three::Three::error(QString("Distance not computed. (Both polyhedra must be triangulated)")); return; } QApplication::setOverrideCursor(Qt::WaitCursor); diff --git a/Polyhedron/demo/Polyhedron/Plugins/PMP/Engrave_text_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/PMP/Engrave_text_plugin.cpp index 6cad4ed03c9..e48566c3383 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PMP/Engrave_text_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/PMP/Engrave_text_plugin.cpp @@ -302,7 +302,11 @@ private: Messages_interface* messages; public : - + ~Engrave_text_plugin() + { + delete graphics_scene; + delete navigation; + } void init(QMainWindow*, CGAL::Three::Scene_interface*, Messages_interface* m) Q_DECL_OVERRIDE{ @@ -734,7 +738,7 @@ public Q_SLOTS: if (PMP::does_self_intersect(text_mesh_complete)) { QApplication::restoreOverrideCursor(); - messages->information("Error: text mesh self-intersects!"); + CGAL::Three::Three::information("Error: text mesh self-intersects!"); return; } @@ -745,7 +749,7 @@ public Q_SLOTS: if (!OK) { QApplication::restoreOverrideCursor(); - messages->information("Error: the output mesh is not manifold!"); + CGAL::Three::Three::information("Error: the output mesh is not manifold!"); return; } diff --git a/Polyhedron/demo/Polyhedron/Plugins/PMP/Extrude_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/PMP/Extrude_plugin.cpp index 8c968b5e323..1a6a6dcc2d1 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PMP/Extrude_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/PMP/Extrude_plugin.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -370,7 +371,7 @@ private Q_SLOTS: pMesh = new Face_graph(); if(!sel_item->export_selected_facets_as_polyhedron(pMesh)) { - messageInterface->error("Face selection is not valid. Aborting."); + CGAL::Three::Three::error("Face selection is not valid. Aborting."); return; } @@ -386,7 +387,7 @@ private Q_SLOTS: return; if(CGAL::is_closed(*pMesh)) { - messageInterface->error("The face graph must be open. Aborting."); + CGAL::Three::Three::error("The face graph must be open. Aborting."); return; } std::vector triangles; @@ -448,6 +449,7 @@ private Q_SLOTS: Kernel::Vector_3(dir.x(), dir.y(), dir.z())); scene->erase(scene->item_id(oliver_queen)); oliver_queen = NULL; + target->resetColors(); target->invalidateOpenGLBuffers(); target->itemChanged(); target = NULL; diff --git a/Polyhedron/demo/Polyhedron/Plugins/PMP/Fairing_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/PMP/Fairing_plugin.cpp index 98cf548d126..d54a23fb011 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PMP/Fairing_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/PMP/Fairing_plugin.cpp @@ -3,6 +3,7 @@ #include "Messages_interface.h" #include +#include #include "Scene_polyhedron_selection_item.h" #include "ui_Fairing_widget.h" @@ -42,7 +43,7 @@ public: return qobject_cast(scene->item(scene->mainSelectionIndex())) || qobject_cast(scene->item(scene->mainSelectionIndex())); } - void print_message(QString message) { messages->information(message);} + void print_message(QString message) { CGAL::Three::Three::information(message);} QList actions() const { return QList() << actionFairing; } @@ -102,6 +103,7 @@ public Q_SLOTS: CGAL::Polygon_mesh_processing::fair(*selection_item->polyhedron(), selection_item->selected_vertices, CGAL::Polygon_mesh_processing::parameters::fairing_continuity(continuity)); + selection_item->polyhedron_item()->resetColors(); selection_item->changed_with_poly_item(); selection_item->invalidateOpenGLBuffers(); QApplication::restoreOverrideCursor(); @@ -127,6 +129,7 @@ public Q_SLOTS: for(std::vector::face_descriptor>::iterator it = new_facets.begin(); it != new_facets.end(); ++it) { selection_item->selected_facets.insert(*it); } + selection_item->polyhedron_item()->resetColors(); selection_item->changed_with_poly_item(); selection_item->invalidateOpenGLBuffers(); QApplication::restoreOverrideCursor(); diff --git a/Polyhedron/demo/Polyhedron/Plugins/PMP/Hole_filling_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/PMP/Hole_filling_plugin.cpp index 88523da2286..76764b80c23 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PMP/Hole_filling_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/PMP/Hole_filling_plugin.cpp @@ -9,6 +9,7 @@ #include "Scene.h" #include +#include #include "ui_Hole_filling_widget.h" #include @@ -323,7 +324,7 @@ class Polyhedron_demo_hole_filling_plugin : public: bool applicable(QAction*) const { return qobject_cast(scene->item(scene->mainSelectionIndex())) || qobject_cast(scene->item(scene->mainSelectionIndex())); } - void print_message(QString message) { messages->information(message); } + void print_message(QString message) { CGAL::Three::Three::information(message); } QList actions() const { return QList() << actionHoleFilling; } @@ -365,6 +366,7 @@ protected: void change_poly_item_by_blocking(Scene_face_graph_item* poly_item, Scene_hole_visualizer* collection) { if(collection) collection->block_poly_item_changed = true; + poly_item->resetColors(); poly_item->invalidateOpenGLBuffers(); poly_item->redraw(); if(collection) collection->block_poly_item_changed = false; @@ -859,7 +861,7 @@ void Polyhedron_demo_hole_filling_plugin::on_Fill_from_selection_button() { last_active_item = edge_selection->polyhedron_item(); accept_reject_toggle(true); } - + edge_selection->polyhedron_item()->resetColors(); edge_selection->polyhedron_item()->invalidateOpenGLBuffers(); edge_selection->polyhedron_item()->itemChanged(); } diff --git a/Polyhedron/demo/Polyhedron/Plugins/PMP/Hole_filling_polyline_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/PMP/Hole_filling_polyline_plugin.cpp index 605703178bc..9d90ffda2fd 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PMP/Hole_filling_polyline_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/PMP/Hole_filling_polyline_plugin.cpp @@ -25,6 +25,7 @@ #include #include +#include struct Face : public CGAL::cpp11::array @@ -48,7 +49,7 @@ class Polyhedron_demo_hole_filling_polyline_plugin : Q_PLUGIN_METADATA(IID "com.geometryfactory.PolyhedronDemo.PluginInterface/1.0") public: bool applicable(QAction *) const { return qobject_cast(scene->item(scene->mainSelectionIndex())); } - void print_message(QString message) { messages->information(message); } + void print_message(QString message) { CGAL::Three::Three::information(message); } QList actions() const { return QList() << actionHoleFillingPolyline; } void init(QMainWindow* mainWindow, CGAL::Three::Scene_interface* scene_interface, Messages_interface* m){ diff --git a/Polyhedron/demo/Polyhedron/Plugins/PMP/Join_and_split_polyhedra_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/PMP/Join_and_split_polyhedra_plugin.cpp index fc681f37cde..7fa8a640351 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PMP/Join_and_split_polyhedra_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/PMP/Join_and_split_polyhedra_plugin.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include @@ -168,7 +169,7 @@ void Polyhedron_demo_join_and_split_polyhedra_plugin::on_actionSplitPolyhedra_tr if (new_polyhedra.size()==1) { delete new_polyhedra.front(); - msg_interface->information( tr("%1 has only one connected component").arg(item->name()) ); + CGAL::Three::Three::information( tr("%1 has only one connected component").arg(item->name()) ); QApplication::restoreOverrideCursor(); continue; } diff --git a/Polyhedron/demo/Polyhedron/Plugins/PMP/Mean_curvature_flow_skeleton_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/PMP/Mean_curvature_flow_skeleton_plugin.cpp index 940fe1144d9..3e72878e7ea 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PMP/Mean_curvature_flow_skeleton_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/PMP/Mean_curvature_flow_skeleton_plugin.cpp @@ -98,6 +98,11 @@ class Polyhedron_demo_mean_curvature_flow_skeleton_plugin : public: + ~Polyhedron_demo_mean_curvature_flow_skeleton_plugin() + { + delete ui; + } + void init(QMainWindow* mainWindow, CGAL::Three::Scene_interface* scene_interface, Messages_interface*) { this->mw = mainWindow; diff --git a/Polyhedron/demo/Polyhedron/Plugins/PMP/Orient_soup_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/PMP/Orient_soup_plugin.cpp index d70f953d9a5..1ae9edc3f74 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PMP/Orient_soup_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/PMP/Orient_soup_plugin.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include "Messages_interface.h" using namespace CGAL::Three; class Polyhedron_demo_orient_soup_plugin : @@ -174,7 +175,7 @@ void Polyhedron_demo_orient_soup_plugin::orientSM() QApplication::restoreOverrideCursor(); } else{ - messages->warning(tr("This function is only applicable on polygon soups.")); + CGAL::Three::Three::warning(tr("This function is only applicable on polygon soups.")); } } } @@ -251,7 +252,7 @@ void Polyhedron_demo_orient_soup_plugin::createPointsAndPolyline() if(nm_vertices.empty()) { delete points; - messages->information(tr("There is no non-manifold vertex in this soup.")); + CGAL::Three::Three::information(tr("There is no non-manifold vertex in this soup.")); } else { @@ -286,7 +287,7 @@ void Polyhedron_demo_orient_soup_plugin::createPointsAndPolyline() } else { - messages->information(tr("There is no non-manifold edge in this soup.")); + CGAL::Three::Three::information(tr("There is no non-manifold edge in this soup.")); } QApplication::restoreOverrideCursor(); if(!items_created) diff --git a/Polyhedron/demo/Polyhedron/Plugins/PMP/Point_inside_polyhedron_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/PMP/Point_inside_polyhedron_plugin.cpp index 9625fc02fc4..ff19d4af3bb 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PMP/Point_inside_polyhedron_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/PMP/Point_inside_polyhedron_plugin.cpp @@ -5,7 +5,7 @@ #include "Scene_surface_mesh_item.h" #include "Scene_points_with_normal_item.h" #include - +#include #include #include @@ -52,7 +52,7 @@ public: //if the loop ends without returning true, return false return false; } - void print_message(QString message) { messages->information(message); } + void print_message(QString message) { CGAL::Three::Three::information(message); } QList actions() const { return QList() << actionPointInsidePolyhedron; } diff --git a/Polyhedron/demo/Polyhedron/Plugins/PMP/Polyhedron_slicer_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/PMP/Polyhedron_slicer_plugin.cpp index 8209f04fe71..dea7f885bb3 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PMP/Polyhedron_slicer_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/PMP/Polyhedron_slicer_plugin.cpp @@ -9,6 +9,7 @@ #include "Scene.h" #include +#include #include "ui_Polyhedron_slicer_widget.h" #include @@ -40,7 +41,7 @@ public: return qobject_cast(scene->item(scene->mainSelectionIndex())); } - void print_message(QString message) { messages->information(message);} + void print_message(QString message) { CGAL::Three::Three::information(message);} void init(QMainWindow* mainWindow, CGAL::Three::Scene_interface* scene_interface, Messages_interface* m); virtual void closure() diff --git a/Polyhedron/demo/Polyhedron/Plugins/PMP/Repair_polyhedron_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/PMP/Repair_polyhedron_plugin.cpp index 548cc110464..2367e703df9 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PMP/Repair_polyhedron_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/PMP/Repair_polyhedron_plugin.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include "Messages_interface.h" #include @@ -125,7 +126,7 @@ void Polyhedron_demo_repair_polyhedron_plugin::on_actionRemoveIsolatedVertices_t std::size_t nbv = CGAL::Polygon_mesh_processing::remove_isolated_vertices( *poly_item->polyhedron()); - messages->information(tr(" %1 isolated vertices have been removed.") + CGAL::Three::Three::information(tr(" %1 isolated vertices have been removed.") .arg(nbv)); poly_item->invalidateOpenGLBuffers(); Q_EMIT poly_item->itemChanged(); @@ -147,10 +148,11 @@ void Polyhedron_demo_repair_polyhedron_plugin::on_actionRemoveDegenerateFaces_tr qobject_cast(scene->item(index)); if (poly_item) { - std::size_t nbv = + std::size_t nbv = num_faces(*poly_item->polyhedron()); CGAL::Polygon_mesh_processing::remove_degenerate_faces( *poly_item->polyhedron()); - messages->information(tr(" %1 degenerate faces have been removed.") + nbv -= num_faces(*poly_item->polyhedron()); + CGAL::Three::Three::information(tr(" %1 degenerate faces have been removed.") .arg(nbv)); poly_item->invalidateOpenGLBuffers(); Q_EMIT poly_item->itemChanged(); @@ -176,7 +178,7 @@ void Polyhedron_demo_repair_polyhedron_plugin::on_actionRemoveSelfIntersections_ CGAL::Polygon_mesh_processing::remove_self_intersections( *poly_item->polyhedron()); if (!solved) - messages->information(tr("Some self-intersection could not be fixed")); + CGAL::Three::Three::information(tr("Some self-intersection could not be fixed")); poly_item->invalidateOpenGLBuffers(); Q_EMIT poly_item->itemChanged(); } @@ -202,7 +204,7 @@ void Polyhedron_demo_repair_polyhedron_plugin::on_actionAutorefine_triggered(Sce } catch(CGAL::Polygon_mesh_processing::Corefinement::Triple_intersection_exception) { - messages->warning(tr("The result of the requested operation is not handled (triple intersection).")); + CGAL::Three::Three::warning(tr("The result of the requested operation is not handled (triple intersection).")); } poly_item->invalidateOpenGLBuffers(); Q_EMIT poly_item->itemChanged(); @@ -229,11 +231,11 @@ void Polyhedron_demo_repair_polyhedron_plugin::on_actionAutorefineAndRMSelfInter CGAL::Polygon_mesh_processing::experimental:: autorefine_and_remove_self_intersections(*poly_item->polyhedron()); if (!solved) - messages->information(tr("Self-intersection could not be removed due to non-manifold edges in the output")); + CGAL::Three::Three::information(tr("Self-intersection could not be removed due to non-manifold edges in the output")); } catch(CGAL::Polygon_mesh_processing::Corefinement::Triple_intersection_exception) { - messages->warning(tr("The result of the requested operation is not handled (triple intersection).")); + CGAL::Three::Three::warning(tr("The result of the requested operation is not handled (triple intersection).")); } poly_item->invalidateOpenGLBuffers(); Q_EMIT poly_item->itemChanged(); @@ -268,7 +270,7 @@ void Polyhedron_demo_repair_polyhedron_plugin::on_actionStitchCloseBorderHalfedg get(boost::vertex_point, *poly_item->polyhedron()), halfedges_to_stitch); PMP::stitch_borders(*poly_item->polyhedron(), halfedges_to_stitch); - messages->information(tr(" %1 pairs of halfedges stitched.").arg(halfedges_to_stitch.size())); + CGAL::Three::Three::information(tr(" %1 pairs of halfedges stitched.").arg(halfedges_to_stitch.size())); poly_item->invalidateOpenGLBuffers(); Q_EMIT poly_item->itemChanged(); } @@ -290,7 +292,7 @@ void Polyhedron_demo_repair_polyhedron_plugin::on_actionDuplicateNMVertices_trig if (Item* poly_item = qobject_cast(scene->item(index))) { std::size_t nb_vd = PMP::duplicate_non_manifold_vertices(*poly_item->polyhedron()); - messages->information(tr(" %1 vertices created").arg(nb_vd)); + CGAL::Three::Three::information(tr(" %1 vertices created").arg(nb_vd)); if (nb_vd) { poly_item->invalidateOpenGLBuffers(); diff --git a/Polyhedron/demo/Polyhedron/Plugins/PMP/Scene_facegraph_item_k_ring_selection.h b/Polyhedron/demo/Polyhedron/Plugins/PMP/Scene_facegraph_item_k_ring_selection.h index 318663f2e65..86747634b0f 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PMP/Scene_facegraph_item_k_ring_selection.h +++ b/Polyhedron/demo/Polyhedron/Plugins/PMP/Scene_facegraph_item_k_ring_selection.h @@ -134,6 +134,8 @@ public Q_SLOTS: // slots are called by signals of polyhedron_item void vertex_has_been_selected(void* void_ptr) { + if((*CGAL::QGLViewer::QGLViewerPool().begin())->property("performing_selection").toBool()) + return; is_active=true; if(active_handle_type == Active_handle::VERTEX || active_handle_type == Active_handle::PATH) { @@ -145,6 +147,8 @@ public Q_SLOTS: } void facet_has_been_selected(void* void_ptr) { + if((*CGAL::QGLViewer::QGLViewerPool().begin())->property("performing_selection").toBool()) + return; is_active=true; if (active_handle_type == Active_handle::FACET || active_handle_type == Active_handle::CONNECTED_COMPONENT) @@ -157,6 +161,8 @@ public Q_SLOTS: } void edge_has_been_selected(void* void_ptr) { + if((*CGAL::QGLViewer::QGLViewerPool().begin())->property("performing_selection").toBool()) + return; is_active=true; if(active_handle_type == Active_handle::EDGE) { diff --git a/Polyhedron/demo/Polyhedron/Plugins/PMP/Selection_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/PMP/Selection_plugin.cpp index baf70e4deed..dc80426098a 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PMP/Selection_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/PMP/Selection_plugin.cpp @@ -1,8 +1,6 @@ #include #include - -#include "Messages_interface.h" #include "Kernel_type.h" #include "Scene_surface_mesh_item.h" #include "Scene_polyhedron_selection_item.h" @@ -10,6 +8,7 @@ #include "Scene_polylines_item.h" #include +#include #include #include #include @@ -118,7 +117,7 @@ public: return qobject_cast(scene->item(scene->mainSelectionIndex())) || qobject_cast(scene->item(scene->mainSelectionIndex())); } - void print_message(QString message) { messages->information(message); } + void print_message(QString message) { CGAL::Three::Three::information(message); } QList actions() const { return QList() << actionSelection; } void init(QMainWindow* mainWindow, CGAL::Three::Scene_interface* scene_interface, Messages_interface* m) { @@ -128,6 +127,7 @@ public: actionSelection = new QAction( QString("Surface Mesh Selection") , mw); + actionSelection->setObjectName("actionSelection"); connect(actionSelection, SIGNAL(triggered()), this, SLOT(selection_action())); last_mode = 0; dock_widget = new QDockWidget( @@ -138,6 +138,11 @@ public: dock_widget->setWindowTitle(tr( "Surface Mesh Selection" )); + connect(dock_widget, &QDockWidget::visibilityChanged, + this, [this](bool b){ + if(!b) + this->set_operation_mode(-1); + }); addDockWidget(dock_widget); @@ -772,7 +777,8 @@ public Q_SLOTS: bool is_valid = true; BOOST_FOREACH(boost::graph_traits::face_descriptor fd, faces(*selection_item->polyhedron())) { - if (CGAL::Polygon_mesh_processing::is_degenerate_triangle_face(fd, *selection_item->polyhedron())) + if (is_triangle(halfedge(fd, *selection_item->polyhedron()), *selection_item->polyhedron()) + && CGAL::Polygon_mesh_processing::is_degenerate_triangle_face(fd, *selection_item->polyhedron())) { is_valid = false; break; diff --git a/Polyhedron/demo/Polyhedron/Plugins/PMP/Selection_widget.ui b/Polyhedron/demo/Polyhedron/Plugins/PMP/Selection_widget.ui index 6cb5504b0c3..22d3ed83b49 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PMP/Selection_widget.ui +++ b/Polyhedron/demo/Polyhedron/Plugins/PMP/Selection_widget.ui @@ -551,7 +551,7 @@ - Split edges + Split edge diff --git a/Polyhedron/demo/Polyhedron/Plugins/PMP/Surface_intersection_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/PMP/Surface_intersection_plugin.cpp index 0bc18398d00..f437347ab0d 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PMP/Surface_intersection_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/PMP/Surface_intersection_plugin.cpp @@ -4,6 +4,7 @@ #include "Kernel_type.h" #include "Scene_surface_mesh_item.h" #include +#include #include "Scene_polylines_item.h" #include "Scene_points_with_normal_item.h" @@ -124,7 +125,7 @@ void Polyhedron_demo_intersection_plugin::intersectionSurfaces() if(!is_triangle_mesh(*itemA->face_graph()) || !is_triangle_mesh(*itemB->face_graph())) { - mi->error("The two meshes must be triangle meshes."); + CGAL::Three::Three::error("The two meshes must be triangle meshes."); } QApplication::setOverrideCursor(Qt::WaitCursor); @@ -282,7 +283,7 @@ void Polyhedron_demo_intersection_plugin::intersectionSurfacePolyline() if(!is_triangle_mesh(*itemA->face_graph())) { - mi->error("The mesh must be a triangle mesh."); + CGAL::Three::Three::error("The mesh must be a triangle mesh."); } QApplication::setOverrideCursor(Qt::WaitCursor); diff --git a/Polyhedron/demo/Polyhedron/Plugins/PMP/Triangulate_facets_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/PMP/Triangulate_facets_plugin.cpp index acf5bf53abe..041a9efb815 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/PMP/Triangulate_facets_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/PMP/Triangulate_facets_plugin.cpp @@ -3,6 +3,7 @@ #include #include "Messages_interface.h" #include +#include #include "Scene_surface_mesh_item.h" #include @@ -53,13 +54,14 @@ public Q_SLOTS: SMesh* pMesh = sm_item->polyhedron(); if(!pMesh) continue; if(is_triangle_mesh(*pMesh)) { - messages->warning(tr("The polyhedron \"%1\" is already triangulated.") + CGAL::Three::Three::warning(tr("The polyhedron \"%1\" is already triangulated.") .arg(sm_item->name()) ); continue; } if(!CGAL::Polygon_mesh_processing::triangulate_faces(*pMesh)) - messages->warning(tr("Some facets could not be triangulated.")); - + CGAL::Three::Three::warning(tr("Some facets could not be triangulated.")); + + sm_item->resetColors(); sm_item->invalidateOpenGLBuffers(); scene->itemChanged(sm_item); } // end of the loop on the selected items diff --git a/Polyhedron/demo/Polyhedron/Plugins/Point_set/Alpha_shape_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/Point_set/Alpha_shape_plugin.cpp index 921ff997411..ad5493d3843 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Point_set/Alpha_shape_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/Point_set/Alpha_shape_plugin.cpp @@ -342,7 +342,7 @@ Scene_alpha_shape_item::Scene_alpha_shape_item(Scene_points_with_normal_item *po { facet_program.addShaderFromSourceCode(QOpenGLShader::Vertex, vertex_source_comp); } - facet_program.addShaderFromSourceFile(QOpenGLShader::Fragment, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_old_flat.f"); + facet_program.addShaderFromSourceFile(QOpenGLShader::Fragment, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_old_flat.frag"); facet_program.link(); invalidateOpenGLBuffers(); alpha_changed(alpha); diff --git a/Polyhedron/demo/Polyhedron/Plugins/Point_set/CMakeLists.txt b/Polyhedron/demo/Polyhedron/Plugins/Point_set/CMakeLists.txt index 2c3571b54c1..9c56ba4df2a 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Point_set/CMakeLists.txt +++ b/Polyhedron/demo/Polyhedron/Plugins/Point_set/CMakeLists.txt @@ -1,21 +1,21 @@ include( polyhedron_demo_macros ) if(EIGEN3_FOUND) qt5_wrap_ui( surface_reconstructionUI_FILES Surface_reconstruction_plugin.ui) - polyhedron_demo_plugin(surface_reconstruction_plugin Surface_reconstruction_plugin Surface_reconstruction_plugin_impl ${surface_reconstructionUI_FILES}) + polyhedron_demo_plugin(surface_reconstruction_plugin Surface_reconstruction_plugin Surface_reconstruction_plugin_impl ${surface_reconstructionUI_FILES} KEYWORDS PointSetProcessing) target_link_libraries(surface_reconstruction_plugin PUBLIC scene_polygon_soup_item scene_surface_mesh_item scene_points_with_normal_item) qt5_wrap_ui( point_set_normal_estimationUI_FILES Point_set_normal_estimation_plugin.ui) - polyhedron_demo_plugin(point_set_normal_estimation_plugin Point_set_normal_estimation_plugin ${point_set_normal_estimationUI_FILES}) + polyhedron_demo_plugin(point_set_normal_estimation_plugin Point_set_normal_estimation_plugin ${point_set_normal_estimationUI_FILES} KEYWORDS PointSetProcessing Classification) target_link_libraries(point_set_normal_estimation_plugin PUBLIC scene_points_with_normal_item scene_callback_signaler) qt5_wrap_ui( features_detection_pluginUI_FILES Features_detection_plugin.ui) - polyhedron_demo_plugin(features_detection_plugin Features_detection_plugin ${features_detection_pluginUI_FILES}) + polyhedron_demo_plugin(features_detection_plugin Features_detection_plugin ${features_detection_pluginUI_FILES} KEYWORDS PointSetProcessing) target_link_libraries(features_detection_plugin PUBLIC scene_points_with_normal_item) - polyhedron_demo_plugin(point_set_smoothing_plugin Point_set_smoothing_plugin) + polyhedron_demo_plugin(point_set_smoothing_plugin Point_set_smoothing_plugin KEYWORDS PointSetProcessing) target_link_libraries(point_set_smoothing_plugin PUBLIC scene_points_with_normal_item scene_callback_signaler) - polyhedron_demo_plugin(point_set_average_spacing_plugin Point_set_average_spacing_plugin) + polyhedron_demo_plugin(point_set_average_spacing_plugin Point_set_average_spacing_plugin KEYWORDS PointSetProcessing Classification) target_link_libraries(point_set_average_spacing_plugin PUBLIC scene_points_with_normal_item scene_callback_signaler) else(EIGEN3_FOUND) @@ -28,45 +28,45 @@ else(EIGEN3_FOUND) endif() qt5_wrap_ui(point_set_bilateral_smoothingUI_FILES Point_set_bilateral_smoothing_plugin.ui) - polyhedron_demo_plugin(point_set_bilateral_smoothing_plugin Point_set_bilateral_smoothing_plugin ${point_set_bilateral_smoothingUI_FILES}) + polyhedron_demo_plugin(point_set_bilateral_smoothing_plugin Point_set_bilateral_smoothing_plugin ${point_set_bilateral_smoothingUI_FILES} KEYWORDS PointSetProcessing) target_link_libraries(point_set_bilateral_smoothing_plugin PUBLIC scene_points_with_normal_item scene_callback_signaler) qt5_wrap_ui( ps_outliers_removal_UI_FILES Point_set_outliers_removal_plugin.ui) - polyhedron_demo_plugin(point_set_outliers_removal_plugin Point_set_outliers_removal_plugin ${ps_outliers_removal_UI_FILES}) + polyhedron_demo_plugin(point_set_outliers_removal_plugin Point_set_outliers_removal_plugin ${ps_outliers_removal_UI_FILES} KEYWORDS PointSetProcessing) target_link_libraries(point_set_outliers_removal_plugin PUBLIC scene_points_with_normal_item scene_callback_signaler) qt5_wrap_ui( point_set_selectionUI_FILES Point_set_selection_widget.ui) - polyhedron_demo_plugin(point_set_selection_plugin Point_set_selection_plugin ${point_set_selectionUI_FILES}) + polyhedron_demo_plugin(point_set_selection_plugin Point_set_selection_plugin ${point_set_selectionUI_FILES} KEYWORDS PointSetProcessing Classification) target_link_libraries(point_set_selection_plugin PUBLIC scene_points_with_normal_item scene_polylines_item scene_edit_box_item) qt5_wrap_ui(point_set_shape_detectionUI_FILES Point_set_shape_detection_plugin.ui) - polyhedron_demo_plugin(point_set_shape_detection_plugin Point_set_shape_detection_plugin ${point_set_shape_detectionUI_FILES}) + polyhedron_demo_plugin(point_set_shape_detection_plugin Point_set_shape_detection_plugin ${point_set_shape_detectionUI_FILES} KEYWORDS PointSetProcessing Classification) target_link_libraries(point_set_shape_detection_plugin PUBLIC scene_surface_mesh_item scene_points_with_normal_item scene_polygon_soup_item scene_callback_signaler) qt5_wrap_ui(point_set_simplificationUI_FILES Point_set_simplification_plugin.ui) - polyhedron_demo_plugin(point_set_simplification_plugin Point_set_simplification_plugin ${point_set_simplificationUI_FILES}) + polyhedron_demo_plugin(point_set_simplification_plugin Point_set_simplification_plugin ${point_set_simplificationUI_FILES} KEYWORDS PointSetProcessing) target_link_libraries(point_set_simplification_plugin PUBLIC scene_points_with_normal_item scene_callback_signaler) qt5_wrap_ui(point_set_upsamplingUI_FILES Point_set_upsampling_plugin.ui) - polyhedron_demo_plugin(point_set_upsampling_plugin Point_set_upsampling_plugin ${point_set_upsamplingUI_FILES}) + polyhedron_demo_plugin(point_set_upsampling_plugin Point_set_upsampling_plugin ${point_set_upsamplingUI_FILES} KEYWORDS PointSetProcessing) target_link_libraries(point_set_upsampling_plugin PUBLIC scene_points_with_normal_item) qt5_wrap_ui(point_set_wlopFILES Point_set_wlop_plugin.ui) - polyhedron_demo_plugin(point_set_wlop_plugin Point_set_wlop_plugin ${point_set_wlopFILES}) + polyhedron_demo_plugin(point_set_wlop_plugin Point_set_wlop_plugin ${point_set_wlopFILES} KEYWORDS PointSetProcessing) target_link_libraries(point_set_wlop_plugin PUBLIC scene_points_with_normal_item scene_callback_signaler) - polyhedron_demo_plugin(merge_point_sets_plugin Merge_point_sets_plugin) + polyhedron_demo_plugin(merge_point_sets_plugin Merge_point_sets_plugin KEYWORDS PointSetProcessing Classification) target_link_libraries(merge_point_sets_plugin PUBLIC scene_points_with_normal_item) - polyhedron_demo_plugin(point_set_interference_plugin Point_set_interference_plugin) + polyhedron_demo_plugin(point_set_interference_plugin Point_set_interference_plugin KEYWORDS PointSetProcessing) target_link_libraries(point_set_interference_plugin PUBLIC scene_points_with_normal_item) qt5_wrap_ui( alpha_shapeUI_FILES Alpha_shape_widget.ui ) - polyhedron_demo_plugin(alpha_shape_plugin Alpha_shape_plugin ${alpha_shapeUI_FILES}) + polyhedron_demo_plugin(alpha_shape_plugin Alpha_shape_plugin ${alpha_shapeUI_FILES} KEYWORDS PointSetProcessing) target_link_libraries(alpha_shape_plugin PUBLIC scene_points_with_normal_item scene_c3t3_item) qt5_wrap_ui( distanceUI_FILES Point_set_to_mesh_distance_widget.ui ) - polyhedron_demo_plugin(point_set_to_mesh_distance_plugin Point_set_to_mesh_distance_plugin ${distanceUI_FILES}) + polyhedron_demo_plugin(point_set_to_mesh_distance_plugin Point_set_to_mesh_distance_plugin ${distanceUI_FILES} KEYWORDS PointSetProcessing) target_link_libraries(point_set_to_mesh_distance_plugin PUBLIC scene_points_with_normal_item scene_surface_mesh_item scene_color_ramp) if(TBB_FOUND) diff --git a/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_normal_estimation_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_normal_estimation_plugin.cpp index 5193fec725f..d0b4bf7bcac 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_normal_estimation_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_normal_estimation_plugin.cpp @@ -254,7 +254,7 @@ void Polyhedron_demo_point_set_normal_estimation_plugin::on_actionNormalEstimati std::cerr << "Estimates normal direction by Jet Fitting (k=" << dialog.jet_neighbors() <<")...\n"; // Estimates normals direction. - Jet_estimate_normals_functor functor (points, dialog.pca_neighbors()); + Jet_estimate_normals_functor functor (points, dialog.jet_neighbors()); run_with_qprogressdialog (functor, "Estimating normals by jet fitting...", mw); std::size_t memory = CGAL::Memory_sizer().virtual_size(); diff --git a/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_selection_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_selection_plugin.cpp index 9b9c5853770..4e8d917e5b9 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_selection_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_selection_plugin.cpp @@ -16,6 +16,7 @@ #include #include +#include #include "ui_Point_set_selection_widget.h" #include #include "Point_set_3.h" @@ -415,7 +416,7 @@ public: bool applicable(QAction*) const { return qobject_cast(scene->item(scene->mainSelectionIndex())); } - void print_message(QString message) { messages->information(message); } + void print_message(QString message) { CGAL::Three::Three::information(message); } QList actions() const { return QList() << actionPointSetSelection; } void init(QMainWindow* mainWindow, CGAL::Three::Scene_interface* scene_interface, Messages_interface* m) { @@ -426,6 +427,7 @@ public: rg_cluster_epsilon = -1; rg_normal_threshold = 20; actionPointSetSelection = new QAction(tr("Selection"), mw); + actionPointSetSelection->setObjectName("actionPointSetSelection"); connect(actionPointSetSelection, SIGNAL(triggered()), this, SLOT(selection_action())); dock_widget = new QDockWidget("Point Set Selection", mw); @@ -615,7 +617,7 @@ protected: Neighbor_search search(tree, Point(point.x, point.y, point.z), 1); Point res = search.begin()->first; - messages->information(QString("Selected point : (%1, %2, %3)").arg(res.x()).arg(res.y()).arg(res.z())); + CGAL::Three::Three::information(QString("Selected point : (%1, %2, %3)").arg(res.x()).arg(res.y()).arg(res.z())); } return false; } diff --git a/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_to_mesh_distance_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_to_mesh_distance_plugin.cpp index 582335319fd..9ea6404172d 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_to_mesh_distance_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_to_mesh_distance_plugin.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -184,7 +185,7 @@ private Q_SLOTS: if(!item || !item->point_set()->has_property_map("distance")) { - messageInterface->warning("You must select the resulting point set."); + CGAL::Three::Three::warning("You must select the resulting point set."); return; } PMap distance_map; diff --git a/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_upsampling_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_upsampling_plugin.cpp index ad3e5642578..2fba3abfcb8 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_upsampling_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_upsampling_plugin.cpp @@ -3,6 +3,7 @@ #include "Messages_interface.h" #include #include +#include #include #include @@ -86,7 +87,7 @@ void Polyhedron_demo_point_set_upsampling_plugin::on_actionEdgeAwareUpsampling_t { if (!(item->has_normals ())) { - message_interface->error("Error: upsampling algorithm requires point set with normals."); + CGAL::Three::Three::error("Error: upsampling algorithm requires point set with normals."); return; } diff --git a/Polyhedron/demo/Polyhedron/Plugins/Subdivision_methods/Subdivision_methods_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/Subdivision_methods/Subdivision_methods_plugin.cpp index 2b54e27cf3e..0d00de8eb16 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Subdivision_methods/Subdivision_methods_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/Subdivision_methods/Subdivision_methods_plugin.cpp @@ -6,6 +6,7 @@ #include #include +#include #include "Messages_interface.h" #include "Scene_surface_mesh_item.h" @@ -82,10 +83,10 @@ void Polyhedron_demo_subdivision_methods_plugin::apply_loop(FaceGraphItem* item, typename FaceGraphItem::Face_graph* graph = item->face_graph(); QTime time; time.start(); - messages->information("Loop subdivision..."); + CGAL::Three::Three::information("Loop subdivision..."); QApplication::setOverrideCursor(Qt::WaitCursor); CGAL::Subdivision_method_3::Loop_subdivision(*graph, params::number_of_iterations(nb_steps)); - messages->information(QString("ok (%1 ms)").arg(time.elapsed())); + CGAL::Three::Three::information(QString("ok (%1 ms)").arg(time.elapsed())); QApplication::restoreOverrideCursor(); item->invalidateOpenGLBuffers(); scene->itemChanged(item); @@ -114,10 +115,10 @@ void Polyhedron_demo_subdivision_methods_plugin::apply_catmullclark(FaceGraphIte if(!graph) return; QTime time; time.start(); - messages->information("Catmull-Clark subdivision..."); + CGAL::Three::Three::information("Catmull-Clark subdivision..."); QApplication::setOverrideCursor(Qt::WaitCursor); CGAL::Subdivision_method_3::CatmullClark_subdivision(*graph, params::number_of_iterations(nb_steps)); - messages->information(QString("ok (%1 ms)").arg(time.elapsed())); + CGAL::Three::Three::information(QString("ok (%1 ms)").arg(time.elapsed())); QApplication::restoreOverrideCursor(); item->invalidateOpenGLBuffers(); scene->itemChanged(item); @@ -144,10 +145,10 @@ void Polyhedron_demo_subdivision_methods_plugin::apply_sqrt3(FaceGraphItem* item if(!graph) return; QTime time; time.start(); - messages->information("Sqrt-3 subdivision..."); + CGAL::Three::Three::information("Sqrt-3 subdivision..."); QApplication::setOverrideCursor(Qt::WaitCursor); CGAL::Subdivision_method_3::Sqrt3_subdivision(*graph, params::number_of_iterations(nb_steps)); - messages->information(QString("ok (%1 ms)").arg(time.elapsed())); + CGAL::Three::Three::information(QString("ok (%1 ms)").arg(time.elapsed())); QApplication::restoreOverrideCursor(); item->invalidateOpenGLBuffers(); scene->itemChanged(item); @@ -176,10 +177,10 @@ void Polyhedron_demo_subdivision_methods_plugin::apply_doosabin(FaceGraphItem* i if(!graph) return; QTime time; time.start(); - messages->information("Doo-Sabin subdivision..."); + CGAL::Three::Three::information("Doo-Sabin subdivision..."); QApplication::setOverrideCursor(Qt::WaitCursor); CGAL::Subdivision_method_3::DooSabin_subdivision(*graph, params::number_of_iterations(nb_steps)); - messages->information(QString("ok (%1 ms)").arg(time.elapsed())); + CGAL::Three::Three::information(QString("ok (%1 ms)").arg(time.elapsed())); QApplication::restoreOverrideCursor(); item->invalidateOpenGLBuffers(); scene->itemChanged(item); diff --git a/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Parameterization_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Parameterization_plugin.cpp index 06a7f88598b..bfd1c597ff7 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Parameterization_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Parameterization_plugin.cpp @@ -9,6 +9,7 @@ #include "SMesh_type.h" #include #include +#include #include "Scene.h" #include #include @@ -316,6 +317,10 @@ public: return _actions; } + ~Polyhedron_demo_parameterization_plugin() + { + delete navigation; + } void init(QMainWindow* mainWindow, Scene_interface* scene_interface, Messages_interface* msg) @@ -540,14 +545,14 @@ void Polyhedron_demo_parameterization_plugin::parameterize(const Parameterizatio if(!poly_item) { - messages->error("Selected item is not of the right type."); + CGAL::Three::Three::error("Selected item is not of the right type."); return; } Face_graph* pMesh = poly_item->face_graph(); if(!pMesh) { - messages->error("Selected item has no valid polyhedron."); + CGAL::Three::Three::error("Selected item has no valid polyhedron."); return; } Scene_polyhedron_selection_item* sel_item = NULL; @@ -579,7 +584,7 @@ void Polyhedron_demo_parameterization_plugin::parameterize(const Parameterizatio if(!is_seamed && is_closed(*pMesh)) { - messages->error("The selected mesh has no (real or virtual) border."); + CGAL::Three::Three::error("The selected mesh has no (real or virtual) border."); return; } @@ -824,6 +829,7 @@ void Polyhedron_demo_parameterization_plugin::parameterize(const Parameterizatio if (i == QDialog::Rejected) { std::cout << "Aborting parameterization" << std::endl; + QApplication::restoreOverrideCursor(); return; } @@ -836,6 +842,7 @@ void Polyhedron_demo_parameterization_plugin::parameterize(const Parameterizatio std::cerr << "Error: incompatible orbifold type and number of cones" << std::endl; std::cerr << "Types I, II & III require 3 selected vertices" << std::endl; std::cerr << "Type IV requires 4 selected vertices" << std::endl; + QApplication::restoreOverrideCursor(); return; } @@ -847,6 +854,7 @@ void Polyhedron_demo_parameterization_plugin::parameterize(const Parameterizatio if(!SMP::locate_unordered_cones(sMesh, unordered_cones.begin(), unordered_cones.end(), cmap)) { std::cerr << "Error: invalid cone or seam selection" << std::endl; + QApplication::restoreOverrideCursor(); return; } @@ -881,6 +889,7 @@ void Polyhedron_demo_parameterization_plugin::parameterize(const Parameterizatio std::cout << "success (in " << time.elapsed() << " ms)" << std::endl; } else { std::cerr << "failure: " << SMP::get_error_message(status) << std::endl; + QApplication::restoreOverrideCursor(); return; } diff --git a/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Scene_polyhedron_shortest_path_item.cpp b/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Scene_polyhedron_shortest_path_item.cpp index c397aa48ebe..9df5eec30ac 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Scene_polyhedron_shortest_path_item.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Scene_polyhedron_shortest_path_item.cpp @@ -9,6 +9,7 @@ #include #include +#include #include typedef Scene_polyhedron_shortest_path_item It; @@ -242,9 +243,9 @@ void Scene_polyhedron_shortest_path_item_priv::ensure_shortest_paths_tree() { if (!m_shortestPaths->changed_since_last_build()) { - m_messages->information("Recomputing shortest paths tree..."); + CGAL::Three::Three::information("Recomputing shortest paths tree..."); m_shortestPaths->build_sequence_tree(); - m_messages->information("Done."); + CGAL::Three::Three::information("Done."); } } @@ -387,7 +388,7 @@ bool Scene_polyhedron_shortest_path_item_priv::run_point_select(const Ray_3& ray if (faceLocation.first == GraphTraits::null_face()) { - m_messages->information(QObject::tr("Shortest Paths: No face under cursor.")); + CGAL::Three::Three::information(QObject::tr("Shortest Paths: No face under cursor.")); QApplication::restoreOverrideCursor(); return false; } @@ -395,7 +396,7 @@ bool Scene_polyhedron_shortest_path_item_priv::run_point_select(const Ray_3& ray { boost::property_map::type fimap = get(CGAL::face_index, *item->polyhedron()); - m_messages->information(QObject::tr("Shortest Paths: Selected Face: %1; Barycentric coordinates: %2 %3 %4") + CGAL::Three::Three::information(QObject::tr("Shortest Paths: Selected Face: %1; Barycentric coordinates: %2 %3 %4") .arg(get(fimap, faceLocation.first)) .arg(double(faceLocation.second[0])) .arg(double(faceLocation.second[1])) @@ -442,7 +443,7 @@ bool Scene_polyhedron_shortest_path_item_priv::run_point_select(const Ray_3& ray polylines->polylines.push_back(Scene_polylines_item::Polyline()); - m_messages->information(QObject::tr("Computing shortest path polyline...")); + CGAL::Three::Three::information(QObject::tr("Computing shortest path polyline...")); QTime time; time.start(); @@ -462,7 +463,7 @@ bool Scene_polyhedron_shortest_path_item_priv::run_point_select(const Ray_3& ray } else { - m_messages->warning(QObject::tr("No source points to compute shortest paths from.")); + CGAL::Three::Three::warning(QObject::tr("No source points to compute shortest paths from.")); } break; } diff --git a/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Shortest_path_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Shortest_path_plugin.cpp index b9995cba4f1..b411c8c6a17 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Shortest_path_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Shortest_path_plugin.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include "Scene_surface_mesh_item.h" #include "Scene_polyhedron_shortest_path_item.h" @@ -192,14 +193,14 @@ void Polyhedron_demo_shortest_path_plugin::new_item(int itemIndex) if(!polyhedronItem) { CGAL_assertion(item->polyhedron_item() == NULL); // which means it is coming from selection_io loader - this->m_messages->information(tr("Error: please select corresponding polyhedron item from Geometric Objects list.")); + CGAL::Three::Three::information(tr("Error: please select corresponding polyhedron item from Geometric Objects list.")); scene->erase(itemIndex); return; } if(!item->deferred_load(polyhedronItem, this->scene, this->m_messages, this->mw)) { - this->m_messages->information("Error: loading selection item is not successful!"); + CGAL::Three::Three::information("Error: loading selection item is not successful!"); scene->erase(itemIndex); return; } @@ -248,12 +249,12 @@ void Polyhedron_demo_shortest_path_plugin::on_actionMakeShortestPaths_triggered( } else { - this->m_messages->warning(tr("A shortest path item for this polyhedron already exists (only one allowed per for now)")); + CGAL::Three::Three::warning(tr("A shortest path item for this polyhedron already exists (only one allowed per for now)")); } } else { - this->m_messages->warning("No polyhedron selected."); + CGAL::Three::Three::warning("No polyhedron selected."); } } diff --git a/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Surface_mesh_approximation_dockwidget.ui b/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Surface_mesh_approximation_dockwidget.ui index 65b1d9a5f1e..8b67236b224 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Surface_mesh_approximation_dockwidget.ui +++ b/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Surface_mesh_approximation_dockwidget.ui @@ -6,8 +6,8 @@ 0 0 - 717 - 356 + 667 + 360 @@ -120,7 +120,7 @@ - true + false Negative value is ignored @@ -135,7 +135,7 @@ 4 - -1.000000000000000 + 0.001000000000000 1.000000000000000 @@ -144,7 +144,7 @@ 0.010000000000000 - -1.000000000000000 + 0.100000000000000 @@ -184,6 +184,13 @@ + + + + + + + @@ -485,5 +492,22 @@ - + + + enable_error_drop + toggled(bool) + error_drop + setEnabled(bool) + + + 127 + 168 + + + 153 + 167 + + + + diff --git a/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Surface_mesh_approximation_plugin.cpp b/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Surface_mesh_approximation_plugin.cpp index b83bf4c9758..ec49ce6c9db 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Surface_mesh_approximation_plugin.cpp +++ b/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Surface_mesh_approximation_plugin.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -243,11 +244,6 @@ public: BOOST_FOREACH(const QColor &c, approx.proxy_colors()) fcolors.push_back(CGAL::Color(c.red(), c.green(), c.blue())); approx.visual_items().planes->load(cvx_hull_points, cvx_hulls, fcolors, std::vector()); - - approx.visual_items().triangles->setVisible(true); - approx.visual_items().polygons->setVisible(true); - approx.visual_items().anchors->setVisible(false); - approx.visual_items().planes->setVisible(false); } public Q_SLOTS: @@ -281,7 +277,7 @@ void Polyhedron_demo_surface_mesh_approximation_plugin::on_buttonSeeding_clicked Scene_surface_mesh_item *sm_item = qobject_cast( scene->item(sm_id)); if (!sm_item) { - mi->information(QString("No surface mesh item selected.")); + CGAL::Three::Three::information(QString("No surface mesh item selected.")); return; } @@ -300,15 +296,16 @@ void Polyhedron_demo_surface_mesh_approximation_plugin::on_buttonSeeding_clicked approx.initialize_seeds(CGAL::parameters::seeding_method( static_cast(ui_widget.comboMethod->currentIndex())) .max_number_of_proxies(ui_widget.nb_proxies->value()) - .min_error_drop(ui_widget.error_drop->value()) + .min_error_drop( + ui_widget.enable_error_drop->isChecked() ? ui_widget.error_drop->value() : -1.0) .number_of_relaxations(ui_widget.nb_relaxations->value())); approx.run(ui_widget.nb_iterations->value()); Patch_id_pmap pidmap(get(CGAL::face_patch_id_t(), *sm_item->face_graph())); approx.output(CGAL::parameters::face_proxy_map(pidmap)); - // TODO: previous items // new group items + // leave the memory management to the scene Scene_group_item *group = new Scene_group_item(tr("Approximation of %1").arg(sm_item->name())); scene->addItem(group); @@ -318,46 +315,17 @@ void Polyhedron_demo_surface_mesh_approximation_plugin::on_buttonSeeding_clicked scene->addItem(seeds_item); scene->changeGroup(seeds_item, group); - Scene_polygon_soup_item *triangles_item = new Scene_polygon_soup_item(); - triangles_item->setName(tr("Triangle soup")); - triangles_item->setColor(Qt::lightGray); - triangles_item->setRenderingMode(FlatPlusEdges); - triangles_item->setVisible(false); - scene->addItem(triangles_item); - scene->changeGroup(triangles_item, group); - - Scene_polylines_item *polygons_item = new Scene_polylines_item(); - polygons_item->setName(tr("Patch polygons")); - polygons_item->setColor(Qt::red); - polygons_item->setVisible(false); - scene->addItem(polygons_item); - scene->changeGroup(polygons_item, group); - - Scene_polylines_item *anchors_item = new Scene_polylines_item(); - anchors_item->setName(tr("Anchors")); - anchors_item->setColor(Qt::blue); - anchors_item->setVisible(false); - scene->addItem(anchors_item); - scene->changeGroup(anchors_item, group); - - Scene_polygon_soup_item *planes_item = new Scene_polygon_soup_item(); - planes_item->setName(tr("Patch planes")); - planes_item->setColor(Qt::yellow); - planes_item->setRenderingMode(FlatPlusEdges); - planes_item->setVisible(false); - scene->addItem(planes_item); - scene->changeGroup(planes_item, group); - approx.visual_items().group = group; approx.visual_items().seeds = seeds_item; - approx.visual_items().triangles = triangles_item; - approx.visual_items().polygons = polygons_item; - approx.visual_items().anchors = anchors_item; - approx.visual_items().planes = planes_item; + approx.visual_items().has_meshing_items = false; + approx.visual_items().triangles = NULL; + approx.visual_items().polygons = NULL; + approx.visual_items().anchors = NULL; + approx.visual_items().planes = NULL; update_seeds_item(approx, pmesh); - mi->information(QString("Done, #proxies = %1. (%2 ms)").arg( + CGAL::Three::Three::information(QString("Done, #proxies = %1. (%2 ms)").arg( approx.number_of_proxies()).arg(time.elapsed())); sm_item->color_vector() = approx.proxy_colors(); sm_item->setItemIsMulticolor(true); @@ -366,14 +334,8 @@ void Polyhedron_demo_surface_mesh_approximation_plugin::on_buttonSeeding_clicked sm_item->invalidateOpenGLBuffers(); scene->itemChanged(scene->item_id(sm_item)); - if (ui_widget.checkAutomatic->isChecked()) { - update_meshing_items(approx, pmesh, - CGAL::parameters::subdivision_ratio(ui_widget.chord_error->value()) - .relative_to_chord(ui_widget.comboRelative->currentIndex() == 1) - .with_dihedral_angle(ui_widget.with_dihedral_angle->isChecked()) - .optimize_anchor_location(ui_widget.if_optimize_anchor_location->isChecked()) - .pca_plane(ui_widget.pca_plane->isChecked())); - } + // default non auto-meshing + ui_widget.checkAutomatic->setChecked(false); scene->setSelectedItem(sm_id); @@ -384,12 +346,12 @@ void Polyhedron_demo_surface_mesh_approximation_plugin::on_buttonFit_clicked() { Scene_surface_mesh_item *sm_item = qobject_cast( scene->item(scene->mainSelectionIndex())); if (!sm_item) { - mi->information(QString("No surface mesh item selected.")); + CGAL::Three::Three::information(QString("No surface mesh item selected.")); return; } SM_wrapper_map::iterator search = m_sm_wrapper_map.find(sm_item); if (search == m_sm_wrapper_map.end() || !search->second->initialized()) { - mi->information(QString("Please initialize seeds first.")); + CGAL::Three::Three::information(QString("Please initialize seeds first.")); return; } SMesh *pmesh = search->first->face_graph(); @@ -402,13 +364,7 @@ void Polyhedron_demo_surface_mesh_approximation_plugin::on_buttonFit_clicked() { approx.output(CGAL::parameters::face_proxy_map(pidmap)); update_seeds_item(approx, pmesh); - mi->information(QString("Fit one iteration, #proxies = %1.").arg(approx.number_of_proxies())); - - sm_item->color_vector() = approx.proxy_colors(); - - sm_item->color_vector() = approx.proxy_colors(); - - sm_item->color_vector() = approx.proxy_colors(); + CGAL::Three::Three::information(QString("Fit one iteration, #proxies = %1.").arg(approx.number_of_proxies())); sm_item->color_vector() = approx.proxy_colors(); sm_item->setItemIsMulticolor(true); @@ -417,6 +373,11 @@ void Polyhedron_demo_surface_mesh_approximation_plugin::on_buttonFit_clicked() { scene->itemChanged(scene->item_id(sm_item)); if (ui_widget.checkAutomatic->isChecked()) { + if (!approx.visual_items().has_meshing_items) { + CGAL::Three::Three::information(QString("Please mesh before checking auto meshing.")); + QApplication::restoreOverrideCursor(); + return; + } update_meshing_items(approx, pmesh, CGAL::parameters::subdivision_ratio(ui_widget.chord_error->value()) .relative_to_chord(ui_widget.comboRelative->currentIndex() == 1) @@ -432,12 +393,12 @@ void Polyhedron_demo_surface_mesh_approximation_plugin::on_buttonAdd_clicked() { Scene_surface_mesh_item *sm_item = qobject_cast( scene->item(scene->mainSelectionIndex())); if (!sm_item) { - mi->information(QString("No surface mesh item selected.")); + CGAL::Three::Three::information(QString("No surface mesh item selected.")); return; } SM_wrapper_map::iterator search = m_sm_wrapper_map.find(sm_item); if (search == m_sm_wrapper_map.end() || !search->second->initialized()) { - mi->information(QString("Please initialize seeds first.")); + CGAL::Three::Three::information(QString("Please initialize seeds first.")); return; } SMesh *pmesh = search->first->face_graph(); @@ -446,22 +407,16 @@ void Polyhedron_demo_surface_mesh_approximation_plugin::on_buttonAdd_clicked() { QApplication::setOverrideCursor(Qt::WaitCursor); if (approx.add_one_proxy() == 0) { - mi->information(QString("No proxy added, #proxies = %1.").arg(approx.number_of_proxies())); + CGAL::Three::Three::information(QString("No proxy added, #proxies = %1.").arg(approx.number_of_proxies())); QApplication::restoreOverrideCursor(); return; } - mi->information(QString("One proxy added, #proxies = %1.").arg(approx.number_of_proxies())); + CGAL::Three::Three::information(QString("One proxy added, #proxies = %1.").arg(approx.number_of_proxies())); Patch_id_pmap pidmap(get(CGAL::face_patch_id_t(), *pmesh)); approx.output(CGAL::parameters::face_proxy_map(pidmap)); update_seeds_item(approx, pmesh); - sm_item->color_vector() = approx.proxy_colors(); - - sm_item->color_vector() = approx.proxy_colors(); - - sm_item->color_vector() = approx.proxy_colors(); - sm_item->color_vector() = approx.proxy_colors(); sm_item->setItemIsMulticolor(true); sm_item->computeItemColorVectorAutomatically(false); @@ -469,6 +424,11 @@ void Polyhedron_demo_surface_mesh_approximation_plugin::on_buttonAdd_clicked() { scene->itemChanged(scene->item_id(sm_item)); if (ui_widget.checkAutomatic->isChecked()) { + if (!approx.visual_items().has_meshing_items) { + CGAL::Three::Three::information(QString("Please mesh before checking auto meshing.")); + QApplication::restoreOverrideCursor(); + return; + } update_meshing_items(approx, pmesh, CGAL::parameters::subdivision_ratio(ui_widget.chord_error->value()) .relative_to_chord(ui_widget.comboRelative->currentIndex() == 1) @@ -484,12 +444,12 @@ void Polyhedron_demo_surface_mesh_approximation_plugin::on_buttonTeleport_clicke Scene_surface_mesh_item *sm_item = qobject_cast( scene->item(scene->mainSelectionIndex())); if (!sm_item) { - mi->information(QString("No surface mesh item selected.")); + CGAL::Three::Three::information(QString("No surface mesh item selected.")); return; } SM_wrapper_map::iterator search = m_sm_wrapper_map.find(sm_item); if (search == m_sm_wrapper_map.end() || !search->second->initialized()) { - mi->information(QString("Please initialize seeds first.")); + CGAL::Three::Three::information(QString("Please initialize seeds first.")); return; } SMesh *pmesh = search->first->face_graph(); @@ -498,7 +458,7 @@ void Polyhedron_demo_surface_mesh_approximation_plugin::on_buttonTeleport_clicke QApplication::setOverrideCursor(Qt::WaitCursor); if (approx.teleport_one_proxy() == 0) { - mi->information(QString("No proxy teleported, #proxies = %1.").arg(approx.number_of_proxies())); + CGAL::Three::Three::information(QString("No proxy teleported, #proxies = %1.").arg(approx.number_of_proxies())); QApplication::restoreOverrideCursor(); return; } @@ -506,13 +466,7 @@ void Polyhedron_demo_surface_mesh_approximation_plugin::on_buttonTeleport_clicke approx.output(CGAL::parameters::face_proxy_map(pidmap)); update_seeds_item(approx, pmesh); - mi->information(QString("One proxy teleported, #proxies = %1.").arg(approx.number_of_proxies())); - - sm_item->color_vector() = approx.proxy_colors(); - - sm_item->color_vector() = approx.proxy_colors(); - - sm_item->color_vector() = approx.proxy_colors(); + CGAL::Three::Three::information(QString("One proxy teleported, #proxies = %1.").arg(approx.number_of_proxies())); sm_item->color_vector() = approx.proxy_colors(); sm_item->setItemIsMulticolor(true); @@ -521,6 +475,11 @@ void Polyhedron_demo_surface_mesh_approximation_plugin::on_buttonTeleport_clicke scene->itemChanged(scene->item_id(sm_item)); if (ui_widget.checkAutomatic->isChecked()) { + if (!approx.visual_items().has_meshing_items) { + CGAL::Three::Three::information(QString("Please mesh before checking auto meshing.")); + QApplication::restoreOverrideCursor(); + return; + } update_meshing_items(approx, pmesh, CGAL::parameters::subdivision_ratio(ui_widget.chord_error->value()) .relative_to_chord(ui_widget.comboRelative->currentIndex() == 1) @@ -536,12 +495,12 @@ void Polyhedron_demo_surface_mesh_approximation_plugin::on_buttonSplit_clicked() Scene_surface_mesh_item *sm_item = qobject_cast( scene->item(scene->mainSelectionIndex())); if (!sm_item) { - mi->information(QString("No surface mesh item selected.")); + CGAL::Three::Three::information(QString("No surface mesh item selected.")); return; } SM_wrapper_map::iterator search = m_sm_wrapper_map.find(sm_item); if (search == m_sm_wrapper_map.end() || !search->second->initialized()) { - mi->information(QString("Please initialize seeds first.")); + CGAL::Three::Three::information(QString("Please initialize seeds first.")); return; } SMesh *pmesh = search->first->face_graph(); @@ -552,22 +511,16 @@ void Polyhedron_demo_surface_mesh_approximation_plugin::on_buttonSplit_clicked() if (!approx.split(ui_widget.split_proxy_idx->value(), ui_widget.split_nb_sections->value(), ui_widget.split_nb_relaxations->value())) { - mi->information(QString("No proxy splitted, #proxies = %1.").arg(approx.number_of_proxies())); + CGAL::Three::Three::information(QString("No proxy splitted, #proxies = %1.").arg(approx.number_of_proxies())); QApplication::restoreOverrideCursor(); return; } - mi->information(QString("One proxy splitted, #proxies = %1.").arg(approx.number_of_proxies())); + CGAL::Three::Three::information(QString("One proxy splitted, #proxies = %1.").arg(approx.number_of_proxies())); Patch_id_pmap pidmap(get(CGAL::face_patch_id_t(), *pmesh)); approx.output(CGAL::parameters::face_proxy_map(pidmap)); update_seeds_item(approx, pmesh); - sm_item->color_vector() = approx.proxy_colors(); - - sm_item->color_vector() = approx.proxy_colors(); - - sm_item->color_vector() = approx.proxy_colors(); - sm_item->color_vector() = approx.proxy_colors(); sm_item->setItemIsMulticolor(true); sm_item->computeItemColorVectorAutomatically(false); @@ -575,6 +528,11 @@ void Polyhedron_demo_surface_mesh_approximation_plugin::on_buttonSplit_clicked() scene->itemChanged(scene->item_id(sm_item)); if (ui_widget.checkAutomatic->isChecked()) { + if (!approx.visual_items().has_meshing_items) { + CGAL::Three::Three::information(QString("Please mesh before checking auto meshing.")); + QApplication::restoreOverrideCursor(); + return; + } update_meshing_items(approx, pmesh, CGAL::parameters::subdivision_ratio(ui_widget.chord_error->value()) .relative_to_chord(ui_widget.comboRelative->currentIndex() == 1) @@ -590,12 +548,12 @@ void Polyhedron_demo_surface_mesh_approximation_plugin::on_buttonMeshing_clicked Scene_surface_mesh_item *sm_item = qobject_cast( scene->item(scene->mainSelectionIndex())); if (!sm_item) { - mi->information(QString("No surface mesh item selected.")); + CGAL::Three::Three::information(QString("No surface mesh item selected.")); return; } SM_wrapper_map::iterator search = m_sm_wrapper_map.find(sm_item); if (search == m_sm_wrapper_map.end() || !search->second->initialized()) { - mi->information(QString("Please initialize seeds first.")); + CGAL::Three::Three::information(QString("Please initialize seeds first.")); return; } SMesh *pmesh = search->first->face_graph(); @@ -603,6 +561,44 @@ void Polyhedron_demo_surface_mesh_approximation_plugin::on_buttonMeshing_clicked QApplication::setOverrideCursor(Qt::WaitCursor); + // and meshing items to group + CGAL::Three::Scene_group_item *group = approx.visual_items().group; + Scene_polygon_soup_item *triangles_item = new Scene_polygon_soup_item(); + triangles_item->setName(tr("Triangle soup")); + triangles_item->setColor(Qt::lightGray); + triangles_item->setRenderingMode(FlatPlusEdges); + triangles_item->setVisible(true); + scene->addItem(triangles_item); + scene->changeGroup(triangles_item, group); + + Scene_polylines_item *polygons_item = new Scene_polylines_item(); + polygons_item->setName(tr("Patch polygons")); + polygons_item->setColor(Qt::red); + polygons_item->setVisible(true); + scene->addItem(polygons_item); + scene->changeGroup(polygons_item, group); + + Scene_polylines_item *anchors_item = new Scene_polylines_item(); + anchors_item->setName(tr("Anchors")); + anchors_item->setColor(Qt::blue); + anchors_item->setVisible(true); + scene->addItem(anchors_item); + scene->changeGroup(anchors_item, group); + + Scene_polygon_soup_item *planes_item = new Scene_polygon_soup_item(); + planes_item->setName(tr("Patch planes")); + planes_item->setColor(Qt::yellow); + planes_item->setRenderingMode(FlatPlusEdges); + planes_item->setVisible(true); + scene->addItem(planes_item); + scene->changeGroup(planes_item, group); + + approx.visual_items().has_meshing_items = true; + approx.visual_items().triangles = triangles_item; + approx.visual_items().polygons = polygons_item; + approx.visual_items().anchors = anchors_item; + approx.visual_items().planes = planes_item; + update_meshing_items(approx, pmesh, CGAL::parameters::subdivision_ratio(ui_widget.chord_error->value()) .relative_to_chord(ui_widget.comboRelative->currentIndex() == 1) @@ -612,7 +608,7 @@ void Polyhedron_demo_surface_mesh_approximation_plugin::on_buttonMeshing_clicked sm_item->setVisible(false); - mi->information(QString("Meshing done.")); + CGAL::Three::Three::information(QString("Meshing done.")); QApplication::restoreOverrideCursor(); } @@ -621,7 +617,7 @@ void Polyhedron_demo_surface_mesh_approximation_plugin::on_comboMetric_currentIn Scene_surface_mesh_item *sm_item = qobject_cast( scene->item(scene->mainSelectionIndex())); if (!sm_item) { - mi->information(QString("No surface mesh item selected.")); + CGAL::Three::Three::information(QString("No surface mesh item selected.")); return; } SM_wrapper_map::iterator search = m_sm_wrapper_map.find(sm_item); diff --git a/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/VSA_wrapper.h b/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/VSA_wrapper.h index 4da8af95e26..96516f5cefb 100644 --- a/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/VSA_wrapper.h +++ b/Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/VSA_wrapper.h @@ -111,6 +111,7 @@ public: Visual_items() : group(NULL), seeds(NULL), + has_meshing_items(false), triangles(NULL), polygons(NULL), anchors(NULL), @@ -118,6 +119,7 @@ public: CGAL::Three::Scene_group_item *group; Scene_polylines_item *seeds; + bool has_meshing_items; Scene_polygon_soup_item *triangles; Scene_polylines_item *polygons; Scene_polylines_item *anchors; diff --git a/Polyhedron/demo/Polyhedron/Polyhedron_3.qrc b/Polyhedron/demo/Polyhedron/Polyhedron_3.qrc index ddfef37241e..bca90692a1f 100644 --- a/Polyhedron/demo/Polyhedron/Polyhedron_3.qrc +++ b/Polyhedron/demo/Polyhedron/Polyhedron_3.qrc @@ -34,23 +34,23 @@ resources/about.html - resources/shader_with_light.v - resources/shader_with_light.f - resources/shader_without_light.f - resources/shader_without_light.v - resources/shader_with_texture.f - resources/shader_with_textured_edges.f - resources/shader_with_textured_edges.v - resources/shader_with_texture.v - resources/shader_instanced.v - resources/shader_no_light_no_selection.f - resources/shader_c3t3_spheres.v - resources/shader_c3t3_edges.v - resources/shader_c3t3_edges.f - resources/shader_c3t3.v - resources/shader_c3t3.f - resources/shader_plane_two_faces.f - resources/shader_spheres.v + resources/shader_with_light.vert + resources/shader_with_light.frag + resources/shader_without_light.frag + resources/shader_without_light.vert + resources/shader_with_texture.frag + resources/shader_with_textured_edges.frag + resources/shader_with_textured_edges.vert + resources/shader_with_texture.vert + resources/shader_instanced.vert + resources/shader_no_light_no_selection.frag + resources/shader_c3t3_spheres.vert + resources/shader_c3t3_edges.vert + resources/shader_c3t3_edges.frag + resources/shader_c3t3.vert + resources/shader_c3t3.frag + resources/shader_plane_two_faces.frag + resources/shader_spheres.vert resources/general_collapse.png resources/add_facet1.png resources/add_facet2.png @@ -58,7 +58,7 @@ resources/euler_facet.png resources/euler_vertex.png javascript/lib.js - resources/shader_flat.f + resources/shader_flat.frag resources/hexahedron.png resources/icosphere.png resources/tetrahedron.png @@ -67,37 +67,37 @@ resources/prism-open.png resources/pyramid.png resources/pyramid-open.png - resources/no_interpolation_shader.f - resources/no_interpolation_shader.g - resources/no_interpolation_shader.v - resources/shader_flat.g - resources/shader_flat.v - resources/shader_old_flat.f - resources/solid_wireframe_shader.v - resources/solid_wireframe_shader.f - resources/solid_wireframe_shader.g - resources/compatibility_shaders/shader_c3t3_edges.f - resources/compatibility_shaders/shader_c3t3_edges.v - resources/compatibility_shaders/shader_c3t3_spheres.v - resources/compatibility_shaders/shader_c3t3.f - resources/compatibility_shaders/shader_c3t3.v - resources/compatibility_shaders/shader_instanced.v - resources/compatibility_shaders/shader_no_light_no_selection.f - resources/compatibility_shaders/shader_old_flat.f - resources/compatibility_shaders/shader_plane_two_faces.f - resources/compatibility_shaders/shader_spheres.v - resources/compatibility_shaders/shader_with_light.f - resources/compatibility_shaders/shader_with_light.v - resources/compatibility_shaders/shader_with_texture.f - resources/compatibility_shaders/shader_with_texture.v - resources/compatibility_shaders/shader_with_textured_edges.f - resources/compatibility_shaders/shader_with_textured_edges.v - resources/compatibility_shaders/shader_without_light.f - resources/compatibility_shaders/shader_without_light.v - resources/heat_intensity_shader.f - resources/heat_intensity_shader.v - resources/compatibility_shaders/heat_intensity_shader.f - resources/compatibility_shaders/heat_intensity_shader.v + resources/no_interpolation_shader.frag + resources/no_interpolation_shader.geom + resources/no_interpolation_shader.vert + resources/shader_flat.geom + resources/shader_flat.vert + resources/shader_old_flat.frag + resources/solid_wireframe_shader.vert + resources/solid_wireframe_shader.frag + resources/solid_wireframe_shader.geom + resources/compatibility_shaders/shader_c3t3_edges.frag + resources/compatibility_shaders/shader_c3t3_edges.vert + resources/compatibility_shaders/shader_c3t3_spheres.vert + resources/compatibility_shaders/shader_c3t3.frag + resources/compatibility_shaders/shader_c3t3.vert + resources/compatibility_shaders/shader_instanced.vert + resources/compatibility_shaders/shader_no_light_no_selection.frag + resources/compatibility_shaders/shader_old_flat.frag + resources/compatibility_shaders/shader_plane_two_faces.frag + resources/compatibility_shaders/shader_spheres.vert + resources/compatibility_shaders/shader_with_light.frag + resources/compatibility_shaders/shader_with_light.vert + resources/compatibility_shaders/shader_with_texture.frag + resources/compatibility_shaders/shader_with_texture.vert + resources/compatibility_shaders/shader_with_textured_edges.frag + resources/compatibility_shaders/shader_with_textured_edges.vert + resources/compatibility_shaders/shader_without_light.frag + resources/compatibility_shaders/shader_without_light.vert + resources/heat_intensity_shader.frag + resources/heat_intensity_shader.vert + resources/compatibility_shaders/heat_intensity_shader.frag + resources/compatibility_shaders/heat_intensity_shader.vert resources/rotate_around_cursor.png diff --git a/Polyhedron/demo/Polyhedron/Preferences.ui b/Polyhedron/demo/Polyhedron/Preferences.ui index 596e8cf2513..34613871e8d 100644 --- a/Polyhedron/demo/Polyhedron/Preferences.ui +++ b/Polyhedron/demo/Polyhedron/Preferences.ui @@ -60,7 +60,7 @@ 0 0 278 - 432 + 499 @@ -118,6 +118,9 @@ Transparency Pass Number: + + 4 + 4 @@ -311,7 +314,7 @@ - Tick plugins you don't want to load at start up + Tick plugins you want to load at start up diff --git a/Polyhedron/demo/Polyhedron/Scene.cpp b/Polyhedron/demo/Polyhedron/Scene.cpp index 03377072591..38956320395 100644 --- a/Polyhedron/demo/Polyhedron/Scene.cpp +++ b/Polyhedron/demo/Polyhedron/Scene.cpp @@ -181,9 +181,9 @@ Scene::erase(Scene::Item_id index) item->deleteLater(); selected_item = -1; //re-creates the Scene_view - Q_FOREACH(Scene_item* item, m_entries) + Q_FOREACH(Item_id id, children) { - organize_items(item, invisibleRootItem(), 0); + organize_items(this->item(id), invisibleRootItem(), 0); } QStandardItemModel::beginResetModel(); Q_EMIT updated(); @@ -233,9 +233,9 @@ Scene::erase(QList indices) continue; if(item->parentGroup()) item->parentGroup()->removeChild(item); - children.removeAll(removed_item); - indexErased(removed_item); - m_entries.removeAll(item); + children.removeAll(removed_item); + indexErased(removed_item); + m_entries.removeAll(item); Q_EMIT itemAboutToBeDestroyed(item); item->aboutToBeDestroyed(); @@ -244,9 +244,9 @@ Scene::erase(QList indices) clear(); index_map.clear(); selected_item = -1; - Q_FOREACH(Scene_item* item, m_entries) + Q_FOREACH(Item_id id, children) { - organize_items(item, invisibleRootItem(), 0); + organize_items(item(id), invisibleRootItem(), 0); } QStandardItemModel::beginResetModel(); Q_EMIT updated(); @@ -276,12 +276,13 @@ void Scene::remove_item_from_groups(Scene_item* item) } Scene::~Scene() { - Q_FOREACH(CGAL::Three::Scene_item* item_ptr, m_entries) - { - item_ptr->deleteLater(); - } - m_entries.clear(); - + vao->destroy(); + delete vao; + Q_FOREACH(CGAL::Three::Scene_item* item_ptr, m_entries) + { + item_ptr->deleteLater(); + } + m_entries.clear(); } CGAL::Three::Scene_item* @@ -683,6 +684,34 @@ Scene::draw_aux(bool with_names, CGAL::Three::Viewer_interface* viewer) transparent_items.push_back(id); } renderScene(children, viewer, picked_item_IDs, with_names, -1, false, NULL); + if(with_names) + { + //here we get the selected point, before erasing the depth buffer. We store it + //in a dynamic property as a QList. If there is some alpha, the + //depth buffer is altered, and the picking will return true even when it is + // performed in the background, when it should return false. To avoid that, + // we distinguish the case were there is no alpha, to let the viewer + //perform it, and the case where the pixel is not found. In the first case, + //we erase the property, in the latter we return an empty list. + //According ot that, in the viewer, either we perform the picking, either we do nothing. + if(has_alpha()) { + bool found = false; + CGAL::qglviewer::Vec point = viewer->camera()->pointUnderPixel(picked_pixel, found) - viewer->offset(); + if(found){ + QList picked_point; + picked_point <setProperty("picked_point", picked_point); + } + else{ + viewer->setProperty("picked_point", QList()); + } + } + else { + viewer->setProperty("picked_point", {}); + } + } if(!with_names && has_alpha()) { std::vector fbos; @@ -1188,8 +1217,9 @@ void Scene::moveRowUp() } } } - if(!to_select.isEmpty()) + if(!to_select.isEmpty()){ selectionChanged(to_select); + } } void Scene::moveRowDown() { @@ -1544,7 +1574,6 @@ void Scene::redraw_model() index_map.clear(); //fills the model Q_FOREACH(Item_id id, children) - { organize_items(m_entries[id], invisibleRootItem(), 0); } diff --git a/Polyhedron/demo/Polyhedron/Scene_c3t3_item.cpp b/Polyhedron/demo/Polyhedron/Scene_c3t3_item.cpp index 8abcf815820..0e9eb038efc 100644 --- a/Polyhedron/demo/Polyhedron/Scene_c3t3_item.cpp +++ b/Polyhedron/demo/Polyhedron/Scene_c3t3_item.cpp @@ -1304,7 +1304,7 @@ QMenu* Scene_c3t3_item::contextMenu() QMenu *container = new QMenu(tr("Alpha value")); container->menuAction()->setProperty("is_groupable", true); QWidgetAction *sliderAction = new QWidgetAction(0); - sliderAction->setDefaultWidget(d->alphaSlider); + sliderAction->setDefaultWidget(alphaSlider()); connect(d->alphaSlider, &QSlider::valueChanged, [this]() { diff --git a/Polyhedron/demo/Polyhedron/Scene_image_item.cpp b/Polyhedron/demo/Polyhedron/Scene_image_item.cpp index c61f608d2f5..8ff062cb5cb 100644 --- a/Polyhedron/demo/Polyhedron/Scene_image_item.cpp +++ b/Polyhedron/demo/Polyhedron/Scene_image_item.cpp @@ -592,16 +592,16 @@ void Scene_image_item_priv::compile_shaders() } else { - if(!rendering_program.addShaderFromSourceFile(QOpenGLShader::Vertex,":/cgal/Polyhedron_3/resources/no_interpolation_shader.v")) + if(!rendering_program.addShaderFromSourceFile(QOpenGLShader::Vertex,":/cgal/Polyhedron_3/resources/no_interpolation_shader.vert")) { std::cerr<<"adding vertex shader FAILED"<normal(*it); - Point_set_3::Point q = p + length * n; + Kernel::FT normalizer = 1.0/CGAL::sqrt(n.squared_length()); + Point_set_3::Point q = p + length * n * normalizer; positions_lines[i * size_p + 3] = q.x() + offset.x; positions_lines[i * size_p + 4] = q.y() + offset.y; positions_lines[i * size_p + 5] = q.z() + offset.z; @@ -432,7 +433,7 @@ void Scene_points_with_normal_item_priv::compute_normals_and_vertices() const // we can't afford computing real average spacing just for display, 0.5% of bbox will do average_spacing = 0.005 * item->diagonalBbox(); normal_length = (std::min)(average_spacing, std::sqrt(region_of_interest.squared_radius() / 1000.)); - length_factor = 5.0/100*normal_Slider->value(); + length_factor = 10.0/100*normal_Slider->value(); } else { diff --git a/Polyhedron/demo/Polyhedron/Scene_polyhedron_item_decorator.cpp b/Polyhedron/demo/Polyhedron/Scene_polyhedron_item_decorator.cpp index b756c37ea46..aec0f873302 100644 --- a/Polyhedron/demo/Polyhedron/Scene_polyhedron_item_decorator.cpp +++ b/Polyhedron/demo/Polyhedron/Scene_polyhedron_item_decorator.cpp @@ -70,18 +70,12 @@ Scene_polyhedron_item_decorator::select(double orig_x, double dir_y, double dir_z) { - Scene_item::select(orig_x, - orig_y, - orig_z, - dir_x, - dir_y, - dir_z); poly_item->select(orig_x, - orig_y, - orig_z, - dir_x, - dir_y, - dir_z); + orig_y, + orig_z, + dir_x, + dir_y, + dir_z); } Scene_face_graph_item* Scene_polyhedron_item_decorator::polyhedron_item() const { diff --git a/Polyhedron/demo/Polyhedron/Scene_polyhedron_selection_item.cpp b/Polyhedron/demo/Polyhedron/Scene_polyhedron_selection_item.cpp index 15f64e2377e..0216c02db64 100644 --- a/Polyhedron/demo/Polyhedron/Scene_polyhedron_selection_item.cpp +++ b/Polyhedron/demo/Polyhedron/Scene_polyhedron_selection_item.cpp @@ -1112,6 +1112,7 @@ bool Scene_polyhedron_selection_item::treat_selection(const std::set(1)); d->tempInstructions("Face split.", "Select a facet (1/3)."); + polyhedron_item()->resetColors(); polyhedron_item()->invalidateOpenGLBuffers(); } } @@ -1337,6 +1338,7 @@ bool Scene_polyhedron_selection_item:: treat_selection(const std::setresetColors(); invalidateOpenGLBuffers(); polyhedron_item()->invalidateOpenGLBuffers(); d->tempInstructions("Face and vertex added.", @@ -1387,6 +1389,7 @@ bool Scene_polyhedron_selection_item:: treat_selection(const std::setresetColors(); invalidateOpenGLBuffers(); polyhedron_item()->invalidateOpenGLBuffers(); d->tempInstructions("Face added.", @@ -1485,6 +1488,7 @@ bool Scene_polyhedron_selection_item::treat_selection(const std::set(0)); + poly_item->resetColors(); poly_item->invalidateOpenGLBuffers(); d->tempInstructions("Vertex splitted.", "Select the vertex you want splitted. (1/3)"); } @@ -1540,6 +1544,7 @@ bool Scene_polyhedron_selection_item::treat_selection(const std::setresetColors(); poly_item->invalidateOpenGLBuffers(); } diff --git a/Polyhedron/demo/Polyhedron/Scene_polylines_item.cpp b/Polyhedron/demo/Polyhedron/Scene_polylines_item.cpp index 801205d5653..fcc1e85634b 100644 --- a/Polyhedron/demo/Polyhedron/Scene_polylines_item.cpp +++ b/Polyhedron/demo/Polyhedron/Scene_polylines_item.cpp @@ -110,6 +110,7 @@ Scene_polylines_item_private::computeElements() const QApplication::setOverrideCursor(Qt::WaitCursor); positions_lines.resize(0); double mean = 0; + bool all_equal=true; //Fills the VBO with the lines for(std::list >::const_iterator it = item->polylines.begin(); it != item->polylines.end(); @@ -122,6 +123,8 @@ Scene_polylines_item_private::computeElements() const { const Point_3& a = (*it)[i]; const Point_3& b = (*it)[i+1]; + if(a!=b) + all_equal = false; if(!computed_stats) { ++nb_edges; @@ -148,6 +151,8 @@ Scene_polylines_item_private::computeElements() const } } + if(all_equal) + item->setPointsMode(); if(!computed_stats) mean_length = mean/double(nb_edges); computed_stats = true; @@ -446,7 +451,9 @@ Scene_polylines_item::drawPoints(CGAL::Three::Viewer_interface* viewer) const { d->computeElements(); d->initializeBuffers(viewer); } - + GLfloat point_size; + viewer->glGetFloatv(GL_POINT_SIZE, &point_size); + viewer->setGlPointSize(GLfloat(5)); vaos[Scene_polylines_item_private::Edges]->bind(); attribBuffers(viewer, PROGRAM_NO_SELECTION); QOpenGLShaderProgram *program = getShaderProgram(PROGRAM_NO_SELECTION); @@ -457,6 +464,7 @@ Scene_polylines_item::drawPoints(CGAL::Three::Viewer_interface* viewer) const { // Clean-up vaos[Scene_polylines_item_private::Edges]->release(); program->release(); + viewer->setGlPointSize(point_size); } if(d->draw_extremities) { diff --git a/Polyhedron/demo/Polyhedron/Scene_surface_mesh_item.cpp b/Polyhedron/demo/Polyhedron/Scene_surface_mesh_item.cpp index 48589cac4b3..bc44f100eff 100644 --- a/Polyhedron/demo/Polyhedron/Scene_surface_mesh_item.cpp +++ b/Polyhedron/demo/Polyhedron/Scene_surface_mesh_item.cpp @@ -537,7 +537,12 @@ void Scene_surface_mesh_item_priv::compute_elements(Scene_item_rendering_helper: Point p = positions[source(hd, *smesh_)]; EPICK::Vector_3 n = fnormals[fd]; CGAL::Color *c; - if(has_fcolors) + if(has_fpatch_id) + { + QColor color = item->color_vector()[fpatch_id_map[fd] - min_patch_id]; + c = new CGAL::Color(color.red(),color.green(),color.blue()); + } + else if(has_fcolors) c= &fcolors[fd]; else c = 0; @@ -572,6 +577,8 @@ void Scene_surface_mesh_item_priv::compute_elements(Scene_item_rendering_helper: ,fnormals[fd] , c , name); + if(has_fpatch_id) + delete c; } else if(is_convex) { @@ -855,7 +862,12 @@ void Scene_surface_mesh_item_priv::triangulate_convex_facet(face_descriptor fd, if(!index) { CGAL::Color* color; - if(has_fcolors) + if(has_fpatch_id) + { + QColor c = item->color_vector()[fpatch_id_map[fd] - min_patch_id]; + color = new CGAL::Color(c.red(),c.green(),c.blue()); + } + else if(has_fcolors) color = &(*fcolors)[fd]; else color = 0; @@ -872,6 +884,8 @@ void Scene_surface_mesh_item_priv::triangulate_convex_facet(face_descriptor fd, (*fnormals)[fd], color, name); + if(has_fpatch_id) + delete color; } else if(name.testFlag(Scene_item_rendering_helper::GEOMETRY)) { @@ -895,11 +909,10 @@ Scene_surface_mesh_item_priv::triangulate_facet(face_descriptor fd, if(normal == CGAL::NULL_VECTOR) { boost::graph_traits::halfedge_descriptor start = prev(halfedge(fd, *smesh_), *smesh_); - boost::graph_traits::halfedge_descriptor next_; + boost::graph_traits::halfedge_descriptor hd = halfedge(fd, *smesh_); + boost::graph_traits::halfedge_descriptor next_=next(hd, *smesh_); do { - boost::graph_traits::halfedge_descriptor hd = halfedge(fd, *smesh_); - next_ =next(hd, *smesh_); const Point_3& pa = smesh_->point(target(hd, *smesh_)); const Point_3& pb = smesh_->point(target(next_, *smesh_)); const Point_3& pc = smesh_->point(target(prev(hd, *smesh_), *smesh_)); @@ -908,6 +921,7 @@ Scene_surface_mesh_item_priv::triangulate_facet(face_descriptor fd, normal = CGAL::cross_product(pb-pa, pc -pa); break; } + next_ =next(next_, *smesh_); }while(next_ != start); if (normal == CGAL::NULL_VECTOR) // No normal could be computed, return @@ -940,7 +954,12 @@ Scene_surface_mesh_item_priv::triangulate_facet(face_descriptor fd, if(!index) { CGAL::Color* color; - if(has_fcolors) + if(has_fpatch_id) + { + QColor c= item->color_vector()[fpatch_id_map[fd] - min_patch_id]; + color = new CGAL::Color(c.red(),c.green(),c.blue()); + } + else if(has_fcolors) color = &(*fcolors)[fd]; else color = 0; @@ -958,6 +977,8 @@ Scene_surface_mesh_item_priv::triangulate_facet(face_descriptor fd, (*fnormals)[fd], color, name); + if(has_fpatch_id) + delete color; } //adds the indices to the appropriate vector else @@ -1230,6 +1251,7 @@ void Scene_surface_mesh_item::invalidate(Gl_data_names name) Q_EMIT item_is_about_to_be_changed(); if(name.testFlag(GEOMETRY)) { + is_bbox_computed = false; delete_aabb_tree(this); d->smesh_->collect_garbage(); d->invalidate_stats(); diff --git a/Polyhedron/demo/Polyhedron/Three.cpp b/Polyhedron/demo/Polyhedron/Three.cpp index b29abaa2e6e..07feeb0b7ac 100644 --- a/Polyhedron/demo/Polyhedron/Three.cpp +++ b/Polyhedron/demo/Polyhedron/Three.cpp @@ -3,6 +3,8 @@ #include #include #include +#include "Messages_interface.h" + using namespace CGAL::Three; QMainWindow* Three::s_mainwindow = NULL; @@ -30,10 +32,6 @@ QObject* Three::connectableScene() return s_connectable_scene; } -Three* Three::messages() -{ - return s_three; -} Three::Three() { @@ -136,6 +134,18 @@ void Three::autoConnectActions(Polyhedron_demo_plugin_interface *plugin) } // end foreach action of actions() } +void Three::information(QString s) +{ + qobject_cast(mainWindow())->message_information(s); +} +void Three::warning(QString s) +{ + qobject_cast(mainWindow())->message_warning(s); +} +void Three::error(QString s) +{ + qobject_cast(mainWindow())->message_error(s); +} RenderingMode Three::defaultSurfaceMeshRenderingMode() { return s_defaultSMRM; diff --git a/Polyhedron/demo/Polyhedron/Viewer.cpp b/Polyhedron/demo/Polyhedron/Viewer.cpp index df0cfd8fe5f..fcd28eb6819 100644 --- a/Polyhedron/demo/Polyhedron/Viewer.cpp +++ b/Polyhedron/demo/Polyhedron/Viewer.cpp @@ -331,7 +331,14 @@ Viewer::~Viewer() .arg(d->specular.z())); viewer_settings.setValue("spec_power", d->spec_power); + if(d->_recentFunctions) + delete d->_recentFunctions; + if(d->painter) + delete d->painter; + if(d->textRenderer) + d->textRenderer->deleteLater(); delete d; + } void Viewer::setScene(CGAL::Three::Scene_draw_interface* scene) @@ -708,12 +715,27 @@ void Viewer::drawWithNames() void Viewer::postSelection(const QPoint& pixel) { Q_EMIT selected(this->selectedName()); - bool found = false; - CGAL::qglviewer::Vec point = camera()->pointUnderPixel(pixel, found) - offset(); + CGAL::qglviewer::Vec point; + bool found = true; + if(property("picked_point").isValid()) { + if(!property("picked_point").toList().isEmpty()) + { + QList picked_point = property("picked_point").toList(); + point = CGAL::qglviewer::Vec (picked_point[0].toDouble(), + picked_point[1].toDouble(), + picked_point[2].toDouble()); + } + else{ + found = false; + } + } + else{ + point = camera()->pointUnderPixel(pixel, found) - offset(); + } if(found) { Q_EMIT selectedPoint(point.x, - point.y, - point.z); + point.y, + point.z); CGAL::qglviewer::Vec dir; CGAL::qglviewer::Vec orig; if(d->projection_is_ortho) @@ -725,8 +747,10 @@ void Viewer::postSelection(const QPoint& pixel) orig = camera()->position() - offset(); dir = point - orig; } + this->setProperty("performing_selection", true); Q_EMIT selectionRay(orig.x, orig.y, orig.z, - dir.x, dir.y, dir.z); + dir.x, dir.y, dir.z); + this->setProperty("performing_selection", false); } } bool CGAL::Three::Viewer_interface::readFrame(QString s, CGAL::qglviewer::Frame& frame) @@ -990,6 +1014,7 @@ void Viewer::drawVisualHints() if (d->_displayMessage) d->textRenderer->removeText(message_text); + delete message_text; } QOpenGLShaderProgram* Viewer::declare_program(int name, @@ -1018,16 +1043,16 @@ QOpenGLShaderProgram* Viewer::declare_program(int name, } if(isOpenGL_4_3()) { - if(strcmp(f_shader,":/cgal/Polyhedron_3/resources/shader_flat.f" ) == 0) + if(strcmp(f_shader,":/cgal/Polyhedron_3/resources/shader_flat.frag" ) == 0) { - if(!program->addShaderFromSourceFile(QOpenGLShader::Geometry,":/cgal/Polyhedron_3/resources/shader_flat.g" )) + if(!program->addShaderFromSourceFile(QOpenGLShader::Geometry,":/cgal/Polyhedron_3/resources/shader_flat.geom" )) { std::cerr<<"adding geometry shader FAILED"<addShaderFromSourceFile(QOpenGLShader::Geometry,":/cgal/Polyhedron_3/resources/solid_wireframe_shader.g" )) + if(!program->addShaderFromSourceFile(QOpenGLShader::Geometry,":/cgal/Polyhedron_3/resources/solid_wireframe_shader.geom" )) { std::cerr<<"adding geometry shader FAILED"<setProperty("hasLight", true); program->setProperty("hasNormals", true); program->setProperty("hasCutPlane", true); @@ -1058,18 +1083,18 @@ QOpenGLShaderProgram* Viewer::getShaderProgram(int name) const case PROGRAM_C3T3_EDGES: { QOpenGLShaderProgram* program = isOpenGL_4_3() - ? declare_program(name, ":/cgal/Polyhedron_3/resources/shader_c3t3_edges.v" , ":/cgal/Polyhedron_3/resources/shader_c3t3_edges.f") - : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_c3t3_edges.v" , - ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_c3t3_edges.f"); + ? declare_program(name, ":/cgal/Polyhedron_3/resources/shader_c3t3_edges.vert" , ":/cgal/Polyhedron_3/resources/shader_c3t3_edges.frag") + : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_c3t3_edges.vert" , + ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_c3t3_edges.frag"); program->setProperty("hasCutPlane", true); return program; } case PROGRAM_WITH_LIGHT: { QOpenGLShaderProgram* program = isOpenGL_4_3() - ? declare_program(name, ":/cgal/Polyhedron_3/resources/shader_with_light.v" , ":/cgal/Polyhedron_3/resources/shader_with_light.f") - : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_with_light.v" , - ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_with_light.f"); + ? declare_program(name, ":/cgal/Polyhedron_3/resources/shader_with_light.vert" , ":/cgal/Polyhedron_3/resources/shader_with_light.frag") + : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_with_light.vert" , + ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_with_light.frag"); program->setProperty("hasLight", true); program->setProperty("hasNormals", true); program->setProperty("hasTransparency", true); @@ -1079,9 +1104,9 @@ QOpenGLShaderProgram* Viewer::getShaderProgram(int name) const case PROGRAM_HEAT_INTENSITY: { QOpenGLShaderProgram* program = isOpenGL_4_3() - ? declare_program(name, ":/cgal/Polyhedron_3/resources/heat_intensity_shader.v" , ":/cgal/Polyhedron_3/resources/heat_intensity_shader.f") - : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/heat_intensity_shader.v" , - ":/cgal/Polyhedron_3/resources/compatibility_shaders/heat_intensity_shader.f"); + ? declare_program(name, ":/cgal/Polyhedron_3/resources/heat_intensity_shader.vert" , ":/cgal/Polyhedron_3/resources/heat_intensity_shader.frag") + : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/heat_intensity_shader.vert" , + ":/cgal/Polyhedron_3/resources/compatibility_shaders/heat_intensity_shader.frag"); program->setProperty("hasLight", true); program->setProperty("hasNormals", true); program->setProperty("hasTransparency", true); @@ -1091,27 +1116,27 @@ QOpenGLShaderProgram* Viewer::getShaderProgram(int name) const case PROGRAM_WITHOUT_LIGHT: { QOpenGLShaderProgram* program = isOpenGL_4_3() - ? declare_program(name, ":/cgal/Polyhedron_3/resources/shader_without_light.v" , ":/cgal/Polyhedron_3/resources/shader_without_light.f") - : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_without_light.v" , - ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_without_light.f"); + ? declare_program(name, ":/cgal/Polyhedron_3/resources/shader_without_light.vert" , ":/cgal/Polyhedron_3/resources/shader_without_light.frag") + : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_without_light.vert" , + ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_without_light.frag"); program->setProperty("hasFMatrix", true); return program; } case PROGRAM_NO_SELECTION: { QOpenGLShaderProgram* program = isOpenGL_4_3() - ? declare_program(name, ":/cgal/Polyhedron_3/resources/shader_without_light.v" , ":/cgal/Polyhedron_3/resources/shader_no_light_no_selection.f") - : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_without_light.v" , - ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_no_light_no_selection.f"); + ? declare_program(name, ":/cgal/Polyhedron_3/resources/shader_without_light.vert" , ":/cgal/Polyhedron_3/resources/shader_no_light_no_selection.frag") + : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_without_light.vert" , + ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_no_light_no_selection.frag"); program->setProperty("hasFMatrix", true); return program; } case PROGRAM_WITH_TEXTURE: { QOpenGLShaderProgram* program = isOpenGL_4_3() - ? declare_program(name, ":/cgal/Polyhedron_3/resources/shader_with_texture.v" , ":/cgal/Polyhedron_3/resources/shader_with_texture.f") - : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_with_texture.v" , - ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_with_texture.f"); + ? declare_program(name, ":/cgal/Polyhedron_3/resources/shader_with_texture.vert" , ":/cgal/Polyhedron_3/resources/shader_with_texture.frag") + : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_with_texture.vert" , + ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_with_texture.frag"); program->setProperty("hasLight", true); program->setProperty("hasNormals", true); program->setProperty("hasFMatrix", true); @@ -1121,9 +1146,9 @@ QOpenGLShaderProgram* Viewer::getShaderProgram(int name) const case PROGRAM_PLANE_TWO_FACES: { QOpenGLShaderProgram* program = isOpenGL_4_3() - ?declare_program(name, ":/cgal/Polyhedron_3/resources/shader_without_light.v" , ":/cgal/Polyhedron_3/resources/shader_plane_two_faces.f") - : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_without_light.v" , - ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_plane_two_faces.f"); + ?declare_program(name, ":/cgal/Polyhedron_3/resources/shader_without_light.vert" , ":/cgal/Polyhedron_3/resources/shader_plane_two_faces.frag") + : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_without_light.vert" , + ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_plane_two_faces.frag"); program->setProperty("hasLight", true); program->setProperty("hasNormals", true); return program; @@ -1131,9 +1156,9 @@ QOpenGLShaderProgram* Viewer::getShaderProgram(int name) const case PROGRAM_WITH_TEXTURED_EDGES: { QOpenGLShaderProgram* program = isOpenGL_4_3() - ? declare_program(name, ":/cgal/Polyhedron_3/resources/shader_with_textured_edges.v" , ":/cgal/Polyhedron_3/resources/shader_with_textured_edges.f") - : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_with_textured_edges.v" , - ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_with_textured_edges.f"); + ? declare_program(name, ":/cgal/Polyhedron_3/resources/shader_with_textured_edges.vert" , ":/cgal/Polyhedron_3/resources/shader_with_textured_edges.frag") + : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_with_textured_edges.vert" , + ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_with_textured_edges.frag"); program->setProperty("hasFMatrix", true); program->setProperty("hasTexture", true); return program; @@ -1141,9 +1166,9 @@ QOpenGLShaderProgram* Viewer::getShaderProgram(int name) const case PROGRAM_INSTANCED: { QOpenGLShaderProgram* program = isOpenGL_4_3() - ? declare_program(name, ":/cgal/Polyhedron_3/resources/shader_instanced.v" , ":/cgal/Polyhedron_3/resources/shader_with_light.f") - : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_instanced.v" , - ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_with_light.f"); + ? declare_program(name, ":/cgal/Polyhedron_3/resources/shader_instanced.vert" , ":/cgal/Polyhedron_3/resources/shader_with_light.frag") + : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_instanced.vert" , + ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_with_light.frag"); program->setProperty("hasLight", true); program->setProperty("hasNormals", true); @@ -1153,9 +1178,9 @@ QOpenGLShaderProgram* Viewer::getShaderProgram(int name) const case PROGRAM_INSTANCED_WIRE: { QOpenGLShaderProgram* program = isOpenGL_4_3() - ? declare_program(name, ":/cgal/Polyhedron_3/resources/shader_instanced.v" , ":/cgal/Polyhedron_3/resources/shader_without_light.f") - : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_instanced.v" , - ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_without_light.f"); + ? declare_program(name, ":/cgal/Polyhedron_3/resources/shader_instanced.vert" , ":/cgal/Polyhedron_3/resources/shader_without_light.frag") + : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_instanced.vert" , + ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_without_light.frag"); program->setProperty("hasLight", true); program->setProperty("hasNormals", true); program->setProperty("hasBarycenter", true); @@ -1165,9 +1190,9 @@ QOpenGLShaderProgram* Viewer::getShaderProgram(int name) const case PROGRAM_CUTPLANE_SPHERES: { QOpenGLShaderProgram* program = isOpenGL_4_3() - ? declare_program(name, ":/cgal/Polyhedron_3/resources/shader_c3t3_spheres.v" , ":/cgal/Polyhedron_3/resources/shader_c3t3.f") - : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_c3t3_spheres.v" , - ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_c3t3.f"); + ? declare_program(name, ":/cgal/Polyhedron_3/resources/shader_c3t3_spheres.vert" , ":/cgal/Polyhedron_3/resources/shader_c3t3.frag") + : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_c3t3_spheres.vert" , + ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_c3t3.frag"); program->setProperty("hasLight", true); program->setProperty("hasNormals", true); program->setProperty("hasBarycenter", true); @@ -1178,9 +1203,9 @@ QOpenGLShaderProgram* Viewer::getShaderProgram(int name) const case PROGRAM_SPHERES: { QOpenGLShaderProgram* program = isOpenGL_4_3() - ?declare_program(name, ":/cgal/Polyhedron_3/resources/shader_spheres.v" , ":/cgal/Polyhedron_3/resources/shader_with_light.f") - : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_spheres.v" , - ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_with_light.f"); + ?declare_program(name, ":/cgal/Polyhedron_3/resources/shader_spheres.vert" , ":/cgal/Polyhedron_3/resources/shader_with_light.frag") + : declare_program(name, ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_spheres.vert" , + ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_with_light.frag"); program->setProperty("hasLight", true); program->setProperty("hasNormals", true); program->setProperty("hasBarycenter", true); @@ -1196,7 +1221,7 @@ QOpenGLShaderProgram* Viewer::getShaderProgram(int name) const std::cerr<<"An OpenGL context of version 4.3 is required for the program ("<setProperty("hasLight", true); program->setProperty("hasNormals", true); return program; @@ -1204,10 +1229,10 @@ QOpenGLShaderProgram* Viewer::getShaderProgram(int name) const case PROGRAM_OLD_FLAT: { QOpenGLShaderProgram* program = isOpenGL_4_3() - ? declare_program(name, ":/cgal/Polyhedron_3/resources/shader_with_light.v", ":/cgal/Polyhedron_3/resources/shader_old_flat.f") + ? declare_program(name, ":/cgal/Polyhedron_3/resources/shader_with_light.vert", ":/cgal/Polyhedron_3/resources/shader_old_flat.frag") : declare_program(name, - ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_with_light.v", - ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_old_flat.f"); + ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_with_light.vert", + ":/cgal/Polyhedron_3/resources/compatibility_shaders/shader_old_flat.frag"); program->setProperty("hasLight", true); program->setProperty("hasNormals", true); return program; @@ -1219,8 +1244,8 @@ QOpenGLShaderProgram* Viewer::getShaderProgram(int name) const return 0; } return declare_program(name, - ":/cgal/Polyhedron_3/resources/solid_wireframe_shader.v", - ":/cgal/Polyhedron_3/resources/solid_wireframe_shader.f"); + ":/cgal/Polyhedron_3/resources/solid_wireframe_shader.vert", + ":/cgal/Polyhedron_3/resources/solid_wireframe_shader.frag"); break; default: std::cerr<<"ERROR : Program not found."<template add_property_map("red", 0).first; + m_green = this->template add_property_map("green", 0).first; + m_blue = this->template add_property_map("blue", 0).first; + + return true; + } + void remove_colors() { if (m_blue != Byte_map()) @@ -284,20 +296,35 @@ public: this->template remove_property_map(m_fblue); } } - + double red (const Index& index) const { return (m_red == Byte_map()) ? m_fred[index] : double(m_red[index]) / 255.; } double green (const Index& index) const { return (m_green == Byte_map()) ? m_fgreen[index] : double(m_green[index]) / 255.; } double blue (const Index& index) const { return (m_blue == Byte_map()) ? m_fblue[index] : double(m_blue[index]) / 255.; } - void set_color (const Index& index, unsigned char r, unsigned char g, unsigned char b) + + void set_color (const Index& index, unsigned char r = 0, unsigned char g = 0, unsigned char b = 0) { m_red[index] = r; m_green[index] = g; m_blue[index] = b; } + void set_color (const Index& index, const QColor& color) + { + m_red[index] = color.red(); + m_green[index] = color.green(); + m_blue[index] = color.blue(); + } + + template + void set_color (const Index& index, const ColorRange& color) + { + m_red[index] = color[0]; + m_green[index] = color[1]; + m_blue[index] = color[2]; + } iterator first_selected() { return this->m_indices.end() - this->m_nb_removed; } diff --git a/Polyhedron/demo/Polyhedron/include/QMultipleInputDialog.h b/Polyhedron/demo/Polyhedron/include/QMultipleInputDialog.h index 4825f59a6c0..f2b13bc84b2 100644 --- a/Polyhedron/demo/Polyhedron/include/QMultipleInputDialog.h +++ b/Polyhedron/demo/Polyhedron/include/QMultipleInputDialog.h @@ -15,6 +15,9 @@ class QMultipleInputDialog { QDialog* dialog; QFormLayout* form; + std::map map_widgets; + + public: QMultipleInputDialog (const char* name, QWidget* parent) { @@ -28,7 +31,7 @@ public: } template - QObjectType* add (const char* name) + QObjectType* add (const char* name, const char* key = NULL) { QObjectType* out = NULL; @@ -43,9 +46,24 @@ public: form->addRow (QString(name), out); } + if (key != NULL) + map_widgets.insert (std::make_pair (key, out)); + return out; } + template + const QObjectType* get (const char* key) const + { + typename std::map::const_iterator + found = map_widgets.find (key); + if (found == map_widgets.end()) + return NULL; + + QWidget* widget_out = found->second; + return qobject_cast(widget_out); + } + int exec() { QDialogButtonBox* oknotok = new QDialogButtonBox @@ -58,6 +76,16 @@ public: return dialog->exec(); } + + void exec_no_cancel() + { + QDialogButtonBox* ok = new QDialogButtonBox + (QDialogButtonBox::Ok, Qt::Horizontal, dialog); + + form->addRow (ok); + QObject::connect (ok, SIGNAL(accepted()), dialog, SLOT(accept())); + dialog->exec(); + } }; diff --git a/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/heat_intensity_shader.f b/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/heat_intensity_shader.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/compatibility_shaders/heat_intensity_shader.f rename to Polyhedron/demo/Polyhedron/resources/compatibility_shaders/heat_intensity_shader.frag diff --git a/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/heat_intensity_shader.v b/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/heat_intensity_shader.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/compatibility_shaders/heat_intensity_shader.v rename to Polyhedron/demo/Polyhedron/resources/compatibility_shaders/heat_intensity_shader.vert diff --git a/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_c3t3.f b/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_c3t3.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_c3t3.f rename to Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_c3t3.frag diff --git a/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_c3t3.v b/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_c3t3.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_c3t3.v rename to Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_c3t3.vert diff --git a/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_c3t3_edges.f b/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_c3t3_edges.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_c3t3_edges.f rename to Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_c3t3_edges.frag diff --git a/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_c3t3_edges.v b/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_c3t3_edges.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_c3t3_edges.v rename to Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_c3t3_edges.vert diff --git a/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_c3t3_spheres.v b/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_c3t3_spheres.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_c3t3_spheres.v rename to Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_c3t3_spheres.vert diff --git a/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_instanced.v b/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_instanced.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_instanced.v rename to Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_instanced.vert diff --git a/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_no_light_no_selection.f b/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_no_light_no_selection.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_no_light_no_selection.f rename to Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_no_light_no_selection.frag diff --git a/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_old_flat.f b/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_old_flat.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_old_flat.f rename to Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_old_flat.frag diff --git a/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_plane_two_faces.f b/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_plane_two_faces.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_plane_two_faces.f rename to Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_plane_two_faces.frag diff --git a/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_spheres.v b/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_spheres.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_spheres.v rename to Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_spheres.vert diff --git a/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_light.f b/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_light.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_light.f rename to Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_light.frag diff --git a/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_light.v b/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_light.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_light.v rename to Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_light.vert diff --git a/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_texture.f b/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_texture.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_texture.f rename to Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_texture.frag diff --git a/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_texture.v b/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_texture.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_texture.v rename to Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_texture.vert diff --git a/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_textured_edges.f b/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_textured_edges.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_textured_edges.f rename to Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_textured_edges.frag diff --git a/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_textured_edges.v b/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_textured_edges.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_textured_edges.v rename to Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_with_textured_edges.vert diff --git a/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_without_light.f b/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_without_light.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_without_light.f rename to Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_without_light.frag diff --git a/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_without_light.v b/Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_without_light.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_without_light.v rename to Polyhedron/demo/Polyhedron/resources/compatibility_shaders/shader_without_light.vert diff --git a/Polyhedron/demo/Polyhedron/resources/heat_intensity_shader.f b/Polyhedron/demo/Polyhedron/resources/heat_intensity_shader.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/heat_intensity_shader.f rename to Polyhedron/demo/Polyhedron/resources/heat_intensity_shader.frag diff --git a/Polyhedron/demo/Polyhedron/resources/heat_intensity_shader.v b/Polyhedron/demo/Polyhedron/resources/heat_intensity_shader.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/heat_intensity_shader.v rename to Polyhedron/demo/Polyhedron/resources/heat_intensity_shader.vert diff --git a/Polyhedron/demo/Polyhedron/resources/no_interpolation_shader.f b/Polyhedron/demo/Polyhedron/resources/no_interpolation_shader.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/no_interpolation_shader.f rename to Polyhedron/demo/Polyhedron/resources/no_interpolation_shader.frag diff --git a/Polyhedron/demo/Polyhedron/resources/no_interpolation_shader.g b/Polyhedron/demo/Polyhedron/resources/no_interpolation_shader.geom similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/no_interpolation_shader.g rename to Polyhedron/demo/Polyhedron/resources/no_interpolation_shader.geom diff --git a/Polyhedron/demo/Polyhedron/resources/no_interpolation_shader.v b/Polyhedron/demo/Polyhedron/resources/no_interpolation_shader.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/no_interpolation_shader.v rename to Polyhedron/demo/Polyhedron/resources/no_interpolation_shader.vert diff --git a/Polyhedron/demo/Polyhedron/resources/shader_c3t3.f b/Polyhedron/demo/Polyhedron/resources/shader_c3t3.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/shader_c3t3.f rename to Polyhedron/demo/Polyhedron/resources/shader_c3t3.frag diff --git a/Polyhedron/demo/Polyhedron/resources/shader_c3t3.v b/Polyhedron/demo/Polyhedron/resources/shader_c3t3.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/shader_c3t3.v rename to Polyhedron/demo/Polyhedron/resources/shader_c3t3.vert diff --git a/Polyhedron/demo/Polyhedron/resources/shader_c3t3_edges.f b/Polyhedron/demo/Polyhedron/resources/shader_c3t3_edges.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/shader_c3t3_edges.f rename to Polyhedron/demo/Polyhedron/resources/shader_c3t3_edges.frag diff --git a/Polyhedron/demo/Polyhedron/resources/shader_c3t3_edges.v b/Polyhedron/demo/Polyhedron/resources/shader_c3t3_edges.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/shader_c3t3_edges.v rename to Polyhedron/demo/Polyhedron/resources/shader_c3t3_edges.vert diff --git a/Polyhedron/demo/Polyhedron/resources/shader_c3t3_spheres.v b/Polyhedron/demo/Polyhedron/resources/shader_c3t3_spheres.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/shader_c3t3_spheres.v rename to Polyhedron/demo/Polyhedron/resources/shader_c3t3_spheres.vert diff --git a/Polyhedron/demo/Polyhedron/resources/shader_flat.f b/Polyhedron/demo/Polyhedron/resources/shader_flat.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/shader_flat.f rename to Polyhedron/demo/Polyhedron/resources/shader_flat.frag diff --git a/Polyhedron/demo/Polyhedron/resources/shader_flat.g b/Polyhedron/demo/Polyhedron/resources/shader_flat.geom similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/shader_flat.g rename to Polyhedron/demo/Polyhedron/resources/shader_flat.geom diff --git a/Polyhedron/demo/Polyhedron/resources/shader_flat.v b/Polyhedron/demo/Polyhedron/resources/shader_flat.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/shader_flat.v rename to Polyhedron/demo/Polyhedron/resources/shader_flat.vert diff --git a/Polyhedron/demo/Polyhedron/resources/shader_instanced.v b/Polyhedron/demo/Polyhedron/resources/shader_instanced.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/shader_instanced.v rename to Polyhedron/demo/Polyhedron/resources/shader_instanced.vert diff --git a/Polyhedron/demo/Polyhedron/resources/shader_no_light_no_selection.f b/Polyhedron/demo/Polyhedron/resources/shader_no_light_no_selection.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/shader_no_light_no_selection.f rename to Polyhedron/demo/Polyhedron/resources/shader_no_light_no_selection.frag diff --git a/Polyhedron/demo/Polyhedron/resources/shader_old_flat.f b/Polyhedron/demo/Polyhedron/resources/shader_old_flat.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/shader_old_flat.f rename to Polyhedron/demo/Polyhedron/resources/shader_old_flat.frag diff --git a/Polyhedron/demo/Polyhedron/resources/shader_plane_two_faces.f b/Polyhedron/demo/Polyhedron/resources/shader_plane_two_faces.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/shader_plane_two_faces.f rename to Polyhedron/demo/Polyhedron/resources/shader_plane_two_faces.frag diff --git a/Polyhedron/demo/Polyhedron/resources/shader_spheres.v b/Polyhedron/demo/Polyhedron/resources/shader_spheres.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/shader_spheres.v rename to Polyhedron/demo/Polyhedron/resources/shader_spheres.vert diff --git a/Polyhedron/demo/Polyhedron/resources/shader_with_light.f b/Polyhedron/demo/Polyhedron/resources/shader_with_light.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/shader_with_light.f rename to Polyhedron/demo/Polyhedron/resources/shader_with_light.frag diff --git a/Polyhedron/demo/Polyhedron/resources/shader_with_light.v b/Polyhedron/demo/Polyhedron/resources/shader_with_light.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/shader_with_light.v rename to Polyhedron/demo/Polyhedron/resources/shader_with_light.vert diff --git a/Polyhedron/demo/Polyhedron/resources/shader_with_texture.f b/Polyhedron/demo/Polyhedron/resources/shader_with_texture.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/shader_with_texture.f rename to Polyhedron/demo/Polyhedron/resources/shader_with_texture.frag diff --git a/Polyhedron/demo/Polyhedron/resources/shader_with_texture.v b/Polyhedron/demo/Polyhedron/resources/shader_with_texture.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/shader_with_texture.v rename to Polyhedron/demo/Polyhedron/resources/shader_with_texture.vert diff --git a/Polyhedron/demo/Polyhedron/resources/shader_with_textured_edges.f b/Polyhedron/demo/Polyhedron/resources/shader_with_textured_edges.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/shader_with_textured_edges.f rename to Polyhedron/demo/Polyhedron/resources/shader_with_textured_edges.frag diff --git a/Polyhedron/demo/Polyhedron/resources/shader_with_textured_edges.v b/Polyhedron/demo/Polyhedron/resources/shader_with_textured_edges.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/shader_with_textured_edges.v rename to Polyhedron/demo/Polyhedron/resources/shader_with_textured_edges.vert diff --git a/Polyhedron/demo/Polyhedron/resources/shader_without_light.f b/Polyhedron/demo/Polyhedron/resources/shader_without_light.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/shader_without_light.f rename to Polyhedron/demo/Polyhedron/resources/shader_without_light.frag diff --git a/Polyhedron/demo/Polyhedron/resources/shader_without_light.v b/Polyhedron/demo/Polyhedron/resources/shader_without_light.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/shader_without_light.v rename to Polyhedron/demo/Polyhedron/resources/shader_without_light.vert diff --git a/Polyhedron/demo/Polyhedron/resources/solid_wireframe_shader.f b/Polyhedron/demo/Polyhedron/resources/solid_wireframe_shader.frag similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/solid_wireframe_shader.f rename to Polyhedron/demo/Polyhedron/resources/solid_wireframe_shader.frag diff --git a/Polyhedron/demo/Polyhedron/resources/solid_wireframe_shader.g b/Polyhedron/demo/Polyhedron/resources/solid_wireframe_shader.geom similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/solid_wireframe_shader.g rename to Polyhedron/demo/Polyhedron/resources/solid_wireframe_shader.geom diff --git a/Polyhedron/demo/Polyhedron/resources/solid_wireframe_shader.v b/Polyhedron/demo/Polyhedron/resources/solid_wireframe_shader.vert similarity index 100% rename from Polyhedron/demo/Polyhedron/resources/solid_wireframe_shader.v rename to Polyhedron/demo/Polyhedron/resources/solid_wireframe_shader.vert diff --git a/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--PolynomialSubresultants.h b/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--PolynomialSubresultants.h index 87cdc87ecc6..026c76a8848 100644 --- a/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--PolynomialSubresultants.h +++ b/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--PolynomialSubresultants.h @@ -3,8 +3,6 @@ \ingroup PkgPolynomialConcepts \cgalConcept -Note: This functor is optional! - Computes the polynomial subresultant of two polynomials \f$ p\f$ and \f$ q\f$ of type `PolynomialTraits_d::Polynomial_d` with respect to outermost variable. Let @@ -23,6 +21,8 @@ The result is written in an output range, starting with the \f$ 0\f$-th subresul \f$ \mathrm{Sres}_0(p,q)\f$ (aka as the resultant of \f$ p\f$ and \f$ q\f$). +\note This functor is optional. + \cgalRefines `AdaptableBinaryFunction` \cgalRefines `CopyConstructible` \cgalRefines `DefaultConstructible` diff --git a/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--PolynomialSubresultantsWithCofactors.h b/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--PolynomialSubresultantsWithCofactors.h index b1981463df7..56c1e14f641 100644 --- a/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--PolynomialSubresultantsWithCofactors.h +++ b/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--PolynomialSubresultantsWithCofactors.h @@ -3,8 +3,6 @@ \ingroup PkgPolynomialConcepts \cgalConcept -Note: This functor is optional! - Computes the polynomial subresultant of two polynomials \f$ p\f$ and \f$ q\f$ of degree \f$ n\f$ and \f$ m\f$, respectively, as defined in the documentation of `PolynomialTraits_d::PolynomialSubresultants`. @@ -16,6 +14,8 @@ the cofactors of \f$ \mathrm{Sres}_i(p,q)\f$. The result is written in three output ranges, each of length \f$ \min\{n,m\}+1\f$, starting with the \f$ 0\f$-th subresultant and the corresponding cofactors. +\note This functor is optional. + \cgalRefines `AdaptableBinaryFunction` \cgalRefines `CopyConstructible` \cgalRefines `DefaultConstructible` diff --git a/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--PrincipalSturmHabichtSequence.h b/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--PrincipalSturmHabichtSequence.h index bd4bd491935..376a3e279ef 100644 --- a/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--PrincipalSturmHabichtSequence.h +++ b/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--PrincipalSturmHabichtSequence.h @@ -3,8 +3,6 @@ \ingroup PkgPolynomialConcepts \cgalConcept -Note: This functor is optional! - Computes the principal leading coefficients of the Sturm-Habicht sequence of a polynomials \f$ f\f$ of type `PolynomialTraits_d::Polynomial_d` with respect a certain variable \f$ x_i\f$. @@ -19,6 +17,8 @@ In case that `PolynomialTraits_d::Coefficient_type` is `RealEmbeddable`, the fun on the resulting sequence to count the number of distinct real roots of the polynomial \f$ f\f$. +\note This functor is optional. + \cgalRefines `AdaptableBinaryFunction` \cgalRefines `CopyConstructible` \cgalRefines `DefaultConstructible` diff --git a/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--PrincipalSubresultants.h b/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--PrincipalSubresultants.h index 2cddb81e1ed..3a63bc6f76d 100644 --- a/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--PrincipalSubresultants.h +++ b/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--PrincipalSubresultants.h @@ -3,8 +3,6 @@ \ingroup PkgPolynomialConcepts \cgalConcept -Note: This functor is optional! - Computes the principal subresultant of two polynomials \f$ p\f$ and \f$ q\f$ of type `PolynomialTraits_d::Coefficient_type` with respect to the outermost variable. @@ -19,6 +17,8 @@ principal subresultant \f$ \mathrm{sres}_0(p,q)\f$ ,aka as the resultant of \f$ p\f$ and \f$ q\f$. (Note that \f$ \mathrm{sres}_0(p,q)=\mathrm{Sres}_0(p,q)\f$ by definition) +\note This functor is optional. + \cgalRefines `AdaptableBinaryFunction` \cgalRefines `CopyConstructible` \cgalRefines `DefaultConstructible` diff --git a/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--SturmHabichtSequence.h b/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--SturmHabichtSequence.h index f6a4676dfc3..32478346def 100644 --- a/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--SturmHabichtSequence.h +++ b/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--SturmHabichtSequence.h @@ -3,8 +3,6 @@ \ingroup PkgPolynomialConcepts \cgalConcept -Note: This functor is optional! - Computes the Sturm-Habicht sequence (aka the signed subresultant sequence) of a polynomial \f$ f\f$ of type @@ -27,6 +25,8 @@ The result is written in an output range, starting with the \f$ 0\f$-th Sturm-Habicht polynomial (which is equal to the discriminant of \f$ f\f$ up to a multiple of the leading coefficient). +\note This functor is optional. + \cgalRefines `AdaptableBinaryFunction` \cgalRefines `CopyConstructible` \cgalRefines `DefaultConstructible` diff --git a/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--SturmHabichtSequenceWithCofactors.h b/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--SturmHabichtSequenceWithCofactors.h index e77f9b78cd2..85efdb9edf9 100644 --- a/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--SturmHabichtSequenceWithCofactors.h +++ b/Polynomial/doc/Polynomial/Concepts/PolynomialTraits_d--SturmHabichtSequenceWithCofactors.h @@ -3,8 +3,6 @@ \ingroup PkgPolynomialConcepts \cgalConcept -Note: This functor is optional! - Computes the Sturm-Habicht polynomials of a polynomial \f$ f\f$ of degree \f$ n\f$, as defined in the documentation of `PolynomialTraits_d::SturmHabichtSequence`. Moreover, for \f$ \mathrm{Stha}_i(f)\f$, polynomials \f$ u_i\f$ and \f$ v_i\f$ @@ -16,6 +14,8 @@ The result is written in three output ranges, each of length \f$ \min\{n,m\}+1\f starting with the \f$ 0\f$-th Sturm-Habicht polynomial \f$ \mathrm{Stha_0(f)}\f$ and the corresponding cofactors. +\note This functor is optional. + \cgalRefines `AdaptableBinaryFunction` \cgalRefines `CopyConstructible` \cgalRefines `DefaultConstructible` diff --git a/Scripts/developer_scripts/cgal_create_release_with_cmake.cmake b/Scripts/developer_scripts/cgal_create_release_with_cmake.cmake index 01f7cde55ad..fb190b50401 100644 --- a/Scripts/developer_scripts/cgal_create_release_with_cmake.cmake +++ b/Scripts/developer_scripts/cgal_create_release_with_cmake.cmake @@ -266,6 +266,7 @@ if (TESTSUITE) endif() #TESTSUITE # removal of extra directories and files +file(REMOVE_RECURSE ${release_dir}/applications) file(REMOVE_RECURSE ${release_dir}/benchmark) file(REMOVE_RECURSE ${release_dir}/archive) file(REMOVE ${release_dir}/include/CGAL/license/generate_files.cmake) diff --git a/Scripts/developer_scripts/list_pull_requests.py b/Scripts/developer_scripts/list_pull_requests.py index 70dfe831f4e..ea93906844e 100755 --- a/Scripts/developer_scripts/list_pull_requests.py +++ b/Scripts/developer_scripts/list_pull_requests.py @@ -68,7 +68,7 @@ else: print_verbose(" index path is {}".format(repo.index_path())) print_verbose("Getting commits in current branch", end='') print_verbose(" {}".\ - format(str(repo.refs.read_ref('HEAD'), "ascii")), end='') + format(str(repo.refs.read_ref(b'HEAD'), "ascii")), end='') sys.stderr.flush() walk = repo.get_walker(include=repo.head(),\ exclude=[repo.get_refs()[b'refs/remotes/cgal/master']]) diff --git a/Segment_Delaunay_graph_Linf_2/include/CGAL/Segment_Delaunay_graph_Linf_filtered_traits_2.h b/Segment_Delaunay_graph_Linf_2/include/CGAL/Segment_Delaunay_graph_Linf_filtered_traits_2.h index 4f9c4a31648..5335a26b209 100644 --- a/Segment_Delaunay_graph_Linf_2/include/CGAL/Segment_Delaunay_graph_Linf_filtered_traits_2.h +++ b/Segment_Delaunay_graph_Linf_2/include/CGAL/Segment_Delaunay_graph_Linf_filtered_traits_2.h @@ -221,7 +221,7 @@ template, #else - class EK = Simple_cartesian< MP_Float >, + class EK = Simple_cartesian< CGAL::Quotient >, #endif class EK_MTag = Integral_domain_without_division_tag, class FK = Simple_cartesian< Interval_nt >, diff --git a/Segment_Delaunay_graph_Linf_2/include/CGAL/Side_of_bounded_square_2.h b/Segment_Delaunay_graph_Linf_2/include/CGAL/Side_of_bounded_square_2.h index 17cfb236743..37f205cf6c4 100644 --- a/Segment_Delaunay_graph_Linf_2/include/CGAL/Side_of_bounded_square_2.h +++ b/Segment_Delaunay_graph_Linf_2/include/CGAL/Side_of_bounded_square_2.h @@ -70,7 +70,7 @@ namespace CGAL { bool samepq = false; bool samepr = false; bool sameqr = false; - const Comparison_result cmppq = compare(p, q); + const Comparison_result cmppq = CGAL::compare(p, q); switch(cmppq) { case SMALLER: min_p = &p; @@ -86,7 +86,7 @@ namespace CGAL { samepq = true; break; } - const Comparison_result cmppr = compare(p, r); + const Comparison_result cmppr = CGAL::compare(p, r); Comparison_result cmpqr; if (samepq) { cmpqr = cmppr; @@ -105,7 +105,7 @@ namespace CGAL { if (min_p == &p) { switch(cmppr) { case SMALLER: - cmpqr = compare(q, r); + cmpqr = CGAL::compare(q, r); switch(cmpqr) { case SMALLER: max_p = &r; @@ -135,7 +135,7 @@ namespace CGAL { max_p = &r; break; case LARGER: - cmpqr = compare(q, r); + cmpqr = CGAL::compare(q, r); switch(cmpqr) { case SMALLER: break; diff --git a/Segment_Delaunay_graph_Linf_2/test/Segment_Delaunay_graph_Linf_2/test_sdg_linf_2_et.cpp b/Segment_Delaunay_graph_Linf_2/test/Segment_Delaunay_graph_Linf_2/test_sdg_linf_2_et.cpp index eca8eee9727..43c4de102d9 100644 --- a/Segment_Delaunay_graph_Linf_2/test/Segment_Delaunay_graph_Linf_2/test_sdg_linf_2_et.cpp +++ b/Segment_Delaunay_graph_Linf_2/test/Segment_Delaunay_graph_Linf_2/test_sdg_linf_2_et.cpp @@ -10,28 +10,18 @@ #include #include -// choose number type -#ifdef CGAL_USE_GMP +#include -# include -typedef CGAL::Gmpq exact_ring_t; -typedef CGAL::Gmpq exact_field_t; +// choose number type +typedef CGAL::Exact_rational exact_ring_t; +typedef CGAL::Exact_rational exact_field_t; namespace CGAL { // needed for the drawing methods -Gmpq sqrt(const Gmpq& x) { - return Gmpq( CGAL::sqrt( CGAL::to_double(x) ) ); +exact_ring_t sqrt(const exact_ring_t& x) { + return exact_ring_t( sqrt( to_double(x) ) ); +} } - -} //namespace CGAL -#else - -# include -# include -typedef CGAL::MP_Float exact_ring_t; -typedef CGAL::Quotient exact_field_t; - -#endif typedef exact_ring_t ring_number_t; typedef exact_field_t field_number_t; diff --git a/Segment_Delaunay_graph_Linf_2/test/Segment_Delaunay_graph_Linf_2/test_sdg_linf_2_ft.cpp b/Segment_Delaunay_graph_Linf_2/test/Segment_Delaunay_graph_Linf_2/test_sdg_linf_2_ft.cpp index 91e5edbe13c..961eaa43605 100644 --- a/Segment_Delaunay_graph_Linf_2/test/Segment_Delaunay_graph_Linf_2/test_sdg_linf_2_ft.cpp +++ b/Segment_Delaunay_graph_Linf_2/test/Segment_Delaunay_graph_Linf_2/test_sdg_linf_2_ft.cpp @@ -10,17 +10,11 @@ #include #include +#include + // choose number type -#ifdef CGAL_USE_GMP -# include -typedef CGAL::Gmpq exact_ring_t; -typedef CGAL::Gmpq exact_field_t; -#else -# include -# include -typedef CGAL::MP_Float exact_ring_t; -typedef CGAL::Quotient exact_field_t; -#endif +typedef CGAL::Exact_rational exact_ring_t; +typedef CGAL::Exact_rational exact_field_t; #include diff --git a/Segment_Delaunay_graph_Linf_2/test/Segment_Delaunay_graph_Linf_2/test_sdg_linf_hierarchy_2_et.cpp b/Segment_Delaunay_graph_Linf_2/test/Segment_Delaunay_graph_Linf_2/test_sdg_linf_hierarchy_2_et.cpp index 2f05e01dac2..8b9733164a2 100644 --- a/Segment_Delaunay_graph_Linf_2/test/Segment_Delaunay_graph_Linf_2/test_sdg_linf_hierarchy_2_et.cpp +++ b/Segment_Delaunay_graph_Linf_2/test/Segment_Delaunay_graph_Linf_2/test_sdg_linf_hierarchy_2_et.cpp @@ -10,28 +10,18 @@ #include #include -// choose number type -#ifdef CGAL_USE_GMP +#include -# include -typedef CGAL::Gmpq exact_ring_t; -typedef CGAL::Gmpq exact_field_t; +// choose number type +typedef CGAL::Exact_rational exact_ring_t; +typedef CGAL::Exact_rational exact_field_t; namespace CGAL { // needed for the drawing methods -Gmpq sqrt(const Gmpq& x) { - return Gmpq( sqrt( to_double(x) ) ); +exact_ring_t sqrt(const exact_ring_t& x) { + return exact_ring_t( sqrt( to_double(x) ) ); +} } - -} //namespace CGAL -#else - -# include -# include -typedef CGAL::MP_Float exact_ring_t; -typedef CGAL::Quotient exact_field_t; - -#endif typedef exact_ring_t ring_number_t; typedef exact_field_t field_number_t; diff --git a/Segment_Delaunay_graph_Linf_2/test/Segment_Delaunay_graph_Linf_2/test_sdg_linf_hierarchy_2_ft.cpp b/Segment_Delaunay_graph_Linf_2/test/Segment_Delaunay_graph_Linf_2/test_sdg_linf_hierarchy_2_ft.cpp index 458a3a81c31..ed6565c1997 100644 --- a/Segment_Delaunay_graph_Linf_2/test/Segment_Delaunay_graph_Linf_2/test_sdg_linf_hierarchy_2_ft.cpp +++ b/Segment_Delaunay_graph_Linf_2/test/Segment_Delaunay_graph_Linf_2/test_sdg_linf_hierarchy_2_ft.cpp @@ -10,17 +10,11 @@ #include #include +#include + // choose number type -#ifdef CGAL_USE_GMP -# include -typedef CGAL::Gmpq exact_ring_t; -typedef CGAL::Gmpq exact_field_t; -#else -# include -# include -typedef CGAL::MP_Float exact_ring_t; -typedef CGAL::Quotient exact_field_t; -#endif +typedef CGAL::Exact_rational exact_ring_t; +typedef CGAL::Exact_rational exact_field_t; #include diff --git a/Segment_Delaunay_graph_Linf_2/test/Segment_Delaunay_graph_Linf_2/test_sdg_linf_new_range_api.cpp b/Segment_Delaunay_graph_Linf_2/test/Segment_Delaunay_graph_Linf_2/test_sdg_linf_new_range_api.cpp index 791a866fb99..8b5124e1c6c 100644 --- a/Segment_Delaunay_graph_Linf_2/test/Segment_Delaunay_graph_Linf_2/test_sdg_linf_new_range_api.cpp +++ b/Segment_Delaunay_graph_Linf_2/test/Segment_Delaunay_graph_Linf_2/test_sdg_linf_new_range_api.cpp @@ -7,12 +7,14 @@ #include #include #include -#include +#include typedef CGAL::Exact_predicates_inexact_constructions_kernel K; typedef CGAL::Field_with_sqrt_tag MTag; typedef CGAL::Integral_domain_without_division_tag EMTag; -typedef CGAL::Simple_cartesian EK; +typedef CGAL::Exact_rational Number_type; + +typedef CGAL::Simple_cartesian EK; typedef CGAL::Segment_Delaunay_graph_Linf_filtered_traits_without_intersections_2 Gt; typedef CGAL::Segment_Delaunay_graph_Linf_2 SDG; diff --git a/Solver_interface/doc/Solver_interface/Concepts/DiagonalizeTraits.h b/Solver_interface/doc/Solver_interface/Concepts/DiagonalizeTraits.h index f982dfc50ad..b29e95b7237 100644 --- a/Solver_interface/doc/Solver_interface/Concepts/DiagonalizeTraits.h +++ b/Solver_interface/doc/Solver_interface/Concepts/DiagonalizeTraits.h @@ -4,7 +4,9 @@ Concept providing functions to extract eigenvectors and eigenvalues from covariance matrices represented by an array `a`, using symmetric -diagonalization. For example, a matrix of dimension 3 is defined as +diagonalization. + +For example, a matrix of dimension 3 is defined as follows:
\f$ \begin{bmatrix} diff --git a/Straight_skeleton_2/doc/Straight_skeleton_2/Concepts/VertexContainer_2.h b/Straight_skeleton_2/doc/Straight_skeleton_2/Concepts/VertexContainer_2.h index 15dfdf25092..b35ba7ee047 100644 --- a/Straight_skeleton_2/doc/Straight_skeleton_2/Concepts/VertexContainer_2.h +++ b/Straight_skeleton_2/doc/Straight_skeleton_2/Concepts/VertexContainer_2.h @@ -2,8 +2,6 @@ \ingroup PkgStraightSkeleton2Concepts \cgalConcept -\cgalHeading{Introduction} - A model for the `VertexContainer_2` concept defines the requirements for a resizable container of 2D points. It is used to output the offset polygons generated by the `Polygon_offset_builder_2` class. \cgalHasModel CGAL::Polygon_2 diff --git a/Stream_support/include/CGAL/IO/write_vtk.h b/Stream_support/include/CGAL/IO/write_vtk.h new file mode 100644 index 00000000000..b55df59c17e --- /dev/null +++ b/Stream_support/include/CGAL/IO/write_vtk.h @@ -0,0 +1,40 @@ +// Copyright (c) 2018 +// GeometryFactory( France) All rights reserved. +// +// This file is part of CGAL (www.cgal.org); you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public License as +// published by the Free Software Foundation; either version 3 of the License, +// or (at your option) any later version. +// +// 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$ +// $Id$ +// SPDX-License-Identifier: LGPL-3.0+ +// +// +// Author(s) : Stephane Tayeb + +#ifndef CGAL_WRITE_VTK_IO_H +#define CGAL_WRITE_VTK_IO_H + +#include + +#include +#include +template +void +write_vector(std::ostream& os, + const std::vector& vect) +{ + const char* buffer = reinterpret_cast(&(vect[0])); + std::size_t size = vect.size()*sizeof(FT); + + os.write(reinterpret_cast(&size), sizeof(std::size_t)); // number of bytes encoded + os.write(buffer, vect.size()*sizeof(FT)); // encoded data +} +#endif diff --git a/Subdivision_method_3/include/CGAL/Subdivision_method_3/subdivision_masks_3.h b/Subdivision_method_3/include/CGAL/Subdivision_method_3/subdivision_masks_3.h index 527b79c21ef..877411cf398 100644 --- a/Subdivision_method_3/include/CGAL/Subdivision_method_3/subdivision_masks_3.h +++ b/Subdivision_method_3/include/CGAL/Subdivision_method_3/subdivision_masks_3.h @@ -215,13 +215,13 @@ public: /// computes the Catmull-Clark vertex-point `pt` of the vertex `vertex`. void vertex_node(vertex_descriptor vertex, Point& pt) { Halfedge_around_target_circulator vcir(vertex, *(this->pmesh)); - typename boost::graph_traits::degree_size_type n = degree(vertex, *(this->pmesh)); + int n = static_cast(degree(vertex, *(this->pmesh))); FT Q[] = {0.0, 0.0, 0.0}, R[] = {0.0, 0.0, 0.0}; Point_ref S = get(this->vpmap,vertex); Point q; - for (typename boost::graph_traits::degree_size_type i = 0; i < n; i++, ++vcir) { + for (int i = 0; i < n; i++, ++vcir) { Point_ref p2 = get(this->vpmap, target(opposite(*vcir, *(this->pmesh)), *(this->pmesh))); R[0] += (S[0] + p2[0]) / 2; R[1] += (S[1] + p2[1]) / 2; diff --git a/Three/include/CGAL/Three/Three.h b/Three/include/CGAL/Three/Three.h index 17197383a41..868d0a69ef9 100644 --- a/Three/include/CGAL/Three/Three.h +++ b/Three/include/CGAL/Three/Three.h @@ -29,6 +29,7 @@ #include #include #include +#include #ifdef three_EXPORTS # define THREE_EXPORT Q_DECL_EXPORT @@ -47,7 +48,6 @@ public: static QMainWindow* mainWindow(); static Scene_interface* scene(); static QObject* connectableScene(); - static Three* messages(); static RenderingMode defaultSurfaceMeshRenderingMode(); static RenderingMode defaultPointSetRenderingMode(); static QString modeName(RenderingMode mode); @@ -77,6 +77,15 @@ public: * in the plugin. */ static void autoConnectActions(CGAL::Three::Polyhedron_demo_plugin_interface* plugin); + static void information(QString); + /*! + * Displays a blue text preceded by the mention "WARNING :". + */ + static void warning(QString); + /*! + * Displays a red text preceded by the mention "ERROR :". + */ + static void error(QString); protected: static QMainWindow* s_mainwindow; static Scene_interface* s_scene; @@ -88,6 +97,18 @@ protected: static int default_normal_length; static int default_lines_width; +public: + struct CursorScopeGuard + { + CursorScopeGuard(QCursor cursor) + { + QApplication::setOverrideCursor(cursor); + } + ~CursorScopeGuard() + { + QApplication::restoreOverrideCursor(); + } + }; }; } } diff --git a/Triangulation/examples/Triangulation/delaunay_triangulation.cpp b/Triangulation/examples/Triangulation/delaunay_triangulation.cpp index 036c0de6d50..f9db18d22c0 100644 --- a/Triangulation/examples/Triangulation/delaunay_triangulation.cpp +++ b/Triangulation/examples/Triangulation/delaunay_triangulation.cpp @@ -1,4 +1,5 @@ -#if defined(__GNUC__) && defined(__GNUC_MINOR__) && (__GNUC__ <= 4) && (__GNUC_MINOR__ < 4) +#include +#if defined(BOOST_GCC) && (__GNUC__ <= 4) && (__GNUC_MINOR__ < 4) #include int main() diff --git a/Triangulation/examples/Triangulation/triangulation.cpp b/Triangulation/examples/Triangulation/triangulation.cpp index 043c3cd38f6..06420697921 100644 --- a/Triangulation/examples/Triangulation/triangulation.cpp +++ b/Triangulation/examples/Triangulation/triangulation.cpp @@ -1,5 +1,5 @@ -#if defined(__GNUC__) && defined(__GNUC_MINOR__) && (__GNUC__ <= 4) && (__GNUC_MINOR__ < 4) - +#include +#if defined(BOOST_GCC) && (__GNUC__ <= 4) && (__GNUC_MINOR__ < 4) #include int main() { diff --git a/Triangulation/test/Triangulation/test_delaunay.cpp b/Triangulation/test/Triangulation/test_delaunay.cpp index a8e5ca5b761..8ba85a3d84d 100644 --- a/Triangulation/test/Triangulation/test_delaunay.cpp +++ b/Triangulation/test/Triangulation/test_delaunay.cpp @@ -1,4 +1,5 @@ -#if defined(__GNUC__) && defined(__GNUC_MINOR__) && (__GNUC__ <= 4) && (__GNUC_MINOR__ < 4) +#include +#if defined(BOOST_GCC) && (__GNUC__ <= 4) && (__GNUC_MINOR__ < 4) #include int main() diff --git a/Triangulation/test/Triangulation/test_torture.cpp b/Triangulation/test/Triangulation/test_torture.cpp index f85047f2293..72cefb83552 100644 --- a/Triangulation/test/Triangulation/test_torture.cpp +++ b/Triangulation/test/Triangulation/test_torture.cpp @@ -1,4 +1,5 @@ -#if defined(__GNUC__) && defined(__GNUC_MINOR__) && (__GNUC__ <= 4) && (__GNUC_MINOR__ < 4) +#include +#if defined(BOOST_GCC) && (__GNUC__ <= 4) && (__GNUC_MINOR__ < 4) #include int main() diff --git a/Triangulation/test/Triangulation/test_triangulation.cpp b/Triangulation/test/Triangulation/test_triangulation.cpp index 308b3f10c7d..1f9a8b5c8a2 100644 --- a/Triangulation/test/Triangulation/test_triangulation.cpp +++ b/Triangulation/test/Triangulation/test_triangulation.cpp @@ -1,5 +1,5 @@ -#if defined(__GNUC__) && defined(__GNUC_MINOR__) && (__GNUC__ <= 4) && (__GNUC_MINOR__ < 4) - +#include +#if defined(BOOST_GCC) && (__GNUC__ <= 4) && (__GNUC_MINOR__ < 4) #include int main() { @@ -7,7 +7,6 @@ int main() } #else - #include #include #include diff --git a/Triangulation_2/include/CGAL/Delaunay_triangulation_2.h b/Triangulation_2/include/CGAL/Delaunay_triangulation_2.h index 4e127cfc2ba..7540cf54b61 100644 --- a/Triangulation_2/include/CGAL/Delaunay_triangulation_2.h +++ b/Triangulation_2/include/CGAL/Delaunay_triangulation_2.h @@ -504,8 +504,11 @@ private: } else { *(pit.first)++ = fn; int j = fn->index(fh); - stack.push(std::make_pair(fn,ccw(j))); + + // In the non-recursive version, we walk via 'ccw(j)' first. Here, we are filling the stack + // and the order is thus the opposite (we want the top element of the stack to be 'ccw(j)') stack.push(std::make_pair(fn,cw(j))); + stack.push(std::make_pair(fn,ccw(j))); } } return pit; diff --git a/Triangulation_2/test/Triangulation_2/data/layers.xy b/Triangulation_2/test/Triangulation_2/data/layers.xy new file mode 100644 index 00000000000..1207d7eeb95 --- /dev/null +++ b/Triangulation_2/test/Triangulation_2/data/layers.xy @@ -0,0 +1,502 @@ +10 0 +10 0.01 +10 0.02 +10 0.029999999999999999 +10 0.040000000000000001 +10 0.050000000000000003 +10 0.059999999999999998 +10 0.070000000000000007 +10 0.080000000000000002 +10 0.089999999999999997 +10 0.10000000000000001 +10 0.11 +10 0.12 +10 0.13 +10 0.14000000000000001 +10 0.14999999999999999 +10 0.16 +10 0.17000000000000001 +10 0.17999999999999999 +10 0.19 +10 0.20000000000000001 +10 0.20999999999999999 +10 0.22 +10 0.23000000000000001 +10 0.23999999999999999 +10 0.25 +10 0.26000000000000001 +10 0.27000000000000002 +10 0.28000000000000003 +10 0.28999999999999998 +10 0.29999999999999999 +10 0.31 +10 0.32000000000000001 +10 0.33000000000000002 +10 0.34000000000000002 +10 0.34999999999999998 +10 0.35999999999999999 +10 0.37 +10 0.38 +10 0.39000000000000001 +10 0.40000000000000002 +10 0.40999999999999998 +10 0.41999999999999998 +10 0.42999999999999999 +10 0.44 +10 0.45000000000000001 +10 0.46000000000000002 +10 0.46999999999999997 +10 0.47999999999999998 +10 0.48999999999999999 +10 0.5 +10 0.51000000000000001 +10 0.52000000000000002 +10 0.53000000000000003 +10 0.54000000000000004 +10 0.55000000000000004 +10 0.56000000000000005 +10 0.56999999999999995 +10 0.57999999999999996 +10 0.58999999999999997 +10 0.59999999999999998 +10 0.60999999999999999 +10 0.62 +10 0.63 +10 0.64000000000000001 +10 0.65000000000000002 +10 0.66000000000000003 +10 0.67000000000000004 +10 0.68000000000000005 +10 0.68999999999999995 +10 0.69999999999999996 +10 0.70999999999999996 +10 0.71999999999999997 +10 0.72999999999999998 +10 0.73999999999999999 +10 0.75 +10 0.76000000000000001 +10 0.77000000000000002 +10 0.78000000000000003 +10 0.79000000000000004 +10 0.80000000000000004 +10 0.81000000000000005 +10 0.81999999999999995 +10 0.82999999999999996 +10 0.83999999999999997 +10 0.84999999999999998 +10 0.85999999999999999 +10 0.87 +10 0.88 +10 0.89000000000000001 +10 0.90000000000000002 +10 0.91000000000000003 +10 0.92000000000000004 +10 0.93000000000000005 +10 0.93999999999999995 +10 0.94999999999999996 +10 0.95999999999999996 +10 0.96999999999999997 +10 0.97999999999999998 +10 0.98999999999999999 +10 1 +10 1.01 +10 1.02 +10 1.03 +10 1.04 +10 1.05 +10 1.0600000000000001 +10 1.0700000000000001 +10 1.0800000000000001 +10 1.0900000000000001 +10 1.1000000000000001 +10 1.1100000000000001 +10 1.1200000000000001 +10 1.1299999999999999 +10 1.1399999999999999 +10 1.1499999999999999 +10 1.1599999999999999 +10 1.1699999999999999 +10 1.1799999999999999 +10 1.1899999999999999 +10 1.2 +10 1.21 +10 1.22 +10 1.23 +10 1.24 +10 1.25 +10 1.26 +10 1.27 +10 1.28 +10 1.29 +10 1.3 +10 1.3100000000000001 +10 1.3200000000000001 +10 1.3300000000000001 +10 1.3400000000000001 +10 1.3500000000000001 +10 1.3600000000000001 +10 1.3700000000000001 +10 1.3799999999999999 +10 1.3899999999999999 +10 1.3999999999999999 +10 1.4099999999999999 +10 1.4199999999999999 +10 1.4299999999999999 +10 1.4399999999999999 +10 1.45 +10 1.46 +10 1.47 +10 1.48 +10 1.49 +10 1.5 +10 1.51 +10 1.52 +10 1.53 +10 1.54 +10 1.55 +10 1.5600000000000001 +10 1.5700000000000001 +10 1.5800000000000001 +10 1.5900000000000001 +10 1.6000000000000001 +10 1.6100000000000001 +10 1.6200000000000001 +10 1.6299999999999999 +10 1.6399999999999999 +10 1.6499999999999999 +10 1.6599999999999999 +10 1.6699999999999999 +10 1.6799999999999999 +10 1.6899999999999999 +10 1.7 +10 1.71 +10 1.72 +10 1.73 +10 1.74 +10 1.75 +10 1.76 +10 1.77 +10 1.78 +10 1.79 +10 1.8 +10 1.8100000000000001 +10 1.8200000000000001 +10 1.8300000000000001 +10 1.8400000000000001 +10 1.8500000000000001 +10 1.8600000000000001 +10 1.8700000000000001 +10 1.8799999999999999 +10 1.8899999999999999 +10 1.8999999999999999 +10 1.9099999999999999 +10 1.9199999999999999 +10 1.9299999999999999 +10 1.9399999999999999 +10 1.95 +10 1.96 +10 1.97 +10 1.98 +10 1.99 +10 2 +10 2.0099999999999998 +10 2.02 +10 2.0299999999999998 +10 2.04 +10 2.0499999999999998 +10 2.0600000000000001 +10 2.0699999999999998 +10 2.0800000000000001 +10 2.0899999999999999 +10 2.1000000000000001 +10 2.1099999999999999 +10 2.1200000000000001 +10 2.1299999999999999 +10 2.1400000000000001 +10 2.1499999999999999 +10 2.1600000000000001 +10 2.1699999999999999 +10 2.1800000000000002 +10 2.1899999999999999 +10 2.2000000000000002 +10 2.21 +10 2.2200000000000002 +10 2.23 +10 2.2400000000000002 +10 2.25 +10 2.2599999999999998 +10 2.27 +10 2.2799999999999998 +10 2.29 +10 2.2999999999999998 +10 2.3100000000000001 +10 2.3199999999999998 +10 2.3300000000000001 +10 2.3399999999999999 +10 2.3500000000000001 +10 2.3599999999999999 +10 2.3700000000000001 +10 2.3799999999999999 +10 2.3900000000000001 +10 2.3999999999999999 +10 2.4100000000000001 +10 2.4199999999999999 +10 2.4300000000000002 +10 2.4399999999999999 +10 2.4500000000000002 +10 2.46 +10 2.4700000000000002 +10 2.48 +10 2.4900000000000002 +10 2.5 +20 0 +20 0.01 +20 0.02 +20 0.029999999999999999 +20 0.040000000000000001 +20 0.050000000000000003 +20 0.059999999999999998 +20 0.070000000000000007 +20 0.080000000000000002 +20 0.089999999999999997 +20 0.10000000000000001 +20 0.11 +20 0.12 +20 0.13 +20 0.14000000000000001 +20 0.14999999999999999 +20 0.16 +20 0.17000000000000001 +20 0.17999999999999999 +20 0.19 +20 0.20000000000000001 +20 0.20999999999999999 +20 0.22 +20 0.23000000000000001 +20 0.23999999999999999 +20 0.25 +20 0.26000000000000001 +20 0.27000000000000002 +20 0.28000000000000003 +20 0.28999999999999998 +20 0.29999999999999999 +20 0.31 +20 0.32000000000000001 +20 0.33000000000000002 +20 0.34000000000000002 +20 0.34999999999999998 +20 0.35999999999999999 +20 0.37 +20 0.38 +20 0.39000000000000001 +20 0.40000000000000002 +20 0.40999999999999998 +20 0.41999999999999998 +20 0.42999999999999999 +20 0.44 +20 0.45000000000000001 +20 0.46000000000000002 +20 0.46999999999999997 +20 0.47999999999999998 +20 0.48999999999999999 +20 0.5 +20 0.51000000000000001 +20 0.52000000000000002 +20 0.53000000000000003 +20 0.54000000000000004 +20 0.55000000000000004 +20 0.56000000000000005 +20 0.56999999999999995 +20 0.57999999999999996 +20 0.58999999999999997 +20 0.59999999999999998 +20 0.60999999999999999 +20 0.62 +20 0.63 +20 0.64000000000000001 +20 0.65000000000000002 +20 0.66000000000000003 +20 0.67000000000000004 +20 0.68000000000000005 +20 0.68999999999999995 +20 0.69999999999999996 +20 0.70999999999999996 +20 0.71999999999999997 +20 0.72999999999999998 +20 0.73999999999999999 +20 0.75 +20 0.76000000000000001 +20 0.77000000000000002 +20 0.78000000000000003 +20 0.79000000000000004 +20 0.80000000000000004 +20 0.81000000000000005 +20 0.81999999999999995 +20 0.82999999999999996 +20 0.83999999999999997 +20 0.84999999999999998 +20 0.85999999999999999 +20 0.87 +20 0.88 +20 0.89000000000000001 +20 0.90000000000000002 +20 0.91000000000000003 +20 0.92000000000000004 +20 0.93000000000000005 +20 0.93999999999999995 +20 0.94999999999999996 +20 0.95999999999999996 +20 0.96999999999999997 +20 0.97999999999999998 +20 0.98999999999999999 +20 1 +20 1.01 +20 1.02 +20 1.03 +20 1.04 +20 1.05 +20 1.0600000000000001 +20 1.0700000000000001 +20 1.0800000000000001 +20 1.0900000000000001 +20 1.1000000000000001 +20 1.1100000000000001 +20 1.1200000000000001 +20 1.1299999999999999 +20 1.1399999999999999 +20 1.1499999999999999 +20 1.1599999999999999 +20 1.1699999999999999 +20 1.1799999999999999 +20 1.1899999999999999 +20 1.2 +20 1.21 +20 1.22 +20 1.23 +20 1.24 +20 1.25 +20 1.26 +20 1.27 +20 1.28 +20 1.29 +20 1.3 +20 1.3100000000000001 +20 1.3200000000000001 +20 1.3300000000000001 +20 1.3400000000000001 +20 1.3500000000000001 +20 1.3600000000000001 +20 1.3700000000000001 +20 1.3799999999999999 +20 1.3899999999999999 +20 1.3999999999999999 +20 1.4099999999999999 +20 1.4199999999999999 +20 1.4299999999999999 +20 1.4399999999999999 +20 1.45 +20 1.46 +20 1.47 +20 1.48 +20 1.49 +20 1.5 +20 1.51 +20 1.52 +20 1.53 +20 1.54 +20 1.55 +20 1.5600000000000001 +20 1.5700000000000001 +20 1.5800000000000001 +20 1.5900000000000001 +20 1.6000000000000001 +20 1.6100000000000001 +20 1.6200000000000001 +20 1.6299999999999999 +20 1.6399999999999999 +20 1.6499999999999999 +20 1.6599999999999999 +20 1.6699999999999999 +20 1.6799999999999999 +20 1.6899999999999999 +20 1.7 +20 1.71 +20 1.72 +20 1.73 +20 1.74 +20 1.75 +20 1.76 +20 1.77 +20 1.78 +20 1.79 +20 1.8 +20 1.8100000000000001 +20 1.8200000000000001 +20 1.8300000000000001 +20 1.8400000000000001 +20 1.8500000000000001 +20 1.8600000000000001 +20 1.8700000000000001 +20 1.8799999999999999 +20 1.8899999999999999 +20 1.8999999999999999 +20 1.9099999999999999 +20 1.9199999999999999 +20 1.9299999999999999 +20 1.9399999999999999 +20 1.95 +20 1.96 +20 1.97 +20 1.98 +20 1.99 +20 2 +20 2.0099999999999998 +20 2.02 +20 2.0299999999999998 +20 2.04 +20 2.0499999999999998 +20 2.0600000000000001 +20 2.0699999999999998 +20 2.0800000000000001 +20 2.0899999999999999 +20 2.1000000000000001 +20 2.1099999999999999 +20 2.1200000000000001 +20 2.1299999999999999 +20 2.1400000000000001 +20 2.1499999999999999 +20 2.1600000000000001 +20 2.1699999999999999 +20 2.1800000000000002 +20 2.1899999999999999 +20 2.2000000000000002 +20 2.21 +20 2.2200000000000002 +20 2.23 +20 2.2400000000000002 +20 2.25 +20 2.2599999999999998 +20 2.27 +20 2.2799999999999998 +20 2.29 +20 2.2999999999999998 +20 2.3100000000000001 +20 2.3199999999999998 +20 2.3300000000000001 +20 2.3399999999999999 +20 2.3500000000000001 +20 2.3599999999999999 +20 2.3700000000000001 +20 2.3799999999999999 +20 2.3900000000000001 +20 2.3999999999999999 +20 2.4100000000000001 +20 2.4199999999999999 +20 2.4300000000000002 +20 2.4399999999999999 +20 2.4500000000000002 +20 2.46 +20 2.4700000000000002 +20 2.48 +20 2.4900000000000002 +20 2.5 diff --git a/Triangulation_2/test/Triangulation_2/include/CGAL/_test_cls_delaunay_triangulation_2.h b/Triangulation_2/test/Triangulation_2/include/CGAL/_test_cls_delaunay_triangulation_2.h index 97419a8cc71..2204331cfe8 100644 --- a/Triangulation_2/test/Triangulation_2/include/CGAL/_test_cls_delaunay_triangulation_2.h +++ b/Triangulation_2/test/Triangulation_2/include/CGAL/_test_cls_delaunay_triangulation_2.h @@ -20,20 +20,21 @@ // coordinator : INRIA Sophia-Antipolis // ============================================================================ -#include -#include -//#include #include +#include +#include +#include +#include +#include #include -using std::rand; +using std::rand; template void _test_delaunay_duality( const Del &T ); - template void _test_cls_delaunay_triangulation_2( const Del & ) @@ -136,14 +137,58 @@ _test_cls_delaunay_triangulation_2( const Del & ) // test insertion through get_conflicts + star_hole conflicts.clear(); hole_bd.clear(); - T2.get_conflicts_and_boundary(Point(1,1,2), - std::back_inserter(conflicts), - std::back_inserter(hole_bd)); + Point query(1,1,2); + T2.get_conflicts_and_boundary(query, + std::back_inserter(conflicts), + std::back_inserter(hole_bd)); + + // check the sanity of the boundary (faces are not in conflict && edges are ccw ordered) + typename std::list::iterator curr = hole_bd.begin(), last = --(hole_bd.end()); + Vertex_handle prev_vh = last->first->vertex(T2.ccw(last->second)); + do + { + assert(curr->first->vertex(T2.cw(curr->second)) == prev_vh); + assert(!T2.test_conflict(query, curr->first)); + prev_vh = curr->first->vertex(T2.ccw(curr->second)); + ++curr; + } + while(curr != hole_bd.end()); + T2.star_hole (Point(1,1,2), hole_bd.begin(), hole_bd.end(), conflicts.begin(), conflicts.end() ); assert(T2.is_valid()); - + + // check get_conflict for a large enough point set (to use the non-recursive function) + double x, y; + std::vector layer_pts; + + std::ifstream in("data/layers.xy"); + assert(in); + while(in >> x >> y) + layer_pts.push_back(Point(x, y)); + + Del T2b(layer_pts.begin(), layer_pts.end()); + + conflicts.clear(); + hole_bd.clear(); + + query = Point(12.25, 0.031250); + T2b.get_conflicts_and_boundary(query, + std::back_inserter(conflicts), + std::back_inserter(hole_bd)); + + // check the sanity of the boundary (faces are not in conflict && edges are ccw ordered) + curr = hole_bd.begin(), last = --(hole_bd.end()); + prev_vh = last->first->vertex(T2b.ccw(last->second)); + do + { + assert(curr->first->vertex(T2b.cw(curr->second)) == prev_vh); + assert(!T2b.test_conflict(query, curr->first)); + prev_vh = curr->first->vertex(T2b.ccw(curr->second)); + ++curr; + } + while(curr != hole_bd.end()); /********************/ /***** Duality ******/