上传文件至 src
This commit is contained in:
parent
6c3477a873
commit
141d1b98d9
599
src/tcpcalibrationwidget.cpp
Normal file
599
src/tcpcalibrationwidget.cpp
Normal file
@ -0,0 +1,599 @@
|
||||
#include "tcpcalibrationwidget.h"
|
||||
|
||||
#include <QCheckBox>
|
||||
#include <QComboBox>
|
||||
#include <QDoubleSpinBox>
|
||||
#include <QFrame>
|
||||
#include <QGridLayout>
|
||||
#include <QHeaderView>
|
||||
#include <QLabel>
|
||||
#include <QLineEdit>
|
||||
#include <QMessageBox>
|
||||
#include <QPushButton>
|
||||
#include <QScrollArea>
|
||||
#include <QSettings>
|
||||
#include <QSignalBlocker>
|
||||
#include <QTableWidget>
|
||||
#include <QTimer>
|
||||
#include <QVBoxLayout>
|
||||
#include <QtMath>
|
||||
#include <cmath>
|
||||
|
||||
namespace {
|
||||
QVBoxLayout *panel(QBoxLayout *parent, const QString &title)
|
||||
{
|
||||
auto *frame = new QFrame;
|
||||
frame->setObjectName(QStringLiteral("panel"));
|
||||
auto *layout = new QVBoxLayout(frame);
|
||||
layout->setContentsMargins(14, 12, 14, 12);
|
||||
layout->setSpacing(8);
|
||||
auto *label = new QLabel(title);
|
||||
label->setObjectName(QStringLiteral("sectionTitle"));
|
||||
layout->addWidget(label);
|
||||
parent->addWidget(frame);
|
||||
return layout;
|
||||
}
|
||||
QLabel *hint(const QString &text)
|
||||
{
|
||||
auto *label = new QLabel(text);
|
||||
label->setObjectName(QStringLiteral("mutedLabel"));
|
||||
label->setWordWrap(true);
|
||||
return label;
|
||||
}
|
||||
const char *keys[] = {"x", "y", "z", "rx", "ry", "rz"};
|
||||
QString axis(int i) { return QString::fromLatin1(keys[i]).toUpper(); }
|
||||
double fromDisplay(double value, int axisIndex)
|
||||
{
|
||||
return axisIndex < 3 ? value / 1000.0 : qDegreesToRadians(value);
|
||||
}
|
||||
double toDisplay(double value, int axisIndex)
|
||||
{
|
||||
return axisIndex < 3 ? value * 1000.0 : qRadiansToDegrees(value);
|
||||
}
|
||||
}
|
||||
|
||||
TcpCalibrationWidget::TcpCalibrationWidget(QWidget *parent) : QWidget(parent)
|
||||
{
|
||||
setObjectName(QStringLiteral("tcpCalibrationPage"));
|
||||
buildUi();
|
||||
m_captureTimer = new QTimer(this);
|
||||
m_captureTimer->setSingleShot(true);
|
||||
m_captureTimer->setInterval(6000);
|
||||
connect(m_captureTimer, &QTimer::timeout, this, [this] {
|
||||
if (m_pendingRow < 0) return;
|
||||
++m_serial;
|
||||
m_pendingRow = -1;
|
||||
refresh();
|
||||
reportError(QStringLiteral("读取实时位姿超时,请检查机械臂连接后重试"));
|
||||
});
|
||||
resizeSamples(4);
|
||||
}
|
||||
|
||||
void TcpCalibrationWidget::buildUi()
|
||||
{
|
||||
auto *outer = new QVBoxLayout(this);
|
||||
outer->setContentsMargins(12, 10, 12, 10);
|
||||
auto *scroll = new QScrollArea(this);
|
||||
scroll->setWidgetResizable(true);
|
||||
scroll->setFrameShape(QFrame::NoFrame);
|
||||
auto *content = new QWidget;
|
||||
auto *layout = new QVBoxLayout(content);
|
||||
layout->setContentsMargins(0, 0, 0, 0);
|
||||
layout->setSpacing(10);
|
||||
scroll->setWidget(content);
|
||||
outer->addWidget(scroll);
|
||||
|
||||
auto *configuration = new QHBoxLayout;
|
||||
configuration->setSpacing(10);
|
||||
layout->addLayout(configuration);
|
||||
auto *toolPanel = panel(configuration, QStringLiteral("工具信息"));
|
||||
auto *toolGrid = new QGridLayout;
|
||||
toolGrid->setHorizontalSpacing(12);
|
||||
m_toolCombo = new QComboBox;
|
||||
m_toolCombo->setObjectName(QStringLiteral("tcpLocalTools"));
|
||||
m_toolCombo->addItem(QStringLiteral("新建工具"));
|
||||
m_name = new QLineEdit;
|
||||
m_name->setObjectName(QStringLiteral("tcpToolName"));
|
||||
m_name->setMaxLength(80);
|
||||
m_name->setPlaceholderText(QStringLiteral("输入工具名称"));
|
||||
m_name->setToolTip(QStringLiteral("保存至当前机械臂,并同步至工具坐标列表。"));
|
||||
m_reload = new QPushButton(QStringLiteral("刷新"));
|
||||
m_delete = new QPushButton(QStringLiteral("删除"));
|
||||
m_delete->setObjectName(QStringLiteral("tcpDelete"));
|
||||
toolGrid->addWidget(new QLabel(QStringLiteral("工具")), 0, 0);
|
||||
toolGrid->addWidget(m_toolCombo, 0, 1);
|
||||
toolGrid->addWidget(new QLabel(QStringLiteral("名称")), 1, 0);
|
||||
toolGrid->addWidget(m_name, 1, 1, 1, 3);
|
||||
toolGrid->addWidget(m_reload, 0, 2);
|
||||
toolGrid->addWidget(m_delete, 0, 3);
|
||||
toolGrid->setColumnStretch(1, 1);
|
||||
toolPanel->addLayout(toolGrid);
|
||||
m_currentTool = hint(QStringLiteral("正在标定:新工具"));
|
||||
toolPanel->addWidget(m_currentTool);
|
||||
toolPanel->addStretch();
|
||||
auto *sourcePanel = panel(configuration, QStringLiteral("控制器 TCP 偏移"));
|
||||
sourcePanel->parentWidget()->setToolTip(QStringLiteral("与示教器当前活动 TCP 一致,用于还原法兰位姿。仅零偏移工具可填全零;采样期间不得切换。"));
|
||||
configuration->setStretch(0,1); configuration->setStretch(1,1);
|
||||
auto *sourceGrid = new QGridLayout;
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
auto *spin = new QDoubleSpinBox;
|
||||
spin->setObjectName(QStringLiteral("tcpSource%1").arg(i));
|
||||
spin->setRange(i < 3 ? -10000 : -360, i < 3 ? 10000 : 360);
|
||||
spin->setDecimals(4);
|
||||
spin->setSuffix(i < 3 ? QStringLiteral(" mm") : QStringLiteral(" °"));
|
||||
m_source.append(spin);
|
||||
sourceGrid->addWidget(new QLabel(axis(i)), i/3, (i%3)*2);
|
||||
sourceGrid->addWidget(spin, i/3, (i%3)*2+1);
|
||||
sourceGrid->setColumnStretch((i%3)*2+1,1);
|
||||
connect(spin, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this,
|
||||
[this](double) { updateSource(); });
|
||||
}
|
||||
sourcePanel->addLayout(sourceGrid);
|
||||
m_sourceConfirmed = new QCheckBox(QStringLiteral(
|
||||
"已确认控制器 TCP 偏移"));
|
||||
m_sourceConfirmed->setToolTip(QStringLiteral("RX/RY/RZ 为 ZYX 欧拉角,非旋转向量。偏移必须与控制器当前活动工具一致。"));
|
||||
m_sourceConfirmed->setObjectName(QStringLiteral("tcpSourceConfirmed"));
|
||||
sourcePanel->addWidget(m_sourceConfirmed);
|
||||
connect(m_sourceConfirmed, &QCheckBox::toggled, this, [this](bool) {
|
||||
resetCalibration();
|
||||
refresh();
|
||||
emit referenceChanged();
|
||||
});
|
||||
|
||||
auto *pointsPanel = panel(layout, QStringLiteral("TCP 采样"));
|
||||
m_instructions = hint(QString());
|
||||
pointsPanel->addWidget(m_instructions);
|
||||
auto *pointActions = new QHBoxLayout;
|
||||
m_method = new QComboBox;
|
||||
m_method->setObjectName(QStringLiteral("tcpCalibrationMethod"));
|
||||
m_method->addItem(QStringLiteral("四点法"),QStringLiteral("four_point"));
|
||||
m_method->addItem(QStringLiteral("六点法 · XZ"),QStringLiteral("six_point_xz"));
|
||||
m_method->addItem(QStringLiteral("六点法 · XY"),QStringLiteral("six_point_xy"));
|
||||
pointActions->addWidget(new QLabel(QStringLiteral("标定方式")));
|
||||
pointActions->addWidget(m_method);
|
||||
pointActions->addStretch();
|
||||
auto *restart = new QPushButton(QStringLiteral("重新标定"));
|
||||
restart->setObjectName(QStringLiteral("tcpClear"));
|
||||
pointActions->addWidget(restart);
|
||||
pointsPanel->addLayout(pointActions);
|
||||
m_table = new QTableWidget(0, 10);
|
||||
m_table->setObjectName(QStringLiteral("tcpSamples"));
|
||||
m_table->setHorizontalHeaderLabels({QStringLiteral("点位"), QStringLiteral("状态"),
|
||||
QStringLiteral("X mm"), QStringLiteral("Y mm"), QStringLiteral("Z mm"),
|
||||
QStringLiteral("RX °"), QStringLiteral("RY °"), QStringLiteral("RZ °"),
|
||||
QStringLiteral("残差 mm"), QStringLiteral("操作")});
|
||||
m_table->setEditTriggers(QAbstractItemView::NoEditTriggers);
|
||||
m_table->setSelectionMode(QAbstractItemView::NoSelection);
|
||||
m_table->setAlternatingRowColors(true);
|
||||
m_table->verticalHeader()->hide();
|
||||
m_table->verticalHeader()->setDefaultSectionSize(36);
|
||||
m_table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
|
||||
m_table->setMinimumHeight(180);
|
||||
pointsPanel->addWidget(m_table);
|
||||
connect(m_method, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this] {
|
||||
resizeSamples(m_method->currentIndex()==0 ? 4 : 6);
|
||||
for (auto *spin : m_orientation) spin->setValue(0);
|
||||
});
|
||||
connect(restart, &QPushButton::clicked, this, &TcpCalibrationWidget::resetCalibration);
|
||||
|
||||
auto *resultPanel = panel(layout, QStringLiteral("TCP 参数(相对法兰)"));
|
||||
auto *resultGrid = new QGridLayout;
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
auto *axisLabel = new QLabel(axis(i) + (i < 3 ? QStringLiteral(" mm") : QStringLiteral(" °(手动)")));
|
||||
resultGrid->addWidget(axisLabel, 0, i);
|
||||
if (i>=3) m_orientationLabels.append(axisLabel);
|
||||
if (i < 3) {
|
||||
auto *value = new QLabel(QStringLiteral("--"));
|
||||
value->setObjectName(QStringLiteral("tcpResult%1").arg(i));
|
||||
value->setTextInteractionFlags(Qt::TextSelectableByMouse);
|
||||
m_results.append(value);
|
||||
resultGrid->addWidget(value, 1, i);
|
||||
} else {
|
||||
auto *spin = new QDoubleSpinBox;
|
||||
spin->setObjectName(QStringLiteral("tcpOrientation%1").arg(i));
|
||||
spin->setRange(-360, 360);
|
||||
spin->setDecimals(4);
|
||||
spin->setSuffix(QStringLiteral(" °"));
|
||||
m_orientation.append(spin);
|
||||
resultGrid->addWidget(spin, 1, i);
|
||||
connect(spin, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this,
|
||||
[this](double) { refresh(); });
|
||||
}
|
||||
}
|
||||
resultPanel->addLayout(resultGrid);
|
||||
for (auto *spin : m_orientation) spin->setToolTip(QStringLiteral("固定点法仅求解平移;工具姿态需手动设置,采用 ZYX 欧拉角。"));
|
||||
m_rms = new QLabel(QStringLiteral("固定点 RMS:--(合格上限 2.000 mm)"));
|
||||
m_rms->setObjectName(QStringLiteral("tcpRms"));
|
||||
resultPanel->addWidget(m_rms);
|
||||
m_preview = hint(QStringLiteral("基座下工具位姿:--"));
|
||||
m_preview->setObjectName(QStringLiteral("tcpToolPreview"));
|
||||
resultPanel->addWidget(m_preview);
|
||||
auto *actions = new QHBoxLayout;
|
||||
m_status = hint(QStringLiteral("等待采样"));
|
||||
m_status->setObjectName(QStringLiteral("tcpStatus"));
|
||||
actions->addWidget(m_status, 1);
|
||||
m_calculate = new QPushButton(QStringLiteral("TCP 标定"));
|
||||
m_calculate->setObjectName(QStringLiteral("primaryButton"));
|
||||
m_calculate->setProperty("tcpAction", QStringLiteral("calculate"));
|
||||
m_save = new QPushButton(QStringLiteral("保存工具"));
|
||||
m_save->setObjectName(QStringLiteral("tcpSave"));
|
||||
actions->addWidget(m_calculate);
|
||||
actions->addWidget(m_save);
|
||||
outer->addLayout(actions);
|
||||
layout->addStretch();
|
||||
connect(m_calculate, &QPushButton::clicked, this, &TcpCalibrationWidget::calculate);
|
||||
connect(m_save, &QPushButton::clicked, this, &TcpCalibrationWidget::saveTool);
|
||||
connect(m_name, &QLineEdit::textChanged, this, [this](const QString &) { refresh(); });
|
||||
connect(m_toolCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &TcpCalibrationWidget::selectTool);
|
||||
connect(m_reload, &QPushButton::clicked, this, [this] { reloadTools(); });
|
||||
connect(m_delete, &QPushButton::clicked, this, &TcpCalibrationWidget::deleteTool);
|
||||
}
|
||||
|
||||
void TcpCalibrationWidget::setContext(const QString &endpoint, const QString &deviceId,
|
||||
bool connected, bool demoMode)
|
||||
{
|
||||
const bool identityChanged = endpoint != m_endpoint || deviceId != m_device;
|
||||
const bool sessionChanged = connected != m_connected || demoMode != m_demo;
|
||||
m_endpoint = endpoint;
|
||||
m_device = deviceId;
|
||||
m_connected = connected;
|
||||
m_demo = demoMode;
|
||||
if (identityChanged || sessionChanged) {
|
||||
const QSignalBlocker blocker(m_sourceConfirmed);
|
||||
m_sourceConfirmed->setChecked(false);
|
||||
resetCalibration();
|
||||
if (identityChanged) {
|
||||
m_loading = true;
|
||||
for (auto *spin : m_source) spin->setValue(0);
|
||||
m_loading = false;
|
||||
}
|
||||
reloadTools();
|
||||
}
|
||||
refresh();
|
||||
emit referenceChanged();
|
||||
}
|
||||
|
||||
bool TcpCalibrationWidget::referenceConfirmed() const
|
||||
{
|
||||
return m_connected && !m_demo && !m_device.trimmed().isEmpty() && m_sourceConfirmed->isChecked();
|
||||
}
|
||||
|
||||
void TcpCalibrationWidget::invalidateReference()
|
||||
{
|
||||
const QSignalBlocker blocker(m_sourceConfirmed);
|
||||
m_sourceConfirmed->setChecked(false);
|
||||
resetCalibration();
|
||||
emit referenceChanged();
|
||||
}
|
||||
|
||||
bool TcpCalibrationWidget::hasSamples() const
|
||||
{
|
||||
for (const auto &sample : m_samples) if (sample.captured) return true;
|
||||
return false;
|
||||
}
|
||||
void TcpCalibrationWidget::invalidateResult()
|
||||
{
|
||||
m_resultValid = false;
|
||||
m_loadedResult = false;
|
||||
m_result = TcpCalibration::Result{};
|
||||
for (auto *label : m_results) label->setText(QStringLiteral("--"));
|
||||
m_rms->setText(QStringLiteral("固定点 RMS:--(合格上限 2.000 mm)"));
|
||||
m_preview->setText(QStringLiteral("基座下工具位姿:--"));
|
||||
}
|
||||
void TcpCalibrationWidget::resetCalibration()
|
||||
{
|
||||
++m_serial;
|
||||
m_pendingRow = -1;
|
||||
if (m_captureTimer) m_captureTimer->stop();
|
||||
for (auto &sample : m_samples) sample = Sample{};
|
||||
invalidateResult();
|
||||
refresh();
|
||||
emit logMessage(QStringLiteral("INFO"), QStringLiteral("TCP 标定临时采样已重置,已保存工具保持不变"));
|
||||
}
|
||||
void TcpCalibrationWidget::resizeSamples(int count)
|
||||
{
|
||||
++m_serial;
|
||||
m_pendingRow = -1;
|
||||
if (m_captureTimer) m_captureTimer->stop();
|
||||
m_samples.assign(size_t(count),Sample{});
|
||||
invalidateResult();
|
||||
m_table->setRowCount(count);
|
||||
m_table->setMinimumHeight(count*36+40);
|
||||
for (int row = 0; row < count; ++row) {
|
||||
for (int col = 0; col < 9; ++col)
|
||||
if (!m_table->item(row, col)) m_table->setItem(row, col, new QTableWidgetItem);
|
||||
if (!m_table->cellWidget(row, 9)) {
|
||||
auto *button = new QPushButton(QStringLiteral("采集"));
|
||||
button->setObjectName(QStringLiteral("tcpCapture%1").arg(row));
|
||||
m_table->setCellWidget(row, 9, button);
|
||||
connect(button, &QPushButton::clicked, this, [this, row] { capture(row); });
|
||||
}
|
||||
}
|
||||
refresh();
|
||||
}
|
||||
TcpCalibration::Pose TcpCalibrationWidget::serverOffset() const
|
||||
{
|
||||
TcpCalibration::Pose pose{};
|
||||
for (int i = 0; i < 6; ++i) pose[size_t(i)] = fromDisplay(m_source.at(i)->value(), i);
|
||||
return pose;
|
||||
}
|
||||
void TcpCalibrationWidget::updateSource()
|
||||
{
|
||||
if (m_loading) return;
|
||||
const QSignalBlocker blocker(m_sourceConfirmed);
|
||||
m_sourceConfirmed->setChecked(false);
|
||||
resetCalibration();
|
||||
emit referenceChanged();
|
||||
}
|
||||
void TcpCalibrationWidget::refresh()
|
||||
{
|
||||
if (!m_table) return;
|
||||
int captured = 0;
|
||||
const bool busy = m_pendingRow >= 0;
|
||||
const bool six = m_method->currentIndex()>0;
|
||||
const bool xz = m_method->currentData().toString()=="six_point_xz";
|
||||
m_instructions->setText(six
|
||||
? QStringLiteral("1–3:固定尖端位置并改变姿态;4:方向原点;5:+X;6:+%1。后三点保持相同姿态。").arg(xz?"Z":"Y")
|
||||
: QStringLiteral("保持尖端位置不变,以四个不同姿态采样;工具方向手动设置。"));
|
||||
m_instructions->setToolTip(six ? QStringLiteral("方向点从原点沿所需工具正轴平移,返回原点姿态后采下一轴。程序不会自动移动机器人。最小方向基线 10 mm;建议在安全行程内增加基线。") : QString());
|
||||
const bool ready = m_connected && !m_demo && !m_device.trimmed().isEmpty()
|
||||
&& m_sourceConfirmed->isChecked() && !busy;
|
||||
for (int row = 0; row < int(m_samples.size()); ++row) {
|
||||
const auto &sample = m_samples[size_t(row)];
|
||||
captured += sample.captured;
|
||||
const QString purpose=!six ? QStringLiteral("固定点") : row<3 ? QStringLiteral("接近点")
|
||||
: row==3 ? QStringLiteral("方向原点") : row==4 ? QStringLiteral("+X") : xz?QStringLiteral("+Z"):QStringLiteral("+Y");
|
||||
m_table->item(row, 0)->setText(QStringLiteral("%1 · %2").arg(row+1).arg(purpose));
|
||||
m_table->item(row, 1)->setText(row == m_pendingRow ? QStringLiteral("读取中")
|
||||
: sample.captured ? QStringLiteral("已采集") : QStringLiteral("未采集"));
|
||||
for (int i = 0; i < 6; ++i) m_table->item(row, 2 + i)->setText(sample.captured
|
||||
? QString::number(toDisplay(sample.flange[size_t(i)], i), 'f', 3) : QStringLiteral("--"));
|
||||
m_table->item(row, 8)->setText(m_resultValid && !m_loadedResult
|
||||
&& row < int(m_result.residualsMm.size())
|
||||
? QString::number(m_result.residualsMm[size_t(row)], 'f', 3) : QStringLiteral("--"));
|
||||
auto *button = qobject_cast<QPushButton *>(m_table->cellWidget(row, 9));
|
||||
button->setText(sample.captured ? QStringLiteral("重新采集") : QStringLiteral("采集"));
|
||||
button->setEnabled(ready);
|
||||
}
|
||||
m_method->setEnabled(!busy);
|
||||
for (int i=0;i<m_orientation.size();++i) {
|
||||
m_orientation[i]->setReadOnly(six); m_orientation[i]->setButtonSymbols(six?QAbstractSpinBox::NoButtons:QAbstractSpinBox::UpDownArrows);
|
||||
m_orientationLabels[i]->setText(axis(i+3)+(six?QStringLiteral(" °(计算)"):QStringLiteral(" °(手动)")));
|
||||
m_orientation[i]->setToolTip(six?QStringLiteral("由方向原点、+X 与第二方向点计算,ZYX 欧拉角。"):QStringLiteral("四点法仅求平移;工具方向手动设置,ZYX 欧拉角。"));
|
||||
}
|
||||
m_toolCombo->setEnabled(!busy);
|
||||
m_name->setEnabled(!busy);
|
||||
m_reload->setEnabled(!busy && !m_device.isEmpty());
|
||||
m_delete->setEnabled(!busy && m_toolCombo->currentIndex() > 0);
|
||||
for (auto *spin : m_source) spin->setEnabled(!busy);
|
||||
m_sourceConfirmed->setEnabled(!busy && m_connected && !m_demo);
|
||||
m_calculate->setEnabled(!busy && captured >= 4 && captured == int(m_samples.size()));
|
||||
m_save->setEnabled(!busy && m_resultValid && m_result.rmsMm <= 2.0
|
||||
&& !m_name->text().trimmed().isEmpty());
|
||||
m_status->setText(busy ? QStringLiteral("正在读取真实位姿…") : m_resultValid
|
||||
? (m_result.rmsMm > 2.0 ? QStringLiteral("误差超限,禁止保存,请重新采样")
|
||||
: m_loadedResult ? (six ? QStringLiteral("已加载六点标定结果") : QStringLiteral("已加载标定结果,可修改名称或手动方向"))
|
||||
: QStringLiteral("已计算,尚未保存"))
|
||||
: QStringLiteral("已采集 %1 / %2 点%3").arg(captured).arg(m_samples.size())
|
||||
.arg(!m_sourceConfirmed->isChecked() ? QStringLiteral(" · 请先核对活动 TCP 偏移") : QString()));
|
||||
}
|
||||
|
||||
void TcpCalibrationWidget::capture(int index)
|
||||
{
|
||||
if (index < 0 || index >= int(m_samples.size()) || m_pendingRow >= 0) return;
|
||||
if (!m_connected || m_demo || !m_sourceConfirmed->isChecked() || m_device.isEmpty()) {
|
||||
reportError(QStringLiteral("请连接真实机械臂并核对服务端活动 TCP 偏移"));
|
||||
return;
|
||||
}
|
||||
invalidateResult();
|
||||
// A failed replacement must not silently reuse the previous observation.
|
||||
m_samples[size_t(index)] = Sample{};
|
||||
m_pendingRow = index;
|
||||
++m_serial;
|
||||
m_captureTimer->start();
|
||||
refresh();
|
||||
emit captureRequested(m_device, m_serial);
|
||||
}
|
||||
bool TcpCalibrationWidget::readPose(const QVariantMap &map, TcpCalibration::Pose &pose) const
|
||||
{
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
const QString name = QString::fromLatin1(keys[i]);
|
||||
bool ok = false;
|
||||
pose[size_t(i)] = map.value(name).toDouble(&ok);
|
||||
if (!map.contains(name) || !ok || !std::isfinite(pose[size_t(i)])) return false;
|
||||
}
|
||||
return TcpCalibration::validPose(pose);
|
||||
}
|
||||
void TcpCalibrationWidget::acceptPose(quint64 requestId, const QString &deviceId,
|
||||
const QVariantMap &pose, const QVariantMap &state,
|
||||
bool success, const QString &detail)
|
||||
{
|
||||
if (requestId != m_serial || deviceId != m_device || m_pendingRow < 0) return;
|
||||
const int row = m_pendingRow;
|
||||
m_pendingRow = -1;
|
||||
m_captureTimer->stop();
|
||||
if (!success) { refresh(); reportError(detail); return; }
|
||||
if (!m_connected || m_demo || !m_sourceConfirmed->isChecked()
|
||||
|| !state.value(QStringLiteral("connected")).toBool()
|
||||
|| state.value(QStringLiteral("moving"), true).toBool()
|
||||
|| state.value(QStringLiteral("fault"), true).toBool()) {
|
||||
refresh(); reportError(QStringLiteral("机械臂状态不可用于采点,请停稳并重新核对")); return;
|
||||
}
|
||||
TcpCalibration::Pose tcp{}, flange{};
|
||||
QString error;
|
||||
if (!readPose(pose, tcp) || !TcpCalibration::flangePose(tcp, serverOffset(), flange, &error)) {
|
||||
refresh(); reportError(QStringLiteral("位姿数据无效:%1").arg(error)); return;
|
||||
}
|
||||
for (int i = 0; i < int(m_samples.size()); ++i) {
|
||||
// Direction origin may legitimately repeat one of the position poses.
|
||||
if (m_method->currentIndex()>0 && ((i<3)!=(row<3))) continue;
|
||||
if (i != row && m_samples[size_t(i)].captured
|
||||
&& TcpCalibration::tooSimilar(m_samples[size_t(i)].flange, flange)) {
|
||||
refresh(); reportError(QStringLiteral("与点位 %1 姿态过于接近,请改变腕部姿态后采集").arg(i + 1)); return;
|
||||
}
|
||||
}
|
||||
m_samples[size_t(row)].flange = flange;
|
||||
m_samples[size_t(row)].captured = true;
|
||||
if (m_toolCombo->currentIndex() > 0 && m_toolCombo->currentIndex() <= m_tools.tools.size()) {
|
||||
TcpCalibration::Pose preview{};
|
||||
if (TcpCalibration::toolPose(flange, m_tools.tools.at(m_toolCombo->currentIndex() - 1).offset, preview)) {
|
||||
QStringList values;
|
||||
for (int i = 0; i < 6; ++i) values << QString::number(toDisplay(preview[size_t(i)], i), 'f', 3);
|
||||
m_preview->setText(QStringLiteral("基座下工具位姿(mm / °):%1").arg(values.join(QStringLiteral(", "))));
|
||||
}
|
||||
}
|
||||
refresh();
|
||||
emit logMessage(QStringLiteral("OK"), QStringLiteral("TCP 点位 %1 已采集 · %2 · 法兰位姿 m/rad,活动 TCP 偏移已换算")
|
||||
.arg(row + 1).arg(m_device));
|
||||
}
|
||||
void TcpCalibrationWidget::calculate()
|
||||
{
|
||||
std::vector<TcpCalibration::Pose> poses;
|
||||
for (const auto &sample : m_samples) {
|
||||
if (!sample.captured) { reportError(QStringLiteral("请先完成所有点位采集")); return; }
|
||||
poses.push_back(sample.flange);
|
||||
}
|
||||
invalidateResult();
|
||||
QString error;
|
||||
const bool solved=m_method->currentIndex()==0 ? TcpCalibration::solve(poses,m_result,&error)
|
||||
: TcpCalibration::solveSixPoint(poses,m_method->currentData().toString()=="six_point_xz"
|
||||
? TcpCalibration::DirectionMethod::XZ : TcpCalibration::DirectionMethod::XY,m_result,&error);
|
||||
if (!solved) {
|
||||
refresh(); reportError(error); return;
|
||||
}
|
||||
m_resultValid = true;
|
||||
showResult(m_result.offset, m_result.rmsMm, false);
|
||||
refresh();
|
||||
emit logMessage(m_result.rmsMm <= 2.0 ? QStringLiteral("OK") : QStringLiteral("WARN"),
|
||||
QStringLiteral("TCP 计算完成,%1 点,RMS %2 mm%3").arg(poses.size())
|
||||
.arg(m_result.rmsMm, 0, 'f', 3)
|
||||
.arg(m_result.rmsMm > 2.0 ? QStringLiteral(",超过 2 mm,禁止保存") : QString()));
|
||||
}
|
||||
void TcpCalibrationWidget::showResult(const TcpCalibration::Pose &offset, double rmsMm, bool loaded)
|
||||
{
|
||||
for (int i = 0; i < 3; ++i) m_results.at(i)->setText(QString::number(offset[size_t(i)] * 1000, 'f', 3));
|
||||
if (m_method->currentIndex()>0)
|
||||
for (int i=0;i<3;++i) m_orientation[i]->setValue(qRadiansToDegrees(offset[size_t(i+3)]));
|
||||
m_rms->setText(QStringLiteral("固定点 RMS:%1 mm · %2%3").arg(rmsMm, 0, 'f', 3)
|
||||
.arg(rmsMm <= 2.0 ? QStringLiteral("合格(≤ 2.000 mm)") : QStringLiteral("超限,禁止保存"))
|
||||
.arg(loaded ? QStringLiteral(" · 已保存结果") : QString()));
|
||||
}
|
||||
void TcpCalibrationWidget::reportError(const QString &message)
|
||||
{
|
||||
emit logMessage(QStringLiteral("ERROR"), QStringLiteral("TCP 标定:%1").arg(message));
|
||||
QMessageBox::warning(this, QStringLiteral("工具坐标标定"), message);
|
||||
}
|
||||
void TcpCalibrationWidget::saveTool()
|
||||
{
|
||||
if (!m_resultValid || !std::isfinite(m_result.rmsMm) || m_result.rmsMm > 2.0) {
|
||||
reportError(QStringLiteral("请先得到 RMS 不超过 2 mm 的有效标定结果")); return;
|
||||
}
|
||||
TcpToolStore::Tool tool;
|
||||
tool.name = m_name->text().trimmed();
|
||||
tool.offset = m_result.offset;
|
||||
if (m_method->currentIndex()==0)
|
||||
for (int i = 0; i < 3; ++i) tool.offset[size_t(i + 3)] = qDegreesToRadians(m_orientation.at(i)->value());
|
||||
tool.rmsMm = m_result.rmsMm;
|
||||
tool.sampleCount = m_loadedResult ? m_loadedSampleCount : int(m_samples.size());
|
||||
tool.method = m_loadedResult ? m_loadedMethod : m_method->currentData().toString();
|
||||
bool replace = false;
|
||||
for (const auto &saved : m_tools.tools) if (saved.name == tool.name) replace = true;
|
||||
if (replace && QMessageBox::question(this, QStringLiteral("覆盖工具"),
|
||||
QStringLiteral("当前机械臂的工具“%1”已存在,是否覆盖?").arg(tool.name),
|
||||
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) return;
|
||||
QSettings settings;
|
||||
QString error;
|
||||
// TODO(controller TCP): ArmService currently has only ListTCPFrame;
|
||||
// there is no Get/Set/Create/Delete TCP-offset RPC to call or verify.
|
||||
// Keep local records distinct until actual persistent controller APIs exist.
|
||||
if (!TcpToolStore::save(settings, m_endpoint, m_device, tool, replace, error)) {
|
||||
reportError(error); return;
|
||||
}
|
||||
reloadTools(tool.name);
|
||||
emit toolsChanged(m_endpoint, m_device, tool.name);
|
||||
emit logMessage(QStringLiteral("OK"), QStringLiteral("TCP 本机工具“%1”已保存 · %2 / %3")
|
||||
.arg(tool.name, m_endpoint, m_device));
|
||||
QMessageBox::information(this, QStringLiteral("保存成功"),
|
||||
QStringLiteral("已保存到当前机器人的工具配置,并同步到机械臂的工具坐标列表。选择该工具后可进行 TCP 点动。"));
|
||||
}
|
||||
void TcpCalibrationWidget::reloadTools(const QString &preferred)
|
||||
{
|
||||
if (m_device.trimmed().isEmpty() || m_endpoint.trimmed().isEmpty()) {
|
||||
m_tools = TcpToolStore::Snapshot{};
|
||||
const QSignalBlocker blocker(m_toolCombo);
|
||||
m_toolCombo->clear();
|
||||
m_toolCombo->addItem(QStringLiteral("新建工具"));
|
||||
selectTool(0);
|
||||
m_currentTool->setText(QStringLiteral("请先选择机械臂"));
|
||||
return;
|
||||
}
|
||||
QSettings settings;
|
||||
QString error;
|
||||
TcpToolStore::Snapshot snapshot;
|
||||
if (!TcpToolStore::load(settings, m_endpoint, m_device, snapshot, error)) {
|
||||
emit logMessage(QStringLiteral("ERROR"), error);
|
||||
m_currentTool->setText(error);
|
||||
m_tools = TcpToolStore::Snapshot{};
|
||||
const QSignalBlocker blocker(m_toolCombo);
|
||||
m_toolCombo->clear(); m_toolCombo->addItem(QStringLiteral("配置读取失败"));
|
||||
resetCalibration();
|
||||
return;
|
||||
}
|
||||
m_tools = snapshot;
|
||||
const QString wanted = preferred.isEmpty() ? snapshot.current : preferred;
|
||||
int selected = 0;
|
||||
{
|
||||
const QSignalBlocker blocker(m_toolCombo);
|
||||
m_toolCombo->clear();
|
||||
m_toolCombo->addItem(QStringLiteral("新建工具"));
|
||||
for (const auto &tool : snapshot.tools) {
|
||||
m_toolCombo->addItem(tool.name);
|
||||
if (tool.name == wanted) selected = m_toolCombo->count() - 1;
|
||||
}
|
||||
m_toolCombo->setCurrentIndex(selected);
|
||||
}
|
||||
selectTool(selected);
|
||||
}
|
||||
void TcpCalibrationWidget::selectTool(int index)
|
||||
{
|
||||
resetCalibration();
|
||||
m_loading = true;
|
||||
if (index <= 0 || index > m_tools.tools.size()) {
|
||||
m_name->clear();
|
||||
for (auto *spin : m_orientation) spin->setValue(0);
|
||||
m_currentTool->setText(QStringLiteral("新工具 · 未保存"));
|
||||
} else {
|
||||
const auto &tool = m_tools.tools.at(index - 1);
|
||||
{ const QSignalBlocker blocker(m_method);
|
||||
m_method->setCurrentIndex(qMax(0,m_method->findData(tool.method))); }
|
||||
resizeSamples(m_method->currentIndex()==0 ? 4 : 6);
|
||||
m_name->setText(tool.name);
|
||||
m_result.offset = tool.offset;
|
||||
m_result.rmsMm = tool.rmsMm;
|
||||
m_loadedSampleCount = tool.sampleCount;
|
||||
m_loadedMethod = tool.method;
|
||||
m_resultValid = true;
|
||||
m_loadedResult = true;
|
||||
for (int i = 0; i < 3; ++i) m_orientation.at(i)->setValue(qRadiansToDegrees(tool.offset[size_t(i + 3)]));
|
||||
showResult(tool.offset, tool.rmsMm, true);
|
||||
m_currentTool->setText(QStringLiteral("%1 · %2 点标定").arg(tool.name).arg(tool.sampleCount));
|
||||
emit logMessage(QStringLiteral("INFO"), QStringLiteral("已加载工具标定结果:%1").arg(tool.name));
|
||||
}
|
||||
m_loading = false;
|
||||
refresh();
|
||||
}
|
||||
void TcpCalibrationWidget::deleteTool()
|
||||
{
|
||||
const int index = m_toolCombo->currentIndex() - 1;
|
||||
if (index < 0 || index >= m_tools.tools.size()) return;
|
||||
const QString name = m_tools.tools.at(index).name;
|
||||
if (QMessageBox::question(this, QStringLiteral("删除工具"),
|
||||
QStringLiteral("删除当前机械臂的工具“%1”?对应的工具坐标选项也将移除。").arg(name),
|
||||
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) return;
|
||||
QSettings settings;
|
||||
QString error;
|
||||
if (!TcpToolStore::remove(settings, m_endpoint, m_device, name, error)) { reportError(error); return; }
|
||||
reloadTools();
|
||||
emit toolsChanged(m_endpoint, m_device, QString());
|
||||
emit logMessage(QStringLiteral("INFO"), QStringLiteral("已删除本机 TCP 工具:%1").arg(name));
|
||||
}
|
||||
446
src/touchoperationwidget.cpp
Normal file
446
src/touchoperationwidget.cpp
Normal file
@ -0,0 +1,446 @@
|
||||
#include "touchoperationwidget.h"
|
||||
#include "touchvideowidget.h"
|
||||
#include <QCheckBox>
|
||||
#include <QComboBox>
|
||||
#include <QCryptographicHash>
|
||||
#include <QDateTime>
|
||||
#include <QDoubleSpinBox>
|
||||
#include <QFrame>
|
||||
#include <QGridLayout>
|
||||
#include <QHeaderView>
|
||||
#include <QHideEvent>
|
||||
#include <QJsonDocument>
|
||||
#include <QLabel>
|
||||
#include <QMessageBox>
|
||||
#include <QPushButton>
|
||||
#include <QScrollArea>
|
||||
#include <QSettings>
|
||||
#include <QSignalBlocker>
|
||||
#include <QSpinBox>
|
||||
#include <QTableWidget>
|
||||
#include <QVBoxLayout>
|
||||
#include <cmath>
|
||||
|
||||
namespace {
|
||||
using Pose=TcpCalibration::Pose;
|
||||
constexpr quint64 kPosePrefix=quint64(1)<<58;
|
||||
constexpr quint64 kImagePrefix=quint64(1)<<57;
|
||||
QVariantList values(const Pose &pose) { QVariantList result; for(double v:pose) result<<v; return result; }
|
||||
bool poseFrom(const QVariant &value,Pose &pose) {
|
||||
auto list=value.toList(); if(list.size()!=6) return false;
|
||||
for(int i=0;i<6;++i) { bool ok=false; pose[i]=list[i].toDouble(&ok); if(!ok) return false; }
|
||||
return TcpCalibration::validPose(pose);
|
||||
}
|
||||
bool decodePose(const QVariantMap &map,Pose &pose) {
|
||||
QVariantList list; for(const auto &key:QStringList{"x","y","z","rx","ry","rz"}) list<<map.value(key);
|
||||
return poseFrom(list,pose);
|
||||
}
|
||||
bool nearPose(const Pose &a,const Pose &b) {
|
||||
TcpCalibration::Matrix x{},y{};
|
||||
if(!TcpCalibration::poseMatrix(a,x)||!TcpCalibration::poseMatrix(b,y)) return false;
|
||||
double distance=0,trace=0;
|
||||
for(int i=0;i<3;++i) { distance+=std::pow(a[i]-b[i],2); for(int j=0;j<3;++j) trace+=x[i*4+j]*y[i*4+j]; }
|
||||
return distance<=.0005*.0005 && std::acos(qBound(-1.0,(trace-1)/2,1.0))<=.2*3.141592653589793/180;
|
||||
}
|
||||
QString poseText(const Pose &pose) {
|
||||
QStringList result; for(int i=0;i<6;++i) result<<QString::number(pose[i]*(i<3?1000:180/3.141592653589793),'f',2);
|
||||
return result.join(" / ");
|
||||
}
|
||||
QVBoxLayout *panel(QBoxLayout *parent,const QString &title) {
|
||||
auto *frame=new QFrame; frame->setObjectName("panel"); parent->addWidget(frame);
|
||||
auto *layout=new QVBoxLayout(frame); layout->setContentsMargins(12,12,12,12); layout->setSpacing(8);
|
||||
auto *label=new QLabel(title); label->setObjectName("sectionTitle"); layout->addWidget(label); return layout;
|
||||
}
|
||||
}
|
||||
|
||||
TouchOperationWidget::TouchOperationWidget(QWidget *parent):QWidget(parent),
|
||||
m_sequence(new TouchSequenceController(this)),m_video(new TouchVideoWidget(this))
|
||||
{
|
||||
setObjectName("touchOperationPage");
|
||||
m_video->setMaxPoints(2);
|
||||
auto *outer=new QVBoxLayout(this); outer->setContentsMargins(12,10,12,10); outer->setSpacing(8);
|
||||
auto *scroll=new QScrollArea; scroll->setWidgetResizable(true); scroll->setFrameShape(QFrame::NoFrame);
|
||||
auto *content=new QWidget; scroll->setWidget(content); outer->addWidget(scroll);
|
||||
auto *root=new QVBoxLayout(content); root->setContentsMargins(0,0,0,0); root->setSpacing(10);
|
||||
auto *top=new QHBoxLayout; top->setSpacing(10); root->addLayout(top);
|
||||
auto *vision=panel(top,QStringLiteral("视觉取点"));
|
||||
m_video->setMinimumWidth(320); m_video->setMaximumWidth(640); m_video->setFrameAspectLayoutEnabled(true);
|
||||
vision->setAlignment(Qt::AlignTop);
|
||||
vision->addWidget(m_video,0,Qt::AlignTop|Qt::AlignHCenter);
|
||||
auto *videoActions=new QHBoxLayout;
|
||||
m_previewButton=new QPushButton(QStringLiteral("开始视频")); m_stopPreviewButton=new QPushButton(QStringLiteral("停止视频"));
|
||||
m_lockButton=new QPushButton(QStringLiteral("锁定观察画面")); m_liveButton=new QPushButton(QStringLiteral("恢复实时"));
|
||||
for(auto *b:{m_previewButton,m_stopPreviewButton,m_lockButton,m_liveButton}) videoActions->addWidget(b);
|
||||
vision->addLayout(videoActions);
|
||||
auto *hint=new QLabel(QStringLiteral("在锁定画面中选择 A / B 点;滑动按 A → B 执行。")); hint->setObjectName("mutedLabel"); vision->addWidget(hint);
|
||||
auto *config=panel(top,QStringLiteral("任务配置")); top->setStretch(0,1); top->setStretch(1,1);
|
||||
auto *grid=new QGridLayout; config->addLayout(grid);
|
||||
m_handEyeChoice=new QComboBox; m_handEyeChoice->setObjectName("touchHandEye");
|
||||
m_toolChoice=new QComboBox; m_toolChoice->setObjectName("touchTcp");
|
||||
for(auto *c:{m_handEyeChoice,m_toolChoice}) { c->setSizePolicy(QSizePolicy::Ignored,QSizePolicy::Fixed); c->setMinimumWidth(130); }
|
||||
m_cameraName=new QLabel; m_cameraName->setWordWrap(true);
|
||||
grid->setColumnStretch(1,1);
|
||||
grid->addWidget(new QLabel(QStringLiteral("手眼标定")),0,0); grid->addWidget(m_handEyeChoice,0,1,1,2);
|
||||
grid->addWidget(new QLabel(QStringLiteral("工具 TCP")),1,0); grid->addWidget(m_toolChoice,1,1,1,2);
|
||||
grid->addWidget(new QLabel(QStringLiteral("相机")),2,0); grid->addWidget(m_cameraName,2,1);
|
||||
m_reloadButton=new QPushButton(QStringLiteral("刷新标定")); grid->addWidget(m_reloadButton,2,2);
|
||||
m_cameraConfirmed=new QCheckBox(QStringLiteral("已核对相机内参与时钟"));
|
||||
m_cameraConfirmed->setToolTip(QStringLiteral("使用该相机 RGB 光学坐标系及标准 Brown 畸变模型;服务与上位机时钟同步,目标保持静止;深度单位及配准由服务提供。")); config->addWidget(m_cameraConfirmed);
|
||||
m_teachObservation=new QPushButton(QStringLiteral("录入当前观察位")); m_teachObservation->setObjectName("touchTeachObservation");
|
||||
m_returnButton=new QPushButton(QStringLiteral("回观察位"));
|
||||
auto *teachRow=new QHBoxLayout; teachRow->addWidget(m_teachObservation,1); teachRow->addWidget(m_returnButton); config->addLayout(teachRow);
|
||||
m_observationText=new QLabel; m_observationText->setWordWrap(true); m_observationText->setObjectName("mutedLabel"); config->addWidget(m_observationText);
|
||||
config->addSpacing(8);
|
||||
auto *actionTitle=new QLabel(QStringLiteral("动作参数")); actionTitle->setObjectName("sectionTitle"); config->addWidget(actionTitle);
|
||||
auto *params=new QGridLayout; params->setHorizontalSpacing(8); params->setVerticalSpacing(8);
|
||||
params->setColumnStretch(1,1); params->setColumnStretch(3,1); config->addLayout(params);
|
||||
m_action=new QComboBox; m_action->setObjectName("touchAction"); m_action->addItems({QStringLiteral("单击"),QStringLiteral("双击"),QStringLiteral("滑动")});
|
||||
params->addWidget(new QLabel(QStringLiteral("动作")),0,0); params->addWidget(m_action,0,1,1,3);
|
||||
auto addSpin=[params](const QString &label,int row,int col,double value,double min,double max,const QString &suffix) {
|
||||
auto *spin=new QDoubleSpinBox; spin->setRange(min,max); spin->setDecimals(2); spin->setValue(value); spin->setSuffix(suffix); spin->setKeyboardTracking(false);
|
||||
params->addWidget(new QLabel(label),row,col); params->addWidget(spin,row,col+1); return spin;
|
||||
};
|
||||
m_approach=addSpin(QStringLiteral("接近高度"),1,0,10,1,50," mm");
|
||||
m_press=addSpin(QStringLiteral("接触偏移"),1,2,0,0,2," mm");
|
||||
m_lift=addSpin(QStringLiteral("双击抬笔"),4,0,1,1,20," mm");
|
||||
m_speed=addSpin(QStringLiteral("移动速度"),2,0,30,5,50," mm/s");
|
||||
m_contactSpeed=addSpin(QStringLiteral("接触速度"),2,2,10,5,30," mm/s");
|
||||
m_travel=addSpin(QStringLiteral("运动范围"),3,0,300,10,1000," mm");
|
||||
m_dwell=new QSpinBox; m_dwell->setRange(0,2000); m_dwell->setValue(50); m_dwell->setSuffix(" ms");
|
||||
params->addWidget(new QLabel(QStringLiteral("接触停留")),3,2); params->addWidget(m_dwell,3,3);
|
||||
m_gap=new QSpinBox; m_gap->setRange(20,500); m_gap->setValue(50); m_gap->setSuffix(" ms");
|
||||
params->addWidget(new QLabel(QStringLiteral("双击间隔")),4,2); params->addWidget(m_gap,4,3);
|
||||
config->addStretch();
|
||||
m_press->setToolTip(QStringLiteral("沿相机 +Z 方向的几何位移,不是力控。首次验证建议为 0。"));
|
||||
m_travel->setToolTip(QStringLiteral("相对观察位的最大位移与每段最大行程;不代替碰撞检查。"));
|
||||
m_gap->setToolTip(QStringLiteral("抬笔到位后的停留;实际两次触点间隔还包含机械臂运动时间。"));
|
||||
auto *bottom=new QHBoxLayout; root->addLayout(bottom);
|
||||
auto *targetPanel=panel(bottom,QStringLiteral("目标点坐标换算结果"));
|
||||
m_conversionStatus=new QLabel; m_conversionStatus->setObjectName("touchConversionStatus"); m_conversionStatus->setWordWrap(true);
|
||||
m_conversionStatus->setToolTip(QStringLiteral("显示深度测量目标点,尚未叠加接触偏移;控制器 TCP 的实际运动目标见执行路径。"));
|
||||
targetPanel->addWidget(m_conversionStatus);
|
||||
m_targets=new QTableWidget(0,4); m_targets->setObjectName("touchTargets");
|
||||
m_targets->setHorizontalHeaderLabels({QStringLiteral("点"),QStringLiteral("像素 · px"),QStringLiteral("相机 XYZ · mm"),QStringLiteral("基座 XYZ · mm")}); targetPanel->addWidget(m_targets);
|
||||
auto *pathPanel=panel(bottom,QStringLiteral("执行路径"));
|
||||
m_steps=new QTableWidget(0,3); m_steps->setObjectName("touchSteps"); m_steps->setHorizontalHeaderLabels({QStringLiteral("步骤"),QStringLiteral("控制器 TCP · XYZ mm / RxRyRz °"),QStringLiteral("速度 mm/s")}); pathPanel->addWidget(m_steps);
|
||||
for(auto *table:{m_targets,m_steps}) { table->verticalHeader()->hide(); table->setEditTriggers(QAbstractItemView::NoEditTriggers); table->setMinimumHeight(150); table->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); table->horizontalHeader()->setStretchLastSection(true); }
|
||||
m_targets->setMinimumHeight(188); m_targets->setMaximumHeight(230); m_targets->setWordWrap(false);
|
||||
m_steps->setMinimumHeight(188); m_steps->setMaximumHeight(260);
|
||||
for(auto *table:{m_targets,m_steps}) { table->setAlternatingRowColors(true); table->setShowGrid(false); }
|
||||
m_targets->horizontalHeader()->setSectionResizeMode(2,QHeaderView::Stretch);
|
||||
m_targets->horizontalHeader()->setSectionResizeMode(3,QHeaderView::Stretch);
|
||||
bottom->setStretch(0,1); bottom->setStretch(1,1);
|
||||
root->addStretch(1);
|
||||
auto *footer=new QHBoxLayout; outer->addLayout(footer);
|
||||
m_status=new QLabel; m_status->setWordWrap(true); m_status->setObjectName("mutedLabel"); outer->insertWidget(1,m_status);
|
||||
m_pathConfirmed=new QCheckBox(QStringLiteral("已核对目标、笔姿及路径净空")); footer->addWidget(m_pathConfirmed);
|
||||
footer->addStretch(1);
|
||||
m_calculateButton=new QPushButton(QStringLiteral("转换 / 预览")); m_executeButton=new QPushButton(QStringLiteral("执行动作")); m_executeButton->setObjectName("primaryButton");
|
||||
auto *stopButton=new QPushButton(QStringLiteral("停止")); stopButton->setObjectName("dangerOutlineButton");
|
||||
footer->addWidget(m_calculateButton); footer->addWidget(m_executeButton); footer->addWidget(stopButton);
|
||||
m_timeout.setSingleShot(true); m_timeout.setInterval(12000);
|
||||
connect(&m_timeout,&QTimer::timeout,this,[this] { fail(QStringLiteral("读取超时,请检查连接后重试。")); });
|
||||
connect(m_previewButton,&QPushButton::clicked,this,&TouchOperationWidget::startPreview);
|
||||
connect(m_stopPreviewButton,&QPushButton::clicked,this,&TouchOperationWidget::stopPreview);
|
||||
connect(m_lockButton,&QPushButton::clicked,this,&TouchOperationWidget::lockFrame);
|
||||
connect(m_liveButton,&QPushButton::clicked,this,[this] { invalidateFrame(); refresh(); });
|
||||
connect(m_teachObservation,&QPushButton::clicked,this,[this] { teach(Phase::Observation); });
|
||||
connect(m_returnButton,&QPushButton::clicked,this,[this] { teach(Phase::Return); });
|
||||
connect(m_calculateButton,&QPushButton::clicked,this,&TouchOperationWidget::calculate);
|
||||
connect(m_executeButton,&QPushButton::clicked,this,&TouchOperationWidget::execute);
|
||||
connect(stopButton,&QPushButton::clicked,this,[this] {
|
||||
const bool active=running(); stop();
|
||||
if(!active&&!m_device.isEmpty()) emit stopRequested(m_device);
|
||||
});
|
||||
connect(m_reloadButton,&QPushButton::clicked,this,&TouchOperationWidget::reloadCalibrations);
|
||||
connect(m_video,&TouchVideoWidget::pointsChanged,this,[this] { invalidatePlan(); refresh(); });
|
||||
connect(m_cameraConfirmed,&QCheckBox::toggled,this,[this] { invalidateFrame(); refresh(); });
|
||||
connect(m_pathConfirmed,&QCheckBox::toggled,this,[this] { refresh(); });
|
||||
connect(m_handEyeChoice,QOverload<int>::of(&QComboBox::currentIndexChanged),this,[this] { if(m_loading) return; stopPreview(); invalidateFrame(); m_cameraConfirmed->setChecked(false); saveTeaching(); refresh(); });
|
||||
connect(m_toolChoice,QOverload<int>::of(&QComboBox::currentIndexChanged),this,[this] { if(m_loading) return; stop(); saveTeaching(); refresh(); });
|
||||
connect(m_action,QOverload<int>::of(&QComboBox::currentIndexChanged),this,[this] { invalidatePlan(); refresh(); });
|
||||
for(auto *spin:{m_approach,m_press,m_lift,m_speed,m_contactSpeed,m_travel}) connect(spin,QOverload<double>::of(&QDoubleSpinBox::valueChanged),this,[this] { invalidatePlan(); refresh(); });
|
||||
for(auto *spin:{m_dwell,m_gap}) connect(spin,QOverload<int>::of(&QSpinBox::valueChanged),this,[this] { invalidatePlan(); refresh(); });
|
||||
connect(m_sequence,&TouchSequenceController::captureRequested,this,&TouchOperationWidget::captureRequested);
|
||||
connect(m_sequence,&TouchSequenceController::moveRequested,this,&TouchOperationWidget::moveRequested);
|
||||
connect(m_sequence,&TouchSequenceController::stopRequested,this,&TouchOperationWidget::stopRequested);
|
||||
connect(m_sequence,&TouchSequenceController::progressChanged,this,[this](int step,int count,const QString &label) { m_status->setText(QStringLiteral("执行 %1 / %2 · %3").arg(step).arg(count).arg(label)); refresh(); });
|
||||
connect(m_sequence,&TouchSequenceController::errorOccurred,this,[this](const QString &error) { emit logMessage("ERROR",error); });
|
||||
connect(m_sequence,&TouchSequenceController::finished,this,[this](bool success,const QString &detail) { invalidateFrame(); refresh(); m_status->setText(detail); emit logMessage(success?"OK":"WARN",QStringLiteral("末端操作:%1").arg(detail)); });
|
||||
refresh();
|
||||
}
|
||||
|
||||
bool TouchOperationWidget::running() const { return m_sequence->running(); }
|
||||
bool TouchOperationWidget::ready() const { return m_connected&&!m_demo&&m_reference&&!m_device.isEmpty()&&TcpCalibration::validPose(m_activeOffset); }
|
||||
const HandEyeStore::Record *TouchOperationWidget::handEye() const {
|
||||
int i=m_handEyeChoice->currentIndex(); return i>=0&&i<m_handEyes.records.size()?&m_handEyes.records[i]:nullptr;
|
||||
}
|
||||
QString TouchOperationWidget::cameraId() const { auto *r=handEye(); return r?r->cameraId:QString(); }
|
||||
bool TouchOperationWidget::selectedTool(Pose &offset) const {
|
||||
int i=m_toolChoice->currentIndex(); if(i<0||i>=m_tools.tools.size()) return false;
|
||||
offset=m_tools.tools[i].offset; return true;
|
||||
}
|
||||
void TouchOperationWidget::setContext(const QString &endpoint,const QString &device,bool connected,bool demo,bool reference,const Pose &offset) {
|
||||
bool scope=endpoint!=m_endpoint||device!=m_device;
|
||||
if(!scope&&offset!=m_activeOffset) { m_observed=false; }
|
||||
if(scope||connected!=m_connected||demo!=m_demo||reference!=m_reference||offset!=m_activeOffset) {
|
||||
stopPreview(); stop(); m_cameraConfirmed->setChecked(false);
|
||||
}
|
||||
m_endpoint=endpoint; m_device=device; m_connected=connected; m_demo=demo; m_reference=reference; m_activeOffset=offset;
|
||||
if(scope) { m_observed=false; reloadCalibrations(); loadTeaching(); }
|
||||
if(m_observed&&m_reference&&m_teachingOffset!=m_activeOffset) { m_observed=false; }
|
||||
m_sequence->setContext(endpoint,device,ready(),offset); refresh();
|
||||
}
|
||||
void TouchOperationWidget::reloadCalibrations() {
|
||||
stopPreview(); stop();
|
||||
const QString oldHand=m_handEyeChoice->currentText(),oldTool=m_toolChoice->currentText();
|
||||
m_loading=true; m_handEyeChoice->clear(); m_toolChoice->clear(); m_handEyes={}; m_tools={};
|
||||
QSettings settings; QString error;
|
||||
bool ok=m_endpoint.isEmpty()||m_device.isEmpty()||
|
||||
(HandEyeStore::load(settings,m_endpoint,m_device,m_handEyes,error)&&TcpToolStore::load(settings,m_endpoint,m_device,m_tools,error));
|
||||
if(ok) {
|
||||
for(const auto &r:m_handEyes.records) m_handEyeChoice->addItem(r.name);
|
||||
for(const auto &t:m_tools.tools) m_toolChoice->addItem(t.name);
|
||||
int h=m_handEyeChoice->findText(oldHand),t=m_toolChoice->findText(oldTool);
|
||||
if(h>=0) m_handEyeChoice->setCurrentIndex(h);
|
||||
if(t>=0) m_toolChoice->setCurrentIndex(t);
|
||||
}
|
||||
m_loading=false;
|
||||
m_cameraConfirmed->setChecked(false); refresh(); if(!ok) fail(error);
|
||||
}
|
||||
void TouchOperationWidget::invalidatePlan() { m_planValid=false; m_plan={}; m_pathConfirmed->setChecked(false); m_steps->setRowCount(0); }
|
||||
void TouchOperationWidget::invalidateFrame() {
|
||||
invalidatePlan(); m_lockedAt=0; m_pendingImage={}; m_depth={}; m_video->unlock(); m_video->clearSelection();
|
||||
}
|
||||
void TouchOperationWidget::stop() {
|
||||
m_sequence->stop(); ++m_serial; m_poseToken=0; m_imageToken=0; m_phase=Phase::Idle; m_timeout.stop(); invalidateFrame(); refresh();
|
||||
}
|
||||
void TouchOperationWidget::fail(const QString &message) {
|
||||
stop(); m_status->setText(message); emit logMessage("ERROR",QStringLiteral("末端操作:%1").arg(message));
|
||||
QMessageBox::warning(this,QStringLiteral("末端操作"),message);
|
||||
}
|
||||
void TouchOperationWidget::hideEvent(QHideEvent *event) { stopPreview(); stop(); QWidget::hideEvent(event); }
|
||||
void TouchOperationWidget::startPreview() {
|
||||
if(!m_connected||m_demo||!handEye()) { fail(QStringLiteral("请连接机器人服务并选择手眼标定。")); return; }
|
||||
stopPreview(); m_previewCamera=cameraId(); m_preview=true; emit previewRequested(m_previewCamera,true); refresh();
|
||||
}
|
||||
void TouchOperationWidget::stopPreview() {
|
||||
const QString camera=m_previewCamera; bool active=m_preview; m_preview=false; m_previewCamera.clear();
|
||||
if(active) emit previewRequested(camera,false);
|
||||
stop(); m_video->clearFrame();
|
||||
}
|
||||
void TouchOperationWidget::acceptFrame(const QString &camera,const VideoFrame &frame,const QString &) {
|
||||
if(!m_preview||camera!=m_previewCamera||!frame.isValid()) return;
|
||||
if(frame.metadata.value("kind").toString()!="rgb") { m_status->setText(QStringLiteral("当前流不是 RGB,请在相机页面切换为彩色视频。")); return; }
|
||||
m_video->present(frame);
|
||||
|
||||
}
|
||||
void TouchOperationWidget::acceptStreamState(const QString &camera,bool active,const QString &detail) {
|
||||
if(m_preview&&camera==m_previewCamera&&!active) { stopPreview(); m_status->setText(QStringLiteral("视频已停止:%1").arg(detail)); }
|
||||
}
|
||||
void TouchOperationWidget::teach(Phase phase) {
|
||||
Pose offset{};
|
||||
if(!ready()||running()||m_phase!=Phase::Idle||(phase!=Phase::Observation&&!selectedTool(offset))) { fail(QStringLiteral("请先连接机械臂、选择 TCP 标定并核对控制器偏移。")); return; }
|
||||
if(phase==Phase::Return&&!m_observed) return;
|
||||
invalidateFrame(); m_phase=phase; readPose();
|
||||
}
|
||||
void TouchOperationWidget::readPose() {
|
||||
m_poseToken=kPosePrefix|++m_serial; m_requestAt=QDateTime::currentMSecsSinceEpoch(); m_timeout.start();
|
||||
emit captureRequested(m_device,m_poseToken); refresh();
|
||||
}
|
||||
void TouchOperationWidget::lockFrame() {
|
||||
if(!ready()||!m_preview||!m_observed||!m_cameraConfirmed->isChecked()||running()||m_phase!=Phase::Idle) return;
|
||||
invalidateFrame(); m_phase=Phase::LockBefore; readPose();
|
||||
}
|
||||
void TouchOperationWidget::acceptPose(quint64 token,const QString &device,const QVariantMap &map,const QVariantMap &state,bool success,const QString &detail) {
|
||||
m_sequence->acceptPose(token,device,map,state,success,detail);
|
||||
if(!m_poseToken||token!=m_poseToken||device!=m_device) return;
|
||||
m_poseToken=0; Pose pose{},tool{},flange{},selected{};
|
||||
const qint64 requested=state.value("requestedAtMs").toLongLong(),received=state.value("receivedAtMs").toLongLong();
|
||||
const qint64 now=QDateTime::currentMSecsSinceEpoch();
|
||||
if(!success||!ready()||!decodePose(map,pose)||(m_phase!=Phase::Observation&&!selectedTool(tool))||requested<m_requestAt||received<requested||received>now||now-received>1500
|
||||
||!state.value("connected").toBool()||state.value("moving",true).toBool()||state.value("fault",true).toBool()
|
||||
||state.value("protectiveStopped",true).toBool()||state.value("emergencyStopped",true).toBool()
|
||||
||state.value("source").toString()!=QStringLiteral("getRobotState.actual_tcp_pose")) { fail(QStringLiteral("实时位姿不可用:%1").arg(detail)); return; }
|
||||
if(!TcpCalibration::flangePose(pose,m_activeOffset,flange)||!TcpCalibration::toolPose(flange,tool,selected)) { fail(QStringLiteral("TCP 位姿转换失败。")); return; }
|
||||
const auto phase=m_phase;
|
||||
if(phase==Phase::LockBefore) {
|
||||
if(!nearPose(pose,m_observation)) { fail(QStringLiteral("机械臂不在观察位,请先回观察位并停稳。")); return; }
|
||||
m_before=pose; m_beforeAt=received; m_phase=Phase::LockImage; m_imageToken=kImagePrefix|++m_serial;
|
||||
emit imageRequested(cameraId(),m_imageToken); refresh(); return;
|
||||
}
|
||||
if(phase==Phase::LockAfter) {
|
||||
if(requested<m_captureAt||!nearPose(m_before,pose)||!nearPose(pose,m_observation)||received-m_beforeAt>10000) { fail(QStringLiteral("取图期间位姿变化或时间窗无效,请停稳后重试。")); return; }
|
||||
TcpCalibration::flangePose(m_before,m_activeOffset,m_lockedFlange);
|
||||
if(!(m_video->lockImage(m_pendingImage))) { fail(QStringLiteral("观察图像无效。")); return; }
|
||||
m_pendingImage={}; m_lockedAt=QDateTime::currentMSecsSinceEpoch();
|
||||
} else if(phase==Phase::Observation) {
|
||||
m_observation=pose; m_observed=true; m_teachingOffset=m_activeOffset; saveTeaching();
|
||||
} else if(phase==Phase::Return) {
|
||||
m_phase=Phase::Idle; m_timeout.stop(); returnObservation(pose); return;
|
||||
}
|
||||
m_phase=Phase::Idle; m_timeout.stop(); refresh(); emit logMessage("OK",QStringLiteral("末端操作:已录入位姿 / 锁定观察图像"));
|
||||
}
|
||||
void TouchOperationWidget::acceptImage(quint64 token,const QString &camera,const QImage &image,const QVariantMap &intrinsics,const QVariantMap &metadata,bool success,const QString &detail) {
|
||||
if(!m_imageToken||token!=m_imageToken||camera!=cameraId()||m_phase!=Phase::LockImage) return;
|
||||
m_imageToken=0; QString error;
|
||||
if(!success) { fail(QStringLiteral("读取 RGBD 失败:%1").arg(detail)); return; }
|
||||
const qint64 colorAt=metadata.value("captureUtcNs").toLongLong()/1000000;
|
||||
const qint64 depthAt=metadata.value("depthCaptureUtcNs").toLongLong()/1000000;
|
||||
const qint64 now=QDateTime::currentMSecsSinceEpoch();
|
||||
if(!metadata.value("alignedToColor").toBool()||!metadata.value("colorAxialZ").toBool()
|
||||
||metadata.value("byteOrder").toString()!="little"||colorAt<=0||depthAt<=0
|
||||
||std::abs(colorAt-depthAt)>33||colorAt>now||depthAt>now) {
|
||||
fail(QStringLiteral("RGBD 缺少有效配准、深度单位或同步时间戳,请更新相机服务。")); return;
|
||||
}
|
||||
if(colorAt<m_beforeAt||depthAt<m_beforeAt||now-qMin(colorAt,depthAt)>1500) {
|
||||
// The server snapshots its acquisition thread. Wait for a new pair;
|
||||
// never combine a live color frame with an older depth image.
|
||||
const quint64 generation=m_serial;
|
||||
QTimer::singleShot(80,this,[this,generation] {
|
||||
if(m_serial!=generation||m_phase!=Phase::LockImage||m_imageToken) return;
|
||||
m_imageToken=kImagePrefix|++m_serial; emit imageRequested(cameraId(),m_imageToken);
|
||||
});
|
||||
return;
|
||||
}
|
||||
TouchPlanner::DepthImage depth;
|
||||
depth.width=metadata.value("depthWidth").toInt(); depth.height=metadata.value("depthHeight").toInt();
|
||||
depth.data=metadata.value("depthData").toByteArray(); depth.float32=metadata.value("depthFloat32").toBool();
|
||||
depth.metresPerUnit=metadata.value("metresPerUnit").toDouble();
|
||||
if(image.isNull()||!TouchPlanner::cameraModel(intrinsics,image.width(),image.height(),m_cameraModel,&error)
|
||||
||depth.width!=image.width()||depth.height!=image.height()
|
||||
||!std::isfinite(depth.metresPerUnit)||depth.metresPerUnit<=0||depth.metresPerUnit>1
|
||||
||qint64(depth.width)*depth.height*(depth.float32?4:2)!=depth.data.size()) {
|
||||
fail(QStringLiteral("RGBD 尺寸、单位或内参无效:%1").arg(error)); return;
|
||||
}
|
||||
m_depth=depth; m_pendingImage=image; m_captureAt=qMax(colorAt,depthAt); m_phase=Phase::LockAfter; readPose();
|
||||
}
|
||||
void TouchOperationWidget::acceptCommand(const QString &command,bool success,const QString &detail) { m_sequence->acceptCommand(command,success,detail); }
|
||||
TouchPlanner::Parameters TouchOperationWidget::parameters() const {
|
||||
TouchPlanner::Parameters p; p.approachM=m_approach->value()/1000; p.contactOffsetM=m_press->value()/1000;
|
||||
p.doubleLiftM=m_lift->value()/1000; p.travelVelocityMps=m_speed->value()/1000; p.contactVelocityMps=m_contactSpeed->value()/1000;
|
||||
p.maxTravelM=m_travel->value()/1000; p.contactDwellMs=m_dwell->value(); p.doubleIntervalMs=m_gap->value(); return p;
|
||||
}
|
||||
bool TouchOperationWidget::buildPlane(TouchPlanner::Plane &plane,QString &error) const {
|
||||
QVector<TouchPlanner::Point> points,cameraPoints;
|
||||
TouchPlanner::Matrix baseCamera{}; Pose offset{},tip{};
|
||||
if(!resolveTargets(points,cameraPoints,error)||!selectedTool(offset)
|
||||
||!TcpCalibration::toolPose(m_lockedFlange,offset,tip,&error)
|
||||
||!TouchPlanner::cameraTransform(*handEye(),m_lockedFlange,baseCamera,&error)) return false;
|
||||
plane.origin=points.first();
|
||||
// Same free-pixel approach direction as phone: negative camera Z.
|
||||
// Preserve the selected stylus orientation taught at the observation pose.
|
||||
for(int i=0;i<3;++i) { plane.normal[i]=-baseCamera[i*4+2]; plane.orientationRad[i]=tip[i+3]; }
|
||||
return true;
|
||||
}
|
||||
void TouchOperationWidget::calculate() {
|
||||
invalidatePlan(); QString error; Pose tool{}; TouchPlanner::Plane plane; QVector<TouchPlanner::Point> points,cameraPoints;
|
||||
TouchPlanner::Matrix baseCamera{};
|
||||
if(!ready()||!handEye()||!selectedTool(tool)||!m_video->locked()||!m_lockedAt||QDateTime::currentMSecsSinceEpoch()-m_lockedAt>60000) { fail(QStringLiteral("请在观察位重新锁定画面后取点。")); return; }
|
||||
if(!buildPlane(plane,error)||!resolveTargets(points,cameraPoints,error)
|
||||
||!TouchPlanner::cameraTransform(*handEye(),m_lockedFlange,baseCamera,&error)
|
||||
||(m_action->currentIndex()==2&&!TouchPlanner::validateDepthSwipe(m_video->selectedPoints(),m_cameraModel,m_depth,baseCamera,parameters(),&error))
|
||||
||!TouchPlanner::buildPlan(static_cast<TouchPlanner::Action>(m_action->currentIndex()),points,plane,m_observation,m_activeOffset,tool,parameters(),m_plan,&error,true)) { fail(error); return; }
|
||||
m_planValid=true; m_steps->setRowCount(m_plan.steps.size());
|
||||
for(int i=0;i<m_plan.steps.size();++i) { const auto &step=m_plan.steps[i]; m_steps->setItem(i,0,new QTableWidgetItem(QString::number(i+1)+" · "+step.label));
|
||||
m_steps->setItem(i,1,new QTableWidgetItem(poseText(step.target))); m_steps->setItem(i,2,new QTableWidgetItem(QString::number(step.velocityMps*1000,'f',1))); }
|
||||
refresh(); emit logMessage("INFO",QStringLiteral("末端操作:已转换 %1 个目标,规划 %2 个动作步骤").arg(points.size()).arg(m_plan.steps.size()));
|
||||
}
|
||||
void TouchOperationWidget::execute() {
|
||||
if(!m_planValid||!m_pathConfirmed->isChecked()||running()||!ready()||QDateTime::currentMSecsSinceEpoch()-m_lockedAt>60000) { fail(QStringLiteral("请重新预览路径并确认后执行。")); return; }
|
||||
QVector<TouchSequenceController::Step> steps;
|
||||
for(const auto &s:m_plan.steps) steps.append({s.target,s.velocityMps,s.accelerationMps2,s.pauseMs,s.label});
|
||||
m_sequence->setContext(m_endpoint,m_device,ready(),m_activeOffset);
|
||||
m_sequence->start(steps,m_observation); refresh();
|
||||
}
|
||||
void TouchOperationWidget::returnObservation(const Pose ¤t) {
|
||||
// Explicit straight return; automatic touch sequences retract before return.
|
||||
auto p=parameters(); double distance=0; for(int i=0;i<3;++i) distance+=std::pow(current[i]-m_observation[i],2);
|
||||
if(std::sqrt(distance)>p.maxTravelM) { fail(QStringLiteral("当前位置超出所设回程范围,请手动接近观察位。")); return; }
|
||||
QVector<TouchSequenceController::Step> steps; Pose tool{};
|
||||
steps.append({m_observation,p.travelVelocityMps,p.accelerationMps2,0,QStringLiteral("返回观察位")});
|
||||
if(!selectedTool(tool)) { fail(QStringLiteral("请选择有效 TCP。")); return; }
|
||||
Pose previous=current,previousFlange{},previousTip{},obsFlange{},obsTip{};
|
||||
if(!TcpCalibration::flangePose(current,m_activeOffset,previousFlange)||!TcpCalibration::toolPose(previousFlange,tool,previousTip)
|
||||
||!TcpCalibration::flangePose(m_observation,m_activeOffset,obsFlange)||!TcpCalibration::toolPose(obsFlange,tool,obsTip)) { fail(QStringLiteral("回程位姿转换失败。")); return; }
|
||||
for(const auto &step:steps) {
|
||||
Pose nextFlange{},nextTip{};
|
||||
if(!TcpCalibration::flangePose(step.target,m_activeOffset,nextFlange)||!TcpCalibration::toolPose(nextFlange,tool,nextTip)) { fail(QStringLiteral("回程位姿转换失败。")); return; }
|
||||
auto norm=[](const Pose &a,const Pose &b) { double sum=0; for(int i=0;i<3;++i) sum+=std::pow(a[i]-b[i],2); return std::sqrt(sum); };
|
||||
const Pose origin{};
|
||||
if(norm(step.target,previous)>p.maxTravelM||norm(nextTip,previousTip)>p.maxTravelM||norm(nextFlange,previousFlange)>p.maxTravelM
|
||||
||norm(step.target,m_observation)>p.maxTravelM||norm(nextTip,obsTip)>p.maxTravelM||norm(nextFlange,obsFlange)>p.maxTravelM
|
||||
||norm(step.target,origin)>p.maxReachM||norm(nextTip,origin)>p.maxReachM||norm(nextFlange,origin)>p.maxReachM) { fail(QStringLiteral("回程路径超出所设运动范围。")); return; }
|
||||
previous=step.target; previousTip=nextTip; previousFlange=nextFlange;
|
||||
}
|
||||
m_sequence->setContext(m_endpoint,m_device,ready(),m_activeOffset); m_sequence->start(steps,current); refresh();
|
||||
}
|
||||
QString TouchOperationWidget::settingsKey() const {
|
||||
QByteArray identity=m_endpoint.toUtf8(); identity.append('\0'); identity.append(m_device.toUtf8());
|
||||
return QStringLiteral("touchOperation/v1/")+QString::fromLatin1(QCryptographicHash::hash(identity,QCryptographicHash::Sha256).toHex());
|
||||
}
|
||||
void TouchOperationWidget::saveTeaching() {
|
||||
if(m_loading||m_endpoint.isEmpty()||m_device.isEmpty()) return;
|
||||
Pose tool{}; QVariantMap data{{"endpoint",m_endpoint},{"device",m_device},{"handEye",m_handEyeChoice->currentText()},{"tool",m_toolChoice->currentText()},
|
||||
{"observed",m_observed},{"observation",values(m_observation)},{"activeOffset",values(m_teachingOffset)}};
|
||||
if(selectedTool(tool)) data.insert("toolOffset",values(tool));
|
||||
QSettings settings; settings.setValue(settingsKey(),QJsonDocument::fromVariant(data).toJson(QJsonDocument::Compact)); settings.sync();
|
||||
if(settings.status()!=QSettings::NoError) { m_status->setText(QStringLiteral("示教配置写入失败")); emit logMessage("ERROR",m_status->text()); }
|
||||
}
|
||||
void TouchOperationWidget::loadTeaching() {
|
||||
QSettings settings; auto bytes=settings.value(settingsKey()).toByteArray(); if(bytes.isEmpty()) return;
|
||||
const auto data=QJsonDocument::fromJson(bytes).toVariant().toMap();
|
||||
if(data.value("endpoint").toString()!=m_endpoint||data.value("device").toString()!=m_device) return;
|
||||
m_loading=true; const int h=m_handEyeChoice->findText(data.value("handEye").toString()),t=m_toolChoice->findText(data.value("tool").toString());
|
||||
if(h>=0) m_handEyeChoice->setCurrentIndex(h);
|
||||
if(t>=0) m_toolChoice->setCurrentIndex(t);
|
||||
m_loading=false;
|
||||
m_observed=data.value("observed").toBool()&&poseFrom(data.value("observation"),m_observation)&&poseFrom(data.value("activeOffset"),m_teachingOffset);
|
||||
|
||||
}
|
||||
void TouchOperationWidget::refresh() {
|
||||
bool busy=running()||m_phase!=Phase::Idle; Pose offset{}; bool selected=selectedTool(offset);
|
||||
m_cameraName->setText(cameraId().isEmpty()?QStringLiteral("请先选择手眼标定"):cameraId());
|
||||
for(auto *w:QList<QWidget*>{m_handEyeChoice,m_toolChoice,m_action,m_reloadButton,m_cameraConfirmed,m_approach,m_press,m_lift,m_speed,m_contactSpeed,m_travel,m_dwell,m_gap}) w->setEnabled(!busy);
|
||||
m_teachObservation->setEnabled(ready()&&!busy); m_returnButton->setEnabled(ready()&&selected&&m_observed&&!busy);
|
||||
|
||||
m_previewButton->setEnabled(m_connected&&!m_demo&&handEye()&&!m_preview&&!busy); m_stopPreviewButton->setEnabled(m_preview);
|
||||
m_lockButton->setEnabled(ready()&&m_observed&&m_preview&&m_cameraConfirmed->isChecked()&&!busy);
|
||||
m_liveButton->setEnabled(m_video->locked()&&!busy); m_video->setEnabled(!busy);
|
||||
m_calculateButton->setEnabled(ready()&&m_video->locked()&&!m_video->selectedPoints().isEmpty()&&!busy);
|
||||
m_executeButton->setEnabled(ready()&&m_planValid&&m_pathConfirmed->isChecked()&&!busy);
|
||||
m_pathConfirmed->setEnabled(m_planValid&&!busy);
|
||||
m_observationText->setText(m_observed?QStringLiteral("观察位 · %1").arg(poseText(m_observation)):QStringLiteral("尚未录入观察位"));
|
||||
refreshTargetResults();
|
||||
if(!running()) m_status->setText(!ready()?QStringLiteral("请连接机械臂并在 TCP 标定页核对控制器工具偏移"):
|
||||
busy?QStringLiteral("正在读取真实位姿 / 图像…"):m_planValid?QStringLiteral("路径已就绪,核对后执行"):m_video->locked()?QStringLiteral("画面已锁定,请选择 1–2 个目标点"):QStringLiteral("录入示教位、选择标定后,在观察位锁定画面"));
|
||||
}
|
||||
|
||||
bool TouchOperationWidget::resolveTargets(QVector<TouchPlanner::Point> &basePoints,
|
||||
QVector<TouchPlanner::Point> &cameraPoints,QString &error) const {
|
||||
if(!m_video->locked()||!m_lockedAt) { error=QStringLiteral("请锁定观察画面后选择目标点"); return false; }
|
||||
if(m_video->selectedPoints().isEmpty()) { error=QStringLiteral("请选择 A / B 目标点"); return false; }
|
||||
if(QDateTime::currentMSecsSinceEpoch()-m_lockedAt>60000) { error=QStringLiteral("观察画面已过期,请重新锁定"); return false; }
|
||||
if(!ready()||!handEye()) { error=QStringLiteral("请核对连接、手眼标定与 TCP 偏移"); return false; }
|
||||
TouchPlanner::Matrix baseCamera{};
|
||||
if(!TouchPlanner::cameraTransform(*handEye(),m_lockedFlange,baseCamera,&error)) return false;
|
||||
return TouchPlanner::resolveDepthPixels(m_video->selectedPoints(),m_cameraModel,m_depth,baseCamera,
|
||||
parameters(),basePoints,cameraPoints,&error);
|
||||
|
||||
}
|
||||
|
||||
void TouchOperationWidget::refreshTargetResults() {
|
||||
const auto pixels=m_video->selectedPoints(); QVector<TouchPlanner::Point> base,camera; QString error;
|
||||
const bool valid=resolveTargets(base,camera,error);
|
||||
m_conversionStatus->setText(valid?QStringLiteral("%1 个深度目标点 · 换算完成").arg(base.size()):error);
|
||||
m_targets->setRowCount(pixels.size());
|
||||
auto xyz=[](const TouchPlanner::Point &point) {
|
||||
return QStringLiteral("X %1\nY %2\nZ %3").arg(point[0]*1000,0,'f',3).arg(point[1]*1000,0,'f',3).arg(point[2]*1000,0,'f',3);
|
||||
};
|
||||
for(int i=0;i<pixels.size();++i) {
|
||||
const QStringList row={i==0?"A":"B",QStringLiteral("u %1\nv %2").arg(pixels[i].x(),0,'f',1).arg(pixels[i].y(),0,'f',1),
|
||||
valid?xyz(camera[i]):QStringLiteral("待换算"),valid?xyz(base[i]):QStringLiteral("待换算")};
|
||||
for(int col=0;col<row.size();++col) { auto *item=new QTableWidgetItem(row[col]); item->setTextAlignment(Qt::AlignLeft|Qt::AlignVCenter); m_targets->setItem(i,col,item); }
|
||||
m_targets->setRowHeight(i,74);
|
||||
}
|
||||
}
|
||||
@ -1,267 +1,307 @@
|
||||
#include "videorenderwidget.h"
|
||||
|
||||
#include <QOpenGLShaderProgram>
|
||||
#include <QPainter>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
const char *vertexShaderSource = R"(
|
||||
attribute vec2 position;
|
||||
attribute vec2 texCoord;
|
||||
varying vec2 textureCoordinate;
|
||||
uniform vec2 contentScale;
|
||||
void main()
|
||||
#include "videorenderwidget.h"
|
||||
|
||||
#include <QOpenGLShaderProgram>
|
||||
#include <QPainter>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
const char *vertexShaderSource = R"(
|
||||
attribute vec2 position;
|
||||
attribute vec2 texCoord;
|
||||
varying vec2 textureCoordinate;
|
||||
uniform vec2 contentScale;
|
||||
void main()
|
||||
{
|
||||
gl_Position = vec4(position * contentScale, 0.0, 1.0);
|
||||
textureCoordinate = texCoord;
|
||||
}
|
||||
)";
|
||||
|
||||
const char *fragmentShaderSource = R"(
|
||||
#ifdef GL_ES
|
||||
precision mediump float;
|
||||
#endif
|
||||
varying vec2 textureCoordinate;
|
||||
uniform sampler2D textureY;
|
||||
uniform sampler2D textureU;
|
||||
uniform sampler2D textureV;
|
||||
uniform float pixelFormat;
|
||||
uniform float scaleY;
|
||||
uniform float scaleU;
|
||||
uniform float scaleV;
|
||||
void main()
|
||||
{
|
||||
if (pixelFormat > 1.5) {
|
||||
gl_FragColor = texture2D(textureY, textureCoordinate);
|
||||
return;
|
||||
}
|
||||
|
||||
float y = texture2D(textureY,
|
||||
vec2(textureCoordinate.x * scaleY, textureCoordinate.y)).r;
|
||||
float u;
|
||||
float v;
|
||||
if (pixelFormat > 0.5) {
|
||||
vec4 uv = texture2D(textureU,
|
||||
vec2(textureCoordinate.x * scaleU, textureCoordinate.y));
|
||||
u = uv.r - 0.5;
|
||||
v = uv.a - 0.5;
|
||||
} else {
|
||||
u = texture2D(textureU,
|
||||
vec2(textureCoordinate.x * scaleU, textureCoordinate.y)).r - 0.5;
|
||||
v = texture2D(textureV,
|
||||
vec2(textureCoordinate.x * scaleV, textureCoordinate.y)).r - 0.5;
|
||||
}
|
||||
y = 1.16438356 * (y - 0.0625);
|
||||
gl_FragColor = vec4(y + 1.59602678 * v,
|
||||
y - 0.39176229 * u - 0.81296764 * v,
|
||||
y + 2.01723214 * u, 1.0);
|
||||
}
|
||||
)";
|
||||
}
|
||||
|
||||
VideoRenderWidget::VideoRenderWidget(QWidget *parent)
|
||||
: QOpenGLWidget(parent)
|
||||
{
|
||||
setAutoFillBackground(false);
|
||||
setUpdateBehavior(QOpenGLWidget::NoPartialUpdate);
|
||||
}
|
||||
|
||||
VideoRenderWidget::~VideoRenderWidget()
|
||||
{
|
||||
if (context()) {
|
||||
makeCurrent();
|
||||
releaseTextures();
|
||||
doneCurrent();
|
||||
}
|
||||
}
|
||||
|
||||
void VideoRenderWidget::setFrameAspectLayoutEnabled(bool enabled)
|
||||
{
|
||||
gl_Position = vec4(position * contentScale, 0.0, 1.0);
|
||||
textureCoordinate = texCoord;
|
||||
}
|
||||
)";
|
||||
|
||||
const char *fragmentShaderSource = R"(
|
||||
#ifdef GL_ES
|
||||
precision mediump float;
|
||||
#endif
|
||||
varying vec2 textureCoordinate;
|
||||
uniform sampler2D textureY;
|
||||
uniform sampler2D textureU;
|
||||
uniform sampler2D textureV;
|
||||
uniform float pixelFormat;
|
||||
uniform float scaleY;
|
||||
uniform float scaleU;
|
||||
uniform float scaleV;
|
||||
void main()
|
||||
{
|
||||
if (pixelFormat > 1.5) {
|
||||
gl_FragColor = texture2D(textureY, textureCoordinate);
|
||||
return;
|
||||
}
|
||||
|
||||
float y = texture2D(textureY,
|
||||
vec2(textureCoordinate.x * scaleY, textureCoordinate.y)).r;
|
||||
float u;
|
||||
float v;
|
||||
if (pixelFormat > 0.5) {
|
||||
vec4 uv = texture2D(textureU,
|
||||
vec2(textureCoordinate.x * scaleU, textureCoordinate.y));
|
||||
u = uv.r - 0.5;
|
||||
v = uv.a - 0.5;
|
||||
} else {
|
||||
u = texture2D(textureU,
|
||||
vec2(textureCoordinate.x * scaleU, textureCoordinate.y)).r - 0.5;
|
||||
v = texture2D(textureV,
|
||||
vec2(textureCoordinate.x * scaleV, textureCoordinate.y)).r - 0.5;
|
||||
}
|
||||
y = 1.16438356 * (y - 0.0625);
|
||||
gl_FragColor = vec4(y + 1.59602678 * v,
|
||||
y - 0.39176229 * u - 0.81296764 * v,
|
||||
y + 2.01723214 * u, 1.0);
|
||||
}
|
||||
)";
|
||||
m_frameAspectLayout = enabled;
|
||||
QSizePolicy policy(QSizePolicy::Expanding, enabled ? QSizePolicy::Fixed : QSizePolicy::Expanding);
|
||||
policy.setHeightForWidth(enabled);
|
||||
setSizePolicy(policy);
|
||||
if (enabled) updateAspectHeight();
|
||||
else { setMinimumHeight(0); setMaximumHeight(QWIDGETSIZE_MAX); }
|
||||
updateGeometry();
|
||||
}
|
||||
|
||||
VideoRenderWidget::VideoRenderWidget(QWidget *parent)
|
||||
: QOpenGLWidget(parent)
|
||||
int VideoRenderWidget::heightForWidth(int width) const
|
||||
{
|
||||
setAutoFillBackground(false);
|
||||
setUpdateBehavior(QOpenGLWidget::NoPartialUpdate);
|
||||
return m_frameAspectLayout ? qMax(1, qRound(double(width) * m_layoutFrameSize.height()
|
||||
/ m_layoutFrameSize.width())) : -1;
|
||||
}
|
||||
|
||||
VideoRenderWidget::~VideoRenderWidget()
|
||||
QSize VideoRenderWidget::sizeHint() const
|
||||
{
|
||||
if (context()) {
|
||||
makeCurrent();
|
||||
releaseTextures();
|
||||
doneCurrent();
|
||||
}
|
||||
return m_frameAspectLayout ? QSize(640,heightForWidth(640)) : QOpenGLWidget::sizeHint();
|
||||
}
|
||||
|
||||
void VideoRenderWidget::updateAspectHeight()
|
||||
{
|
||||
if (!m_frameAspectLayout) return;
|
||||
const int wanted = heightForWidth(width());
|
||||
if (minimumHeight() != wanted || maximumHeight() != wanted) setFixedHeight(wanted);
|
||||
}
|
||||
|
||||
void VideoRenderWidget::resizeEvent(QResizeEvent *event)
|
||||
{
|
||||
QOpenGLWidget::resizeEvent(event);
|
||||
updateAspectHeight();
|
||||
}
|
||||
|
||||
void VideoRenderWidget::setFrame(const VideoFrame &frame)
|
||||
{
|
||||
if (!frame.isValid())
|
||||
return;
|
||||
{
|
||||
if (!frame.isValid())
|
||||
return;
|
||||
m_frame = frame;
|
||||
m_message.clear();
|
||||
m_frameDirty = true;
|
||||
update();
|
||||
}
|
||||
|
||||
void VideoRenderWidget::setImage(const QImage &image)
|
||||
{
|
||||
if (image.isNull())
|
||||
return;
|
||||
const QImage converted = image.convertToFormat(QImage::Format_RGBA8888);
|
||||
VideoFrame frame;
|
||||
frame.width = converted.width();
|
||||
frame.height = converted.height();
|
||||
frame.format = VideoPixelFormat::RGBA;
|
||||
frame.stride0 = frame.width * 4;
|
||||
frame.plane0.resize(frame.width * frame.height * 4);
|
||||
for (int row = 0; row < frame.height; ++row) {
|
||||
std::memcpy(frame.plane0.data() + row * frame.width * 4,
|
||||
converted.constScanLine(row), static_cast<size_t>(frame.width * 4));
|
||||
if (m_layoutFrameSize != QSize(frame.width, frame.height)) {
|
||||
m_layoutFrameSize = QSize(frame.width, frame.height);
|
||||
updateAspectHeight();
|
||||
if (m_frameAspectLayout) updateGeometry();
|
||||
}
|
||||
setFrame(frame);
|
||||
}
|
||||
|
||||
void VideoRenderWidget::clearFrame(const QString &message)
|
||||
{
|
||||
m_frame = VideoFrame();
|
||||
m_message = message;
|
||||
m_frameDirty = false;
|
||||
update();
|
||||
}
|
||||
|
||||
void VideoRenderWidget::initializeGL()
|
||||
{
|
||||
initializeOpenGLFunctions();
|
||||
glClearColor(0.055f, 0.067f, 0.078f, 1.0f);
|
||||
glGenTextures(3, m_textures);
|
||||
|
||||
m_program.reset(new QOpenGLShaderProgram);
|
||||
if (!m_program->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSource) ||
|
||||
!m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource) ||
|
||||
!m_program->link()) {
|
||||
m_message = QStringLiteral("OpenGL 视频着色器初始化失败:%1").arg(m_program->log());
|
||||
m_program.reset();
|
||||
return;
|
||||
}
|
||||
m_glReady = true;
|
||||
}
|
||||
|
||||
void VideoRenderWidget::uploadPlane(unsigned int texture, int unit, int width,
|
||||
int height, unsigned int format,
|
||||
const QByteArray &data, int textureIndex)
|
||||
{
|
||||
glActiveTexture(GL_TEXTURE0 + unit);
|
||||
glBindTexture(GL_TEXTURE_2D, texture);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
||||
if (m_textureWidths[textureIndex] != width ||
|
||||
m_textureHeights[textureIndex] != height ||
|
||||
m_textureFormats[textureIndex] != format) {
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, static_cast<int>(format), width, height, 0,
|
||||
format, GL_UNSIGNED_BYTE, data.constData());
|
||||
m_textureWidths[textureIndex] = width;
|
||||
m_textureHeights[textureIndex] = height;
|
||||
m_textureFormats[textureIndex] = format;
|
||||
} else {
|
||||
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format,
|
||||
GL_UNSIGNED_BYTE, data.constData());
|
||||
}
|
||||
}
|
||||
|
||||
void VideoRenderWidget::paintGL()
|
||||
{
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
if (!m_glReady || !m_program || !m_frame.isValid()) {
|
||||
drawMessage(m_message);
|
||||
return;
|
||||
}
|
||||
|
||||
// Qt 5.12's ANGLE backend can upload RGBA QImage data with an incorrect
|
||||
// channel layout. Draw still RGBA frames with the CPU painter instead.
|
||||
if (m_frame.format == VideoPixelFormat::RGBA) {
|
||||
const QImage image(reinterpret_cast<const uchar *>(m_frame.plane0.constData()),
|
||||
m_frame.width, m_frame.height, m_frame.stride0,
|
||||
QImage::Format_RGBA8888);
|
||||
QPainter painter(this);
|
||||
painter.fillRect(rect(), QColor(QStringLiteral("#0e1115")));
|
||||
QSize target = image.size();
|
||||
target.scale(size(), Qt::KeepAspectRatio);
|
||||
const QRect destination((width() - target.width()) / 2,
|
||||
(height() - target.height()) / 2,
|
||||
target.width(), target.height());
|
||||
painter.drawImage(destination, image);
|
||||
m_frameDirty = false;
|
||||
return;
|
||||
}
|
||||
|
||||
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
|
||||
if (m_frameDirty) {
|
||||
if (m_frame.format == VideoPixelFormat::I420) {
|
||||
uploadPlane(m_textures[0], 0, m_frame.stride0, m_frame.height,
|
||||
GL_LUMINANCE, m_frame.plane0, 0);
|
||||
uploadPlane(m_textures[1], 1, m_frame.stride1,
|
||||
(m_frame.height + 1) / 2, GL_LUMINANCE, m_frame.plane1, 1);
|
||||
uploadPlane(m_textures[2], 2, m_frame.stride2,
|
||||
(m_frame.height + 1) / 2, GL_LUMINANCE, m_frame.plane2, 2);
|
||||
} else if (m_frame.format == VideoPixelFormat::NV12) {
|
||||
uploadPlane(m_textures[0], 0, m_frame.stride0, m_frame.height,
|
||||
GL_LUMINANCE, m_frame.plane0, 0);
|
||||
uploadPlane(m_textures[1], 1, m_frame.stride1 / 2,
|
||||
(m_frame.height + 1) / 2, GL_LUMINANCE_ALPHA,
|
||||
m_frame.plane1, 1);
|
||||
} else {
|
||||
uploadPlane(m_textures[0], 0, m_frame.width, m_frame.height,
|
||||
GL_RGBA, m_frame.plane0, 0);
|
||||
}
|
||||
m_frameDirty = false;
|
||||
}
|
||||
|
||||
const GLfloat vertices[] = {
|
||||
-1.0f, -1.0f, 0.0f, 1.0f,
|
||||
1.0f, -1.0f, 1.0f, 1.0f,
|
||||
-1.0f, 1.0f, 0.0f, 0.0f,
|
||||
1.0f, 1.0f, 1.0f, 0.0f
|
||||
};
|
||||
float scaleX = 1.0f;
|
||||
float scaleY = 1.0f;
|
||||
const float frameAspect = static_cast<float>(m_frame.width) / m_frame.height;
|
||||
const float widgetAspect = width() > 0 && height() > 0
|
||||
? static_cast<float>(width()) / height() : frameAspect;
|
||||
if (frameAspect > widgetAspect)
|
||||
scaleY = widgetAspect / frameAspect;
|
||||
else
|
||||
scaleX = frameAspect / widgetAspect;
|
||||
|
||||
m_program->bind();
|
||||
m_program->setUniformValue("contentScale", scaleX, scaleY);
|
||||
m_program->setUniformValue("textureY", 0);
|
||||
m_program->setUniformValue("textureU", 1);
|
||||
m_program->setUniformValue("textureV", 2);
|
||||
m_program->setUniformValue("pixelFormat",
|
||||
m_frame.format == VideoPixelFormat::NV12 ? 1.0f :
|
||||
m_frame.format == VideoPixelFormat::RGBA ? 2.0f : 0.0f);
|
||||
m_program->setUniformValue("scaleY", m_frame.format == VideoPixelFormat::RGBA
|
||||
? 1.0f : static_cast<float>(m_frame.width) / m_frame.stride0);
|
||||
m_program->setUniformValue("scaleU", m_frame.format == VideoPixelFormat::NV12
|
||||
? static_cast<float>((m_frame.width + 1) / 2) / (m_frame.stride1 / 2)
|
||||
: static_cast<float>((m_frame.width + 1) / 2) / m_frame.stride1);
|
||||
m_program->setUniformValue("scaleV", m_frame.format == VideoPixelFormat::I420
|
||||
? static_cast<float>((m_frame.width + 1) / 2) / m_frame.stride2 : 1.0f);
|
||||
const int position = m_program->attributeLocation("position");
|
||||
const int texCoord = m_program->attributeLocation("texCoord");
|
||||
m_program->enableAttributeArray(position);
|
||||
m_program->enableAttributeArray(texCoord);
|
||||
m_program->setAttributeArray(position, GL_FLOAT, vertices, 2, 4 * sizeof(GLfloat));
|
||||
m_program->setAttributeArray(texCoord, GL_FLOAT, vertices + 2, 2,
|
||||
4 * sizeof(GLfloat));
|
||||
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
|
||||
m_program->disableAttributeArray(position);
|
||||
m_program->disableAttributeArray(texCoord);
|
||||
m_program->release();
|
||||
}
|
||||
|
||||
void VideoRenderWidget::drawMessage(const QString &message)
|
||||
{
|
||||
if (message.isEmpty())
|
||||
return;
|
||||
QPainter painter(this);
|
||||
painter.setPen(QColor(QStringLiteral("#8d98a5")));
|
||||
painter.drawText(rect(), Qt::AlignCenter | Qt::TextWordWrap, message);
|
||||
}
|
||||
|
||||
void VideoRenderWidget::releaseTextures()
|
||||
{
|
||||
if (m_textures[0]) {
|
||||
glDeleteTextures(3, m_textures);
|
||||
m_textures[0] = m_textures[1] = m_textures[2] = 0;
|
||||
std::fill(m_textureWidths, m_textureWidths + 3, 0);
|
||||
std::fill(m_textureHeights, m_textureHeights + 3, 0);
|
||||
std::fill(m_textureFormats, m_textureFormats + 3, 0);
|
||||
}
|
||||
}
|
||||
m_message.clear();
|
||||
m_frameDirty = true;
|
||||
update();
|
||||
}
|
||||
|
||||
void VideoRenderWidget::setImage(const QImage &image)
|
||||
{
|
||||
if (image.isNull())
|
||||
return;
|
||||
const QImage converted = image.convertToFormat(QImage::Format_RGBA8888);
|
||||
VideoFrame frame;
|
||||
frame.width = converted.width();
|
||||
frame.height = converted.height();
|
||||
frame.format = VideoPixelFormat::RGBA;
|
||||
frame.stride0 = frame.width * 4;
|
||||
frame.plane0.resize(frame.width * frame.height * 4);
|
||||
for (int row = 0; row < frame.height; ++row) {
|
||||
std::memcpy(frame.plane0.data() + row * frame.width * 4,
|
||||
converted.constScanLine(row), static_cast<size_t>(frame.width * 4));
|
||||
}
|
||||
setFrame(frame);
|
||||
}
|
||||
|
||||
void VideoRenderWidget::clearFrame(const QString &message)
|
||||
{
|
||||
m_frame = VideoFrame();
|
||||
m_message = message;
|
||||
m_frameDirty = false;
|
||||
update();
|
||||
}
|
||||
|
||||
void VideoRenderWidget::initializeGL()
|
||||
{
|
||||
initializeOpenGLFunctions();
|
||||
glClearColor(0.055f, 0.067f, 0.078f, 1.0f);
|
||||
glGenTextures(3, m_textures);
|
||||
|
||||
m_program.reset(new QOpenGLShaderProgram);
|
||||
if (!m_program->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSource) ||
|
||||
!m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource) ||
|
||||
!m_program->link()) {
|
||||
m_message = QStringLiteral("OpenGL 视频着色器初始化失败:%1").arg(m_program->log());
|
||||
m_program.reset();
|
||||
return;
|
||||
}
|
||||
m_glReady = true;
|
||||
}
|
||||
|
||||
void VideoRenderWidget::uploadPlane(unsigned int texture, int unit, int width,
|
||||
int height, unsigned int format,
|
||||
const QByteArray &data, int textureIndex)
|
||||
{
|
||||
glActiveTexture(GL_TEXTURE0 + unit);
|
||||
glBindTexture(GL_TEXTURE_2D, texture);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
||||
if (m_textureWidths[textureIndex] != width ||
|
||||
m_textureHeights[textureIndex] != height ||
|
||||
m_textureFormats[textureIndex] != format) {
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, static_cast<int>(format), width, height, 0,
|
||||
format, GL_UNSIGNED_BYTE, data.constData());
|
||||
m_textureWidths[textureIndex] = width;
|
||||
m_textureHeights[textureIndex] = height;
|
||||
m_textureFormats[textureIndex] = format;
|
||||
} else {
|
||||
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format,
|
||||
GL_UNSIGNED_BYTE, data.constData());
|
||||
}
|
||||
}
|
||||
|
||||
void VideoRenderWidget::paintGL()
|
||||
{
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
if (!m_glReady || !m_program || !m_frame.isValid()) {
|
||||
drawMessage(m_message);
|
||||
return;
|
||||
}
|
||||
|
||||
// Qt 5.12's ANGLE backend can upload RGBA QImage data with an incorrect
|
||||
// channel layout. Draw still RGBA frames with the CPU painter instead.
|
||||
if (m_frame.format == VideoPixelFormat::RGBA) {
|
||||
const QImage image(reinterpret_cast<const uchar *>(m_frame.plane0.constData()),
|
||||
m_frame.width, m_frame.height, m_frame.stride0,
|
||||
QImage::Format_RGBA8888);
|
||||
QPainter painter(this);
|
||||
painter.fillRect(rect(), QColor(QStringLiteral("#0e1115")));
|
||||
QSize target = image.size();
|
||||
target.scale(size(), Qt::KeepAspectRatio);
|
||||
const QRect destination((width() - target.width()) / 2,
|
||||
(height() - target.height()) / 2,
|
||||
target.width(), target.height());
|
||||
painter.drawImage(destination, image);
|
||||
m_frameDirty = false;
|
||||
return;
|
||||
}
|
||||
|
||||
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
|
||||
if (m_frameDirty) {
|
||||
if (m_frame.format == VideoPixelFormat::I420) {
|
||||
uploadPlane(m_textures[0], 0, m_frame.stride0, m_frame.height,
|
||||
GL_LUMINANCE, m_frame.plane0, 0);
|
||||
uploadPlane(m_textures[1], 1, m_frame.stride1,
|
||||
(m_frame.height + 1) / 2, GL_LUMINANCE, m_frame.plane1, 1);
|
||||
uploadPlane(m_textures[2], 2, m_frame.stride2,
|
||||
(m_frame.height + 1) / 2, GL_LUMINANCE, m_frame.plane2, 2);
|
||||
} else if (m_frame.format == VideoPixelFormat::NV12) {
|
||||
uploadPlane(m_textures[0], 0, m_frame.stride0, m_frame.height,
|
||||
GL_LUMINANCE, m_frame.plane0, 0);
|
||||
uploadPlane(m_textures[1], 1, m_frame.stride1 / 2,
|
||||
(m_frame.height + 1) / 2, GL_LUMINANCE_ALPHA,
|
||||
m_frame.plane1, 1);
|
||||
} else {
|
||||
uploadPlane(m_textures[0], 0, m_frame.width, m_frame.height,
|
||||
GL_RGBA, m_frame.plane0, 0);
|
||||
}
|
||||
m_frameDirty = false;
|
||||
}
|
||||
|
||||
const GLfloat vertices[] = {
|
||||
-1.0f, -1.0f, 0.0f, 1.0f,
|
||||
1.0f, -1.0f, 1.0f, 1.0f,
|
||||
-1.0f, 1.0f, 0.0f, 0.0f,
|
||||
1.0f, 1.0f, 1.0f, 0.0f
|
||||
};
|
||||
float scaleX = 1.0f;
|
||||
float scaleY = 1.0f;
|
||||
const float frameAspect = static_cast<float>(m_frame.width) / m_frame.height;
|
||||
const float widgetAspect = width() > 0 && height() > 0
|
||||
? static_cast<float>(width()) / height() : frameAspect;
|
||||
if (frameAspect > widgetAspect)
|
||||
scaleY = widgetAspect / frameAspect;
|
||||
else
|
||||
scaleX = frameAspect / widgetAspect;
|
||||
|
||||
m_program->bind();
|
||||
m_program->setUniformValue("contentScale", scaleX, scaleY);
|
||||
m_program->setUniformValue("textureY", 0);
|
||||
m_program->setUniformValue("textureU", 1);
|
||||
m_program->setUniformValue("textureV", 2);
|
||||
m_program->setUniformValue("pixelFormat",
|
||||
m_frame.format == VideoPixelFormat::NV12 ? 1.0f :
|
||||
m_frame.format == VideoPixelFormat::RGBA ? 2.0f : 0.0f);
|
||||
m_program->setUniformValue("scaleY", m_frame.format == VideoPixelFormat::RGBA
|
||||
? 1.0f : static_cast<float>(m_frame.width) / m_frame.stride0);
|
||||
m_program->setUniformValue("scaleU", m_frame.format == VideoPixelFormat::NV12
|
||||
? static_cast<float>((m_frame.width + 1) / 2) / (m_frame.stride1 / 2)
|
||||
: static_cast<float>((m_frame.width + 1) / 2) / m_frame.stride1);
|
||||
m_program->setUniformValue("scaleV", m_frame.format == VideoPixelFormat::I420
|
||||
? static_cast<float>((m_frame.width + 1) / 2) / m_frame.stride2 : 1.0f);
|
||||
const int position = m_program->attributeLocation("position");
|
||||
const int texCoord = m_program->attributeLocation("texCoord");
|
||||
m_program->enableAttributeArray(position);
|
||||
m_program->enableAttributeArray(texCoord);
|
||||
m_program->setAttributeArray(position, GL_FLOAT, vertices, 2, 4 * sizeof(GLfloat));
|
||||
m_program->setAttributeArray(texCoord, GL_FLOAT, vertices + 2, 2,
|
||||
4 * sizeof(GLfloat));
|
||||
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
|
||||
m_program->disableAttributeArray(position);
|
||||
m_program->disableAttributeArray(texCoord);
|
||||
m_program->release();
|
||||
}
|
||||
|
||||
void VideoRenderWidget::drawMessage(const QString &message)
|
||||
{
|
||||
if (message.isEmpty())
|
||||
return;
|
||||
QPainter painter(this);
|
||||
painter.setPen(QColor(QStringLiteral("#8d98a5")));
|
||||
painter.drawText(rect(), Qt::AlignCenter | Qt::TextWordWrap, message);
|
||||
}
|
||||
|
||||
void VideoRenderWidget::releaseTextures()
|
||||
{
|
||||
if (m_textures[0]) {
|
||||
glDeleteTextures(3, m_textures);
|
||||
m_textures[0] = m_textures[1] = m_textures[2] = 0;
|
||||
std::fill(m_textureWidths, m_textureWidths + 3, 0);
|
||||
std::fill(m_textureHeights, m_textureHeights + 3, 0);
|
||||
std::fill(m_textureFormats, m_textureFormats + 3, 0);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,47 +1,55 @@
|
||||
#pragma once
|
||||
|
||||
#include "videoframe.h"
|
||||
|
||||
#include <QImage>
|
||||
#include <QOpenGLFunctions>
|
||||
#include <QOpenGLWidget>
|
||||
#include <QString>
|
||||
|
||||
#include <memory>
|
||||
|
||||
class QOpenGLShaderProgram;
|
||||
|
||||
class VideoRenderWidget : public QOpenGLWidget, protected QOpenGLFunctions
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit VideoRenderWidget(QWidget *parent = nullptr);
|
||||
~VideoRenderWidget() override;
|
||||
|
||||
void setFrame(const VideoFrame &frame);
|
||||
void setImage(const QImage &image);
|
||||
void clearFrame(const QString &message = QStringLiteral("暂无画面"));
|
||||
#pragma once
|
||||
|
||||
#include "videoframe.h"
|
||||
|
||||
#include <QImage>
|
||||
#include <QOpenGLFunctions>
|
||||
#include <QOpenGLWidget>
|
||||
#include <QString>
|
||||
|
||||
#include <memory>
|
||||
|
||||
class QOpenGLShaderProgram;
|
||||
|
||||
class VideoRenderWidget : public QOpenGLWidget, protected QOpenGLFunctions
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit VideoRenderWidget(QWidget *parent = nullptr);
|
||||
~VideoRenderWidget() override;
|
||||
|
||||
void setFrame(const VideoFrame &frame);
|
||||
void setImage(const QImage &image);
|
||||
void clearFrame(const QString &message = QStringLiteral("暂无画面"));
|
||||
bool hasFrame() const { return m_frame.isValid(); }
|
||||
|
||||
protected:
|
||||
void initializeGL() override;
|
||||
// Opt-in for calibration panels; other video pages keep their layout.
|
||||
void setFrameAspectLayoutEnabled(bool enabled);
|
||||
int heightForWidth(int width) const override;
|
||||
QSize sizeHint() const override;
|
||||
|
||||
protected:
|
||||
void initializeGL() override;
|
||||
void paintGL() override;
|
||||
|
||||
private:
|
||||
void releaseTextures();
|
||||
void uploadPlane(unsigned int texture, int unit, int width, int height,
|
||||
unsigned int format, const QByteArray &data,
|
||||
int textureIndex);
|
||||
void resizeEvent(QResizeEvent *event) override;
|
||||
|
||||
private:
|
||||
void releaseTextures();
|
||||
void uploadPlane(unsigned int texture, int unit, int width, int height,
|
||||
unsigned int format, const QByteArray &data,
|
||||
int textureIndex);
|
||||
void drawMessage(const QString &message);
|
||||
|
||||
std::unique_ptr<QOpenGLShaderProgram> m_program;
|
||||
VideoFrame m_frame;
|
||||
QString m_message = QStringLiteral("暂无画面");
|
||||
unsigned int m_textures[3] = {0, 0, 0};
|
||||
int m_textureWidths[3] = {0, 0, 0};
|
||||
int m_textureHeights[3] = {0, 0, 0};
|
||||
unsigned int m_textureFormats[3] = {0, 0, 0};
|
||||
bool m_frameDirty = false;
|
||||
bool m_glReady = false;
|
||||
};
|
||||
void updateAspectHeight();
|
||||
bool m_frameAspectLayout = false;
|
||||
QSize m_layoutFrameSize{640, 480}; // Placeholder until the first camera frame.
|
||||
|
||||
std::unique_ptr<QOpenGLShaderProgram> m_program;
|
||||
VideoFrame m_frame;
|
||||
QString m_message = QStringLiteral("暂无画面");
|
||||
unsigned int m_textures[3] = {0, 0, 0};
|
||||
int m_textureWidths[3] = {0, 0, 0};
|
||||
int m_textureHeights[3] = {0, 0, 0};
|
||||
unsigned int m_textureFormats[3] = {0, 0, 0};
|
||||
bool m_frameDirty = false;
|
||||
bool m_glReady = false;
|
||||
};
|
||||
|
||||
Loading…
Reference in New Issue
Block a user