RobotImporterWidget.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <AzCore/IO/FileIO.h>
  9. #include <AzCore/IO/Path/Path.h>
  10. #include <AzCore/Math/Uuid.h>
  11. #include <AzCore/Utils/Utils.h>
  12. #include "FixURDF/URDFModifications.h"
  13. #include "RobotImporterWidget.h"
  14. #include <QApplication>
  15. #include <QScreen>
  16. #include <QTranslator>
  17. #include <RobotImporter/URDF/URDFPrefabMaker.h>
  18. #include <RobotImporter/URDF/UrdfParser.h>
  19. #include <RobotImporter/Utils/ErrorUtils.h>
  20. #include <RobotImporter/Utils/FilePath.h>
  21. #include <RobotImporter/Utils/RobotImporterUtils.h>
  22. #include <RobotImporter/Utils/SourceAssetsStorage.h>
  23. #include <SdfAssetBuilder/SdfAssetBuilderSettings.h>
  24. namespace ROS2RobotImporter
  25. {
  26. RobotImporterWidget::RobotImporterWidget(QWidget* parent)
  27. : QWizard(parent)
  28. {
  29. m_introPage = new IntroPage(this);
  30. m_fileSelectPage = new FileSelectionPage(this);
  31. m_robotDescriptionPage = new RobotDescriptionPage(this);
  32. m_assetPage = new CheckAssetPage(this);
  33. m_prefabMakerPage = new PrefabMakerPage(this);
  34. m_xacroParamsPage = new XacroParamsPage(this);
  35. m_modifiedUrdfWindow = new ModifiedURDFWindow();
  36. addPage(m_introPage);
  37. addPage(m_fileSelectPage);
  38. addPage(m_xacroParamsPage);
  39. addPage(m_robotDescriptionPage);
  40. addPage(m_assetPage);
  41. addPage(m_prefabMakerPage);
  42. connect(this, &QWizard::currentIdChanged, this, &RobotImporterWidget::onCurrentIdChanged);
  43. connect(m_prefabMakerPage, &QWizardPage::completeChanged, this, &RobotImporterWidget::OnUrdfCreated);
  44. connect(m_prefabMakerPage, &PrefabMakerPage::onCreateButtonPressed, this, &RobotImporterWidget::onCreateButtonPressed);
  45. connect(
  46. m_robotDescriptionPage,
  47. &RobotDescriptionPage::onSaveModifiedUrdfPressed,
  48. this,
  49. &RobotImporterWidget::onSaveModifiedUrdfPressed);
  50. connect(
  51. m_robotDescriptionPage,
  52. &RobotDescriptionPage::onShowModifiedUrdfPressed,
  53. this,
  54. &RobotImporterWidget::onShowModifiedUrdfPressed);
  55. connect(
  56. this,
  57. &QWizard::customButtonClicked,
  58. this,
  59. [this](int id)
  60. {
  61. if (id == PrefabCreationButtonId)
  62. {
  63. this->onCreateButtonPressed();
  64. }
  65. });
  66. void onCreateButtonPressed();
  67. setWindowTitle(tr("Robot Import Wizard"));
  68. connect(
  69. this,
  70. &QDialog::finished,
  71. [this](int id)
  72. {
  73. AZ_Printf("page", "QDialog::finished : %d", id);
  74. parentWidget()->close();
  75. });
  76. m_refreshTimerCheckAssets = new QTimer(this);
  77. m_refreshTimerCheckAssets->setInterval(250);
  78. m_refreshTimerCheckAssets->setSingleShot(false);
  79. connect(m_refreshTimerCheckAssets, &QTimer::timeout, this, &RobotImporterWidget::RefreshTimerElapsed);
  80. }
  81. void RobotImporterWidget::OnUrdfCreated()
  82. {
  83. // hide cancel and back buttons when last page succeed
  84. if (currentPage() == m_prefabMakerPage && m_prefabMakerPage->isComplete())
  85. {
  86. QWizard::button(QWizard::CancelButton)->hide();
  87. QWizard::button(QWizard::BackButton)->hide();
  88. QWizard::button(PrefabCreationButtonId)->hide();
  89. }
  90. }
  91. void RobotImporterWidget::AddModificationWarningsToReportString(QString& report, const UrdfParser::RootObjectOutcome& parsedSdfOutcome)
  92. {
  93. // This is a URDF only path, and therefore the report text does not mention SDF
  94. report += "# " + tr("The URDF was parsed, though results were modified to be compatible with SDFormat") + "\n";
  95. if (!parsedSdfOutcome.m_urdfModifications.missingInertias.empty())
  96. {
  97. report += "## " + tr("Inertial information in the following links is missing, reset to default: ") + "\n";
  98. for (const auto& modifiedTag : parsedSdfOutcome.m_urdfModifications.missingInertias)
  99. {
  100. report += " - " + QString::fromUtf8(modifiedTag.linkName.data(), static_cast<int>(modifiedTag.linkName.size())) + "\n";
  101. }
  102. report += "\n";
  103. }
  104. if (!parsedSdfOutcome.m_urdfModifications.incompleteInertias.empty())
  105. {
  106. report +=
  107. "## " + tr("Inertial information in the following links is incomplete, set default values for listed subtags: ") + "\n";
  108. for (const auto& modifiedTag : parsedSdfOutcome.m_urdfModifications.incompleteInertias)
  109. {
  110. report += " - " + QString::fromUtf8(modifiedTag.linkName.data(), static_cast<int>(modifiedTag.linkName.size())) + ": ";
  111. for (const auto& tag : modifiedTag.missingTags)
  112. {
  113. report += QString::fromUtf8(tag.data(), static_cast<int>(tag.size())) + ", ";
  114. }
  115. report += "\n";
  116. }
  117. report += "\n";
  118. }
  119. if (!parsedSdfOutcome.m_urdfModifications.duplicatedJoints.empty())
  120. {
  121. report += "## " + tr("The following joints were renamed to avoid duplication") + "\n";
  122. for (const auto& modifiedTag : parsedSdfOutcome.m_urdfModifications.duplicatedJoints)
  123. {
  124. report += " - " + QString::fromUtf8(modifiedTag.oldName.data(), static_cast<int>(modifiedTag.oldName.size())) + " -> " +
  125. QString::fromUtf8(modifiedTag.newName.data(), static_cast<int>(modifiedTag.newName.size())) + "\n";
  126. }
  127. }
  128. report += "\n\n# " + tr("💡Please check the modified code and/or save it using the interface below.") + "\n";
  129. m_modifiedUrdfWindow->SetUrdfData(AZStd::move(parsedSdfOutcome.m_modifiedURDFContent));
  130. }
  131. void RobotImporterWidget::OpenUrdf()
  132. {
  133. UrdfParser::RootObjectOutcome parsedSdfOutcome;
  134. QString report;
  135. if (!m_urdfPath.empty())
  136. {
  137. // Read the SDF Settings from PrefabMakerPage
  138. const SdfAssetBuilderSettings& sdfBuilderSettings = m_fileSelectPage->GetSdfAssetBuilderSettings();
  139. // Set the parser config settings for URDF content
  140. sdf::ParserConfig parserConfig = Utils::SDFormat::CreateSdfParserConfigFromSettings(sdfBuilderSettings, m_urdfPath);
  141. if (Utils::IsFileXacro(m_urdfPath))
  142. {
  143. Utils::xacro::ExecutionOutcome outcome =
  144. Utils::xacro::ParseXacro(m_urdfPath.String(), m_params, parserConfig, sdfBuilderSettings);
  145. // Store off the URDF parsing outcome which will be output later in this function
  146. parsedSdfOutcome = AZStd::move(outcome.m_urdfHandle);
  147. if (outcome)
  148. {
  149. report += "# " + tr("XACRO execution succeeded") + "\n";
  150. m_assetPage->ClearAssetsList();
  151. }
  152. else
  153. {
  154. if (outcome.m_succeed)
  155. {
  156. report += "# " + tr("XACRO execution succeeded, but URDF parsing failed") + "\n";
  157. }
  158. else
  159. {
  160. report += "# " + tr("XACRO parsing failed") + "\n";
  161. report += "\n\n## " + tr("Command called") + "\n\n`" + QString::fromUtf8(outcome.m_called.data()) + "`";
  162. report += "\n\n" + tr("Process failed");
  163. report += "\n\n## " + tr("Error output") + "\n\n";
  164. report += "```\n";
  165. if (outcome.m_logErrorOutput.size())
  166. {
  167. report += QString::fromUtf8(outcome.m_logErrorOutput.data(), static_cast<int>(outcome.m_logErrorOutput.size()));
  168. }
  169. else
  170. {
  171. report += tr("(EMPTY)");
  172. }
  173. report += "\n```";
  174. report += "\n\n## " + tr("Standard output") + "\n\n";
  175. report += "```\n";
  176. if (outcome.m_logStandardOutput.size())
  177. {
  178. report +=
  179. QString::fromUtf8(outcome.m_logStandardOutput.data(), static_cast<int>(outcome.m_logStandardOutput.size()));
  180. }
  181. else
  182. {
  183. report += tr("(EMPTY)");
  184. }
  185. report += "\n```";
  186. constexpr bool isSuccess = false;
  187. m_robotDescriptionPage->ReportParsingResult(report, isSuccess);
  188. return;
  189. }
  190. }
  191. }
  192. else if (Utils::IsFileUrdfOrSdf(m_urdfPath))
  193. {
  194. // standard URDF
  195. parsedSdfOutcome = UrdfParser::ParseFromFile(m_urdfPath, parserConfig, sdfBuilderSettings);
  196. }
  197. else
  198. {
  199. AZ_Assert(false, "Unknown file extension : %s \n", m_urdfPath.c_str());
  200. }
  201. AZStd::string log;
  202. const bool urdfParsedSuccess{ parsedSdfOutcome };
  203. bool urdfParsedWithWarnings{ parsedSdfOutcome.UrdfParsedWithModifiedContent() };
  204. if (urdfParsedSuccess)
  205. {
  206. if (urdfParsedWithWarnings)
  207. {
  208. AddModificationWarningsToReportString(report, parsedSdfOutcome);
  209. }
  210. else
  211. {
  212. report += "# " + tr("The URDF/SDF was parsed and opened successfully") + "\n";
  213. }
  214. m_parsedSdf = AZStd::move(parsedSdfOutcome.GetRoot());
  215. m_prefabMaker.reset();
  216. m_assetNames = Utils::GetReferencedAssetFilenames(m_parsedSdf);
  217. m_assetPage->ClearAssetsList();
  218. }
  219. else
  220. {
  221. log = Utils::JoinSdfErrorsToString(parsedSdfOutcome.GetSdfErrors());
  222. report += "# " + tr("The URDF/SDF was not opened") + "\n";
  223. report += "## " + tr("URDF/SDF parser returned following errors:") + "\n\n";
  224. }
  225. if (!log.empty())
  226. {
  227. report += "```\n";
  228. report += QString::fromUtf8(log.data(), int(log.size()));
  229. report += "\n```\n";
  230. AZ_Printf("RobotImporterWidget", "SDF Stream: %s\n", log.c_str());
  231. urdfParsedWithWarnings = true;
  232. }
  233. const auto& messages = parsedSdfOutcome.GetParseMessages();
  234. if (!messages.empty())
  235. {
  236. report += "\n\n";
  237. report += "## " + tr("URDF/SDF parser returned following messages:") + "\n\n";
  238. report += "```\n";
  239. report += QString::fromUtf8(messages.c_str(), int(messages.size()));
  240. report += "\n```\n";
  241. AZ_Printf("RobotImporterWidget", "SDF Stream: %s\n", messages.c_str());
  242. urdfParsedWithWarnings = true;
  243. }
  244. m_robotDescriptionPage->ReportParsingResult(report, urdfParsedSuccess, urdfParsedWithWarnings);
  245. }
  246. }
  247. void RobotImporterWidget::onCurrentIdChanged(int id)
  248. {
  249. AZ_Printf("Wizard", "Wizard at page %d", id);
  250. QWizard::setOption(HavePrefabCreationButton, false);
  251. if (currentPage() == m_assetPage)
  252. {
  253. FillAssetPage();
  254. }
  255. else if (currentPage() == m_prefabMakerPage)
  256. {
  257. FillPrefabMakerPage();
  258. }
  259. else if (currentPage() == m_robotDescriptionPage)
  260. {
  261. AZStd::string urdfName = m_urdfPath.ReplaceExtension("").String();
  262. urdfName.append("_modified.urdf");
  263. m_robotDescriptionPage->SetModifiedUrdfName(urdfName);
  264. }
  265. }
  266. AZ::Outcome<bool> RobotImporterWidget::CheckIfAssetFinished(const AZStd::string& assetGlobalPath)
  267. {
  268. using namespace AzToolsFramework;
  269. using namespace AzToolsFramework::AssetSystem;
  270. AZ::Outcome<AssetSystem::JobInfoContainer> result = AZ::Failure();
  271. AssetSystemJobRequestBus::BroadcastResult(result, &AssetSystemJobRequestBus::Events::GetAssetJobsInfo, assetGlobalPath, true);
  272. if (result)
  273. {
  274. bool allFinished = true;
  275. bool productAssetFailed = false;
  276. JobInfoContainer& allJobs = result.GetValue();
  277. for (const JobInfo& job : allJobs)
  278. {
  279. if (job.m_status == JobStatus::Queued || job.m_status == JobStatus::InProgress)
  280. {
  281. allFinished = false;
  282. }
  283. if (job.m_status == JobStatus::Failed)
  284. {
  285. productAssetFailed = true;
  286. }
  287. }
  288. if (allFinished)
  289. {
  290. return AZ::Success(!productAssetFailed);
  291. }
  292. }
  293. return AZ::Failure();
  294. }
  295. void RobotImporterWidget::FillAssetPage()
  296. {
  297. if (m_assetPage->IsEmpty())
  298. {
  299. QWizard::button(QWizard::NextButton)->setDisabled(true);
  300. AZ::Uuid::FixedString dirSuffix;
  301. if (!m_params.empty())
  302. {
  303. auto paramsUuid = AZ::Uuid::CreateNull();
  304. for (auto& [key, value] : m_params)
  305. {
  306. paramsUuid += AZ::Uuid::CreateName(key);
  307. paramsUuid += AZ::Uuid::CreateName(value);
  308. }
  309. dirSuffix = paramsUuid.ToFixedString();
  310. }
  311. // Read the SDF Settings from PrefabMakerPage
  312. const SdfAssetBuilderSettings& sdfBuilderSettings = m_fileSelectPage->GetSdfAssetBuilderSettings();
  313. if (m_importAssetWithUrdf)
  314. {
  315. m_urdfAssetsMapping =
  316. AZStd::make_shared<Utils::UrdfAssetMap>(Utils::CreateAssetMap(m_assetNames, m_urdfPath.String(), sdfBuilderSettings));
  317. }
  318. else
  319. {
  320. m_urdfAssetsMapping = AZStd::make_shared<Utils::UrdfAssetMap>(
  321. Utils::FindReferencedAssets(m_assetNames, m_urdfPath.String(), sdfBuilderSettings));
  322. for (const auto& [assetPath, assetReferenceType] : m_assetNames)
  323. {
  324. if (m_urdfAssetsMapping->contains(assetPath))
  325. {
  326. const auto& asset = m_urdfAssetsMapping->at(assetPath);
  327. bool visual =
  328. (assetReferenceType & Utils::ReferencedAssetType::VisualMesh) == Utils::ReferencedAssetType::VisualMesh;
  329. bool collider =
  330. (assetReferenceType & Utils::ReferencedAssetType::ColliderMesh) == Utils::ReferencedAssetType::ColliderMesh;
  331. if (visual || collider)
  332. {
  333. Utils::CreateSceneManifest(asset.m_availableAssetInfo.m_sourceAssetGlobalPath, collider, visual);
  334. }
  335. }
  336. }
  337. };
  338. for (auto& [unresolvedFileName, urdfAsset] : *m_urdfAssetsMapping)
  339. {
  340. QString type = tr("Unknown");
  341. bool visual =
  342. (urdfAsset.m_assetReferenceType & Utils::ReferencedAssetType::VisualMesh) == Utils::ReferencedAssetType::VisualMesh;
  343. bool collider =
  344. (urdfAsset.m_assetReferenceType & Utils::ReferencedAssetType::ColliderMesh) == Utils::ReferencedAssetType::ColliderMesh;
  345. bool texture =
  346. (urdfAsset.m_assetReferenceType & Utils::ReferencedAssetType::Texture) == Utils::ReferencedAssetType::Texture;
  347. if (visual && collider)
  348. {
  349. type = tr("Visual and Collider Mesh");
  350. }
  351. else if (visual)
  352. {
  353. type = tr("Visual Mesh");
  354. }
  355. else if (collider)
  356. {
  357. type = tr("Collider Mesh");
  358. }
  359. else if (texture)
  360. {
  361. type = tr("Texture");
  362. }
  363. m_assetPage->ReportAsset(unresolvedFileName.c_str(), urdfAsset, type);
  364. }
  365. m_refreshTimerCheckAssets->start();
  366. if (m_importAssetWithUrdf)
  367. {
  368. m_copyReferencedAssetsThread = AZStd::make_shared<AZStd::thread>(
  369. [this, dirSuffix]()
  370. {
  371. auto destStatus = Utils::PrepareImportedAssetsDest(m_urdfPath.String(), dirSuffix);
  372. if (!destStatus.IsSuccess())
  373. {
  374. AZ_Error("RobotImporterWidget", false, "Failed to create destination folder for imported assets");
  375. QWizard::button(QWizard::NextButton)->setDisabled(false);
  376. return;
  377. }
  378. AZStd::unordered_map<AZ::IO::Path, unsigned int> duplicatedFilenames;
  379. for (auto& [unresolvedFileName, urdfAsset] : *m_urdfAssetsMapping)
  380. {
  381. if (duplicatedFilenames.contains(unresolvedFileName))
  382. {
  383. duplicatedFilenames[unresolvedFileName]++;
  384. }
  385. else
  386. {
  387. duplicatedFilenames[unresolvedFileName] = 0;
  388. }
  389. if (urdfAsset.m_copyStatus == Utils::CopyStatus::Waiting)
  390. {
  391. m_assetPage->OnAssetCopyStatusChanged(
  392. Utils::CopyStatus::Copying, AZStd::string(unresolvedFileName.c_str()), "");
  393. }
  394. auto copyStatus = Utils::CopyReferencedAsset(
  395. unresolvedFileName, destStatus.GetValue(), urdfAsset, duplicatedFilenames[unresolvedFileName]);
  396. m_assetPage->OnAssetCopyStatusChanged(
  397. copyStatus,
  398. AZStd::string(unresolvedFileName.c_str()),
  399. AZStd::string(urdfAsset.m_availableAssetInfo.m_sourceAssetRelativePath.c_str()));
  400. if (copyStatus == Utils::CopyStatus::Copied || copyStatus == Utils::CopyStatus::Exists)
  401. {
  402. m_toProcessAssets.insert(unresolvedFileName);
  403. }
  404. // Check all assets that are ready to be processed
  405. CheckToProcessAssets();
  406. }
  407. Utils::RemoveTmpDir(destStatus.GetValue().importDirectoryTmp);
  408. if (!m_toProcessAssets.empty())
  409. {
  410. m_shouldCheckAssets = true;
  411. }
  412. QWizard::button(QWizard::NextButton)->setDisabled(false);
  413. });
  414. }
  415. else
  416. {
  417. QWizard::button(QWizard::NextButton)->setDisabled(false);
  418. }
  419. }
  420. }
  421. void RobotImporterWidget::RefreshTimerElapsed()
  422. {
  423. if (!m_shouldCheckAssets)
  424. {
  425. return;
  426. }
  427. CheckToProcessAssets();
  428. if (m_toProcessAssets.empty())
  429. {
  430. m_refreshTimerCheckAssets->stop();
  431. }
  432. }
  433. void RobotImporterWidget::CheckToProcessAssets()
  434. {
  435. AZStd::set<AZ::IO::Path> processedAssets;
  436. for (auto& assetToProcessPath : m_toProcessAssets)
  437. {
  438. auto urdfAsset = m_urdfAssetsMapping->find(assetToProcessPath)->second;
  439. auto assetFinishedOutcome = CheckIfAssetFinished(urdfAsset.m_availableAssetInfo.m_sourceAssetGlobalPath.c_str());
  440. if (assetFinishedOutcome.IsSuccess())
  441. {
  442. processedAssets.insert(assetToProcessPath);
  443. if (assetFinishedOutcome.GetValue() == false)
  444. {
  445. m_assetPage->OnAssetProcessStatusChanged(assetToProcessPath.c_str(), urdfAsset, true);
  446. }
  447. else
  448. {
  449. m_assetPage->OnAssetProcessStatusChanged(assetToProcessPath.c_str(), urdfAsset, false);
  450. }
  451. }
  452. }
  453. for (auto& processedAsset : processedAssets)
  454. {
  455. m_toProcessAssets.erase(processedAsset);
  456. }
  457. }
  458. void RobotImporterWidget::FillPrefabMakerPage()
  459. {
  460. // Use the URDF/SDF file name stem the prefab name
  461. AZStd::string robotName = AZStd::string::format("%.*s.prefab", AZ_PATH_ARG(m_urdfPath.Stem()));
  462. m_prefabMakerPage->SetProposedPrefabName(robotName);
  463. QWizard::button(PrefabCreationButtonId)->setText(tr("Create Prefab"));
  464. QWizard::setOption(HavePrefabCreationButton, true);
  465. }
  466. bool RobotImporterWidget::validateCurrentPage()
  467. {
  468. // If SDF file are desired to be brought in via the RobotImporter workflow
  469. // an OpenSdf function would need to be added
  470. if (currentPage() == m_fileSelectPage)
  471. {
  472. m_params.clear();
  473. m_urdfPath = AZStd::string(m_fileSelectPage->getFileName().toUtf8().constData());
  474. if (Utils::IsFileXacro(m_urdfPath))
  475. {
  476. m_params = Utils::xacro::GetParameterFromXacroFile(m_urdfPath.String());
  477. AZ_Printf("RobotImporterWidget", "Xacro has %d arguments\n", m_params.size());
  478. m_xacroParamsPage->SetXacroParameters(m_params);
  479. }
  480. // no need to wait for param page - parse urdf now, nextId will skip unnecessary pages
  481. if (const bool isFileXacroUrdfOrSdf = Utils::IsFileXacroOrUrdfOrSdf(m_urdfPath); m_params.empty() && isFileXacroUrdfOrSdf)
  482. {
  483. OpenUrdf();
  484. }
  485. m_importAssetWithUrdf = m_fileSelectPage->GetSdfAssetBuilderSettings().m_importReferencedMeshFiles;
  486. }
  487. if (currentPage() == m_xacroParamsPage)
  488. {
  489. m_params = m_xacroParamsPage->GetXacroParameters();
  490. if (const bool isFileXacroUrdfOrSdf = Utils::IsFileXacroOrUrdfOrSdf(m_urdfPath); isFileXacroUrdfOrSdf)
  491. {
  492. OpenUrdf();
  493. }
  494. }
  495. if (currentPage() == m_introPage)
  496. {
  497. AZ::EntityId levelEntityId;
  498. AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult(
  499. levelEntityId, &AzToolsFramework::ToolsApplicationRequests::GetCurrentLevelEntityId);
  500. AZ::Entity* levelEntity{ nullptr };
  501. AZ::ComponentApplicationBus::BroadcastResult(levelEntity, &AZ::ComponentApplicationRequests::FindEntity, levelEntityId);
  502. if (!levelEntityId.IsValid() || levelEntity == nullptr)
  503. {
  504. QMessageBox noLevelLoadedMessage;
  505. noLevelLoadedMessage.critical(0, "No level opened", "A level must be opened before using the Robot Importer");
  506. noLevelLoadedMessage.setFixedSize(500, 200);
  507. return false;
  508. }
  509. }
  510. return currentPage()->validatePage();
  511. }
  512. int RobotImporterWidget::nextId() const
  513. {
  514. if (currentPage() == m_assetPage)
  515. {
  516. if (m_copyReferencedAssetsThread)
  517. {
  518. m_copyReferencedAssetsThread->join();
  519. }
  520. }
  521. if ((currentPage() == m_fileSelectPage && m_params.empty()) || currentPage() == m_xacroParamsPage)
  522. {
  523. if (m_robotDescriptionPage->isComplete())
  524. {
  525. if (m_robotDescriptionPage->isWarning())
  526. {
  527. // do not skip robot description page
  528. return m_xacroParamsPage->nextId();
  529. }
  530. if (m_assetNames.empty())
  531. {
  532. // skip two pages when urdf/sdf is parsed without problems, and it has no assets
  533. return m_assetPage->nextId();
  534. }
  535. else
  536. {
  537. // skip one page when urdf/sdf is parsed without problems
  538. return m_robotDescriptionPage->nextId();
  539. }
  540. }
  541. else
  542. {
  543. // XACRO parameters page is already active or can be skipped
  544. return m_xacroParamsPage->nextId();
  545. }
  546. }
  547. return currentPage()->nextId();
  548. }
  549. void RobotImporterWidget::CreatePrefab(AZStd::string prefabName)
  550. {
  551. const AZ::IO::Path prefabPathRelative(AZ::IO::Path("Assets") / "Importer" / prefabName);
  552. const AZ::IO::Path prefabPath(AZ::IO::Path(AZ::Utils::GetProjectPath()) / prefabPathRelative);
  553. bool fileExists = AZ::IO::FileIOBase::GetInstance()->Exists(prefabPath.c_str());
  554. if (CheckCyclicalDependency(prefabPathRelative))
  555. {
  556. m_prefabMakerPage->SetSuccess(false);
  557. return;
  558. }
  559. if (fileExists)
  560. {
  561. QMessageBox msgBox;
  562. msgBox.setText(tr("Prefab with this name already exists"));
  563. msgBox.setInformativeText(tr("Do you want to overwrite existing prefab?"));
  564. msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
  565. msgBox.setDefaultButton(QMessageBox::Cancel);
  566. int ret = msgBox.exec();
  567. if (ret == QMessageBox::Cancel)
  568. {
  569. m_prefabMakerPage->SetSuccess(false);
  570. return;
  571. }
  572. }
  573. const auto& sdfAssetBuilderSettings = m_fileSelectPage->GetSdfAssetBuilderSettings();
  574. const bool useArticulation = sdfAssetBuilderSettings.m_useArticulations;
  575. m_prefabMaker = AZStd::make_unique<URDFPrefabMaker>(
  576. m_urdfPath.String(),
  577. &m_parsedSdf,
  578. prefabPath.String(),
  579. m_urdfAssetsMapping,
  580. useArticulation,
  581. m_prefabMakerPage->getSelectedSpawnPoint());
  582. auto prefabOutcome = m_prefabMaker->CreatePrefabFromUrdfOrSdf();
  583. if (prefabOutcome.IsSuccess())
  584. {
  585. AZStd::string status = m_prefabMaker->GetStatus();
  586. m_prefabMakerPage->ReportProgress(status);
  587. m_prefabMakerPage->SetSuccess(true);
  588. }
  589. else
  590. {
  591. AZStd::string status = "# Failed to create prefab\n";
  592. status += prefabOutcome.GetError() + "\n";
  593. status += m_prefabMaker->GetStatus();
  594. m_prefabMakerPage->ReportProgress(status);
  595. m_prefabMakerPage->SetSuccess(false);
  596. }
  597. }
  598. void RobotImporterWidget::onCreateButtonPressed()
  599. {
  600. CreatePrefab(m_prefabMakerPage->GetPrefabName());
  601. }
  602. void RobotImporterWidget::onSaveModifiedUrdfPressed()
  603. {
  604. const auto filePath = m_robotDescriptionPage->GetModifiedUrdfName();
  605. const auto& streamData = m_modifiedUrdfWindow->GetUrdfData();
  606. AZ::IO::FileIOBase* fileIo = AZ::IO::FileIOBase::GetInstance();
  607. AZ::IO::FixedMaxPathString resolvedPath;
  608. if (fileIo == nullptr || !fileIo->ResolvePath(filePath.c_str(), resolvedPath.data(), resolvedPath.capacity() + 1))
  609. {
  610. resolvedPath = filePath;
  611. }
  612. if (AZ::IO::SystemFile fileHandle; fileHandle.Open(
  613. resolvedPath.c_str(),
  614. AZ::IO::SystemFile::SF_OPEN_CREATE | AZ::IO::SystemFile::SF_OPEN_CREATE_PATH | AZ::IO::SystemFile::SF_OPEN_WRITE_ONLY))
  615. {
  616. [[maybe_unused]] const AZ::IO::SizeType bytesWritten = fileHandle.Write(streamData.data(), streamData.size());
  617. AZ_Warning(
  618. "onSaveModifiedUrdfPressed", (bytesWritten == streamData.size()), "Cannot save the output file %s", filePath.c_str());
  619. }
  620. }
  621. void RobotImporterWidget::onShowModifiedUrdfPressed()
  622. {
  623. m_modifiedUrdfWindow->resize(this->size());
  624. m_modifiedUrdfWindow->show();
  625. }
  626. bool RobotImporterWidget::CheckCyclicalDependency(AZ::IO::Path importedPrefabPath)
  627. {
  628. AzFramework::EntityContextId contextId;
  629. AzFramework::EntityIdContextQueryBus::BroadcastResult(contextId, &AzFramework::EntityIdContextQueryBus::Events::GetOwningContextId);
  630. AZ_Printf("CheckCyclicalDependency", "CheckCyclicalDependency %s\n", importedPrefabPath.Native().c_str());
  631. auto focusInterface = AZ::Interface<AzToolsFramework::Prefab::PrefabFocusInterface>::Get();
  632. if (!focusInterface)
  633. {
  634. ReportError(tr("Imported prefab could not be validated.\nImport aborted."));
  635. return true;
  636. }
  637. auto focusedPrefabInstance = focusInterface->GetFocusedPrefabInstance(contextId);
  638. if (!focusedPrefabInstance)
  639. {
  640. ReportError(tr("Imported prefab could not be validated.\nImport aborted."));
  641. return true;
  642. }
  643. auto focusPrefabFilename = focusedPrefabInstance.value().get().GetTemplateSourcePath();
  644. if (focusPrefabFilename == importedPrefabPath)
  645. {
  646. ReportError(tr(
  647. "Cyclical dependency detected.\nSelected URDF/SDF model is currently being edited. Exit prefab edit mode and try again."));
  648. return true;
  649. }
  650. return false;
  651. }
  652. void RobotImporterWidget::ReportError(const QString& errorMessage)
  653. {
  654. QMessageBox::critical(this, QObject::tr("Error"), errorMessage);
  655. AZ_Error("RobotImporterWidget", false, "%s", errorMessage.toUtf8().constData());
  656. }
  657. } // namespace ROS2RobotImporter