ScriptManager.h 16 KB

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