feat(minco_ws): MID360 + Point-LIO + SCAN/MINCO 导航工作区(19 个包)
- scan/: SCAN 无图局部规划(6 包)+ step_blocker(台阶封堵)+ body_odom(雷达→车体中心) - navigation/: MINCO + Nav2 有图方案;perception/: Livox 驱动 + Point-LIO + rog_map - chassis/: R2 底盘串口桥 - docs/: QUICKSTART(上机流程)/ SCAN_VEHICLE(方案与限制)/ DEPLOY_ROBOT(双机部署) - scripts/: setup_deps.sh(依赖体检/安装)+ deploy_to_robot.sh(rsync 同步/远程编译) 排除 build/ install/ log/、PCD 地图(155 MB,单独 rsync)。
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
cmake_minimum_required(VERSION 3.8)
|
||||
project(body_odom)
|
||||
|
||||
# 同 step_blocker:纯 Python,但用 ament_cmake 安装脚本。
|
||||
# ament_python 装完后前缀没进 AMENT_PREFIX_PATH(缺 ament_prefix_path 钩子),
|
||||
# ros2 run/launch 找不到包;ament_cmake 由 ament_package() 生成钩子,稳定。
|
||||
#
|
||||
# 注意:install(PROGRAMS) 需要脚本带 shebang 且有可执行位。
|
||||
|
||||
find_package(ament_cmake REQUIRED)
|
||||
|
||||
install(PROGRAMS body_odom/body_odom_node.py
|
||||
DESTINATION lib/${PROJECT_NAME}
|
||||
RENAME body_odom)
|
||||
|
||||
install(DIRECTORY config launch
|
||||
DESTINATION share/${PROJECT_NAME})
|
||||
|
||||
ament_package()
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
#!/usr/bin/env python3
|
||||
"""把「雷达里程计」换算成「车体中心里程计」。
|
||||
|
||||
为什么需要:SCAN 里有两个位姿输入,用途不同——
|
||||
|
||||
* ``sensor_pose``:射线起点,必须是**雷达**的位置;
|
||||
* ``body_pose``:轨迹起点、到点判定、双圆柱碰撞中心,必须是**车体中心**。
|
||||
|
||||
Point-LIO 输出的是雷达位姿(它的 body 就是雷达)。雷达不在车体中心时,
|
||||
直接把同一个 odom 喂给两者,会让车停在离目标一个偏移量的地方,并让碰撞模型
|
||||
偏向雷达那一侧。本节点按固定外参把雷达位姿换算成车体中心位姿。
|
||||
|
||||
外参定义(由 yaml 给):
|
||||
|
||||
offset_x / offset_y / offset_z
|
||||
车体中心在**雷达坐标系**下的坐标 [m](x 前、y 左、z 上)。
|
||||
例:雷达装在车体中心正前方 0.30 m、高 0.20 m
|
||||
⇒ 车体中心在雷达后方 0.30、下方 0.20
|
||||
⇒ offset_x=-0.30, offset_y=0.0, offset_z=-0.20
|
||||
|
||||
offset_yaw
|
||||
车体朝向相对雷达朝向的偏航差 [rad],一般 0。
|
||||
|
||||
z 的取法:``body_pose`` 的 z 会直接成为轨迹的高度,也是碰撞检测查询的 z。
|
||||
建议让它落在「车体碰撞参考高度」(离地 0.2~0.3 m),而不是雷达实际高度,
|
||||
否则轨迹会贴太高、漏掉矮障碍。
|
||||
|
||||
twist 原样透传(SCAN 只用 pose,不用 twist)。
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
import rclpy
|
||||
from nav_msgs.msg import Odometry
|
||||
from rclpy.node import Node
|
||||
from rclpy.qos import qos_profile_sensor_data
|
||||
|
||||
|
||||
def _yaw_from_quat(q):
|
||||
# yaw (z 轴),输入 geometry_msgs Quaternion
|
||||
siny_cosp = 2.0 * (q.w * q.z + q.x * q.y)
|
||||
cosy_cosp = 1.0 - 2.0 * (q.y * q.y + q.z * q.z)
|
||||
return math.atan2(siny_cosp, cosy_cosp)
|
||||
|
||||
|
||||
class BodyOdom(Node):
|
||||
def __init__(self):
|
||||
super().__init__('body_odom')
|
||||
|
||||
self.declare_parameter('input_topic', '/aft_mapped_to_init')
|
||||
self.declare_parameter('output_topic', '/body_odom')
|
||||
self.declare_parameter('offset_x', 0.0)
|
||||
self.declare_parameter('offset_y', 0.0)
|
||||
self.declare_parameter('offset_z', 0.0)
|
||||
self.declare_parameter('offset_yaw', 0.0)
|
||||
self.declare_parameter('child_frame_id', 'base_link')
|
||||
|
||||
self.ox = float(self.get_parameter('offset_x').value)
|
||||
self.oy = float(self.get_parameter('offset_y').value)
|
||||
self.oz = float(self.get_parameter('offset_z').value)
|
||||
self.oyaw = float(self.get_parameter('offset_yaw').value)
|
||||
self.child = str(self.get_parameter('child_frame_id').value)
|
||||
|
||||
in_topic = self.get_parameter('input_topic').value
|
||||
out_topic = self.get_parameter('output_topic').value
|
||||
|
||||
self.pub = self.create_publisher(Odometry, out_topic, qos_profile_sensor_data)
|
||||
self.sub = self.create_subscription(
|
||||
Odometry, in_topic, self._cb, qos_profile_sensor_data)
|
||||
|
||||
self.get_logger().info(
|
||||
f'body_odom: {in_topic} -> {out_topic}, '
|
||||
f'offset=({self.ox:.3f}, {self.oy:.3f}, {self.oz:.3f}) m, '
|
||||
f'yaw_offset={self.oyaw:.3f} rad')
|
||||
|
||||
def _cb(self, msg):
|
||||
yaw = _yaw_from_quat(msg.pose.pose.orientation)
|
||||
c, s = math.cos(yaw), math.sin(yaw)
|
||||
|
||||
# 车体中心 = 雷达位置 + R(yaw) * offset
|
||||
px = msg.pose.pose.position.x + c * self.ox - s * self.oy
|
||||
py = msg.pose.pose.position.y + s * self.ox + c * self.oy
|
||||
pz = msg.pose.pose.position.z + self.oz
|
||||
|
||||
yaw_body = yaw + self.oyaw
|
||||
|
||||
out = Odometry()
|
||||
out.header = msg.header
|
||||
out.child_frame_id = self.child
|
||||
out.pose.pose.position.x = px
|
||||
out.pose.pose.position.y = py
|
||||
out.pose.pose.position.z = pz
|
||||
out.pose.pose.orientation.z = math.sin(yaw_body * 0.5)
|
||||
out.pose.pose.orientation.w = math.cos(yaw_body * 0.5)
|
||||
out.pose.pose.orientation.x = 0.0
|
||||
out.pose.pose.orientation.y = 0.0
|
||||
# 协方差按原样透传(SCAN 不使用)
|
||||
out.pose.covariance = msg.pose.covariance
|
||||
out.twist = msg.twist
|
||||
|
||||
self.pub.publish(out)
|
||||
|
||||
|
||||
def main(args=None):
|
||||
rclpy.init(args=args)
|
||||
node = BodyOdom()
|
||||
try:
|
||||
rclpy.spin(node)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
node.destroy_node()
|
||||
if rclpy.ok():
|
||||
rclpy.shutdown()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,21 @@
|
||||
# 雷达 -> 车体中心 的外参。
|
||||
#
|
||||
# offset_x/y/z = 车体中心在【雷达坐标系】下的坐标 [m](x 前、y 左、z 上)。
|
||||
# 例:雷达装在车体中心正前方 0.30 m、高 0.20 m
|
||||
# ⇒ 车体中心在雷达后方 0.30、下方 0.20
|
||||
# ⇒ offset_x: -0.30, offset_y: 0.0, offset_z: -0.20
|
||||
#
|
||||
# offset_z 建议让输出的 z 落在「车体碰撞参考高度」(离地 0.2~0.3 m):
|
||||
# SCAN 用这个 z 去碰撞检测查询体素,z 太高会漏掉矮障碍。
|
||||
#
|
||||
# 全 0 = 与雷达里程计完全一致(雷达就在车体中心时的默认)。
|
||||
|
||||
body_odom:
|
||||
ros__parameters:
|
||||
input_topic: /aft_mapped_to_init
|
||||
output_topic: /body_odom
|
||||
offset_x: 0.0
|
||||
offset_y: 0.0
|
||||
offset_z: 0.0
|
||||
offset_yaw: 0.0
|
||||
child_frame_id: base_link
|
||||
@@ -0,0 +1,61 @@
|
||||
"""启动雷达->车体中心 的里程计换算。
|
||||
|
||||
ros2 launch body_odom body_odom.launch.py
|
||||
# 临时改外参,不改 yaml
|
||||
ros2 launch body_odom body_odom.launch.py offset_x:=-0.30 offset_z:=-0.20
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from ament_index_python.packages import get_package_share_directory
|
||||
from launch import LaunchDescription
|
||||
from launch.actions import DeclareLaunchArgument
|
||||
from launch.substitutions import LaunchConfiguration
|
||||
from launch_ros.actions import Node
|
||||
|
||||
|
||||
def _yaml_default(params_file, name, fallback='0.0'):
|
||||
try:
|
||||
import yaml
|
||||
with open(params_file, 'r') as f:
|
||||
p = yaml.safe_load(f)['body_odom']['ros__parameters']
|
||||
return str(p[name])
|
||||
except Exception:
|
||||
return fallback
|
||||
|
||||
|
||||
def generate_launch_description():
|
||||
share = get_package_share_directory('body_odom')
|
||||
default_params = os.path.join(share, 'config', 'body_odom.yaml')
|
||||
|
||||
declared = [
|
||||
DeclareLaunchArgument(
|
||||
'params_file', default_value=default_params,
|
||||
description='参数文件(install 里是拷贝;改了 src 那份要重建)'),
|
||||
DeclareLaunchArgument(
|
||||
'offset_x', default_value=_yaml_default(default_params, 'offset_x')),
|
||||
DeclareLaunchArgument(
|
||||
'offset_y', default_value=_yaml_default(default_params, 'offset_y')),
|
||||
DeclareLaunchArgument(
|
||||
'offset_z', default_value=_yaml_default(default_params, 'offset_z')),
|
||||
DeclareLaunchArgument(
|
||||
'offset_yaw', default_value=_yaml_default(default_params, 'offset_yaw')),
|
||||
]
|
||||
|
||||
node = Node(
|
||||
package='body_odom',
|
||||
executable='body_odom',
|
||||
name='body_odom',
|
||||
output='screen',
|
||||
parameters=[
|
||||
LaunchConfiguration('params_file'),
|
||||
{
|
||||
'offset_x': LaunchConfiguration('offset_x'),
|
||||
'offset_y': LaunchConfiguration('offset_y'),
|
||||
'offset_z': LaunchConfiguration('offset_z'),
|
||||
'offset_yaw': LaunchConfiguration('offset_yaw'),
|
||||
},
|
||||
],
|
||||
)
|
||||
|
||||
return LaunchDescription(declared + [node])
|
||||
@@ -0,0 +1,20 @@
|
||||
<?xml version="1.0"?>
|
||||
<package format="3">
|
||||
<name>body_odom</name>
|
||||
<version>0.1.0</version>
|
||||
<description>Convert lidar odometry to body-center odometry using a fixed extrinsic.</description>
|
||||
<maintainer email="[email protected]">kevin</maintainer>
|
||||
<license>Apache-2.0</license>
|
||||
|
||||
<buildtool_depend>ament_cmake</buildtool_depend>
|
||||
|
||||
<exec_depend>rclpy</exec_depend>
|
||||
<exec_depend>nav_msgs</exec_depend>
|
||||
<exec_depend>launch</exec_depend>
|
||||
<exec_depend>launch_ros</exec_depend>
|
||||
<exec_depend>ament_index_python</exec_depend>
|
||||
|
||||
<export>
|
||||
<build_type>ament_cmake</build_type>
|
||||
</export>
|
||||
</package>
|
||||
@@ -0,0 +1,39 @@
|
||||
cmake_minimum_required(VERSION 3.8)
|
||||
project(bspline_opt)
|
||||
|
||||
if(NOT CMAKE_CXX_STANDARD)
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
endif()
|
||||
add_compile_options(-Wall -Wextra -Wpedantic)
|
||||
|
||||
find_package(ament_cmake REQUIRED)
|
||||
find_package(Eigen3 REQUIRED)
|
||||
find_package(path_searching REQUIRED)
|
||||
find_package(plan_env REQUIRED)
|
||||
find_package(rclcpp REQUIRED)
|
||||
|
||||
add_library(bspline_opt
|
||||
src/uniform_bspline.cpp
|
||||
src/bspline_optimizer.cpp
|
||||
src/gradient_descent_optimizer.cpp)
|
||||
target_include_directories(bspline_opt PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>)
|
||||
ament_target_dependencies(bspline_opt path_searching plan_env rclcpp)
|
||||
target_link_libraries(bspline_opt Eigen3::Eigen)
|
||||
|
||||
install(TARGETS bspline_opt EXPORT export_bspline_opt
|
||||
ARCHIVE DESTINATION lib LIBRARY DESTINATION lib RUNTIME DESTINATION bin)
|
||||
install(DIRECTORY include/ DESTINATION include)
|
||||
ament_export_targets(export_bspline_opt HAS_LIBRARY_TARGET)
|
||||
ament_export_dependencies(Eigen3 path_searching plan_env rclcpp)
|
||||
|
||||
if(BUILD_TESTING)
|
||||
find_package(ament_cmake_gtest REQUIRED)
|
||||
ament_add_gtest(test_uniform_bspline test/test_uniform_bspline.cpp)
|
||||
if(TARGET test_uniform_bspline)
|
||||
target_link_libraries(test_uniform_bspline bspline_opt Eigen3::Eigen)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
ament_package()
|
||||
@@ -0,0 +1,162 @@
|
||||
#ifndef _BSPLINE_OPTIMIZER_H_
|
||||
#define _BSPLINE_OPTIMIZER_H_
|
||||
|
||||
#include <Eigen/Eigen>
|
||||
#include <path_searching/dyn_a_star.h>
|
||||
#include <bspline_opt/uniform_bspline.h>
|
||||
#include <plan_env/grid_map.h>
|
||||
#include <rclcpp/rclcpp.hpp>
|
||||
#include "bspline_opt/lbfgs.hpp"
|
||||
|
||||
// Gradient and elastic band optimization
|
||||
|
||||
// Input: a signed distance field and a sequence of points
|
||||
// Output: the optimized sequence of points
|
||||
// The format of points: N x 3 matrix, each row is a point
|
||||
namespace scan_planner
|
||||
{
|
||||
|
||||
class ControlPoints
|
||||
{
|
||||
public:
|
||||
double clearance;
|
||||
int size;
|
||||
Eigen::MatrixXd points;
|
||||
std::vector<std::vector<Eigen::Vector3d>> base_point; // The point at the start of the direction vector (collision point)
|
||||
std::vector<std::vector<Eigen::Vector3d>> direction; // Direction vector, must be normalized.
|
||||
std::vector<bool> flag_temp; // A flag that used in many places. Initialize it every time before using it.
|
||||
// std::vector<bool> occupancy;
|
||||
|
||||
void resize(const int size_set)
|
||||
{
|
||||
size = size_set;
|
||||
|
||||
base_point.clear();
|
||||
direction.clear();
|
||||
flag_temp.clear();
|
||||
// occupancy.clear();
|
||||
|
||||
points.resize(3, size_set);
|
||||
base_point.resize(size);
|
||||
direction.resize(size);
|
||||
flag_temp.resize(size);
|
||||
// occupancy.resize(size);
|
||||
}
|
||||
};
|
||||
|
||||
class BsplineOptimizer
|
||||
{
|
||||
|
||||
public:
|
||||
BsplineOptimizer() {}
|
||||
~BsplineOptimizer() {}
|
||||
|
||||
/* main API */
|
||||
void setEnvironment(const GridMap::Ptr &env);
|
||||
void setParam(rclcpp::Node *node);
|
||||
Eigen::MatrixXd BsplineOptimizeTraj(const Eigen::MatrixXd &points, const double &ts,
|
||||
const int &cost_function, int max_num_id, int max_time_id);
|
||||
|
||||
/* helper function */
|
||||
|
||||
// required inputs
|
||||
void setControlPoints(const Eigen::MatrixXd &points);
|
||||
void setBsplineInterval(const double &ts);
|
||||
void setCostFunction(const int &cost_function);
|
||||
void setTerminateCond(const int &max_num_id, const int &max_time_id);
|
||||
|
||||
// optional inputs
|
||||
void setGuidePath(const vector<Eigen::Vector3d> &guide_pt);
|
||||
void setWaypoints(const vector<Eigen::Vector3d> &waypts,
|
||||
const vector<int> &waypt_idx); // N-2 constraints at most
|
||||
|
||||
void optimize();
|
||||
|
||||
Eigen::MatrixXd getControlPoints();
|
||||
|
||||
AStar::Ptr a_star_;
|
||||
std::vector<Eigen::Vector3d> ref_pts_;
|
||||
|
||||
std::vector<std::vector<Eigen::Vector3d>> initControlPoints(Eigen::MatrixXd &init_points, bool flag_first_init = true);
|
||||
bool BsplineOptimizeTrajRebound(Eigen::MatrixXd &optimal_points, double ts); // must be called after initControlPoints()
|
||||
bool BsplineOptimizeTrajRefine(const Eigen::MatrixXd &init_points, const double ts, Eigen::MatrixXd &optimal_points);
|
||||
|
||||
inline int getOrder(void) { return order_; }
|
||||
|
||||
private:
|
||||
GridMap::Ptr grid_map_;
|
||||
|
||||
enum FORCE_STOP_OPTIMIZE_TYPE
|
||||
{
|
||||
DONT_STOP,
|
||||
STOP_FOR_REBOUND,
|
||||
STOP_FOR_ERROR
|
||||
} force_stop_type_;
|
||||
|
||||
// main input
|
||||
// Eigen::MatrixXd control_points_; // B-spline control points, N x dim
|
||||
double bspline_interval_; // B-spline knot span
|
||||
Eigen::Vector3d end_pt_; // end of the trajectory
|
||||
// int dim_; // dimension of the B-spline
|
||||
//
|
||||
vector<Eigen::Vector3d> guide_pts_; // geometric guiding path points, N-6
|
||||
vector<Eigen::Vector3d> waypoints_; // waypts constraints
|
||||
vector<int> waypt_idx_; // waypts constraints index
|
||||
//
|
||||
int max_num_id_, max_time_id_; // stopping criteria
|
||||
int cost_function_; // used to determine objective function
|
||||
double start_time_; // global time for moving obstacles
|
||||
|
||||
/* optimization parameters */
|
||||
int order_; // bspline degree
|
||||
double lambda1_; // jerk smoothness weight
|
||||
double lambda2_, new_lambda2_; // distance weight
|
||||
double lambda3_; // feasibility weight
|
||||
double lambda4_; // curve fitting
|
||||
int a;
|
||||
//
|
||||
double dist0_; // safe distance
|
||||
double max_vel_, max_acc_; // dynamic limits
|
||||
|
||||
int variable_num_; // optimization variables
|
||||
int iter_num_; // iteration of the solver
|
||||
Eigen::VectorXd best_variable_; //
|
||||
double min_cost_; //
|
||||
|
||||
ControlPoints cps_;
|
||||
|
||||
/* cost function */
|
||||
/* calculate each part of cost function with control points q as input */
|
||||
|
||||
static double costFunction(const std::vector<double> &x, std::vector<double> &grad, void *func_data);
|
||||
void combineCost(const std::vector<double> &x, vector<double> &grad, double &cost);
|
||||
|
||||
// q contains all control points
|
||||
void calcSmoothnessCost(const Eigen::MatrixXd &q, double &cost,
|
||||
Eigen::MatrixXd &gradient, bool falg_use_jerk = true);
|
||||
void calcFeasibilityCost(const Eigen::MatrixXd &q, double &cost,
|
||||
Eigen::MatrixXd &gradient);
|
||||
void calcDistanceCostRebound(const Eigen::MatrixXd &q, double &cost, Eigen::MatrixXd &gradient, int iter_num, double smoothness_cost);
|
||||
void calcFitnessCost(const Eigen::MatrixXd &q, double &cost, Eigen::MatrixXd &gradient);
|
||||
bool check_collision_and_rebound(void);
|
||||
double estimateSegmentYaw(const Eigen::Vector3d &from, const Eigen::Vector3d &to) const;
|
||||
double estimateControlPointYaw(const Eigen::MatrixXd &q, int id) const;
|
||||
|
||||
static int earlyExit(void *func_data, const double *x, const double *g, const double fx, const double xnorm, const double gnorm, const double step, int n, int k, int ls);
|
||||
static double costFunctionRebound(void *func_data, const double *x, double *grad, const int n);
|
||||
static double costFunctionRefine(void *func_data, const double *x, double *grad, const int n);
|
||||
|
||||
bool rebound_optimize();
|
||||
bool refine_optimize();
|
||||
void combineCostRebound(const double *x, double *grad, double &f_combine, const int n);
|
||||
void combineCostRefine(const double *x, double *grad, double &f_combine, const int n);
|
||||
|
||||
/* for benchmark evaluation only */
|
||||
public:
|
||||
typedef unique_ptr<BsplineOptimizer> Ptr;
|
||||
|
||||
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
|
||||
};
|
||||
|
||||
} // namespace scan_planner
|
||||
#endif
|
||||
@@ -0,0 +1,53 @@
|
||||
#ifndef _GRADIENT_DESCENT_OPT_H_
|
||||
#define _GRADIENT_DESCENT_OPT_H_
|
||||
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#include <vector>
|
||||
#include <Eigen/Eigen>
|
||||
|
||||
using namespace std;
|
||||
|
||||
class GradientDescentOptimizer
|
||||
{
|
||||
|
||||
public:
|
||||
EIGEN_MAKE_ALIGNED_OPERATOR_NEW;
|
||||
|
||||
typedef double (*objfunDef)(const Eigen::VectorXd &x, Eigen::VectorXd &grad, bool &force_return, void *data);
|
||||
enum RESULT
|
||||
{
|
||||
FIND_MIN,
|
||||
FAILED,
|
||||
RETURN_BY_ORDER,
|
||||
REACH_MAX_ITERATION
|
||||
};
|
||||
|
||||
GradientDescentOptimizer(int v_num, objfunDef objf, void *f_data)
|
||||
{
|
||||
variable_num_ = v_num;
|
||||
objfun_ = objf;
|
||||
f_data_ = f_data;
|
||||
};
|
||||
|
||||
void set_maxiter(int limit) { iter_limit_ = limit; }
|
||||
void set_maxeval(int limit) { invoke_limit_ = limit; }
|
||||
void set_xtol_rel(double xtol_rel) { xtol_rel_ = xtol_rel; }
|
||||
void set_xtol_abs(double xtol_abs) { xtol_abs_ = xtol_abs; }
|
||||
void set_min_grad(double min_grad) { min_grad_ = min_grad; }
|
||||
|
||||
RESULT optimize(Eigen::VectorXd &x_init_optimal, double &opt_f);
|
||||
|
||||
private:
|
||||
int variable_num_{0};
|
||||
int iter_limit_{std::numeric_limits<int>::max()};
|
||||
int invoke_limit_{std::numeric_limits<int>::max()};
|
||||
double xtol_rel_;
|
||||
double xtol_abs_;
|
||||
double min_grad_;
|
||||
double time_limit_;
|
||||
void *f_data_;
|
||||
objfunDef objfun_;
|
||||
};
|
||||
|
||||
#endif
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,80 @@
|
||||
#ifndef _UNIFORM_BSPLINE_H_
|
||||
#define _UNIFORM_BSPLINE_H_
|
||||
|
||||
#include <Eigen/Eigen>
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
namespace scan_planner
|
||||
{
|
||||
// An implementation of non-uniform B-spline with different dimensions
|
||||
// It also represents uniform B-spline which is a special case of non-uniform
|
||||
class UniformBspline
|
||||
{
|
||||
private:
|
||||
// control points for B-spline with different dimensions.
|
||||
// Each row represents one single control point
|
||||
// The dimension is determined by column number
|
||||
// e.g. B-spline with N points in 3D space -> Nx3 matrix
|
||||
Eigen::MatrixXd control_points_;
|
||||
|
||||
int p_, n_, m_; // p degree, n+1 control points, m = n+p+1
|
||||
Eigen::VectorXd u_; // knots vector
|
||||
double interval_; // knot span \delta t
|
||||
|
||||
Eigen::MatrixXd getDerivativeControlPoints();
|
||||
|
||||
double limit_vel_, limit_acc_, feasibility_tolerance_; // physical limits and feasibility tolerance
|
||||
|
||||
public:
|
||||
UniformBspline() {}
|
||||
UniformBspline(const Eigen::MatrixXd &points, const int &order, const double &interval);
|
||||
~UniformBspline();
|
||||
|
||||
Eigen::MatrixXd get_control_points(void) { return control_points_; }
|
||||
|
||||
// initialize as an uniform B-spline
|
||||
void setUniformBspline(const Eigen::MatrixXd &points, const int &order, const double &interval);
|
||||
|
||||
// get / set basic bspline info
|
||||
|
||||
void setKnot(const Eigen::VectorXd &knot);
|
||||
Eigen::VectorXd getKnot();
|
||||
Eigen::MatrixXd getControlPoint();
|
||||
double getInterval();
|
||||
bool getTimeSpan(double &um, double &um_p);
|
||||
|
||||
// compute position / derivative
|
||||
|
||||
Eigen::VectorXd evaluateDeBoor(const double &u) const; // use u \in [up, u_mp]
|
||||
inline Eigen::VectorXd evaluateDeBoorT(const double &t) const { return evaluateDeBoor(t + u_(p_)); } // use t \in [0, duration]
|
||||
UniformBspline getDerivative();
|
||||
|
||||
// 3D B-spline interpolation of points in point_set, with boundary vel&acc
|
||||
// constraints
|
||||
// input : (K+2) points with boundary vel/acc; ts
|
||||
// output: (K+6) control_pts
|
||||
static void parameterizeToBspline(const double &ts, const vector<Eigen::Vector3d> &point_set,
|
||||
const vector<Eigen::Vector3d> &start_end_derivative,
|
||||
Eigen::MatrixXd &ctrl_pts);
|
||||
|
||||
/* check feasibility, adjust time */
|
||||
|
||||
void setPhysicalLimits(const double &vel, const double &acc, const double &tolerance);
|
||||
bool checkFeasibility(double &ratio, bool show = false);
|
||||
void lengthenTime(const double &ratio);
|
||||
|
||||
/* for performance evaluation */
|
||||
|
||||
double getTimeSum();
|
||||
double getLength(const double &res = 0.01);
|
||||
double getJerk();
|
||||
void getMeanAndMaxVel(double &mean_v, double &max_v);
|
||||
void getMeanAndMaxAcc(double &mean_a, double &max_a);
|
||||
|
||||
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
|
||||
};
|
||||
} // namespace scan_planner
|
||||
#endif
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0"?>
|
||||
<package format="3">
|
||||
<name>bspline_opt</name>
|
||||
<version>0.1.0</version>
|
||||
<description>B-spline trajectory optimization for SCAN-Planner.</description>
|
||||
<maintainer email="[email protected]">SCAN-Planner maintainers</maintainer>
|
||||
<license>Apache-2.0</license>
|
||||
<buildtool_depend>ament_cmake</buildtool_depend>
|
||||
<depend>eigen</depend>
|
||||
<depend>path_searching</depend>
|
||||
<depend>plan_env</depend>
|
||||
<depend>rclcpp</depend>
|
||||
<test_depend>ament_cmake_gtest</test_depend>
|
||||
<export><build_type>ament_cmake</build_type></export>
|
||||
</package>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,94 @@
|
||||
#include <bspline_opt/gradient_descent_optimizer.h>
|
||||
|
||||
#define RESET "\033[0m"
|
||||
#define RED "\033[31m"
|
||||
|
||||
GradientDescentOptimizer::RESULT
|
||||
GradientDescentOptimizer::optimize(Eigen::VectorXd &x_init_optimal, double &opt_f)
|
||||
{
|
||||
if (min_grad_ < 1e-10)
|
||||
{
|
||||
cout << RED << "min_grad_ is invalid:" << min_grad_ << RESET << endl;
|
||||
return FAILED;
|
||||
}
|
||||
if (iter_limit_ <= 2)
|
||||
{
|
||||
cout << RED << "iter_limit_ is invalid:" << iter_limit_ << RESET << endl;
|
||||
return FAILED;
|
||||
}
|
||||
|
||||
void *f_data = f_data_;
|
||||
int iter = 2;
|
||||
int invoke_count = 2;
|
||||
bool force_return;
|
||||
Eigen::VectorXd x_k(x_init_optimal), x_kp1(x_init_optimal.rows());
|
||||
double cost_k, cost_kp1, cost_min;
|
||||
Eigen::VectorXd grad_k(x_init_optimal.rows()), grad_kp1(x_init_optimal.rows());
|
||||
|
||||
cost_k = objfun_(x_k, grad_k, force_return, f_data);
|
||||
if (force_return)
|
||||
return RETURN_BY_ORDER;
|
||||
cost_min = cost_k;
|
||||
double max_grad = max(abs(grad_k.maxCoeff()), abs(grad_k.minCoeff()));
|
||||
constexpr double MAX_MOVEMENT_AT_FIRST_ITERATION = 0.1; // meter
|
||||
double alpha0 = max_grad < MAX_MOVEMENT_AT_FIRST_ITERATION ? 1.0 : (MAX_MOVEMENT_AT_FIRST_ITERATION / max_grad);
|
||||
x_kp1 = x_k - alpha0 * grad_k;
|
||||
cost_kp1 = objfun_(x_kp1, grad_kp1, force_return, f_data);
|
||||
if (force_return)
|
||||
return RETURN_BY_ORDER;
|
||||
if (cost_min > cost_kp1)
|
||||
cost_min = cost_kp1;
|
||||
|
||||
/*** start iteration ***/
|
||||
while (++iter <= iter_limit_ && invoke_count <= invoke_limit_)
|
||||
{
|
||||
Eigen::VectorXd s = x_kp1 - x_k;
|
||||
Eigen::VectorXd y = grad_kp1 - grad_k;
|
||||
double alpha = s.dot(y) / y.dot(y);
|
||||
if (isnan(alpha) || isinf(alpha))
|
||||
{
|
||||
cout << RED << "step size invalid! alpha=" << alpha << RESET << endl;
|
||||
return FAILED;
|
||||
}
|
||||
|
||||
if (iter % 2) // to avoid copying operations
|
||||
{
|
||||
do
|
||||
{
|
||||
x_k = x_kp1 - alpha * grad_kp1;
|
||||
cost_k = objfun_(x_k, grad_k, force_return, f_data);
|
||||
invoke_count++;
|
||||
if (force_return)
|
||||
return RETURN_BY_ORDER;
|
||||
alpha *= 0.5;
|
||||
} while (cost_k > cost_kp1 - 1e-4 * alpha * grad_kp1.transpose() * grad_kp1); // Armijo condition
|
||||
|
||||
if (grad_k.norm() < min_grad_)
|
||||
{
|
||||
opt_f = cost_k;
|
||||
return FIND_MIN;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
do
|
||||
{
|
||||
x_kp1 = x_k - alpha * grad_k;
|
||||
cost_kp1 = objfun_(x_kp1, grad_kp1, force_return, f_data);
|
||||
invoke_count++;
|
||||
if (force_return)
|
||||
return RETURN_BY_ORDER;
|
||||
alpha *= 0.5;
|
||||
} while (cost_kp1 > cost_k - 1e-4 * alpha * grad_k.transpose() * grad_k); // Armijo condition
|
||||
|
||||
if (grad_kp1.norm() < min_grad_)
|
||||
{
|
||||
opt_f = cost_kp1;
|
||||
return FIND_MIN;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
opt_f = iter_limit_ % 2 ? cost_k : cost_kp1;
|
||||
return REACH_MAX_ITERATION;
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
#include "bspline_opt/uniform_bspline.h"
|
||||
|
||||
namespace scan_planner
|
||||
{
|
||||
|
||||
UniformBspline::UniformBspline(const Eigen::MatrixXd &points, const int &order,
|
||||
const double &interval)
|
||||
{
|
||||
setUniformBspline(points, order, interval);
|
||||
}
|
||||
|
||||
UniformBspline::~UniformBspline() {}
|
||||
|
||||
void UniformBspline::setUniformBspline(const Eigen::MatrixXd &points, const int &order,
|
||||
const double &interval)
|
||||
{
|
||||
control_points_ = points;
|
||||
p_ = order;
|
||||
interval_ = interval;
|
||||
|
||||
n_ = points.cols() - 1;
|
||||
m_ = n_ + p_ + 1;
|
||||
|
||||
u_ = Eigen::VectorXd::Zero(m_ + 1);
|
||||
for (int i = 0; i <= m_; ++i)
|
||||
{
|
||||
|
||||
if (i <= p_)
|
||||
{
|
||||
u_(i) = double(-p_ + i) * interval_;
|
||||
}
|
||||
else if (i > p_ && i <= m_ - p_)
|
||||
{
|
||||
u_(i) = u_(i - 1) + interval_;
|
||||
}
|
||||
else if (i > m_ - p_)
|
||||
{
|
||||
u_(i) = u_(i - 1) + interval_;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void UniformBspline::setKnot(const Eigen::VectorXd &knot) { this->u_ = knot; }
|
||||
|
||||
Eigen::VectorXd UniformBspline::getKnot() { return this->u_; }
|
||||
|
||||
bool UniformBspline::getTimeSpan(double &um, double &um_p)
|
||||
{
|
||||
if (p_ > u_.rows() || m_ - p_ > u_.rows())
|
||||
return false;
|
||||
|
||||
um = u_(p_);
|
||||
um_p = u_(m_ - p_);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
Eigen::MatrixXd UniformBspline::getControlPoint() { return control_points_; }
|
||||
|
||||
Eigen::VectorXd UniformBspline::evaluateDeBoor(const double &u) const
|
||||
{
|
||||
|
||||
double ub = min(max(u_(p_), u), u_(m_ - p_));
|
||||
|
||||
// determine which [ui,ui+1] lay in
|
||||
int k = p_;
|
||||
while (true)
|
||||
{
|
||||
if (u_(k + 1) >= ub)
|
||||
break;
|
||||
++k;
|
||||
}
|
||||
|
||||
/* deBoor's alg */
|
||||
vector<Eigen::VectorXd> d;
|
||||
for (int i = 0; i <= p_; ++i)
|
||||
{
|
||||
d.push_back(control_points_.col(k - p_ + i));
|
||||
// cout << d[i].transpose() << endl;
|
||||
}
|
||||
|
||||
for (int r = 1; r <= p_; ++r)
|
||||
{
|
||||
for (int i = p_; i >= r; --i)
|
||||
{
|
||||
double alpha = (ub - u_[i + k - p_]) / (u_[i + 1 + k - r] - u_[i + k - p_]);
|
||||
// cout << "alpha: " << alpha << endl;
|
||||
d[i] = (1 - alpha) * d[i - 1] + alpha * d[i];
|
||||
}
|
||||
}
|
||||
|
||||
return d[p_];
|
||||
}
|
||||
|
||||
// Eigen::VectorXd UniformBspline::evaluateDeBoorT(const double& t) {
|
||||
// return evaluateDeBoor(t + u_(p_));
|
||||
// }
|
||||
|
||||
Eigen::MatrixXd UniformBspline::getDerivativeControlPoints()
|
||||
{
|
||||
// The derivative of a b-spline is also a b-spline, its order become p_-1
|
||||
// control point Qi = p_*(Pi+1-Pi)/(ui+p_+1-ui+1)
|
||||
Eigen::MatrixXd ctp(control_points_.rows(), control_points_.cols() - 1);
|
||||
for (int i = 0; i < ctp.cols(); ++i)
|
||||
{
|
||||
ctp.col(i) =
|
||||
p_ * (control_points_.col(i + 1) - control_points_.col(i)) / (u_(i + p_ + 1) - u_(i + 1));
|
||||
}
|
||||
return ctp;
|
||||
}
|
||||
|
||||
UniformBspline UniformBspline::getDerivative()
|
||||
{
|
||||
Eigen::MatrixXd ctp = getDerivativeControlPoints();
|
||||
UniformBspline derivative(ctp, p_ - 1, interval_);
|
||||
|
||||
/* cut the first and last knot */
|
||||
Eigen::VectorXd knot(u_.rows() - 2);
|
||||
knot = u_.segment(1, u_.rows() - 2);
|
||||
derivative.setKnot(knot);
|
||||
|
||||
return derivative;
|
||||
}
|
||||
|
||||
double UniformBspline::getInterval() { return interval_; }
|
||||
|
||||
void UniformBspline::setPhysicalLimits(const double &vel, const double &acc, const double &tolerance)
|
||||
{
|
||||
limit_vel_ = vel;
|
||||
limit_acc_ = acc;
|
||||
feasibility_tolerance_ = tolerance;
|
||||
}
|
||||
|
||||
bool UniformBspline::checkFeasibility(double &ratio, bool show)
|
||||
{
|
||||
bool fea = true;
|
||||
|
||||
Eigen::MatrixXd P = control_points_;
|
||||
int dimension = control_points_.rows();
|
||||
|
||||
/* check vel feasibility and insert points */
|
||||
double max_vel = -1.0;
|
||||
double enlarged_vel_lim = limit_vel_ * (1.0 + feasibility_tolerance_) + 1e-4;
|
||||
for (int i = 0; i < P.cols() - 1; ++i)
|
||||
{
|
||||
Eigen::VectorXd vel = p_ * (P.col(i + 1) - P.col(i)) / (u_(i + p_ + 1) - u_(i + 1));
|
||||
|
||||
if (fabs(vel(0)) > enlarged_vel_lim || fabs(vel(1)) > enlarged_vel_lim ||
|
||||
fabs(vel(2)) > enlarged_vel_lim)
|
||||
{
|
||||
|
||||
if (show)
|
||||
cout << "[Check]: Infeasible vel " << i << " :" << vel.transpose() << endl;
|
||||
fea = false;
|
||||
|
||||
for (int j = 0; j < dimension; ++j)
|
||||
{
|
||||
max_vel = max(max_vel, fabs(vel(j)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* acc feasibility */
|
||||
double max_acc = -1.0;
|
||||
double enlarged_acc_lim = limit_acc_ * (1.0 + feasibility_tolerance_) + 1e-4;
|
||||
for (int i = 0; i < P.cols() - 2; ++i)
|
||||
{
|
||||
|
||||
Eigen::VectorXd acc = p_ * (p_ - 1) *
|
||||
((P.col(i + 2) - P.col(i + 1)) / (u_(i + p_ + 2) - u_(i + 2)) -
|
||||
(P.col(i + 1) - P.col(i)) / (u_(i + p_ + 1) - u_(i + 1))) /
|
||||
(u_(i + p_ + 1) - u_(i + 2));
|
||||
|
||||
if (fabs(acc(0)) > enlarged_acc_lim || fabs(acc(1)) > enlarged_acc_lim ||
|
||||
fabs(acc(2)) > enlarged_acc_lim)
|
||||
{
|
||||
|
||||
if (show)
|
||||
cout << "[Check]: Infeasible acc " << i << " :" << acc.transpose() << endl;
|
||||
fea = false;
|
||||
|
||||
for (int j = 0; j < dimension; ++j)
|
||||
{
|
||||
max_acc = max(max_acc, fabs(acc(j)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ratio = max(max_vel / limit_vel_, sqrt(fabs(max_acc) / limit_acc_));
|
||||
|
||||
return fea;
|
||||
}
|
||||
|
||||
void UniformBspline::lengthenTime(const double &ratio)
|
||||
{
|
||||
int num1 = 5;
|
||||
int num2 = getKnot().rows() - 1 - 5;
|
||||
|
||||
double delta_t = (ratio - 1.0) * (u_(num2) - u_(num1));
|
||||
double t_inc = delta_t / double(num2 - num1);
|
||||
for (int i = num1 + 1; i <= num2; ++i)
|
||||
u_(i) += double(i - num1) * t_inc;
|
||||
for (int i = num2 + 1; i < u_.rows(); ++i)
|
||||
u_(i) += delta_t;
|
||||
}
|
||||
|
||||
// void UniformBspline::recomputeInit() {}
|
||||
|
||||
void UniformBspline::parameterizeToBspline(const double &ts, const vector<Eigen::Vector3d> &point_set,
|
||||
const vector<Eigen::Vector3d> &start_end_derivative,
|
||||
Eigen::MatrixXd &ctrl_pts)
|
||||
{
|
||||
if (ts <= 0)
|
||||
{
|
||||
cout << "[B-spline]:time step error." << endl;
|
||||
return;
|
||||
}
|
||||
|
||||
if (point_set.size() <= 3)
|
||||
{
|
||||
cout << "[B-spline]:point set have only " << point_set.size() << " points." << endl;
|
||||
return;
|
||||
}
|
||||
|
||||
if (start_end_derivative.size() != 4)
|
||||
{
|
||||
cout << "[B-spline]:derivatives error." << endl;
|
||||
}
|
||||
|
||||
int K = point_set.size();
|
||||
|
||||
// write A
|
||||
Eigen::Vector3d prow(3), vrow(3), arow(3);
|
||||
prow << 1, 4, 1;
|
||||
vrow << -1, 0, 1;
|
||||
arow << 1, -2, 1;
|
||||
|
||||
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(K + 4, K + 2);
|
||||
|
||||
for (int i = 0; i < K; ++i)
|
||||
A.block(i, i, 1, 3) = (1 / 6.0) * prow.transpose();
|
||||
|
||||
A.block(K, 0, 1, 3) = (1 / 2.0 / ts) * vrow.transpose();
|
||||
A.block(K + 1, K - 1, 1, 3) = (1 / 2.0 / ts) * vrow.transpose();
|
||||
|
||||
A.block(K + 2, 0, 1, 3) = (1 / ts / ts) * arow.transpose();
|
||||
A.block(K + 3, K - 1, 1, 3) = (1 / ts / ts) * arow.transpose();
|
||||
|
||||
//cout << "A" << endl << A << endl << endl;
|
||||
|
||||
// write b
|
||||
Eigen::VectorXd bx(K + 4), by(K + 4), bz(K + 4);
|
||||
for (int i = 0; i < K; ++i)
|
||||
{
|
||||
bx(i) = point_set[i](0);
|
||||
by(i) = point_set[i](1);
|
||||
bz(i) = point_set[i](2);
|
||||
}
|
||||
|
||||
for (int i = 0; i < 4; ++i)
|
||||
{
|
||||
bx(K + i) = start_end_derivative[i](0);
|
||||
by(K + i) = start_end_derivative[i](1);
|
||||
bz(K + i) = start_end_derivative[i](2);
|
||||
}
|
||||
|
||||
// solve Ax = b
|
||||
Eigen::VectorXd px = A.colPivHouseholderQr().solve(bx);
|
||||
Eigen::VectorXd py = A.colPivHouseholderQr().solve(by);
|
||||
Eigen::VectorXd pz = A.colPivHouseholderQr().solve(bz);
|
||||
|
||||
// convert to control pts
|
||||
ctrl_pts.resize(3, K + 2);
|
||||
ctrl_pts.row(0) = px.transpose();
|
||||
ctrl_pts.row(1) = py.transpose();
|
||||
ctrl_pts.row(2) = pz.transpose();
|
||||
|
||||
// cout << "[B-spline]: parameterization ok." << endl;
|
||||
}
|
||||
|
||||
double UniformBspline::getTimeSum()
|
||||
{
|
||||
double tm, tmp;
|
||||
if (getTimeSpan(tm, tmp))
|
||||
return tmp - tm;
|
||||
else
|
||||
return -1.0;
|
||||
}
|
||||
|
||||
double UniformBspline::getLength(const double &res)
|
||||
{
|
||||
double length = 0.0;
|
||||
double dur = getTimeSum();
|
||||
Eigen::VectorXd p_l = evaluateDeBoorT(0.0), p_n;
|
||||
for (double t = res; t <= dur + 1e-4; t += res)
|
||||
{
|
||||
p_n = evaluateDeBoorT(t);
|
||||
length += (p_n - p_l).norm();
|
||||
p_l = p_n;
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
double UniformBspline::getJerk()
|
||||
{
|
||||
UniformBspline jerk_traj = getDerivative().getDerivative().getDerivative();
|
||||
|
||||
Eigen::VectorXd times = jerk_traj.getKnot();
|
||||
Eigen::MatrixXd ctrl_pts = jerk_traj.getControlPoint();
|
||||
int dimension = ctrl_pts.rows();
|
||||
|
||||
double jerk = 0.0;
|
||||
for (int i = 0; i < ctrl_pts.cols(); ++i)
|
||||
{
|
||||
for (int j = 0; j < dimension; ++j)
|
||||
{
|
||||
jerk += (times(i + 1) - times(i)) * ctrl_pts(j, i) * ctrl_pts(j, i);
|
||||
}
|
||||
}
|
||||
|
||||
return jerk;
|
||||
}
|
||||
|
||||
void UniformBspline::getMeanAndMaxVel(double &mean_v, double &max_v)
|
||||
{
|
||||
UniformBspline vel = getDerivative();
|
||||
double tm, tmp;
|
||||
vel.getTimeSpan(tm, tmp);
|
||||
|
||||
double max_vel = -1.0, mean_vel = 0.0;
|
||||
int num = 0;
|
||||
for (double t = tm; t <= tmp; t += 0.01)
|
||||
{
|
||||
Eigen::VectorXd vxd = vel.evaluateDeBoor(t);
|
||||
double vn = vxd.norm();
|
||||
|
||||
mean_vel += vn;
|
||||
++num;
|
||||
if (vn > max_vel)
|
||||
{
|
||||
max_vel = vn;
|
||||
}
|
||||
}
|
||||
|
||||
mean_vel = mean_vel / double(num);
|
||||
mean_v = mean_vel;
|
||||
max_v = max_vel;
|
||||
}
|
||||
|
||||
void UniformBspline::getMeanAndMaxAcc(double &mean_a, double &max_a)
|
||||
{
|
||||
UniformBspline acc = getDerivative().getDerivative();
|
||||
double tm, tmp;
|
||||
acc.getTimeSpan(tm, tmp);
|
||||
|
||||
double max_acc = -1.0, mean_acc = 0.0;
|
||||
int num = 0;
|
||||
for (double t = tm; t <= tmp; t += 0.01)
|
||||
{
|
||||
Eigen::VectorXd axd = acc.evaluateDeBoor(t);
|
||||
double an = axd.norm();
|
||||
|
||||
mean_acc += an;
|
||||
++num;
|
||||
if (an > max_acc)
|
||||
{
|
||||
max_acc = an;
|
||||
}
|
||||
}
|
||||
|
||||
mean_acc = mean_acc / double(num);
|
||||
mean_a = mean_acc;
|
||||
max_a = max_acc;
|
||||
}
|
||||
} // namespace scan_planner
|
||||
@@ -0,0 +1,27 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <Eigen/Core>
|
||||
#include <bspline_opt/uniform_bspline.h>
|
||||
|
||||
TEST(UniformBspline, EvaluatesLinearControlPoints)
|
||||
{
|
||||
Eigen::MatrixXd points = Eigen::MatrixXd::Zero(3, 6);
|
||||
for (int i = 0; i < points.cols(); ++i) points(0, i) = static_cast<double>(i);
|
||||
|
||||
scan_planner::UniformBspline spline(points, 3, 1.0);
|
||||
EXPECT_NEAR(spline.evaluateDeBoorT(0.0).x(), 1.0, 1e-9);
|
||||
EXPECT_NEAR(spline.evaluateDeBoorT(2.0).x(), 3.0, 1e-9);
|
||||
EXPECT_NEAR(spline.evaluateDeBoorT(2.0).y(), 0.0, 1e-9);
|
||||
}
|
||||
|
||||
TEST(UniformBspline, DerivativeMatchesLinearSlope)
|
||||
{
|
||||
Eigen::MatrixXd points = Eigen::MatrixXd::Zero(3, 6);
|
||||
for (int i = 0; i < points.cols(); ++i) points(0, i) = static_cast<double>(i);
|
||||
|
||||
auto derivative = scan_planner::UniformBspline(points, 3, 0.5).getDerivative();
|
||||
const Eigen::Vector3d velocity = derivative.evaluateDeBoorT(0.75);
|
||||
EXPECT_NEAR(velocity.x(), 2.0, 1e-9);
|
||||
EXPECT_NEAR(velocity.y(), 0.0, 1e-9);
|
||||
EXPECT_NEAR(velocity.z(), 0.0, 1e-9);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
cmake_minimum_required(VERSION 3.8)
|
||||
project(path_searching)
|
||||
|
||||
if(NOT CMAKE_CXX_STANDARD)
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
endif()
|
||||
add_compile_options(-Wall -Wextra -Wpedantic)
|
||||
|
||||
find_package(ament_cmake REQUIRED)
|
||||
find_package(Eigen3 REQUIRED)
|
||||
find_package(plan_env REQUIRED)
|
||||
find_package(rclcpp REQUIRED)
|
||||
|
||||
add_library(path_searching src/dyn_a_star.cpp)
|
||||
target_include_directories(path_searching PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>)
|
||||
ament_target_dependencies(path_searching plan_env rclcpp)
|
||||
target_link_libraries(path_searching Eigen3::Eigen)
|
||||
|
||||
install(TARGETS path_searching EXPORT export_path_searching
|
||||
ARCHIVE DESTINATION lib LIBRARY DESTINATION lib RUNTIME DESTINATION bin)
|
||||
install(DIRECTORY include/ DESTINATION include)
|
||||
ament_export_targets(export_path_searching HAS_LIBRARY_TARGET)
|
||||
ament_export_dependencies(Eigen3 plan_env rclcpp)
|
||||
ament_package()
|
||||
@@ -0,0 +1,122 @@
|
||||
#ifndef _DYN_A_STAR_H_
|
||||
#define _DYN_A_STAR_H_
|
||||
|
||||
#include <iostream>
|
||||
#include <rclcpp/rclcpp.hpp>
|
||||
#include <Eigen/Eigen>
|
||||
#include <plan_env/grid_map.h>
|
||||
#include <queue>
|
||||
|
||||
constexpr double inf = 1 >> 20;
|
||||
struct GridNode;
|
||||
typedef GridNode *GridNodePtr;
|
||||
|
||||
enum ASTAR_RET
|
||||
{
|
||||
SUCCESS,
|
||||
INIT_ERR,
|
||||
SEARCH_ERR
|
||||
};
|
||||
|
||||
struct GridNode
|
||||
{
|
||||
enum enum_state
|
||||
{
|
||||
OPENSET = 1,
|
||||
CLOSEDSET = 2,
|
||||
UNDEFINED = 3
|
||||
};
|
||||
|
||||
int rounds{0}; // Distinguish every call
|
||||
enum enum_state state
|
||||
{
|
||||
UNDEFINED
|
||||
};
|
||||
Eigen::Vector3i index;
|
||||
|
||||
double gScore{inf}, fScore{inf};
|
||||
GridNodePtr cameFrom{NULL};
|
||||
};
|
||||
|
||||
class NodeComparator
|
||||
{
|
||||
public:
|
||||
bool operator()(GridNodePtr node1, GridNodePtr node2)
|
||||
{
|
||||
return node1->fScore > node2->fScore;
|
||||
}
|
||||
};
|
||||
|
||||
class AStar
|
||||
{
|
||||
private:
|
||||
GridMap::Ptr grid_map_;
|
||||
|
||||
inline void coord2gridIndexFast(const double x, const double y, const double z, int &id_x, int &id_y, int &id_z);
|
||||
|
||||
double getDiagHeu(GridNodePtr node1, GridNodePtr node2);
|
||||
double getManhHeu(GridNodePtr node1, GridNodePtr node2);
|
||||
double getEuclHeu(GridNodePtr node1, GridNodePtr node2);
|
||||
inline double getHeu(GridNodePtr node1, GridNodePtr node2);
|
||||
|
||||
bool ConvertToIndexAndAdjustStartEndPoints(const Eigen::Vector3d start_pt, const Eigen::Vector3d end_pt, Eigen::Vector3i &start_idx, Eigen::Vector3i &end_idx);
|
||||
|
||||
inline Eigen::Vector3d Index2Coord(const Eigen::Vector3i &index) const;
|
||||
inline bool Coord2Index(const Eigen::Vector3d &pt, Eigen::Vector3i &idx) const;
|
||||
|
||||
//bool (*checkOccupancyPtr)( const Eigen::Vector3d &pos );
|
||||
|
||||
inline int checkOccupancy(const Eigen::Vector3d &pos, const double yaw) { return grid_map_->getInflateOccupancy(pos, yaw); }
|
||||
|
||||
std::vector<GridNodePtr> retrievePath(GridNodePtr current);
|
||||
|
||||
double step_size_, inv_step_size_;
|
||||
Eigen::Vector3d center_;
|
||||
Eigen::Vector3i CENTER_IDX_, POOL_SIZE_;
|
||||
const double tie_breaker_ = 1.0 + 1.0 / 10000;
|
||||
|
||||
std::vector<GridNodePtr> gridPath_;
|
||||
|
||||
GridNodePtr ***GridNodeMap_;
|
||||
std::priority_queue<GridNodePtr, std::vector<GridNodePtr>, NodeComparator> openSet_;
|
||||
|
||||
int rounds_{0};
|
||||
|
||||
public:
|
||||
typedef std::shared_ptr<AStar> Ptr;
|
||||
|
||||
AStar(){};
|
||||
~AStar();
|
||||
|
||||
void initGridMap(GridMap::Ptr occ_map, const Eigen::Vector3i pool_size);
|
||||
|
||||
ASTAR_RET AstarSearch(const double step_size, Eigen::Vector3d start_pt, Eigen::Vector3d end_pt);
|
||||
|
||||
std::vector<Eigen::Vector3d> getPath();
|
||||
};
|
||||
|
||||
inline double AStar::getHeu(GridNodePtr node1, GridNodePtr node2)
|
||||
{
|
||||
return tie_breaker_ * getDiagHeu(node1, node2);
|
||||
}
|
||||
|
||||
inline Eigen::Vector3d AStar::Index2Coord(const Eigen::Vector3i &index) const
|
||||
{
|
||||
return ((index - CENTER_IDX_).cast<double>() * step_size_) + center_;
|
||||
};
|
||||
|
||||
inline bool AStar::Coord2Index(const Eigen::Vector3d &pt, Eigen::Vector3i &idx) const
|
||||
{
|
||||
idx = ((pt - center_) * inv_step_size_ + Eigen::Vector3d(0.5, 0.5, 0.5)).cast<int>() + CENTER_IDX_;
|
||||
|
||||
if (idx(0) < 0 || idx(0) >= POOL_SIZE_(0) || idx(1) < 0 || idx(1) >= POOL_SIZE_(1) || idx(2) < 0 || idx(2) >= POOL_SIZE_(2))
|
||||
{
|
||||
RCLCPP_ERROR(rclcpp::get_logger("path_searching"),
|
||||
"Ran out of pool, index=%d %d %d", idx(0), idx(1), idx(2));
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0"?>
|
||||
<package format="3">
|
||||
<name>path_searching</name>
|
||||
<version>0.1.0</version>
|
||||
<description>Dynamic A-star path search for SCAN-Planner.</description>
|
||||
<maintainer email="[email protected]">SCAN-Planner maintainers</maintainer>
|
||||
<license>Apache-2.0</license>
|
||||
<buildtool_depend>ament_cmake</buildtool_depend>
|
||||
<depend>eigen</depend>
|
||||
<depend>plan_env</depend>
|
||||
<depend>rclcpp</depend>
|
||||
<export><build_type>ament_cmake</build_type></export>
|
||||
</package>
|
||||
@@ -0,0 +1,309 @@
|
||||
#include "path_searching/dyn_a_star.h"
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
|
||||
using namespace std;
|
||||
using namespace Eigen;
|
||||
|
||||
AStar::~AStar()
|
||||
{
|
||||
for (int i = 0; i < POOL_SIZE_(0); i++)
|
||||
for (int j = 0; j < POOL_SIZE_(1); j++)
|
||||
for (int k = 0; k < POOL_SIZE_(2); k++)
|
||||
delete GridNodeMap_[i][j][k];
|
||||
}
|
||||
|
||||
void AStar::initGridMap(GridMap::Ptr occ_map, const Eigen::Vector3i pool_size)
|
||||
{
|
||||
POOL_SIZE_ = pool_size;
|
||||
CENTER_IDX_ = pool_size / 2;
|
||||
|
||||
GridNodeMap_ = new GridNodePtr **[POOL_SIZE_(0)];
|
||||
for (int i = 0; i < POOL_SIZE_(0); i++)
|
||||
{
|
||||
GridNodeMap_[i] = new GridNodePtr *[POOL_SIZE_(1)];
|
||||
for (int j = 0; j < POOL_SIZE_(1); j++)
|
||||
{
|
||||
GridNodeMap_[i][j] = new GridNodePtr[POOL_SIZE_(2)];
|
||||
for (int k = 0; k < POOL_SIZE_(2); k++)
|
||||
{
|
||||
GridNodeMap_[i][j][k] = new GridNode;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
grid_map_ = occ_map;
|
||||
}
|
||||
|
||||
double AStar::getDiagHeu(GridNodePtr node1, GridNodePtr node2)
|
||||
{
|
||||
double dx = abs(node1->index(0) - node2->index(0));
|
||||
double dy = abs(node1->index(1) - node2->index(1));
|
||||
double dz = abs(node1->index(2) - node2->index(2));
|
||||
|
||||
double h = 0.0;
|
||||
int diag = min(min(dx, dy), dz);
|
||||
dx -= diag;
|
||||
dy -= diag;
|
||||
dz -= diag;
|
||||
|
||||
if (dx == 0)
|
||||
{
|
||||
h = 1.0 * sqrt(3.0) * diag + sqrt(2.0) * min(dy, dz) + 1.0 * abs(dy - dz);
|
||||
}
|
||||
if (dy == 0)
|
||||
{
|
||||
h = 1.0 * sqrt(3.0) * diag + sqrt(2.0) * min(dx, dz) + 1.0 * abs(dx - dz);
|
||||
}
|
||||
if (dz == 0)
|
||||
{
|
||||
h = 1.0 * sqrt(3.0) * diag + sqrt(2.0) * min(dx, dy) + 1.0 * abs(dx - dy);
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
double AStar::getManhHeu(GridNodePtr node1, GridNodePtr node2)
|
||||
{
|
||||
double dx = abs(node1->index(0) - node2->index(0));
|
||||
double dy = abs(node1->index(1) - node2->index(1));
|
||||
double dz = abs(node1->index(2) - node2->index(2));
|
||||
|
||||
return dx + dy + dz;
|
||||
}
|
||||
|
||||
double AStar::getEuclHeu(GridNodePtr node1, GridNodePtr node2)
|
||||
{
|
||||
return (node2->index - node1->index).norm();
|
||||
}
|
||||
|
||||
vector<GridNodePtr> AStar::retrievePath(GridNodePtr current)
|
||||
{
|
||||
vector<GridNodePtr> path;
|
||||
path.push_back(current);
|
||||
|
||||
while (current->cameFrom != NULL)
|
||||
{
|
||||
current = current->cameFrom;
|
||||
path.push_back(current);
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
bool AStar::ConvertToIndexAndAdjustStartEndPoints(Vector3d start_pt, Vector3d end_pt, Vector3i &start_idx, Vector3i &end_idx)
|
||||
{
|
||||
if (!Coord2Index(start_pt, start_idx) || !Coord2Index(end_pt, end_idx))
|
||||
return false;
|
||||
|
||||
Eigen::Vector3d start_to_end = end_pt - start_pt;
|
||||
if (start_to_end.norm() < 1e-6)
|
||||
return false;
|
||||
const double path_yaw = std::atan2(start_to_end(1), start_to_end(0));
|
||||
start_to_end.normalize();
|
||||
|
||||
int occ = checkOccupancy(Index2Coord(start_idx), path_yaw);
|
||||
if (occ)
|
||||
{
|
||||
//ROS_WARN("Start point is insdide an obstacle.");
|
||||
do
|
||||
{
|
||||
start_pt -= start_to_end * step_size_;
|
||||
if (!Coord2Index(start_pt, start_idx))
|
||||
return false;
|
||||
|
||||
occ = checkOccupancy(Index2Coord(start_idx), path_yaw);
|
||||
if (occ == -1)
|
||||
{
|
||||
RCLCPP_WARN(rclcpp::get_logger("path_searching"), "[Astar] Start point outside the map region.");
|
||||
return false;
|
||||
}
|
||||
} while (occ);
|
||||
}
|
||||
|
||||
occ = checkOccupancy(Index2Coord(end_idx), path_yaw);
|
||||
if (occ)
|
||||
{
|
||||
//ROS_WARN("End point is insdide an obstacle.");
|
||||
do
|
||||
{
|
||||
end_pt += start_to_end * step_size_;
|
||||
if (!Coord2Index(end_pt, end_idx))
|
||||
return false;
|
||||
|
||||
occ = checkOccupancy(Index2Coord(end_idx), path_yaw);
|
||||
if (occ == -1)
|
||||
{
|
||||
RCLCPP_WARN(rclcpp::get_logger("path_searching"), "[Astar] End point outside the map region.");
|
||||
return false;
|
||||
}
|
||||
} while (occ);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
ASTAR_RET AStar::AstarSearch(const double step_size, Vector3d start_pt, Vector3d end_pt)
|
||||
{
|
||||
const auto time_1 = std::chrono::steady_clock::now();
|
||||
++rounds_;
|
||||
|
||||
step_size_ = step_size;
|
||||
inv_step_size_ = 1 / step_size;
|
||||
center_ = (start_pt + end_pt) / 2;
|
||||
|
||||
Vector3i start_idx, end_idx;
|
||||
if (!ConvertToIndexAndAdjustStartEndPoints(start_pt, end_pt, start_idx, end_idx))
|
||||
{
|
||||
RCLCPP_ERROR(rclcpp::get_logger("path_searching"),
|
||||
"Unable to handle the initial or end point, force return!");
|
||||
return ASTAR_RET::INIT_ERR;
|
||||
}
|
||||
|
||||
const Eigen::Vector3d search_start = Index2Coord(start_idx);
|
||||
const Eigen::Vector3d search_end = Index2Coord(end_idx);
|
||||
const Eigen::Vector2d search_start_xy = search_start.head<2>();
|
||||
const Eigen::Vector2d search_xy_delta = search_end.head<2>() - search_start_xy;
|
||||
const double search_xy_len2 = search_xy_delta.squaredNorm();
|
||||
|
||||
auto interpolateZIndexOnSearchPlane = [&](const int x_idx, const int y_idx) -> int {
|
||||
if (search_xy_len2 < 1e-8)
|
||||
return start_idx(2);
|
||||
|
||||
Eigen::Vector3i sample_idx(x_idx, y_idx, start_idx(2));
|
||||
const Eigen::Vector2d sample_xy = Index2Coord(sample_idx).head<2>();
|
||||
double ratio = (sample_xy - search_start_xy).dot(search_xy_delta) / search_xy_len2;
|
||||
ratio = std::max(0.0, std::min(1.0, ratio));
|
||||
|
||||
const double z = search_start(2) + ratio * (search_end(2) - search_start(2));
|
||||
return static_cast<int>((z - center_(2)) * inv_step_size_ + 0.5) + CENTER_IDX_(2);
|
||||
};
|
||||
|
||||
// if ( start_pt(0) > -1 && start_pt(0) < 0 )
|
||||
// cout << "start_pt=" << start_pt.transpose() << " end_pt=" << end_pt.transpose() << endl;
|
||||
|
||||
GridNodePtr startPtr = GridNodeMap_[start_idx(0)][start_idx(1)][start_idx(2)];
|
||||
GridNodePtr endPtr = GridNodeMap_[end_idx(0)][end_idx(1)][end_idx(2)];
|
||||
|
||||
std::priority_queue<GridNodePtr, std::vector<GridNodePtr>, NodeComparator> empty;
|
||||
openSet_.swap(empty);
|
||||
|
||||
GridNodePtr neighborPtr = NULL;
|
||||
GridNodePtr current = NULL;
|
||||
|
||||
endPtr->index = end_idx;
|
||||
|
||||
startPtr->index = start_idx;
|
||||
startPtr->rounds = rounds_;
|
||||
startPtr->gScore = 0;
|
||||
startPtr->fScore = getHeu(startPtr, endPtr);
|
||||
startPtr->state = GridNode::OPENSET; //put start node in open set
|
||||
startPtr->cameFrom = NULL;
|
||||
openSet_.push(startPtr); //put start in open set
|
||||
|
||||
double tentative_gScore;
|
||||
|
||||
int num_iter = 0;
|
||||
while (!openSet_.empty())
|
||||
{
|
||||
num_iter++;
|
||||
current = openSet_.top();
|
||||
openSet_.pop();
|
||||
|
||||
// if ( num_iter < 10000 )
|
||||
// cout << "current=" << current->index.transpose() << endl;
|
||||
|
||||
if (current->index(0) == endPtr->index(0) && current->index(1) == endPtr->index(1) && current->index(2) == endPtr->index(2))
|
||||
{
|
||||
// ros::Time time_2 = ros::Time::now();
|
||||
// printf("\033[34mA star iter:%d, time:%.3f\033[0m\n",num_iter, (time_2 - time_1).toSec()*1000);
|
||||
// if((time_2 - time_1).toSec() > 0.1)
|
||||
// ROS_WARN("Time consume in A star path finding is %f", (time_2 - time_1).toSec() );
|
||||
gridPath_ = retrievePath(current);
|
||||
return ASTAR_RET::SUCCESS;
|
||||
}
|
||||
current->state = GridNode::CLOSEDSET; //move current node from open set to closed set.
|
||||
|
||||
for (int dx = -1; dx <= 1; dx++)
|
||||
for (int dy = -1; dy <= 1; dy++)
|
||||
{
|
||||
if (dx == 0 && dy == 0)
|
||||
continue;
|
||||
|
||||
Vector3i neighborIdx;
|
||||
neighborIdx(0) = (current->index)(0) + dx;
|
||||
neighborIdx(1) = (current->index)(1) + dy;
|
||||
neighborIdx(2) = interpolateZIndexOnSearchPlane(neighborIdx(0), neighborIdx(1));
|
||||
|
||||
if (neighborIdx(0) < 1 || neighborIdx(0) >= POOL_SIZE_(0) - 1 || neighborIdx(1) < 1 || neighborIdx(1) >= POOL_SIZE_(1) - 1 || neighborIdx(2) < 1 || neighborIdx(2) >= POOL_SIZE_(2) - 1)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
neighborPtr = GridNodeMap_[neighborIdx(0)][neighborIdx(1)][neighborIdx(2)];
|
||||
neighborPtr->index = neighborIdx;
|
||||
|
||||
bool flag_explored = neighborPtr->rounds == rounds_;
|
||||
|
||||
if (flag_explored && neighborPtr->state == GridNode::CLOSEDSET)
|
||||
{
|
||||
continue; //in closed set.
|
||||
}
|
||||
|
||||
neighborPtr->rounds = rounds_;
|
||||
|
||||
const double neighbor_yaw = std::atan2(static_cast<double>(dy), static_cast<double>(dx));
|
||||
if (checkOccupancy(Index2Coord(neighborPtr->index), neighbor_yaw))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
const int dz = neighborIdx(2) - current->index(2);
|
||||
double static_cost = sqrt(dx * dx + dy * dy + dz * dz);
|
||||
tentative_gScore = current->gScore + static_cost;
|
||||
|
||||
if (!flag_explored)
|
||||
{
|
||||
//discover a new node
|
||||
neighborPtr->state = GridNode::OPENSET;
|
||||
neighborPtr->cameFrom = current;
|
||||
neighborPtr->gScore = tentative_gScore;
|
||||
neighborPtr->fScore = tentative_gScore + getHeu(neighborPtr, endPtr);
|
||||
openSet_.push(neighborPtr); //put neighbor in open set and record it.
|
||||
}
|
||||
else if (tentative_gScore < neighborPtr->gScore)
|
||||
{ //in open set and need update
|
||||
neighborPtr->cameFrom = current;
|
||||
neighborPtr->gScore = tentative_gScore;
|
||||
neighborPtr->fScore = tentative_gScore + getHeu(neighborPtr, endPtr);
|
||||
}
|
||||
}
|
||||
const auto time_2 = std::chrono::steady_clock::now();
|
||||
if (std::chrono::duration<double>(time_2 - time_1).count() > 0.2)
|
||||
{
|
||||
RCLCPP_WARN(rclcpp::get_logger("path_searching"),
|
||||
"Failed in A-star path search: 0.2 second time limit exceeded");
|
||||
return ASTAR_RET::SEARCH_ERR;
|
||||
}
|
||||
}
|
||||
|
||||
const auto time_2 = std::chrono::steady_clock::now();
|
||||
|
||||
const double elapsed = std::chrono::duration<double>(time_2 - time_1).count();
|
||||
if (elapsed > 0.1)
|
||||
RCLCPP_WARN(rclcpp::get_logger("path_searching"),
|
||||
"A-star path search took %.3fs, iter=%d", elapsed, num_iter);
|
||||
|
||||
return ASTAR_RET::SEARCH_ERR;
|
||||
}
|
||||
|
||||
vector<Vector3d> AStar::getPath()
|
||||
{
|
||||
vector<Vector3d> path;
|
||||
|
||||
for (auto ptr : gridPath_)
|
||||
path.push_back(Index2Coord(ptr->index));
|
||||
|
||||
reverse(path.begin(), path.end());
|
||||
return path;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
cmake_minimum_required(VERSION 3.8)
|
||||
project(plan_env)
|
||||
|
||||
if(NOT CMAKE_CXX_STANDARD)
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
endif()
|
||||
add_compile_options(-Wall -Wextra -Wpedantic)
|
||||
|
||||
find_package(ament_cmake REQUIRED)
|
||||
find_package(cv_bridge REQUIRED)
|
||||
find_package(Eigen3 REQUIRED)
|
||||
find_package(geometry_msgs REQUIRED)
|
||||
find_package(message_filters REQUIRED)
|
||||
find_package(nav_msgs REQUIRED)
|
||||
find_package(OpenCV REQUIRED)
|
||||
find_package(PCL REQUIRED COMPONENTS common io filters)
|
||||
find_package(pcl_conversions REQUIRED)
|
||||
find_package(rclcpp REQUIRED)
|
||||
find_package(sensor_msgs REQUIRED)
|
||||
find_package(tf2 REQUIRED)
|
||||
find_package(tf2_ros REQUIRED)
|
||||
find_package(visualization_msgs REQUIRED)
|
||||
|
||||
add_library(plan_env src/grid_map.cpp src/raycast.cpp)
|
||||
target_include_directories(plan_env PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
${PCL_INCLUDE_DIRS}
|
||||
${OpenCV_INCLUDE_DIRS}
|
||||
)
|
||||
ament_target_dependencies(plan_env
|
||||
cv_bridge geometry_msgs message_filters nav_msgs pcl_conversions rclcpp
|
||||
sensor_msgs tf2 tf2_ros visualization_msgs
|
||||
)
|
||||
target_link_libraries(plan_env Eigen3::Eigen ${PCL_LIBRARIES} ${OpenCV_LIBS})
|
||||
|
||||
install(TARGETS plan_env EXPORT export_plan_env
|
||||
ARCHIVE DESTINATION lib LIBRARY DESTINATION lib RUNTIME DESTINATION bin)
|
||||
install(DIRECTORY include/ DESTINATION include)
|
||||
ament_export_targets(export_plan_env HAS_LIBRARY_TARGET)
|
||||
ament_export_dependencies(
|
||||
cv_bridge Eigen3 geometry_msgs message_filters nav_msgs pcl_conversions
|
||||
rclcpp sensor_msgs tf2 tf2_ros visualization_msgs)
|
||||
ament_package()
|
||||
@@ -0,0 +1,467 @@
|
||||
#ifndef _GRID_MAP_H
|
||||
#define _GRID_MAP_H
|
||||
|
||||
#include <Eigen/Eigen>
|
||||
#include <Eigen/StdVector>
|
||||
#include <algorithm>
|
||||
#include <cv_bridge/cv_bridge.h>
|
||||
#include <cmath>
|
||||
#include <geometry_msgs/msg/pose_stamped.hpp>
|
||||
#include <iostream>
|
||||
#include <random>
|
||||
#include <nav_msgs/msg/odometry.hpp>
|
||||
#include <queue>
|
||||
#include <rclcpp/rclcpp.hpp>
|
||||
#include <rmw/qos_profiles.h>
|
||||
#include <tuple>
|
||||
#include <sensor_msgs/msg/image.hpp>
|
||||
#include <sensor_msgs/image_encodings.hpp>
|
||||
#include <sensor_msgs/msg/point_cloud2.hpp>
|
||||
#include <tf2_ros/transform_broadcaster.h>
|
||||
#include <visualization_msgs/msg/marker.hpp>
|
||||
|
||||
#include <pcl/point_cloud.h>
|
||||
#include <pcl/point_types.h>
|
||||
#include <pcl_conversions/pcl_conversions.h>
|
||||
|
||||
#include <message_filters/subscriber.h>
|
||||
#include <message_filters/sync_policies/approximate_time.h>
|
||||
#include <message_filters/sync_policies/exact_time.h>
|
||||
#include <message_filters/time_synchronizer.h>
|
||||
|
||||
#include <plan_env/raycast.h>
|
||||
|
||||
#define logit(x) (log((x) / (1 - (x))))
|
||||
|
||||
using namespace std;
|
||||
// voxel hashing
|
||||
template <typename T>
|
||||
struct matrix_hash {
|
||||
std::size_t operator()(T const& matrix) const {
|
||||
size_t seed = 0;
|
||||
for (size_t i = 0; i < matrix.size(); ++i) {
|
||||
auto elem = *(matrix.data() + i);
|
||||
seed ^= std::hash<typename T::Scalar>()(elem) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
|
||||
}
|
||||
return seed;
|
||||
}
|
||||
};
|
||||
|
||||
// constant parameters
|
||||
|
||||
struct MappingParameters {
|
||||
|
||||
/* map properties */
|
||||
Eigen::Vector3d map_origin_, map_size_;
|
||||
Eigen::Vector3d map_min_boundary_, map_max_boundary_; // map range in pos
|
||||
Eigen::Vector3i map_voxel_num_; // map range in index
|
||||
Eigen::Vector3i map_bound_min_idx_, map_bound_max_idx_;
|
||||
Eigen::Vector3i map_origin_idx_;
|
||||
Eigen::Vector3d local_update_range_;
|
||||
double resolution_, resolution_inv_;
|
||||
double obstacles_inflation_z_up, obstacles_inflation_z_down;
|
||||
double double_cylinder_radius_, double_cylinder_offset_;
|
||||
bool map_sliding_en_;
|
||||
double map_sliding_thresh_;
|
||||
int map_sliding_thresh_vox_;
|
||||
string frame_id_, sliding_map_frame_id_;
|
||||
|
||||
/* depth camera intrinsics */
|
||||
double cx_, cy_, fx_, fy_;
|
||||
|
||||
/* depth image projection filtering */
|
||||
double depth_filter_maxdist_, depth_filter_mindist_;
|
||||
int depth_filter_margin_;
|
||||
double k_depth_scaling_factor_;
|
||||
int skip_pixel_;
|
||||
|
||||
/* raycasting */
|
||||
double p_hit_, p_miss_, p_min_, p_max_, p_occ_; // occupancy probability
|
||||
double prob_hit_log_, prob_miss_log_, clamp_min_log_, clamp_max_log_,
|
||||
min_occupancy_log_; // logit of occupancy probability
|
||||
double min_ray_length_, max_ray_length_; // range of doing raycasting
|
||||
|
||||
/* visualization and computation time display */
|
||||
double vis_height_, ground_height_;
|
||||
bool show_occ_time_;
|
||||
|
||||
/* mapping sensor input */
|
||||
string sensor_type_;
|
||||
bool cloud_is_world_;
|
||||
bool need_extrinsic_;
|
||||
Eigen::Matrix4d lidar_extrinsic_;
|
||||
Eigen::Matrix4d depth_extrinsic_;
|
||||
|
||||
/* active mapping */
|
||||
double unknown_flag_;
|
||||
};
|
||||
|
||||
// intermediate mapping data for fusion
|
||||
|
||||
struct MappingData {
|
||||
// main map data, occupancy of each voxel and Euclidean distance
|
||||
|
||||
std::vector<double> occupancy_buffer_;
|
||||
std::vector<char> occupancy_buffer_inflate_;
|
||||
std::vector<int> occupancy_buffer_inflate_cnt_;
|
||||
vector<Eigen::Vector3i> inflate_offsets_;
|
||||
|
||||
// raycast origin and sensor pose data
|
||||
|
||||
Eigen::Vector3d ray_pos_;
|
||||
Eigen::Quaterniond ray_q_;
|
||||
Eigen::Vector3d sliding_map_frame_pos_;
|
||||
|
||||
// depth image data
|
||||
|
||||
cv::Mat depth_image_;
|
||||
int image_cnt_;
|
||||
// flags of map state
|
||||
|
||||
bool occ_need_update_;
|
||||
bool use_cloud_update_;
|
||||
bool has_first_depth_;
|
||||
bool has_ray_pose_, has_cloud_;
|
||||
|
||||
// depth image projected point cloud
|
||||
|
||||
vector<Eigen::Vector3d> proj_points_;
|
||||
int proj_points_cnt;
|
||||
|
||||
// flag buffers for speeding up raycasting
|
||||
|
||||
vector<short> count_hit_, count_hit_and_miss_;
|
||||
vector<char> flag_traverse_, flag_rayend_;
|
||||
char raycast_num_;
|
||||
queue<Eigen::Vector3i> cache_voxel_;
|
||||
|
||||
// range of updating grid
|
||||
|
||||
Eigen::Vector3i local_bound_min_, local_bound_max_;
|
||||
|
||||
// computation time
|
||||
|
||||
double fuse_time_, max_fuse_time_;
|
||||
int update_num_;
|
||||
|
||||
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
|
||||
};
|
||||
|
||||
class GridMap {
|
||||
public:
|
||||
GridMap() {}
|
||||
~GridMap() {}
|
||||
|
||||
enum { INVALID_IDX = -10000 };
|
||||
|
||||
// occupancy map management
|
||||
void resetBuffer();
|
||||
void resetBuffer(Eigen::Vector3d min, Eigen::Vector3d max);
|
||||
|
||||
inline void posToIndex(const Eigen::Vector3d& pos, Eigen::Vector3i& id);
|
||||
inline void indexToPos(const Eigen::Vector3i& id, Eigen::Vector3d& pos);
|
||||
inline int toAddress(const Eigen::Vector3i& id);
|
||||
inline int toAddress(int& x, int& y, int& z);
|
||||
inline bool isInMap(const Eigen::Vector3d& pos);
|
||||
inline bool isInMap(const Eigen::Vector3i& idx);
|
||||
|
||||
inline void setOccupancy(Eigen::Vector3d pos, double occ = 1);
|
||||
inline void setOccupied(Eigen::Vector3d pos);
|
||||
inline int getOccupancy(Eigen::Vector3d pos);
|
||||
inline int getOccupancy(Eigen::Vector3i id);
|
||||
inline int getInflateOccupancy(Eigen::Vector3d pos, double yaw);
|
||||
|
||||
inline void boundIndex(Eigen::Vector3i& id);
|
||||
inline bool isUnknown(const Eigen::Vector3i& id);
|
||||
inline bool isUnknown(const Eigen::Vector3d& pos);
|
||||
inline bool isKnownFree(const Eigen::Vector3i& id);
|
||||
inline bool isKnownOccupied(const Eigen::Vector3i& id);
|
||||
|
||||
void initMap(rclcpp::Node* node);
|
||||
|
||||
void publishMap();
|
||||
void publishMapInflate(bool all_info = false);
|
||||
|
||||
void publishUnknown();
|
||||
void publishDepth();
|
||||
void publishDepthCloud();
|
||||
void publishSlidingMapBBox();
|
||||
void publishSlidingMapFrame();
|
||||
|
||||
bool hasDepthObservation();
|
||||
bool odomValid();
|
||||
void getRegion(Eigen::Vector3d& ori, Eigen::Vector3d& size);
|
||||
inline double getResolution();
|
||||
Eigen::Vector3d getOrigin();
|
||||
int getVoxelNum();
|
||||
|
||||
typedef std::shared_ptr<GridMap> Ptr;
|
||||
|
||||
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
|
||||
|
||||
private:
|
||||
MappingParameters mp_;
|
||||
MappingData md_;
|
||||
|
||||
// get depth image and sensor pose
|
||||
void depthPoseCallback(const sensor_msgs::msg::Image::ConstSharedPtr& img,
|
||||
const nav_msgs::msg::Odometry::ConstSharedPtr& pose);
|
||||
void sensorPoseCallback(const nav_msgs::msg::Odometry::ConstSharedPtr& pose);
|
||||
void slidingMapFrameCallback(const nav_msgs::msg::Odometry::ConstSharedPtr& pose);
|
||||
void cloudCallback(const sensor_msgs::msg::PointCloud2::ConstSharedPtr& img);
|
||||
|
||||
// update occupancy by raycasting
|
||||
void updateOccupancyCallback();
|
||||
void visCallback();
|
||||
|
||||
// main update process
|
||||
void projectDepthImage();
|
||||
void raycastProcess();
|
||||
|
||||
inline void inflatePoint(const Eigen::Vector3i& pt, int inf_step_xy, int inf_step_z_up, int inf_step_z_down, vector<Eigen::Vector3i>& pts);
|
||||
inline int getInflateOccupancyFromBuffer(Eigen::Vector3d pos, const std::vector<char>& buffer);
|
||||
inline int getLocalIndex(int id, int dim) const;
|
||||
inline int toAddressLocal(const Eigen::Vector3i& id_l) const;
|
||||
inline int toAddressLocal(int x, int y, int z) const;
|
||||
int setCacheOccupancy(Eigen::Vector3d pos, int occ);
|
||||
Eigen::Vector3d closetPointInMap(const Eigen::Vector3d& pt, const Eigen::Vector3d& ray_pos);
|
||||
void updateSlidingMap(const Eigen::Vector3d& center);
|
||||
void updateMapBoundaryFromIndex();
|
||||
void resetAllMapData();
|
||||
void resetCellByAddress(int addr);
|
||||
void resetCellByAddressForSliding(int addr, const std::vector<char>& clear_mask);
|
||||
void hashIdToGlobalIndex(int addr, Eigen::Vector3i& id_g) const;
|
||||
void applyOccupancyUpdate(const Eigen::Vector3i& id, double new_log_odds);
|
||||
void rebuildInflationOffsets();
|
||||
void updateInflation(const Eigen::Vector3i& id, int delta, const std::vector<char>* ignore_mask = nullptr);
|
||||
void updateInflationLayer(const Eigen::Vector3i& id, int delta,
|
||||
const vector<Eigen::Vector3i>& offsets,
|
||||
std::vector<int>& cnt_buffer,
|
||||
std::vector<char>& flag_buffer,
|
||||
const std::vector<char>* ignore_mask);
|
||||
|
||||
// typedef message_filters::sync_policies::ExactTime<sensor_msgs::Image,
|
||||
// nav_msgs::Odometry> SyncPolicyImageOdom; typedef
|
||||
// message_filters::sync_policies::ExactTime<sensor_msgs::Image,
|
||||
// nav_msgs::Odometry> SyncPolicyImagePose;
|
||||
typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::msg::Image, nav_msgs::msg::Odometry>
|
||||
SyncPolicyImagePose;
|
||||
typedef shared_ptr<message_filters::Synchronizer<SyncPolicyImagePose>> SynchronizerImagePose;
|
||||
|
||||
rclcpp::Node* node_{nullptr};
|
||||
std::shared_ptr<tf2_ros::TransformBroadcaster> tf_broadcaster_;
|
||||
shared_ptr<message_filters::Subscriber<sensor_msgs::msg::Image>> depth_sub_;
|
||||
shared_ptr<message_filters::Subscriber<nav_msgs::msg::Odometry>> depth_pose_sub_;
|
||||
SynchronizerImagePose sync_image_pose_;
|
||||
|
||||
rclcpp::Subscription<nav_msgs::msg::Odometry>::SharedPtr lidar_pose_sub_;
|
||||
rclcpp::Subscription<nav_msgs::msg::Odometry>::SharedPtr sliding_map_frame_sub_;
|
||||
rclcpp::Subscription<sensor_msgs::msg::PointCloud2>::SharedPtr cloud_sub_;
|
||||
rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr map_pub_;
|
||||
rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr map_inf_pub_;
|
||||
rclcpp::Publisher<visualization_msgs::msg::Marker>::SharedPtr sliding_map_bbox_pub_;
|
||||
rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr unknown_pub_;
|
||||
rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr depth_cloud_pub_;
|
||||
rclcpp::Publisher<nav_msgs::msg::Odometry>::SharedPtr extrinsic_pose_pub_;
|
||||
rclcpp::TimerBase::SharedPtr occ_timer_, vis_timer_;
|
||||
|
||||
//
|
||||
uniform_real_distribution<double> rand_noise_;
|
||||
normal_distribution<double> rand_noise2_;
|
||||
default_random_engine eng_;
|
||||
};
|
||||
|
||||
/* ============================== definition of inline function
|
||||
* ============================== */
|
||||
|
||||
inline int GridMap::toAddress(const Eigen::Vector3i& id) {
|
||||
return getLocalIndex(id(0), 0) * mp_.map_voxel_num_(1) * mp_.map_voxel_num_(2) +
|
||||
getLocalIndex(id(1), 1) * mp_.map_voxel_num_(2) + getLocalIndex(id(2), 2);
|
||||
}
|
||||
|
||||
inline int GridMap::toAddress(int& x, int& y, int& z) {
|
||||
return getLocalIndex(x, 0) * mp_.map_voxel_num_(1) * mp_.map_voxel_num_(2) +
|
||||
getLocalIndex(y, 1) * mp_.map_voxel_num_(2) + getLocalIndex(z, 2);
|
||||
}
|
||||
|
||||
inline int GridMap::getLocalIndex(int id, int dim) const {
|
||||
int local_id = id % mp_.map_voxel_num_(dim);
|
||||
if (local_id < 0) local_id += mp_.map_voxel_num_(dim);
|
||||
return local_id;
|
||||
}
|
||||
|
||||
inline int GridMap::toAddressLocal(const Eigen::Vector3i& id_l) const {
|
||||
return id_l(0) * mp_.map_voxel_num_(1) * mp_.map_voxel_num_(2) + id_l(1) * mp_.map_voxel_num_(2) + id_l(2);
|
||||
}
|
||||
|
||||
inline int GridMap::toAddressLocal(int x, int y, int z) const {
|
||||
return x * mp_.map_voxel_num_(1) * mp_.map_voxel_num_(2) + y * mp_.map_voxel_num_(2) + z;
|
||||
}
|
||||
|
||||
inline void GridMap::boundIndex(Eigen::Vector3i& id) {
|
||||
Eigen::Vector3i id1;
|
||||
id1(0) = max(min(id(0), mp_.map_bound_max_idx_(0)), mp_.map_bound_min_idx_(0));
|
||||
id1(1) = max(min(id(1), mp_.map_bound_max_idx_(1)), mp_.map_bound_min_idx_(1));
|
||||
id1(2) = max(min(id(2), mp_.map_bound_max_idx_(2)), mp_.map_bound_min_idx_(2));
|
||||
id = id1;
|
||||
}
|
||||
|
||||
inline bool GridMap::isUnknown(const Eigen::Vector3i& id) {
|
||||
Eigen::Vector3i id1 = id;
|
||||
boundIndex(id1);
|
||||
return md_.occupancy_buffer_[toAddress(id1)] < mp_.clamp_min_log_ - 1e-3;
|
||||
}
|
||||
|
||||
inline bool GridMap::isUnknown(const Eigen::Vector3d& pos) {
|
||||
Eigen::Vector3i idc;
|
||||
posToIndex(pos, idc);
|
||||
return isUnknown(idc);
|
||||
}
|
||||
|
||||
inline bool GridMap::isKnownFree(const Eigen::Vector3i& id) {
|
||||
Eigen::Vector3i id1 = id;
|
||||
boundIndex(id1);
|
||||
int adr = toAddress(id1);
|
||||
|
||||
// return md_.occupancy_buffer_[adr] >= mp_.clamp_min_log_ &&
|
||||
// md_.occupancy_buffer_[adr] < mp_.min_occupancy_log_;
|
||||
return md_.occupancy_buffer_[adr] >= mp_.clamp_min_log_ && md_.occupancy_buffer_inflate_[adr] == 0;
|
||||
}
|
||||
|
||||
inline bool GridMap::isKnownOccupied(const Eigen::Vector3i& id) {
|
||||
Eigen::Vector3i id1 = id;
|
||||
boundIndex(id1);
|
||||
int adr = toAddress(id1);
|
||||
|
||||
return md_.occupancy_buffer_inflate_[adr] == 1;
|
||||
}
|
||||
|
||||
inline void GridMap::setOccupied(Eigen::Vector3d pos) {
|
||||
if (!isInMap(pos)) return;
|
||||
|
||||
Eigen::Vector3i id;
|
||||
posToIndex(pos, id);
|
||||
|
||||
applyOccupancyUpdate(id, mp_.clamp_max_log_);
|
||||
}
|
||||
|
||||
inline void GridMap::setOccupancy(Eigen::Vector3d pos, double occ) {
|
||||
if (occ != 1 && occ != 0) {
|
||||
cout << "occ value error!" << endl;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isInMap(pos)) return;
|
||||
|
||||
Eigen::Vector3i id;
|
||||
posToIndex(pos, id);
|
||||
|
||||
applyOccupancyUpdate(id, occ > 0.5 ? mp_.clamp_max_log_ : mp_.clamp_min_log_);
|
||||
}
|
||||
|
||||
inline int GridMap::getOccupancy(Eigen::Vector3d pos) {
|
||||
if (!isInMap(pos)) return -1;
|
||||
|
||||
Eigen::Vector3i id;
|
||||
posToIndex(pos, id);
|
||||
|
||||
return md_.occupancy_buffer_[toAddress(id)] > mp_.min_occupancy_log_ ? 1 : 0;
|
||||
}
|
||||
|
||||
inline int GridMap::getInflateOccupancy(Eigen::Vector3d pos, double yaw) {
|
||||
Eigen::Vector3d heading(std::cos(yaw), std::sin(yaw), 0.0);
|
||||
Eigen::Vector3d front = pos + mp_.double_cylinder_offset_ * heading;
|
||||
Eigen::Vector3d rear = pos - mp_.double_cylinder_offset_ * heading;
|
||||
|
||||
int front_occ = getInflateOccupancyFromBuffer(front, md_.occupancy_buffer_inflate_);
|
||||
if (front_occ != 0) return front_occ;
|
||||
|
||||
return getInflateOccupancyFromBuffer(rear, md_.occupancy_buffer_inflate_);
|
||||
}
|
||||
|
||||
inline int GridMap::getInflateOccupancyFromBuffer(Eigen::Vector3d pos, const std::vector<char>& buffer) {
|
||||
if (!isInMap(pos)) return -1;
|
||||
|
||||
Eigen::Vector3i id;
|
||||
posToIndex(pos, id);
|
||||
|
||||
return int(buffer[toAddress(id)]);
|
||||
}
|
||||
|
||||
inline int GridMap::getOccupancy(Eigen::Vector3i id) {
|
||||
if (!isInMap(id))
|
||||
return -1;
|
||||
|
||||
return md_.occupancy_buffer_[toAddress(id)] > mp_.min_occupancy_log_ ? 1 : 0;
|
||||
}
|
||||
|
||||
inline bool GridMap::isInMap(const Eigen::Vector3d& pos) {
|
||||
if (pos(0) < mp_.map_min_boundary_(0) + 1e-4 || pos(1) < mp_.map_min_boundary_(1) + 1e-4 ||
|
||||
pos(2) < mp_.map_min_boundary_(2) + 1e-4) {
|
||||
// cout << "less than min range!" << endl;
|
||||
return false;
|
||||
}
|
||||
if (pos(0) > mp_.map_max_boundary_(0) - 1e-4 || pos(1) > mp_.map_max_boundary_(1) - 1e-4 ||
|
||||
pos(2) > mp_.map_max_boundary_(2) - 1e-4) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
inline bool GridMap::isInMap(const Eigen::Vector3i& idx) {
|
||||
if (idx(0) < mp_.map_bound_min_idx_(0) || idx(1) < mp_.map_bound_min_idx_(1) ||
|
||||
idx(2) < mp_.map_bound_min_idx_(2)) {
|
||||
return false;
|
||||
}
|
||||
if (idx(0) > mp_.map_bound_max_idx_(0) || idx(1) > mp_.map_bound_max_idx_(1) ||
|
||||
idx(2) > mp_.map_bound_max_idx_(2)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
inline void GridMap::posToIndex(const Eigen::Vector3d& pos, Eigen::Vector3i& id) {
|
||||
for (int i = 0; i < 3; ++i) id(i) = floor(pos(i) * mp_.resolution_inv_);
|
||||
}
|
||||
|
||||
inline void GridMap::indexToPos(const Eigen::Vector3i& id, Eigen::Vector3d& pos) {
|
||||
for (int i = 0; i < 3; ++i) pos(i) = (id(i) + 0.5) * mp_.resolution_;
|
||||
}
|
||||
|
||||
inline void GridMap::inflatePoint(const Eigen::Vector3i& pt, int inf_step_xy, int inf_step_z_up, int inf_step_z_down, vector<Eigen::Vector3i>& pts) {
|
||||
|
||||
/* ---------- + shape inflate ---------- */
|
||||
// for (int x = -step; x <= step; ++x)
|
||||
// {
|
||||
// if (x == 0)
|
||||
// continue;
|
||||
// pts[num++] = Eigen::Vector3i(pt(0) + x, pt(1), pt(2));
|
||||
// }
|
||||
// for (int y = -step; y <= step; ++y)
|
||||
// {
|
||||
// if (y == 0)
|
||||
// continue;
|
||||
// pts[num++] = Eigen::Vector3i(pt(0), pt(1) + y, pt(2));
|
||||
// }
|
||||
// for (int z = -1; z <= 1; ++z)
|
||||
// {
|
||||
// pts[num++] = Eigen::Vector3i(pt(0), pt(1), pt(2) + z);
|
||||
// }
|
||||
|
||||
/* ---------- all inflate ---------- */
|
||||
pts.clear();
|
||||
for (int x = -inf_step_xy; x <= inf_step_xy; ++x)
|
||||
for (int y = -inf_step_xy; y <= inf_step_xy; ++y)
|
||||
{
|
||||
if (std::sqrt(x * x + y * y) > inf_step_xy)
|
||||
continue;
|
||||
|
||||
for (int z = -inf_step_z_down; z <= inf_step_z_up; ++z) {
|
||||
pts.push_back(Eigen::Vector3i(pt(0) + x, pt(1) + y, pt(2) + z));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline double GridMap::getResolution() { return mp_.resolution_; }
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,63 @@
|
||||
#ifndef RAYCAST_H_
|
||||
#define RAYCAST_H_
|
||||
|
||||
#include <Eigen/Eigen>
|
||||
#include <vector>
|
||||
|
||||
double signum(double x);
|
||||
|
||||
double mod(double value, double modulus);
|
||||
|
||||
double intbound(double s, double ds);
|
||||
|
||||
void Raycast(const Eigen::Vector3d& start, const Eigen::Vector3d& end, const Eigen::Vector3d& min,
|
||||
const Eigen::Vector3d& max, int& output_points_cnt, Eigen::Vector3d* output);
|
||||
|
||||
void Raycast(const Eigen::Vector3d& start, const Eigen::Vector3d& end, const Eigen::Vector3d& min,
|
||||
const Eigen::Vector3d& max, std::vector<Eigen::Vector3d>* output);
|
||||
|
||||
class RayCaster {
|
||||
private:
|
||||
/* data */
|
||||
Eigen::Vector3d start_;
|
||||
Eigen::Vector3d end_;
|
||||
Eigen::Vector3d direction_;
|
||||
Eigen::Vector3d min_;
|
||||
Eigen::Vector3d max_;
|
||||
int x_;
|
||||
int y_;
|
||||
int z_;
|
||||
int endX_;
|
||||
int endY_;
|
||||
int endZ_;
|
||||
double maxDist_;
|
||||
double dx_;
|
||||
double dy_;
|
||||
double dz_;
|
||||
int stepX_;
|
||||
int stepY_;
|
||||
int stepZ_;
|
||||
double tMaxX_;
|
||||
double tMaxY_;
|
||||
double tMaxZ_;
|
||||
double tDeltaX_;
|
||||
double tDeltaY_;
|
||||
double tDeltaZ_;
|
||||
double dist_;
|
||||
|
||||
int step_num_;
|
||||
|
||||
public:
|
||||
RayCaster(/* args */) {
|
||||
}
|
||||
~RayCaster() {
|
||||
}
|
||||
|
||||
bool setInput(const Eigen::Vector3d& start,
|
||||
const Eigen::Vector3d& end /* , const Eigen::Vector3d& min,
|
||||
const Eigen::Vector3d& max */);
|
||||
|
||||
bool step(Eigen::Vector3d& ray_pt);
|
||||
};
|
||||
|
||||
#endif // RAYCAST_H_
|
||||
@@ -0,0 +1,21 @@
|
||||
<?xml version="1.0"?>
|
||||
<package format="3">
|
||||
<name>plan_env</name>
|
||||
<version>0.1.0</version>
|
||||
<description>Local occupancy map and ray casting for SCAN-Planner.</description>
|
||||
<maintainer email="[email protected]">SCAN-Planner maintainers</maintainer>
|
||||
<license>Apache-2.0</license>
|
||||
<buildtool_depend>ament_cmake</buildtool_depend>
|
||||
<depend>cv_bridge</depend>
|
||||
<depend>eigen</depend>
|
||||
<depend>geometry_msgs</depend>
|
||||
<depend>message_filters</depend>
|
||||
<depend>nav_msgs</depend>
|
||||
<depend>pcl_conversions</depend>
|
||||
<depend>rclcpp</depend>
|
||||
<depend>sensor_msgs</depend>
|
||||
<depend>tf2</depend>
|
||||
<depend>tf2_ros</depend>
|
||||
<depend>visualization_msgs</depend>
|
||||
<export><build_type>ament_cmake</build_type></export>
|
||||
</package>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,321 @@
|
||||
#include <Eigen/Eigen>
|
||||
#include <cmath>
|
||||
#include <iostream>
|
||||
#include <plan_env/raycast.h>
|
||||
|
||||
int signum(int x) {
|
||||
return x == 0 ? 0 : x < 0 ? -1 : 1;
|
||||
}
|
||||
|
||||
double mod(double value, double modulus) {
|
||||
return fmod(fmod(value, modulus) + modulus, modulus);
|
||||
}
|
||||
|
||||
double intbound(double s, double ds) {
|
||||
// Find the smallest positive t such that s+t*ds is an integer.
|
||||
if (ds < 0) {
|
||||
return intbound(-s, -ds);
|
||||
} else {
|
||||
s = mod(s, 1);
|
||||
// problem is now s+t*ds = 1
|
||||
return (1 - s) / ds;
|
||||
}
|
||||
}
|
||||
|
||||
void Raycast(const Eigen::Vector3d& start, const Eigen::Vector3d& end, const Eigen::Vector3d& min,
|
||||
const Eigen::Vector3d& max, int& output_points_cnt, Eigen::Vector3d* output) {
|
||||
// std::cout << start << ' ' << end << std::endl;
|
||||
// From "A Fast Voxel Traversal Algorithm for Ray Tracing"
|
||||
// by John Amanatides and Andrew Woo, 1987
|
||||
// <http://www.cse.yorku.ca/~amana/research/grid.pdf>
|
||||
// <http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.3443>
|
||||
// Extensions to the described algorithm:
|
||||
// • Imposed a distance limit.
|
||||
// • The face passed through to reach the current cube is provided to
|
||||
// the callback.
|
||||
|
||||
// The foundation of this algorithm is a parameterized representation of
|
||||
// the provided ray,
|
||||
// origin + t * direction,
|
||||
// except that t is not actually stored; rather, at any given point in the
|
||||
// traversal, we keep track of the *greater* t values which we would have
|
||||
// if we took a step sufficient to cross a cube boundary along that axis
|
||||
// (i.e. change the integer part of the coordinate) in the variables
|
||||
// tMaxX, tMaxY, and tMaxZ.
|
||||
|
||||
// Cube containing origin point.
|
||||
int x = (int)std::floor(start.x());
|
||||
int y = (int)std::floor(start.y());
|
||||
int z = (int)std::floor(start.z());
|
||||
int endX = (int)std::floor(end.x());
|
||||
int endY = (int)std::floor(end.y());
|
||||
int endZ = (int)std::floor(end.z());
|
||||
Eigen::Vector3d direction = (end - start);
|
||||
double maxDist = direction.squaredNorm();
|
||||
|
||||
// Break out direction vector.
|
||||
double dx = endX - x;
|
||||
double dy = endY - y;
|
||||
double dz = endZ - z;
|
||||
|
||||
// Direction to increment x,y,z when stepping.
|
||||
int stepX = (int)signum((int)dx);
|
||||
int stepY = (int)signum((int)dy);
|
||||
int stepZ = (int)signum((int)dz);
|
||||
|
||||
// See description above. The initial values depend on the fractional
|
||||
// part of the origin.
|
||||
double tMaxX = intbound(start.x(), dx);
|
||||
double tMaxY = intbound(start.y(), dy);
|
||||
double tMaxZ = intbound(start.z(), dz);
|
||||
|
||||
// The change in t when taking a step (always positive).
|
||||
double tDeltaX = ((double)stepX) / dx;
|
||||
double tDeltaY = ((double)stepY) / dy;
|
||||
double tDeltaZ = ((double)stepZ) / dz;
|
||||
|
||||
// Avoids an infinite loop.
|
||||
if (stepX == 0 && stepY == 0 && stepZ == 0) return;
|
||||
|
||||
double dist = 0;
|
||||
while (true) {
|
||||
if (x >= min.x() && x < max.x() && y >= min.y() && y < max.y() && z >= min.z() && z < max.z()) {
|
||||
output[output_points_cnt](0) = x;
|
||||
output[output_points_cnt](1) = y;
|
||||
output[output_points_cnt](2) = z;
|
||||
|
||||
output_points_cnt++;
|
||||
dist = sqrt((x - start(0)) * (x - start(0)) + (y - start(1)) * (y - start(1)) +
|
||||
(z - start(2)) * (z - start(2)));
|
||||
|
||||
if (dist > maxDist) return;
|
||||
|
||||
/* if (output_points_cnt > 1500) {
|
||||
std::cerr << "Error, too many racyast voxels." <<
|
||||
std::endl;
|
||||
throw std::out_of_range("Too many raycast voxels");
|
||||
}*/
|
||||
}
|
||||
|
||||
if (x == endX && y == endY && z == endZ) break;
|
||||
|
||||
// tMaxX stores the t-value at which we cross a cube boundary along the
|
||||
// X axis, and similarly for Y and Z. Therefore, choosing the least tMax
|
||||
// chooses the closest cube boundary. Only the first case of the four
|
||||
// has been commented in detail.
|
||||
if (tMaxX < tMaxY) {
|
||||
if (tMaxX < tMaxZ) {
|
||||
// Update which cube we are now in.
|
||||
x += stepX;
|
||||
// Adjust tMaxX to the next X-oriented boundary crossing.
|
||||
tMaxX += tDeltaX;
|
||||
} else {
|
||||
z += stepZ;
|
||||
tMaxZ += tDeltaZ;
|
||||
}
|
||||
} else {
|
||||
if (tMaxY < tMaxZ) {
|
||||
y += stepY;
|
||||
tMaxY += tDeltaY;
|
||||
} else {
|
||||
z += stepZ;
|
||||
tMaxZ += tDeltaZ;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Raycast(const Eigen::Vector3d& start, const Eigen::Vector3d& end, const Eigen::Vector3d& min,
|
||||
const Eigen::Vector3d& max, std::vector<Eigen::Vector3d>* output) {
|
||||
// std::cout << start << ' ' << end << std::endl;
|
||||
// From "A Fast Voxel Traversal Algorithm for Ray Tracing"
|
||||
// by John Amanatides and Andrew Woo, 1987
|
||||
// <http://www.cse.yorku.ca/~amana/research/grid.pdf>
|
||||
// <http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.3443>
|
||||
// Extensions to the described algorithm:
|
||||
// • Imposed a distance limit.
|
||||
// • The face passed through to reach the current cube is provided to
|
||||
// the callback.
|
||||
|
||||
// The foundation of this algorithm is a parameterized representation of
|
||||
// the provided ray,
|
||||
// origin + t * direction,
|
||||
// except that t is not actually stored; rather, at any given point in the
|
||||
// traversal, we keep track of the *greater* t values which we would have
|
||||
// if we took a step sufficient to cross a cube boundary along that axis
|
||||
// (i.e. change the integer part of the coordinate) in the variables
|
||||
// tMaxX, tMaxY, and tMaxZ.
|
||||
|
||||
// Cube containing origin point.
|
||||
int x = (int)std::floor(start.x());
|
||||
int y = (int)std::floor(start.y());
|
||||
int z = (int)std::floor(start.z());
|
||||
int endX = (int)std::floor(end.x());
|
||||
int endY = (int)std::floor(end.y());
|
||||
int endZ = (int)std::floor(end.z());
|
||||
Eigen::Vector3d direction = (end - start);
|
||||
double maxDist = direction.squaredNorm();
|
||||
|
||||
// Break out direction vector.
|
||||
double dx = endX - x;
|
||||
double dy = endY - y;
|
||||
double dz = endZ - z;
|
||||
|
||||
// Direction to increment x,y,z when stepping.
|
||||
int stepX = (int)signum((int)dx);
|
||||
int stepY = (int)signum((int)dy);
|
||||
int stepZ = (int)signum((int)dz);
|
||||
|
||||
// See description above. The initial values depend on the fractional
|
||||
// part of the origin.
|
||||
double tMaxX = intbound(start.x(), dx);
|
||||
double tMaxY = intbound(start.y(), dy);
|
||||
double tMaxZ = intbound(start.z(), dz);
|
||||
|
||||
// The change in t when taking a step (always positive).
|
||||
double tDeltaX = ((double)stepX) / dx;
|
||||
double tDeltaY = ((double)stepY) / dy;
|
||||
double tDeltaZ = ((double)stepZ) / dz;
|
||||
|
||||
output->clear();
|
||||
|
||||
// Avoids an infinite loop.
|
||||
if (stepX == 0 && stepY == 0 && stepZ == 0) return;
|
||||
|
||||
double dist = 0;
|
||||
while (true) {
|
||||
if (x >= min.x() && x < max.x() && y >= min.y() && y < max.y() && z >= min.z() && z < max.z()) {
|
||||
output->push_back(Eigen::Vector3d(x, y, z));
|
||||
|
||||
dist = (Eigen::Vector3d(x, y, z) - start).squaredNorm();
|
||||
|
||||
if (dist > maxDist) return;
|
||||
|
||||
if (output->size() > 1500) {
|
||||
std::cerr << "Error, too many racyast voxels." << std::endl;
|
||||
throw std::out_of_range("Too many raycast voxels");
|
||||
}
|
||||
}
|
||||
|
||||
if (x == endX && y == endY && z == endZ) break;
|
||||
|
||||
// tMaxX stores the t-value at which we cross a cube boundary along the
|
||||
// X axis, and similarly for Y and Z. Therefore, choosing the least tMax
|
||||
// chooses the closest cube boundary. Only the first case of the four
|
||||
// has been commented in detail.
|
||||
if (tMaxX < tMaxY) {
|
||||
if (tMaxX < tMaxZ) {
|
||||
// Update which cube we are now in.
|
||||
x += stepX;
|
||||
// Adjust tMaxX to the next X-oriented boundary crossing.
|
||||
tMaxX += tDeltaX;
|
||||
} else {
|
||||
z += stepZ;
|
||||
tMaxZ += tDeltaZ;
|
||||
}
|
||||
} else {
|
||||
if (tMaxY < tMaxZ) {
|
||||
y += stepY;
|
||||
tMaxY += tDeltaY;
|
||||
} else {
|
||||
z += stepZ;
|
||||
tMaxZ += tDeltaZ;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool RayCaster::setInput(const Eigen::Vector3d& start,
|
||||
const Eigen::Vector3d& end /* , const Eigen::Vector3d& min,
|
||||
const Eigen::Vector3d& max */) {
|
||||
start_ = start;
|
||||
end_ = end;
|
||||
// max_ = max;
|
||||
// min_ = min;
|
||||
|
||||
x_ = (int)std::floor(start_.x());
|
||||
y_ = (int)std::floor(start_.y());
|
||||
z_ = (int)std::floor(start_.z());
|
||||
endX_ = (int)std::floor(end_.x());
|
||||
endY_ = (int)std::floor(end_.y());
|
||||
endZ_ = (int)std::floor(end_.z());
|
||||
direction_ = (end_ - start_);
|
||||
maxDist_ = direction_.squaredNorm();
|
||||
|
||||
// Break out direction vector.
|
||||
dx_ = endX_ - x_;
|
||||
dy_ = endY_ - y_;
|
||||
dz_ = endZ_ - z_;
|
||||
|
||||
// Direction to increment x,y,z when stepping.
|
||||
stepX_ = (int)signum((int)dx_);
|
||||
stepY_ = (int)signum((int)dy_);
|
||||
stepZ_ = (int)signum((int)dz_);
|
||||
|
||||
// See description above. The initial values depend on the fractional
|
||||
// part of the origin.
|
||||
tMaxX_ = intbound(start_.x(), dx_);
|
||||
tMaxY_ = intbound(start_.y(), dy_);
|
||||
tMaxZ_ = intbound(start_.z(), dz_);
|
||||
|
||||
// The change in t when taking a step (always positive).
|
||||
tDeltaX_ = ((double)stepX_) / dx_;
|
||||
tDeltaY_ = ((double)stepY_) / dy_;
|
||||
tDeltaZ_ = ((double)stepZ_) / dz_;
|
||||
|
||||
dist_ = 0;
|
||||
|
||||
step_num_ = 0;
|
||||
|
||||
// Avoids an infinite loop.
|
||||
if (stepX_ == 0 && stepY_ == 0 && stepZ_ == 0)
|
||||
return false;
|
||||
else
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RayCaster::step(Eigen::Vector3d& ray_pt) {
|
||||
// if (x_ >= min_.x() && x_ < max_.x() && y_ >= min_.y() && y_ < max_.y() &&
|
||||
// z_ >= min_.z() && z_ <
|
||||
// max_.z())
|
||||
ray_pt = Eigen::Vector3d(x_, y_, z_);
|
||||
|
||||
// step_num_++;
|
||||
|
||||
// dist_ = (Eigen::Vector3d(x_, y_, z_) - start_).squaredNorm();
|
||||
|
||||
if (x_ == endX_ && y_ == endY_ && z_ == endZ_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// if (dist_ > maxDist_)
|
||||
// {
|
||||
// return false;
|
||||
// }
|
||||
|
||||
// tMaxX stores the t-value at which we cross a cube boundary along the
|
||||
// X axis, and similarly for Y and Z. Therefore, choosing the least tMax
|
||||
// chooses the closest cube boundary. Only the first case of the four
|
||||
// has been commented in detail.
|
||||
if (tMaxX_ < tMaxY_) {
|
||||
if (tMaxX_ < tMaxZ_) {
|
||||
// Update which cube we are now in.
|
||||
x_ += stepX_;
|
||||
// Adjust tMaxX to the next X-oriented boundary crossing.
|
||||
tMaxX_ += tDeltaX_;
|
||||
} else {
|
||||
z_ += stepZ_;
|
||||
tMaxZ_ += tDeltaZ_;
|
||||
}
|
||||
} else {
|
||||
if (tMaxY_ < tMaxZ_) {
|
||||
y_ += stepY_;
|
||||
tMaxY_ += tDeltaY_;
|
||||
} else {
|
||||
z_ += stepZ_;
|
||||
tMaxZ_ += tDeltaZ_;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
cmake_minimum_required(VERSION 3.8)
|
||||
project(scan_planner)
|
||||
|
||||
if(NOT CMAKE_CXX_STANDARD)
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
endif()
|
||||
add_compile_options(-Wall -Wextra -Wpedantic)
|
||||
|
||||
find_package(ament_cmake REQUIRED)
|
||||
find_package(ament_index_cpp REQUIRED)
|
||||
find_package(bspline_opt REQUIRED)
|
||||
find_package(Eigen3 REQUIRED)
|
||||
find_package(geometry_msgs REQUIRED)
|
||||
find_package(nav_msgs REQUIRED)
|
||||
find_package(path_searching REQUIRED)
|
||||
find_package(plan_env REQUIRED)
|
||||
find_package(rclcpp REQUIRED)
|
||||
find_package(scan_planner_msgs REQUIRED)
|
||||
find_package(sensor_msgs REQUIRED)
|
||||
find_package(std_msgs REQUIRED)
|
||||
find_package(tf2 REQUIRED)
|
||||
find_package(tf2_geometry_msgs REQUIRED)
|
||||
find_package(tf2_ros REQUIRED)
|
||||
find_package(traj_utils REQUIRED)
|
||||
find_package(visualization_msgs REQUIRED)
|
||||
|
||||
set(scan_planner_dependencies
|
||||
ament_index_cpp bspline_opt geometry_msgs nav_msgs path_searching plan_env
|
||||
rclcpp scan_planner_msgs sensor_msgs std_msgs tf2 tf2_geometry_msgs tf2_ros
|
||||
traj_utils visualization_msgs)
|
||||
|
||||
add_executable(scan_planner_node
|
||||
src/scan_planner_node.cpp
|
||||
src/scan_replan_fsm.cpp
|
||||
src/planner_manager.cpp)
|
||||
target_include_directories(scan_planner_node PRIVATE include)
|
||||
ament_target_dependencies(scan_planner_node ${scan_planner_dependencies})
|
||||
target_link_libraries(scan_planner_node Eigen3::Eigen)
|
||||
|
||||
foreach(target open_loop_controller closed_loop_controller go2_kinematic_sim go2_gait_publisher)
|
||||
add_executable(${target} src/${target}.cpp)
|
||||
target_include_directories(${target} PRIVATE include)
|
||||
ament_target_dependencies(${target}
|
||||
bspline_opt geometry_msgs nav_msgs rclcpp scan_planner_msgs sensor_msgs
|
||||
std_msgs tf2 tf2_geometry_msgs tf2_ros)
|
||||
target_link_libraries(${target} Eigen3::Eigen)
|
||||
endforeach()
|
||||
|
||||
install(TARGETS
|
||||
scan_planner_node open_loop_controller closed_loop_controller
|
||||
go2_kinematic_sim go2_gait_publisher
|
||||
DESTINATION lib/${PROJECT_NAME})
|
||||
install(DIRECTORY include/ DESTINATION include)
|
||||
install(DIRECTORY launch config DESTINATION share/${PROJECT_NAME} OPTIONAL)
|
||||
install(FILES launch/default.rviz launch/building.rviz
|
||||
DESTINATION share/${PROJECT_NAME}/rviz OPTIONAL)
|
||||
install(PROGRAMS
|
||||
scripts/keypoint_recorder.py
|
||||
scripts/reference_path_publisher.py
|
||||
DESTINATION lib/${PROJECT_NAME} OPTIONAL)
|
||||
|
||||
if(BUILD_TESTING)
|
||||
find_package(ament_cmake_gtest REQUIRED)
|
||||
find_package(ament_cmake_pytest REQUIRED)
|
||||
find_package(launch_testing_ament_cmake REQUIRED)
|
||||
ament_add_gtest(test_reference_path_utils test/test_reference_path_utils.cpp)
|
||||
target_include_directories(test_reference_path_utils PRIVATE include)
|
||||
ament_target_dependencies(test_reference_path_utils nav_msgs traj_utils)
|
||||
target_link_libraries(test_reference_path_utils Eigen3::Eigen)
|
||||
set(_pytest_disable_plugin_autoload "$ENV{PYTEST_DISABLE_PLUGIN_AUTOLOAD}")
|
||||
set(ENV{PYTEST_DISABLE_PLUGIN_AUTOLOAD} "1")
|
||||
ament_add_pytest_test(
|
||||
test_reference_path_publisher_unit
|
||||
test/test_reference_path_publisher_unit.py
|
||||
PYTHON_EXECUTABLE /usr/bin/python3
|
||||
ENV PYTEST_DISABLE_PLUGIN_AUTOLOAD=1)
|
||||
set(ENV{PYTEST_DISABLE_PLUGIN_AUTOLOAD} "${_pytest_disable_plugin_autoload}")
|
||||
add_launch_test(test/test_planner_startup.py TIMEOUT 30)
|
||||
add_launch_test(test/test_reference_path_publisher_launch.py TIMEOUT 30)
|
||||
add_launch_test(test/test_waypoint_parameters.py TIMEOUT 30)
|
||||
endif()
|
||||
|
||||
ament_package()
|
||||
@@ -0,0 +1,52 @@
|
||||
closed_loop_controller:
|
||||
ros__parameters:
|
||||
use_sim_time: false
|
||||
time_forward: 0.8
|
||||
heading_error_threshold: 0.8
|
||||
kp_pos: 0.8
|
||||
kp_yaw: 1.5
|
||||
max_vx: 0.75
|
||||
max_vy: 0.35
|
||||
max_vyaw: 1.0
|
||||
finish_dist: 0.15
|
||||
|
||||
open_loop_controller:
|
||||
ros__parameters:
|
||||
use_sim_time: false
|
||||
frame_id: world
|
||||
child_frame_id: base
|
||||
publish_rate: 100.0
|
||||
yaw_min_speed: 0.05
|
||||
hold_final_position: true
|
||||
init_x: -19.0
|
||||
init_y: 1.0
|
||||
init_z: 0.3
|
||||
init_yaw: 0.0
|
||||
|
||||
go2_kinematic_sim:
|
||||
ros__parameters:
|
||||
use_sim_time: false
|
||||
init_x: -19.0
|
||||
init_y: 1.0
|
||||
init_z: 0.3
|
||||
init_yaw: 0.0
|
||||
max_vx: 0.75
|
||||
max_vy: 0.35
|
||||
max_vyaw: 1.0
|
||||
cmd_timeout: 0.3
|
||||
sim_rate: 100.0
|
||||
publish_tf: true
|
||||
frame_id: world
|
||||
child_frame_id: base
|
||||
|
||||
go2_gait_publisher:
|
||||
ros__parameters:
|
||||
use_sim_time: false
|
||||
rate: 60.0
|
||||
gait_frequency: 2.2
|
||||
min_walk_speed: 0.05
|
||||
max_walk_speed: 1.0
|
||||
always_trot: false
|
||||
hip_swing: 0.08
|
||||
thigh_swing: 0.32
|
||||
calf_swing: 0.42
|
||||
@@ -0,0 +1,15 @@
|
||||
# 轮式全向底盘控制器参数(复制自 controllers.yaml,按轮式车改)。
|
||||
# 只保留真机用得到的 closed_loop_controller;open_loop/go2_* 是仿真用的,未复制。
|
||||
|
||||
closed_loop_controller:
|
||||
ros__parameters:
|
||||
use_sim_time: false
|
||||
time_forward: 0.8
|
||||
# 朝向误差超过该值(rad)就原地转、不前进。四足原来 0.8,轮式收紧到 0.6。
|
||||
heading_error_threshold: 0.6
|
||||
kp_pos: 0.8
|
||||
kp_yaw: 1.5
|
||||
max_vx: 0.80
|
||||
max_vy: 0.40
|
||||
max_vyaw: 1.20
|
||||
finish_dist: 0.15
|
||||
@@ -0,0 +1,4 @@
|
||||
scan_planner_node:
|
||||
ros__parameters:
|
||||
fsm.navi_mode: 2
|
||||
fsm.waypoints: [0.0, 0.0, 0.3, 2.0, 0.0, 0.3]
|
||||
@@ -0,0 +1,67 @@
|
||||
scan_planner_node:
|
||||
ros__parameters:
|
||||
use_sim_time: false
|
||||
|
||||
fsm.navi_mode: 1
|
||||
fsm.thresh_replan: 1.0
|
||||
fsm.thresh_no_replan: 0.1
|
||||
fsm.planning_horizon: 3.5
|
||||
fsm.emergency_time: 1.0
|
||||
fsm.fail_safe: true
|
||||
fsm.max_replan_fail_count: 1000
|
||||
|
||||
grid_map.resolution: 0.05
|
||||
grid_map.sliding_map_size_x: 10.0
|
||||
grid_map.sliding_map_size_y: 10.0
|
||||
grid_map.sliding_map_size_z: 5.0
|
||||
grid_map.local_update_range_x: 5.0
|
||||
grid_map.local_update_range_y: 5.0
|
||||
grid_map.local_update_range_z: 2.5
|
||||
grid_map.map_sliding_en: true
|
||||
grid_map.map_sliding_thresh: 0.2
|
||||
grid_map.double_cylinder_radius: 0.25
|
||||
grid_map.double_cylinder_offset: 0.18
|
||||
grid_map.body_height: 0.4
|
||||
grid_map.obstacles_inflation_z_up: 0.1
|
||||
grid_map.obstacles_inflation_z_down: 0.1
|
||||
grid_map.frame_id: world
|
||||
grid_map.sliding_map_frame_id: sliding_map
|
||||
grid_map.ground_height: 0.0
|
||||
grid_map.sensor_type: lidar
|
||||
grid_map.cloud_is_world: true
|
||||
grid_map.need_extrinsic: false
|
||||
|
||||
grid_map.cx: 321.04638671875
|
||||
grid_map.cy: 243.44969177246094
|
||||
grid_map.fx: 387.229248046875
|
||||
grid_map.fy: 387.229248046875
|
||||
grid_map.depth_filter_maxdist: 3.0
|
||||
grid_map.depth_filter_mindist: 0.3
|
||||
grid_map.depth_filter_margin: 1
|
||||
grid_map.k_depth_scaling_factor: 1000.0
|
||||
grid_map.skip_pixel: 2
|
||||
|
||||
grid_map.p_hit: 0.85
|
||||
grid_map.p_miss: 0.30
|
||||
grid_map.p_min: 0.12
|
||||
grid_map.p_max: 0.98
|
||||
grid_map.p_occ: 0.80
|
||||
grid_map.max_ray_length: 5.0
|
||||
grid_map.vis_height: 0.3
|
||||
grid_map.show_occ_time: false
|
||||
|
||||
manager.max_vel: 0.75
|
||||
manager.max_acc: 0.5
|
||||
manager.max_jerk: 4.0
|
||||
manager.control_points_distance: 0.2
|
||||
manager.feasibility_tolerance: 0.5
|
||||
manager.planning_horizon: 3.5
|
||||
|
||||
optimization.lambda_smooth: 1.0
|
||||
optimization.lambda_collision: 1.0
|
||||
optimization.lambda_feasibility: 0.1
|
||||
optimization.lambda_fitness: 1.0
|
||||
optimization.dist0: 0.2
|
||||
optimization.max_vel: 0.75
|
||||
optimization.max_acc: 0.5
|
||||
optimization.order: 3
|
||||
@@ -0,0 +1,86 @@
|
||||
# 轮式全向底盘专用参数(复制自 planner.yaml,按轮式车改)。
|
||||
#
|
||||
# 与 planner.yaml 的差异只在这几项:
|
||||
# 1. 碰撞模型按轮式车体(双圆柱)放大;
|
||||
# 2. 速度/加速度按底盘能力;
|
||||
# 3. frame_id 保持 world,由 launch 里的静态 TF world->camera_init 接到 Point-LIO。
|
||||
#
|
||||
# ⚠️ 轮式车不能跨台阶。SCAN 的 3D 体素只会把“坡面上方 free”判为可通行,
|
||||
# 台阶对四足可过、对轮式不可过,但算法本身不区分。场地有台阶时,
|
||||
# 要么绕开,要么在点云里把台阶标成障碍(或调小 obstacles_inflation_z_down)。
|
||||
|
||||
scan_planner_node:
|
||||
ros__parameters:
|
||||
use_sim_time: false
|
||||
|
||||
# 1 = 纯局部(无先验地图);2 = keypoints 引导;3 = PCT 全局路线
|
||||
fsm.navi_mode: 1
|
||||
fsm.thresh_replan: 1.0
|
||||
fsm.thresh_no_replan: 0.1
|
||||
fsm.planning_horizon: 3.5
|
||||
fsm.emergency_time: 1.0
|
||||
fsm.fail_safe: true
|
||||
fsm.max_replan_fail_count: 1000
|
||||
|
||||
grid_map.resolution: 0.05
|
||||
grid_map.sliding_map_size_x: 10.0
|
||||
grid_map.sliding_map_size_y: 10.0
|
||||
grid_map.sliding_map_size_z: 5.0
|
||||
grid_map.local_update_range_x: 5.0
|
||||
grid_map.local_update_range_y: 5.0
|
||||
grid_map.local_update_range_z: 2.5
|
||||
grid_map.map_sliding_en: true
|
||||
grid_map.map_sliding_thresh: 0.2
|
||||
|
||||
# ---- 车体碰撞模型(轮式,按实车量)----------------------------------
|
||||
# 双圆柱:两个半径 0.30 m 的圆,圆心沿车体 x 前后各偏 0.20 m
|
||||
grid_map.double_cylinder_radius: 0.30
|
||||
grid_map.double_cylinder_offset: 0.20
|
||||
grid_map.body_height: 0.50
|
||||
grid_map.obstacles_inflation_z_up: 0.15
|
||||
grid_map.obstacles_inflation_z_down: 0.05
|
||||
|
||||
grid_map.frame_id: world
|
||||
grid_map.sliding_map_frame_id: sliding_map
|
||||
grid_map.ground_height: 0.0
|
||||
grid_map.sensor_type: lidar
|
||||
# 点云已经是世界系(Point-LIO 的 /cloud_registered)⇒ 不需要外参
|
||||
grid_map.cloud_is_world: true
|
||||
grid_map.need_extrinsic: false
|
||||
|
||||
# 以下仅 sensor_type=depth 时有效,保留占位
|
||||
grid_map.cx: 321.04638671875
|
||||
grid_map.cy: 243.44969177246094
|
||||
grid_map.fx: 387.229248046875
|
||||
grid_map.fy: 387.229248046875
|
||||
grid_map.depth_filter_maxdist: 3.0
|
||||
grid_map.depth_filter_mindist: 0.3
|
||||
grid_map.depth_filter_margin: 1
|
||||
grid_map.k_depth_scaling_factor: 1000.0
|
||||
grid_map.skip_pixel: 2
|
||||
|
||||
grid_map.p_hit: 0.85
|
||||
grid_map.p_miss: 0.30
|
||||
grid_map.p_min: 0.12
|
||||
grid_map.p_max: 0.98
|
||||
grid_map.p_occ: 0.80
|
||||
grid_map.max_ray_length: 5.0
|
||||
grid_map.vis_height: 0.3
|
||||
grid_map.show_occ_time: false
|
||||
|
||||
# ---- 速度/加速度(不得超过底盘能力)--------------------------------
|
||||
manager.max_vel: 0.80
|
||||
manager.max_acc: 0.60
|
||||
manager.max_jerk: 4.0
|
||||
manager.control_points_distance: 0.2
|
||||
manager.feasibility_tolerance: 0.5
|
||||
manager.planning_horizon: 3.5
|
||||
|
||||
optimization.lambda_smooth: 1.0
|
||||
optimization.lambda_collision: 1.0
|
||||
optimization.lambda_feasibility: 0.1
|
||||
optimization.lambda_fitness: 1.0
|
||||
optimization.dist0: 0.2
|
||||
optimization.max_vel: 0.80
|
||||
optimization.max_acc: 0.60
|
||||
optimization.order: 3
|
||||
@@ -0,0 +1,17 @@
|
||||
reference_path_publisher:
|
||||
ros__parameters:
|
||||
frame_id: world
|
||||
publish_delay_sec: 0.5
|
||||
# Ground/route heights. scan_planner adds grid_map.body_height (0.4 m).
|
||||
waypoints:
|
||||
[-5.5, 5.5, 0.10,
|
||||
-5.5, 4.5, 0.30,
|
||||
-5.5, 3.5, 0.40,
|
||||
-5.5, 2.5, 0.55,
|
||||
-5.5, 1.5, 0.70,
|
||||
-5.5, 0.5, 0.85,
|
||||
-5.5, -0.5, 1.00,
|
||||
-5.5, -1.5, 1.20,
|
||||
-5.5, -2.5, 1.40,
|
||||
-5.5, -3.5, 1.55,
|
||||
-5.5, -4.5, 1.55]
|
||||
@@ -0,0 +1,73 @@
|
||||
mockamap_node:
|
||||
ros__parameters:
|
||||
use_sim_time: false
|
||||
seed: 127
|
||||
update_freq: 0.5
|
||||
resolution: 0.1
|
||||
x_length: 40
|
||||
y_length: 40
|
||||
z_length: 5
|
||||
type: 2
|
||||
complexity: 0.05
|
||||
fill: 0.12
|
||||
fractal: 1
|
||||
attenuation: 0.1
|
||||
width_min: 0.2
|
||||
width_max: 0.8
|
||||
height_min: 2.0
|
||||
height_max: 2.0
|
||||
obstacle_number: 500
|
||||
surface_resolution: 0.05
|
||||
|
||||
pcl_render_node:
|
||||
ros__parameters:
|
||||
use_sim_time: false
|
||||
quadrotor_name: quad_0
|
||||
sensor_type: lidar
|
||||
body_pose_topic: body_pose
|
||||
map.resolution: 0.1
|
||||
map.x_size: 40.0
|
||||
map.y_size: 40.0
|
||||
map.z_size: 5.0
|
||||
sensing_horizon: 40.0
|
||||
sensing_rate: 10.0
|
||||
estimation_rate: 10.0
|
||||
polar_resolution: 0.2
|
||||
yaw_fov: 360.0
|
||||
vertical_fov: 90.0
|
||||
min_raylength: 1.0
|
||||
downsample_res: 0.1
|
||||
lidar_pitch: 45.0
|
||||
is_360lidar: 1
|
||||
use_minicf_pattern: 1
|
||||
use_avia_pattern: 0
|
||||
use_vlp32_pattern: 0
|
||||
use_os64_pattern: 0
|
||||
use_os128_pattern: 0
|
||||
cam_width: 640
|
||||
cam_height: 480
|
||||
cam_fx: 387.229248046875
|
||||
cam_fy: 387.229248046875
|
||||
cam_cx: 321.04638671875
|
||||
cam_cy: 243.44969177246094
|
||||
dynamic.enable: 0
|
||||
dynamic.object_size: 0.0
|
||||
dynamic.object_count: 0
|
||||
dynamic.mode: 0
|
||||
dynamic.velocity: 0.0
|
||||
collision_check.enable: 0
|
||||
collision_check.range: 0.3
|
||||
use_global_map_topic: true
|
||||
pcd_map_file: ''
|
||||
|
||||
odom_visualization:
|
||||
ros__parameters:
|
||||
use_sim_time: false
|
||||
frame_id: world
|
||||
child_frame_id: base
|
||||
publish_tf: true
|
||||
robot_scale: 1.0
|
||||
color.r: 0.0
|
||||
color.g: 0.0
|
||||
color.b: 0.0
|
||||
color.a: 1.0
|
||||
@@ -0,0 +1,220 @@
|
||||
#ifndef _PLAN_CONTAINER_H_
|
||||
#define _PLAN_CONTAINER_H_
|
||||
|
||||
#include <Eigen/Eigen>
|
||||
#include <vector>
|
||||
#include <rclcpp/rclcpp.hpp>
|
||||
|
||||
#include <bspline_opt/uniform_bspline.h>
|
||||
#include <traj_utils/polynomial_traj.h>
|
||||
|
||||
using std::vector;
|
||||
|
||||
namespace scan_planner
|
||||
{
|
||||
|
||||
class GlobalTrajData
|
||||
{
|
||||
private:
|
||||
public:
|
||||
PolynomialTraj global_traj_;
|
||||
vector<UniformBspline> local_traj_;
|
||||
|
||||
double global_duration_;
|
||||
rclcpp::Time global_start_time_;
|
||||
double local_start_time_, local_end_time_;
|
||||
double time_increase_;
|
||||
double last_time_inc_;
|
||||
double last_progress_time_;
|
||||
|
||||
GlobalTrajData(/* args */) {}
|
||||
|
||||
~GlobalTrajData() {}
|
||||
|
||||
bool localTrajReachTarget() { return fabs(local_end_time_ - global_duration_) < 0.1; }
|
||||
|
||||
void setGlobalTraj(const PolynomialTraj &traj, const rclcpp::Time &time)
|
||||
{
|
||||
global_traj_ = traj;
|
||||
global_traj_.init();
|
||||
global_duration_ = global_traj_.getTimeSum();
|
||||
global_start_time_ = time;
|
||||
|
||||
local_traj_.clear();
|
||||
local_start_time_ = -1;
|
||||
local_end_time_ = -1;
|
||||
time_increase_ = 0.0;
|
||||
last_time_inc_ = 0.0;
|
||||
last_progress_time_ = 0.0;
|
||||
}
|
||||
|
||||
void setLocalTraj(UniformBspline traj, double local_ts, double local_te, double time_inc)
|
||||
{
|
||||
local_traj_.resize(3);
|
||||
local_traj_[0] = traj;
|
||||
local_traj_[1] = local_traj_[0].getDerivative();
|
||||
local_traj_[2] = local_traj_[1].getDerivative();
|
||||
|
||||
local_start_time_ = local_ts;
|
||||
local_end_time_ = local_te;
|
||||
global_duration_ += time_inc;
|
||||
time_increase_ += time_inc;
|
||||
last_time_inc_ = time_inc;
|
||||
}
|
||||
|
||||
Eigen::Vector3d getPosition(double t)
|
||||
{
|
||||
if (t >= -1e-3 && t <= local_start_time_)
|
||||
{
|
||||
return global_traj_.evaluate(t - time_increase_ + last_time_inc_);
|
||||
}
|
||||
else if (t >= local_end_time_ && t <= global_duration_ + 1e-3)
|
||||
{
|
||||
return global_traj_.evaluate(t - time_increase_);
|
||||
}
|
||||
else
|
||||
{
|
||||
double tm, tmp;
|
||||
local_traj_[0].getTimeSpan(tm, tmp);
|
||||
return local_traj_[0].evaluateDeBoor(tm + t - local_start_time_);
|
||||
}
|
||||
}
|
||||
|
||||
Eigen::Vector3d getVelocity(double t)
|
||||
{
|
||||
if (t >= -1e-3 && t <= local_start_time_)
|
||||
{
|
||||
return global_traj_.evaluateVel(t);
|
||||
}
|
||||
else if (t >= local_end_time_ && t <= global_duration_ + 1e-3)
|
||||
{
|
||||
return global_traj_.evaluateVel(t - time_increase_);
|
||||
}
|
||||
else
|
||||
{
|
||||
double tm, tmp;
|
||||
local_traj_[0].getTimeSpan(tm, tmp);
|
||||
return local_traj_[1].evaluateDeBoor(tm + t - local_start_time_);
|
||||
}
|
||||
}
|
||||
|
||||
Eigen::Vector3d getAcceleration(double t)
|
||||
{
|
||||
if (t >= -1e-3 && t <= local_start_time_)
|
||||
{
|
||||
return global_traj_.evaluateAcc(t);
|
||||
}
|
||||
else if (t >= local_end_time_ && t <= global_duration_ + 1e-3)
|
||||
{
|
||||
return global_traj_.evaluateAcc(t - time_increase_);
|
||||
}
|
||||
else
|
||||
{
|
||||
double tm, tmp;
|
||||
local_traj_[0].getTimeSpan(tm, tmp);
|
||||
return local_traj_[2].evaluateDeBoor(tm + t - local_start_time_);
|
||||
}
|
||||
}
|
||||
|
||||
// get Bspline parameterization data of a local trajectory within a sphere
|
||||
// start_t: start time of the trajectory
|
||||
// dist_pt: distance between the discretized points
|
||||
void getTrajByRadius(const double &start_t, const double &des_radius, const double &dist_pt,
|
||||
vector<Eigen::Vector3d> &point_set, vector<Eigen::Vector3d> &start_end_derivative,
|
||||
double &dt, double &seg_duration)
|
||||
{
|
||||
double seg_length = 0.0; // length of the truncated segment
|
||||
double seg_time = 0.0; // duration of the truncated segment
|
||||
double radius = 0.0; // distance to the first point of the segment
|
||||
|
||||
double delta = 0.2;
|
||||
Eigen::Vector3d first_pt = getPosition(start_t); // first point of the segment
|
||||
Eigen::Vector3d prev_pt = first_pt; // previous point
|
||||
Eigen::Vector3d cur_pt; // current point
|
||||
|
||||
// go forward until the traj exceed radius or global time
|
||||
|
||||
while (radius < des_radius && seg_time < global_duration_ - start_t - 1e-3)
|
||||
{
|
||||
seg_time += delta;
|
||||
seg_time = min(seg_time, global_duration_ - start_t);
|
||||
|
||||
cur_pt = getPosition(start_t + seg_time);
|
||||
seg_length += (cur_pt - prev_pt).norm();
|
||||
prev_pt = cur_pt;
|
||||
radius = (cur_pt - first_pt).norm();
|
||||
}
|
||||
|
||||
// get parameterization dt by desired density of points
|
||||
int seg_num = floor(seg_length / dist_pt);
|
||||
|
||||
// get outputs
|
||||
|
||||
seg_duration = seg_time; // duration of the truncated segment
|
||||
dt = seg_time / seg_num; // time difference between two points
|
||||
|
||||
for (double tp = 0.0; tp <= seg_time + 1e-4; tp += dt)
|
||||
{
|
||||
cur_pt = getPosition(start_t + tp);
|
||||
point_set.push_back(cur_pt);
|
||||
}
|
||||
|
||||
start_end_derivative.push_back(getVelocity(start_t));
|
||||
start_end_derivative.push_back(getVelocity(start_t + seg_time));
|
||||
start_end_derivative.push_back(getAcceleration(start_t));
|
||||
start_end_derivative.push_back(getAcceleration(start_t + seg_time));
|
||||
}
|
||||
|
||||
// get Bspline parameterization data of a fixed duration local trajectory
|
||||
// start_t: start time of the trajectory
|
||||
// duration: time length of the segment
|
||||
// seg_num: discretized the segment into *seg_num* parts
|
||||
void getTrajByDuration(double start_t, double duration, int seg_num,
|
||||
vector<Eigen::Vector3d> &point_set,
|
||||
vector<Eigen::Vector3d> &start_end_derivative, double &dt)
|
||||
{
|
||||
dt = duration / seg_num;
|
||||
Eigen::Vector3d cur_pt;
|
||||
for (double tp = 0.0; tp <= duration + 1e-4; tp += dt)
|
||||
{
|
||||
cur_pt = getPosition(start_t + tp);
|
||||
point_set.push_back(cur_pt);
|
||||
}
|
||||
|
||||
start_end_derivative.push_back(getVelocity(start_t));
|
||||
start_end_derivative.push_back(getVelocity(start_t + duration));
|
||||
start_end_derivative.push_back(getAcceleration(start_t));
|
||||
start_end_derivative.push_back(getAcceleration(start_t + duration));
|
||||
}
|
||||
};
|
||||
|
||||
struct PlanParameters
|
||||
{
|
||||
/* planning algorithm parameters */
|
||||
double max_vel_, max_acc_, max_jerk_; // physical limits
|
||||
double vel_tolerance_, acc_tolerance_;
|
||||
double ctrl_pt_dist; // distance between adjacient B-spline control points
|
||||
double feasibility_tolerance_; // permitted ratio of vel/acc exceeding limits
|
||||
double planning_horizon_;
|
||||
|
||||
/* processing time */
|
||||
double time_search_ = 0.0;
|
||||
double time_optimize_ = 0.0;
|
||||
double time_adjust_ = 0.0;
|
||||
};
|
||||
|
||||
struct LocalTrajData
|
||||
{
|
||||
/* info of generated traj */
|
||||
|
||||
int traj_id_;
|
||||
double duration_;
|
||||
double global_time_offset; // This is because when the local traj finished and is going to switch back to the global traj, the global traj time is no longer matches the world time.
|
||||
rclcpp::Time start_time_;
|
||||
Eigen::Vector3d start_pos_;
|
||||
UniformBspline position_traj_, velocity_traj_, acceleration_traj_;
|
||||
};
|
||||
|
||||
} // namespace scan_planner
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,72 @@
|
||||
#ifndef _PLANNER_MANAGER_H_
|
||||
#define _PLANNER_MANAGER_H_
|
||||
|
||||
#include <stdlib.h>
|
||||
|
||||
#include <bspline_opt/bspline_optimizer.h>
|
||||
#include <bspline_opt/uniform_bspline.h>
|
||||
#include <plan_env/grid_map.h>
|
||||
#include <plan_manage/plan_container.hpp>
|
||||
#include <rclcpp/rclcpp.hpp>
|
||||
#include <traj_utils/planning_visualization.h>
|
||||
|
||||
namespace scan_planner
|
||||
{
|
||||
|
||||
// Fast Planner Manager
|
||||
// Key algorithms of mapping and planning are called
|
||||
|
||||
class SCANPlannerManager
|
||||
{
|
||||
// SECTION stable
|
||||
public:
|
||||
SCANPlannerManager();
|
||||
~SCANPlannerManager();
|
||||
|
||||
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
|
||||
|
||||
/* main planning interface */
|
||||
bool reboundReplan(Eigen::Vector3d start_pt, Eigen::Vector3d start_vel, Eigen::Vector3d start_acc,
|
||||
Eigen::Vector3d end_pt, Eigen::Vector3d end_vel, bool flag_polyInit, bool flag_randomPolyTraj);
|
||||
bool EmergencyStop(Eigen::Vector3d stop_pos);
|
||||
bool planGlobalTraj(const Eigen::Vector3d &start_pos, const Eigen::Vector3d &start_vel, const Eigen::Vector3d &start_acc,
|
||||
const Eigen::Vector3d &end_pos, const Eigen::Vector3d &end_vel, const Eigen::Vector3d &end_acc);
|
||||
bool planGlobalTrajWaypoints(const Eigen::Vector3d &start_pos, const Eigen::Vector3d &start_vel, const Eigen::Vector3d &start_acc,
|
||||
const std::vector<Eigen::Vector3d> &waypoints, const Eigen::Vector3d &end_vel, const Eigen::Vector3d &end_acc);
|
||||
|
||||
void initPlanModules(rclcpp::Node *node, PlanningVisualization::Ptr vis = nullptr);
|
||||
|
||||
PlanParameters pp_;
|
||||
LocalTrajData local_data_;
|
||||
GlobalTrajData global_data_;
|
||||
GridMap::Ptr grid_map_;
|
||||
|
||||
private:
|
||||
rclcpp::Node *node_{nullptr};
|
||||
/* main planning algorithms & modules */
|
||||
PlanningVisualization::Ptr visualization_;
|
||||
|
||||
BsplineOptimizer::Ptr bspline_optimizer_rebound_;
|
||||
|
||||
int continuous_failures_count_{0};
|
||||
|
||||
void updateTrajInfo(const UniformBspline &position_traj, const rclcpp::Time time_now);
|
||||
bool checkDynamicFeasibility(UniformBspline position_traj);
|
||||
|
||||
void reparamBspline(UniformBspline &bspline, vector<Eigen::Vector3d> &start_end_derivative, double ratio, Eigen::MatrixXd &ctrl_pts, double &dt,
|
||||
double &time_inc);
|
||||
|
||||
bool refineTrajAlgo(UniformBspline &traj, vector<Eigen::Vector3d> &start_end_derivative, double ratio, double &ts, Eigen::MatrixXd &optimal_control_points);
|
||||
|
||||
// !SECTION stable
|
||||
|
||||
// SECTION developing
|
||||
|
||||
public:
|
||||
typedef unique_ptr<SCANPlannerManager> Ptr;
|
||||
|
||||
// !SECTION
|
||||
};
|
||||
} // namespace scan_planner
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,65 @@
|
||||
#ifndef PLAN_MANAGE_POLYLINE_TRAJECTORY_UTILS_H
|
||||
#define PLAN_MANAGE_POLYLINE_TRAJECTORY_UTILS_H
|
||||
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <Eigen/Eigen>
|
||||
#include <traj_utils/polynomial_traj.h>
|
||||
|
||||
namespace scan_planner
|
||||
{
|
||||
|
||||
inline bool makePiecewiseLinearTrajectory(
|
||||
const std::vector<Eigen::Vector3d> &input_points,
|
||||
double speed,
|
||||
PolynomialTraj &trajectory,
|
||||
std::string *error = nullptr)
|
||||
{
|
||||
trajectory.reset();
|
||||
if (!std::isfinite(speed) || speed <= 0.0)
|
||||
{
|
||||
if (error) *error = "polyline speed must be finite and positive";
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<Eigen::Vector3d> points;
|
||||
points.reserve(input_points.size());
|
||||
for (const auto &point : input_points)
|
||||
{
|
||||
if (!point.allFinite())
|
||||
{
|
||||
if (error) *error = "polyline contains a non-finite point";
|
||||
return false;
|
||||
}
|
||||
if (points.empty() || (point - points.back()).norm() > 1e-6)
|
||||
points.push_back(point);
|
||||
}
|
||||
if (points.size() < 2)
|
||||
{
|
||||
if (error) *error = "polyline requires at least two distinct points";
|
||||
return false;
|
||||
}
|
||||
|
||||
for (size_t index = 0; index + 1 < points.size(); ++index)
|
||||
{
|
||||
const Eigen::Vector3d delta = points[index + 1] - points[index];
|
||||
const double length = delta.norm();
|
||||
const double duration = length / speed;
|
||||
const Eigen::Vector3d velocity = delta / duration;
|
||||
|
||||
// PolynomialTraj stores each axis in descending power order. A linear
|
||||
// segment is therefore [0*t^5, 0*t^4, 0*t^3, 0*t^2, v*t, p0].
|
||||
std::vector<double> cx{0.0, 0.0, 0.0, 0.0, velocity.x(), points[index].x()};
|
||||
std::vector<double> cy{0.0, 0.0, 0.0, 0.0, velocity.y(), points[index].y()};
|
||||
std::vector<double> cz{0.0, 0.0, 0.0, 0.0, velocity.z(), points[index].z()};
|
||||
trajectory.addSegment(cx, cy, cz, duration);
|
||||
}
|
||||
trajectory.init();
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace scan_planner
|
||||
|
||||
#endif // PLAN_MANAGE_POLYLINE_TRAJECTORY_UTILS_H
|
||||
@@ -0,0 +1,145 @@
|
||||
#ifndef PLAN_MANAGE_REFERENCE_PATH_UTILS_H
|
||||
#define PLAN_MANAGE_REFERENCE_PATH_UTILS_H
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include <Eigen/Eigen>
|
||||
#include <nav_msgs/msg/path.hpp>
|
||||
|
||||
namespace scan_planner
|
||||
{
|
||||
|
||||
inline std::vector<Eigen::Vector3d> simplifyReferenceWaypoints(
|
||||
const std::vector<Eigen::Vector3d> &points,
|
||||
double tolerance)
|
||||
{
|
||||
if (points.size() <= 2 || tolerance <= 0.0)
|
||||
return points;
|
||||
|
||||
std::vector<bool> keep(points.size(), false);
|
||||
keep.front() = true;
|
||||
keep.back() = true;
|
||||
std::vector<std::pair<size_t, size_t>> ranges{{0, points.size() - 1}};
|
||||
|
||||
while (!ranges.empty())
|
||||
{
|
||||
const auto [first, last] = ranges.back();
|
||||
ranges.pop_back();
|
||||
if (last <= first + 1)
|
||||
continue;
|
||||
|
||||
const Eigen::Vector3d segment = points[last] - points[first];
|
||||
const double squared_length = segment.squaredNorm();
|
||||
double max_distance = -1.0;
|
||||
size_t max_index = first;
|
||||
|
||||
for (size_t index = first + 1; index < last; ++index)
|
||||
{
|
||||
double distance;
|
||||
if (squared_length <= 1e-12)
|
||||
{
|
||||
distance = (points[index] - points[first]).norm();
|
||||
}
|
||||
else
|
||||
{
|
||||
const double ratio = std::clamp(
|
||||
(points[index] - points[first]).dot(segment) / squared_length,
|
||||
0.0, 1.0);
|
||||
const Eigen::Vector3d projection = points[first] + ratio * segment;
|
||||
distance = (points[index] - projection).norm();
|
||||
}
|
||||
|
||||
if (distance > max_distance)
|
||||
{
|
||||
max_distance = distance;
|
||||
max_index = index;
|
||||
}
|
||||
}
|
||||
|
||||
if (max_distance > tolerance)
|
||||
{
|
||||
keep[max_index] = true;
|
||||
ranges.emplace_back(first, max_index);
|
||||
ranges.emplace_back(max_index, last);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<Eigen::Vector3d> simplified;
|
||||
simplified.reserve(points.size());
|
||||
for (size_t index = 0; index < points.size(); ++index)
|
||||
{
|
||||
if (keep[index])
|
||||
simplified.push_back(points[index]);
|
||||
}
|
||||
return simplified;
|
||||
}
|
||||
|
||||
inline bool prepareReferenceWaypoints(
|
||||
const nav_msgs::msg::Path &path,
|
||||
double body_height,
|
||||
double min_distance,
|
||||
std::vector<Eigen::Vector3d> &waypoints,
|
||||
std::string *error = nullptr,
|
||||
double simplify_tolerance = 0.0)
|
||||
{
|
||||
waypoints.clear();
|
||||
if (path.poses.empty())
|
||||
{
|
||||
if (error) *error = "reference path is empty";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(body_height) || !std::isfinite(min_distance) || min_distance < 0.0 ||
|
||||
!std::isfinite(simplify_tolerance) || simplify_tolerance < 0.0)
|
||||
{
|
||||
if (error)
|
||||
*error = "body height, minimum distance, and simplify tolerance must be finite and non-negative";
|
||||
return false;
|
||||
}
|
||||
|
||||
waypoints.reserve(path.poses.size());
|
||||
Eigen::Vector3d final_waypoint;
|
||||
Eigen::Vector3d last_waypoint;
|
||||
bool first = true;
|
||||
|
||||
for (const auto &pose_stamped : path.poses)
|
||||
{
|
||||
const auto &position = pose_stamped.pose.position;
|
||||
if (!std::isfinite(position.x) || !std::isfinite(position.y) ||
|
||||
!std::isfinite(position.z))
|
||||
{
|
||||
waypoints.clear();
|
||||
if (error) *error = "reference path contains a non-finite coordinate";
|
||||
return false;
|
||||
}
|
||||
|
||||
Eigen::Vector3d waypoint(position.x, position.y, position.z + body_height);
|
||||
final_waypoint = waypoint;
|
||||
if (first || (waypoint - last_waypoint).norm() >= min_distance)
|
||||
{
|
||||
waypoints.push_back(waypoint);
|
||||
last_waypoint = waypoint;
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
|
||||
if ((waypoints.back() - final_waypoint).norm() > 1e-6)
|
||||
waypoints.push_back(final_waypoint);
|
||||
|
||||
if (waypoints.size() < 2)
|
||||
{
|
||||
waypoints.clear();
|
||||
if (error) *error = "reference path requires at least two distinct points";
|
||||
return false;
|
||||
}
|
||||
|
||||
waypoints = simplifyReferenceWaypoints(waypoints, simplify_tolerance);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace scan_planner
|
||||
|
||||
#endif // PLAN_MANAGE_REFERENCE_PATH_UTILS_H
|
||||
@@ -0,0 +1,150 @@
|
||||
#ifndef _SCAN_REPLAN_FSM_H_
|
||||
#define _SCAN_REPLAN_FSM_H_
|
||||
|
||||
#include <Eigen/Eigen>
|
||||
#include <algorithm>
|
||||
#include <geometry_msgs/msg/pose_stamped.hpp>
|
||||
#include <iostream>
|
||||
#include <nav_msgs/msg/odometry.hpp>
|
||||
#include <nav_msgs/msg/path.hpp>
|
||||
#include <rclcpp/rclcpp.hpp>
|
||||
#include <std_msgs/msg/bool.hpp>
|
||||
#include <vector>
|
||||
#include <visualization_msgs/msg/marker.hpp>
|
||||
|
||||
#include <bspline_opt/bspline_optimizer.h>
|
||||
#include <plan_env/grid_map.h>
|
||||
#include <scan_planner_msgs/msg/bspline.hpp>
|
||||
#include <scan_planner_msgs/msg/data_disp.hpp>
|
||||
#include <plan_manage/planner_manager.h>
|
||||
#include <traj_utils/planning_visualization.h>
|
||||
|
||||
using std::vector;
|
||||
|
||||
namespace scan_planner
|
||||
{
|
||||
|
||||
class SCANReplanFSM
|
||||
{
|
||||
|
||||
private:
|
||||
/* ---------- flag ---------- */
|
||||
enum FSM_EXEC_STATE
|
||||
{
|
||||
INIT,
|
||||
WAIT_TARGET,
|
||||
GEN_NEW_TRAJ,
|
||||
REPLAN_TRAJ,
|
||||
EXEC_TRAJ,
|
||||
EMERGENCY_STOP
|
||||
};
|
||||
enum NAVI_MODE
|
||||
{
|
||||
MANUAL_TARGET = 1,
|
||||
PRESET_TARGET = 2,
|
||||
REFERENCE_PATH = 3,
|
||||
};
|
||||
|
||||
/* planning utils */
|
||||
SCANPlannerManager::Ptr planner_manager_;
|
||||
PlanningVisualization::Ptr visualization_;
|
||||
scan_planner_msgs::msg::DataDisp data_disp_;
|
||||
|
||||
/* parameters */
|
||||
int navi_mode_; // 1 manual select, 2 hard code
|
||||
double no_replan_thresh_, replan_thresh_;
|
||||
std::vector<Eigen::Vector3d> preset_waypoints_;
|
||||
int waypoint_num_;
|
||||
double planning_horizon_;
|
||||
double emergency_time_;
|
||||
double rviz_goal_height_;
|
||||
double self_inflation_z_up_, self_inflation_z_down_;
|
||||
double self_double_cylinder_radius_, self_double_cylinder_offset_;
|
||||
double body_height_;
|
||||
double reference_path_min_distance_, reference_path_simplify_tolerance_;
|
||||
std::string self_inflation_frame_id_;
|
||||
|
||||
/* planning data */
|
||||
bool trigger_, have_target_, have_odom_, have_new_target_;
|
||||
bool preset_started_{false};
|
||||
bool rviz_height_ready_;
|
||||
bool go2_execution_frozen_;
|
||||
bool enable_fail_safe_, need_hover_stop_;
|
||||
FSM_EXEC_STATE exec_state_;
|
||||
int continuously_called_times_{0};
|
||||
int replan_fail_count_{0};
|
||||
int max_replan_fail_count_{1000};
|
||||
rclcpp::Time last_freeze_update_time_;
|
||||
|
||||
Eigen::Vector3d odom_pos_, odom_vel_, odom_acc_; // odometry state
|
||||
Eigen::Quaterniond odom_orient_;
|
||||
|
||||
Eigen::Vector3d init_pt_, start_pt_, start_vel_, start_acc_, start_yaw_; // start state
|
||||
Eigen::Vector3d end_pt_, end_vel_; // goal state
|
||||
Eigen::Vector3d local_target_pt_, local_target_vel_; // local target state
|
||||
std::vector<Eigen::Vector3d> active_waypoints_;
|
||||
int current_wp_;
|
||||
|
||||
bool flag_escape_emergency_;
|
||||
|
||||
/* ROS utils */
|
||||
rclcpp::Node *node_{nullptr};
|
||||
rclcpp::TimerBase::SharedPtr exec_timer_, safety_timer_;
|
||||
rclcpp::Subscription<geometry_msgs::msg::PoseStamped>::SharedPtr goal_sub_;
|
||||
rclcpp::Subscription<nav_msgs::msg::Odometry>::SharedPtr odom_sub_;
|
||||
rclcpp::Subscription<nav_msgs::msg::Path>::SharedPtr path_sub_;
|
||||
rclcpp::Subscription<std_msgs::msg::Bool>::SharedPtr go2_execution_frozen_sub_;
|
||||
rclcpp::Publisher<scan_planner_msgs::msg::Bspline>::SharedPtr bspline_pub_;
|
||||
rclcpp::Publisher<scan_planner_msgs::msg::DataDisp>::SharedPtr data_disp_pub_;
|
||||
rclcpp::Publisher<visualization_msgs::msg::Marker>::SharedPtr self_inflation_pub_;
|
||||
|
||||
/* helper functions */
|
||||
bool callReboundReplan(bool flag_use_poly_init, bool flag_randomPolyTraj); // front-end and back-end method
|
||||
bool callEmergencyStop(Eigen::Vector3d stop_pos); // front-end and back-end method
|
||||
bool planFromCurrentTraj();
|
||||
void setStartStateFromOdomOrCurrentTraj();
|
||||
|
||||
/* return value: std::pair< Times of the same state be continuously called, current continuously called state > */
|
||||
void changeFSMExecState(FSM_EXEC_STATE new_state, string pos_call);
|
||||
std::pair<int, SCANReplanFSM::FSM_EXEC_STATE> timesOfConsecutiveStateCalls();
|
||||
void printFSMExecState();
|
||||
|
||||
void planGlobalTrajbyGivenWps();
|
||||
bool planGlobalTrajByWaypoints(const std::vector<Eigen::Vector3d> &waypoints);
|
||||
bool planNextWaypoint();
|
||||
bool isWaypointSequenceMode() const;
|
||||
bool adjustGlobalTargetIfOccupied();
|
||||
void getLocalTarget();
|
||||
void finishProcess();
|
||||
void publishSelfInflationMarker();
|
||||
double getOdomYaw() const;
|
||||
double estimateYawFromSegment(const Eigen::Vector3d &from, const Eigen::Vector3d &to) const;
|
||||
void updateLocalTrajTimeFreeze();
|
||||
|
||||
/* ROS functions */
|
||||
void execFSMCallback();
|
||||
void checkCollisionCallback();
|
||||
void rvizGoalCallback(const geometry_msgs::msg::PoseStamped::ConstSharedPtr &msg);
|
||||
void waypointCallback(const nav_msgs::msg::Path::ConstSharedPtr &msg);
|
||||
void pathCallback(const nav_msgs::msg::Path::ConstSharedPtr &msg);
|
||||
void odometryCallback(const nav_msgs::msg::Odometry::ConstSharedPtr &msg);
|
||||
void go2ExecutionFrozenCallback(const std_msgs::msg::Bool::ConstSharedPtr &msg);
|
||||
|
||||
bool checkCollision();
|
||||
|
||||
public:
|
||||
SCANReplanFSM(/* args */)
|
||||
{
|
||||
}
|
||||
~SCANReplanFSM()
|
||||
{
|
||||
}
|
||||
|
||||
void init(rclcpp::Node *node);
|
||||
|
||||
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
|
||||
};
|
||||
|
||||
} // namespace scan_planner
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,586 @@
|
||||
Panels:
|
||||
- Class: rviz_common/Displays
|
||||
Help Height: 0
|
||||
Name: Displays
|
||||
Property Tree Widget:
|
||||
Expanded:
|
||||
- /PCT Global Path1
|
||||
Splitter Ratio: 0.5
|
||||
Tree Height: 1225
|
||||
- Class: rviz_common/Selection
|
||||
Name: Selection
|
||||
- Class: rviz_common/Tool Properties
|
||||
Expanded: ~
|
||||
Name: Tool Properties
|
||||
Splitter Ratio: 0.5
|
||||
- Class: rviz_common/Views
|
||||
Expanded:
|
||||
- /Current View1
|
||||
Name: Views
|
||||
Splitter Ratio: 0.5
|
||||
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: Ground Grid
|
||||
Normal Cell Count: 0
|
||||
Offset:
|
||||
X: 0
|
||||
Y: 0
|
||||
Z: 0
|
||||
Plane: XY
|
||||
Plane Cell Count: 40
|
||||
Reference Frame: <Fixed Frame>
|
||||
Value: true
|
||||
- Alpha: 1
|
||||
Class: rviz_default_plugins/RobotModel
|
||||
Collision Enabled: false
|
||||
Description File: ""
|
||||
Description Source: Topic
|
||||
Description Topic:
|
||||
Depth: 1
|
||||
Durability Policy: Transient Local
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Reliable
|
||||
Value: /robot_description
|
||||
Enabled: true
|
||||
Links:
|
||||
All Links Enabled: true
|
||||
Expand Joint Details: false
|
||||
Expand Link Details: false
|
||||
Expand Tree: false
|
||||
FL_calf:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FL_calf_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FL_foot:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FL_hip:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FL_hip_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FL_thigh:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FL_thigh_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FR_calf:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FR_calf_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FR_foot:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FR_hip:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FR_hip_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FR_thigh:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FR_thigh_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
Link Tree Style: Links in Alphabetic Order
|
||||
RL_calf:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RL_calf_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RL_foot:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RL_hip:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RL_hip_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RL_thigh:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RL_thigh_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RR_calf:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RR_calf_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RR_foot:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RR_hip:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RR_hip_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RR_thigh:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RR_thigh_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
base:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
front_camera:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
imu_link:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
trunk:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
Mass Properties:
|
||||
Inertia: false
|
||||
Mass: false
|
||||
Name: Go2
|
||||
TF Prefix: ""
|
||||
Update Interval: 0
|
||||
Value: true
|
||||
Visual Enabled: true
|
||||
- Alpha: 1
|
||||
Buffer Length: 1
|
||||
Class: rviz_default_plugins/Path
|
||||
Color: 25; 255; 0
|
||||
Enabled: true
|
||||
Head Diameter: 0.30000001192092896
|
||||
Head Length: 0.20000000298023224
|
||||
Length: 0.30000001192092896
|
||||
Line Style: Lines
|
||||
Line Width: 0.029999999329447746
|
||||
Name: Robot Path
|
||||
Offset:
|
||||
X: 0
|
||||
Y: 0
|
||||
Z: 0
|
||||
Pose Color: 255; 85; 255
|
||||
Pose Style: None
|
||||
Radius: 0.029999999329447746
|
||||
Shaft Diameter: 0.10000000149011612
|
||||
Shaft Length: 0.10000000149011612
|
||||
Topic:
|
||||
Depth: 10
|
||||
Durability Policy: Volatile
|
||||
Filter size: 10
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Reliable
|
||||
Value: /quad_0/path
|
||||
Value: true
|
||||
- Alpha: 1
|
||||
Buffer Length: 1
|
||||
Class: rviz_default_plugins/Path
|
||||
Color: 255; 170; 0
|
||||
Enabled: true
|
||||
Head Diameter: 0.30000001192092896
|
||||
Head Length: 0.20000000298023224
|
||||
Length: 0.30000001192092896
|
||||
Line Style: Billboards
|
||||
Line Width: 0.5
|
||||
Name: PCT Global Path
|
||||
Offset:
|
||||
X: 0
|
||||
Y: 0
|
||||
Z: 0
|
||||
Pose Color: 255; 170; 0
|
||||
Pose Style: None
|
||||
Radius: 0.029999999329447746
|
||||
Shaft Diameter: 0.10000000149011612
|
||||
Shaft Length: 0.10000000149011612
|
||||
Topic:
|
||||
Depth: 1
|
||||
Durability Policy: Transient Local
|
||||
Filter size: 10
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Reliable
|
||||
Value: /pct_path
|
||||
Value: true
|
||||
- Class: rviz_default_plugins/InteractiveMarkers
|
||||
Enable Transparency: true
|
||||
Enabled: true
|
||||
Interactive Markers Namespace: /pct_waypoints
|
||||
Name: PCT Start and Goal
|
||||
Show Axes: true
|
||||
Show Descriptions: true
|
||||
Show Visual Aids: true
|
||||
Value: true
|
||||
- Alpha: 1
|
||||
Autocompute Intensity Bounds: false
|
||||
Autocompute Value Bounds:
|
||||
Max Value: 60
|
||||
Min Value: -20
|
||||
Value: true
|
||||
Axis: Z
|
||||
Channel Name: intensity
|
||||
Class: rviz_default_plugins/PointCloud2
|
||||
Color: 255; 255; 255
|
||||
Color Transformer: Intensity
|
||||
Decay Time: 0
|
||||
Enabled: true
|
||||
Invert Rainbow: true
|
||||
Max Color: 255; 80; 20
|
||||
Max Intensity: 60
|
||||
Min Color: 30; 90; 255
|
||||
Min Intensity: -20
|
||||
Name: PCT Full Cost Tomogram
|
||||
Position Transformer: XYZ
|
||||
Selectable: true
|
||||
Size (Pixels): 4
|
||||
Size (m): 0.10000000149011612
|
||||
Style: Boxes
|
||||
Topic:
|
||||
Depth: 1
|
||||
Durability Policy: Transient Local
|
||||
Filter size: 10
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Reliable
|
||||
Value: /pct_tomogram
|
||||
Use Fixed Frame: true
|
||||
Use rainbow: true
|
||||
Value: true
|
||||
- Alpha: 0.11999999731779099
|
||||
Autocompute Intensity Bounds: true
|
||||
Autocompute Value Bounds:
|
||||
Max Value: 20.178617477416992
|
||||
Min Value: -20.31769561767578
|
||||
Value: true
|
||||
Axis: X
|
||||
Channel Name: intensity
|
||||
Class: rviz_default_plugins/PointCloud2
|
||||
Color: 160; 160; 160
|
||||
Color Transformer: FlatColor
|
||||
Decay Time: 0
|
||||
Enabled: true
|
||||
Invert Rainbow: false
|
||||
Max Color: 255; 255; 255
|
||||
Max Intensity: 4096
|
||||
Min Color: 0; 0; 0
|
||||
Min Intensity: 0
|
||||
Name: Global Map
|
||||
Position Transformer: XYZ
|
||||
Selectable: true
|
||||
Size (Pixels): 1
|
||||
Size (m): 0.019999999552965164
|
||||
Style: Flat Squares
|
||||
Topic:
|
||||
Depth: 1
|
||||
Durability Policy: Transient Local
|
||||
Filter size: 10
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Reliable
|
||||
Value: /map_generator/global_cloud
|
||||
Use Fixed Frame: true
|
||||
Use rainbow: false
|
||||
Value: true
|
||||
- Alpha: 1
|
||||
Autocompute Intensity Bounds: true
|
||||
Autocompute Value Bounds:
|
||||
Max Value: 2.1538519859313965
|
||||
Min Value: -0.15081557631492615
|
||||
Value: true
|
||||
Axis: Z
|
||||
Channel Name: intensity
|
||||
Class: rviz_default_plugins/PointCloud2
|
||||
Color: 255; 255; 255
|
||||
Color Transformer: FlatColor
|
||||
Decay Time: 0
|
||||
Enabled: false
|
||||
Invert Rainbow: false
|
||||
Max Color: 255; 255; 255
|
||||
Max Intensity: 199
|
||||
Min Color: 0; 0; 0
|
||||
Min Intensity: 199
|
||||
Name: Sensor Cloud
|
||||
Position Transformer: XYZ
|
||||
Selectable: true
|
||||
Size (Pixels): 4
|
||||
Size (m): 0.009999999776482582
|
||||
Style: Points
|
||||
Topic:
|
||||
Depth: 5
|
||||
Durability Policy: Volatile
|
||||
Filter size: 10
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Best Effort
|
||||
Value: /quad_0/cloud
|
||||
Use Fixed Frame: true
|
||||
Use rainbow: true
|
||||
Value: false
|
||||
- Alpha: 1
|
||||
Autocompute Intensity Bounds: true
|
||||
Autocompute Value Bounds:
|
||||
Max Value: 3.875
|
||||
Min Value: 1.0750000476837158
|
||||
Value: true
|
||||
Axis: Z
|
||||
Channel Name: intensity
|
||||
Class: rviz_default_plugins/PointCloud2
|
||||
Color: 255; 255; 255
|
||||
Color Transformer: AxisColor
|
||||
Decay Time: 0
|
||||
Enabled: true
|
||||
Invert Rainbow: false
|
||||
Max Color: 255; 255; 255
|
||||
Max Intensity: 4096
|
||||
Min Color: 0; 0; 0
|
||||
Min Intensity: 0
|
||||
Name: Occupancy
|
||||
Position Transformer: XYZ
|
||||
Selectable: true
|
||||
Size (Pixels): 3
|
||||
Size (m): 0.05000000074505806
|
||||
Style: Squares
|
||||
Topic:
|
||||
Depth: 5
|
||||
Durability Policy: Volatile
|
||||
Filter size: 10
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Best Effort
|
||||
Value: /grid_map/occupancy
|
||||
Use Fixed Frame: true
|
||||
Use rainbow: true
|
||||
Value: true
|
||||
- Alpha: 1
|
||||
Autocompute Intensity Bounds: true
|
||||
Autocompute Value Bounds:
|
||||
Max Value: 0.574999988079071
|
||||
Min Value: -0.5249999761581421
|
||||
Value: true
|
||||
Axis: Z
|
||||
Channel Name: intensity
|
||||
Class: rviz_default_plugins/PointCloud2
|
||||
Color: 255; 255; 255
|
||||
Color Transformer: AxisColor
|
||||
Decay Time: 0
|
||||
Enabled: false
|
||||
Invert Rainbow: false
|
||||
Max Color: 255; 255; 255
|
||||
Max Intensity: 4096
|
||||
Min Color: 0; 0; 0
|
||||
Min Intensity: 0
|
||||
Name: Inflated Occupancy
|
||||
Position Transformer: XYZ
|
||||
Selectable: true
|
||||
Size (Pixels): 3
|
||||
Size (m): 0.03999999910593033
|
||||
Style: Squares
|
||||
Topic:
|
||||
Depth: 5
|
||||
Durability Policy: Volatile
|
||||
Filter size: 10
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Best Effort
|
||||
Value: /grid_map/occupancy_inflate
|
||||
Use Fixed Frame: true
|
||||
Use rainbow: true
|
||||
Value: false
|
||||
- Class: rviz_default_plugins/Marker
|
||||
Enabled: false
|
||||
Name: Sliding Map Bounds
|
||||
Namespaces:
|
||||
{}
|
||||
Topic:
|
||||
Depth: 5
|
||||
Durability Policy: Volatile
|
||||
Filter size: 10
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Reliable
|
||||
Value: /grid_map/sliding_map_bbox
|
||||
Value: false
|
||||
- Class: rviz_default_plugins/Marker
|
||||
Enabled: true
|
||||
Name: Goal
|
||||
Namespaces:
|
||||
"": true
|
||||
Topic:
|
||||
Depth: 5
|
||||
Durability Policy: Volatile
|
||||
Filter size: 10
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Reliable
|
||||
Value: /goal_point
|
||||
Value: true
|
||||
- Class: rviz_default_plugins/TF
|
||||
Enabled: false
|
||||
Frame Timeout: 15
|
||||
Frames:
|
||||
All Enabled: true
|
||||
Marker Scale: 1
|
||||
Name: TF
|
||||
Show Arrows: true
|
||||
Show Axes: true
|
||||
Show Names: false
|
||||
Tree:
|
||||
{}
|
||||
Update Interval: 0
|
||||
Value: false
|
||||
- Class: rviz_default_plugins/Marker
|
||||
Enabled: true
|
||||
Name: Marker
|
||||
Namespaces:
|
||||
"": true
|
||||
Topic:
|
||||
Depth: 5
|
||||
Durability Policy: Volatile
|
||||
Filter size: 10
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Reliable
|
||||
Value: /optimal_list
|
||||
Value: true
|
||||
Enabled: true
|
||||
Global Options:
|
||||
Background Color: 48; 48; 48
|
||||
Fixed Frame: world
|
||||
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/SetGoal
|
||||
Topic:
|
||||
Depth: 5
|
||||
Durability Policy: Volatile
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Reliable
|
||||
Value: /move_base_simple/goal
|
||||
- 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: 28
|
||||
Enable Stereo Rendering:
|
||||
Stereo Eye Separation: 0.05999999865889549
|
||||
Stereo Focal Distance: 1
|
||||
Swap Stereo Eyes: false
|
||||
Value: false
|
||||
Focal Point:
|
||||
X: 0
|
||||
Y: 1.5
|
||||
Z: 6.5
|
||||
Focal Shape Fixed Size: true
|
||||
Focal Shape Size: 0.05000000074505806
|
||||
Invert Z Axis: false
|
||||
Name: Current View
|
||||
Near Clip Distance: 0.009999999776482582
|
||||
Pitch: 0.38000059127807617
|
||||
Target Frame: <Fixed Frame>
|
||||
Value: Orbit (rviz_default_plugins)
|
||||
Yaw: 1.824995994567871
|
||||
Saved: ~
|
||||
Window Geometry:
|
||||
Displays:
|
||||
collapsed: false
|
||||
Height: 1376
|
||||
Hide Left Dock: false
|
||||
Hide Right Dock: false
|
||||
QMainWindow State: 000000ff00000000fd00000001000000000000032f00000506fc0200000004fb000000100044006900730070006c006100790073010000003d00000506000000c900fffffffb0000001200530065006c0065006300740069006f006e000000031d000001350000005c00fffffffb0000001e0054006f006f006c002000500072006f007000650072007400690065007300000003f9000001990000005c00fffffffb0000000a00560069006500770073000000041b00000177000000a400ffffff000006cb0000050600000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000
|
||||
Selection:
|
||||
collapsed: false
|
||||
Tool Properties:
|
||||
collapsed: false
|
||||
Views:
|
||||
collapsed: false
|
||||
Width: 2560
|
||||
X: 0
|
||||
Y: 27
|
||||
@@ -0,0 +1,709 @@
|
||||
Panels:
|
||||
- Class: rviz_common/Displays
|
||||
Help Height: 0
|
||||
Name: Displays
|
||||
Property Tree Widget:
|
||||
Expanded: ~
|
||||
Splitter Ratio: 0.5
|
||||
Tree Height: 1206
|
||||
- Class: rviz_common/Selection
|
||||
Name: Selection
|
||||
- Class: rviz_common/Tool Properties
|
||||
Expanded: ~
|
||||
Name: Tool Properties
|
||||
Splitter Ratio: 0.5
|
||||
- Class: rviz_common/Views
|
||||
Expanded:
|
||||
- /Current View1
|
||||
Name: Views
|
||||
Splitter Ratio: 0.5
|
||||
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: Ground Grid
|
||||
Normal Cell Count: 0
|
||||
Offset:
|
||||
X: 0
|
||||
Y: 0
|
||||
Z: 0
|
||||
Plane: XY
|
||||
Plane Cell Count: 60
|
||||
Reference Frame: <Fixed Frame>
|
||||
Value: true
|
||||
- Alpha: 1
|
||||
Class: rviz_default_plugins/RobotModel
|
||||
Collision Enabled: false
|
||||
Description File: ""
|
||||
Description Source: Topic
|
||||
Description Topic:
|
||||
Depth: 1
|
||||
Durability Policy: Transient Local
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Reliable
|
||||
Value: /robot_description
|
||||
Enabled: true
|
||||
Links:
|
||||
All Links Enabled: true
|
||||
Expand Joint Details: false
|
||||
Expand Link Details: false
|
||||
Expand Tree: false
|
||||
FL_calf:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FL_calf_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FL_foot:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FL_hip:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FL_hip_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FL_thigh:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FL_thigh_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FR_calf:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FR_calf_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FR_foot:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FR_hip:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FR_hip_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FR_thigh:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
FR_thigh_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
Link Tree Style: Links in Alphabetic Order
|
||||
RL_calf:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RL_calf_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RL_foot:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RL_hip:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RL_hip_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RL_thigh:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RL_thigh_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RR_calf:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RR_calf_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RR_foot:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RR_hip:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RR_hip_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RR_thigh:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
RR_thigh_rotor:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
base:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
front_camera:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
imu_link:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
trunk:
|
||||
Alpha: 1
|
||||
Show Axes: false
|
||||
Show Trail: false
|
||||
Value: true
|
||||
Mass Properties:
|
||||
Inertia: false
|
||||
Mass: false
|
||||
Name: Go2
|
||||
TF Prefix: ""
|
||||
Update Interval: 0
|
||||
Value: true
|
||||
Visual Enabled: true
|
||||
- Alpha: 1
|
||||
Buffer Length: 1
|
||||
Class: rviz_default_plugins/Path
|
||||
Color: 25; 255; 0
|
||||
Enabled: true
|
||||
Head Diameter: 0.30000001192092896
|
||||
Head Length: 0.20000000298023224
|
||||
Length: 0.30000001192092896
|
||||
Line Style: Lines
|
||||
Line Width: 0.029999999329447746
|
||||
Name: Robot Path
|
||||
Offset:
|
||||
X: 0
|
||||
Y: 0
|
||||
Z: 0
|
||||
Pose Color: 255; 85; 255
|
||||
Pose Style: None
|
||||
Radius: 0.029999999329447746
|
||||
Shaft Diameter: 0.10000000149011612
|
||||
Shaft Length: 0.10000000149011612
|
||||
Topic:
|
||||
Depth: 10
|
||||
Durability Policy: Volatile
|
||||
Filter size: 10
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Reliable
|
||||
Value: /quad_0/path
|
||||
Value: true
|
||||
- Alpha: 1
|
||||
Buffer Length: 1
|
||||
Class: rviz_default_plugins/Path
|
||||
Color: 255; 170; 0
|
||||
Enabled: true
|
||||
Head Diameter: 0.30000001192092896
|
||||
Head Length: 0.20000000298023224
|
||||
Length: 0.30000001192092896
|
||||
Line Style: Billboards
|
||||
Line Width: 0.10000000149011612
|
||||
Name: PCT Global Path
|
||||
Offset:
|
||||
X: 0
|
||||
Y: 0
|
||||
Z: 0
|
||||
Pose Color: 255; 170; 0
|
||||
Pose Style: None
|
||||
Radius: 0.029999999329447746
|
||||
Shaft Diameter: 0.10000000149011612
|
||||
Shaft Length: 0.10000000149011612
|
||||
Topic:
|
||||
Depth: 1
|
||||
Durability Policy: Transient Local
|
||||
Filter size: 10
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Reliable
|
||||
Value: /pct_path
|
||||
Value: true
|
||||
- Class: rviz_default_plugins/InteractiveMarkers
|
||||
Enable Transparency: true
|
||||
Enabled: true
|
||||
Interactive Markers Namespace: /pct_waypoints
|
||||
Name: PCT Start and Goal
|
||||
Show Axes: true
|
||||
Show Descriptions: true
|
||||
Show Visual Aids: true
|
||||
Value: true
|
||||
- Alpha: 0.8999999761581421
|
||||
Autocompute Intensity Bounds: false
|
||||
Autocompute Value Bounds:
|
||||
Max Value: 20
|
||||
Min Value: 0
|
||||
Value: true
|
||||
Axis: Z
|
||||
Channel Name: intensity
|
||||
Class: rviz_default_plugins/PointCloud2
|
||||
Color: 255; 255; 255
|
||||
Color Transformer: Intensity
|
||||
Decay Time: 0
|
||||
Enabled: true
|
||||
Invert Rainbow: true
|
||||
Max Color: 255; 80; 20
|
||||
Max Intensity: 20
|
||||
Min Color: 30; 90; 255
|
||||
Min Intensity: 0
|
||||
Name: PCT Traversable Tomogram
|
||||
Position Transformer: XYZ
|
||||
Selectable: true
|
||||
Size (Pixels): 4
|
||||
Size (m): 0.18000000715255737
|
||||
Style: Boxes
|
||||
Topic:
|
||||
Depth: 1
|
||||
Durability Policy: Transient Local
|
||||
Filter size: 10
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Reliable
|
||||
Value: /pct_tomogram
|
||||
Use Fixed Frame: true
|
||||
Use rainbow: true
|
||||
Value: true
|
||||
- Alpha: 0.18000000715255737
|
||||
Autocompute Intensity Bounds: true
|
||||
Autocompute Value Bounds:
|
||||
Max Value: 20.178617477416992
|
||||
Min Value: -20.31769561767578
|
||||
Value: true
|
||||
Axis: X
|
||||
Channel Name: intensity
|
||||
Class: rviz_default_plugins/PointCloud2
|
||||
Color: 160; 160; 160
|
||||
Color Transformer: FlatColor
|
||||
Decay Time: 0
|
||||
Enabled: true
|
||||
Invert Rainbow: false
|
||||
Max Color: 255; 255; 255
|
||||
Max Intensity: 4096
|
||||
Min Color: 0; 0; 0
|
||||
Min Intensity: 0
|
||||
Name: Global Map
|
||||
Position Transformer: XYZ
|
||||
Selectable: true
|
||||
Size (Pixels): 1
|
||||
Size (m): 0.012000000104308128
|
||||
Style: Flat Squares
|
||||
Topic:
|
||||
Depth: 1
|
||||
Durability Policy: Transient Local
|
||||
Filter size: 10
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Reliable
|
||||
Value: /map_generator/global_cloud
|
||||
Use Fixed Frame: true
|
||||
Use rainbow: false
|
||||
Value: true
|
||||
- Alpha: 1
|
||||
Autocompute Intensity Bounds: true
|
||||
Autocompute Value Bounds:
|
||||
Max Value: 2.1538519859313965
|
||||
Min Value: -0.15081557631492615
|
||||
Value: true
|
||||
Axis: Z
|
||||
Channel Name: intensity
|
||||
Class: rviz_default_plugins/PointCloud2
|
||||
Color: 255; 255; 255
|
||||
Color Transformer: FlatColor
|
||||
Decay Time: 0
|
||||
Enabled: false
|
||||
Invert Rainbow: false
|
||||
Max Color: 255; 255; 255
|
||||
Max Intensity: 199
|
||||
Min Color: 0; 0; 0
|
||||
Min Intensity: 199
|
||||
Name: Sensor Cloud
|
||||
Position Transformer: XYZ
|
||||
Selectable: true
|
||||
Size (Pixels): 4
|
||||
Size (m): 0.009999999776482582
|
||||
Style: Points
|
||||
Topic:
|
||||
Depth: 5
|
||||
Durability Policy: Volatile
|
||||
Filter size: 10
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Best Effort
|
||||
Value: /quad_0/cloud
|
||||
Use Fixed Frame: true
|
||||
Use rainbow: true
|
||||
Value: false
|
||||
- Alpha: 1
|
||||
Autocompute Intensity Bounds: true
|
||||
Autocompute Value Bounds:
|
||||
Max Value: 0.574999988079071
|
||||
Min Value: -0.125
|
||||
Value: true
|
||||
Axis: Z
|
||||
Channel Name: intensity
|
||||
Class: rviz_default_plugins/PointCloud2
|
||||
Color: 255; 255; 255
|
||||
Color Transformer: AxisColor
|
||||
Decay Time: 0
|
||||
Enabled: false
|
||||
Invert Rainbow: false
|
||||
Max Color: 255; 255; 255
|
||||
Max Intensity: 4096
|
||||
Min Color: 0; 0; 0
|
||||
Min Intensity: 0
|
||||
Name: Occupancy
|
||||
Position Transformer: XYZ
|
||||
Selectable: true
|
||||
Size (Pixels): 3
|
||||
Size (m): 0.05000000074505806
|
||||
Style: Squares
|
||||
Topic:
|
||||
Depth: 5
|
||||
Durability Policy: Volatile
|
||||
Filter size: 10
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Best Effort
|
||||
Value: /grid_map/occupancy
|
||||
Use Fixed Frame: true
|
||||
Use rainbow: true
|
||||
Value: false
|
||||
- Alpha: 1
|
||||
Autocompute Intensity Bounds: true
|
||||
Autocompute Value Bounds:
|
||||
Max Value: 0.574999988079071
|
||||
Min Value: -0.5249999761581421
|
||||
Value: true
|
||||
Axis: Z
|
||||
Channel Name: intensity
|
||||
Class: rviz_default_plugins/PointCloud2
|
||||
Color: 255; 255; 255
|
||||
Color Transformer: AxisColor
|
||||
Decay Time: 0
|
||||
Enabled: false
|
||||
Invert Rainbow: false
|
||||
Max Color: 255; 255; 255
|
||||
Max Intensity: 4096
|
||||
Min Color: 0; 0; 0
|
||||
Min Intensity: 0
|
||||
Name: Inflated Occupancy
|
||||
Position Transformer: XYZ
|
||||
Selectable: true
|
||||
Size (Pixels): 3
|
||||
Size (m): 0.03999999910593033
|
||||
Style: Squares
|
||||
Topic:
|
||||
Depth: 5
|
||||
Durability Policy: Volatile
|
||||
Filter size: 10
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Best Effort
|
||||
Value: /grid_map/occupancy_inflate
|
||||
Use Fixed Frame: true
|
||||
Use rainbow: true
|
||||
Value: false
|
||||
- Class: rviz_default_plugins/Marker
|
||||
Enabled: false
|
||||
Name: Sliding Map Bounds
|
||||
Namespaces:
|
||||
sliding_map: true
|
||||
Topic:
|
||||
Depth: 5
|
||||
Durability Policy: Volatile
|
||||
Filter size: 10
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Reliable
|
||||
Value: /grid_map/sliding_map_bbox
|
||||
Value: false
|
||||
- Class: rviz_default_plugins/Marker
|
||||
Enabled: true
|
||||
Name: Goal
|
||||
Namespaces:
|
||||
"": true
|
||||
Topic:
|
||||
Depth: 5
|
||||
Durability Policy: Volatile
|
||||
Filter size: 10
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Reliable
|
||||
Value: /goal_point
|
||||
Value: true
|
||||
- Class: rviz_default_plugins/TF
|
||||
Enabled: false
|
||||
Frame Timeout: 15
|
||||
Frames:
|
||||
All Enabled: true
|
||||
FL_calf:
|
||||
Value: true
|
||||
FL_calf_rotor:
|
||||
Value: true
|
||||
FL_foot:
|
||||
Value: true
|
||||
FL_hip:
|
||||
Value: true
|
||||
FL_hip_rotor:
|
||||
Value: true
|
||||
FL_thigh:
|
||||
Value: true
|
||||
FL_thigh_rotor:
|
||||
Value: true
|
||||
FR_calf:
|
||||
Value: true
|
||||
FR_calf_rotor:
|
||||
Value: true
|
||||
FR_foot:
|
||||
Value: true
|
||||
FR_hip:
|
||||
Value: true
|
||||
FR_hip_rotor:
|
||||
Value: true
|
||||
FR_thigh:
|
||||
Value: true
|
||||
FR_thigh_rotor:
|
||||
Value: true
|
||||
RL_calf:
|
||||
Value: true
|
||||
RL_calf_rotor:
|
||||
Value: true
|
||||
RL_foot:
|
||||
Value: true
|
||||
RL_hip:
|
||||
Value: true
|
||||
RL_hip_rotor:
|
||||
Value: true
|
||||
RL_thigh:
|
||||
Value: true
|
||||
RL_thigh_rotor:
|
||||
Value: true
|
||||
RR_calf:
|
||||
Value: true
|
||||
RR_calf_rotor:
|
||||
Value: true
|
||||
RR_foot:
|
||||
Value: true
|
||||
RR_hip:
|
||||
Value: true
|
||||
RR_hip_rotor:
|
||||
Value: true
|
||||
RR_thigh:
|
||||
Value: true
|
||||
RR_thigh_rotor:
|
||||
Value: true
|
||||
base:
|
||||
Value: true
|
||||
front_camera:
|
||||
Value: true
|
||||
imu_link:
|
||||
Value: true
|
||||
sensor:
|
||||
Value: true
|
||||
sliding_map:
|
||||
Value: true
|
||||
trunk:
|
||||
Value: true
|
||||
world:
|
||||
Value: true
|
||||
Marker Scale: 1
|
||||
Name: TF
|
||||
Show Arrows: true
|
||||
Show Axes: true
|
||||
Show Names: false
|
||||
Tree:
|
||||
world:
|
||||
base:
|
||||
trunk:
|
||||
FL_hip:
|
||||
FL_thigh:
|
||||
FL_calf:
|
||||
FL_foot:
|
||||
{}
|
||||
FL_calf_rotor:
|
||||
{}
|
||||
FL_thigh_rotor:
|
||||
{}
|
||||
FL_hip_rotor:
|
||||
{}
|
||||
FR_hip:
|
||||
FR_thigh:
|
||||
FR_calf:
|
||||
FR_foot:
|
||||
{}
|
||||
FR_calf_rotor:
|
||||
{}
|
||||
FR_thigh_rotor:
|
||||
{}
|
||||
FR_hip_rotor:
|
||||
{}
|
||||
RL_hip:
|
||||
RL_thigh:
|
||||
RL_calf:
|
||||
RL_foot:
|
||||
{}
|
||||
RL_calf_rotor:
|
||||
{}
|
||||
RL_thigh_rotor:
|
||||
{}
|
||||
RL_hip_rotor:
|
||||
{}
|
||||
RR_hip:
|
||||
RR_thigh:
|
||||
RR_calf:
|
||||
RR_foot:
|
||||
{}
|
||||
RR_calf_rotor:
|
||||
{}
|
||||
RR_thigh_rotor:
|
||||
{}
|
||||
RR_hip_rotor:
|
||||
{}
|
||||
front_camera:
|
||||
{}
|
||||
imu_link:
|
||||
{}
|
||||
sensor:
|
||||
{}
|
||||
sliding_map:
|
||||
{}
|
||||
Update Interval: 0
|
||||
Value: false
|
||||
- Class: rviz_default_plugins/Marker
|
||||
Enabled: true
|
||||
Name: Marker
|
||||
Namespaces:
|
||||
"": true
|
||||
Topic:
|
||||
Depth: 5
|
||||
Durability Policy: Volatile
|
||||
Filter size: 10
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Reliable
|
||||
Value: /optimal_list
|
||||
Value: true
|
||||
Enabled: true
|
||||
Global Options:
|
||||
Background Color: 48; 48; 48
|
||||
Fixed Frame: world
|
||||
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/SetGoal
|
||||
Topic:
|
||||
Depth: 5
|
||||
Durability Policy: Volatile
|
||||
History Policy: Keep Last
|
||||
Reliability Policy: Reliable
|
||||
Value: /move_base_simple/goal
|
||||
- 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: 31.07322120666504
|
||||
Enable Stereo Rendering:
|
||||
Stereo Eye Separation: 0.05999999865889549
|
||||
Stereo Focal Distance: 1
|
||||
Swap Stereo Eyes: false
|
||||
Value: false
|
||||
Focal Point:
|
||||
X: -4.47959041595459
|
||||
Y: 1.29607355594635
|
||||
Z: -8.791008949279785
|
||||
Focal Shape Fixed Size: true
|
||||
Focal Shape Size: 0.05000000074505806
|
||||
Invert Z Axis: false
|
||||
Name: Current View
|
||||
Near Clip Distance: 0.009999999776482582
|
||||
Pitch: 1.0549992322921753
|
||||
Target Frame: <Fixed Frame>
|
||||
Value: Orbit (rviz_default_plugins)
|
||||
Yaw: 2.970010995864868
|
||||
Saved: ~
|
||||
Window Geometry:
|
||||
Displays:
|
||||
collapsed: false
|
||||
Height: 1472
|
||||
Hide Left Dock: false
|
||||
Hide Right Dock: false
|
||||
QMainWindow State: 000000ff00000000fd00000001000000000000032f00000524fc0200000004fb000000100044006900730070006c006100790073010000006e000005240000018200fffffffb0000001200530065006c0065006300740069006f006e000000031d00000135000000b000fffffffb0000001e0054006f006f006c002000500072006f007000650072007400690065007300000003f900000199000000b000fffffffb0000000a00560069006500770073000000041b000001770000013200ffffff000006410000052400000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000
|
||||
Selection:
|
||||
collapsed: false
|
||||
Tool Properties:
|
||||
collapsed: false
|
||||
Views:
|
||||
collapsed: false
|
||||
Width: 2428
|
||||
X: 132
|
||||
Y: 54
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Phase 1: interactive PCT global path feeding SCAN's closed-loop stack."""
|
||||
|
||||
import os
|
||||
|
||||
from ament_index_python.packages import get_package_share_directory
|
||||
from launch import LaunchDescription
|
||||
from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription, OpaqueFunction
|
||||
from launch.launch_description_sources import PythonLaunchDescriptionSource
|
||||
from launch.substitutions import LaunchConfiguration
|
||||
from launch_ros.actions import Node
|
||||
|
||||
|
||||
def _as_bool(value):
|
||||
return value.lower() in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
def _setup(context):
|
||||
asset_root = LaunchConfiguration("asset_root").perform(context)
|
||||
tomogram_path = LaunchConfiguration("tomogram_path").perform(context)
|
||||
pcd_map_file = LaunchConfiguration("pcd_map_file").perform(context)
|
||||
|
||||
if not tomogram_path:
|
||||
tomogram_path = os.path.join(
|
||||
asset_root, "source", "scene", "multifloor", "mutifloor_upstream.pickle"
|
||||
)
|
||||
if not pcd_map_file:
|
||||
pcd_map_file = os.path.join(
|
||||
asset_root, "source", "scene", "multifloor", "pcd", "collision_map.pcd"
|
||||
)
|
||||
|
||||
for description, path in (
|
||||
("PCT tomogram", tomogram_path),
|
||||
("SCAN collision PCD", pcd_map_file),
|
||||
):
|
||||
if not os.path.isfile(path):
|
||||
raise RuntimeError(f"{description} does not exist: {path}")
|
||||
|
||||
pct_share = get_package_share_directory("pct_planner")
|
||||
scan_share = get_package_share_directory("scan_planner")
|
||||
|
||||
actions = [
|
||||
IncludeLaunchDescription(
|
||||
PythonLaunchDescriptionSource(
|
||||
os.path.join(pct_share, "launch", "planner.launch.py")
|
||||
),
|
||||
launch_arguments={
|
||||
"scene_name": "Multifloor",
|
||||
"tomogram_path": tomogram_path,
|
||||
"frame_id": "world",
|
||||
"coord_mode": "sim_to_pct_180deg",
|
||||
"path_topic": "/pct_path",
|
||||
"restrict_endpoints_to_main_components": "true",
|
||||
"endpoint_height_tolerance": "0.4",
|
||||
"plan_on_startup": LaunchConfiguration("plan_on_startup"),
|
||||
"plan_on_marker_release": "false",
|
||||
}.items(),
|
||||
),
|
||||
IncludeLaunchDescription(
|
||||
PythonLaunchDescriptionSource(
|
||||
os.path.join(scan_share, "launch", "run.launch.py")
|
||||
),
|
||||
launch_arguments={
|
||||
"is_real_world": "false",
|
||||
"navi_mode": "3",
|
||||
"sensor_type": "lidar",
|
||||
"controller_mode": "closed_loop",
|
||||
"initial_path_topic": "/pct_path",
|
||||
"use_gpu": LaunchConfiguration("use_gpu"),
|
||||
"use_pcd_map": "true",
|
||||
"pcd_map_file": pcd_map_file,
|
||||
"map_size_x": "50.0",
|
||||
"map_size_y": "50.0",
|
||||
"map_size_z": "10.0",
|
||||
# PCT path z is ground height. SCAN adds its configured 0.4 m
|
||||
# body height once, so the kinematic base starts at z=0.227271.
|
||||
"init_x": "-3.503225",
|
||||
"init_y": "6.663706",
|
||||
"init_z": "0.227271",
|
||||
"use_sim_time": "false",
|
||||
}.items(),
|
||||
),
|
||||
]
|
||||
|
||||
if _as_bool(LaunchConfiguration("use_rviz").perform(context)):
|
||||
actions.append(
|
||||
Node(
|
||||
package="rviz2",
|
||||
executable="rviz2",
|
||||
name="rviz2",
|
||||
output="screen",
|
||||
arguments=["-d", os.path.join(scan_share, "rviz", "default.rviz")],
|
||||
parameters=[{"use_sim_time": False}],
|
||||
)
|
||||
)
|
||||
|
||||
return actions
|
||||
|
||||
|
||||
def generate_launch_description():
|
||||
default_asset_root = os.environ.get("PCT_SCAN_ASSET_ROOT", "")
|
||||
return LaunchDescription(
|
||||
[
|
||||
DeclareLaunchArgument(
|
||||
"asset_root",
|
||||
default_value=default_asset_root,
|
||||
description="Root of the repository that owns the multifloor assets",
|
||||
),
|
||||
DeclareLaunchArgument(
|
||||
"tomogram_path",
|
||||
default_value="",
|
||||
description="Override path to mutifloor_upstream.pickle",
|
||||
),
|
||||
DeclareLaunchArgument(
|
||||
"pcd_map_file",
|
||||
default_value="",
|
||||
description="Override path to collision_map.pcd",
|
||||
),
|
||||
DeclareLaunchArgument("use_gpu", default_value="false"),
|
||||
DeclareLaunchArgument("use_rviz", default_value="true"),
|
||||
DeclareLaunchArgument(
|
||||
"plan_on_startup",
|
||||
default_value="false",
|
||||
description="Plan the default route automatically for headless smoke tests",
|
||||
),
|
||||
OpaqueFunction(function=_setup),
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,306 @@
|
||||
"""Main ROS 2 launch entry point for simulation and real-robot remapping."""
|
||||
|
||||
import os
|
||||
|
||||
from ament_index_python.packages import get_package_share_directory
|
||||
from launch import LaunchDescription
|
||||
from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription, OpaqueFunction
|
||||
from launch.launch_description_sources import PythonLaunchDescriptionSource
|
||||
from launch.substitutions import Command, LaunchConfiguration
|
||||
from launch_ros.actions import Node
|
||||
|
||||
|
||||
def _as_bool(value):
|
||||
return value.lower() in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
def _setup(context):
|
||||
scan_share = get_package_share_directory("scan_planner")
|
||||
go2_share = get_package_share_directory("go2_description")
|
||||
planner_yaml = os.path.join(scan_share, "config", "planner.yaml")
|
||||
controllers_yaml = os.path.join(scan_share, "config", "controllers.yaml")
|
||||
is_real = _as_bool(LaunchConfiguration("is_real_world").perform(context))
|
||||
use_sim_time = _as_bool(LaunchConfiguration("use_sim_time").perform(context))
|
||||
enable_local_sensing = _as_bool(
|
||||
LaunchConfiguration("enable_local_sensing").perform(context)
|
||||
)
|
||||
sensor_type = LaunchConfiguration("sensor_type").perform(context)
|
||||
controller_mode = LaunchConfiguration("controller_mode").perform(context)
|
||||
keypoints_file = LaunchConfiguration("keypoints_file").perform(context)
|
||||
reference_path_file = LaunchConfiguration("reference_path_file").perform(context)
|
||||
initial_path_topic = LaunchConfiguration("initial_path_topic").perform(context)
|
||||
reference_path_min_distance = float(
|
||||
LaunchConfiguration("reference_path_min_distance").perform(context)
|
||||
)
|
||||
reference_path_simplify_tolerance = float(
|
||||
LaunchConfiguration("reference_path_simplify_tolerance").perform(context)
|
||||
)
|
||||
planning_horizon = float(LaunchConfiguration("planning_horizon").perform(context))
|
||||
max_vel_text = LaunchConfiguration("max_vel").perform(context)
|
||||
max_acc_text = LaunchConfiguration("max_acc").perform(context)
|
||||
collision_radius_text = LaunchConfiguration("collision_radius").perform(context)
|
||||
collision_offset_text = LaunchConfiguration("collision_offset").perform(context)
|
||||
inflation_z_up_text = LaunchConfiguration("inflation_z_up").perform(context)
|
||||
inflation_z_down_text = LaunchConfiguration("inflation_z_down").perform(context)
|
||||
navi_mode = int(LaunchConfiguration("navi_mode").perform(context))
|
||||
if sensor_type not in ("lidar", "depth"):
|
||||
raise RuntimeError("sensor_type must be 'lidar' or 'depth'")
|
||||
if controller_mode not in ("open_loop", "closed_loop"):
|
||||
raise RuntimeError("controller_mode must be 'open_loop' or 'closed_loop'")
|
||||
if navi_mode not in (1, 2, 3):
|
||||
raise RuntimeError("navi_mode must be 1, 2, or 3")
|
||||
if navi_mode == 2 and (not keypoints_file or not os.path.isfile(keypoints_file)):
|
||||
raise RuntimeError(
|
||||
"navi_mode=2 requires keypoints_file to reference a ROS 2 parameter YAML"
|
||||
)
|
||||
if reference_path_file and navi_mode != 3:
|
||||
raise RuntimeError("reference_path_file is only valid when navi_mode=3")
|
||||
if reference_path_file and not os.path.isfile(reference_path_file):
|
||||
raise RuntimeError(
|
||||
"reference_path_file must reference an existing ROS 2 parameter YAML"
|
||||
)
|
||||
|
||||
mode_default_init = (-19.0, 1.0, 0.25) if navi_mode == 1 else (-5.5, 5.5, 0.5)
|
||||
initial_position = []
|
||||
for name, default in zip(("init_x", "init_y", "init_z"), mode_default_init):
|
||||
value = LaunchConfiguration(name).perform(context)
|
||||
initial_position.append(default if value == "" else float(value))
|
||||
init_x, init_y, init_z = initial_position
|
||||
|
||||
if is_real:
|
||||
body_pose = "/LIO/odom_vehicle"
|
||||
sensor_pose = "/LIO/odom_imu"
|
||||
cloud = "/LIO/clouds_lidar"
|
||||
depth = "/camera/aligned_depth_to_color/image_raw"
|
||||
cloud_is_world = False
|
||||
need_extrinsic = True
|
||||
intrinsics = {
|
||||
"grid_map.cx": 317.19183349609375,
|
||||
"grid_map.cy": 256.4806823730469,
|
||||
"grid_map.fx": 609.5884399414062,
|
||||
"grid_map.fy": 609.22021484375,
|
||||
}
|
||||
else:
|
||||
body_pose = "/quad_0/body_pose"
|
||||
sensor_pose = "/quad_0/camera_pose" if sensor_type == "depth" else "/quad_0/lidar_pose"
|
||||
if not enable_local_sensing:
|
||||
# Keep the sliding collision-map window centered even when the
|
||||
# video-only demo intentionally omits the simulated sensor node.
|
||||
sensor_pose = body_pose
|
||||
cloud = "/quad_0/cloud"
|
||||
depth = "/quad_0/depth"
|
||||
cloud_is_world = True
|
||||
need_extrinsic = False
|
||||
intrinsics = {}
|
||||
|
||||
common = {"use_sim_time": use_sim_time}
|
||||
planner_overrides = {
|
||||
**common,
|
||||
**intrinsics,
|
||||
"fsm.navi_mode": navi_mode,
|
||||
"fsm.reference_path_min_distance": reference_path_min_distance,
|
||||
"fsm.reference_path_simplify_tolerance": reference_path_simplify_tolerance,
|
||||
"fsm.planning_horizon": planning_horizon,
|
||||
"manager.planning_horizon": planning_horizon,
|
||||
"grid_map.sensor_type": sensor_type,
|
||||
"grid_map.cloud_is_world": cloud_is_world,
|
||||
"grid_map.need_extrinsic": need_extrinsic,
|
||||
}
|
||||
if max_vel_text:
|
||||
max_vel = float(max_vel_text)
|
||||
if max_vel <= 0.0:
|
||||
raise RuntimeError("max_vel must be positive")
|
||||
planner_overrides["manager.max_vel"] = max_vel
|
||||
planner_overrides["optimization.max_vel"] = max_vel
|
||||
if max_acc_text:
|
||||
max_acc = float(max_acc_text)
|
||||
if max_acc <= 0.0:
|
||||
raise RuntimeError("max_acc must be positive")
|
||||
planner_overrides["manager.max_acc"] = max_acc
|
||||
planner_overrides["optimization.max_acc"] = max_acc
|
||||
for text, parameter in (
|
||||
(collision_radius_text, "grid_map.double_cylinder_radius"),
|
||||
(collision_offset_text, "grid_map.double_cylinder_offset"),
|
||||
(inflation_z_up_text, "grid_map.obstacles_inflation_z_up"),
|
||||
(inflation_z_down_text, "grid_map.obstacles_inflation_z_down"),
|
||||
):
|
||||
if text:
|
||||
value = float(text)
|
||||
if value < 0.0:
|
||||
raise RuntimeError(f"{parameter} must be non-negative")
|
||||
planner_overrides[parameter] = value
|
||||
actions = [
|
||||
Node(
|
||||
package="scan_planner",
|
||||
executable="scan_planner_node",
|
||||
name="scan_planner_node",
|
||||
output="screen",
|
||||
parameters=[planner_yaml] + ([keypoints_file] if keypoints_file else []) + [planner_overrides],
|
||||
remappings=[
|
||||
("body_pose", body_pose),
|
||||
("sensor_pose", sensor_pose),
|
||||
("cloud", cloud),
|
||||
("depth", depth),
|
||||
("move_base_simple/goal", "/move_base_simple/goal"),
|
||||
("initial_path", initial_path_topic),
|
||||
],
|
||||
)
|
||||
]
|
||||
actions.append(
|
||||
Node(
|
||||
package="robot_state_publisher",
|
||||
executable="robot_state_publisher",
|
||||
name="go2_robot_state_publisher",
|
||||
output="screen",
|
||||
parameters=[
|
||||
common,
|
||||
{
|
||||
"robot_description": Command(
|
||||
["xacro ", os.path.join(go2_share, "xacro", "robot.xacro"),
|
||||
" use_gazebo:=false"]
|
||||
)
|
||||
},
|
||||
],
|
||||
)
|
||||
)
|
||||
|
||||
if controller_mode == "open_loop":
|
||||
actions.append(
|
||||
Node(
|
||||
package="scan_planner",
|
||||
executable="open_loop_controller",
|
||||
name="open_loop_controller",
|
||||
output="screen",
|
||||
parameters=[
|
||||
controllers_yaml,
|
||||
common,
|
||||
{"init_x": init_x, "init_y": init_y, "init_z": init_z},
|
||||
],
|
||||
remappings=[
|
||||
("planning/bspline", "/planning/bspline"),
|
||||
("body_pose", body_pose),
|
||||
],
|
||||
)
|
||||
)
|
||||
else:
|
||||
actions.append(
|
||||
Node(
|
||||
package="scan_planner",
|
||||
executable="closed_loop_controller",
|
||||
name="closed_loop_controller",
|
||||
output="screen",
|
||||
parameters=[controllers_yaml, common],
|
||||
remappings=[
|
||||
("body_pose", body_pose),
|
||||
("cmd_vel", "/cmd_vel" if is_real else "/quad_0/cmd_vel"),
|
||||
],
|
||||
)
|
||||
)
|
||||
if not is_real:
|
||||
actions.append(
|
||||
Node(
|
||||
package="scan_planner",
|
||||
executable="go2_kinematic_sim",
|
||||
name="go2_kinematic_sim",
|
||||
output="screen",
|
||||
parameters=[
|
||||
controllers_yaml,
|
||||
common,
|
||||
{
|
||||
"init_x": init_x,
|
||||
"init_y": init_y,
|
||||
"init_z": init_z,
|
||||
"publish_tf": False,
|
||||
},
|
||||
],
|
||||
remappings=[
|
||||
("body_pose", "/quad_0/body_pose"),
|
||||
("cmd_vel", "/quad_0/cmd_vel"),
|
||||
],
|
||||
)
|
||||
)
|
||||
|
||||
if reference_path_file:
|
||||
actions.append(
|
||||
Node(
|
||||
package="scan_planner",
|
||||
executable="reference_path_publisher.py",
|
||||
name="reference_path_publisher",
|
||||
output="screen",
|
||||
parameters=[reference_path_file, common],
|
||||
remappings=[
|
||||
("body_pose", body_pose),
|
||||
("initial_path", initial_path_topic),
|
||||
],
|
||||
)
|
||||
)
|
||||
|
||||
if not is_real:
|
||||
actions.extend(
|
||||
[
|
||||
Node(
|
||||
package="scan_planner",
|
||||
executable="go2_gait_publisher",
|
||||
name="go2_gait_publisher",
|
||||
output="screen",
|
||||
parameters=[controllers_yaml, common],
|
||||
remappings=[("body_pose", body_pose)],
|
||||
),
|
||||
IncludeLaunchDescription(
|
||||
PythonLaunchDescriptionSource(
|
||||
os.path.join(scan_share, "launch", "simulator.launch.py")
|
||||
),
|
||||
launch_arguments={
|
||||
name: LaunchConfiguration(name)
|
||||
for name in (
|
||||
"is_real_world",
|
||||
"sensor_type",
|
||||
"use_gpu",
|
||||
"enable_local_sensing",
|
||||
"use_pcd_map",
|
||||
"pcd_map_file",
|
||||
"map_size_x",
|
||||
"map_size_y",
|
||||
"map_size_z",
|
||||
"use_sim_time",
|
||||
)
|
||||
}.items(),
|
||||
),
|
||||
]
|
||||
)
|
||||
return actions
|
||||
|
||||
|
||||
def generate_launch_description():
|
||||
return LaunchDescription(
|
||||
[
|
||||
DeclareLaunchArgument("is_real_world", default_value="false"),
|
||||
DeclareLaunchArgument("navi_mode", default_value="1"),
|
||||
DeclareLaunchArgument("sensor_type", default_value="lidar"),
|
||||
DeclareLaunchArgument("controller_mode", default_value="closed_loop"),
|
||||
DeclareLaunchArgument("keypoints_file", default_value=""),
|
||||
DeclareLaunchArgument("reference_path_file", default_value=""),
|
||||
DeclareLaunchArgument("initial_path_topic", default_value="/initial_path"),
|
||||
DeclareLaunchArgument("reference_path_min_distance", default_value="0.5"),
|
||||
DeclareLaunchArgument("reference_path_simplify_tolerance", default_value="0.0"),
|
||||
DeclareLaunchArgument("planning_horizon", default_value="3.5"),
|
||||
DeclareLaunchArgument("max_vel", default_value=""),
|
||||
DeclareLaunchArgument("max_acc", default_value=""),
|
||||
DeclareLaunchArgument("collision_radius", default_value=""),
|
||||
DeclareLaunchArgument("collision_offset", default_value=""),
|
||||
DeclareLaunchArgument("inflation_z_up", default_value=""),
|
||||
DeclareLaunchArgument("inflation_z_down", default_value=""),
|
||||
DeclareLaunchArgument("use_gpu", default_value="false"),
|
||||
DeclareLaunchArgument("enable_local_sensing", default_value="true"),
|
||||
DeclareLaunchArgument("use_pcd_map", default_value="false"),
|
||||
DeclareLaunchArgument("pcd_map_file", default_value=""),
|
||||
DeclareLaunchArgument("map_size_x", default_value="40.0"),
|
||||
DeclareLaunchArgument("map_size_y", default_value="40.0"),
|
||||
DeclareLaunchArgument("map_size_z", default_value="5.0"),
|
||||
DeclareLaunchArgument("init_x", default_value=""),
|
||||
DeclareLaunchArgument("init_y", default_value=""),
|
||||
DeclareLaunchArgument("init_z", default_value=""),
|
||||
DeclareLaunchArgument("use_sim_time", default_value="false"),
|
||||
OpaqueFunction(function=_setup),
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,103 @@
|
||||
"""SCAN 规划器(轮式底盘,真机)—— 只起规划 + 控制,不含雷达/LIO/底盘桥。
|
||||
|
||||
话题约定(配合 Point-LIO + body_odom):
|
||||
body_pose <- /body_odom (车体中心,body_odom 节点输出)
|
||||
sensor_pose <- /aft_mapped_to_init (雷达,Point-LIO 输出)
|
||||
cloud <- /cloud_registered_for_scan (世界系、经台阶封堵)
|
||||
goal <- /move_base_simple/goal (geometry_msgs/PoseStamped)
|
||||
|
||||
输出:``/cmd_vel`` (geometry_msgs/Twist, vx/vy/wz)
|
||||
|
||||
单独调试::
|
||||
|
||||
ros2 launch scan_planner run_vehicle.launch.py
|
||||
|
||||
整机(含雷达/LIO/底盘桥)用 ``vehicle_bringup.launch.py``。
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from ament_index_python.packages import get_package_share_directory
|
||||
from launch import LaunchDescription
|
||||
from launch.actions import DeclareLaunchArgument
|
||||
from launch.substitutions import LaunchConfiguration
|
||||
from launch_ros.actions import Node
|
||||
from launch_ros.parameter_descriptions import ParameterValue
|
||||
|
||||
|
||||
def generate_launch_description():
|
||||
share = get_package_share_directory('scan_planner')
|
||||
planner_yaml = os.path.join(share, 'config', 'planner_vehicle.yaml')
|
||||
controllers_yaml = os.path.join(share, 'config', 'controllers_vehicle.yaml')
|
||||
|
||||
navi_mode = LaunchConfiguration('navi_mode')
|
||||
max_vel = LaunchConfiguration('max_vel')
|
||||
max_acc = LaunchConfiguration('max_acc')
|
||||
collision_radius = LaunchConfiguration('collision_radius')
|
||||
body_height = LaunchConfiguration('body_height')
|
||||
cloud_topic = LaunchConfiguration('cloud_topic')
|
||||
odom_topic = LaunchConfiguration('odom_topic')
|
||||
body_odom_topic = LaunchConfiguration('body_odom_topic')
|
||||
|
||||
declared = [
|
||||
DeclareLaunchArgument(
|
||||
'navi_mode', default_value='1',
|
||||
description='1=纯局部(无图);2=keypoints 引导;3=PCT 全局路线'),
|
||||
DeclareLaunchArgument('max_vel', default_value='0.80',
|
||||
description='规划/控制速度上限 [m/s]'),
|
||||
DeclareLaunchArgument('max_acc', default_value='0.60',
|
||||
description='加速度上限 [m/s^2]'),
|
||||
DeclareLaunchArgument('collision_radius', default_value='0.30',
|
||||
description='双圆柱碰撞半径 [m]'),
|
||||
DeclareLaunchArgument('body_height', default_value='0.50',
|
||||
description='车体高度 [m],用于障碍 z 向膨胀'),
|
||||
DeclareLaunchArgument('cloud_topic', default_value='/cloud_registered',
|
||||
description='世界系点云话题(Point-LIO 输出)'),
|
||||
DeclareLaunchArgument('odom_topic', default_value='/aft_mapped_to_init',
|
||||
description='雷达里程计(Point-LIO 输出),给 sensor_pose'),
|
||||
DeclareLaunchArgument('body_odom_topic', default_value='/body_odom',
|
||||
description='车体中心里程计(body_odom 节点输出),给 body_pose'),
|
||||
]
|
||||
|
||||
planner = Node(
|
||||
package='scan_planner',
|
||||
executable='scan_planner_node',
|
||||
name='scan_planner_node',
|
||||
output='screen',
|
||||
parameters=[
|
||||
planner_yaml,
|
||||
{
|
||||
'fsm.navi_mode': ParameterValue(navi_mode, value_type=int),
|
||||
'manager.max_vel': ParameterValue(max_vel, value_type=float),
|
||||
'manager.max_acc': ParameterValue(max_acc, value_type=float),
|
||||
'optimization.max_vel': ParameterValue(max_vel, value_type=float),
|
||||
'optimization.max_acc': ParameterValue(max_acc, value_type=float),
|
||||
'grid_map.double_cylinder_radius':
|
||||
ParameterValue(collision_radius, value_type=float),
|
||||
'grid_map.body_height': ParameterValue(body_height, value_type=float),
|
||||
},
|
||||
],
|
||||
remappings=[
|
||||
('body_pose', body_odom_topic), # 车体中心:轨迹起点/到点判定/碰撞
|
||||
('sensor_pose', odom_topic), # 雷达:射线起点
|
||||
('cloud', cloud_topic),
|
||||
('depth', '/camera/aligned_depth_to_color/image_raw'),
|
||||
('move_base_simple/goal', '/move_base_simple/goal'),
|
||||
],
|
||||
)
|
||||
|
||||
controller = Node(
|
||||
package='scan_planner',
|
||||
executable='closed_loop_controller',
|
||||
name='closed_loop_controller',
|
||||
output='screen',
|
||||
parameters=[controllers_yaml, {
|
||||
'max_vx': ParameterValue(max_vel, value_type=float),
|
||||
}],
|
||||
remappings=[
|
||||
('body_pose', body_odom_topic),
|
||||
('cmd_vel', '/cmd_vel'),
|
||||
],
|
||||
)
|
||||
|
||||
return LaunchDescription(declared + [planner, controller])
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Start RViz2 with the SCAN-Planner display configuration."""
|
||||
|
||||
import os
|
||||
|
||||
from ament_index_python.packages import get_package_share_directory
|
||||
from launch import LaunchDescription
|
||||
from launch.actions import DeclareLaunchArgument
|
||||
from launch.substitutions import LaunchConfiguration
|
||||
from launch_ros.actions import Node
|
||||
|
||||
|
||||
def generate_launch_description():
|
||||
config = os.path.join(get_package_share_directory("scan_planner"), "rviz", "default.rviz")
|
||||
return LaunchDescription(
|
||||
[
|
||||
DeclareLaunchArgument("use_sim_time", default_value="false"),
|
||||
Node(
|
||||
package="rviz2",
|
||||
executable="rviz2",
|
||||
name="rviz2",
|
||||
output="screen",
|
||||
arguments=["-d", config],
|
||||
parameters=[{"use_sim_time": LaunchConfiguration("use_sim_time")}],
|
||||
),
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Native ROS 2 simulation for SCAN-Planner's deterministic regression setup."""
|
||||
|
||||
import os
|
||||
|
||||
from ament_index_python.packages import get_package_share_directory
|
||||
from launch import LaunchDescription
|
||||
from launch.actions import DeclareLaunchArgument, OpaqueFunction
|
||||
from launch.substitutions import LaunchConfiguration
|
||||
from launch_ros.actions import Node
|
||||
|
||||
|
||||
def _as_bool(value):
|
||||
return value.lower() in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
def _setup(context):
|
||||
if _as_bool(LaunchConfiguration("is_real_world").perform(context)):
|
||||
return []
|
||||
|
||||
use_pcd_map = _as_bool(LaunchConfiguration("use_pcd_map").perform(context))
|
||||
use_gpu = _as_bool(LaunchConfiguration("use_gpu").perform(context))
|
||||
enable_local_sensing = _as_bool(
|
||||
LaunchConfiguration("enable_local_sensing").perform(context)
|
||||
)
|
||||
use_sim_time = _as_bool(LaunchConfiguration("use_sim_time").perform(context))
|
||||
pcd_map_file = LaunchConfiguration("pcd_map_file").perform(context)
|
||||
sensor_type = LaunchConfiguration("sensor_type").perform(context)
|
||||
map_x = float(LaunchConfiguration("map_size_x").perform(context))
|
||||
map_y = float(LaunchConfiguration("map_size_y").perform(context))
|
||||
map_z = float(LaunchConfiguration("map_size_z").perform(context))
|
||||
|
||||
if use_pcd_map and (not pcd_map_file or not os.path.isfile(pcd_map_file)):
|
||||
raise RuntimeError(
|
||||
"use_pcd_map=true requires pcd_map_file to reference an existing PCD file"
|
||||
)
|
||||
|
||||
scan_share = get_package_share_directory("scan_planner")
|
||||
simulator_yaml = os.path.join(scan_share, "config", "simulator.yaml")
|
||||
nodes = []
|
||||
|
||||
if use_pcd_map:
|
||||
nodes.append(
|
||||
Node(
|
||||
package="map_generator",
|
||||
executable="map_pub",
|
||||
name="map_pub",
|
||||
namespace="map_generator",
|
||||
output="screen",
|
||||
parameters=[
|
||||
{
|
||||
"use_sim_time": use_sim_time,
|
||||
"file_name": pcd_map_file,
|
||||
"frame_id": "world",
|
||||
"publish_rate": 0.2,
|
||||
"downsample_res": 0.1,
|
||||
}
|
||||
],
|
||||
)
|
||||
)
|
||||
else:
|
||||
nodes.append(
|
||||
Node(
|
||||
package="mockamap",
|
||||
executable="mockamap_node",
|
||||
name="mockamap_node",
|
||||
output="screen",
|
||||
parameters=[
|
||||
simulator_yaml,
|
||||
{
|
||||
"use_sim_time": use_sim_time,
|
||||
"x_length": int(map_x),
|
||||
"y_length": int(map_y),
|
||||
"z_length": int(map_z),
|
||||
},
|
||||
],
|
||||
remappings=[("mock_map", "/map_generator/global_cloud")],
|
||||
)
|
||||
)
|
||||
|
||||
if enable_local_sensing:
|
||||
nodes.append(
|
||||
Node(
|
||||
package="local_sensing_node",
|
||||
executable="opengl_render_node" if use_gpu else "pcl_render_node",
|
||||
name="pcl_render_node",
|
||||
output="screen",
|
||||
parameters=[
|
||||
simulator_yaml,
|
||||
{
|
||||
"use_sim_time": use_sim_time,
|
||||
"sensor_type": sensor_type,
|
||||
"body_pose_topic": "body_pose",
|
||||
"map.x_size": map_x,
|
||||
"map.y_size": map_y,
|
||||
"map.z_size": map_z,
|
||||
"use_global_map_topic": True,
|
||||
"pcd_map_file": pcd_map_file,
|
||||
},
|
||||
],
|
||||
remappings=[
|
||||
("global_map", "/map_generator/global_cloud"),
|
||||
("body_pose", "/quad_0/body_pose"),
|
||||
("cloud", "/quad_0/cloud"),
|
||||
("sensor_cloud", "/quad_0/sensor_cloud"),
|
||||
("depth", "/quad_0/depth"),
|
||||
("dyn_cloud", "/quad_0/dyn_cloud"),
|
||||
("uav_cloud", "/quad_0/uav_cloud"),
|
||||
],
|
||||
)
|
||||
)
|
||||
|
||||
nodes.append(
|
||||
Node(
|
||||
package="odom_visualization",
|
||||
executable="odom_visualization",
|
||||
name="odom_visualization",
|
||||
output="screen",
|
||||
parameters=[simulator_yaml, {"use_sim_time": use_sim_time}],
|
||||
remappings=[
|
||||
("body_pose", "/quad_0/body_pose"),
|
||||
("pose", "/quad_0/pose"),
|
||||
("path", "/quad_0/path"),
|
||||
("velocity", "/quad_0/velocity"),
|
||||
("trajectory", "/quad_0/trajectory"),
|
||||
("robot", "/quad_0/robot"),
|
||||
("height", "/quad_0/height"),
|
||||
],
|
||||
)
|
||||
)
|
||||
return nodes
|
||||
|
||||
|
||||
def generate_launch_description():
|
||||
return LaunchDescription(
|
||||
[
|
||||
DeclareLaunchArgument("is_real_world", default_value="false"),
|
||||
DeclareLaunchArgument("sensor_type", default_value="lidar"),
|
||||
DeclareLaunchArgument("use_gpu", default_value="false"),
|
||||
DeclareLaunchArgument("enable_local_sensing", default_value="true"),
|
||||
DeclareLaunchArgument("use_pcd_map", default_value="false"),
|
||||
DeclareLaunchArgument("pcd_map_file", default_value=""),
|
||||
DeclareLaunchArgument("map_size_x", default_value="40.0"),
|
||||
DeclareLaunchArgument("map_size_y", default_value="40.0"),
|
||||
DeclareLaunchArgument("map_size_z", default_value="5.0"),
|
||||
DeclareLaunchArgument("use_sim_time", default_value="false"),
|
||||
OpaqueFunction(function=_setup),
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,177 @@
|
||||
"""整机启动(轮式底盘 + MID360 + Point-LIO + SCAN + 底盘串口桥)。
|
||||
|
||||
顺序:
|
||||
1. Point-LIO 组合容器(livox 驱动 + LIO),提供 /aft_mapped_to_init 与 /cloud_registered;
|
||||
2. 静态 TF ``world -> camera_init``(SCAN 的 grid_map.frame_id 是 world,
|
||||
Point-LIO 的世界系叫 camera_init,这里把两者接上,供 RViz 显示);
|
||||
3. 延迟后起 SCAN(等点云/odom 有数据);
|
||||
4. 底盘桥把 ``/cmd_vel`` 转成 10 字节串口帧发给 STM32。
|
||||
|
||||
用法::
|
||||
|
||||
ros2 launch scan_planner vehicle_bringup.launch.py
|
||||
ros2 launch scan_planner vehicle_bringup.launch.py launch_chassis:=false
|
||||
ros2 launch scan_planner vehicle_bringup.launch.py max_vel:=0.5 scan_delay:=8.0
|
||||
|
||||
发目标:RViz 的 "2D Goal Pose"(发 /move_base_simple/goal),或
|
||||
ros2 topic pub --once /move_base_simple/goal geometry_msgs/msg/PoseStamped \\
|
||||
"{header: {frame_id: camera_init}, pose: {position: {x: 3.0, y: 0.0}}}"
|
||||
"""
|
||||
|
||||
from launch import LaunchDescription
|
||||
from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription, TimerAction
|
||||
from launch.conditions import IfCondition
|
||||
from launch.launch_description_sources import PythonLaunchDescriptionSource
|
||||
from launch.substitutions import LaunchConfiguration
|
||||
from launch_ros.actions import Node
|
||||
from launch_ros.substitutions import FindPackageShare
|
||||
|
||||
|
||||
def _default_step_regions():
|
||||
"""从 step_blocker 的 yaml 读默认台阶区域,避免 launch 覆盖成空。"""
|
||||
try:
|
||||
import os
|
||||
import yaml
|
||||
from ament_index_python.packages import get_package_share_directory
|
||||
p = os.path.join(get_package_share_directory('step_blocker'),
|
||||
'config', 'step_blocker.yaml')
|
||||
with open(p, 'r') as f:
|
||||
params = yaml.safe_load(f)['step_blocker']['ros__parameters']
|
||||
return str(params.get('regions', ''))
|
||||
except Exception:
|
||||
return ''
|
||||
|
||||
|
||||
def _default_body_offset(name, fallback='0.0'):
|
||||
"""从 body_odom 的 yaml 读默认外参,避免 launch 覆盖成 0。"""
|
||||
try:
|
||||
import os
|
||||
import yaml
|
||||
from ament_index_python.packages import get_package_share_directory
|
||||
p = os.path.join(get_package_share_directory('body_odom'),
|
||||
'config', 'body_odom.yaml')
|
||||
with open(p, 'r') as f:
|
||||
params = yaml.safe_load(f)['body_odom']['ros__parameters']
|
||||
return str(params.get(name, fallback))
|
||||
except Exception:
|
||||
return fallback
|
||||
|
||||
|
||||
def generate_launch_description():
|
||||
launch_chassis = LaunchConfiguration('launch_chassis')
|
||||
launch_scan = LaunchConfiguration('launch_scan')
|
||||
launch_blocker = LaunchConfiguration('launch_blocker')
|
||||
scan_delay = LaunchConfiguration('scan_delay')
|
||||
step_regions = _default_step_regions()
|
||||
|
||||
declared = [
|
||||
DeclareLaunchArgument('launch_chassis', default_value='true',
|
||||
description='是否启动 /cmd_vel -> STM32 串口桥'),
|
||||
DeclareLaunchArgument('launch_scan', default_value='true',
|
||||
description='是否启动 SCAN(只测 LIO 时可关)'),
|
||||
DeclareLaunchArgument('launch_blocker', default_value='true',
|
||||
description='是否启动台阶封堵(把台阶从点云里堵死)'),
|
||||
DeclareLaunchArgument('scan_delay', default_value='5.0',
|
||||
description='等点云/odom 有数据的秒数'),
|
||||
DeclareLaunchArgument('navi_mode', default_value='1'),
|
||||
DeclareLaunchArgument('max_vel', default_value='0.80'),
|
||||
DeclareLaunchArgument('max_acc', default_value='0.60'),
|
||||
DeclareLaunchArgument('collision_radius', default_value='0.30'),
|
||||
DeclareLaunchArgument('body_height', default_value='0.50'),
|
||||
DeclareLaunchArgument('cloud_topic',
|
||||
default_value='/cloud_registered_for_scan',
|
||||
description='送进 SCAN 的点云(默认经过 step_blocker)'),
|
||||
DeclareLaunchArgument('odom_topic', default_value='/aft_mapped_to_init'),
|
||||
DeclareLaunchArgument('step_regions', default_value=step_regions,
|
||||
description='台阶矩形,世界系;留空则不封堵'),
|
||||
DeclareLaunchArgument('body_offset_x',
|
||||
default_value=_default_body_offset('offset_x'),
|
||||
description='车体中心在雷达系下的 x [m]'),
|
||||
DeclareLaunchArgument('body_offset_y',
|
||||
default_value=_default_body_offset('offset_y'),
|
||||
description='车体中心在雷达系下的 y [m]'),
|
||||
DeclareLaunchArgument('body_offset_z',
|
||||
default_value=_default_body_offset('offset_z'),
|
||||
description='车体中心在雷达系下的 z [m]'),
|
||||
DeclareLaunchArgument('body_offset_yaw',
|
||||
default_value=_default_body_offset('offset_yaw'),
|
||||
description='车体相对雷达的 yaw 差 [rad]'),
|
||||
]
|
||||
|
||||
# ---- 1. MID360 + Point-LIO ---------------------------------------------
|
||||
lio = IncludeLaunchDescription(
|
||||
PythonLaunchDescriptionSource([
|
||||
FindPackageShare('point_lio'), '/launch',
|
||||
'/single_livox_pointlio_intra_process.launch.py',
|
||||
]),
|
||||
)
|
||||
|
||||
# ---- 2. world -> camera_init(SCAN 与 Point-LIO 的坐标系桥)------------
|
||||
tf_bridge = Node(
|
||||
package='tf2_ros',
|
||||
executable='static_transform_publisher',
|
||||
name='static_tf_world_to_camera_init',
|
||||
arguments=['--frame-id', 'world', '--child-frame-id', 'camera_init'],
|
||||
output='screen',
|
||||
)
|
||||
|
||||
# ---- 2b. 雷达 odom -> 车体中心 odom -------------------------------------
|
||||
body_odom_node = IncludeLaunchDescription(
|
||||
PythonLaunchDescriptionSource([
|
||||
FindPackageShare('body_odom'), '/launch',
|
||||
'/body_odom.launch.py',
|
||||
]),
|
||||
launch_arguments={
|
||||
'offset_x': LaunchConfiguration('body_offset_x'),
|
||||
'offset_y': LaunchConfiguration('body_offset_y'),
|
||||
'offset_z': LaunchConfiguration('body_offset_z'),
|
||||
'offset_yaw': LaunchConfiguration('body_offset_yaw'),
|
||||
}.items(),
|
||||
)
|
||||
|
||||
# ---- 3. 台阶封堵:/cloud_registered -> /cloud_registered_for_scan ------
|
||||
blocker = IncludeLaunchDescription(
|
||||
PythonLaunchDescriptionSource([
|
||||
FindPackageShare('step_blocker'), '/launch',
|
||||
'/step_blocker.launch.py',
|
||||
]),
|
||||
condition=IfCondition(launch_blocker),
|
||||
launch_arguments={
|
||||
'regions': LaunchConfiguration('step_regions'),
|
||||
}.items(),
|
||||
)
|
||||
|
||||
# ---- 4. SCAN -----------------------------------------------------------
|
||||
scan = TimerAction(
|
||||
period=scan_delay,
|
||||
actions=[
|
||||
IncludeLaunchDescription(
|
||||
PythonLaunchDescriptionSource([
|
||||
FindPackageShare('scan_planner'), '/launch',
|
||||
'/run_vehicle.launch.py',
|
||||
]),
|
||||
condition=IfCondition(launch_scan),
|
||||
launch_arguments={
|
||||
'navi_mode': LaunchConfiguration('navi_mode'),
|
||||
'max_vel': LaunchConfiguration('max_vel'),
|
||||
'max_acc': LaunchConfiguration('max_acc'),
|
||||
'collision_radius': LaunchConfiguration('collision_radius'),
|
||||
'body_height': LaunchConfiguration('body_height'),
|
||||
'cloud_topic': LaunchConfiguration('cloud_topic'),
|
||||
'odom_topic': LaunchConfiguration('odom_topic'),
|
||||
}.items(),
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
# ---- 5. 底盘串口桥 ------------------------------------------------------
|
||||
chassis = IncludeLaunchDescription(
|
||||
PythonLaunchDescriptionSource([
|
||||
FindPackageShare('techx_r2_chassis_control'), '/launch',
|
||||
'/chassis_serial.launch.py',
|
||||
]),
|
||||
condition=IfCondition(launch_chassis),
|
||||
)
|
||||
|
||||
return LaunchDescription(
|
||||
declared + [lio, tf_bridge, body_odom_node, blocker, scan, chassis])
|
||||
@@ -0,0 +1,39 @@
|
||||
<?xml version="1.0"?>
|
||||
<package format="3">
|
||||
<name>scan_planner</name>
|
||||
<version>0.1.0</version>
|
||||
<description>SCAN-Planner ROS 2 nodes, controllers, launch and configuration.</description>
|
||||
<maintainer email="[email protected]">SCAN-Planner maintainers</maintainer>
|
||||
<license>Apache-2.0</license>
|
||||
|
||||
<buildtool_depend>ament_cmake</buildtool_depend>
|
||||
<depend>ament_index_cpp</depend>
|
||||
<exec_depend>ament_index_python</exec_depend>
|
||||
<depend>bspline_opt</depend>
|
||||
<depend>eigen</depend>
|
||||
<depend>geometry_msgs</depend>
|
||||
<depend>nav_msgs</depend>
|
||||
<depend>path_searching</depend>
|
||||
<depend>plan_env</depend>
|
||||
<depend>rclcpp</depend>
|
||||
<depend>rclpy</depend>
|
||||
<depend>scan_planner_msgs</depend>
|
||||
<depend>sensor_msgs</depend>
|
||||
<depend>std_msgs</depend>
|
||||
<depend>tf2</depend>
|
||||
<depend>tf2_geometry_msgs</depend>
|
||||
<depend>tf2_ros</depend>
|
||||
<depend>traj_utils</depend>
|
||||
<depend>visualization_msgs</depend>
|
||||
|
||||
<exec_depend>launch</exec_depend>
|
||||
<exec_depend>launch_ros</exec_depend>
|
||||
<exec_depend>robot_state_publisher</exec_depend>
|
||||
<exec_depend>rviz2</exec_depend>
|
||||
<test_depend>launch_testing_ament_cmake</test_depend>
|
||||
<test_depend>ament_cmake_gtest</test_depend>
|
||||
<test_depend>ament_cmake_pytest</test_depend>
|
||||
<test_depend>python3-pytest</test_depend>
|
||||
|
||||
<export><build_type>ament_cmake</build_type></export>
|
||||
</package>
|
||||
@@ -0,0 +1,146 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Interactively record odometry positions as ROS 2 SCAN-Planner parameters."""
|
||||
|
||||
import argparse
|
||||
import math
|
||||
import os
|
||||
import select
|
||||
import sys
|
||||
import termios
|
||||
import tty
|
||||
|
||||
import rclpy
|
||||
from nav_msgs.msg import Odometry
|
||||
from rclpy.node import Node
|
||||
from rclpy.qos import qos_profile_sensor_data
|
||||
from rclpy.utilities import remove_ros_args
|
||||
|
||||
|
||||
DEFAULT_OUTPUT = os.path.join(os.getcwd(), "keypoints.yaml")
|
||||
|
||||
|
||||
def format_float(value):
|
||||
text = f"{float(value):.6f}".rstrip("0").rstrip(".")
|
||||
return "0" if text in ("", "-0") else text
|
||||
|
||||
|
||||
def atomic_write(path, content):
|
||||
directory = os.path.dirname(os.path.abspath(path))
|
||||
os.makedirs(directory, exist_ok=True)
|
||||
temporary = path + ".tmp"
|
||||
with open(temporary, "w", encoding="utf-8") as handle:
|
||||
handle.write(content)
|
||||
os.replace(temporary, path)
|
||||
|
||||
|
||||
class KeypointRecorder(Node):
|
||||
def __init__(self, odom_topic, output_path):
|
||||
super().__init__("keypoint_recorder")
|
||||
self.odom_topic = odom_topic
|
||||
self.output_path = os.path.abspath(output_path)
|
||||
self.latest_odom = None
|
||||
self.waypoints = []
|
||||
self.create_subscription(Odometry, odom_topic, self.odom_callback, qos_profile_sensor_data)
|
||||
|
||||
def odom_callback(self, message):
|
||||
self.latest_odom = message
|
||||
|
||||
def current_point(self):
|
||||
if self.latest_odom is None:
|
||||
return None
|
||||
position = self.latest_odom.pose.pose.position
|
||||
point = (float(position.x), float(position.y), float(position.z))
|
||||
return point if all(math.isfinite(value) for value in point) else None
|
||||
|
||||
def record_current(self):
|
||||
point = self.current_point()
|
||||
if point is None:
|
||||
self.get_logger().warning("No valid odometry received yet")
|
||||
return
|
||||
self.waypoints.append(point)
|
||||
self.get_logger().info(f"Recorded waypoint {len(self.waypoints)}: {point}")
|
||||
|
||||
def replace_current(self, index):
|
||||
point = self.current_point()
|
||||
if point is None or not 1 <= index <= len(self.waypoints):
|
||||
self.get_logger().warning("Invalid waypoint index or odometry")
|
||||
return
|
||||
self.waypoints[index - 1] = point
|
||||
|
||||
def delete_waypoint(self, index):
|
||||
if 1 <= index <= len(self.waypoints):
|
||||
self.waypoints.pop(index - 1)
|
||||
else:
|
||||
self.get_logger().warning("Invalid waypoint index")
|
||||
|
||||
def build_yaml(self):
|
||||
values = [format_float(value) for point in self.waypoints for value in point]
|
||||
return (
|
||||
"scan_planner_node:\n"
|
||||
" ros__parameters:\n"
|
||||
f" fsm.waypoints: [{', '.join(values)}]\n"
|
||||
)
|
||||
|
||||
def save(self):
|
||||
atomic_write(self.output_path, self.build_yaml())
|
||||
self.get_logger().info(f"Saved {len(self.waypoints)} waypoint(s) to {self.output_path}")
|
||||
|
||||
def prompt_index(self, settings, action):
|
||||
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)
|
||||
try:
|
||||
return int(input(f"{action} waypoint index (1-{len(self.waypoints)}): ").strip())
|
||||
except ValueError:
|
||||
return -1
|
||||
finally:
|
||||
tty.setcbreak(sys.stdin.fileno())
|
||||
|
||||
def run(self):
|
||||
if not sys.stdin.isatty():
|
||||
raise RuntimeError("keyboard control requires a TTY")
|
||||
print("Enter/Space/a: add, r: replace, d: delete, u: undo, l: list, s: save, q: save+quit")
|
||||
settings = termios.tcgetattr(sys.stdin)
|
||||
tty.setcbreak(sys.stdin.fileno())
|
||||
try:
|
||||
while rclpy.ok():
|
||||
rclpy.spin_once(self, timeout_sec=0.05)
|
||||
ready, _, _ = select.select([sys.stdin], [], [], 0.0)
|
||||
if not ready:
|
||||
continue
|
||||
key = sys.stdin.read(1).lower()
|
||||
if key in ("\n", "\r", " ", "a"):
|
||||
self.record_current()
|
||||
elif key == "r":
|
||||
self.replace_current(self.prompt_index(settings, "Replace"))
|
||||
elif key == "d":
|
||||
self.delete_waypoint(self.prompt_index(settings, "Delete"))
|
||||
elif key == "u" and self.waypoints:
|
||||
self.waypoints.pop()
|
||||
elif key == "l":
|
||||
print("\n".join(f"{i}: {point}" for i, point in enumerate(self.waypoints, 1)))
|
||||
elif key == "s":
|
||||
self.save()
|
||||
elif key in ("q", "\x03"):
|
||||
self.save()
|
||||
break
|
||||
finally:
|
||||
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--odom", default="/LIO/odom_vehicle")
|
||||
parser.add_argument("--output", default=DEFAULT_OUTPUT)
|
||||
arguments = parser.parse_args(remove_ros_args(args=sys.argv)[1:])
|
||||
rclpy.init(args=sys.argv)
|
||||
recorder = KeypointRecorder(arguments.odom, arguments.output)
|
||||
try:
|
||||
recorder.run()
|
||||
except (KeyboardInterrupt, RuntimeError) as error:
|
||||
recorder.get_logger().error(str(error))
|
||||
finally:
|
||||
recorder.destroy_node()
|
||||
rclpy.try_shutdown()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,118 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish one configured 3D reference path after odometry is available."""
|
||||
|
||||
import math
|
||||
|
||||
import rclpy
|
||||
from geometry_msgs.msg import PoseStamped
|
||||
from nav_msgs.msg import Odometry, Path
|
||||
from rclpy.node import Node
|
||||
from rclpy.parameter import Parameter
|
||||
from rclpy.qos import (
|
||||
DurabilityPolicy,
|
||||
QoSProfile,
|
||||
ReliabilityPolicy,
|
||||
qos_profile_sensor_data,
|
||||
)
|
||||
|
||||
|
||||
def parse_waypoints(values):
|
||||
if values is None or len(values) < 6 or len(values) % 3 != 0:
|
||||
raise ValueError("waypoints must contain at least two x,y,z triples")
|
||||
numbers = [float(value) for value in values]
|
||||
if not all(math.isfinite(value) for value in numbers):
|
||||
raise ValueError("waypoints must contain only finite values")
|
||||
return [tuple(numbers[index : index + 3]) for index in range(0, len(numbers), 3)]
|
||||
|
||||
|
||||
def build_path_message(waypoints, frame_id, stamp):
|
||||
message = Path()
|
||||
message.header.frame_id = frame_id
|
||||
message.header.stamp = stamp
|
||||
for x, y, z in waypoints:
|
||||
pose = PoseStamped()
|
||||
message.poses.append(pose)
|
||||
pose.header = message.header
|
||||
pose.pose.position.x = x
|
||||
pose.pose.position.y = y
|
||||
pose.pose.position.z = z
|
||||
pose.pose.orientation.w = 1.0
|
||||
return message
|
||||
|
||||
|
||||
class ReferencePathPublisher(Node):
|
||||
def __init__(self):
|
||||
super().__init__("reference_path_publisher")
|
||||
self.declare_parameter("frame_id", "world")
|
||||
self.declare_parameter("waypoints", Parameter.Type.DOUBLE_ARRAY)
|
||||
self.declare_parameter("publish_delay_sec", 0.5)
|
||||
|
||||
self.frame_id = self.get_parameter("frame_id").value
|
||||
self.waypoints = parse_waypoints(self.get_parameter("waypoints").value)
|
||||
self.publish_delay_sec = float(self.get_parameter("publish_delay_sec").value)
|
||||
if not self.frame_id:
|
||||
raise ValueError("frame_id must not be empty")
|
||||
if not math.isfinite(self.publish_delay_sec) or self.publish_delay_sec < 0.0:
|
||||
raise ValueError("publish_delay_sec must be finite and non-negative")
|
||||
|
||||
path_qos = QoSProfile(
|
||||
depth=1,
|
||||
reliability=ReliabilityPolicy.RELIABLE,
|
||||
durability=DurabilityPolicy.TRANSIENT_LOCAL,
|
||||
)
|
||||
self.path_publisher = self.create_publisher(Path, "initial_path", path_qos)
|
||||
self.odom_subscription = self.create_subscription(
|
||||
Odometry, "body_pose", self.odom_callback, qos_profile_sensor_data
|
||||
)
|
||||
self.first_odom_time = None
|
||||
self.published = False
|
||||
self.timer = self.create_timer(0.05, self.try_publish)
|
||||
self.get_logger().info(
|
||||
f"Waiting to publish {len(self.waypoints)} reference-path points"
|
||||
)
|
||||
|
||||
def odom_callback(self, _message):
|
||||
if self.first_odom_time is None:
|
||||
self.first_odom_time = self.get_clock().now()
|
||||
|
||||
def try_publish(self):
|
||||
if self.published or self.first_odom_time is None:
|
||||
return
|
||||
if self.path_publisher.get_subscription_count() == 0:
|
||||
return
|
||||
elapsed = (self.get_clock().now() - self.first_odom_time).nanoseconds / 1e9
|
||||
if elapsed < self.publish_delay_sec:
|
||||
return
|
||||
|
||||
message = build_path_message(
|
||||
self.waypoints, self.frame_id, self.get_clock().now().to_msg()
|
||||
)
|
||||
self.path_publisher.publish(message)
|
||||
self.published = True
|
||||
self.timer.cancel()
|
||||
self.get_logger().info(
|
||||
f"Published reference path on initial_path with {len(message.poses)} points"
|
||||
)
|
||||
|
||||
|
||||
def main(args=None):
|
||||
rclpy.init(args=args)
|
||||
node = None
|
||||
try:
|
||||
node = ReferencePathPublisher()
|
||||
rclpy.spin(node)
|
||||
except (KeyboardInterrupt, ValueError) as error:
|
||||
if node is not None:
|
||||
node.get_logger().error(str(error))
|
||||
else:
|
||||
rclpy.logging.get_logger("reference_path_publisher").error(str(error))
|
||||
if isinstance(error, ValueError):
|
||||
raise
|
||||
finally:
|
||||
if node is not None:
|
||||
node.destroy_node()
|
||||
rclpy.try_shutdown()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,188 @@
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
#include <Eigen/Eigen>
|
||||
#include <geometry_msgs/msg/twist.hpp>
|
||||
#include <nav_msgs/msg/odometry.hpp>
|
||||
#include <rclcpp/rclcpp.hpp>
|
||||
#include <scan_planner_msgs/msg/bspline.hpp>
|
||||
#include <std_msgs/msg/bool.hpp>
|
||||
#include <tf2_geometry_msgs/tf2_geometry_msgs.hpp>
|
||||
#include <tf2/utils.hpp>
|
||||
|
||||
#include "bspline_opt/uniform_bspline.h"
|
||||
|
||||
namespace scan_planner
|
||||
{
|
||||
class ClosedLoopController : public rclcpp::Node
|
||||
{
|
||||
public:
|
||||
ClosedLoopController() : Node("closed_loop_controller")
|
||||
{
|
||||
time_forward_ = declare_parameter<double>("time_forward", 0.8);
|
||||
heading_error_threshold_ = declare_parameter<double>("heading_error_threshold", 0.8);
|
||||
kp_pos_ = declare_parameter<double>("kp_pos", 0.8);
|
||||
kp_yaw_ = declare_parameter<double>("kp_yaw", 1.5);
|
||||
max_vx_ = declare_parameter<double>("max_vx", 0.75);
|
||||
max_vy_ = declare_parameter<double>("max_vy", 0.35);
|
||||
max_vyaw_ = std::min(declare_parameter<double>("max_vyaw", 1.0), kMaxVYawLimit);
|
||||
finish_dist_ = declare_parameter<double>("finish_dist", 0.15);
|
||||
|
||||
bspline_sub_ = create_subscription<scan_planner_msgs::msg::Bspline>(
|
||||
"planning/bspline", 10,
|
||||
std::bind(&ClosedLoopController::bsplineCallback, this, std::placeholders::_1));
|
||||
odom_sub_ = create_subscription<nav_msgs::msg::Odometry>(
|
||||
"body_pose", rclcpp::SensorDataQoS(),
|
||||
std::bind(&ClosedLoopController::odomCallback, this, std::placeholders::_1));
|
||||
cmd_vel_pub_ = create_publisher<geometry_msgs::msg::Twist>("cmd_vel", 20);
|
||||
execution_frozen_pub_ = create_publisher<std_msgs::msg::Bool>("planning/go2_execution_frozen", 10);
|
||||
cmd_timer_ = create_wall_timer(std::chrono::milliseconds(10),
|
||||
std::bind(&ClosedLoopController::cmdCallback, this));
|
||||
last_update_time_ = now();
|
||||
RCLCPP_INFO(get_logger(), "Closed-loop controller ready");
|
||||
}
|
||||
|
||||
private:
|
||||
static constexpr double kMaxVYawLimit = 1.0;
|
||||
|
||||
static double normalizeAngle(double angle)
|
||||
{
|
||||
while (angle > M_PI) angle -= 2.0 * M_PI;
|
||||
while (angle < -M_PI) angle += 2.0 * M_PI;
|
||||
return angle;
|
||||
}
|
||||
|
||||
static Eigen::Vector2d clampNorm(const Eigen::Vector2d &value, double max_norm)
|
||||
{
|
||||
const double norm = value.norm();
|
||||
return (norm <= max_norm || norm < 1e-6) ? value : value / norm * max_norm;
|
||||
}
|
||||
|
||||
double estimateDesiredYaw(double t_cur, const Eigen::Vector3d &pos_des) const
|
||||
{
|
||||
const double t_look = std::min(traj_duration_, t_cur + time_forward_);
|
||||
Eigen::Vector3d direction = traj_[0].evaluateDeBoorT(t_look) - pos_des;
|
||||
if (direction.head<2>().squaredNorm() < 1e-4)
|
||||
direction = traj_[1].evaluateDeBoorT(t_cur);
|
||||
return direction.head<2>().squaredNorm() < 1e-4
|
||||
? odom_yaw_ : std::atan2(direction.y(), direction.x());
|
||||
}
|
||||
|
||||
void publishStop(double yaw_rate = 0.0)
|
||||
{
|
||||
geometry_msgs::msg::Twist cmd;
|
||||
cmd.angular.z = std::clamp(yaw_rate, -max_vyaw_, max_vyaw_);
|
||||
cmd_vel_pub_->publish(cmd);
|
||||
}
|
||||
|
||||
void publishExecutionFrozen(bool frozen)
|
||||
{
|
||||
std_msgs::msg::Bool msg;
|
||||
msg.data = frozen;
|
||||
execution_frozen_pub_->publish(msg);
|
||||
}
|
||||
|
||||
void bsplineCallback(const scan_planner_msgs::msg::Bspline::ConstSharedPtr msg)
|
||||
{
|
||||
if (msg->pos_pts.empty() || msg->knots.empty() || msg->order <= 0)
|
||||
{
|
||||
RCLCPP_WARN(get_logger(), "Ignoring invalid B-spline");
|
||||
return;
|
||||
}
|
||||
Eigen::MatrixXd points(3, msg->pos_pts.size());
|
||||
for (size_t i = 0; i < msg->pos_pts.size(); ++i)
|
||||
points.col(i) << msg->pos_pts[i].x, msg->pos_pts[i].y, msg->pos_pts[i].z;
|
||||
Eigen::VectorXd knots(msg->knots.size());
|
||||
for (size_t i = 0; i < msg->knots.size(); ++i) knots(i) = msg->knots[i];
|
||||
UniformBspline position(points, msg->order, 0.1);
|
||||
position.setKnot(knots);
|
||||
traj_ = {position, position.getDerivative()};
|
||||
traj_.push_back(traj_[1].getDerivative());
|
||||
traj_duration_ = traj_[0].getTimeSum();
|
||||
traj_id_ = msg->traj_id;
|
||||
exec_time_ = 0.0;
|
||||
last_update_time_ = now();
|
||||
receive_traj_ = true;
|
||||
RCLCPP_INFO(get_logger(), "Received trajectory %lld, duration %.3fs",
|
||||
static_cast<long long>(traj_id_), traj_duration_);
|
||||
}
|
||||
|
||||
void odomCallback(const nav_msgs::msg::Odometry::ConstSharedPtr msg)
|
||||
{
|
||||
odom_pos_ << msg->pose.pose.position.x, msg->pose.pose.position.y, msg->pose.pose.position.z;
|
||||
odom_yaw_ = tf2::getYaw(msg->pose.pose.orientation);
|
||||
have_odom_ = true;
|
||||
}
|
||||
|
||||
void cmdCallback()
|
||||
{
|
||||
if (!receive_traj_ || !have_odom_)
|
||||
{
|
||||
publishExecutionFrozen(false);
|
||||
publishStop();
|
||||
return;
|
||||
}
|
||||
const auto current_time = now();
|
||||
double dt = (current_time - last_update_time_).seconds();
|
||||
if (dt < 0.0 || dt > 0.2) dt = 0.0;
|
||||
const double t_eval = std::min(exec_time_, traj_duration_);
|
||||
Eigen::Vector3d pos_des = traj_[0].evaluateDeBoorT(t_eval);
|
||||
const double yaw_error = normalizeAngle(estimateDesiredYaw(t_eval, pos_des) - odom_yaw_);
|
||||
const double yaw_command = std::clamp(kp_yaw_ * yaw_error, -max_vyaw_, max_vyaw_);
|
||||
if (std::abs(yaw_error) > heading_error_threshold_)
|
||||
{
|
||||
publishExecutionFrozen(true);
|
||||
publishStop(yaw_command);
|
||||
last_update_time_ = current_time;
|
||||
return;
|
||||
}
|
||||
|
||||
publishExecutionFrozen(false);
|
||||
exec_time_ = std::min(traj_duration_, exec_time_ + dt);
|
||||
last_update_time_ = current_time;
|
||||
pos_des = traj_[0].evaluateDeBoorT(exec_time_);
|
||||
const Eigen::Vector3d vel_des = traj_[1].evaluateDeBoorT(exec_time_);
|
||||
const Eigen::Vector2d pos_error(pos_des.x() - odom_pos_.x(), pos_des.y() - odom_pos_.y());
|
||||
const Eigen::Vector2d vel_world = clampNorm(
|
||||
Eigen::Vector2d(vel_des.x(), vel_des.y()) + kp_pos_ * pos_error,
|
||||
std::max(max_vx_, max_vy_));
|
||||
const double c = std::cos(odom_yaw_);
|
||||
const double s = std::sin(odom_yaw_);
|
||||
geometry_msgs::msg::Twist command;
|
||||
command.linear.x = std::clamp(c * vel_world.x() + s * vel_world.y(), -max_vx_, max_vx_);
|
||||
command.linear.y = std::clamp(-s * vel_world.x() + c * vel_world.y(), -max_vy_, max_vy_);
|
||||
command.angular.z = yaw_command;
|
||||
if (exec_time_ >= traj_duration_ && pos_error.norm() < finish_dist_)
|
||||
command = geometry_msgs::msg::Twist();
|
||||
cmd_vel_pub_->publish(command);
|
||||
}
|
||||
|
||||
rclcpp::Publisher<geometry_msgs::msg::Twist>::SharedPtr cmd_vel_pub_;
|
||||
rclcpp::Publisher<std_msgs::msg::Bool>::SharedPtr execution_frozen_pub_;
|
||||
rclcpp::Subscription<scan_planner_msgs::msg::Bspline>::SharedPtr bspline_sub_;
|
||||
rclcpp::Subscription<nav_msgs::msg::Odometry>::SharedPtr odom_sub_;
|
||||
rclcpp::TimerBase::SharedPtr cmd_timer_;
|
||||
bool receive_traj_{false};
|
||||
bool have_odom_{false};
|
||||
std::vector<UniformBspline> traj_;
|
||||
double traj_duration_{0.0};
|
||||
std::int64_t traj_id_{0};
|
||||
Eigen::Vector3d odom_pos_{Eigen::Vector3d::Zero()};
|
||||
double odom_yaw_{0.0};
|
||||
double exec_time_{0.0};
|
||||
rclcpp::Time last_update_time_{0, 0, RCL_ROS_TIME};
|
||||
double time_forward_, heading_error_threshold_, kp_pos_, kp_yaw_;
|
||||
double max_vx_, max_vy_, max_vyaw_, finish_dist_;
|
||||
};
|
||||
} // namespace scan_planner
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
rclcpp::init(argc, argv);
|
||||
rclcpp::spin(std::make_shared<scan_planner::ClosedLoopController>());
|
||||
rclcpp::shutdown();
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <memory>
|
||||
|
||||
#include <nav_msgs/msg/odometry.hpp>
|
||||
#include <rclcpp/rclcpp.hpp>
|
||||
#include <sensor_msgs/msg/joint_state.hpp>
|
||||
|
||||
namespace scan_planner
|
||||
{
|
||||
class Go2GaitPublisher : public rclcpp::Node
|
||||
{
|
||||
public:
|
||||
Go2GaitPublisher() : Node("go2_gait_publisher")
|
||||
{
|
||||
const double rate = declare_parameter<double>("rate", 60.0);
|
||||
gait_frequency_ = declare_parameter<double>("gait_frequency", 2.2);
|
||||
min_walk_speed_ = declare_parameter<double>("min_walk_speed", 0.05);
|
||||
max_walk_speed_ = declare_parameter<double>("max_walk_speed", 1.0);
|
||||
always_trot_ = declare_parameter<bool>("always_trot", false);
|
||||
hip_swing_ = declare_parameter<double>("hip_swing", 0.08);
|
||||
thigh_swing_ = declare_parameter<double>("thigh_swing", 0.32);
|
||||
calf_swing_ = declare_parameter<double>("calf_swing", 0.42);
|
||||
|
||||
odom_sub_ = create_subscription<nav_msgs::msg::Odometry>(
|
||||
"body_pose", rclcpp::SensorDataQoS(),
|
||||
std::bind(&Go2GaitPublisher::odomCallback, this, std::placeholders::_1));
|
||||
joint_pub_ = create_publisher<sensor_msgs::msg::JointState>("joint_states", 10);
|
||||
timer_ = create_wall_timer(
|
||||
std::chrono::duration<double>(1.0 / std::max(1.0, rate)),
|
||||
std::bind(&Go2GaitPublisher::timerCallback, this));
|
||||
|
||||
joint_msg_.name = {
|
||||
"FL_hip_joint", "FL_thigh_joint", "FL_calf_joint",
|
||||
"FR_hip_joint", "FR_thigh_joint", "FR_calf_joint",
|
||||
"RL_hip_joint", "RL_thigh_joint", "RL_calf_joint",
|
||||
"RR_hip_joint", "RR_thigh_joint", "RR_calf_joint"};
|
||||
joint_msg_.position.resize(joint_msg_.name.size(), 0.0);
|
||||
joint_msg_.velocity.resize(joint_msg_.name.size(), 0.0);
|
||||
}
|
||||
|
||||
private:
|
||||
static constexpr double kPi = 3.14159265358979323846;
|
||||
|
||||
void odomCallback(const nav_msgs::msg::Odometry::ConstSharedPtr odom)
|
||||
{
|
||||
const double vx = odom->twist.twist.linear.x;
|
||||
const double vy = odom->twist.twist.linear.y;
|
||||
const double twist_speed = std::hypot(vx, vy);
|
||||
rclcpp::Time stamp(odom->header.stamp);
|
||||
if (stamp.nanoseconds() == 0) stamp = now();
|
||||
const double x = odom->pose.pose.position.x;
|
||||
const double y = odom->pose.pose.position.y;
|
||||
double pose_speed = 0.0;
|
||||
if (has_prev_pose_)
|
||||
{
|
||||
const double dt = (stamp - last_odom_time_).seconds();
|
||||
if (dt > 1e-4) pose_speed = std::hypot(x - last_odom_x_, y - last_odom_y_) / dt;
|
||||
}
|
||||
horizontal_speed_ = twist_speed > min_walk_speed_ ? twist_speed : pose_speed;
|
||||
last_odom_x_ = x;
|
||||
last_odom_y_ = y;
|
||||
last_odom_time_ = stamp;
|
||||
has_prev_pose_ = true;
|
||||
has_odom_ = true;
|
||||
}
|
||||
|
||||
void timerCallback()
|
||||
{
|
||||
const auto stamp = now();
|
||||
if (!has_odom_)
|
||||
{
|
||||
publishStance(stamp);
|
||||
return;
|
||||
}
|
||||
const double ratio = always_trot_ ? 0.45 : std::clamp(
|
||||
(horizontal_speed_ - min_walk_speed_) / std::max(1e-3, max_walk_speed_ - min_walk_speed_),
|
||||
0.0, 1.0);
|
||||
if (ratio <= 1e-3)
|
||||
{
|
||||
publishStance(stamp);
|
||||
return;
|
||||
}
|
||||
const double phase = 2.0 * kPi * gait_frequency_ * stamp.seconds();
|
||||
fillLeg(0, phase, ratio, true);
|
||||
fillLeg(3, phase + kPi, ratio, false);
|
||||
fillLeg(6, phase + kPi, ratio, true);
|
||||
fillLeg(9, phase, ratio, false);
|
||||
joint_msg_.header.stamp = stamp;
|
||||
joint_pub_->publish(joint_msg_);
|
||||
}
|
||||
|
||||
void publishStance(const rclcpp::Time &stamp)
|
||||
{
|
||||
const std::array<double, 12> stance = {
|
||||
0.05, 0.82, -1.58, -0.05, 0.82, -1.58,
|
||||
0.05, 0.95, -1.62, -0.05, 0.95, -1.62};
|
||||
for (size_t i = 0; i < stance.size(); ++i)
|
||||
{
|
||||
joint_msg_.position[i] = stance[i];
|
||||
joint_msg_.velocity[i] = 0.0;
|
||||
}
|
||||
joint_msg_.header.stamp = stamp;
|
||||
joint_pub_->publish(joint_msg_);
|
||||
}
|
||||
|
||||
void fillLeg(size_t offset, double phase, double ratio, bool left_side)
|
||||
{
|
||||
const double s = std::sin(phase), c = std::cos(phase), swing = std::max(0.0, s);
|
||||
const double side = left_side ? 1.0 : -1.0;
|
||||
const bool rear = offset >= 6;
|
||||
const double thigh_stance = rear ? 0.95 : 0.82;
|
||||
const double calf_stance = rear ? -1.62 : -1.58;
|
||||
joint_msg_.position[offset] = side * (0.05 + hip_swing_ * ratio * 0.35 * s);
|
||||
joint_msg_.position[offset + 1] = thigh_stance + thigh_swing_ * ratio * c;
|
||||
joint_msg_.position[offset + 2] = calf_stance + calf_swing_ * ratio * swing - 0.10 * ratio * (1.0 - swing);
|
||||
joint_msg_.position[offset] = std::clamp(joint_msg_.position[offset], -1.0, 1.0);
|
||||
joint_msg_.position[offset + 1] = std::clamp(joint_msg_.position[offset + 1], -1.2, 3.0);
|
||||
joint_msg_.position[offset + 2] = std::clamp(joint_msg_.position[offset + 2], -2.6, -0.9);
|
||||
const double omega = 2.0 * kPi * gait_frequency_;
|
||||
joint_msg_.velocity[offset] = side * hip_swing_ * ratio * 0.35 * c * omega;
|
||||
joint_msg_.velocity[offset + 1] = -thigh_swing_ * ratio * s * omega;
|
||||
joint_msg_.velocity[offset + 2] = calf_swing_ * ratio * (s > 0.0 ? c : 0.0) * omega;
|
||||
}
|
||||
|
||||
rclcpp::Subscription<nav_msgs::msg::Odometry>::SharedPtr odom_sub_;
|
||||
rclcpp::Publisher<sensor_msgs::msg::JointState>::SharedPtr joint_pub_;
|
||||
rclcpp::TimerBase::SharedPtr timer_;
|
||||
sensor_msgs::msg::JointState joint_msg_;
|
||||
rclcpp::Time last_odom_time_{0, 0, RCL_ROS_TIME};
|
||||
double horizontal_speed_{0.0}, last_odom_x_{0.0}, last_odom_y_{0.0};
|
||||
double gait_frequency_{2.2}, min_walk_speed_{0.05}, max_walk_speed_{1.0};
|
||||
double hip_swing_{0.08}, thigh_swing_{0.32}, calf_swing_{0.42};
|
||||
bool always_trot_{false}, has_odom_{false}, has_prev_pose_{false};
|
||||
};
|
||||
} // namespace scan_planner
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
rclcpp::init(argc, argv);
|
||||
rclcpp::spin(std::make_shared<scan_planner::Go2GaitPublisher>());
|
||||
rclcpp::shutdown();
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include <geometry_msgs/msg/transform_stamped.hpp>
|
||||
#include <geometry_msgs/msg/twist.hpp>
|
||||
#include <nav_msgs/msg/odometry.hpp>
|
||||
#include <rclcpp/rclcpp.hpp>
|
||||
#include <tf2/LinearMath/Quaternion.h>
|
||||
#include <tf2_geometry_msgs/tf2_geometry_msgs.hpp>
|
||||
#include <tf2_ros/transform_broadcaster.h>
|
||||
|
||||
namespace scan_planner
|
||||
{
|
||||
class Go2KinematicSim : public rclcpp::Node
|
||||
{
|
||||
public:
|
||||
Go2KinematicSim() : Node("go2_kinematic_sim")
|
||||
{
|
||||
x_ = declare_parameter<double>("init_x", 0.0);
|
||||
y_ = declare_parameter<double>("init_y", 0.0);
|
||||
z_ = declare_parameter<double>("init_z", 0.3);
|
||||
yaw_ = declare_parameter<double>("init_yaw", 0.0);
|
||||
max_vx_ = declare_parameter<double>("max_vx", 0.75);
|
||||
max_vy_ = declare_parameter<double>("max_vy", 0.35);
|
||||
max_vyaw_ = std::min(declare_parameter<double>("max_vyaw", 1.0), kMaxVYawLimit);
|
||||
cmd_timeout_ = declare_parameter<double>("cmd_timeout", 0.3);
|
||||
const double sim_rate = declare_parameter<double>("sim_rate", 100.0);
|
||||
publish_tf_ = declare_parameter<bool>("publish_tf", false);
|
||||
frame_id_ = declare_parameter<std::string>("frame_id", "world");
|
||||
child_frame_id_ = declare_parameter<std::string>("child_frame_id", "base");
|
||||
|
||||
tf_broadcaster_ = std::make_unique<tf2_ros::TransformBroadcaster>(*this);
|
||||
odom_pub_ = create_publisher<nav_msgs::msg::Odometry>("body_pose", 100);
|
||||
cmd_sub_ = create_subscription<geometry_msgs::msg::Twist>(
|
||||
"cmd_vel", 20, std::bind(&Go2KinematicSim::cmdCallback, this, std::placeholders::_1));
|
||||
last_cmd_time_ = now();
|
||||
last_sim_time_ = now();
|
||||
timer_ = create_wall_timer(
|
||||
std::chrono::duration<double>(1.0 / std::max(1.0, sim_rate)),
|
||||
std::bind(&Go2KinematicSim::simCallback, this));
|
||||
RCLCPP_INFO(get_logger(), "Go2 kinematic simulator ready");
|
||||
}
|
||||
|
||||
private:
|
||||
static constexpr double kMaxVYawLimit = 1.0;
|
||||
|
||||
static double normalizeAngle(double angle)
|
||||
{
|
||||
while (angle > M_PI) angle -= 2.0 * M_PI;
|
||||
while (angle < -M_PI) angle += 2.0 * M_PI;
|
||||
return angle;
|
||||
}
|
||||
|
||||
void cmdCallback(const geometry_msgs::msg::Twist::ConstSharedPtr msg)
|
||||
{
|
||||
vx_cmd_ = std::clamp(msg->linear.x, -max_vx_, max_vx_);
|
||||
vy_cmd_ = std::clamp(msg->linear.y, -max_vy_, max_vy_);
|
||||
vyaw_cmd_ = std::clamp(msg->angular.z, -max_vyaw_, max_vyaw_);
|
||||
last_cmd_time_ = now();
|
||||
}
|
||||
|
||||
void publishOdom(const rclcpp::Time &stamp)
|
||||
{
|
||||
tf2::Quaternion quaternion;
|
||||
quaternion.setRPY(0.0, 0.0, yaw_);
|
||||
const auto orientation = tf2::toMsg(quaternion);
|
||||
nav_msgs::msg::Odometry odom;
|
||||
odom.header.stamp = stamp;
|
||||
odom.header.frame_id = frame_id_;
|
||||
odom.child_frame_id = child_frame_id_;
|
||||
odom.pose.pose.position.x = x_;
|
||||
odom.pose.pose.position.y = y_;
|
||||
odom.pose.pose.position.z = z_;
|
||||
odom.pose.pose.orientation = orientation;
|
||||
odom.twist.twist.linear.x = vx_world_;
|
||||
odom.twist.twist.linear.y = vy_world_;
|
||||
odom.twist.twist.angular.z = vyaw_cmd_;
|
||||
odom_pub_->publish(odom);
|
||||
|
||||
if (publish_tf_)
|
||||
{
|
||||
geometry_msgs::msg::TransformStamped transform;
|
||||
transform.header = odom.header;
|
||||
transform.child_frame_id = child_frame_id_;
|
||||
transform.transform.translation.x = x_;
|
||||
transform.transform.translation.y = y_;
|
||||
transform.transform.translation.z = z_;
|
||||
transform.transform.rotation = orientation;
|
||||
tf_broadcaster_->sendTransform(transform);
|
||||
}
|
||||
}
|
||||
|
||||
void simCallback()
|
||||
{
|
||||
const auto current_time = now();
|
||||
double dt = (current_time - last_sim_time_).seconds();
|
||||
last_sim_time_ = current_time;
|
||||
if (dt < 0.0 || dt > 0.2) dt = 0.0;
|
||||
double vx = vx_cmd_, vy = vy_cmd_, wz = vyaw_cmd_;
|
||||
if ((current_time - last_cmd_time_).seconds() > cmd_timeout_)
|
||||
vx = vy = wz = 0.0;
|
||||
const double c = std::cos(yaw_);
|
||||
const double s = std::sin(yaw_);
|
||||
vx_world_ = c * vx - s * vy;
|
||||
vy_world_ = s * vx + c * vy;
|
||||
x_ += vx_world_ * dt;
|
||||
y_ += vy_world_ * dt;
|
||||
yaw_ = normalizeAngle(yaw_ + wz * dt);
|
||||
publishOdom(current_time);
|
||||
}
|
||||
|
||||
rclcpp::Publisher<nav_msgs::msg::Odometry>::SharedPtr odom_pub_;
|
||||
rclcpp::Subscription<geometry_msgs::msg::Twist>::SharedPtr cmd_sub_;
|
||||
rclcpp::TimerBase::SharedPtr timer_;
|
||||
std::unique_ptr<tf2_ros::TransformBroadcaster> tf_broadcaster_;
|
||||
double x_{0.0}, y_{0.0}, z_{0.3}, yaw_{0.0};
|
||||
double vx_cmd_{0.0}, vy_cmd_{0.0}, vyaw_cmd_{0.0};
|
||||
double vx_world_{0.0}, vy_world_{0.0};
|
||||
double max_vx_{0.75}, max_vy_{0.35}, max_vyaw_{1.0}, cmd_timeout_{0.3};
|
||||
bool publish_tf_{false};
|
||||
std::string frame_id_, child_frame_id_;
|
||||
rclcpp::Time last_cmd_time_{0, 0, RCL_ROS_TIME};
|
||||
rclcpp::Time last_sim_time_{0, 0, RCL_ROS_TIME};
|
||||
};
|
||||
} // namespace scan_planner
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
rclcpp::init(argc, argv);
|
||||
rclcpp::spin(std::make_shared<scan_planner::Go2KinematicSim>());
|
||||
rclcpp::shutdown();
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <Eigen/Eigen>
|
||||
#include <nav_msgs/msg/odometry.hpp>
|
||||
#include <rclcpp/rclcpp.hpp>
|
||||
#include <scan_planner_msgs/msg/bspline.hpp>
|
||||
#include <tf2/LinearMath/Quaternion.h>
|
||||
#include <tf2_geometry_msgs/tf2_geometry_msgs.hpp>
|
||||
|
||||
#include "bspline_opt/uniform_bspline.h"
|
||||
|
||||
namespace scan_planner
|
||||
{
|
||||
class OpenLoopController : public rclcpp::Node
|
||||
{
|
||||
public:
|
||||
OpenLoopController() : Node("open_loop_controller")
|
||||
{
|
||||
frame_id_ = declare_parameter<std::string>("frame_id", "world");
|
||||
child_frame_id_ = declare_parameter<std::string>("child_frame_id", "quadruped");
|
||||
const double publish_rate = declare_parameter<double>("publish_rate", 100.0);
|
||||
yaw_min_speed_ = declare_parameter<double>("yaw_min_speed", 0.05);
|
||||
hold_final_position_ = declare_parameter<bool>("hold_final_position", true);
|
||||
last_yaw_ = declare_parameter<double>("init_yaw", 0.0);
|
||||
current_pos_ = Eigen::Vector3d(
|
||||
declare_parameter<double>("init_x", 0.0),
|
||||
declare_parameter<double>("init_y", 0.0),
|
||||
declare_parameter<double>("init_z", 0.3));
|
||||
|
||||
odom_pub_ = create_publisher<nav_msgs::msg::Odometry>("body_pose", 20);
|
||||
bspline_sub_ = create_subscription<scan_planner_msgs::msg::Bspline>(
|
||||
"planning/bspline", 10,
|
||||
std::bind(&OpenLoopController::bsplineCallback, this, std::placeholders::_1));
|
||||
timer_ = create_wall_timer(
|
||||
std::chrono::duration<double>(1.0 / std::max(1.0, publish_rate)),
|
||||
std::bind(&OpenLoopController::publishOdom, this));
|
||||
RCLCPP_INFO(get_logger(), "Open-loop controller ready");
|
||||
}
|
||||
|
||||
private:
|
||||
bool parseBspline(const scan_planner_msgs::msg::Bspline::ConstSharedPtr &msg,
|
||||
UniformBspline &pos_traj)
|
||||
{
|
||||
if (msg->pos_pts.empty() || msg->knots.empty() || msg->order <= 0)
|
||||
{
|
||||
RCLCPP_WARN(get_logger(), "Ignoring invalid B-spline");
|
||||
return false;
|
||||
}
|
||||
Eigen::MatrixXd pos_pts(3, msg->pos_pts.size());
|
||||
for (size_t i = 0; i < msg->pos_pts.size(); ++i)
|
||||
pos_pts.col(i) << msg->pos_pts[i].x, msg->pos_pts[i].y, msg->pos_pts[i].z;
|
||||
Eigen::VectorXd knots(msg->knots.size());
|
||||
for (size_t i = 0; i < msg->knots.size(); ++i) knots(i) = msg->knots[i];
|
||||
pos_traj = UniformBspline(pos_pts, msg->order, 0.1);
|
||||
pos_traj.setKnot(knots);
|
||||
return true;
|
||||
}
|
||||
|
||||
void bsplineCallback(const scan_planner_msgs::msg::Bspline::ConstSharedPtr msg)
|
||||
{
|
||||
UniformBspline pos_traj;
|
||||
if (!parseBspline(msg, pos_traj)) return;
|
||||
traj_ = {pos_traj, pos_traj.getDerivative()};
|
||||
traj_.push_back(traj_[1].getDerivative());
|
||||
start_time_ = rclcpp::Time(msg->start_time);
|
||||
traj_id_ = msg->traj_id;
|
||||
traj_duration_ = traj_[0].getTimeSum();
|
||||
receive_traj_ = true;
|
||||
RCLCPP_INFO(get_logger(), "Received trajectory %lld, duration %.3fs",
|
||||
static_cast<long long>(traj_id_), traj_duration_);
|
||||
}
|
||||
|
||||
void publishState(const rclcpp::Time &stamp, const Eigen::Vector3d &pos,
|
||||
const Eigen::Vector3d &vel, double yaw, double yaw_rate)
|
||||
{
|
||||
nav_msgs::msg::Odometry odom;
|
||||
odom.header.stamp = stamp;
|
||||
odom.header.frame_id = frame_id_;
|
||||
odom.child_frame_id = child_frame_id_;
|
||||
odom.pose.pose.position.x = pos.x();
|
||||
odom.pose.pose.position.y = pos.y();
|
||||
odom.pose.pose.position.z = pos.z();
|
||||
tf2::Quaternion quaternion;
|
||||
quaternion.setRPY(0.0, 0.0, yaw);
|
||||
odom.pose.pose.orientation = tf2::toMsg(quaternion);
|
||||
odom.twist.twist.linear.x = vel.x();
|
||||
odom.twist.twist.linear.y = vel.y();
|
||||
odom.twist.twist.linear.z = vel.z();
|
||||
odom.twist.twist.angular.z = yaw_rate;
|
||||
odom_pub_->publish(odom);
|
||||
}
|
||||
|
||||
void publishOdom()
|
||||
{
|
||||
const auto now = this->now();
|
||||
if (!receive_traj_)
|
||||
{
|
||||
publishState(now, current_pos_, current_vel_, last_yaw_, 0.0);
|
||||
return;
|
||||
}
|
||||
const double elapsed = (now - start_time_).seconds();
|
||||
if (elapsed < 0.0)
|
||||
{
|
||||
publishState(now, current_pos_, current_vel_, last_yaw_, 0.0);
|
||||
return;
|
||||
}
|
||||
if (!hold_final_position_ && elapsed > traj_duration_) return;
|
||||
const double t = std::clamp(elapsed, 0.0, traj_duration_);
|
||||
const Eigen::Vector3d pos = traj_[0].evaluateDeBoorT(t);
|
||||
Eigen::Vector3d vel = Eigen::Vector3d::Zero();
|
||||
Eigen::Vector3d acc = Eigen::Vector3d::Zero();
|
||||
if (elapsed <= traj_duration_)
|
||||
{
|
||||
vel = traj_[1].evaluateDeBoorT(t);
|
||||
acc = traj_[2].evaluateDeBoorT(t);
|
||||
}
|
||||
const double speed = std::hypot(vel.x(), vel.y());
|
||||
if (speed > yaw_min_speed_) last_yaw_ = std::atan2(vel.y(), vel.x());
|
||||
const double yaw_rate = speed > yaw_min_speed_
|
||||
? (vel.x() * acc.y() - vel.y() * acc.x()) / std::max(speed * speed, 1e-6) : 0.0;
|
||||
current_pos_ = pos;
|
||||
current_vel_ = vel;
|
||||
publishState(now, pos, vel, last_yaw_, yaw_rate);
|
||||
}
|
||||
|
||||
rclcpp::Publisher<nav_msgs::msg::Odometry>::SharedPtr odom_pub_;
|
||||
rclcpp::Subscription<scan_planner_msgs::msg::Bspline>::SharedPtr bspline_sub_;
|
||||
rclcpp::TimerBase::SharedPtr timer_;
|
||||
bool receive_traj_{false};
|
||||
bool hold_final_position_{true};
|
||||
std::vector<UniformBspline> traj_;
|
||||
double traj_duration_{0.0};
|
||||
rclcpp::Time start_time_{0, 0, RCL_ROS_TIME};
|
||||
std::int64_t traj_id_{0};
|
||||
std::string frame_id_;
|
||||
std::string child_frame_id_;
|
||||
double last_yaw_{0.0};
|
||||
double yaw_min_speed_{0.05};
|
||||
Eigen::Vector3d current_pos_{Eigen::Vector3d::Zero()};
|
||||
Eigen::Vector3d current_vel_{Eigen::Vector3d::Zero()};
|
||||
};
|
||||
} // namespace scan_planner
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
rclcpp::init(argc, argv);
|
||||
rclcpp::spin(std::make_shared<scan_planner::OpenLoopController>());
|
||||
rclcpp::shutdown();
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,510 @@
|
||||
// #include <fstream>
|
||||
#include <plan_manage/planner_manager.h>
|
||||
#include <plan_manage/polyline_trajectory_utils.h>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
|
||||
namespace scan_planner
|
||||
{
|
||||
namespace
|
||||
{
|
||||
void applyLinearZReference(std::vector<Eigen::Vector3d> &points, const double start_z, const double target_z)
|
||||
{
|
||||
if (points.empty())
|
||||
return;
|
||||
|
||||
if (points.size() == 1)
|
||||
{
|
||||
points.front()(2) = start_z;
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<double> accumulated_xy_length(points.size(), 0.0);
|
||||
for (size_t i = 1; i < points.size(); ++i)
|
||||
{
|
||||
accumulated_xy_length[i] = accumulated_xy_length[i - 1] +
|
||||
(points[i].head<2>() - points[i - 1].head<2>()).norm();
|
||||
}
|
||||
|
||||
const double total_xy_length = accumulated_xy_length.back();
|
||||
for (size_t i = 0; i < points.size(); ++i)
|
||||
{
|
||||
const double ratio = total_xy_length > 1e-6
|
||||
? accumulated_xy_length[i] / total_xy_length
|
||||
: static_cast<double>(i) / static_cast<double>(points.size() - 1);
|
||||
points[i](2) = start_z + ratio * (target_z - start_z);
|
||||
}
|
||||
|
||||
points.front()(2) = start_z;
|
||||
points.back()(2) = target_z;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// SECTION interfaces for setup and query
|
||||
|
||||
SCANPlannerManager::SCANPlannerManager() {}
|
||||
|
||||
SCANPlannerManager::~SCANPlannerManager() { std::cout << "des manager" << std::endl; }
|
||||
|
||||
void SCANPlannerManager::initPlanModules(rclcpp::Node *node, PlanningVisualization::Ptr vis)
|
||||
{
|
||||
node_ = node;
|
||||
/* read algorithm parameters */
|
||||
const auto get_double = [node](const std::string &name, double default_value) {
|
||||
if (!node->has_parameter(name)) node->declare_parameter<double>(name, default_value);
|
||||
return node->get_parameter(name).as_double();
|
||||
};
|
||||
pp_.max_vel_ = get_double("manager.max_vel", -1.0);
|
||||
pp_.max_acc_ = get_double("manager.max_acc", -1.0);
|
||||
pp_.max_jerk_ = get_double("manager.max_jerk", -1.0);
|
||||
pp_.vel_tolerance_ = get_double("optimization.vel_tolerance", 1.0);
|
||||
pp_.acc_tolerance_ = get_double("optimization.acc_tolerance", 1.0);
|
||||
pp_.feasibility_tolerance_ = get_double("manager.feasibility_tolerance", 0.0);
|
||||
pp_.ctrl_pt_dist = get_double("manager.control_points_distance", -1.0);
|
||||
pp_.planning_horizon_ = get_double("manager.planning_horizon", 5.0);
|
||||
|
||||
local_data_.traj_id_ = 0;
|
||||
grid_map_.reset(new GridMap);
|
||||
grid_map_->initMap(node_);
|
||||
|
||||
bspline_optimizer_rebound_.reset(new BsplineOptimizer);
|
||||
bspline_optimizer_rebound_->setParam(node_);
|
||||
bspline_optimizer_rebound_->setEnvironment(grid_map_);
|
||||
bspline_optimizer_rebound_->a_star_.reset(new AStar);
|
||||
bspline_optimizer_rebound_->a_star_->initGridMap(grid_map_, Eigen::Vector3i(100, 100, 100));
|
||||
|
||||
visualization_ = vis;
|
||||
}
|
||||
|
||||
// !SECTION
|
||||
|
||||
// SECTION rebond replanning
|
||||
|
||||
bool SCANPlannerManager::reboundReplan(Eigen::Vector3d start_pt, Eigen::Vector3d start_vel,
|
||||
Eigen::Vector3d start_acc, Eigen::Vector3d local_target_pt,
|
||||
Eigen::Vector3d local_target_vel, bool flag_polyInit, bool flag_randomPolyTraj)
|
||||
{
|
||||
|
||||
static int count = 0;
|
||||
std::cout << endl
|
||||
<< "[rebo replan]: -------------------------------------" << count++ << std::endl;
|
||||
cout.precision(3);
|
||||
cout << "start: " << start_pt.transpose() << ", " << start_vel.transpose() << "\ngoal:" << local_target_pt.transpose() << ", " << local_target_vel.transpose()
|
||||
<< endl;
|
||||
|
||||
if ((start_pt - local_target_pt).norm() < 0.2)
|
||||
{
|
||||
cout << "Close to goal" << endl;
|
||||
continuous_failures_count_++;
|
||||
return false;
|
||||
}
|
||||
|
||||
auto t_start = std::chrono::steady_clock::now();
|
||||
double t_init = 0.0, t_opt = 0.0, t_refine = 0.0;
|
||||
|
||||
/*** STEP 1: INIT ***/
|
||||
double ts = (start_pt - local_target_pt).norm() > 0.1 ? pp_.ctrl_pt_dist / pp_.max_vel_ * 1.2 : pp_.ctrl_pt_dist / pp_.max_vel_ * 5; // pp_.ctrl_pt_dist / pp_.max_vel_ is too tense, and will surely exceed the acc/vel limits
|
||||
vector<Eigen::Vector3d> point_set, start_end_derivatives;
|
||||
static bool flag_first_call = true, flag_force_polynomial = false;
|
||||
bool flag_regenerate = false;
|
||||
do
|
||||
{
|
||||
point_set.clear();
|
||||
start_end_derivatives.clear();
|
||||
flag_regenerate = false;
|
||||
|
||||
if (flag_first_call || flag_polyInit || flag_force_polynomial /*|| ( start_pt - local_target_pt ).norm() < 1.0*/) // Initial path generated from a min-snap traj by order.
|
||||
{
|
||||
flag_first_call = false;
|
||||
flag_force_polynomial = false;
|
||||
|
||||
PolynomialTraj gl_traj;
|
||||
|
||||
double dist = (start_pt - local_target_pt).norm();
|
||||
double time = pow(pp_.max_vel_, 2) / pp_.max_acc_ > dist ? sqrt(dist / pp_.max_acc_) : (dist - pow(pp_.max_vel_, 2) / pp_.max_acc_) / pp_.max_vel_ + 2 * pp_.max_vel_ / pp_.max_acc_;
|
||||
|
||||
if (!flag_randomPolyTraj)
|
||||
{
|
||||
gl_traj = PolynomialTraj::one_segment_traj_gen(start_pt, start_vel, start_acc, local_target_pt, local_target_vel, Eigen::Vector3d::Zero(), time);
|
||||
}
|
||||
else
|
||||
{
|
||||
Eigen::Vector3d horizon_dir = ((start_pt - local_target_pt).cross(Eigen::Vector3d(0, 0, 1))).normalized();
|
||||
Eigen::Vector3d vertical_dir = ((start_pt - local_target_pt).cross(horizon_dir)).normalized();
|
||||
Eigen::Vector3d random_inserted_pt = (start_pt + local_target_pt) / 2 +
|
||||
(((double)rand()) / RAND_MAX - 0.5) * (start_pt - local_target_pt).norm() * horizon_dir * 0.8 * (-0.978 / (continuous_failures_count_ + 0.989) + 0.989) +
|
||||
(((double)rand()) / RAND_MAX - 0.5) * (start_pt - local_target_pt).norm() * vertical_dir * 0.4 * (-0.978 / (continuous_failures_count_ + 0.989) + 0.989);
|
||||
Eigen::MatrixXd pos(3, 3);
|
||||
pos.col(0) = start_pt;
|
||||
pos.col(1) = random_inserted_pt;
|
||||
pos.col(2) = local_target_pt;
|
||||
Eigen::VectorXd t(2);
|
||||
t(0) = t(1) = time / 2;
|
||||
gl_traj = PolynomialTraj::minSnapTraj(pos, start_vel, local_target_vel, start_acc, Eigen::Vector3d::Zero(), t);
|
||||
}
|
||||
|
||||
double t;
|
||||
bool flag_too_far;
|
||||
ts *= 1.5; // ts will be divided by 1.5 in the next
|
||||
do
|
||||
{
|
||||
ts /= 1.5;
|
||||
point_set.clear();
|
||||
flag_too_far = false;
|
||||
Eigen::Vector3d last_pt = gl_traj.evaluate(0);
|
||||
for (t = 0; t < time; t += ts)
|
||||
{
|
||||
Eigen::Vector3d pt = gl_traj.evaluate(t);
|
||||
if ((last_pt - pt).norm() > pp_.ctrl_pt_dist * 1.5)
|
||||
{
|
||||
flag_too_far = true;
|
||||
break;
|
||||
}
|
||||
last_pt = pt;
|
||||
point_set.push_back(pt);
|
||||
}
|
||||
} while (flag_too_far || point_set.size() < 7); // To make sure the initial path has enough points.
|
||||
t -= ts;
|
||||
start_end_derivatives.push_back(gl_traj.evaluateVel(0));
|
||||
start_end_derivatives.push_back(local_target_vel);
|
||||
start_end_derivatives.push_back(gl_traj.evaluateAcc(0));
|
||||
start_end_derivatives.push_back(gl_traj.evaluateAcc(t));
|
||||
}
|
||||
else // Initial path generated from previous trajectory.
|
||||
{
|
||||
|
||||
double t;
|
||||
double t_cur = (node_->now() - local_data_.start_time_).seconds();
|
||||
|
||||
vector<double> pseudo_arc_length;
|
||||
vector<Eigen::Vector3d> segment_point;
|
||||
pseudo_arc_length.push_back(0.0);
|
||||
for (t = t_cur; t < local_data_.duration_ + 1e-3; t += ts)
|
||||
{
|
||||
segment_point.push_back(local_data_.position_traj_.evaluateDeBoorT(t));
|
||||
if (t > t_cur)
|
||||
{
|
||||
pseudo_arc_length.push_back((segment_point.back() - segment_point[segment_point.size() - 2]).norm() + pseudo_arc_length.back());
|
||||
}
|
||||
}
|
||||
t -= ts;
|
||||
|
||||
double poly_time = (local_data_.position_traj_.evaluateDeBoorT(t) - local_target_pt).norm() / pp_.max_vel_ * 2;
|
||||
if (poly_time > ts)
|
||||
{
|
||||
PolynomialTraj gl_traj = PolynomialTraj::one_segment_traj_gen(local_data_.position_traj_.evaluateDeBoorT(t),
|
||||
local_data_.velocity_traj_.evaluateDeBoorT(t),
|
||||
local_data_.acceleration_traj_.evaluateDeBoorT(t),
|
||||
local_target_pt, local_target_vel, Eigen::Vector3d::Zero(), poly_time);
|
||||
|
||||
for (t = ts; t < poly_time; t += ts)
|
||||
{
|
||||
if (!pseudo_arc_length.empty())
|
||||
{
|
||||
segment_point.push_back(gl_traj.evaluate(t));
|
||||
pseudo_arc_length.push_back((segment_point.back() - segment_point[segment_point.size() - 2]).norm() + pseudo_arc_length.back());
|
||||
}
|
||||
else
|
||||
{
|
||||
RCLCPP_ERROR(node_->get_logger(), "pseudo_arc_length is empty; aborting replan");
|
||||
continuous_failures_count_++;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
double sample_length = 0;
|
||||
double cps_dist = pp_.ctrl_pt_dist * 1.5; // cps_dist will be divided by 1.5 in the next
|
||||
size_t id = 0;
|
||||
do
|
||||
{
|
||||
cps_dist /= 1.5;
|
||||
point_set.clear();
|
||||
sample_length = 0;
|
||||
id = 0;
|
||||
while ((id <= pseudo_arc_length.size() - 2) && sample_length <= pseudo_arc_length.back())
|
||||
{
|
||||
if (sample_length >= pseudo_arc_length[id] && sample_length < pseudo_arc_length[id + 1])
|
||||
{
|
||||
point_set.push_back((sample_length - pseudo_arc_length[id]) / (pseudo_arc_length[id + 1] - pseudo_arc_length[id]) * segment_point[id + 1] +
|
||||
(pseudo_arc_length[id + 1] - sample_length) / (pseudo_arc_length[id + 1] - pseudo_arc_length[id]) * segment_point[id]);
|
||||
sample_length += cps_dist;
|
||||
}
|
||||
else
|
||||
id++;
|
||||
}
|
||||
point_set.push_back(local_target_pt);
|
||||
} while (point_set.size() < 7); // If the start point is very close to end point, this will help
|
||||
|
||||
start_end_derivatives.push_back(local_data_.velocity_traj_.evaluateDeBoorT(t_cur));
|
||||
start_end_derivatives.push_back(local_target_vel);
|
||||
start_end_derivatives.push_back(local_data_.acceleration_traj_.evaluateDeBoorT(t_cur));
|
||||
start_end_derivatives.push_back(Eigen::Vector3d::Zero());
|
||||
|
||||
if (point_set.size() > pp_.planning_horizon_ / pp_.ctrl_pt_dist * 3) // The initial path is abnormally too long!
|
||||
{
|
||||
flag_force_polynomial = true;
|
||||
flag_regenerate = true;
|
||||
}
|
||||
}
|
||||
} while (flag_regenerate);
|
||||
|
||||
applyLinearZReference(point_set, start_pt(2), local_target_pt(2));
|
||||
|
||||
Eigen::MatrixXd ctrl_pts;
|
||||
UniformBspline::parameterizeToBspline(ts, point_set, start_end_derivatives, ctrl_pts);
|
||||
|
||||
vector<vector<Eigen::Vector3d>> a_star_paths;
|
||||
a_star_paths = bspline_optimizer_rebound_->initControlPoints(ctrl_pts, true);
|
||||
|
||||
t_init = std::chrono::duration<double>(std::chrono::steady_clock::now() - t_start).count();
|
||||
|
||||
static int vis_id = 0;
|
||||
visualization_->displayInitPathList(point_set, 0.2, 0);
|
||||
visualization_->displayAStarList(a_star_paths, vis_id);
|
||||
|
||||
t_start = std::chrono::steady_clock::now();
|
||||
|
||||
/*** STEP 2: OPTIMIZE ***/
|
||||
bool flag_step_1_success = bspline_optimizer_rebound_->BsplineOptimizeTrajRebound(ctrl_pts, ts);
|
||||
cout << "first_optimize_step_success=" << flag_step_1_success << endl;
|
||||
if (!flag_step_1_success)
|
||||
{
|
||||
// visualization_->displayOptimalList( ctrl_pts, vis_id );
|
||||
continuous_failures_count_++;
|
||||
return false;
|
||||
}
|
||||
//visualization_->displayOptimalList( ctrl_pts, vis_id );
|
||||
|
||||
t_opt = std::chrono::duration<double>(std::chrono::steady_clock::now() - t_start).count();
|
||||
t_start = std::chrono::steady_clock::now();
|
||||
|
||||
/*** STEP 3: REFINE(RE-ALLOCATE TIME) IF NECESSARY ***/
|
||||
UniformBspline pos = UniformBspline(ctrl_pts, 3, ts);
|
||||
pos.setPhysicalLimits(pp_.max_vel_, pp_.max_acc_, pp_.feasibility_tolerance_);
|
||||
|
||||
double ratio;
|
||||
bool flag_step_2_success = true;
|
||||
if (!pos.checkFeasibility(ratio, false))
|
||||
{
|
||||
cout << "Need to reallocate time." << endl;
|
||||
|
||||
Eigen::MatrixXd optimal_control_points;
|
||||
flag_step_2_success = refineTrajAlgo(pos, start_end_derivatives, ratio, ts, optimal_control_points);
|
||||
if (flag_step_2_success)
|
||||
pos = UniformBspline(optimal_control_points, 3, ts);
|
||||
}
|
||||
|
||||
if (!flag_step_2_success || !checkDynamicFeasibility(pos))
|
||||
{
|
||||
printf("\033[34mThis refined trajectory is unsafe or dynamically infeasible. Skip publishing it.\n\033[0m");
|
||||
continuous_failures_count_++;
|
||||
return false;
|
||||
}
|
||||
|
||||
t_refine = std::chrono::duration<double>(std::chrono::steady_clock::now() - t_start).count();
|
||||
|
||||
// save planned results
|
||||
updateTrajInfo(pos, node_->now());
|
||||
|
||||
cout << "total time:\033[42m" << (t_init + t_opt + t_refine)
|
||||
<< "\033[0m,optimize:" << (t_init + t_opt) << ",refine:" << t_refine << endl;
|
||||
|
||||
// success. YoY
|
||||
continuous_failures_count_ = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SCANPlannerManager::EmergencyStop(Eigen::Vector3d stop_pos)
|
||||
{
|
||||
Eigen::MatrixXd control_points(3, 6);
|
||||
for (int i = 0; i < 6; i++)
|
||||
{
|
||||
control_points.col(i) = stop_pos;
|
||||
}
|
||||
|
||||
updateTrajInfo(UniformBspline(control_points, 3, 1.0), node_->now());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SCANPlannerManager::planGlobalTrajWaypoints(const Eigen::Vector3d &start_pos, const Eigen::Vector3d &start_vel, const Eigen::Vector3d &start_acc,
|
||||
const std::vector<Eigen::Vector3d> &waypoints, const Eigen::Vector3d &end_vel, const Eigen::Vector3d &end_acc)
|
||||
{
|
||||
if (waypoints.empty())
|
||||
return false;
|
||||
|
||||
vector<Eigen::Vector3d> points;
|
||||
points.push_back(start_pos);
|
||||
points.insert(points.end(), waypoints.begin(), waypoints.end());
|
||||
PolynomialTraj gl_traj;
|
||||
std::string error;
|
||||
if (!makePiecewiseLinearTrajectory(points, pp_.max_vel_, gl_traj, &error))
|
||||
{
|
||||
RCLCPP_ERROR(node_->get_logger(), "Unable to build polyline reference trajectory: %s", error.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
(void)start_vel;
|
||||
(void)start_acc;
|
||||
(void)end_vel;
|
||||
(void)end_acc;
|
||||
|
||||
auto time_now = node_->now();
|
||||
global_data_.setGlobalTraj(gl_traj, time_now);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SCANPlannerManager::planGlobalTraj(const Eigen::Vector3d &start_pos, const Eigen::Vector3d &start_vel, const Eigen::Vector3d &start_acc,
|
||||
const Eigen::Vector3d &end_pos, const Eigen::Vector3d &end_vel, const Eigen::Vector3d &end_acc)
|
||||
{
|
||||
|
||||
// generate global reference trajectory
|
||||
|
||||
vector<Eigen::Vector3d> points;
|
||||
points.push_back(start_pos);
|
||||
points.push_back(end_pos);
|
||||
|
||||
// insert intermediate points if too far
|
||||
vector<Eigen::Vector3d> inter_points;
|
||||
const double dist_thresh = 4.0;
|
||||
|
||||
for (size_t i = 0; i < points.size() - 1; ++i)
|
||||
{
|
||||
inter_points.push_back(points.at(i));
|
||||
double dist = (points.at(i + 1) - points.at(i)).norm();
|
||||
|
||||
if (dist > dist_thresh)
|
||||
{
|
||||
int id_num = floor(dist / dist_thresh) + 1;
|
||||
|
||||
for (int j = 1; j < id_num; ++j)
|
||||
{
|
||||
Eigen::Vector3d inter_pt =
|
||||
points.at(i) * (1.0 - double(j) / id_num) + points.at(i + 1) * double(j) / id_num;
|
||||
inter_points.push_back(inter_pt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inter_points.push_back(points.back());
|
||||
|
||||
// write position matrix
|
||||
int pt_num = inter_points.size();
|
||||
Eigen::MatrixXd pos(3, pt_num);
|
||||
for (int i = 0; i < pt_num; ++i)
|
||||
pos.col(i) = inter_points[i];
|
||||
|
||||
Eigen::Vector3d zero(0, 0, 0);
|
||||
Eigen::VectorXd time(pt_num - 1);
|
||||
for (int i = 0; i < pt_num - 1; ++i)
|
||||
{
|
||||
time(i) = (pos.col(i + 1) - pos.col(i)).norm() / (pp_.max_vel_);
|
||||
}
|
||||
|
||||
time(0) *= 2.0;
|
||||
time(time.rows() - 1) *= 2.0;
|
||||
|
||||
PolynomialTraj gl_traj;
|
||||
if (pos.cols() >= 3)
|
||||
gl_traj = PolynomialTraj::minSnapTraj(pos, start_vel, end_vel, start_acc, end_acc, time);
|
||||
else if (pos.cols() == 2)
|
||||
gl_traj = PolynomialTraj::one_segment_traj_gen(start_pos, start_vel, start_acc, end_pos, end_vel, end_acc, time(0));
|
||||
else
|
||||
return false;
|
||||
|
||||
auto time_now = node_->now();
|
||||
global_data_.setGlobalTraj(gl_traj, time_now);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SCANPlannerManager::refineTrajAlgo(UniformBspline &traj, vector<Eigen::Vector3d> &start_end_derivative, double ratio, double &ts, Eigen::MatrixXd &optimal_control_points)
|
||||
{
|
||||
double t_inc;
|
||||
|
||||
Eigen::MatrixXd ctrl_pts; // = traj.getControlPoint()
|
||||
|
||||
// std::cout << "ratio: " << ratio << std::endl;
|
||||
reparamBspline(traj, start_end_derivative, ratio, ctrl_pts, ts, t_inc);
|
||||
|
||||
traj = UniformBspline(ctrl_pts, 3, ts);
|
||||
|
||||
double t_step = traj.getTimeSum() / (ctrl_pts.cols() - 3);
|
||||
bspline_optimizer_rebound_->ref_pts_.clear();
|
||||
for (double t = 0; t < traj.getTimeSum() + 1e-4; t += t_step)
|
||||
bspline_optimizer_rebound_->ref_pts_.push_back(traj.evaluateDeBoorT(t));
|
||||
|
||||
bool success = bspline_optimizer_rebound_->BsplineOptimizeTrajRefine(ctrl_pts, ts, optimal_control_points);
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
void SCANPlannerManager::updateTrajInfo(const UniformBspline &position_traj, const rclcpp::Time time_now)
|
||||
{
|
||||
local_data_.start_time_ = time_now;
|
||||
local_data_.position_traj_ = position_traj;
|
||||
local_data_.velocity_traj_ = local_data_.position_traj_.getDerivative();
|
||||
local_data_.acceleration_traj_ = local_data_.velocity_traj_.getDerivative();
|
||||
local_data_.start_pos_ = local_data_.position_traj_.evaluateDeBoorT(0.0);
|
||||
local_data_.duration_ = local_data_.position_traj_.getTimeSum();
|
||||
local_data_.traj_id_ += 1;
|
||||
}
|
||||
|
||||
bool SCANPlannerManager::checkDynamicFeasibility(UniformBspline position_traj)
|
||||
{
|
||||
UniformBspline vel_traj = position_traj.getDerivative();
|
||||
UniformBspline acc_traj = vel_traj.getDerivative();
|
||||
const double duration = position_traj.getTimeSum();
|
||||
const double sample_dt = std::max(0.01, std::min(0.05, duration / 50.0));
|
||||
const double vel_limit = pp_.max_vel_ + pp_.vel_tolerance_;
|
||||
const double acc_limit = pp_.max_acc_ + pp_.acc_tolerance_;
|
||||
|
||||
for (double t = 0.0; t < duration + 1e-6; t += sample_dt)
|
||||
{
|
||||
const double tc = std::min(t, duration);
|
||||
Eigen::Vector3d vel = vel_traj.evaluateDeBoorT(tc);
|
||||
if (vel.norm() > vel_limit)
|
||||
{
|
||||
RCLCPP_WARN(node_->get_logger(),
|
||||
"Dynamic feasibility failed: velocity at t=%.3f is %.3f > %.3f",
|
||||
tc, vel.norm(), vel_limit);
|
||||
return false;
|
||||
}
|
||||
|
||||
Eigen::Vector3d acc = acc_traj.evaluateDeBoorT(tc);
|
||||
if (acc.norm() > acc_limit)
|
||||
{
|
||||
RCLCPP_WARN(node_->get_logger(),
|
||||
"Dynamic feasibility failed: acceleration at t=%.3f is %.3f > %.3f",
|
||||
tc, acc.norm(), acc_limit);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void SCANPlannerManager::reparamBspline(UniformBspline &bspline, vector<Eigen::Vector3d> &start_end_derivative, double ratio,
|
||||
Eigen::MatrixXd &ctrl_pts, double &dt, double &time_inc)
|
||||
{
|
||||
double time_origin = bspline.getTimeSum();
|
||||
int seg_num = bspline.getControlPoint().cols() - 3;
|
||||
// double length = bspline.getLength(0.1);
|
||||
// int seg_num = ceil(length / pp_.ctrl_pt_dist);
|
||||
|
||||
bspline.lengthenTime(ratio);
|
||||
double duration = bspline.getTimeSum();
|
||||
dt = duration / double(seg_num);
|
||||
time_inc = duration - time_origin;
|
||||
|
||||
vector<Eigen::Vector3d> point_set;
|
||||
for (double time = 0.0; time <= duration + 1e-4; time += dt)
|
||||
{
|
||||
point_set.push_back(bspline.evaluateDeBoorT(time));
|
||||
}
|
||||
UniformBspline::parameterizeToBspline(dt, point_set, start_end_derivative, ctrl_pts);
|
||||
}
|
||||
|
||||
} // namespace scan_planner
|
||||
@@ -0,0 +1,29 @@
|
||||
#include <memory>
|
||||
#include <exception>
|
||||
|
||||
#include <rclcpp/rclcpp.hpp>
|
||||
#include <plan_manage/scan_replan_fsm.h>
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
rclcpp::init(argc, argv);
|
||||
auto node = std::make_shared<rclcpp::Node>("scan_planner_node");
|
||||
|
||||
try
|
||||
{
|
||||
scan_planner::SCANReplanFSM planner;
|
||||
planner.init(node.get());
|
||||
rclcpp::executors::SingleThreadedExecutor executor;
|
||||
executor.add_node(node);
|
||||
executor.spin();
|
||||
}
|
||||
catch (const std::exception &error)
|
||||
{
|
||||
RCLCPP_FATAL(node->get_logger(), "Failed to initialize SCAN-Planner: %s", error.what());
|
||||
rclcpp::shutdown();
|
||||
return 1;
|
||||
}
|
||||
|
||||
rclcpp::shutdown();
|
||||
return 0;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,32 @@
|
||||
"""Smoke-test that the migrated planner accepts its ROS 2 parameter file."""
|
||||
|
||||
import os
|
||||
|
||||
import launch
|
||||
import launch_ros.actions
|
||||
import launch_testing
|
||||
import launch_testing.actions
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.launch_test
|
||||
def generate_test_description():
|
||||
config = os.path.abspath(
|
||||
os.path.join(os.path.dirname(__file__), "..", "config", "planner.yaml")
|
||||
)
|
||||
planner = launch_ros.actions.Node(
|
||||
package="scan_planner",
|
||||
executable="scan_planner_node",
|
||||
name="scan_planner_node",
|
||||
parameters=[config],
|
||||
output="screen",
|
||||
)
|
||||
return (
|
||||
launch.LaunchDescription([planner, launch_testing.actions.ReadyToTest()]),
|
||||
{"planner": planner},
|
||||
)
|
||||
|
||||
|
||||
class TestPlannerStartup:
|
||||
def test_process_starts(self, proc_info, planner):
|
||||
proc_info.assertWaitForStartup(process=planner, timeout=15)
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Verify that the demo path waits for odometry and publishes only once."""
|
||||
|
||||
import time
|
||||
import unittest
|
||||
|
||||
import launch
|
||||
import launch_ros.actions
|
||||
import launch_testing
|
||||
import launch_testing.actions
|
||||
import pytest
|
||||
import rclpy
|
||||
from nav_msgs.msg import Odometry, Path
|
||||
from rclpy.executors import SingleThreadedExecutor
|
||||
from rclpy.qos import (
|
||||
DurabilityPolicy,
|
||||
QoSProfile,
|
||||
ReliabilityPolicy,
|
||||
qos_profile_sensor_data,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.launch_test
|
||||
def generate_test_description():
|
||||
publisher = launch_ros.actions.Node(
|
||||
package="scan_planner",
|
||||
executable="reference_path_publisher.py",
|
||||
name="reference_path_publisher",
|
||||
parameters=[
|
||||
{
|
||||
"frame_id": "world",
|
||||
"publish_delay_sec": 0.1,
|
||||
"waypoints": [0.0, 0.0, 0.0, 1.0, 0.0, 0.5],
|
||||
}
|
||||
],
|
||||
output="screen",
|
||||
)
|
||||
return (
|
||||
launch.LaunchDescription(
|
||||
[
|
||||
publisher,
|
||||
launch_testing.actions.ReadyToTest(),
|
||||
launch.actions.TimerAction(
|
||||
period=5.0,
|
||||
actions=[launch.actions.Shutdown(reason="publisher test complete")],
|
||||
),
|
||||
]
|
||||
),
|
||||
{"publisher": publisher},
|
||||
)
|
||||
|
||||
|
||||
class TestReferencePathPublisher(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.context = rclpy.context.Context()
|
||||
rclpy.init(context=cls.context)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.context.shutdown()
|
||||
|
||||
def test_waits_for_odom_and_publishes_once(self, proc_info, publisher):
|
||||
proc_info.assertWaitForStartup(process=publisher, timeout=10)
|
||||
node = rclpy.create_node(
|
||||
"reference_path_publisher_test", context=self.context
|
||||
)
|
||||
received = []
|
||||
path_qos = QoSProfile(
|
||||
depth=10,
|
||||
reliability=ReliabilityPolicy.RELIABLE,
|
||||
durability=DurabilityPolicy.TRANSIENT_LOCAL,
|
||||
)
|
||||
subscription = node.create_subscription(
|
||||
Path, "initial_path", received.append, path_qos
|
||||
)
|
||||
odom_publisher = node.create_publisher(
|
||||
Odometry, "body_pose", qos_profile_sensor_data
|
||||
)
|
||||
executor = SingleThreadedExecutor(context=self.context)
|
||||
executor.add_node(node)
|
||||
try:
|
||||
deadline = time.monotonic() + 0.4
|
||||
while time.monotonic() < deadline:
|
||||
executor.spin_once(timeout_sec=0.05)
|
||||
self.assertEqual(received, [])
|
||||
|
||||
deadline = time.monotonic() + 3.0
|
||||
while time.monotonic() < deadline and not received:
|
||||
odom_publisher.publish(Odometry())
|
||||
executor.spin_once(timeout_sec=0.05)
|
||||
self.assertEqual(len(received), 1)
|
||||
self.assertEqual(len(received[0].poses), 2)
|
||||
self.assertEqual(received[0].header.frame_id, "world")
|
||||
self.assertAlmostEqual(received[0].poses[-1].pose.position.x, 1.0)
|
||||
self.assertAlmostEqual(received[0].poses[-1].pose.position.z, 0.5)
|
||||
|
||||
deadline = time.monotonic() + 0.5
|
||||
while time.monotonic() < deadline:
|
||||
odom_publisher.publish(Odometry())
|
||||
executor.spin_once(timeout_sec=0.05)
|
||||
self.assertEqual(len(received), 1)
|
||||
finally:
|
||||
executor.remove_node(node)
|
||||
executor.shutdown()
|
||||
node.destroy_subscription(subscription)
|
||||
node.destroy_publisher(odom_publisher)
|
||||
node.destroy_node()
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Unit tests for reference-path configuration and message construction."""
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
SCRIPT = os.path.abspath(
|
||||
os.path.join(os.path.dirname(__file__), "..", "scripts", "reference_path_publisher.py")
|
||||
)
|
||||
SPEC = importlib.util.spec_from_file_location("reference_path_publisher", SCRIPT)
|
||||
MODULE = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(MODULE)
|
||||
|
||||
|
||||
def test_parse_waypoints_accepts_xyz_triples():
|
||||
points = MODULE.parse_waypoints([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
|
||||
assert points == [(0.0, 1.0, 2.0), (3.0, 4.0, 5.0)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"values",
|
||||
[[], [0.0, 1.0, 2.0], [0.0] * 7, [0.0, 1.0, 2.0, float("nan"), 4.0, 5.0]],
|
||||
)
|
||||
def test_parse_waypoints_rejects_invalid_values(values):
|
||||
with pytest.raises(ValueError):
|
||||
MODULE.parse_waypoints(values)
|
||||
|
||||
|
||||
def test_build_path_message_preserves_coordinates_and_frame():
|
||||
from builtin_interfaces.msg import Time
|
||||
|
||||
message = MODULE.build_path_message(
|
||||
[(-5.5, 5.5, 0.1), (-5.5, 4.5, 0.3)], "world", Time(sec=12)
|
||||
)
|
||||
assert message.header.frame_id == "world"
|
||||
assert message.header.stamp.sec == 12
|
||||
assert len(message.poses) == 2
|
||||
assert message.poses[-1].pose.position.y == pytest.approx(4.5)
|
||||
assert message.poses[-1].pose.position.z == pytest.approx(0.3)
|
||||
assert message.poses[-1].pose.orientation.w == pytest.approx(1.0)
|
||||
@@ -0,0 +1,126 @@
|
||||
#include <limits>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <plan_manage/reference_path_utils.h>
|
||||
#include <plan_manage/polyline_trajectory_utils.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
geometry_msgs::msg::PoseStamped pose(double x, double y, double z)
|
||||
{
|
||||
geometry_msgs::msg::PoseStamped result;
|
||||
result.pose.position.x = x;
|
||||
result.pose.position.y = y;
|
||||
result.pose.position.z = z;
|
||||
result.pose.orientation.w = 1.0;
|
||||
return result;
|
||||
}
|
||||
|
||||
TEST(ReferencePathUtils, RejectsEmptyAndSinglePointPaths)
|
||||
{
|
||||
std::vector<Eigen::Vector3d> waypoints;
|
||||
std::string error;
|
||||
nav_msgs::msg::Path path;
|
||||
EXPECT_FALSE(scan_planner::prepareReferenceWaypoints(path, 0.4, 0.5, waypoints, &error));
|
||||
EXPECT_TRUE(waypoints.empty());
|
||||
|
||||
path.poses.push_back(pose(0.0, 0.0, 0.0));
|
||||
EXPECT_FALSE(scan_planner::prepareReferenceWaypoints(path, 0.4, 0.5, waypoints, &error));
|
||||
EXPECT_TRUE(waypoints.empty());
|
||||
}
|
||||
|
||||
TEST(ReferencePathUtils, DownsamplesInThreeDimensionsAndPreservesFinalPoint)
|
||||
{
|
||||
nav_msgs::msg::Path path;
|
||||
path.poses = {
|
||||
pose(0.0, 0.0, 0.1),
|
||||
pose(0.0, 0.0, 0.1),
|
||||
pose(0.2, 0.0, 0.1),
|
||||
pose(0.4, 0.0, 0.1),
|
||||
pose(0.6, 0.0, 0.1),
|
||||
pose(0.7, 0.0, 0.1),
|
||||
};
|
||||
|
||||
std::vector<Eigen::Vector3d> waypoints;
|
||||
ASSERT_TRUE(scan_planner::prepareReferenceWaypoints(path, 0.4, 0.5, waypoints));
|
||||
ASSERT_EQ(waypoints.size(), 3u);
|
||||
EXPECT_NEAR(waypoints.front().z(), 0.5, 1e-9);
|
||||
EXPECT_NEAR(waypoints[1].x(), 0.6, 1e-9);
|
||||
EXPECT_NEAR(waypoints.back().x(), 0.7, 1e-9);
|
||||
EXPECT_NEAR(waypoints.back().z(), 0.5, 1e-9);
|
||||
|
||||
path.poses = {pose(1.0, 2.0, 0.0), pose(1.0, 2.0, 0.6)};
|
||||
ASSERT_TRUE(scan_planner::prepareReferenceWaypoints(path, 0.4, 0.5, waypoints));
|
||||
ASSERT_EQ(waypoints.size(), 2u);
|
||||
EXPECT_NEAR(waypoints.back().z(), 1.0, 1e-9);
|
||||
}
|
||||
|
||||
TEST(ReferencePathUtils, RejectsNonFiniteCoordinates)
|
||||
{
|
||||
nav_msgs::msg::Path path;
|
||||
path.poses = {
|
||||
pose(0.0, 0.0, 0.0),
|
||||
pose(std::numeric_limits<double>::quiet_NaN(), 1.0, 0.0),
|
||||
};
|
||||
|
||||
std::vector<Eigen::Vector3d> waypoints;
|
||||
EXPECT_FALSE(scan_planner::prepareReferenceWaypoints(path, 0.4, 0.5, waypoints));
|
||||
EXPECT_TRUE(waypoints.empty());
|
||||
}
|
||||
|
||||
TEST(ReferencePathUtils, SimplifiesPolylineWithinToleranceAndKeepsCorners)
|
||||
{
|
||||
nav_msgs::msg::Path path;
|
||||
path.poses = {
|
||||
pose(0.0, 0.0, 0.0),
|
||||
pose(1.0, 0.02, 0.0),
|
||||
pose(2.0, -0.02, 0.0),
|
||||
pose(3.0, 0.0, 0.0),
|
||||
pose(3.0, 1.0, 0.0),
|
||||
pose(3.0, 2.0, 0.0),
|
||||
};
|
||||
|
||||
std::vector<Eigen::Vector3d> waypoints;
|
||||
ASSERT_TRUE(scan_planner::prepareReferenceWaypoints(
|
||||
path, 0.4, 0.0, waypoints, nullptr, 0.1));
|
||||
ASSERT_EQ(waypoints.size(), 3u);
|
||||
EXPECT_NEAR(waypoints.front().x(), 0.0, 1e-9);
|
||||
EXPECT_NEAR(waypoints[1].x(), 3.0, 1e-9);
|
||||
EXPECT_NEAR(waypoints[1].y(), 0.0, 1e-9);
|
||||
EXPECT_NEAR(waypoints.back().y(), 2.0, 1e-9);
|
||||
EXPECT_NEAR(waypoints.back().z(), 0.4, 1e-9);
|
||||
}
|
||||
|
||||
TEST(ReferencePathUtils, PiecewiseLinearTrajectoryStaysOnPolyline)
|
||||
{
|
||||
const std::vector<Eigen::Vector3d> points = {
|
||||
{0.0, 0.0, 0.0},
|
||||
{2.0, 0.0, 0.5},
|
||||
{2.0, 3.0, 1.0},
|
||||
};
|
||||
PolynomialTraj trajectory;
|
||||
std::string error;
|
||||
ASSERT_TRUE(scan_planner::makePiecewiseLinearTrajectory(
|
||||
points, 1.0, trajectory, &error)) << error;
|
||||
|
||||
const double first_duration = (points[1] - points[0]).norm();
|
||||
EXPECT_TRUE(trajectory.evaluate(0.0).isApprox(points[0], 1e-9));
|
||||
EXPECT_TRUE(trajectory.evaluate(first_duration).isApprox(points[1], 1e-6));
|
||||
EXPECT_TRUE(trajectory.evaluate(trajectory.getTimeSum()).isApprox(points[2], 1e-6));
|
||||
|
||||
const Eigen::Vector3d first_midpoint = trajectory.evaluate(0.5 * first_duration);
|
||||
EXPECT_TRUE(first_midpoint.isApprox(0.5 * (points[0] + points[1]), 1e-9));
|
||||
}
|
||||
|
||||
TEST(ReferencePathUtils, PiecewiseLinearTrajectoryRejectsInvalidInput)
|
||||
{
|
||||
PolynomialTraj trajectory;
|
||||
EXPECT_FALSE(scan_planner::makePiecewiseLinearTrajectory(
|
||||
{{0.0, 0.0, 0.0}}, 1.0, trajectory));
|
||||
EXPECT_FALSE(scan_planner::makePiecewiseLinearTrajectory(
|
||||
{{0.0, 0.0, 0.0}, {1.0, 0.0, 0.0}}, 0.0, trajectory));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Verify that the flat ROS 2 waypoint array is accepted at startup."""
|
||||
|
||||
import os
|
||||
|
||||
import launch
|
||||
import launch_ros.actions
|
||||
import launch_testing.actions
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.launch_test
|
||||
def generate_test_description():
|
||||
root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
||||
planner = launch_ros.actions.Node(
|
||||
package="scan_planner",
|
||||
executable="scan_planner_node",
|
||||
name="scan_planner_node",
|
||||
parameters=[
|
||||
os.path.join(root, "config", "planner.yaml"),
|
||||
os.path.join(root, "config", "keypoints.example.yaml"),
|
||||
],
|
||||
output="screen",
|
||||
)
|
||||
return (
|
||||
launch.LaunchDescription([planner, launch_testing.actions.ReadyToTest()]),
|
||||
{"planner": planner},
|
||||
)
|
||||
|
||||
|
||||
class TestWaypointParameters:
|
||||
def test_process_starts(self, proc_info, planner):
|
||||
proc_info.assertWaitForStartup(process=planner, timeout=15)
|
||||
@@ -0,0 +1,17 @@
|
||||
cmake_minimum_required(VERSION 3.8)
|
||||
project(scan_planner_msgs)
|
||||
|
||||
find_package(ament_cmake REQUIRED)
|
||||
find_package(builtin_interfaces REQUIRED)
|
||||
find_package(geometry_msgs REQUIRED)
|
||||
find_package(rosidl_default_generators REQUIRED)
|
||||
find_package(std_msgs REQUIRED)
|
||||
|
||||
rosidl_generate_interfaces(${PROJECT_NAME}
|
||||
"msg/Bspline.msg"
|
||||
"msg/DataDisp.msg"
|
||||
DEPENDENCIES builtin_interfaces geometry_msgs std_msgs
|
||||
)
|
||||
|
||||
ament_export_dependencies(rosidl_default_runtime)
|
||||
ament_package()
|
||||
@@ -0,0 +1,9 @@
|
||||
int32 order
|
||||
int64 traj_id
|
||||
builtin_interfaces/Time start_time
|
||||
|
||||
float64[] knots
|
||||
geometry_msgs/Point[] pos_pts
|
||||
|
||||
float64[] yaw_pts
|
||||
float64 yaw_dt
|
||||
@@ -0,0 +1,7 @@
|
||||
std_msgs/Header header
|
||||
|
||||
float64 a
|
||||
float64 b
|
||||
float64 c
|
||||
float64 d
|
||||
float64 e
|
||||
@@ -0,0 +1,20 @@
|
||||
<?xml version="1.0"?>
|
||||
<package format="3">
|
||||
<name>scan_planner_msgs</name>
|
||||
<version>0.1.0</version>
|
||||
<description>ROS 2 interfaces used by SCAN-Planner.</description>
|
||||
<maintainer email="[email protected]">SCAN-Planner maintainers</maintainer>
|
||||
<license>Apache-2.0</license>
|
||||
|
||||
<buildtool_depend>ament_cmake</buildtool_depend>
|
||||
<buildtool_depend>rosidl_default_generators</buildtool_depend>
|
||||
<depend>builtin_interfaces</depend>
|
||||
<depend>geometry_msgs</depend>
|
||||
<depend>std_msgs</depend>
|
||||
<exec_depend>rosidl_default_runtime</exec_depend>
|
||||
<member_of_group>rosidl_interface_packages</member_of_group>
|
||||
|
||||
<export>
|
||||
<build_type>ament_cmake</build_type>
|
||||
</export>
|
||||
</package>
|
||||
@@ -0,0 +1,22 @@
|
||||
cmake_minimum_required(VERSION 3.8)
|
||||
project(step_blocker)
|
||||
|
||||
# 纯 Python 节点,但用 ament_cmake 安装脚本。
|
||||
#
|
||||
# 2026-10-19 实测:用 ament_python 装完,ros2 pkg / ros2 launch 报 "package not found",
|
||||
# 因为 install/<pkg>/share/<pkg>/hook/ 里只有 pythonpath.*,缺 ament_prefix_path.*,
|
||||
# 前缀没进 AMENT_PREFIX_PATH。改成 ament_cmake 由 ament_package() 生成环境钩子后正常,
|
||||
# 且不再依赖 colcon 的 ament_python 实现(不同 colcon 版本行为不一致)。
|
||||
#
|
||||
# 注意:install(PROGRAMS) 需要脚本带 shebang 且有可执行位。
|
||||
|
||||
find_package(ament_cmake REQUIRED)
|
||||
|
||||
install(PROGRAMS step_blocker/step_blocker_node.py
|
||||
DESTINATION lib/${PROJECT_NAME}
|
||||
RENAME step_blocker)
|
||||
|
||||
install(DIRECTORY config launch
|
||||
DESTINATION share/${PROJECT_NAME})
|
||||
|
||||
ament_package()
|
||||
@@ -0,0 +1,31 @@
|
||||
# 台阶封堵节点参数。
|
||||
#
|
||||
# regions 是**世界系**(Point-LIO 的 camera_init)下的矩形,格式:
|
||||
# "xmin,xmax,ymin,ymax" 一块
|
||||
# "xmin,xmax,ymin,ymax; xmin,... " 多块,分号分隔
|
||||
#
|
||||
# 怎么标:
|
||||
# 1) 起驱动 + LIO,在 RViz 里看 /cloud_registered;
|
||||
# 2) 用 "Publish Point" 工具点台阶区域的**两个对角**,读 /clicked_point 的 x/y;
|
||||
# 3) 把两组 x/y 填进来(顺序无所谓,节点会自动排序)。
|
||||
#
|
||||
# 区域要**盖住台阶的整个投影**,稍微外扩 10~20 cm,避免边缘漏过去。
|
||||
# 墙从 z_min 一直填到 wall_height,所以斜坡不要落进矩形里。
|
||||
#
|
||||
# 验证:ros2 topic echo /cloud_registered_for_scan --once --no-arr
|
||||
# 台阶区域应出现密集点阵;也可在 RViz 里直接看这堵墙。
|
||||
|
||||
step_blocker:
|
||||
ros__parameters:
|
||||
input_topic: /cloud_registered
|
||||
output_topic: /cloud_registered_for_scan
|
||||
|
||||
# ⚠️ 默认空 = 纯透传(不封堵)。先填上你们场地的台阶矩形。
|
||||
regions: ""
|
||||
|
||||
wall_height: 2.0 # 墙的高度 [m],要高于车体 + 规划余量
|
||||
cell_size: 0.10 # 点阵间距 [m];越小越密、越耗 CPU
|
||||
z_min: 0.0 # 墙的起始高度 [m]
|
||||
|
||||
# 输入点云超过这个数就等间隔抽稀,避免 Python 端跟不上
|
||||
max_input_points: 200000
|
||||
@@ -0,0 +1,53 @@
|
||||
"""启动台阶封堵节点。
|
||||
|
||||
ros2 launch step_blocker step_blocker.launch.py
|
||||
# 临时换区域,不改 yaml
|
||||
ros2 launch step_blocker step_blocker.launch.py regions:="1.0,2.5,-1.0,1.0"
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from ament_index_python.packages import get_package_share_directory
|
||||
from launch import LaunchDescription
|
||||
from launch.actions import DeclareLaunchArgument
|
||||
from launch.substitutions import LaunchConfiguration
|
||||
from launch_ros.actions import Node
|
||||
|
||||
|
||||
def _yaml_default(params_file, name, fallback=''):
|
||||
try:
|
||||
import yaml
|
||||
with open(params_file, 'r') as f:
|
||||
p = yaml.safe_load(f)['step_blocker']['ros__parameters']
|
||||
return str(p[name])
|
||||
except Exception:
|
||||
return fallback
|
||||
|
||||
|
||||
def generate_launch_description():
|
||||
share = get_package_share_directory('step_blocker')
|
||||
default_params = os.path.join(share, 'config', 'step_blocker.yaml')
|
||||
|
||||
declared = [
|
||||
DeclareLaunchArgument(
|
||||
'params_file', default_value=default_params,
|
||||
description='参数文件(install 里是拷贝,改了 src 那份要重建;'
|
||||
'或把这里指向 src)'),
|
||||
DeclareLaunchArgument(
|
||||
'regions',
|
||||
default_value=_yaml_default(default_params, 'regions', ''),
|
||||
description='台阶矩形,世界系 "xmin,xmax,ymin,ymax[; ...]"'),
|
||||
]
|
||||
|
||||
node = Node(
|
||||
package='step_blocker',
|
||||
executable='step_blocker',
|
||||
name='step_blocker',
|
||||
output='screen',
|
||||
parameters=[
|
||||
LaunchConfiguration('params_file'),
|
||||
{'regions': LaunchConfiguration('regions')},
|
||||
],
|
||||
)
|
||||
|
||||
return LaunchDescription(declared + [node])
|
||||
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0"?>
|
||||
<package format="3">
|
||||
<name>step_blocker</name>
|
||||
<version>0.1.0</version>
|
||||
<description>Block the stair region in the input point cloud so SCAN only plans via the ramp.</description>
|
||||
<maintainer email="[email protected]">kevin</maintainer>
|
||||
<license>Apache-2.0</license>
|
||||
|
||||
<buildtool_depend>ament_cmake</buildtool_depend>
|
||||
|
||||
<exec_depend>rclpy</exec_depend>
|
||||
<exec_depend>sensor_msgs</exec_depend>
|
||||
<exec_depend>sensor_msgs_py</exec_depend>
|
||||
<exec_depend>python3-numpy</exec_depend>
|
||||
<exec_depend>launch</exec_depend>
|
||||
<exec_depend>launch_ros</exec_depend>
|
||||
<exec_depend>ament_index_python</exec_depend>
|
||||
|
||||
<export>
|
||||
<build_type>ament_cmake</build_type>
|
||||
</export>
|
||||
</package>
|
||||
@@ -0,0 +1,146 @@
|
||||
#!/usr/bin/env python3
|
||||
"""把场地的台阶区域“堵死”:输入点云 → 输出点云。
|
||||
|
||||
用途:SCAN 的碰撞检测是单点判定(``grid_map.h:371``),它分不清“斜坡”和“台阶”,
|
||||
只要 3D 体素连通就会规划过去。轮式车爬不上台阶,所以这里在点云进入 SCAN 之前,
|
||||
把台阶所在的矩形区域填成一堵从地面到 ``wall_height`` 的实心点阵墙。
|
||||
|
||||
- 区域外的点原样透传;
|
||||
- 区域内**额外**插入规则网格点(不删除原点),保证墙是实心的、不会因点云稀疏漏洞;
|
||||
- 输出只保留 x/y/z 三个字段(SCAN 的 grid_map 只用 xyz)。
|
||||
|
||||
区域在**世界系**(Point-LIO 的 camera_init)里定义。因为起点固定、台阶固定,
|
||||
标一次即可;若以后换场地,改 yaml 里的 ``regions``。
|
||||
|
||||
regions 格式(字符串,避免 ROS 2 不支持二维数组参数)::
|
||||
|
||||
regions: "1.0,2.5,-1.0,1.0; 5.0,6.0,0.0,2.0"
|
||||
└ xmin,xmax,ymin,ymax ┘ └ 第二块 ┘
|
||||
|
||||
查看当前点云坐标来标区域::
|
||||
|
||||
ros2 topic echo /cloud_registered --once --no-arr | head -20
|
||||
# 或在 RViz 里用 Publish Point 工具点台阶的两个角,读 /clicked_point
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
import rclpy
|
||||
from rclpy.node import Node
|
||||
from rclpy.qos import qos_profile_sensor_data
|
||||
from sensor_msgs.msg import PointCloud2
|
||||
from sensor_msgs_py import point_cloud2 as pc2
|
||||
|
||||
|
||||
def _parse_regions(text):
|
||||
"""'x0,x1,y0,y1; x0,x1,y0,y1' -> [(x0,x1,y0,y1), ...]"""
|
||||
regions = []
|
||||
if not text or not text.strip():
|
||||
return regions
|
||||
for block in text.split(';'):
|
||||
block = block.strip()
|
||||
if not block:
|
||||
continue
|
||||
parts = [p.strip() for p in block.split(',')]
|
||||
if len(parts) != 4:
|
||||
raise ValueError(
|
||||
f"Bad region '{block}': need xmin,xmax,ymin,ymax (4 numbers)")
|
||||
x0, x1, y0, y1 = (float(p) for p in parts)
|
||||
if x1 < x0:
|
||||
x0, x1 = x1, x0
|
||||
if y1 < y0:
|
||||
y0, y1 = y1, y0
|
||||
regions.append((x0, x1, y0, y1))
|
||||
return regions
|
||||
|
||||
|
||||
class StepBlocker(Node):
|
||||
def __init__(self):
|
||||
super().__init__('step_blocker')
|
||||
|
||||
self.declare_parameter('input_topic', '/cloud_registered')
|
||||
self.declare_parameter('output_topic', '/cloud_registered_for_scan')
|
||||
self.declare_parameter('regions', '')
|
||||
self.declare_parameter('wall_height', 2.0)
|
||||
self.declare_parameter('cell_size', 0.10)
|
||||
self.declare_parameter('z_min', 0.0)
|
||||
self.declare_parameter('max_input_points', 200000)
|
||||
|
||||
in_topic = self.get_parameter('input_topic').value
|
||||
out_topic = self.get_parameter('output_topic').value
|
||||
self.wall_height = float(self.get_parameter('wall_height').value)
|
||||
self.cell = float(self.get_parameter('cell_size').value)
|
||||
self.z_min = float(self.get_parameter('z_min').value)
|
||||
self.max_pts = int(self.get_parameter('max_input_points').value)
|
||||
self.regions = _parse_regions(self.get_parameter('regions').value)
|
||||
|
||||
self._grids = self._build_walls()
|
||||
total = sum(g.shape[0] for g in self._grids)
|
||||
if self.regions:
|
||||
self.get_logger().info(
|
||||
f'step_blocker: {len(self.regions)} region(s), '
|
||||
f'{total} wall points, wall_height={self.wall_height} m')
|
||||
for i, (x0, x1, y0, y1) in enumerate(self.regions, 1):
|
||||
self.get_logger().info(
|
||||
f' region {i}: x[{x0}, {x1}] y[{y0}, {y1}]')
|
||||
else:
|
||||
self.get_logger().warn(
|
||||
'step_blocker: regions is empty -> pure passthrough. '
|
||||
'Set config/step_blocker.yaml before use.')
|
||||
|
||||
self.pub = self.create_publisher(PointCloud2, out_topic,
|
||||
qos_profile_sensor_data)
|
||||
self.sub = self.create_subscription(
|
||||
PointCloud2, in_topic, self._cb, qos_profile_sensor_data)
|
||||
self.get_logger().info(f'{in_topic} -> {out_topic}')
|
||||
|
||||
def _build_walls(self):
|
||||
"""预生成每块区域的规则点阵,运行时只做拼接。"""
|
||||
grids = []
|
||||
if self.cell <= 0.0:
|
||||
raise ValueError('cell_size must be > 0')
|
||||
for (x0, x1, y0, y1) in self.regions:
|
||||
xs = np.arange(x0, x1 + 1e-9, self.cell, dtype=np.float32)
|
||||
ys = np.arange(y0, y1 + 1e-9, self.cell, dtype=np.float32)
|
||||
zs = np.arange(self.z_min, self.wall_height + 1e-9,
|
||||
self.cell, dtype=np.float32)
|
||||
if xs.size == 0 or ys.size == 0 or zs.size == 0:
|
||||
continue
|
||||
gx, gy, gz = np.meshgrid(xs, ys, zs, indexing='ij')
|
||||
grids.append(np.stack(
|
||||
[gx.reshape(-1), gy.reshape(-1), gz.reshape(-1)], axis=1))
|
||||
return grids
|
||||
|
||||
def _cb(self, msg):
|
||||
raw = pc2.read_points(msg, field_names=('x', 'y', 'z'), skip_nans=True)
|
||||
pts = np.asarray(list(raw), dtype=np.float32)
|
||||
if pts.size == 0:
|
||||
pts = np.zeros((0, 3), dtype=np.float32)
|
||||
elif pts.ndim == 1:
|
||||
pts = pts.reshape(-1, 3)
|
||||
|
||||
if pts.shape[0] > self.max_pts:
|
||||
step = max(1, pts.shape[0] // self.max_pts)
|
||||
pts = pts[::step]
|
||||
|
||||
if self._grids:
|
||||
pts = np.vstack([pts] + self._grids)
|
||||
|
||||
out = pc2.create_cloud_xyz32(msg.header, pts)
|
||||
self.pub.publish(out)
|
||||
|
||||
|
||||
def main(args=None):
|
||||
rclpy.init(args=args)
|
||||
node = StepBlocker()
|
||||
try:
|
||||
rclpy.spin(node)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
node.destroy_node()
|
||||
if rclpy.ok():
|
||||
rclpy.shutdown()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,28 @@
|
||||
cmake_minimum_required(VERSION 3.8)
|
||||
project(traj_utils)
|
||||
|
||||
if(NOT CMAKE_CXX_STANDARD)
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
endif()
|
||||
add_compile_options(-Wall -Wextra -Wpedantic)
|
||||
|
||||
find_package(ament_cmake REQUIRED)
|
||||
find_package(bspline_opt REQUIRED)
|
||||
find_package(Eigen3 REQUIRED)
|
||||
find_package(rclcpp REQUIRED)
|
||||
find_package(std_msgs REQUIRED)
|
||||
find_package(visualization_msgs REQUIRED)
|
||||
|
||||
add_library(traj_utils src/planning_visualization.cpp src/polynomial_traj.cpp)
|
||||
target_include_directories(traj_utils PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>)
|
||||
ament_target_dependencies(traj_utils bspline_opt rclcpp std_msgs visualization_msgs)
|
||||
target_link_libraries(traj_utils Eigen3::Eigen)
|
||||
|
||||
install(TARGETS traj_utils EXPORT export_traj_utils
|
||||
ARCHIVE DESTINATION lib LIBRARY DESTINATION lib RUNTIME DESTINATION bin)
|
||||
install(DIRECTORY include/ DESTINATION include)
|
||||
ament_export_targets(export_traj_utils HAS_LIBRARY_TARGET)
|
||||
ament_export_dependencies(bspline_opt Eigen3 rclcpp std_msgs visualization_msgs)
|
||||
ament_package()
|
||||
@@ -0,0 +1,57 @@
|
||||
#ifndef _PLANNING_VISUALIZATION_H_
|
||||
#define _PLANNING_VISUALIZATION_H_
|
||||
|
||||
#include <Eigen/Eigen>
|
||||
#include <algorithm>
|
||||
#include <bspline_opt/uniform_bspline.h>
|
||||
#include <geometry_msgs/msg/point.hpp>
|
||||
#include <iostream>
|
||||
#include <traj_utils/polynomial_traj.h>
|
||||
#include <rclcpp/rclcpp.hpp>
|
||||
#include <vector>
|
||||
#include <visualization_msgs/msg/marker.hpp>
|
||||
#include <visualization_msgs/msg/marker_array.hpp>
|
||||
#include <stdlib.h>
|
||||
|
||||
using std::vector;
|
||||
namespace scan_planner
|
||||
{
|
||||
class PlanningVisualization
|
||||
{
|
||||
private:
|
||||
using MarkerPublisher = rclcpp::Publisher<visualization_msgs::msg::Marker>;
|
||||
using MarkerArrayPublisher = rclcpp::Publisher<visualization_msgs::msg::MarkerArray>;
|
||||
rclcpp::Node *node_{nullptr};
|
||||
|
||||
MarkerPublisher::SharedPtr goal_point_pub;
|
||||
MarkerPublisher::SharedPtr global_list_pub;
|
||||
MarkerPublisher::SharedPtr init_list_pub;
|
||||
MarkerPublisher::SharedPtr optimal_list_pub;
|
||||
MarkerPublisher::SharedPtr a_star_list_pub;
|
||||
|
||||
public:
|
||||
PlanningVisualization(/* args */) {}
|
||||
~PlanningVisualization() {}
|
||||
explicit PlanningVisualization(rclcpp::Node *node);
|
||||
|
||||
typedef std::shared_ptr<PlanningVisualization> Ptr;
|
||||
|
||||
void displayMarkerList(const MarkerPublisher::SharedPtr &pub, const vector<Eigen::Vector3d> &list, double scale,
|
||||
Eigen::Vector4d color, int id);
|
||||
void generatePathDisplayArray(visualization_msgs::msg::MarkerArray &array,
|
||||
const vector<Eigen::Vector3d> &list, double scale, Eigen::Vector4d color, int id);
|
||||
void generateArrowDisplayArray(visualization_msgs::msg::MarkerArray &array,
|
||||
const vector<Eigen::Vector3d> &list, double scale, Eigen::Vector4d color, int id);
|
||||
void displayGoalPoint(Eigen::Vector3d goal_point, Eigen::Vector4d color, const double scale, int id);
|
||||
void displayGlobalPathList(vector<Eigen::Vector3d> global_pts, const double scale, int id);
|
||||
void displayInitPathList(vector<Eigen::Vector3d> init_pts, const double scale, int id);
|
||||
void displayOptimalList(Eigen::MatrixXd optimal_pts, int id);
|
||||
void displayOptimalTraj(UniformBspline position_traj, int id);
|
||||
void displayAStarList(std::vector<std::vector<Eigen::Vector3d>> a_star_paths, int id);
|
||||
void displayArrowList(const MarkerArrayPublisher::SharedPtr &pub, const vector<Eigen::Vector3d> &list,
|
||||
double scale, Eigen::Vector4d color, int id);
|
||||
// void displayIntermediateState(ros::Publisher& intermediate_pub, scan_planner::BsplineOptimizer::Ptr optimizer, double sleep_time, const int start_iteration);
|
||||
// void displayNewArrow(ros::Publisher& guide_vector_pub, scan_planner::BsplineOptimizer::Ptr optimizer);
|
||||
};
|
||||
} // namespace scan_planner
|
||||
#endif
|
||||
@@ -0,0 +1,336 @@
|
||||
#ifndef _POLYNOMIAL_TRAJ_H
|
||||
#define _POLYNOMIAL_TRAJ_H
|
||||
|
||||
#include <Eigen/Eigen>
|
||||
#include <vector>
|
||||
|
||||
using std::vector;
|
||||
|
||||
class PolynomialTraj
|
||||
{
|
||||
private:
|
||||
vector<double> times; // time of each segment
|
||||
vector<vector<double>> cxs; // coefficient of x of each segment, from n-1 -> 0
|
||||
vector<vector<double>> cys; // coefficient of y of each segment
|
||||
vector<vector<double>> czs; // coefficient of z of each segment
|
||||
|
||||
double time_sum;
|
||||
int num_seg;
|
||||
|
||||
/* evaluation */
|
||||
vector<Eigen::Vector3d> traj_vec3d;
|
||||
double length;
|
||||
|
||||
public:
|
||||
PolynomialTraj(/* args */)
|
||||
{
|
||||
}
|
||||
~PolynomialTraj()
|
||||
{
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
times.clear(), cxs.clear(), cys.clear(), czs.clear();
|
||||
time_sum = 0.0, num_seg = 0;
|
||||
}
|
||||
|
||||
void addSegment(vector<double> cx, vector<double> cy, vector<double> cz, double t)
|
||||
{
|
||||
cxs.push_back(cx), cys.push_back(cy), czs.push_back(cz), times.push_back(t);
|
||||
}
|
||||
|
||||
void init()
|
||||
{
|
||||
num_seg = times.size();
|
||||
time_sum = 0.0;
|
||||
for (int i = 0; i < times.size(); ++i)
|
||||
{
|
||||
time_sum += times[i];
|
||||
}
|
||||
}
|
||||
|
||||
vector<double> getTimes()
|
||||
{
|
||||
return times;
|
||||
}
|
||||
|
||||
vector<vector<double>> getCoef(int axis)
|
||||
{
|
||||
switch (axis)
|
||||
{
|
||||
case 0:
|
||||
return cxs;
|
||||
case 1:
|
||||
return cys;
|
||||
case 2:
|
||||
return czs;
|
||||
default:
|
||||
std::cout << "\033[31mIllegal axis!\033[0m" << std::endl;
|
||||
}
|
||||
|
||||
vector<vector<double>> empty;
|
||||
return empty;
|
||||
}
|
||||
|
||||
Eigen::Vector3d evaluate(double t)
|
||||
{
|
||||
/* detetrmine segment num */
|
||||
int idx = 0;
|
||||
while (times[idx] + 1e-4 < t)
|
||||
{
|
||||
t -= times[idx];
|
||||
++idx;
|
||||
}
|
||||
|
||||
/* evaluation */
|
||||
int order = cxs[idx].size();
|
||||
Eigen::VectorXd cx(order), cy(order), cz(order), tv(order);
|
||||
for (int i = 0; i < order; ++i)
|
||||
{
|
||||
cx(i) = cxs[idx][i], cy(i) = cys[idx][i], cz(i) = czs[idx][i];
|
||||
tv(order - 1 - i) = std::pow(t, double(i));
|
||||
}
|
||||
|
||||
Eigen::Vector3d pt;
|
||||
pt(0) = tv.dot(cx), pt(1) = tv.dot(cy), pt(2) = tv.dot(cz);
|
||||
return pt;
|
||||
}
|
||||
|
||||
Eigen::Vector3d evaluateVel(double t)
|
||||
{
|
||||
/* detetrmine segment num */
|
||||
int idx = 0;
|
||||
while (times[idx] + 1e-4 < t)
|
||||
{
|
||||
t -= times[idx];
|
||||
++idx;
|
||||
}
|
||||
|
||||
/* evaluation */
|
||||
int order = cxs[idx].size();
|
||||
Eigen::VectorXd vx(order - 1), vy(order - 1), vz(order - 1);
|
||||
|
||||
/* coef of vel */
|
||||
for (int i = 0; i < order - 1; ++i)
|
||||
{
|
||||
vx(i) = double(i + 1) * cxs[idx][order - 2 - i];
|
||||
vy(i) = double(i + 1) * cys[idx][order - 2 - i];
|
||||
vz(i) = double(i + 1) * czs[idx][order - 2 - i];
|
||||
}
|
||||
double ts = t;
|
||||
Eigen::VectorXd tv(order - 1);
|
||||
for (int i = 0; i < order - 1; ++i)
|
||||
tv(i) = pow(ts, i);
|
||||
|
||||
Eigen::Vector3d vel;
|
||||
vel(0) = tv.dot(vx), vel(1) = tv.dot(vy), vel(2) = tv.dot(vz);
|
||||
return vel;
|
||||
}
|
||||
|
||||
Eigen::Vector3d evaluateAcc(double t)
|
||||
{
|
||||
/* detetrmine segment num */
|
||||
int idx = 0;
|
||||
while (times[idx] + 1e-4 < t)
|
||||
{
|
||||
t -= times[idx];
|
||||
++idx;
|
||||
}
|
||||
|
||||
/* evaluation */
|
||||
int order = cxs[idx].size();
|
||||
Eigen::VectorXd ax(order - 2), ay(order - 2), az(order - 2);
|
||||
|
||||
/* coef of vel */
|
||||
for (int i = 0; i < order - 2; ++i)
|
||||
{
|
||||
ax(i) = double((i + 2) * (i + 1)) * cxs[idx][order - 3 - i];
|
||||
ay(i) = double((i + 2) * (i + 1)) * cys[idx][order - 3 - i];
|
||||
az(i) = double((i + 2) * (i + 1)) * czs[idx][order - 3 - i];
|
||||
}
|
||||
double ts = t;
|
||||
Eigen::VectorXd tv(order - 2);
|
||||
for (int i = 0; i < order - 2; ++i)
|
||||
tv(i) = pow(ts, i);
|
||||
|
||||
Eigen::Vector3d acc;
|
||||
acc(0) = tv.dot(ax), acc(1) = tv.dot(ay), acc(2) = tv.dot(az);
|
||||
return acc;
|
||||
}
|
||||
|
||||
/* for evaluating traj, should be called in sequence!!! */
|
||||
double getTimeSum()
|
||||
{
|
||||
return this->time_sum;
|
||||
}
|
||||
|
||||
vector<Eigen::Vector3d> getTraj()
|
||||
{
|
||||
double eval_t = 0.0;
|
||||
traj_vec3d.clear();
|
||||
while (eval_t < time_sum)
|
||||
{
|
||||
Eigen::Vector3d pt = evaluate(eval_t);
|
||||
traj_vec3d.push_back(pt);
|
||||
eval_t += 0.01;
|
||||
}
|
||||
return traj_vec3d;
|
||||
}
|
||||
|
||||
double getLength()
|
||||
{
|
||||
length = 0.0;
|
||||
|
||||
Eigen::Vector3d p_l = traj_vec3d[0], p_n;
|
||||
for (int i = 1; i < traj_vec3d.size(); ++i)
|
||||
{
|
||||
p_n = traj_vec3d[i];
|
||||
length += (p_n - p_l).norm();
|
||||
p_l = p_n;
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
double getMeanVel()
|
||||
{
|
||||
double mean_vel = length / time_sum;
|
||||
}
|
||||
|
||||
double getAccCost()
|
||||
{
|
||||
double cost = 0.0;
|
||||
int order = cxs[0].size();
|
||||
|
||||
for (int s = 0; s < times.size(); ++s)
|
||||
{
|
||||
Eigen::Vector3d um;
|
||||
um(0) = 2 * cxs[s][order - 3], um(1) = 2 * cys[s][order - 3], um(2) = 2 * czs[s][order - 3];
|
||||
cost += um.squaredNorm() * times[s];
|
||||
}
|
||||
|
||||
return cost;
|
||||
}
|
||||
|
||||
double getJerk()
|
||||
{
|
||||
double jerk = 0.0;
|
||||
|
||||
/* evaluate jerk */
|
||||
for (int s = 0; s < times.size(); ++s)
|
||||
{
|
||||
Eigen::VectorXd cxv(cxs[s].size()), cyv(cys[s].size()), czv(czs[s].size());
|
||||
/* convert coefficient */
|
||||
int order = cxs[s].size();
|
||||
for (int j = 0; j < order; ++j)
|
||||
{
|
||||
cxv(j) = cxs[s][order - 1 - j], cyv(j) = cys[s][order - 1 - j], czv(j) = czs[s][order - 1 - j];
|
||||
}
|
||||
double ts = times[s];
|
||||
|
||||
/* jerk matrix */
|
||||
Eigen::MatrixXd mat_jerk(order, order);
|
||||
mat_jerk.setZero();
|
||||
for (int i = 3; i < order; i += 1)
|
||||
for (int j = 3; j < order; j += 1)
|
||||
{
|
||||
mat_jerk(i, j) =
|
||||
i * (i - 1) * (i - 2) * j * (j - 1) * (j - 2) * pow(ts, i + j - 5) / (i + j - 5);
|
||||
}
|
||||
|
||||
jerk += (cxv.transpose() * mat_jerk * cxv)(0, 0);
|
||||
jerk += (cyv.transpose() * mat_jerk * cyv)(0, 0);
|
||||
jerk += (czv.transpose() * mat_jerk * czv)(0, 0);
|
||||
}
|
||||
|
||||
return jerk;
|
||||
}
|
||||
|
||||
void getMeanAndMaxVel(double &mean_v, double &max_v)
|
||||
{
|
||||
int num = 0;
|
||||
mean_v = 0.0, max_v = -1.0;
|
||||
for (int s = 0; s < times.size(); ++s)
|
||||
{
|
||||
int order = cxs[s].size();
|
||||
Eigen::VectorXd vx(order - 1), vy(order - 1), vz(order - 1);
|
||||
|
||||
/* coef of vel */
|
||||
for (int i = 0; i < order - 1; ++i)
|
||||
{
|
||||
vx(i) = double(i + 1) * cxs[s][order - 2 - i];
|
||||
vy(i) = double(i + 1) * cys[s][order - 2 - i];
|
||||
vz(i) = double(i + 1) * czs[s][order - 2 - i];
|
||||
}
|
||||
double ts = times[s];
|
||||
|
||||
double eval_t = 0.0;
|
||||
while (eval_t < ts)
|
||||
{
|
||||
Eigen::VectorXd tv(order - 1);
|
||||
for (int i = 0; i < order - 1; ++i)
|
||||
tv(i) = pow(ts, i);
|
||||
Eigen::Vector3d vel;
|
||||
vel(0) = tv.dot(vx), vel(1) = tv.dot(vy), vel(2) = tv.dot(vz);
|
||||
double vn = vel.norm();
|
||||
mean_v += vn;
|
||||
if (vn > max_v)
|
||||
max_v = vn;
|
||||
++num;
|
||||
|
||||
eval_t += 0.01;
|
||||
}
|
||||
}
|
||||
|
||||
mean_v = mean_v / double(num);
|
||||
}
|
||||
|
||||
void getMeanAndMaxAcc(double &mean_a, double &max_a)
|
||||
{
|
||||
int num = 0;
|
||||
mean_a = 0.0, max_a = -1.0;
|
||||
for (int s = 0; s < times.size(); ++s)
|
||||
{
|
||||
int order = cxs[s].size();
|
||||
Eigen::VectorXd ax(order - 2), ay(order - 2), az(order - 2);
|
||||
|
||||
/* coef of acc */
|
||||
for (int i = 0; i < order - 2; ++i)
|
||||
{
|
||||
ax(i) = double((i + 2) * (i + 1)) * cxs[s][order - 3 - i];
|
||||
ay(i) = double((i + 2) * (i + 1)) * cys[s][order - 3 - i];
|
||||
az(i) = double((i + 2) * (i + 1)) * czs[s][order - 3 - i];
|
||||
}
|
||||
double ts = times[s];
|
||||
|
||||
double eval_t = 0.0;
|
||||
while (eval_t < ts)
|
||||
{
|
||||
Eigen::VectorXd tv(order - 2);
|
||||
for (int i = 0; i < order - 2; ++i)
|
||||
tv(i) = pow(ts, i);
|
||||
Eigen::Vector3d acc;
|
||||
acc(0) = tv.dot(ax), acc(1) = tv.dot(ay), acc(2) = tv.dot(az);
|
||||
double an = acc.norm();
|
||||
mean_a += an;
|
||||
if (an > max_a)
|
||||
max_a = an;
|
||||
++num;
|
||||
|
||||
eval_t += 0.01;
|
||||
}
|
||||
}
|
||||
|
||||
mean_a = mean_a / double(num);
|
||||
}
|
||||
|
||||
static PolynomialTraj minSnapTraj(const Eigen::MatrixXd &Pos, const Eigen::Vector3d &start_vel,
|
||||
const Eigen::Vector3d &end_vel, const Eigen::Vector3d &start_acc,
|
||||
const Eigen::Vector3d &end_acc, const Eigen::VectorXd &Time);
|
||||
|
||||
static PolynomialTraj one_segment_traj_gen(const Eigen::Vector3d &start_pt, const Eigen::Vector3d &start_vel, const Eigen::Vector3d &start_acc,
|
||||
const Eigen::Vector3d &end_pt, const Eigen::Vector3d &end_vel, const Eigen::Vector3d &end_acc,
|
||||
double t);
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0"?>
|
||||
<package format="3">
|
||||
<name>traj_utils</name>
|
||||
<version>0.1.0</version>
|
||||
<description>Trajectory primitives and visualization for SCAN-Planner.</description>
|
||||
<maintainer email="[email protected]">SCAN-Planner maintainers</maintainer>
|
||||
<license>Apache-2.0</license>
|
||||
<buildtool_depend>ament_cmake</buildtool_depend>
|
||||
<depend>bspline_opt</depend>
|
||||
<depend>eigen</depend>
|
||||
<depend>rclcpp</depend>
|
||||
<depend>std_msgs</depend>
|
||||
<depend>visualization_msgs</depend>
|
||||
<export><build_type>ament_cmake</build_type></export>
|
||||
</package>
|
||||
@@ -0,0 +1,318 @@
|
||||
#include <traj_utils/planning_visualization.h>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <std_msgs/msg/color_rgba.hpp>
|
||||
|
||||
using std::cout;
|
||||
using std::endl;
|
||||
namespace scan_planner
|
||||
{
|
||||
PlanningVisualization::PlanningVisualization(rclcpp::Node *node)
|
||||
{
|
||||
node_ = node;
|
||||
const auto marker_qos = rclcpp::QoS(20).reliable().transient_local();
|
||||
goal_point_pub = node_->create_publisher<visualization_msgs::msg::Marker>("goal_point", marker_qos);
|
||||
global_list_pub = node_->create_publisher<visualization_msgs::msg::Marker>("global_list", marker_qos);
|
||||
init_list_pub = node_->create_publisher<visualization_msgs::msg::Marker>("init_list", marker_qos);
|
||||
optimal_list_pub = node_->create_publisher<visualization_msgs::msg::Marker>("optimal_list", marker_qos);
|
||||
a_star_list_pub = node_->create_publisher<visualization_msgs::msg::Marker>("a_star_list", marker_qos);
|
||||
}
|
||||
|
||||
// // real ids used: {id, id+1000}
|
||||
void PlanningVisualization::displayMarkerList(const MarkerPublisher::SharedPtr &pub, const vector<Eigen::Vector3d> &list, double scale,
|
||||
Eigen::Vector4d color, int id)
|
||||
{
|
||||
visualization_msgs::msg::Marker sphere, line_strip;
|
||||
sphere.header.frame_id = line_strip.header.frame_id = "world";
|
||||
sphere.header.stamp = line_strip.header.stamp = node_->now();
|
||||
sphere.type = visualization_msgs::msg::Marker::SPHERE_LIST;
|
||||
line_strip.type = visualization_msgs::msg::Marker::LINE_STRIP;
|
||||
sphere.action = line_strip.action = visualization_msgs::msg::Marker::ADD;
|
||||
sphere.id = id;
|
||||
line_strip.id = id + 1000;
|
||||
|
||||
sphere.pose.orientation.w = line_strip.pose.orientation.w = 1.0;
|
||||
sphere.color.r = line_strip.color.r = color(0);
|
||||
sphere.color.g = line_strip.color.g = color(1);
|
||||
sphere.color.b = line_strip.color.b = color(2);
|
||||
sphere.color.a = line_strip.color.a = color(3) > 1e-5 ? color(3) : 1.0;
|
||||
sphere.scale.x = scale;
|
||||
sphere.scale.y = scale;
|
||||
sphere.scale.z = scale;
|
||||
line_strip.scale.x = scale / 2;
|
||||
geometry_msgs::msg::Point pt;
|
||||
for (int i = 0; i < int(list.size()); i++)
|
||||
{
|
||||
pt.x = list[i](0);
|
||||
pt.y = list[i](1);
|
||||
pt.z = list[i](2);
|
||||
sphere.points.push_back(pt);
|
||||
line_strip.points.push_back(pt);
|
||||
}
|
||||
pub->publish(sphere);
|
||||
pub->publish(line_strip);
|
||||
}
|
||||
|
||||
// real ids used: {id, id+1}
|
||||
void PlanningVisualization::generatePathDisplayArray(visualization_msgs::msg::MarkerArray &array,
|
||||
const vector<Eigen::Vector3d> &list, double scale, Eigen::Vector4d color, int id)
|
||||
{
|
||||
visualization_msgs::msg::Marker sphere, line_strip;
|
||||
sphere.header.frame_id = line_strip.header.frame_id = "map";
|
||||
sphere.header.stamp = line_strip.header.stamp = node_->now();
|
||||
sphere.type = visualization_msgs::msg::Marker::SPHERE_LIST;
|
||||
line_strip.type = visualization_msgs::msg::Marker::LINE_STRIP;
|
||||
sphere.action = line_strip.action = visualization_msgs::msg::Marker::ADD;
|
||||
sphere.id = id;
|
||||
line_strip.id = id + 1;
|
||||
|
||||
sphere.pose.orientation.w = line_strip.pose.orientation.w = 1.0;
|
||||
sphere.color.r = line_strip.color.r = color(0);
|
||||
sphere.color.g = line_strip.color.g = color(1);
|
||||
sphere.color.b = line_strip.color.b = color(2);
|
||||
sphere.color.a = line_strip.color.a = color(3) > 1e-5 ? color(3) : 1.0;
|
||||
sphere.scale.x = scale;
|
||||
sphere.scale.y = scale;
|
||||
sphere.scale.z = scale;
|
||||
line_strip.scale.x = scale / 3;
|
||||
geometry_msgs::msg::Point pt;
|
||||
for (int i = 0; i < int(list.size()); i++)
|
||||
{
|
||||
pt.x = list[i](0);
|
||||
pt.y = list[i](1);
|
||||
pt.z = list[i](2);
|
||||
sphere.points.push_back(pt);
|
||||
line_strip.points.push_back(pt);
|
||||
}
|
||||
array.markers.push_back(sphere);
|
||||
array.markers.push_back(line_strip);
|
||||
}
|
||||
|
||||
// real ids used: {1000*id ~ (arrow nums)+1000*id}
|
||||
void PlanningVisualization::generateArrowDisplayArray(visualization_msgs::msg::MarkerArray &array,
|
||||
const vector<Eigen::Vector3d> &list, double scale, Eigen::Vector4d color, int id)
|
||||
{
|
||||
visualization_msgs::msg::Marker arrow;
|
||||
arrow.header.frame_id = "map";
|
||||
arrow.header.stamp = node_->now();
|
||||
arrow.type = visualization_msgs::msg::Marker::ARROW;
|
||||
arrow.action = visualization_msgs::msg::Marker::ADD;
|
||||
|
||||
// geometry_msgs::Point start, end;
|
||||
// arrow.points
|
||||
|
||||
arrow.color.r = color(0);
|
||||
arrow.color.g = color(1);
|
||||
arrow.color.b = color(2);
|
||||
arrow.color.a = color(3) > 1e-5 ? color(3) : 1.0;
|
||||
arrow.scale.x = scale;
|
||||
arrow.scale.y = 2 * scale;
|
||||
arrow.scale.z = 2 * scale;
|
||||
|
||||
geometry_msgs::msg::Point start, end;
|
||||
for (int i = 0; i < int(list.size() / 2); i++)
|
||||
{
|
||||
// arrow.color.r = color(0) / (1+i);
|
||||
// arrow.color.g = color(1) / (1+i);
|
||||
// arrow.color.b = color(2) / (1+i);
|
||||
|
||||
start.x = list[2 * i](0);
|
||||
start.y = list[2 * i](1);
|
||||
start.z = list[2 * i](2);
|
||||
end.x = list[2 * i + 1](0);
|
||||
end.y = list[2 * i + 1](1);
|
||||
end.z = list[2 * i + 1](2);
|
||||
arrow.points.clear();
|
||||
arrow.points.push_back(start);
|
||||
arrow.points.push_back(end);
|
||||
arrow.id = i + id * 1000;
|
||||
|
||||
array.markers.push_back(arrow);
|
||||
}
|
||||
}
|
||||
|
||||
void PlanningVisualization::displayGoalPoint(Eigen::Vector3d goal_point, Eigen::Vector4d color, const double scale, int id)
|
||||
{
|
||||
visualization_msgs::msg::Marker sphere;
|
||||
sphere.header.frame_id = "world";
|
||||
sphere.header.stamp = node_->now();
|
||||
sphere.type = visualization_msgs::msg::Marker::SPHERE;
|
||||
sphere.action = visualization_msgs::msg::Marker::ADD;
|
||||
sphere.id = id;
|
||||
|
||||
sphere.pose.orientation.w = 1.0;
|
||||
sphere.color.r = 1.0;
|
||||
sphere.color.g = 1.0;
|
||||
sphere.color.b = 1.0;
|
||||
sphere.color.a = color(3);
|
||||
sphere.scale.x = scale;
|
||||
sphere.scale.y = scale;
|
||||
sphere.scale.z = scale;
|
||||
sphere.pose.position.x = goal_point(0);
|
||||
sphere.pose.position.y = goal_point(1);
|
||||
sphere.pose.position.z = goal_point(2);
|
||||
|
||||
goal_point_pub->publish(sphere);
|
||||
}
|
||||
|
||||
void PlanningVisualization::displayGlobalPathList(vector<Eigen::Vector3d> init_pts, const double scale, int id)
|
||||
{
|
||||
|
||||
if (global_list_pub->get_subscription_count() == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Eigen::Vector4d color(0, 0.5, 0.5, 1);
|
||||
displayMarkerList(global_list_pub, init_pts, scale, color, id);
|
||||
}
|
||||
|
||||
void PlanningVisualization::displayInitPathList(vector<Eigen::Vector3d> init_pts, const double scale, int id)
|
||||
{
|
||||
|
||||
if (init_list_pub->get_subscription_count() == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Eigen::Vector4d color(0, 0, 1, 1);
|
||||
displayMarkerList(init_list_pub, init_pts, scale, color, id);
|
||||
}
|
||||
|
||||
void PlanningVisualization::displayOptimalList(Eigen::MatrixXd optimal_pts, int id)
|
||||
{
|
||||
|
||||
if (optimal_list_pub->get_subscription_count() == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
vector<Eigen::Vector3d> list;
|
||||
for (int i = 0; i < optimal_pts.cols(); i++)
|
||||
{
|
||||
Eigen::Vector3d pt = optimal_pts.col(i).transpose();
|
||||
list.push_back(pt);
|
||||
}
|
||||
Eigen::Vector4d color(1, 0, 0, 1);
|
||||
displayMarkerList(optimal_list_pub, list, 0.15, color, id);
|
||||
}
|
||||
|
||||
void PlanningVisualization::displayOptimalTraj(UniformBspline position_traj, int id)
|
||||
{
|
||||
if (optimal_list_pub->get_subscription_count() == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
const double duration = position_traj.getTimeSum();
|
||||
if (duration < 1e-6)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
UniformBspline velocity_traj = position_traj.getDerivative();
|
||||
const int sample_num = std::max(2, static_cast<int>(std::ceil(duration / 0.1)) + 1);
|
||||
|
||||
std::vector<Eigen::Vector3d> points;
|
||||
std::vector<double> speeds;
|
||||
points.reserve(sample_num);
|
||||
speeds.reserve(sample_num);
|
||||
|
||||
double min_speed = std::numeric_limits<double>::max();
|
||||
double max_speed = 0.0;
|
||||
for (int i = 0; i < sample_num; ++i)
|
||||
{
|
||||
const double t = duration * static_cast<double>(i) / static_cast<double>(sample_num - 1);
|
||||
Eigen::Vector3d pos = position_traj.evaluateDeBoorT(t);
|
||||
const double speed = velocity_traj.evaluateDeBoorT(t).norm();
|
||||
|
||||
points.push_back(pos);
|
||||
speeds.push_back(speed);
|
||||
min_speed = std::min(min_speed, speed);
|
||||
max_speed = std::max(max_speed, speed);
|
||||
}
|
||||
|
||||
visualization_msgs::msg::Marker sphere, line_strip;
|
||||
sphere.header.frame_id = line_strip.header.frame_id = "world";
|
||||
sphere.header.stamp = line_strip.header.stamp = node_->now();
|
||||
sphere.type = visualization_msgs::msg::Marker::SPHERE_LIST;
|
||||
line_strip.type = visualization_msgs::msg::Marker::LINE_STRIP;
|
||||
sphere.action = line_strip.action = visualization_msgs::msg::Marker::ADD;
|
||||
sphere.id = id;
|
||||
line_strip.id = id + 1000;
|
||||
sphere.pose.orientation.w = line_strip.pose.orientation.w = 1.0;
|
||||
sphere.scale.x = sphere.scale.y = sphere.scale.z = 0.08;
|
||||
line_strip.scale.x = 0.08;
|
||||
|
||||
const double speed_range = std::max(1e-6, max_speed - min_speed);
|
||||
for (size_t i = 0; i < points.size(); ++i)
|
||||
{
|
||||
geometry_msgs::msg::Point pt;
|
||||
pt.x = points[i](0);
|
||||
pt.y = points[i](1);
|
||||
pt.z = points[i](2);
|
||||
sphere.points.push_back(pt);
|
||||
line_strip.points.push_back(pt);
|
||||
|
||||
const double ratio = std::min(1.0, std::max(0.0, (speeds[i] - min_speed) / speed_range));
|
||||
std_msgs::msg::ColorRGBA color;
|
||||
color.a = 1.0;
|
||||
color.r = 1.0;
|
||||
color.g = 1.0 - ratio;
|
||||
color.b = 0.0;
|
||||
sphere.colors.push_back(color);
|
||||
line_strip.colors.push_back(color);
|
||||
}
|
||||
|
||||
optimal_list_pub->publish(sphere);
|
||||
optimal_list_pub->publish(line_strip);
|
||||
}
|
||||
|
||||
void PlanningVisualization::displayAStarList(std::vector<std::vector<Eigen::Vector3d>> a_star_paths, int id /* = Eigen::Vector4d(0.5,0.5,0,1)*/)
|
||||
{
|
||||
|
||||
if (a_star_list_pub->get_subscription_count() == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int i = 0;
|
||||
vector<Eigen::Vector3d> list;
|
||||
|
||||
Eigen::Vector4d color = Eigen::Vector4d(0.5 + ((double)rand() / RAND_MAX / 2), 0.5 + ((double)rand() / RAND_MAX / 2), 0, 1); // make the A star paths different every time.
|
||||
double scale = 0.05 + (double)rand() / RAND_MAX / 10;
|
||||
|
||||
// for ( int i=0; i<10; i++ )
|
||||
// {
|
||||
// //Eigen::Vector4d color(1,1,0,0);
|
||||
// displayMarkerList(a_star_list_pub, list, scale, color, id+i);
|
||||
// }
|
||||
|
||||
for (auto block : a_star_paths)
|
||||
{
|
||||
list.clear();
|
||||
for (auto pt : block)
|
||||
{
|
||||
list.push_back(pt);
|
||||
}
|
||||
//Eigen::Vector4d color(0.5,0.5,0,1);
|
||||
displayMarkerList(a_star_list_pub, list, scale, color, id + i); // real ids used: [ id ~ id+a_star_paths.size() ]
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
void PlanningVisualization::displayArrowList(const MarkerArrayPublisher::SharedPtr &pub,
|
||||
const vector<Eigen::Vector3d> &list,
|
||||
double scale, Eigen::Vector4d color, int id)
|
||||
{
|
||||
visualization_msgs::msg::MarkerArray array;
|
||||
// clear
|
||||
pub->publish(array);
|
||||
|
||||
generateArrowDisplayArray(array, list, scale, color, id);
|
||||
|
||||
pub->publish(array);
|
||||
}
|
||||
|
||||
// PlanningVisualization::
|
||||
} // namespace scan_planner
|
||||
@@ -0,0 +1,224 @@
|
||||
#include <iostream>
|
||||
#include <traj_utils/polynomial_traj.h>
|
||||
|
||||
PolynomialTraj PolynomialTraj::minSnapTraj(const Eigen::MatrixXd &Pos, const Eigen::Vector3d &start_vel,
|
||||
const Eigen::Vector3d &end_vel, const Eigen::Vector3d &start_acc,
|
||||
const Eigen::Vector3d &end_acc, const Eigen::VectorXd &Time)
|
||||
{
|
||||
int seg_num = Time.size();
|
||||
Eigen::MatrixXd poly_coeff(seg_num, 3 * 6);
|
||||
Eigen::VectorXd Px(6 * seg_num), Py(6 * seg_num), Pz(6 * seg_num);
|
||||
|
||||
int num_f, num_p; // number of fixed and free variables
|
||||
int num_d; // number of all segments' derivatives
|
||||
|
||||
const static auto Factorial = [](int x) {
|
||||
int fac = 1;
|
||||
for (int i = x; i > 0; i--)
|
||||
fac = fac * i;
|
||||
return fac;
|
||||
};
|
||||
|
||||
/* ---------- end point derivative ---------- */
|
||||
Eigen::VectorXd Dx = Eigen::VectorXd::Zero(seg_num * 6);
|
||||
Eigen::VectorXd Dy = Eigen::VectorXd::Zero(seg_num * 6);
|
||||
Eigen::VectorXd Dz = Eigen::VectorXd::Zero(seg_num * 6);
|
||||
|
||||
for (int k = 0; k < seg_num; k++)
|
||||
{
|
||||
/* position to derivative */
|
||||
Dx(k * 6) = Pos(0, k);
|
||||
Dx(k * 6 + 1) = Pos(0, k + 1);
|
||||
Dy(k * 6) = Pos(1, k);
|
||||
Dy(k * 6 + 1) = Pos(1, k + 1);
|
||||
Dz(k * 6) = Pos(2, k);
|
||||
Dz(k * 6 + 1) = Pos(2, k + 1);
|
||||
|
||||
if (k == 0)
|
||||
{
|
||||
Dx(k * 6 + 2) = start_vel(0);
|
||||
Dy(k * 6 + 2) = start_vel(1);
|
||||
Dz(k * 6 + 2) = start_vel(2);
|
||||
|
||||
Dx(k * 6 + 4) = start_acc(0);
|
||||
Dy(k * 6 + 4) = start_acc(1);
|
||||
Dz(k * 6 + 4) = start_acc(2);
|
||||
}
|
||||
else if (k == seg_num - 1)
|
||||
{
|
||||
Dx(k * 6 + 3) = end_vel(0);
|
||||
Dy(k * 6 + 3) = end_vel(1);
|
||||
Dz(k * 6 + 3) = end_vel(2);
|
||||
|
||||
Dx(k * 6 + 5) = end_acc(0);
|
||||
Dy(k * 6 + 5) = end_acc(1);
|
||||
Dz(k * 6 + 5) = end_acc(2);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- Mapping Matrix A ---------- */
|
||||
Eigen::MatrixXd Ab;
|
||||
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(seg_num * 6, seg_num * 6);
|
||||
|
||||
for (int k = 0; k < seg_num; k++)
|
||||
{
|
||||
Ab = Eigen::MatrixXd::Zero(6, 6);
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
Ab(2 * i, i) = Factorial(i);
|
||||
for (int j = i; j < 6; j++)
|
||||
Ab(2 * i + 1, j) = Factorial(j) / Factorial(j - i) * pow(Time(k), j - i);
|
||||
}
|
||||
A.block(k * 6, k * 6, 6, 6) = Ab;
|
||||
}
|
||||
|
||||
/* ---------- Produce Selection Matrix C' ---------- */
|
||||
Eigen::MatrixXd Ct, C;
|
||||
|
||||
num_f = 2 * seg_num + 4; // 3 + 3 + (seg_num - 1) * 2 = 2m + 4
|
||||
num_p = 2 * seg_num - 2; //(seg_num - 1) * 2 = 2m - 2
|
||||
num_d = 6 * seg_num;
|
||||
Ct = Eigen::MatrixXd::Zero(num_d, num_f + num_p);
|
||||
Ct(0, 0) = 1;
|
||||
Ct(2, 1) = 1;
|
||||
Ct(4, 2) = 1; // stack the start point
|
||||
Ct(1, 3) = 1;
|
||||
Ct(3, 2 * seg_num + 4) = 1;
|
||||
Ct(5, 2 * seg_num + 5) = 1;
|
||||
|
||||
Ct(6 * (seg_num - 1) + 0, 2 * seg_num + 0) = 1;
|
||||
Ct(6 * (seg_num - 1) + 1, 2 * seg_num + 1) = 1; // Stack the end point
|
||||
Ct(6 * (seg_num - 1) + 2, 4 * seg_num + 0) = 1;
|
||||
Ct(6 * (seg_num - 1) + 3, 2 * seg_num + 2) = 1; // Stack the end point
|
||||
Ct(6 * (seg_num - 1) + 4, 4 * seg_num + 1) = 1;
|
||||
Ct(6 * (seg_num - 1) + 5, 2 * seg_num + 3) = 1; // Stack the end point
|
||||
|
||||
for (int j = 2; j < seg_num; j++)
|
||||
{
|
||||
Ct(6 * (j - 1) + 0, 2 + 2 * (j - 1) + 0) = 1;
|
||||
Ct(6 * (j - 1) + 1, 2 + 2 * (j - 1) + 1) = 1;
|
||||
Ct(6 * (j - 1) + 2, 2 * seg_num + 4 + 2 * (j - 2) + 0) = 1;
|
||||
Ct(6 * (j - 1) + 3, 2 * seg_num + 4 + 2 * (j - 1) + 0) = 1;
|
||||
Ct(6 * (j - 1) + 4, 2 * seg_num + 4 + 2 * (j - 2) + 1) = 1;
|
||||
Ct(6 * (j - 1) + 5, 2 * seg_num + 4 + 2 * (j - 1) + 1) = 1;
|
||||
}
|
||||
|
||||
C = Ct.transpose();
|
||||
|
||||
Eigen::VectorXd Dx1 = C * Dx;
|
||||
Eigen::VectorXd Dy1 = C * Dy;
|
||||
Eigen::VectorXd Dz1 = C * Dz;
|
||||
|
||||
/* ---------- minimum snap matrix ---------- */
|
||||
Eigen::MatrixXd Q = Eigen::MatrixXd::Zero(seg_num * 6, seg_num * 6);
|
||||
|
||||
for (int k = 0; k < seg_num; k++)
|
||||
{
|
||||
for (int i = 3; i < 6; i++)
|
||||
{
|
||||
for (int j = 3; j < 6; j++)
|
||||
{
|
||||
Q(k * 6 + i, k * 6 + j) =
|
||||
i * (i - 1) * (i - 2) * j * (j - 1) * (j - 2) / (i + j - 5) * pow(Time(k), (i + j - 5));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- R matrix ---------- */
|
||||
Eigen::MatrixXd R = C * A.transpose().inverse() * Q * A.inverse() * Ct;
|
||||
|
||||
Eigen::VectorXd Dxf(2 * seg_num + 4), Dyf(2 * seg_num + 4), Dzf(2 * seg_num + 4);
|
||||
|
||||
Dxf = Dx1.segment(0, 2 * seg_num + 4);
|
||||
Dyf = Dy1.segment(0, 2 * seg_num + 4);
|
||||
Dzf = Dz1.segment(0, 2 * seg_num + 4);
|
||||
|
||||
Eigen::MatrixXd Rff(2 * seg_num + 4, 2 * seg_num + 4);
|
||||
Eigen::MatrixXd Rfp(2 * seg_num + 4, 2 * seg_num - 2);
|
||||
Eigen::MatrixXd Rpf(2 * seg_num - 2, 2 * seg_num + 4);
|
||||
Eigen::MatrixXd Rpp(2 * seg_num - 2, 2 * seg_num - 2);
|
||||
|
||||
Rff = R.block(0, 0, 2 * seg_num + 4, 2 * seg_num + 4);
|
||||
Rfp = R.block(0, 2 * seg_num + 4, 2 * seg_num + 4, 2 * seg_num - 2);
|
||||
Rpf = R.block(2 * seg_num + 4, 0, 2 * seg_num - 2, 2 * seg_num + 4);
|
||||
Rpp = R.block(2 * seg_num + 4, 2 * seg_num + 4, 2 * seg_num - 2, 2 * seg_num - 2);
|
||||
|
||||
/* ---------- close form solution ---------- */
|
||||
|
||||
Eigen::VectorXd Dxp(2 * seg_num - 2), Dyp(2 * seg_num - 2), Dzp(2 * seg_num - 2);
|
||||
Dxp = -(Rpp.inverse() * Rfp.transpose()) * Dxf;
|
||||
Dyp = -(Rpp.inverse() * Rfp.transpose()) * Dyf;
|
||||
Dzp = -(Rpp.inverse() * Rfp.transpose()) * Dzf;
|
||||
|
||||
Dx1.segment(2 * seg_num + 4, 2 * seg_num - 2) = Dxp;
|
||||
Dy1.segment(2 * seg_num + 4, 2 * seg_num - 2) = Dyp;
|
||||
Dz1.segment(2 * seg_num + 4, 2 * seg_num - 2) = Dzp;
|
||||
|
||||
Px = (A.inverse() * Ct) * Dx1;
|
||||
Py = (A.inverse() * Ct) * Dy1;
|
||||
Pz = (A.inverse() * Ct) * Dz1;
|
||||
|
||||
for (int i = 0; i < seg_num; i++)
|
||||
{
|
||||
poly_coeff.block(i, 0, 1, 6) = Px.segment(i * 6, 6).transpose();
|
||||
poly_coeff.block(i, 6, 1, 6) = Py.segment(i * 6, 6).transpose();
|
||||
poly_coeff.block(i, 12, 1, 6) = Pz.segment(i * 6, 6).transpose();
|
||||
}
|
||||
|
||||
/* ---------- use polynomials ---------- */
|
||||
PolynomialTraj poly_traj;
|
||||
for (int i = 0; i < poly_coeff.rows(); ++i)
|
||||
{
|
||||
vector<double> cx(6), cy(6), cz(6);
|
||||
for (int j = 0; j < 6; ++j)
|
||||
{
|
||||
cx[j] = poly_coeff(i, j), cy[j] = poly_coeff(i, j + 6), cz[j] = poly_coeff(i, j + 12);
|
||||
}
|
||||
reverse(cx.begin(), cx.end());
|
||||
reverse(cy.begin(), cy.end());
|
||||
reverse(cz.begin(), cz.end());
|
||||
double ts = Time(i);
|
||||
poly_traj.addSegment(cx, cy, cz, ts);
|
||||
}
|
||||
|
||||
return poly_traj;
|
||||
}
|
||||
|
||||
PolynomialTraj PolynomialTraj::one_segment_traj_gen(const Eigen::Vector3d &start_pt, const Eigen::Vector3d &start_vel, const Eigen::Vector3d &start_acc,
|
||||
const Eigen::Vector3d &end_pt, const Eigen::Vector3d &end_vel, const Eigen::Vector3d &end_acc,
|
||||
double t)
|
||||
{
|
||||
Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 6), Crow(1, 6);
|
||||
Eigen::VectorXd Bx(6), By(6), Bz(6);
|
||||
|
||||
C(0, 5) = 1;
|
||||
C(1, 4) = 1;
|
||||
C(2, 3) = 2;
|
||||
Crow << pow(t, 5), pow(t, 4), pow(t, 3), pow(t, 2), t, 1;
|
||||
C.row(3) = Crow;
|
||||
Crow << 5 * pow(t, 4), 4 * pow(t, 3), 3 * pow(t, 2), 2 * t, 1, 0;
|
||||
C.row(4) = Crow;
|
||||
Crow << 20 * pow(t, 3), 12 * pow(t, 2), 6 * t, 2, 0, 0;
|
||||
C.row(5) = Crow;
|
||||
|
||||
Bx << start_pt(0), start_vel(0), start_acc(0), end_pt(0), end_vel(0), end_acc(0);
|
||||
By << start_pt(1), start_vel(1), start_acc(1), end_pt(1), end_vel(1), end_acc(1);
|
||||
Bz << start_pt(2), start_vel(2), start_acc(2), end_pt(2), end_vel(2), end_acc(2);
|
||||
|
||||
Eigen::VectorXd Cofx = C.colPivHouseholderQr().solve(Bx);
|
||||
Eigen::VectorXd Cofy = C.colPivHouseholderQr().solve(By);
|
||||
Eigen::VectorXd Cofz = C.colPivHouseholderQr().solve(Bz);
|
||||
|
||||
vector<double> cx(6), cy(6), cz(6);
|
||||
for (int i = 0; i < 6; i++)
|
||||
{
|
||||
cx[i] = Cofx(i);
|
||||
cy[i] = Cofy(i);
|
||||
cz[i] = Cofz(i);
|
||||
}
|
||||
|
||||
PolynomialTraj poly_traj;
|
||||
poly_traj.addSegment(cx, cy, cz, t);
|
||||
|
||||
return poly_traj;
|
||||
}
|
||||
Reference in New Issue
Block a user