wip: state before depth cleanup

Uncommitted work as it ran on the KIT robot until 2026-10-20: the ROC observed_volume tuning patch on top of 63707c9 and the DepthCameraObstacleLayer plugin (clone of tsengapola/costmap_depth_camera noetic, B6 window fix), its 17 unit tests and the CMake wiring. Kept as one commit so the cleanup that follows has a recoverable starting point; not meant to be pushed.
This commit is contained in:
2026-10-20 09:36:53 +07:00
parent 63707c968c
commit 9a67eee148
16 changed files with 1816 additions and 13 deletions

View File

@@ -0,0 +1,221 @@
/*********************************************************************
* Port of costmap_depth_camera::DepthCameraObstacleLayer (BSD, Apola),
* https://github.com/tsengapola/costmap_depth_camera, noetic branch 59b7737,
* onto robot_costmap_2d (boost::dll, robot::NodeHandle, tf3).
*
* The algorithm is kept as in the source on purpose, so that it can be compared
* A/B against VoxelLayer on the same robot. Only what the host forces is changed:
* - data arrives through handleImpl() instead of a ROS subscriber, and the cloud
* is processed in updateBounds() once TF at its stamp exists (the role of the
* tf2_ros::MessageFilter in the source);
* - getType() is VOXEL_LAYER, the only type SensorGateway feeds sensor data to;
* - no debug publishers and no dynamic_reconfigure (no ROS inside the core);
* - `sensor_frame_is_optical` builds the frustum in a Z-forward optical frame,
* because this robot's TF has no X-forward camera_link;
* - B6: markings that left the rolling window are dropped instead of kept forever.
* `clear_touches_bounds` (B7) is an optional fix, off by default as in the source.
*********************************************************************/
#ifndef ROBOT_COSTMAP_2D_DEPTH_CAMERA_OBSTACLE_LAYER_H_
#define ROBOT_COSTMAP_2D_DEPTH_CAMERA_OBSTACLE_LAYER_H_
#include <robot/robot.h>
#include <robot_costmap_2d/costmap_layer.h>
#include <robot_costmap_2d/layered_costmap.h>
#include <robot_costmap_2d/footprint.h>
#include <robot_geometry_msgs/Point.h>
#include <robot_sensor_msgs/PointCloud2.h>
#include <tf3/buffer_core.h>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <array>
#include <list>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <utility>
#include <vector>
namespace robot_costmap_2d
{
/**
* @brief Truncated pyramid of one depth camera observation, in the global frame.
*
* Same construction as costmap_depth_camera::Observation: 8 vertices from the configured
* FOV and detect range in the sensor frame, transformed to the global frame, then 6 inward
* normals (inside test) and 6 plane equations (12 cm "attach" band test).
*/
struct DepthCameraFrustum
{
Eigen::Vector3f origin = Eigen::Vector3f::Zero(); ///< sensor origin, global frame [m]
std::array<Eigen::Vector3f, 8> vertices; ///< TLNear TRNear BLNear BRNear TLFar TRFar BLFar BRFar
std::array<Eigen::Vector3f, 6> normals; ///< near right bottom left far top
std::array<Eigen::Vector4f, 6> planes; ///< a, b, c, d of each face
double max_detect_distance = 2.5; ///< [m]
/**
* @brief Build the frustum.
* @param T_global_sensor pose of the sensor frame in the global frame
* @param fov_w, fov_v full horizontal / vertical field of view [rad]
* @param min_d, max_d near / far plane distance along the viewing axis [m]
* @param optical true: sensor frame is Z forward, X right, Y down (REP 103 optical);
* false: X forward, Y left, Z up (camera_link), as the source assumes
*/
void build(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v, double min_d,
double max_d, bool optical);
/// Inside all 6 faces (FrustumUtils::isInsideFRUSTUMwoAttach without the band test).
bool inside(const Eigen::Vector3f& p) const;
/// Within 0.12 m of a face plane and within max_detect_distance + 0.5 m of the origin in XY.
bool nearFace(const Eigen::Vector3f& p) const;
};
/// FrustumUtils::isInsideFRUSTUMs: inside at least one frustum.
bool insideAnyFrustum(const std::vector<DepthCameraFrustum>& frustums, const Eigen::Vector3f& p);
/// FrustumUtils::isAttachFRUSTUMs: near a face of one frustum and not well inside another.
bool attachedToFrustums(const std::vector<DepthCameraFrustum>& frustums, const Eigen::Vector3f& p);
class DepthCameraObstacleLayer : public CostmapLayer
{
public:
DepthCameraObstacleLayer();
~DepthCameraObstacleLayer() override;
void onInitialize() override;
void updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x, double* min_y,
double* max_x, double* max_y) override;
void updateCosts(Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j) override;
void activate() override;
void deactivate() override;
void reset() override;
/// SensorGateway only delivers obstacle data to VOXEL_LAYER plugins.
LayerType getType() const override
{
return LayerType::VOXEL_LAYER;
}
/// Number of stored (column, height) points, for tests and the stats log.
std::size_t storedPoints() const;
protected:
void handleImpl(const void* data, const std::type_info& type, const std::string& topic) override;
private:
/// One observation: cloud after TF and the height gate, plus its frustum (both global frame).
struct Observation
{
robot::Time stamp;
std::vector<Eigen::Vector3f> points;
DepthCameraFrustum frustum;
};
/// ObservationBuffer of the source, one per entry of observation_sources.
struct Source
{
std::string name;
std::string topic;
std::string sensor_frame;
bool sensor_frame_is_optical = false;
double observation_keep_time = 0.0; ///< [s] 0 keeps only the newest observation
double expected_update_rate = 0.0; ///< [s] 0 disables the staleness check
double min_obstacle_height = 0.0; ///< [m] global-frame z gate
double max_obstacle_height = 2.0; ///< [m]
double fov_w = 1.5; ///< [rad]
double fov_v = 1.0; ///< [rad]
double min_detect_distance = 0.15; ///< [m]
double max_detect_distance = 2.5; ///< [m]
bool marking = true;
std::list<Observation> observations; ///< newest first
robot::Time last_updated;
std::mutex pending_mutex; ///< guards pending: handleImpl runs on the producer thread
std::shared_ptr<const robot_sensor_msgs::PointCloud2> pending;
};
void loadParameters();
bool processPending(Source& source);
bool bufferCloud(Source& source, const robot_sensor_msgs::PointCloud2& cloud);
void purgeStale(Source& source) const;
bool sourceIsCurrent(const Source& source) const;
void 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);
void processCluster(const std::vector<DepthCameraFrustum>& frustums,
const std::vector<Eigen::Vector3f>& cluster, double* min_x, double* min_y,
double* max_x, double* max_y);
void updateFootprint(double robot_x, double robot_y, double robot_yaw, double* min_x,
double* min_y, double* max_x, double* max_y);
bool isValid(int mx, int my) const;
void logStats();
// (int)(x / res) toward zero and back to the cell corner, exactly as the source stores points.
void worldToIntIndex(double wx, double wy, int& mx, int& my, double resolution) const
{
mx = static_cast<int>(wx / resolution);
my = static_cast<int>(wy / resolution);
}
void intIndexToWorld(double& wx, double& wy, int mx, int my, double resolution) const
{
wx = mx * resolution;
wy = my * resolution;
}
std::string global_frame_;
bool rolling_window_ = false;
std::vector<std::unique_ptr<Source>> sources_;
// Parameters, names and defaults as in the source.
bool footprint_clearing_enabled_ = true;
int combination_method_ = 1; ///< 0 overwrite, 1 maximum, other: nothing
bool enable_near_blocked_protection_ = true;
int number_points_considered_as_blocked_ = 5;
double forced_clearing_distance_ = 0.1; ///< [m] from robot_base_frame
double ec_seg_distance_ = 0.2; ///< [m] Euclidean cluster tolerance
int ec_cluster_min_size_ = 5;
int size_of_cluster_rejection_ = 5; ///< clusters with <= this many points are not marked
double voxel_resolution_ = 0.01; ///< [m] height quantization of stored points
double check_radius_ = 0.1; ///< [m] kd-tree radius of the "seen again" test
int number_clearing_threshold_ = 2; ///< fewer neighbours than this clears the point
bool use_voxelized_observation_ = true; ///< VoxelGrid 5 cm on the combined cloud
double transform_tolerance_ = 0.2; ///< [s] how long a cloud may wait for its TF
double marking_height_under_ground_ = 100.0;
double marking_height_above_ground_ = -100.0;
// Additions of this port.
bool clear_touches_bounds_ = false; ///< B7 fix: a cleared point also resets its master cell
bool debug_stats_ = true; ///< debug/stats: periodic counters log
double debug_stats_period_ = 5.0; ///< [s]
/// (ix, iy) of the cell corner -> {height index -> label}, global frame (use_global_frame_to_mark).
std::map<std::pair<int, int>, std::map<int, float>> pc_3d_map_global_;
std::vector<robot_geometry_msgs::Point> transformed_footprint_;
struct Stats
{
std::size_t cycles = 0;
std::size_t cloud_points = 0;
std::size_t marked = 0;
std::size_t cleared = 0;
std::size_t cleared_all_frames = 0;
std::size_t bypassed_frames = 0;
std::size_t tf_waits = 0;
std::size_t tf_drops = 0;
std::size_t dropped_out_of_window = 0;
double bounds_ms_sum = 0.0;
double bounds_ms_max = 0.0;
} stats_;
robot::Time last_stats_log_;
};
} // namespace robot_costmap_2d
#endif // ROBOT_COSTMAP_2D_DEPTH_CAMERA_OBSTACLE_LAYER_H_

View File

@@ -48,8 +48,13 @@ public:
unsigned int pointsPerVoxel() const { return points_per_voxel_; }
/// Records a marking point [global frame, m]. fresh = true drops points left over from
/// an earlier occupancy of the voxel (it was not MARKED before this point).
/// an earlier occupancy of the voxel (it was not MARKED before this point). A marking
/// point also restarts the voxel's re-observe miss count.
void add(const VoxelKey& key, const Eigen::Vector3f& point, bool fresh);
/// Re-observe-or-clear: adds weight to the voxel's miss count and returns the new count;
/// 0 when the voxel has no evidence.
float addMiss(const VoxelKey& key, float weight);
void resetMiss(const VoxelKey& key);
/// Distinct evidence points of one voxel. Returns false when the voxel has none.
bool points(const VoxelKey& key, std::vector<Eigen::Vector3d>& out) const;
@@ -75,6 +80,7 @@ private:
std::array<Eigen::Vector3f, kMaxPoints> points;
unsigned char count = 0; ///< valid slots, extremes included
unsigned char next_recent = 0; ///< ring position among the recent slots
float miss = 0.f; ///< re-observe misses since last marked or confirmed
};
unsigned int points_per_voxel_;

View File

@@ -9,6 +9,8 @@ namespace robot_costmap_2d
{
enum class DepthVisibility { Free, Unknown, Surface };
enum class DepthVisibilityReason { Free, OutsideView, InvalidDepth, Surface, EmptyRegion };
/// What one frame says about a marked voxel under the re-observe-or-clear rule, weakest first.
enum class DepthObservation { OutOfView, NoReturn, SeenThrough, Occluded, Confirmed };
struct DepthVisibilityResult
{
DepthVisibility state{DepthVisibility::Unknown};
@@ -35,13 +37,27 @@ public:
*/
DepthVisibilityResult classifyPoints(const std::vector<Eigen::Vector3d>& points) const;
/**
* @brief Re-observes the measured evidence points of one voxel [global frame, m].
*
* Per point, its projection_margin_px patch decides: a valid pixel within confirm_tolerance_m
* of the point is Confirmed; otherwise a valid pixel in front is Occluded; otherwise one
* behind is SeenThrough; otherwise NoReturn. A point outside the trusted depth range, the
* usable image or the stereo band is OutOfView. The voxel takes its strongest point result.
*/
DepthObservation observePoints(const std::vector<Eigen::Vector3d>& points) const;
/// True when a global-frame point projects at least border_px inside the usable image
/// (the clear_left/right border strips are not usable). Used to gate evidence marking.
/// (the clear_left/right border strips and the stereo band are not usable). Used to gate
/// evidence marking, so every marked point can be re-checked later.
bool projectsInside(const Eigen::Vector3d& point, unsigned int border_px) const;
private:
/// Raw depth at a pixel [m]; NaN for an unsupported encoding. Caller checks bounds.
double depthAt(int u, int v) const;
/// First usable image column for a point at depth z [m] > 0: the left border strip or the
/// stereo no-disparity band, whichever is wider.
int usableLeft(double z) const;
robot_sensor_msgs::DepthCameraData::ConstPtr data_;
Eigen::Isometry3d camera_from_global_{Eigen::Isometry3d::Identity()};

View File

@@ -104,6 +104,25 @@ struct DepthFrustumConfig
/// With evidence points, a valid return deeper than valid_max_z_m counts as behind a point
/// that lies at least free_margin_m inside the trusted range: the ray passed the point.
bool far_return_is_behind = false;
/// Re-observe-or-clear rule (needs evidence points). A marked voxel in view must be measured
/// again at one of its points each frame; seen through for miss_frames frames in a row frees
/// it. Occluded, out-of-view and no-return frames keep it, so nothing expires out of the FOV.
/// false: a voxel is freed only when every pixel of every point proves free space.
bool reobserve_clearing = false;
/// [m] Re-observe: |measured - point depth| within this means the surface is still there.
/// Nearer than that is an occluder, deeper is free space seen through. Replaces free_margin_m.
double confirm_tolerance_m = 0.05;
/// [frames] Re-observe: seen-through frames in a row that free a voxel.
unsigned int miss_frames = 3;
/// [0..1] Re-observe: miss added by a frame whose patch pixels are all invalid. 0 keeps invalid
/// depth as unknown; > 0 lets voxels in view expire where the camera returns nothing.
double no_return_weight = 0.0;
/// [m] Stereo baseline of the left no-disparity band, fx * baseline / z + stereo_band_margin_px
/// wide at depth z. Points inside it cannot be re-checked: they are out of view and are not
/// marked. 0 disables (only clear_left_border_px applies).
double stereo_baseline_m = 0.0;
/// [px] Added to the stereo band width.
unsigned int stereo_band_margin_px = 10;
};
class DepthCameraObservation

View File

@@ -59,6 +59,7 @@ namespace robot_costmap_2d
{
class DepthVisibilityChecker;
enum class DepthObservation;
class VoxelLayer : public ObstacleLayer
{
@@ -132,7 +133,13 @@ private:
uint64_t free{0}, unknown{0}, surface{0}, frames{0};
uint64_t by_evidence{0}; ///< decisions made from evidence points
uint64_t border_dropped{0}; ///< marking points dropped at the image border
/// re-observe-or-clear outcomes per voxel and frame
uint64_t confirmed{0}, occluded{0}, seen_through{0}, no_return{0}, out_of_view{0};
} visibility_counts_;
/// Re-observe-or-clear: applies one frame's observation to the voxel's miss count.
/// Returns true when the voxel is to be freed.
bool reobserveFrees(DepthObservation observation, const DepthEvidenceStore::VoxelKey& key,
const DepthFrustumConfig& config);
/// Window-independent key: local cell index plus the cells the rolling origin moved.
DepthEvidenceStore::VoxelKey evidenceKey(unsigned int x, unsigned int y, unsigned int z) const