diff --git a/apps/camera_lidar_calibration/App.cpp b/apps/camera_lidar_calibration/App.cpp index cf388be10..8bbdee6f6 100644 --- a/apps/camera_lidar_calibration/App.cpp +++ b/apps/camera_lidar_calibration/App.cpp @@ -7,11 +7,14 @@ #include #include #include +#include #include #include #include #include +#include #include +#include #include #include #include @@ -103,7 +106,7 @@ void AppState::setPendingImagePoint(float u, float v) } else { - statusMsg = "Image point set -- Shift+click the matching point in the 3D View"; + statusMsg = "Image point set -- Shift+click the matching point in the 3D View, or Shift+Alt+click it in the Image View"; } } @@ -134,6 +137,69 @@ void AppState::clearPending() statusMsg = "Pending pick cleared"; } +Intrinsics AppState::displayIntrinsics() const +{ + Intrinsics K = intrinsics; + if (imageRectified) + { + K.k1 = K.k2 = K.k3 = K.k4 = K.k5 = K.k6 = 0.f; + K.p1 = K.p2 = 0.f; + } + return K; +} + +bool AppState::pickLidarPointAtPixel(float u, float v) +{ + if (cloud.empty()) + { + statusMsg = "No point cloud loaded"; + return false; + } + + // Same projection, depth range and decimation as the GPU pass that drew + // the intensity image (Renderer::renderImageOverlay), so the pick is the + // point under the cursor. Points are square splats, pointSize px wide. + const Intrinsics K = displayIntrinsics(); + const Eigen::Matrix3f R_wc = omFiKaToMat3(extrinsics.om, extrinsics.fi, extrinsics.ka); + const Eigen::Vector3f C(extrinsics.tx, extrinsics.ty, extrinsics.tz); + const float half = std::max(vizParams.pointSize, 1.f) * 0.5f; + constexpr float kNearbyPx = 8.f; + + long covering = -1, nearby = -1; + float coveringDepth = std::numeric_limits::max(); + float nearbyDist2 = kNearbyPx * kNearbyPx; + for (size_t i = 0; i < cloud.points.size(); ++i) + { + if (!Renderer::isPointDrawn(i, vizParams.drawDecim)) + continue; + const auto& p = cloud.points[i]; + float pu, pv, depth; + if (!projectPoint(p.x, p.y, p.z, K, R_wc, C, pu, pv, depth) || depth < vizParams.depthMin || depth > vizParams.depthMax) + continue; + const float du = pu - u, dv = pv - v; + if (std::fabs(du) <= half && std::fabs(dv) <= half && depth < coveringDepth) + { + covering = static_cast(i); + coveringDepth = depth; + } + if (du * du + dv * dv < nearbyDist2) + { + nearby = static_cast(i); + nearbyDist2 = du * du + dv * dv; + } + } + + const long hit = covering >= 0 ? covering : nearby; + if (hit < 0) + { + statusMsg = "No LiDAR point at that pixel"; + return false; + } + const auto& p = cloud.points[static_cast(hit)]; + setPendingCloudPoint(p.x, p.y, p.z); + return true; +} + void AppState::removePair(int index) { if (index < 0 || index >= static_cast(pairs.size())) @@ -145,13 +211,141 @@ void AppState::removePair(int index) selectedPairIndex--; } +// ── AppState pairs file ─────────────────────────────────────────────────────── +void AppState::savePairs(const char* path) +{ + nlohmann::json j; + // u/v are pixels of the displayed image: rectified or raw, at this size. + // The paths are a note of what the pairs were picked on; loading ignores them. + j["image"] = { { "path", imagePath }, { "width", imageW }, { "height", imageH }, { "rectified", imageRectified } }; + j["clouds"] = cloudPaths; + j["pairs"] = nlohmann::json::array(); + for (const auto& p : pairs) + j["pairs"].push_back({ { "u", p.u }, { "v", p.v }, { "point", { p.px, p.py, p.pz } } }); + + std::ofstream f(path); + if (!f) + { + statusMsg = std::string("Cannot write: ") + path; + return; + } + f << j.dump(2); + pairsPath = path; + statusMsg = "Saved " + std::to_string(pairs.size()) + " pairs to " + path; +} + +bool AppState::isPairsFile(const char* path) +{ + std::string ext = std::filesystem::path(path).extension().string(); + std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); + if (ext != ".json") + return false; + std::ifstream f(path); + const nlohmann::json j = nlohmann::json::parse(f, nullptr, false); + return j.is_object() && j.contains("pairs") && j["pairs"].is_array(); +} + +void AppState::loadPairs(const char* path) +{ + std::ifstream f(path); + if (!f) + { + statusMsg = std::string("Cannot open: ") + path; + return; + } + std::vector loaded; + int fileW = 0, fileH = 0; + bool fileRectified = false; + try + { + nlohmann::json j; + f >> j; + if (!j.contains("pairs") || !j["pairs"].is_array()) + { + statusMsg = std::string("No pairs found in: ") + path; + return; + } + const nlohmann::json ji = j.value("image", nlohmann::json::object()); + fileW = ji.value("width", 0); + fileH = ji.value("height", 0); + fileRectified = ji.value("rectified", false); + for (const auto& jp : j["pairs"]) + { + const auto& pt = jp.at("point"); + CorrespondencePair p; + p.u = jp.at("u").get(); + p.v = jp.at("v").get(); + p.px = pt.at(0).get(); + p.py = pt.at(1).get(); + p.pz = pt.at(2).get(); + loaded.push_back(p); + } + } catch (const nlohmann::json::exception& e) + { + statusMsg = std::string("Bad pairs file ") + path + ": " + e.what(); + return; + } + + std::string notes; + if (imageLoaded && fileW > 0 && fileH > 0 && (fileW != imageW || fileH != imageH)) + { + const float sx = static_cast(imageW) / fileW, sy = static_cast(imageH) / fileH; + for (auto& p : loaded) + { + p.u *= sx; + p.v *= sy; + } + notes += "; pixels scaled from " + std::to_string(fileW) + "x" + std::to_string(fileH) + " to the loaded image"; + } + if (imageLoaded && fileRectified != imageRectified) + notes += std::string("; WARNING: picked in the ") + (fileRectified ? "rectified" : "raw") + " image, the shown one is " + + (imageRectified ? "rectified" : "raw"); + + pairs = std::move(loaded); + pairsPath = path; + selectedPairIndex = -1; + lastSolveRmsPixels = -1.0; + statusMsg = "Loaded " + std::to_string(pairs.size()) + " pairs from " + path + notes; +} + +calib::ExtrinsicsPriors AppState::defaultPriors() +{ + calib::ExtrinsicsPriors priors; + for (int i = 0; i < 6; ++i) + priors[i].sigma = i < 3 ? 0.01 : 0.5; + return priors; +} + +std::string AppState::refinedIntrinsicsLabel() const +{ + if (intrinsics.model != CameraModel::Mei) + return ""; + std::string label; + auto add = [&label](bool on, const char* names) + { + if (on) + label += (label.empty() ? "" : ", ") + std::string(names); + }; + add(refineIntrinsics.focal, "fx, fy"); + add(refineIntrinsics.principalPoint, "cx, cy"); + add(refineIntrinsics.xi, "xi"); + add(refineIntrinsics.distortion, "k1-k3, p1, p2"); + return label; +} + bool AppState::solvePairs() { + const std::string refined = refinedIntrinsicsLabel(); if (pairs.size() < 3) { statusMsg = "Need at least 3 pairs to solve"; return false; } + if (lockTranslation && lockRotation && refined.empty()) + { + statusMsg = "Translation and rotation are both locked -- nothing to solve"; + return false; + } std::vector corr; corr.reserve(pairs.size()); @@ -167,11 +361,20 @@ bool AppState::solvePairs() double rms = -1.0; std::string solveErr; // Pinhole's observation equations are a plain rectilinear projection, so - // Mei and Fisheye use solveExtrinsicsCeres instead. See - // CameraCalibrationSolver.h. + // Mei and Fisheye use the Ceres solver instead, which can also refine Mei + // intrinsics. See CameraCalibrationSolver.h. bool ok = (intrinsics.model == CameraModel::Mei || intrinsics.model == CameraModel::Fisheye) - ? calib::solveExtrinsicsCeres(corr, intrinsics, extrinsics, solveErr, &rms, lockTranslation) - : calib::solveExtrinsicsFromCorrespondences(corr, intrinsics, extrinsics, &rms, lockTranslation); + ? calib::solveExtrinsicsAndIntrinsicsCeres( + corr, + intrinsics, + extrinsics, + refined.empty() ? calib::MeiIntrinsicsRefinement{} : refineIntrinsics, + solveErr, + &rms, + lockTranslation, + lockRotation, + priors) + : calib::solveExtrinsicsFromCorrespondences(corr, intrinsics, extrinsics, &rms, lockTranslation, lockRotation, priors); if (!ok) { statusMsg = !solveErr.empty() ? ("Solve failed: " + solveErr) : "Solve failed (degenerate correspondences)"; @@ -179,9 +382,30 @@ bool AppState::solvePairs() } lastSolveRmsPixels = rms; - statusMsg = - lockTranslation ? "Solved rotation (translation locked): RMS reprojection error " : "Solved extrinsics: RMS reprojection error "; - statusMsg += std::to_string(rms) + " px"; + std::string solved; + if (lockTranslation && lockRotation) + solved = refined + " (extrinsics locked)"; + else + { + if (lockTranslation) + solved = "rotation (translation locked)"; + else if (lockRotation) + solved = "translation (rotation locked)"; + else + solved = "extrinsics"; + if (!refined.empty()) + solved += " + " + refined; + } + statusMsg = "Solved " + solved + ": RMS reprojection error " + std::to_string(rms) + " px"; + const int nPriors = static_cast(std::count_if( + priors.begin(), + priors.end(), + [](const auto& p) + { + return p.enabled; + })); + if (nPriors > 0) + statusMsg += " (" + std::to_string(nPriors) + (nPriors == 1 ? " prior)" : " priors)"); if (!imageRectified && intrinsicsLoaded == false) statusMsg += " (no intrinsics loaded -- distortion assumed zero)"; return true; @@ -210,6 +434,55 @@ void AppState::loadImage(const char* path) statusMsg += "; " + scaleNote; } +// ── AppState::loadImageClosestToCloudTime ───────────────────────────────────── +void AppState::loadImageClosestToCloudTime(const char* dir) +{ + int64_t t0 = std::numeric_limits::max(), t1 = std::numeric_limits::min(); + for (const auto& p : cloud.points) + if (p.ts_ns != 0) + { + t0 = std::min(t0, p.ts_ns); + t1 = std::max(t1, p.ts_ns); + } + if (t0 > t1) + { + statusMsg = std::string("No point times in the loaded clouds, so no image picked from ") + dir; + return; + } + const int64_t mid = t0 + (t1 - t0) / 2; + const auto image = calib::closestImage(dir, mid); + if (!image) + { + statusMsg = std::string("No image with a capture time in ") + dir; + return; + } + loadImage(image->path.c_str()); + if (imagePath != image->path) + return; // loadImage said why + char buf[256]; + std::snprintf( + buf, + sizeof(buf), + "%s is %+.3f s from the middle of the clouds' %.1f s; ", + std::filesystem::path(image->path).filename().string().c_str(), + static_cast(image->tsNs - mid) * 1e-9, + static_cast(t1 - t0) * 1e-9); + statusMsg = buf + statusMsg; +} + +// ── AppState::focusOnSensors ────────────────────────────────────────────────── +void AppState::focusOnSensors() +{ + // LiDAR origin and optical centre in raylib coords (x, z, -y). + const Vector3 lidar = { 0.f, 0.f, 0.f }; + const Vector3 camera = { extrinsics.tx, extrinsics.tz, -extrinsics.ty }; + // Holds both bodies: the X5 reaches ~0.1 m from its optical centre. + const float radius = 0.5f * Vector3Distance(lidar, camera) + 0.1f; + orbit.target = Vector3Scale(Vector3Add(lidar, camera), 0.5f); + // Fits that sphere in OrbitCamera's 45 deg vertical FOV, no closer than its 0.5 m wheel-zoom limit. + orbit.distance = std::max(0.5f, radius / std::sin(22.5f * DEG2RAD)); +} + // ── AppState::loadCloud ─────────────────────────────────────────────────────── static void centerOrbitOnCloud(AppState& s) { @@ -736,8 +1009,8 @@ void App::run() SetConfigFlags(FLAG_WINDOW_RESIZABLE); InitWindow(W, H, ("LiDAR-Camera Calibration " HDMAPPING_CONFIGURE_PROJECT_VERSION)); raylib_widgets::fitWindowToScreen(); - // The 340px-wide side panel is fixed-width; below this the 3D/image - // views and the panel start overlapping instead of scrolling. + // Below this the 3D/image views and the side panel (340 px wide until + // resized) start overlapping instead of scrolling. SetWindowMinSize(900, 500); SetTargetFPS(60); @@ -754,6 +1027,22 @@ void App::run() state.loadIntrinsics(pendingIntrinsics.c_str()); if (!pendingCalibration.empty()) state.loadCalibration(pendingCalibration.c_str()); + // Last, so its message is the one left in the status line. + if (!pendingImageDirByTime.empty()) + { + state.loadImageClosestToCloudTime(pendingImageDirByTime.c_str()); + std::printf("%s\n", state.statusMsg.c_str()); + } + if (!pendingPairs.empty()) + { + if (std::filesystem::exists(pendingPairs)) + state.loadPairs(pendingPairs.c_str()); + else + { + state.pairsPath = pendingPairs; + state.statusMsg = "New pairs file " + pendingPairs + ": Ctrl+S saves the picked pairs there"; + } + } while (!WindowShouldClose()) { @@ -777,6 +1066,13 @@ static bool shiftHeld() return IsKeyDown(KEY_LEFT_SHIFT) || IsKeyDown(KEY_RIGHT_SHIFT); } +// Alt on top of Shift turns the Image View into the LiDAR intensity image, +// to pick the LiDAR point there instead of the pixel. +static bool altHeld() +{ + return IsKeyDown(KEY_LEFT_ALT) || IsKeyDown(KEY_RIGHT_ALT); +} + // Loads one dropped file by extension -- the same extension -> action mapping as main.cpp's // preloadByExt(), but applied immediately (the window is already running) instead of queued for // App::run()'s startup pass. `sawCloud` tracks whether a *.laz/*.las has already landed in this @@ -820,15 +1116,25 @@ void App::update() state.orbit.update(allowOrbit); // Drag & drop images (*.jpg/*.jpeg/*.png/*.bmp), point clouds (*.laz/*.las), intrinsics - // (*.yml/*.yaml) or a calibration (*.json) onto the window to load them -- raylib's GLFW - // backend surfaces OS drag & drop the same way on Windows, Linux and macOS, so no - // platform-specific code is needed here. + // (*.yml/*.yaml), a calibration or saved pairs (*.json) onto the window to load them -- + // raylib's GLFW backend surfaces OS drag & drop the same way on Windows, Linux and macOS, + // so no platform-specific code is needed here. if (IsFileDropped()) { FilePathList dropped = LoadDroppedFiles(); bool sawCloud = false; + // Pairs go last, so the image and calibration dropped with them are what + // loadPairs() rescales to and checks rectification against. + std::vector pairFiles; for (unsigned int i = 0; i < dropped.count; i++) - handleDroppedFile(state, dropped.paths[i], sawCloud); + { + if (AppState::isPairsFile(dropped.paths[i])) + pairFiles.push_back(dropped.paths[i]); + else + handleDroppedFile(state, dropped.paths[i], sawCloud); + } + for (const std::string& path : pairFiles) + state.loadPairs(path.c_str()); UnloadDroppedFiles(dropped); } } @@ -872,15 +1178,25 @@ static void updateAndDrawPicking3D( } // Large 3-axis cross for the pair selected in the Correspondences - // panel, so it's easy to spot in the (usually much busier) 3D view. - if (state.selectedPairIndex >= 0 && state.selectedPairIndex < (int)state.pairs.size()) + // panel, so it's easy to spot in the (usually much busier) 3D view; + // a red one for the pair whose Remove button is hovered. + auto pairCross = [&state](int index, Color color) { - const auto& p = state.pairs[state.selectedPairIndex]; + if (index < 0 || index >= (int)state.pairs.size()) + return; + const auto& p = state.pairs[index]; Vector3 wp = { p.px, p.pz, -p.py }; const float armLen = 0.5f; - DrawLine3D(Vector3{ wp.x - armLen, wp.y, wp.z }, Vector3{ wp.x + armLen, wp.y, wp.z }, MAGENTA); - DrawLine3D(Vector3{ wp.x, wp.y - armLen, wp.z }, Vector3{ wp.x, wp.y + armLen, wp.z }, MAGENTA); - DrawLine3D(Vector3{ wp.x, wp.y, wp.z - armLen }, Vector3{ wp.x, wp.y, wp.z + armLen }, MAGENTA); + DrawLine3D(Vector3{ wp.x - armLen, wp.y, wp.z }, Vector3{ wp.x + armLen, wp.y, wp.z }, color); + DrawLine3D(Vector3{ wp.x, wp.y - armLen, wp.z }, Vector3{ wp.x, wp.y + armLen, wp.z }, color); + DrawLine3D(Vector3{ wp.x, wp.y, wp.z - armLen }, Vector3{ wp.x, wp.y, wp.z + armLen }, color); + }; + pairCross(state.selectedPairIndex, MAGENTA); + pairCross(state.hoveredRemoveIndex, RED); + if (state.hoveredRemoveIndex >= 0 && state.hoveredRemoveIndex < (int)state.pairs.size()) + { + const auto& p = state.pairs[state.hoveredRemoveIndex]; + DrawSphereWires(Vector3{ p.px, p.pz, -p.py }, 0.12f, 6, 8, RED); } if (state.pendingHasCloud) @@ -930,13 +1246,13 @@ static void updateAndDrawPicking3D( void App::draw() { float menuBarH = ImGui::GetFrameHeight(); - float panelW = 340.f; - float viewW = (float)GetScreenWidth() - panelW; + float viewW = (float)GetScreenWidth() - state.panelW; float viewH = (float)GetScreenHeight() - menuBarH; // ── Image + projection overlay (GPU, into render texture) - // Hide the projected-point overlay while Shift is held (picking mode) - // so it doesn't obscure the pixel the user is aiming for. + // Shift (picking a pixel) hides the projected points so they don't + // obscure the pixel the user is aiming for; Shift+Alt (picking a LiDAR + // point) shows those points alone, as an intensity image. if (state.imageLoaded) state.renderer.renderImageOverlay( state.imageTexture, @@ -946,7 +1262,9 @@ void App::draw() state.extrinsics, !state.imageRectified, state.vizParams, - !shiftHeld()); + !shiftHeld() ? ImageOverlay::Points + : altHeld() ? ImageOverlay::LidarIntensity + : ImageOverlay::None); // ── 3D scene renders as the raylib background, filling the whole view BeginDrawing(); @@ -970,6 +1288,10 @@ void App::draw() if (state.imageLoaded) state.renderer.drawCameraFrustum(state.intrinsics, state.extrinsics, state.imageW, state.imageH); state.renderer.drawAxes(2.f); + if (state.showLidarModel) + state.renderer.drawLidarModel(); + if (state.showCameraModel) + state.renderer.drawCameraModel(state.extrinsics, state.cameraBody); // Grid on ground plane DrawGrid(20, 1.f); @@ -998,7 +1320,7 @@ void App::draw() if (shiftHeld()) DrawText("Shift+click to pick a 3D point (green = candidate)", 8, (int)menuBarH + 4, 14, YELLOW); else - DrawText("3D View [LMB: orbit | RMB: pan | Scroll: zoom | Shift: pick]", 8, (int)menuBarH + 4, 14, LIGHTGRAY); + DrawText("3D View [LMB: orbit | RMB: pan | Scroll: zoom | Shift: pick | F: focus sensors]", 8, (int)menuBarH + 4, 14, LIGHTGRAY); DrawFPS((int)viewW - 90, (int)menuBarH + 4); diff --git a/apps/camera_lidar_calibration/App.h b/apps/camera_lidar_calibration/App.h index f72eff2a0..f0f96918d 100644 --- a/apps/camera_lidar_calibration/App.h +++ b/apps/camera_lidar_calibration/App.h @@ -3,6 +3,7 @@ #include "UI.h" #include "raylib.h" #include +#include #include #include #include @@ -58,6 +59,14 @@ struct AppState // ── visualization ───────────────────────────────────────────────────────── VisualizationParams vizParams; bool showCompassRuler = true; + //! Simplified real-size sensor models in the 3D view: a Mid-360 at the + //! LiDAR origin, cameraBody at the camera pose. + bool showLidarModel = true; + bool showCameraModel = true; + CameraBody cameraBody = CameraBody::Insta360X5; + + //! Width of the Controls panel on the right, px; dragging its left edge changes it. + float panelW = 340.f; // ── 3D camera ───────────────────────────────────────────────────────────── OrbitCamera orbit; @@ -82,6 +91,9 @@ struct AppState // Row selected in the Correspondences panel list (-1 = none); drawn as // a large cross in both the 3D view and the image view. int selectedPairIndex = -1; + //! Pair whose Remove button is hovered (-1 = none), marked in red in both views + //! so it is clear which pair the click removes. Set by UI::draw each frame. + int hoveredRemoveIndex = -1; // When set, "Solve Extrinsics from Pairs" refines orientation only and // leaves tx/ty/tz exactly as they are -- for when the camera's position // relative to the LiDAR is already known (e.g. measured by hand) and @@ -89,15 +101,61 @@ struct AppState // disables the tx/ty/tz drag sliders in the Extrinsics panel so they // can't be nudged by accident while locked. bool lockTranslation = false; + //! Rotation counterpart of lockTranslation: the solve refines tx/ty/tz + //! only and the om/fi/ka sliders are disabled. + bool lockRotation = false; + //! Soft constraints for "Solve Extrinsics from Pairs": each enabled one + //! adds an observation equation pulling that parameter towards its + //! target, e.g. to keep the camera height (tz) from drifting when the + //! pairs barely constrain it. Indexed as calib::kPriorTx..kPriorKa. + calib::ExtrinsicsPriors priors = defaultPriors(); + //! Mei intrinsics "Solve Extrinsics from Pairs" refines too; ignored for + //! other models. + calib::MeiIntrinsicsRefinement refineIntrinsics; + //! @return the intrinsics the solve refines, e.g. "fx, fy, xi"; empty when none + std::string refinedIntrinsicsLabel() const; + + /** + * @brief Priors all disabled, with a sigma of 1 cm for tx/ty/tz and + * 0.5 deg for om/fi/ka. + * @return the default priors + */ + static calib::ExtrinsicsPriors defaultPriors(); void setPendingImagePoint(float u, float v); // completes the pair if a cloud point is already pending void setPendingCloudPoint(float px, float py, float pz); // completes the pair if an image point is already pending void clearPending(); // discards the in-progress pending pick, if any + //! Makes the LiDAR point drawn at pixel (u, v) of the Image View's + //! intensity image (Shift+Alt) the pending cloud point: the nearest one + //! whose splat covers the pixel, else the closest within a few pixels. + //! @return false, with the reason in statusMsg, when there is none + bool pickLidarPointAtPixel(float u, float v); + //! `intrinsics` as the displayed image needs them: distortion zeroed when + //! the image is rectified. + Intrinsics displayIntrinsics() const; void removePair(int index); bool solvePairs(); // solves extrinsics from `pairs`, updates statusMsg + //! Writes `pairs` to a JSON file, with the size and rectification of the + //! image their u/v were picked in. + void savePairs(const char* path); + //! Replaces `pairs` with those in a savePairs() file, rescaling u/v when the + //! loaded image's size differs from the file's. + void loadPairs(const char* path); + //! @return whether `path` is a savePairs() file, i.e. a .json with a "pairs" array + static bool isPairsFile(const char* path); + //! File Ctrl+S saves the pairs to: --pairs, else the last pairs file loaded or + //! saved; empty = ask for one. + std::string pairsPath; // ── operations ──────────────────────────────────────────────────────────── + //! Points the 3D view at the LiDAR origin and the camera pose, close enough + //! to see the sensor models, keeping the current viewing angle. + void focusOnSensors(); void loadImage(const char* path); + //! Loads the image in `dir` taken closest to the middle of the loaded + //! clouds' point times (calib::closestImage); leaves the image as it is, + //! saying why in statusMsg, when the clouds or images carry no times. + void loadImageClosestToCloudTime(const char* dir); void loadCloud(const char* path); // clear + load void addCloud(const char* path); // merge into existing cloud void loadIntrinsics(const char* path); @@ -134,6 +192,18 @@ class App { pendingCalibration = path; } + //! After the clouds load, replace the image with the one in `dir` taken + //! closest to their time (AppState::loadImageClosestToCloudTime). + void preloadImageClosestToClouds(const char* dir) + { + pendingImageDirByTime = dir; + } + //! Picked pairs file: loaded after everything else, as from a drop, when it + //! exists; Ctrl+S saves the pairs to it either way. + void preloadPairs(const char* path) + { + pendingPairs = path; + } void run(); @@ -143,6 +213,8 @@ class App std::vector pendingClouds; std::string pendingIntrinsics; std::string pendingCalibration; + std::string pendingImageDirByTime; + std::string pendingPairs; void update(); void draw(); diff --git a/apps/camera_lidar_calibration/Renderer.cpp b/apps/camera_lidar_calibration/Renderer.cpp index 7f5db1b0a..49fb241d7 100644 --- a/apps/camera_lidar_calibration/Renderer.cpp +++ b/apps/camera_lidar_calibration/Renderer.cpp @@ -163,7 +163,7 @@ void Renderer::renderImageOverlay( const Extrinsics& E, bool applyDistortion, const VisualizationParams& vp, - bool showOverlay) + ImageOverlay overlay) { if (!imageTexValid) return; @@ -171,10 +171,12 @@ void Renderer::renderImageOverlay( BeginTextureMode(imageTex); ClearBackground(BLACK); - DrawTexturePro( - img, Rectangle{ 0, 0, (float)imgW, (float)imgH }, Rectangle{ 0, 0, (float)texW, (float)texH }, Vector2{ 0, 0 }, 0.f, WHITE); + const bool intensityImage = overlay == ImageOverlay::LidarIntensity; + if (!intensityImage) + DrawTexturePro( + img, Rectangle{ 0, 0, (float)imgW, (float)imgH }, Rectangle{ 0, 0, (float)texW, (float)texH }, Vector2{ 0, 0 }, 0.f, WHITE); - if (showOverlay && cloudCount > 0 && projShaderValid) + if (overlay != ImageOverlay::None && cloudCount > 0 && projShaderValid) { rlDrawRenderBatchActive(); // flush the image quad before raw GL draw @@ -216,6 +218,12 @@ void Renderer::renderImageOverlay( } } float depthRange[2] = { vp.depthMin, vp.depthMax }; + // The intensity image is the points alone: opaque, coloured by + // intensity whatever the colour mode, nearest point on top. + const int colorMode = intensityImage ? 1 : vp.colorMode; + const float opacity = intensityImage ? 1.f : vp.opacity; + if (intensityImage) + rlEnableDepthTest(); rlEnableShader(projShader.id); rlSetUniformMatrix(locPrjXform, xform); @@ -228,18 +236,27 @@ void Renderer::renderImageOverlay( rlSetUniform(locPrjXi, &xiVal, RL_SHADER_UNIFORM_FLOAT, 1); rlSetUniform(locPrjThetaMax, &thetaMax, RL_SHADER_UNIFORM_FLOAT, 1); rlSetUniform(locPrjDepthRange, depthRange, RL_SHADER_UNIFORM_VEC2, 1); - rlSetUniform(locPrjOpacity, &vp.opacity, RL_SHADER_UNIFORM_FLOAT, 1); + rlSetUniform(locPrjOpacity, &opacity, RL_SHADER_UNIFORM_FLOAT, 1); rlSetUniform(locPrjPointSize, &vp.pointSize, RL_SHADER_UNIFORM_FLOAT, 1); - rlSetUniform(locPrjColorMode, &vp.colorMode, RL_SHADER_UNIFORM_INT, 1); + rlSetUniform(locPrjColorMode, &colorMode, RL_SHADER_UNIFORM_INT, 1); rlSetUniform(locPrjDecim, &vp.drawDecim, RL_SHADER_UNIFORM_INT, 1); raylib_widgets::drawPointBufferParts(cloudParts); rlDisableShader(); + if (intensityImage) + rlDisableDepthTest(); } EndTextureMode(); } +bool Renderer::isPointDrawn(size_t index, int drawDecim) +{ + // Mirrors the shaders' gl_VertexID % drawDecim, and gl_VertexID restarts + // in every buffer part. + return drawDecim <= 1 || (index % raylib_widgets::kMaxVerticesPerPart) % static_cast(drawDecim) == 0; +} + void Renderer::draw3DCloud( const PointCloud& cloud, const VisualizationParams& vp, @@ -377,3 +394,120 @@ void Renderer::drawAxes(float len) DrawLine3D({ 0, 0, 0 }, { 0, len, 0 }, GREEN); // Y (= LiDAR Z = up) DrawLine3D({ 0, 0, 0 }, { 0, 0, -len }, BLUE); // Z (= LiDAR Y) } + +// ── Sensor models ───────────────────────────────────────────────────────────── +// Dimensions in millimetres, read off the Livox Mid-360 and Insta360 X5 CAD +// models. +namespace +{ + //! Pushes a local frame posed at (R, t) in the LiDAR frame onto the + //! matrix stack, with local lengths in millimetres. Pair with + //! rlPopMatrix(). + //! @param R local axes in the LiDAR frame + //! @param t local origin in the LiDAR frame, metres + void pushPoseMm(const Eigen::Matrix3f& R, const Eigen::Vector3f& t) + { + Eigen::Matrix3f lidarToRaylib; // (x, y, z) -> (x, z, -y) + lidarToRaylib << 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, -1.f, 0.f; + const Eigen::Matrix3f M = lidarToRaylib * R * 0.001f; + const Eigen::Vector3f T = lidarToRaylib * t; + const Matrix m = { M(0, 0), M(0, 1), M(0, 2), T(0), M(1, 0), M(1, 1), M(1, 2), T(1), + M(2, 0), M(2, 1), M(2, 2), T(2), 0.f, 0.f, 0.f, 1.f }; + rlPushMatrix(); + rlMultMatrixf(MatrixToFloat(m)); + } + + void box(Vector3 lo, Vector3 hi, Color fill, Color edge) + { + const Vector3 centre = Vector3Scale(Vector3Add(lo, hi), 0.5f); + const Vector3 size = Vector3Subtract(hi, lo); + DrawCubeV(centre, size, fill); + DrawCubeWiresV(centre, size, edge); + } + + void circleZ(float z, float r, Color color) + { + constexpr int kSegments = 32; + for (int i = 0; i < kSegments; ++i) + { + const float a0 = 2.f * PI * i / kSegments, a1 = 2.f * PI * (i + 1) / kSegments; + DrawLine3D({ r * cosf(a0), r * sinf(a0), z }, { r * cosf(a1), r * sinf(a1), z }, color); + } + } + + //! Solid cone frustum along local z, outlined at both ends. + void coneZ(float z0, float z1, float r0, float r1, Color fill, Color edge) + { + DrawCylinderEx({ 0.f, 0.f, z0 }, { 0.f, 0.f, z1 }, r0, r1, 32, fill); + circleZ(z0, r0, edge); + circleZ(z1, r1, edge); + } + + //! In the optical frame: the X5's optical centre sits midway between its + //! two lenses, with the body running down the image. + void drawInsta360X5() + { + const Color body = { 70, 70, 75, 255 }, bodyEdge = { 150, 150, 155, 255 }; + const Color glass = { 25, 25, 30, 255 }; + + box({ -23.f, -21.5f, -12.5f }, { 23.f, 103.f, 12.5f }, body, bodyEdge); + for (const float side : { 1.f, -1.f }) + { + coneZ(side * 12.5f, side * 15.f, 17.f, 17.f, body, side > 0.f ? YELLOW : bodyEdge); + DrawSphereEx({ 0.f, 0.f, side * 8.f }, 12.5f, 12, 24, glass); + } + } + + //! In the optical frame: a Raspberry Pi format camera board (IMX519-style + //! autofocus module). The sensor sits ~4.3 mm (the lens' focal length) + //! behind the optical centre; the lens is 9.5 mm below the board's top + //! edge, the ribbon connector on the back at the bottom. + void drawPcbCamera() + { + const Color pcb = { 20, 110, 60, 255 }, pcbEdge = { 140, 200, 160, 255 }; + const Color module = { 35, 35, 40, 255 }, moduleEdge = { 130, 130, 135, 255 }; + const Color pad = { 200, 170, 80, 255 }, connector = { 60, 60, 60, 255 }; + const Color glass = { 15, 15, 20, 255 }; + constexpr float kSensorZ = -4.3f, kPcbT = 1.f; + + box({ -12.5f, -9.5f, kSensorZ - kPcbT }, { 12.5f, 14.5f, kSensorZ }, pcb, pcbEdge); + for (const float x : { -10.5f, 10.5f }) + for (const float y : { -7.5f, 5.f }) + DrawCylinderEx({ x, y, kSensorZ - kPcbT - 0.05f }, { x, y, kSensorZ + 0.05f }, 1.2f, 1.2f, 12, pad); + box({ -10.5f, 10.f, kSensorZ - kPcbT - 3.f }, { 10.5f, 14.f, kSensorZ - kPcbT }, connector, moduleEdge); + box({ -4.25f, -4.25f, kSensorZ }, { 4.25f, 4.25f, 1.5f }, module, moduleEdge); + coneZ(1.5f, 2.2f, 2.5f, 2.5f, glass, YELLOW); + } +} // namespace + +void Renderer::drawLidarModel() +{ + const Color body = { 150, 150, 155, 255 }, bodyEdge = { 70, 70, 75, 255 }; + const Color connector = { 95, 95, 100, 255 }; + const Color window = { 40, 40, 45, 255 }, windowEdge = { 120, 120, 125, 255 }; + + pushPoseMm(Eigen::Matrix3f::Identity(), Eigen::Vector3f::Zero()); + box({ -32.5f, -32.5f, -26.f }, { 32.5f, 32.5f, 1.f }, body, bodyEdge); + box({ -40.f, -10.f, -21.f }, { -32.5f, 10.f, -4.f }, connector, bodyEdge); + coneZ(1.f, 4.f, 31.f, 31.f, body, bodyEdge); + coneZ(4.f, 14.f, 25.5f, 25.5f, window, windowEdge); + coneZ(14.f, 34.f, 25.5f, 15.f, window, windowEdge); + rlPopMatrix(); +} + +void Renderer::drawCameraModel(const Extrinsics& E, CameraBody body) +{ + // Local frame = the optical frame (x right, y down, z forward), origin at + // the optical centre. + pushPoseMm(omFiKaToMat3(E.om, E.fi, E.ka), Eigen::Vector3f(E.tx, E.ty, E.tz)); + switch (body) + { + case CameraBody::Insta360X5: + drawInsta360X5(); + break; + case CameraBody::PcbCamera: + drawPcbCamera(); + break; + } + rlPopMatrix(); +} diff --git a/apps/camera_lidar_calibration/Renderer.h b/apps/camera_lidar_calibration/Renderer.h index 8a804e9e8..a919cdf90 100644 --- a/apps/camera_lidar_calibration/Renderer.h +++ b/apps/camera_lidar_calibration/Renderer.h @@ -15,7 +15,7 @@ struct VisualizationParams float depthMin = 0.f; float depthMax = 50.f; float opacity = 1.f; - int colorMode = 0; // 0=depth(jet), 1=intensity, 2=height(z), 3=Camera RGB + int colorMode = 1; // 0=depth(jet), 1=intensity (the default), 2=height(z), 3=Camera RGB // Draw only every Nth point (GPU-side, like camera_lidar_trajectory_viewer's // "Draw decimation") -- 1 = draw all points. int drawDecim = 1; @@ -23,6 +23,21 @@ struct VisualizationParams Color jetColor(float t); // t in [0,1] +//! Camera hardware Renderer::drawCameraModel draws at the camera pose. +enum class CameraBody +{ + Insta360X5, //!< dual-fisheye body, optical centre midway between its lenses + PcbCamera, //!< bare board camera in the Raspberry Pi camera format: 25 x 24 mm board, lens module, connector at the bottom +}; + +//! What Renderer::renderImageOverlay draws into the Image View. +enum class ImageOverlay +{ + Points, //!< the photo, projected points on top + None, //!< the photo alone, for picking an image pixel + LidarIntensity, //!< no photo: the projected points coloured by intensity, nearest on top, for picking a LiDAR point +}; + class Renderer { public: @@ -42,8 +57,6 @@ class Renderer // Render image + GPU-projected point overlay into imageTex. // If the displayed image is rectified, pass applyDistortion=false. - // showOverlay=false draws just the plain image (e.g. while picking, so - // projected points don't obscure the pixel the user is aiming for). void renderImageOverlay( const Texture2D& img, int imgW, @@ -52,7 +65,11 @@ class Renderer const Extrinsics& E, bool applyDistortion, const VisualizationParams& vp, - bool showOverlay = true); + ImageOverlay overlay = ImageOverlay::Points); + + //! Whether the GPU shaders draw cloud point `index` at "Draw decimation" + //! `drawDecim`, so a CPU pick can skip exactly the points not shown. + static bool isPointDrawn(size_t index, int drawDecim); // Draw 3D point cloud into current BeginMode3D context (GPU shader path). // For colorMode 3 (camera RGB) pass the displayed image texture and the @@ -73,6 +90,15 @@ class Renderer // Draw world axes at origin void drawAxes(float len = 2.f); + //! Draws a simplified, real-size Livox Mid-360 at the LiDAR origin in the + //! current BeginMode3D context; its connector marks the back (-x). + void drawLidarModel(); + + //! Draws a simplified, real-size camera at the camera pose in the current + //! BeginMode3D context. The lens these extrinsics describe (optical +z) is + //! ringed in the frustum's yellow. + void drawCameraModel(const Extrinsics& E, CameraBody body); + private: int texW = 0, texH = 0; diff --git a/apps/camera_lidar_calibration/RendererShaders.h b/apps/camera_lidar_calibration/RendererShaders.h index f0ac0ff9c..2ffe9cc02 100644 --- a/apps/camera_lidar_calibration/RendererShaders.h +++ b/apps/camera_lidar_calibration/RendererShaders.h @@ -146,6 +146,7 @@ uniform float xi; // CameraModel::Mei only uniform float thetaMax; // calib::fisheyeMaxTheta, CameraModel::Fisheye only uniform float pointSize; uniform int drawDecim; // draw only every Nth point; 1 = draw all +uniform vec2 depthRange; // shared with kProjFS out float fragDepth; out float fragIntensity; void main() { @@ -196,10 +197,15 @@ void main() { } vec2 uv = K.xy * d + K.zw; // pixel coords + // Depth across depthRange, for the LiDAR intensity image's depth test + // (the only pass that enables one). Clamped so it never clips a point + // kProjFS would keep -- kProjFS discards out-of-range depths itself. + float z = clamp(2.0 * (fragDepth - depthRange.x) / max(depthRange.y - depthRange.x, 1e-6) - 1.0, -1.0, 1.0); + // pixel -> clip space (y down, like raylib's render-texture ortho) gl_Position = vec4((2.0*uv.x/imgSize.x - 1.0) * w, -(2.0*uv.y/imgSize.y - 1.0) * w, - 0.0, + z * w, w); gl_PointSize = pointSize; } diff --git a/apps/camera_lidar_calibration/UI.cpp b/apps/camera_lidar_calibration/UI.cpp index 6f45e78e6..c63c9b9e0 100644 --- a/apps/camera_lidar_calibration/UI.cpp +++ b/apps/camera_lidar_calibration/UI.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -72,20 +73,26 @@ static void drawSensorIds(const AppState& state) // ── Main draw ──────────────────────────────────────────────────────────────── void UI::draw(AppState& state) { + // Set again below while a Remove button is hovered; the 3D view, drawn + // before the UI, shows the previous frame's. + state.hoveredRemoveIndex = -1; panelMenuBar(state); handleShortcuts(state); ImGuiIO& io = ImGui::GetIO(); float menuBarH = ImGui::GetFrameHeight(); - float panelW = 340.f; float panelH = (float)GetScreenHeight() - menuBarH; - ImGui::SetNextWindowPos(ImVec2(io.DisplaySize.x - panelW, menuBarH), ImGuiCond_Always); - ImGui::SetNextWindowSize(ImVec2(panelW, panelH), ImGuiCond_Always); - ImGui::Begin( - "Controls", - nullptr, - ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse); + // Pinned to the right edge at full height; dragging its left edge resizes + // it, between kMinPanelW and leaving the 3D view kMinViewW. + constexpr float kMinPanelW = 260.f, kMinViewW = 400.f; + const float maxPanelW = std::max(kMinPanelW, io.DisplaySize.x - kMinViewW); + state.panelW = std::clamp(state.panelW, kMinPanelW, maxPanelW); + ImGui::SetNextWindowPos(ImVec2(io.DisplaySize.x - state.panelW, menuBarH), ImGuiCond_Always); + ImGui::SetNextWindowSize(ImVec2(state.panelW, panelH), ImGuiCond_Always); + ImGui::SetNextWindowSizeConstraints(ImVec2(kMinPanelW, panelH), ImVec2(maxPanelW, panelH)); + ImGui::Begin("Controls", nullptr, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse); + state.panelW = ImGui::GetWindowWidth(); ImGui::TextColored(ImVec4(0.4f, 0.8f, 1.f, 1.f), "LiDAR-Camera Calibration"); ImGui::Separator(); @@ -94,16 +101,25 @@ void UI::draw(AppState& state) // Alt/Cmd = toggle Camera RGB ↔ Intensity (works anywhere in the window). // Cmd (Super) alongside Alt for macOS, where Option is awkward to use as - // a modifier (it composes special characters). - if (ImGui::IsKeyPressed(ImGuiKey_LeftAlt) || ImGui::IsKeyPressed(ImGuiKey_RightAlt) || ImGui::IsKeyPressed(ImGuiKey_LeftSuper) || - ImGui::IsKeyPressed(ImGuiKey_RightSuper)) + // a modifier (it composes special characters). Fires on release, unless + // Shift joined in: Shift+Alt is the Image View's LiDAR-pick chord. + const bool altDown = ImGui::IsKeyDown(ImGuiKey_LeftAlt) || ImGui::IsKeyDown(ImGuiKey_RightAlt) || + ImGui::IsKeyDown(ImGuiKey_LeftSuper) || ImGui::IsKeyDown(ImGuiKey_RightSuper); + if (altDown && io.KeyShift) + altChorded = true; + if (altWasDown && !altDown) { - auto& cm = state.vizParams.colorMode; - if (cm == 3) - cm = 1; // RGB → Intensity - else - cm = 3; // anything → RGB + if (!altChorded) + { + auto& cm = state.vizParams.colorMode; + if (cm == 3) + cm = 1; // RGB → Intensity + else + cm = 3; // anything → RGB + } + altChorded = false; } + altWasDown = altDown; panelStatus(state); ImGui::Spacing(); @@ -130,7 +146,7 @@ void UI::draw(AppState& state) // persists. if (state.renderer.imageTexValid) { - float viewW = io.DisplaySize.x - panelW; + float viewW = io.DisplaySize.x - state.panelW; float viewH = io.DisplaySize.y - menuBarH; ImGui::SetNextWindowPos(ImVec2(0, menuBarH), ImGuiCond_FirstUseEver); ImGui::SetNextWindowSize(ImVec2(viewW * 0.6f, viewH * 0.6f), ImGuiCond_FirstUseEver); @@ -172,9 +188,15 @@ void UI::drawImageView(AppState& state) // Shift is the modifier that dedicates the mouse to picking, mirroring // App.cpp's 3D-view picking and the CTRL-to-pick convention // core/src/control_points.cpp already uses elsewhere in this codebase. + // Adding Alt picks the LiDAR point instead, in the intensity image + // App::draw renders here meanwhile. const bool picking = ImGui::GetIO().KeyShift; + const bool pickingLidar = picking && ImGui::GetIO().KeyAlt; ImGui::TextColored( - ImVec4(1, 1, 0, 0.8f), picking ? "Shift+click to pick a point" : "Scroll: zoom | Drag: pan with middle | Dbl-click: reset zoom"); + ImVec4(1, 1, 0, 0.8f), + pickingLidar ? "LiDAR intensity image: Shift+Alt+click to pick a LiDAR point" + : picking ? "Shift+click to pick a pixel | add Alt to pick a LiDAR point" + : "Scroll: zoom | Drag: pan with middle | Dbl-click: reset zoom"); ImGui::BeginChild("image_scroll", ImVec2(0, 0), false, ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_NoScrollWithMouse); @@ -207,7 +229,10 @@ void UI::drawImageView(AppState& state) if (ImGui::IsMouseClicked(ImGuiMouseButton_Left)) { ImVec2 p = screenToImg(io.MousePos); - state.setPendingImagePoint(std::clamp(p.x, 0.f, imgW), std::clamp(p.y, 0.f, imgH)); + if (pickingLidar) + state.pickLidarPointAtPixel(p.x, p.y); + else + state.setPendingImagePoint(std::clamp(p.x, 0.f, imgW), std::clamp(p.y, 0.f, imgH)); } } else if (ImGui::IsMouseDragging(ImGuiMouseButton_Middle)) @@ -264,12 +289,42 @@ void UI::drawImageView(AppState& state) dl->AddCircle(s, 6.f, IM_COL32(255, 140, 0, 255), 0, 2.f); } // Large cross for the pair selected in the Correspondences panel -- - // matches the magenta cross drawn for it in the 3D view. - if (state.selectedPairIndex >= 0 && state.selectedPairIndex < (int)state.pairs.size()) + // matches the magenta cross drawn for it in the 3D view -- and a red + // one, ringed, for the pair whose Remove button is hovered. + auto pairCross = [&](int index, ImU32 color) + { + if (index < 0 || index >= (int)state.pairs.size()) + return ImVec2(0, 0); + ImVec2 s = imgToScreen(ImVec2(state.pairs[index].u, state.pairs[index].v)); + dl->AddLine(ImVec2(s.x - 18, s.y), ImVec2(s.x + 18, s.y), color, 2.f); + dl->AddLine(ImVec2(s.x, s.y - 18), ImVec2(s.x, s.y + 18), color, 2.f); + return s; + }; + pairCross(state.selectedPairIndex, IM_COL32(255, 0, 255, 255)); + if (state.hoveredRemoveIndex >= 0 && state.hoveredRemoveIndex < (int)state.pairs.size()) + dl->AddCircle(pairCross(state.hoveredRemoveIndex, IM_COL32(255, 40, 40, 255)), 12.f, IM_COL32(255, 40, 40, 255), 0, 2.f); + + // In the intensity image, also the LiDAR side of each pair, + // projected through the current calibration (cyan squares). + if (pickingLidar) { - ImVec2 s = imgToScreen(ImVec2(state.pairs[state.selectedPairIndex].u, state.pairs[state.selectedPairIndex].v)); - dl->AddLine(ImVec2(s.x - 18, s.y), ImVec2(s.x + 18, s.y), IM_COL32(255, 0, 255, 255), 2.f); - dl->AddLine(ImVec2(s.x, s.y - 18), ImVec2(s.x, s.y + 18), IM_COL32(255, 0, 255, 255), 2.f); + const Intrinsics K = state.displayIntrinsics(); + const Eigen::Matrix3f R_wc = omFiKaToMat3(state.extrinsics.om, state.extrinsics.fi, state.extrinsics.ka); + const Eigen::Vector3f C(state.extrinsics.tx, state.extrinsics.ty, state.extrinsics.tz); + auto lidarMarker = [&](float x, float y, float z, ImU32 color, const char* label) + { + float u, v, depth; + if (!projectPoint(x, y, z, K, R_wc, C, u, v, depth)) + return; + ImVec2 s = imgToScreen(ImVec2(u, v)); + dl->AddRect(ImVec2(s.x - 6, s.y - 6), ImVec2(s.x + 6, s.y + 6), color, 0.f, 0, 2.f); + if (label) + dl->AddText(ImVec2(s.x + 8, s.y - 8), color, label); + }; + for (size_t i = 0; i < state.pairs.size(); i++) + lidarMarker(state.pairs[i].px, state.pairs[i].py, state.pairs[i].pz, IM_COL32(0, 255, 255, 255), std::to_string(i).c_str()); + if (state.pendingHasCloud) + lidarMarker(state.pendingPair.px, state.pendingPair.py, state.pendingPair.pz, IM_COL32(255, 140, 0, 255), nullptr); } } @@ -345,6 +400,32 @@ void UI::actionSaveCalibration(AppState& state) } } +static const std::vector kPairsFilter = { "Picked pairs (*.json)", "*.json", "All files", "*" }; + +void UI::actionLoadPairs(AppState& state) +{ + std::string path = mandeye::fd::OpenFileDialogOneFile("Load picked pairs", kPairsFilter); + if (!path.empty()) + state.loadPairs(path.c_str()); +} + +void UI::actionSavePairs(AppState& state) +{ + if (!state.pairsPath.empty()) + state.savePairs(state.pairsPath.c_str()); + else if (state.pairs.empty()) + state.statusMsg = "No pairs to save"; + else + actionSavePairsAs(state); +} + +void UI::actionSavePairsAs(AppState& state) +{ + std::string path = mandeye::fd::SaveFileDialog("Save picked pairs", kPairsFilter, ".json", "pairs.json"); + if (!path.empty()) + state.savePairs(path.c_str()); +} + // ── Keyboard shortcuts ─────────────────────────────────────────────────────── // Ctrl-combos follow the io.KeyCtrl && ImGui::IsKeyPressed(ImGuiKey_X, false) // + io.AddKeyEvent(...) reset convention used by mandeye_single_session_viewer @@ -377,11 +458,15 @@ void UI::handleShortcuts(AppState& state) actionOpenIntrinsics(state); if (ctrlPressed(ImGuiKey_L)) actionOpenCalibration(state); - if (ctrlPressed(ImGuiKey_S)) + if (io.KeyShift && ctrlPressed(ImGuiKey_S)) actionSaveCalibration(state); + else if (ctrlPressed(ImGuiKey_S)) + actionSavePairs(state); if (ImGui::IsKeyPressed(ImGuiKey_C, false)) state.showCompassRuler = !state.showCompassRuler; + if (ImGui::IsKeyPressed(ImGuiKey_F, false)) + state.focusOnSensors(); } void UI::panelMenuBar(AppState& state) @@ -403,8 +488,15 @@ void UI::panelMenuBar(AppState& state) ImGui::Separator(); if (ImGui::MenuItem("Open Calibration...", "Ctrl+L")) actionOpenCalibration(state); - if (ImGui::MenuItem("Save Calibration...", "Ctrl+S")) + if (ImGui::MenuItem("Save Calibration...", "Ctrl+Shift+S")) actionSaveCalibration(state); + ImGui::Separator(); + if (ImGui::MenuItem("Load Pairs...")) + actionLoadPairs(state); + if (ImGui::MenuItem("Save Pairs", "Ctrl+S", false, !state.pairs.empty() || !state.pairsPath.empty())) + actionSavePairs(state); + if (ImGui::MenuItem("Save Pairs As...", nullptr, false, !state.pairs.empty())) + actionSavePairsAs(state); ImGui::EndMenu(); } @@ -417,6 +509,8 @@ void UI::panelMenuBar(AppState& state) ImGui::SliderInt("Draw decimation", &state.vizParams.drawDecim, 1, 64); if (ImGui::IsItemHovered()) ImGui::SetTooltip("Renders only every Nth point -- raise this if the 3D view is slow with a large cloud."); + if (ImGui::MenuItem("Focus on sensors", "F")) + state.focusOnSensors(); ImGui::EndMenu(); } @@ -515,6 +609,22 @@ void UI::panelIntrinsics(AppState& state) helpMarker( "Drag to adjust. Hold Ctrl+click to type a value.\nUnlike Pinhole, the displayed image is never undistorted for " "Mei -- the projection overlay and Camera RGB coloring apply this distortion to the raw image directly."); + + ImGui::Text("Refine with \"Solve Extrinsics from Pairs\":"); + // Own ID scope: "xi" is also the drag field's label above. + ImGui::PushID("refine"); + ImGui::Checkbox("fx, fy", &state.refineIntrinsics.focal); + ImGui::SameLine(); + ImGui::Checkbox("cx, cy", &state.refineIntrinsics.principalPoint); + ImGui::SameLine(); + ImGui::Checkbox("xi", &state.refineIntrinsics.xi); + ImGui::Checkbox("k1-k3, p1, p2", &state.refineIntrinsics.distortion); + ImGui::PopID(); + helpMarker( + "Solved together with the extrinsics; the values above are replaced.\n" + "Each pair gives 2 equations. xi trades off against fx/fy, and a few\n" + "pairs barely pin the distortion -- refine only what the pairs support.\n" + "Reload the calibration to undo."); } else if (K.model == CameraModel::Fisheye) { @@ -561,6 +671,12 @@ void UI::panelExtrinsics(AppState& state) ImGui::SetTooltip( "Blocks tx/ty/tz from being edited here or changed by\n\"Solve Extrinsics from Pairs\" -- use when the camera\nposition is " "already known and only orientation needs solving."); + ImGui::SameLine(); + ImGui::Checkbox("Lock rotation", &state.lockRotation); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip( + "Blocks om/fi/ka from being edited here or changed by\n\"Solve Extrinsics from Pairs\" -- use when the camera\norientation is " + "already known and only position needs solving."); ImGui::Text("Camera position in world (m):"); ImGui::BeginDisabled(state.lockTranslation); @@ -571,30 +687,94 @@ void UI::panelExtrinsics(AppState& state) ImGui::Spacing(); ImGui::Text("Camera orientation in world, om/fi/ka (deg):"); + ImGui::BeginDisabled(state.lockRotation); dragFloat("om", &E.om, 0.1f, -180.f, 180.f, "%.2f"); dragFloat("fi", &E.fi, 0.1f, -180.f, 180.f, "%.2f"); dragFloat("ka", &E.ka, 0.1f, -180.f, 180.f, "%.2f"); + ImGui::EndDisabled(); helpMarker( "R_wc = Rx(om)*Ry(fi)*Rz(ka): camera orientation in LiDAR world.\nT_lidar2cam = R_wc^T * (p - C).\nAt fi=+/-90 deg (gimbal lock), " "om and ka are not individually\nunique -- only om+ka (or om-ka) is determined."); ImGui::Spacing(); + ImGui::BeginDisabled(state.lockTranslation && state.lockRotation); if (ImGui::Button("Reset Extrinsics", ImVec2(-1, 0))) { - // Respect the translation lock: only reset orientation while locked. - Extrinsics defaults; - if (state.lockTranslation) + // Respect the locks: reset only the unlocked half. + const Extrinsics defaults; + if (!state.lockTranslation) + { + E.tx = defaults.tx; + E.ty = defaults.ty; + E.tz = defaults.tz; + } + if (!state.lockRotation) { E.om = defaults.om; E.fi = defaults.fi; E.ka = defaults.ka; } - else + } + ImGui::EndDisabled(); + ImGui::PopItemWidth(); + + if (ImGui::TreeNode("Priors (soft constraints)")) + { + helpMarker( + "Each enabled prior adds an observation equation\n(value - target) / sigma to \"Solve Extrinsics from Pairs\".\n" + "A parameter sigma away from its target costs as much\nas 1 px of reprojection error, so it stays near the\n" + "target unless the pairs clearly say otherwise.\nUse it for directions the pairs barely constrain,\n" + "e.g. the camera height tz. Ignored while locked."); + static const char* const kNames[6] = { "tx", "ty", "tz", "om", "fi", "ka" }; + float* const current[6] = { &E.tx, &E.ty, &E.tz, &E.om, &E.fi, &E.ka }; + if (ImGui::BeginTable("priors", 4, ImGuiTableFlags_SizingStretchProp)) { - E = defaults; + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed); + ImGui::TableSetupColumn("target"); + ImGui::TableSetupColumn("sigma"); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed); + ImGui::TableHeadersRow(); + for (int i = 0; i < 6; ++i) + { + const bool isTranslation = i < 3; + calib::ParameterPrior& prior = state.priors[i]; + ImGui::PushID(i); + ImGui::BeginDisabled(isTranslation ? state.lockTranslation : state.lockRotation); + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + // Enabling a prior holds the parameter where it is now. + if (ImGui::Checkbox(kNames[i], &prior.enabled) && prior.enabled) + prior.target = *current[i]; + ImGui::BeginDisabled(!prior.enabled); + ImGui::TableNextColumn(); + ImGui::SetNextItemWidth(-FLT_MIN); + float target = static_cast(prior.target); + if (dragFloat("##target", &target, isTranslation ? 0.01f : 0.1f, -180.f, 180.f, isTranslation ? "%.3f m" : "%.2f deg")) + prior.target = target; + ImGui::TableNextColumn(); + ImGui::SetNextItemWidth(-FLT_MIN); + float sigma = static_cast(prior.sigma); + if (dragFloat( + "##sigma", + &sigma, + isTranslation ? 0.001f : 0.01f, + isTranslation ? 0.0001f : 0.001f, + isTranslation ? 10.f : 90.f, + isTranslation ? "%.4f m" : "%.3f deg")) + prior.sigma = std::max(sigma, isTranslation ? 0.0001f : 0.001f); + ImGui::TableNextColumn(); + if (ImGui::SmallButton("= current")) + prior.target = *current[i]; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Set the target to the current %s", kNames[i]); + ImGui::EndDisabled(); + ImGui::EndDisabled(); + ImGui::PopID(); + } + ImGui::EndTable(); } + ImGui::TreePop(); } - ImGui::PopItemWidth(); // Show current rotation matrix if (ImGui::TreeNode("Rotation matrix")) @@ -627,6 +807,29 @@ void UI::panelVisualization(AppState& state) ImGui::PopItemWidth(); ImGui::Checkbox("Show compass/ruler (C)", &state.showCompassRuler); + ImGui::Checkbox("Lidar model", &state.showLidarModel); + ImGui::SameLine(); + ImGui::Checkbox("Camera model", &state.showCameraModel); + helpMarker( + "Simplified, real-size Livox Mid-360 at the LiDAR origin (connector at the back, -x) and\n" + "the camera body below at the camera pose. The yellow ring marks the lens these extrinsics describe.\n" + "Focus on sensors (F) zooms in on them."); + + // Order matches CameraBody's enumerators. + const char* bodies[] = { "Insta360 X5", "PCB camera" }; + int body = static_cast(state.cameraBody); + ImGui::BeginDisabled(!state.showCameraModel); + ImGui::PushItemWidth(-140.f); + if (ImGui::Combo("Camera body", &body, bodies, IM_ARRAYSIZE(bodies))) + state.cameraBody = static_cast(body); + ImGui::PopItemWidth(); + ImGui::EndDisabled(); + helpMarker( + "PCB camera: a bare board in the Raspberry Pi camera format (25 x 24 mm, e.g. an IMX519\n" + "module), ribbon connector at the bottom of the image."); + + if (ImGui::Button("Focus on sensors (F)")) + state.focusOnSensors(); } // ── Correspondences ────────────────────────────────────────────────────────── @@ -635,7 +838,9 @@ void UI::panelVisualization(AppState& state) // ControlPoints::imgui (core/src/control_points.cpp). void UI::panelCorrespondences(AppState& state) { - ImGui::TextWrapped("Hold Shift and click a point in the Image View or the 3D View. Picking both sides completes a pair."); + ImGui::TextWrapped( + "Shift+click the pixel in the Image View, and the LiDAR point in the 3D View -- or Shift+Alt+click it in the Image View, " + "which shows the LiDAR intensity image while both are held. Picking both sides completes a pair."); ImGui::Text("Pending pair:"); ImGui::SameLine(); @@ -685,18 +890,48 @@ void UI::panelCorrespondences(AppState& state) ImGui::SameLine(); if (ImGui::SmallButton("Remove")) removeIndex = i; + if (ImGui::IsItemHovered()) + state.hoveredRemoveIndex = i; ImGui::PopID(); } if (removeIndex >= 0) state.removePair(removeIndex); + ImGui::BeginDisabled(state.pairs.empty() && state.pairsPath.empty()); + if (ImGui::Button("Save pairs")) + actionSavePairs(state); + ImGui::EndDisabled(); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + { + if (state.pairsPath.empty()) + ImGui::SetTooltip("Ctrl+S; asks for a file"); + else + ImGui::SetTooltip("Ctrl+S, to %s", state.pairsPath.c_str()); + } + ImGui::SameLine(); + if (ImGui::Button("Load pairs...")) + actionLoadPairs(state); + helpMarker( + "Or drop a saved pairs .json on the window, or pass --pairs .\n" + "Loading replaces the current pairs. Ctrl+S saves to the last pairs file\n" + "loaded or saved, or the --pairs one (created if it does not exist yet).\n" + "Pixels are of the shown image (rectified or raw) -- load the same image and calibration first."); + if (!state.pairsPath.empty()) + ImGui::TextDisabled("Pairs file: %s", std::filesystem::path(state.pairsPath).filename().string().c_str()); + ImGui::Spacing(); - ImGui::BeginDisabled(state.pairs.size() < 3); + const std::string refined = state.refinedIntrinsicsLabel(); + const bool nothingFree = state.lockTranslation && state.lockRotation && refined.empty(); + ImGui::BeginDisabled(state.pairs.size() < 3 || nothingFree); if (ImGui::Button("Solve Extrinsics from Pairs", ImVec2(-1, 0))) state.solvePairs(); ImGui::EndDisabled(); if (state.pairs.size() < 3) ImGui::TextDisabled("At least 3 pairs needed"); + else if (nothingFree) + ImGui::TextDisabled("Translation and rotation are both locked"); + if (!refined.empty()) + ImGui::TextDisabled("Also refines %s", refined.c_str()); if (state.lastSolveRmsPixels >= 0.0) ImGui::Text("Last solve RMS reprojection error: %.2f px", state.lastSolveRmsPixels); } diff --git a/apps/camera_lidar_calibration/UI.h b/apps/camera_lidar_calibration/UI.h index 27c056f83..7955c7d93 100644 --- a/apps/camera_lidar_calibration/UI.h +++ b/apps/camera_lidar_calibration/UI.h @@ -25,6 +25,11 @@ class UI float imgZoom = 1.f; // 1 = actual size (1 image px = 1 screen px) int lastImgW = 0, lastImgH = 0; // detects a newly-loaded image, to reset imgZoom + //! Alt's colour-mode toggle fires on release, and only when Shift was not + //! part of the chord (Shift+Alt picks in the LiDAR intensity image). + bool altWasDown = false; + bool altChorded = false; + void drawImageView(AppState& state); void panelMenuBar(AppState& state); void panelFiles(AppState& state); @@ -42,5 +47,8 @@ class UI void actionOpenIntrinsics(AppState& state); void actionOpenCalibration(AppState& state); void actionSaveCalibration(AppState& state); + void actionLoadPairs(AppState& state); + void actionSavePairs(AppState& state); // to state.pairsPath, else asks + void actionSavePairsAs(AppState& state); void handleShortcuts(AppState& state); }; diff --git a/apps/camera_lidar_calibration/main.cpp b/apps/camera_lidar_calibration/main.cpp index 18148fb8d..4cd54aa8d 100644 --- a/apps/camera_lidar_calibration/main.cpp +++ b/apps/camera_lidar_calibration/main.cpp @@ -23,7 +23,7 @@ static bool isImage(const std::string& e) return e == "jpg" || e == "jpeg" || e == "png" || e == "bmp"; } -// Load each path by file type (clouds, images, intrinsics, calibration). +// Load each path by file type (clouds, images, intrinsics, calibration, picked pairs). static void preloadByExt(App& app, const std::string& p) { std::string e = ext(p); @@ -33,14 +33,22 @@ static void preloadByExt(App& app, const std::string& p) app.preloadCloud(p.c_str()); else if (e == "yml" || e == "yaml") app.preloadIntrinsics(p.c_str()); + else if (e == "json" && AppState::isPairsFile(p.c_str())) + app.preloadPairs(p.c_str()); else if (e == "json") app.preloadCalibration(p.c_str()); } +static constexpr const char* kClosestToLaz = " --closest_to_laz with --camera_dir : load the image taken closest\n" + " to the middle of the --laz clouds' point times"; + +static constexpr const char* kPairs = " --pairs picked pairs: loaded when the file exists; Ctrl+S saves\n" + " the pairs to it"; + int main(int argc, char* argv[]) { CliArgs args = parseArgs(argc, argv); - const std::vector usage = { cliopt::CAMERA_DIR, cliopt::LAZ, cliopt::CALIB }; + const std::vector usage = { cliopt::CAMERA_DIR, kClosestToLaz, cliopt::LAZ, cliopt::CALIB, kPairs }; if (args.help) { printUsage("CalibrationApp", "Camera/LiDAR calibration tool", usage); @@ -63,7 +71,16 @@ int main(int argc, char* argv[]) if (args.has("calib")) app.preloadCalibration(args.get("calib").c_str()); - // --camera_dir: load the first image found in the directory. + // --pairs: picked pairs, loaded if the file exists; Ctrl+S saves to it. + if (args.has("pairs")) + app.preloadPairs(args.get("pairs").c_str()); + + // --camera_dir: load the first image found in the directory; with + // --closest_to_laz it is replaced, once the clouds are loaded, by the one + // taken closest to their time. + const bool closestToLaz = args.has("closest_to_laz"); + if (closestToLaz && !(args.has("camera_dir") && fs::is_directory(args.get("camera_dir")))) + std::fprintf(stderr, "--closest_to_laz needs --camera_dir ; ignored\n"); if (args.has("camera_dir")) { fs::path dir(args.get("camera_dir")); @@ -76,6 +93,8 @@ int main(int argc, char* argv[]) std::sort(imgs.begin(), imgs.end()); if (!imgs.empty()) app.preloadImage(imgs.front().string().c_str()); + if (closestToLaz) + app.preloadImageClosestToClouds(dir.string().c_str()); } else if (fs::is_regular_file(dir)) { @@ -84,8 +103,13 @@ int main(int argc, char* argv[]) } // Positional files keep working by extension (drag-and-drop / shell glob). + // The parser gives a flag every plain argument after it, so files that + // follow the value-less --closest_to_laz are positional too. for (const auto& p : args.positional) preloadByExt(app, p); + for (const auto& p : args.getAll("closest_to_laz")) + if (!p.empty()) + preloadByExt(app, p); app.run(); return 0; diff --git a/apps/camera_lidar_depth_images/CMakeLists.txt b/apps/camera_lidar_depth_images/CMakeLists.txt new file mode 100644 index 000000000..eab04ca4c --- /dev/null +++ b/apps/camera_lidar_depth_images/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 4.0.0) + +project(camera_lidar_depth_images) + +# Command-line tool: renders a session's lidar points into the camera every N +# seconds and writes depth and intensity images. Same inputs as +# camera_lidar_trajectory_viewer (--mjs, --calib, --camera_dir); no GUI. +add_executable(camera_lidar_depth_images + DepthImages.cpp +) + +target_include_directories(camera_lidar_depth_images PRIVATE + ${EIGEN3_INCLUDE_DIR} +) + +target_link_libraries(camera_lidar_depth_images PRIVATE + calib_core + ${OpenCV_LIBS} + ${PLATFORM_MISCELLANEOUS_LIBS} +) + +if(MSVC) + target_compile_options(camera_lidar_depth_images PRIVATE /W4) + target_compile_definitions(camera_lidar_depth_images PRIVATE _USE_MATH_DEFINES) +else() + target_compile_options(camera_lidar_depth_images PRIVATE -Wall -Wextra) +endif() + +if(WIN32) + add_custom_command( + TARGET camera_lidar_depth_images + POST_BUILD + COMMAND + ${CMAKE_COMMAND} -E copy + $ + $ + COMMAND_EXPAND_LISTS) +endif() + +hdmapping_install_app(camera_lidar_depth_images) diff --git a/apps/camera_lidar_depth_images/DepthImages.cpp b/apps/camera_lidar_depth_images/DepthImages.cpp new file mode 100644 index 000000000..7c637caf3 --- /dev/null +++ b/apps/camera_lidar_depth_images/DepthImages.cpp @@ -0,0 +1,462 @@ +//! camera_lidar_depth_images: renders a session's lidar points into the camera +//! at regular intervals and writes, per selected frame, a depth image and an +//! intensity image the size of the camera image (or scaled by --scale). +//! +//! Same inputs as camera_lidar_trajectory_viewer: the session (.mjs), the +//! camera-lidar calibration JSON and the camera frames, whose timestamps must be +//! on the lidar clock. Every point within --window seconds of the frame is moved +//! into the lidar frame at the frame time (trajectory interpolated) and +//! projected with calib::projectPoint; the nearest point wins each pixel. + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; +using namespace calib; + +namespace +{ + constexpr const char* kAppName = "camera_lidar_depth_images"; + + //! Depth images store millimetres in 16 bits, so this is the farthest depth they can hold. + constexpr float kMaxEncodableDepthM = 65.534f; + + //! Intensity shown white in the intensity preview. Livox reflectivity is diffuse up to 150 of 255 and + //! retroreflective above, so the grey scale spans the diffuse range. + constexpr float kPreviewMaxIntensity = 150.f / 255.f; + + struct Options + { + fs::path mjs, calib, cameraDir, outDir; + double everySec = 5.0; + double windowSec = 10.0; + float scale = 1.f; + float minDepth = 0.3f; + float maxDepth = kMaxEncodableDepthM; + int pointRadius = 0; + bool previewDepth = false; + bool previewIntensity = false; + }; + + //! A lidar point in the session's world frame. + struct WorldPoint + { + Eigen::Vector3f p; + float intensity; //!< [0,1], as calib::PointCloud normalizes it + int64_t ts_ns; + }; + + //! One scan_lio_N chunk and the time span of its trajectory. + struct Chunk + { + fs::path laz; + Eigen::Affine3f pose = Eigen::Affine3f::Identity(); + int64_t first = 0, last = 0; + }; + + struct Frame + { + int64_t ts; + fs::path image; + Eigen::Affine3f T_wl; //!< lidar pose at the frame time + }; + + bool parseNumber(const CliArgs& a, const char* key, double& out) + { + if (!a.has(key)) + return true; + try + { + out = std::stod(a.get(key)); + return true; + } catch (const std::exception&) + { + std::fprintf(stderr, "--%s: not a number: '%s'\n", key, a.get(key).c_str()); + return false; + } + } + + void usage(bool toStderr) + { + printUsage( + kAppName, + "renders lidar depth and intensity images at camera frames, one frame every --every seconds", + { cliopt::MJS, + cliopt::CALIB, + cliopt::CAMERA_DIR, + " --out output directory (default: _lidar_images)", + " --every seconds between rendered frames (default 5)", + " --window use points within +/- this many seconds of the frame (default 10)", + " --scale output size relative to the camera image (default 1)", + " --min_depth drop points closer than this (default 0.3)", + " --max_depth drop points farther than this (default and maximum 65.534)", + " --point_radius draw each point as a disc of this radius (default 0 = one pixel)", + " --preview [depth] [intensity] also write images for viewing: depth over the camera image\n" + " (preview/.jpg, the default) and/or the intensity image\n" + " with enlarged points (preview_intensity/.jpg)" }, + toStderr); + } + + bool parseOptions(int argc, char* argv[], Options& o) + { + const CliArgs a = parseArgs(argc, argv); + if (a.help) + { + usage(false); + std::exit(0); + } + if (!a.valid || !a.has("mjs") || !a.has("calib") || !a.has("camera_dir")) + { + if (!a.valid) + std::fprintf(stderr, "%s\n", a.error.c_str()); + usage(true); + return false; + } + o.mjs = a.get("mjs"); + o.calib = a.get("calib"); + o.cameraDir = fs::path(a.get("camera_dir")); + if (!o.cameraDir.has_filename()) + o.cameraDir = o.cameraDir.parent_path(); // trailing separator + o.outDir = a.has("out") ? fs::path(a.get("out")) : o.cameraDir.parent_path() / (o.cameraDir.filename().string() + "_lidar_images"); + double scale = o.scale, minDepth = o.minDepth, maxDepth = o.maxDepth, radius = o.pointRadius; + if (!parseNumber(a, "every", o.everySec) || !parseNumber(a, "window", o.windowSec) || !parseNumber(a, "scale", scale) || + !parseNumber(a, "min_depth", minDepth) || !parseNumber(a, "max_depth", maxDepth) || !parseNumber(a, "point_radius", radius)) + return false; + o.scale = float(scale); + o.minDepth = float(minDepth); + o.maxDepth = std::min(float(maxDepth), kMaxEncodableDepthM); + o.pointRadius = std::max(0, int(std::lround(radius))); + for (const std::string& v : a.getAll("preview")) + { + if (v.empty() || v == "depth") + o.previewDepth = true; + else if (v == "intensity") + o.previewIntensity = true; + else + { + std::fprintf(stderr, "--preview: expected depth or intensity, got '%s'\n", v.c_str()); + return false; + } + } + if (o.everySec < 0.0 || o.windowSec < 0.0 || o.scale <= 0.f || o.minDepth >= o.maxDepth) + { + std::fprintf(stderr, "Invalid --every, --window, --scale or depth range\n"); + return false; + } + return true; + } + + //! Every chunk of the session with its pose and the time span of its trajectory CSV. + std::vector listChunks(const SessionFiles& sf) + { + std::vector chunks; + for (const auto& lp : sf.lazPaths) + { + Trajectory t; + t.loadCSV(chunkTrajectoryCsv(lp).string()); + t.sort(); + if (t.empty()) + { + std::fprintf(stderr, "No trajectory for %s, skipped\n", lp.string().c_str()); + continue; + } + Chunk c; + c.laz = lp; + if (auto it = sf.poses.find(lp.stem().string()); it != sf.poses.end()) + c.pose = it->second; + c.first = t.poses.front().ts_ns; + c.last = t.poses.back().ts_ns; + chunks.push_back(std::move(c)); + } + return chunks; + } + + std::vector loadChunk(const Chunk& c) + { + std::vector out; + PointCloud pc; + if (!pc.load(c.laz.string())) + { + std::fprintf(stderr, "Cannot read %s\n", c.laz.string().c_str()); + return out; + } + out.reserve(pc.points.size()); + for (const auto& pt : pc.points) + out.push_back({ c.pose * Eigen::Vector3f(pt.x, pt.y, pt.z), pt.intensity, pt.ts_ns }); + return out; + } + + //! Depth (metres, 0 = no point) and intensity ([0,1]) of the nearest point per pixel. + struct Rendering + { + cv::Mat depth; //!< CV_32F + cv::Mat intensity; //!< CV_32F + size_t projected = 0; + }; + + Rendering render( + const std::vector*>& clouds, + const Frame& f, + const Options& o, + const Intrinsics& Ks, + const Eigen::Matrix3f& R_wc, + const Eigen::Vector3f& C) + { + Rendering r; + r.depth = cv::Mat(Ks.height, Ks.width, CV_32F, cv::Scalar(std::numeric_limits::infinity())); + r.intensity = cv::Mat(Ks.height, Ks.width, CV_32F, cv::Scalar(0.f)); + const Eigen::Affine3f T_lw = f.T_wl.inverse(); + const int64_t windowNs = std::llround(o.windowSec * 1e9); + const int rad = o.pointRadius; + + for (const auto* cloud : clouds) + { + for (const auto& wp : *cloud) + { + if (std::llabs(wp.ts_ns - f.ts) > windowNs) + continue; + const Eigen::Vector3f pl = T_lw * wp.p; + float u, v, depth; + if (!projectPoint(pl.x(), pl.y(), pl.z(), Ks, R_wc, C, u, v, depth)) + continue; + if (depth < o.minDepth || depth > o.maxDepth) + continue; + // Bounded before the int conversion: near-grazing points can land far outside. + if (!(u > -0.5f - rad && v > -0.5f - rad && u < Ks.width - 0.5f + rad && v < Ks.height - 0.5f + rad)) + continue; + const int iu = int(std::lround(u)); + const int iv = int(std::lround(v)); + ++r.projected; + for (int dy = -rad; dy <= rad; ++dy) + { + const int y = iv + dy; + if (y < 0 || y >= Ks.height) + continue; + for (int dx = -rad; dx <= rad; ++dx) + { + const int x = iu + dx; + if (x < 0 || x >= Ks.width || dx * dx + dy * dy > rad * rad) + continue; + float& zb = r.depth.at(y, x); + if (depth < zb) + { + zb = depth; + r.intensity.at(y, x) = wp.intensity; + } + } + } + } + } + r.depth.setTo(0.f, r.depth == std::numeric_limits::infinity()); + return r; + } + + //! The camera image resized to the rendering, or an empty Mat when it can't be read. + cv::Mat readPhoto(const fs::path& image, cv::Size size) + { + cv::Mat img = cv::imread(image.string(), cv::IMREAD_COLOR); + if (!img.empty() && img.size() != size) + cv::resize(img, img, size, 0, 0, cv::INTER_AREA); + return img; + } + + //! `values` scaled so that maxValue maps to 255, clamped. + cv::Mat toByte(const cv::Mat& values, float maxValue) + { + cv::Mat value8; + values.convertTo(value8, CV_8U, 255.0 / maxValue); + return value8; + } + + //! `canvas` with `colors` copied into every pixel that has a point. Single pixels vanish in a downscaled + //! view of a large image, so the points are grown for display. + cv::Mat paintPoints(cv::Mat canvas, const cv::Mat& colors, const cv::Mat& hasPoint) + { + const int grow = std::max(1, colors.cols / 1000); + const cv::Mat kernel = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(2 * grow + 1, 2 * grow + 1)); + cv::Mat grown, valid; + cv::dilate(colors, grown, kernel); + cv::dilate(hasPoint, valid, kernel); + grown.copyTo(canvas, valid); + return canvas; + } +} // namespace + +int main(int argc, char* argv[]) +{ + Options o; + if (!parseOptions(argc, argv, o)) + return 1; + + std::string err; + const fs::path mjs = resolveMjs(o.mjs, err); + SessionFiles sf; + if (mjs.empty() || !readSessionFiles(mjs, sf, err)) + { + std::fprintf(stderr, "%s\n", err.c_str()); + return 1; + } + if (!sf.hasPoses) + std::fprintf(stderr, "Warning: no poses file in %s, chunks stay in their local frames\n", mjs.string().c_str()); + Trajectory traj; + loadSessionTrajectory(sf, traj); + if (traj.empty()) + { + std::fprintf(stderr, "No trajectory in %s\n", mjs.string().c_str()); + return 1; + } + const auto trajMap = buildTrajMap(traj); + const std::vector chunks = listChunks(sf); + + Intrinsics K; + Eigen::Matrix3f R_wc = Eigen::Matrix3f::Identity(); + Eigen::Vector3f C = Eigen::Vector3f::Zero(); + Roi roi; + if (!loadCalibrationJson(o.calib.string(), K, R_wc, C, roi, err)) + { + std::fprintf(stderr, "%s\n", err.c_str()); + return 1; + } + + // Frames on the trajectory, one every o.everySec. + std::map images; + if (!fs::is_directory(o.cameraDir)) + { + std::fprintf(stderr, "No camera directory %s\n", o.cameraDir.string().c_str()); + return 1; + } + for (const auto& e : fs::directory_iterator(o.cameraDir)) + if (const int64_t ts = parseImageTsNs(e.path()); ts >= 0) + images[ts] = e.path(); + std::vector frames; + int64_t next = std::numeric_limits::min(); + const int64_t everyNs = std::llround(o.everySec * 1e9); + for (const auto& [ts, path] : images) + { + Eigen::Affine3f T; + if (ts < next || !interpPose(trajMap, ts, T)) + continue; + frames.push_back({ ts, path, T }); + next = ts + everyNs; + } + if (frames.empty()) + { + std::fprintf(stderr, "None of the %zu images in %s falls on the trajectory\n", images.size(), o.cameraDir.string().c_str()); + return 1; + } + + const cv::Mat probe = cv::imread(frames.front().image.string(), cv::IMREAD_COLOR); + if (probe.empty()) + { + std::fprintf(stderr, "Cannot read %s\n", frames.front().image.string().c_str()); + return 1; + } + K.width = probe.cols; + K.height = probe.rows; + const Intrinsics Ks = scaleIntrinsics(K, o.scale); + + std::error_code ec; + fs::create_directories(o.outDir / "depth", ec); + fs::create_directories(o.outDir / "intensity", ec); + if (o.previewDepth) + fs::create_directories(o.outDir / "preview", ec); + if (o.previewIntensity) + fs::create_directories(o.outDir / "preview_intensity", ec); + std::ofstream index(o.outDir / "frames.csv"); + if (!index) + { + std::fprintf(stderr, "Cannot write to %s\n", o.outDir.string().c_str()); + return 1; + } + index << "image,timestamp_ns,points_projected,pixels_with_depth\n"; + + std::printf( + "%zu images, %zu frames to render (every %.1f s), %zu chunks, %dx%d px -> %s\n", + images.size(), + frames.size(), + o.everySec, + chunks.size(), + Ks.width, + Ks.height, + o.outDir.string().c_str()); + + // Frames are in time order, so the chunks a frame needs are kept until a later frame no longer does. + std::map> loaded; + const int64_t windowNs = std::llround(o.windowSec * 1e9); + for (size_t fi = 0; fi < frames.size(); ++fi) + { + const Frame& f = frames[fi]; + std::vector*> clouds; + for (size_t ci = 0; ci < chunks.size(); ++ci) + { + // A chunk's points can sit a little past its last trajectory pose; one second covers that. + const int64_t margin = 1'000'000'000; + const bool needed = chunks[ci].first - margin <= f.ts + windowNs && chunks[ci].last + margin >= f.ts - windowNs; + if (!needed) + { + loaded.erase(ci); + continue; + } + auto it = loaded.find(ci); + if (it == loaded.end()) + it = loaded.emplace(ci, loadChunk(chunks[ci])).first; + clouds.push_back(&it->second); + } + + const Rendering r = render(clouds, f, o, Ks, R_wc, C); + cv::Mat depthMm, intensity8; + r.depth.convertTo(depthMm, CV_16U, 1000.0); + r.intensity.convertTo(intensity8, CV_8U, 255.0); + const int withDepth = cv::countNonZero(depthMm); + const std::string stem = f.image.stem().string(); + bool ok = cv::imwrite((o.outDir / "depth" / (stem + ".png")).string(), depthMm); + ok &= cv::imwrite((o.outDir / "intensity" / (stem + ".png")).string(), intensity8); + const cv::Mat hasPoint = r.depth > 0.f; + if (o.previewDepth) + { + // Turbo, near = blue, over the camera image. + cv::Mat photo = readPhoto(f.image, r.depth.size()); + cv::Mat colors; + cv::applyColorMap(toByte(r.depth, o.maxDepth), colors, cv::COLORMAP_TURBO); + ok &= !photo.empty() && + cv::imwrite((o.outDir / "preview" / (stem + ".jpg")).string(), paintPoints(std::move(photo), colors, hasPoint)); + } + if (o.previewIntensity) + { + const cv::Mat black = cv::Mat::zeros(r.intensity.size(), CV_8U); + ok &= cv::imwrite( + (o.outDir / "preview_intensity" / (stem + ".jpg")).string(), + paintPoints(black, toByte(r.intensity, kPreviewMaxIntensity), hasPoint)); + } + if (!ok) + std::fprintf(stderr, "Failed to write the images of %s\n", stem.c_str()); + index << f.image.filename().string() << ',' << f.ts << ',' << r.projected << ',' << withDepth << '\n'; + std::printf( + "[%zu/%zu] %s %zu points, %.2f%% pixels with depth\n", + fi + 1, + frames.size(), + stem.c_str(), + r.projected, + 100.0 * withDepth / (double(Ks.width) * Ks.height)); + std::fflush(stdout); + } + return 0; +} diff --git a/apps/camera_lidar_trajectory_viewer/TrajectoryViewer.cpp b/apps/camera_lidar_trajectory_viewer/TrajectoryViewer.cpp index 319f7924e..544635047 100644 --- a/apps/camera_lidar_trajectory_viewer/TrajectoryViewer.cpp +++ b/apps/camera_lidar_trajectory_viewer/TrajectoryViewer.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -178,87 +179,6 @@ static double trajectoryDurationSec(const Trajectory& traj) return double(traj.poses.back().ts_ns - traj.poses.front().ts_ns) * 1e-9; } -//! Smallest "round" tick step (s) that keeps ticks at least `minPx` apart. -static double timelineTickStep(double durationSec, float widthPx, float minPx) -{ - static const double kSteps[] = { 0.1, 0.2, 0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600 }; - const double pxPerSec = widthPx / durationSec; - for (double step : kSteps) - if (step * pxPerSec >= minPx) - return step; - double step = kSteps[std::size(kSteps) - 1]; - while (step * pxPerSec < minPx) - step *= 2.0; - return step; -} - -//! Tick label: "m:ss" from a minute on, else seconds with a decimal only when -//! the tick step needs one. -static std::string formatTickLabel(double sec, double step) -{ - char buf[32]; - if (sec >= 60.0) - std::snprintf(buf, sizeof(buf), "%d:%02d", int(sec + 1e-6) / 60, int(sec + 1e-6) % 60); - else if (step < 1.0) - std::snprintf(buf, sizeof(buf), "%.1fs", sec); - else - std::snprintf(buf, sizeof(buf), "%.0fs", sec); - return buf; -} - -//! Timeline across the available width, with time ticks and a playhead. -//! Click or drag on it to scrub. -//! @param id ImGui id of the scrub area -//! @param progress 0-1 playhead position; written while the user drags -//! @param durationSec time the full width spans, for the tick labels -//! @param height total height, including the tick label row -static void flyoverTimeline(const char* id, float& progress, double durationSec, float height) -{ - ImDrawList* dl = ImGui::GetWindowDrawList(); - const ImVec2 p0 = ImGui::GetCursorScreenPos(); - const float w = std::max(1.f, ImGui::GetContentRegionAvail().x); - const float trackH = height - ImGui::GetTextLineHeight(); - const ImVec2 p1(p0.x + w, p0.y + trackH); - - ImGui::InvisibleButton(id, ImVec2(w, height)); - if (ImGui::IsItemActive()) - progress = std::clamp((ImGui::GetIO().MousePos.x - p0.x) / w, 0.f, 1.f); - if (ImGui::IsItemHovered() && durationSec > 0.0) - { - const float f = std::clamp((ImGui::GetIO().MousePos.x - p0.x) / w, 0.f, 1.f); - ImGui::SetTooltip("%.2f s", f * durationSec); - } - - dl->AddRectFilled(p0, p1, IM_COL32(40, 40, 40, 255), 3.f); - dl->AddRectFilled(p0, ImVec2(p0.x + w * progress, p1.y), IM_COL32(60, 110, 160, 255), 3.f, ImDrawFlags_RoundCornersLeft); - - if (durationSec > 0.0) - { - // Major ticks carry a label; four unlabelled minor ticks between them. - const double major = timelineTickStep(durationSec, w, 70.f); - const double minor = major / 5.0; - const double pxPerSec = w / durationSec; - for (int k = 0; k * minor <= durationSec + 1e-9; ++k) - { - const bool isMajor = k % 5 == 0; - const float x = p0.x + float(k * minor * pxPerSec); - dl->AddLine(ImVec2(x, p1.y - trackH * (isMajor ? 0.6f : 0.3f)), ImVec2(x, p1.y), IM_COL32(170, 170, 170, 255)); - if (isMajor) - { - const std::string label = formatTickLabel(k * minor, major); - const float lw = ImGui::CalcTextSize(label.c_str()).x; - const float lx = std::clamp(x - lw * 0.5f, p0.x, p0.x + w - lw); - dl->AddText(ImVec2(lx, p1.y), IM_COL32(200, 200, 200, 255), label.c_str()); - } - } - } - - const float px = p0.x + w * progress; - const ImU32 playheadCol = IM_COL32(255, 220, 60, 255); - dl->AddLine(ImVec2(px, p0.y), ImVec2(px, p1.y), playheadCol, 2.f); - dl->AddTriangleFilled(ImVec2(px - 5.f, p0.y), ImVec2(px + 5.f, p0.y), ImVec2(px, p0.y + 6.f), playheadCol); -} - using trajectory_viewer_shaders::kFS; using trajectory_viewer_shaders::kVS; @@ -3464,7 +3384,7 @@ int main(int argc, char* argv[]) if (ImGui::Button("Close")) toggleFlyover(s); - flyoverTimeline("##flyoverTimeline", s.flyoverProgress, durationSec, timelineH); + raylib_widgets::timeline("##flyoverTimeline", s.flyoverProgress, durationSec, timelineH); ImGui::End(); } diff --git a/apps/lidar_odometry_step_1/lidar_odometry.cpp b/apps/lidar_odometry_step_1/lidar_odometry.cpp index 2cfd90f58..d90f7d9d0 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry.cpp +++ b/apps/lidar_odometry_step_1/lidar_odometry.cpp @@ -112,6 +112,20 @@ static void report_lidar_gaps( std::cerr << "WARNING: ... and " << lines.size() - kMaxLines << " more\n"; } +//! Time span and sample count of one IMU file's samples. +static InputFileSpan imu_file_span(const std::string& file, const Imu& samples) +{ + InputFileSpan span{ file }; + for (const auto& sample : samples) + { + const double t = std::get<0>(sample).first; + span.first = span.count == 0 ? t : std::min(span.first, t); + span.last = span.count == 0 ? t : std::max(span.last, t); + span.count++; + } + return span; +} + bool load_data( std::vector& input_file_names, LidarOdometryParams& params, @@ -119,6 +133,19 @@ bool load_data( Imu& imu_data, bool debugMsg) { + InputFileSpans unused; + return load_data(input_file_names, params, pointsPerFile, imu_data, debugMsg, unused); +} + +bool load_data( + std::vector& input_file_names, + LidarOdometryParams& params, + std::vector>& pointsPerFile, + Imu& imu_data, + bool debugMsg, + InputFileSpans& fileSpans) +{ + fileSpans = {}; if (!params.run_report || params.run_report->live().status != "running") params.run_report = std::make_shared( input_file_names.empty() ? fs::path{} : fs::path(input_file_names.front()).parent_path(), params.points_global_spill_directory); @@ -313,6 +340,9 @@ bool load_data( } }); + for (size_t i = 0; i < minSize; ++i) + fileSpans.imu.push_back(imu_file_span(csv_files[i], imuChunks[i])); + // Merge all chunks sequentially at the end for (auto& chunk : imuChunks) imu_data.insert(imu_data.end(), std::make_move_iterator(chunk.begin()), std::make_move_iterator(chunk.end())); @@ -342,6 +372,9 @@ bool load_data( { murataChunks[i] = load_imu(murataFiles[i], imuNumberToUse); }); + fileSpans.imu.clear(); + for (size_t i = 0; i < murataFiles.size(); ++i) + fileSpans.imu.push_back(imu_file_span(murataFiles[i], murataChunks[i])); for (auto& chunk : murataChunks) imu_data.insert(imu_data.end(), std::make_move_iterator(chunk.begin()), std::make_move_iterator(chunk.end())); } @@ -430,6 +463,8 @@ bool load_data( gaps_in_file[i] = find_lidar_gaps(data, kLidarGapWarningS); }); report_lidar_gaps(L.files, firstUsedFile, gaps_in_file, L.t_first, L.t_last); + for (size_t i = 0; i < minSize; ++i) + fileSpans.laz.push_back({ L.files[i], L.t_first[i], L.t_last[i], L.n[i] }); if (params.save_calibration_validation && minSize > 0) // as the eager load: the first file, then dropped write_calibration_validation(wdp, L.load(0), params); size_t totalPoints = 0; @@ -476,6 +511,8 @@ bool load_data( pointsPerFile[i] = std::move(data); }); report_lidar_gaps(laz_files, firstUsedFile, gaps_in_file, t_first, t_last); + for (size_t i = 0; i < minSize; ++i) + fileSpans.laz.push_back({ laz_files[i], t_first[i], t_last[i], pointsPerFile[i].size() }); if (params.skip_first_file && pointsPerFile.size() > 0) pointsPerFile.front().clear(); diff --git a/apps/lidar_odometry_step_1/lidar_odometry.h b/apps/lidar_odometry_step_1/lidar_odometry.h index f76757ec2..6ca4c19ed 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry.h +++ b/apps/lidar_odometry_step_1/lidar_odometry.h @@ -16,12 +16,40 @@ using Trajectory = std::map>; using Imu = std::vector, Eigen::Vector3f, Eigen::Vector3f>>; +//! Time span of one input file as load_data read it. +struct InputFileSpan +{ + std::string file; + double first = 0.0; //!< first sample's LiDAR-clock time [s]; 0 when count is 0 + double last = 0.0; //!< last sample's LiDAR-clock time [s] + size_t count = 0; //!< points or IMU samples read +}; + +//! Per-file spans load_data reports when asked, e.g. for a Gantt chart of the session. +struct InputFileSpans +{ + //! LAZ files paired with an IMU file, the first one included although load_data drops its points + //! (count 0 for it with lazy_load_raw_clouds, which never reads it) + std::vector laz; + //! IMU files the samples came from: imu****.csv, or MURATA_IMU's csv files when those are used + std::vector imu; +}; + bool load_data( std::vector& input_file_names, LidarOdometryParams& params, std::vector>& pointsPerFile, Imu& imu_data, bool debugMsg); +//! As above, and reports each input file's time span. +//! @param fileSpans receives the spans; reset first +bool load_data( + std::vector& input_file_names, + LidarOdometryParams& params, + std::vector>& pointsPerFile, + Imu& imu_data, + bool debugMsg, + InputFileSpans& fileSpans); void calculate_trajectory(Trajectory& trajectory, Imu& imu_data, LidarOdometryParams& params, bool debugMsg); // pointsPerFile is read, and with lazy_load_raw_clouds loaded and freed file by file bool compute_step_1( diff --git a/apps/mandeye_raw_data_viewer/mandeye_raw_data_viewer.cpp b/apps/mandeye_raw_data_viewer/mandeye_raw_data_viewer.cpp index 13115a6fc..535df5524 100644 --- a/apps/mandeye_raw_data_viewer/mandeye_raw_data_viewer.cpp +++ b/apps/mandeye_raw_data_viewer/mandeye_raw_data_viewer.cpp @@ -20,13 +20,20 @@ #include #include +#include + #include #include "../lidar_odometry_step_1/lidar_odometry.h" #include "../lidar_odometry_step_1/lidar_odometry_utils.h" #include #include +#include #include +#include +#include +#include +#include #include @@ -86,6 +93,11 @@ struct ImuData ImuData imu_data_plot; std::vector laz_files; +//! Time span of every LAZ and IMU file load_data read, drawn as lanes under the playback timeline. +InputFileSpans file_spans; +//! [start, end] LiDAR-clock times [s] of the stretches VQF detected the IMU at rest. +std::vector> motionless_segments; +bool show_file_lanes = true; std::vector photos_files; std::map photo_files_ts; @@ -98,6 +110,13 @@ bool fusionConventionNed = false; int number_of_points_threshold = 20000; bool is_init = false; int index_rendered_points_local = -1; + +// Playback bar (bottom of the window). The playhead is a time in seconds since the +// first chunk's start; index_rendered_points_local follows it while playing/scrubbing. +double playhead_sec = 0.0; +bool playback_playing = false; +float playback_speed = 1.0f; +int playhead_index = -1; //!< chunk the playhead last matched; another index means it was picked elsewhere // std::vector> all_points_local; // std::vector> all_points_local; // std::vector> all_lidar_ids; @@ -888,7 +907,7 @@ std::vector> get_mean_cov() // Re-chunks the already-loaded points (g_points_per_file / g_timestamps_cache / g_poses_cache) // into all_data using the current number_of_points_threshold. Smaller thresholds mean each -// Index step in the toolbar covers less time, giving finer time navigation. +// Index step in the playback bar covers less time, giving finer time navigation. void rebuildAllData(bool preserve_position) { double preserved_time = 0.0; @@ -1007,6 +1026,11 @@ void rebuildAllData(bool preserve_position) is_init = false; index_rendered_points_local = -1; } + + // re-anchor the playhead on the (re)selected chunk; a new dataset starts paused + playhead_index = -1; + if (!preserve_position) + playback_playing = false; } void loadFiles(std::vector input_file_names) @@ -1025,7 +1049,7 @@ void loadFiles(std::vector input_file_names) if (input_file_names.empty()) return; - if (load_data(input_file_names, params, pointsPerFile, imu_data, false)) + if (load_data(input_file_names, params, pointsPerFile, imu_data, false, file_spans)) { // clear possible previous data @@ -1130,6 +1154,12 @@ void loadFiles(std::vector input_file_names) std::map> trajectory; + // Motionless segments: runs of samples VQF flags as rest. It flags rest once the + // IMU has been still for restMinT, so each run is moved that much earlier. + motionless_segments.clear(); + bool resting = false; + double rest_start = 0.0, previous_t = 0.0; + int counter = 1; for (const auto& [timestamp_pair, gyr, acc] : imu_data) @@ -1142,6 +1172,18 @@ void loadFiles(std::vector input_file_names) vqf.update(gyr_vqf, acc_vqf); + const bool rest = vqf.getRestDetected(); + if (rest && !resting) + { + rest_start = timestamp_pair.first - vqf_params.restMinT; + if (!motionless_segments.empty()) + rest_start = std::max(rest_start, motionless_segments.back().second); + } + else if (!rest && resting) + motionless_segments.emplace_back(rest_start, previous_t); + resting = rest; + previous_t = timestamp_pair.first; + vqf_real_t quat[4]; vqf.getQuat6D(quat); Eigen::Quaterniond d(quat[0], quat[1], quat[2], quat[3]); @@ -1170,6 +1212,10 @@ void loadFiles(std::vector input_file_names) imu_data_plot.roll.push_back(euler.x()); } + if (resting) + motionless_segments.emplace_back(rest_start, previous_t); + spdlog::info("{} motionless segment(s) detected", motionless_segments.size()); + // timeline x-axis is shown relative to the first IMU sample so it starts at 0 [s]; // datasetStart keeps the absolute value for reference / annotations if (!imu_data_plot.timestampLidar.empty()) @@ -1380,7 +1426,7 @@ void settings_gui() { ImGui::BeginTooltip(); ImGui::Text("Max number of points per rendered chunk (one 'Index' step)."); - ImGui::Text("Lower = shorter time span per chunk = finer time navigation with the Index slider."); + ImGui::Text("Lower = shorter time span per chunk = finer time navigation in the playback bar."); ImGui::EndTooltip(); } ImGui::BeginDisabled(!is_init); @@ -1539,6 +1585,210 @@ void settings_gui() ImGui::End(); } +//! Absolute LiDAR time of chunk `i`'s first point [s]. +static double chunkStartSec(int i) +{ + return all_data[i].points_local.front().timestamp; +} + +//! Time the playback bar spans [s]: from the first chunk's start to the last chunk's last point. +static double playbackDurationSec() +{ + return std::max(0.0, all_data.back().points_local.back().timestamp - chunkStartSec(0)); +} + +//! Chunk shown at the playhead: the last one starting at or before it. +//! @param t time since the first chunk's start [s] +static int chunkAtSec(double t) +{ + const double abs_t = chunkStartSec(0) + t; + const auto it = std::upper_bound( + all_data.begin(), + all_data.end(), + abs_t, + [](double lhs, const AllData& rhs) + { + return lhs < rhs.points_local.front().timestamp; + }); + return std::max(0, static_cast(std::distance(all_data.begin(), it)) - 1); +} + +//! "YYYY-MM-DD HH:MM:SS.mmm UTC" for a Unix-epoch time; empty when `sec` is not one. +//! LiDARs synced to PTP/GNSS count from 1970; unsynced ones count from power-on, which +//! stays far below the year-2000 cutoff. +static std::string epochToUtcString(double sec) +{ + if (!(sec >= 946684800.0 && sec < 4102444800.0)) // 2000-01-01 .. 2100-01-01 + return {}; + const long long totalMs = std::llround(sec * 1000.0); + const std::time_t whole = static_cast(totalMs / 1000); + std::tm tm{}; +#ifdef _WIN32 + gmtime_s(&tm, &whole); +#else + gmtime_r(&whole, &tm); +#endif + char buf[48]; + const size_t n = std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tm); + std::snprintf(buf + n, sizeof(buf) - n, ".%03d UTC", static_cast(totalMs % 1000)); + return buf; +} + +//! Plays or pauses, replaying from the start once the end was reached -- shared by the +//! Play/Pause button and Space. +static void togglePlayback() +{ + if (!playback_playing && playhead_sec >= playbackDurationSec()) + { + playhead_sec = 0.0; + index_rendered_points_local = 0; + playhead_index = 0; + } + playback_playing = !playback_playing; +} + +//! Re-anchors the playhead on a chunk picked elsewhere (arrow keys, index field, Rebin), +//! handles Space and advances the playhead while playing. Needs a valid index_rendered_points_local. +static void updatePlayback() +{ + const ImGuiIO& io = ImGui::GetIO(); + if (index_rendered_points_local != playhead_index) + playhead_sec = chunkStartSec(index_rendered_points_local) - chunkStartSec(0); + + if (!io.WantTextInput && ImGui::IsKeyPressed(ImGuiKey_Space, false)) + togglePlayback(); + + if (playback_playing) + { + const double duration = playbackDurationSec(); + playhead_sec += io.DeltaTime * playback_speed; + if (playhead_sec >= duration) + { + playhead_sec = duration; + playback_playing = false; + } + index_rendered_points_local = chunkAtSec(playhead_sec); + } + playhead_index = index_rendered_points_local; +} + +//! Bar along the bottom of the window: Play/Pause, playhead time, speed, chunk index, +//! chunk timestamp and a scrubbable timeline. +static void playbackBar() +{ + const double duration = playbackDurationSec(); + // The timeline starts at the first chunk. + auto pos = [duration](double t) + { + return static_cast((t - chunkStartSec(0)) / duration); + }; + + // Motionless segments as green bands on the track, and the LAZ and IMU files as + // Gantt-style lanes under it, alternating shades telling neighbours apart. + std::vector spans; + std::vector lanes; + if (duration > 0.0) + { + for (const auto& [from, to] : motionless_segments) + if (pos(to) >= 0.f && pos(from) <= 1.f) + spans.push_back({ pos(from), pos(to), IM_COL32(80, 200, 120, 110), "motionless" }); + + if (show_file_lanes) + { + const auto addLane = + [&](std::string name, std::string_view unit, const std::vector& files, ImU32 shade, ImU32 altShade) + { + raylib_widgets::TimelineLane lane{ std::move(name), {} }; + for (const InputFileSpan& f : files) + { + if (f.count == 0) + continue; + std::ostringstream label; + label << fs::path(f.file).filename().string() << "\n" + << std::fixed << std::setprecision(3) << f.first - chunkStartSec(0) << " .. " << f.last - chunkStartSec(0) + << " s (" << f.last - f.first << " s), " << f.count << " " << unit; + lane.bars.push_back({ pos(f.first), pos(f.last), lane.bars.size() % 2 == 0 ? shade : altShade, label.str() }); + } + if (!lane.bars.empty()) + lanes.push_back(std::move(lane)); + }; + addLane("LAZ", "points", file_spans.laz, IM_COL32(80, 140, 230, 255), IM_COL32(50, 100, 190, 255)); + addLane("IMU", "samples", file_spans.imu, IM_COL32(230, 150, 60, 255), IM_COL32(190, 110, 40, 255)); + } + } + + const ImGuiStyle& style = ImGui::GetStyle(); + const float timelineH = 18.f + ImGui::GetTextLineHeight(); + const float barH = style.WindowPadding.y * 2.f + ImGui::GetFrameHeight() + style.ItemSpacing.y + timelineH + + raylib_widgets::kTimelineLaneHeight * static_cast(lanes.size()); + // NoNav: Space must not also press a focused bar button, and the arrows keep stepping chunks. + if (ImGui::BeginViewportSideBar( + "##playback", + ImGui::GetMainViewport(), + ImGuiDir_Down, + barH, + ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNav)) + { + if (ImGui::Button(playback_playing ? "Pause" : "Play", ImVec2(60.f, 0.f))) + togglePlayback(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Space"); + ImGui::SameLine(); + ImGui::Text("%7.1f / %.1f s", playhead_sec, duration); + ImGui::SameLine(); + ImGui::SetNextItemWidth(160.f); + ImGui::SliderFloat("Speed", &playback_speed, 0.1f, 50.f, "%.1fx", ImGuiSliderFlags_Logarithmic); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Playback rate, as a multiple of real time (Ctrl+click to type)"); + + ImGui::SameLine(); + ImGui::Dummy(ImVec2(20, 0)); + ImGui::SameLine(); + ImGui::TextUnformatted("Index:"); + ImGui::SameLine(); + int tempIndex = index_rendered_points_local; + ImGui::SetNextItemWidth(ImGuiNumberWidth); + if (ImGui::InputInt("##irpli", &tempIndex, 1, 10)) + index_rendered_points_local = std::clamp(tempIndex, 0, static_cast(all_data.size()) - 1); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", laz_files[indexes_to_filename[index_rendered_points_local]].c_str()); + ImGui::SameLine(); + ImGui::Text("/ %d", static_cast(all_data.size()) - 1); + + ImGui::SameLine(); + ImGui::Dummy(ImVec2(20, 0)); + ImGui::SameLine(); + const double ts = chunkStartSec(index_rendered_points_local); + const std::string utc = epochToUtcString(ts); + if (utc.empty()) + ImGui::Text("Timestamp: %.6f [s]", ts); + else + ImGui::Text("Timestamp: %s", utc.c_str()); + if (ImGui::IsItemHovered()) + { + if (utc.empty()) + ImGui::SetTooltip("Click to copy to clipboard"); + else + ImGui::SetTooltip("%.6f [s] since 1970-01-01 UTC\nClick to copy to clipboard", ts); + } + if (ImGui::IsItemClicked()) + { + char tmp[64]; + snprintf(tmp, sizeof(tmp), "%.6f", ts); + ImGui::SetClipboardText(tmp); + } + + float progress = duration > 0.0 ? static_cast(playhead_sec / duration) : 0.f; + if (raylib_widgets::timeline("##timeline", progress, duration, timelineH, spans, lanes)) + { + playhead_sec = progress * duration; + index_rendered_points_local = chunkAtSec(playhead_sec); + playhead_index = index_rendered_points_local; + } + } + ImGui::End(); +} + void display() { ImGuiIO& io = ImGui::GetIO(); @@ -1772,6 +2022,8 @@ void display() index_rendered_points_local = 0; if (index_rendered_points_local >= all_data.size()) index_rendered_points_local = all_data.size() - 1; + + updatePlayback(); } // ask to load the nearest photo @@ -1867,6 +2119,9 @@ void display() ImGui::SetTooltip("Show the mean and covariance ellipsoid representation"); ImGui::MenuItem("Show IMU data", nullptr, &show_imu_data); + ImGui::MenuItem("Show files on the timeline", nullptr, &show_file_lanes); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("LAZ and IMU csv files as lanes under the playback timeline, Gantt-style"); ImGui::MenuItem("Show cameras data", nullptr, &show_cameras_data); ImGui::MenuItem("Intensity shading", nullptr, &intensity_shading); @@ -1910,55 +2165,6 @@ void display() ImGui::SameLine(); ImGui::Dummy(ImVec2(20, 0)); - ImGui::SameLine(); - - if (all_data.size() > 0) - { - int tempIndex = index_rendered_points_local; - ImGui::Text("Index: "); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("Index of rendered points local"); - ImGui::SameLine(); - ImGui::PushItemWidth(ImGuiNumberWidth); - ImGui::SliderInt("##irpls", &tempIndex, 0, static_cast(all_data.size() - 1)); - if (ImGui::IsItemHovered()) - { - ImGui::BeginTooltip(); - std::string fn = laz_files[indexes_to_filename[index_rendered_points_local]]; - ImGui::Text(fn.c_str()); - ImGui::EndTooltip(); - } - ImGui::SameLine(); - ImGui::InputInt("##irpli", &tempIndex, 1, 10); - if (ImGui::IsItemHovered()) - { - ImGui::BeginTooltip(); - std::string fn = laz_files[indexes_to_filename[index_rendered_points_local]]; - ImGui::Text(fn.c_str()); - ImGui::EndTooltip(); - } - ImGui::PopItemWidth(); - - if ((tempIndex >= 0) && (tempIndex < all_data.size())) - index_rendered_points_local = tempIndex; - - ImGui::SameLine(); - double ts = all_data[index_rendered_points_local].points_local[0].timestamp; // * 1e9; - ImGui::Text("Timestamp: %.6f [ns]", ts); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("Click to copy to clipboard"); - if (ImGui::IsItemClicked()) - { - char tmp[64]; - snprintf(tmp, sizeof(tmp), "%.6f", ts); - ImGui::SetClipboardText(tmp); - } - - ImGui::SameLine(); - ImGui::Dummy(ImVec2(20, 0)); - ImGui::SameLine(); - } - ImGui::SameLine(); ImGui::Text("(%.1f FPS)", ImGui::GetIO().Framerate); @@ -1980,6 +2186,9 @@ void display() ImGui::EndMainMenuBar(); } + if (!all_data.empty()) + playbackBar(); + info_window(infoLines, appShortcuts); end3DAndDrawLabels(); diff --git a/calib_core/CMakeLists.txt b/calib_core/CMakeLists.txt index 4a98a14aa..e40d6e386 100644 --- a/calib_core/CMakeLists.txt +++ b/calib_core/CMakeLists.txt @@ -33,6 +33,12 @@ add_library(calib_core STATIC # cmake -DCALIB_ENABLE_CERES=ON (needs libceres-dev or equivalent). option(CALIB_ENABLE_CERES "Enable the Ceres-based extrinsics solver for the Mei and fisheye camera models" OFF) if(CALIB_ENABLE_CERES) + # Ceres' FindSuiteSparse runs find_package(TBB QUIET). With the bundled oneTBB + # already defining TBB::tbb, a system TBBConfig.cmake aborts on the partial + # target set, so keep that lookup from running in this directory. + if(TARGET TBB::tbb) + set(CMAKE_DISABLE_FIND_PACKAGE_TBB ON) + endif() find_package(Ceres REQUIRED) # PUBLIC so calib_core_tests can #ifdef on it to build the real-solve # test only when it can actually run. diff --git a/calib_core/include/CalibCore/Camera.h b/calib_core/include/CalibCore/Camera.h index 997121d64..845b4555a 100644 --- a/calib_core/include/CalibCore/Camera.h +++ b/calib_core/include/CalibCore/Camera.h @@ -2,6 +2,7 @@ #include #include #include +#include #include #include @@ -245,4 +246,26 @@ namespace calib //! @return the timestamp in nanoseconds, or nullopt if the sidecar is //! missing, unreadable, or has no FRAME_WALL_CLOCK field std::optional LoadTimestampFromSideCar(const std::string& path); + + //! Capture time of a camera frame: its sidecar's FRAME_WALL_CLOCK (@ref + //! LoadTimestampFromSideCar) when there is one, else the digits after the + //! last '_' of the file name ("cam0_.jpg", "front_.jpg") or the + //! whole name (".jpg"). + //! @param path image file + //! @return nanoseconds since epoch, or nullopt when neither gives a time + std::optional imageTimestampNs(const std::string& path); + + //! A camera frame and its capture time. + struct TimedImage + { + std::string path; + int64_t tsNs = 0; //!< see @ref imageTimestampNs + }; + + //! The frame in `dir` (not its subfolders) captured closest to `tsNs`. + //! @param dir folder of .jpg/.jpeg/.png/.bmp frames + //! @param tsNs time to match, nanoseconds since epoch + //! @return the closest frame, the earlier one on a tie, or nullopt when no + //! image in `dir` has a capture time + std::optional closestImage(const std::string& dir, int64_t tsNs); } // namespace calib diff --git a/calib_core/include/CalibCore/CameraCalibrationSolver.h b/calib_core/include/CalibCore/CameraCalibrationSolver.h index 344484268..ad2e83680 100644 --- a/calib_core/include/CalibCore/CameraCalibrationSolver.h +++ b/calib_core/include/CalibCore/CameraCalibrationSolver.h @@ -1,6 +1,7 @@ #pragma once #include "Camera.h" #include +#include #include #include @@ -22,6 +23,43 @@ namespace calib double u = 0.0, v = 0.0; }; + /** + * @brief Soft constraint (prior) on one extrinsic parameter: an extra + * observation equation (value - target) / sigma alongside the + * reprojection residuals, which are in pixels. A parameter sigma + * away from its target costs as much as one pixel of reprojection + * error, so it can still move when the pairs demand it, unlike a + * lock. Meant for directions the picked pairs constrain poorly, + * such as the camera's height (tz) when every point lies near the + * horizon. + */ + struct ParameterPrior + { + //! Add the observation equation for this parameter. + bool enabled = false; + //! Value the parameter is pulled towards: metres for tx/ty/tz, + //! degrees for om/fi/ka, in the same frame as Extrinsics. + double target = 0.0; + //! Allowed deviation, metres for tx/ty/tz, degrees for om/fi/ka. + //! Must be > 0 when enabled. + double sigma = 0.01; + }; + + /** + * @brief One ParameterPrior per Extrinsics parameter, indexed as + * kPriorTx..kPriorKa. All disabled by default. + */ + using ExtrinsicsPriors = std::array; + enum ExtrinsicsPriorIndex + { + kPriorTx = 0, + kPriorTy, + kPriorTz, + kPriorOm, + kPriorFi, + kPriorKa + }; + //! Solve for the extrinsics (camera position + orientation) that best //! explain the given LiDAR-point <-> image-pixel correspondences, via //! damped Gauss-Newton (Levenberg-Marquardt) on the reused observation @@ -35,9 +73,17 @@ namespace calib //! @param fixTranslation pin tx/ty/tz at their initial values and optimize //! orientation only (3-DOF) -- useful when the camera position //! relative to the LiDAR is already known precisely + //! @param fixRotation pin om/fi/ka at their initial values and optimize + //! position only (3-DOF) -- useful when the camera orientation is + //! already known precisely + //! @param priors soft constraints pulling individual parameters towards + //! a target (see ParameterPrior); ignored for a locked parameter. + //! outRmsPixels reports the reprojection error only, without them //! @return false, leaving extrinsicsInOut unchanged, for fewer than 3 //! correspondences, fewer correspondences than free parameters - //! (3 with fixTranslation, else 6), or a singular system + //! (3 with fixTranslation or fixRotation, else 6), both fix flags + //! set (nothing left to solve), an enabled prior with sigma <= 0, + //! or a singular system //! @note Pinhole only: the reused observation equations are a pure //! rectilinear perspective projection, with no distortion and no //! unified-sphere term. @see solveExtrinsicsCeres @@ -46,7 +92,9 @@ namespace calib const Intrinsics& K, Extrinsics& extrinsicsInOut, double* outRmsPixels = nullptr, - bool fixTranslation = false); + bool fixTranslation = false, + bool fixRotation = false, + const ExtrinsicsPriors& priors = {}); //! CameraModel::Mei and CameraModel::Fisheye counterpart to //! @ref solveExtrinsicsFromCorrespondences. No vendored analytic Jacobian @@ -63,8 +111,11 @@ namespace calib //! dropped //! @param outRmsPixels optionally receives the RMS reprojection error //! @param fixTranslation as in @ref solveExtrinsicsFromCorrespondences + //! @param fixRotation as in @ref solveExtrinsicsFromCorrespondences + //! @param priors as in @ref solveExtrinsicsFromCorrespondences //! @return false on failure, with the reason in errorMessage -- including - //! any other K.model + //! any other K.model, both fix flags set, or an enabled prior with + //! sigma <= 0 //! @note Needs -DCALIB_ENABLE_CERES=ON (OFF by default). Built without it //! this always returns false and says so, so callers never need an //! \#ifdef of their own. @@ -74,6 +125,64 @@ namespace calib Extrinsics& extrinsicsInOut, std::string& errorMessage, double* outRmsPixels = nullptr, - bool fixTranslation = false); + bool fixTranslation = false, + bool fixRotation = false, + const ExtrinsicsPriors& priors = {}); + + /** + * @brief Which CameraModel::Mei intrinsics @ref solveExtrinsicsAndIntrinsicsCeres + * refines along with the extrinsics; the rest stay as given. + */ + struct MeiIntrinsicsRefinement + { + bool focal = false; //!< fx, fy + bool principalPoint = false; //!< cx, cy + bool xi = false; //!< unified-sphere parameter, kept >= 0 + bool distortion = false; //!< k1, k2, k3, p1, p2 + + //! @return how many intrinsics are refined + int count() const + { + return (focal ? 2 : 0) + (principalPoint ? 2 : 0) + (xi ? 1 : 0) + (distortion ? 5 : 0); + } + }; + + /** + * @brief @ref solveExtrinsicsCeres that also refines the CameraModel::Mei + * intrinsics `refine` selects. + * @param correspondences picked pairs, as in solveExtrinsicsCeres; each gives + * 2 equations, so at least half as many as there are free parameters + * @param intrinsicsInOut intrinsics in, refined ones replaced on success; + * model Mei or Fisheye, and Mei when refining any + * @param extrinsicsInOut initial guess in, solved result out + * @param refine intrinsics to refine; none behaves as solveExtrinsicsCeres + * @param errorMessage set on failure, as in solveExtrinsicsCeres + * @param outRmsPixels optionally receives the RMS reprojection error + * @param fixTranslation as in @ref solveExtrinsicsFromCorrespondences + * @param fixRotation as in @ref solveExtrinsicsFromCorrespondences; with + * fixTranslation too, only the intrinsics are solved + * @param priors as in @ref solveExtrinsicsFromCorrespondences + * @return false, leaving both in/out parameters unchanged, on the failures + * solveExtrinsicsCeres has, or when refining a model other than Mei + * @note xi trades off against fx/fy, and a few pairs barely pin the + * distortion: refine only what the pairs support. + */ + bool solveExtrinsicsAndIntrinsicsCeres( + const std::vector& correspondences, + Intrinsics& intrinsicsInOut, + Extrinsics& extrinsicsInOut, + const MeiIntrinsicsRefinement& refine, + std::string& errorMessage, + double* outRmsPixels = nullptr, + bool fixTranslation = false, + bool fixRotation = false, + const ExtrinsicsPriors& priors = {}); + + /** + * @brief Checks that every enabled prior has a positive sigma. + * @param priors priors to check + * @return true when the priors can be passed to a solver + */ + bool extrinsicsPriorsValid(const ExtrinsicsPriors& priors); } // namespace calib diff --git a/calib_core/include/CalibCore/PointCloud.h b/calib_core/include/CalibCore/PointCloud.h index 1f75a4a0c..fb3b97d38 100644 --- a/calib_core/include/CalibCore/PointCloud.h +++ b/calib_core/include/CalibCore/PointCloud.h @@ -9,7 +9,7 @@ namespace calib { struct Point3D { float x, y, z; float intensity; // normalized to [0,1] - int64_t ts_ns = 0; // GPS time cast from gps_time field (0 if unavailable) + int64_t ts_ns = 0; // gps_time in nanoseconds, read as seconds or ns (0 if unavailable) uint8_t r = 0, g = 0, b = 0; // LAS rgb (16-bit >> 8); 0 when the file has none }; diff --git a/calib_core/include/CalibCore/Session.h b/calib_core/include/CalibCore/Session.h new file mode 100644 index 000000000..deedbb770 --- /dev/null +++ b/calib_core/include/CalibCore/Session.h @@ -0,0 +1,51 @@ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace calib { + +//! One session's files, read from its *.mjs manifest rather than by scanning +//! the directory -- a directory can hold more than one session, each with its +//! own poses file and chunk list. +struct SessionFiles +{ + std::filesystem::path mjs; + //! Chunk stem (e.g. "scan_lio_0") -> world pose; poses_file_name, else initial_poses_file_name. + std::map poses; + bool hasPoses = false; + //! laz_file_names, in manifest order. + std::vector lazPaths; +}; + +//! Reads a poses file (session_poses.mrp / session_ini_poses.mri). +//! @param mrpPath file to read +//! @return chunk stem (e.g. "scan_lio_0") -> pose; empty when the file can't be read +std::map parseMRP(const std::filesystem::path& mrpPath); + +//! The session manifest a path names: a *.mjs file as is; a directory resolves +//! to its session.mjs (what lidar_odometry_step_1 writes), else its only *.mjs. +//! @param p file or directory +//! @param err receives the reason when there is no single answer +//! @return the manifest, or an empty path +std::filesystem::path resolveMjs(const std::filesystem::path& p, std::string& err); + +//! Reads the manifest's poses and chunk list. Stored paths resolve as in +//! Session::load (see HDMapping/SessionPaths.h). +//! @param mjs manifest to read +//! @param out overwritten with the session's files +//! @param err receives the reason on failure +//! @return false when the manifest can't be read or parsed +bool readSessionFiles(const std::filesystem::path& mjs, SessionFiles& out, std::string& err); + +//! A "scan_lio_N" chunk's trajectory: trajectory_lio_N.csv next to its laz. +std::filesystem::path chunkTrajectoryCsv(const std::filesystem::path& lazPath); + +//! Appends every chunk's trajectory CSV to `traj`, each with its chunk's pose +//! applied, then sorts it. Chunks without a CSV are skipped. +void loadSessionTrajectory(const SessionFiles& sf, Trajectory& traj); + +} // namespace calib diff --git a/calib_core/src/Camera.cpp b/calib_core/src/Camera.cpp index a2b0c1df5..2431dda6b 100644 --- a/calib_core/src/Camera.cpp +++ b/calib_core/src/Camera.cpp @@ -2,6 +2,8 @@ #include #include +#include +#include #include #include @@ -108,6 +110,49 @@ std::optional LoadTimestampFromSideCar(const std::string& path) return std::nullopt; } +std::optional imageTimestampNs(const std::string& path) +{ + if (const auto sidecarTs = LoadTimestampFromSideCar(path)) + return std::llround(*sidecarTs); + + std::string stem = std::filesystem::path(path).stem().string(); + if (const auto us = stem.rfind('_'); us != std::string::npos) + stem = stem.substr(us + 1); + // The all-digits check rejects unrelated names before std::stoll. + if (stem.empty() || stem.find_first_not_of("0123456789") != std::string::npos) + return std::nullopt; + try + { + return std::stoll(stem); + } catch (const std::exception&) + { + return std::nullopt; + } +} + +std::optional closestImage(const std::string& dir, int64_t tsNs) +{ + std::error_code ec; + std::optional best; + for (const auto& entry : std::filesystem::directory_iterator(dir, ec)) + { + std::string ext = entry.path().extension().string(); + std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); + if (!entry.is_regular_file() || (ext != ".jpg" && ext != ".jpeg" && ext != ".png" && ext != ".bmp")) + continue; + const auto ts = imageTimestampNs(entry.path().string()); + if (!ts) + continue; + const auto gap = [tsNs](int64_t t) + { + return t > tsNs ? t - tsNs : tsNs - t; + }; + if (!best || gap(*ts) < gap(best->tsNs) || (gap(*ts) == gap(best->tsNs) && *ts < best->tsNs)) + best = TimedImage{ entry.path().string(), *ts }; + } + return best; +} + Eigen::Matrix3f omFiKaToMat3(float om_deg, float fi_deg, float ka_deg) { TaitBryanPose pose; pose.om = deg2rad(om_deg); diff --git a/calib_core/src/CameraCalibrationSolver.cpp b/calib_core/src/CameraCalibrationSolver.cpp index 98cc91fc7..2ca8c054c 100644 --- a/calib_core/src/CameraCalibrationSolver.cpp +++ b/calib_core/src/CameraCalibrationSolver.cpp @@ -44,21 +44,57 @@ namespace calib } return sumSq; } + + //! One prior as a linear observation equation on the solver's own + //! parameter vector x = [tx',ty',tz',om,fi,ka] (rotated position, + //! radians): residual = (target - J*x) * invSigma. + struct PriorRow + { + Eigen::Matrix J = Eigen::Matrix::Zero(); + double target = 0.0; + double invSigma = 1.0; + }; + + double priorSumSquared(const std::vector& rows, const Eigen::Matrix& x) + { + double sumSq = 0.0; + for (const auto& r : rows) + { + const double res = (r.target - r.J.dot(x)) * r.invSigma; + sumSq += res * res; + } + return sumSq; + } } // namespace + bool extrinsicsPriorsValid(const ExtrinsicsPriors& priors) + { + for (const auto& p : priors) + if (p.enabled && !(p.sigma > 0.0)) + return false; + return true; + } + bool solveExtrinsicsFromCorrespondences( const std::vector& correspondences, const Intrinsics& K, Extrinsics& extrinsicsInOut, double* outRmsPixels, - bool fixTranslation) + bool fixTranslation, + bool fixRotation, + const ExtrinsicsPriors& priors) { // Free parameters are always a contiguous slice of the full // [tx,ty,tz,om,fi,ka] (columns 0-5 of the 2x9 jacobian): all 6 of - // them normally, or just [om,fi,ka] (columns 3-5) when translation - // is pinned -- tx/ty/tz then never appear in the normal equations - // at all, so they cannot move. - const int nParams = fixTranslation ? 3 : 6; + // them normally, just [om,fi,ka] (columns 3-5) when translation is + // pinned, or just [tx,ty,tz] (columns 0-2) when rotation is pinned + // -- the pinned ones then never appear in the normal equations at + // all, so they cannot move. + if (fixTranslation && fixRotation) + return false; + if (!extrinsicsPriorsValid(priors)) + return false; + const int nParams = (fixTranslation || fixRotation) ? 3 : 6; const int colOffset = fixTranslation ? 3 : 0; if (static_cast(correspondences.size()) < 3 || static_cast(correspondences.size()) * 2 < nParams) return false; @@ -96,7 +132,41 @@ namespace calib const double fx = K.fx, fy = K.fy, cx = K.cx, cy = K.cy; - double cost = sumSquaredResiduals(rotated, fx, fy, cx, cy, tx, ty, tz, om, fi, ka); + // Priors are on the real Extrinsics (C, om/fi/ka in degrees), but the + // solver's position is C' = offset^T * C, so a prior on C's i-th + // component is a prior on offset.row(i) * C'. A locked parameter's + // prior is dropped: it cannot move anyway. + const Eigen::Matrix3d offset = kCameraLidarAxisOffset.cast(); + std::vector priorRows; + for (int i = 0; i < 6; ++i) + { + const ParameterPrior& prior = priors[i]; + const bool isTranslation = i < 3; + if (!prior.enabled || (isTranslation && fixTranslation) || (!isTranslation && fixRotation)) + continue; + PriorRow row; + if (isTranslation) + { + row.J.head<3>() = offset.row(i); + row.target = prior.target; + row.invSigma = 1.0 / prior.sigma; + } + else + { + row.J(i) = 1.0; + row.target = prior.target * d2r; + row.invSigma = 1.0 / (prior.sigma * d2r); + } + priorRows.push_back(row); + } + auto totalCost = [&](double tx_, double ty_, double tz_, double om_, double fi_, double ka_) + { + Eigen::Matrix x; + x << tx_, ty_, tz_, om_, fi_, ka_; + return sumSquaredResiduals(rotated, fx, fy, cx, cy, tx_, ty_, tz_, om_, fi_, ka_) + priorSumSquared(priorRows, x); + }; + + double cost = totalCost(tx, ty, tz, om, fi, ka); bool solvedOnce = false; // Levenberg-Marquardt: plain (undamped) Gauss-Newton can take huge, @@ -129,14 +199,29 @@ namespace calib // Only the free-parameter columns -- the 3D points // (columns 6-8) are fixed observations, not solved for, and - // translation (columns 0-2) is skipped entirely when - // fixTranslation is set. + // translation (columns 0-2) or rotation (columns 3-5) is + // skipped entirely when its fix flag is set. Eigen::MatrixXd A = -jFull.block(0, colOffset, 2, nParams); AtA += A.transpose() * A; AtB += A.transpose() * delta; } + // Prior observation equations, same convention: A = d(predicted)/dx, + // delta = observed - predicted, both scaled by 1/sigma. + if (!priorRows.empty()) + { + Eigen::Matrix x; + x << tx, ty, tz, om, fi, ka; + for (const auto& r : priorRows) + { + const Eigen::VectorXd a = (r.J.segment(colOffset, nParams) * r.invSigma).transpose(); + const double delta = (r.target - r.J.dot(x)) * r.invSigma; + AtA += a * a.transpose(); + AtB += a * delta; + } + } + bool improved = false; for (int lmTry = 0; lmTry < kMaxLmTries; ++lmTry) { @@ -153,22 +238,10 @@ namespace calib Eigen::VectorXd x = lu.solve(AtB); double tx2 = tx, ty2 = ty, tz2 = tz, om2 = om, fi2 = fi, ka2 = ka; - if (fixTranslation) - { - om2 += x(0); - fi2 += x(1); - ka2 += x(2); - } - else - { - tx2 += x(0); - ty2 += x(1); - tz2 += x(2); - om2 += x(3); - fi2 += x(4); - ka2 += x(5); - } - double newCost = sumSquaredResiduals(rotated, fx, fy, cx, cy, tx2, ty2, tz2, om2, fi2, ka2); + double* const all[6] = { &tx2, &ty2, &tz2, &om2, &fi2, &ka2 }; + for (int k = 0; k < nParams; ++k) + *all[colOffset + k] += x(k); + double newCost = totalCost(tx2, ty2, tz2, om2, fi2, ka2); if (newCost < cost) { @@ -210,8 +283,10 @@ namespace calib extrinsicsInOut.fi = static_cast(fi / d2r); extrinsicsInOut.ka = static_cast(ka / d2r); + // Reprojection error only, without the priors' share of the cost. if (outRmsPixels) - *outRmsPixels = std::sqrt(cost / (2.0 * static_cast(correspondences.size()))); + *outRmsPixels = std::sqrt( + sumSquaredResiduals(rotated, fx, fy, cx, cy, tx, ty, tz, om, fi, ka) / (2.0 * static_cast(correspondences.size()))); return true; } diff --git a/calib_core/src/CameraCalibrationSolverCeres.cpp b/calib_core/src/CameraCalibrationSolverCeres.cpp index 122bf00c6..603b18f0d 100644 --- a/calib_core/src/CameraCalibrationSolverCeres.cpp +++ b/calib_core/src/CameraCalibrationSolverCeres.cpp @@ -2,12 +2,14 @@ // Always compiled; the #ifdef below picks between the real Ceres // implementation and a stub that explains why it isn't available, so callers -// check solveExtrinsicsCeres's return value rather than an #ifdef. +// check solveExtrinsicsAndIntrinsicsCeres's return value rather than an #ifdef. #ifdef CALIB_ENABLE_CERES #include +#include #include +#include namespace calib { @@ -22,7 +24,7 @@ namespace calib // rows rather than a general 3x3 product: offset = // [[0,0,1],[-1,0,0],[0,-1,0]], so row 0 of R is row 2 of Rdelta, // row 1 is -(row 0), row 2 is -(row 1). - template + template void rotationMatrix(const T& om, const T& fi, const T& ka, T R[3][3]) { const T sx = sin(om), cx = cos(om); @@ -48,42 +50,53 @@ namespace calib } } - // Templated equivalent of calib::projectPoint's Mei branch, for - // Ceres autodiff -- - // same formula. Intrinsics stay plain doubles (fixed, not solved - // for); only pc is the Jet-typed variable. - template + //! p_cam = R_wc^T * (p_world - C), from the two extrinsic parameter blocks. + template + void lidarToCamera(const Eigen::Vector3d& p, const T* tx_ty_tz, const T* om_fi_ka, T pc[3]) + { + T R[3][3]; + rotationMatrix(om_fi_ka[0], om_fi_ka[1], om_fi_ka[2], R); + const T d[3] = { T(p.x()) - tx_ty_tz[0], T(p.y()) - tx_ty_tz[1], T(p.z()) - tx_ty_tz[2] }; + pc[0] = R[0][0] * d[0] + R[1][0] * d[1] + R[2][0] * d[2]; + pc[1] = R[0][1] * d[0] + R[1][1] * d[1] + R[2][1] * d[2]; + pc[2] = R[0][2] * d[0] + R[1][2] * d[1] + R[2][2] * d[2]; + } + + //! Templated calib::projectPoint Mei branch, for Ceres autodiff; the + //! intrinsics are Jets too, so they can be refined. + template void projectMei( const T pc[3], - double fx, - double fy, - double cx, - double cy, - double xi, - double k1, - double k2, - double k3, - double p1, - double p2, + const T& fx, + const T& fy, + const T& cx, + const T& cy, + const T& xi, + const T& k1, + const T& k2, + const T& k3, + const T& p1, + const T& p2, T& u, T& v) { const T n = sqrt(pc[0] * pc[0] + pc[1] * pc[1] + pc[2] * pc[2]); const T Xx = pc[0] / n, Xy = pc[1] / n, Xz = pc[2] / n; - const T denom = Xz + T(xi); + const T denom = Xz + xi; const T x = Xx / denom, y = Xy / denom; const T r2 = x * x + y * y; - const T radial = T(1.0) + T(k1) * r2 + T(k2) * r2 * r2 + T(k3) * r2 * r2 * r2; - const T xd = x * radial + T(2.0 * p1) * x * y + T(p2) * (r2 + T(2.0) * x * x); - const T yd = y * radial + T(p1) * (r2 + T(2.0) * y * y) + T(2.0 * p2) * x * y; - u = T(fx) * xd + T(cx); - v = T(fy) * yd + T(cy); + const T radial = T(1.0) + k1 * r2 + k2 * r2 * r2 + k3 * r2 * r2 * r2; + const T xd = x * radial + T(2.0) * p1 * x * y + p2 * (r2 + T(2.0) * x * x); + const T yd = y * radial + p1 * (r2 + T(2.0) * y * y) + T(2.0) * p2 * x * y; + u = fx * xd + cx; + v = fy * yd + cy; } // Templated equivalent of calib::projectPoint's Fisheye branch, for // Ceres autodiff. - template - void projectFisheye(const T pc[3], double fx, double fy, double cx, double cy, double k1, double k2, double k3, double k4, T& u, T& v) + template + void projectFisheye( + const T pc[3], double fx, double fy, double cx, double cy, double k1, double k2, double k3, double k4, T& u, T& v) { const T r2 = pc[0] * pc[0] + pc[1] * pc[1]; // theta_d / r, the factor that scales (x, y) onto the image plane. @@ -105,36 +118,63 @@ namespace calib v = T(fy) * pc[1] * s + T(cy); } - // Reprojection residual for one correspondence: predicted (u, v) + // Reprojection residuals for one correspondence: predicted (u, v) // minus the picked pixel, like the Pinhole solver's observation // equation but autodiff'd, no vendored Mei or fisheye Jacobian - // existing. K.model must be Mei or Fisheye. - struct ReprojectionResidual + // existing. + + //! Mei, with the intrinsics as parameter blocks (fx fy | cx cy | xi | + //! k1 k2 k3 p1 p2), held constant unless refined. + struct MeiReprojectionResidual { - ReprojectionResidual(const Eigen::Vector3d& p, double u_kp, double v_kp, const Intrinsics& K) - : p_(p), u_kp_(u_kp), v_kp_(v_kp), K_(K) + MeiReprojectionResidual(const Eigen::Vector3d& p, double u_kp, double v_kp) + : p_(p) + , u_kp_(u_kp) + , v_kp_(v_kp) { } - template - bool operator()(const T* const tx_ty_tz, const T* const om_fi_ka, T* residual) const + template + bool operator()( + const T* const tx_ty_tz, + const T* const om_fi_ka, + const T* const focal, + const T* const centre, + const T* const xi, + const T* const dist, + T* residual) const { - T R[3][3]; - rotationMatrix(om_fi_ka[0], om_fi_ka[1], om_fi_ka[2], R); + T pc[3]; + lidarToCamera(p_, tx_ty_tz, om_fi_ka, pc); + T u, v; + projectMei(pc, focal[0], focal[1], centre[0], centre[1], xi[0], dist[0], dist[1], dist[2], dist[3], dist[4], u, v); + residual[0] = u - T(u_kp_); + residual[1] = v - T(v_kp_); + return true; + } + + const Eigen::Vector3d p_; + const double u_kp_, v_kp_; + }; - const T d[3] = { T(p_.x()) - tx_ty_tz[0], T(p_.y()) - tx_ty_tz[1], T(p_.z()) - tx_ty_tz[2] }; - // p_cam = R_wc^T * (p_world - C) - const T pc[3] = { - R[0][0] * d[0] + R[1][0] * d[1] + R[2][0] * d[2], - R[0][1] * d[0] + R[1][1] * d[1] + R[2][1] * d[2], - R[0][2] * d[0] + R[1][2] * d[1] + R[2][2] * d[2], - }; + //! Fisheye, intrinsics fixed. + struct FisheyeReprojectionResidual + { + FisheyeReprojectionResidual(const Eigen::Vector3d& p, double u_kp, double v_kp, const Intrinsics& K) + : p_(p) + , u_kp_(u_kp) + , v_kp_(v_kp) + , K_(K) + { + } + template + bool operator()(const T* const tx_ty_tz, const T* const om_fi_ka, T* residual) const + { + T pc[3]; + lidarToCamera(p_, tx_ty_tz, om_fi_ka, pc); T u, v; - if (K_.model == CameraModel::Fisheye) - projectFisheye(pc, K_.fx, K_.fy, K_.cx, K_.cy, K_.k1, K_.k2, K_.k3, K_.k4, u, v); - else - projectMei(pc, K_.fx, K_.fy, K_.cx, K_.cy, K_.xi, K_.k1, K_.k2, K_.k3, K_.p1, K_.p2, u, v); + projectFisheye(pc, K_.fx, K_.fy, K_.cx, K_.cy, K_.k1, K_.k2, K_.k3, K_.k4, u, v); residual[0] = u - T(u_kp_); residual[1] = v - T(v_kp_); return true; @@ -144,41 +184,128 @@ namespace calib const double u_kp_, v_kp_; const Intrinsics K_; }; + + // Prior observation equation on one component of a 3-parameter block: + // (value - target) / sigma, in the block's own units (metres, or + // radians for om/fi/ka). + struct PriorResidual + { + PriorResidual(int index, double target, double invSigma) + : index_(index) + , target_(target) + , invSigma_(invSigma) + { + } + + template + bool operator()(const T* const block, T* residual) const + { + residual[0] = (block[index_] - T(target_)) * T(invSigma_); + return true; + } + + const int index_; + const double target_, invSigma_; + }; } // namespace - bool solveExtrinsicsCeres( + bool solveExtrinsicsAndIntrinsicsCeres( const std::vector& correspondences, - const Intrinsics& K, + Intrinsics& intrinsicsInOut, Extrinsics& extrinsicsInOut, + const MeiIntrinsicsRefinement& refine, std::string& errorMessage, double* outRmsPixels, - bool fixTranslation) + bool fixTranslation, + bool fixRotation, + const ExtrinsicsPriors& priors) { + const Intrinsics& K = intrinsicsInOut; if (K.model != CameraModel::Mei && K.model != CameraModel::Fisheye) { errorMessage = std::string("The Ceres solver handles the mei and fisheye models only, not ") + modelToString(K.model); return false; } + if (refine.count() > 0 && K.model != CameraModel::Mei) + { + errorMessage = std::string("Refining intrinsics is supported for the mei model only, not ") + modelToString(K.model); + return false; + } + if (fixTranslation && fixRotation && refine.count() == 0) + { + errorMessage = "Translation and rotation are both locked -- nothing to solve"; + return false; + } + if (!extrinsicsPriorsValid(priors)) + { + errorMessage = "Every enabled prior needs a sigma > 0"; + return false; + } - const int nParams = fixTranslation ? 3 : 6; - if (static_cast(correspondences.size()) < 3 || static_cast(correspondences.size()) * 2 < nParams) + // Each correspondence gives 2 equations. + const int nParams = (fixTranslation ? 0 : 3) + (fixRotation ? 0 : 3) + refine.count(); + const int nNeeded = std::max(3, (nParams + 1) / 2); + if (static_cast(correspondences.size()) < nNeeded) { - errorMessage = "Need at least 3 correspondences"; + errorMessage = + "Need at least " + std::to_string(nNeeded) + " correspondences for " + std::to_string(nParams) + " free parameters"; return false; } const double d2r = M_PI / 180.0; double txyz[3] = { extrinsicsInOut.tx, extrinsicsInOut.ty, extrinsicsInOut.tz }; double omfika[3] = { extrinsicsInOut.om * d2r, extrinsicsInOut.fi * d2r, extrinsicsInOut.ka * d2r }; + double focal[2] = { K.fx, K.fy }; + double centre[2] = { K.cx, K.cy }; + double xi[1] = { K.xi }; + double dist[5] = { K.k1, K.k2, K.k3, K.p1, K.p2 }; ceres::Problem problem; + std::vector reprojectionBlocks; for (const auto& c : correspondences) { - auto* cost = new ceres::AutoDiffCostFunction(new ReprojectionResidual(c.p, c.u, c.v, K)); - problem.AddResidualBlock(cost, nullptr, txyz, omfika); + if (K.model == CameraModel::Mei) + { + auto* cost = new ceres::AutoDiffCostFunction( + new MeiReprojectionResidual(c.p, c.u, c.v)); + reprojectionBlocks.push_back(problem.AddResidualBlock(cost, nullptr, txyz, omfika, focal, centre, xi, dist)); + } + else + { + auto* cost = new ceres::AutoDiffCostFunction( + new FisheyeReprojectionResidual(c.p, c.u, c.v, K)); + reprojectionBlocks.push_back(problem.AddResidualBlock(cost, nullptr, txyz, omfika)); + } + } + if (K.model == CameraModel::Mei) + { + if (!refine.focal) + problem.SetParameterBlockConstant(focal); + if (!refine.principalPoint) + problem.SetParameterBlockConstant(centre); + if (refine.xi) + problem.SetParameterLowerBound(xi, 0, 0.0); + else + problem.SetParameterBlockConstant(xi); + if (!refine.distortion) + problem.SetParameterBlockConstant(dist); + } + // A locked parameter's prior is dropped: it cannot move anyway. + for (int i = 0; i < 6; ++i) + { + const ParameterPrior& prior = priors[i]; + const bool isTranslation = i < 3; + if (!prior.enabled || (isTranslation && fixTranslation) || (!isTranslation && fixRotation)) + continue; + const double scale = isTranslation ? 1.0 : d2r; + auto* cost = new ceres::AutoDiffCostFunction( + new PriorResidual(i % 3, prior.target * scale, 1.0 / (prior.sigma * scale))); + problem.AddResidualBlock(cost, nullptr, isTranslation ? txyz : omfika); } if (fixTranslation) problem.SetParameterBlockConstant(txyz); + if (fixRotation) + problem.SetParameterBlockConstant(omfika); ceres::Solver::Options options; options.linear_solver_type = ceres::DENSE_QR; @@ -200,12 +327,33 @@ namespace calib extrinsicsInOut.om = static_cast(omfika[0] / d2r); extrinsicsInOut.fi = static_cast(omfika[1] / d2r); extrinsicsInOut.ka = static_cast(omfika[2] / d2r); + if (refine.count() > 0) + { + intrinsicsInOut.fx = static_cast(focal[0]); + intrinsicsInOut.fy = static_cast(focal[1]); + intrinsicsInOut.cx = static_cast(centre[0]); + intrinsicsInOut.cy = static_cast(centre[1]); + intrinsicsInOut.xi = static_cast(xi[0]); + intrinsicsInOut.k1 = static_cast(dist[0]); + intrinsicsInOut.k2 = static_cast(dist[1]); + intrinsicsInOut.k3 = static_cast(dist[2]); + intrinsicsInOut.p1 = static_cast(dist[3]); + intrinsicsInOut.p2 = static_cast(dist[4]); + } - // final_cost is 0.5*sum(residual^2) over every SCALAR residual (2 per + // Reprojection error only, without the priors' share of the cost: + // evaluate just the reprojection blocks. Their cost is + // 0.5*sum(residual^2) over every SCALAR residual (2 per // correspondence), so the Pinhole solver's rms formula - // sqrt(sum(du^2+dv^2) / (2*N)) simplifies to sqrt(final_cost/N). + // sqrt(sum(du^2+dv^2) / (2*N)) simplifies to sqrt(cost/N). if (outRmsPixels) - *outRmsPixels = std::sqrt(summary.final_cost / static_cast(correspondences.size())); + { + ceres::Problem::EvaluateOptions evalOptions; + evalOptions.residual_blocks = reprojectionBlocks; + double reprojectionCost = 0.0; + problem.Evaluate(evalOptions, &reprojectionCost, nullptr, nullptr, nullptr); + *outRmsPixels = std::sqrt(reprojectionCost / static_cast(correspondences.size())); + } return true; } @@ -217,19 +365,39 @@ namespace calib namespace calib { - bool solveExtrinsicsCeres( + bool solveExtrinsicsAndIntrinsicsCeres( const std::vector&, - const Intrinsics&, + Intrinsics&, Extrinsics&, + const MeiIntrinsicsRefinement&, std::string& errorMessage, double*, - bool) + bool, + bool, + const ExtrinsicsPriors&) { - errorMessage = - "Mei/fisheye extrinsics solving needs calib_core built with -DCALIB_ENABLE_CERES=ON (see calib_core/CMakeLists.txt)"; + errorMessage = "Mei/fisheye extrinsics solving needs calib_core built with -DCALIB_ENABLE_CERES=ON (see calib_core/CMakeLists.txt)"; std::cerr << errorMessage << std::endl; return false; } } // namespace calib -#endif \ No newline at end of file +#endif + +namespace calib +{ + bool solveExtrinsicsCeres( + const std::vector& correspondences, + const Intrinsics& K, + Extrinsics& extrinsicsInOut, + std::string& errorMessage, + double* outRmsPixels, + bool fixTranslation, + bool fixRotation, + const ExtrinsicsPriors& priors) + { + Intrinsics fixedK = K; + return solveExtrinsicsAndIntrinsicsCeres( + correspondences, fixedK, extrinsicsInOut, {}, errorMessage, outRmsPixels, fixTranslation, fixRotation, priors); + } +} // namespace calib \ No newline at end of file diff --git a/calib_core/src/PointCloud.cpp b/calib_core/src/PointCloud.cpp index dfb4984e0..1c3921bb1 100644 --- a/calib_core/src/PointCloud.cpp +++ b/calib_core/src/PointCloud.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include #include #include @@ -67,7 +68,9 @@ bool PointCloud::load(const std::string& path) { p.y = static_cast(coords[1]); p.z = static_cast(coords[2]); p.intensity = static_cast(point->intensity); - p.ts_ns = static_cast(point->gps_time); + // Mandeye writes gps_time in seconds, core's export_laz.h in + // nanoseconds; epoch seconds stay below 1e14, epoch nanoseconds don't. + p.ts_ns = point->gps_time < 1e14 ? std::llround(point->gps_time * 1e9) : std::llround(point->gps_time); if (formatHasRgb) { rgb16.push_back({ point->rgb[0], point->rgb[1], point->rgb[2] }); maxRgb = std::max({ maxRgb, point->rgb[0], point->rgb[1], point->rgb[2] }); diff --git a/calib_core/src/Session.cpp b/calib_core/src/Session.cpp new file mode 100644 index 000000000..6ca1e15b3 --- /dev/null +++ b/calib_core/src/Session.cpp @@ -0,0 +1,113 @@ +#include + +#include + +#include +#include + +namespace fs = std::filesystem; + +namespace calib { + +std::map parseMRP(const fs::path& mrpPath) +{ + std::map result; + std::ifstream f(mrpPath); + if (!f) + return result; + int n; + f >> n; + for (int i = 0; i < n; i++) + { + std::string name; + f >> name; + auto dot = name.rfind('.'); + std::string key = (dot != std::string::npos) ? name.substr(0, dot) : name; + float raw[16]; + for (int r = 0; r < 16; r++) + f >> raw[r]; + if (!f) + continue; + Eigen::Matrix4f M4; + for (int r = 0; r < 4; r++) + for (int c = 0; c < 4; c++) + M4(r, c) = raw[r * 4 + c]; + result[key] = Eigen::Affine3f(M4); + } + return result; +} + +fs::path resolveMjs(const fs::path& p, std::string& err) +{ + if (!fs::is_directory(p)) + { + if (fs::is_regular_file(p)) + return p; + err = "Session file not found: " + p.string(); + return {}; + } + if (fs::is_regular_file(p / "session.mjs")) + return p / "session.mjs"; + std::vector found; + for (const auto& e : fs::directory_iterator(p)) + if (e.path().extension() == ".mjs") + found.push_back(e.path()); + if (found.size() == 1) + return found.front(); + err = found.empty() ? "No .mjs session file in " + p.string() + : std::to_string(found.size()) + " .mjs files in " + p.string() + " -- pick one"; + return {}; +} + +bool readSessionFiles(const fs::path& mjs, SessionFiles& out, std::string& err) +{ + out = SessionFiles{}; + out.mjs = mjs; + auto relocate = [&](const std::string& path) -> fs::path + { + return path.empty() ? fs::path() : fs::path(resolveSessionPath(path, mjs.string())); + }; + try + { + std::ifstream f(mjs); + if (!f) + { + err = "Cannot open " + mjs.string(); + return false; + } + nlohmann::json data = nlohmann::json::parse(f); + const auto& settings = data["Session Settings"]; + out.poses = parseMRP(relocate(settings.value("poses_file_name", ""))); + if (out.poses.empty()) + out.poses = parseMRP(relocate(settings.value("initial_poses_file_name", ""))); + out.hasPoses = !out.poses.empty(); + for (const auto& fn : data["laz_file_names"]) + out.lazPaths.push_back(relocate(fn.value("file_name", ""))); + } catch (const std::exception& e) + { + err = "Bad session file " + mjs.string() + ": " + e.what(); + return false; + } + return true; +} + +fs::path chunkTrajectoryCsv(const fs::path& lazPath) +{ + std::string stem = lazPath.stem().string(); + return lazPath.parent_path() / ("trajectory_lio_" + stem.substr(stem.rfind('_') + 1) + ".csv"); +} + +void loadSessionTrajectory(const SessionFiles& sf, Trajectory& traj) +{ + for (const auto& lp : sf.lazPaths) + { + fs::path cp = chunkTrajectoryCsv(lp); + if (!fs::exists(cp)) + continue; + auto it = sf.poses.find(lp.stem().string()); + traj.loadCSV(cp.string(), it != sf.poses.end() ? &it->second : nullptr); + } + traj.sort(); +} + +} // namespace calib diff --git a/calib_core/tests/test_camera.cpp b/calib_core/tests/test_camera.cpp index 28a2bd087..8e6225268 100644 --- a/calib_core/tests/test_camera.cpp +++ b/calib_core/tests/test_camera.cpp @@ -856,3 +856,76 @@ TEST_CASE("LoadTimestampFromSideCar: an unquoted numeric value is read too") REQUIRE(ts.has_value()); CHECK(*ts == doctest::Approx(1789125060554994432.0)); } + +// ── imageTimestampNs / closestImage ────────────────────────────────────────── + +namespace +{ + //! Empty folder under the temp dir, removed with everything in it on scope exit. + struct TempDir + { + std::filesystem::path path; + explicit TempDir(const std::string& name) + : path(std::filesystem::temp_directory_path() / name) + { + std::filesystem::remove_all(path); + std::filesystem::create_directories(path); + } + ~TempDir() + { + std::filesystem::remove_all(path); + } + void touch(const std::string& file, const std::string& body = "") const + { + std::ofstream(path / file) << body; + } + }; +} // namespace + +TEST_CASE("imageTimestampNs: the sidecar wins, else the digits after the last '_'") +{ + TempDir dir("calib_core_test_image_ts"); + dir.touch("cam0_1794577043530708168.jpg"); + dir.touch("cam0_1794577043530708168.meta.json", R"({"FRAME_WALL_CLOCK": "1794577043412505088"})"); + dir.touch("front_1794530692539566915.jpg"); + dir.touch("1794530692706426915.png"); + dir.touch("IMG_0042b.jpg"); + dir.touch("photo.jpg"); + + CHECK(imageTimestampNs((dir.path / "cam0_1794577043530708168.jpg").string()) == 1794577043412505088LL); + CHECK(imageTimestampNs((dir.path / "front_1794530692539566915.jpg").string()) == 1794530692539566915LL); + CHECK(imageTimestampNs((dir.path / "1794530692706426915.png").string()) == 1794530692706426915LL); + CHECK_FALSE(imageTimestampNs((dir.path / "IMG_0042b.jpg").string()).has_value()); + CHECK_FALSE(imageTimestampNs((dir.path / "photo.jpg").string()).has_value()); +} + +TEST_CASE("closestImage: picks the frame nearest in time, ignoring untimed and non-image files") +{ + TempDir dir("calib_core_test_closest_image"); + dir.touch("front_1000.jpg"); + dir.touch("front_2000.jpg"); + dir.touch("front_3000.JPG"); + dir.touch("front_2600.txt"); + dir.touch("notes.jpg"); + + auto best = closestImage(dir.path.string(), 2600); + REQUIRE(best.has_value()); + CHECK(best->tsNs == 3000); + CHECK(std::filesystem::path(best->path).filename() == "front_3000.JPG"); + + best = closestImage(dir.path.string(), 1500); // tie: the earlier frame + REQUIRE(best.has_value()); + CHECK(best->tsNs == 1000); + + best = closestImage(dir.path.string(), -5); + REQUIRE(best.has_value()); + CHECK(best->tsNs == 1000); +} + +TEST_CASE("closestImage: nullopt for a folder with no timed images, or no folder") +{ + TempDir dir("calib_core_test_closest_image_empty"); + dir.touch("notes.jpg"); + CHECK_FALSE(closestImage(dir.path.string(), 0).has_value()); + CHECK_FALSE(closestImage("/nonexistent/calib_core_test_dir", 0).has_value()); +} diff --git a/calib_core/tests/test_solver.cpp b/calib_core/tests/test_solver.cpp index 095236bec..8ed20a6ac 100644 --- a/calib_core/tests/test_solver.cpp +++ b/calib_core/tests/test_solver.cpp @@ -23,32 +23,12 @@ namespace K.p1 = 0.001f; K.p2 = -0.0005f; return K; } -} // namespace - -#ifndef CALIB_ENABLE_CERES -TEST_CASE("solveExtrinsicsCeres: stub explains the build flag when Ceres is disabled") -{ - std::vector corr(3); // content doesn't matter -- fails before using it - Extrinsics E; - std::string err; - CHECK_FALSE(solveExtrinsicsCeres(corr, meiIntrinsics(), E, err)); - CHECK(err.find("CALIB_ENABLE_CERES") != std::string::npos); -} - -#else // CALIB_ENABLE_CERES - -namespace -{ - // Coefficients in the range a real ~180 deg OpenCV fisheye calibration - // produces, not a specific camera. - Intrinsics fisheyeIntrinsics() + Intrinsics pinholeIntrinsics() { - Intrinsics K; - K.model = CameraModel::Fisheye; - K.fx = 285.f; K.fy = 286.f; - K.cx = 322.f; K.cy = 238.f; - K.k1 = -0.0075f; K.k2 = 0.0435f; K.k3 = -0.0414f; K.k4 = 0.0077f; + Intrinsics K; // Pinhole, no distortion + K.fx = 500.f; K.fy = 500.f; + K.cx = 320.f; K.cy = 240.f; return K; } @@ -65,13 +45,16 @@ namespace // A handful of LiDAR-frame points spread across the field of view, // roughly in front of groundTruthExtrinsics()'s camera. The last one is - // ~100 deg off-axis, past where a pinhole model could see it. + // ~100 deg off-axis, behind a pinhole camera. const Eigen::Vector3f kLidarPoints[] = { { 3.f, 0.f, 0.f }, { 4.f, 1.5f, 0.5f }, { 5.f, -1.f, -0.5f }, { 3.5f, 0.8f, -0.8f }, { 6.f, -1.8f, 1.f }, { 4.5f, 0.3f, 1.2f }, { 3.f, -0.6f, 0.4f }, { 1.f, 3.f, 0.5f }, }; - std::vector syntheticCorrespondences(const Intrinsics& K, const Extrinsics& truth) + //! @param dropUnprojectable skip points K cannot see (the off-axis one, + //! for Pinhole) instead of failing the test on them + std::vector syntheticCorrespondences( + const Intrinsics& K, const Extrinsics& truth, bool dropUnprojectable = false) { const Eigen::Matrix3f R_wc = omFiKaToMat3(truth.om, truth.fi, truth.ka); const Eigen::Vector3f C(truth.tx, truth.ty, truth.tz); @@ -80,7 +63,10 @@ namespace for (const auto& p : kLidarPoints) { float u, v, depth; - REQUIRE(projectPoint(p.x(), p.y(), p.z(), K, R_wc, C, u, v, depth)); + const bool projected = projectPoint(p.x(), p.y(), p.z(), K, R_wc, C, u, v, depth); + if (!projected && dropUnprojectable) + continue; + REQUIRE(projected); PointPixelCorrespondence c; c.p = p.cast(); c.u = u; @@ -89,6 +75,178 @@ namespace } return corr; } + + //! Truth with every one of the six parameters nudged off it. + Extrinsics perturbed(const Extrinsics& truth) + { + Extrinsics E = truth; + E.tx += 0.3f; E.ty -= 0.2f; E.tz += 0.15f; + E.om += 2.f; E.fi -= 1.5f; E.ka += 1.f; + return E; + } +} // namespace + +TEST_CASE("solveExtrinsicsFromCorrespondences: locks keep their parameters and solve the rest") +{ + const Intrinsics K = pinholeIntrinsics(); + const Extrinsics truth = groundTruthExtrinsics(); + const auto corr = syntheticCorrespondences(K, truth, /*dropUnprojectable=*/true); + REQUIRE(corr.size() >= 6); + + SUBCASE("no lock recovers all six") + { + Extrinsics E = perturbed(truth); + double rms = -1.0; + REQUIRE(solveExtrinsicsFromCorrespondences(corr, K, E, &rms)); + CHECK(rms < 0.5); + CHECK(E.tx == doctest::Approx(truth.tx).epsilon(1e-3)); + CHECK(E.ty == doctest::Approx(truth.ty).epsilon(1e-3)); + CHECK(E.tz == doctest::Approx(truth.tz).epsilon(1e-3)); + CHECK(E.om == doctest::Approx(truth.om).epsilon(1e-2)); + CHECK(E.fi == doctest::Approx(truth.fi).epsilon(1e-2)); + CHECK(E.ka == doctest::Approx(truth.ka).epsilon(1e-2)); + } + SUBCASE("fixTranslation") + { + Extrinsics E = truth; + E.om += 3.f; E.fi -= 2.f; E.ka += 1.5f; + REQUIRE(solveExtrinsicsFromCorrespondences(corr, K, E, nullptr, /*fixTranslation=*/true)); + CHECK(E.tx == doctest::Approx(truth.tx)); + CHECK(E.ty == doctest::Approx(truth.ty)); + CHECK(E.tz == doctest::Approx(truth.tz)); + CHECK(E.om == doctest::Approx(truth.om).epsilon(1e-2)); + CHECK(E.fi == doctest::Approx(truth.fi).epsilon(1e-2)); + CHECK(E.ka == doctest::Approx(truth.ka).epsilon(1e-2)); + } + SUBCASE("fixRotation") + { + Extrinsics E = truth; + E.tx += 0.3f; E.ty -= 0.2f; E.tz += 0.15f; + REQUIRE(solveExtrinsicsFromCorrespondences(corr, K, E, nullptr, false, /*fixRotation=*/true)); + CHECK(E.om == doctest::Approx(truth.om)); + CHECK(E.fi == doctest::Approx(truth.fi)); + CHECK(E.ka == doctest::Approx(truth.ka)); + CHECK(E.tx == doctest::Approx(truth.tx).epsilon(1e-3)); + CHECK(E.ty == doctest::Approx(truth.ty).epsilon(1e-3)); + CHECK(E.tz == doctest::Approx(truth.tz).epsilon(1e-3)); + } + SUBCASE("a wrong locked value is held, not pulled to the truth") + { + for (const bool lockRotation : { false, true }) + { + CAPTURE(lockRotation); + Extrinsics E = perturbed(truth); + const Extrinsics locked = E; + REQUIRE(solveExtrinsicsFromCorrespondences(corr, K, E, nullptr, !lockRotation, lockRotation)); + if (lockRotation) + { + CHECK(E.om == doctest::Approx(locked.om)); + CHECK(E.fi == doctest::Approx(locked.fi)); + CHECK(E.ka == doctest::Approx(locked.ka)); + } + else + { + CHECK(E.tx == doctest::Approx(locked.tx)); + CHECK(E.ty == doctest::Approx(locked.ty)); + CHECK(E.tz == doctest::Approx(locked.tz)); + } + } + } + SUBCASE("both locked fails and leaves the extrinsics alone") + { + Extrinsics E = perturbed(truth); + const Extrinsics before = E; + CHECK_FALSE(solveExtrinsicsFromCorrespondences(corr, K, E, nullptr, true, true)); + CHECK(E.tx == before.tx); + CHECK(E.om == before.om); + } +} + +TEST_CASE("solveExtrinsicsFromCorrespondences: priors pull a parameter towards its target") +{ + const Intrinsics K = pinholeIntrinsics(); + const Extrinsics truth = groundTruthExtrinsics(); + const auto corr = syntheticCorrespondences(K, truth, /*dropUnprojectable=*/true); + const float wrongTz = truth.tz + 0.5f; + + SUBCASE("a tight prior holds tz at a wrong target; the reported RMS is reprojection only") + { + ExtrinsicsPriors priors; + priors[kPriorTz] = { true, wrongTz, 1e-5 }; + Extrinsics E = perturbed(truth); + double rms = -1.0; + REQUIRE(solveExtrinsicsFromCorrespondences(corr, K, E, &rms, false, false, priors)); + CHECK(E.tz == doctest::Approx(wrongTz).epsilon(1e-3)); + CHECK(rms > 1.0); + } + SUBCASE("a loose prior barely moves the solution") + { + ExtrinsicsPriors priors; + priors[kPriorTz] = { true, wrongTz, 100.0 }; + priors[kPriorKa] = { true, truth.ka + 5.0, 1000.0 }; + Extrinsics E = perturbed(truth); + double rms = -1.0; + REQUIRE(solveExtrinsicsFromCorrespondences(corr, K, E, &rms, false, false, priors)); + CHECK(rms < 0.5); + CHECK(E.tz == doctest::Approx(truth.tz).epsilon(1e-3)); + CHECK(E.ka == doctest::Approx(truth.ka).epsilon(1e-2)); + } + SUBCASE("a tight rotation prior holds ka") + { + ExtrinsicsPriors priors; + priors[kPriorKa] = { true, truth.ka + 3.0, 1e-5 }; + Extrinsics E = perturbed(truth); + REQUIRE(solveExtrinsicsFromCorrespondences(corr, K, E, nullptr, false, false, priors)); + CHECK(E.ka == doctest::Approx(truth.ka + 3.0).epsilon(1e-3)); + } + SUBCASE("a prior on a locked parameter is ignored") + { + ExtrinsicsPriors priors; + priors[kPriorTz] = { true, wrongTz, 1e-5 }; + Extrinsics withPrior = perturbed(truth); + Extrinsics without = withPrior; + REQUIRE(solveExtrinsicsFromCorrespondences(corr, K, withPrior, nullptr, true, false, priors)); + REQUIRE(solveExtrinsicsFromCorrespondences(corr, K, without, nullptr, true, false)); + CHECK(withPrior.tz == without.tz); + CHECK(withPrior.om == doctest::Approx(without.om)); + } + SUBCASE("an enabled prior with sigma <= 0 fails and leaves the extrinsics alone") + { + ExtrinsicsPriors priors; + priors[kPriorTz] = { true, wrongTz, 0.0 }; + Extrinsics E = perturbed(truth); + const Extrinsics before = E; + CHECK_FALSE(solveExtrinsicsFromCorrespondences(corr, K, E, nullptr, false, false, priors)); + CHECK(E.tz == before.tz); + } +} + +#ifndef CALIB_ENABLE_CERES + +TEST_CASE("solveExtrinsicsCeres: stub explains the build flag when Ceres is disabled") +{ + std::vector corr(3); // content doesn't matter -- fails before using it + Extrinsics E; + std::string err; + CHECK_FALSE(solveExtrinsicsCeres(corr, meiIntrinsics(), E, err)); + CHECK(err.find("CALIB_ENABLE_CERES") != std::string::npos); +} + +#else // CALIB_ENABLE_CERES + +namespace +{ + // Coefficients in the range a real ~180 deg OpenCV fisheye calibration + // produces, not a specific camera. + Intrinsics fisheyeIntrinsics() + { + Intrinsics K; + K.model = CameraModel::Fisheye; + K.fx = 285.f; K.fy = 286.f; + K.cx = 322.f; K.cy = 238.f; + K.k1 = -0.0075f; K.k2 = 0.0435f; K.k3 = -0.0414f; K.k4 = 0.0077f; + return K; + } } // namespace TEST_CASE("solveExtrinsicsCeres: recovers known extrinsics from synthetic correspondences") @@ -145,6 +303,86 @@ TEST_CASE("solveExtrinsicsCeres: fixTranslation leaves tx/ty/tz untouched") } } +TEST_CASE("solveExtrinsicsCeres: fixRotation leaves om/fi/ka untouched") +{ + for (const Intrinsics& K : { meiIntrinsics(), fisheyeIntrinsics() }) + { + CAPTURE(modelToString(K.model)); + const Extrinsics truth = groundTruthExtrinsics(); + const auto corr = syntheticCorrespondences(K, truth); + + Extrinsics guess = truth; + guess.tx += 0.3f; guess.ty -= 0.2f; guess.tz += 0.15f; + + double rms = -1.0; + std::string err; + REQUIRE(solveExtrinsicsCeres(corr, K, guess, err, &rms, false, /*fixRotation=*/true)); + + CHECK(guess.om == doctest::Approx(truth.om)); + CHECK(guess.fi == doctest::Approx(truth.fi)); + CHECK(guess.ka == doctest::Approx(truth.ka)); + CHECK(guess.tx == doctest::Approx(truth.tx).epsilon(1e-3)); + CHECK(guess.ty == doctest::Approx(truth.ty).epsilon(1e-3)); + CHECK(guess.tz == doctest::Approx(truth.tz).epsilon(1e-3)); + + // A wrong locked rotation is held, not pulled to the truth. + Extrinsics wrong = perturbed(truth); + const Extrinsics locked = wrong; + REQUIRE(solveExtrinsicsCeres(corr, K, wrong, err, &rms, false, /*fixRotation=*/true)); + CHECK(wrong.om == doctest::Approx(locked.om)); + CHECK(wrong.fi == doctest::Approx(locked.fi)); + CHECK(wrong.ka == doctest::Approx(locked.ka)); + } +} + +TEST_CASE("solveExtrinsicsCeres: priors pull a parameter towards its target") +{ + for (const Intrinsics& K : { meiIntrinsics(), fisheyeIntrinsics() }) + { + CAPTURE(modelToString(K.model)); + const Extrinsics truth = groundTruthExtrinsics(); + const auto corr = syntheticCorrespondences(K, truth); + std::string err; + + ExtrinsicsPriors tight; + tight[kPriorTz] = { true, truth.tz + 0.5, 1e-5 }; + tight[kPriorKa] = { true, truth.ka + 3.0, 1e-5 }; + Extrinsics E = perturbed(truth); + double rms = -1.0; + REQUIRE(solveExtrinsicsCeres(corr, K, E, err, &rms, false, false, tight)); + CHECK(E.tz == doctest::Approx(truth.tz + 0.5).epsilon(1e-3)); + CHECK(E.ka == doctest::Approx(truth.ka + 3.0).epsilon(1e-3)); + CHECK(rms > 1.0); + + ExtrinsicsPriors loose; + loose[kPriorTz] = { true, truth.tz + 0.5, 100.0 }; + Extrinsics F = perturbed(truth); + REQUIRE(solveExtrinsicsCeres(corr, K, F, err, &rms, false, false, loose)); + CHECK(rms < 0.5); + CHECK(F.tz == doctest::Approx(truth.tz).epsilon(1e-3)); + + ExtrinsicsPriors invalid; + invalid[kPriorOm].enabled = true; + invalid[kPriorOm].sigma = -1.0; + Extrinsics G = perturbed(truth); + CHECK_FALSE(solveExtrinsicsCeres(corr, K, G, err, nullptr, false, false, invalid)); + CHECK(err.find("sigma") != std::string::npos); + } +} + +TEST_CASE("solveExtrinsicsCeres: both locks set fails and says why") +{ + const Intrinsics K = meiIntrinsics(); + const auto corr = syntheticCorrespondences(K, groundTruthExtrinsics()); + Extrinsics E = perturbed(groundTruthExtrinsics()); + const Extrinsics before = E; + std::string err; + CHECK_FALSE(solveExtrinsicsCeres(corr, K, E, err, nullptr, true, true)); + CHECK(err.find("locked") != std::string::npos); + CHECK(E.tx == before.tx); + CHECK(E.om == before.om); +} + TEST_CASE("solveExtrinsicsCeres: a model it has no residual for fails and says why") { // Routing a pinhole camera here by mistake would otherwise solve it as Mei. @@ -157,4 +395,84 @@ TEST_CASE("solveExtrinsicsCeres: a model it has no residual for fails and says w CHECK(E.tx == groundTruthExtrinsics().tx); } +TEST_CASE("solveExtrinsicsAndIntrinsicsCeres: refines the selected Mei intrinsics, keeps the rest") +{ + const Intrinsics truthK = meiIntrinsics(); + const Extrinsics truthE = groundTruthExtrinsics(); + const auto corr = syntheticCorrespondences(truthK, truthE); + + Intrinsics K = truthK; + K.fx *= 1.04f; + K.fy *= 0.97f; + K.cx += 8.f; + K.cy -= 5.f; + Extrinsics E = perturbed(truthE); + + MeiIntrinsicsRefinement refine; + refine.focal = true; + refine.principalPoint = true; + double rms = -1.0; + std::string err; + REQUIRE(solveExtrinsicsAndIntrinsicsCeres(corr, K, E, refine, err, &rms)); + + CHECK(rms < 0.5); + CHECK(K.fx == doctest::Approx(truthK.fx).epsilon(1e-3)); + CHECK(K.fy == doctest::Approx(truthK.fy).epsilon(1e-3)); + CHECK(K.cx == doctest::Approx(truthK.cx).epsilon(1e-3)); + CHECK(K.cy == doctest::Approx(truthK.cy).epsilon(1e-3)); + CHECK(E.tx == doctest::Approx(truthE.tx).epsilon(1e-3)); + CHECK(E.ka == doctest::Approx(truthE.ka).epsilon(1e-2)); + // Not selected: bit-for-bit what went in. + CHECK(K.xi == truthK.xi); + CHECK(K.k1 == truthK.k1); + CHECK(K.p2 == truthK.p2); +} + +TEST_CASE("solveExtrinsicsAndIntrinsicsCeres: intrinsics alone, with both extrinsics locked") +{ + const Intrinsics truthK = meiIntrinsics(); + const Extrinsics truthE = groundTruthExtrinsics(); + const auto corr = syntheticCorrespondences(truthK, truthE); + + Intrinsics K = truthK; + K.cx += 6.f; + Extrinsics E = truthE; + MeiIntrinsicsRefinement refine; + refine.principalPoint = true; + std::string err; + REQUIRE(solveExtrinsicsAndIntrinsicsCeres(corr, K, E, refine, err, nullptr, true, true)); + CHECK(K.cx == doctest::Approx(truthK.cx).epsilon(1e-3)); + CHECK(E.tx == truthE.tx); + CHECK(E.om == truthE.om); +} + +TEST_CASE("solveExtrinsicsAndIntrinsicsCeres: refusals leave both inputs unchanged") +{ + MeiIntrinsicsRefinement all; + all.focal = all.principalPoint = all.xi = all.distortion = true; + std::string err; + + SUBCASE("refining a fisheye") + { + Intrinsics K = fisheyeIntrinsics(); + const auto corr = syntheticCorrespondences(K, groundTruthExtrinsics()); + Extrinsics E = perturbed(groundTruthExtrinsics()); + const Extrinsics before = E; + CHECK_FALSE(solveExtrinsicsAndIntrinsicsCeres(corr, K, E, all, err)); + CHECK(err.find("mei model only") != std::string::npos); + CHECK(E.tx == before.tx); + CHECK(K.fx == fisheyeIntrinsics().fx); + } + SUBCASE("fewer pairs than half the free parameters") + { + Intrinsics K = meiIntrinsics(); + auto corr = syntheticCorrespondences(K, groundTruthExtrinsics()); + corr.pop_back(); // 7 pairs, 16 free parameters + Extrinsics E = perturbed(groundTruthExtrinsics()); + CHECK_FALSE(solveExtrinsicsAndIntrinsicsCeres(corr, K, E, all, err)); + CHECK(err.find("at least 8") != std::string::npos); + CHECK(K.k1 == meiIntrinsics().k1); + } +} + #endif // CALIB_ENABLE_CERES \ No newline at end of file diff --git a/core/src/raylib_utils.cpp b/core/src/raylib_utils.cpp index f6250f7aa..7f536236a 100644 --- a/core/src/raylib_utils.cpp +++ b/core/src/raylib_utils.cpp @@ -446,12 +446,16 @@ void drawMiniCompassWithRuler() // Rows 0/1 of the world-to-eye rotation are the world directions of screen right/up. const Eigen::Matrix3f& R = viewLocal.rotation(); Color rulerColor = ColorFromNormalized(Vector4{ 1.0f - bg_color.x, 1.0f - bg_color.y, 1.0f - bg_color.z, 1.0f }); + // Stay above ImGui bars docked to the bottom edge (BeginViewportSideBar). + const ImGuiViewport* vp = ImGui::GetMainViewport(); + const float bottomInset = std::max(0.f, (vp->Pos.y + vp->Size.y) - (vp->WorkPos.y + vp->WorkSize.y)); raylib_widgets::drawCompassRuler( Vector3{ R(0, 0), R(0, 1), R(0, 2) }, Vector3{ R(1, 0), R(1, 1), R(1, 2) }, camera.euler.translate.z, rulerColor, - raylib_widgets::CompassAxisLabels{ "X (long.)", "Y (lat.)", "Z (vert.)" }); + raylib_widgets::CompassAxisLabels{ "X (long.)", "Y (lat.)", "Z (vert.)" }, + bottomInset); } void draw_ellipse(const Eigen::Affine3d& transform, Eigen::Vector3f color) diff --git a/raylib_widgets/CMakeLists.txt b/raylib_widgets/CMakeLists.txt index 285f7abd3..dfef7c5f2 100644 --- a/raylib_widgets/CMakeLists.txt +++ b/raylib_widgets/CMakeLists.txt @@ -23,6 +23,7 @@ add_library(raylib_widgets STATIC src/PointPicking.cpp src/AppShell.cpp src/RayPlaneD.cpp + src/Timeline.cpp ) target_include_directories(raylib_widgets PUBLIC include ${EIGEN3_INCLUDE_DIR}) diff --git a/raylib_widgets/include/RaylibWidgets/CompassRuler.h b/raylib_widgets/include/RaylibWidgets/CompassRuler.h index f77fa4485..2c34e74ba 100644 --- a/raylib_widgets/include/RaylibWidgets/CompassRuler.h +++ b/raylib_widgets/include/RaylibWidgets/CompassRuler.h @@ -22,8 +22,10 @@ namespace raylib_widgets // or the first two rows of a world-to-eye rotation matrix). // zoomDistance: current camera distance/zoom, used to size the ruler. // rulerColor: contrast color for the ruler ticks/label (axis lines are - // always drawn in RGB = X/Y/Z). Call after 3D drawing ends (2D screen-space - // overlay). - void drawCompassRuler(Vector3 right, Vector3 up, float zoomDistance, Color rulerColor, CompassAxisLabels labels = {}); + // always drawn in RGB = X/Y/Z). bottomInset: screen pixels to keep clear + // along the bottom edge (e.g. a bottom toolbar). Call after 3D drawing ends + // (2D screen-space overlay). + void drawCompassRuler( + Vector3 right, Vector3 up, float zoomDistance, Color rulerColor, CompassAxisLabels labels = {}, float bottomInset = 0.f); } // namespace raylib_widgets diff --git a/raylib_widgets/include/RaylibWidgets/Timeline.h b/raylib_widgets/include/RaylibWidgets/Timeline.h new file mode 100644 index 000000000..6cb768400 --- /dev/null +++ b/raylib_widgets/include/RaylibWidgets/Timeline.h @@ -0,0 +1,48 @@ +#pragma once + +#include +#include + +// Scrubbable time ruler with ticks and a playhead, shared between +// camera_lidar_trajectory_viewer's flyover bar and mandeye_raw_data_viewer's +// playback bar. +namespace raylib_widgets +{ + + //! A band marked across the timeline's track, e.g. a segment of interest. + struct TimelineSpan + { + float from = 0.f, to = 0.f; //!< 0-1 positions along the timeline + unsigned int color = 0; //!< ImU32, drawn over the track; give it some transparency + std::string label; //!< added to the hover tooltip over the band; may be empty + }; + + //! A row of bars under the timeline's track, e.g. one bar per input file, Gantt-style. + struct TimelineLane + { + std::string name; //!< drawn at the lane's left end; may be empty + std::vector bars; //!< in time order; their labels name them in the tooltip + }; + + //! Height of one TimelineLane [px]. + inline constexpr float kTimelineLaneHeight = 12.f; + + //! Timeline across the available width, with time ticks and a playhead. + //! Click or drag on it to scrub. + //! @param id ImGui id of the scrub area + //! @param progress 0-1 playhead position; written while the user drags + //! @param durationSec time the full width spans, for the tick labels + //! @param height height of the track and the tick label row + //! @param spans bands to mark on the track + //! @param lanes rows of bars between the track and the tick labels, each adding + //! kTimelineLaneHeight to the height; hovering between two bars shows the gap + //! @return true on the frames the user moved the playhead + bool timeline( + const char* id, + float& progress, + double durationSec, + float height, + const std::vector& spans = {}, + const std::vector& lanes = {}); + +} // namespace raylib_widgets diff --git a/raylib_widgets/src/CompassRuler.cpp b/raylib_widgets/src/CompassRuler.cpp index ade1a0b22..058e7bbf7 100644 --- a/raylib_widgets/src/CompassRuler.cpp +++ b/raylib_widgets/src/CompassRuler.cpp @@ -9,11 +9,11 @@ namespace raylib_widgets { - void drawCompassRuler(Vector3 right, Vector3 up, float zoomDistance, Color rulerColor, CompassAxisLabels labels) + void drawCompassRuler(Vector3 right, Vector3 up, float zoomDistance, Color rulerColor, CompassAxisLabels labels, float bottomInset) { const float compassSize = 200.0f; const float originX = compassSize * 0.5f; - const float originY = static_cast(GetScreenHeight()) - compassSize * 0.5f; + const float originY = static_cast(GetScreenHeight()) - bottomInset - compassSize * 0.5f; const float axisPixelLength = compassSize * 0.35f; struct Axis diff --git a/raylib_widgets/src/Timeline.cpp b/raylib_widgets/src/Timeline.cpp new file mode 100644 index 000000000..4e3477203 --- /dev/null +++ b/raylib_widgets/src/Timeline.cpp @@ -0,0 +1,170 @@ +#include + +#include + +#include +#include +#include +#include + +namespace raylib_widgets +{ + + namespace + { + //! Smallest "round" tick step (s) that keeps ticks at least `minPx` apart. + double tickStep(double durationSec, float widthPx, float minPx) + { + static const double kSteps[] = { 0.1, 0.2, 0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600 }; + const double pxPerSec = widthPx / durationSec; + for (double step : kSteps) + if (step * pxPerSec >= minPx) + return step; + double step = kSteps[std::size(kSteps) - 1]; + while (step * pxPerSec < minPx) + step *= 2.0; + return step; + } + + //! Tick label: "m:ss" from a minute on, else seconds with a decimal only when + //! the tick step needs one. + std::string tickLabel(double sec, double step) + { + char buf[32]; + if (sec >= 60.0) + std::snprintf(buf, sizeof(buf), "%d:%02d", int(sec + 1e-6) / 60, int(sec + 1e-6) % 60); + else if (step < 1.0) + std::snprintf(buf, sizeof(buf), "%.1fs", sec); + else + std::snprintf(buf, sizeof(buf), "%.0fs", sec); + return buf; + } + } // namespace + + bool timeline( + const char* id, + float& progress, + double durationSec, + float height, + const std::vector& spans, + const std::vector& lanes) + { + ImDrawList* dl = ImGui::GetWindowDrawList(); + const ImVec2 p0 = ImGui::GetCursorScreenPos(); + const float w = std::max(1.f, ImGui::GetContentRegionAvail().x); + const float trackH = height - ImGui::GetTextLineHeight(); + const ImVec2 p1(p0.x + w, p0.y + trackH); + // Lanes sit between the track and the tick labels. + const float lanesBottom = p1.y + kTimelineLaneHeight * static_cast(lanes.size()); + auto toX = [&](float f) + { + return p0.x + w * std::clamp(f, 0.f, 1.f); + }; + + ImGui::InvisibleButton(id, ImVec2(w, height + (lanesBottom - p1.y))); + bool moved = false; + if (ImGui::IsItemActive()) + { + const float f = std::clamp((ImGui::GetIO().MousePos.x - p0.x) / w, 0.f, 1.f); + moved = f != progress; + progress = f; + } + if (ImGui::IsItemHovered() && durationSec > 0.0) + { + const ImVec2 mouse = ImGui::GetIO().MousePos; + const float f = std::clamp((mouse.x - p0.x) / w, 0.f, 1.f); + char text[256]; + std::snprintf(text, sizeof(text), "%.2f s", f * durationSec); + std::string tip = text; + if (mouse.y < p1.y) + { + for (const TimelineSpan& span : spans) + if (!span.label.empty() && f >= span.from && f <= span.to) + tip += ", " + span.label; + } + else if (mouse.y < lanesBottom) + { + const auto& bars = lanes[std::min(lanes.size() - 1, static_cast((mouse.y - p1.y) / kTimelineLaneHeight))].bars; + for (size_t k = 0; k < bars.size(); ++k) + { + if (f >= bars[k].from && f <= bars[k].to) + { + if (!bars[k].label.empty()) + tip += "\n" + bars[k].label; + break; + } + if (k + 1 < bars.size() && f > bars[k].to && f < bars[k + 1].from) + { + std::snprintf(text, sizeof(text), "\ngap of %.3f s", (bars[k + 1].from - bars[k].to) * durationSec); + tip += text; + break; + } + } + } + ImGui::SetTooltip("%s", tip.c_str()); + } + + dl->AddRectFilled(p0, p1, IM_COL32(40, 40, 40, 255), 3.f); + dl->AddRectFilled(p0, ImVec2(p0.x + w * progress, p1.y), IM_COL32(60, 110, 160, 255), 3.f, ImDrawFlags_RoundCornersLeft); + // At least a pixel wide, so a short span still shows on a long timeline. + for (const TimelineSpan& span : spans) + { + const float x0 = toX(span.from); + dl->AddRectFilled(ImVec2(x0, p0.y), ImVec2(std::max(x0 + 1.f, toX(span.to)), p1.y), span.color); + } + + for (size_t l = 0; l < lanes.size(); ++l) + { + const float y0 = p1.y + kTimelineLaneHeight * static_cast(l) + 1.f; + const float y1 = y0 + kTimelineLaneHeight - 1.f; + dl->AddRectFilled(ImVec2(p0.x, y0), ImVec2(p1.x, y1), IM_COL32(30, 30, 30, 255)); + const auto& bars = lanes[l].bars; + for (size_t k = 0; k < bars.size(); ++k) + { + if (bars[k].to < 0.f || bars[k].from > 1.f) + continue; + const float x0 = toX(bars[k].from); + float x1 = std::max(x0 + 1.f, toX(bars[k].to)); + // A gap narrower than a pixel would only show where it straddles a pixel centre. + if (k + 1 < bars.size() && toX(bars[k + 1].from) - x1 < 1.f) + x1 = std::max(x1, toX(bars[k + 1].from)); + dl->AddRectFilled(ImVec2(x0, y0), ImVec2(x1, y1), bars[k].color); + } + if (!lanes[l].name.empty()) + dl->AddText( + ImGui::GetFont(), + kTimelineLaneHeight - 1.f, + ImVec2(p0.x + 3.f, y0), + IM_COL32(255, 255, 255, 230), + lanes[l].name.c_str()); + } + + if (durationSec > 0.0) + { + // Major ticks carry a label; four unlabelled minor ticks between them. + const double major = tickStep(durationSec, w, 70.f); + const double minor = major / 5.0; + const double pxPerSec = w / durationSec; + for (int k = 0; k * minor <= durationSec + 1e-9; ++k) + { + const bool isMajor = k % 5 == 0; + const float x = p0.x + float(k * minor * pxPerSec); + dl->AddLine(ImVec2(x, p1.y - trackH * (isMajor ? 0.6f : 0.3f)), ImVec2(x, p1.y), IM_COL32(170, 170, 170, 255)); + if (isMajor) + { + const std::string label = tickLabel(k * minor, major); + const float lw = ImGui::CalcTextSize(label.c_str()).x; + const float lx = std::clamp(x - lw * 0.5f, p0.x, p0.x + w - lw); + dl->AddText(ImVec2(lx, lanesBottom), IM_COL32(200, 200, 200, 255), label.c_str()); + } + } + } + + const float px = p0.x + w * progress; + const ImU32 playheadCol = IM_COL32(255, 220, 60, 255); + dl->AddLine(ImVec2(px, p0.y), ImVec2(px, lanesBottom), playheadCol, 2.f); + dl->AddTriangleFilled(ImVec2(px - 5.f, p0.y), ImVec2(px + 5.f, p0.y), ImVec2(px, p0.y + 6.f), playheadCol); + return moved; + } + +} // namespace raylib_widgets