Files
dock_pattern_detector/test/v_pattern_matcher_test.cpp
duongtd d58d08eda3 feat: confirm a candidate with reflective tape when the profile asks for it
Geometry alone cannot answer the question that matters in a warehouse. Every
wall corner and every pair of pallets stacked at a right angle is a V of some
size, and enough of them are the right size. None of them carry two strips of
reflective tape at the expected spacing.

Off by default: with tape_enabled false the matcher never reads the intensity
array and nothing about the existing behaviour changes.

On, it is an extra criterion, not a fifth pattern type. Shape still decides
where the apex is and the pose that comes out is still entirely from shape;
the tape only answers whether this is the dock. The check runs after every
geometric gate, because it is the expensive one and geometry has already
thrown out nearly every candidate by then - measured at +0.11 us per scan
against the 508 us the line extraction ahead of it already costs.

On each wing it takes the longest consecutive run of bright rays, then:
  - the two run centres must be tape_spacing apart;
  - each run must be tape_width long, checked only when the run has 2 or more
    rays. One ray tells you it is bright but not how wide, and at the range
    where that happens the tape is what you needed most, so the criterion is
    skipped rather than guessed.

Runs are searched across the whole ray span the wing covers, not only the rays
that supported the fitted line: tape that stands proud of the wing surface can
be split off into its own segment, and then the very rays being looked for no
longer belong to any wing.

The measured width is always short - the outermost bright rays land inside the
strip, not on its edges, so the span between them misses up to one ray spacing.
At 3 m one nanoscan3 ray spacing is 0.021 m, 17% of a 0.12 m strip. That is
systematic, not noise, so it is corrected: n bright rays span exactly n-1 gaps,
and adding one gap adds half a gap at each edge. The gap comes from the run
itself, so it self-calibrates for range and for how obliquely the plate is
seen, with no extra parameter. On a deliberately coarse 200-ray scan it reads
0.119 m against a true 0.120 m.

tape_min_intensity carries each sensor's own units and has no common scale -
Gazebo passes laser_retro straight through, a real nanoscan3 does not. When the
profile asks for tape and the scan carries no intensities at all, the reason
says so, because that symptom is otherwise identical to "the dock is not in
range" and only one of the two is fixable in config.
2026-08-26 16:46:33 +07:00

749 lines
26 KiB
C++

/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Kiểm khớp chữ V bằng scan TỔNG HỢP — dựng hình trước, sinh tia sau, nên biết trước đáp án.
*
* Bốn nhóm:
* 1. dò đúng — đỉnh, hướng, offset, hình nghiêng;
* 2. TỪ CHỐI — đây mới là phần quan trọng: pallet đánh lừa, tường cắt nhau ở xa, hình méo;
* 3. cổng tìm kiếm — prior và quạt;
* 4. nhiều ứng viên, và config hỏng;
* 5. dải phản quang — dữ liệu cường độ THÊM vào việc dò hình.
*
* Author: DuongTD
*********************************************************************/
#include <gtest/gtest.h>
#include <cmath>
#include <limits>
#include <string>
#include <vector>
#include <robot_line_extraction/line_extractor.h>
#include <dock_pattern_detector/v_pattern_matcher.h>
namespace
{
using dock_pattern_detector::Detection;
using dock_pattern_detector::DockProfile;
using dock_pattern_detector::PatternType;
using dock_pattern_detector::VPatternMatcher;
using robot_line_extraction::Line;
using robot_line_extraction::LineExtractionParams;
using robot_line_extraction::LineExtractor;
using robot_line_extraction::ScanGeometry;
constexpr double kInf = std::numeric_limits<double>::infinity();
struct Segment
{
double ax, ay, bx, by; // [m]
};
ScanGeometry geometry(std::size_t rays = 600, double angle_min = -0.8, double angle_max = 0.8)
{
ScanGeometry g;
g.angle_min = angle_min;
g.angle_increment = (angle_max - angle_min) / static_cast<double>(rays - 1);
g.size = rays;
return g;
}
/// @brief Chiếu tia lên một tập đoạn thẳng, lấy điểm trúng gần nhất. Không trúng gì thì kInf.
std::vector<double> rayCast(const ScanGeometry& g, const std::vector<Segment>& world)
{
std::vector<double> ranges(g.size, kInf);
for (std::size_t i = 0; i < g.size; ++i)
{
const double bearing = g.angle_min + static_cast<double>(i) * g.angle_increment;
const double dx = std::cos(bearing);
const double dy = std::sin(bearing);
for (const Segment& s : world)
{
const double ex = s.bx - s.ax;
const double ey = s.by - s.ay;
const double det = dx * (-ey) - dy * (-ex);
if (std::fabs(det) < 1e-12)
{
continue;
}
const double t = (s.ax * (-ey) - s.ay * (-ex)) / det;
const double u = (dx * s.ay - dy * s.ax) / det;
if (t > 0.0 && u >= 0.0 && u <= 1.0 && t < ranges[i])
{
ranges[i] = t;
}
}
}
return ranges;
}
/**
* @brief Hai cánh của một tấm chữ V.
*
* @param apex_x [m] đỉnh trên trục x
* @param half_angle [rad] độ nghiêng mỗi cánh so với trục y
* @param wing [m] chiều dài một cánh
* @param yaw [rad] xoay cả tấm quanh đỉnh
*
* Góc TRONG tại đỉnh = pi - 2*half_angle. `half = pi/4` cho tấm mở 90 độ.
*/
std::vector<Segment> vPlate(double apex_x, double half_angle, double wing, double yaw = 0.0)
{
const double c = std::cos(yaw);
const double s = std::sin(yaw);
const auto rot = [&](double x, double y, double& ox, double& oy) {
ox = apex_x + c * (x - apex_x) - s * y;
oy = s * (x - apex_x) + c * y;
};
const double tip_x = apex_x + wing * std::sin(half_angle);
const double tip_y = wing * std::cos(half_angle);
Segment w1;
Segment w2;
rot(apex_x, 0.0, w1.ax, w1.ay);
rot(tip_x, tip_y, w1.bx, w1.by);
rot(apex_x, 0.0, w2.ax, w2.ay);
rot(tip_x, -tip_y, w2.bx, w2.by);
return { w1, w2 };
}
/// @brief [m] Cự ly từ điểm (@p px, @p py) tới đoạn @p s.
double distToSegment(double px, double py, const Segment& s)
{
const double ex = s.bx - s.ax;
const double ey = s.by - s.ay;
const double len2 = ex * ex + ey * ey;
double t = (len2 > 0.0) ? ((px - s.ax) * ex + (py - s.ay) * ey) / len2 : 0.0;
t = std::max(0.0, std::min(1.0, t));
return std::hypot(px - (s.ax + t * ex), py - (s.ay + t * ey));
}
/**
* @brief Hai dải phản quang dán GIỮA mỗi cánh của tấm dựng bởi @ref vPlate.
*
* Đặt giữa cánh đúng như tấm mẫu trong `dock_pattern_action/sim/models/dock_plate_v`, nên khoảng
* cách hai tâm dải suy được từ hình chứ không phải một con số rời.
*/
std::vector<Segment> vPlateTapes(double apex_x, double half_angle, double wing, double tape_width,
double yaw = 0.0)
{
std::vector<Segment> tapes;
for (const Segment& w : vPlate(apex_x, half_angle, wing, yaw))
{
const double len = std::hypot(w.bx - w.ax, w.by - w.ay);
const double dx = (w.bx - w.ax) / len;
const double dy = (w.by - w.ay) / len;
const double mid_x = w.ax + dx * len / 2.0;
const double mid_y = w.ay + dy * len / 2.0;
Segment tape;
tape.ax = mid_x - dx * tape_width / 2.0;
tape.ay = mid_y - dy * tape_width / 2.0;
tape.bx = mid_x + dx * tape_width / 2.0;
tape.by = mid_y + dy * tape_width / 2.0;
tapes.push_back(tape);
}
return tapes;
}
/**
* @brief Cường độ theo TIA: sáng khi điểm trúng nằm trên một dải, tối ở mọi chỗ khác.
*
* Đúng cách Gazebo trả `laser_retro`: một giá trị cao trên vật khai phản quang, 0 trên mọi vật
* khác. Cảm biến thật trả thang khác, nhưng cái được kiểm ở đây là LUẬT phân tách, không phải thang.
*/
std::vector<float> tapeIntensities(const ScanGeometry& g, const std::vector<double>& ranges,
const std::vector<Segment>& tapes, float bright = 2000.0f)
{
std::vector<float> intensities(g.size, 0.0f);
for (std::size_t i = 0; i < g.size; ++i)
{
if (!std::isfinite(ranges[i]))
{
continue;
}
const double bearing = g.angle_min + static_cast<double>(i) * g.angle_increment;
const double px = ranges[i] * std::cos(bearing);
const double py = ranges[i] * std::sin(bearing);
for (const Segment& tape : tapes)
{
if (distToSegment(px, py, tape) <= 1e-6)
{
intensities[i] = bright;
break;
}
}
}
return intensities;
}
DockProfile vProfile()
{
DockProfile p;
p.pattern = PatternType::kV;
p.vertex_angle = M_PI / 2.0; // [rad] tấm mở 90 độ
p.wing_length = 0.30; // [m]
p.angle_tolerance = 0.20; // [rad]
p.length_tolerance = 0.06; // [m]
p.vertex_gap = 0.05; // [m]
p.min_wing_points = 5;
p.min_confidence = 0.3;
return p;
}
LineExtractionParams extractorParams()
{
LineExtractionParams p;
p.min_split_dist = 0.02; // [m]
p.max_line_gap = 0.08; // [m]
p.min_line_length = 0.05; // [m]
p.min_line_points = 5;
p.outlier_dist = 0.10; // [m]
return p;
}
/// @brief Dựng thế giới, chiếu tia, trích đoạn, khớp — đúng chuỗi mà handler sẽ chạy.
class Rig
{
public:
explicit Rig(const DockProfile& profile = vProfile())
{
std::string error;
ok_ = extractor_.configure(extractorParams(), error) && matcher_.configure(profile, error);
error_ = error;
}
Detection run(const std::vector<Segment>& world, const ScanGeometry& g = geometry())
{
std::string error;
if (!extractor_.extract(g, rayCast(g, world), lines_, error))
{
Detection d;
d.reason = error;
return d;
}
return matcher_.match(lines_);
}
/// @brief Như trên, kèm dải phản quang: cường độ sinh từ chính các điểm trúng.
Detection run(const std::vector<Segment>& world, const std::vector<Segment>& tapes,
const ScanGeometry& g = geometry())
{
const std::vector<double> ranges = rayCast(g, world);
std::string error;
if (!extractor_.extract(g, ranges, lines_, error))
{
Detection d;
d.reason = error;
return d;
}
return matcher_.match(lines_, tapeIntensities(g, ranges, tapes));
}
bool ok_ = false;
std::string error_;
LineExtractor extractor_;
VPatternMatcher matcher_;
std::vector<Line> lines_;
};
// ================================================================================================
// 1. Dò đúng
// ================================================================================================
TEST(VPatternMatcher, FindsTheApexOfAPlateInFront)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const Detection d = rig.run(vPlate(1.20, M_PI / 4.0, 0.30));
ASSERT_TRUE(d.valid) << d.reason;
EXPECT_NEAR(d.apex_x, 1.20, 0.02);
EXPECT_NEAR(d.apex_y, 0.00, 0.02);
EXPECT_NEAR(d.measured_vertex_angle, M_PI / 2.0, 0.10);
EXPECT_GT(d.confidence, 0.5);
}
TEST(VPatternMatcher, TheYawPointsBackAtTheSensorNotIntoThePlate)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const Detection d = rig.run(vPlate(1.20, M_PI / 4.0, 0.30));
ASSERT_TRUE(d.valid) << d.reason;
// Tấm ở phía +x, cảm biến ở gốc, nên phân giác phải chỉ về -x tức yaw ~ pi. Lệch 180 độ ở đây là
// robot lùi vào tấm sạc thay vì tiến vào — chính vì thế dấu được chọn theo vị trí cảm biến chứ
// không theo thứ tự hai cánh.
EXPECT_NEAR(std::fabs(d.yaw), M_PI, 0.10);
}
TEST(VPatternMatcher, TheOffsetMovesTheGoalOutTowardTheRobot)
{
DockProfile p = vProfile();
p.offset_x = 0.60; // [m] lùi ra trước mặt sạc
Rig rig(p);
ASSERT_TRUE(rig.ok_) << rig.error_;
const Detection d = rig.run(vPlate(1.20, M_PI / 4.0, 0.30));
ASSERT_TRUE(d.valid) << d.reason;
// Đỉnh ở x=1.20; offset dọc pháp tuyến hướng RA phía robot nên goal phải ở x ~ 0.60, GẦN hơn.
EXPECT_NEAR(d.apex_x, 1.20, 0.02);
EXPECT_NEAR(d.x, 0.60, 0.03);
EXPECT_NEAR(d.y, 0.00, 0.03);
}
TEST(VPatternMatcher, ATiltedPlateIsStillFoundAndItsYawFollows)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const Detection d = rig.run(vPlate(1.20, M_PI / 4.0, 0.30, 0.25));
ASSERT_TRUE(d.valid) << d.reason;
EXPECT_NEAR(d.measured_vertex_angle, M_PI / 2.0, 0.12);
// Tấm xoay 0.25 rad thì phân giác hướng ra cũng xoay đúng ngần ấy.
const double expected = std::atan2(std::sin(M_PI + 0.25), std::cos(M_PI + 0.25));
EXPECT_NEAR(std::atan2(std::sin(d.yaw - expected), std::cos(d.yaw - expected)), 0.0, 0.12);
}
TEST(VPatternMatcher, AWiderPlateIsFoundWhenTheProfileSaysSo)
{
DockProfile p = vProfile();
p.vertex_angle = 2.0944; // [rad] 120 độ
p.wing_length = 0.25; // [m]
Rig rig(p);
ASSERT_TRUE(rig.ok_) << rig.error_;
// Góc trong = pi - 2*half; muốn 120 độ thì half = 30 độ.
const Detection d = rig.run(vPlate(1.10, M_PI / 6.0, 0.25));
ASSERT_TRUE(d.valid) << d.reason;
EXPECT_NEAR(d.measured_vertex_angle, 2.0944, 0.12);
}
// ================================================================================================
// 2. Từ chối — phần quan trọng nhất
// ================================================================================================
TEST(VPatternMatcher, AWingHiddenByAnObliqueViewIsStillAV)
{
DockProfile p = vProfile();
p.min_wing_points = 5;
Rig rig(p);
ASSERT_TRUE(rig.ok_) << rig.error_;
// Cánh xa bị nhìn nghiêng nên chỉ thấy 0.18 m thay vì 0.30 m. Che khuất chỉ làm NGẮN đi, không
// bao giờ dài ra — nên đây vẫn là chữ V thật. Bắt cả hai cánh đủ 0.30 m nghĩa là chỉ dò được khi
// robot đứng gần chính diện; đo được: nghiêng 40 độ là tỉ lệ trúng về 0.
const double ax = 1.20;
const std::vector<Segment> world = {
{ ax, 0.0, ax - 0.2121, 0.2121 }, // cánh đủ
{ ax, 0.0, ax - 0.1273, -0.1273 }, // cánh chỉ thấy 0.18 m
};
const Detection d = rig.run(world);
ASSERT_TRUE(d.valid) << d.reason;
EXPECT_NEAR(d.apex_x, ax, 0.03);
EXPECT_NEAR(std::max(d.measured_wing_length[0], d.measured_wing_length[1]), 0.30, 0.04);
EXPECT_LT(std::min(d.measured_wing_length[0], d.measured_wing_length[1]), 0.24);
}
TEST(VPatternMatcher, AWingLongerThanTheProfileIsStillRejected)
{
DockProfile p = vProfile();
p.min_wing_points = 5;
Rig rig(p);
ASSERT_TRUE(rig.ok_) << rig.error_;
// Luật bất đối xứng chỉ nới phía NGẮN. Một cạnh dài hơn `wing_length + tol` vẫn phải bị loại —
// đó là thứ giữ nguyên tác dụng chặn góc pallet, và pallet có CẢ HAI cạnh dài.
const double ax = 1.20;
const std::vector<Segment> world = {
{ ax, 0.0, ax - 0.2121, 0.2121 }, // cánh đủ 0.30 m
{ ax, 0.0, ax - 0.4243, -0.4243 }, // cạnh 0.60 m — quá dài
};
const Detection d = rig.run(world);
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("wing length"), std::string::npos) << d.reason;
}
TEST(VPatternMatcher, APalletCornerIsNotADock)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
// Hai mặt vuông góc của một pallet: ĐÚNG góc 90 độ, nhưng cạnh dài 0.8 m chứ không phải 0.30 m.
// Đây là dương tính giả điển hình trong kho, và chỉ cổng chiều dài chặn được nó.
const Detection d = rig.run(vPlate(1.20, M_PI / 4.0, 0.80));
ASSERT_EQ(rig.lines_.size(), 2U) << "cần đúng 2 đoạn, nếu không thì cổng chiều dài chưa bị thử";
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("wing length"), std::string::npos) << d.reason;
}
TEST(VPatternMatcher, TwoWallsThatCrossFarFromTheirEndsAreNotAV)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
// Hai bức tường vuông góc nhưng KHÔNG chạm nhau — giao điểm của hai ĐƯỜNG nằm ngoài cả hai đoạn.
// Chỉ dựa vào góc thì ca này lọt; cổng `vertex_gap` là thứ chặn nó.
const std::vector<Segment> world = {
{ 1.00, 0.35, 1.30, 0.65 },
{ 1.00, -0.35, 1.30, -0.65 },
};
const Detection d = rig.run(world);
ASSERT_EQ(rig.lines_.size(), 2U) << "cần đúng 2 đoạn, nếu không thì matcher chưa hề bị thử";
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("do not end at the crossing"), std::string::npos) << d.reason;
}
TEST(VPatternMatcher, AFlatWallHasNoVertexAtAll)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const Detection d = rig.run({ { 1.50, -1.00, 1.50, 1.00 } });
EXPECT_FALSE(d.valid);
EXPECT_FALSE(d.reason.empty());
}
TEST(VPatternMatcher, APlateWithTheWrongOpeningIsRejected)
{
Rig rig; // profile chờ 90 độ
ASSERT_TRUE(rig.ok_) << rig.error_;
// Tấm mở 140 độ: đúng chiều dài cánh, đúng chỗ, chỉ sai góc.
const Detection d = rig.run(vPlate(1.20, M_PI / 9.0, 0.30));
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("angle"), std::string::npos) << d.reason;
}
TEST(VPatternMatcher, HalfAPlateIsNotEnough)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
// Một cánh bị vật khác che hoàn toàn. Còn một đoạn thì không có đỉnh nào để đo.
std::vector<Segment> world = vPlate(1.20, M_PI / 4.0, 0.30);
world.pop_back();
const Detection d = rig.run(world);
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("2 line segments"), std::string::npos) << d.reason;
}
TEST(VPatternMatcher, AnEmptySceneSaysSoInsteadOfGuessing)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const Detection d = rig.run({});
EXPECT_FALSE(d.valid);
EXPECT_EQ(d.candidate_count, 0U);
EXPECT_FALSE(d.reason.empty());
}
// ================================================================================================
// 3. Cổng tìm kiếm
// ================================================================================================
TEST(VPatternMatcher, ThePriorGateRejectsATrueVInTheWrongPlace)
{
DockProfile p = vProfile();
p.has_prior = true;
p.prior_x = 1.20; // [m] trạm kỳ vọng ở đây
p.prior_y = 0.00; // [m]
p.search_radius = 0.30; // [m]
Rig rig(p);
ASSERT_TRUE(rig.ok_) << rig.error_;
// Một tấm chữ V hoàn hảo, nhưng ở chỗ khác — trong kho thì đó là trạm của người khác, hoặc một
// vật thể trùng hình. Không có cổng này thì robot dock vào nhầm chỗ, rất tự tin.
const Detection d = rig.run(vPlate(2.20, M_PI / 4.0, 0.30));
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("search gate"), std::string::npos) << d.reason;
}
TEST(VPatternMatcher, ThePriorGateAcceptsTheOneItExpects)
{
DockProfile p = vProfile();
p.has_prior = true;
p.prior_x = 1.20;
p.prior_y = 0.00;
p.search_radius = 0.30;
Rig rig(p);
ASSERT_TRUE(rig.ok_) << rig.error_;
const Detection d = rig.run(vPlate(1.20, M_PI / 4.0, 0.30));
EXPECT_TRUE(d.valid) << d.reason;
}
TEST(VPatternMatcher, TheSectorGateRejectsWhatIsNotInFront)
{
DockProfile p = vProfile();
p.search_fov = 0.15; // [rad] quạt hẹp quanh trục x
Rig rig(p);
ASSERT_TRUE(rig.ok_) << rig.error_;
// Tấm lệch sang bên: bearing của đỉnh ~0.46 rad, ngoài quạt.
const std::vector<Segment> world = vPlate(1.20, M_PI / 4.0, 0.30);
std::vector<Segment> shifted;
for (Segment s : world)
{
s.ay += 0.60;
s.by += 0.60;
shifted.push_back(s);
}
const Detection d = rig.run(shifted);
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("search gate"), std::string::npos) << d.reason;
}
// ================================================================================================
// 4. Nhiều ứng viên và config hỏng
// ================================================================================================
TEST(VPatternMatcher, TwoPlatesInViewAreBothCountedAndTheBetterOneWins)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
std::vector<Segment> world = vPlate(1.20, M_PI / 4.0, 0.30);
for (Segment s : vPlate(1.60, M_PI / 4.0, 0.30))
{
s.ay += 0.90;
s.by += 0.90;
world.push_back(s);
}
const Detection d = rig.run(world);
ASSERT_TRUE(d.valid) << d.reason;
// Đếm được nhiều hơn một là tín hiệu cho tầng trên: trong tầm có nhiều hình giống nhau, và cổng
// prior mới là thứ quyết định lấy cái nào.
EXPECT_GE(d.candidate_count, 2U);
}
TEST(VPatternMatcher, RefusesAProfileThatCanNeverMatch)
{
VPatternMatcher matcher;
std::string error;
DockProfile flat = vProfile();
flat.vertex_angle = M_PI; // hai cánh thành một đường thẳng
EXPECT_FALSE(matcher.configure(flat, error));
EXPECT_NE(error.find("vertex_angle"), std::string::npos);
DockProfile loose_gap = vProfile();
loose_gap.vertex_gap = loose_gap.wing_length;
// Khe đỉnh rộng bằng cả cánh thì hai bức tường cắt nhau ở đâu cũng lọt — mất đúng cái cổng phân
// biệt chữ V thật với giao điểm ngẫu nhiên.
EXPECT_FALSE(matcher.configure(loose_gap, error));
EXPECT_NE(error.find("vertex_gap"), std::string::npos);
DockProfile loose_len = vProfile();
loose_len.length_tolerance = loose_len.wing_length;
EXPECT_FALSE(matcher.configure(loose_len, error));
DockProfile not_ready = vProfile();
not_ready.pattern = PatternType::kCylinder;
// Nói thẳng thay vì nhận config rồi không bao giờ dò ra gì.
EXPECT_FALSE(matcher.configure(not_ready, error));
EXPECT_NE(error.find("not implemented"), std::string::npos);
// Profile hỏng bị từ chối thì bộ cũ phải còn nguyên.
DockProfile good = vProfile();
ASSERT_TRUE(matcher.configure(good, error)) << error;
EXPECT_DOUBLE_EQ(matcher.profile().wing_length, good.wing_length);
}
// ================================================================================================
// 5. Dải phản quang
// ================================================================================================
namespace
{
/// @brief Tấm chuẩn của nhóm test này: đỉnh ở 1.5 m, mở 90 độ, cánh 0.30 m, dải 0.12 m giữa cánh.
constexpr double kApexX = 1.5; // [m]
constexpr double kHalf = M_PI / 4.0; // [rad]
constexpr double kWing = 0.30; // [m]
constexpr double kTapeWidth = 0.12; // [m]
/// [m] Hai tâm dải nằm ở giữa hai cánh, nên khoảng cách giữa chúng suy ra từ hình.
const double kTapeSpacing = 2.0 * (kWing / 2.0) * std::cos(kHalf);
DockProfile vTapeProfile()
{
DockProfile p = vProfile();
p.tape_enabled = true;
p.tape_spacing = kTapeSpacing;
p.tape_width = kTapeWidth;
p.tape_spacing_tolerance = 0.04; // [m]
p.tape_width_tolerance = 0.05; // [m]
p.tape_min_intensity = 500.0;
return p;
}
} // namespace
TEST(VPatternMatcher, TapeConfirmsAPlateThatCarriesIt)
{
Rig rig(vTapeProfile());
ASSERT_TRUE(rig.ok_) << rig.error_;
const Detection d = rig.run(vPlate(kApexX, kHalf, kWing), vPlateTapes(kApexX, kHalf, kWing,
kTapeWidth));
ASSERT_TRUE(d.valid) << d.reason;
EXPECT_NEAR(d.apex_x, kApexX, 0.02);
EXPECT_NEAR(d.measured_tape_spacing, kTapeSpacing, 0.01);
EXPECT_GT(d.tape_points[0], 1u);
EXPECT_GT(d.tape_points[1], 1u);
}
TEST(VPatternMatcher, TapeRejectsAVOfTheRightShapeThatCarriesNoTape)
{
// Đây là lý do tồn tại của cả tính năng. Hình ở đây ĐÚNG hoàn hảo — cùng góc, cùng chiều dài
// cánh, cùng chỗ — nên mọi cổng hình học đều cho qua. Ngoài kho thì hai tấm pallet kê vuông góc
// dựng ra đúng cái hình này, và không có cách nào phân biệt bằng hình.
Rig rig(vTapeProfile());
ASSERT_TRUE(rig.ok_) << rig.error_;
const Detection d = rig.run(vPlate(kApexX, kHalf, kWing), std::vector<Segment>{}); // không dải nào
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("reflective tape"), std::string::npos) << d.reason;
}
TEST(VPatternMatcher, TheSamePlateWithoutTapePassesWhenTheTapeCheckIsOff)
{
// Mặt kia của test trên: chính cái hình vừa bị từ chối phải được nhận khi tắt cổng. Không có cặp
// này thì một lỗi làm hỏng hẳn phép dò cũng trông y hệt "cổng phản quang đang làm việc".
Rig rig(vProfile()); // tape_enabled = false, mặc định
ASSERT_TRUE(rig.ok_) << rig.error_;
const Detection d = rig.run(vPlate(kApexX, kHalf, kWing), std::vector<Segment>{});
ASSERT_TRUE(d.valid) << d.reason;
EXPECT_EQ(d.measured_tape_spacing, 0.0);
}
TEST(VPatternMatcher, TapeRejectsStripsAtTheWrongSpacing)
{
// Dải có thật, sáng thật, nhưng dán sai chỗ — dồn ra sát hai đầu mút. Cổng khoảng cách phải bắt
// được, nếu không thì bất kỳ vật phản quang nào trên một chữ V cũng thành cái sạc.
Rig rig(vTapeProfile());
ASSERT_TRUE(rig.ok_) << rig.error_;
std::vector<Segment> tapes;
for (const Segment& w : vPlate(kApexX, kHalf, kWing))
{
const double len = std::hypot(w.bx - w.ax, w.by - w.ay);
const double dx = (w.bx - w.ax) / len;
const double dy = (w.by - w.ay) / len;
Segment tape; // dồn ra đầu mút cánh thay vì giữa cánh
tape.ax = w.bx - dx * kTapeWidth;
tape.ay = w.by - dy * kTapeWidth;
tape.bx = w.bx;
tape.by = w.by;
tapes.push_back(tape);
}
const Detection d = rig.run(vPlate(kApexX, kHalf, kWing), tapes);
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("reflective tape"), std::string::npos) << d.reason;
}
TEST(VPatternMatcher, TapeOnOnlyOneWingIsNotEnough)
{
Rig rig(vTapeProfile());
ASSERT_TRUE(rig.ok_) << rig.error_;
std::vector<Segment> tapes = vPlateTapes(kApexX, kHalf, kWing, kTapeWidth);
tapes.resize(1);
const Detection d = rig.run(vPlate(kApexX, kHalf, kWing), tapes);
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("reflective tape"), std::string::npos) << d.reason;
}
TEST(VPatternMatcher, TapeEnabledButNoIntensityDataSaysSoInsteadOfFindingNothing)
{
// Driver không gửi `intensities` và trạm không có trong tầm cho ra cùng một triệu chứng — dò mãi
// không ra. Chỉ một trong hai sửa được bằng config, nên hai ca phải nói ra hai câu khác nhau.
Rig rig(vTapeProfile());
ASSERT_TRUE(rig.ok_) << rig.error_;
const Detection d = rig.run(vPlate(kApexX, kHalf, kWing)); // bản match() không cường độ
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("no intensity data"), std::string::npos) << d.reason;
}
TEST(VPatternMatcher, TheMeasuredTapeWidthCorrectsForRaySpacing)
{
// Tia sáng ngoài cùng nằm BÊN TRONG dải chứ không đúng ở mép, nên khoảng cách giữa hai tia ngoài
// cùng luôn hụt tới một bước tia. Đây là sai lệch hệ thống chứ không phải nhiễu: quét thưa thì
// hụt nhiều, và nếu không bù thì dải thật bị chấm là hẹp rồi trượt cổng chiều dài.
//
// Quét thưa có chủ đích — 200 tia trên 1.6 rad, khoảng 7 tia trúng dải — để chỗ hụt lớn hơn hẳn
// dung sai đo.
Rig rig(vTapeProfile());
ASSERT_TRUE(rig.ok_) << rig.error_;
const ScanGeometry coarse = geometry(200, -0.8, 0.8);
const Detection d = rig.run(vPlate(kApexX, kHalf, kWing),
vPlateTapes(kApexX, kHalf, kWing, kTapeWidth), coarse);
ASSERT_TRUE(d.valid) << d.reason;
// Một bước tia dọc dải ở tầm này vào khoảng 0.017 m; đo được phải nằm trong ngần ấy quanh 0.12 m.
EXPECT_NEAR(d.measured_tape_width[0], kTapeWidth, 0.02);
EXPECT_NEAR(d.measured_tape_width[1], kTapeWidth, 0.02);
}
TEST(VPatternMatcher, RefusesATapeProfileWithImpossibleNumbers)
{
std::string error;
VPatternMatcher m;
DockProfile p = vTapeProfile();
p.tape_spacing = 5.0; // [m] xa hơn hai lần chiều dài cánh: dải không thể nằm trên cánh
EXPECT_FALSE(m.configure(p, error));
EXPECT_NE(error.find("tape_spacing"), std::string::npos) << error;
p = vTapeProfile();
p.tape_width = 0.9; // [m] dài hơn cả cánh
EXPECT_FALSE(m.configure(p, error));
EXPECT_NE(error.find("tape_width"), std::string::npos) << error;
p = vTapeProfile();
p.tape_spacing_tolerance = p.tape_spacing; // dung sai nuốt trọn phép đo
EXPECT_FALSE(m.configure(p, error));
EXPECT_NE(error.find("tape_spacing_tolerance"), std::string::npos) << error;
}
} // namespace
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}