ScriptReporter.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project
  3. *
  4. * SPDX-License-Identifier: Apache-2.0 OR MIT
  5. *
  6. */
  7. #include <Automation/ScriptReporter.h>
  8. #include <Utils/Utils.h>
  9. #include <imgui/imgui.h>
  10. #include <Atom/RHI/Factory.h>
  11. #include <AzFramework/API/ApplicationAPI.h>
  12. #include <AzFramework/StringFunc/StringFunc.h>
  13. #include <AzFramework/IO/LocalFileIO.h>
  14. #include <AzCore/IO/SystemFile.h>
  15. #include <AzCore/Utils/Utils.h>
  16. namespace AtomSampleViewer
  17. {
  18. // Must match ScriptReporter::DisplayOption Enum
  19. static const char* DiplayOptions[] =
  20. {
  21. "All Results", "Warnings & Errors", "Errors Only",
  22. };
  23. namespace ScreenshotPaths
  24. {
  25. AZStd::string GetScreenshotsFolder(bool resolvePath)
  26. {
  27. AZStd::string path = "@user@/scripts/screenshots/";
  28. if (resolvePath)
  29. {
  30. path = Utils::ResolvePath(path);
  31. }
  32. return path;
  33. }
  34. AZStd::string GetLocalBaselineFolder(bool resolvePath)
  35. {
  36. AZStd::string path = AZStd::string::format("@user@/scripts/screenshotslocalbaseline/%s", AZ::RHI::Factory::Get().GetName().GetCStr());
  37. if (resolvePath)
  38. {
  39. path = Utils::ResolvePath(path);
  40. }
  41. return path;
  42. }
  43. AZStd::string GetOfficialBaselineFolder(bool resolvePath)
  44. {
  45. AZStd::string path = "scripts/expectedscreenshots/";
  46. if (resolvePath)
  47. {
  48. path = Utils::ResolvePath(path);
  49. }
  50. return path;
  51. }
  52. AZStd::string GetLocalBaseline(const AZStd::string& forScreenshotFile)
  53. {
  54. AZStd::string localBaselineFolder = GetLocalBaselineFolder(false);
  55. AzFramework::StringFunc::Replace(localBaselineFolder, "@user@/", "");
  56. AZStd::string newPath = forScreenshotFile;
  57. if (!AzFramework::StringFunc::Replace(newPath, "scripts/screenshots", localBaselineFolder.c_str()))
  58. {
  59. newPath = "";
  60. }
  61. return newPath;
  62. }
  63. AZStd::string GetOfficialBaseline(const AZStd::string& forScreenshotFile)
  64. {
  65. AZStd::string path = forScreenshotFile;
  66. const AZStd::string userPath = Utils::ResolvePath("@user@");
  67. // make the path relative to the user folder
  68. if (!AzFramework::StringFunc::Replace(path, userPath.c_str(), ""))
  69. {
  70. return "";
  71. }
  72. // After replacing "screenshots" with "expectedscreenshots", the path should be a valid asset path, relative to asset root.
  73. if (!AzFramework::StringFunc::Replace(path, "scripts/screenshots", "scripts/expectedscreenshots"))
  74. {
  75. return "";
  76. }
  77. // Turn it back into a full path
  78. path = Utils::ResolvePath("@devassets@" + path);
  79. return path;
  80. }
  81. }
  82. AZStd::string ScriptReporter::ImageComparisonResult::GetSummaryString() const
  83. {
  84. AZStd::string resultString;
  85. if (m_resultCode == ResultCode::ThresholdExceeded || m_resultCode == ResultCode::Pass)
  86. {
  87. resultString = AZStd::string::format("Diff Score: %f", m_finalDiffScore);
  88. }
  89. else if (m_resultCode == ResultCode::WrongSize)
  90. {
  91. resultString = "Wrong size";
  92. }
  93. else if (m_resultCode == ResultCode::FileNotFound)
  94. {
  95. resultString = "File not found";
  96. }
  97. else if (m_resultCode == ResultCode::FileNotLoaded)
  98. {
  99. resultString = "File load failed";
  100. }
  101. else if (m_resultCode == ResultCode::WrongFormat)
  102. {
  103. resultString = "Format is not supported";
  104. }
  105. else if (m_resultCode == ResultCode::NullImageComparisonToleranceLevel)
  106. {
  107. resultString = "ImageComparisonToleranceLevel not provided";
  108. }
  109. else if (m_resultCode == ResultCode::None)
  110. {
  111. // "None" could be the case if the results dialog is open while the script is running
  112. resultString = "No results";
  113. }
  114. else
  115. {
  116. resultString = "Unhandled Image Comparison ResultCode";
  117. AZ_Assert(false, "Unhandled Image Comparison ResultCode");
  118. }
  119. return resultString;
  120. }
  121. void ScriptReporter::SetAvailableToleranceLevels(const AZStd::vector<ImageComparisonToleranceLevel>& toleranceLevels)
  122. {
  123. m_availableToleranceLevels = toleranceLevels;
  124. }
  125. void ScriptReporter::Reset()
  126. {
  127. m_scriptReports.clear();
  128. m_currentScriptIndexStack.clear();
  129. m_invalidationMessage.clear();
  130. }
  131. void ScriptReporter::SetInvalidationMessage(const AZStd::string& message)
  132. {
  133. m_invalidationMessage = message;
  134. // Reporting this message here instead of when running the script so it won't show up as an error in the ImGui report.
  135. AZ_Error("Automation", m_invalidationMessage.empty(), "Subsequent test results will be invalid because '%s'", m_invalidationMessage.c_str());
  136. }
  137. void ScriptReporter::PushScript(const AZStd::string& scriptAssetPath)
  138. {
  139. if (GetCurrentScriptReport())
  140. {
  141. // Only the current script should listen for Trace Errors
  142. GetCurrentScriptReport()->BusDisconnect();
  143. }
  144. m_currentScriptIndexStack.push_back(m_scriptReports.size());
  145. m_scriptReports.push_back();
  146. m_scriptReports.back().m_scriptAssetPath = scriptAssetPath;
  147. m_scriptReports.back().BusConnect();
  148. }
  149. void ScriptReporter::PopScript()
  150. {
  151. AZ_Assert(GetCurrentScriptReport(), "There is no active script");
  152. if (GetCurrentScriptReport())
  153. {
  154. GetCurrentScriptReport()->BusDisconnect();
  155. m_currentScriptIndexStack.pop_back();
  156. }
  157. if (GetCurrentScriptReport())
  158. {
  159. // Make sure the newly restored current script is listening for Trace Errors
  160. GetCurrentScriptReport()->BusConnect();
  161. }
  162. }
  163. bool ScriptReporter::HasActiveScript() const
  164. {
  165. return !m_currentScriptIndexStack.empty();
  166. }
  167. bool ScriptReporter::AddScreenshotTest(const AZStd::string& path)
  168. {
  169. AZ_Assert(GetCurrentScriptReport(), "There is no active script");
  170. ScreenshotTestInfo screenshotTestInfo;
  171. screenshotTestInfo.m_screenshotFilePath = path;
  172. GetCurrentScriptReport()->m_screenshotTests.push_back(AZStd::move(screenshotTestInfo));
  173. return true;
  174. }
  175. void ScriptReporter::TickImGui()
  176. {
  177. if (m_showReportDialog)
  178. {
  179. ShowReportDialog();
  180. }
  181. }
  182. bool ScriptReporter::HasErrorsAssertsInReport() const
  183. {
  184. for (const ScriptReport& scriptReport : m_scriptReports)
  185. {
  186. if (scriptReport.m_assertCount > 0 || scriptReport.m_generalErrorCount > 0 || scriptReport.m_screenshotErrorCount > 0)
  187. {
  188. return true;
  189. }
  190. }
  191. return false;
  192. }
  193. void ScriptReporter::ShowDiffButton(const char* buttonLabel, const AZStd::string& imagePathA, const AZStd::string& imagePathB)
  194. {
  195. if (ImGui::Button(buttonLabel))
  196. {
  197. if (!Utils::RunDiffTool(imagePathA, imagePathB))
  198. {
  199. m_messageBox.OpenPopupMessage("Can't Diff", "Image diff is not supported on this platform, or the required diff tool is not installed.");
  200. }
  201. }
  202. }
  203. const ImageComparisonToleranceLevel* ScriptReporter::FindBestToleranceLevel(float diffScore, bool filterImperceptibleDiffs) const
  204. {
  205. float thresholdChecked = 0.0f;
  206. bool ignoringMinorDiffs = false;
  207. for (const ImageComparisonToleranceLevel& level : m_availableToleranceLevels)
  208. {
  209. AZ_Assert(level.m_threshold > thresholdChecked || thresholdChecked == 0.0f, "Threshold values are not sequential");
  210. AZ_Assert(level.m_filterImperceptibleDiffs >= ignoringMinorDiffs, "filterImperceptibleDiffs values are not sequential");
  211. thresholdChecked = level.m_threshold;
  212. ignoringMinorDiffs = level.m_filterImperceptibleDiffs;
  213. if (filterImperceptibleDiffs <= level.m_filterImperceptibleDiffs && diffScore <= level.m_threshold)
  214. {
  215. return &level;
  216. }
  217. }
  218. return nullptr;
  219. }
  220. void ScriptReporter::ShowReportDialog()
  221. {
  222. if (ImGui::Begin("Script Results", &m_showReportDialog) && !m_scriptReports.empty())
  223. {
  224. const ImVec4& bgColor = ImGui::GetStyleColorVec4(ImGuiCol_WindowBg);
  225. const bool isDarkStyle = bgColor.x < 0.2 && bgColor.y < 0.2 && bgColor.z < 0.2;
  226. const ImVec4 HighlightPassed = isDarkStyle ? ImVec4{0.5, 1, 0.5, 1} : ImVec4{0, 0.75, 0, 1};
  227. const ImVec4 HighlightFailed = isDarkStyle ? ImVec4{1, 0.5, 0.5, 1} : ImVec4{0.75, 0, 0, 1};
  228. const ImVec4 HighlightWarning = isDarkStyle ? ImVec4{1, 1, 0.5, 1} : ImVec4{0.5, 0.5, 0, 1};
  229. // Local utilities for setting text color
  230. bool colorHasBeenSet = false;
  231. auto highlightTextIf = [&colorHasBeenSet](bool shouldSet, ImVec4 color)
  232. {
  233. if (colorHasBeenSet)
  234. {
  235. ImGui::PopStyleColor();
  236. colorHasBeenSet = false;
  237. }
  238. if (shouldSet)
  239. {
  240. ImGui::PushStyleColor(ImGuiCol_Text, color);
  241. colorHasBeenSet = true;
  242. }
  243. };
  244. auto highlightTextFailedOrWarning = [&](bool isFailed, bool isWarning)
  245. {
  246. if (colorHasBeenSet)
  247. {
  248. ImGui::PopStyleColor();
  249. colorHasBeenSet = false;
  250. }
  251. if (isFailed)
  252. {
  253. ImGui::PushStyleColor(ImGuiCol_Text, HighlightFailed);
  254. colorHasBeenSet = true;
  255. }
  256. else if (isWarning)
  257. {
  258. ImGui::PushStyleColor(ImGuiCol_Text, HighlightWarning);
  259. colorHasBeenSet = true;
  260. }
  261. };
  262. auto resetTextHighlight = [&colorHasBeenSet]()
  263. {
  264. if (colorHasBeenSet)
  265. {
  266. ImGui::PopStyleColor();
  267. colorHasBeenSet = false;
  268. }
  269. };
  270. auto seeConsole = [](uint32_t issueCount, const char* searchString)
  271. {
  272. if (issueCount == 0)
  273. {
  274. return AZStd::string{};
  275. }
  276. else
  277. {
  278. return AZStd::string::format("(See \"%s\" messages in console output)", searchString);
  279. }
  280. };
  281. auto seeBelow = [](uint32_t issueCount)
  282. {
  283. if (issueCount == 0)
  284. {
  285. return AZStd::string{};
  286. }
  287. else
  288. {
  289. return AZStd::string::format("(See below)");
  290. }
  291. };
  292. uint32_t totalAsserts = 0;
  293. uint32_t totalErrors = 0;
  294. uint32_t totalWarnings = 0;
  295. uint32_t totalScreenshotsCount = 0;
  296. uint32_t totalScreenshotsFailed = 0;
  297. uint32_t totalScreenshotWarnings = 0;
  298. for (ScriptReport& scriptReport : m_scriptReports)
  299. {
  300. totalAsserts += scriptReport.m_assertCount;
  301. // We don't include screenshot errors and warnings in these totals because those have their own line-items.
  302. totalErrors += scriptReport.m_generalErrorCount;
  303. totalWarnings += scriptReport.m_generalWarningCount;
  304. totalScreenshotWarnings += scriptReport.m_screenshotWarningCount;
  305. totalScreenshotsFailed += scriptReport.m_screenshotErrorCount;
  306. // This will catch any false-negatives that could occur if the screenshot failure error messages change without also updating ScriptReport::OnPreError()
  307. for (ScreenshotTestInfo& screenshotTest : scriptReport.m_screenshotTests)
  308. {
  309. if (screenshotTest.m_officialComparisonResult.m_resultCode != ImageComparisonResult::ResultCode::Pass &&
  310. screenshotTest.m_officialComparisonResult.m_resultCode != ImageComparisonResult::ResultCode::None)
  311. {
  312. AZ_Assert(scriptReport.m_screenshotErrorCount > 0, "If screenshot comparison failed in any way, m_screenshotErrorCount should be non-zero.");
  313. }
  314. }
  315. }
  316. ImGui::Separator();
  317. if (HasActiveScript())
  318. {
  319. ImGui::PushStyleColor(ImGuiCol_Text, HighlightWarning);
  320. ImGui::Text("Script is running... (_ _)zzz");
  321. ImGui::PopStyleColor();
  322. }
  323. else if (totalErrors > 0 || totalAsserts > 0 || totalScreenshotsFailed > 0)
  324. {
  325. ImGui::PushStyleColor(ImGuiCol_Text, HighlightFailed);
  326. ImGui::Text("(>_<) FAILED (>_<)");
  327. ImGui::PopStyleColor();
  328. }
  329. else
  330. {
  331. if (m_invalidationMessage.empty())
  332. {
  333. ImGui::PushStyleColor(ImGuiCol_Text, HighlightPassed);
  334. ImGui::Text("\\(^_^)/ PASSED \\(^_^)/");
  335. ImGui::PopStyleColor();
  336. }
  337. else
  338. {
  339. ImGui::Text("(-_-) INVALID ... but passed (-_-)");
  340. }
  341. }
  342. if (!m_invalidationMessage.empty())
  343. {
  344. ImGui::Separator();
  345. ImGui::PushStyleColor(ImGuiCol_Text, HighlightFailed);
  346. ImGui::Text("(%s)", m_invalidationMessage.c_str());
  347. ImGui::PopStyleColor();
  348. }
  349. ImGui::Separator();
  350. ImGui::Text("Test Script Count: %zu", m_scriptReports.size());
  351. highlightTextIf(totalAsserts > 0, HighlightFailed);
  352. ImGui::Text("Total Asserts: %u %s", totalAsserts, seeConsole(totalAsserts, "Trace::Assert").c_str());
  353. highlightTextIf(totalErrors > 0, HighlightFailed);
  354. ImGui::Text("Total Errors: %u %s", totalErrors, seeConsole(totalErrors, "Trace::Error").c_str());
  355. highlightTextIf(totalWarnings > 0, HighlightWarning);
  356. ImGui::Text("Total Warnings: %u %s", totalWarnings, seeConsole(totalWarnings, "Trace::Warning").c_str());
  357. resetTextHighlight();
  358. ImGui::Text("Total Screenshot Count: %u", totalScreenshotsCount);
  359. highlightTextIf(totalScreenshotsFailed > 0, HighlightFailed);
  360. ImGui::Text("Total Screenshot Failures: %u %s", totalScreenshotsFailed, seeBelow(totalScreenshotsFailed).c_str());
  361. highlightTextIf(totalScreenshotWarnings > 0, HighlightWarning);
  362. ImGui::Text("Total Screenshot Warnings: %u %s", totalScreenshotWarnings, seeBelow(totalScreenshotWarnings).c_str());
  363. resetTextHighlight();
  364. if (ImGui::Button("Update All Local Baseline Images"))
  365. {
  366. m_messageBox.OpenPopupConfirmation(
  367. "Update All Local Baseline Images",
  368. "This will replace all local baseline images \n"
  369. "with the images captured during this test run. \n"
  370. "Are you sure?",
  371. [this]() {
  372. UpdateAllLocalBaselineImages();
  373. });
  374. }
  375. int displayOption = m_displayOption;
  376. ImGui::Combo("Display", &displayOption, DiplayOptions, AZ_ARRAY_SIZE(DiplayOptions));
  377. m_displayOption = (DisplayOption)displayOption;
  378. ImGui::Checkbox("Force Show 'Update' Buttons", &m_forceShowUpdateButtons);
  379. bool showWarnings = (m_displayOption == DisplayOption::AllResults) || (m_displayOption == DisplayOption::WarningsAndErrors);
  380. bool showAll = (m_displayOption == DisplayOption::AllResults);
  381. ImGui::Separator();
  382. const ImGuiTreeNodeFlags FlagDefaultOpen = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_DefaultOpen;
  383. const ImGuiTreeNodeFlags FlagDefaultClosed = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick;
  384. for (ScriptReport& scriptReport : m_scriptReports)
  385. {
  386. const bool scriptPassed = scriptReport.m_assertCount == 0 && scriptReport.m_generalErrorCount == 0 && scriptReport.m_screenshotErrorCount == 0;
  387. const bool scriptHasWarnings = scriptReport.m_generalWarningCount > 0 || scriptReport.m_screenshotWarningCount > 0;
  388. // Skip if tests passed without warnings and we don't want to show successes
  389. bool skipReport = (scriptPassed && !scriptHasWarnings && !showAll);
  390. // Skip if we only have warnings only and we don't want to show warnings
  391. skipReport = skipReport || (scriptPassed && scriptHasWarnings && !showWarnings);
  392. if (skipReport)
  393. {
  394. continue;
  395. }
  396. ImGuiTreeNodeFlags scriptNodeFlag = scriptPassed ? FlagDefaultClosed : FlagDefaultOpen;
  397. AZStd::string header = AZStd::string::format("%s %s",
  398. scriptPassed ? "PASSED" : "FAILED",
  399. scriptReport.m_scriptAssetPath.c_str()
  400. );
  401. highlightTextFailedOrWarning(!scriptPassed, scriptHasWarnings);
  402. if (ImGui::TreeNodeEx(&scriptReport, scriptNodeFlag, "%s", header.c_str()))
  403. {
  404. resetTextHighlight();
  405. // Number of Asserts
  406. highlightTextIf(scriptReport.m_assertCount > 0, HighlightFailed);
  407. if (showAll || scriptReport.m_assertCount > 0)
  408. {
  409. ImGui::Text("Asserts: %u %s", scriptReport.m_assertCount, seeConsole(scriptReport.m_assertCount, "Trace::Assert").c_str());
  410. }
  411. // Number of Errors
  412. highlightTextIf(scriptReport.m_generalErrorCount > 0, HighlightFailed);
  413. if (showAll || scriptReport.m_generalErrorCount > 0)
  414. {
  415. ImGui::Text("Errors: %u %s", scriptReport.m_generalErrorCount, seeConsole(scriptReport.m_generalErrorCount, "Trace::Error").c_str());
  416. }
  417. // Number of Warnings
  418. highlightTextIf(scriptReport.m_generalWarningCount > 0, HighlightWarning);
  419. if (showAll || (showWarnings && scriptReport.m_generalWarningCount > 0))
  420. {
  421. ImGui::Text("Warnings: %u %s", scriptReport.m_generalWarningCount, seeConsole(scriptReport.m_generalWarningCount, "Trace::Warning").c_str());
  422. }
  423. resetTextHighlight();
  424. // Number of screenshots
  425. if (showAll || scriptReport.m_screenshotErrorCount > 0 || (showWarnings && scriptReport.m_screenshotWarningCount > 0))
  426. {
  427. ImGui::Text("Screenshot Test Count: %zu", scriptReport.m_screenshotTests.size());
  428. }
  429. // Number of screenshot failures
  430. highlightTextIf(scriptReport.m_screenshotErrorCount > 0, HighlightFailed);
  431. if (showAll || scriptReport.m_screenshotErrorCount > 0)
  432. {
  433. ImGui::Text("Screenshot Tests Failed: %u %s", scriptReport.m_screenshotErrorCount, seeBelow(scriptReport.m_screenshotErrorCount).c_str());
  434. }
  435. // Number of screenshot warnings
  436. highlightTextIf(scriptReport.m_screenshotWarningCount > 0, HighlightWarning);
  437. if (showAll || (showWarnings && scriptReport.m_screenshotWarningCount > 0))
  438. {
  439. ImGui::Text("Screenshot Warnings: %u %s", scriptReport.m_screenshotWarningCount, seeBelow(scriptReport.m_screenshotWarningCount).c_str());
  440. }
  441. resetTextHighlight();
  442. for (ScreenshotTestInfo& screenshotResult : scriptReport.m_screenshotTests)
  443. {
  444. const bool screenshotPassed = screenshotResult.m_officialComparisonResult.m_resultCode == ImageComparisonResult::ResultCode::Pass;
  445. const bool localBaselineWarning = screenshotResult.m_localComparisonResult.m_resultCode != ImageComparisonResult::ResultCode::Pass;
  446. // Skip if tests passed without warnings and we don't want to show successes
  447. bool skipScreenshot = (screenshotPassed && !localBaselineWarning && !showAll);
  448. // Skip if we only have warnings only and we don't want to show warnings
  449. skipScreenshot = skipScreenshot || (screenshotPassed && localBaselineWarning && !showWarnings);
  450. if (skipScreenshot)
  451. {
  452. continue;
  453. }
  454. AZStd::string fileName;
  455. AzFramework::StringFunc::Path::GetFullFileName(screenshotResult.m_screenshotFilePath.c_str(), fileName);
  456. AZStd::string headerSummary;
  457. if (!screenshotPassed)
  458. {
  459. headerSummary = "(" + screenshotResult.m_officialComparisonResult.GetSummaryString() + ") ";
  460. }
  461. if (localBaselineWarning)
  462. {
  463. headerSummary += "(Local Baseline Warning)";
  464. }
  465. ImGuiTreeNodeFlags screenshotNodeFlag = FlagDefaultClosed;
  466. AZStd::string screenshotHeader = AZStd::string::format("%s %s %s", screenshotPassed ? "PASSED" : "FAILED", fileName.c_str(), headerSummary.c_str());
  467. highlightTextFailedOrWarning(!screenshotPassed, localBaselineWarning);
  468. if (ImGui::TreeNodeEx(&screenshotResult, screenshotNodeFlag, "%s", screenshotHeader.c_str()))
  469. {
  470. resetTextHighlight();
  471. ImGui::Text(("Screenshot: " + screenshotResult.m_screenshotFilePath).c_str());
  472. ImGui::Spacing();
  473. highlightTextIf(!screenshotPassed, HighlightFailed);
  474. ImGui::Text(("Official Baseline: " + screenshotResult.m_officialBaselineScreenshotFilePath).c_str());
  475. // Official Baseline Result
  476. ImGui::Indent();
  477. {
  478. ImGui::Text(screenshotResult.m_officialComparisonResult.GetSummaryString().c_str());
  479. if (screenshotResult.m_officialComparisonResult.m_resultCode == ImageComparisonResult::ResultCode::ThresholdExceeded ||
  480. screenshotResult.m_officialComparisonResult.m_resultCode == ImageComparisonResult::ResultCode::Pass)
  481. {
  482. ImGui::Text("Used Tolerance: %s", screenshotResult.m_toleranceLevel.ToString().c_str());
  483. const ImageComparisonToleranceLevel* suggestedTolerance = ScriptReporter::FindBestToleranceLevel(
  484. screenshotResult.m_officialComparisonResult.m_finalDiffScore,
  485. screenshotResult.m_toleranceLevel.m_filterImperceptibleDiffs);
  486. if(suggestedTolerance)
  487. {
  488. ImGui::Text("Suggested Tolerance: %s", suggestedTolerance->ToString().c_str());
  489. }
  490. if (screenshotResult.m_toleranceLevel.m_filterImperceptibleDiffs)
  491. {
  492. // This gives an idea of what the tolerance level would be if the imperceptible diffs were not filtered out.
  493. const ImageComparisonToleranceLevel* unfilteredTolerance = ScriptReporter::FindBestToleranceLevel(
  494. screenshotResult.m_officialComparisonResult.m_standardDiffScore, false);
  495. ImGui::Text("(Unfiltered Diff Score: %f%s)",
  496. screenshotResult.m_officialComparisonResult.m_standardDiffScore,
  497. unfilteredTolerance ? AZStd::string::format(" ~ '%s'", unfilteredTolerance->m_name.c_str()).c_str() : "");
  498. }
  499. }
  500. resetTextHighlight();
  501. ImGui::PushID("Official");
  502. ShowDiffButton("View Diff", screenshotResult.m_officialBaselineScreenshotFilePath, screenshotResult.m_screenshotFilePath);
  503. ImGui::PopID();
  504. if ((!screenshotPassed || m_forceShowUpdateButtons) && ImGui::Button("Update##Official"))
  505. {
  506. if (screenshotResult.m_localComparisonResult.m_resultCode == ImageComparisonResult::ResultCode::FileNotFound)
  507. {
  508. UpdateSourceBaselineImage(screenshotResult, true);
  509. }
  510. else
  511. {
  512. m_messageBox.OpenPopupConfirmation(
  513. "Update Official Baseline Image",
  514. "This will replace the official baseline image \n"
  515. "with the image captured during this test run. \n"
  516. "Are you sure?",
  517. // It's important to bind screenshotResult by reference because UpdateOfficialBaselineImage will update it
  518. [this, &screenshotResult]() {
  519. UpdateSourceBaselineImage(screenshotResult, true);
  520. });
  521. }
  522. }
  523. }
  524. ImGui::Unindent();
  525. ImGui::Spacing();
  526. highlightTextIf(localBaselineWarning, HighlightWarning);
  527. ImGui::Text(("Local Baseline: " + screenshotResult.m_localBaselineScreenshotFilePath).c_str());
  528. // Local Baseline Result
  529. ImGui::Indent();
  530. {
  531. ImGui::Text(screenshotResult.m_localComparisonResult.GetSummaryString().c_str());
  532. resetTextHighlight();
  533. ImGui::PushID("Local");
  534. ShowDiffButton("View Diff", screenshotResult.m_localBaselineScreenshotFilePath, screenshotResult.m_screenshotFilePath);
  535. ImGui::PopID();
  536. if ((localBaselineWarning || m_forceShowUpdateButtons) && ImGui::Button("Update##Local"))
  537. {
  538. if (screenshotResult.m_localComparisonResult.m_resultCode == ImageComparisonResult::ResultCode::FileNotFound)
  539. {
  540. UpdateLocalBaselineImage(screenshotResult, true);
  541. }
  542. else
  543. {
  544. m_messageBox.OpenPopupConfirmation(
  545. "Update Local Baseline Image",
  546. "This will replace the local baseline image \n"
  547. "with the image captured during this test run. \n"
  548. "Are you sure?",
  549. // It's important to bind screenshotResult by reference because UpdateLocalBaselineImage will update it
  550. [this, &screenshotResult]() {
  551. UpdateLocalBaselineImage(screenshotResult, true);
  552. });
  553. }
  554. }
  555. }
  556. ImGui::Unindent();
  557. ImGui::Spacing();
  558. resetTextHighlight();
  559. ImGui::TreePop();
  560. }
  561. }
  562. ImGui::TreePop();
  563. }
  564. resetTextHighlight();
  565. }
  566. resetTextHighlight();
  567. // Repeat the m_invalidationMessage at the bottom as well, to make sure the user doesn't miss it.
  568. if (!m_invalidationMessage.empty())
  569. {
  570. ImGui::Separator();
  571. ImGui::PushStyleColor(ImGuiCol_Text, HighlightFailed);
  572. ImGui::Text("(%s)", m_invalidationMessage.c_str());
  573. ImGui::PopStyleColor();
  574. }
  575. }
  576. m_messageBox.TickPopup();
  577. ImGui::End();
  578. }
  579. void ScriptReporter::OpenReportDialog()
  580. {
  581. m_showReportDialog = true;
  582. }
  583. ScriptReporter::ScriptReport* ScriptReporter::GetCurrentScriptReport()
  584. {
  585. if (!m_currentScriptIndexStack.empty())
  586. {
  587. return &m_scriptReports[m_currentScriptIndexStack.back()];
  588. }
  589. else
  590. {
  591. return nullptr;
  592. }
  593. }
  594. void ScriptReporter::ReportScriptError([[maybe_unused]] const AZStd::string& message)
  595. {
  596. AZ_Error("Automation", false, "Script: %s", message.c_str());
  597. }
  598. void ScriptReporter::ReportScriptWarning([[maybe_unused]] const AZStd::string& message)
  599. {
  600. AZ_Warning("Automation", false, "Script: %s", message.c_str());
  601. }
  602. void ScriptReporter::ReportScriptIssue(const AZStd::string& message, TraceLevel traceLevel)
  603. {
  604. switch (traceLevel)
  605. {
  606. case TraceLevel::Error:
  607. ReportScriptError(message);
  608. break;
  609. case TraceLevel::Warning:
  610. ReportScriptWarning(message);
  611. break;
  612. default:
  613. AZ_Assert(false, "Unhandled TraceLevel");
  614. }
  615. }
  616. void ScriptReporter::ReportScreenshotComparisonIssue(const AZStd::string& message, const AZStd::string& expectedImageFilePath, const AZStd::string& actualImageFilePath, TraceLevel traceLevel)
  617. {
  618. AZStd::string fullMessage = AZStd::string::format("%s\n Expected: '%s'\n Actual: '%s'",
  619. message.c_str(),
  620. expectedImageFilePath.c_str(),
  621. actualImageFilePath.c_str());
  622. ReportScriptIssue(fullMessage, traceLevel);
  623. }
  624. bool ScriptReporter::DiffImages(ImageComparisonResult& imageComparisonResult, const AZStd::string& expectedImageFilePath, const AZStd::string& actualImageFilePath, TraceLevel traceLevel)
  625. {
  626. using namespace AZ::Utils;
  627. AZStd::vector<uint8_t> actualImageBuffer;
  628. AZ::RHI::Size actualImageSize;
  629. AZ::RHI::Format actualImageFormat;
  630. if (!LoadPngData(imageComparisonResult, actualImageFilePath, actualImageBuffer, actualImageSize, actualImageFormat, traceLevel))
  631. {
  632. return false;
  633. }
  634. AZStd::vector<uint8_t> expectedImageBuffer;
  635. AZ::RHI::Size expectedImageSize;
  636. AZ::RHI::Format expectedImageFormat;
  637. if (!LoadPngData(imageComparisonResult, expectedImageFilePath, expectedImageBuffer, expectedImageSize, expectedImageFormat, traceLevel))
  638. {
  639. return false;
  640. }
  641. float diffScore = 0.0f;
  642. float filteredDiffScore = 0.0f;
  643. static constexpr float ImperceptibleDiffFilter = 0.01;
  644. ImageDiffResultCode rmsResult = AZ::Utils::CalcImageDiffRms(
  645. actualImageBuffer, actualImageSize, actualImageFormat,
  646. expectedImageBuffer, expectedImageSize, expectedImageFormat,
  647. &diffScore,
  648. &filteredDiffScore,
  649. ImperceptibleDiffFilter);
  650. if (rmsResult != ImageDiffResultCode::Success)
  651. {
  652. if(rmsResult == ImageDiffResultCode::SizeMismatch)
  653. {
  654. ReportScreenshotComparisonIssue(AZStd::string::format("Screenshot check failed. Sizes don't match. Expected %u x %u but was %u x %u.",
  655. expectedImageSize.m_width, expectedImageSize.m_height,
  656. actualImageSize.m_width, actualImageSize.m_height),
  657. expectedImageFilePath,
  658. actualImageFilePath,
  659. traceLevel);
  660. imageComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::WrongSize;
  661. return false;
  662. }
  663. else if (rmsResult == ImageDiffResultCode::FormatMismatch || rmsResult == ImageDiffResultCode::UnsupportedFormat)
  664. {
  665. ReportScreenshotComparisonIssue(AZStd::string::format("Screenshot check failed. Could not compare screenshots due to a format issue."),
  666. expectedImageFilePath,
  667. actualImageFilePath,
  668. traceLevel);
  669. imageComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::WrongFormat;
  670. return false;
  671. }
  672. }
  673. imageComparisonResult.m_standardDiffScore = diffScore;
  674. imageComparisonResult.m_filteredDiffScore = filteredDiffScore;
  675. imageComparisonResult.m_finalDiffScore = diffScore; // Set the final score to the standard score just in case the filtered one is ignored
  676. return true;
  677. }
  678. void ScriptReporter::UpdateAllLocalBaselineImages()
  679. {
  680. int failureCount = 0;
  681. int successCount = 0;
  682. for (ScriptReport& report : m_scriptReports)
  683. {
  684. for (ScreenshotTestInfo& screenshotTest : report.m_screenshotTests)
  685. {
  686. if (UpdateLocalBaselineImage(screenshotTest, false))
  687. {
  688. successCount++;
  689. }
  690. else
  691. {
  692. failureCount++;
  693. }
  694. }
  695. }
  696. ShowUpdateLocalBaselineResult(successCount, failureCount);
  697. }
  698. bool ScriptReporter::UpdateLocalBaselineImage(ScreenshotTestInfo& screenshotTest, bool showResultDialog)
  699. {
  700. const AZStd::string destinationFile = ScreenshotPaths::GetLocalBaseline(screenshotTest.m_screenshotFilePath);
  701. AZStd::string destinationFolder = destinationFile;
  702. AzFramework::StringFunc::Path::StripFullName(destinationFolder);
  703. m_fileIoErrorHandler.BusConnect();
  704. bool failed = false;
  705. if (!AZ::IO::LocalFileIO::GetInstance()->CreatePath(destinationFolder.c_str()))
  706. {
  707. failed = true;
  708. m_fileIoErrorHandler.ReportLatestIOError(AZStd::string::format("Failed to create folder '%s'.", destinationFolder.c_str()));
  709. }
  710. if (!AZ::IO::LocalFileIO::GetInstance()->Copy(screenshotTest.m_screenshotFilePath.c_str(), destinationFile.c_str()))
  711. {
  712. failed = true;
  713. m_fileIoErrorHandler.ReportLatestIOError(AZStd::string::format("Failed to copy '%s' to '%s'.", screenshotTest.m_screenshotFilePath.c_str(), destinationFile.c_str()));
  714. }
  715. m_fileIoErrorHandler.BusDisconnect();
  716. if (!failed)
  717. {
  718. // Since we just replaced the baseline image, we can update this screenshot test result as an exact match.
  719. // This will update the ImGui report dialog by the next frame.
  720. ClearImageComparisonResult(screenshotTest.m_localComparisonResult);
  721. }
  722. if (showResultDialog)
  723. {
  724. int successCount = !failed;
  725. int failureCount = failed;
  726. ShowUpdateLocalBaselineResult(successCount, failureCount);
  727. }
  728. return !failed;
  729. }
  730. bool ScriptReporter::UpdateSourceBaselineImage(ScreenshotTestInfo& screenshotTest, bool showResultDialog)
  731. {
  732. bool success = true;
  733. auto io = AZ::IO::LocalFileIO::GetInstance();
  734. // Get source folder
  735. if (m_officialBaselineSourceFolder.empty())
  736. {
  737. m_officialBaselineSourceFolder = (AZ::IO::FixedMaxPath(AZ::Utils::GetProjectPath()) / "Scripts" / "ExpectedScreenshots").String();
  738. if (!io->Exists(m_officialBaselineSourceFolder.c_str()))
  739. {
  740. AZ_Error("Automation", false, "Could not find source folder '%s'. Copying to source baseline can only be used on dev platforms.", m_officialBaselineSourceFolder.c_str());
  741. m_officialBaselineSourceFolder.clear();
  742. success = false;
  743. }
  744. }
  745. // Get official cache baseline file
  746. const AZStd::string cacheFilePath = ScreenshotPaths::GetOfficialBaseline(screenshotTest.m_screenshotFilePath);
  747. // Divide cache file path into components to we can access the file name and the parent folder
  748. AZStd::fixed_vector<AZ::IO::FixedMaxPathString, 16> reversePathComponents;
  749. auto GatherPathSegments = [&reversePathComponents](AZStd::string_view token)
  750. {
  751. reversePathComponents.emplace_back(token);
  752. };
  753. AzFramework::StringFunc::TokenizeVisitorReverse(cacheFilePath, GatherPathSegments, "/\\");
  754. // Source folder path
  755. // ".../AtomSampleViewer/Scripts/ExpectedScreenshots/" + "MyTestFolder/"
  756. AZStd::string sourceFolderPath = AZStd::string::format("%s\\%s", m_officialBaselineSourceFolder.c_str(), reversePathComponents[1].c_str());
  757. // Source file path
  758. // ".../AtomSampleViewer/Scripts/ExpectedScreenshots/MyTestFolder/" + "MyTest.png"
  759. AZStd::string sourceFilePath = AZStd::string::format("%s\\%s", sourceFolderPath.c_str(), reversePathComponents[0].c_str());
  760. m_fileIoErrorHandler.BusConnect();
  761. // Create parent folder if it doesn't exist
  762. if (success && !io->CreatePath(sourceFolderPath.c_str()))
  763. {
  764. success = false;
  765. m_fileIoErrorHandler.ReportLatestIOError(AZStd::string::format("Failed to create folder '%s'.", sourceFolderPath.c_str()));
  766. }
  767. // Replace source screenshot with new result
  768. if (success && !io->Copy(screenshotTest.m_screenshotFilePath.c_str(), sourceFilePath.c_str()))
  769. {
  770. success = false;
  771. m_fileIoErrorHandler.ReportLatestIOError(AZStd::string::format("Failed to copy '%s' to '%s'.", screenshotTest.m_screenshotFilePath.c_str(), sourceFilePath.c_str()));
  772. }
  773. m_fileIoErrorHandler.BusDisconnect();
  774. if (success)
  775. {
  776. // Since we just replaced the baseline image, we can update this screenshot test result as an exact match.
  777. // This will update the ImGui report dialog by the next frame.
  778. ClearImageComparisonResult(screenshotTest.m_officialComparisonResult);
  779. }
  780. if (showResultDialog)
  781. {
  782. AZStd::string message = "Destination: " + sourceFilePath + "\n";
  783. message += success
  784. ? AZStd::string::format("Copy successful!.\n")
  785. : AZStd::string::format("Copy failed!\n");
  786. m_messageBox.OpenPopupMessage("Update Baseline Image(s) Result", message);
  787. }
  788. return success;
  789. }
  790. void ScriptReporter::ClearImageComparisonResult(ImageComparisonResult& comparisonResult)
  791. {
  792. comparisonResult.m_resultCode = ImageComparisonResult::ResultCode::Pass;
  793. comparisonResult.m_standardDiffScore = 0.0f;
  794. comparisonResult.m_filteredDiffScore = 0.0f;
  795. comparisonResult.m_finalDiffScore = 0.0f;
  796. }
  797. void ScriptReporter::ShowUpdateLocalBaselineResult(int successCount, int failureCount)
  798. {
  799. AZStd::string message;
  800. if (failureCount == 0 && successCount == 0)
  801. {
  802. message = "No screenshots found.";
  803. }
  804. else
  805. {
  806. message = "Destination: " + ScreenshotPaths::GetLocalBaselineFolder(true) + "\n";
  807. if (successCount > 0)
  808. {
  809. message += AZStd::string::format("Successfully copied %d files.\n", successCount);
  810. }
  811. if (failureCount > 0)
  812. {
  813. message += AZStd::string::format("Failed to copy %d files.\n", failureCount);
  814. }
  815. }
  816. m_messageBox.OpenPopupMessage("Update Baseline Image(s) Result", message);
  817. }
  818. void ScriptReporter::CheckLatestScreenshot(const ImageComparisonToleranceLevel* toleranceLevel)
  819. {
  820. AZ_Assert(GetCurrentScriptReport(), "There is no active script");
  821. if (GetCurrentScriptReport() == nullptr || GetCurrentScriptReport()->m_screenshotTests.empty())
  822. {
  823. ReportScriptError("CheckLatestScreenshot() did not find any screenshots to check.");
  824. return;
  825. }
  826. ScreenshotTestInfo& screenshotTestInfo = GetCurrentScriptReport()->m_screenshotTests.back();
  827. if (toleranceLevel == nullptr)
  828. {
  829. screenshotTestInfo.m_officialComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::NullImageComparisonToleranceLevel;
  830. ReportScriptError("Screenshot check failed. No ImageComparisonToleranceLevel provided.");
  831. return;
  832. }
  833. screenshotTestInfo.m_toleranceLevel = *toleranceLevel;
  834. screenshotTestInfo.m_officialBaselineScreenshotFilePath = ScreenshotPaths::GetOfficialBaseline(screenshotTestInfo.m_screenshotFilePath);
  835. if (screenshotTestInfo.m_officialBaselineScreenshotFilePath.empty())
  836. {
  837. ReportScriptError(AZStd::string::format("Screenshot check failed. Could not determine expected screenshot path for '%s'", screenshotTestInfo.m_screenshotFilePath.c_str()));
  838. screenshotTestInfo.m_officialComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::FileNotFound;
  839. }
  840. else
  841. {
  842. bool imagesWereCompared = DiffImages(
  843. screenshotTestInfo.m_officialComparisonResult,
  844. screenshotTestInfo.m_officialBaselineScreenshotFilePath,
  845. screenshotTestInfo.m_screenshotFilePath,
  846. TraceLevel::Error);
  847. if (imagesWereCompared)
  848. {
  849. screenshotTestInfo.m_officialComparisonResult.m_finalDiffScore = toleranceLevel->m_filterImperceptibleDiffs ?
  850. screenshotTestInfo.m_officialComparisonResult.m_filteredDiffScore :
  851. screenshotTestInfo.m_officialComparisonResult.m_standardDiffScore;
  852. if (screenshotTestInfo.m_officialComparisonResult.m_finalDiffScore <= toleranceLevel->m_threshold)
  853. {
  854. screenshotTestInfo.m_officialComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::Pass;
  855. }
  856. else
  857. {
  858. // Be aware there is an automation test script that looks for the "Screenshot check failed. Diff score" string text to report failures.
  859. // If you change this message, be sure to update the associated tests as well located here: "C:/path/to/Lumberyard/AtomSampleViewer/Standalone/PythonTests"
  860. ReportScreenshotComparisonIssue(
  861. AZStd::string::format("Screenshot check failed. Diff score %f exceeds threshold of %f ('%s').",
  862. screenshotTestInfo.m_officialComparisonResult.m_finalDiffScore, toleranceLevel->m_threshold, toleranceLevel->m_name.c_str()),
  863. screenshotTestInfo.m_officialBaselineScreenshotFilePath,
  864. screenshotTestInfo.m_screenshotFilePath,
  865. TraceLevel::Error);
  866. screenshotTestInfo.m_officialComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::ThresholdExceeded;
  867. }
  868. }
  869. }
  870. screenshotTestInfo.m_localBaselineScreenshotFilePath = ScreenshotPaths::GetLocalBaseline(screenshotTestInfo.m_screenshotFilePath);
  871. if (screenshotTestInfo.m_localBaselineScreenshotFilePath.empty())
  872. {
  873. ReportScriptWarning(AZStd::string::format("Screenshot check failed. Could not determine local baseline screenshot path for '%s'", screenshotTestInfo.m_screenshotFilePath.c_str()));
  874. screenshotTestInfo.m_localComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::FileNotFound;
  875. }
  876. else
  877. {
  878. // Local screenshots should be expected match 100% every time, otherwise warnings are reported. This will help developers track and investigate changes,
  879. // for example if they make local changes that impact some unrelated AtomSampleViewer sample in an unexpected way, they will see a warning about this.
  880. bool imagesWereCompared = DiffImages(
  881. screenshotTestInfo.m_localComparisonResult,
  882. screenshotTestInfo.m_localBaselineScreenshotFilePath,
  883. screenshotTestInfo.m_screenshotFilePath,
  884. TraceLevel::Warning);
  885. if (imagesWereCompared)
  886. {
  887. if(screenshotTestInfo.m_localComparisonResult.m_standardDiffScore == 0.0f)
  888. {
  889. screenshotTestInfo.m_localComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::Pass;
  890. }
  891. else
  892. {
  893. ReportScreenshotComparisonIssue(
  894. AZStd::string::format("Screenshot check failed. Screenshot does not match the local baseline; something has changed. Diff score is %f.", screenshotTestInfo.m_localComparisonResult.m_standardDiffScore),
  895. screenshotTestInfo.m_localBaselineScreenshotFilePath,
  896. screenshotTestInfo.m_screenshotFilePath,
  897. TraceLevel::Warning);
  898. screenshotTestInfo.m_localComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::ThresholdExceeded;
  899. }
  900. }
  901. }
  902. }
  903. } // namespace AtomSampleViewer