ScriptManager.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. #pragma once
  9. #include <Atom/Component/DebugCamera/CameraControllerBus.h>
  10. #include <Atom/Feature/Utils/FrameCaptureBus.h>
  11. #include <Atom/Feature/Utils/ProfilingCaptureBus.h>
  12. #include <Automation/PrecommitWizardSettings.h>
  13. #include <Automation/ScriptRepeaterBus.h>
  14. #include <Automation/ScriptRunnerBus.h>
  15. #include <Automation/AssetStatusTracker.h>
  16. #include <Automation/ScriptReporter.h>
  17. #include <Automation/ImageComparisonConfig.h>
  18. #include <Utils/ImGuiAssetBrowser.h>
  19. #include <AzCore/Debug/ProfilerBus.h>
  20. namespace AZ
  21. {
  22. class ScriptContext;
  23. class ScriptDataContext;
  24. class ScriptAsset;
  25. }
  26. namespace AtomSampleViewer
  27. {
  28. //! Manages running lua scripts for test automation.
  29. //! This initializes a lua context, binds C++ callback functions, does per-frame processing to execute
  30. //! scripts, manages the ScriptableImGui utility, and provides an ImGui dialog for opening and running scripts.
  31. //!
  32. //! This uses an asynchronous execution model, which is necessary in order to allow scripts
  33. //! to simply call functions like IdleFrames() or IdleSeconds() to insert delays, making scripts much
  34. //! easier to write. When a script runs, every callback function adds an entry to an operations queue,
  35. //! and the Tick() function works its way through this queue every frame.
  36. //! Note that this means the C++ functions we expose to lua cannot return dynamic data; the only data we can
  37. //! return are constants like the number of samples available, or stateless utility functions like DegToRad().
  38. //!
  39. //! (Eventually we could improve this by putting the lua execution in the top-level application loop code, in
  40. //! AtomSampleViewerApplication::Tick() and make the "Idle" functions pump AtomSampleViewerApplication::Tick() manually.
  41. //! But that is only used in AtomSampleViewer.exe, not AtomSampleViewerLauncher.exe which is necessary for cross platform
  42. //! testing. Someday we'll probably make AtomSampleViewer.exe work across multiple platforms and then we could change
  43. //! our scripting execution model).
  44. class ScriptManager final
  45. : public ScriptRepeaterRequestBus::Handler
  46. , public ScriptRunnerRequestBus::Handler
  47. , public AZ::Debug::CameraControllerNotificationBus::Handler
  48. , public AZ::Render::FrameCaptureNotificationBus::Handler
  49. , public AZ::Render::ProfilingCaptureNotificationBus::Handler
  50. , public AZ::Debug::ProfilerNotificationBus::Handler
  51. {
  52. public:
  53. ScriptManager();
  54. void Activate();
  55. void Deactivate();
  56. void SetCameraEntity(AZ::Entity* cameraEntity);
  57. void TickScript(float deltaTime);
  58. void TickImGui();
  59. void OpenScriptRunnerDialog();
  60. void OpenPrecommitWizard();
  61. void RunMainTestSuite(const AZStd::string& suiteFilePath, bool exitOnTestEnd, int randomSeed);
  62. private:
  63. static constexpr const char* FullSuiteScriptFilepath = "scripts/_fulltestsuite_.bv.luac";
  64. void ShowScriptRunnerDialog();
  65. // PrecommitWizard Gui
  66. void ShowPrecommitWizard();
  67. // PrecommitWizard stages
  68. void ShowPrecommitWizardIntro();
  69. void ShowPrecommitWizardRunFullsuiteTest();
  70. void ShowPrecommitWizardReportFullsuiteTest();
  71. void ShowPrecomitWizardManualInspection();
  72. void ShowPrecommitWizardReportFinalSummary();
  73. void ShowBackToIntroWarning();
  74. // Registers functions in a BehaviorContext so they can be exposed to Lua scripts.
  75. static void ReflectScriptContext(AZ::BehaviorContext* context);
  76. ///////////////////////////////////////////////////////////////////////
  77. // Script callback functions...
  78. // Utilities...
  79. static void Script_RunScript(const AZStd::string& scriptFilePath);
  80. static void Script_Error(const AZStd::string& message);
  81. static void Script_Warning(const AZStd::string& message);
  82. static void Script_Print(const AZStd::string& message);
  83. static void Script_IdleFrames(int numFrames);
  84. static void Script_IdleSeconds(float numSeconds);
  85. static void Script_LockFrameTime(float seconds);
  86. static void Script_UnlockFrameTime();
  87. static void Script_ResizeViewport(int width, int height);
  88. static void Script_ExecuteConsoleCommand(const AZStd::string& command);
  89. // Show/Hide ImGui
  90. static void Script_SetShowImGui(bool show);
  91. // Utilities returning data (these special functions do return data because they don't read dynamic state)...
  92. static AZStd::string Script_ResolvePath(const AZStd::string& path);
  93. static AZStd::string Script_NormalizePath(const AZStd::string& path);
  94. static float Script_DegToRad(float degrees);
  95. static AZStd::string Script_GetRenderApiName();
  96. static int Script_GetRandomTestSeed();
  97. // Samples...
  98. static void Script_OpenSample(const AZStd::string& sampleName);
  99. static void Script_SetImguiValue(AZ::ScriptDataContext& dc);
  100. // Debug tools...
  101. // Show or hide a debug tool with the given name
  102. static void Script_ShowTool(const AZStd::string& toolName, bool enable);
  103. // Screenshots...
  104. // Set the path and folder that are used to find screenshots and baseline images.
  105. // The full path of the screenshot consists of: screenshotFolder + envPath + imageName/testcaseName.
  106. // The full path of the baseline folder consists of: baselineFolder + imageName/testcaseName.
  107. static void Script_SetScreenshotFolder(const AZStd::string& screenshotFolder);
  108. static void Script_SetTestEnvPath(const AZStd::string& envPath);
  109. static void Script_SetOfficialBaselineImageFolder(const AZStd::string& baselineFolder);
  110. static void Script_SetLocalBaselineImageFolder(const AZStd::string& baselineFolder);
  111. // Call this function before capturing screenshots to indicate which comparison tolerance level should be used.
  112. // The list of available tolerance levels can be found in "AtomSampleViewer/Config/ImageComparisonToleranceLevels.azasset".
  113. static void Script_SelectImageComparisonToleranceLevel(const AZStd::string& toleranceLevelName);
  114. // All of the following functions capture a frame and save it to the given file path.
  115. // The path must be under the "scripts/Screenshots" folder and have extension ".ppm".
  116. // If screenshot comparison testing is enabled, this will also check the captured image against a
  117. // baseline image file. The function will assume the corresponding expected image will be in a similar path,
  118. // but with "Screenshots" replaced with "ExpectedScreenshots". For example, the expected file for
  119. // "scripts/Screenshots/StandardPbr/test.ppm" should be at "scripts/ExpectedScreenshots/StandardPbr/test.ppm".
  120. static void Script_CaptureScreenshot(const AZStd::string& imageName);
  121. static void Script_CaptureScreenshotWithImGui(const AZStd::string& imageName);
  122. // Capture a pass attachment and save it to a file (*.ppm or *.dds for image, *.buffer for buffer)
  123. // The order of input parameters in ScriptDataContext would be
  124. // 0: table of strings for pass hierarchy
  125. // 1: string for the slot name
  126. // 2: string for output file path
  127. // Check the description of FrameCaptureRequests::CapturePassAttachment function for detail
  128. static void Script_CapturePassAttachment(AZ::ScriptDataContext& dc);
  129. // Capture a screentshot with pass image attachment preview when the preview enabled.
  130. static void Script_CaptureScreenshotWithPreview(const AZStd::string& imageName);
  131. // Profiling statistics data...
  132. static void Script_CapturePassTimestamp(AZ::ScriptDataContext& dc);
  133. static void Script_CaptureCpuFrameTime(AZ::ScriptDataContext& dc);
  134. static void Script_CapturePassPipelineStatistics(AZ::ScriptDataContext& dc);
  135. static void Script_CaptureCpuProfilingStatistics(AZ::ScriptDataContext& dc);
  136. static void Script_CaptureBenchmarkMetadata(AZ::ScriptDataContext& dc);
  137. // Camera...
  138. static void Script_ArcBallCameraController_SetCenter(AZ::Vector3 center);
  139. static void Script_ArcBallCameraController_SetPan(AZ::Vector3 pan);
  140. static void Script_ArcBallCameraController_SetDistance(float distance);
  141. static void Script_ArcBallCameraController_SetHeading(float heading);
  142. static void Script_ArcBallCameraController_SetPitch(float pitch);
  143. static void Script_NoClipCameraController_SetPosition(AZ::Vector3 center);
  144. static void Script_NoClipCameraController_SetHeading(float heading);
  145. static void Script_NoClipCameraController_SetPitch(float pitch);
  146. static void Script_NoClipCameraController_SetFov(float fov);
  147. // Asset System...
  148. // Starts tracking asset status updates from the Asset Processor. Clears any asset status information already collected.
  149. static void Script_AssetTracking_Start();
  150. // Sets the AssetStatusTracker to expect a particular asset with specific expected results.
  151. // Note this can be called multiple times with the same assetPath, in which case the expected counts will be added.
  152. // @param sourceAssetPath the source asset path, relative to the watch folder. Will be normalized and matched case-insensitive.
  153. // @param expectedCount number of completed jobs expected for this asset.
  154. static void Script_AssetTracking_ExpectAsset(const AZStd::string& sourceAssetPath, uint32_t expectedCount);
  155. // The system will idle until all expected assets have been reported as finished, either succeeded or failed.
  156. // Returns immediately if all the assets ware already finished any time since AssetTracking_Start() was called.
  157. // @param timeout Float timeout for the idle operation
  158. static void Script_AssetTracking_IdleUntilExpectedAssetsFinish(float timeout);
  159. // Stops tracking asset status updates from the Asset Processor. Clears any asset status information already collected.
  160. static void Script_AssetTracking_Stop();
  161. ///////////////////////////////////////////////////////////////////////
  162. static void CheckArcBallControllerHandler();
  163. static void CheckNoClipControllerHandler();
  164. // Similar to Script_Error, but reports the message immediately
  165. static void ReportScriptError(const AZStd::string& message);
  166. // Similar to Script_Warning, but reports the message immediately
  167. static void ReportScriptWarning(const AZStd::string& message);
  168. // ScriptRunnerRequestBus overrides...
  169. void PauseScript() override;
  170. void PauseScriptWithTimeout(float timeout) override;
  171. void ResumeScript() override;
  172. // Execute a lua script. Each function call in the script will call one of the above Script_ functions,
  173. // which will push operations onto the m_scriptOperations queue for deferred execution in TickScript().
  174. void ExecuteScript(const AZStd::string& scriptFilePath);
  175. // Prepare test environment and logging and then execute the script
  176. void PrepareAndExecuteScript(const AZStd::string& scriptFilePath);
  177. // ScriptRepeaterRequestBus overrides...
  178. void ReportScriptableAction(AZStd::string_view scriptCommand) override;
  179. // CameraControllerNotificationBus overrides...
  180. void OnCameraMoveEnded(AZ::TypeId controllerTypeId, uint32_t channels) override;
  181. // FrameCaptureNotificationBus overrides...
  182. void OnFrameCaptureFinished(AZ::Render::FrameCaptureResult result, const AZStd::string& info) override;
  183. // ProfilingCaptureNotificationBus overrides...
  184. void OnCaptureQueryTimestampFinished(bool result, const AZStd::string& info) override;
  185. void OnCaptureCpuFrameTimeFinished(bool result, const AZStd::string& info) override;
  186. void OnCaptureQueryPipelineStatisticsFinished(bool result, const AZStd::string& info) override;
  187. void OnCaptureBenchmarkMetadataFinished(bool result, const AZStd::string& info) override;
  188. // ProfilerNotificationBus overrides...
  189. void OnCaptureFinished(bool result, const AZStd::string& info) override;
  190. void AbortScripts(const AZStd::string& reason);
  191. // Validates the ScriptDataContext for ProfilingCapture script requests
  192. static bool ValidateProfilingCaptureScripContexts(AZ::ScriptDataContext& dc, AZStd::string& outputFilePath);
  193. static bool PrepareForScreenCapture(const AZStd::string& imageName);
  194. // show/hide imgui
  195. void SetShowImGui(bool show);
  196. struct TestSuiteExecutionConfig
  197. {
  198. bool m_automatedRunEnabled = false;
  199. bool m_isStarted = false;
  200. bool m_closeOnTestScriptFinish = false;
  201. AZStd::string m_testSuitePath;
  202. int m_randomSeed = 0; // Used to shuffle test order in a random manner
  203. };
  204. TestSuiteExecutionConfig m_testSuiteRunConfig;
  205. static constexpr float DefaultPauseTimeout = 5.0f;
  206. int m_scriptIdleFrames = 0;
  207. float m_scriptIdleSeconds = 0.0f;
  208. bool m_scriptPaused = false;
  209. float m_scriptPauseTimeout = 0.0f;
  210. bool m_waitForAssetTracker = false;
  211. float m_assetTrackingTimeout = 0.0f;
  212. AssetStatusTracker m_assetStatusTracker;
  213. AZStd::unique_ptr<AZ::ScriptContext> m_scriptContext; //< Provides the lua scripting system
  214. AZStd::unique_ptr<AZ::BehaviorContext> m_sriptBehaviorContext; //< Used to bind script callback functions to lua
  215. bool m_shouldRestoreViewportSize = false;
  216. int m_savedViewportWidth = 0;
  217. int m_savedViewportHeight = 0;
  218. AZ::Entity* m_cameraEntity = nullptr;
  219. ImGuiMessageBox m_messageBox;
  220. using ScriptOp = AZStd::function<void()>;
  221. AZStd::queue<ScriptOp> m_scriptOperations;
  222. bool m_doFinalScriptCleanup = false;
  223. ImGuiAssetBrowser m_scriptBrowser;
  224. AZStd::unordered_set<AZ::Data::AssetId> m_executingScripts; //< Tracks which lua scripts are currently being executed. Used to prevent infinite recursion.
  225. bool m_shouldPopScript = false; //< Tracks when an executing script just finished so we know when to call ScriptReporter::PopScript().
  226. ScriptReporter m_scriptReporter;
  227. // Manages the available ImageComparisonToleranceLevels and override options
  228. class ImageComparisonOptions : public AZ::Data::AssetBus::Handler
  229. {
  230. public:
  231. void Activate();
  232. void Deactivate();
  233. //! Return the tolerance level with the given name.
  234. //! The returned level may be adjusted according to the user's "Level Adjustment" setting in ImGui.
  235. //! @param name name of the tolerance level to find.
  236. //! @param allowLevelAdjustment may be set to false to avoid applying the user's "Level Adjustment" setting.
  237. ImageComparisonToleranceLevel* FindToleranceLevel(const AZStd::string& name, bool allowLevelAdjustment = true);
  238. //! Returns the list of all available tolerance levels, sorted most- to least-strict.
  239. const AZStd::vector<ImageComparisonToleranceLevel>& GetAvailableToleranceLevels() const;
  240. //! Sets the active tolerance level.
  241. //! The selected level may be adjusted according to the user's "Level Adjustment" setting in ImGui.
  242. //! @param name name of the tolerance level to select.
  243. //! @param allowLevelAdjustment may be set to false to avoid applying the user's "Level Adjustment" setting.
  244. void SelectToleranceLevel(const AZStd::string& name, bool allowLevelAdjustment = true);
  245. //! Sets the active tolerance level.
  246. //! @param level must be one of the tolerance levels already available.
  247. void SelectToleranceLevel(ImageComparisonToleranceLevel* level);
  248. //! Returns the active tolerance level.
  249. ImageComparisonToleranceLevel* GetCurrentToleranceLevel();
  250. //! Returns whether the user has configured the script to control tolerance
  251. //! level selection, otherwise they have selected a specific override level.
  252. bool IsScriptControlled() const;
  253. //! Returns true if the user has applied a level up/down adjustment in ImGui.
  254. bool IsLevelAdjusted() const;
  255. void DrawImGuiSettings();
  256. void ResetImGuiSettings();
  257. private:
  258. // AssetBus overrides...
  259. void OnAssetReloaded(AZ::Data::Asset<AZ::Data::AssetData> asset) override;
  260. AZ::Data::Asset<AZ::RPI::AnyAsset> m_configAsset;
  261. ImageComparisonConfig m_config;
  262. ImageComparisonToleranceLevel* m_currentToleranceLevel = nullptr;
  263. static constexpr int OverrideSetting_ScriptControlled = 0;
  264. AZStd::vector<const char*> m_overrideSettings;
  265. int m_selectedOverrideSetting = 0;
  266. int m_toleranceAdjustment = 0;
  267. } m_imageComparisonOptions;
  268. bool m_showPrecommitWizard = false;
  269. PrecommitWizardSettings m_wizardSettings;
  270. AZ::Render::FrameCaptureId m_frameCaptureId = AZ::Render::InvalidFrameCaptureId;
  271. bool m_showScriptRunnerDialog = false;
  272. bool m_isCapturePending = false;
  273. bool m_frameTimeIsLocked = false;
  274. bool m_prevShowImGui = true;
  275. bool m_showImGui = true;
  276. static ScriptManager* s_instance;
  277. };
  278. } // namespace AtomSampleViewer