Files
costmap_2d/plugins/static_layer.cpp
duongtd e40e9c0104 fix(costmap): one parameter flow for every layer; fail on a bad layer
Each layer reads its default file under $PNKX_NAV_CORE_CONFIG_DIR/config,
then overrides a key from "<costmap>/<plugin>".
Costmap2DROBOT::copyParentParameters() copies the shared "<plugin>:"
block there first. This was broken in three ways:
- the copy lists covered only part of what the layers read, so a key set
  in the shared block was dropped without a word;
- DepthCameraObstacleLayer had no default file and read the shared block
  itself;
- a layer that failed to initialize left a half-built costmap that
  reported READY.

Failing loudly:
- costmap_2d_robot.cpp: a failing layer, a malformed plugins: list or a
  missing costmap_params.yaml throws std::runtime_error with the costmap
  and layer name, after releasing layered_costmap_.
  NavigationRuntime::buildCostmaps() turns this into an initialization
  error, so the host never reports READY.
- Static/Obstacle/Voxel/Inflation and DepthCameraObstacleLayer throw when
  their default file cannot be opened.
- A key whose value does not convert to the type the layer reads throws.
  getParam() used to write 0, false or "" into the value, and that was
  copied as if configured.

One flow:
- copyParentParameters() copies every key each layer reads, with the
  layer's type, including a new DepthCameraObstacleLayer branch. Copies no
  layer reads are dropped.
- DepthCameraObstacleLayer::loadParameters() reads
  config/depth_camera_obstacle_layer_params.yaml (new, equal to the C++
  defaults), then "<costmap>/<plugin>". ParamReader is gone, and so is the
  node_handle.cpp:265 warning at start-up.
- VoxelLayer: z_resolution can be overridden; unknown_threshold is
  computed after the final z_voxels; the column keys are range-checked;
  the effective column is logged once at start-up.
- config/obstacle_layer_params.yaml: drop the per-source keys the layer
  never read there.
- depth_camera_obstacle_layer_test: set PNKX_NAV_CORE_CONFIG_DIR; add
  tests for a wrong type and a missing default file.

Squash of fix/config-flow (ae7fce9, f8705e1). Checked on the KIT robot on
22/10/2026:
- the depth layer summary at start-up is unchanged;
- a shared-block key now reaches VoxelLayer;
- FOV_W 3.5, z_voxels 17, a wrong-typed key and a missing default file
  each give INITIALIZATION_FAILED.
2026-10-22 10:49:31 +07:00

442 lines
15 KiB
C++
Executable File

/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, 2013, Willow Garage, Inc.
* Copyright (c) 2015, Fetch Robotics, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: Eitan Marder-Eppstein
* David V. Lu!!
*********************************************************************/
#include <robot_costmap_2d/static_layer.h>
#include <robot_costmap_2d/costmap_math.h>
#include <tf3/convert.h>
#include <robot_tf3_geometry_msgs/tf3_geometry_msgs.h>
#include <boost/dll/alias.hpp>
#include <stdexcept>
#include <fstream>
#include <cxxabi.h>
using robot_costmap_2d::NO_INFORMATION;
using robot_costmap_2d::LETHAL_OBSTACLE;
using robot_costmap_2d::FREE_SPACE;
namespace robot_costmap_2d
{
StaticLayer::StaticLayer()
{
threshold_ = &lethal_threshold_;
}
StaticLayer::~StaticLayer()
{}
void StaticLayer::onInitialize()
{
robot::NodeHandle nh("~");
robot::NodeHandle priv_nh(nh, name_);
current_ = true;
global_frame_ = layered_costmap_->getGlobalFrameID();
std::string config_file_name = "static_layer_params.yaml";
if (!getParams(config_file_name, priv_nh))
throw std::runtime_error("StaticLayer " + name_ + ": cannot open the default file " + config_file_name);
robot::log_warning("Initializing static layer with map topic \"%s\" in frame \"%s\"", map_topic_.c_str(), global_frame_.c_str());
}
bool StaticLayer::getParams(const std::string& config_file_name, robot::NodeHandle &nh)
{
try {
const char *env_config = std::getenv("PNKX_NAV_CORE_CONFIG_DIR");
std::string folder;
if (env_config && std::filesystem::exists(env_config))
{
folder = std::string(env_config);
// robot::log_error("config_directory: %s", folder.c_str());
}
std::string path_source = getSourceFile(folder,config_file_name);
YAML::Node config = YAML::LoadFile(path_source);
YAML::Node layer = config["static_layer"];
// ===== 1. Load default từ layer (yaml / plugin config) =====
bool enabled = loadParam(layer, "enabled", true);
bool first_map_only = loadParam(layer, "first_map_only", false);
bool subscribe_to_updates = loadParam(layer, "subscribe_to_updates", false);
bool track_unknown_space = loadParam(layer, "track_unknown_space", true);
bool use_maximum = loadParam(layer, "use_maximum", false);
int lethal_cost_threshold = loadParam(layer, "lethal_cost_threshold", 100);
int unknown_cost_value = loadParam(layer, "unknown_cost_value", -1);
bool trinary_costmap = loadParam(layer, "trinary_costmap", true);
std::string map_topic = loadParam(layer, "map_topic", std::string("map"));
std::string base_frame_id = loadParam(layer, "base_frame_id", std::string("map"));
// ===== 2. Override từ ROS param server (chỉ khi param tồn tại) =====
if (nh.hasParam("enabled"))
nh.getParam("enabled", enabled, enabled);
if (nh.hasParam("map_topic"))
nh.getParam("map_topic", map_topic);
if (nh.hasParam("first_map_only"))
nh.getParam("first_map_only", first_map_only);
if (nh.hasParam("subscribe_to_updates"))
nh.getParam("subscribe_to_updates", subscribe_to_updates);
if (nh.hasParam("track_unknown_space"))
nh.getParam("track_unknown_space", track_unknown_space);
if (nh.hasParam("use_maximum"))
nh.getParam("use_maximum", use_maximum);
if (nh.hasParam("trinary_costmap"))
nh.getParam("trinary_costmap", trinary_costmap);
if (nh.hasParam("base_frame_id"))
nh.getParam("base_frame_id", base_frame_id);
if (nh.hasParam("lethal_cost_threshold"))
nh.getParam("lethal_cost_threshold", lethal_cost_threshold);
if (nh.hasParam("unknown_cost_value"))
nh.getParam("unknown_cost_value", unknown_cost_value);
map_topic_ = map_topic;
first_map_only_ = first_map_only;
subscribe_to_updates_ = subscribe_to_updates;
track_unknown_space_ = track_unknown_space;
use_maximum_ = use_maximum;
lethal_threshold_ = std::max(std::min(lethal_cost_threshold, 100), 0);
unknown_cost_value_ = unknown_cost_value;
trinary_costmap_ = trinary_costmap;
base_frame_id_ = base_frame_id;
if (enabled_ != enabled) {
enabled_ = enabled;
has_updated_data_ = true;
x_ = y_ = 0;
width_ = size_x_;
height_ = size_y_;
}
}
catch (const YAML::BadFile& e) {
std::cerr << "Cannot open YAML file: " << e.what() << std::endl;
return false;
}
return true;
}
void StaticLayer::matchSize()
{
// If we are using rolling costmap, the static map size is
// unrelated to the size of the layered costmap
if (!layered_costmap_->isRolling())
{
Costmap2D* master = layered_costmap_->getCostmap();
resizeMap(master->getSizeInCellsX(), master->getSizeInCellsY(), master->getResolution(),
master->getOriginX(), master->getOriginY());
}
}
unsigned char StaticLayer::interpretValue(unsigned char value)
{
// check if the static value is above the unknown or lethal thresholds
if (track_unknown_space_ && value == unknown_cost_value_)
{
return NO_INFORMATION;
}
else if (!track_unknown_space_ && value == unknown_cost_value_)
{
return FREE_SPACE;
}
else if (value >= lethal_threshold_)
{
return LETHAL_OBSTACLE;
}
else if (trinary_costmap_)
{
return FREE_SPACE;
}
double scale = (double) value / lethal_threshold_;
return scale * LETHAL_OBSTACLE;
}
void StaticLayer::handleImpl(const void* data,
const std::type_info& type,
const std::string& topic)
{
if (type == typeid(robot_nav_msgs::OccupancyGrid) &&
(topic == map_topic_ || topic == "/" + map_topic_)) {
incomingMap(*static_cast<const robot_nav_msgs::OccupancyGrid*>(data));
} else if (type == typeid(robot_map_msgs::OccupancyGridUpdate) &&
(topic == map_topic_ + "_updates" || topic == "/" + map_topic_ + "_updates")) {
incomingUpdate(*static_cast<const robot_map_msgs::OccupancyGridUpdate*>(data));
} else {
std::string readable = boost::core::demangle(type.name());
size_t pos = readable.find("<");
if (pos != std::string::npos)
{
readable = readable.substr(0, pos);
}
robot::log_error("[] con1: %x, con2: %x ", type == typeid(robot_nav_msgs::OccupancyGrid), (topic == map_topic_ || topic == "/" + map_topic_));
robot::log_error("[StaticLayer] Received data of unknown type: %s on topic: %s, map_topic_: %s\n", readable.c_str(), topic.c_str(), map_topic_.c_str());
// std::cout << "[StaticLayer] Unknown type: " << type.name() << " on topic: " << topic << std::endl;
}
}
void StaticLayer::incomingMap(const robot_nav_msgs::OccupancyGrid& new_map)
{
if(!map_shutdown_)
{
std::cout << "[StaticLayer] Received new map!" << std::endl;
unsigned int size_x = new_map.info.width, size_y = new_map.info.height;
robot::log_info("Received a %d X %d map at %f m/pix\n", size_x, size_y, new_map.info.resolution);
// resize costmap if size, resolution or origin do not match
Costmap2D* master = layered_costmap_->getCostmap();
if (!layered_costmap_->isRolling() &&
(master->getSizeInCellsX() != size_x ||
master->getSizeInCellsY() != size_y ||
master->getResolution() != new_map.info.resolution ||
master->getOriginX() != new_map.info.origin.position.x ||
master->getOriginY() != new_map.info.origin.position.y))
{
// Update the size of the layered costmap (and all layers, including this one)
robot::log_info("Resizing costmap to %d X %d at %f m/pix\n", size_x, size_y, new_map.info.resolution);
layered_costmap_->resizeMap(size_x, size_y, new_map.info.resolution, new_map.info.origin.position.x,
new_map.info.origin.position.y,
true /* set size_locked to true, prevents reconfigureCb from overriding map size*/);
}
else if (size_x_ != size_x || size_y_ != size_y ||
resolution_ != new_map.info.resolution ||
origin_x_ != new_map.info.origin.position.x ||
origin_y_ != new_map.info.origin.position.y)
{
// only update the size of the costmap stored locally in this layer
robot::log_info("Resizing static layer to %d X %d at %f m/pix\n", size_x, size_y, new_map.info.resolution);
resizeMap(size_x, size_y, new_map.info.resolution,
new_map.info.origin.position.x, new_map.info.origin.position.y);
}
unsigned int index = 0;
// // 1. Tạo file (nếu chưa có) + mở để ghi
// std::ofstream file("/home/duongtd/ros_test_ws/src/third_party/costmap_2d/data.txt", std::ios::app);
// // 2. Kiểm tra mở file thành công
// if (!file)
// {
// std::cerr << "Cannot create file\n";
// return ;
// }
// initialize the costmap with static data
for (unsigned int i = 0; i < size_y; ++i)
{
for (unsigned int j = 0; j < size_x; ++j)
{
unsigned char value = new_map.data[index];
costmap_[index] = interpretValue(value);
// 3. Ghi giá trị biến
// file << static_cast<int>(costmap_[index]) << " , ";
++index;
}
// file << std::endl;
}
// // 4. Đóng file
// file.close();
map_frame_ = new_map.header.frame_id;
// we have a new map, update full size of map
x_ = y_ = 0;
width_ = size_x_;
height_ = size_y_;
map_received_ = true;
has_updated_data_ = true;
}
else
{
robot::log_info("Stop receive new map!\n");
}
// shutdown the map subscrber if firt_map_only_ flag is on
if (first_map_only_)
{
robot::log_info("Shutting down the map subscriber. first_map_only flag is on\n");
map_shutdown_ = true;
}
}
void StaticLayer::incomingUpdate(const robot_map_msgs::OccupancyGridUpdate& update)
{
if(!map_update_shutdown_)
{
robot::log_info("Update new map!\n");
unsigned int di = 0;
for (unsigned int y = 0; y < update.height ; y++)
{
unsigned int index_base = (update.y + y) * size_x_;
for (unsigned int x = 0; x < update.width ; x++)
{
unsigned int index = index_base + x + update.x;
costmap_[index] = interpretValue(update.data[di++]);
}
}
x_ = update.x;
y_ = update.y;
width_ = update.width;
height_ = update.height;
has_updated_data_ = true;
}
}
void StaticLayer::activate()
{
map_shutdown_ = false;
map_update_shutdown_ = false;
onInitialize();
}
void StaticLayer::deactivate()
{
map_shutdown_ = true;
if (subscribe_to_updates_)
map_update_shutdown_ = true;
}
void StaticLayer::reset()
{
if (first_map_only_)
{
map_shutdown_ = false;
map_update_shutdown_ = false;
has_updated_data_ = true;
}
else
{
onInitialize();
}
}
void StaticLayer::updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x, double* min_y,
double* max_x, double* max_y)
{
if( !layered_costmap_->isRolling() ){
if (!map_received_ || !(has_updated_data_ || has_extra_bounds_))
return;
}
useExtraBounds(min_x, min_y, max_x, max_y);
double wx, wy;
mapToWorld(x_, y_, wx, wy);
*min_x = std::min(wx, *min_x);
*min_y = std::min(wy, *min_y);
mapToWorld(x_ + width_, y_ + height_, wx, wy);
*max_x = std::max(wx, *max_x);
*max_y = std::max(wy, *max_y);
has_updated_data_ = false;
}
void StaticLayer::updateCosts(robot_costmap_2d::Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j)
{
if (!map_received_)
return;
if (!layered_costmap_->isRolling())
{
// if not rolling, the layered costmap (master_grid) has same coordinates as this layer
if (!use_maximum_)
updateWithOverwrite(master_grid, min_i, min_j, max_i, max_j);
else
updateWithMax(master_grid, min_i, min_j, max_i, max_j);
}
else
{
// If rolling window, the master_grid is unlikely to have same coordinates as this layer
unsigned int mx, my;
double wx, wy;
// Might even be in a different frame
// robot_geometry_msgs::TransformStamped transform;
tf3::TransformStampedMsg transformMsg;
try
{
transformMsg = tf_->lookupTransform(map_frame_, global_frame_, tf3::Time());
}
catch (tf3::TransformException ex)
{
robot::log_error("StaticLayer::updateCosts(): %s \n", ex.what());
return;
}
// Copy map data given proper transformations
tf3::Transform tf3_transform;
tf3_transform = data_convert::convertTotf3Transform(transformMsg.transform);
// tf2::Transform tf2_transform;
// tf2::convert(transform.transform, tf2_transform);
for (unsigned int i = min_i; i < max_i; ++i)
{
for (unsigned int j = min_j; j < max_j; ++j)
{
// Convert master_grid coordinates (i,j) into global_frame_(wx,wy) coordinates
layered_costmap_->getCostmap()->mapToWorld(i, j, wx, wy);
// Transform from global_frame_ to map_frame_
tf3::Vector3 p(wx, wy, 0);
p = tf3_transform*p;
// Set master_grid with cell from map
if (worldToMap(p.x(), p.y(), mx, my))
{
if (!use_maximum_)
master_grid.setCost(i, j, getCost(mx, my));
else
master_grid.setCost(i, j, std::max(getCost(mx, my), master_grid.getCost(i, j)));
}
}
}
}
}
// Export factory function
static boost::shared_ptr<Layer> create_static_plugin() {
return boost::make_shared<StaticLayer>();
}
// Alias cho Boost.DLL (nếu muốn dùng boost::dll::import_alias)
BOOST_DLL_ALIAS(create_static_plugin, StaticLayer)
} // namespace robot_costmap_2d