diff --git a/command/arms_rviz_control_plugin/CMakeLists.txt b/command/arms_rviz_control_plugin/CMakeLists.txt index 21a931f2..af96081d 100644 --- a/command/arms_rviz_control_plugin/CMakeLists.txt +++ b/command/arms_rviz_control_plugin/CMakeLists.txt @@ -11,6 +11,8 @@ set(CMAKE_EXPORT_COMPILE_COMMANDS ON) find_package(ament_cmake REQUIRED) find_package(rclcpp REQUIRED) find_package(rviz_common REQUIRED) +find_package(rviz_ogre_vendor REQUIRED) +find_package(rviz_rendering REQUIRED) find_package(arms_controller_common REQUIRED) find_package(sensor_msgs REQUIRED) find_package(std_msgs REQUIRED) @@ -35,6 +37,7 @@ cmake_language(CALL qt${QT_VERSION_MAJOR}_wrap_cpp MOC_FILES include/arms_rviz_control_plugin/gripper_control_panel.hpp include/arms_rviz_control_plugin/joint_control_panel.hpp include/arms_rviz_control_plugin/wbc_capability_panel.hpp + include/arms_rviz_control_plugin/target_error_display.hpp include/arms_rviz_control_plugin/switch_button.hpp ) @@ -44,6 +47,7 @@ set(SRC_FILES src/gripper_control_panel.cpp src/joint_control_panel.cpp src/wbc_capability_panel.cpp + src/target_error_display.cpp src/switch_button.cpp ) @@ -57,6 +61,8 @@ target_link_libraries(${PROJECT_NAME} PUBLIC Qt${QT_VERSION_MAJOR}::Widgets ${rclcpp_TARGETS} rviz_common::rviz_common + rviz_ogre_vendor::OgreOverlay + rviz_rendering::rviz_rendering arms_controller_common::arms_controller_common ${sensor_msgs_TARGETS} ${std_msgs_TARGETS} diff --git a/command/arms_rviz_control_plugin/README.md b/command/arms_rviz_control_plugin/README.md index 49bdcedf..25bb0ba9 100644 --- a/command/arms_rviz_control_plugin/README.md +++ b/command/arms_rviz_control_plugin/README.md @@ -201,3 +201,23 @@ source install/setup.bash - 相对增量的角速度分量约定为 RPY(与控制器 `PoseBasedReferenceManager` 一致:`dq = Rz·Ry·Rx`)。 - Body TRACKING 笛卡尔目标与腰部 Float64 点动分离:追踪时用 `body_target/*`,点动仅用于 MOVEJ / 非追踪场景。 - 旧 README 中的 `/control_input` 已废弃,现统一使用 `/fsm_command`。 + +### 三维视窗中的目标跟踪误差 HUD + +HUD 作为 `arms_rviz_control_plugin/TargetErrorDisplay` 显示在 RViz 网格视图右上角, +不再位于 JointControlPanel,也不依赖该控制面板存在。 +W2 的 fullbody/splitbody 和通用 humanoid 配置已启用。 +已有用户配置可在 Displays → Add → TargetErrorDisplay 添加,用 Displays 复选框开关。 + +独立订阅 left/right/body/head_current_pose 与对应的 current_target,以及 +`/ocs2_wbc_controller/current_state`。没有命令发布器,不影响机器人控制。 +以最高 10 Hz 更新显示内容,仅在文字或颜色变化时更新 Ogre 文字元素、实测 1 秒超时,目标保留最后一帧;不同 frame 或无效位姿不计算误差。 +只显示已启用的手臂(ARM_ENABLED)、位姿跟踪中的 BODY(BODY_TRACKING,且非 HEAD_FORWARD)和 HEAD(HEAD_TRACKING)。未启用部分隐藏并收拢空位,切换时清空对应曲线;未收到模式状态时全部隐藏。模式订阅使用 transient-local,支持 RViz 晚于控制器启动。 + +位置 ≤5 mm 为绿色、≥20 mm 为红色;姿态 ≤1°为绿色、≥5°为红色,中间黄色。 +无效或超时数值灰色,数值显示破折号。颜色阈值调整入口隐藏,Display 配置中仍保存阈值。 +使用 RViz 底层 Ogre Overlay 的原生 BorderPanel 与 TextArea 元素,每个末端使用独立细边框、完全透明且无填充的背景、大数字和单位标签,无 QWidget 叠加;文字使用原生 Ogre 元素,趋势线使用小尺寸透明纹理。LEFT ARM / RIGHT ARM / BODY / HEAD 分别表示左臂、右臂、躯干和头部;POS (mm) / ANG (deg) 分别为位置和姿态误差。使用 RViz 自带 Liberation Sans Bold 字体并一次性生成高清字形纹理,不需要额外插件。有效误差仅通过数值颜色表示等级,不显示等级文案;无效数据保留具体原因,未启用跟踪时隐藏整个框。固定标签为黑色粗体。数值不截断。此显示为屏幕叠加,不随 Grid 的相机缩放或旋转。 + +每个框的位置、姿态数字背后各叠加最近 5 秒的半透明误差曲线,最多 5 Hz 更新。横轴按实际时间滚动;纵轴固定为 0 到对应红色阈值的两倍,红色虚线表示红色阈值,超出上限时在顶部显示短标记。无效数据或采样间隔超过 0.6 秒时断线,RViz Reset 清空历史。不显示时间窗口标注,曲线不另占高度;数字保持不透明并在曲线上层显示,单位沿用下方标签。 + +HUD 以控制器实际反馈 `/fsm_state`(transient-local)为总开关,仅状态 3(OCS2)计算和显示误差。HOME、HOLD、MOVEJ、未知状态或尚未收到状态时隐藏并跳过误差/曲线更新;状态切换清空曲线并等待新的实际位姿。保留目标缓存以兼容仅在目标变化时发布的话题;非 OCS2 模式直接丢弃实际位姿回调数据。 diff --git a/command/arms_rviz_control_plugin/include/arms_rviz_control_plugin/error_dashboard.hpp b/command/arms_rviz_control_plugin/include/arms_rviz_control_plugin/error_dashboard.hpp new file mode 100644 index 00000000..cd49d5d6 --- /dev/null +++ b/command/arms_rviz_control_plugin/include/arms_rviz_control_plugin/error_dashboard.hpp @@ -0,0 +1,185 @@ +#pragma once +#include "arms_rviz_control_plugin/error_sparkline.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace arms_rviz_control_plugin { +// Screen-space text rendered by RViz's Ogre overlay system; no QWidget; only the small trend textures update at 5 Hz. +class ErrorDashboard { +public: + ErrorDashboard() { + static std::atomic next_id{0}; + name_ = "TrackingErrorHUD/" + std::to_string(next_id++); + font_ = Ogre::FontManager::getSingleton().create(name_+"/font", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); + font_->setType(Ogre::FT_TRUETYPE); + font_->setSource("LiberationSans-Bold.ttf"); + font_->setTrueTypeSize(40); + font_->setTrueTypeResolution(192); + font_->load(); + createMaterial("border", Ogre::ColourValue(0.43, 0.49, 0.57, 1)); + auto& manager = Ogre::OverlayManager::getSingleton(); + overlay_ = manager.create(name_); + overlay_->setZOrder(500); + panel_ = static_cast(manager.createOverlayElement("Panel", name_+"/panel")); + panel_->setMetricsMode(Ogre::GMM_PIXELS); + panel_->setHorizontalAlignment(Ogre::GHA_RIGHT); + panel_->setPosition(-366, 16); + panel_->setDimensions(350, 574); + overlay_->add2D(panel_); + const char* names[] = {"LEFT ARM", "RIGHT ARM", "BODY", "HEAD"}; + for (size_t row = 0; row < 4; ++row) { + const float top = row * 146; + auto* card = static_cast(manager.createOverlayElement( + "BorderPanel", name_+"/card"+std::to_string(row))); + card->setMetricsMode(Ogre::GMM_PIXELS); + card->setPosition(0, top); + card->setDimensions(350, 136); + card->setBorderSize(1); + card->setBorderMaterialName(name_+"/border"); + panel_->addChild(card); + cards_[row] = card; + card->hide(); + text_parent_ = card; + addText(names[row], 12, 8, 24, Ogre::ColourValue::Black); + for (size_t col = 0; col < 2; ++col) { + charts_[row][col] = std::make_unique(name_+"/chart"+std::to_string(row*2+col), card, 12+col*174); + values_[row][col] = addText("--", 12+col*174, 38, 46, muted()); + addText(col == 0 ? "POS (mm)" : "ANG (deg)", 12+col*174, 86, 20, Ogre::ColourValue::Black); + } + status_[row] = addText("Waiting for poses", 12, 112, 16, Ogre::ColourValue::Black); + } + } + ~ErrorDashboard() { + auto& manager = Ogre::OverlayManager::getSingleton(); + overlay_->hide(); + for (auto& row : charts_) for (auto& chart : row) chart.reset(); + for (auto* text : texts_) { + text->getParent()->removeChild(text->getName()); + manager.destroyOverlayElement(text); + } + for (auto* card : cards_) { + panel_->removeChild(card->getName()); + manager.destroyOverlayElement(card); + } + overlay_->remove2D(panel_); + manager.destroyOverlayElement(panel_); + manager.destroy(overlay_); + for (const auto& material : materials_) Ogre::MaterialManager::getSingleton().remove(material->getName()); + Ogre::FontManager::getSingleton().remove(font_->getName()); + } + ErrorDashboard(const ErrorDashboard&) = delete; + ErrorDashboard& operator=(const ErrorDashboard&) = delete; + void setActive(const std::array& active) { + if (active == active_) return; + size_t visible = 0; + for (size_t row = 0; row < cards_.size(); ++row) { + if (active[row] != active_[row]) { + for (auto& chart : charts_[row]) chart->clear(); + } + if (active[row]) { + cards_[row]->setPosition(0, 146*visible++); + cards_[row]->show(); + } else { + cards_[row]->hide(); + } + } + active_ = active; + layout_pending_ = true; + } + void clearHistory() { for (auto& row : charts_) for (auto& chart : row) chart->clear(); } + void show() { overlay_->show(); } + void hide() { overlay_->hide(); } + void refreshLayout() { + // TextArea adjusts its width on the first rendered frame. Refresh once afterwards + // so short static labels use their final clipping rectangle. + if (!layout_pending_) return; + for (auto* text : texts_) text->_positionsOutOfDate(); + layout_pending_ = false; + } + void setRow(size_t row, double mm, double degrees, bool valid, + const QString& status, const std::array& limits) { + charts_[row][0]->update(mm, valid, limits[0], limits[1]); + charts_[row][1]->update(degrees, valid, limits[2], limits[3]); + setReading(values_[row][0], mm, valid, limits[0], limits[1]); + setReading(values_[row][1], degrees, valid, limits[2], limits[3]); + // The font shipped with RViz supports Latin labels; retain all invalid-state reasons. + const std::string message = valid ? "" : + status == "当前位姿已超时" ? "State timed out" : + status == "参考坐标系不一致" ? "Frame mismatch" : + status == "位姿数据无效" ? "Invalid pose" : "Waiting for poses"; + if (status_[row]->getCaption() != message) status_[row]->setCaption(message); + } +private: + void createMaterial(const std::string& suffix, const Ogre::ColourValue& color) { + auto material = Ogre::MaterialManager::getSingleton().create( + name_+"/"+suffix, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); + auto* pass = material->getTechnique(0)->getPass(0); + pass->setLightingEnabled(false); + pass->setDepthCheckEnabled(false); + pass->setDepthWriteEnabled(false); + pass->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA); + auto* unit = pass->createTextureUnitState(); + unit->setColourOperationEx(Ogre::LBX_SOURCE1, Ogre::LBS_MANUAL, Ogre::LBS_CURRENT, color); + unit->setAlphaOperation(Ogre::LBX_SOURCE1, Ogre::LBS_MANUAL, Ogre::LBS_CURRENT, color.a); + materials_.push_back(material); + } + static Ogre::ColourValue muted() { return Ogre::ColourValue(0.72f, 0.76f, 0.81f, 1); } + Ogre::TextAreaOverlayElement* addText(const std::string& caption, float x, float y, + float height, const Ogre::ColourValue& color) { + auto* text = static_cast( + Ogre::OverlayManager::getSingleton().createOverlayElement( + "TextArea", name_+"/text"+std::to_string(texts_.size()))); + texts_.push_back(text); + text->initialise(); + text->setMetricsMode(Ogre::GMM_PIXELS); + text->setPosition(x, y); + text->setDimensions(170, height+2); + text->setFontName(font_->getName()); + text->setCharHeight(height); + text->setCaption(caption); + text->setColour(color); + text_parent_->addChild(text); + return text; + } + static void setReading(Ogre::TextAreaOverlayElement* text, double value, bool valid, + double green, double red) { + valid = valid && std::isfinite(value) && value >= 0 && + std::isfinite(green) && std::isfinite(red) && green >= 0 && red > green; + const auto caption = valid ? QString::number(value, 'f', 2).toStdString() : "--"; + const auto color = !valid ? muted() : value <= green ? Ogre::ColourValue(0.22, 0.72, 0.46) : + value >= red ? Ogre::ColourValue(0.90, 0.34, 0.40) : Ogre::ColourValue(0.86, 0.63, 0.22); + if (text->getCaption() != caption) text->setCaption(caption); + if (text->getColour() != color) text->setColour(color); + // Keep large readings inside their card without clipping the actual value. + const float height = caption.size() > 7 ? 32 : 46; + if (text->getCharHeight() != height) text->setCharHeight(height); + } + std::array, 2>, 4> charts_{}; + std::array active_{}; + bool layout_pending_{true}; + std::string name_; + Ogre::Overlay* overlay_{}; + Ogre::OverlayContainer* panel_{}; + Ogre::FontPtr font_; + std::vector materials_; + std::array cards_{}; + Ogre::OverlayContainer* text_parent_{}; + std::vector texts_; + std::array, 4> values_{}; + std::array status_{}; +}; +} diff --git a/command/arms_rviz_control_plugin/include/arms_rviz_control_plugin/error_sparkline.hpp b/command/arms_rviz_control_plugin/include/arms_rviz_control_plugin/error_sparkline.hpp new file mode 100644 index 00000000..b3e40f23 --- /dev/null +++ b/command/arms_rviz_control_plugin/include/arms_rviz_control_plugin/error_sparkline.hpp @@ -0,0 +1,113 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace arms_rviz_control_plugin { +// Small transparent texture on a native Ogre overlay, sampled at most 5 Hz. +class ErrorSparkline { +public: + ErrorSparkline(const std::string& name, Ogre::OverlayContainer* parent, float x) + : name_(name), parent_(parent) { + texture_ = Ogre::TextureManager::getSingleton().createManual(name_, + Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, + width, height, 0, Ogre::PF_BYTE_RGBA, Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE); + material_ = Ogre::MaterialManager::getSingleton().create(name_, + Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); + auto* pass = material_->getTechnique(0)->getPass(0); + pass->setLightingEnabled(false); + pass->setDepthCheckEnabled(false); + pass->setDepthWriteEnabled(false); + pass->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA); + pass->createTextureUnitState(name_)->setTextureFiltering(Ogre::TFO_NONE); + panel_ = static_cast( + Ogre::OverlayManager::getSingleton().createOverlayElement("Panel", name_)); + panel_->setMetricsMode(Ogre::GMM_PIXELS); + panel_->setPosition(x, 38); + panel_->setDimensions(width, height); + panel_->setMaterialName(name_); + parent_->addChild(panel_); + QImage blank(width, height, QImage::Format_RGBA8888); + blank.fill(Qt::transparent); + upload(blank); + } + ~ErrorSparkline() { + parent_->removeChild(panel_->getName()); + Ogre::OverlayManager::getSingleton().destroyOverlayElement(panel_); + Ogre::MaterialManager::getSingleton().remove(name_); + material_.reset(); + Ogre::TextureManager::getSingleton().remove(name_); + } + void clear() { + samples_.clear(); + last_ = {}; + QImage blank(width, height, QImage::Format_RGBA8888); + blank.fill(Qt::transparent); + upload(blank); + } + void update(double value, bool valid, double green, double red) { + const auto now = std::chrono::steady_clock::now(); + if (last_.time_since_epoch().count() && now-last_ < std::chrono::milliseconds(200)) return; + last_ = now; + const double t = std::chrono::duration(now.time_since_epoch()).count(); + valid = valid && std::isfinite(value) && value >= 0; + samples_.push_back({t, value, valid}); + while (!samples_.empty() && samples_.front().time < t-window_seconds) samples_.pop_front(); + const double ceiling = 2*red; + if (!std::isfinite(ceiling) || ceiling <= 0) return; + QImage image(width, height, QImage::Format_RGBA8888); + image.fill(Qt::transparent); + QPainter painter(&image); + painter.setRenderHint(QPainter::Antialiasing); + painter.setPen(QPen(QColor(110, 125, 145, 65), 1)); + painter.drawLine(1, 44, width-1, 44); + painter.setPen(QPen(QColor(200, 80, 90, 65), 1, Qt::DashLine)); + painter.drawLine(1, 23, width-1, 23); // Red threshold; fixed upper bound is twice red. + QPointF previous; + bool connected = false; + double previous_time = 0; + for (const auto& sample : samples_) { + if (!sample.valid) { connected = false; continue; } + const QPointF point(1+(sample.time-(t-window_seconds))/window_seconds*(width-2), + 44-std::clamp(sample.value/ceiling, 0.0, 1.0)*42); + const QColor color = sample.value <= green ? QColor(56,184,117,110) : + sample.value >= red ? QColor(230,87,102,110) : QColor(219,161,56,110); + painter.setPen(QPen(color, 2)); + if (connected && sample.time-previous_time < 0.6) painter.drawLine(previous, point); + else painter.drawPoint(point); + if (sample.value > ceiling) painter.drawLine(QPointF(point.x(), 1), QPointF(point.x(), 5)); + previous = point; + previous_time = sample.time; + connected = true; + } + painter.end(); + upload(image); + } +private: + void upload(QImage& image) { + Ogre::PixelBox pixels(width, height, 1, Ogre::PF_BYTE_RGBA, image.bits()); + texture_->getBuffer()->blitFromMemory(pixels); + } + static constexpr double window_seconds = 5.0; + static constexpr int width = 150, height = 46; + struct Sample { double time, value; bool valid; }; + std::string name_; + Ogre::OverlayContainer* parent_; + Ogre::OverlayContainer* panel_{}; + Ogre::TexturePtr texture_; + Ogre::MaterialPtr material_; + std::deque samples_; + std::chrono::steady_clock::time_point last_{}; +}; +} diff --git a/command/arms_rviz_control_plugin/include/arms_rviz_control_plugin/joint_control_panel.hpp b/command/arms_rviz_control_plugin/include/arms_rviz_control_plugin/joint_control_panel.hpp index f021f328..ebdd7800 100644 --- a/command/arms_rviz_control_plugin/include/arms_rviz_control_plugin/joint_control_panel.hpp +++ b/command/arms_rviz_control_plugin/include/arms_rviz_control_plugin/joint_control_panel.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include #include @@ -212,6 +213,7 @@ namespace arms_rviz_control_plugin bool right_current_pose_valid_ = false; bool body_current_pose_valid_ = false; uint8_t wbc_body_state_ = 0; // WbcCurrentState::body_state + uint8_t wbc_head_state_ = 0; // WbcCurrentState::head_state(1 = HEAD_TRACKING) // Joint limits manager std::shared_ptr joint_limits_manager_; diff --git a/command/arms_rviz_control_plugin/include/arms_rviz_control_plugin/target_error_display.hpp b/command/arms_rviz_control_plugin/include/arms_rviz_control_plugin/target_error_display.hpp new file mode 100644 index 00000000..fba0c64e --- /dev/null +++ b/command/arms_rviz_control_plugin/include/arms_rviz_control_plugin/target_error_display.hpp @@ -0,0 +1,49 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "arms_rviz_control_plugin/error_dashboard.hpp" + +namespace arms_rviz_control_plugin { +class TargetErrorDisplay : public rviz_common::Display { + Q_OBJECT +public: + TargetErrorDisplay() = default; + ~TargetErrorDisplay() override; + void update(float wall_dt, float ros_dt) override; + void reset() override; + void load(const rviz_common::Config& config) override; + void save(rviz_common::Config config) const override; +protected: + void onInitialize() override; + void onEnable() override; + void onDisable() override; +private: + struct Sample { + geometry_msgs::msg::PoseStamped pose{}; + std::chrono::steady_clock::time_point received{}; + bool valid{false}; + }; + struct Data { + std::mutex mutex; + std::array, 4> samples{}; + std::array active{}; + bool ocs2_active{false}; + uint64_t fsm_generation{0}; + }; + std::shared_ptr data_{std::make_shared()}; + std::array::SharedPtr, 8> subscriptions_; + rclcpp::Subscription::SharedPtr mode_subscription_; + rclcpp::Subscription::SharedPtr fsm_subscription_; + std::unique_ptr dashboard_; + uint64_t fsm_generation_{0}; + std::array thresholds_{5, 20, 1, 5}; + float elapsed_{0}; +}; +} diff --git a/command/arms_rviz_control_plugin/package.xml b/command/arms_rviz_control_plugin/package.xml index 61817656..e3b072a7 100644 --- a/command/arms_rviz_control_plugin/package.xml +++ b/command/arms_rviz_control_plugin/package.xml @@ -10,6 +10,8 @@ rclcpp rviz_common + rviz_ogre_vendor + rviz_rendering arms_controller_common arms_ros2_control_msgs sensor_msgs diff --git a/command/arms_rviz_control_plugin/plugin_description.xml b/command/arms_rviz_control_plugin/plugin_description.xml index f0fb0255..00cb7c90 100644 --- a/command/arms_rviz_control_plugin/plugin_description.xml +++ b/command/arms_rviz_control_plugin/plugin_description.xml @@ -23,4 +23,9 @@ base_class_type="rviz_common::Panel"> WBC capability status panel + + Tracking error dashboard over the RViz 3D viewport. + diff --git a/command/arms_rviz_control_plugin/src/joint_control_panel.cpp b/command/arms_rviz_control_plugin/src/joint_control_panel.cpp index 16aa4431..0198b01d 100644 --- a/command/arms_rviz_control_plugin/src/joint_control_panel.cpp +++ b/command/arms_rviz_control_plugin/src/joint_control_panel.cpp @@ -11,12 +11,17 @@ #include #include #include +#include +#include +#include +#include #include #include #include namespace { + // ABB OrientZYX(z, y, x) ≡ tf2 setRPY(roll=x, pitch=y, yaw=z) ≡ Rz * Ry * Rx geometry_msgs::msg::Quaternion orientZyx(double roll, double pitch, double yaw) { @@ -729,6 +734,7 @@ namespace arms_rviz_control_plugin { return; } + wbc_head_state_ = msg->head_state; const uint8_t prev = wbc_body_state_; wbc_body_state_ = msg->body_state; if (prev != wbc_body_state_ && is_joint_control_enabled_) @@ -2983,7 +2989,6 @@ namespace arms_rviz_control_plugin void JointControlPanel::load(const rviz_common::Config& config) { Panel::load(config); - QString unit; if (config.mapGetString("DisplayUnit", &unit) && display_unit_combo_) { diff --git a/command/arms_rviz_control_plugin/src/target_error_display.cpp b/command/arms_rviz_control_plugin/src/target_error_display.cpp new file mode 100644 index 00000000..0610c322 --- /dev/null +++ b/command/arms_rviz_control_plugin/src/target_error_display.cpp @@ -0,0 +1,159 @@ +#include "arms_rviz_control_plugin/target_error_display.hpp" +#include +#include +#include +#include +#include + +namespace arms_rviz_control_plugin { +TargetErrorDisplay::~TargetErrorDisplay() { + fsm_subscription_.reset(); + mode_subscription_.reset(); + for (auto& subscription : subscriptions_) subscription.reset(); + dashboard_.reset(); +} +void TargetErrorDisplay::onInitialize() { + rviz_rendering::RenderSystem::get()->prepareOverlays(scene_manager_); + auto node = context_->getRosNodeAbstraction().lock()->get_raw_node(); + fsm_subscription_ = node->create_subscription( + "/fsm_state", rclcpp::QoS(1).transient_local(), + [data = data_](std_msgs::msg::Int32::ConstSharedPtr message) { + std::lock_guard lock(data->mutex); + // Actual controller state: HOME=1, HOLD=2, OCS2=3, MOVEJ=4. + const bool active = message->data == 3; + if (active != data->ocs2_active) { + data->ocs2_active = active; + ++data->fsm_generation; + // Keep cached targets, which may only be published on change. + for (auto& row : data->samples) row[0].valid = false; + } + }); + const char* topics[4][2] = { + {"left_current_pose", "left_current_target"}, + {"right_current_pose", "right_current_target"}, + {"body_current_pose", "body_current_target"}, + {"head_current_pose", "head_current_target"}}; + for (size_t row = 0; row < 4; ++row) { + for (size_t side = 0; side < 2; ++side) { + subscriptions_[row*2+side] = node->create_subscription( + topics[row][side], rclcpp::SensorDataQoS().keep_last(1), + [data = data_, row, side](geometry_msgs::msg::PoseStamped::ConstSharedPtr message) { + std::lock_guard lock(data->mutex); + if (side == 0 && !data->ocs2_active) return; + Sample sample{*message, std::chrono::steady_clock::now(), true}; + data->samples[row][side] = std::move(sample); + }); + } + } + mode_subscription_ = node->create_subscription( + "/ocs2_wbc_controller/current_state", rclcpp::QoS(1).transient_local(), + [data = data_](arms_ros2_control_msgs::msg::WbcCurrentState::ConstSharedPtr message) { + std::lock_guard lock(data->mutex); + using State = arms_ros2_control_msgs::msg::WbcCurrentState; + data->active = {message->left_arm_state == State::ARM_ENABLED, + message->right_arm_state == State::ARM_ENABLED, + message->body_state == State::BODY_TRACKING && message->head_state != State::HEAD_FORWARD, + message->head_state == State::HEAD_TRACKING}; + }); +} +void TargetErrorDisplay::onEnable() { elapsed_ = 1; } +void TargetErrorDisplay::onDisable() { if (dashboard_) dashboard_->hide(); } +void TargetErrorDisplay::reset() { + Display::reset(); + if (dashboard_) dashboard_->clearHistory(); + std::lock_guard lock(data_->mutex); + data_->samples = {}; + elapsed_ = 1; +} +void TargetErrorDisplay::update(float wall_dt, float) { + if (!isEnabled()) return; + bool ocs2_active; + uint64_t generation; + { + std::lock_guard lock(data_->mutex); + ocs2_active = data_->ocs2_active; + generation = data_->fsm_generation; + } + if (generation != fsm_generation_) { + if (dashboard_) dashboard_->clearHistory(); + fsm_generation_ = generation; + elapsed_ = 1; + } + if (!ocs2_active) { + if (dashboard_) dashboard_->hide(); + return; + } + if (!dashboard_) { + dashboard_ = std::make_unique(); + dashboard_->show(); + elapsed_ = 0; + return; // Allow the initial text geometry to render before the layout refresh. + } + dashboard_->show(); + elapsed_ += wall_dt; + if (elapsed_ < 0.1f) return; + elapsed_ = 0; + dashboard_->refreshLayout(); + std::array, 4> samples; + std::array active; + { + std::lock_guard lock(data_->mutex); + if (!data_->ocs2_active || data_->fsm_generation != generation) { + dashboard_->hide(); + return; + } + samples = data_->samples; + active = data_->active; + } + dashboard_->setActive(active); + const auto now = std::chrono::steady_clock::now(); + for (size_t row = 0; row < 4; ++row) { + if (!active[row]) continue; + const auto& measured = samples[row][0]; + const auto& target = samples[row][1]; + bool valid = false; + double mm = 0, degrees = 0; + QString status; + if (!measured.valid || !target.valid) status = "等待当前 / 目标位姿"; + else if (now-measured.received > std::chrono::seconds(1)) status = "当前位姿已超时"; + else if (measured.pose.header.frame_id.empty() || + measured.pose.header.frame_id != target.pose.header.frame_id) + status = "参考坐标系不一致"; + else { + const auto& a = measured.pose.pose; + const auto& b = target.pose.pose; + mm = 1000*std::hypot(b.position.x-a.position.x, + std::hypot(b.position.y-a.position.y, b.position.z-a.position.z)); + tf2::Quaternion qa(a.orientation.x,a.orientation.y,a.orientation.z,a.orientation.w); + tf2::Quaternion qb(b.orientation.x,b.orientation.y,b.orientation.z,b.orientation.w); + if (!std::isfinite(mm) || !std::isfinite(qa.length2()) || !std::isfinite(qb.length2()) || + qa.length2() < 1e-18 || qb.length2() < 1e-18) status = "位姿数据无效"; + else { + qa.normalize(); qb.normalize(); + degrees = 2*std::acos(std::clamp(std::abs(qa.dot(qb)),0.0,1.0))*180/std::acos(-1.0); + valid = true; + status = "数据有效"; + } + } + dashboard_->setRow(row, mm, degrees, valid, status, thresholds_); + } +} +void TargetErrorDisplay::load(const rviz_common::Config& config) { + Display::load(config); + const char* keys[] = {"ErrorPositionGreenMm", "ErrorPositionRedMm", + "ErrorOrientationGreenDeg", "ErrorOrientationRedDeg"}; + for (size_t i = 0; i < 4; i += 2) { + float green, red; + if (config.mapGetFloat(keys[i], &green) && config.mapGetFloat(keys[i+1], &red) && + std::isfinite(green) && std::isfinite(red) && green > 0 && red > green) + { thresholds_[i] = green; thresholds_[i+1] = red; } + } +} +void TargetErrorDisplay::save(rviz_common::Config config) const { + Display::save(config); + const char* keys[] = {"ErrorPositionGreenMm", "ErrorPositionRedMm", + "ErrorOrientationGreenDeg", "ErrorOrientationRedDeg"}; + for (size_t i = 0; i < 4; ++i) config.mapSetValue(keys[i], thresholds_[i]); +} +} +PLUGINLIB_EXPORT_CLASS(arms_rviz_control_plugin::TargetErrorDisplay, rviz_common::Display)