initial commit

This commit is contained in:
Jensen committed 2024-11-26 09:25:23 -07:00
1 parent 9d32f6a917
commit aa4290ceef
19 files changed
+33101

No files matched your search

+53
View File
@@ -0,0 +1,53 @@
devel/
logs/
build/
bin/
lib/
msg_gen/
srv_gen/
msg/*Action.msg
msg/*ActionFeedback.msg
msg/*ActionGoal.msg
msg/*ActionResult.msg
msg/*Feedback.msg
msg/*Goal.msg
msg/*Result.msg
msg/_*.py
build_isolated/
devel_isolated/
# Generated by dynamic reconfigure
*.cfgc
/cfg/cpp/
/cfg/*.py
# Ignore generated docs
*.dox
*.wikidoc
# eclipse stuff
.project
.cproject
# qcreator stuff
CMakeLists.txt.user
srv/_*.py
*.pcd
*.pyc
qtcreator-*
*.user
/planning/cfg
/planning/docs
/planning/src
*~
# Emacs
.#*
# Catkin custom files
CATKIN_IGNORE
Eigen
+60
View File
@@ -0,0 +1,60 @@
cmake_minimum_required(VERSION 3.8)
project(aerial_inspection_planner)
# Default to C++14
# if(NOT CMAKE_CXX_STANDARD)
# set(CMAKE_CXX_STANDARD 14)
# endif()
if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
add_compile_options(-Wall -Wextra -Wpedantic)
endif()
# Set the path to the OR-Tools directory. **Update file path if located elsewhere**
set(ORTOOLS_DIR "/or-tools_x86_64_Ubuntu-22.04_cpp_v9.10.4067")
set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} ${ORTOOLS_DIR})
include_directories(${ORTOOLS_DIR}/include)
link_directories(${ORTOOLS_DIR}/lib)
# Find dependencies
find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)
find_package(std_msgs REQUIRED)
find_package(nav_msgs REQUIRED)
find_package(visualization_msgs REQUIRED)
find_package(Eigen3 REQUIRED)
find_package(Protobuf REQUIRED)
add_executable(cpp_planner src/cpp_planner.cpp src/bvh.cpp src/mesh_utils.cpp)
ament_target_dependencies(cpp_planner rclcpp std_msgs nav_msgs visualization_msgs Eigen3)
target_link_libraries(cpp_planner ortools protobuf::libprotobuf)
target_include_directories(cpp_planner PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
${ORTOOLS_DIR}/include
${EIGEN3_INCLUDE_DIR}
$<INSTALL_INTERFACE:include>)
target_compile_features(cpp_planner PUBLIC c_std_99 cxx_std_17) # Require C99 and C++17
install(TARGETS
cpp_planner
DESTINATION lib/${PROJECT_NAME})
install(DIRECTORY
data
launch
config
DESTINATION share/${PROJECT_NAME})
if(BUILD_TESTING)
find_package(ament_cmake_gtest REQUIRED)
ament_add_gtest(${PROJECT_NAME}_test test/planner_test.cpp src/mesh_utils.cpp)
target_include_directories(${PROJECT_NAME}_test PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
${EIGEN3_INCLUDE_DIR}
$<INSTALL_INTERFACE:include>
)
ament_target_dependencies(${PROJECT_NAME}_test rclcpp std_msgs nav_msgs visualization_msgs Eigen3)
target_link_libraries(${PROJECT_NAME}_test ortools protobuf::libprotobuf)
endif()
ament_package()
+98
View File
@@ -0,0 +1,98 @@
# Aerial Inspection Planners
This repo contains methods for 3D inspection using aerial vehicles.
![Example image](data/example.png)
## Workspace setup
Pull this code into a ROS workspace. The directory structure should look something like `inspection_ws/src/aerial_inspection_planners`.
For example:
```sh
mkdir -p inspection_ws/src
cd inspection_ws/src
git clone <repo_address> (or copy the repo folder to here)
```
## Using Docker
If you would like to build and run everything in Docker, follow the instructions in `docker/notes.md`. Otherwise, the stack was built using Ubuntu 22.04 with ROS Humble.
## Building
Navigate to the workspace directory and run
```sh
colcon build --symlink-install --cmake-args -DCMAKE_BUILD_TYPE=Release
```
If using Docker, you may need to first source ROS2 with `source /opt/ros/humble/setup.bash`.
## Launching package
Source and launch the package with
```sh
source install/setup.bash
ros2 launch aerial_inspection_planner cpp_planner_launch.py
```
You should see an RViz window pop up and visualize the mesh, viewpoints, and the final plan.
## Configuration
In RViz you can configure what you want to visualize. There are various mesh visualizations that show how many viewpoints can view each surface of the mesh. You can also visualize all of the sample viewpoints, how many mesh surfaces each viewpoint sees, and which viewpoints are selected for the final path.
You can find all of the planner parameters in `config/cpp_planner.yaml`.
The parameters include
* `visualize_mesh`: Boolean on if you want to publish the visualization messages. Default is true;
* `mesh_name`: The name of the mesh file to use. Expected to be located in the `data/meshes` folder.
* `distance_from_surface`: The distance from the surface for created viewpoints
* `min_height`: The minimum distance to the ground for the planned path.
* `max_height`: The maximium height of the planned path.
* `min_distance`: The minimum distance to a surface for a planned path.
* `min_view_redundancy`: The minimum number of views wanted for every surface.
* `max_incidence_angle`: The maximum incidence angle of a viewpoint to a surface for it to be counted as viewed.
* `max_view_distance`: The maximum distance of a viewpoint to a surface for it to be counted as viewed.
* `camera_half_fov`: The camera field of view divided by two.
* `planner_type`: Options are greedy (recommended) and iterative.
* `tsp_method`: Options are greedy, hc, sa, bnb, and ortools (recommended).
* `tsp_solver_allowed_time`: Allowed time for the tsp solver. Used by hc, sa, bnb, and ortools.
* `rviz_scale`: Scales the rviz visualizations.
* `export_to_yaml`: Boolean to export the final trajectory to yaml or not.
## ROS2 Tips, Tricks, and Notes
Build options
```sh
colcon build --symlink-install --packages-select aerial_inspection_planner --event-handlers console_direct+
colcon build --symlink-install --cmake-args -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DCMAKE_BUILD_TYPE=RelWithDebInfo
colcon test
colcon test-results --verbose
ros2 run --prefix 'gdb -ex run --args' aerial_inspection_planner cpp_planner
```
Set just cpp_planner to debug
```sh
ros2 run aerial_inspection_planner cpp_planner --ros-args --log-level cpp_planner:=DEBUG
```
Sets all to debug, run one of the following
```sh
ros2 run aerial_inspection_planner cpp_planner --ros-args --log-level debug
ros2 launch aerial_inpsection_planner cpp_planner log_level:=debug
```
To build for debugging
```sh
colcon build --cmake-args -DCMAKE_BUILD_TYPE=RelWithDebInfo
colcon build --symlink-install --cmake-args -DCMAKE_BUILD_TYPE=Debug
```
To modify the console outpute
`export RCUTILS_COLORIZED_OUTPUT=1`
`export RCUTILS_CONSOLE_OUTPUT_FORMAT="[{severity}] [{name}]: {message}"`
`export RCUTILS_CONSOLE_OUTPUT_FORMAT="[{severity}] [{time}] [{name}]: {message}"`
`export RCUTILS_CONSOLE_OUTPUT_FORMAT="[{severity} {time}] [{name}]: {message} ({function_name}() at {file_name}:{line_number})"`
rosdep install -i --from-path src --rosdistro humble -y
+219
View File
@@ -0,0 +1,219 @@
Panels:
- Class: rviz_common/Displays
Help Height: 78
Name: Displays
Property Tree Widget:
Expanded: ~
Splitter Ratio: 0.5764706134796143
Tree Height: 571
- Class: rviz_common/Selection
Name: Selection
- Class: rviz_common/Tool Properties
Expanded:
- /2D Goal Pose1
- /Publish Point1
Name: Tool Properties
Splitter Ratio: 0.5886790156364441
- Class: rviz_common/Views
Expanded:
- /Current View1
Name: Views
Splitter Ratio: 0.5
- Class: rviz_common/Time
Experimental: false
Name: Time
SyncMode: 0
SyncSource: ""
Visualization Manager:
Class: ""
Displays:
- Alpha: 0.5
Cell Size: 1
Class: rviz_default_plugins/Grid
Color: 160; 160; 164
Enabled: true
Line Style:
Line Width: 0.029999999329447746
Value: Lines
Name: Grid
Normal Cell Count: 0
Offset:
X: 0
Y: 0
Z: 0
Plane: XY
Plane Cell Count: 10
Reference Frame: <Fixed Frame>
Value: true
- Class: rviz_default_plugins/Marker
Enabled: true
Name: Mesh
Namespaces:
{}
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /visualization_mesh
Value: true
- Class: rviz_default_plugins/MarkerArray
Enabled: false
Name: All Viewpoints
Namespaces:
{}
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /all_vps
Value: false
- Class: rviz_default_plugins/Marker
Enabled: false
Name: Mesh colored as Num Views
Namespaces:
{}
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /visualization_mesh_colored_as_views
Value: false
- Class: rviz_default_plugins/MarkerArray
Enabled: false
Name: VP Colored with Redundancy
Namespaces:
{}
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /all_vps_redundancy
Value: false
- Class: rviz_default_plugins/Marker
Enabled: true
Name: Mesh After Trim
Namespaces:
cpp_planner: true
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /visualization_mesh_colored_as_views_after_trimmed
Value: true
- Class: rviz_default_plugins/MarkerArray
Enabled: true
Name: Viewpoints after Trim
Namespaces:
cpp_planner: true
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /visualize_vps_after_trimmed
Value: true
- Class: rviz_default_plugins/Marker
Enabled: true
Name: Final Path
Namespaces:
{}
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /visualization_final_path
Value: true
Enabled: true
Global Options:
Background Color: 48; 48; 48
Fixed Frame: map
Frame Rate: 30
Name: root
Tools:
- Class: rviz_default_plugins/Interact
Hide Inactive Objects: true
- Class: rviz_default_plugins/MoveCamera
- Class: rviz_default_plugins/Select
- Class: rviz_default_plugins/FocusCamera
- Class: rviz_default_plugins/Measure
Line color: 128; 128; 0
- Class: rviz_default_plugins/SetInitialPose
Covariance x: 0.25
Covariance y: 0.25
Covariance yaw: 0.06853891909122467
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /initialpose
- Class: rviz_default_plugins/SetGoal
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /goal_pose
- Class: rviz_default_plugins/PublishPoint
Single click: true
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /clicked_point
Transformation:
Current:
Class: rviz_default_plugins/TF
Value: true
Views:
Current:
Class: rviz_default_plugins/Orbit
Distance: 116.85099029541016
Enable Stereo Rendering:
Stereo Eye Separation: 0.05999999865889549
Stereo Focal Distance: 1
Swap Stereo Eyes: false
Value: false
Focal Point:
X: 3.692190647125244
Y: 5.024622440338135
Z: 2.43805193901062
Focal Shape Fixed Size: true
Focal Shape Size: 0.05000000074505806
Invert Z Axis: false
Name: Current View
Near Clip Distance: 0.009999999776482582
Pitch: 0.5703979134559631
Target Frame: <Fixed Frame>
Value: Orbit (rviz)
Yaw: 5.058587551116943
Saved: ~
Window Geometry:
Displays:
collapsed: false
Height: 862
Hide Left Dock: false
Hide Right Dock: true
QMainWindow State: 000000ff00000000fd000000040000000000000156000002c4fc0200000008fb0000001200530065006c0065006300740069006f006e00000001e10000009b0000005c00fffffffb0000001e0054006f006f006c002000500072006f007000650072007400690065007302000001ed000001df00000185000000a3fb000000120056006900650077007300200054006f006f02000001df000002110000018500000122fb000000200054006f006f006c002000500072006f0070006500720074006900650073003203000002880000011d000002210000017afb000000100044006900730070006c006100790073010000003b000002c4000000c700fffffffb0000002000730065006c0065006300740069006f006e00200062007500660066006500720200000138000000aa0000023a00000294fb00000014005700690064006500530074006500720065006f02000000e6000000d2000003ee0000030bfb0000000c004b0069006e0065006300740200000186000001060000030c00000261000000010000010f000002b4fc0200000003fb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000041000000780000000000000000fb0000000a00560069006500770073000000003b000002b4000000a000fffffffb0000001200530065006c0065006300740069006f006e010000025a000000b200000000000000000000000200000490000000a9fc0100000001fb0000000a00560069006500770073030000004e00000080000002e10000019700000003000004b00000003efc0100000002fb0000000800540069006d00650100000000000004b00000025300fffffffb0000000800540069006d0065010000000000000450000000000000000000000354000002c400000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000
Selection:
collapsed: false
Time:
collapsed: false
Tool Properties:
collapsed: false
Views:
collapsed: true
Width: 1200
X: 194
Y: 1138
+53
View File
@@ -0,0 +1,53 @@
# cargo_decimate
/cpp_planner:
ros__parameters:
visualize_mesh: true
mesh_name: "cargo_decimate" # cargo_decimate, f4
distance_from_surface: 4.0
min_height: -9999.0
max_height: 9999.0
min_view_redundancy: 2
max_incidence_angle: 50.0
max_view_distance: 10.0
min_distance: 1.5
camera_half_fov: 55.0
planner_type: greedy
tsp_method: ortools # bnb, greedy, hc (recommended), sa, ortools
tsp_solver_allowed_time: 5.0 # used by bnb, hc, sa
rviz_scale: 1.0
export_to_yaml: false
# # f4
# /cpp_planner:
# ros__parameters:
# visualize_mesh: true
# mesh_name: "f4" # cargo_decimate, f4
# distance_from_surface: 2.0
# min_view_redundancy: 2
# max_incidence_angle: 25.0
# max_view_distance: 4.0
# min_distance: 1.0
# camera_half_fov: 55.0
# planner_type: greedy
# tsp_method: ortools # bnb, greedy, hc (recommended), sa, ortools
# tsp_solver_allowed_time: 10.0 # used by bnb, hc, sa
# rviz_scale: 0.25
# mocap
# /cpp_planner:
# ros__parameters:
# visualize_mesh: true
# mesh_name: "mocap" # cargo_decimate, f4
# distance_from_surface: 1.5
# min_height: 0.5 # could go to 0.5
# max_height: 3.0
# min_view_redundancy: 1
# max_incidence_angle: 20.0
# max_view_distance: 2.0
# min_distance: 0.75
# camera_half_fov: 25.0
# planner_type: greedy
# tsp_method: ortools # bnb, greedy, hc (recommended), sa, ortools
# tsp_solver_allowed_time: 6.0 # used by bnb, hc, sa
# rviz_scale: 0.15
# export_to_yaml: true
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

+30648
View File
File diff suppressed because it is too large. Load diff
+16
View File
@@ -0,0 +1,16 @@
FROM ros:humble
# Enable Nvidia Driver Capabilities
ENV NVIDIA_VISIBLE_DEVICES all
ENV NVIDIA_DRIVER_CAPABILITIES compute,utility,display
RUN apt-get update
RUN apt-get install vim libeigen3-dev wget ros-humble-rviz2 -y
RUN wget https://github.com/google/or-tools/releases/download/v9.10/or-tools_amd64_ubuntu-22.04_cpp_v9.10.4067.tar.gz
RUN tar -xvzf or-tools_amd64_ubuntu-22.04_cpp_v9.10.4067.tar.gz
RUN rm or-tools_amd64_ubuntu-22.04_cpp_v9.10.4067.tar.gz
WORKDIR /or-tools_x86_64_Ubuntu-22.04_cpp_v9.10.4067
RUN make test
WORKDIR /inspection_ws
+52
View File
@@ -0,0 +1,52 @@
## Docker for Aerial Inspection Planners
**Note: If you did not get this code from the Sandia GitLab, will need to use the external.Dockerfile as the default Dockerfile includes the necessary proxies and certificates for Sandia use.**
### To Build Docker Image
Run in the docker folder
```sh
docker build -t aerial-inspection .
```
### To run Docker container
Run one of the following commands **at the top of the workspace** so it is mounts the workspace correctly.
Ubuntu/WSL command:
```sh
docker run -it --rm \
--name aerial-inspection-docker \
--env="DISPLAY" \
--env="QT_X11_NO_MITSHM=1" \
--volume="/tmp/.X11-unix:/tmp/.X11-unix:rw" \
--mount type=bind,source="$(pwd)",target=/inspection_ws aerial-inspection
```
Windows command:
```sh
docker run -it --rm --name aerial-inspection-docker --env="DISPLAY" --env="QT_X11_NO_MITSHM=1" --volume="/tmp/.X11-unix:/tmp/.X11-unix:rw" --mount type=bind,source="$(pwd)",target=/inspection_ws aerial-inspection
```
## Getting RViz to show up
If you are on windows, I haven't figured out how to get rviz to show up. Sorry! If you are using WSL, then you should be good to go.
If on ubuntu, go to the next step for rviz to work.
To get the xhost to work on ubuntu
```sh
export containerId=$(docker ps -l -q)
xhost +local:`docker inspect --format='{{ .Config.Hostname }}' $containerId`
docker start $containerId
```
## Other
To join a running container:
```sh
docker exec -it aerial-inspection-docker /bin/bash
```
### If you want to develop in vscode
1. Start container
2. Join in vscode
3. Build code and launch package
Or can just not remove the container and start it up from vscode. You can do this by removing the `--rm` flag on the docker run command.
+37
View File
@@ -0,0 +1,37 @@
#pragma once
#include <Eigen/Dense>
#include <vector>
#include <array>
#include <algorithm>
#include <limits>
#include <cmath>
#include "aerial_inspection_planner/mesh_utils.hpp"
struct AABB {
Eigen::Vector3f min;
Eigen::Vector3f max;
};
struct BVHNode {
AABB boundingBox;
BVHNode* left;
BVHNode* right;
mesh_utils::Triangle* triangle;
};
class BVH
{
public:
private:
AABB computeBoundingBox(const mesh_utils::Triangle& triangle);
BVHNode* buildBVH(std::vector<mesh_utils::Triangle>& triangles, int start, int end);
};
@@ -0,0 +1,73 @@
#pragma once
#include <algorithm>
#include <Eigen/Dense>
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
#include "visualization_msgs/msg/marker.hpp"
#include "visualization_msgs/msg/marker_array.hpp"
#include "geometry_msgs/msg/polygon.hpp"
// #include "tsp_solvers/greedy.hpp"
// #include "tsp_solvers/bnb.hpp"
// #include "tsp_solvers/hill_climb.hpp"
// #include "tsp_solvers/simulation_annealing.hpp"
#include "aerial_inspection_planner/bvh.hpp"
#include "tsp_solvers/ortools.hpp"
class InspectionPlanner : public rclcpp::Node
{
public:
InspectionPlanner();
~InspectionPlanner(){
RCLCPP_INFO(this->get_logger(), "cpp_planner node destructor called");
}
void plan();
private:
rclcpp::TimerBase::SharedPtr timer_;
rclcpp::Publisher<visualization_msgs::msg::Marker>::SharedPtr mesh_publisher_;
rclcpp::Publisher<visualization_msgs::msg::Marker>::SharedPtr mesh_colored_as_views_;
rclcpp::Publisher<visualization_msgs::msg::Marker>::SharedPtr mesh_colored_as_views_after_trim_;
rclcpp::Publisher<visualization_msgs::msg::Marker>::SharedPtr final_path_visualization_;
rclcpp::Publisher<visualization_msgs::msg::MarkerArray>::SharedPtr all_vps_publisher_;
rclcpp::Publisher<visualization_msgs::msg::MarkerArray>::SharedPtr vps_redundancy_publisher_;
rclcpp::Publisher<visualization_msgs::msg::MarkerArray>::SharedPtr vps_after_trim_;
// Set by ros param config
bool visualize_mesh_;
double distance_from_surface_;
double min_height_;
double max_height_;
size_t min_view_redundancy_;
double max_incidence_angle_;
double max_view_distance_;
double min_distance_;
double camera_half_fov_;
std::string planner_type_;
std::string tsp_method_;
double tsp_solver_allowed_time_;
std::string mesh_name_;
double rviz_scale_;
bool export_to_yaml_;
std::unique_ptr<std::vector<mesh_utils::Triangle>> mesh; // triangle mesh
std::vector<Eigen::Vector3f> vp_positions;
std::vector<Eigen::Vector3f> vp_orientation_vec;
std::vector<Eigen::Vector3f> mesh_surface_normals;
std::vector<std::vector<int>> mesh_to_vp_map;
std::vector<std::vector<int>> vp_to_mesh_map;
std::vector<bool> vp_keep;
std::vector<int> final_path;
bool mesh_to_iterative_vps();
bool mesh_to_greedy_vps();
bool solve_tsp();
visualization_msgs::msg::Marker create_mesh_visualization_msg(bool color_as_redundancy);
visualization_msgs::msg::MarkerArray create_vps_visualization_msg(bool color_as_redundancy);
visualization_msgs::msg::Marker create_path_visualization_msg(bool color_as_progress);
void determine_visibility(bool save_mesh_to_vp_map);
bool create_vps_for_all_triangles();
bool is_collision(int vp_i, int vp_j) const;
bool is_collision(Eigen::Vector3f point) const;
void export_to_yaml();
};
@@ -0,0 +1,67 @@
#pragma once
#include <cstdlib>
#include <fstream>
#include <cfloat>
#include <Eigen/Dense>
#include "nav_msgs/msg/path.hpp"
#include "geometry_msgs/msg/polygon.hpp"
#include "rclcpp/rclcpp.hpp"
/**
* \brief This function reads an ACII STL file for inspection planning
From https://github.com/ethz-asl/StructuralInspectionPlanner
*/
namespace mesh_utils
{
struct Triangle {
std::array<Eigen::Vector3f, 3> vertices;
};
std::unique_ptr<std::vector<Triangle>> readSTLfile(std::string name, rclcpp::Logger logger_);
Eigen::Vector3f calculate_surface_normal(const Eigen::Vector3f& v0, const Eigen::Vector3f& v1, const Eigen::Vector3f& v2);
Eigen::Vector3f calculate_centroid(const Eigen::Vector3f& v0, const Eigen::Vector3f& v1, const Eigen::Vector3f& v2);
Eigen::Quaternionf vector_to_quaternion(const Eigen::Vector3f& unit_vector);
double vector_to_yaw(const Eigen::Vector3f& unit_vector);
// Function to compute the angle between two vectors in degrees
float angle_between_vectors(const Eigen::Vector3f& u, const Eigen::Vector3f& v);
/*
Checks
- Point within vp fov
- Point within incendent angle from surface normal
- Checks within max view distance
- Checks collisions TODO
*/
bool ray_views_point(const Eigen::Vector3f& vp_pose,
const Eigen::Vector3f& vp_orient,
const Eigen::Vector3f& ray_direction,
const Eigen::Vector3f& surface_normal,
const Eigen::Vector3f& point,
double& max_incidence_angle,
double& max_view_distance,
double& camera_half_fov);
// From embree library. Find the closest point between a point and a triangle
Eigen::Vector3f closest_point_to_triangle(Eigen::Vector3f const& p, const Triangle& triangle);
float point_to_triangle_distance(const Eigen::Vector3f& point, const mesh_utils::Triangle& triangle);
float closest_distance_between_segments(
const Eigen::Vector3f& a0, const Eigen::Vector3f& a1,
const Eigen::Vector3f& b0, const Eigen::Vector3f& b1);
float closest_distance_between_segments(
const Eigen::Vector3f& a0, const Eigen::Vector3f& a1,
const Eigen::Vector3f& b0, const Eigen::Vector3f& b1,
bool clampAll, bool clampA0, bool clampA1,
bool clampB0, bool clampB1);
}
+101
View File
@@ -0,0 +1,101 @@
// Derived from example https://developers.google.com/optimization/routing/tsp#c++
#include <cmath>
#include <cstdint>
#include <sstream>
#include <vector>
#include <rclcpp/rclcpp.hpp>
#include "ortools/constraint_solver/routing.h"
#include "ortools/constraint_solver/routing_enums.pb.h"
#include "ortools/constraint_solver/routing_index_manager.h"
#include "ortools/constraint_solver/routing_parameters.h"
namespace operations_research {
struct DataModel {
std::vector<std::vector<int>> distance_matrix;
const int num_vehicles = 1;
const RoutingIndexManager::NodeIndex depot{0};
};
//! @brief Print the solution.
//! @param[in] manager Index manager used.
//! @param[in] routing Routing solver used.
//! @param[in] solution Solution found by the solver.
void PrintSolution(const RoutingIndexManager& manager,
const RoutingModel& routing, const Assignment& solution,
rclcpp::Logger logger_) {
// Inspect solution.
RCLCPP_INFO_STREAM(logger_, "Objective: " << solution.ObjectiveValue() << " miles");
int64_t index = routing.Start(0);
RCLCPP_INFO_STREAM(logger_, "Route:");
int64_t distance{0};
std::stringstream route;
while (!routing.IsEnd(index)) {
route << manager.IndexToNode(index).value() << " -> ";
const int64_t previous_index = index;
index = solution.Value(routing.NextVar(index));
distance += routing.GetArcCostForVehicle(previous_index, index, int64_t{0});
}
// RCLCPP_INFO_STREAM(logger_, route.str() << manager.IndexToNode(index).value());
RCLCPP_INFO_STREAM(logger_, "Route cost: " << distance << " m");
// RCLCPP_INFO_STREAM(logger_, "");
// RCLCPP_INFO_STREAM(logger_, "Advanced usage:");
// RCLCPP_INFO_STREAM(logger_, "Problem solved in " << routing.solver()->wall_time() << "ms");
}
std::vector<int> Tsp(std::vector<std::vector<int>> &distance, double planning_time, rclcpp::Logger logger_) {
RCLCPP_INFO(logger_, "Starting the ortools tsp solver");
// Instantiate the data problem.
DataModel data;
data.distance_matrix = distance;
// Create Routing Index Manager
RoutingIndexManager manager(data.distance_matrix.size(), data.num_vehicles,
data.depot);
// Create Routing Model.
RoutingModel routing(manager);
const int transit_callback_index = routing.RegisterTransitCallback(
[&data, &manager](const int64_t from_index,
const int64_t to_index) -> int64_t {
// Convert from routing variable Index to distance matrix NodeIndex.
const int from_node = manager.IndexToNode(from_index).value();
const int to_node = manager.IndexToNode(to_index).value();
return data.distance_matrix[from_node][to_node];
});
// Define cost of each arc.
routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index);
// Setting first solution heuristic.
RoutingSearchParameters searchParameters = DefaultRoutingSearchParameters();
searchParameters.set_local_search_metaheuristic(
LocalSearchMetaheuristic::GUIDED_LOCAL_SEARCH);
// Other options https://developers.google.com/optimization/routing/routing_options#local_search_options
searchParameters.mutable_time_limit()->set_seconds(planning_time);
// searchParameters.set_log_search(true);
// searchParameters.set_first_solution_strategy(
// FirstSolutionStrategy::PATH_CHEAPEST_ARC);
// Solve the problem.
const Assignment* solution = routing.SolveWithParameters(searchParameters);
// Print solution on console.
PrintSolution(manager, routing, *solution, logger_);
std::vector<int> solution_order;
int64_t index = routing.Start(0);
while (!routing.IsEnd(index)) {
solution_order.push_back(manager.IndexToNode(index).value());
index = solution->Value(routing.NextVar(index));
}
return solution_order;
}
} // namespace operations_research
// int main(int /*argc*/, char* /*argv*/[]) {
// operations_research::Tsp();
// return EXIT_SUCCESS;
// }
+51
View File
@@ -0,0 +1,51 @@
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch_ros.actions import Node
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration, TextSubstitution
def generate_launch_description():
run_rviz = True
log_level_launch_arg = DeclareLaunchArgument(
'log_level', default_value='info'
)
config = os.path.join(
get_package_share_directory('aerial_inspection_planner'),
'config',
'cpp_planner.yaml'
)
planner_node = Node(
package='aerial_inspection_planner',
# namespace='',
executable='cpp_planner',
# name='',
# prefix=['valgrind --leak-check=full --track-origins=yes --show-leak-kinds=all'],
# prefix=['valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes --verbose'],
# prefix=["valgrind --tool=callgrind --callgrind-out-file='callgrind.listener.%p' "],
arguments=['--ros-args', '--log-level', LaunchConfiguration('log_level')],
parameters=[config])
rviz_node = Node(
package='rviz2',
namespace='',
executable='rviz2',
name='rviz2',
arguments=['-d' + os.path.join(
get_package_share_directory(
'aerial_inspection_planner'), 'config', 'config.rviz')]
)
ld = LaunchDescription([
log_level_launch_arg,
planner_node
])
if (run_rviz):
ld.add_entity(rviz_node)
return ld
+28
View File
@@ -0,0 +1,28 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>aerial_inspection_planner</name>
<version>0.0.0</version>
<description>This package contains planners for aerial inspection.</description>
<maintainer email="bgmoon@sandia.gov">root</maintainer>
<license>TODO: License declaration</license>
<buildtool_depend>ament_cmake</buildtool_depend>
<depend>rclcpp</depend>
<depend>std_msgs</depend>
<depend>visualization_msgs</depend>
<!-- <test_depend>ament_lint_auto</test_depend>
<test_depend>ament_lint_common</test_depend> -->
<test_depend>ament_cmake_gtest</test_depend>
<!-- <test_depend>ament_cmake_cppcheck</test_depend>
<test_depend>ament_cmake_uncrustify</test_depend>
<test_depend>ament_cmake_cpplint</test_depend> -->
<exec_depend>ros2launch</exec_depend>
<export>
<build_type>ament_cmake</build_type>
</export>
</package>
+55
View File
@@ -0,0 +1,55 @@
#include "aerial_inspection_planner/bvh.hpp"
AABB BVH::computeBoundingBox(const mesh_utils::Triangle& triangle)
{
Eigen::Vector3f minCorner = triangle.vertices[0];
Eigen::Vector3f maxCorner = triangle.vertices[0];
for (const auto& vertex : triangle.vertices)
{
minCorner = {std::min(minCorner.x(), vertex.x()), std::min(minCorner.y(), vertex.y()), std::min(minCorner.z(), vertex.z())};
maxCorner = {std::max(maxCorner.x(), vertex.x()), std::max(maxCorner.y(), vertex.y()), std::max(maxCorner.z(), vertex.z())};
}
return {minCorner, maxCorner};
}
BVHNode* BVH::buildBVH(std::vector<mesh_utils::Triangle>& triangles, int start, int end)
{
if (start == end)
{
return nullptr;
}
if (start + 1 == end)
{
BVHNode* node = new BVHNode();
node->boundingBox = computeBoundingBox(triangles[start]);
node->triangle = &triangles[start];
node->left = node->right = nullptr;
return node;
}
AABB boundingBox = computeBoundingBox(triangles[start]);
for (int i = start + 1; i < end; ++i)
{
AABB box = computeBoundingBox(triangles[i]);
boundingBox.min = {std::min(boundingBox.min.x(), box.min.x()), std::min(boundingBox.min.y(), box.min.y()), std::min(boundingBox.min.z(), box.min.z())};
boundingBox.max = {std::max(boundingBox.max.x(), box.max.x()), std::max(boundingBox.max.y(), box.max.y()), std::max(boundingBox.max.z(), box.max.z())};
}
int axis = 0;
Eigen::Vector3f extents = boundingBox.max - boundingBox.min;
if (extents.y() > extents.x()) axis = 1;
if (extents.z() > extents[axis]) axis = 2;
sort(triangles.begin() + start, triangles.begin() + end, [axis](const mesh_utils::Triangle& a, const mesh_utils::Triangle& b)
{
return a.vertices[0][axis] < b.vertices[0][axis];
});
int mid = (start + end) / 2;
BVHNode* node = new BVHNode();
node->boundingBox = boundingBox;
node->left = buildBVH(triangles, start, mid);
node->right = buildBVH(triangles, mid, end);
node->triangle = nullptr;
return node;
}
+1000
View File
@@ -0,0 +1,1000 @@
#include <ament_index_cpp/get_package_share_directory.hpp>
#include "aerial_inspection_planner/cpp_planner.hpp"
#include "aerial_inspection_planner/mesh_utils.hpp"
InspectionPlanner::InspectionPlanner()
: Node("cpp_planner")
{
mesh_publisher_ = this->create_publisher<visualization_msgs::msg::Marker>("visualization_mesh", 10);
all_vps_publisher_ = this->create_publisher<visualization_msgs::msg::MarkerArray>("all_vps", 10);
vps_redundancy_publisher_ = this->create_publisher<visualization_msgs::msg::MarkerArray>("all_vps_redundancy", 10);
mesh_colored_as_views_ = this->create_publisher<visualization_msgs::msg::Marker>("visualization_mesh_colored_as_views", 10);
vps_after_trim_ = this->create_publisher<visualization_msgs::msg::MarkerArray>("visualize_vps_after_trimmed", 10);
mesh_colored_as_views_after_trim_ = this->create_publisher<visualization_msgs::msg::Marker>("visualization_mesh_colored_as_views_after_trimmed", 10);
final_path_visualization_ = this->create_publisher<visualization_msgs::msg::Marker>("visualization_final_path", 10);
this->declare_parameter("visualize_mesh", true);
this->declare_parameter("distance_from_surface", 4.0);
this->declare_parameter("min_height", 0.3);
this->declare_parameter("max_height", 999999.0);
this->declare_parameter("min_view_redundancy", 2);
this->declare_parameter("max_incidence_angle", 50.0);
this->declare_parameter("max_view_distance", 10.0);
this->declare_parameter("camera_half_fov", 55.0);
this->declare_parameter("planner_type", "greedy");
this->declare_parameter("min_distance", 1.5);
this->declare_parameter("tsp_method", "greedy");
this->declare_parameter("tsp_solver_allowed_time", 5.0);
this->declare_parameter("mesh_name", "cargo_decimate");
this->declare_parameter("rviz_scale", 1.0);
this->declare_parameter("export_to_yaml", false);
get_parameter("visualize_mesh", visualize_mesh_);
get_parameter("distance_from_surface", distance_from_surface_);
get_parameter("min_height", min_height_);
get_parameter("max_height", max_height_);
get_parameter("min_view_redundancy", min_view_redundancy_);
get_parameter("max_incidence_angle", max_incidence_angle_);
get_parameter("max_view_distance", max_view_distance_);
get_parameter("camera_half_fov", camera_half_fov_);
get_parameter("planner_type", planner_type_);
get_parameter("min_distance", min_distance_);
get_parameter("tsp_method", tsp_method_);
get_parameter("tsp_solver_allowed_time", tsp_solver_allowed_time_);
get_parameter("mesh_name", mesh_name_);
get_parameter("rviz_scale", rviz_scale_);
get_parameter("export_to_yaml", export_to_yaml_);
}
visualization_msgs::msg::Marker InspectionPlanner::create_mesh_visualization_msg(bool color_as_redundancy = false)
{
visualization_msgs::msg::Marker marker;
std_msgs::msg::ColorRGBA triangle_color;
std_msgs::msg::ColorRGBA triangle_color2;
std_msgs::msg::ColorRGBA triangle_color3;
marker.header.frame_id = "map";
marker.header.stamp = this->now();
marker.ns = "cpp_planner";
marker.id = 0;
marker.type = visualization_msgs::msg::Marker::TRIANGLE_LIST;
marker.action = visualization_msgs::msg::Marker::ADD;
marker.pose.position.x = 0;
marker.pose.position.y = 0;
marker.pose.position.z = 0;
marker.pose.orientation.x = 0.0;
marker.pose.orientation.y = 0.0;
marker.pose.orientation.z = 0.0;
marker.pose.orientation.w = 1.0;
marker.scale.x = 1;
marker.scale.y = 1;
marker.scale.z = 1;
triangle_color.a = 1.0;
triangle_color.r = 0.0;
triangle_color.g = 1.0;
triangle_color.b = 0.0;
triangle_color2.a = 1.0;
triangle_color2.r = 0.8;
triangle_color2.g = 1.0;
triangle_color2.b = 0.0;
triangle_color3.a = 1.0;
triangle_color3.r = 0.0;
triangle_color3.g = 0.5;
triangle_color3.b = 0.5;
double max_view_color = 1;
double min_view_color = 9999999;
if (color_as_redundancy)
{
for (size_t j = 0; j < mesh->size(); ++j)
{
int vp_count = mesh_to_vp_map[j].size();
if (vp_count > max_view_color)
{
max_view_color = vp_count;
}
if (vp_count < min_view_color)
{
min_view_color = vp_count;
}
}
}
geometry_msgs::msg::Point pt;
for (size_t j = 0; j < mesh->size(); ++j)
{
if (color_as_redundancy)
{
int vp_count = mesh_to_vp_map[j].size();
double view_mixer = std::min(vp_count, (int) max_view_color)/max_view_color;
triangle_color.r = view_mixer;
triangle_color.g = 0;
triangle_color.b = 1 - view_mixer;
triangle_color2 = triangle_color;
triangle_color3 = triangle_color;
}
const mesh_utils::Triangle& triangle = (*mesh)[j];
pt.x = triangle.vertices[0].x();
pt.y = triangle.vertices[0].y();
pt.z = triangle.vertices[0].z();
marker.points.push_back(pt);
marker.colors.push_back(triangle_color);
pt.x = triangle.vertices[1].x();
pt.y = triangle.vertices[1].y();
pt.z = triangle.vertices[1].z();
marker.points.push_back(pt);
marker.colors.push_back(triangle_color2);
pt.x = triangle.vertices[2].x();
pt.y = triangle.vertices[2].y();
pt.z = triangle.vertices[2].z();
marker.points.push_back(pt);
marker.colors.push_back(triangle_color3);
}
return marker;
}
visualization_msgs::msg::Marker InspectionPlanner::create_path_visualization_msg(bool color_as_progress = false)
{
visualization_msgs::msg::Marker marker;
std_msgs::msg::ColorRGBA line_color;
marker.header.frame_id = "map";
marker.header.stamp = this->now();
marker.ns = "cpp_planner";
marker.id = 0;
marker.type = visualization_msgs::msg::Marker::LINE_STRIP;
marker.action = visualization_msgs::msg::Marker::ADD;
marker.pose.position.x = 0;
marker.pose.position.y = 0;
marker.pose.position.z = 0;
marker.pose.orientation.x = 0.0;
marker.pose.orientation.y = 0.0;
marker.pose.orientation.z = 0.0;
marker.pose.orientation.w = 1.0;
marker.scale.x = 0.5 * rviz_scale_;
marker.color.a = 1.0;
marker.color.r = 1.0;
marker.color.g = 0.0;
marker.color.b = 0.0;
line_color.a = 1.0;
// Create and initialize start_color
std_msgs::msg::ColorRGBA start_color;
start_color.r = 0.0 / 255.0; // Normalize to [0, 1]
start_color.g = 255.0 / 255.0;
start_color.b = 135.0 / 255.0;
start_color.a = 1.0; // Fully opaque
// Create and initialize end_color
std_msgs::msg::ColorRGBA end_color;
end_color.r = 0.0 / 255.0;
end_color.g = 97.0 / 255.0;
end_color.b = 255.0 / 255.0;
end_color.a = 1.0; // Fully opaque
double num_points = final_path.size();
geometry_msgs::msg::Point pt;
for (size_t j = 0; j < final_path.size(); ++j)
{
if (color_as_progress)
{
line_color.r = (end_color.r-start_color.r)*j/num_points + start_color.r;
line_color.g = (end_color.g-start_color.g)*j/num_points + start_color.g;
line_color.b = (end_color.b-start_color.b)*j/num_points + start_color.b;
}
auto curr_point = vp_positions[final_path[j]];
pt.x = curr_point.x();
pt.y = curr_point.y();
pt.z = curr_point.z();
marker.points.push_back(pt);
marker.colors.push_back(line_color);
}
return marker;
}
visualization_msgs::msg::MarkerArray InspectionPlanner::create_vps_visualization_msg(bool color_as_redundancy = false)
{
visualization_msgs::msg::MarkerArray marker_array;
visualization_msgs::msg::Marker marker;
marker.header.frame_id = "map";
marker.header.stamp = this->now();
marker.ns = "cpp_planner";
marker.type = visualization_msgs::msg::Marker::ARROW;
marker.action = visualization_msgs::msg::Marker::ADD;
if (color_as_redundancy)
{
marker.scale.x = 1.5 * rviz_scale_;
marker.scale.y = .3 * rviz_scale_;
marker.scale.z = .3 * rviz_scale_;
}
else
{
marker.scale.x = 1 * rviz_scale_;
marker.scale.y = .1 * rviz_scale_;
marker.scale.z = .1 * rviz_scale_;
}
marker.color.a = 1.0;
marker.color.r = 1.0;
marker.color.g = 0.0;
marker.color.b = 0.0;
double max_view_color = 1;
double min_view_color = 9999999;
if (color_as_redundancy)
{
for (auto i = 0u; i < vp_positions.size(); i++)
{
if (!vp_keep[i])
{
continue;
}
int vp_count = vp_to_mesh_map[i].size();
if (vp_count > max_view_color)
{
max_view_color = vp_count;
}
if (vp_count < min_view_color)
{
min_view_color = vp_count;
}
}
}
Eigen::Quaternionf orientation;
for (auto i = 0u; i < vp_positions.size(); i++)
{
if (!vp_keep[i])
{
continue;
}
marker.id = i;
marker.pose.position.x = vp_positions[i].x();
marker.pose.position.y = vp_positions[i].y();
marker.pose.position.z = vp_positions[i].z();
orientation = mesh_utils::vector_to_quaternion(vp_orientation_vec[i]);
marker.pose.orientation.x = orientation.x();
marker.pose.orientation.y = orientation.y();
marker.pose.orientation.z = orientation.z();
marker.pose.orientation.w = orientation.w();
if (color_as_redundancy)
{
int vp_count = vp_to_mesh_map[i].size();
double view_mixer = std::min(vp_count, (int) max_view_color)/max_view_color;
marker.color.r = view_mixer;
marker.color.g = 0.0;
marker.color.b = 1 - view_mixer;
}
marker_array.markers.push_back(marker);
}
return marker_array;
}
void InspectionPlanner::determine_visibility(bool save_mesh_to_vp_map = true)
{
RCLCPP_INFO(this->get_logger(), "Calculating visibility for vps");
auto start_time = this->now();
// Resize the vectors before filling for faster execution
mesh_to_vp_map.resize(mesh->size());
vp_to_mesh_map.resize(vp_positions.size());
// Determine visibility
for (size_t i = 0; i < vp_positions.size(); ++i) // Viewpoints
{
const auto& vp_pose = vp_positions[i];
const auto& vp_orient = vp_orientation_vec[i];
// TODO Or already computed below? Just need to evaluate? Just look at all visible meshes and make sure they don't occlude each other?
// actually still more complex. Need to look at all triangles, not just those passing the test
for (size_t j = 0; j < mesh->size(); ++j) // Mesh triangles
{
const mesh_utils::Triangle& triangle = (*mesh)[j];
bool all_corners_visible = true;
for (size_t k = 0; k < triangle.vertices.size(); ++k) // Check all three corners
{
Eigen::Vector3f ray_direction(triangle.vertices[k] - vp_pose);
ray_direction.normalize();
if (!mesh_utils::ray_views_point(vp_pose, vp_orient, ray_direction, mesh_surface_normals[j],
triangle.vertices[k], max_incidence_angle_, max_view_distance_,
camera_half_fov_))
{
all_corners_visible = false;
break;
}
}
if (all_corners_visible)
{
if (save_mesh_to_vp_map)
{
mesh_to_vp_map[j].push_back(i);
}
vp_to_mesh_map[i].push_back(j);
}
}
}
RCLCPP_INFO_STREAM(this->get_logger(), "Time to calc visibility: " << this->now().seconds() - start_time.seconds());
}
bool InspectionPlanner::create_vps_for_all_triangles()
{
RCLCPP_INFO(this->get_logger(), "**Creating all vps**");
int in_collision_count = 0;
for (std::vector<mesh_utils::Triangle>::iterator it = mesh->begin(); it != mesh->end(); it++)
{
int polygon_size = it->vertices.size();
// RCLCPP_INFO_STREAM_ONCE(this->get_logger(), "Size is " << polygon_size);
// Check that all polygons are triangles
if (polygon_size != 3)
{
RCLCPP_ERROR(this->get_logger(), "Encountered polygon not of size 3");
return false;
}
const Eigen::Vector3f v0(it->vertices[0].x(), it->vertices[0].y(), it->vertices[0].z());
const Eigen::Vector3f v1(it->vertices[1].x(), it->vertices[1].y(), it->vertices[1].z());
const Eigen::Vector3f v2(it->vertices[2].x(), it->vertices[2].y(), it->vertices[2].z());
Eigen::Vector3f surface_normal = mesh_utils::calculate_surface_normal(v0, v1, v2);
mesh_surface_normals.push_back(surface_normal);
Eigen::Vector3f centroid = mesh_utils::calculate_centroid(v0, v1, v2);
// Find viewpoint out from mesh, set the viewing angle as opposite of the normal.
Eigen::Vector3f new_vp = centroid + surface_normal*distance_from_surface_;
// Check for collisions
// TODO adjust vp if in collision.
if (is_collision(new_vp))
{
in_collision_count++;
continue;
}
// TODO check for visibility of the mesh it cares about
vp_positions.push_back(new_vp);
vp_orientation_vec.push_back(-surface_normal); // pointing to surface normal, so negative
}
vp_keep.resize(vp_positions.size(), true);
if (in_collision_count > 0)
{
RCLCPP_WARN_STREAM(this->get_logger(), "Didn't create "
<< in_collision_count << " vps because of collisions\n");
}
return true;
}
bool InspectionPlanner::mesh_to_iterative_vps()
{
RCLCPP_INFO(this->get_logger(), "Running Iterative VP creation");
auto start_time = this->now();
if (!mesh)
{
RCLCPP_ERROR(this->get_logger(), "Called VP sampling, but there is no mesh");
return false;
}
// Create viewpoint for all triangles
if (!create_vps_for_all_triangles())
{
return false;
}
if (this->visualize_mesh_)
{
visualization_msgs::msg::MarkerArray marker_array = this->create_vps_visualization_msg();
// RCLCPP_INFO(this->get_logger(), "Publishing the vps!");
all_vps_publisher_->publish(marker_array);
}
// Calculate visibility and view redundancy for each surface.
determine_visibility();
// Visualize with redundancy as color.
if (this->visualize_mesh_)
{
visualization_msgs::msg::Marker marker = this->create_mesh_visualization_msg(true);
// RCLCPP_INFO(this->get_logger(), "Publishing the mesh visualization with redundancy color!");
mesh_colored_as_views_->publish(marker);
visualization_msgs::msg::MarkerArray marker_array = this->create_vps_visualization_msg(true);
// RCLCPP_INFO(this->get_logger(), "Publishing the vps with color based on number mesh seen!");
vps_redundancy_publisher_->publish(marker_array);
}
// Iterate over list and remove as many as possible
RCLCPP_INFO(this->get_logger(), "Removing Unnecessary Viewpoints");
size_t vp_index = 0;
int count_removed = 0;
int count_vp_sees_nothing = 0;
while (vp_index < vp_positions.size())
{
// Check if all triangles viewed by vp have above the min_view_redundancy, and can be removed
bool can_remove = true;
if (vp_to_mesh_map[vp_index].size() == 0)
{
vp_index++;
count_vp_sees_nothing++;
continue; // TODO, need better way. Each vp should be able to view its assigned mesh.
// Maybe have the vp move back from surface? Incident angle though?
}
for (size_t i = 0; i < vp_to_mesh_map[vp_index].size(); i++)
{
int mesh_index_i_of_vp = vp_to_mesh_map[vp_index][i];
if (mesh_to_vp_map[mesh_index_i_of_vp].size() <= min_view_redundancy_)
{
vp_index++;
can_remove = false;
break;
}
}
// TODO swap to pointers. For now just make a vp_keep vector. Will be faster too.
if (can_remove)
{
vp_keep[vp_index] = false;
count_removed++;
// Update the mesh to viewpoint map to not include this viewpoint
for (size_t i = 0; i < vp_to_mesh_map[vp_index].size(); i++)
{
int mesh_index_i_of_vp = vp_to_mesh_map[vp_index][i];
std::vector<int>::iterator position = std::find(
mesh_to_vp_map[mesh_index_i_of_vp].begin(),
mesh_to_vp_map[mesh_index_i_of_vp].end(),
vp_index); // looks for vp_index
if (position != mesh_to_vp_map[mesh_index_i_of_vp].end())
{
mesh_to_vp_map[mesh_index_i_of_vp].erase(position);
}
}
vp_index++; // TODO remove later when switch to pointers
}
}
RCLCPP_INFO(this->get_logger(), "Finished Trimming");
RCLCPP_INFO_STREAM(this->get_logger(), "Number VPs that can't see anything (and kept): " << count_vp_sees_nothing);
RCLCPP_INFO_STREAM(this->get_logger(), "Number of VPs before and after: "
<< vp_positions.size()
<< " -> "
<< vp_positions.size() - count_removed);
// Visualize the updates after trimming
if (this->visualize_mesh_)
{
visualization_msgs::msg::Marker marker = this->create_mesh_visualization_msg(true);
// RCLCPP_INFO(this->get_logger(), "Publishing the mesh visualization with removed vps!");
mesh_colored_as_views_after_trim_->publish(marker);
visualization_msgs::msg::MarkerArray marker_array = this->create_vps_visualization_msg(true);
// RCLCPP_INFO(this->get_logger(), "Publishing the reduced number of vps!");
vps_after_trim_->publish(marker_array);
}
RCLCPP_INFO_STREAM(this->get_logger(), "Total time to solve: " << this->now().seconds() - start_time.seconds());
return true;
}
bool InspectionPlanner::mesh_to_greedy_vps()
{
RCLCPP_INFO(this->get_logger(), "Running Greedy VP Creation");
auto start_time = this->now();
if (!mesh)
{
RCLCPP_ERROR(this->get_logger(), "Called VP sampling, but there is no mesh! Exiting");
return false;
}
// Create viewpoint for all triangles
if (!create_vps_for_all_triangles())
{
return false;
}
if (this->visualize_mesh_)
{
visualization_msgs::msg::MarkerArray marker_array = this->create_vps_visualization_msg();
RCLCPP_INFO(this->get_logger(), "Publishing the vps!");
all_vps_publisher_->publish(marker_array);
}
// Calculate visibility and view redundancy for each surface.
determine_visibility(false);
// Visualize with redundancy as color.
if (this->visualize_mesh_)
{
visualization_msgs::msg::Marker marker = this->create_mesh_visualization_msg(true);
RCLCPP_DEBUG(this->get_logger(), "Publishing the mesh visualization with redundancy color!");
mesh_colored_as_views_->publish(marker);
visualization_msgs::msg::MarkerArray marker_array = this->create_vps_visualization_msg(true);
RCLCPP_DEBUG(this->get_logger(), "Publishing the vps with color based on number mesh seen!");
vps_redundancy_publisher_->publish(marker_array);
}
// Greedily keep nodes
RCLCPP_INFO(this->get_logger(), "**Greedily selecting nodes**");
vp_keep.resize(vp_positions.size(), false);
std::fill(vp_keep.begin(), vp_keep.end(), false);
int count_added = 0;
int count_vp_sees_nothing = 0;
std::vector<std::pair<int, int>> vp_to_value_pair;
for (size_t i = 0; i < vp_to_mesh_map.size(); i++)
{
// If vp has a score of 0, add right away and don't add to sort pair list
if (vp_to_mesh_map[i].size() == 0)
{
count_vp_sees_nothing++;
count_added++;
vp_keep[i] = true;
continue; // TODO, need better way. Each vp should be able to view its assigned mesh.
// Maybe have the vp move back from surface? Incident angle though?
// This shouldn't happen in the future. Means there isn't full coverage. But best to its
// abilities.
}
// Create new entry
vp_to_value_pair.push_back(std::make_pair(i, vp_to_mesh_map[i].size()));
}
// Sort the vector of pairs based on value
sort(vp_to_value_pair.begin(), vp_to_value_pair.end(), [=](std::pair<int, int>& a, std::pair<int, int>& b)
{
return a.second > b.second;
}
);
RCLCPP_INFO_STREAM(this->get_logger(), "High vp index and value: " << vp_to_value_pair.front().first << ", " << vp_to_value_pair.front().second);
RCLCPP_INFO_STREAM(this->get_logger(), "Low vp index and value: " << vp_to_value_pair.back().first << ", " << vp_to_value_pair.back().second);
while (vp_to_value_pair.size() > 0 && vp_to_value_pair.front().second != 0)
{
bool top_val_updated_and_sorted = false;
while (!top_val_updated_and_sorted)
{
// Update top entry
int new_count_val = 0;
int current_vp_index = vp_to_value_pair.front().first;
for (size_t i = 0; i < vp_to_mesh_map[current_vp_index].size(); i++)
{
if (mesh_to_vp_map[vp_to_mesh_map[current_vp_index].at(i)].size() < min_view_redundancy_)
{
new_count_val++;
}
}
vp_to_value_pair.front().second = new_count_val;
// The case where only one value left
if (vp_to_value_pair.size() == 1)
{
top_val_updated_and_sorted = true;
break;
}
// Resort top entry in the list
bool sorted = false;
for (size_t i = 1; i < vp_to_value_pair.size(); i++)
{
if (vp_to_value_pair[i].second <= vp_to_value_pair.front().second)
{
if (i == 1)
{
top_val_updated_and_sorted = true;
sorted = true;
break;
}
// Move to i-1 location
auto new_pos = vp_to_value_pair.begin() + i - 1;
std::rotate(vp_to_value_pair.begin(), vp_to_value_pair.begin() + 1, new_pos);
sorted = true;
}
}
// The case where it is the smallest value
if (!sorted)
{
std::rotate(vp_to_value_pair.begin(), vp_to_value_pair.begin() + 1, vp_to_value_pair.end());
}
}
// RCLCPP_INFO_STREAM_ONCE(this->get_logger(), "High vp index and value after update and resort: " << vp_to_value_pair.front().first << ", " << vp_to_value_pair.front().second);
// Add top entry to list of kept vps, update the mesh to vp map, and remove from pair list
int top_vp_index = vp_to_value_pair.front().first;
vp_keep[top_vp_index] = true;
for (size_t i = 0; i < vp_to_mesh_map[top_vp_index].size(); i++)
{
mesh_to_vp_map[vp_to_mesh_map[top_vp_index].at(i)].push_back(top_vp_index);
}
vp_to_value_pair.erase(vp_to_value_pair.begin());
count_added++;
}
RCLCPP_INFO(this->get_logger(), "Finished vp selection");
RCLCPP_INFO_STREAM(this->get_logger(), "Number VPs that can't see anything (and kept): " << count_vp_sees_nothing);
RCLCPP_INFO_STREAM(this->get_logger(), "Number of VPs before and after: "
<< vp_positions.size()
<< " -> "
<< count_added);
// Visualize the updates after trimming
if (this->visualize_mesh_)
{
visualization_msgs::msg::Marker marker = this->create_mesh_visualization_msg(true);
RCLCPP_DEBUG(this->get_logger(), "Publishing the mesh visualization with removed vps!");
mesh_colored_as_views_after_trim_->publish(marker);
visualization_msgs::msg::MarkerArray marker_array = this->create_vps_visualization_msg(true);
RCLCPP_DEBUG(this->get_logger(), "Publishing the reduced number of vps!");
vps_after_trim_->publish(marker_array);
}
RCLCPP_INFO_STREAM(this->get_logger(), "Total time to find vps: " << this->now().seconds() - start_time.seconds());
return true;
}
bool InspectionPlanner::is_collision(Eigen::Vector3f point) const
{
if (point.z() < min_height_ || point.z() > max_height_) // min_distance
{
return true;
}
for (size_t j = 0; j < mesh->size(); j++)
{
// Check endpoints for being close to the mesh
const mesh_utils::Triangle& triangle = (*mesh)[j];
if (mesh_utils::point_to_triangle_distance(point, triangle) < min_distance_)
{
return true;
}
}
return false;
}
// Checks for collisions of a line segment between index vp_i and vp_j of the vp_positions
bool InspectionPlanner::is_collision(int vp_i, int vp_j) const
{
// TODO RRT*, especially for nodes that have no connections
// Could use BVH, Octree, or k-d tree to speed up, octomap TODO BVH if need to save time or later.
Eigen::Vector3f first_state = vp_positions[vp_i];
Eigen::Vector3f last_state = vp_positions[vp_j];
// Check for collision with ground
if (first_state.z() < min_height_ || last_state.z() < min_height_
|| first_state.z() > max_height_ || last_state.z() > max_height_)
{
return true;
}
// Check mesh
for (size_t j = 0; j < mesh->size(); j++)
{
const mesh_utils::Triangle& triangle = (*mesh)[j];
// Could technically not check the endpoints because they are already checked
if (mesh_utils::point_to_triangle_distance(first_state, triangle) < min_distance_ ||
mesh_utils::point_to_triangle_distance(last_state, triangle) < min_distance_ ||
mesh_utils::closest_distance_between_segments(first_state, last_state, triangle.vertices[0], triangle.vertices[1]) < min_distance_ ||
mesh_utils::closest_distance_between_segments(first_state, last_state, triangle.vertices[1], triangle.vertices[2]) < min_distance_ ||
mesh_utils::closest_distance_between_segments(first_state, last_state, triangle.vertices[2], triangle.vertices[0]) < min_distance_)
{
return true;
}
}
return false;
}
bool InspectionPlanner::solve_tsp()
{
// TODO fix bnb or find better solver. Greedy can allow collisions, and hc isn't able to fix sometimes
RCLCPP_INFO(this->get_logger(), "Starting TSP");
auto start_time = this->now();
double collision_cost = 999999;
// Create vector of kept vp indexes to map (TODO swap out when switch to pointers)
std::vector<int> kept_vp_indexes;
for (size_t i = 0; i < vp_keep.size(); i++)
{
if (vp_keep[i])
{
kept_vp_indexes.push_back(i);
}
}
// Compute distance matrix
std::vector<std::vector<double>> distance;
distance.resize(kept_vp_indexes.size());
for (size_t i = 0; i < kept_vp_indexes.size(); i++)
{
distance[i].resize(kept_vp_indexes.size());
for (size_t j = 0; j <= i; j++) // Only iterate up to i
{
if (!is_collision(kept_vp_indexes[i], kept_vp_indexes[j]))
{
double dist = (vp_positions[kept_vp_indexes[i]] - vp_positions[kept_vp_indexes[j]]).norm();
distance[i][j] = dist;
distance[j][i] = dist;
}
else
{
distance[i][j] = collision_cost;
distance[j][i] = collision_cost;
}
}
}
RCLCPP_INFO_STREAM(this->get_logger(), "Time to calc distances: " << this->now().seconds() - start_time.seconds());
start_time = this->now();
// check for the case where none can connect to a node
std::vector<size_t> rows_to_remove;
for (size_t i = 0; i < distance.size(); i++)
{
bool all_collision = true;
for (size_t j = 0; j < distance.size(); j++) // Only iterate up to i
{
if (distance[i][j] < collision_cost)
{
all_collision = false;
break;
}
}
if (all_collision)
{
// remove from keep list and remove from distance matrix
rows_to_remove.push_back(i);
vp_keep[kept_vp_indexes[i]] = false;
}
}
if (rows_to_remove.size() > 0)
{
RCLCPP_WARN_STREAM(this->get_logger(), "Removing "
<< rows_to_remove.size() << " vps because no vps connect to them in a straight line\n"
<< "Could be due to geometry or vp being inside the mesh."); // TODO these viewpoints should have been made differently so this doesn't happen.
// Remove rows from distance matrix
for (size_t i = 0; i < rows_to_remove.size(); i++)
{
distance.erase(distance.begin() + rows_to_remove[i] - i);
kept_vp_indexes.erase(kept_vp_indexes.begin() + rows_to_remove[i] - i);
}
// Remove columns from distance matrix
for (size_t i = 0; i < rows_to_remove.size(); i++)
{
for (size_t j = 0; j < distance.size(); j++)
{
distance[j].erase(distance[j].begin() + rows_to_remove[i] - i);
}
}
}
// Solve TSP
RCLCPP_INFO_STREAM(this->get_logger(), "TSP solver method: " << tsp_method_);
std::vector<int> tsp_index_order;
if (tsp_method_ == "greedy")
{
// tsp_index_order = greedy_tsp_algo(distance, this->get_logger());
RCLCPP_ERROR_STREAM(this->get_logger(), tsp_method_ << " has been removed for public release. Please try ortools for the TSP solver");
return false;
}
else if (tsp_method_ == "bnb")
{
// int source = 0;
// std::unique_ptr<TspNode> solution = BranchAndBound(
// distance, source, tsp_solver_allowed_time_, this->get_logger());
// if (solution->time < tsp_solver_allowed_time_)
// {
// RCLCPP_INFO_STREAM(this->get_logger(), "Optimal solution found:");
// RCLCPP_INFO_STREAM(this->get_logger(), "Total cost:" << solution->value);
// RCLCPP_DEBUG_STREAM(this->get_logger(), "Optimal cycle:");
// for(std::vector<int>::const_iterator it=solution->path->begin();it!=solution->path->end();it++)
// {
// tsp_index_order.push_back(*it);
// }
// // tsp_index_order.push_back(source);
// RCLCPP_INFO_STREAM(this->get_logger(), "Elapsed time:"<< solution->time << "s");
// }
// else
// {
// RCLCPP_INFO_STREAM(this->get_logger(), "Optimal solution NOT found in specified time:");
// RCLCPP_INFO_STREAM(this->get_logger(), "Total cost: " << solution->value);
// RCLCPP_DEBUG_STREAM(this->get_logger(), "Solution cycle:");
// for (std::vector<int>::const_iterator it = solution->path->begin(); it != solution->path->end(); it++)
// {
// tsp_index_order.push_back(*it);
// }
// // tsp_index_order.push_back(source);
// RCLCPP_INFO_STREAM(this->get_logger(), "Elapsed time:"<< solution->time << "s");
// }
// delete solution->path;
RCLCPP_ERROR_STREAM(this->get_logger(), tsp_method_ << " has been removed for public release. Please try ortools for the TSP solver");
return false;
}
else if (tsp_method_ == "hc")
{
// unsigned seed = 1;
// tsp_index_order = greedy_tsp_algo(distance, this->get_logger());
// tsp_index_order = HC(distance, tsp_index_order, tsp_solver_allowed_time_, seed, this->get_logger());
RCLCPP_ERROR_STREAM(this->get_logger(), tsp_method_ << " has been removed for public release. Please try ortools for the TSP solver");
return false;
}
else if (tsp_method_ == "ortools")
{
std::vector<std::vector<int>> distance_int;
double double_to_int_scale = 1000;
distance_int.resize(distance.size());
for (size_t i = 0; i < distance.size(); i++)
{
distance_int[i].resize(distance.size());
for (size_t j = 0; j <= i; j++) // Only iterate up to i
{
distance_int[i][j] = distance[i][j] * double_to_int_scale;
distance_int[j][i] = distance[j][i] * double_to_int_scale;
}
}
tsp_index_order = operations_research::Tsp(distance_int, tsp_solver_allowed_time_, this->get_logger());
}
else if (tsp_method_ == "sa")
{
// unsigned seed = 1;
// tsp_index_order = greedy_tsp_algo(distance, this->get_logger());
// // double T = distance[initial[9]][initial[10]]*2*distance.size();
// // double T = .8;
// double T = 100;
// double T_min = 0.1 * distance.size();
// double r = 0.99;
// tsp_index_order = SA(distance, tsp_index_order, T, T_min, r, tsp_solver_allowed_time_, seed, this->get_logger());
RCLCPP_ERROR_STREAM(this->get_logger(), tsp_method_ << " has been removed for public release. Please try ortools for the TSP solver");
return false;
}
else
{
RCLCPP_ERROR(this->get_logger(), "VP sampling failed");
return false;
}
std::ostringstream oss;
for (size_t i = 0; i < tsp_index_order.size(); i++)
{
oss << tsp_index_order[i] << ",";
}
RCLCPP_DEBUG_STREAM(this->get_logger(), oss.str());
// Map indexes to true vp index and set
for (size_t i = 0; i < tsp_index_order.size(); i++)
{
final_path.push_back(kept_vp_indexes[tsp_index_order[i]]);
}
RCLCPP_INFO_STREAM(this->get_logger(), "Time to solve TSP: " << this->now().seconds() - start_time.seconds());
// Visualize final path
if (final_path.size() > 0 && this->visualize_mesh_)
{
visualization_msgs::msg::Marker marker = this->create_path_visualization_msg(true);
RCLCPP_DEBUG(this->get_logger(), "Publishing the final path visualization");
final_path_visualization_->publish(marker);
}
return true;
}
void InspectionPlanner::export_to_yaml()
{
std::string file_name = ament_index_cpp::get_package_share_directory("aerial_inspection_planner") + "/inspection_path.yaml";
std::fstream oss(file_name, std::ios::out);
if (!oss.is_open()) {
RCLCPP_ERROR_STREAM(rclcpp::get_logger("export_to_file"), "Failed to open file: " << file_name);
return;
}
oss << "/drone_names: ['icarus']\n\n";
oss << "# Icarus Drone\n/icarus:\n properties:\n use_sim: True\n pose:";
oss << "\n initial:\n position:\n x: 2.5\n y: -2.5\n z: 2.0"; // TODO udpate initial position?? z position?
oss << "\n orientation:\n roll: 0.0\n pitch: 0.0\n yaw: 0.0";
oss << "\n waypoints: [";
for (size_t j = 0; j < final_path.size(); ++j)
{
Eigen::Vector3f curr_point = vp_positions[final_path[j]];
Eigen::Vector3f curr_orient = vp_orientation_vec[final_path[j]];
if (j != 0)
{
oss << ",\n ";
}
double yaw = mesh_utils::vector_to_yaw(curr_orient);
oss << "[" << curr_point.x()
<< ", " << curr_point.y()
<< ", " << curr_point.z()
<< ", " << yaw
<< "]";
}
oss << "]";
oss.close();
RCLCPP_INFO_STREAM(this->get_logger(), "Finishing export to csv file: " << file_name);
}
void InspectionPlanner::plan()
{
RCLCPP_WARN(this->get_logger(), "Starting New Plan!");
auto start_time = this->now();
// Process stl file to mesh
RCLCPP_DEBUG(this->get_logger(), "Converting STL to Mesh");
auto path = ament_index_cpp::get_package_share_directory("aerial_inspection_planner");
RCLCPP_DEBUG_STREAM(this->get_logger(), path);
this->mesh = mesh_utils::readSTLfile(
ament_index_cpp::get_package_share_directory(
"aerial_inspection_planner") + "/data/meshes/" + mesh_name_ + ".stl", this->get_logger());
if (this->mesh->size() == 0)
{
RCLCPP_ERROR(this->get_logger(), "STL error. Exiting");
return;
}
// Visualize mesh
if (this->visualize_mesh_ && mesh)
{
visualization_msgs::msg::Marker marker = this->create_mesh_visualization_msg();
RCLCPP_INFO(this->get_logger(), "Visualizing Mesh. Waiting for 3 seconds for Rviz to start...");
rclcpp::sleep_for(std::chrono::seconds{3});
// RCLCPP_INFO(this->get_logger(), "Publishing the mesh visualization!");
mesh_publisher_->publish(marker);
}
// Process mesh file to VPs
bool sampling_success = false;
if (planner_type_ == "iterative")
{
sampling_success = this->mesh_to_iterative_vps();
}
else if (planner_type_ == "greedy")
{
sampling_success = this->mesh_to_greedy_vps();
}
else
{
RCLCPP_ERROR(this->get_logger(), "planner_type doesn't match existing method");
return;
}
if (!sampling_success)
{
RCLCPP_ERROR(this->get_logger(), "VP sampling failed");
return;
}
// Process VPs to graph or directly optimize
// Find path between vps
RCLCPP_INFO(this->get_logger(), "**Solving for flight path**");
bool success_tsp = this->solve_tsp();
if (!success_tsp || final_path.size() == 0)
{
RCLCPP_ERROR_STREAM(this->get_logger(), "TSP failed? Path size: " << final_path.size());
return;
}
double path_length = 0;
Eigen::Vector3f prev_vp_pos = vp_positions[final_path[0]];
for (size_t j = 1; j < final_path.size(); ++j)
{
Eigen::Vector3f cur_vp_pos = vp_positions.at(final_path[j]);
path_length += (prev_vp_pos - cur_vp_pos).norm();
prev_vp_pos = cur_vp_pos;
}
RCLCPP_INFO_STREAM(this->get_logger(), "Final path length: " << path_length);
RCLCPP_WARN(this->get_logger(), "Finished making plan!");
RCLCPP_INFO_STREAM(this->get_logger(), "Total Time: " << this->now().seconds() - start_time.seconds());
if (export_to_yaml_)
{
RCLCPP_INFO_STREAM(this->get_logger(), "Exporting to CSV...");
this->export_to_yaml();
}
return;
}
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
auto planner_node = std::make_shared<InspectionPlanner>();
planner_node->plan();
// rclcpp::spin(planner_node);
rclcpp::shutdown();
return 0;
}
+431
View File
@@ -0,0 +1,431 @@
#include "aerial_inspection_planner/mesh_utils.hpp"
namespace mesh_utils
{
// From ATL inspection stack with modifications
std::unique_ptr<std::vector<Triangle>> readSTLfile(std::string name, rclcpp::Logger logger_)
{
std::vector<nav_msgs::msg::Path> mesh;
auto inspection_area = std::make_unique<std::vector<Triangle>>();
std::fstream f;
f.open(name.c_str());
assert(f.is_open());
int MaxLine = 0;
char* line = nullptr;
double maxX = -DBL_MAX;
double maxY = -DBL_MAX;
double maxZ = -DBL_MAX;
double minX = DBL_MAX;
double minY = DBL_MAX;
double minZ = DBL_MAX;
line = (char *) malloc(MaxLine = 80);
assert(line != nullptr);
f.getline(line, MaxLine);
// (line) ? RCLCPP_ERROR(logger_, "Getline failed") : RCLCPP_INFO(logger_, "Read first line");
assert(line);
RCLCPP_INFO(logger_, "Opened file and read first line");
char* token = strtok(line, " ");
if (token == NULL)
{
std::cout << "Line: " << line << std::endl << std::endl;
RCLCPP_ERROR(logger_, "Issue reading first line");
rclcpp::shutdown();
return inspection_area;
}
if (0 != strcmp(token, "solid"))
{
RCLCPP_ERROR(logger_, "Invalid mesh file! Make sure the file is given in ascii-format.");
rclcpp::shutdown();
}
RCLCPP_INFO(logger_, "Mesh file is valid");
line = (char *) malloc(MaxLine = 80);
assert(line != nullptr);
f.getline(line, MaxLine);
int k = 0;
while (0 != strcmp(strtok(line, " "), "endsolid")) // && !ros::isShuttingDown()
{
int q = 0;
nav_msgs::msg::Path p;
geometry_msgs::msg::PoseStamped v1;
for (int i = 0; i<7; i++)
{
while (line[q] == ' ')
{
q++;
}
if (line[q] == 'v')
{
const double yawTrafo = 0.0; // used to rotate the mesh before processing
const double scaleFactor = 1.0; // used to scale the mesh before processing
const double offsetX = 0.0; // used to offset the mesh before processing
const double offsetY = 0.0; // used to offset the mesh before processing
const double offsetZ = 0.0; // used to offset the mesh before processing
geometry_msgs::msg::PoseStamped vert;
char* v = strtok(line+q," ");
v = strtok(NULL," ");
double xtmp = atof(v)/scaleFactor;
v = strtok(NULL," ");
double ytmp = atof(v)/scaleFactor;
vert.pose.position.x = cos(yawTrafo)*xtmp-sin(yawTrafo)*ytmp;
vert.pose.position.y = sin(yawTrafo)*xtmp+cos(yawTrafo)*ytmp;
v = strtok(NULL," ");
vert.pose.position.z = atof(v)/scaleFactor;
vert.pose.position.x -= offsetX;
vert.pose.position.y -= offsetY;
vert.pose.position.z -= offsetZ;
if(maxX<vert.pose.position.x)
maxX=vert.pose.position.x;
if(maxY<vert.pose.position.y)
maxY=vert.pose.position.y;
if(maxZ<vert.pose.position.z)
maxZ=vert.pose.position.z;
if(minX>vert.pose.position.x)
minX=vert.pose.position.x;
if(minY>vert.pose.position.y)
minY=vert.pose.position.y;
if(minZ>vert.pose.position.z)
minZ=vert.pose.position.z;
vert.pose.orientation.x = 0.0;
vert.pose.orientation.y = 0.0;
vert.pose.orientation.z = 0.0;
vert.pose.orientation.w = 1.0;
p.poses.push_back(vert);
if(p.poses.size() == 1)
v1 = vert;
}
line = (char *) malloc(MaxLine = 80);
assert(line != nullptr);
f.getline(line, MaxLine);
}
p.poses.push_back(v1);
p.header.frame_id = "/kopt_frame";
// p.header.stamp = ros::Time::now();
mesh.push_back(p);
k++;
}
free(line);
f.close();
RCLCPP_INFO(logger_, "Mesh area is bounded by: [%2.2f,%2.2f]x[%2.2f,%2.2f]x[%2.2f,%2.2f]", minX,maxX,minY,maxY,minZ,maxZ);
for (std::vector<nav_msgs::msg::Path>::iterator it = mesh.begin(); it != mesh.end(); it++)
{
Triangle new_triangle;
Eigen::Vector3f vertex;
vertex[0] = it->poses[0].pose.position.x;
vertex[1] = it->poses[0].pose.position.y;
vertex[2] = it->poses[0].pose.position.z;
new_triangle.vertices[0] = vertex;
vertex[0] = it->poses[1].pose.position.x;
vertex[1] = it->poses[1].pose.position.y;
vertex[2] = it->poses[1].pose.position.z;
new_triangle.vertices[1] = vertex;
vertex[0] = it->poses[2].pose.position.x;
vertex[1] = it->poses[2].pose.position.y;
vertex[2] = it->poses[2].pose.position.z;
new_triangle.vertices[2] = vertex;
inspection_area->push_back(new_triangle);
}
RCLCPP_INFO_STREAM(logger_, "Mesh has " << inspection_area->size() << " triangles");
return inspection_area;
}
Eigen::Vector3f calculate_surface_normal(const Eigen::Vector3f& v0, const Eigen::Vector3f& v1, const Eigen::Vector3f& v2)
{
Eigen::Vector3f edge1 = v1 - v0;
Eigen::Vector3f edge2 = v2 - v0;
Eigen::Vector3f normal = edge1.cross(edge2);
normal.normalize();
return normal;
}
Eigen::Vector3f calculate_centroid(const Eigen::Vector3f& v0, const Eigen::Vector3f& v1, const Eigen::Vector3f& v2)
{
return (v0 + v1 + v2) / 3.0f;
}
Eigen::Quaternionf vector_to_quaternion(const Eigen::Vector3f& unit_vector)
{
// Define the reference direction (z-axis)
Eigen::Vector3f reference_direction(1.0, 0.0, 0.0);
// Create a quaternion and set it from the two vectors
Eigen::Quaternionf quaternion;
quaternion.setFromTwoVectors(reference_direction, unit_vector);
return quaternion;
}
double vector_to_yaw(const Eigen::Vector3f& unit_vector)
{
// Ensure the vector is normalized
Eigen::Vector3f normalized_vector = unit_vector.normalized();
// Calculate the yaw angle (rotation around the z-axis)
double yaw = std::atan2(normalized_vector.y(), normalized_vector.x());
return yaw;
}
// Function to compute the angle between two vectors in degrees
float angle_between_vectors(const Eigen::Vector3f& u, const Eigen::Vector3f& v)
{
// Compute the dot product
float dot_product = u.dot(v);
// Compute the norms of the vectors
float norm_u = u.norm();
float norm_v = v.norm();
// Compute the cosine of the angle
float cos_angle = dot_product / (norm_u * norm_v);
// Clamp the cosine to avoid numerical issues with acos
cos_angle = std::max(-1.0f, std::min(1.0f, cos_angle));
// Compute the angle in radians
float angle_radians = std::acos(cos_angle);
// Convert the angle to degrees
float angle_degrees = angle_radians * 180.0f / M_PI;
return angle_degrees;
}
/*
Checks
- Point within vp fov
- Point within incendent angle from surface normal
- Checks within max view distance
- Checks collisions TODO
*/
bool ray_views_point(const Eigen::Vector3f& vp_pose,
const Eigen::Vector3f& vp_orient,
const Eigen::Vector3f& ray_direction,
const Eigen::Vector3f& surface_normal,
const Eigen::Vector3f& point,
double& max_incidence_angle,
double& max_view_distance,
double& camera_half_fov)
{
// point within fov
if (angle_between_vectors(vp_orient, ray_direction) > camera_half_fov)
{
return false;
}
// point within incendent angle from surface normal
if (angle_between_vectors(surface_normal, -ray_direction) > max_incidence_angle)
{
return false;
}
// Checks Max distance
if ((vp_pose-point).norm() > max_view_distance)
{
return false;
}
return true;
}
// From embree library. Find the closest point between a point and a triangle
Eigen::Vector3f closest_point_to_triangle(Eigen::Vector3f const& p, const Triangle& triangle)
{
const Eigen::Vector3f& a = triangle.vertices[0];
const Eigen::Vector3f& b = triangle.vertices[1];
const Eigen::Vector3f& c = triangle.vertices[2];
const Eigen::Vector3f ab = b - a;
const Eigen::Vector3f ac = c - a;
const Eigen::Vector3f ap = p - a;
const float d1 = ab.dot(ap);
const float d2 = ac.dot(ap);
if (d1 <= 0.f && d2 <= 0.f) return a;
const Eigen::Vector3f bp = p - b;
const float d3 = ab.dot(bp);
const float d4 = ac.dot(bp);
if (d3 >= 0.f && d4 <= d3) return b;
const Eigen::Vector3f cp = p - c;
const float d5 = ab.dot(cp);
const float d6 = ac.dot(cp);
if (d6 >= 0.f && d5 <= d6) return c;
const float vc = d1 * d4 - d3 * d2;
if (vc <= 0.f && d1 >= 0.f && d3 <= 0.f)
{
const float v = d1 / (d1 - d3);
return a + v * ab;
}
const float vb = d5 * d2 - d1 * d6;
if (vb <= 0.f && d2 >= 0.f && d6 <= 0.f)
{
const float v = d2 / (d2 - d6);
return a + v * ac;
}
const float va = d3 * d6 - d5 * d4;
if (va <= 0.f && (d4 - d3) >= 0.f && (d5 - d6) >= 0.f)
{
const float v = (d4 - d3) / ((d4 - d3) + (d5 - d6));
return b + v * (c - b);
}
const float denom = 1.f / (va + vb + vc);
const float v = vb * denom;
const float w = vc * denom;
return a + v * ab + w * ac;
}
float point_to_triangle_distance(const Eigen::Vector3f& point, const mesh_utils::Triangle& triangle) {
Eigen::Vector3f closest_point = mesh_utils::closest_point_to_triangle(point, triangle);
return (closest_point - point).norm();
}
// Overloaded function with default arguments
float closest_distance_between_segments(
const Eigen::Vector3f& a0, const Eigen::Vector3f& a1,
const Eigen::Vector3f& b0, const Eigen::Vector3f& b1) {
return closest_distance_between_segments(a0, a1, b0, b1, true, false, false, false, false);
}
// From https://stackoverflow.com/questions/2824478/shortest-distance-between-two-line-segments
float closest_distance_between_segments(
const Eigen::Vector3f& a0, const Eigen::Vector3f& a1,
const Eigen::Vector3f& b0, const Eigen::Vector3f& b1,
bool clampAll = true, bool clampA0 = false, bool clampA1 = false,
bool clampB0 = false, bool clampB1 = false)
{
// If clampAll is true, set all clamps to true
if (clampAll)
{
clampA0 = true;
clampA1 = true;
clampB0 = true;
clampB1 = true;
}
// Calculate vectors and their magnitudes
Eigen::Vector3f A = a1 - a0;
Eigen::Vector3f B = b1 - b0;
float magA = A.norm();
float magB = B.norm();
Eigen::Vector3f _A = A / magA;
Eigen::Vector3f _B = B / magB;
Eigen::Vector3f cross = _A.cross(_B);
float denom = cross.squaredNorm();
// Define a small epsilon for floating-point comparison
const float epsilon = 1e-6;
// If lines are parallel (denom is close to 0), test if lines overlap
if (denom < epsilon)
{
float d0 = _A.dot(b0 - a0);
// Overlap only possible with clamping
if (clampA0 || clampA1 || clampB0 || clampB1)
{
float d1 = _A.dot(b1 - a0);
// Is segment B before A?
if (d0 <= 0 && d1 <= 0)
{
if (clampA0 && clampB1)
{
if (std::abs(d0) < std::abs(d1))
{
return (a0 - b0).norm();
}
return (a0 - b1).norm();
}
}
// Is segment B after A?
else if (d0 >= magA && d1 >= magA)
{
if (clampA1 && clampB0)
{
if (std::abs(d0) < std::abs(d1))
{
return (a1 - b0).norm();
}
return (a1 - b1).norm();
}
}
}
// Segments overlap, return distance between parallel segments
return ((d0 * _A) + a0 - b0).norm();
}
// Lines criss-cross: Calculate the projected closest points
Eigen::Vector3f t = b0 - a0;
float detA = t.dot(_B.cross(cross));
float detB = t.dot(_A.cross(cross));
float t0 = detA / denom;
float t1 = detB / denom;
Eigen::Vector3f pA = a0 + (_A * t0); // Projected closest point on segment A
Eigen::Vector3f pB = b0 + (_B * t1); // Projected closest point on segment B
// Clamp projections
if (clampA0 || clampA1 || clampB0 || clampB1)
{
if (clampA0 && t0 < 0)
{
pA = a0;
}
else if (clampA1 && t0 > magA)
{
pA = a1;
}
if (clampB0 && t1 < 0)
{
pB = b0;
}
else if (clampB1 && t1 > magB)
{
pB = b1;
}
// Clamp projection A
if ((clampA0 && t0 < 0) || (clampA1 && t0 > magA))
{
float dot = _B.dot(pA - b0);
if (clampB0 && dot < 0)
{
dot = 0;
}
else if (clampB1 && dot > magB)
{
dot = magB;
}
pB = b0 + (_B * dot);
}
// Clamp projection B
if ((clampB0 && t1 < 0) || (clampB1 && t1 > magB))
{
float dot = _A.dot(pB - a0);
if (clampA0 && dot < 0)
{
dot = 0;
}
else if (clampA1 && dot > magA)
{
dot = magA;
}
pA = a0 + (_A * dot);
}
}
return (pA - pB).norm();
}
}
+59
View File
@@ -0,0 +1,59 @@
#include <gtest/gtest.h>
#include "aerial_inspection_planner/cpp_planner.hpp"
#include "aerial_inspection_planner/mesh_utils.hpp"
TEST(package_name, a_first_test)
{
ASSERT_EQ(4, 2 + 2);
ASSERT_TRUE(true);
}
TEST(cpp_planner, point_to_triangle)
{
double abs_error = 0.0001;
mesh_utils::Triangle new_triangle;
Eigen::Vector3f vertex = {0, 0, 0};
vertex[0] = 0;
vertex[1] = 0;
vertex[2] = 0;
new_triangle.vertices[0] = vertex;
vertex[0] = 2;
vertex[1] = 0;
vertex[2] = 0;
new_triangle.vertices[1] = vertex;
vertex[0] = 0;
vertex[1] = 2;
vertex[2] = 0;
new_triangle.vertices[2] = vertex;
Eigen::Vector3f point = {2.0, 2.0, 1.0};
Eigen::Vector3f closest_point = mesh_utils::closest_point_to_triangle(point, new_triangle);
ASSERT_NEAR(closest_point.x(), 1, abs_error);
ASSERT_NEAR(closest_point.y(), 1, abs_error);
ASSERT_NEAR(closest_point.z(), 0, abs_error);
point = {3.0, 0.0, 1.0};
closest_point = mesh_utils::closest_point_to_triangle(point, new_triangle);
ASSERT_NEAR(closest_point.x(), 2, abs_error);
ASSERT_NEAR(closest_point.y(), 0, abs_error);
ASSERT_NEAR(closest_point.z(), 0, abs_error);
}
TEST(cpp_planner, distance_between_segments)
{
double abs_error = 0.0001;
Eigen::Vector3f a0 = {0, 0, 0};
Eigen::Vector3f a1 = {0, 2, 0};
Eigen::Vector3f b0 = {-1, -1, 0};
Eigen::Vector3f b1 = {1, -1, 0};
float dist = mesh_utils::closest_distance_between_segments(a0, a1, b0, b1);
ASSERT_NEAR(dist, 1, abs_error);
}
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}