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.
975 lines
41 KiB
C++
975 lines
41 KiB
C++
/*********************************************************************
|
|
* Software License Agreement (BSD License)
|
|
*
|
|
* Copyright (c) 2008, 2013, Willow Garage, 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: Apola (costmap_depth_camera); port to robot_costmap_2d.
|
|
*********************************************************************/
|
|
#include <robot_costmap_2d/depth_camera_obstacle_layer.h>
|
|
|
|
#include <robot_costmap_2d/cost_values.h>
|
|
#include <robot_sensor_msgs/point_cloud2_iterator.h>
|
|
#include <tf3/exceptions.h>
|
|
#include <data_convert/data_convert.h>
|
|
#include <boost/dll/alias.hpp>
|
|
#include <boost/make_shared.hpp>
|
|
#include <boost/thread/locks.hpp>
|
|
|
|
#include <pcl/point_cloud.h>
|
|
#include <pcl/point_types.h>
|
|
#include <pcl/filters/voxel_grid.h>
|
|
#include <pcl/kdtree/kdtree_flann.h>
|
|
#include <pcl/search/kdtree.h>
|
|
#include <pcl/segmentation/extract_clusters.h>
|
|
|
|
#include <robot_costmap_2d/utils.h>
|
|
|
|
#include <algorithm>
|
|
#include <chrono>
|
|
#include <cmath>
|
|
#include <cstdlib>
|
|
#include <filesystem>
|
|
#include <limits>
|
|
#include <sstream>
|
|
#include <stdexcept>
|
|
#include <unordered_set>
|
|
|
|
namespace robot_costmap_2d
|
|
{
|
|
namespace
|
|
{
|
|
// Distance of the "attach" band around each frustum face, hard-coded in the source [m].
|
|
constexpr float kAttachDistance = 0.12f;
|
|
// Stored columns farther than this from the robot are not tested for clearing [m].
|
|
constexpr double kClearingSkipDistance = 10.0;
|
|
// VoxelGrid leaf of the combined observation, hard-coded in the source [m].
|
|
constexpr float kObservationLeaf = 0.05f;
|
|
|
|
Eigen::Isometry3d toIsometry(const tf3::TransformStampedMsg& t)
|
|
{
|
|
const auto& q = t.transform.rotation;
|
|
const auto& p = t.transform.translation;
|
|
Eigen::Isometry3d iso = Eigen::Isometry3d::Identity();
|
|
iso.linear() = Eigen::Quaterniond(q.w, q.x, q.y, q.z).normalized().toRotationMatrix();
|
|
iso.translation() << p.x, p.y, p.z;
|
|
return iso;
|
|
}
|
|
|
|
// Steps 1 and 3 of the costmap layer config flow for one key: the value in the layer's default
|
|
// file, overridden by "<costmap>/<plugin>/<key>", which Costmap2DROBOT::copyParentParameters() has
|
|
// filled from the shared "<plugin>:" block. A value that does not convert to T is a configuration
|
|
// error: getParam() would otherwise replace it with 0, false or "" without a word.
|
|
template <typename T>
|
|
T readParam(const YAML::Node& file_node, const std::string& file_key, const robot::NodeHandle& nh,
|
|
const std::string& key, const T& fallback)
|
|
{
|
|
T value = loadParam(file_node, file_key, fallback);
|
|
if (nh.hasParam(key) && !nh.getParam(key, value, value))
|
|
throw std::invalid_argument("DepthCameraObstacleLayer: '" + nh.getNamespace() + "/" + key +
|
|
"' does not convert to the type the layer reads");
|
|
return value;
|
|
}
|
|
|
|
template <typename T>
|
|
T readParam(const YAML::Node& file_node, const robot::NodeHandle& nh, const std::string& key, const T& fallback)
|
|
{
|
|
return readParam(file_node, key, nh, key, fallback);
|
|
}
|
|
|
|
void requireRange(bool ok, const std::string& what)
|
|
{
|
|
if (!ok)
|
|
throw std::invalid_argument("DepthCameraObstacleLayer: " + what);
|
|
}
|
|
} // namespace
|
|
|
|
// ---------------------------------------------------------------------------------------------
|
|
// Frustum (costmap_depth_camera::Observation::findFrustum* and FrustumUtils)
|
|
// ---------------------------------------------------------------------------------------------
|
|
|
|
void DepthCameraFrustum::build(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v,
|
|
double min_d, double max_d, bool optical)
|
|
{
|
|
max_detect_distance = max_d;
|
|
const double tw = std::tan(fov_w / 2.0);
|
|
const double tv = std::tan(fov_v / 2.0);
|
|
// findFrustumVertex(): X forward, +Y left, +Z up. TL = +Y +Z, BR = -Y -Z.
|
|
const std::array<Eigen::Vector3d, 8> local = {
|
|
Eigen::Vector3d(min_d, min_d * tw, min_d * tv), Eigen::Vector3d(min_d, -min_d * tw, min_d * tv),
|
|
Eigen::Vector3d(min_d, min_d * tw, -min_d * tv), Eigen::Vector3d(min_d, -min_d * tw, -min_d * tv),
|
|
Eigen::Vector3d(max_d, max_d * tw, max_d * tv), Eigen::Vector3d(max_d, -max_d * tw, max_d * tv),
|
|
Eigen::Vector3d(max_d, max_d * tw, -max_d * tv), Eigen::Vector3d(max_d, -max_d * tw, -max_d * tv)};
|
|
for (std::size_t i = 0; i < local.size(); ++i)
|
|
{
|
|
Eigen::Vector3d v = local[i];
|
|
// Same pyramid expressed in an optical frame: forward = +Z, left = -X, up = -Y.
|
|
if (optical)
|
|
v = Eigen::Vector3d(-local[i].y(), -local[i].z(), local[i].x());
|
|
vertices[i] = (T_global_sensor * v).cast<float>();
|
|
}
|
|
origin = T_global_sensor.translation().cast<float>();
|
|
|
|
const Eigen::Vector3f& TLNear = vertices[0];
|
|
const Eigen::Vector3f& TRNear = vertices[1];
|
|
const Eigen::Vector3f& BLNear = vertices[2];
|
|
const Eigen::Vector3f& BRNear = vertices[3];
|
|
const Eigen::Vector3f& TLFar = vertices[4];
|
|
const Eigen::Vector3f& TRFar = vertices[5];
|
|
const Eigen::Vector3f& BLFar = vertices[6];
|
|
const Eigen::Vector3f& BRFar = vertices[7];
|
|
|
|
// findFrustumNormal(): getVec(a, b) = b - a, inward normals in this order.
|
|
normals[0] = (TRNear - TLNear).cross(BRNear - TRNear); // near
|
|
normals[1] = (TRFar - TRNear).cross(BRFar - TRFar); // right
|
|
normals[2] = (BRFar - BRNear).cross(BLFar - BRFar); // bottom
|
|
normals[3] = (BLFar - BLNear).cross(TLFar - BLFar); // left
|
|
normals[4] = (TRFar - BRFar).cross(TLFar - TRFar); // far
|
|
normals[5] = (TRFar - TLFar).cross(TRNear - TRFar); // top
|
|
|
|
// findFrustumPlane(): getPlaneN(p1, p2, p3) = cross(p2 - p1, p3 - p1), d = -n . p1.
|
|
const auto plane = [](const Eigen::Vector3f& p1, const Eigen::Vector3f& p2, const Eigen::Vector3f& p3) {
|
|
const Eigen::Vector3f n = (p2 - p1).cross(p3 - p1);
|
|
return Eigen::Vector4f(n.x(), n.y(), n.z(), -n.dot(p1));
|
|
};
|
|
planes[0] = plane(TLNear, TLFar, BLNear);
|
|
planes[1] = plane(BLNear, BRNear, BLFar);
|
|
planes[2] = plane(TRNear, BRNear, BRFar);
|
|
planes[3] = plane(TLNear, TRNear, TLFar);
|
|
planes[4] = plane(TLNear, BLNear, BRNear);
|
|
planes[5] = plane(TLFar, TRFar, BRFar);
|
|
}
|
|
|
|
bool DepthCameraFrustum::inside(const Eigen::Vector3f& p) const
|
|
{
|
|
// Faces 0..2 pass through BRNear, faces 3..5 through TLFar.
|
|
for (int i = 0; i < 6; ++i)
|
|
{
|
|
const Eigen::Vector3f& corner = i < 3 ? vertices[3] : vertices[4];
|
|
if ((p - corner).dot(normals[i]) < 0.f)
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
bool DepthCameraFrustum::nearFace(const Eigen::Vector3f& p) const
|
|
{
|
|
for (const Eigen::Vector4f& pl : planes)
|
|
{
|
|
const float dis = std::fabs(pl[0] * p.x() + pl[1] * p.y() + pl[2] * p.z() + pl[3]) /
|
|
std::sqrt(pl[0] * pl[0] + pl[1] * pl[1] + pl[2] * pl[2]);
|
|
if (dis <= kAttachDistance &&
|
|
std::hypot(p.x() - origin.x(), p.y() - origin.y()) < max_detect_distance + 0.5)
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
bool insideAnyFrustum(const std::vector<DepthCameraFrustum>& frustums, const Eigen::Vector3f& p)
|
|
{
|
|
for (const DepthCameraFrustum& f : frustums)
|
|
if (f.inside(p))
|
|
return true;
|
|
return false;
|
|
}
|
|
|
|
bool attachedToFrustums(const std::vector<DepthCameraFrustum>& frustums, const Eigen::Vector3f& p)
|
|
{
|
|
for (std::size_t i = 0; i < frustums.size(); ++i)
|
|
{
|
|
if (!frustums[i].nearFace(p))
|
|
continue;
|
|
// Attached to this one; not attached overall if it lies well inside another camera's frustum.
|
|
for (std::size_t j = 0; j < frustums.size(); ++j)
|
|
if (j != i && !frustums[j].nearFace(p) && frustums[j].inside(p))
|
|
return false;
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------------------------
|
|
// Layer
|
|
// ---------------------------------------------------------------------------------------------
|
|
|
|
DepthCameraObstacleLayer::DepthCameraObstacleLayer()
|
|
{
|
|
costmap_ = NULL; // the unsigned char* of the parent Costmap2D
|
|
}
|
|
|
|
DepthCameraObstacleLayer::~DepthCameraObstacleLayer() = default;
|
|
|
|
void DepthCameraObstacleLayer::onInitialize()
|
|
{
|
|
rolling_window_ = layered_costmap_->isRolling();
|
|
global_frame_ = layered_costmap_->getGlobalFrameID();
|
|
loadParameters();
|
|
matchSize();
|
|
current_ = true;
|
|
last_stats_log_ = robot::Time::now();
|
|
}
|
|
|
|
void DepthCameraObstacleLayer::loadParameters()
|
|
{
|
|
// Step 1 of the config flow: the default file, like the other layers. A missing file or block
|
|
// stops the costmap from being built instead of running on C++ defaults.
|
|
const std::string config_file_name = "depth_camera_obstacle_layer_params.yaml";
|
|
const char* env_config = std::getenv("PNKX_NAV_CORE_CONFIG_DIR");
|
|
const std::string folder = (env_config && std::filesystem::exists(env_config)) ? env_config : "";
|
|
YAML::Node config;
|
|
try
|
|
{
|
|
config = YAML::LoadFile(getSourceFile(folder, config_file_name));
|
|
}
|
|
catch (const YAML::BadFile&)
|
|
{
|
|
throw std::runtime_error("DepthCameraObstacleLayer " + name_ + ": cannot open the default file " +
|
|
config_file_name);
|
|
}
|
|
YAML::Node layer = config["depth_camera_obstacle_layer"];
|
|
if (!layer.IsMap())
|
|
throw std::runtime_error("DepthCameraObstacleLayer " + name_ + ": " + config_file_name +
|
|
" has no depth_camera_obstacle_layer: block");
|
|
|
|
// Step 3: "<costmap>/<plugin>", filled by copyParentParameters() from the shared block.
|
|
robot::NodeHandle nh("~");
|
|
const robot::NodeHandle priv_nh(nh, name_);
|
|
|
|
// Not in the default file on purpose: unset, the layer follows the costmap's track_unknown_space.
|
|
const bool track_unknown_space =
|
|
readParam(layer, priv_nh, "track_unknown_space", layered_costmap_->isTrackingUnknown());
|
|
default_value_ = track_unknown_space ? NO_INFORMATION : FREE_SPACE;
|
|
|
|
enabled_ = readParam(layer, priv_nh, "enabled", true);
|
|
footprint_clearing_enabled_ = readParam(layer, priv_nh, "footprint_clearing_enabled", true);
|
|
combination_method_ = readParam(layer, priv_nh, "combination_method", 1);
|
|
enable_near_blocked_protection_ = readParam(layer, priv_nh, "enable_near_blocked_protection", true);
|
|
number_points_considered_as_blocked_ = readParam(layer, priv_nh, "number_points_considered_as_blocked", 5);
|
|
forced_clearing_distance_ = readParam(layer, priv_nh, "forced_clearing_distance", 0.1);
|
|
ec_seg_distance_ = readParam(layer, priv_nh, "ec_seg_distance", 0.2);
|
|
ec_cluster_min_size_ = readParam(layer, priv_nh, "ec_cluster_min_size", 5);
|
|
size_of_cluster_rejection_ = readParam(layer, priv_nh, "size_of_cluster_rejection", 5);
|
|
voxel_resolution_ = readParam(layer, priv_nh, "voxel_resolution", 0.01);
|
|
check_radius_ = readParam(layer, priv_nh, "check_radius", 0.1);
|
|
number_clearing_threshold_ = readParam(layer, priv_nh, "number_clearing_threshold", 2);
|
|
use_voxelized_observation_ = readParam(layer, priv_nh, "use_voxelized_observation", true);
|
|
transform_tolerance_ = readParam(layer, priv_nh, "transform_tolerance", 0.2);
|
|
const bool use_global_frame_to_mark = readParam(layer, priv_nh, "use_global_frame_to_mark", true);
|
|
if (layer["clear_touches_bounds"] || priv_nh.hasParam("clear_touches_bounds"))
|
|
robot::log_warning("DepthCameraObstacleLayer %s: clear_touches_bounds is obsolete and ignored: a cleared "
|
|
"cell now always resets its master cell\n", name_.c_str());
|
|
YAML::Node debug = layer["debug"];
|
|
debug_stats_ = readParam(debug, "stats", priv_nh, "debug/stats", true);
|
|
debug_stats_period_ = readParam(debug, "stats_period", priv_nh, "debug/stats_period", 5.0);
|
|
|
|
// The source's local mode keys points by costmap index, so markings move with a rolling
|
|
// window (its README shows it). Only the global mode is ported.
|
|
requireRange(use_global_frame_to_mark, "use_global_frame_to_mark: false is not ported");
|
|
requireRange(voxel_resolution_ > 0.0 && std::isfinite(voxel_resolution_), "voxel_resolution must be > 0");
|
|
requireRange(check_radius_ > 0.0 && std::isfinite(check_radius_), "check_radius must be > 0");
|
|
requireRange(ec_seg_distance_ > 0.0 && std::isfinite(ec_seg_distance_), "ec_seg_distance must be > 0");
|
|
requireRange(ec_cluster_min_size_ >= 1, "ec_cluster_min_size must be >= 1");
|
|
requireRange(size_of_cluster_rejection_ >= 0, "size_of_cluster_rejection must be >= 0");
|
|
requireRange(number_clearing_threshold_ >= 1, "number_clearing_threshold must be >= 1");
|
|
requireRange(number_points_considered_as_blocked_ >= 0, "number_points_considered_as_blocked must be >= 0");
|
|
requireRange(forced_clearing_distance_ >= 0.0, "forced_clearing_distance must be >= 0");
|
|
requireRange(transform_tolerance_ >= 0.0 && std::isfinite(transform_tolerance_), "transform_tolerance must be >= 0");
|
|
requireRange(debug_stats_period_ > 0.0, "debug/stats_period must be > 0");
|
|
|
|
marking_height_under_ground_ = 100.0;
|
|
marking_height_above_ground_ = -100.0;
|
|
|
|
std::stringstream ss(readParam(layer, priv_nh, "observation_sources", std::string("")));
|
|
std::string name;
|
|
while (ss >> name)
|
|
{
|
|
// Like obstacle_layer_params.yaml, the default file has no block per source, so a source key
|
|
// comes from "<costmap>/<plugin>/<source>/" or falls back to the C++ default below.
|
|
YAML::Node source_defaults = layer[name];
|
|
const robot::NodeHandle s(priv_nh, name);
|
|
std::unique_ptr<Source> src(new Source());
|
|
src->name = name;
|
|
src->topic = readParam(source_defaults, s, "topic", name);
|
|
src->sensor_frame = readParam(source_defaults, s, "sensor_frame", std::string(""));
|
|
src->sensor_frame_is_optical = readParam(source_defaults, s, "sensor_frame_is_optical", false);
|
|
src->observation_keep_time = readParam(source_defaults, s, "observation_persistence", 0.0);
|
|
src->expected_update_rate = readParam(source_defaults, s, "expected_update_rate", 0.0);
|
|
src->min_obstacle_height = readParam(source_defaults, s, "min_obstacle_height", 0.0);
|
|
src->max_obstacle_height = readParam(source_defaults, s, "max_obstacle_height", 2.0);
|
|
src->marking = readParam(source_defaults, s, "marking", true);
|
|
src->fov_v = readParam(source_defaults, s, "FOV_V", 1.0);
|
|
src->fov_w = readParam(source_defaults, s, "FOV_W", 1.5);
|
|
src->min_detect_distance = readParam(source_defaults, s, "min_detect_distance", 0.15);
|
|
src->max_detect_distance = readParam(source_defaults, s, "max_detect_distance", 2.5);
|
|
if (readParam(source_defaults, s, "inf_is_valid", false))
|
|
robot::log_warning("DepthCameraObstacleLayer: inf_is_valid is not applicable to PointCloud observations\n");
|
|
|
|
const std::string what = "source " + name + ": ";
|
|
requireRange(src->fov_w > 0.0 && src->fov_w < M_PI, what + "FOV_W must be in (0, pi) [rad]");
|
|
requireRange(src->fov_v > 0.0 && src->fov_v < M_PI, what + "FOV_V must be in (0, pi) [rad]");
|
|
requireRange(src->min_detect_distance >= 0.0 && src->max_detect_distance > src->min_detect_distance,
|
|
what + "need 0 <= min_detect_distance < max_detect_distance [m]");
|
|
requireRange(src->min_obstacle_height <= src->max_obstacle_height,
|
|
what + "min_obstacle_height must be <= max_obstacle_height [m]");
|
|
requireRange(src->observation_keep_time >= 0.0 && src->expected_update_rate >= 0.0,
|
|
what + "observation_persistence and expected_update_rate must be >= 0 [s]");
|
|
|
|
// Update minimum height and maximum height for overall marking.
|
|
marking_height_above_ground_ = std::max(marking_height_above_ground_, src->max_obstacle_height);
|
|
marking_height_under_ground_ = std::min(marking_height_under_ground_, src->min_obstacle_height);
|
|
src->last_updated = robot::Time::now();
|
|
|
|
robot::log_info("DepthCameraObstacleLayer %s: source %s topic=%s sensor_frame=%s optical=%s "
|
|
"FOV_W=%.3f FOV_V=%.3f rad detect=[%.2f, %.2f] m height=[%.2f, %.2f] m "
|
|
"persistence=%.2f s expected_update_rate=%.2f s marking=%s\n",
|
|
name_.c_str(), name.c_str(), src->topic.c_str(),
|
|
src->sensor_frame.empty() ? "(cloud frame)" : src->sensor_frame.c_str(),
|
|
src->sensor_frame_is_optical ? "true" : "false", src->fov_w, src->fov_v,
|
|
src->min_detect_distance, src->max_detect_distance, src->min_obstacle_height,
|
|
src->max_obstacle_height, src->observation_keep_time, src->expected_update_rate,
|
|
src->marking ? "true" : "false");
|
|
sources_.push_back(std::move(src));
|
|
}
|
|
if (sources_.empty())
|
|
robot::log_warning("DepthCameraObstacleLayer %s: observation_sources is empty, the layer marks nothing\n",
|
|
name_.c_str());
|
|
|
|
robot::log_info("DepthCameraObstacleLayer %s: global_frame=%s rolling=%s track_unknown=%s "
|
|
"voxel_resolution=%.3f m check_radius=%.3f m number_clearing_threshold=%d "
|
|
"ec_seg_distance=%.2f m ec_cluster_min_size=%d size_of_cluster_rejection=%d "
|
|
"forced_clearing_distance=%.2f m near_blocked_protection=%s (%d pts) "
|
|
"voxelized_observation=%s transform_tolerance=%.2f s combination_method=%d "
|
|
"footprint_clearing=%s marking_height=[%.2f, %.2f] m debug/stats=%s\n",
|
|
name_.c_str(), global_frame_.c_str(), rolling_window_ ? "true" : "false",
|
|
track_unknown_space ? "true" : "false", voxel_resolution_, check_radius_,
|
|
number_clearing_threshold_, ec_seg_distance_, ec_cluster_min_size_,
|
|
size_of_cluster_rejection_, forced_clearing_distance_,
|
|
enable_near_blocked_protection_ ? "true" : "false", number_points_considered_as_blocked_,
|
|
use_voxelized_observation_ ? "true" : "false", transform_tolerance_, combination_method_,
|
|
footprint_clearing_enabled_ ? "true" : "false",
|
|
marking_height_under_ground_, marking_height_above_ground_, debug_stats_ ? "on" : "off");
|
|
}
|
|
|
|
void DepthCameraObstacleLayer::handleImpl(const void* data, const std::type_info& type,
|
|
const std::string& topic)
|
|
{
|
|
// DepthCameraData, LaserScan, ... are meant for other layers of the same type.
|
|
if (type != typeid(robot_sensor_msgs::PointCloud2))
|
|
return;
|
|
const auto& cloud = *static_cast<const robot_sensor_msgs::PointCloud2*>(data);
|
|
std::shared_ptr<const robot_sensor_msgs::PointCloud2> copy;
|
|
for (const auto& source : sources_)
|
|
{
|
|
if (source->topic != topic)
|
|
continue;
|
|
if (!copy)
|
|
copy = std::make_shared<const robot_sensor_msgs::PointCloud2>(cloud);
|
|
// Newest only: the source buffer keeps one observation, and a cloud still waiting for its
|
|
// TF is superseded by a newer one, like a full tf2_ros::MessageFilter queue.
|
|
std::lock_guard<std::mutex> lock(source->pending_mutex);
|
|
source->pending = copy;
|
|
}
|
|
}
|
|
|
|
bool DepthCameraObstacleLayer::processPending(Source& source)
|
|
{
|
|
std::shared_ptr<const robot_sensor_msgs::PointCloud2> cloud;
|
|
{
|
|
std::lock_guard<std::mutex> lock(source.pending_mutex);
|
|
cloud = source.pending;
|
|
}
|
|
if (!cloud)
|
|
return false;
|
|
|
|
bool done = true;
|
|
try
|
|
{
|
|
bufferCloud(source, *cloud);
|
|
}
|
|
catch (const tf3::TransformException& ex)
|
|
{
|
|
// Measurement TF only, never the latest TF. Wait while the cloud is younger than the
|
|
// tolerance, then drop it.
|
|
const double age = (robot::Time::now() - cloud->header.stamp).toSec();
|
|
if (age <= transform_tolerance_)
|
|
{
|
|
++stats_.tf_waits;
|
|
done = false;
|
|
}
|
|
else
|
|
{
|
|
++stats_.tf_drops;
|
|
robot::log_error_throttle(5.0, "DepthCameraObstacleLayer %s: no TF %s <- %s at the cloud stamp "
|
|
"(%.3f s old), cloud dropped: %s\n", name_.c_str(), global_frame_.c_str(),
|
|
cloud->header.frame_id.c_str(), age, ex.what());
|
|
}
|
|
}
|
|
catch (const std::exception& ex)
|
|
{
|
|
robot::log_error_throttle(5.0, "DepthCameraObstacleLayer %s: malformed cloud on %s dropped: %s\n",
|
|
name_.c_str(), source.topic.c_str(), ex.what());
|
|
}
|
|
|
|
if (done)
|
|
{
|
|
std::lock_guard<std::mutex> lock(source.pending_mutex);
|
|
if (source.pending == cloud)
|
|
source.pending.reset();
|
|
}
|
|
return done;
|
|
}
|
|
|
|
bool DepthCameraObstacleLayer::bufferCloud(Source& source, const robot_sensor_msgs::PointCloud2& cloud)
|
|
{
|
|
if (cloud.header.frame_id.empty())
|
|
throw std::invalid_argument("cloud has no frame_id");
|
|
const std::string origin_frame = source.sensor_frame.empty() ? cloud.header.frame_id : source.sensor_frame;
|
|
const tf3::Time stamp = data_convert::convertTime(cloud.header.stamp);
|
|
|
|
const Eigen::Isometry3d T_cloud = toIsometry(tf_->lookupTransform(global_frame_, cloud.header.frame_id, stamp));
|
|
const Eigen::Isometry3d T_origin = origin_frame == cloud.header.frame_id
|
|
? T_cloud : toIsometry(tf_->lookupTransform(global_frame_, origin_frame, stamp));
|
|
|
|
Observation obs;
|
|
obs.stamp = cloud.header.stamp;
|
|
// Frustum vertices are given in the sensor frame, then everything is in the global frame.
|
|
obs.frustum.build(T_origin, source.fov_w, source.fov_v, source.min_detect_distance,
|
|
source.max_detect_distance, source.sensor_frame_is_optical);
|
|
|
|
const std::size_t size = static_cast<std::size_t>(cloud.width) * cloud.height;
|
|
obs.points.reserve(size);
|
|
robot_sensor_msgs::PointCloud2ConstIterator<float> iter_x(cloud, "x");
|
|
robot_sensor_msgs::PointCloud2ConstIterator<float> iter_y(cloud, "y");
|
|
robot_sensor_msgs::PointCloud2ConstIterator<float> iter_z(cloud, "z");
|
|
for (std::size_t i = 0; i < size; ++i, ++iter_x, ++iter_y, ++iter_z)
|
|
{
|
|
// The source relies on dense clouds; NaN would only disappear later in PCL. Drop it here.
|
|
if (!std::isfinite(*iter_x) || !std::isfinite(*iter_y) || !std::isfinite(*iter_z))
|
|
continue;
|
|
const Eigen::Vector3d g = T_cloud * Eigen::Vector3d(*iter_x, *iter_y, *iter_z);
|
|
if (g.z() <= source.max_obstacle_height && g.z() >= source.min_obstacle_height)
|
|
obs.points.push_back(g.cast<float>());
|
|
}
|
|
|
|
source.observations.push_front(std::move(obs));
|
|
source.last_updated = robot::Time::now();
|
|
purgeStale(source);
|
|
return true;
|
|
}
|
|
|
|
void DepthCameraObstacleLayer::purgeStale(Source& source) const
|
|
{
|
|
if (source.observations.empty())
|
|
return;
|
|
// Keeping observations for no time keeps exactly one.
|
|
if (source.observation_keep_time == 0.0)
|
|
{
|
|
source.observations.erase(std::next(source.observations.begin()), source.observations.end());
|
|
return;
|
|
}
|
|
for (auto it = source.observations.begin(); it != source.observations.end(); ++it)
|
|
{
|
|
if ((source.last_updated - it->stamp).toSec() > source.observation_keep_time)
|
|
{
|
|
source.observations.erase(it, source.observations.end());
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
bool DepthCameraObstacleLayer::sourceIsCurrent(const Source& source) const
|
|
{
|
|
if (source.expected_update_rate == 0.0)
|
|
return true;
|
|
const double since = (robot::Time::now() - source.last_updated).toSec();
|
|
const bool current = since <= source.expected_update_rate;
|
|
if (!current)
|
|
robot::log_warning_throttle(5.0, "DepthCameraObstacleLayer %s: source %s not updated for %.2f s, expected "
|
|
"every %.2f s\n", name_.c_str(), source.name.c_str(), since,
|
|
source.expected_update_rate);
|
|
return current;
|
|
}
|
|
|
|
void DepthCameraObstacleLayer::updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x,
|
|
double* min_y, double* max_x, double* max_y)
|
|
{
|
|
// ClearCostmapRecovery and resetLayers() reach the stored points from other threads.
|
|
boost::unique_lock<mutex_t> lock(*getMutex());
|
|
if (rolling_window_)
|
|
updateOrigin(robot_x - getSizeInMetersX() / 2, robot_y - getSizeInMetersY() / 2);
|
|
if (!enabled_)
|
|
return;
|
|
const auto start = std::chrono::steady_clock::now();
|
|
useExtraBounds(min_x, min_y, max_x, max_y);
|
|
dropColumnsOutsideWindow(min_x, min_y, max_x, max_y);
|
|
|
|
bool current = true;
|
|
std::vector<DepthCameraFrustum> frustums;
|
|
std::vector<Eigen::Vector3f> combined;
|
|
for (const auto& source : sources_)
|
|
{
|
|
if (!source->marking)
|
|
continue; // the source marks and clears with marking observations only
|
|
processPending(*source);
|
|
purgeStale(*source);
|
|
for (const Observation& obs : source->observations)
|
|
{
|
|
frustums.push_back(obs.frustum);
|
|
combined.insert(combined.end(), obs.points.begin(), obs.points.end());
|
|
}
|
|
current = sourceIsCurrent(*source) && current;
|
|
}
|
|
current_ = current;
|
|
|
|
pcl::PointCloud<pcl::PointXYZI>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZI>);
|
|
cloud->points.reserve(combined.size());
|
|
for (const Eigen::Vector3f& q : combined)
|
|
{
|
|
pcl::PointXYZI pt;
|
|
pt.x = q.x();
|
|
pt.y = q.y();
|
|
pt.z = q.z();
|
|
pt.intensity = 0.f;
|
|
cloud->points.push_back(pt);
|
|
}
|
|
cloud->width = static_cast<std::uint32_t>(cloud->points.size());
|
|
cloud->height = 1;
|
|
cloud->is_dense = true;
|
|
|
|
// Voxelized combined observation to save computation.
|
|
if (use_voxelized_observation_ && !cloud->points.empty())
|
|
{
|
|
pcl::VoxelGrid<pcl::PointXYZI> voxel;
|
|
voxel.setLeafSize(kObservationLeaf, kObservationLeaf, kObservationLeaf);
|
|
voxel.setInputCloud(cloud);
|
|
pcl::PointCloud<pcl::PointXYZI>::Ptr filtered(new pcl::PointCloud<pcl::PointXYZI>);
|
|
voxel.filter(*filtered);
|
|
cloud = filtered;
|
|
}
|
|
std::vector<Eigen::Vector3f> points;
|
|
points.reserve(cloud->points.size());
|
|
for (const auto& pt : cloud->points)
|
|
points.emplace_back(pt.x, pt.y, pt.z);
|
|
stats_.cloud_points += points.size();
|
|
|
|
clearMarkingByKdtree(points, frustums, robot_x, robot_y, min_x, min_y, max_x, max_y);
|
|
|
|
if (cloud->points.size() > 5)
|
|
{
|
|
pcl::search::KdTree<pcl::PointXYZI>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZI>);
|
|
tree->setInputCloud(cloud);
|
|
std::vector<pcl::PointIndices> clusters;
|
|
pcl::EuclideanClusterExtraction<pcl::PointXYZI> ec;
|
|
ec.setClusterTolerance(ec_seg_distance_);
|
|
ec.setMinClusterSize(ec_cluster_min_size_);
|
|
ec.setMaxClusterSize(static_cast<int>(cloud->points.size()));
|
|
ec.setSearchMethod(tree);
|
|
ec.setInputCloud(cloud);
|
|
ec.extract(clusters);
|
|
std::vector<Eigen::Vector3f> cluster;
|
|
for (const pcl::PointIndices& indices : clusters)
|
|
{
|
|
// PCL can still output clusters below ec_cluster_min_size; the source rejects them here.
|
|
if (static_cast<int>(indices.indices.size()) <= size_of_cluster_rejection_)
|
|
continue;
|
|
cluster.clear();
|
|
for (int idx : indices.indices)
|
|
cluster.push_back(points[idx]);
|
|
processCluster(frustums, cluster, min_x, min_y, max_x, max_y);
|
|
}
|
|
}
|
|
updateFootprint(robot_x, robot_y, robot_yaw, min_x, min_y, max_x, max_y);
|
|
|
|
const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
|
|
++stats_.cycles;
|
|
stats_.bounds_ms_sum += ms;
|
|
stats_.bounds_ms_max = std::max(stats_.bounds_ms_max, ms);
|
|
logStats();
|
|
}
|
|
|
|
void DepthCameraObstacleLayer::clearMarkingByKdtree(const std::vector<Eigen::Vector3f>& cloud,
|
|
const std::vector<DepthCameraFrustum>& frustums,
|
|
double robot_x, double robot_y, double* min_x,
|
|
double* min_y, double* max_x, double* max_y)
|
|
{
|
|
bool bypass_clearing = false;
|
|
if (enable_near_blocked_protection_ &&
|
|
static_cast<int>(cloud.size()) < number_points_considered_as_blocked_)
|
|
{
|
|
robot::log_warning_throttle(30.0, "DepthCameraObstacleLayer %s: blocked by something, clearing is skipped\n",
|
|
name_.c_str());
|
|
bypass_clearing = true;
|
|
}
|
|
|
|
bool clear_all_marking_in_this_frame = false;
|
|
pcl::KdTreeFLANN<pcl::PointXYZI> kdtree;
|
|
if (cloud.size() > 5)
|
|
{
|
|
pcl::PointCloud<pcl::PointXYZI>::Ptr input(new pcl::PointCloud<pcl::PointXYZI>);
|
|
input->points.reserve(cloud.size());
|
|
for (const Eigen::Vector3f& q : cloud)
|
|
{
|
|
pcl::PointXYZI pt;
|
|
pt.x = q.x();
|
|
pt.y = q.y();
|
|
pt.z = q.z();
|
|
pt.intensity = 0.f;
|
|
input->points.push_back(pt);
|
|
}
|
|
input->width = static_cast<std::uint32_t>(input->points.size());
|
|
input->height = 1;
|
|
kdtree.setInputCloud(input);
|
|
}
|
|
else if (!enable_near_blocked_protection_)
|
|
clear_all_marking_in_this_frame = true; // we really see nothing in the space
|
|
else
|
|
bypass_clearing = true;
|
|
if (clear_all_marking_in_this_frame)
|
|
++stats_.cleared_all_frames;
|
|
else if (bypass_clearing)
|
|
++stats_.bypassed_frames;
|
|
|
|
const double resolution = layered_costmap_->getCostmap()->getResolution();
|
|
std::vector<int> indices;
|
|
std::vector<float> sq_distances;
|
|
for (auto column = pc_3d_map_global_.begin(); column != pc_3d_map_global_.end();)
|
|
{
|
|
double wx, wy;
|
|
intIndexToWorld(wx, wy, column->first.first, column->first.second, resolution);
|
|
// Marked points this far from the robot are out of every frustum.
|
|
const double pc_dis = std::hypot(wx - robot_x, wy - robot_y);
|
|
if (pc_dis > kClearingSkipDistance)
|
|
{
|
|
++column;
|
|
continue;
|
|
}
|
|
|
|
auto& heights = column->second;
|
|
for (auto it = heights.begin(), next_it = it; it != heights.end(); it = next_it)
|
|
{
|
|
++next_it;
|
|
// Clearing tests the stored cell-corner position; the attach band is cleared too.
|
|
const Eigen::Vector3f search(static_cast<float>(wx), static_cast<float>(wy),
|
|
static_cast<float>(it->first * voxel_resolution_));
|
|
if (!insideAnyFrustum(frustums, search))
|
|
continue;
|
|
bool erase = false;
|
|
if (clear_all_marking_in_this_frame)
|
|
erase = true;
|
|
else if (!bypass_clearing && pc_dis <= forced_clearing_distance_)
|
|
erase = true;
|
|
else if (!bypass_clearing)
|
|
{
|
|
pcl::PointXYZI q;
|
|
q.x = search.x();
|
|
q.y = search.y();
|
|
q.z = search.z();
|
|
erase = kdtree.radiusSearch(q, check_radius_, indices, sq_distances) < number_clearing_threshold_;
|
|
}
|
|
if (!erase)
|
|
continue;
|
|
heights.erase(it);
|
|
++stats_.cleared;
|
|
}
|
|
// The last point of the column is gone: the cell is free again, in the own grid and,
|
|
// through the bounds, in the master this cycle.
|
|
column = heights.empty() ? eraseColumn(column, min_x, min_y, max_x, max_y) : std::next(column);
|
|
}
|
|
}
|
|
|
|
void DepthCameraObstacleLayer::processCluster(const std::vector<DepthCameraFrustum>& frustums,
|
|
const std::vector<Eigen::Vector3f>& cluster, double* min_x,
|
|
double* min_y, double* max_x, double* max_y)
|
|
{
|
|
const double resolution = layered_costmap_->getCostmap()->getResolution();
|
|
const int h_max = static_cast<int>(marking_height_above_ground_ / voxel_resolution_);
|
|
const int h_min = static_cast<int>(marking_height_under_ground_ / voxel_resolution_);
|
|
for (const Eigen::Vector3f& p : cluster)
|
|
{
|
|
// Robust marking condition: the raw point, inside a frustum and away from its faces.
|
|
if (!insideAnyFrustum(frustums, p) || attachedToFrustums(frustums, p))
|
|
continue;
|
|
int mmx, mmy;
|
|
worldToIntIndex(p.x(), p.y(), mmx, mmy, resolution);
|
|
const int h_ind = static_cast<int>(std::round(p.z() * (1 / voxel_resolution_)));
|
|
if (h_ind > h_max || h_ind < h_min)
|
|
continue;
|
|
const std::pair<int, int> key(mmx, mmy);
|
|
unsigned int cx, cy;
|
|
if (!columnCell(key, cx, cy))
|
|
continue; // would be dropped as out of the window anyway
|
|
auto& slot = pc_3d_map_global_[key];
|
|
auto inserted = slot.insert(std::make_pair(h_ind, 0.f));
|
|
if (inserted.second)
|
|
++stats_.marked;
|
|
setCost(cx, cy, LETHAL_OBSTACLE);
|
|
double wx, wy;
|
|
intIndexToWorld(wx, wy, mmx, mmy, resolution);
|
|
touch(wx, wy, min_x, min_y, max_x, max_y);
|
|
}
|
|
}
|
|
|
|
void DepthCameraObstacleLayer::updateFootprint(double robot_x, double robot_y, double robot_yaw, double* min_x,
|
|
double* min_y, double* max_x, double* max_y)
|
|
{
|
|
if (!footprint_clearing_enabled_)
|
|
return;
|
|
transformFootprint(robot_x, robot_y, robot_yaw, getFootprint(), transformed_footprint_);
|
|
for (const auto& pt : transformed_footprint_)
|
|
touch(pt.x, pt.y, min_x, min_y, max_x, max_y);
|
|
|
|
// updateCosts() frees the footprint in the own grid like ObstacleLayer; the stored points under
|
|
// it must go too, or the next marking pass would not bring them back but nothing would ever
|
|
// remove them either.
|
|
std::vector<MapLocation> polygon, cells;
|
|
for (const auto& pt : transformed_footprint_)
|
|
{
|
|
MapLocation loc;
|
|
if (!worldToMap(pt.x, pt.y, loc.x, loc.y))
|
|
return; // footprint leaves the window: same give-up as setConvexPolygonCost
|
|
polygon.push_back(loc);
|
|
}
|
|
if (polygon.size() < 3)
|
|
return;
|
|
convexFillCells(polygon, cells);
|
|
std::unordered_set<unsigned int> under;
|
|
for (const MapLocation& c : cells)
|
|
under.insert(getIndex(c.x, c.y));
|
|
for (auto it = pc_3d_map_global_.begin(); it != pc_3d_map_global_.end();)
|
|
{
|
|
unsigned int mx, my;
|
|
if (columnCell(it->first, mx, my) && under.count(getIndex(mx, my)))
|
|
{
|
|
++stats_.footprint_cleared;
|
|
it = eraseColumn(it, min_x, min_y, max_x, max_y);
|
|
}
|
|
else
|
|
++it;
|
|
}
|
|
}
|
|
|
|
bool DepthCameraObstacleLayer::isValid(int mx, int my) const
|
|
{
|
|
// Same result as the source's unsigned test: mx - 1 of cell 0 is out of range.
|
|
return mx >= 0 && my >= 0 && mx <= static_cast<int>(getSizeInCellsX()) &&
|
|
my <= static_cast<int>(getSizeInCellsY());
|
|
}
|
|
|
|
bool DepthCameraObstacleLayer::columnCell(const std::pair<int, int>& column, unsigned int& mx,
|
|
unsigned int& my) const
|
|
{
|
|
double wx, wy;
|
|
intIndexToWorld(wx, wy, column.first, column.second, getResolution());
|
|
if (!worldToMap(wx, wy, mx, my))
|
|
return false;
|
|
// The +-1 cells guard the rounding of the stored corner, as in the source.
|
|
const int x = static_cast<int>(mx), y = static_cast<int>(my);
|
|
return isValid(x - 1, y - 1) && isValid(x - 1, y + 1) && isValid(x + 1, y - 1) && isValid(x + 1, y + 1);
|
|
}
|
|
|
|
std::map<std::pair<int, int>, std::map<int, float>>::iterator DepthCameraObstacleLayer::eraseColumn(
|
|
std::map<std::pair<int, int>, std::map<int, float>>::iterator it, double* min_x, double* min_y,
|
|
double* max_x, double* max_y)
|
|
{
|
|
unsigned int mx, my;
|
|
if (columnCell(it->first, mx, my))
|
|
{
|
|
setCost(mx, my, FREE_SPACE);
|
|
double wx, wy;
|
|
intIndexToWorld(wx, wy, it->first.first, it->first.second, getResolution());
|
|
touch(wx, wy, min_x, min_y, max_x, max_y);
|
|
}
|
|
return pc_3d_map_global_.erase(it);
|
|
}
|
|
|
|
void DepthCameraObstacleLayer::dropColumnsOutsideWindow(double* min_x, double* min_y, double* max_x,
|
|
double* max_y)
|
|
{
|
|
for (auto it = pc_3d_map_global_.begin(); it != pc_3d_map_global_.end();)
|
|
{
|
|
unsigned int mx, my;
|
|
if (columnCell(it->first, mx, my))
|
|
{
|
|
// Keep the own grid in step with the points even after matchSize() or a cleared area
|
|
// wiped the cell: one O(columns) pass that writes only when something is missing.
|
|
if (getCost(mx, my) != LETHAL_OBSTACLE)
|
|
{
|
|
setCost(mx, my, LETHAL_OBSTACLE);
|
|
double wx, wy;
|
|
intIndexToWorld(wx, wy, it->first.first, it->first.second, getResolution());
|
|
touch(wx, wy, min_x, min_y, max_x, max_y);
|
|
}
|
|
++it;
|
|
continue;
|
|
}
|
|
// B6: the source keeps such points forever, so the map and every loop over it grow.
|
|
++stats_.dropped_out_of_window;
|
|
double wx, wy;
|
|
intIndexToWorld(wx, wy, it->first.first, it->first.second, getResolution());
|
|
if (worldToMap(wx, wy, mx, my))
|
|
{
|
|
// Still inside the window, on its edge row/column: free that cell as well.
|
|
setCost(mx, my, FREE_SPACE);
|
|
touch(wx, wy, min_x, min_y, max_x, max_y);
|
|
}
|
|
it = pc_3d_map_global_.erase(it);
|
|
}
|
|
}
|
|
|
|
void DepthCameraObstacleLayer::updateCosts(Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j)
|
|
{
|
|
boost::unique_lock<mutex_t> lock(*getMutex());
|
|
if (!enabled_)
|
|
return;
|
|
|
|
// The own grid mirrors the stored points (see updateBounds), so the layer merges like
|
|
// ObstacleLayer and the master is only changed inside the update bounds.
|
|
if (footprint_clearing_enabled_)
|
|
setConvexPolygonCost(transformed_footprint_, FREE_SPACE);
|
|
|
|
switch (combination_method_)
|
|
{
|
|
case 0: // Overwrite
|
|
updateWithOverwrite(master_grid, min_i, min_j, max_i, max_j);
|
|
break;
|
|
case 1: // Maximum
|
|
updateWithMax(master_grid, min_i, min_j, max_i, max_j);
|
|
break;
|
|
default: // Nothing
|
|
break;
|
|
}
|
|
}
|
|
|
|
std::size_t DepthCameraObstacleLayer::storedPoints() const
|
|
{
|
|
std::size_t n = 0;
|
|
for (const auto& column : pc_3d_map_global_)
|
|
n += column.second.size();
|
|
return n;
|
|
}
|
|
|
|
void DepthCameraObstacleLayer::logStats()
|
|
{
|
|
const robot::Time now = robot::Time::now();
|
|
const double since = (now - last_stats_log_).toSec();
|
|
if (since < debug_stats_period_ && since >= 0.0)
|
|
return;
|
|
last_stats_log_ = now;
|
|
if (debug_stats_ && stats_.cycles > 0)
|
|
robot::log_info("[debug/stats] DepthCameraObstacleLayer %s: cycles=%zu cloud_pts/cycle=%.0f stored=%zu "
|
|
"columns=%zu marked=%zu cleared=%zu footprint_cleared=%zu clear_all_cycles=%zu bypass_cycles=%zu "
|
|
"tf_wait=%zu tf_drop=%zu out_of_window=%zu bounds_ms avg=%.1f max=%.1f\n",
|
|
name_.c_str(), stats_.cycles, static_cast<double>(stats_.cloud_points) / stats_.cycles,
|
|
storedPoints(), pc_3d_map_global_.size(), stats_.marked, stats_.cleared, stats_.footprint_cleared,
|
|
stats_.cleared_all_frames, stats_.bypassed_frames, stats_.tf_waits, stats_.tf_drops,
|
|
stats_.dropped_out_of_window, stats_.bounds_ms_sum / stats_.cycles, stats_.bounds_ms_max);
|
|
stats_ = Stats();
|
|
}
|
|
|
|
void DepthCameraObstacleLayer::activate()
|
|
{
|
|
for (const auto& source : sources_)
|
|
source->last_updated = robot::Time::now();
|
|
}
|
|
|
|
void DepthCameraObstacleLayer::deactivate()
|
|
{
|
|
// The source unsubscribes and clears its local-mode map only; the global-mode map stays.
|
|
for (const auto& source : sources_)
|
|
{
|
|
std::lock_guard<std::mutex> lock(source->pending_mutex);
|
|
source->pending.reset();
|
|
}
|
|
}
|
|
|
|
void DepthCameraObstacleLayer::reset()
|
|
{
|
|
boost::unique_lock<mutex_t> lock(*getMutex());
|
|
deactivate();
|
|
resetMaps();
|
|
// The source keeps its global-mode points here (B9), so a reset changed nothing on the master.
|
|
pc_3d_map_global_.clear();
|
|
for (const auto& source : sources_)
|
|
source->observations.clear();
|
|
current_ = true;
|
|
activate();
|
|
}
|
|
|
|
void DepthCameraObstacleLayer::matchSize()
|
|
{
|
|
// The master was resized (or this is onInitialize): CostmapLayer::matchSize() rebuilds the own
|
|
// grid with default_value_, so put the stored columns back now instead of waiting a cycle, and
|
|
// ask the next update to merge the whole layer.
|
|
boost::unique_lock<mutex_t> lock(*getMutex());
|
|
CostmapLayer::matchSize();
|
|
for (const auto& column : pc_3d_map_global_)
|
|
{
|
|
unsigned int mx, my;
|
|
if (columnCell(column.first, mx, my))
|
|
setCost(mx, my, LETHAL_OBSTACLE);
|
|
}
|
|
if (!pc_3d_map_global_.empty())
|
|
addExtraBounds(getOriginX(), getOriginY(), getOriginX() + getSizeInMetersX(),
|
|
getOriginY() + getSizeInMetersY());
|
|
}
|
|
|
|
void DepthCameraObstacleLayer::clearArea(int start_x, int start_y, int end_x, int end_y, bool invert_area)
|
|
{
|
|
boost::unique_lock<mutex_t> lock(*getMutex());
|
|
CostmapLayer::clearArea(start_x, start_y, end_x, end_y, invert_area);
|
|
for (auto it = pc_3d_map_global_.begin(); it != pc_3d_map_global_.end();)
|
|
{
|
|
unsigned int mx, my;
|
|
if (columnCell(it->first, mx, my))
|
|
{
|
|
// Same test as CostmapLayer::clearArea: keep what it keeps.
|
|
const int x = static_cast<int>(mx), y = static_cast<int>(my);
|
|
const bool inside = x > start_x && x < end_x && y > start_y && y < end_y;
|
|
if (inside != invert_area)
|
|
{
|
|
++it;
|
|
continue;
|
|
}
|
|
}
|
|
// The own grid cell is already NO_INFORMATION from CostmapLayer::clearArea.
|
|
it = pc_3d_map_global_.erase(it);
|
|
}
|
|
}
|
|
|
|
// Export factory function
|
|
static boost::shared_ptr<Layer> create_depth_camera_obstacle_plugin()
|
|
{
|
|
return boost::make_shared<DepthCameraObstacleLayer>();
|
|
}
|
|
|
|
BOOST_DLL_ALIAS(create_depth_camera_obstacle_plugin, DepthCameraObstacleLayer)
|
|
|
|
} // namespace robot_costmap_2d
|