/********************************************************************* * * Software License Agreement (BSD License) * * dock_pattern_detector — khớp chữ V. * * Author: DuongTD *********************************************************************/ #include #include #include #include #include namespace dock_pattern_detector { namespace { using robot_line_extraction::Line; struct Point { double x = 0.0; double y = 0.0; }; double dist(const Point& a, const Point& b) { return std::hypot(a.x - b.x, a.y - b.y); } Point startOf(const Line& line) { return { line.getStart()[0], line.getStart()[1] }; } Point endOf(const Line& line) { return { line.getEnd()[0], line.getEnd()[1] }; } /** * @brief Giao điểm hai đường ở dạng cực. * * Đường i: `x*cos(a_i) + y*sin(a_i) = r_i`. Định thức là `sin(a_2 - a_1)`, bằng 0 đúng khi hai * đường song song — khi ấy không có đỉnh nào để nói tới. */ bool intersect(const Line& l1, const Line& l2, Point& out) { const double a1 = l1.getAngle(); const double a2 = l2.getAngle(); const double det = std::cos(a1) * std::sin(a2) - std::sin(a1) * std::cos(a2); if (std::fabs(det) < 1e-9) { return false; } const double r1 = l1.getRadius(); const double r2 = l2.getRadius(); out.x = (r1 * std::sin(a2) - r2 * std::sin(a1)) / det; out.y = (r2 * std::cos(a1) - r1 * std::cos(a2)) / det; return std::isfinite(out.x) && std::isfinite(out.y); } /// @brief Đầu mút của @p line xa @p apex nhất — đó là đầu MÚT cánh; đầu kia là chân cánh tại đỉnh. Point farEndpoint(const Line& line, const Point& apex) { const Point s = startOf(line); const Point e = endOf(line); return dist(s, apex) >= dist(e, apex) ? s : e; } /// @brief Đầu mút của @p line gần @p apex nhất. Point nearEndpoint(const Line& line, const Point& apex) { const Point s = startOf(line); const Point e = endOf(line); return dist(s, apex) < dist(e, apex) ? s : e; } /** * @struct TapeRun * @brief Vệt tia sáng dài nhất trên một cánh. */ struct TapeRun { bool found = false; Point centre; double width = 0.0; ///< [m] đã bù lượng tử hoá; 0 khi chỉ có 1 tia bool width_known = false; std::size_t points = 0; }; /** * @brief Tìm vệt tia sáng dài nhất mà @p line trải qua. * * Quét toàn bộ khoảng tia từ đầu đến cuối phần đỡ của đoạn, KHÔNG chỉ các tia đã đỡ nó. Dải dán * nổi lên khỏi mặt cánh có thể bị bước tách cắt ra thành đoạn riêng, và khi ấy đúng những tia cần * tìm lại không còn thuộc cánh nào. * * Chiều dài vệt luôn bị ĐO HỤT: tia sáng đầu và tia sáng cuối nằm bên trong dải chứ không đúng ở * hai mép, nên khoảng cách giữa chúng thiếu tới một bước tia. Ở 3 m một bước tia của nanoscan3 là * 0.021 m, tức 17% của dải 0.12 m — đó là sai lệch hệ thống, không phải nhiễu, và bù được: khoảng * cách giữa hai tia sáng ngoài cùng trải qua đúng `n-1` bước, nên cộng thêm một bước là thêm nửa * bước ở mỗi mép. Bước tia lấy từ chính vệt đó, nên nó tự hiệu chỉnh theo tầm lẫn theo độ chếch mà * không cần khai thêm tham số nào. */ TapeRun findTape(const Line& line, const std::vector& intensities, double min_intensity) { TapeRun best; const std::vector& support = line.getIndices(); if (support.empty()) { return best; } const unsigned int first = support.front(); const unsigned int last = support.back(); if (static_cast(last) >= intensities.size()) { return best; // Scan và mảng cường độ không cùng độ dài. Không đoán, coi như không có dữ liệu. } std::size_t run_begin = 0; std::size_t run_len = 0; std::size_t best_begin = 0; std::size_t best_len = 0; for (unsigned int index = first; index <= last; ++index) { const std::array point = line.pointAt(index); const bool bright = intensities[index] >= min_intensity && std::isfinite(point[0]) && std::isfinite(point[1]); if (bright) { if (run_len == 0) { run_begin = index; } ++run_len; if (run_len > best_len) { best_len = run_len; best_begin = run_begin; } } else { run_len = 0; } } if (best_len == 0) { return best; } double sum_x = 0.0; double sum_y = 0.0; for (std::size_t k = 0; k < best_len; ++k) { const std::array point = line.pointAt(static_cast(best_begin + k)); sum_x += point[0]; sum_y += point[1]; } best.found = true; best.points = best_len; best.centre.x = sum_x / static_cast(best_len); best.centre.y = sum_y / static_cast(best_len); if (best_len >= 2) { const std::array a = line.pointAt(static_cast(best_begin)); const std::array b = line.pointAt(static_cast(best_begin + best_len - 1)); const double span = std::hypot(a[0] - b[0], a[1] - b[1]); best.width = span + span / static_cast(best_len - 1); best.width_known = true; } return best; } /// @brief Điểm khớp trong [0, 1]: 1 khi lệch bằng 0, 0 khi lệch chạm dung sai. double score(double deviation, double tolerance) { if (tolerance <= 0.0) { return 0.0; } return std::max(0.0, 1.0 - std::fabs(deviation) / tolerance); } } // namespace bool VPatternMatcher::configure(const DockProfile& profile, std::string& error) { if (!profile.validate(error)) { return false; // Giữ bộ cũ; một profile áp nửa vời còn tệ hơn không áp. } if (profile.pattern != PatternType::kV) { // `validate` chỉ kiểm profile có tự mâu thuẫn không, nó không biết ai đang cầm profile. Thiếu // chỗ này thì một profile `pattern: arc` được bộ khớp chữ V nhận im lặng, rồi đi tìm hai cánh // trên một mặt cong — dò mãi không ra, mà log thì báo là đang tìm chữ V. error = std::string("VPatternMatcher was given pattern '") + toString(profile.pattern) + "'"; return false; } profile_ = profile; return true; } Detection VPatternMatcher::match(const std::vector& lines) const { static const std::vector kNoIntensities; return match(lines, kNoIntensities); } Detection VPatternMatcher::match(const std::vector& lines, const std::vector& intensities) const { Detection best; if (profile_.tape_enabled && intensities.empty()) { // Nói thẳng thay vì lặng lẽ không dò ra gì: "cảm biến không gửi cường độ" và "trạm không có // trong tầm" là hai chuyện khác hẳn, và chỉ chuyện đầu sửa được bằng config. best.reason = "profile requires reflective tape but the scan carries no intensity data — " "either the driver does not publish 'intensities' or tape_enabled is wrong"; best.segment_count = lines.size(); return best; } if (lines.size() < 2) { best.reason = "need 2 line segments, scan yielded " + std::to_string(lines.size()); return best; } // Vì sao đếm riêng từng lý do loại: "thấy nhiều cặp nhưng cặp nào cũng sai góc" và "không cặp nào // có đầu mút chụm" đòi hai cách xử trí khác hẳn nhau — chỉnh dung sai, hay chỉnh chỗ đứng. std::size_t rejected_vertex_gap = 0; std::size_t rejected_angle = 0; std::size_t rejected_length = 0; std::size_t rejected_shape = 0; std::size_t rejected_support = 0; std::size_t rejected_prior = 0; std::size_t rejected_tape = 0; std::size_t rejected_confidence = 0; std::size_t accepted = 0; // Ứng viên GẦN ĐÚNG NHẤT bị cổng tìm kiếm loại. Chỉ đếm số lượng thì không trả lời được câu duy // nhất đáng hỏi lúc đó: nới quạt ra, hay xoay robot lại? Cần biết nó nằm ở đâu. bool have_gated = false; Point gated_apex; double gated_dist = 0.0; // Ứng viên trượt SÁT NHẤT ở cổng góc / cổng chiều dài, kèm số ĐO ĐƯỢC. Chỉ đếm số cặp thì không // biết nên nới dung sai hay sửa chỗ khác — mà "cánh ngắn vì bị che" và "cánh dài vì bắt nhầm // vật" đòi hai cách xử trí ngược nhau. // Ứng viên đúng hình nhưng trượt cổng phản quang, kèm số ĐO ĐƯỢC. "Không thấy dải nào" và "thấy // hai dải nhưng cách nhau 0.31 m" đòi hai cách xử trí ngược nhau: cái đầu là ngưỡng cường độ hoặc // dải bẩn, cái sau là bắt nhầm vật khác. bool have_tape_miss = false; double tape_miss_spacing = 0.0; std::size_t tape_miss_points[2] = { 0, 0 }; Point tape_miss_apex; bool have_near = false; double near_penalty = 0.0; double near_vertex = 0.0; double near_len[2] = { 0.0, 0.0 }; Point near_apex; const auto noteNearMiss = [&](double penalty, double vertex, double l1v, double l2v, const Point& apex_pt) { if (have_near && penalty >= near_penalty) { return; } have_near = true; near_penalty = penalty; near_vertex = vertex; near_len[0] = l1v; near_len[1] = l2v; near_apex = apex_pt; }; for (std::size_t i = 0; i + 1 < lines.size(); ++i) { for (std::size_t j = i + 1; j < lines.size(); ++j) { const Line& l1 = lines[i]; const Line& l2 = lines[j]; if (l1.numPoints() < profile_.min_wing_points || l2.numPoints() < profile_.min_wing_points) { ++rejected_support; continue; } Point apex; if (!intersect(l1, l2, apex)) { continue; // Song song. Không phải "gần đúng chữ V", chỉ là không phải chữ V. } // Cổng quyết định: hai ĐẦU ĐOẠN phải nằm ngay tại giao điểm. Hai bức tường không song song // nào cũng cắt nhau ở đâu đó; chỉ chữ V thật mới có hai đoạn kết thúc tại chỗ cắt. const Point near1 = nearEndpoint(l1, apex); const Point near2 = nearEndpoint(l2, apex); if (dist(near1, apex) > profile_.vertex_gap || dist(near2, apex) > profile_.vertex_gap) { ++rejected_vertex_gap; continue; } // Góc TRONG tại đỉnh, đo giữa hai vector cánh. Không đo giữa hai pháp tuyến: hai cách trùng // nhau ở đúng 90 độ và lệch nhau ở mọi góc khác, nên nhầm là sai âm thầm. const Point tip1 = farEndpoint(l1, apex); const Point tip2 = farEndpoint(l2, apex); const double v1x = tip1.x - apex.x; const double v1y = tip1.y - apex.y; const double v2x = tip2.x - apex.x; const double v2y = tip2.y - apex.y; const double len1 = std::hypot(v1x, v1y); const double len2 = std::hypot(v2x, v2y); if (len1 < 1e-9 || len2 < 1e-9) { continue; } const double cos_vertex = (v1x * v2x + v1y * v2y) / (len1 * len2); const double vertex = std::acos(std::max(-1.0, std::min(1.0, cos_vertex))); const double angle_dev = vertex - profile_.vertex_angle; if (std::fabs(angle_dev) > profile_.angle_tolerance) { ++rejected_angle; noteNearMiss(std::fabs(angle_dev) / profile_.angle_tolerance, vertex, len1, len2, apex); continue; } // Luật chiều dài KHÔNG đối xứng, và đó là chủ đích. // // Nhìn tấm chếch thì cánh xa gần như song song với tia: rất ít tia trúng nó, đoạn trích ra // NGẮN hơn thật. Che khuất chỉ làm ngắn đi, không bao giờ dài ra. Bắt cả hai cánh đúng // `wing_length` 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. // // Nên: // - KHÔNG cánh nào được DÀI hơn `wing_length + tol`. Đây là cổng giữ nguyên tác dụng chặn // góc pallet: pallet có CẢ HAI cạnh dài, nên nó vẫn bị loại. // - ÍT NHẤT MỘT cánh phải đúng `wing_length ± tol`. Vẫn phải nhìn thấy trọn một cánh, nếu // không thì hai mẩu ngắn bất kỳ gặp nhau ở 90 độ cũng lọt. const double longest = std::max(len1, len2); const double shortest = std::min(len1, len2); if (longest > profile_.wing_length + profile_.length_tolerance || longest < profile_.wing_length - profile_.length_tolerance) { ++rejected_length; noteNearMiss(std::fabs(longest - profile_.wing_length) / profile_.length_tolerance, vertex, len1, len2, apex); continue; } if (shortest > profile_.wing_length + profile_.length_tolerance) { ++rejected_length; noteNearMiss(std::fabs(shortest - profile_.wing_length) / profile_.length_tolerance, vertex, len1, len2, apex); continue; } // Điểm tin chấm chiều dài theo cánh DÀI, không phải cánh ngắn. Cánh ngắn được luật ở trên // cho phép ngắn — trừ điểm nó nữa là phạt hai lần cùng một chuyện, và tạo ra vách: ứng viên // vừa lọt cổng chiều dài lại rớt ngay cổng độ tin. // // Việc "nhìn được ít quá nên đừng tin" đã có `support` lo: nó tính theo số tia đỡ của cánh ÍT // tia nhất, nên nhìn càng chếch điểm càng xuống — giảm dần, không phải vách. const double len_dev1 = longest - profile_.wing_length; const double len_dev2 = len_dev1; // Phân giác, rồi lật cho hướng RA phía cảm biến. Chọn dấu bằng vị trí cảm biến chứ không bằng // thứ tự hai cánh: thứ tự đổi theo phía robot đứng, và lệch 180 độ ở đây là robot lùi vào // tấm sạc thay vì tiến vào. double bx = v1x / len1 + v2x / len2; double by = v1y / len1 + v2y / len2; const double bn = std::hypot(bx, by); if (bn < 1e-9) { continue; // Hai cánh ngược chiều nhau: một đường thẳng, không phải chữ V. } bx /= bn; by /= bn; // Gốc cảm biến là (0, 0) trong frame của scan, nên vector từ đỉnh về phía cảm biến là -apex. // TRƯỚC khi lật: b đang chỉ vào LÒNG chữ V (xem class doc). Lòng V đã hướng VỀ cảm biến // (dot >= 0) là V LÕM — tấm ôm lấy robot; lòng V hướng RA XA cảm biến (dot < 0) là V LỒI — // góc ngoài của một vật khác (tủ, pallet). Phải đọc dấu NGAY ĐÂY, trước khi bước lật dưới // xoá mất nó bằng cách luôn quay b về phía cảm biến. const double dot_to_sensor = bx * (-apex.x) + by * (-apex.y); const bool opens_to_sensor = dot_to_sensor >= 0.0; // true = lõm, false = lồi if ((profile_.v_shape == VShape::kConcave && !opens_to_sensor) || (profile_.v_shape == VShape::kConvex && opens_to_sensor)) { ++rejected_shape; continue; } if (dot_to_sensor < 0.0) { bx = -bx; by = -by; } const double yaw = std::atan2(by, bx); // Cổng phản quang. Đặt SAU mọi cổng hình học vì nó đắt hơn hẳn — quét lại từng tia của hai // cánh — và hình học đã loại gần hết ứng viên trước khi tới đây. double tape_spacing_score = 1.0; double tape_width_score = 1.0; TapeRun tape1; TapeRun tape2; if (profile_.tape_enabled) { tape1 = findTape(l1, intensities, profile_.tape_min_intensity); tape2 = findTape(l2, intensities, profile_.tape_min_intensity); const double measured_spacing = (tape1.found && tape2.found) ? dist(tape1.centre, tape2.centre) : 0.0; if (!have_tape_miss || (tape1.points + tape2.points) > (tape_miss_points[0] + tape_miss_points[1])) { have_tape_miss = true; tape_miss_spacing = measured_spacing; tape_miss_points[0] = tape1.points; tape_miss_points[1] = tape2.points; tape_miss_apex = apex; } if (!tape1.found || !tape2.found) { ++rejected_tape; continue; } const double spacing_dev = measured_spacing - profile_.tape_spacing; if (std::fabs(spacing_dev) > profile_.tape_spacing_tolerance) { ++rejected_tape; continue; } tape_spacing_score = score(spacing_dev, profile_.tape_spacing_tolerance); // Chiều dài chỉ kiểm khi đo được. Một tia thì biết là sáng nhưng không biết rộng bao nhiêu; // bỏ qua tiêu chí ấy là trung thực hơn đoán, và ở tầm xa đó lại đúng là lúc cần dải nhất. for (const TapeRun& tape : { tape1, tape2 }) { if (!tape.width_known) { continue; } const double width_dev = tape.width - profile_.tape_width; if (std::fabs(width_dev) > profile_.tape_width_tolerance) { ++rejected_tape; tape_width_score = -1.0; // đánh dấu trượt, kiểm ngay dưới break; } tape_width_score = std::min(tape_width_score, score(width_dev, profile_.tape_width_tolerance)); } if (tape_width_score < 0.0) { continue; } } if (profile_.has_prior) { const double d = std::hypot(apex.x - profile_.prior_x, apex.y - profile_.prior_y); if (d > profile_.search_radius) { ++rejected_prior; if (!have_gated || d < gated_dist) { have_gated = true; gated_apex = apex; gated_dist = d; } continue; } } if (profile_.search_fov > 0.0 && std::fabs(std::atan2(apex.y, apex.x)) > profile_.search_fov) { ++rejected_prior; const double bearing = std::fabs(std::atan2(apex.y, apex.x)); if (!have_gated || bearing < gated_dist) { have_gated = true; gated_apex = apex; gated_dist = bearing; } continue; } // Điểm tin: trục tệ nhất trong ba tiêu chí, không phải trung bình. Trung bình cho một hình // sai hẳn góc nhưng đúng chiều dài lọt qua bằng điểm của hai tiêu chí kia. const double support = std::min(1.0, static_cast(std::min(l1.numPoints(), l2.numPoints())) / static_cast(profile_.min_wing_points * 2)); const double confidence = std::min({ score(angle_dev, profile_.angle_tolerance), score(len_dev1, profile_.length_tolerance), score(len_dev2, profile_.length_tolerance), support, tape_spacing_score, tape_width_score }); if (confidence < profile_.min_confidence) { ++rejected_confidence; continue; } ++accepted; if (confidence <= best.confidence && best.valid) { continue; } best.valid = true; best.confidence = confidence; best.apex_x = apex.x; best.apex_y = apex.y; best.measured_vertex_angle = vertex; best.measured_wing_length[0] = len1; best.measured_wing_length[1] = len2; best.measured_tape_spacing = (tape1.found && tape2.found) ? dist(tape1.centre, tape2.centre) : 0.0; best.measured_tape_width[0] = tape1.width; best.measured_tape_width[1] = tape2.width; best.tape_points[0] = tape1.points; best.tape_points[1] = tape2.points; // Pose đích = đỉnh dịch theo offset của profile, trong hệ của CHÍNH hình: x dọc pháp tuyến // hướng ra phía robot, y sang trái. const double cos_y = std::cos(yaw); const double sin_y = std::sin(yaw); best.x = apex.x + cos_y * profile_.offset_x - sin_y * profile_.offset_y; best.y = apex.y + sin_y * profile_.offset_x + cos_y * profile_.offset_y; best.yaw = std::atan2(std::sin(yaw + profile_.offset_yaw), std::cos(yaw + profile_.offset_yaw)); } } best.candidate_count = accepted; best.segment_count = lines.size(); if (!best.valid) { // Lý do cụ thể nhất trước: cái đếm nào lớn nhất nói đúng chỗ đang hỏng. "Không thấy gì" và // "thấy nhưng méo" đòi hai cách xử trí ngược nhau, mà một dòng "detection failed" thì không. if (rejected_prior > 0) { // Kèm VỊ TRÍ và HƯỚNG của ứng viên gần nhất bị loại. Chỉ có con số thì không biết nên nới // quạt hay xoay robot — mà đó đúng là câu duy nhất cần trả lời lúc này. char detail[192] = { 0 }; if (have_gated) { std::snprintf(detail, sizeof(detail), " (nearest at (%.2f, %.2f) m, bearing %.2f rad = %.0f deg, range %.2f m;" " gate search_fov=%.2f rad", gated_apex.x, gated_apex.y, std::atan2(gated_apex.y, gated_apex.x), std::atan2(gated_apex.y, gated_apex.x) * 180.0 / M_PI, std::hypot(gated_apex.x, gated_apex.y), profile_.search_fov); std::string tail = profile_.has_prior ? ", search_radius=" + std::to_string(profile_.search_radius) + " m)" : ")"; best.reason = std::to_string(rejected_prior) + " candidate(s) matched the shape but fell outside the search gate" + detail + tail; } else { best.reason = std::to_string(rejected_prior) + " candidate(s) matched the shape but fell outside the search gate"; } } else if (rejected_tape > 0) { char detail[224] = { 0 }; if (have_tape_miss) { std::snprintf(detail, sizeof(detail), " (nearest: %zu + %zu bright ray(s), spacing %.3f m vs %.3f+-%.3f," " apex at (%.2f, %.2f); threshold tape_min_intensity=%.0f)", tape_miss_points[0], tape_miss_points[1], tape_miss_spacing, profile_.tape_spacing, profile_.tape_spacing_tolerance, tape_miss_apex.x, tape_miss_apex.y, profile_.tape_min_intensity); } best.reason = std::to_string(rejected_tape) + " candidate(s) had the right shape but not the reflective tape signature"; best.reason += detail; } else if (rejected_confidence > 0) { best.reason = std::to_string(rejected_confidence) + " candidate(s) matched but scored below min_confidence"; } else if (rejected_shape > 0) { // Nói rõ profile đang đòi hướng nào — "đúng hình nhưng sai hướng" đòi xử trí khác hẳn "sai // góc/chiều dài": đây không phải lỗi dung sai, mà là một vật khác hình chữ V thật (góc tủ, // góc pallet lồi ra phía cảm biến thay vì lõm vào). best.reason = std::to_string(rejected_shape) + " candidate(s) had the right vertex angle and wing length but the wrong " "concave/convex orientation (profile requires v_shape=" + toString(profile_.v_shape) + ")"; } else if (rejected_length > 0 || rejected_angle > 0) { // Số ĐO ĐƯỢC của ứng viên trượt sát nhất. Không có nó thì "cánh 0.22 m vì bị che" và // "cánh 0.80 m vì đó là góc pallet" ra cùng một dòng log. char detail[224] = { 0 }; if (have_near) { std::snprintf(detail, sizeof(detail), " (nearest: vertex %.3f rad vs %.3f+-%.3f, wings %.3f / %.3f m vs %.3f+-%.3f," " apex at (%.2f, %.2f) range %.2f m)", near_vertex, profile_.vertex_angle, profile_.angle_tolerance, near_len[0], near_len[1], profile_.wing_length, profile_.length_tolerance, near_apex.x, near_apex.y, std::hypot(near_apex.x, near_apex.y)); } best.reason = rejected_length > 0 ? std::to_string(rejected_length) + " pair(s) had the right vertex angle but the wrong wing length" : std::to_string(rejected_angle) + " pair(s) met at a vertex but at the wrong angle"; best.reason += detail; } else if (rejected_vertex_gap > 0) { best.reason = std::to_string(rejected_vertex_gap) + " pair(s) of lines cross but do not end at the crossing — not a V"; } else if (rejected_support > 0) { best.reason = std::to_string(rejected_support) + " pair(s) had too few supporting rays; move closer or lower min_wing_points"; } else { best.reason = "no pair of segments forms a vertex"; } // Số ĐOẠN của chính scan đó. Thiếu nó thì "cảnh vụn thành 12 mẩu" và "chỉ thấy đúng hai bức // tường" in ra cùng một dòng, mà hai ca ấy đòi chỉnh hai khoá khác nhau: `min_split_dist` / // `min_line_length` cho ca đầu, chỗ đứng cho ca sau. best.reason += " [" + std::to_string(lines.size()) + " segment(s) in the scan]"; } return best; } } // namespace dock_pattern_detector