ScriptReporter.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. /*
  2. * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
  3. * its licensors.
  4. *
  5. * For complete copyright and license terms please see the LICENSE at the root of this
  6. * distribution (the "License"). All use of this software is governed by the License,
  7. * or, if provided, by the license below or the license accompanying this file. Do not
  8. * remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
  9. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. *
  11. */
  12. #pragma once
  13. #include <AzCore/Debug/TraceMessageBus.h>
  14. #include <AzFramework/StringFunc/StringFunc.h>
  15. #include <Atom/Utils/ImageComparison.h>
  16. #include <Automation/ImageComparisonConfig.h>
  17. #include <Utils/ImGuiMessageBox.h>
  18. #include <Utils/FileIOErrorHandler.h>
  19. namespace AtomSampleViewer
  20. {
  21. struct ImageComparisonToleranceLevel;
  22. namespace ScreenshotPaths
  23. {
  24. //! Returns the path to the screenshots capture folder.
  25. //! @resolvePath indicates whether to call ResolvePath() which will produce a full path, or keep the shorter asset folder path.
  26. AZStd::string GetScreenshotsFolder(bool resolvePath);
  27. //! Returns the path to the local baseline folder, which stores copies of screenshots previously taken on this machine.
  28. //! @resolvePath indicates whether to call ResolvePath() which will produce a full path, or keep the shorter asset folder path.
  29. AZStd::string GetLocalBaselineFolder(bool resolvePath);
  30. //! Returns the path to the official baseline folder, which stores copies of expected screenshots saved in source control.
  31. //! @resolvePath indicates whether to call ResolvePath() which will produce a full path, or keep the shorter asset folder path.
  32. AZStd::string GetOfficialBaselineFolder(bool resolvePath);
  33. //! Returns the path to the local baseline image that corresponds to @forScreenshotFile
  34. AZStd::string GetLocalBaseline(const AZStd::string& forScreenshotFile);
  35. //! Returns the path to the official baseline image that corresponds to @forScreenshotFile
  36. AZStd::string GetOfficialBaseline(const AZStd::string& forScreenshotFile);
  37. }
  38. //! Collects data about each script run by the ScriptManager.
  39. //! This includes counting errors, checking screenshots, and providing a final report dialog.
  40. class ScriptReporter
  41. {
  42. public:
  43. //! Set the list of available tolerance levels, so the report can suggest an alternate level that matches the actual results.
  44. void SetAvailableToleranceLevels(const AZStd::vector<ImageComparisonToleranceLevel>& toleranceLevels);
  45. //! Clears all recorded data.
  46. void Reset();
  47. //! Invalidates the final results when displaying a report to the user. This can be used to highlight
  48. //! local changes that were made, and remind the user that these results should not be considered official.
  49. //! Use an empty string to clear the invalidation.
  50. void SetInvalidationMessage(const AZStd::string& message);
  51. //! Indicates that a new script has started processing.
  52. //! Any subsequent errors will be included as part of this script's report.
  53. void PushScript(const AZStd::string& scriptAssetPath);
  54. //! Indicates that the current script has finished executing.
  55. //! Any subsequent errors will be included as part of the prior script's report.
  56. void PopScript();
  57. //! Returns whether there are active processing scripts (i.e. more PushScript() calls than PopScript() calls)
  58. bool HasActiveScript() const;
  59. //! Indicates that a new screenshot is about to be captured.
  60. bool AddScreenshotTest(const AZStd::string& path);
  61. //! Check the latest screenshot using default thresholds.
  62. void CheckLatestScreenshot(const ImageComparisonToleranceLevel* comparisonPreset);
  63. //! Opens the script report dialog.
  64. //! This displays all the collected script reporting data, provides links to tools for analyzing data like
  65. //! viewing screenshot diffs. It can be left open during processing and will update in real-time.
  66. void OpenReportDialog();
  67. //! Called every frame to update the ImGui dialog
  68. void TickImGui();
  69. //! Returns true if there are any errors or asserts in the script report
  70. bool HasErrorsAssertsInReport() const;
  71. struct ImageComparisonResult
  72. {
  73. enum class ResultCode
  74. {
  75. None,
  76. Pass,
  77. FileNotFound,
  78. FileNotLoaded,
  79. WrongSize,
  80. WrongFormat,
  81. NullImageComparisonToleranceLevel,
  82. ThresholdExceeded
  83. };
  84. ResultCode m_resultCode = ResultCode::None;
  85. float m_standardDiffScore = 0.0f;
  86. float m_filteredDiffScore = 0.0f; //!< The diff score after filtering out visually imperceptible differences.
  87. float m_finalDiffScore = 0.0f; //! The diff score that was used for comparison. May be m_diffScore or m_filteredDiffScore.
  88. AZStd::string GetSummaryString() const;
  89. };
  90. //! Records all the information about a screenshot comparison test.
  91. struct ScreenshotTestInfo
  92. {
  93. AZStd::string m_screenshotFilePath;
  94. AZStd::string m_officialBaselineScreenshotFilePath; //!< The path to the official baseline image that is checked into source control
  95. AZStd::string m_localBaselineScreenshotFilePath; //!< The path to a local baseline image that was established by the user
  96. ImageComparisonToleranceLevel m_toleranceLevel; //!< Tolerance for checking against the official baseline image
  97. ImageComparisonResult m_officialComparisonResult; //!< Result of comparing against the official baseline image, for reporting test failure
  98. ImageComparisonResult m_localComparisonResult; //!< Result of comparing against a local baseline, for reporting warnings
  99. };
  100. //! Records all the information about a single test script.
  101. struct ScriptReport : public AZ::Debug::TraceMessageBus::Handler
  102. {
  103. ~ScriptReport()
  104. {
  105. AZ::Debug::TraceMessageBus::Handler::BusDisconnect();
  106. }
  107. bool OnPreAssert(const char* /*fileName*/, int /*line*/, const char* /*func*/, [[maybe_unused]] const char* message) override
  108. {
  109. ++m_assertCount;
  110. return false;
  111. }
  112. bool OnPreError(const char* /*window*/, const char* /*fileName*/, int /*line*/, const char* /*func*/, const char* message) override
  113. {
  114. if (AZStd::string::npos == AzFramework::StringFunc::Find(message, "Screenshot check failed"))
  115. {
  116. ++m_generalErrorCount;
  117. }
  118. else
  119. {
  120. ++m_screenshotErrorCount;
  121. }
  122. return false;
  123. }
  124. bool OnPreWarning(const char* /*window*/, const char* /*fileName*/, int /*line*/, const char* /*func*/, const char* message) override
  125. {
  126. if (AZStd::string::npos == AzFramework::StringFunc::Find(message, "Screenshot does not match the local baseline"))
  127. {
  128. ++m_generalWarningCount;
  129. }
  130. else
  131. {
  132. ++m_screenshotWarningCount;
  133. }
  134. return false;
  135. }
  136. AZStd::string m_scriptAssetPath;
  137. uint32_t m_assertCount = 0;
  138. uint32_t m_generalErrorCount = 0;
  139. uint32_t m_screenshotErrorCount = 0;
  140. uint32_t m_generalWarningCount = 0;
  141. uint32_t m_screenshotWarningCount = 0;
  142. AZStd::vector<ScreenshotTestInfo> m_screenshotTests;
  143. };
  144. const AZStd::vector<ScriptReport>& GetScriptReport() const { return m_scriptReports; }
  145. private:
  146. // Reports a script error using standard formatting that matches ScriptManager
  147. enum class TraceLevel
  148. {
  149. Error,
  150. Warning
  151. };
  152. // Controls which results are shown to the user
  153. // Must match static const char* DiplayOptions in .cpp file
  154. enum DisplayOption : int
  155. {
  156. AllResults,
  157. WarningsAndErrors,
  158. ErrorsOnly
  159. };
  160. static void ReportScriptError(const AZStd::string& message);
  161. static void ReportScriptWarning(const AZStd::string& message);
  162. static void ReportScriptIssue(const AZStd::string& message, TraceLevel traceLevel);
  163. static void ReportScreenshotComparisonIssue(const AZStd::string& message, const AZStd::string& expectedImageFilePath, const AZStd::string& actualImageFilePath, TraceLevel traceLevel);
  164. // Loads image data from a .ppm file.
  165. // @param imageComparisonResult will be set to an error code if the function fails
  166. // @param path the path the .ppm file
  167. // @param buffer will be filled with the raw image data from the .ppm file
  168. // @param size will be set to the image size of the .ppm file
  169. // @param format will be set to the pixel format of the .ppm file
  170. // @return true if the file was loaded successfully
  171. static bool LoadPpmData(ImageComparisonResult& imageComparisonResult, const AZStd::string& path, AZStd::vector<uint8_t>& buffer, AZ::RHI::Size& size, AZ::RHI::Format& format, TraceLevel traceLevel);
  172. // Compares two image files and updates the ImageComparisonResult accordingly.
  173. // Returns false if an error prevented the comparison.
  174. static bool DiffImages(ImageComparisonResult& imageComparisonResult, const AZStd::string& expectedImageFilePath, const AZStd::string& actualImageFilePath, TraceLevel traceLevel);
  175. // Copies all captured screenshots to the local baseline folder. These can be used as an alternative to the central baseline for comparison.
  176. void UpdateAllLocalBaselineImages();
  177. // Copies a single captured screenshot to the local baseline folder. This can be used as an alternative to the central baseline for comparison.
  178. bool UpdateLocalBaselineImage(ScreenshotTestInfo& screenshotTest, bool showResultDialog);
  179. // Copies a single captured screenshot to the official baseline source folder.
  180. bool UpdateSourceBaselineImage(ScreenshotTestInfo& screenshotTest, bool showResultDialog);
  181. // Clears comparison result to passing with no errors or warnings
  182. void ClearImageComparisonResult(ImageComparisonResult& comparisonResult);
  183. // Show a message box to let the user know the results of updating local baseline images
  184. void ShowUpdateLocalBaselineResult(int successCount, int failureCount);
  185. const ImageComparisonToleranceLevel* FindBestToleranceLevel(float diffScore, bool filterImperceptibleDiffs) const;
  186. void ShowReportDialog();
  187. void ShowDiffButton(const char* buttonLabel, const AZStd::string& imagePathA, const AZStd::string& imagePathB);
  188. ScriptReport* GetCurrentScriptReport();
  189. ImGuiMessageBox m_messageBox;
  190. FileIOErrorHandler m_fileIoErrorHandler;
  191. AZStd::vector<ImageComparisonToleranceLevel> m_availableToleranceLevels;
  192. AZStd::string m_invalidationMessage;
  193. AZStd::vector<ScriptReport> m_scriptReports; //< Tracks errors for the current active script
  194. AZStd::vector<size_t> m_currentScriptIndexStack; //< Tracks which of the scripts in m_scriptReports is currently active
  195. bool m_showReportDialog = false;
  196. DisplayOption m_displayOption = DisplayOption::AllResults;
  197. AZStd::string m_officialBaselineSourceFolder; //< Used for updating official baseline screenshots
  198. };
  199. } // namespace AtomSampleViewer