#include #include #include #include namespace dock_pattern_detector { namespace { constexpr double kPi = 3.14159265358979323846; constexpr double kEpsilon = 1e-9; double wrap(double angle) { return std::atan2(std::sin(angle), std::cos(angle)); } bool finitePose(const ReflectorPose2D& p) { return std::isfinite(p.x) && std::isfinite(p.y) && std::isfinite(p.yaw); } } // namespace bool ReflectorPairMatcher::configure(const ReflectorPairProfile& profile, std::string& error) { if (!profile.validate(error)) { return false; } profile_ = profile; if (std::isnan(profile_.tape_core_intensity)) profile_.tape_core_intensity = profile_.tape_min_intensity; if (std::isnan(profile_.tape_plateau_min_fraction)) profile_.tape_plateau_min_fraction = 1.0; configured_ = true; return true; } bool ReflectorPairMatcher::fitLine(const std::vector& indices, Line& line) const { if (indices.size() < 3) { return false; } double mx = 0.0; double my = 0.0; for (const auto index : indices) { mx += rays_[index].x; my += rays_[index].y; } mx /= static_cast(indices.size()); my /= static_cast(indices.size()); double xx = 0.0; double xy = 0.0; double yy = 0.0; for (const auto i : indices) { const double dx = rays_[i].x - mx; const double dy = rays_[i].y - my; xx += dx * dx; xy += dx * dy; yy += dy * dy; } if (!std::isfinite(xx + yy) || xx + yy < kEpsilon || std::hypot(xx - yy, 2.0 * xy) < kEpsilon) { return false; } const double angle = 0.5 * std::atan2(2.0 * xy, xx - yy); line.nx = -std::sin(angle); line.ny = std::cos(angle); line.rho = line.nx * mx + line.ny * my; // n phải hướng từ tường về gốc sensor, nghĩa là rho mang dấu âm. if (line.rho > 0.0) { line.nx = -line.nx; line.ny = -line.ny; line.rho = -line.rho; } if (line.rho >= -kEpsilon) { return false; } double sum = 0.0; line.max_residual = 0.0; for (const auto i : indices) { const double e = std::abs(line.nx * rays_[i].x + line.ny * rays_[i].y - line.rho); sum += e * e; line.max_residual = std::max(line.max_residual, e); } line.rms = std::sqrt(sum / static_cast(indices.size())); return std::isfinite(line.rms) && std::isfinite(line.max_residual); } bool ReflectorPairMatcher::evaluatePair(const Candidate& first_candidate, const Candidate& second_candidate, const robot_line_extraction::ScanGeometry& geometry, const ReflectorPose2D& scan_in_prior, ReflectorPairDetection& out, const char*& reason) { const auto fail = [&reason](const char* why) { reason = why; return false; }; support_.clear(); left_support_.clear(); right_support_.clear(); std::size_t lo = first_candidate.first; std::size_t hi = second_candidate.last; bool left_open = true; bool right_open = true; // Khi gặp mép tường, giữ chỉ số tia hợp lệ cuối; phía còn lại vẫn có thể bù baseline. for (;;) { const bool have_sides = left_support_.size() >= profile_.wall_min_points_each_side && right_support_.size() >= profile_.wall_min_points_each_side; bool have_span = false; if (have_sides && std::hypot(rays_[left_support_.back()].x - rays_[right_support_.back()].x, rays_[left_support_.back()].y - rays_[right_support_.back()].y) >= profile_.wall_min_span) { // Span phải đo theo TLS, không theo dây nối hai đầu: nhiễu pháp tuyến làm dây dài giả. support_.clear(); for (std::size_t index = lo; index <= hi; ++index) { if (!rays_[index].valid) { return fail("wall_occluded_or_invalid"); } if (!rays_[index].masked) { support_.push_back(index); } } Line provisional_wall; if (!fitLine(support_, provisional_wall)) { return fail("wall_degenerate"); } double minimum = std::numeric_limits::infinity(); double maximum = -minimum; for (const std::size_t index : support_) { const double along = -provisional_wall.ny * rays_[index].x + provisional_wall.nx * rays_[index].y; minimum = std::min(minimum, along); maximum = std::max(maximum, along); } have_span = maximum - minimum >= profile_.wall_min_span; } if (have_sides && have_span) { break; } bool advanced = false; if (left_open && (left_support_.size() < profile_.wall_min_points_each_side || !have_span)) { if (lo == 0 || !rays_[lo - 1].valid) { left_open = false; } else { --lo; if (!rays_[lo].masked) { left_support_.push_back(lo); } advanced = true; } } if (right_open && (right_support_.size() < profile_.wall_min_points_each_side || !have_span)) { if (hi + 1 >= rays_.size() || !rays_[hi + 1].valid) { right_open = false; } else { ++hi; if (!rays_[hi].masked) { right_support_.push_back(hi); } advanced = true; } } if (!advanced) { return fail("wall_support"); } } support_.clear(); for (std::size_t i = lo; i <= hi; ++i) { if (!rays_[i].valid) { return fail("wall_occluded_or_invalid"); } if (!rays_[i].masked) { if (!support_.empty()) { const Ray& prev = rays_[support_.back()]; if (std::hypot(rays_[i].x - prev.x, rays_[i].y - prev.y) > profile_.wall_max_gap) { return fail("wall_gap_or_occlusion"); } } support_.push_back(i); } } Line wall; if (!fitLine(support_, wall)) { return fail("wall_degenerate"); } if (wall.rms > profile_.wall_max_rms || wall.max_residual > profile_.wall_max_residual) { return fail("wall_residual_or_occlusion"); } // Range sáng không tham gia fit hay tọa độ mép; chỉ dùng để loại vật sáng rõ ràng // nằm ngoài mặt tường. Dung sai này cho phép bias range phản quang hữu hạn, cần hiệu chuẩn. for (std::size_t i = lo; i <= hi; ++i) { if (!rays_[i].masked) { continue; } const double angle = geometry.angle_min + static_cast(i) * geometry.angle_increment; const double ray_normal_dot = wall.nx * std::cos(angle) + wall.ny * std::sin(angle); if (std::abs(ray_normal_dot) < kEpsilon) { return fail("wall_occlusion_unknown"); } const double expected = wall.rho / ray_normal_dot; if (expected <= 0.0 || !std::isfinite(expected)) { return fail("wall_occlusion_unknown"); } const double observed = rays_[i].range; if (rays_[i].bright) { if (std::abs(observed - expected) * std::abs(ray_normal_dot) > profile_.wall_max_residual + profile_.wall_merge_distance) { return fail("bright_off_wall"); } } else if ((expected - observed) * std::abs(ray_normal_dot) > profile_.wall_max_residual) { return fail("wall_occlusion"); } } // So phần dư trung bình có dấu của hai đầu và vùng giữa trên CÙNG đường fit. // Góc fit riêng trên đoạn ngắn rất nhạy với nhiễu range và không đo được hai mặt bền vững. double left_residual = 0.0; double middle_residual = 0.0; double right_residual = 0.0; std::size_t middle_count = 0; for (const std::size_t index : support_) { const double residual = wall.nx * rays_[index].x + wall.ny * rays_[index].y - wall.rho; if (index < first_candidate.first) { left_residual += residual; } else if (index > second_candidate.last) { right_residual += residual; } else { middle_residual += residual; ++middle_count; } } left_residual /= static_cast(left_support_.size()); right_residual /= static_cast(right_support_.size()); if (std::abs(left_residual - right_residual) > profile_.wall_merge_distance) { return fail("wall_not_same_line"); } // Khe giữa hai dải có thể rất hẹp (dải 3 cm cách tâm 9 cm chỉ chừa 6 cm) và bloom có thể che kín // nó. Nhóm giữa chỉ vào cổng đồng mặt khi đủ tia như mỗi phía ngoài: vài tia thì trung bình của // chúng quá nhiễu để so. Tia bị che trong khe vẫn qua cổng `bright_off_wall` / `wall_occlusion` // ở trên, nên vật chắn trong khe vẫn bị loại. if (middle_count >= profile_.wall_min_points_each_side) { middle_residual /= static_cast(middle_count); if (std::abs(left_residual - middle_residual) > profile_.wall_merge_distance || std::abs(right_residual - middle_residual) > profile_.wall_merge_distance) { return fail("wall_not_same_line"); } } const double tangent_x = -wall.ny; const double tangent_y = wall.nx; double support_min = std::numeric_limits::infinity(); double support_max = -support_min; for (const auto i : support_) { const double v = tangent_x * rays_[i].x + tangent_y * rays_[i].y; support_min = std::min(support_min, v); support_max = std::max(support_max, v); } if (support_max - support_min < profile_.wall_min_span) { return fail("wall_span"); } const std::array core{{first_candidate.core_first, first_candidate.core_last, second_candidate.core_first, second_candidate.core_last}}; std::array edge_x{}; std::array edge_y{}; std::array uncertainty{}; for (std::size_t j = 0; j < 4; ++j) { const double index = static_cast(core[j]) + (j % 2 == 0 ? -0.5 : 0.5); const double angle = geometry.angle_min + index * geometry.angle_increment; const double ux = std::cos(angle); const double uy = std::sin(angle); const double denominator = wall.nx * ux + wall.ny * uy; if (std::abs(denominator) < profile_.min_ray_wall_cos) { return fail("edge_parallel"); } const double distance = wall.rho / denominator; if (!std::isfinite(distance) || distance <= 0.0) { return fail("edge_behind_sensor"); } edge_x[j] = distance * ux; edge_y[j] = distance * uy; const double along = tangent_x * edge_x[j] + tangent_y * edge_y[j]; if (along < support_min - profile_.wall_max_extrapolation || along > support_max + profile_.wall_max_extrapolation) { return fail("wall_extrapolation"); } uncertainty[j] = std::abs(wall.rho) * std::abs(geometry.angle_increment) / (2.0 * denominator * denominator) + profile_.edge_bias_bound; if (!std::isfinite(uncertainty[j]) || uncertainty[j] > profile_.max_edge_uncertainty) { return fail("edge_uncertainty"); } } const double first_width = std::hypot(edge_x[1] - edge_x[0], edge_y[1] - edge_y[0]); const double second_width = std::hypot(edge_x[3] - edge_x[2], edge_y[3] - edge_y[2]); if (std::abs(first_width - profile_.tape_width) > profile_.width_tolerance || std::abs(second_width - profile_.tape_width) > profile_.width_tolerance) { return fail("width"); } const double first_center_x = (edge_x[0] + edge_x[1]) / 2.0; const double first_center_y = (edge_y[0] + edge_y[1]) / 2.0; const double second_center_x = (edge_x[2] + edge_x[3]) / 2.0; const double second_center_y = (edge_y[2] + edge_y[3]) / 2.0; const double spacing = std::hypot(second_center_x - first_center_x, second_center_y - first_center_y); if (std::abs(spacing - profile_.tape_spacing) > profile_.spacing_tolerance) { return fail("spacing"); } const double cos_yaw = std::cos(scan_in_prior.yaw); const double sin_yaw = std::sin(scan_in_prior.yaw); const double center_x = (first_center_x + second_center_x) / 2.0; const double center_y = (first_center_y + second_center_y) / 2.0; const double yaw = wrap(std::atan2(wall.ny, wall.nx) + scan_in_prior.yaw); ReflectorPose2D marker{scan_in_prior.x + cos_yaw * center_x - sin_yaw * center_y, scan_in_prior.y + sin_yaw * center_x + cos_yaw * center_y, yaw}; if (!finitePose(marker)) { return fail("nonfinite_pose"); } if (std::abs(wrap(std::atan2(marker.y, marker.x) - profile_.search_center_yaw)) > profile_.search_fov) { return fail("search_fov"); } if (profile_.has_prior && (std::hypot(marker.x - profile_.prior_x, marker.y - profile_.prior_y) > profile_.prior_position_tolerance || std::abs(wrap(marker.yaw - profile_.prior_yaw)) > profile_.prior_yaw_tolerance)) { return fail("prior"); } const double nx = std::cos(yaw); const double ny = std::sin(yaw); ReflectorPose2D target{marker.x + profile_.offset_x * nx - profile_.offset_y * ny, marker.y + profile_.offset_x * ny + profile_.offset_y * nx, wrap(yaw + profile_.offset_yaw)}; if (!finitePose(target)) { return fail("nonfinite_pose"); } out.marker = marker; out.target = target; out.widths = {{first_width, second_width}}; out.spacing = spacing; out.wall_rms = wall.rms; out.wall_max_residual = wall.max_residual; out.wall_support = {{left_support_.size(), right_support_.size()}}; out.edge_uncertainty = uncertainty; return true; } ReflectorPairDetection ReflectorPairMatcher::match( const robot_line_extraction::ScanGeometry& geometry, const std::vector& ranges, const std::vector& intensities, const ReflectorPairLimits& limits, const ReflectorPose2D& scan_in_prior) { ReflectorPairDetection result; const auto fail = [&result](const char* why) { result.reason = why; return result; }; if (!configured_) { return fail("not_configured"); } if (!std::isfinite(limits.min_range) || !std::isfinite(limits.max_range) || limits.min_range < 0.0 || limits.max_range <= limits.min_range || limits.max_candidates < 2 || limits.max_candidates > 128 || limits.max_pairs < 1 || limits.max_pairs > 8128 || limits.max_scan_rays < 2 || limits.max_scan_rays > 65536 || !finitePose(scan_in_prior)) { return fail("invalid_limits_or_transform"); } if (geometry.size > limits.max_scan_rays) { return fail("capacity_scan_rays"); } std::string geometry_error; if (!geometry.validate(geometry_error) || ranges.size() != geometry.size || !std::isfinite(geometry.angle_min + (geometry.size - 1) * geometry.angle_increment)) { return fail("invalid_scan_geometry_or_ranges"); } if (intensities.empty()) { return fail("no_intensity_data"); } if (intensities.size() != ranges.size()) { return fail("intensity_size_mismatch"); } rays_.resize(geometry.size); candidates_.clear(); // Reserve theo scan lớn nhất từng thấy, không tạo vector tạm cho từng cặp. support_.reserve(geometry.size); left_support_.reserve(geometry.size); right_support_.reserve(geometry.size); candidates_.reserve(limits.max_candidates); for (std::size_t i = 0; i < geometry.size; ++i) { Ray& ray = rays_[i]; ray = Ray{}; const double r = ranges[i]; ray.valid = std::isfinite(r) && r > 0.0 && r >= limits.min_range && r <= limits.max_range && std::isfinite(intensities[i]); if (ray.valid) { ray.range = r; ray.bright = intensities[i] >= profile_.tape_min_intensity; if (!ray.bright) { const double angle = geometry.angle_min + static_cast(i) * geometry.angle_increment; ray.x = r * std::cos(angle); ray.y = r * std::sin(angle); } } } const double steps_d = std::ceil(profile_.tape_bloom_max_angle / std::abs(geometry.angle_increment)); const std::size_t skirt = steps_d >= static_cast(geometry.size) ? geometry.size : static_cast(steps_d); for (std::size_t i = 0; i < geometry.size;) { if (!rays_[i].valid || !rays_[i].bright) { ++i; continue; } const std::size_t first = i; while (i < geometry.size && rays_[i].valid && rays_[i].bright) { ++i; } const std::size_t last = i - 1; const std::size_t mask_first = first > skirt ? first - skirt : 0; const std::size_t mask_last = last + std::min(skirt, geometry.size - 1 - last); for (std::size_t j = mask_first; j <= mask_last; ++j) { rays_[j].masked = true; } // Mọi đoạn lõi (>= tape_core_intensity) liên tiếp trong run. Hai dải đặt sát nhau (3 cm cách // tâm 9 cm) có thể bị bloom nối thành MỘT bright run chứa hai lõi; mỗi lõi phải thành một // candidate riêng, nếu không cặp thật bị loại như một dải "hai lõi". cores_.clear(); for (std::size_t j = first; j <= last;) { if (intensities[j] < profile_.tape_core_intensity) { ++j; continue; } const std::size_t start = j; while (j <= last && intensities[j] >= profile_.tape_core_intensity) { ++j; } cores_.push_back(CoreSegment{start, j - 1}); } if (cores_.empty()) { ++result.rejected_runs; continue; } // Chia run tại tia tối nhất giữa hai lõi kề nhau: mỗi lõi giữ phần bloom về phía nó. Một dải // có vết lõm giữa sẽ thành hai lõi hẹp; cổng width ở bước ghép cặp loại chúng. std::size_t sub_first = first; for (std::size_t k = 0; k < cores_.size(); ++k) { std::size_t sub_last = last; if (k + 1 < cores_.size()) { // Tia tối nhất của khe; nhiều tia cùng mức tối (bloom phẳng, bão hòa) thì lấy giữa vùng đó // để hai lõi chia đều phần bloom, không dồn cả khe cho một bên. const std::size_t gap_first = cores_[k].last + 1; const std::size_t gap_last = cores_[k + 1].first - 1; float darkest = intensities[gap_first]; for (std::size_t j = gap_first; j <= gap_last; ++j) { darkest = std::min(darkest, intensities[j]); } std::size_t darkest_first = gap_last; std::size_t darkest_last = gap_first; for (std::size_t j = gap_first; j <= gap_last; ++j) { if (intensities[j] == darkest) { darkest_first = std::min(darkest_first, j); darkest_last = std::max(darkest_last, j); } } sub_last = darkest_first + (darkest_last - darkest_first) / 2; } const std::size_t core_first = cores_[k].first; const std::size_t core_last = cores_[k].last; const std::size_t core_length = core_last - core_first + 1; const std::size_t sub_length = sub_last - sub_first + 1; const bool accepted = core_length >= profile_.tape_min_points && static_cast(core_length) / static_cast(sub_length) >= profile_.tape_plateau_min_fraction && core_first > 0 && core_last + 1 < geometry.size && rays_[core_first - 1].valid && rays_[core_last + 1].valid && intensities[core_first - 1] < profile_.tape_core_intensity && intensities[core_last + 1] < profile_.tape_core_intensity; if (!accepted) { ++result.rejected_runs; } else { if (candidates_.size() >= limits.max_candidates) { result.candidate_count = candidates_.size() + 1; return fail("capacity_candidates"); } candidates_.push_back(Candidate{sub_first, sub_last, core_first, core_last}); } sub_first = sub_last + 1; } } result.candidate_count = candidates_.size(); if (candidates_.size() < 2) { return fail(result.rejected_runs ? "insufficient_candidates_or_core" : "insufficient_candidates"); } const std::size_t count = candidates_.size() * (candidates_.size() - 1) / 2; if (count > limits.max_pairs) { return fail("capacity_pairs"); } const char* last_reason = "no_valid_pair"; for (std::size_t i = 0; i < candidates_.size(); ++i) { for (std::size_t j = i + 1; j < candidates_.size(); ++j) { ++result.tested_pairs; ReflectorPairDetection pair; if (evaluatePair(candidates_[i], candidates_[j], geometry, scan_in_prior, pair, last_reason)) { ++result.valid_pairs; if (result.valid_pairs == 1) { result.marker = pair.marker; result.target = pair.target; result.widths = pair.widths; result.spacing = pair.spacing; result.wall_rms = pair.wall_rms; result.wall_max_residual = pair.wall_max_residual; result.wall_support = pair.wall_support; result.edge_uncertainty = pair.edge_uncertainty; } } } } if (result.valid_pairs > 1) { // Không trả pose tùy ý khi còn nhiều cặp hợp lệ. result.marker = ReflectorPose2D{}; result.target = ReflectorPose2D{}; result.widths = {{0.0, 0.0}}; result.spacing = 0.0; result.wall_rms = 0.0; result.wall_max_residual = 0.0; result.wall_support = {{0, 0}}; result.edge_uncertainty = {{0.0, 0.0, 0.0, 0.0}}; return fail("ambiguous"); } if (result.valid_pairs == 0) { result.reason = last_reason; return result; } result.valid = true; result.reason.clear(); return result; } } // namespace dock_pattern_detector