From f0c5ddb6b87585d06d3fb49bba37432ed474af07 Mon Sep 17 00:00:00 2001 From: trung09122002 Date: Tue, 6 Oct 2026 10:17:17 +0700 Subject: [PATCH] reloc,web: dinh vi lai TREN DOC (slope.enabled) -- loc gia thuyet bang do nghieng IMU vs do doc ban do, chan mu doc truc (ShiftScoreRatio), vong DUNG YEN khong xoay (ty le nho nhat >= 3 vong / hai cho cung pose), tu chay bo thang tren doc; camera VPR+PnP tren doc (>= 2 anh trung, khop nghieng, LiDAR khong phan doi, pose = trung binh camera) -- sim 10 cho chot dung 1.4-2.9 cm, 0 chot sai; web 3D: ban do uon theo san (FLH1), scan/quy dao theo z, het nen lung, sua ro GPU; CMake: TensorRT tren CMake < 3.17 --- app/src/runtime.cc | 520 +++++++++++++++++- app/src/runtime.h | 33 ++ app/src/wiring.cc | 1 + libs/vslam_slam/CMakeLists.txt | 21 +- .../include/vslam/global_localizer.h | 107 +++- libs/vslam_slam/include/vslam/height_map.h | 12 + libs/vslam_slam/src/global_localizer.cc | 245 ++++++++- libs/vslam_slam/src/height_map.cc | 24 + libs/vslam_web/include/vslam/binary_codec.h | 25 +- libs/vslam_web/include/vslam/web_snapshot.h | 3 + libs/vslam_web/src/binary_codec.cc | 37 +- libs/vslam_web/src/web_server.cc | 3 +- libs/vslam_web/www/app.js | 27 +- libs/vslam_web/www/app3d.js | 169 +++++- test/CMakeLists.txt | 9 + test/test_binary_codec.cc | 54 ++ test/test_global_localizer.cc | 286 ++++++++++ test/test_height_map.cc | 34 ++ test/www/test_map_floor.js | 405 ++++++++++++++ 19 files changed, 1947 insertions(+), 68 deletions(-) create mode 100644 test/www/test_map_floor.js diff --git a/app/src/runtime.cc b/app/src/runtime.cc index c606013..1cede2a 100644 --- a/app/src/runtime.cc +++ b/app/src/runtime.cc @@ -59,6 +59,35 @@ namespace { // // Chi de CANH BAO, khong dieu khien gi. constexpr double kFastAccelWarn = 0.7; + +#ifdef VSLAM_HAVE_SLAM +// Do cao SAN cho web (che do doc): luoi 0.2 m phu CUNG khung voi luoi 2D, moi +// o lay mat phang node gan nhat. Web uon mat phang ban do theo no -- khong co +// thi mat doc va san tang tren ve o z = 0, duoi tuong voxel (o z that), trong +// nhu san bi thung. +std::shared_ptr BuildMapFloorGrid(const FloorModel& fm, + const OccupancyGrid& grid) { + if (fm.empty() || grid.resolution <= 0.0f) return nullptr; + auto fg = std::make_shared(); + fg->resolution = 0.2f; + fg->origin_x = static_cast(grid.origin.position.x); + fg->origin_y = static_cast(grid.origin.position.y); + fg->width = static_cast(std::ceil(grid.width * grid.resolution / fg->resolution)); + fg->height = static_cast(std::ceil(grid.height * grid.resolution / fg->resolution)); + fg->mm.assign(static_cast(fg->width) * fg->height, kFloorUnknown); + for (uint32_t r = 0; r < fg->height; ++r) { + for (uint32_t c = 0; c < fg->width; ++c) { + double fz = 0.0; + if (fm.FloorAt(fg->origin_x + (c + 0.5) * fg->resolution, + fg->origin_y + (r + 0.5) * fg->resolution, &fz)) { + fg->mm[static_cast(r) * fg->width + c] = static_cast( + std::max(-32000.0, std::min(32000.0, std::round(fz * 1000.0)))); + } + } + } + return fg; +} +#endif } // namespace StatusResponse Runtime::OpenSource() { @@ -564,7 +593,11 @@ StatusResponse Runtime::Start() { vverif_.reset(new VisualVerifier); VSLAM_INFO("slam: camera cho dinh vi lai -- mo ta VPR " << vpr_ids_.size() << " anh ban do trong " << dv << " s; chot khi PnP >= 12 inlier TRUNG" - " LiDAR (0.5 m / 10 do)."); + " LiDAR (0.5 m / 10 do)" + << (cfg_->slope.enabled + ? "; tren doc: >= 2 anh trung nhau, khop do nghieng IMU, LiDAR " + "khong phan doi -> pose camera." + : ".")); } } } @@ -574,6 +607,19 @@ StatusResponse Runtime::Start() { { OccupancyGrid shown = g; VoxelGridPtr vptr; + // Ban do quet o che do doc: z node nam san trong DB. Giai do thi z + // TRUOC khi xuat, khong thi tang tren + mat doc ve het o z = 0 cho toi + // khi chot (slope_on_ chi bat o duoi doan nay). + const FloorModel* floor = nullptr; + if (cfg_->slope.enabled) { + ZGraphConfig zc; + zc.clamp_rad = cfg_->slope.clamp_deg * M_PI / 180.0; + zc.sigma_rel = cfg_->slope.sigma_rel; + slam_->SetUseHeights(true); + if (slam_->UpdateHeights(zc).ok() && !slam_->floor_model().empty()) { + floor = &slam_->floor_model(); + } + } if (voxel_enabled_) { VoxelExportOptions vo; vo.emit_size_m = cfg_->voxel.emit_size_m; @@ -589,8 +635,12 @@ StatusResponse Runtime::Start() { VoxelGrid vg; const StatusResponse vst = slam_->ExportVoxels(vo, &vg); if (vst.ok()) { + if (floor != nullptr) { + ClearLidarOnSeenRamps(&shown, slam_->floor_cells(), cfg_->voxel.emit_size_m, + *floor, cfg_->slope.clamp_deg * M_PI / 180.0, 1.0); + } MarkVoxelObstacles(vg, cfg_->voxel.obstacle_z_min, - cfg_->voxel.obstacle_z_max, &shown); + cfg_->voxel.obstacle_z_max, &shown, floor); vg.epoch = ++voxel_epoch_; prev_voxel_cells_ = vg.cells; vptr = std::make_shared(std::move(vg)); @@ -599,8 +649,11 @@ StatusResponse Runtime::Start() { << ") -- 3D se hien sau khi DA DINH VI, 2D van hien ngay."); } } + std::shared_ptr floor_ptr; + if (floor != nullptr) floor_ptr = BuildMapFloorGrid(*floor, shown); std::lock_guard lk(slam_mu_); slam_map_ = std::make_shared(std::move(shown)); + slam_map_floor_ = floor_ptr; slam_published_version_ = 1; slam_voxels_ = vptr; } @@ -1487,9 +1540,13 @@ void Runtime::SlamLoop() { // ban chua gop roi thay bang ban da gop CUNG version la web khong bao // gio thay ban da gop. if (st.ok()) { + // Di tren doc: do cao san de web uon mat phang ban do. + std::shared_ptr floor_ptr; + if (slope_on_) floor_ptr = BuildMapFloorGrid(slam_->floor_model(), grid); auto ptr = std::make_shared(std::move(grid)); std::lock_guard lk(slam_mu_); slam_map_ = ptr; + slam_map_floor_ = floor_ptr; slam_published_version_ = slam_map_version_; } } @@ -1523,8 +1580,100 @@ constexpr double kRelocSpeed = 0.12; // m/s constexpr int kRelocMaxCycles = 6; constexpr double kRelocMaxDrive = 12.0; // m constexpr double kRelocPhaseTimeout = 20.0; // s -- bi lop an toan chan thi thoi +// Tren doc: vong DUNG YEN -- khong xoay robot, khop scan tai cho (bo khop da +// thu moi huong bang phan mem). Sim 2026-10-05: xoay tai cho tren doc 15-30 do +// lam scan meo (6 vong deu MAU THUAN / khop sai cho); dung yen thi chon dung +// lan + huong. Doc that con truot banh khi xoay. Tu chay cung KHONG tu di tren +// doc: chua chot thi khop lai tai cho roi goi nguoi. +constexpr double kRelocStaticTiltDeg = 3.0; // nghieng hon nguong nay = tren doc +constexpr double kRelocStaticWindow = 3.0; // s gom scan tai cho moi vong +constexpr double kRelocTiltStableDeg = 0.3; // do nghieng coi la on dinh: doi duoi +constexpr double kRelocTiltStableSec = 1.0; // nguong nay trong chung nay giay +// Nguoi xoay robot qua goc nay trong vong dung yen -> doi thanh vong xoay thuong. +constexpr double kRelocStaticMaxTurn = 15.0 * M_PI / 180.0; +// Tu chay tren doc: khop tai cho kRelocStaticBeforeCreep lan chua chot thi BO +// THANG kRelocCreepStep (khong quay -- phia truoc khong thoang moi quay ve cho +// thoang; khong lui -- sau lung la vung mu LiDAR), tong toi da +// kRelocSlopeCreepMax. Hai goc nhin o hai cho khac nhau cung chi mot pose = +// luat chuoi sau khi di chuyen (Decide). Sim 2026-10-05: dung yen gan dinh doc +// 5 do, nguoi thang DUNG ca 6 vong nhung ty le 1.57-1.60 (bat --sim-gl) < +// chuan mot goc nhin 1.60 -> dung han goi nguoi. +constexpr int kRelocStaticBeforeCreep = 3; +constexpr double kRelocCreepStep = 0.5; // m +// Mu doc truc (dich 1 m van khop >= 95%): moi cho gan day nhin y het -> khop +// lai tai cho vo ich, bo NGAY va xa hon. Sim: giua lan doc bo 4 x 0.5 m van +// mu, dung han giua lan. +constexpr double kRelocCreepBlind = 1.5; // m +// = kRelocMaxDrive: lan doc dai 17 m, nhin XUONG doc thoai thi tia cam vao san +// duoi chan doc truoc khi toi tuong xa -> mu toi khi ra gan chan doc. +constexpr double kRelocSlopeCreepMax = kRelocMaxDrive; // m +constexpr double kRelocCreepMargin = 0.6; // m chua truoc vat can (lop an toan dung 0.45) } // namespace +double Runtime::RelocFrontClear(const LaserScan& scan) const { + constexpr double kHalf = 15.0 * M_PI / 180.0; // = 3 o 10 do cua RelocPlanDrive + double near = reloc_cfg_.max_range; + bool seen = false; + for (size_t i = 0; i < scan.ranges.size(); ++i) { + const float r = scan.ranges[i]; + if (std::isnan(r)) continue; // khong do duoc / bi bo + if (!std::isinf(r) && (r > scan.range_max || r <= scan.range_min)) continue; // bi cat + const double a = scan.angle_min + static_cast(i) * scan.angle_increment; + const double d = std::isinf(r) ? reloc_cfg_.max_range : static_cast(r); + Point pl; + pl.x = d * std::cos(a); + pl.y = d * std::sin(a); + const Point pb = TransformPoint(slam_laser_to_base_, pl); + if (std::fabs(std::atan2(pb.y, pb.x)) > kHalf) continue; + seen = true; + if (!std::isinf(r)) near = std::min(near, std::hypot(pb.x, pb.y)); + } + return seen ? near : 0.0; +} + +bool Runtime::RelocPoseAdmissible(const Pose2D& p, double tilt_r, double tilt_p) const { + // Robot phai DUNG duoc o do: o TRONG cua ban do. Gia thuyet dat robot trong tuong / + // ngoai vung da quet khong duoc canh tranh (sim: doi thu cua cho dung nam ngoai tuong + // nha, y = -0.04). + const LikelihoodField* lf = reloc_field_.get(); + const int c = static_cast(std::lround((p.x - lf->origin_x()) / lf->resolution())); + const int r = static_cast(std::lround((p.y - lf->origin_y()) / lf->resolution())); + if (!lf->Free(r, c)) return false; + double gx = 0.0, gy = 0.0; + if (!FloorGradientAt(slam_->floor_model(), p.x, p.y, reloc_cfg_.tilt_node_radius, &gx, &gy)) { + return true; // khong biet san o do -- khong loai + } + return TiltResidual(tilt_r, tilt_p, p.theta, gx, gy) <= + std::tan(reloc_cfg_.tilt_tol_deg * M_PI / 180.0); +} + +bool Runtime::RelocOnSlope(double* deg) const { + // Goc giua truc z than va trong luc: cos = cos(roll) * cos(pitch). + const double r = tilt_roll_.load(std::memory_order_relaxed); + const double p = tilt_pitch_.load(std::memory_order_relaxed); + const double t = std::acos(std::min(1.0, std::cos(r) * std::cos(p))); + if (deg != nullptr) *deg = t * 180.0 / M_PI; + return slope_on_ && t > kRelocStaticTiltDeg * M_PI / 180.0; +} + +RelocVerdict Runtime::RelocStaticDecide(const RelocMatch& m, const Pose2D& odom, double shift_ratio, + bool use_shift, bool* along_axis, std::string* why) { + *along_axis = false; + if (!m.ok) { + reloc_static_hist_.clear(); + *why = "khong khop duoc"; + return RelocVerdict::kFailed; + } + StaticRound r; + r.robot = Pose2DCompose(m.map_from_odom, odom); + r.map_from_odom = m.map_from_odom; + r.ratio = m.ratio(); + r.ratio_yaw = m.ratio_yaw(); + r.shift = shift_ratio; + return DecideStatic(&reloc_static_hist_, r, reloc_static_places_, reloc_cfg_, use_shift, + along_axis, why); +} + void Runtime::RelocCommand(double v, double w) { std::lock_guard lk(cmd_mu_); raw_cmd_.linear.x = v; @@ -1682,25 +1831,60 @@ void Runtime::RelocStep(const LaserScan& scan, const Pose2D& odom) { // Het quang duong, hoac lop an toan chan qua lau (vat can, sieu am) -> xoay. if (moved >= reloc_drive_len_ || t > kRelocPhaseTimeout) { reloc_total_drive_ += moved; + if (reloc_creeping_) { + reloc_slope_creep_ += moved; + reloc_creeping_ = false; + } if (!yielding) RelocCommand(0.0, 0.0); RelocStartSweep(); return; } if (!yielding) RelocCommand(kRelocSpeed, 0.0); - char buf[96]; - std::snprintf(buf, sizeof(buf), "TU DI %.1f/%.1f m%s", moved, reloc_drive_len_, + char buf[128]; + std::snprintf(buf, sizeof(buf), "%s %.1f/%.1f m%s", + reloc_creeping_ ? "BO THANG TREN DOC" : "TU DI", moved, reloc_drive_len_, yielding ? " -- NHUONG NGUOI" : ""); SetRelocStatus(buf, true); return; } - // --- GOM (tu chay: pha XOAY; tay: nguoi xoay) --- + // --- GOM (tu chay: pha XOAY; tay: nguoi xoay; tren doc: DUNG YEN) --- + double tilt_deg = 0.0; + // Che do doc: CHO do nghieng IMU hop le VA ON DINH roi moi quyet xoay hay dung + // yen. Ngay luc khoi dong roll/pitch con = 0 gia -> vong dau tuong san phang, + // xoay 300 do roi TU DI 1 m tren doc (sim 2026-10-05). valid() bat tu mau IMU + // DAU, khi bo loc bu con dang hoi tu: sim 2026-10-06 vong dau thay 3.2 do tren + // doc 10 do -> anh camera dau bi xet theo luat san phang. On dinh = doi duoi + // kRelocTiltStableDeg trong kRelocTiltStableSec. Qua 8 s thi chay nhu cu. + if (!reloc_have_prev_ && slope_on_ && + std::chrono::duration(now - reloc_epoch_).count() < 8.0) { + double tdeg = 0.0; + RelocOnSlope(&tdeg); + if (!tilt_valid_.load(std::memory_order_relaxed) || + std::fabs(tdeg - reloc_tilt_ref_deg_) > kRelocTiltStableDeg) { + reloc_tilt_ref_deg_ = tdeg; + reloc_tilt_ref_t_ = now; + } + if (std::chrono::duration(now - reloc_tilt_ref_t_).count() < kRelocTiltStableSec) { + if (running && !yielding) RelocCommand(0.0, 0.0); + char tb[96]; + std::snprintf(tb, sizeof(tb), "CHO IMU on dinh (nghieng %.1f do) truoc khi dinh vi lai", tdeg); + SetRelocStatus(tb, true); + return; + } + } if (!reloc_have_prev_) { reloc_t0_ = now; reloc_swept_ = 0.0; reloc_cam_have_last_ = false; // chup ngay anh dau cua vong gom reloc_cam_shots_ = 0; reloc_cam_best_inl_ = 0; + reloc_static_round_ = RelocOnSlope(&tilt_deg); + if (reloc_static_round_) { + VSLAM_INFO("slam: reloc vong " << reloc_cycle_ + 1 << " DUNG YEN tren doc (nghieng " + << tilt_deg << " do) -- khong xoay, khop scan tai cho sau " + << kRelocStaticWindow << " s."); + } } else { // Goc da quet do bang odom: xoay tai cho thi odometry rat chinh xac (ban // ROS do: 0.1 do troi tren 1086 do xoay). @@ -1710,8 +1894,13 @@ void Runtime::RelocStep(const LaserScan& scan, const Pose2D& odom) { reloc_have_prev_ = true; const std::vector p = ScanToFrame(scan, odom); reloc_pts_.insert(reloc_pts_.end(), p.begin(), p.end()); - // Camera: chot SOM ngay giua vong xoay neu anh + LiDAR cung chi mot pose. - if (vpr_ && RelocCamera(scan, odom, now)) { + // Camera: chot SOM ngay giua vong xoay neu anh + LiDAR cung chi mot pose. Vong + // DUNG YEN: chup trong giay CUOI cua cua so -- LiDAR da gom du diem de kiem anh, + // do nghieng da lang sau khi robot vua dung (bo xong / vua khoi dong). + const bool cam_turn = + !reloc_static_round_ || + std::chrono::duration(now - reloc_t0_).count() >= kRelocStaticWindow - 1.0; + if (vpr_ && cam_turn && RelocCamera(scan, odom, now)) { if (running && !yielding) RelocCommand(0.0, 0.0); return; } @@ -1723,7 +1912,36 @@ void Runtime::RelocStep(const LaserScan& scan, const Pose2D& odom) { constexpr double kTimeout = 30.0; const double elapsed = std::chrono::duration(now - reloc_t0_).count(); const int swept_deg = static_cast(reloc_swept_ * 180.0 / M_PI); - if (reloc_swept_ < kSweep && elapsed < kTimeout) { + if (reloc_static_round_ && reloc_swept_ > kRelocStaticMaxTurn) { + // Nguoi dang xoay robot -> de nguoi xoay het, khop nhu vong xoay thuong. + reloc_static_round_ = false; + VSLAM_INFO("slam: reloc -- robot dang duoc xoay, vong nay khop sau khi xoay du."); + } else if (!reloc_static_round_ && reloc_swept_ < kRelocStaticMaxTurn && RelocOnSlope(&tilt_deg)) { + // Moi xoay vai do ma da thay dang tren doc (do nghieng vua on dinh) -> dung. + reloc_static_round_ = true; + reloc_t0_ = now; + reloc_cam_have_last_ = false; // anh luc con xoay khong tinh -- chup lai cuoi cua so + VSLAM_INFO("slam: reloc -- phat hien dang tren doc (nghieng " << tilt_deg + << " do) khi moi xoay " << reloc_swept_ * 180.0 / M_PI << " do -> DUNG YEN."); + } + if (reloc_static_round_ && elapsed < kRelocStaticWindow) { + if (running && !yielding) RelocCommand(0.0, 0.0); + RelocOnSlope(&tilt_deg); + char sb[160]; + if (running) { + std::snprintf(sb, sizeof(sb), + "DUNG YEN TREN DOC (nghieng %.1f do) -- khop tai cho, lan %d/%d, da bo %.1f/%.0f m", + tilt_deg, reloc_static_here_ + 1, kRelocStaticBeforeCreep, reloc_slope_creep_, + kRelocSlopeCreepMax); + } else { + std::snprintf(sb, sizeof(sb), "%sDUNG YEN TREN DOC (nghieng %.1f do) -- khop tai cho, lan %d", + reloc_exec_ == RelocExec::kHalted ? "DUNG HAN tu chay -- " : "", tilt_deg, + reloc_cycle_ + 1); + } + SetRelocStatus(std::string(sb) + (yielding ? " -- NHUONG NGUOI" : "") + cam_note(), true); + return; + } + if (!reloc_static_round_ && reloc_swept_ < kSweep && elapsed < kTimeout) { if (running) { if (!yielding) RelocCommand(0.0, kRelocTurnRate); SetRelocStatus("TU XOAY " + std::to_string(swept_deg) + "/300 do (vong " + @@ -1745,17 +1963,64 @@ void Runtime::RelocStep(const LaserScan& scan, const Pose2D& odom) { // --- Khop toan cuc --- const auto tm = std::chrono::steady_clock::now(); - const RelocMatch m = GlobalMatch(*reloc_field_, reloc_pts_, reloc_cfg_); + // Che do doc: do nghieng IMU (theo trong luc, khong can ban do) loai gia + // thuyet ma mat san ban do o do khong the gay ra -- lat 180 do tren doc, doc + // o cho phang, sai lan. Chi phan xu giua cac gia thuyet LiDAR ngang diem + // (xem GlobalMatch). Robot vua dung xoay nen do nghieng la luc dung yen. + RelocAdmit admit; + const double tilt_r = tilt_roll_.load(std::memory_order_relaxed); + const double tilt_p = tilt_pitch_.load(std::memory_order_relaxed); + if (slope_on_ && !slam_->floor_model().empty()) { + admit = [this, odom, tilt_r, tilt_p](const Pose2D& T) { + return RelocPoseAdmissible(Pose2DCompose(T, odom), tilt_r, tilt_p); + }; + } + const RelocMatch m = GlobalMatch(*reloc_field_, reloc_pts_, reloc_cfg_, admit); const double ms = std::chrono::duration( std::chrono::steady_clock::now() - tm).count(); reloc_tracker_->Add(m, odom, std::chrono::duration(now - reloc_epoch_).count()); const int streak = m.ok ? reloc_tracker_->Streak(m.map_from_odom) : 0; - const RelocVerdict v = Decide(m, streak, reloc_cfg_); + RelocVerdict v = Decide(m, streak, reloc_cfg_); + // Chot NHO do nghieng con phai qua kiem suy bien doc truc: bo loc loai het + // doi thu XA, nhung o hanh lang / doc deu vi tri doc truc van mu (doi thu + // nam trong reject_radius, cong ty le khong thay) -- xem ShiftScoreRatio. + double shift_ratio = -1.0; + bool along_axis = false; + std::string static_why; + if (admit && m.ok) { + shift_ratio = ShiftScoreRatio(*reloc_field_, reloc_pts_, m.map_from_odom, reloc_cfg_.tilt_shift_m); + } + if (reloc_static_round_) { + // Dung yen: ty le NHO NHAT qua moi vong cung cho; hoac hai cho (truoc / sau + // khi bo) cung pose, moi cho deu qua -- xem DecideStatic. KHONG dung streak + // cua tracker: no da cho chot sai 1.5-2 m o chan doc (ty le nhay 1.32). + v = RelocStaticDecide(m, odom, shift_ratio, static_cast(admit), &along_axis, &static_why); + } else { + reloc_static_hist_.clear(); + reloc_static_places_.clear(); + if (admit && m.ok && v == RelocVerdict::kAccept && m.tilt_used && + shift_ratio >= reloc_cfg_.tilt_max_shift_ratio) { + v = RelocVerdict::kAmbiguous; + along_axis = true; + } + } ++reloc_cycle_; - VSLAM_INFO("slam: reloc vong " << reloc_cycle_ << " -- quet " << swept_deg << " do / " - << elapsed << " s, " << m.points << " diem, ty le " << m.ratio() << " / huong " - << m.ratio_yaw() << ", streak " << streak << " -> " << RelocVerdictName(v) - << " (" << ms << " ms)"); + std::string tilt_note; + if (admit) { + char tb[160]; + std::snprintf(tb, sizeof(tb), "; nghieng IMU roll %.1f / pitch %.1f do: %s; dich %.1f m giu %.0f%% diem", + tilt_r * 180.0 / M_PI, tilt_p * 180.0 / M_PI, + m.tilt_used ? (std::to_string(m.tilt_rejected) + " ung vien mau thuan bi loai").c_str() + : m.tilt_conflict ? "MAU THUAN voi LiDAR -- bo qua, giu ket qua LiDAR" + : "khong loai ung vien nao", + reloc_cfg_.tilt_shift_m, 100.0 * shift_ratio); + tilt_note = tb; + } + VSLAM_INFO("slam: reloc vong " << reloc_cycle_ << (reloc_static_round_ ? " (DUNG YEN)" : "") + << " -- quet " << swept_deg << " do / " << elapsed << " s, " << m.points + << " diem, ty le " << m.ratio() << " / huong " << m.ratio_yaw() << ", streak " + << streak << " -> " << RelocVerdictName(v) << " (" << ms << " ms)" << tilt_note + << (static_why.empty() ? "" : "; " + static_why)); // Vong gom moi, du ket qua the nao. reloc_pts_.clear(); @@ -1766,20 +2031,109 @@ void Runtime::RelocStep(const LaserScan& scan, const Pose2D& odom) { // Nhap nhang la ket qua DUNG, khong phai loi: tra loi sai tu tin te hon // nhieu so voi im lang. Noi ro phai lam gi. const char* hint = - v == RelocVerdict::kNeedCycles ? "DAI BIEN -- di chuyen >= 0.2 m roi xoay tiep" + along_axis ? "NHAP NHANG DOC TRUC (hanh lang / doc deu) -- di chuyen toi cho co dac diem" + : reloc_static_round_ + ? (v == RelocVerdict::kNeedCycles ? "DUNG YEN TREN DOC -- chua du tin cay" + : "DUNG YEN TREN DOC -- nhap nhang") + : v == RelocVerdict::kNeedCycles ? "DAI BIEN -- di chuyen >= 0.2 m roi xoay tiep" : v == RelocVerdict::kAmbiguousYaw ? "NHAP NHANG HUONG -- di chuyen vai met roi xoay tiep" : v == RelocVerdict::kAmbiguous ? "NHAP NHANG VI TRI -- di chuyen vai met roi xoay tiep" : "KHONG KHOP -- xoay tiep"; - char buf[160]; - std::snprintf(buf, sizeof(buf), "%s (ty le %.2f / huong %.2f)", hint, m.ratio(), m.ratio_yaw()); - VSLAM_WARN("slam: reloc chua chot -- " << buf); + char buf[220]; + std::snprintf(buf, sizeof(buf), "%s (ty le %.2f / huong %.2f%s%s)", hint, m.ratio(), + m.ratio_yaw(), static_why.empty() ? "" : "; ", static_why.c_str()); + // Nhap nhang voi CHO NAO: pose robot cua nguoi thang va hai doi thu. + char who[200] = ""; + if (m.ok) { + const Pose2D w = Pose2DCompose(m.map_from_odom, odom); + const Pose2D p2 = Pose2DCompose(m.s2_from_odom, odom); + const Pose2D py = Pose2DCompose(m.s2_yaw_from_odom, odom); + std::snprintf(who, sizeof(who), + "; thang (%.2f, %.2f, %.0f do), doi thu vi tri (%.2f, %.2f, %.0f do), doi thu " + "huong (%.2f, %.2f, %.0f do)", + w.x, w.y, w.theta * 180.0 / M_PI, p2.x, p2.y, p2.theta * 180.0 / M_PI, py.x, + py.y, py.theta * 180.0 / M_PI); + } + VSLAM_WARN("slam: reloc chua chot -- " << buf << who); if (!running) { SetRelocStatus(buf, true); return; } // Tu chay: sang cho khac roi xoay tiep -- doi xung cuc bo thuong vo khi // doi goc nhin, va streak chi tang khi DA DI >= 0.2 m. - ++reloc_exec_cycles_; + // ⚠️ Vong tren doc KHONG tinh vao tran kRelocMaxCycles (chung co tran rieng + // = quang bo): sim, bo xuong toi sanh roi vong xoay dau o sanh (ty le 1.43, + // can them mot vong) bi dung han ngay vi bo dem da len 20 tu cac vong doc. + if (!reloc_static_round_) ++reloc_exec_cycles_; + if (reloc_static_round_) { + // Tren doc: khop lai TAI CHO vai lan; chua chot thi BO 0.5 m roi khop + // tiep o cho moi (xem kRelocStaticBeforeCreep). Het tran bo / khong co + // huong nao thoang thi goi nguoi. + ++reloc_static_here_; + // Mu doc truc -> bo ngay, xa hon; chi thieu tin cay -> khop lai tai cho vai lan. + // ⚠️ Xet THANG chi so dich cua vong nay, khong qua `along_axis`: ty le + // < min_ratio thi DecideStatic tra truoc khi kiem doc truc (sim: giua lan + // dich 1 m giu 100% ma van bo tung 0.5 m sau 3 lan). + const bool blind = admit && shift_ratio >= reloc_cfg_.tilt_max_shift_ratio; + if (!blind && reloc_static_here_ < kRelocStaticBeforeCreep) { + RelocStartSweep(); + VSLAM_INFO("reloc_exec: vong " << reloc_cycle_ << " chua chot -- tren doc: khop lai tai cho (" + << reloc_static_here_ << "/" << kRelocStaticBeforeCreep << ")."); + SetRelocStatus(std::string(buf) + " -- tren doc: khop lai tai cho", true); + return; + } + char hb[160]; + const double budget = std::min(kRelocSlopeCreepMax - reloc_slope_creep_, + kRelocMaxDrive - reloc_total_drive_); + double step = std::min(blind ? kRelocCreepBlind : kRelocCreepStep, budget); + if (step < 0.3) { + std::snprintf(hb, sizeof(hb), "tren doc: da bo %.1f m, %d lan khop tai cho chua chot", + reloc_slope_creep_, reloc_static_here_); + RelocHalt(hb); + return; + } + reloc_static_here_ = 0; + reloc_creeping_ = true; + // Chot CHO nay truoc khi bo: chot "hai cho" so cho moi voi no. + if (!reloc_static_hist_.empty()) { + reloc_static_places_.push_back(SummarizePlace(reloc_static_hist_)); + while (reloc_static_places_.size() > 4) reloc_static_places_.erase(reloc_static_places_.begin()); + reloc_static_hist_.clear(); + } + const double clear = RelocFrontClear(scan); + if (clear - kRelocCreepMargin >= std::min(step, kRelocCreepStep)) { + // Thang toi, KHONG quay: quay tai cho tren doc lam truot banh. + step = std::min(step, clear - kRelocCreepMargin); + reloc_exec_ = RelocExec::kDrive; + reloc_drive_start_ = odom; + reloc_drive_len_ = step; + reloc_phase_t0_ = now; + VSLAM_INFO("reloc_exec: tren doc chua chot" << (blind ? " (MU doc truc)" : "") << " -- BO THANG " + << step << " m (khong quay; da bo " << reloc_slope_creep_ << "/" + << kRelocSlopeCreepMax << " m) roi khop tiep."); + char cb[64]; + std::snprintf(cb, sizeof(cb), " -- BO THANG %.1f m tren doc", step); + SetRelocStatus(std::string(buf) + cb, true); + return; + } + // Phia truoc khong thoang (vd nhin xuong doc: tia cham san da bi bo) -> + // quay ve huong thoang nhat roi moi bo. + if (!RelocPlanDrive(scan, odom)) { + reloc_creeping_ = false; + RelocHalt("tren doc: phia truoc chi thoang " + std::to_string(clear) + + " m va khong co huong nao thoang >= 1 m"); + return; + } + reloc_drive_len_ = std::min(reloc_drive_len_, step); + reloc_exec_ = RelocExec::kTurn; + reloc_phase_t0_ = now; + VSLAM_INFO("reloc_exec: tren doc chua chot, phia truoc khong thoang (" << clear + << " m) -- quay ve huong " << reloc_turn_target_ * 180.0 / M_PI << " do (odom) roi bo " + << reloc_drive_len_ << " m."); + SetRelocStatus(std::string(buf) + " -- QUAY roi BO tren doc", true); + return; + } + reloc_static_here_ = 0; if (reloc_exec_cycles_ >= kRelocMaxCycles || reloc_total_drive_ >= kRelocMaxDrive) { RelocHalt("het tran " + std::to_string(kRelocMaxCycles) + " vong / " + std::to_string(static_cast(kRelocMaxDrive)) + " m"); @@ -1800,8 +2154,15 @@ void Runtime::RelocStep(const LaserScan& scan, const Pose2D& odom) { // --- CHOT -> dung yen roi tinh chinh (RelocSettle) --- if (running && !yielding) RelocCommand(0.0, 0.0); - char src[48]; - std::snprintf(src, sizeof(src), "LiDAR, ty le %.2f", m.ratio()); + // Lan dinh vi lai SAU (vd canh lac) khong duoc dung lai cac vong dung yen cu. + reloc_static_hist_.clear(); + reloc_static_places_.clear(); + char src[96]; + std::snprintf(src, sizeof(src), + reloc_static_round_ ? "LiDAR + do nghieng IMU, DUNG YEN tren doc, ty le %.2f" + : m.tilt_used ? "LiDAR + do nghieng IMU, ty le %.2f" + : "LiDAR, ty le %.2f", + m.ratio()); RelocBeginSettle(m.map_from_odom, m.ratio(), odom, now, src); } @@ -1841,6 +2202,15 @@ constexpr double kCamAgreeM = 0.5; constexpr double kCamAgreeRad = 10.0 * M_PI / 180.0; constexpr double kCamLidarRadius = 2.5; // LiDAR cuc bo quanh node anh VPR constexpr double kCamLidarYaw = 45.0 * M_PI / 180.0; +// --- Tren DOC (RelocOnSlope): luat rieng --- +// Sim 2026-10-06 (5 cho giua lan doc, robot dung yen): 3/5 cho ca 5 ung vien VPR+PnP +// DUNG toi 1-5 cm, 2/5 cho sai het (nham lan khac / lat 180 do -- do nghieng IMU loai +// duoc). Luat phang (LiDAR cuc bo quanh node phai TRUNG PnP) chan ca ung vien dung +// (LiDAR mu doc lan) va mot lan con chot pose LiDAR roi tinh chinh keo lech 0.75 m. +// Tren doc: LiDAR chi can KHONG PHAN DOI; pose chot la TRUNG BINH cac pose CAMERA, khong +// tinh chinh LiDAR (do: tinh chinh keo pose 8-13 cm doc lan, diem chi nhich 0.996 -> 0.999). +constexpr double kCamSlopeLidarKeep = 0.9; // diem LiDAR tai pose camera / tot nhat quanh do +constexpr size_t kCamSlopeMinAgree = 2; // ung vien tu node KHAC nhau phai trung nhau cv::Matx44d MatxFromTransform(const Transform& t) { const Vector3 ex = RotateVector(t.rotation, Vector3{1.0, 0.0, 0.0}); @@ -1919,7 +2289,21 @@ bool Runtime::RelocCamera(const LaserScan& scan, const Pose2D& odom, TiltLift(roll, pitch, cfg_->robot.geometry().wheel_radius), slam_cam_to_link_)); std::vector acc; // T_map_odom (pose LiDAR) cua ung vien DUOC CHOT + std::vector cams; // tren doc: pose robot theo camera cua ung vien duoc chot std::string why; + // Tren doc: luat rieng (xem kCamSlopeLidarKeep). Phang: luat da kiem, giu nguyen. + const bool slope_cam = !slam_->floor_model().empty() && RelocOnSlope(); + const double tilt_r = tilt_roll_.load(std::memory_order_relaxed); + const double tilt_p = tilt_pitch_.load(std::memory_order_relaxed); + auto lidar_at = [this](const Pose2D& T) { + const double c = std::cos(T.theta), s = std::sin(T.theta); + std::vector m(reloc_pts_.size()); + for (size_t i = 0; i < reloc_pts_.size(); ++i) { + m[i].x = T.x + c * reloc_pts_[i].x - s * reloc_pts_[i].y; + m[i].y = T.y + s * reloc_pts_[i].x + c * reloc_pts_[i].y; + } + return reloc_field_->MeanScore(m); + }; for (size_t k = 0; k < topk; ++k) { const int id = vpr_ids_[sc[k].second]; auto it = vpr_shots_.find(id); @@ -1936,13 +2320,64 @@ bool Runtime::RelocCamera(const LaserScan& scan, const Pose2D& odom, } const PnpResult r = vverif_->Solve(qf, it->second.f, it->second.T_map_base); reloc_cam_best_inl_ = std::max(reloc_cam_best_inl_, r.inliers); - if (r.inliers < kCamMinInliers || std::fabs(r.dz) > kCamMaxDz || r.tilt_deg > kCamMaxTiltDeg) { + // `dz` = do cao robot SO VOI node anh (ca hai da can trong luc). San phang: ~0. Tren + // doc: = chenh san giua hai cho theo mo hinh san -- hai diem cach 2 m tren doc 15 do + // chenh 0.5 m, dung nguong phang 0.3 m la loai oan nghiem DUNG. + double dz_expect = 0.0; + if (slope_on_ && !slam_->floor_model().empty() && r.inliers > 0) { + double zq = 0.0, zn = 0.0; + const cv::Matx44d& Tm = it->second.T_map_base; + if (slam_->floor_model().FloorAt(r.x, r.y, &zq) && + slam_->floor_model().FloorAt(Tm(0, 3), Tm(1, 3), &zn)) { + dz_expect = zq - zn; + } + } + if (r.inliers > 0) { + VSLAM_INFO("slam: reloc camera -- node " << id << " giong " << sc[k].first << ", PnP " + << r.inliers << "/" << r.matches << " inlier, pose (" << r.x << ", " << r.y << ", " + << r.yaw * 180.0 / M_PI << " do), dz " << r.dz << " (ky vong " << dz_expect + << "), nghieng " << r.tilt_deg << " do"); + } + if (r.inliers < kCamMinInliers || std::fabs(r.dz - dz_expect) > kCamMaxDz || + r.tilt_deg > kCamMaxTiltDeg) { continue; } Pose2D cam; cam.x = r.x; cam.y = r.y; cam.theta = r.yaw; + if (slope_cam) { + // 1. Do nghieng IMU khop do doc ban do tai pose camera + dung tren o trong: loai + // nham lan (doc goc khac) va lat 180 do (doc nguoc dau). + if (!RelocPoseAdmissible(cam, tilt_r, tilt_p)) { + VSLAM_INFO("slam: reloc camera -- node " << id << " loai: do nghieng / o trong khong khop"); + continue; + } + // 2. LiDAR KHONG PHAN DOI: diem tai pose camera >= kCamSlopeLidarKeep x tot nhat + // quanh do. Hanh lang/doc deu: LiDAR dung moi cho doc truc -> khong phan doi. + const Pose2D Tcam = Pose2DCompose(cam, Pose2DInverse(odom)); + Point cc; + cc.x = cam.x; + cc.y = cam.y; + const RelocHypothesis hb = LocalMatch(*reloc_field_, reloc_pts_, odom, cc, kCamLidarRadius, + reloc_cfg_); + const double s_cam = lidar_at(Tcam); + const double s_best = hb.score > 0.0 ? lidar_at(hb.map_from_odom) : -1.0; + if (s_cam <= 0.0 || (s_best > 0.0 && s_cam < kCamSlopeLidarKeep * s_best)) { + VSLAM_INFO("slam: reloc camera -- node " << id << " loai: LiDAR phan doi (diem " << s_cam + << " / tot nhat " << s_best << ")"); + continue; + } + acc.push_back(Tcam); // pose CAMERA -- LiDAR mu doc lan, khong lay pose LiDAR + cams.push_back(cam); + if (why.empty()) { + char b[120]; + std::snprintf(b, sizeof(b), "node %d, giong %.2f, PnP %d inlier, LiDAR %.0f%%", id, + sc[k].first, r.inliers, s_best > 0.0 ? 100.0 * s_cam / s_best : 100.0); + why = b; + } + continue; + } // LiDAR cuc bo quanh node anh VPR: gioi han huong truoc, tu do huong sau (nhu da do). const cv::Matx44d& Tn = it->second.T_map_base; Point center; @@ -1966,6 +2401,10 @@ bool Runtime::RelocCamera(const LaserScan& scan, const Pose2D& odom, } } } + if (reloc_cam_best_inl_ == 0 && topk > 0) { + VSLAM_INFO("slam: reloc camera -- anh " << reloc_cam_shots_ << ": top-" << topk << " node giong " + << sc[0].first << ".." << sc[topk - 1].first << ", khong PnP nao ra inlier."); + } if (acc.empty()) return false; for (const Pose2D& T : acc) { if (!CamAgree(Pose2DCompose(T, odom), Pose2DCompose(acc[0], odom))) { @@ -1974,11 +2413,37 @@ bool Runtime::RelocCamera(const LaserScan& scan, const Pose2D& odom, return false; } } + if (slope_cam && acc.size() < kCamSlopeMinAgree) { + VSLAM_INFO("slam: reloc camera -- tren doc moi " << acc.size() << " ung vien dat, can " + << kCamSlopeMinAgree << " trung nhau -- chua chot."); + return false; + } // Chot: vong gom nay coi nhu xong. ++reloc_cycle_; reloc_pts_.clear(); reloc_have_prev_ = false; reloc_swept_ = 0.0; + if (slope_cam) { + // Moi ung vien la PnP voi mot anh ban do KHAC -> lay trung binh. Anh va scan cung luc, + // robot dung yen: dat pose ngay, khong qua buoc tinh chinh LiDAR. + const double n = static_cast(cams.size()); + Pose2D mean; + double dth = 0.0; + for (const Pose2D& c : cams) { + mean.x += c.x / n; + mean.y += c.y / n; + dth += AngleDiff(c.theta, cams[0].theta) / n; + } + mean.theta = NormalizeAngle(cams[0].theta + dth); + const Pose2D T = Pose2DCompose(mean, Pose2DInverse(odom)); + RelocBeginSettle(T, 0.0, odom, now, + "camera tren doc (" + std::to_string(cams.size()) + " ung vien trung; " + why + ")"); + reloc_static_hist_.clear(); + reloc_static_places_.clear(); + RelocFinish(T, odom, scan, "trung binh " + std::to_string(cams.size()) + + " pose camera, khong tinh chinh LiDAR -- mu doc lan"); + return true; + } RelocBeginSettle(acc[0], 0.0, odom, now, "camera+LiDAR (" + why + ")"); return true; } @@ -2145,6 +2610,11 @@ void Runtime::RelocWatch(const LaserScan& scan, const Pose2D& pose_map) { reloc_tracker_->Clear(); reloc_ref_score_ = -1.0; reloc_lost_pending_ = false; + reloc_static_hist_.clear(); + reloc_static_places_.clear(); + reloc_static_here_ = 0; + reloc_slope_creep_ = 0.0; + reloc_creeping_ = false; if (opts_.slam_reloc_auto) { // Lan dinh vi MOI: dat lai tran cung. reloc_exec_cycles_ = 0; @@ -2355,7 +2825,10 @@ void Runtime::WebLoop() { } snap.slam.voxels_source = voxels_source; #endif - if (slam_map_) snap.map = slam_map_; + if (slam_map_) { + snap.map = slam_map_; + snap.map_floor = slam_map_floor_; + } } else { snap.pose_map = ekf_pose; snap.slam.mode = !snap.slam.reloc.empty() ? "dinh vi lai" @@ -2365,6 +2838,7 @@ void Runtime::WebLoop() { // Dang dinh vi lai: ban do DB dung san luc Init. if (slam_map_) { snap.map = slam_map_; + snap.map_floor = slam_map_floor_; snap.slam.map_version = static_cast(slam_published_version_); } snap.voxels = slam_voxels_; diff --git a/app/src/runtime.h b/app/src/runtime.h index 8090a34..0472780 100644 --- a/app/src/runtime.h +++ b/app/src/runtime.h @@ -179,6 +179,19 @@ class Runtime { bool RelocPlanDrive(const LaserScan& scan, const Pose2D& odom); void RelocStartSweep(); void RelocHalt(const std::string& why); + // Dang dung tren doc (che do doc bat, nghieng than so voi trong luc qua + // nguong) -> vong dinh vi lai DUNG YEN, khong xoay robot. `deg`: goc nghieng. + bool RelocOnSlope(double* deg = nullptr) const; + // Khoang thoang PHIA TRUOC (+-15 do, frame base) theo scan; 0 = khong co tia + // nao trong quat do (khong biet -> khong di). + double RelocFrontClear(const LaserScan& scan) const; + // Che do doc: pose robot `p` (map) co hop khong -- dung tren o TRONG cua ban do, va + // do doc ban do tai do gay ra dung do nghieng IMU (roll/pitch) dang do. + bool RelocPoseAdmissible(const Pose2D& p, double tilt_r, double tilt_p) const; + // Quyet dinh cho vong DUNG YEN: trung vi `static_rounds` vong lien tiep cung + // nguoi thang thay cho mot vong. `*along_axis` = bi chan vi mu doc truc. + RelocVerdict RelocStaticDecide(const RelocMatch& m, const Pose2D& odom, double shift_ratio, + bool use_shift, bool* along_axis, std::string* why); // Sau khi CHOT: cho robot DUNG YEN, gom scan luc dung yen (khong nhoe do // quay), khop cuc bo quanh pose vua chot roi moi dat pose ban dau. void RelocSettle(const LaserScan& scan, const Pose2D& odom, @@ -350,6 +363,8 @@ class Runtime { size_t last_map_occ_ = 0; size_t last_map_free_ = 0; OccupancyGridPtr slam_map_; + // Do cao san cua ban do (che do doc), cung phien ban voi slam_map_. + std::shared_ptr slam_map_floor_; double slam_process_ms_ = 0.0; int slam_loops_ = 0; // Phat hien KE CAN -- co che cat sai so cong don that su cua SLAM scan-only. @@ -380,6 +395,21 @@ class Runtime { double reloc_swept_ = 0.0; // rad da xoay trong vong gom nay Pose2D reloc_prev_odom_; bool reloc_have_prev_ = false; + // Vong gom nay DUNG YEN tren doc (chot luc dau vong, xem RelocOnSlope): khong + // xoay, gom scan tai cho vai giay roi khop -- bo khop da thu moi huong. + bool reloc_static_round_ = false; + // Do nghieng (do) va luc no doi qua nguong lan cuoi -- cho on dinh truoc vong dau. + double reloc_tilt_ref_deg_ = -1.0; + std::chrono::steady_clock::time_point reloc_tilt_ref_t_; + // Ket qua cac vong DUNG YEN lien tiep cung nguoi thang (xem DecideStatic), + // va tom tat cac CHO dung truoc (moi lan bo tren doc chot mot cho). + std::vector reloc_static_hist_; + std::vector reloc_static_places_; + // Tu chay tren doc: so lan khop tai cho o CHO hien tai, quang da BO tren doc + // (tong, co tran), va pha DI hien tai co phai la mot lan BO khong. + int reloc_static_here_ = 0; + double reloc_slope_creep_ = 0.0; + bool reloc_creeping_ = false; std::chrono::steady_clock::time_point reloc_t0_; // dau vong gom std::chrono::steady_clock::time_point reloc_epoch_; // moc thoi gian cho tracker int reloc_cycle_ = 0; @@ -497,6 +527,9 @@ class Runtime { std::atomic tilt_roll_{0.0}; std::atomic tilt_pitch_{0.0}; std::atomic tilt_accel_ok_{false}; + // GravityAlign da khoi tao (co mau IMU) -- truoc do roll/pitch = 0 gia. Dinh + // vi lai tren doc CHO co nay roi moi quyet xoay hay dung yen. + std::atomic tilt_valid_{false}; // ---- Di tren doc (slam.yaml `slope:`) ---- // slope_on_ doc-only sau Start(). Tat thi KHONG doi tuong nao duoi day diff --git a/app/src/wiring.cc b/app/src/wiring.cc index 728d64c..fb3f88d 100644 --- a/app/src/wiring.cc +++ b/app/src/wiring.cc @@ -83,6 +83,7 @@ StatusResponse Runtime::Wire() { tilt_pitch_.store(perception_->gravity().pitch(), std::memory_order_relaxed); tilt_accel_ok_.store(perception_->gravity().accel_ok(), std::memory_order_relaxed); + tilt_valid_.store(perception_->gravity().valid(), std::memory_order_relaxed); std::lock_guard lk(odom_mu_); wheel_odom_->FeedGyroZ(m->header.stamp, m->angular_velocity.z); diff --git a/libs/vslam_slam/CMakeLists.txt b/libs/vslam_slam/CMakeLists.txt index 7b9e43b..4056695 100644 --- a/libs/vslam_slam/CMakeLists.txt +++ b/libs/vslam_slam/CMakeLists.txt @@ -63,7 +63,22 @@ if(VSLAM_WITH_TENSORRT) if(NOT DEFINED CUDAToolkit_ROOT AND EXISTS /usr/local/cuda) set(CUDAToolkit_ROOT /usr/local/cuda) endif() - find_package(CUDAToolkit REQUIRED) + # FindCUDAToolkit chi co tu CMake 3.17 (JetPack 6: 3.22). May dev Ubuntu 20.04 co CMake + # 3.16 nhung van co TensorRT + CUDA (chay VPR trong mo phong) -> tim tay cudart. + if(CMAKE_VERSION VERSION_LESS 3.17) + find_path(VSLAM_CUDA_INCLUDE_DIR cuda_runtime_api.h HINTS ${CUDAToolkit_ROOT}/include) + find_library(VSLAM_CUDART cudart HINTS ${CUDAToolkit_ROOT}/lib64) + if(NOT VSLAM_CUDA_INCLUDE_DIR OR NOT VSLAM_CUDART) + message(FATAL_ERROR "VSLAM_WITH_TENSORRT=ON nhung khong thay CUDA runtime trong " + "${CUDAToolkit_ROOT}") + endif() + set(_vslam_cudart ${VSLAM_CUDART}) + set(_vslam_cuda_inc ${VSLAM_CUDA_INCLUDE_DIR}) + else() + find_package(CUDAToolkit REQUIRED) + set(_vslam_cudart CUDA::cudart) + set(_vslam_cuda_inc "") + endif() find_path(TENSORRT_INCLUDE_DIR NvInfer.h PATH_SUFFIXES aarch64-linux-gnu x86_64-linux-gnu) find_library(TENSORRT_NVINFER nvinfer) if(NOT TENSORRT_INCLUDE_DIR OR NOT TENSORRT_NVINFER) @@ -71,7 +86,7 @@ if(VSLAM_WITH_TENSORRT) "(JetPack: goi libnvinfer-dev)") endif() target_sources(vslam_slam PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/vpr_tensorrt.cc) - target_include_directories(vslam_slam SYSTEM PRIVATE ${TENSORRT_INCLUDE_DIR}) - target_link_libraries(vslam_slam PRIVATE ${TENSORRT_NVINFER} CUDA::cudart) + target_include_directories(vslam_slam SYSTEM PRIVATE ${TENSORRT_INCLUDE_DIR} ${_vslam_cuda_inc}) + target_link_libraries(vslam_slam PRIVATE ${TENSORRT_NVINFER} ${_vslam_cudart}) target_compile_definitions(vslam_slam PRIVATE VSLAM_HAVE_TENSORRT=1) endif() diff --git a/libs/vslam_slam/include/vslam/global_localizer.h b/libs/vslam_slam/include/vslam/global_localizer.h index ebce461..cf4a58c 100644 --- a/libs/vslam_slam/include/vslam/global_localizer.h +++ b/libs/vslam_slam/include/vslam/global_localizer.h @@ -32,6 +32,7 @@ #include #include #include +#include #include #include @@ -81,6 +82,37 @@ struct GlobalLocalizerConfig { // --- Canh "da lac" --- double lost_score_ratio = 0.55; // diem tut duoi ty le nay so voi luc khop double lost_hold = 3.0; // s, phai tut lien tuc ngan nay + + // --- Do nghieng IMU vs do doc ban do (che do doc, xem GlobalMatch) --- + // Gia thuyet ma mat san o do gay ra do nghieng lech qua nguong nay so voi + // IMU thi bi loai. 3.5 do: tach duoc doc 5 do khoi san phang (5 do) va cac + // lan 5/10/15/20/30 do khoi nhau, van chiu sai IMU + sai do nghieng node + // ~1-2 do. + double tilt_tol_deg = 3.5; + // Chi tin do doc cua node trong ban kinh nay; xa hon = khong biet san o do + // (khong loai). + double tilt_node_radius = 1.5; // m + // Chot NHO do nghieng (tilt_used) con phai qua kiem suy bien doc truc: dich + // pose `tilt_shift_m` theo 8 huong ma diem LiDAR van >= ty le nay so voi + // pose chot -> hanh lang / doc deu, vi tri doc truc khong quan sat duoc -> + // KHONG chot. Xem ShiftScoreRatio. Do sim 2026-10-05 (dich 1 m): giua lan doc + // MU = 100% (5 ca, mot ca da chot lech 0.77 m); gan dinh doc 5 do thay tuong + // sanh tren cach 10 m = 90-92% (8/8 vong dung cho, lech 7 cm); sanh 62-65%. + double tilt_shift_m = 1.0; + double tilt_max_shift_ratio = 0.95; + + // --- Vong DUNG YEN tren doc (runtime: khong xoay robot) --- + // Dung yen thi cac vong nhin GAN NHU Y HET: streak (can di >= 0.2 m) khong + // ap dung, va thu mai roi chot o vong vot qua cong la "dao nhieu". Sim + // 2026-10-05, cung mot cho: ty le NHAY hai muc -- ~1.44 khi tim thay doi thu + // that (12 m doc cung lan), ~1.63 khi vong do bo sot no; trung vi 3 vong van + // lot (1.63 / 1.40 / 1.64). Nen quyet bang ty le NHO NHAT qua moi vong lien + // tiep CUNG nguoi thang (doi thu tung hien ra = co that), can >= `static_rounds` + // vong. Nguong mac dinh = min_ratio_fast (chuan mot goc nhin). + int static_rounds = 3; + double static_min_ratio = 1.60; + double static_agree_m = 0.3; + double static_agree_deg = 5.0; }; // Truong likelihood tren luoi chiem dung. Dung chung cho khop toan cuc VA cho @@ -130,22 +162,61 @@ struct RelocMatch { double s1 = 0.0; // diem nguoi thang double s2 = 0.0; // doi thu VI TRI tot nhat (> reject_radius) double s2_yaw = 0.0; // doi thu HUONG tot nhat (cung cho) + // T_map_odom cua hai doi thu tren (de log "nhap nhang voi cho nao"). + Pose2D s2_from_odom; + Pose2D s2_yaw_from_odom; size_t points = 0; // so diem da dung sau khi gop std::vector hyps; // da tinh chinh, [0] = nguoi thang + // Loc bang bang chung ngoai LiDAR (`admit` cua GlobalMatch): + bool tilt_used = false; // ket qua tren DA loai it nhat mot gia thuyet + int tilt_rejected = 0; // so gia thuyet mau thuan bi loai (ung vien + doi thu) + // LiDAR CHAC CHAN o mot cho ma bang chung noi khong the -> bo loc, giu ket + // qua LiDAR nhu cu (khong te hon truoc), nhung phai biet. + bool tilt_conflict = false; + double ratio() const { return s1 / (s2 > 1e-9 ? s2 : 1e-9); } double ratio_yaw() const { return s1 / (s2_yaw > 1e-9 ? s2_yaw : 1e-9); } }; +// Bang chung DOC LAP voi LiDAR cho mot gia thuyet T_map_odom: false = mau +// thuan (vd do nghieng IMU khac do doc ban do tai cho do). Xem GlobalMatch. +using RelocAdmit = std::function; + // Gop diem ve o luoi `res` roi rut con toi `max_points` (giu thu tu). std::vector DownsamplePoints(const std::vector& pts, double res, size_t max_points); // Khop TOAN CUC. `pts_odom`: diem da gom trong frame ODOM (co dinh trong luc // xoay), da cat theo max_range. Tra ok=false neu khong co dinh nao > 0. +// +// `admit` (tuy chon) chi PHAN XU giua cac gia thuyet LiDAR KHONG phan biet +// duoc: gia thuyet bi loai khong duoc thang va khong tinh la doi thu. Nguoi +// thang hop le phai co diem >= s_tot_nhat / min_ratio (trong dai ma LiDAR mot +// minh cung nhap nhang) -- khong bao gio day mot khop LiDAR KEM ro len thang. +// Khong co gia thuyet hop le nao trong dai do -> giu ket qua LiDAR nhu cu, +// danh dau `tilt_conflict`. +// +// ⚠️ Vi sao can (sim 2026-10-05, slope_test.world): robot dat giua doc 5/10/15 +// do, 6 vong x 3 doc deu NHAP NHANG (ty le ~1.00). LiDAR nghieng theo doc chi +// thay hai tuong lan; ban sao doi xung (cho phang o dau kia lan, mui nguoc) +// khop y het. IMU biet robot dang chuc 15 do -- ban sao do o san phang. RelocMatch GlobalMatch(const LikelihoodField& field, const std::vector& pts_odom, - const GlobalLocalizerConfig& cfg); + const GlobalLocalizerConfig& cfg, + const RelocAdmit& admit = nullptr); + +// Suy bien DOC TRUC: diem trung binh cua dam diem tai pose dich `shift_m` theo +// 8 huong (giu huong xoay), chia cho diem tai chinh pose -- lon nhat trong 8. +// ~1 = co mot huong dich ma khop khong xau di (hanh lang, doc deu): vi tri doc +// huong do KHONG quan sat duoc. -1 neu khong tinh duoc. +// +// ⚠️ Cong ty le chi so voi doi thu XA hon reject_radius (2 m). Sim 2026-10-05: +// robot DUNG YEN giua doc 30 do, bo loc nghieng loai het doi thu xa (lan khac, +// cho phang) -> ty le 2.17 -> chot lech 0.77 m DOC lan, cong khong thay. +double ShiftScoreRatio(const LikelihoodField& field, const std::vector& pts_odom, + const Pose2D& map_from_odom, double shift_m, + size_t max_points = 1500); // Khop CUC BO: robot phai nam trong `radius` quanh `center` (frame map). De // XAC MINH ung vien tu nguon khac (VPR). `odom_now`: pose robot trong frame @@ -205,6 +276,40 @@ const char* RelocVerdictName(RelocVerdict v); // Thu tu cong nhu ban ROS: huong truoc, roi vi tri, roi dai bien + streak. RelocVerdict Decide(const RelocMatch& m, int streak, const GlobalLocalizerConfig& cfg); +// --- Vong DUNG YEN (robot khong xoay, vd tren doc) --- +struct StaticRound { + Pose2D robot; // pose robot trong map theo nguoi thang vong do + Pose2D map_from_odom; // T_map_odom cua nguoi thang (bat bien khi robot di) + double ratio = 0.0; + double ratio_yaw = 0.0; + double shift = -1.0; // ShiftScoreRatio; < 0 = khong tinh +}; +// Tom tat cac vong o MOT cho dung (goi khi roi cho do). +struct StaticPlace { + Pose2D map_from_odom; + size_t rounds = 0; + double min_ratio = 0.0; + double min_yaw = 0.0; + double max_shift = -1.0; +}; +StaticPlace SummarizePlace(const std::vector& hist); + +// Them `r` vao `hist` (xoa truoc neu nguoi thang KHAC vong truoc qua +// static_agree_m / static_agree_deg) roi quyet. Chot khi MOT trong hai: +// 1. MOT cho: >= static_rounds vong, ty le NHO NHAT >= static_min_ratio; +// 2. HAI cho khac nhau (`prev`, truoc khi bo): MOI cho >= static_rounds vong +// voi ty le NHO NHAT >= min_ratio, CUNG T_map_odom (static_agree_*). +// Ca hai: ty le huong nho nhat >= min_ratio_yaw, shift lon nhat < nguong (neu +// `use_shift`). +// +// ⚠️ Vi sao KHONG dung streak cua HypothesisTracker o day: sim 2026-10-05, bo +// xuong chan doc 10 / 15 do, nguoi thang SAI on dinh (cao hon 2 m doc lan), +// streak len 4-6 qua cac lan bo trong khi ty le 1.0-1.2; mot vong nhay 1.32 / +// 1.34 -> chot sai 2.0 / 1.5 m. Ty le NHO NHAT moi cho chan duoc kieu do. +RelocVerdict DecideStatic(std::vector* hist, const StaticRound& r, + const std::vector& prev, const GlobalLocalizerConfig& cfg, + bool use_shift, bool* along_axis, std::string* why); + } // namespace vslam #endif // VSLAM_GLOBAL_LOCALIZER_H diff --git a/libs/vslam_slam/include/vslam/height_map.h b/libs/vslam_slam/include/vslam/height_map.h index d1e93b6..24036d5 100644 --- a/libs/vslam_slam/include/vslam/height_map.h +++ b/libs/vslam_slam/include/vslam/height_map.h @@ -93,6 +93,18 @@ class FloorModel { // Do cao mat phang cua node n tai (x, y). double PlaneZ(const FloorNode& n, double x, double y); +// Do doc SAN tai (x, y): gradient (dz/dx, dz/dy, frame map) cua mat phang node +// gan nhat. false neu node gan nhat xa hon `max_dist` (khong biet san o do). +bool FloorGradientAt(const FloorModel& fm, double x, double y, double max_dist, double* gx, + double* gy); + +// Do lech giua do nghieng than DO DUOC (roll, pitch -- ROS, tu IMU) va do +// nghieng ma mat san gradient (gx, gy) GAY RA cho robot mui huong `yaw` (frame +// map). Don vi: do doc (tan) -- 0.087 ~ 5 do. Dinh vi lai dung no de loai gia +// thuyet mau thuan voi IMU: quay nguoc 180 do tren doc, doc o cho phang, doc +// sai goc. +double TiltResidual(double roll, double pitch, double yaw, double gx, double gy); + } // namespace vslam #endif // VSLAM_HEIGHT_MAP_H diff --git a/libs/vslam_slam/src/global_localizer.cc b/libs/vslam_slam/src/global_localizer.cc index ece11b4..7e5990b 100644 --- a/libs/vslam_slam/src/global_localizer.cc +++ b/libs/vslam_slam/src/global_localizer.cc @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -321,7 +322,8 @@ Pose2D ToMap(const Refined& rf, const Point& cen, const LikelihoodField& f) { RelocMatch GlobalMatch(const LikelihoodField& field, const std::vector& pts_odom, - const GlobalLocalizerConfig& cfg) { + const GlobalLocalizerConfig& cfg, + const RelocAdmit& admit) { RelocMatch out; if (field.empty() || pts_odom.empty()) return out; @@ -354,6 +356,15 @@ RelocMatch GlobalMatch(const LikelihoodField& field, [](const AnglePeak& a, const AnglePeak& b) { return a.score > b.score; }); if (peaks.empty() || peaks[0].score <= 0.0) return out; + // T_map_odom cua mot o tho: TAM dam diem dat vao tam khoi (r, c), xoay th. + auto coarse_map = [&](int r, int c, double th) { + Refined q; + q.x = block_center(c); + q.y = block_center(r); + q.th = th; + return ToMap(q, cz.cen, field); + }; + // --- Gom TOP-K dinh tho, khu trung trong reject_radius --- // Xet nhieu dinh chu khong chi cai cao nhat: muc tho dung max-pool nen rat // rong rai, thu tu o day chua chac dung. @@ -370,17 +381,98 @@ RelocMatch GlobalMatch(const LikelihoodField& field, if (static_cast(cand.size()) >= cfg.max_candidates) break; } + // Co bang chung ngoai: them dinh TOT NHAT HOP LE cua moi goc. Dinh tho cao + // nhat moi goc co the deu la ban sao doi xung bi loai, va khi do cho that + // khong bao gio duoc tinh chinh. Chi goi `admit` khi o vuot dinh hien tai. + std::vector acand; + if (admit) { + std::vector apeaks; + for (int ia = 0; ia < n_ang; ++ia) { + const double th = ia * step; + const std::vector& sc = scores[ia]; + AnglePeak bp{0.0, -1, -1, th}; + for (int r = 0; r < Hc; ++r) { + for (int c = 0; c < Wc; ++c) { + const float v = sc[static_cast(r) * Wc + c]; + if (v > bp.score && admit(coarse_map(r, c, th))) bp = AnglePeak{v, r, c, th}; + } + } + if (bp.r >= 0) apeaks.push_back(bp); + } + std::sort(apeaks.begin(), apeaks.end(), + [](const AnglePeak& a, const AnglePeak& b) { return a.score > b.score; }); + const double min_sep = cfg.min_angle_sep_deg * kDegToRad; + for (int i = 0; i < std::min(cfg.top_k, static_cast(apeaks.size())); ++i) { + const AnglePeak& p = apeaks[i]; + bool dup = false; + auto near = [&](const AnglePeak& q) { + const double dr = p.r - q.r, dc = p.c - q.c; + return dr * dr + dc * dc <= rad_c * rad_c; + }; + // Dinh LiDAR goc o CUNG cho nhung lat huong la ung vien KHAC han. + for (const AnglePeak& q : cand) { + if (near(q) && std::fabs(AngleDiff(p.th, q.th)) < min_sep) { dup = true; break; } + } + for (const AnglePeak& q : acand) { + if (!dup && near(q)) { dup = true; break; } + } + if (!dup) acand.push_back(p); + if (static_cast(acand.size()) >= cfg.max_candidates) break; + } + } + // ⚠️ Tinh chinh TUNG ung vien roi moi so diem voi nhau. So o muc tho (co // max-pool) thi gan nhu moi cho canh tuong deu diem cao -- ban ROS do duoc // tot/xau chi cach nhau 1.18 lan, cong chan loai ca ca DUNG. + auto refine_all = [&](const std::vector& src, std::vector* dst) { + for (const AnglePeak& p : src) { + const Refined rf = Refine(field, P, block_center(p.c), block_center(p.r), p.th, rc, cfg); + if (rf.score >= 0.0) dst->push_back(rf); + } + std::sort(dst->begin(), dst->end(), + [](const Refined& a, const Refined& b) { return a.score > b.score; }); + }; std::vector refined; - for (const AnglePeak& p : cand) { - const Refined rf = Refine(field, P, block_center(p.c), block_center(p.r), p.th, rc, cfg); - if (rf.score >= 0.0) refined.push_back(rf); - } + refine_all(cand, &refined); if (refined.empty()) return out; - std::sort(refined.begin(), refined.end(), - [](const Refined& a, const Refined& b) { return a.score > b.score; }); + + // --- Loc bang bang chung ngoai LiDAR (xem global_localizer.h) --- + // Nguoi thang hop le phai nam trong dai LiDAR mot minh cung nhap nhang + // (>= s_tot_nhat / min_ratio). Ngoai dai do = LiDAR CHAC o cho bang chung noi + // khong the -> giu nguyen ket qua LiDAR (y het khong co `admit`: ung vien them + // tu `acand` khong duoc dung), chi danh dau. + bool filt = false; + if (admit) { + std::vector keep; + refine_all(acand, &keep); // dinh hop le them -- da hop le o muc tho + keep.erase(std::remove_if(keep.begin(), keep.end(), + [&](const Refined& rf) { return !admit(ToMap(rf, cz.cen, field)); }), + keep.end()); + for (const Refined& rf : refined) { + if (admit(ToMap(rf, cz.cen, field))) { + keep.push_back(rf); + } else { + ++out.tilt_rejected; + } + } + std::sort(keep.begin(), keep.end(), + [](const Refined& a, const Refined& b) { return a.score > b.score; }); + if (!keep.empty() && keep[0].score >= refined[0].score / cfg.min_ratio) { + refined.swap(keep); + filt = true; + } else { + out.tilt_conflict = true; + } + } + // Doi thu cung phai hop le: gia thuyet bang chung noi khong the thi khong + // canh tranh. ⚠️ Ke ca khi KHONG ung vien nao bi loai: ban lat 180 do o CUNG + // cho khong nam trong danh sach tinh chinh (gom theo vi tri) ma chi hien o + // doi thu HUONG -- dung ca lan doc. Xung dot thi moi thu nhu cu. + auto rival_ok = [&](int r, int c, double th) { + if (!filt || admit(coarse_map(r, c, th))) return true; + ++out.tilt_rejected; + return false; + }; const Refined& best = refined[0]; // --- Doi thu VI TRI --- @@ -389,8 +481,10 @@ RelocMatch GlobalMatch(const LikelihoodField& field, // chot bua (9.3% duong tinh gia, sai 9-13 m). Nen quet lai diem THO o vung xa. double s2 = 0.0; for (size_t i = 1; i < refined.size(); ++i) { - if (std::hypot(refined[i].x - best.x, refined[i].y - best.y) > cfg.reject_radius) { - s2 = std::max(s2, refined[i].score); + if (std::hypot(refined[i].x - best.x, refined[i].y - best.y) > cfg.reject_radius && + refined[i].score > s2) { + s2 = refined[i].score; + out.s2_from_odom = ToMap(refined[i], cz.cen, field); } } const int rw = static_cast(std::lround(best.y / res)) / k; @@ -408,13 +502,18 @@ RelocMatch GlobalMatch(const LikelihoodField& field, for (int r = 0; r < Hc; ++r) { for (int c = 0; c < Wc; ++c) { const float v = sc[static_cast(r) * Wc + c]; - if (v > fv && is_far(r, c)) { fv = v; fr = r; fc = c; fth = ia * step; } + if (v > fv && is_far(r, c) && rival_ok(r, c, ia * step)) { + fv = v; fr = r; fc = c; fth = ia * step; + } } } } if (fr >= 0 && fv > 0.0) { const Refined alt = Refine(field, P, block_center(fc), block_center(fr), fth, rc, cfg); - s2 = std::max(s2, alt.score); + if (alt.score > s2) { + s2 = alt.score; + out.s2_from_odom = ToMap(alt, cz.cen, field); + } } } @@ -432,15 +531,18 @@ RelocMatch GlobalMatch(const LikelihoodField& field, for (int r = 0; r < Hc; ++r) { for (int c = 0; c < Wc; ++c) { const float v = sc[static_cast(r) * Wc + c]; - if (v > gv && !is_far(r, c)) { gv = v; gr = r; gc = c; gth = th; } + if (v > gv && !is_far(r, c) && rival_ok(r, c, th)) { gv = v; gr = r; gc = c; gth = th; } } } } if (gr >= 0 && gv > 0.0) { - s2_yaw = Refine(field, P, block_center(gc), block_center(gr), gth, rc, cfg).score; + const Refined alt = Refine(field, P, block_center(gc), block_center(gr), gth, rc, cfg); + s2_yaw = alt.score; + out.s2_yaw_from_odom = ToMap(alt, cz.cen, field); } } + out.tilt_used = filt && out.tilt_rejected > 0; for (const Refined& rf : refined) out.hyps.push_back({ToMap(rf, cz.cen, field), rf.score}); out.map_from_odom = out.hyps[0].map_from_odom; out.s1 = best.score; @@ -450,6 +552,32 @@ RelocMatch GlobalMatch(const LikelihoodField& field, return out; } +double ShiftScoreRatio(const LikelihoodField& field, const std::vector& pts_odom, + const Pose2D& map_from_odom, double shift_m, size_t max_points) { + if (field.empty() || pts_odom.empty()) return -1.0; + const std::vector pts = DownsamplePoints(pts_odom, field.resolution(), max_points); + auto score = [&](const Pose2D& T) { + const double c = std::cos(T.theta), s = std::sin(T.theta); + std::vector m(pts.size()); + for (size_t i = 0; i < pts.size(); ++i) { + m[i].x = T.x + c * pts[i].x - s * pts[i].y; + m[i].y = T.y + s * pts[i].x + c * pts[i].y; + } + return field.MeanScore(m); + }; + const double s0 = score(map_from_odom); + if (s0 <= 0.0) return -1.0; + double best = 0.0; + for (int k = 0; k < 8; ++k) { + const double a = k * M_PI / 4.0; + Pose2D t = map_from_odom; + t.x += shift_m * std::cos(a); + t.y += shift_m * std::sin(a); + best = std::max(best, score(t)); + } + return best / s0; +} + RelocHypothesis LocalMatch(const LikelihoodField& field, const std::vector& pts_odom, const Pose2D& odom_now, const Point& center, double radius, @@ -610,4 +738,95 @@ RelocVerdict Decide(const RelocMatch& m, int streak, const GlobalLocalizerConfig return RelocVerdict::kAccept; } +StaticPlace SummarizePlace(const std::vector& hist) { + StaticPlace p; + if (hist.empty()) return p; + p.map_from_odom = hist.back().map_from_odom; + p.rounds = hist.size(); + p.min_ratio = 1e9; + p.min_yaw = 1e9; + p.max_shift = -1.0; + for (const StaticRound& h : hist) { + p.min_ratio = std::min(p.min_ratio, h.ratio); + p.min_yaw = std::min(p.min_yaw, h.ratio_yaw); + p.max_shift = std::max(p.max_shift, h.shift); + } + return p; +} + +RelocVerdict DecideStatic(std::vector* hist, const StaticRound& r, + const std::vector& prev, const GlobalLocalizerConfig& cfg, + bool use_shift, bool* along_axis, std::string* why) { + *along_axis = false; + // Robot dung yen -> nguoi thang cac vong phai la CUNG mot pose robot. + if (!hist->empty()) { + const Pose2D& b = hist->back().robot; + if (std::hypot(r.robot.x - b.x, r.robot.y - b.y) > cfg.static_agree_m || + std::fabs(AngleDiff(r.robot.theta, b.theta)) > cfg.static_agree_deg * kDegToRad) { + hist->clear(); + } + } + hist->push_back(r); + // Giu MOI vong lien tiep cung cho (chan tren de khong phinh): doi thu tung + // hien ra o bat ky vong nao deu tinh. + constexpr size_t kMaxHist = 30; + while (hist->size() > kMaxHist) hist->erase(hist->begin()); + const size_t k = static_cast(std::max(1, cfg.static_rounds)); + const StaticPlace cur = SummarizePlace(*hist); + const size_t n = cur.rounds; + char b[200]; + if (cur.min_yaw < cfg.min_ratio_yaw) { + std::snprintf(b, sizeof(b), "ty le huong nho nhat %zu vong %.2f < %.2f", n, cur.min_yaw, + cfg.min_ratio_yaw); + *why = b; + return RelocVerdict::kAmbiguousYaw; + } + if (cur.min_ratio < cfg.min_ratio) { + std::snprintf(b, sizeof(b), "ty le nho nhat %zu vong %.2f < %.2f", n, cur.min_ratio, cfg.min_ratio); + *why = b; + return RelocVerdict::kAmbiguous; + } + if (use_shift && cur.max_shift >= cfg.tilt_max_shift_ratio) { + *along_axis = true; + std::snprintf(b, sizeof(b), "dich %.1f m van giu %.0f%% diem", cfg.tilt_shift_m, + 100.0 * cur.max_shift); + *why = b; + return RelocVerdict::kAmbiguous; + } + if (n < k) { + std::snprintf(b, sizeof(b), "cho %zu vong lien tiep cung cho (%zu/%zu), ty le nho nhat %.2f", k, n, + k, cur.min_ratio); + *why = b; + return RelocVerdict::kNeedCycles; + } + // 1. Mot cho, chuan mot goc nhin. + if (cur.min_ratio >= cfg.static_min_ratio) { + std::snprintf(b, sizeof(b), "%zu vong cung cho: ty le nho nhat %.2f / huong %.2f", n, cur.min_ratio, + cur.min_yaw); + *why = b; + return RelocVerdict::kAccept; + } + // 2. Hai cho khac nhau, MOI cho deu qua min_ratio o moi vong cua no, cung gia thuyet. + for (const StaticPlace& p : prev) { + if (p.rounds < k || p.min_ratio < cfg.min_ratio || p.min_yaw < cfg.min_ratio_yaw) continue; + if (use_shift && p.max_shift >= cfg.tilt_max_shift_ratio) continue; + if (std::hypot(p.map_from_odom.x - cur.map_from_odom.x, p.map_from_odom.y - cur.map_from_odom.y) > + cfg.static_agree_m || + std::fabs(AngleDiff(p.map_from_odom.theta, cur.map_from_odom.theta)) > + cfg.static_agree_deg * kDegToRad) { + continue; + } + std::snprintf(b, sizeof(b), + "hai cho cung pose: ty le nho nhat %.2f (cho nay, %zu vong) / %.2f (cho truoc, %zu vong)", + cur.min_ratio, n, p.min_ratio, p.rounds); + *why = b; + return RelocVerdict::kAccept; + } + std::snprintf(b, sizeof(b), + "ty le nho nhat %zu vong %.2f < %.2f -- can them mot cho khac (sau khi bo) cung pose", + n, cur.min_ratio, cfg.static_min_ratio); + *why = b; + return RelocVerdict::kNeedCycles; +} + } // namespace vslam diff --git a/libs/vslam_slam/src/height_map.cc b/libs/vslam_slam/src/height_map.cc index 8874cc0..4663e6b 100644 --- a/libs/vslam_slam/src/height_map.cc +++ b/libs/vslam_slam/src/height_map.cc @@ -147,4 +147,28 @@ bool FloorModel::FloorAt(double x, double y, double* z, double* dist) const { return true; } +bool FloorGradientAt(const FloorModel& fm, double x, double y, double max_dist, double* gx, + double* gy) { + FloorNode n; + double d = 0.0; + if (!fm.NearestNode(x, y, &n, &d) || d > max_dist) return false; + // Dao ham cua PlaneZ: z = z_n - fwd * tan(pitch) + left * tan(roll). + const double c = std::cos(n.theta), s = std::sin(n.theta); + const double tp = std::tan(n.pitch), tr = std::tan(n.roll); + *gx = -tp * c - tr * s; + *gy = -tp * s + tr * c; + return true; +} + +double TiltResidual(double roll, double pitch, double yaw, double gx, double gy) { + const double c = std::cos(yaw), s = std::sin(yaw); + const double sf = gx * c + gy * s; // doc theo huong mui (len = duong) + const double sl = -gx * s + gy * c; // doc sang trai + // Than nam tren mat do, R = Rz(yaw) Ry(pitch) Rx(roll): truc x than nam trong + // mat -> tan(pitch) = -sf; truc y than nam trong mat -> tan(roll) = sl * cos(pitch). + const double mf = -std::tan(pitch); + const double ml = std::tan(roll) / std::max(1e-6, std::cos(pitch)); + return std::hypot(mf - sf, ml - sl); +} + } // namespace vslam diff --git a/libs/vslam_web/include/vslam/binary_codec.h b/libs/vslam_web/include/vslam/binary_codec.h index 4139bed..9dd7ea3 100644 --- a/libs/vslam_web/include/vslam/binary_codec.h +++ b/libs/vslam_web/include/vslam/binary_codec.h @@ -80,12 +80,31 @@ void EncodeScan(const LaserScan& scan, UnixTime stamp, std::string* out); void EncodeCloud(const PointCloudXYZ& cloud, UnixTime stamp, uint32_t max_points, float quant_m, const Pose2D& delta, std::string* out); +// Do cao SAN cua ban do (slam.yaml slope.enabled): luoi THO, mm, kFloorUnknown +// = chua biet. Web uon mat phang ban do 2D theo luoi nay -- khong co no thi +// mat doc va san tang tren duoc ve o z = 0, nam DUOI tuong voxel (o z that) +// va trong nhu san bi thung. +constexpr int16_t kFloorUnknown = -32768; +struct MapFloorGrid { + float resolution = 0.2f; + uint32_t width = 0; + uint32_t height = 0; + float origin_x = 0.0f; + float origin_y = 0.0f; + std::vector mm; // hang chinh, hang 0 = y nho nhat (nhu OccupancyGrid) +}; + // RLE hang-chinh. Xem rle.h. // `type` cho phep dung chung bo ma hoa cho ban do SLAM (kMapFull) va ban do // THE GIOI cua bo mo phong (kWorldMap): khung giong het nhau, chi khac y // nghia. Mot bo ma hoa thu hai se la hai cho de lech dinh dang. +// +// `floor_grid` (tuy chon): khoi do cao san NOI SAU phan RLE -- magic "FLH1", f32 +// res, i32 w, i32 h, f32 ox, f32 oy, roi w*h int16 (mm). Khong co thi khung y +// het cu. void EncodeMapFull(const OccupancyGrid& map, UnixTime stamp, std::string* out, - BinaryType type = BinaryType::kMapFull); + BinaryType type = BinaryType::kMapFull, + const MapFloorGrid* floor_grid = nullptr); // (kMapPatch = 4 da bi BO. No noi duoc vao dau: cong per-session chi la mot // atomic `acked_map_version_`, khong dien ta noi "session nay dang giu luoi @@ -149,7 +168,9 @@ struct BinaryHeader { bool DecodeHeader(const std::string& buf, size_t offset, BinaryHeader* out); bool DecodeScan(const std::string& buf, LaserScan* out); -bool DecodeMapFull(const std::string& buf, OccupancyGrid* out); +// `floor_grid` (tuy chon) nhan khoi do cao san neu khung co; khong co thi width = 0. +bool DecodeMapFull(const std::string& buf, OccupancyGrid* out, + MapFloorGrid* floor_grid = nullptr); // Giai mot manh. `out` duoc NOI THEM, khong xoa -- rap nhieu manh bang cach // goi lien tiep. `total`/`chunk_index`/`chunk_count`/`epoch` tra qua con tro diff --git a/libs/vslam_web/include/vslam/web_snapshot.h b/libs/vslam_web/include/vslam/web_snapshot.h index 115d2e7..2a86507 100644 --- a/libs/vslam_web/include/vslam/web_snapshot.h +++ b/libs/vslam_web/include/vslam/web_snapshot.h @@ -13,6 +13,7 @@ #include #include +#include "vslam/binary_codec.h" #include "vslam/stats.h" #include "vslam/vslam_common.h" @@ -181,6 +182,8 @@ struct WebSnapshot { Pose2D cloud_delta; bool have_cloud_delta = false; OccupancyGridPtr map; // ban do SLAM dung + // Do cao SAN cua ban do (che do doc), gui kem khung map. Null = phang. + std::shared_ptr map_floor; // Ban do THE GIOI cua bo mo phong (khung nhin "Gazebo"). Null khi chay // that -- luc do khong co su that nao de doi chieu. OccupancyGridPtr world_map; diff --git a/libs/vslam_web/src/binary_codec.cc b/libs/vslam_web/src/binary_codec.cc index ac25a3f..ccaa3a5 100644 --- a/libs/vslam_web/src/binary_codec.cc +++ b/libs/vslam_web/src/binary_codec.cc @@ -147,7 +147,7 @@ void EncodeCloud(const PointCloudXYZ& cloud, UnixTime stamp, uint32_t max_points } void EncodeMapFull(const OccupancyGrid& map, UnixTime stamp, std::string* out, - BinaryType type) { + BinaryType type, const MapFloorGrid* floor_grid) { PutHeader(out, type, stamp); PutF32(out, map.resolution); PutI32(out, static_cast(map.width)); @@ -169,6 +169,19 @@ void EncodeMapFull(const OccupancyGrid& map, UnixTime stamp, std::string* out, (*out)[run_count_off + static_cast(i)] = static_cast((r32 >> (8 * i)) & 0xFF); } + + // Khoi do cao san (che do doc), NOI SAU phan RLE -- xem binary_codec.h. + const MapFloorGrid* fg = floor_grid; + if (fg != nullptr && fg->width > 0 && fg->height > 0 && + fg->mm.size() == static_cast(fg->width) * fg->height) { + out->append("FLH1", 4); + PutF32(out, fg->resolution); + PutI32(out, static_cast(fg->width)); + PutI32(out, static_cast(fg->height)); + PutF32(out, fg->origin_x); + PutF32(out, fg->origin_y); + for (int16_t v : fg->mm) PutI16(out, v); + } } // --- Ban do voxel 3D ------------------------------------------------------- @@ -333,9 +346,10 @@ bool DecodeScan(const std::string& buf, LaserScan* out) { return true; } -bool DecodeMapFull(const std::string& buf, OccupancyGrid* out) { +bool DecodeMapFull(const std::string& buf, OccupancyGrid* out, MapFloorGrid* floor_grid) { BinaryHeader h; if (!DecodeHeader(buf, 0, &h) || h.type != BinaryType::kMapFull) return false; + if (floor_grid != nullptr) *floor_grid = MapFloorGrid{}; size_t o = kBinaryHeaderSize; if (buf.size() < o + 28) return false; @@ -351,6 +365,25 @@ bool DecodeMapFull(const std::string& buf, OccupancyGrid* out) { const size_t expected = static_cast(out->width) * out->height; if (!RleDecode(buf, o, runs, expected, &out->data)) return false; + // Khoi do cao san tuy chon, ngay sau RLE (3 byte moi run). + o += static_cast(runs) * 3; + if (floor_grid != nullptr && buf.size() >= o + 24 && buf.compare(o, 4, "FLH1") == 0) { + MapFloorGrid f; + f.resolution = GetF32(buf, o + 4); + f.width = static_cast(GetI32(buf, o + 8)); + f.height = static_cast(GetI32(buf, o + 12)); + f.origin_x = GetF32(buf, o + 16); + f.origin_y = GetF32(buf, o + 20); + const size_t n = static_cast(f.width) * f.height; + if (buf.size() >= o + 24 + 2 * n) { + f.mm.resize(n); + for (size_t i = 0; i < n; ++i) { + f.mm[i] = static_cast(GetU16(buf, o + 24 + 2 * i)); + } + *floor_grid = std::move(f); + } + } + out->header.stamp = UnixTime::fromNSec(static_cast(h.stamp_ns)); return true; } diff --git a/libs/vslam_web/src/web_server.cc b/libs/vslam_web/src/web_server.cc index 556adf3..a86efcd 100644 --- a/libs/vslam_web/src/web_server.cc +++ b/libs/vslam_web/src/web_server.cc @@ -830,7 +830,8 @@ void WebServer::Publish(const WebSnapshot& snap) { if (s->acked_map_version() == snap.slam.map_version) continue; if (!buf) { buf = std::make_shared(); - EncodeMapFull(*snap.map, snap.stamp, buf.get()); + EncodeMapFull(*snap.map, snap.stamp, buf.get(), BinaryType::kMapFull, + snap.map_floor.get()); } s->Send(buf, true, /*is_map=*/true); s->set_acked_map_version(snap.slam.map_version); diff --git a/libs/vslam_web/www/app.js b/libs/vslam_web/www/app.js index 386d1fb..b6c0a8a 100644 --- a/libs/vslam_web/www/app.js +++ b/libs/vslam_web/www/app.js @@ -12,7 +12,7 @@ const MAGIC = 0x314C5356; // 'VSL1' little-endian // Phien ban ma nguon giao dien. TANG khi doi app.js / app3d.js / style.css. // Hien ngay tren thanh tren cung de phan biet "chua sua" voi "trinh duyet con // cache ban cu". -const UI_VERSION = '2026-09-30a'; +const UI_VERSION = '2026-10-05c'; // ⚠️ HAI bang mau, mot cho moi khung. Chung KHONG duoc giong nhau. // @@ -68,6 +68,8 @@ const T_SCAN = 1, T_CLOUD = 2, T_MAP_FULL = 3, T_PATH = 5; const T_WORLD_MAP = 6; // Ban do voxel 3D: tap day du (chia manh) va phan them/bot. const T_VOXEL_FULL = 7, T_VOXEL_DELTA = 8; +// Khoi do cao SAN noi sau RLE cua khung ban do (che do doc, binary_codec.h). +const FLOOR_MAGIC = 0x31484C46; // 'FLH1' little-endian // Ba ngu nghia cua mot tia. Lan lon chung la lam sai ca man hinh. const R_NAN = 0xFFFF; // khong do duoc (duoi range_min) @@ -229,7 +231,21 @@ function onBinary(dv) { cells.fill(val, p, p + len); p += len; } - const grid = { res, w, h, ox, oy, cells }; + // Do cao san (mm, -32768 = chua biet) ngay sau RLE. Khong co thi ban do + // phang nhu cu. + let floor = null; + const fo = off + 28 + runs * 3; + if (type === T_MAP_FULL && dv.byteLength >= fo + 24 && + dv.getUint32(fo, true) === FLOOR_MAGIC) { + const fw = dv.getInt32(fo + 8, true), fh = dv.getInt32(fo + 12, true); + if (fw > 0 && fh > 0 && dv.byteLength >= fo + 24 + fw * fh * 2) { + const mm = new Int16Array(fw * fh); + for (let i = 0; i < fw * fh; i++) mm[i] = dv.getInt16(fo + 24 + i * 2, true); + floor = { res: dv.getFloat32(fo + 4, true), w: fw, h: fh, + ox: dv.getFloat32(fo + 16, true), oy: dv.getFloat32(fo + 20, true), mm }; + } + } + const grid = { res, w, h, ox, oy, cells, floor }; if (type === T_WORLD_MAP) { // Ban do THE GIOI: su that, de lai cho chuan. KHONG lan vao state.map. state.worldMap = grid; @@ -620,6 +636,11 @@ function anchorPose(robotPose, anchoredAt) { x: robotPose.x + c * lx - s * ly, y: robotPose.y + s * lx + c * ly, yaw: robotPose.yaw + (anchoredAt.yaw - state.pose.yaw), + // Cao do san duoi robot va do nghieng than (che do doc): khung 3D nang + // scan/cloud len theo z, va xoay scan tho theo roll/pitch. + z: robotPose.z, + roll: robotPose.roll, + pitch: robotPose.pitch, }; } @@ -1314,7 +1335,7 @@ function draw3d() { v3dSetMap({ ...state.map, data: state.map.cells, version: state.mapVersion }); } if (V3D.mapMesh) V3D.mapMesh.visible = on('lyMap') && !!state.map; - if (on('lyPath')) v3dSetPath(state.path); + if (on('lyPath')) v3dSetPath(state.path, state.map && state.map.floor); else if (V3D.pathLine) V3D.pathLine.visible = false; v3dRender(cv3d, on('lyFollow'), split3d); diff --git a/libs/vslam_web/www/app3d.js b/libs/vslam_web/www/app3d.js index a758723..c9593ce 100644 --- a/libs/vslam_web/www/app3d.js +++ b/libs/vslam_web/www/app3d.js @@ -456,8 +456,16 @@ function v3dSetScan(arr, pose, r) { const n = arr.length / 2; const pos = new Float32Array(n * 3); // Scan nam o do cao cua LiDAR, khong phai o san. Ve o san se lam nguoi xem - // tuong LiDAR thay duoc vat thap -- no KHONG thay. - const z = r.laser_z + r.wheel_radius; + // tuong LiDAR thay duoc vat thap -- no KHONG thay. Cong cao do san duoi + // robot (che do doc), khong thi o tang tren scan ve chui duoi san. + const z0 = pose.z || 0; + const zl = r.laser_z + r.wheel_radius; // goc LiDAR tren san, he footprint + // Web nhan scan THO: tia nam trong mat phang LiDAR, NGHIENG theo than robot. + // Tren doc 15 do ve phang thi diem cach 3 m lech ~0.8 m (chui vao mat doc) + // -> xoay theo roll/pitch quanh footprint, nhu v3dSetPose xoay hinh robot. + // ROS R = Rz(yaw) Ry(pitch) Rx(roll); khong co tilt thi y het cu. + const cr = Math.cos(pose.roll || 0), sr = Math.sin(pose.roll || 0); + const cp = Math.cos(pose.pitch || 0), sp = Math.sin(pose.pitch || 0); // ⚠️ Scan den trong frame LASER, khong phai frame BASE. // // `laser_link` cach `base_link` 0.24 m ve phia truoc (robot.yaml). Dat thang @@ -469,9 +477,12 @@ function v3dSetScan(arr, pose, r) { const lx = r.laser_x || 0, ly = r.laser_y || 0; for (let i = 0; i < n; ++i) { const x = arr[i * 2] + lx, y = arr[i * 2 + 1] + ly; - pos[i * 3] = pose.x + c * x - s * y; - pos[i * 3 + 1] = z; - pos[i * 3 + 2] = -(pose.y + s * x + c * y); + // Rx(roll) roi Ry(pitch), trong he footprint (truoc khi quay yaw). + const y1 = y * cr - zl * sr, z1 = y * sr + zl * cr; + const x2 = x * cp + z1 * sp, z2 = -x * sp + z1 * cp; + pos[i * 3] = pose.x + c * x2 - s * y1; + pos[i * 3 + 1] = z0 + z2; + pos[i * 3 + 2] = -(pose.y + s * x2 + c * y1); } V3D.scanPts.geometry.dispose(); V3D.scanPts.geometry = new THREE.BufferGeometry(); @@ -493,10 +504,11 @@ function v3dSetCloud(arr, pose) { const c = Math.cos(pose.yaw), s = Math.sin(pose.yaw); const n = arr.length / 3; const pos = new Float32Array(n * 3), col = new Float32Array(n * 3); + const z0 = pose.z || 0; // cao do san duoi robot (che do doc) for (let i = 0; i < n; ++i) { const x = arr[i * 3], y = arr[i * 3 + 1], z = arr[i * 3 + 2]; pos[i * 3] = pose.x + c * x - s * y; - pos[i * 3 + 1] = z; + pos[i * 3 + 1] = z0 + z; pos[i * 3 + 2] = -(pose.y + s * x + c * y); // To mau theo do cao, cung bang mau voi khung 2D. const t = Math.max(0, Math.min(1, z / 1.2)); @@ -618,12 +630,22 @@ function v3dSetMapCloud(v, visible) { // San dat o TOA DO THE GIOI chu khong theo robot. Dat theo robot la dung cai // bay "sàn troi theo robot": robot dung yen giua man hinh con ca the gioi // truot qua, trong y het loi dinh vi. +// +// ⚠️ Chi dung lai khi BAO the gioi doi. Chay tu `.world`, v3dSetWorld() goi +// ham nay MOI khung hinh (nhanh mesh that thoat som truoc khoa worldKey), va +// ban cu dung lai mat san + GridHelper moi khung ma khong giai phong cai cu. +// Do tren slope_test.world: geometry tren GPU tang ~1 moi khung (20 -> 203 +// sau 183 khung), tuc ~3600/phut o 60 fps -- trinh duyet cham dan. function v3dSetGround(grid) { if (!V3D.ready || !grid) return; + const key = grid.w + 'x' + grid.h + '@' + grid.res + ':' + grid.ox + ',' + grid.oy; + if (V3D.groundKey === key && V3D.floorMesh) return; + V3D.groundKey = key; const r = grid.res; if (V3D.floorMesh) { V3D.root.remove(V3D.floorMesh); V3D.floorMesh.geometry.dispose(); + V3D.floorMesh.material.dispose(); } const fw = grid.w * r, fh = grid.h * r; V3D.floorMesh = new THREE.Mesh( @@ -640,7 +662,11 @@ function v3dSetGround(grid) { const span = Math.max(fw, fh); V3D.scene.fog.near = span * 0.35; V3D.scene.fog.far = span * 1.4; - if (V3D.gridHelper) V3D.root.remove(V3D.gridHelper); + if (V3D.gridHelper) { + V3D.root.remove(V3D.gridHelper); + V3D.gridHelper.geometry.dispose(); + V3D.gridHelper.material.dispose(); + } V3D.gridHelper = new THREE.GridHelper(Math.ceil(span), Math.ceil(span), 0x93a2b0, 0xa6b3c0); V3D.root.add(V3D.gridHelper); @@ -844,11 +870,69 @@ function v3dSetWorld(grid, wallHeight) { v3dSetGround(grid); } -// Ban do occupancy -> mot mat phang co texture, dat o san. +// --- Do cao SAN cua ban do (che do doc) --- +// +// Luoi tho (0.2 m, mm, -32768 = chua biet) di kem khung ban do SLAM. O chua +// biet (xa moi node > 4 m: tuong LiDAR thay tu xa) lay gia tri o DA BIET gan +// nhat -- de 0 thi mat phang tu tang tren cam xuong z = 0 thanh mot tam xien. +const FLOOR_UNKNOWN = -32768; +// Mat ban do uon dat CAO hon san uoc luong 4 cm. Trong khung gop, mesh san +// THAT cua world (doc, san) la mat duc trung cho voi no: thap hon du chi 2 mm +// la bi che, ngang nhau la nhap nhay rang cua -- chinh la "nen bi lung". Da do +// (sim, map 645 node): sai uoc - that p1 -2.3 cm, p50 +3.3 cm; nang 3 cm con +// 0.3% o chim, 4 cm con 0%. Robot that khong co mesh world: chi noi 4 cm. +const FLOOR_LIFT = 0.04; + +function v3dFloorFill(fl) { + const n = fl.w * fl.h; + const out = new Int16Array(fl.mm); + const q = new Int32Array(n); + let head = 0, tail = 0; + for (let i = 0; i < n; ++i) if (out[i] !== FLOOR_UNKNOWN) q[tail++] = i; + if (tail === 0) return null; + while (head < tail) { + const i = q[head++], c = i % fl.w, r = (i - c) / fl.w; + const nb = [c > 0 ? i - 1 : -1, c + 1 < fl.w ? i + 1 : -1, + r > 0 ? i - fl.w : -1, r + 1 < fl.h ? i + fl.w : -1]; + for (const j of nb) { + if (j >= 0 && out[j] === FLOOR_UNKNOWN) { out[j] = out[i]; q[tail++] = j; } + } + } + return { ...fl, mm: out }; +} + +// Do cao san (m) tai (x, y) ROS: noi suy song tuyen giua TAM 4 o quanh diem +// (dinh mat phang nam dung GOC o -- lay o gan nhat thi tren doc 15 do lech +// ~3 cm theo phia lam tron). null neu ngoai luoi / chua biet. +function v3dFloorAt(fl, x, y) { + if (!fl) return null; + const gx = (x - fl.ox) / fl.res - 0.5, gy = (y - fl.oy) / fl.res - 0.5; + const c0 = Math.floor(gx), r0 = Math.floor(gy); + const fx = gx - c0, fy = gy - r0; + let sw = 0, sz = 0; + for (let k = 0; k < 4; ++k) { + const c = c0 + (k & 1), r = r0 + (k >> 1); + if (c < 0 || r < 0 || c >= fl.w || r >= fl.h) continue; + const v = fl.mm[r * fl.w + c]; + if (v === FLOOR_UNKNOWN) continue; + const wgt = ((k & 1) ? fx : 1 - fx) * ((k >> 1) ? fy : 1 - fy); + sw += wgt; + sz += wgt * v; + } + return sw > 1e-6 ? (sz / sw) * 0.001 : null; +} + +// Ban do occupancy -> mot mat phang co texture, dat o san -- UON theo do cao +// san khi ban do co (che do doc): mat doc va san tang tren o dung cao do, +// khong nam bep o z = 0 duoi tuong voxel. function v3dSetMap(map) { if (!V3D.ready || !map || !map.w || !map.h) return; - if (V3D.mapKey === map.version) return; - V3D.mapKey = map.version; + // Khoa theo MANG O, khong theo so phien ban: khung JSON mang phien ban moi + // toi TRUOC khung ban do, nen khoa theo phien ban co the chot luoi CU voi + // phien ban MOI roi khong bao gio ve lai -- ma o che do dinh vi phien ban + // chi doi khi co lien ket moi. + if (V3D.mapData === map.data) return; + V3D.mapData = map.data; const cv = document.createElement('canvas'); cv.width = map.w; cv.height = map.h; @@ -880,23 +964,57 @@ function v3dSetMap(map) { tex.magFilter = THREE.NearestFilter; tex.minFilter = THREE.LinearMipmapLinearFilter; - if (V3D.mapMesh) { V3D.root.remove(V3D.mapMesh); V3D.mapMesh.geometry.dispose(); } + if (V3D.mapMesh) { + V3D.root.remove(V3D.mapMesh); + V3D.mapMesh.geometry.dispose(); + if (V3D.mapMesh.material.map) V3D.mapMesh.material.map.dispose(); + V3D.mapMesh.material.dispose(); + } const wM = map.w * map.res, hM = map.h * map.res; + const fl = map.floor ? v3dFloorFill(map.floor) : null; + let geom; + if (fl) { + // Mot dinh moi o luoi san, tran 256 doan moi chieu (ban do 100 m van + // chi ~66k dinh). + const sx = Math.max(1, Math.min(256, Math.round(wM / fl.res))); + const sy = Math.max(1, Math.min(256, Math.round(hM / fl.res))); + geom = new THREE.PlaneGeometry(wM, hM, sx, sy); + // Dinh cuc bo (x, y, z) -> sau rotation.x = -PI/2 la ROS (x, y, z) quanh + // tam mat phang: cuc bo +y = ROS +y, cuc bo +z = LEN. + const p = geom.attributes.position; + for (let i = 0; i < p.count; ++i) { + const z = v3dFloorAt(fl, map.ox + wM / 2 + p.getX(i), map.oy + hM / 2 + p.getY(i)); + p.setZ(i, z === null ? 0 : z); + } + p.needsUpdate = true; + } else { + geom = new THREE.PlaneGeometry(wM, hM); + } V3D.mapMesh = new THREE.Mesh( - new THREE.PlaneGeometry(wM, hM), + geom, new THREE.MeshBasicMaterial({ map: tex, transparent: true, depthWrite: false })); V3D.mapMesh.rotation.x = -Math.PI / 2; - // Hoi thap hon san mot chut de khong z-fight voi luoi va vanh cliff. - V3D.mapMesh.position.set(map.ox + wM / 2, -0.002, -(map.oy + hM / 2)); + // Phang: hoi thap hon san mot chut de khong z-fight voi luoi va vanh cliff. + // Uon: nang FLOOR_LIFT len tren mesh san that cua world (xem tren). + V3D.mapMesh.position.set(map.ox + wM / 2, fl ? FLOOR_LIFT : -0.002, -(map.oy + hM / 2)); + V3D.mapHasFloor = !!fl; V3D.root.add(V3D.mapMesh); } -function v3dSetPath(pts) { +// `floor` (tuy chon): luoi do cao san cua ban do -- quy dao di theo mat doc / +// tang tren thay vi chui duoi san. +function v3dSetPath(pts, floor) { if (!V3D.ready) return; if (V3D.pathLine) { V3D.root.remove(V3D.pathLine); V3D.pathLine.geometry.dispose(); } if (!pts || pts.length < 4) return; + // Quy dao luon nam sat node nen khong can lap o chua biet nhu v3dSetMap. + // Ve TREN mat ban do uon (nang FLOOR_LIFT), khong thi lop trong suot phu len + // lam quy dao mo di. const v = []; - for (let i = 0; i + 1 < pts.length; i += 2) v.push(toScene(pts[i], pts[i + 1], 0.01)); + for (let i = 0; i + 1 < pts.length; i += 2) { + const z = v3dFloorAt(floor, pts[i], pts[i + 1]); + v.push(toScene(pts[i], pts[i + 1], z === null ? 0.01 : z + FLOOR_LIFT + 0.01)); + } V3D.pathLine = new THREE.Line( new THREE.BufferGeometry().setFromPoints(v), new THREE.LineBasicMaterial({ color: 0xffb300 })); @@ -912,6 +1030,10 @@ function v3dSetPath(pts) { function v3dSetWorldVisible(on) { if (V3D.meshWorld) V3D.meshWorld.visible = on; if (V3D.worldMesh) V3D.worldMesh.visible = on; + // Mat san the gioi (z = 0) o lai lam moc khi tat the gioi -- tru khi ban do + // co do cao san: luc do no nam duoi tang tren nhu mot san sai cho (xem nua + // SLAM trong v3dRender). + if (V3D.floorMesh) V3D.floorMesh.visible = on || !V3D.mapHasFloor; } // Dat khung nhin ve mot goc chuan. @@ -989,17 +1111,21 @@ function v3dRender(canvas, follow, splitSlam) { } // Tam quay: bam theo robot neu bat, khong thi theo diem pan cua nguoi dung. - let cx = V3D.orbit.tx, cz = V3D.orbit.ty; + // Bam ca CAO DO (che do doc): o tang tren 1.5 m ma tam quay van o san duoi + // thi camera xoay quanh mot diem chui duoi chan robot. Pose 2D (khong z) + // thi robotGroup o y = 0, y het cu. + let cx = V3D.orbit.tx, cz = V3D.orbit.ty, cy = 0; if (follow && V3D.robotGroup) { cx = V3D.robotGroup.position.x + V3D.orbit.tx; cz = V3D.robotGroup.position.z + V3D.orbit.ty; + cy = V3D.robotGroup.position.y; } const o = V3D.orbit; V3D.camera.position.set( cx + o.dist * Math.cos(o.el) * Math.cos(o.az), - o.dist * Math.sin(o.el), + cy + o.dist * Math.sin(o.el), cz + o.dist * Math.cos(o.el) * Math.sin(o.az)); - V3D.camera.lookAt(cx, 0.2, cz); + V3D.camera.lookAt(cx, cy + 0.2, cz); const r = V3D.renderer; if (!splitSlam) { @@ -1038,7 +1164,10 @@ function v3dRender(canvas, follow, splitSlam) { show(hid); // --- Nua PHAI: chi SLAM, khong co the gioi --- - hid = hide([V3D.meshWorld, V3D.worldMesh]); + // Ban do co do cao san (che do doc) thi an ca mat san THE GIOI (z = 0, tu + // v3dSetGround): duoi tang tren 1.5 m no hien qua lop ban do trong suot + // nhu mot "san" sai cho -- SLAM da tu mang mat san cua no. + hid = hide([V3D.meshWorld, V3D.worldMesh, V3D.mapHasFloor ? V3D.floorMesh : null]); r.setViewport(half, 0, w - half, h); r.setScissor(half, 0, w - half, h); r.render(V3D.scene, V3D.camera); diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 4a10d96..302fc77 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -260,6 +260,15 @@ if(VSLAM_NODE_EXE AND TARGET vslam_world_export) ${CMAKE_CURRENT_SOURCE_DIR}/www/test_orbit_camera.js) set_tests_properties(www_orbit_camera PROPERTIES PASS_REGULAR_EXPRESSION "=> DAT") + # Do cao san (che do doc): khoi FLH1 sau RLE, mat phang ban do uon theo san, + # scan/cloud/quy dao nang theo z. Sai dau o phep doi truc -> doc nghieng + # nguoc, van ve duoc. Kem: mat san the gioi KHONG dung lai moi khung (ban + # cu ro ~1 geometry GPU moi khung khi chay tu `.world`). + add_test(NAME www_map_floor + COMMAND ${VSLAM_NODE_EXE} + ${CMAKE_CURRENT_SOURCE_DIR}/www/test_map_floor.js) + set_tests_properties(www_map_floor PROPERTIES + PASS_REGULAR_EXPRESSION "=> DAT") else() message(STATUS "vslam: khong tim thay `node` -- bo qua bai kiem frontend") endif() diff --git a/test/test_binary_codec.cc b/test/test_binary_codec.cc index da767bb..30845fd 100644 --- a/test/test_binary_codec.cc +++ b/test/test_binary_codec.cc @@ -129,6 +129,60 @@ TEST(BinaryCodec, MapFullNenTotTrenBanDoThua) { EXPECT_EQ(out.data, m.data); } +// Che do doc: khoi do cao san noi sau RLE. Phan luoi 2D phai giai y het khung +// khong co khoi (client cu bo qua duoi khung), va khoi giu dung tung o, ke ca +// o CHUA BIET va gia tri am (tang ham). +TEST(BinaryCodec, MapFullKhoiDoCaoSan) { + OccupancyGrid m; + m.width = 40; + m.height = 30; + m.resolution = 0.05f; + m.origin.position.x = -1.25; + m.origin.position.y = -2.5; + m.data.assign(static_cast(m.width) * m.height, -1); + for (uint32_t x = 5; x < 35; ++x) m.data[10 * m.width + x] = 100; + + MapFloorGrid f; + f.resolution = 0.2f; + f.width = 10; + f.height = 8; + f.origin_x = -1.25f; + f.origin_y = -2.5f; + f.mm.assign(80, kFloorUnknown); + f.mm[0] = 0; + f.mm[17] = 1500; + f.mm[79] = -320; + + std::string plain, with_floor; + EncodeMapFull(m, UnixTime::fromSec(2.0), &plain); + EncodeMapFull(m, UnixTime::fromSec(2.0), &with_floor, BinaryType::kMapFull, &f); + ASSERT_EQ(with_floor.size(), plain.size() + 24 + 80 * 2); + EXPECT_EQ(with_floor.compare(0, plain.size(), plain), 0); + + OccupancyGrid out; + MapFloorGrid fout; + ASSERT_TRUE(DecodeMapFull(with_floor, &out, &fout)); + EXPECT_EQ(out.data, m.data); + EXPECT_EQ(fout.width, f.width); + EXPECT_EQ(fout.height, f.height); + EXPECT_NEAR(fout.resolution, f.resolution, 1e-6); + EXPECT_NEAR(fout.origin_x, f.origin_x, 1e-6); + EXPECT_NEAR(fout.origin_y, f.origin_y, 1e-6); + EXPECT_EQ(fout.mm, f.mm); + + // Khung khong co khoi: luoi san tra ve rong, khong phai rac cua lan truoc. + ASSERT_TRUE(DecodeMapFull(plain, &out, &fout)); + EXPECT_EQ(fout.width, 0u); + EXPECT_TRUE(fout.mm.empty()); + + // Kich thuoc sai (mm thieu o) -> khong ghi khoi, khung y het ban phang. + MapFloorGrid bad = f; + bad.mm.pop_back(); + std::string with_bad; + EncodeMapFull(m, UnixTime::fromSec(2.0), &with_bad, BinaryType::kMapFull, &bad); + EXPECT_EQ(with_bad, plain); +} + // --- Ban do voxel 3D ------------------------------------------------------- namespace { diff --git a/test/test_global_localizer.cc b/test/test_global_localizer.cc index aa91a11..0bec6bc 100644 --- a/test/test_global_localizer.cc +++ b/test/test_global_localizer.cc @@ -261,6 +261,292 @@ TEST(GlobalLocalizer, PhongDoiXungQuay180ChanOCongHuong) { EXPECT_EQ(Decide(m, 5, cfg), RelocVerdict::kAmbiguousYaw); } +// --- Bang chung ngoai LiDAR (`admit`) ------------------------------------- +// +// Tren doc, do nghieng IMU noi robot dang chuc bao nhieu, ve phia nao; ban do +// biet doc o dau. Hai test dau la hai ca LiDAR nhap nhang o tren -- bang chung +// ngoai phai PHAN XU dung. Hai test sau khoa phan an toan: khong bao gio day +// mot khop LiDAR kem ro len thang, va bang chung "cai gi cung duoc" khong lam +// lech nguoi thang. + +TEST(GlobalLocalizer, BangChungNgoaiTachHaiPhongGiongHet) { + OccupancyGrid g = MakeGrid(24.0, 10.0); + AsymRoom(&g, 0.0, 0.0); + AsymRoom(&g, 12.0, 0.0); + const LikelihoodField f = LikelihoodField::FromGrid(g, 0.15); + const GlobalLocalizerConfig cfg; + + const Pose2D truth = kAsymTruth; + const Pose2D odom{-1.0, 0.5, -0.3}; + const std::vector pts = ToOdom(Raycast(g, truth), odom); + // Vd phong phai la san doc ma IMU do phang: robot KHONG the o do. + const RelocAdmit admit = [&](const Pose2D& T) { return Pose2DCompose(T, odom).x < 12.0; }; + + const RelocMatch m = GlobalMatch(f, pts, cfg, admit); + ASSERT_TRUE(m.ok); + EXPECT_TRUE(m.tilt_used); + EXPECT_FALSE(m.tilt_conflict); + EXPECT_GT(m.tilt_rejected, 0); + const Pose2D est = Pose2DCompose(m.map_from_odom, odom); + EXPECT_LT(std::hypot(est.x - truth.x, est.y - truth.y), 0.1); + EXPECT_LT(std::fabs(AngleDiff(est.theta, truth.theta)) * 180.0 / M_PI, 1.0); + EXPECT_EQ(Decide(m, cfg.min_cycles, cfg), RelocVerdict::kAccept) + << "ty le " << m.ratio() << ", ty le huong " << m.ratio_yaw(); + for (const RelocHypothesis& h : m.hyps) { + EXPECT_LT(Pose2DCompose(h.map_from_odom, odom).x, 12.0) << "gia thuyet bi loai van tra ve"; + } +} + +TEST(GlobalLocalizer, BangChungNgoaiChonHuongPhongDoiXung) { + // Phong doi xung quay 180 do: LiDAR khong biet huong (PhongDoiXungQuay180...). + // Bang chung chi nhan nua huong quanh `want` -> ra DUNG `want`, ca hai chieu: + // chinh bang chung quyet dinh, khong phai may rui. + OccupancyGrid g = MakeGrid(9.0, 6.0); + Room(&g, 0.5, 0.5, 8.5, 5.5); + const LikelihoodField f = LikelihoodField::FromGrid(g, 0.15); + const GlobalLocalizerConfig cfg; + + const Pose2D truth{4.5, 3.0, 0.3}; + const Pose2D odom{-1.0, 0.5, -0.3}; + const std::vector pts = ToOdom(Raycast(g, truth), odom); + for (const double want : {truth.theta, truth.theta + M_PI}) { + const RelocAdmit admit = [&](const Pose2D& T) { + return std::fabs(AngleDiff(Pose2DCompose(T, odom).theta, want)) < M_PI / 2; + }; + const RelocMatch m = GlobalMatch(f, pts, cfg, admit); + ASSERT_TRUE(m.ok); + const Pose2D est = Pose2DCompose(m.map_from_odom, odom); + EXPECT_LT(std::fabs(AngleDiff(est.theta, want)) * 180.0 / M_PI, 1.0) << "want " << want; + EXPECT_LT(std::hypot(est.x - truth.x, est.y - truth.y), 0.1); + EXPECT_GE(m.ratio_yaw(), cfg.min_ratio_yaw) << "doi thu huong (lat 180) chua bi loai"; + EXPECT_NE(Decide(m, cfg.min_cycles, cfg), RelocVerdict::kAmbiguousYaw); + } +} + +TEST(GlobalLocalizer, BangChungMauThuanLiDARChacThiGiuLiDAR) { + // Phong KHONG doi xung: LiDAR chac chan. Bang chung noi "khong the o do" + // (vd IMU hong) -- KHONG duoc day mot cho kem han len thang. Ket qua phai y + // het khi khong co bang chung, va danh dau xung dot. + OccupancyGrid g = MakeGrid(12.0, 10.0); + AsymRoom(&g, 0.0, 0.0); + const LikelihoodField f = LikelihoodField::FromGrid(g, 0.15); + const GlobalLocalizerConfig cfg; + + const Pose2D truth = kAsymTruth; + const Pose2D odom{-1.0, 0.5, -0.3}; + const std::vector pts = ToOdom(Raycast(g, truth), odom); + const RelocMatch base = GlobalMatch(f, pts, cfg); + const RelocAdmit admit = [&](const Pose2D& T) { + const Pose2D p = Pose2DCompose(T, odom); + return std::hypot(p.x - truth.x, p.y - truth.y) > 1.5; + }; + const RelocMatch m = GlobalMatch(f, pts, cfg, admit); + ASSERT_TRUE(m.ok); + EXPECT_TRUE(m.tilt_conflict); + EXPECT_FALSE(m.tilt_used); + EXPECT_NEAR(m.map_from_odom.x, base.map_from_odom.x, 1e-9); + EXPECT_NEAR(m.map_from_odom.y, base.map_from_odom.y, 1e-9); + EXPECT_NEAR(m.map_from_odom.theta, base.map_from_odom.theta, 1e-9); + EXPECT_DOUBLE_EQ(m.s1, base.s1); + EXPECT_DOUBLE_EQ(m.s2, base.s2); + EXPECT_DOUBLE_EQ(m.s2_yaw, base.s2_yaw); +} + +TEST(GlobalLocalizer, BangChungChapNhanHetKhongLechNguoiThang) { + // San phang + IMU phang: moi gia thuyet hop le. Nguoi thang va cong phai + // nhu cu; ung vien them chi co the lam doi thu MANH hon (than trong hon). + OccupancyGrid g = MakeGrid(12.0, 10.0); + AsymRoom(&g, 0.0, 0.0); + const LikelihoodField f = LikelihoodField::FromGrid(g, 0.15); + const GlobalLocalizerConfig cfg; + + const Pose2D truth = kAsymTruth; + const Pose2D odom{-1.0, 0.5, -0.3}; + const std::vector pts = ToOdom(Raycast(g, truth), odom); + const RelocMatch base = GlobalMatch(f, pts, cfg); + const RelocMatch m = GlobalMatch(f, pts, cfg, [](const Pose2D&) { return true; }); + ASSERT_TRUE(m.ok); + EXPECT_FALSE(m.tilt_used); + EXPECT_FALSE(m.tilt_conflict); + const Pose2D a = Pose2DCompose(base.map_from_odom, odom); + const Pose2D b = Pose2DCompose(m.map_from_odom, odom); + EXPECT_LT(std::hypot(a.x - b.x, a.y - b.y), 0.01); + EXPECT_LT(std::fabs(AngleDiff(a.theta, b.theta)), 0.002); + EXPECT_LE(m.ratio(), base.ratio() + 1e-9); + EXPECT_EQ(Decide(m, cfg.min_cycles, cfg), Decide(base, cfg.min_cycles, cfg)); +} + +TEST(GlobalLocalizer, SuyBienDocTrucHanhLangVaPhong) { + // Hanh lang dai 20 m chi co hai tuong song song: dich doc hanh lang khong + // lam xau khop (~100%). Phong khong doi xung: dich 1 m thi tut ro. Day la + // kiem chan chot nho do nghieng (sim: doc 30 do, chot lech 0.77 m doc lan). + OccupancyGrid g = MakeGrid(24.0, 6.0); + Fill(&g, 0.0, 1.5, 24.0, 4.5, 0); + Fill(&g, 0.0, 1.5, 24.0, 1.6, 100); + Fill(&g, 0.0, 4.4, 24.0, 4.5, 100); + const LikelihoodField fc = LikelihoodField::FromGrid(g, 0.15); + const Pose2D in_corridor{12.0, 3.0, 0.2}; + const Pose2D odom{-1.0, 0.5, -0.3}; + // T_map_odom dung = truth o (-) odom. + auto T_of = [&](const Pose2D& truth) { return Pose2DCompose(truth, Pose2DInverse(odom)); }; + const double rc = + ShiftScoreRatio(fc, ToOdom(Raycast(g, in_corridor, 720, 6.0), odom), T_of(in_corridor), 1.0); + EXPECT_GT(rc, 0.95) << "hanh lang ma dich doc truc lai tut diem"; + + OccupancyGrid r = MakeGrid(12.0, 10.0); + AsymRoom(&r, 0.0, 0.0); + const LikelihoodField fr = LikelihoodField::FromGrid(r, 0.15); + const double rr = + ShiftScoreRatio(fr, ToOdom(Raycast(r, kAsymTruth), odom), T_of(kAsymTruth), 1.0); + EXPECT_GT(rr, 0.0); + EXPECT_LT(rr, 0.9) << "phong co dac diem ma dich 1 m van giu diem"; +} + +// --- Vong DUNG YEN (DecideStatic) --- +// +// Dung yen thi cac vong nhin gan y het: thu mai roi chot o vong VOT qua cong +// la dao nhieu. Sim 2026-10-05 da lot hai lan: chot vong le (1.63 sau 21 vong +// ~1.44), roi trung vi 3 vong (1.63 / 1.40 / 1.64). Luat: NHO NHAT qua moi vong +// cung cho. +namespace { +StaticRound Round(double x, double ratio, double yaw = 3.5, double shift = 0.85) { + StaticRound r; + r.robot = Pose2D{x, 23.0, 1.67}; + r.map_from_odom = r.robot; // odom trung map trong test + r.ratio = ratio; + r.ratio_yaw = yaw; + r.shift = shift; + return r; +} +} // namespace + +TEST(GlobalLocalizer, DungYenKhongDaoNhieu) { + const GlobalLocalizerConfig cfg; + std::vector h; + bool ax = false; + std::string why; + // Doi thu that (~1.44) chi bi bo sot o vai vong -> KHONG bao gio chot. + for (const double r : {1.63, 1.40, 1.64, 1.63, 1.65, 1.62, 1.64}) { + EXPECT_NE(DecideStatic(&h, Round(1.2, r), {}, cfg, true, &ax, &why), RelocVerdict::kAccept) + << "vong " << h.size() << ": " << why; + } +} + +TEST(GlobalLocalizer, DungYenDuVongDeuCaoThiChot) { + const GlobalLocalizerConfig cfg; + std::vector h; + bool ax = false; + std::string why; + EXPECT_EQ(DecideStatic(&h, Round(1.2, 1.64), {}, cfg, true, &ax, &why), RelocVerdict::kNeedCycles); + EXPECT_EQ(DecideStatic(&h, Round(1.21, 1.95), {}, cfg, true, &ax, &why), RelocVerdict::kNeedCycles); + EXPECT_EQ(DecideStatic(&h, Round(1.19, 1.96), {}, cfg, true, &ax, &why), RelocVerdict::kAccept) << why; + EXPECT_FALSE(ax); +} + +TEST(GlobalLocalizer, DungYenDoiNguoiThangThiDemLai) { + const GlobalLocalizerConfig cfg; + std::vector h; + bool ax = false; + std::string why; + DecideStatic(&h, Round(1.2, 2.0), {}, cfg, true, &ax, &why); + DecideStatic(&h, Round(1.2, 2.0), {}, cfg, true, &ax, &why); + // Vong 3 ra cho khac (cach 1 m) -> dem lai tu dau, chua du vong. + EXPECT_EQ(DecideStatic(&h, Round(2.2, 2.0), {}, cfg, true, &ax, &why), RelocVerdict::kNeedCycles); + EXPECT_EQ(h.size(), 1u); +} + +TEST(GlobalLocalizer, DungYenChanMuDocTrucVaNhapNhang) { + const GlobalLocalizerConfig cfg; + bool ax = false; + std::string why; + { + // Mot vong mu doc truc (dich 1 m giu 100%) la du chan, ke ca ty le cao. + std::vector h; + DecideStatic(&h, Round(1.2, 2.0), {}, cfg, true, &ax, &why); + DecideStatic(&h, Round(1.2, 2.0, 3.5, 1.0), {}, cfg, true, &ax, &why); + EXPECT_EQ(DecideStatic(&h, Round(1.2, 2.0), {}, cfg, true, &ax, &why), RelocVerdict::kAmbiguous); + EXPECT_TRUE(ax); + // Khong ap kiem doc truc (vd khong co bang chung nghieng) -> qua. + std::vector h2 = h; + h2.pop_back(); + EXPECT_EQ(DecideStatic(&h2, Round(1.2, 2.0), {}, cfg, false, &ax, &why), RelocVerdict::kAccept); + } + { + std::vector h; + for (int i = 0; i < 3; ++i) DecideStatic(&h, Round(1.2, 2.0, 1.1), {}, cfg, true, &ax, &why); + EXPECT_EQ(DecideStatic(&h, Round(1.2, 2.0, 1.1), {}, cfg, true, &ax, &why), + RelocVerdict::kAmbiguousYaw); + } + { + std::vector h; + for (int i = 0; i < 3; ++i) DecideStatic(&h, Round(1.2, 1.2), {}, cfg, true, &ax, &why); + EXPECT_EQ(DecideStatic(&h, Round(1.2, 1.2), {}, cfg, true, &ax, &why), RelocVerdict::kAmbiguous); + EXPECT_FALSE(ax); + } +} + +// Hai cho (truoc / sau khi bo tren doc). Robot di 0.5 m nen pose robot doi, +// nhung T_map_odom cua CUNG gia thuyet giu nguyen. +namespace { +StaticRound Placed(double y, double ratio, const Pose2D& T) { + StaticRound r; + r.robot = Pose2D{1.2, y, 1.67}; + r.map_from_odom = T; + r.ratio = ratio; + r.ratio_yaw = 3.5; + r.shift = 0.85; + return r; +} +// Chay cac vong o mot cho; tra verdict vong cuoi. +RelocVerdict AtPlace(std::vector* h, const std::vector& prev, double y, + const Pose2D& T, std::initializer_list ratios, std::string* why) { + const GlobalLocalizerConfig cfg; + bool ax = false; + RelocVerdict v = RelocVerdict::kFailed; + for (const double r : ratios) v = DecideStatic(h, Placed(y, r, T), prev, cfg, true, &ax, why); + return v; +} +} // namespace + +TEST(GlobalLocalizer, HaiChoCungPoseMoiChoDeuQuaThiChot) { + // Sim: gan dinh doc 5 do, cho 1 ty le 1.57-1.60 (duoi chuan mot cho 1.60), + // bo 0.5 m, cho 2 ~1.49 -> hai cho cung pose, moi cho deu >= 1.30 -> chot. + const Pose2D T{0.1, -0.2, 0.05}; + std::vector h; + std::vector places; + std::string why; + EXPECT_NE(AtPlace(&h, places, 23.0, T, {1.57, 1.60, 1.58}, &why), RelocVerdict::kAccept) << why; + places.push_back(SummarizePlace(h)); + h.clear(); + EXPECT_EQ(AtPlace(&h, places, 23.5, T, {1.49}, &why), RelocVerdict::kNeedCycles) << "1 vong chua du"; + EXPECT_EQ(AtPlace(&h, places, 23.5, T, {1.47, 1.50}, &why), RelocVerdict::kAccept) << why; +} + +TEST(GlobalLocalizer, HaiChoMaMotChoTungTutThiKhongChot) { + // Dung kieu chot SAI o chan doc 10 / 15 do: nguoi thang sai on dinh, ty le + // 1.0-1.2 roi mot vong nhay 1.32. Moi cho phai qua o MOI vong cua no. + const Pose2D T{0.1, -0.2, 0.05}; + std::vector h; + std::vector places; + std::string why; + AtPlace(&h, places, 9.0, T, {1.05, 1.19, 1.32}, &why); + places.push_back(SummarizePlace(h)); + h.clear(); + EXPECT_NE(AtPlace(&h, places, 8.5, T, {1.32, 1.34, 1.31}, &why), RelocVerdict::kAccept) << why; +} + +TEST(GlobalLocalizer, HaiChoKhacGiaThuyetThiKhongChot) { + // Hai cho deu qua 1.30 nhung chi ve HAI pose khac nhau (T lech 0.5 m) -> khong chot. + std::vector h; + std::vector places; + std::string why; + AtPlace(&h, places, 23.0, Pose2D{0.1, -0.2, 0.05}, {1.5, 1.5, 1.5}, &why); + places.push_back(SummarizePlace(h)); + h.clear(); + EXPECT_NE(AtPlace(&h, places, 23.5, Pose2D{0.1, 0.3, 0.05}, {1.5, 1.5, 1.5}, &why), + RelocVerdict::kAccept) << why; +} + TEST(GlobalLocalizer, DiemCanhLacTutKhiPoseSai) { OccupancyGrid g = MakeGrid(12.0, 10.0); AsymRoom(&g, 0.0, 0.0); diff --git a/test/test_height_map.cc b/test/test_height_map.cc index 7a5114d..d1364a7 100644 --- a/test/test_height_map.cc +++ b/test/test_height_map.cc @@ -97,3 +97,37 @@ TEST(FloorModel, RollNghiengSangTrai) { ASSERT_TRUE(fm.FloorAt(-1.0, 0.0, &z)); EXPECT_NEAR(z, std::tan(5 * kDeg), 1e-6); } + +// Do doc san + do lech nghieng: nen cua viec loai gia thuyet dinh vi lai tren +// doc (GlobalMatch + `admit`). Sai dau o day thi bo loc loai DUNG cho that. +TEST(FloorModel, DoDocVaDoLechNghieng) { + // Doc 15 do di LEN theo +y cua map (node huong +y, mui ngoc = pitch am). + std::vector nodes(1); + nodes[0].theta = M_PI / 2; + nodes[0].pitch = -15 * kDeg; + FloorModel fm; + fm.Build(nodes); + double gx = 0, gy = 0; + ASSERT_TRUE(FloorGradientAt(fm, 0.3, 0.2, 1.5, &gx, &gy)); + EXPECT_NEAR(gx, 0.0, 1e-9); + EXPECT_NEAR(gy, std::tan(15 * kDeg), 1e-9); + // Node xa hon max_dist -> khong biet san o do. + EXPECT_FALSE(FloorGradientAt(fm, 3.0, 0.0, 1.5, &gx, &gy)); + + const double t15 = std::tan(15 * kDeg); + // Robot mui LEN doc (yaw +y) do duoc pitch -15: khop. + EXPECT_NEAR(TiltResidual(0.0, -15 * kDeg, M_PI / 2, 0.0, t15), 0.0, 1e-9); + // Cung do nghieng nhung gia thuyet mui XUONG doc (lat 180 do): lech 2 lan doc. + EXPECT_NEAR(TiltResidual(0.0, -15 * kDeg, -M_PI / 2, 0.0, t15), 2 * t15, 1e-9); + // Gia thuyet o san PHANG: lech dung bang doc do duoc. + EXPECT_NEAR(TiltResidual(0.0, -15 * kDeg, 0.3, 0.0, 0.0), t15, 1e-9); + // Mui NGANG doc (yaw +x, doc len ve +y = ben TRAI): roll duong, pitch 0. + const double roll = std::atan(t15); // cos(pitch) = 1 + EXPECT_NEAR(TiltResidual(roll, 0.0, 0.0, 0.0, t15), 0.0, 1e-9); + EXPECT_NEAR(TiltResidual(-roll, 0.0, 0.0, 0.0, t15), 2 * t15, 1e-9); + // Than nghieng ca hai truc (mui len doc cheo 45 do): van khop khi dung huong. + const double g = 0.2; // doc theo +y + const double sf = g * std::sin(M_PI / 4), sl = g * std::cos(M_PI / 4); + const double p = -std::atan(sf), r = std::atan(sl * std::cos(p)); + EXPECT_NEAR(TiltResidual(r, p, M_PI / 4, 0.0, g), 0.0, 1e-9); +} diff --git a/test/www/test_map_floor.js b/test/www/test_map_floor.js new file mode 100644 index 0000000..270e334 --- /dev/null +++ b/test/www/test_map_floor.js @@ -0,0 +1,405 @@ +// Do cao SAN cua ban do SLAM (che do doc): giai khoi FLH1 o app.js, uon mat +// phang ban do va nang scan/cloud/quy dao o app3d.js. +// +// ================== VI SAO CAN BAI KIEM NAY ================== +// Mat phang ban do 2D ve phang o z = 0 trong khi tuong voxel o z that: tren +// tang cao 1.5 m nguoi xem thay tuong lo lung con san "thung" xuong tang duoi. +// Sai mot dau trong phep doi truc cuc bo -> ROS (PlaneGeometry quay -PI/2 +// quanh X) thi doc nghieng NGUOC chieu -- van ve duoc, khong mot loi nao. + +const fs = require('fs'); +const path = require('path'); +const vm = require('vm'); + +const WWW = path.join(__dirname, '..', '..', 'libs', 'vslam_web', 'www'); +let bad = 0; +function check(name, cond, chiTiet) { + if (cond) return; + bad++; + console.log(` ${name}: HONG${chiTiet ? ' -- ' + chiTiet : ''}`); +} +const near = (a, b, tol) => a !== null && Math.abs(a - b) <= tol; + +// --- Khung ban do y het binary_codec.cc EncodeMapFull ---------------------- +// Luoi 2D 0.05 m, 40 x 20 o, mot run duy nhat (toan o trong = 0). +const MAP = { res: 0.05, w: 40, h: 20, ox: -1.0, oy: 2.0 }; +// Luoi san 0.2 m phu cung khung: 10 x 5 o. Doc 1 m/1 m theo +x tu cot 2 toi +// cot 7 (z = 0 .. 1.0), san tren 1.5 m o cot 8-9; hang 4 chua biet. Mot HO +// -0.1 m o goc tay-nam (hang 0, cot 0-1) de bat loi lat chieu y. +const FL = { res: 0.2, w: 10, h: 5 }; +function floorMm(c, r) { + if (r === 4) return -32768; + if (c >= 8) return 1500; + if (c < 2) return r === 0 ? -100 : 0; + return Math.round((c - 2) * 200); // tam o: doc 45 do de so de doc +} + +function mapFrame(withFloor) { + const n = MAP.w * MAP.h; + const runs = Math.ceil(n / 65535); + const tail = withFloor ? 24 + FL.w * FL.h * 2 : 0; + const buf = new ArrayBuffer(16 + 28 + runs * 3 + tail); + const dv = new DataView(buf); + dv.setUint8(0, 0x56); dv.setUint8(1, 0x53); dv.setUint8(2, 0x4C); dv.setUint8(3, 0x31); + dv.setUint8(4, 3); + dv.setUint8(5, 1); + let o = 16; + dv.setFloat32(o, MAP.res, true); + dv.setInt32(o + 4, MAP.w, true); + dv.setInt32(o + 8, MAP.h, true); + dv.setFloat32(o + 12, MAP.ox, true); + dv.setFloat32(o + 16, MAP.oy, true); + dv.setFloat32(o + 20, 0, true); + dv.setUint32(o + 24, runs, true); + o += 28; + dv.setUint16(o, n, true); + dv.setInt8(o + 2, 0); + o += 3; + if (withFloor) { + 'FLH1'.split('').forEach((ch, i) => dv.setUint8(o + i, ch.charCodeAt(0))); + dv.setFloat32(o + 4, FL.res, true); + dv.setInt32(o + 8, FL.w, true); + dv.setInt32(o + 12, FL.h, true); + dv.setFloat32(o + 16, MAP.ox, true); + dv.setFloat32(o + 20, MAP.oy, true); + for (let r = 0; r < FL.h; ++r) { + for (let c = 0; c < FL.w; ++c) { + dv.setInt16(o + 24 + (r * FL.w + c) * 2, floorMm(c, r), true); + } + } + } + return dv; +} + +// --- Phan 1: app.js giai khoi ---------------------------------------------- +const el = () => ({ + textContent: '', className: '', value: '', checked: false, style: {}, + width: 0, height: 0, clientWidth: 800, clientHeight: 600, + addEventListener() {}, getContext: () => ctx2d(), classList: { toggle() {}, add() {}, remove() {} }, + appendChild() {}, querySelectorAll: () => [], getBoundingClientRect: () => + ({ left: 0, top: 0, width: 800, height: 600 }), +}); +const ctx2d = () => new Proxy({}, { + get: (t, k) => (k === 'canvas' ? el() : () => ({ data: new Uint8ClampedArray(4) })), +}); +const ws = { readyState: 1, send() {} }; +const sbApp = { + console, Date, Math, JSON, Set, Map, Number, String, Array, Object, + Float32Array, Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, + DataView, ArrayBuffer, isNaN, parseFloat, parseInt, + document: { + getElementById: () => el(), querySelectorAll: () => [], querySelector: () => el(), + addEventListener() {}, createElement: () => el(), body: el(), documentElement: el(), + }, + window: { addEventListener() {}, devicePixelRatio: 1, location: { search: '', host: 'x' } }, + location: { search: '', host: 'x', protocol: 'http:' }, + navigator: { userAgent: 'node' }, + requestAnimationFrame: () => 0, + setInterval: () => 0, setTimeout: () => 0, clearTimeout: () => 0, + fetch: () => new Promise(() => {}), + URLSearchParams: class { constructor() {} get() { return null; } }, + WebSocket: function () { return ws; }, + performance: { now: () => 0 }, + // rasterize() cua app.js dung ImageData khi nhan khung ban do. + ImageData: function (w, h) { this.width = w; this.height = h; + this.data = new Uint8ClampedArray(w * h * 4); }, +}; +sbApp.globalThis = sbApp; +vm.createContext(sbApp); +try { + vm.runInContext(fs.readFileSync(path.join(WWW, 'app.js'), 'utf8'), sbApp, { filename: 'app.js' }); +} catch (e) { + console.log(' (app.js dung som: ' + e.message + ')'); +} +let state = null; +try { state = vm.runInContext('state', sbApp); } catch (e) { /* bao o duoi */ } +if (typeof sbApp.onBinary !== 'function' || !state) { + console.log(' KHONG lay duoc onBinary/state tu app.js\n\n => HONG'); + process.exit(1); +} + +sbApp.onBinary(mapFrame(true)); +const g = state.map; +check('giai: co ban do', g && g.w === MAP.w && g.h === MAP.h); +const f = g && g.floor; +check('giai: co khoi san', f && f.w === FL.w && f.h === FL.h, JSON.stringify(f && { w: f.w, h: f.h })); +if (f) { + check('giai: res/goc', Math.abs(f.res - 0.2) < 1e-6 && Math.abs(f.ox - MAP.ox) < 1e-6 && + Math.abs(f.oy - MAP.oy) < 1e-6); + check('giai: san tren', f.mm[2 * FL.w + 9] === 1500, String(f.mm[2 * FL.w + 9])); + check('giai: o chua biet', f.mm[4 * FL.w + 3] === -32768, String(f.mm[4 * FL.w + 3])); +} +// Luoi 2D khong bi khoi phia sau lam lech. +check('giai: o 2D dung', g && g.cells.every((v) => v === 0)); + +sbApp.onBinary(mapFrame(false)); +check('khong khoi: floor = null', state.map && state.map.floor === null); + +// --- Phan 2: app3d.js uon mat phang + nang scan/cloud/quy dao -------------- +class V3 { + constructor(x, y, z) { this.x = x || 0; this.y = y || 0; this.z = z || 0; } + set(x, y, z) { this.x = x; this.y = y; this.z = z; return this; } +} +const node = () => ({ position: new V3(), rotation: { x: 0, y: 0, z: 0 }, userData: {}, + visible: true }); +class Attr { + constructor(a, n) { this.array = a; this.itemSize = n; this.count = a.length / n; } + getX(i) { return this.array[i * 3]; } + getY(i) { return this.array[i * 3 + 1]; } + setZ(i, v) { this.array[i * 3 + 2] = v; } +} +// Bo cuc dinh y het three.js PlaneGeometry: hang tu +h/2 xuong -h/2, cot tu +// -w/2 sang +w/2, mat phang z = 0. +class PlaneGeometry { + constructor(w, h, sx = 1, sy = 1) { + const a = []; + for (let iy = 0; iy <= sy; ++iy) { + for (let ix = 0; ix <= sx; ++ix) a.push(ix * w / sx - w / 2, -(iy * h / sy - h / 2), 0); + } + this.attributes = { position: new Attr(new Float32Array(a), 3) }; + } + dispose() {} +} +class BufferGeometry { + constructor() { this.attributes = {}; } + setAttribute(n, a) { this.attributes[n] = a; } + setFromPoints(p) { this.points = p; return this; } + dispose() {} +} +const obj = () => class { + constructor(g, m) { Object.assign(this, node()); this.geometry = g; this.material = m; } +}; +const THREE = { + PlaneGeometry, BufferGeometry, Vector3: V3, + BufferAttribute: class { constructor(a, n) { this.array = a; this.itemSize = n; } }, + Mesh: obj(), Points: obj(), Line: obj(), + MeshBasicMaterial: class { constructor(o) { Object.assign(this, o); } dispose() {} }, + PointsMaterial: class { constructor(o) { Object.assign(this, o); } }, + LineBasicMaterial: class { constructor(o) { Object.assign(this, o); } }, + CanvasTexture: class { dispose() {} }, + NearestFilter: 1, LinearMipmapLinearFilter: 2, +}; +class Root { + constructor() { this.children = []; } + add(c) { this.children.push(c); } + remove(c) { this.children = this.children.filter((x) => x !== c); } +} +const canvas = () => ({ + width: 0, height: 0, + getContext: () => ({ + createImageData: (w, h) => ({ data: new Uint8ClampedArray(w * h * 4) }), + putImageData() {}, + }), +}); +const sb3 = { THREE, console, Math, Int16Array, Int32Array, Float32Array, + window: {}, document: { createElement: canvas } }; +vm.createContext(sb3); +vm.runInContext(fs.readFileSync(path.join(WWW, 'app3d.js'), 'utf8') + + '\n;this.__V3D = V3D; this.__at = v3dFloorAt; this.__fill = v3dFloorFill;' + + '\n;this.__map = v3dSetMap; this.__scan = v3dSetScan; this.__cloud = v3dSetCloud;' + + '\n;this.__path = v3dSetPath; this.__render = v3dRender; this.__lift = FLOOR_LIFT;' + + '\n;this.__worldVis = v3dSetWorldVisible; this.__ground = v3dSetGround;', sb3); +const V3D = sb3.__V3D; +V3D.ready = true; +V3D.root = new Root(); +const L = sb3.__lift; // mat ban do uon nang len tren san uoc luong +check('nang: 2-10 cm', L >= 0.02 && L <= 0.1, String(L)); + +// v3dFloorAt: tam o tra dung gia tri o; giua hai tam noi suy tuyen tinh. +{ + const fl = f; + const cx = (c) => MAP.ox + (c + 0.5) * 0.2, cy = (r) => MAP.oy + (r + 0.5) * 0.2; + check('at: tam o san duoi', near(sb3.__at(fl, cx(0), cy(1)), 0.0, 1e-6)); + check('at: tam o san tren', near(sb3.__at(fl, cx(9), cy(1)), 1.5, 1e-6)); + // Giua tam cot 4 (0.4) va cot 5 (0.6) -> 0.5. + check('at: noi suy tren doc', near(sb3.__at(fl, cx(4) + 0.1, cy(1)), 0.5, 1e-6), + String(sb3.__at(fl, cx(4) + 0.1, cy(1)))); + // Chi o chua biet -> null (khong phai 0). + check('at: chua biet = null', sb3.__at(fl, cx(3), cy(4)) === null, + String(sb3.__at(fl, cx(3), cy(4)))); + check('at: ngoai luoi = null', sb3.__at(fl, MAP.ox - 5, cy(1)) === null); + check('at: khong co luoi = null', sb3.__at(null, 0, 0) === null); + + // Lap o chua biet bang o DA BIET gan nhat: hang 4 lay hang 3. + const filled = sb3.__fill(fl); + check('fill: khong con o chua biet', filled && filled.mm.every((v) => v !== -32768)); + check('fill: lay o ke', filled && filled.mm[4 * FL.w + 9] === 1500 && + filled.mm[4 * FL.w + 4] === 400, filled && String(filled.mm.slice(40))); + check('fill: khong dong vao luoi goc', fl.mm[4 * FL.w + 9] === -32768); +} + +// v3dSetMap: dinh mat phang o dung cao do san, dung chieu doc. +{ + sb3.__map({ ...g, data: g.cells, floor: f }); + const m = V3D.mapMesh; + check('map: co mesh', !!m); + if (m) { + check('map: quay -PI/2 quanh X', Math.abs(m.rotation.x + Math.PI / 2) < 1e-9); + const p = m.geometry.attributes.position; + check('map: chia doan theo luoi san', p.count === (FL.w + 1) * (FL.h + 1), String(p.count)); + // Dinh cuc bo -> ROS: x = pos.x + lx, y = -pos.z + ly, z = pos.y + lz. + const ros = (i) => [m.position.x + p.getX(i), -m.position.z + p.getY(i), + m.position.y + p.array[i * 3 + 2]]; + const zAt = (qx, qy) => { + for (let i = 0; i < p.count; ++i) { + const [x, y, z] = ros(i); + if (Math.abs(x - qx) < 1e-4 && Math.abs(y - qy) < 1e-4) return z; + } + return null; + }; + let maxEast = -1e9, maxWest = -1e9; + for (let i = 0; i < p.count; ++i) { + const [x, , z] = ros(i); + if (x > MAP.ox + 1.9) maxEast = Math.max(maxEast, z); + if (x < MAP.ox + 0.1) maxWest = Math.max(maxWest, z); + } + // Ca mat nang L tren san uoc luong (khong chim duoi mesh san that). + check('map: nang L', Math.abs(m.position.y - L) < 1e-9, String(m.position.y)); + check('map: co co mapHasFloor', V3D.mapHasFloor === true); + // Chieu x: mep dong (cot 9, san tren) ~1.5; mep tay (san duoi) ~0. + check('map: mep dong o san tren', Math.abs(maxEast - (1.5 + L)) < 0.01, String(maxEast)); + check('map: mep tay o san duoi', Math.abs(maxWest - L) < 0.01, String(maxWest)); + // Chieu y: ho o goc tay-NAM (y nho), goc tay-BAC phang. + const sw = zAt(MAP.ox, MAP.oy), nw = zAt(MAP.ox, MAP.oy + 1.0); + check('map: ho o goc tay-nam', near(sw, -0.1 + L, 1e-3), String(sw)); + check('map: goc tay-bac phang', near(nw, L, 1e-3), String(nw)); + // Dinh tai x = ox + 1.0 (ranh cot 4|5) tren hang giua: (0.4 + 0.6) / 2. + const mid = zAt(MAP.ox + 1.0, MAP.oy + 0.4); + check('map: dinh giua doc', near(mid, 0.5 + L, 1e-3), String(mid)); + } + // Cung mang o -> khong dung lai; mang moi -> dung lai. + const truoc = V3D.mapMesh; + sb3.__map({ ...g, data: g.cells, floor: f }); + check('map: cung du lieu khong dung lai', V3D.mapMesh === truoc); + sb3.__map({ ...g, data: new Int8Array(g.cells), floor: null }); + check('map: du lieu moi dung lai', V3D.mapMesh !== truoc); + const pf = V3D.mapMesh.geometry.attributes.position; + check('map: khong san -> phang', pf.count === 4 && + [0, 1, 2, 3].every((i) => pf.array[i * 3 + 2] === 0)); + // Ban do phang giu nguyen cao do cu (duoi luoi va vanh cliff). + check('map: khong san -> y cu', V3D.mapMesh.position.y === -0.002 && V3D.mapHasFloor === false, + String(V3D.mapMesh.position.y)); +} + +// Scan/cloud nang theo cao do san duoi robot; quy dao theo luoi san. +{ + const r = { laser_x: 0.24, laser_y: 0, laser_z: 0.1415, wheel_radius: 0.075 }; + sb3.__scan(new Float32Array([1.0, 0.0]), { x: 0, y: 0, yaw: 0, z: 1.5 }, r); + const sy = V3D.scanPts.geometry.attributes.position.array[1]; + check('scan: nang theo z', Math.abs(sy - (1.5 + 0.1415 + 0.075)) < 1e-6, String(sy)); + sb3.__scan(new Float32Array([1.0, 0.0]), { x: 0, y: 0, yaw: 0 }, r); + const sy0 = V3D.scanPts.geometry.attributes.position.array[1]; + check('scan: khong z -> nhu cu', Math.abs(sy0 - (0.1415 + 0.075)) < 1e-6, String(sy0)); + + sb3.__cloud(new Float32Array([1.0, 0.0, 0.3]), { x: 0, y: 0, yaw: 0, z: 1.5 }); + const cy = V3D.cloudPts.geometry.attributes.position.array[1]; + check('cloud: nang theo z', Math.abs(cy - 1.8) < 1e-6, String(cy)); + + // Scan THO nghieng theo than: doc 15 do mui NGANG len (pitch ROS am). + // Diem 1 m truoc LiDAR: he footprint (1.24, 0, 0.2165) quay Ry(-15 do). + const P = -15 * Math.PI / 180; + sb3.__scan(new Float32Array([1.0, 0.0]), { x: 0, y: 0, yaw: 0, z: 0.5, pitch: P }, r); + const a = V3D.scanPts.geometry.attributes.position.array; + const ex = 1.24 * Math.cos(P) + 0.2165 * Math.sin(P); + const ez = -1.24 * Math.sin(P) + 0.2165 * Math.cos(P); + check('scan: pitch keo diem truoc len', Math.abs(a[0] - ex) < 1e-6 && Math.abs(a[1] - (0.5 + ez)) < 1e-6, + a[0] + ', ' + a[1]); + // Roll +10 do (ROS: ben TRAI len): diem 1 m ben trai cao hon goc LiDAR. + const R = 10 * Math.PI / 180; + sb3.__scan(new Float32Array([0.0, 1.0]), { x: 0, y: 0, yaw: 0, roll: R }, r); + const b = V3D.scanPts.geometry.attributes.position.array; + check('scan: roll keo ben trai len', + Math.abs(b[1] - (Math.sin(R) + 0.2165 * Math.cos(R))) < 1e-6 && + Math.abs(b[2] + (Math.cos(R) - 0.2165 * Math.sin(R))) < 1e-6, b[1] + ', ' + b[2]); + + const cx = (c) => MAP.ox + (c + 0.5) * 0.2, yy = MAP.oy + 0.3; + sb3.__path([cx(0), yy, cx(9), yy], f); + const pts = V3D.pathLine.geometry.points; + // Tren mat ban do uon (nang L) 1 cm. + check('path: diem san duoi', pts && Math.abs(pts[0].y - (L + 0.01)) < 1e-6, + pts && String(pts[0].y)); + check('path: diem san tren', pts && Math.abs(pts[1].y - (1.5 + L + 0.01)) < 1e-6, + pts && String(pts[1].y)); + sb3.__path([cx(0), yy, cx(9), yy], null); + const pts0 = V3D.pathLine.geometry.points; + check('path: khong luoi -> 0.01 nhu cu', pts0 && pts0.every((q) => Math.abs(q.y - 0.01) < 1e-9)); +} + +// v3dRender: tam quay bam CAO DO robot khi "bam robot"; nua SLAM an mat san +// the gioi khi ban do co do cao san. +{ + const calls = []; + V3D.floorMesh = { visible: true }; + V3D.renderer = { + setSize() {}, setScissorTest() {}, setViewport() {}, setScissor() {}, + render() { calls.push(V3D.floorMesh.visible); }, + }; + V3D.camera = { aspect: 1, updateProjectionMatrix() {}, position: new V3(), + lookAt(x, y, z) { this.look = [x, y, z]; } }; + V3D.robotGroup = { position: new V3(2, 1.5, -3) }; + const cv = { clientWidth: 800, clientHeight: 600, width: 800, height: 600 }; + const o = V3D.orbit; + + sb3.__map({ ...g, data: new Int8Array(g.cells), floor: f }); // co san + sb3.__render(cv, true, true); + check('render: tam quay o cao do robot', Math.abs(V3D.camera.look[1] - 1.7) < 1e-9, + String(V3D.camera.look)); + check('render: camera nang theo robot', + Math.abs(V3D.camera.position.y - (1.5 + o.dist * Math.sin(o.el))) < 1e-9); + check('render: nua the gioi CO san, nua SLAM KHONG', calls.length === 2 && calls[0] === true && + calls[1] === false, JSON.stringify(calls)); + check('render: tra lai san sau khi ve', V3D.floorMesh.visible === true); + + calls.length = 0; + sb3.__render(cv, false, true); + check('render: khong bam -> tam quay 0.2 nhu cu', Math.abs(V3D.camera.look[1] - 0.2) < 1e-9, + String(V3D.camera.look)); + + // Tat "the gioi": ban do co san -> an mat san z = 0; bat lai -> hien. + sb3.__worldVis(false); + check('tat the gioi + co san -> an mat san', V3D.floorMesh.visible === false); + sb3.__worldVis(true); + check('bat the gioi -> hien mat san', V3D.floorMesh.visible === true); + + calls.length = 0; + sb3.__map({ ...g, data: new Int8Array(g.cells), floor: null }); // ban do phang + sb3.__render(cv, false, true); + check('render: ban do phang -> nua SLAM van co san', calls[1] === true, JSON.stringify(calls)); + sb3.__worldVis(false); + check('tat the gioi + ban do phang -> giu mat san nhu cu', V3D.floorMesh.visible === true); +} + +// v3dSetGround: duoc goi MOI khung khi chay tu `.world`. Cung luoi -> KHONG +// dung lai (ban cu dung lai moi khung va ro GridHelper tren GPU); luoi moi -> +// dung lai va giai phong ca geometry lan material cu. +{ + let disposed = 0; + const disp = () => { disposed++; }; + THREE.GridHelper = class { + constructor() { Object.assign(this, node()); this.geometry = { dispose: disp }; + this.material = { dispose: disp }; } + }; + THREE.MeshStandardMaterial = class { constructor(o) { Object.assign(this, o); } dispose() { disp(); } }; + V3D.scene = { fog: { near: 0, far: 0 } }; + V3D.floorMesh = null; + V3D.gridHelper = null; + const wg = { res: 0.05, w: 400, h: 600, ox: -1, oy: -2 }; + sb3.__ground(wg); + const f1 = V3D.floorMesh, g1 = V3D.gridHelper; + const n0 = V3D.root.children.length; + for (let i = 0; i < 100; ++i) sb3.__ground(wg); + check('ground: cung luoi khong dung lai', V3D.floorMesh === f1 && V3D.gridHelper === g1 && + disposed === 0, String(disposed)); + check('ground: root khong phinh', V3D.root.children.length === n0); + check('ground: suong mu theo bao the gioi', Math.abs(V3D.scene.fog.far - 30 * 1.4) < 1e-9, + String(V3D.scene.fog.far)); + f1.geometry.dispose = disp; + sb3.__ground({ ...wg, w: 500 }); + check('ground: luoi moi dung lai', V3D.floorMesh !== f1 && V3D.gridHelper !== g1); + check('ground: giai phong san + luoi cu (geometry + material)', disposed === 4, String(disposed)); + check('ground: root van 1 san 1 luoi', V3D.root.children.length === n0 && + !V3D.root.children.includes(f1) && !V3D.root.children.includes(g1)); +} + +console.log(bad ? '\n => HONG' : '\n => DAT'); +process.exit(bad ? 1 : 0);