25 #include <MemoryX/gui-plugins/WorkingMemoryGui/ui_WorkingMemoryConfigDialog.h>
30 #include <ArmarXCore/interface/core/Log.h>
32 #include <RobotAPI/interface/core/RobotState.h>
47 #include <VirtualRobot/XML/RobotIO.h>
48 #include <VirtualRobot/XML/ObjectIO.h>
49 #include <VirtualRobot/ManipulationObject.h>
50 #include <VirtualRobot/Grasping/GraspSet.h>
51 #include <VirtualRobot/Grasping/Grasp.h>
52 #include <VirtualRobot/Visualization/CoinVisualization/CoinVisualizationFactory.h>
53 #include <VirtualRobot/Visualization/CoinVisualization/CoinVisualizationNode.h>
54 #include <VirtualRobot/Visualization/CoinVisualization/CoinVisualization.h>
56 #include <SimoxUtility/algorithm/string/string_tools.h>
63 #include <QPushButton>
64 #include <QStringList>
68 #include <QMessageBox>
71 #include <QTreeWidget>
72 #include <QTreeWidgetItem>
74 #include <QDialogButtonBox>
75 #include <QHeaderView>
76 #include <QFileDialog>
80 #include <Inventor/SoDB.h>
81 #include <Inventor/Qt/SoQt.h>
82 #include <Inventor/nodes/SoUnits.h>
87 #include <Inventor/actions/SoWriteAction.h>
88 #include <Inventor/actions/SoToVRML2Action.h>
89 #include <Inventor/VRMLnodes/SoVRMLGroup.h>
90 #include <Inventor/nodes/SoRotation.h>
94 #include <eigen3/Eigen/Core>
107 Q_DECLARE_METATYPE(::memoryx::EntityBasePtr)
113 #define DEFAULT_SETTINGS_PLUGIN_NAME "WorkingMemoryGuiPlugin"
114 #define DEFAULT_SETTINGS_PRIORMEMORY_NAME "PriorKnowledge"
115 #define DEFAULT_SETTINGS_WORKINGMEMORY_NAME "WorkingMemory"
116 #define DEFAULT_SETTINGS_WORKINGMEMORY_UPDATESTOPIC "WorkingMemoryUpdates"
117 #define DEFAULT_SETTINGS_OBJECT_INSTANCES_SEGMENT_NAME "objectInstances"
118 #define DEFAULT_SETTINGS_AGENT_INSTANCES_SEGMENT_NAME "agentInstances"
119 #define DEFAULT_SETTINGS_WORLD_STATE_SEGMENT_NAME "worldState"
120 #define DEFAULT_SETTINGS_ADDITIONAL_PACKAGES "RobotAPI,Armar3,Armar4"
121 #define DEFAULT_SETTINGS_COMMONSTORAGE_NAME "CommonStorage"
122 #define MIN_OBJECT_TRANSPARENCY 0.1f
127 static const int DEFAULT_ROBOT_UPDATE_STEP = 33;
134 eItemAttr = QTreeWidgetItem::UserType + 2,
139 WorkingMemoryGuiPlugin::WorkingMemoryGuiPlugin()
142 addWidget<WorkingMemoryController>();
143 qRegisterMetaType<memoryx::EntityBasePtr>(
"memoryx::EntityBasePtr");
144 qRegisterMetaType<Qt::SortOrder>(
"Qt::SortOrder");
147 WorkingMemoryController::WorkingMemoryController()
151 objectsVisu =
nullptr;
152 agentsVisu =
nullptr;
153 debugLayerVisu =
nullptr;
154 show3DViewer =
false;
155 customToolbar =
nullptr;
157 debugDrawer =
nullptr;
158 sceneConfigDialog =
nullptr;
159 debugDrawerConfigWidget =
nullptr;
161 ui.setupUi(getWidget());
163 visuSetting_transparentExistanceCertatinty = ui.checkBox_existenceCertainty->isChecked();
164 visuSetting_showObjectModels = ui.cbShowObjectModels->isChecked();
166 showObjInstanceUncertainties = ui.cbShowPositionUncertainty->isChecked();
167 getWidget()->setEnabled(
false);
169 ui.tabWidget->removeTab(0);
173 ui.layerWidget->layout()->addWidget(debugLayerControlWidget);
176 WorkingMemoryController::~WorkingMemoryController()
179 ARMARX_INFO <<
"Destructor WorkingMemoryController";
188 std::unique_lock lock(*mutex3D);
192 debugLayerVisu->removeAllChildren();
193 debugLayerVisu->unref();
194 debugLayerVisu =
nullptr;
199 agentsVisu->removeAllChildren();
201 agentsVisu =
nullptr;
206 objectsVisu->removeAllChildren();
207 objectsVisu->unref();
208 objectsVisu =
nullptr;
213 rootVisu->removeAllChildren();
219 if (debugDrawer && debugDrawer->getObjectScheduler())
221 ARMARX_INFO <<
"Removing DebugDrawer component...";
222 debugDrawer->getObjectScheduler()->terminate();
223 ARMARX_INFO <<
"Removing DebugDrawer component...done";
227 void WorkingMemoryController::onInitComponent()
234 rootVisu =
new SoSeparator();
238 std::string debugDrawerComponentName =
"WorkingMemoryDebugDrawer_" + getName();
239 ARMARX_INFO <<
"Creating component " << debugDrawerComponentName;
240 debugDrawer = Component::create<EntityDrawerComponent>(getIceProperties(), debugDrawerComponentName);
244 debugDrawer->setMutex(mutex3D);
252 m->addObject(debugDrawer);
254 debugLayerControlWidget->setEntityDrawer(debugDrawer);
257 std::unique_lock lock(*mutex3D);
258 debugLayerVisu =
new SoSeparator();
259 debugLayerVisu->ref();
260 debugLayerVisu->addChild(debugDrawer->getVisualization());
262 objectsVisu =
new SoSeparator();
265 agentsVisu =
new SoSeparator();
269 rootVisu->addChild(objectsVisu);
270 rootVisu->addChild(agentsVisu);
271 rootVisu->addChild(debugLayerVisu);
273 up << 0.0f, 0.0f, 1.0f;
277 planeVisu = CoinVisualizationFactory::CreatePlaneVisualization(pos, up, 30000.0f, 0);
279 rootVisu->addChild(planeVisu);
282 ARMARX_INFO <<
"WorkingMemory: " << settings_workingMemoryName;
284 usingProxy(settings_workingMemoryName);
285 usingProxy(settings_priorMemoryName);
291 void WorkingMemoryController::onConnectComponent()
294 ARMARX_INFO <<
" Connecting WorkingMemoryController";
298 std::unique_lock lock(mutexEntities);
299 memoryPrx = getProxy<AbstractWorkingMemoryInterfacePrx>(settings_workingMemoryName);
301 ARMARX_DEBUG <<
"Getting object instances segment " << settings_objectInstancesSegmentName;
302 objectInstancesPrx = ObjectInstanceMemorySegmentBasePrx::uncheckedCast(memoryPrx->getSegment(settings_objectInstancesSegmentName));
303 ARMARX_DEBUG <<
"Getting agent instances segment " << settings_agentInstancesSegmentName;
304 agentInstancesProxy = AgentInstancesSegmentBasePrx::uncheckedCast(memoryPrx->getSegment(settings_agentInstancesSegmentName));
305 ARMARX_DEBUG <<
"Getting world state segment " << settings_worldStateSegmentName;
306 worldStateProxy = WorldStateSegmentBasePrx::uncheckedCast(memoryPrx->getSegment(settings_worldStateSegmentName));
311 segmentNames = memoryPrx->getSegmentNames();
313 ARMARX_DEBUG <<
"Getting prior knowledge " << settings_priorMemoryName;
314 priorKnowledgePrx = getProxy<PriorKnowledgeInterfacePrx>(settings_priorMemoryName);
317 classesSegmentPrx = priorKnowledgePrx->getObjectClassesSegment();
318 if (!classesSegmentPrx)
320 ARMARX_ERROR <<
"Classes Segment not found in PriorKnowledge";
325 ARMARX_ERROR <<
"Could not connect to other components (WM/PriorKnowledge/CommonStorage)...";
329 usingTopic(settings_workingMemoryUpdatesTopic);
330 enableMainWidgetAsync(
true);
331 QMetaObject::invokeMethod(
this,
"startTimerInGUIThread");
333 QMetaObject::invokeMethod(
this,
"refetchEntitiesFromMemory");
337 void WorkingMemoryController::onDisconnectComponent()
345 emit signalClearEntities(
"");
346 emit signalRemoveTabs();
348 enableMainWidgetAsync(
false);
349 killTimer(robotUpdateTimerId);
352 std::unique_lock lock(mutexEntities);
358 void WorkingMemoryController::onExitComponent()
361 ARMARX_INFO <<
" Exiting component WorkingMemoryController";
405 std::unique_lock lock(mutexEntities);
406 std::unique_lock lock2(*mutex3D);
412 QPointer<QDialog> WorkingMemoryController::getConfigDialog(QWidget* parent)
429 return qobject_cast<WorkingMemoryConfigDialog*>(dialog);
432 void WorkingMemoryController::processPackages(
const std::string& packages)
435 QString addPacksString = QString::fromStdString(packages);
436 auto addPacks = addPacksString.split(
",", QString::SkipEmptyParts);
438 for (QString& package : addPacks)
446 void WorkingMemoryController::configured()
449 settings_priorMemoryName = dialog->ui->editPriorMemoryName->text().toStdString();
450 settings_workingMemoryName = dialog->ui->editWorkingMemoryName->text().toStdString();
451 settings_objectInstancesSegmentName = dialog->ui->editObjectInstancesSegmentName->text().toStdString();
452 settings_agentInstancesSegmentName = dialog->ui->editAgentInstancesSegmentName->text().toStdString();
453 settings_worldStateSegmentName = dialog->ui->editWorldStateSegmentName->text().toStdString();
454 settings_workingMemoryUpdatesTopic = dialog->ui->editWorkingMemoryUpdatesTopic->text().toStdString();
455 settings_packages = dialog->ui->editAdditionalPackages->text().toStdString();
456 processPackages(settings_packages);
458 this->setInstanceName(dialog->ui->editWorkingMemoryGuiName->text());
461 void WorkingMemoryController::loadSettings(QSettings* settings)
472 visuSetting_transparentExistanceCertatinty = settings->value(
"settings_existenceCertaintyTransparency",
true).toBool();
473 ui.checkBox_existenceCertainty->setChecked(visuSetting_transparentExistanceCertatinty);
475 visuSetting_showObjectModels = settings->value(
"settings_showObjectModels",
true).toBool();
476 ui.cbShowObjectModels->setChecked(visuSetting_showObjectModels);
480 processPackages(settings_packages);
481 this->setInstanceName(instanceN);
483 settings->beginGroup(
"DebugDrawer");
484 if (!settings->allKeys().empty())
486 getSceneConfigDialog();
487 debugDrawerConfigWidget->loadSettings(settings);
489 settings->endGroup();
492 void WorkingMemoryController::saveSettings(QSettings* settings)
495 settings->setValue(
"settings_priorMemoryName", QString::fromStdString(settings_priorMemoryName));
496 settings->setValue(
"settings_workingMemoryName", QString::fromStdString(settings_workingMemoryName));
497 settings->setValue(
"settings_objectInstancesSegmentName", QString::fromStdString(settings_objectInstancesSegmentName));
498 settings->setValue(
"settings_agentInstancesSegmentName", QString::fromStdString(settings_agentInstancesSegmentName));
499 settings->setValue(
"settings_worldStateSegmentName", QString::fromStdString(settings_worldStateSegmentName));
500 settings->setValue(
"settings_workingMemoryUpdatesTopic", QString::fromStdString(settings_workingMemoryUpdatesTopic));
501 settings->setValue(
"settings_packages", QString::fromStdString(settings_packages));
502 settings->setValue(
"instanceName", this->getInstanceName());
503 settings->setValue(
"settings_existenceCertaintyTransparency", ui.checkBox_existenceCertainty->isChecked());
504 settings->setValue(
"settings_showObjectModels", ui.cbShowObjectModels->isChecked());
505 settings->beginGroup(
"DebugDrawer");
506 if (debugDrawerConfigWidget)
508 debugDrawerConfigWidget->saveSettings(settings);
510 settings->endGroup();
513 SoNode* WorkingMemoryController::getScene()
524 QPointer<QDialog> WorkingMemoryController::getSceneConfigDialog(QWidget* parent)
527 if (!sceneConfigDialog)
529 sceneConfigDialog =
new QDialog(parent);
530 QVBoxLayout* verticalLayout =
new QVBoxLayout(sceneConfigDialog);
531 sceneConfigDialog->setLayout(verticalLayout);
534 verticalLayout->addWidget(debugDrawerConfigWidget);
536 QDialogButtonBox* buttonBox =
new QDialogButtonBox(sceneConfigDialog);
537 buttonBox->setOrientation(Qt::Horizontal);
538 buttonBox->setStandardButtons(QDialogButtonBox::Ok);
539 verticalLayout->addWidget(buttonBox);
540 QObject::connect(buttonBox, SIGNAL(accepted()), sceneConfigDialog, SLOT(accept()));
542 else if (!debugDrawerConfigWidget->getDebugDrawer())
544 debugDrawerConfigWidget->setDebugDrawer(debugDrawer);
546 return sceneConfigDialog;
549 void WorkingMemoryController::connectSlots()
555 connect(ui.cbShowObjectModels, SIGNAL(toggled(
bool)),
this, SLOT(setupVisualization()), Qt::QueuedConnection);
556 connect(ui.cbShowPositionUncertainty, SIGNAL(toggled(
bool)),
this, SLOT(setupVisualization()), Qt::QueuedConnection);
557 connect(ui.checkBoxVisuLayers, SIGNAL(toggled(
bool)),
this, SLOT(showVisuLayers(
bool)), Qt::QueuedConnection);
558 connect(ui.rbEllipse, SIGNAL(toggled(
bool)),
this, SLOT(uncertaintyVisuToggled(
bool)), Qt::QueuedConnection);
559 connect(ui.rbHeatMap, SIGNAL(toggled(
bool)),
this, SLOT(uncertaintyVisuToggled(
bool)), Qt::QueuedConnection);
560 connect(ui.rbHeatSurface, SIGNAL(toggled(
bool)),
this, SLOT(uncertaintyVisuToggled(
bool)), Qt::QueuedConnection);
561 connect(ui.spinEllipseRadius, SIGNAL(valueChanged(
double)),
this, SLOT(setupVisualization()), Qt::QueuedConnection);
563 connect(ui.spinDisplayThreshold, SIGNAL(valueChanged(
double)),
this, SLOT(setupVisualization()), Qt::QueuedConnection);
564 connect(ui.spinGridSize, SIGNAL(valueChanged(
int)),
this, SLOT(setupVisualization()), Qt::QueuedConnection);
566 connect(
this, SIGNAL(signalRebuildVisualization()),
this, SLOT(rebuildVisualization()), Qt::QueuedConnection);
567 connect(
this, SIGNAL(entityChanged(memoryx::EntityBasePtr, QString,
bool)),
this, SLOT(updateEntityVisu(memoryx::EntityBasePtr, QString,
bool)), Qt::QueuedConnection);
568 connect(
this, SIGNAL(entityChanged(memoryx::EntityBasePtr, QString,
bool)),
this, SLOT(updateEntityTree(memoryx::EntityBasePtr, QString,
bool)), Qt::QueuedConnection);
570 connect(ui.checkBoxAgents, SIGNAL(toggled(
bool)),
this, SLOT(showAgents(
bool)), Qt::QueuedConnection);
571 connect(ui.checkBox_existenceCertainty, SIGNAL(toggled(
bool)),
this, SLOT(existenceCertaintyToggled(
bool)), Qt::QueuedConnection);
573 connect(ui.checkBoxShowPlane, SIGNAL(toggled(
bool)),
this, SLOT(showPlane(
bool)), Qt::QueuedConnection);
575 connect(
this, SIGNAL(signalAgentsRemoved()),
this, SLOT(agentsRemoved()), Qt::QueuedConnection);
576 connect(
this, SIGNAL(signalObjectRemoved()),
this, SLOT(objectsRemoved()), Qt::QueuedConnection);
577 connect(
this, SIGNAL(signalRefetchEntities()),
this, SLOT(refetchEntitiesFromMemory()), Qt::QueuedConnection);
578 connect(
this, SIGNAL(signalClearEntities(
const std::string&)),
this, SLOT(clearEntitiesVisu(
const std::string&)), Qt::QueuedConnection);
579 connect(
this, SIGNAL(signalRemoveTabs()),
this, SLOT(removeTabs()), Qt::QueuedConnection);
586 QString fi = QFileDialog::getSaveFileName(Q_NULLPTR, tr(
"VRML 2.0 File"), QString(), tr(
"VRML Files (*.wrl)"));
587 std::string
s = std::string(fi.toLatin1());
598 std::unique_lock lock(*mutex3D);
600 SoOutput*
so =
new SoOutput();
601 if (!
so->openFile(
s.c_str()))
603 ARMARX_ERROR <<
"Could not open file " <<
s <<
" for writing." << std::endl;
607 so->setHeaderString(
"#VRML V2.0 utf8");
609 SoGroup* n =
new SoGroup;
611 n->addChild(rootVisu);
612 SoGroup* newVisu = CoinVisualizationFactory::convertSoFileChildren(n);
615 SoToVRML2Action tovrml2;
616 tovrml2.apply(newVisu);
617 SoVRMLGroup* newroot = tovrml2.getVRML2SceneGraph();
619 SoWriteAction wra(
so);
629 void WorkingMemoryController::timerEvent(QTimerEvent*)
632 std::unique_lock lock(mutexEntities);
635 for (
const auto& agent : currentAgents)
637 updateAgent(agent.second);
641 void WorkingMemoryController::treeItemDoubleClicked(QTreeWidgetItem* item,
int column)
648 msgBox.setText(
"Entity selected: id = " + item->text(1));
650 const std::string
id = item->text(1).toStdString();
656 void WorkingMemoryController::refetchEntitiesFromMemory()
664 QObject::disconnect(
this, SIGNAL(entityChanged(memoryx::EntityBasePtr, QString,
bool)),
this, SLOT(updateEntityTree(memoryx::EntityBasePtr, QString,
bool)));
665 QObject::disconnect(
this, SIGNAL(entityChanged(memoryx::EntityBasePtr, QString,
bool)),
this, SLOT(updateEntityVisu(memoryx::EntityBasePtr, QString,
bool)));
667 debugDrawer->clearDebugLayer();
668 debugDrawer->clearLayer(
"ObjectUncertainties");
670 std::string selectedTabName =
"";
672 if (ui.tabWidget->count())
674 selectedTabName = ui.tabWidget->tabText(ui.tabWidget->currentIndex()).toStdString();
679 ARMARX_INFO <<
"Refetching data from WorkingmemoryPrxMemory";
689 for (
const auto& segmentName : segmentNames)
692 ARMARX_INFO <<
"Processing segment " << segmentName;
693 WorkingMemoryEntitySegmentBasePrx segmentPrx = WorkingMemoryEntitySegmentBasePrx::uncheckedCast(memoryPrx->getSegment(segmentName));
695 int index = addTab(segmentName);
697 if (segmentName == selectedTabName)
699 ui.tabWidget->setCurrentIndex(
index);
703 for (
const EntityBasePtr& entityBase : segmentPrx->getAllEntities())
705 ARMARX_INFO <<
"Processing entity " << entityBase->getName();
707 if (createEntity(entityBase, segmentName))
709 updateEntityTree(entityBase, QString(segmentName.c_str()),
false);
710 updateEntityVisu(entityBase, QString(segmentName.c_str()),
false);
722 connect(
this, SIGNAL(entityChanged(memoryx::EntityBasePtr, QString,
bool)),
this, SLOT(updateEntityTree(memoryx::EntityBasePtr, QString,
bool)), Qt::QueuedConnection);
723 connect(
this, SIGNAL(entityChanged(memoryx::EntityBasePtr, QString,
bool)),
this, SLOT(updateEntityVisu(memoryx::EntityBasePtr, QString,
bool)), Qt::QueuedConnection);
726 std::unique_lock lock(*mutex3D);
729 if (ui.checkBoxViewAll->isChecked() &&
main->getViewerWidget())
731 main->getViewerWidget()->viewer->viewAll();
734 emit signalRebuildVisualization();
737 void WorkingMemoryController::startTimerInGUIThread()
740 robotUpdateTimerId = startTimer((DEFAULT_ROBOT_UPDATE_STEP > 0 ? DEFAULT_ROBOT_UPDATE_STEP : 1));
745 void WorkingMemoryController::convertObjectInstanceToGlobalPose(
ObjectInstance& obj)
760 for (
auto& [name, agentDef] : currentAgents)
762 if (agentDef.robot->getName() == pose->agent)
771 ARMARX_WARNING <<
"Agent " << pose->agent <<
" not found in current agents.";
772 obj.
setPose(agentInstancesProxy->convertToWorldPose(pose->agent, obj.
getPose()));
781 bool sync_successful =
true;
783 if (localizationTimestamp != agent->
timestamp)
787 agent->
timestamp = localizationTimestamp;
799 ARMARX_WARNING <<
"Agent " << pose->agent <<
" could not successfully be synced. Try to calculate pose with current agent of agentSegment.";
800 obj.
setPose(agentInstancesProxy->convertToWorldPose(pose->agent, obj.
getPose()));
820 std::unique_lock lock(mutexEntities);
822 ARMARX_DEBUG <<
"Updating object entity " << obj->getName();
827 if (obj->getPosition()->frame != obj->getOrientation()->frame)
829 ARMARX_ERROR <<
"Frame of pos and orientation are not the same of object " << obj->getName()
830 <<
" pos frame: " << obj->getPosition()->frame <<
" ori frame: " << obj->getOrientation()->frame;
833 IceUtil::Time localizationTimestamp = obj->getLocalizationTimestamp();
834 if (lastUpdated.find(obj->getName()) == lastUpdated.end() || localizationTimestamp.toMicroSeconds() > lastUpdated.at(obj->getName()).first)
837 convertObjectInstanceToGlobalPose(*obj);
838 lastUpdated[obj->getName()] = std::make_pair(localizationTimestamp.toMicroSeconds(), obj->getPose());
842 obj->setPose(lastUpdated.at(obj->getName()).second);
845 if (showObjInstanceUncertainties)
848 auto uncertainty = obj->getPositionUncertainty();
852 float variance =
std::min(5000.0f, uncertainty->getVarianceScalar());
853 auto pos = obj->getPosition();
857 debugDrawer->setSphereVisu(
"ObjectUncertainties", obj->getName() + obj->getId() +
"_uncertainty", pos,
858 armarx::DrawColor { std::min(1.0f, variance / 1000), std::max(0.0f, 1 - variance / 1000), 0, 0.2f},
873 ARMARX_DEBUG <<
deactivateSpam(5, obj->getName() + obj->getId()) <<
"Position uncertainty is not shown for " << obj->getName() + obj->getId();
878 ARMARX_ERROR <<
"Execption during update object data...";
882 bool WorkingMemoryController::createEntity(memoryx::EntityBasePtr entity,
const std::string& entityType)
885 const std::string
id = entity->getId();
886 if (entityType == settings_objectInstancesSegmentName || entityType == settings_worldStateSegmentName)
890 std::unique_lock lock(mutexEntities);
891 EntityEntryMap::iterator itEntity = currentEntities.find(
id);
892 found = itEntity != currentEntities.end();
898 ARMARX_INFO <<
"Creating entity instance, id:" <<
id <<
", type " << entityType;
901 EntityPtr e = EntityPtr::dynamicCast(entity);
909 convertObjectInstanceToGlobalPose(*obj);
925 std::unique_lock lock(mutexEntities);
926 currentEntities[id] = o;
934 else if (entityType == settings_agentInstancesSegmentName)
939 std::unique_lock lock(mutexEntities);
940 AgentEntryMap::iterator itAgent = currentAgents.find(
id);
941 found = itAgent != currentAgents.end();
945 ARMARX_INFO <<
"Creating agent entity, id:" <<
id <<
" name: " << entity->getName() <<
", type " << entity->ice_id();
947 if (!agent || !addAgent(agent))
962 void WorkingMemoryController::updateEntityVisu(memoryx::EntityBasePtr entity, QString entityType,
bool isNew)
965 const std::string
id = entity->getId();
966 const std::string typeS = entityType.toStdString();
967 ARMARX_DEBUG <<
"Updating visualization, id:" <<
id <<
", type " << typeS;
969 std::unique_lock lock1(mutexEntities);
970 std::unique_lock lock2(*mutex3D);
973 if (typeS == settings_objectInstancesSegmentName || typeS == settings_worldStateSegmentName)
976 EntityEntryMap::iterator itEntity = currentEntities.find(
id);
978 if (itEntity == currentEntities.end())
980 ARMARX_INFO <<
"Could not find currentEntity entry for object with id = " <<
id <<
", building new entry";
981 if (!createEntity(entity, typeS))
986 itEntity = currentEntities.find(
id);
992 createObjectVisualization(itEntity->second);
997 if (itEntity->second.simoxWrapper)
999 itEntity->second.simoxWrapper->updateFromEntity(entity);
1001 if (visuSetting_transparentExistanceCertatinty)
1004 ARMARX_DEBUG <<
"transparency for object " << itEntity->second.manipObj->getName() <<
":" << itEntity->second.obj->getExistenceCertainty();
1008 if (itEntity->second.cv)
1010 itEntity->second.cv->setTransparency(t);
1018 else if (typeS == settings_agentInstancesSegmentName)
1021 AgentEntryMap::iterator itAgent = currentAgents.find(
id);
1023 if (itAgent == currentAgents.end())
1025 ARMARX_VERBOSE <<
"Could not find currentAgents entry for object with id = " <<
id <<
", loading agent data...";
1026 if (!createEntity(entity, typeS))
1034 createAgentVisualisation(
id);
1044 ARMARX_DEBUG <<
"Updating visualization END, id:" <<
id <<
", type " << typeS;
1055 std::unique_lock lock(*mutex3D);
1059 SoNode*
s =
nullptr;
1063 o.
cv = o.
manipObj->getVisualization<VirtualRobot::CoinVisualization>();
1067 if (visuSetting_transparentExistanceCertatinty)
1074 o.
cv->setTransparency(t);
1076 s = o.
cv->getCoinVisualization();
1083 CoinVisualizationFactoryPtr coinVisFactory(
new CoinVisualizationFactory());
1085 s = std::dynamic_pointer_cast<VirtualRobot::CoinVisualizationNode>(coinVisFactory->createCoordSystem(1.0, &name))->getCoinVisualization();
1088 if (
s && objectsVisu)
1092 if (objectsVisu->findChild(
s) < 0)
1094 objectsVisu->addChild(
s);
1102 if (objWrapper && objWrapper->getManipulationObject())
1104 ARMARX_DEBUG <<
"updateVisualization, object:" << objWrapper->getManipulationObject()->getName();
1116 std::unique_lock lock(*mutex3D);
1119 objWrapper->refreshVisuPose();
1123 void WorkingMemoryController::updateEntityTree(memoryx::EntityBasePtr entity, QString entityType,
bool isNew)
1128 ARMARX_DEBUG <<
"updateEntityTree:" << entity->getName() <<
",type:" << entityType;
1130 EntityPtr obj = EntityPtr::dynamicCast(entity);
1131 std::string entityTypeS = entityType.toStdString();
1133 if (!segmentTabs.count(entityTypeS))
1135 ARMARX_INFO <<
"Segment " << entityTypeS <<
" not yet displayed";
1139 QString objName(obj->getName().c_str());
1140 QString objId = QString::fromStdString(entity->getId());
1142 QList<QTreeWidgetItem*> oldItems;
1143 QTreeWidgetItem* objItem;
1145 QTreeWidget* tree = segmentTabs.at(entityTypeS).tree;
1146 oldItems = tree->findItems(objId, Qt::MatchFixedString, 1);
1148 objItem->setText(0, objName);
1149 objItem->setText(1, objId);
1158 QList<QTreeWidgetItem*> oldAttrs = objItem->takeChildren();
1160 while (!oldAttrs.empty())
1162 delete oldAttrs.takeFirst();
1165 QBrush evenRow(QColor(217, 255, 226));
1166 QBrush oddRow(Qt::white);
1168 memoryx::NameList attrNames = obj->getAttributeNames();
1170 for (
const auto& attrName : attrNames)
1175 attrItem->setText(0, QString::fromStdString(attrName));
1178 auto uncertainty = obj->getAttribute(attrName)->getUncertainty();
1182 QString attrValStr(attrValue->getOutputValueOnly().c_str());
1186 attrValStr += QString(
"\nUncertainty: ") + QString::fromStdString(uncertainty->output());
1189 attrItem->setText(1, attrValStr);
1193 attrItem->setText(1,
"Missing/unsupported value");
1197 QBrush& bgBrush = (i % 2 == 0) ? evenRow : oddRow;
1198 attrItem->setBackground(0, bgBrush);
1199 attrItem->setBackground(1, bgBrush);
1202 ARMARX_DEBUG <<
"updateEntityTree END:" << entity->getName() <<
",type:" << entityType;
1206 void WorkingMemoryController::clearWorkingMemory()
1211 std::unique_lock lock(mutexEntities);
1219 ARMARX_ERROR <<
"Execption during clear working memory...";
1224 void WorkingMemoryController::showVisuLayers(
bool show)
1231 debugDrawer->enableAllLayers();
1235 debugDrawer->disableAllLayers();
1240 void WorkingMemoryController::showAgents(
bool show)
1243 std::unique_lock lock(*mutex3D);
1245 if (!rootVisu || !agentsVisu)
1252 if (rootVisu->findChild(agentsVisu) < 0)
1254 rootVisu->addChild(agentsVisu);
1259 if (rootVisu->findChild(agentsVisu) >= 0)
1261 rootVisu->removeChild(agentsVisu);
1266 void WorkingMemoryController::showPlane(
bool show)
1269 std::unique_lock lock(*mutex3D);
1271 if (!rootVisu || !planeVisu)
1278 if (rootVisu->findChild(planeVisu) < 0)
1280 rootVisu->addChild(planeVisu);
1285 if (rootVisu->findChild(planeVisu) >= 0)
1287 rootVisu->removeChild(planeVisu);
1292 void WorkingMemoryController::clearEntitiesData()
1295 std::unique_lock lock(mutexEntities);
1299 for (
auto& entity : currentEntities)
1301 deletedEntities[entity.first] = entity.second;
1304 currentEntities.clear();
1306 for (
auto& entity : currentAgents)
1308 deletedAgents[entity.first] = entity.second;
1311 currentAgents.clear();
1314 void WorkingMemoryController::clearEntitiesVisu(
const std::string& segmentName)
1317 std::unique_lock lock(mutexEntities);
1320 if (segmentName ==
"" || segmentName == settings_objectInstancesSegmentName)
1324 for (
auto& entity : deletedEntities)
1326 entity.second.manipObj.reset();
1328 if (entity.second.simoxWrapper)
1330 entity.second.simoxWrapper->setEntity(EntityBasePtr());
1331 entity.second.simoxWrapper =
nullptr;
1335 deletedEntities.clear();
1338 if (segmentName ==
"" || segmentName == settings_agentInstancesSegmentName)
1341 deletedAgents.clear();
1344 std::unique_lock lock2(*mutex3D);
1348 agentsVisu->removeAllChildren();
1353 objectsVisu->removeAllChildren();
1359 void WorkingMemoryController::rebuildVisualization()
1362 ARMARX_INFO <<
"Rebuilding complete visualization";
1363 std::unique_lock lock1(mutexEntities);
1364 std::unique_lock lock2(*mutex3D);
1369 objectsVisu->removeAllChildren();
1372 ARMARX_INFO <<
"Rebuilding entity visualization for " << currentEntities.size() <<
" elements";
1374 for (
auto& entity : currentEntities)
1376 ARMARX_VERBOSE <<
"Rebuilding entity visualization for: " << entity.first;
1377 createObjectVisualization(entity.second);
1383 ARMARX_INFO <<
"Rebuilding robot visualization for " << currentAgents.size() <<
" agents";
1384 agentsVisu->removeAllChildren();
1386 for (
const auto& agent : currentAgents)
1388 ARMARX_VERBOSE <<
"Rebuilding robot visualization for: " << agent.first;
1391 createAgentVisualisation(agent.first);
1397 if (
main &&
main->getViewerWidget())
1399 auto l =
main->getViewerWidget()->viewer->getScopedLock();
1401 if (ui.checkBoxViewAll->isChecked() &&
main->getViewerWidget())
1403 main->getViewerWidget()->viewer->viewAll();
1408 void WorkingMemoryController::uncertaintyVisuToggled(
bool isChecked)
1414 setupVisualization();
1418 void WorkingMemoryController::existenceCertaintyToggled(
bool isChecked)
1421 visuSetting_transparentExistanceCertatinty = isChecked;
1422 setupVisualization();
1425 void WorkingMemoryController::setupVisualization()
1428 std::unique_lock lock(mutexEntities);
1430 for (
const auto& entity : currentEntities)
1432 setupEntityVisu(entity.second);
1435 showObjInstanceUncertainties = ui.cbShowPositionUncertainty->isChecked();
1436 visuSetting_showObjectModels = ui.cbShowObjectModels->isChecked();
1438 if (!showObjInstanceUncertainties)
1440 debugDrawer->clearLayer(
"ObjectUncertainties");
1461 std::unique_lock lock(*mutex3D);
1466 ARMARX_VERBOSE <<
"Only ObjectInstances are currently supported";
1470 bool showMainVisu = ui.cbShowObjectModels->isChecked() || !obj->getPositionAttribute()->getUncertainty();
1471 bool showUncertaintyVisu = ui.cbShowPositionUncertainty->isChecked();
1473 if (showUncertaintyVisu)
1478 if (ui.rbEllipse->isChecked())
1480 visuType = EntityWrappers::SimoxObjectWrapper::eEllipse;
1482 else if (ui.rbHeatMap->isChecked())
1484 visuType = EntityWrappers::SimoxObjectWrapper::eHeatMap;
1486 else if (ui.rbHeatSurface->isChecked())
1488 visuType = EntityWrappers::SimoxObjectWrapper::eHeatSurface;
1490 objWrapper.
simoxWrapper->setUncertaintyVisuType(visuType);
1491 objWrapper.
simoxWrapper->setUncertaintyVisuParams(ui.spinEllipseRadius->value(), ui.spinMinVariance->value(),
1492 expf(-ui.spinDisplayThreshold->value()), ui.spinGridSize->value());
1498 objWrapper.
manipObj->setupVisualization(showMainVisu, showUncertaintyVisu);
1502 void WorkingMemoryController::reportEntityCreated(
const std::string& segmentName,
const EntityBasePtr& entityBase,
const Ice::Current&)
1505 std::unique_lock lock(mutexEntities);
1509 ARMARX_VERBOSE <<
"Entity created. Segment:" << segmentName <<
", entity:" << entityBase->getName();
1511 EntityPtr entity = EntityPtr::dynamicCast(entityBase);
1514 QString entityType(segmentName.c_str());
1521 updateObjectData(obj);
1533 ARMARX_VERBOSE <<
"reportEntityCreated: entity type not supported: " << segmentName;
1537 emit entityChanged(entityBase, entityType,
true);
1541 ARMARX_ERROR <<
"Execption during reportEntityCreated...";
1545 void WorkingMemoryController::reportEntityUpdated(
1546 const std::string& segmentName,
const EntityBasePtr& entityBaseOld,
const EntityBasePtr& entityBaseNew,
const Ice::Current&)
1549 (void) entityBaseOld;
1551 ARMARX_DEBUG <<
"entity " << entityBaseNew->getName() <<
" got updated";
1552 std::unique_lock lock(mutexEntities);
1558 EntityPtr entity = EntityPtr::dynamicCast(entityBaseNew);
1560 QString entityId(entity->getId().c_str());
1561 QString entityType(segmentName.c_str());
1568 updateObjectData(obj);
1577 auto it = currentAgents.find(entityId.toStdString());
1579 if (it == currentAgents.end())
1586 emit entityChanged(entityBaseNew, entityType,
false);
1590 ARMARX_ERROR <<
"Exception during reportEntityUpdated...";
1592 ARMARX_DEBUG <<
"entity " << entityBaseNew->getName() <<
" got updated END";
1595 void WorkingMemoryController::reportEntityRemoved(
const std::string& segmentName,
const EntityBasePtr& entity,
const Ice::Current&)
1598 std::unique_lock lock(mutexEntities);
1602 std::string entityId = entity->getId();
1611 auto it = currentEntities.find(entityId);
1613 if (it != currentEntities.end())
1615 ARMARX_INFO <<
"Object removed: id = " << entityId;
1616 deletedEntities[entityId] = currentEntities[entityId];
1617 currentEntities.erase(it);
1618 QMetaObject::invokeMethod(
this,
"objectsRemoved");
1622 ARMARX_INFO <<
"Object not present, id = " << entityId;
1633 auto it = currentAgents.find(entityId);
1635 if (it != currentAgents.end())
1637 ARMARX_INFO <<
"Object removed (agent): id = " << entityId;
1638 deletedAgents[entityId] = currentAgents[entityId];
1639 currentAgents.erase(it);
1640 QMetaObject::invokeMethod(
this,
"agentsRemoved");
1644 ARMARX_INFO <<
"agent not present, id = " << entityId;
1649 QMetaObject::invokeMethod(
this,
"removeEntityInTree", Q_ARG(std::string, entityId), Q_ARG(std::string, segmentName));
1655 ARMARX_ERROR <<
"Execption during reportEntityRemoved...";
1660 void WorkingMemoryController::objectsRemoved()
1663 std::unique_lock lock(mutexEntities);
1664 std::unique_lock lock2(*mutex3D);
1666 for (
auto& e : deletedEntities)
1668 if (objectsVisu && e.second.visualization && objectsVisu->findChild(e.second.visualization) >= 0)
1670 objectsVisu->removeChild(e.second.visualization);
1673 removeEntityInTree(e.first, settings_objectInstancesSegmentName);
1676 deletedEntities.clear();
1679 void WorkingMemoryController::agentsRemoved()
1682 std::unique_lock lock(mutexEntities);
1683 std::unique_lock lock2(*mutex3D);
1686 for (
auto& e : deletedAgents)
1689 if (agentsVisu && e.second.visualization && agentsVisu->findChild(e.second.visualization) >= 0)
1691 agentsVisu->removeChild(e.second.visualization);
1694 removeEntityInTree(e.first, settings_agentInstancesSegmentName);
1697 deletedAgents.clear();
1700 void WorkingMemoryController::reportSnapshotLoaded(
const std::string& segmentName,
const Ice::Current&)
1706 void WorkingMemoryController::reportSnapshotCompletelyLoaded(
const Ice::Current&)
1709 std::unique_lock lock(mutexEntities);
1712 emit signalRefetchEntities();
1716 void WorkingMemoryController::reportMemoryCleared(
const std::string& segmentName,
const Ice::Current&)
1719 std::unique_lock lock(mutexEntities);
1722 ARMARX_INFO <<
"segment " << segmentName <<
" cleared";
1726 if (segmentName == settings_objectInstancesSegmentName)
1729 for (
auto& entity : currentEntities)
1731 deletedEntities[entity.first] = entity.second;
1734 currentEntities.clear();
1737 if (segmentName == settings_agentInstancesSegmentName)
1739 for (
auto& entity : currentAgents)
1741 deletedAgents[entity.first] = entity.second;
1744 currentAgents.clear();
1752 ARMARX_ERROR <<
"Execption during reportMemoryCleared...";
1755 emit signalClearEntities(segmentName);
1761 this->mutex3D = mutex3D;
1765 debugDrawer->setMutex(mutex3D);
1770 void WorkingMemoryController::removeEntityInTree(
const std::string entityId,
const std::string entityType)
1772 ARMARX_INFO <<
"Remove qt element: " << entityId <<
", " << entityType;
1773 QString entityItemId(entityId.c_str());
1774 QTreeWidgetItem* entityItem =
nullptr;
1776 if (segmentTabs.count(entityType))
1778 QList<QTreeWidgetItem*> items = segmentTabs.at(entityType).tree->findItems(entityItemId, Qt::MatchFixedString, 1);
1779 if (items.size() > 0)
1781 entityItem = items.at(0);
1786 ARMARX_WARNING <<
"Undefined entity type: " << entityType << std::endl;
1792 ARMARX_WARNING <<
"Could not determine Qt tree item for entity " << entityId <<
", type " << entityType;
1796 QList<QTreeWidgetItem*> entityAttributes = entityItem->takeChildren();
1798 while (!entityAttributes.empty())
1800 delete entityAttributes.takeFirst();
1807 int WorkingMemoryController::addTab(std::string segmentName)
1812 if (!segmentTabs.count(segmentName))
1816 QWidget* tab =
new QWidget();
1817 QGridLayout* layout =
new QGridLayout();
1818 tab->setLayout(layout);
1821 QTreeWidget* tree =
new QTreeWidget();
1822 tree->setColumnCount(2);
1824 header <<
"Name" <<
"ID/Value";
1825 tree->setHeaderLabels(header);
1826 tree->header()->setDefaultSectionSize(200);
1827 tree->setSortingEnabled(
true);
1828 tree->sortByColumn(0, Qt::SortOrder::AscendingOrder);
1829 index = ui.tabWidget->addTab(tab, QString::fromStdString(segmentName));
1832 layout->addWidget(tree);
1835 segmentTabs.insert(std::pair<std::string, struct SegmentTab>(segmentName, et));
1837 connect(tree, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,
int)),
1838 this, SLOT(treeItemDoubleClicked(QTreeWidgetItem*,
int)));
1842 index = segmentTabs.at(segmentName).tabIndex;
1848 void WorkingMemoryController::removeTab(std::string segmentName)
1851 if (segmentTabs.count(segmentName))
1854 struct SegmentTab tab = segmentTabs.at(segmentName);
1855 QObject::disconnect(tab.
tree, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,
int)),
1856 this, SLOT(treeItemDoubleClicked(QTreeWidgetItem*,
int)));
1858 ui.tabWidget->removeTab(tab.
tabIndex);
1859 tab.
tree->~QTreeWidget();
1860 tab.
tab->~QWidget();
1861 segmentTabs.erase(segmentName);
1865 void WorkingMemoryController::removeTabs()
1869 for (
auto& entry : segmentTabs)
1871 removeTab(entry.first);
1875 QPointer<QWidget> WorkingMemoryController::getCustomTitlebarWidget(QWidget* parent)
1880 if (parent != customToolbar->parent())
1882 customToolbar->setParent(parent);
1885 return customToolbar;
1888 customToolbar =
new QToolBar(parent);
1889 customToolbar->setIconSize(QSize(16, 16));
1891 customToolbar->addAction(QIcon(
":/icons/view-refresh-7.png"),
"Refetch Data",
this, SLOT(refetchEntitiesFromMemory()));
1892 customToolbar->addAction(QIcon(
":/icons/dialog-close.ico"),
"Clear Working Memory",
this, SLOT(clearWorkingMemory()));
1894 return customToolbar;
1897 void WorkingMemoryController::createAgentVisualisation(
const std::string entityId)
1900 std::unique_lock lock(mutexEntities);
1901 if (currentAgents.find(entityId) == currentAgents.end() || !currentAgents[entityId].robot)
1905 currentAgents[entityId].visualization = VirtualRobot::CoinVisualizationFactory::getCoinVisualization(currentAgents[entityId].robot, VirtualRobot::SceneObject::Full,
false);
1907 if (!currentAgents[entityId].visualization)
1909 ARMARX_WARNING <<
"createAgentVisualisation: could not retrieve visualisation from robot " << currentAgents[entityId].robot->getName() <<
"; using ellipse";
1910 currentAgents[entityId].visualization = VirtualRobot::CoinVisualizationFactory::CreateEllipse(0.5, 0.5, 1,
nullptr,
false);
1914 if (agentsVisu && agentsVisu->findChild(currentAgents[entityId].visualization) < 0)
1916 agentsVisu->addChild(currentAgents[entityId].visualization);
1919 updateAgentVisualisation(entityId);
1925 std::unique_lock lock(mutexEntities);
1931 ARMARX_ERROR <<
"addAgent: entity is not of type AgentInstance";
1935 const std::string agentId = agent->getId();
1938 if (!agent->hasAttribute(
"agentFilePath"))
1940 ARMARX_INFO <<
"No filepath available for agent " << agent->getName();
1943 std::string agentFilePath = agent->getAgentFilePath();
1944 ARMARX_INFO <<
"Adding agent " << agent->getName() <<
" agentId:" << agentId <<
", filepath: " << agentFilePath;
1946 if (sharedRobotInterfaceProxy)
1948 ARMARX_INFO << agent->getName() <<
" proxy: " << sharedRobotInterfaceProxy->ice_toString();
1952 ARMARX_INFO << agent->getName() <<
" proxy nullptr";
1956 if (!sharedRobotInterfaceProxy && !agent->getStringifiedSharedRobotInterfaceProxy().empty())
1958 sharedRobotInterfaceProxy = armarx::SharedRobotInterfacePrx::checkedCast(iceCommunicator->stringToProxy(agent->getStringifiedSharedRobotInterfaceProxy()));
1961 catch (std::exception& e)
1963 ARMARX_ERROR <<
"Failed to get robot state proxy for agent " << agent->getName() <<
": " << e.what();
1966 if (sharedRobotInterfaceProxy)
1969 if (sharedRobotInterfaceProxy->getRobotStateComponent())
1971 auto packages = sharedRobotInterfaceProxy->getRobotStateComponent()->getArmarXPackages();
1973 for (
auto& p : packages)
1984 ARMARX_INFO <<
"RobotStateComponent proxy is empty";
1990 ARMARX_ERROR <<
"Could not find robot file " << agentFilePath;
2008 sharedRobotInterfaceProxy->getScaling());
2009 robotDefinition.
robot->setName(sharedRobotInterfaceProxy->getName());
2016 robotDefinition.
robot.reset();
2021 ARMARX_VERBOSE <<
"addAgent: loaded robot from file " << agentFilePath;
2023 robotDefinition.
robotStateComponent = sharedRobotInterfaceProxy->getRobotStateComponent();
2027 currentAgents[agentId] = robotDefinition;
2037 void WorkingMemoryController::updateAgentVisualisation(
const std::string entityId)
2040 std::unique_lock lock(mutexEntities);
2041 auto entity = agentInstancesProxy->getEntityById(entityId);
2042 updateAgentVisualisation(entity);
2045 void WorkingMemoryController::updateAgentVisualisation(
const EntityBasePtr entity)
2048 std::unique_lock lock(*mutex3D);
2052 if (!agent || currentAgents.find(entity->getId()) == currentAgents.end())
2057 auto entityId = entity->getId();
2064 matrix.block(0, 3, 3, 1) = agentPosition->toEigen();
2069 if (agentOrientation)
2071 matrix.block(0, 0, 3, 3) = agentOrientation->toEigen();
2074 auto& agentInstance = currentAgents[entityId];
2075 agentInstance.robot->setGlobalPose(matrix);
2081 std::unique_lock lock(mutexEntities);
2082 std::unique_lock lock2(*mutex3D);
2089 std::map<std::string, float> jointValues;
2090 std::vector<RobotNodePtr> storeNodesRemote;