ScriptManager.cpp 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183
  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 <Automation/ScriptManager.h>
  9. #include <Automation/ScriptableImGui.h>
  10. #include <SampleComponentManagerBus.h>
  11. #include <imgui/imgui_internal.h>
  12. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  13. #include <Atom/RPI.Public/RPISystemInterface.h>
  14. #include <Atom/Component/DebugCamera/CameraComponent.h>
  15. #include <Atom/Component/DebugCamera/NoClipControllerComponent.h>
  16. #include <Atom/Component/DebugCamera/ArcBallControllerComponent.h>
  17. #include <Atom/Feature/ImGui/SystemBus.h>
  18. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  19. #include <Atom/RHI/Factory.h>
  20. #include <AzCore/Component/Entity.h>
  21. #include <AzCore/Settings/SettingsRegistryScriptUtils.h>
  22. #include <AzCore/Script/ScriptContext.h>
  23. #include <AzCore/Script/ScriptSystemBus.h>
  24. #include <AzCore/Script/ScriptAsset.h>
  25. #include <AzCore/Math/MathReflection.h>
  26. #include <AzCore/Console/IConsole.h>
  27. #include <AzCore/Time/ITime.h>
  28. #include <AzFramework/API/ApplicationAPI.h>
  29. #include <AzFramework/Components/ConsoleBus.h>
  30. #include <AzFramework/IO/LocalFileIO.h>
  31. #include <AzFramework/Windowing/WindowBus.h>
  32. #include <AtomSampleViewerRequestBus.h>
  33. #include <Utils/Utils.h>
  34. namespace AtomSampleViewer
  35. {
  36. ScriptManager* ScriptManager::s_instance = nullptr;
  37. ScriptManager::ScriptManager()
  38. : m_scriptBrowser("@user@/lua_script_browser.xml")
  39. {
  40. }
  41. void ScriptManager::Activate()
  42. {
  43. AZ_Assert(s_instance == nullptr, "ScriptManager is already activated");
  44. s_instance = this;
  45. ScriptableImGui::Create();
  46. m_scriptContext = AZStd::make_unique<AZ::ScriptContext>();
  47. m_sriptBehaviorContext = AZStd::make_unique<AZ::BehaviorContext>();
  48. ReflectScriptContext(m_sriptBehaviorContext.get());
  49. m_scriptContext->BindTo(m_sriptBehaviorContext.get());
  50. m_scriptBrowser.SetFilter([](const AZ::Data::AssetInfo& assetInfo)
  51. {
  52. return AzFramework::StringFunc::EndsWith(assetInfo.m_relativePath, ".bv.luac");
  53. });
  54. m_scriptBrowser.Activate();
  55. ScriptRepeaterRequestBus::Handler::BusConnect();
  56. ScriptRunnerRequestBus::Handler::BusConnect();
  57. m_imageComparisonOptions.Activate();
  58. }
  59. void ScriptManager::Deactivate()
  60. {
  61. s_instance = nullptr;
  62. m_scriptContext = nullptr;
  63. m_sriptBehaviorContext = nullptr;
  64. m_scriptBrowser.Deactivate();
  65. ScriptableImGui::Destory();
  66. m_imageComparisonOptions.Deactivate();
  67. ScriptRunnerRequestBus::Handler::BusDisconnect();
  68. ScriptRepeaterRequestBus::Handler::BusDisconnect();
  69. AZ::Debug::CameraControllerNotificationBus::Handler::BusDisconnect();
  70. }
  71. void ScriptManager::SetCameraEntity(AZ::Entity* cameraEntity)
  72. {
  73. AZ::Debug::CameraControllerNotificationBus::Handler::BusDisconnect();
  74. m_cameraEntity = cameraEntity;
  75. AZ::Debug::CameraControllerNotificationBus::Handler::BusConnect(m_cameraEntity->GetId());
  76. }
  77. void ScriptManager::PauseScript()
  78. {
  79. PauseScriptWithTimeout(DefaultPauseTimeout);
  80. }
  81. void ScriptManager::PauseScriptWithTimeout(float timeout)
  82. {
  83. m_scriptPaused = true;
  84. m_scriptPauseTimeout = AZ::GetMax(timeout, m_scriptPauseTimeout);
  85. }
  86. void ScriptManager::ResumeScript()
  87. {
  88. AZ_Warning("Automation", m_scriptPaused, "Script is not paused");
  89. m_scriptPaused = false;
  90. }
  91. void ScriptManager::ReportScriptError([[maybe_unused]] const AZStd::string& message)
  92. {
  93. AZ_Error("Automation", false, "Script: %s", message.c_str());
  94. }
  95. void ScriptManager::ReportScriptWarning([[maybe_unused]] const AZStd::string& message)
  96. {
  97. AZ_Warning("Automation", false, "Script: %s", message.c_str());
  98. }
  99. void ScriptManager::ReportScriptableAction([[maybe_unused]] AZStd::string_view scriptCommand)
  100. {
  101. AZ_TracePrintf("Automation", "Scriptable Action: %.*s\n", AZ_STRING_ARG(scriptCommand));
  102. }
  103. void ScriptManager::ImageComparisonOptions::Activate()
  104. {
  105. m_configAsset = AZ::RPI::AssetUtils::LoadAssetByProductPath<AZ::RPI::AnyAsset>("config/ImageComparisonConfig.azasset", AZ::RPI::AssetUtils::TraceLevel::Assert);
  106. if (m_configAsset)
  107. {
  108. AZ::Data::AssetBus::Handler::BusConnect(m_configAsset.GetId());
  109. OnAssetReloaded(m_configAsset);
  110. }
  111. }
  112. void ScriptManager::ImageComparisonOptions::Deactivate()
  113. {
  114. m_configAsset.Release();
  115. ResetImGuiSettings();
  116. AZ::Data::AssetBus::Handler::BusDisconnect();
  117. }
  118. ImageComparisonToleranceLevel* ScriptManager::ImageComparisonOptions::FindToleranceLevel(const AZStd::string& name, bool allowLevelAdjustment)
  119. {
  120. size_t foundIndex = m_config.m_toleranceLevels.size();
  121. for (size_t i = 0; i < m_config.m_toleranceLevels.size(); ++i)
  122. {
  123. if (m_config.m_toleranceLevels[i].m_name == name)
  124. {
  125. foundIndex = i;
  126. break;
  127. }
  128. }
  129. if (foundIndex == m_config.m_toleranceLevels.size())
  130. {
  131. return nullptr;
  132. }
  133. if (allowLevelAdjustment)
  134. {
  135. int adjustedIndex = aznumeric_cast<int>(foundIndex);
  136. adjustedIndex += m_toleranceAdjustment;
  137. adjustedIndex = AZ::GetClamp(adjustedIndex, 0, aznumeric_cast<int>(m_config.m_toleranceLevels.size()) - 1);
  138. foundIndex = aznumeric_cast<size_t>(adjustedIndex);
  139. }
  140. return &m_config.m_toleranceLevels[foundIndex];
  141. }
  142. const AZStd::vector<ImageComparisonToleranceLevel>& ScriptManager::ImageComparisonOptions::GetAvailableToleranceLevels() const
  143. {
  144. return m_config.m_toleranceLevels;
  145. }
  146. void ScriptManager::ImageComparisonOptions::SelectToleranceLevel(const AZStd::string& name, bool allowLevelAdjustment)
  147. {
  148. if (m_selectedOverrideSetting == OverrideSetting_ScriptControlled)
  149. {
  150. ImageComparisonToleranceLevel* level = FindToleranceLevel(name, allowLevelAdjustment);
  151. if (level)
  152. {
  153. m_currentToleranceLevel = level;
  154. }
  155. else
  156. {
  157. ReportScriptError(AZStd::string::format("ImageComparisonToleranceLevel '%s' not found.", name.c_str()));
  158. }
  159. }
  160. }
  161. void ScriptManager::ImageComparisonOptions::SelectToleranceLevel(ImageComparisonToleranceLevel* level)
  162. {
  163. if (nullptr == level)
  164. {
  165. m_currentToleranceLevel = level;
  166. return;
  167. }
  168. else
  169. {
  170. SelectToleranceLevel(level->m_name);
  171. AZ_Assert(GetCurrentToleranceLevel() == level, "Wrong ImageComparisonToleranceLevel pointer used");
  172. }
  173. }
  174. ImageComparisonToleranceLevel* ScriptManager::ImageComparisonOptions::GetCurrentToleranceLevel()
  175. {
  176. return m_currentToleranceLevel;
  177. }
  178. bool ScriptManager::ImageComparisonOptions::IsScriptControlled() const
  179. {
  180. return m_selectedOverrideSetting == OverrideSetting_ScriptControlled;
  181. }
  182. bool ScriptManager::ImageComparisonOptions::IsLevelAdjusted() const
  183. {
  184. return m_toleranceAdjustment != 0;
  185. }
  186. void ScriptManager::ImageComparisonOptions::DrawImGuiSettings()
  187. {
  188. ImGui::Text("Tolerance");
  189. ImGui::Indent();
  190. if (ImGui::Combo("Level",
  191. &m_selectedOverrideSetting,
  192. m_overrideSettings.data(),
  193. aznumeric_cast<int>(m_overrideSettings.size())))
  194. {
  195. if (m_selectedOverrideSetting == OverrideSetting_ScriptControlled)
  196. {
  197. m_currentToleranceLevel = nullptr;
  198. }
  199. else
  200. {
  201. m_currentToleranceLevel = &m_config.m_toleranceLevels[m_selectedOverrideSetting - 1];
  202. }
  203. }
  204. if (IsScriptControlled())
  205. {
  206. ImGui::InputInt("Level Adjustment", &m_toleranceAdjustment);
  207. }
  208. ImGui::Unindent();
  209. }
  210. void ScriptManager::ImageComparisonOptions::ResetImGuiSettings()
  211. {
  212. m_currentToleranceLevel = nullptr;
  213. m_selectedOverrideSetting = OverrideSetting_ScriptControlled;
  214. m_toleranceAdjustment = 0;
  215. }
  216. void ScriptManager::ImageComparisonOptions::OnAssetReloaded(AZ::Data::Asset<AZ::Data::AssetData> asset)
  217. {
  218. m_configAsset = asset;
  219. m_config = *m_configAsset->GetDataAs<ImageComparisonConfig>();
  220. m_overrideSettings.clear();
  221. m_overrideSettings.push_back("[Script-controlled]");
  222. for (size_t i = 0; i < m_config.m_toleranceLevels.size(); ++i)
  223. {
  224. AZ_Assert(i == 0 || m_config.m_toleranceLevels[i].m_threshold > m_config.m_toleranceLevels[i - 1].m_threshold, "Threshold values are not sequential");
  225. m_overrideSettings.push_back(m_config.m_toleranceLevels[i].m_name.c_str());
  226. }
  227. }
  228. void ScriptManager::TickImGui()
  229. {
  230. if (m_showScriptRunnerDialog)
  231. {
  232. ShowScriptRunnerDialog();
  233. }
  234. m_scriptReporter.TickImGui();
  235. if (m_showPrecommitWizard)
  236. {
  237. ShowPrecommitWizard();
  238. }
  239. if (m_testSuiteRunConfig.m_automatedRunEnabled)
  240. {
  241. if (m_testSuiteRunConfig.m_isStarted == false)
  242. {
  243. m_testSuiteRunConfig.m_isStarted = true;
  244. PrepareAndExecuteScript(m_testSuiteRunConfig.m_testSuitePath);
  245. }
  246. }
  247. }
  248. void ScriptManager::TickScript(float deltaTime)
  249. {
  250. // All actions must be consumed each frame. Otherwise, this indicates that a script is
  251. // scheduling ScriptableImGui actions for fields that don't exist.
  252. ScriptableImGui::CheckAllActionsConsumed();
  253. ScriptableImGui::ClearActions();
  254. // We delayed PopScript() until after the above CheckAllActionsConsumed(), so that any errors
  255. // reported by that function will be associated with the proper script.
  256. if (m_shouldPopScript)
  257. {
  258. m_scriptReporter.PopScript();
  259. m_shouldPopScript = false;
  260. }
  261. while (!m_scriptOperations.empty())
  262. {
  263. if (m_shouldPopScript)
  264. {
  265. // If we just finished executing a script, the remaining m_scriptOperations are for some other script.
  266. // We need to proceed to the next frame and allow that PopScript() to happen, otherwise any errors related
  267. // to subsequent operations would be reported against the prior script.
  268. break;
  269. }
  270. if (m_scriptPaused)
  271. {
  272. m_scriptPauseTimeout -= deltaTime;
  273. if (m_scriptPauseTimeout < 0)
  274. {
  275. AZ_Error("Automation", false, "Script pause timed out. Continuing...");
  276. m_scriptPaused = false;
  277. }
  278. else
  279. {
  280. break;
  281. }
  282. }
  283. if (m_waitForAssetTracker)
  284. {
  285. m_assetTrackingTimeout -= deltaTime;
  286. if (m_assetTrackingTimeout < 0)
  287. {
  288. auto incomplateAssetList = m_assetStatusTracker.GetIncompleteAssetList();
  289. AZStd::string incompleteAssetListString;
  290. AzFramework::StringFunc::Join(incompleteAssetListString, incomplateAssetList.begin(), incomplateAssetList.end(), "\n ");
  291. AZ_Error("Automation", false, "Script asset tracking timed out waiting for:\n %s \n Continuing...", incompleteAssetListString.c_str());
  292. m_waitForAssetTracker = false;
  293. }
  294. else if (m_assetStatusTracker.DidExpectedAssetsFinish())
  295. {
  296. AZ_Printf("Automation", "Asset Tracker finished with %f seconds remaining.", m_assetTrackingTimeout);
  297. m_waitForAssetTracker = false;
  298. }
  299. else
  300. {
  301. break;
  302. }
  303. }
  304. if (m_scriptIdleFrames > 0)
  305. {
  306. m_scriptIdleFrames--;
  307. break;
  308. }
  309. if (m_scriptIdleSeconds > 0)
  310. {
  311. m_scriptIdleSeconds -= deltaTime;
  312. break;
  313. }
  314. // Execute the next operation
  315. m_scriptOperations.front()();
  316. m_scriptOperations.pop();
  317. if (m_scriptOperations.empty())
  318. {
  319. m_doFinalScriptCleanup = true;
  320. }
  321. }
  322. if (m_shouldPopScript)
  323. {
  324. // We need to proceed for one more frame to do the last PopScript() before final cleanup
  325. return;
  326. }
  327. if (m_doFinalScriptCleanup)
  328. {
  329. bool frameCapturePending = false;
  330. SampleComponentManagerRequestBus::BroadcastResult(frameCapturePending, &SampleComponentManagerRequests::IsFrameCapturePending);
  331. if (!frameCapturePending && !m_isCapturePending)
  332. {
  333. AZ_Assert(m_scriptPaused == false, "Script manager is in an unexpected state.");
  334. AZ_Assert(m_scriptIdleFrames == 0, "Script manager is in an unexpected state.");
  335. AZ_Assert(m_scriptIdleSeconds <= 0.0f, "Script manager is in an unexpected state.");
  336. AZ_Assert(m_waitForAssetTracker == false, "Script manager is in an unexpected state.");
  337. AZ_Assert(!m_scriptReporter.HasActiveScript(), "Script manager is in an unexpected state.");
  338. AZ_Assert(m_executingScripts.size() == 0, "Script manager is in an unexpected state");
  339. m_assetStatusTracker.StopTracking();
  340. if (m_frameTimeIsLocked)
  341. {
  342. AZ::Interface<AZ::IConsole>::Get()->PerformCommand("t_simulationTickDeltaOverride 0");
  343. m_frameTimeIsLocked = false;
  344. }
  345. if (m_shouldRestoreViewportSize)
  346. {
  347. Utils::ResizeClientArea(m_savedViewportWidth, m_savedViewportHeight, AzFramework::WindowPosOptions());
  348. m_shouldRestoreViewportSize = false;
  349. }
  350. // In case scripts were aborted while ImGui was temporarily hidden, show it again.
  351. SetShowImGui(true);
  352. m_scriptReporter.SortScriptReports();
  353. m_scriptReporter.OpenReportDialog();
  354. m_shouldPopScript = false;
  355. m_doFinalScriptCleanup = false;
  356. if (m_testSuiteRunConfig.m_automatedRunEnabled && m_testSuiteRunConfig.m_closeOnTestScriptFinish)
  357. {
  358. m_testSuiteRunConfig.m_automatedRunEnabled = false;
  359. if (m_scriptReporter.HasErrorsAssertsInReport())
  360. {
  361. AtomSampleViewerRequestsBus::Broadcast(&AtomSampleViewerRequestsBus::Events::SetExitCode, 1);
  362. // Useful console logging for Hydra tests
  363. int failedTests = 0;
  364. for (const ScriptReporter::ScriptReport& testReport : m_scriptReporter.GetScriptReport())
  365. {
  366. if (testReport.m_assertCount > 0 || testReport.m_generalErrorCount > 0 || testReport.m_screenshotErrorCount > 0)
  367. {
  368. ++failedTests;
  369. AZ_Printf("AtomSampleViewer", "Test failure %s: asserts %u, general errors %u, screenshot failures %u\n", testReport.m_scriptAssetPath.c_str(),
  370. testReport.m_assertCount, testReport.m_generalErrorCount, testReport.m_screenshotErrorCount);
  371. }
  372. }
  373. AZ_Printf("AtomSampleViewer", "%d tests failed\n", failedTests);
  374. }
  375. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::ExitMainLoop);
  376. }
  377. }
  378. }
  379. }
  380. void ScriptManager::OpenScriptRunnerDialog()
  381. {
  382. m_showScriptRunnerDialog = true;
  383. }
  384. void ScriptManager::OpenPrecommitWizard()
  385. {
  386. m_showPrecommitWizard = true;
  387. }
  388. void ScriptManager::RunMainTestSuite(const AZStd::string& suiteFilePath, bool exitOnTestEnd, int randomSeed)
  389. {
  390. m_testSuiteRunConfig.m_automatedRunEnabled = true;
  391. m_testSuiteRunConfig.m_testSuitePath = suiteFilePath;
  392. m_testSuiteRunConfig.m_closeOnTestScriptFinish = exitOnTestEnd;
  393. m_testSuiteRunConfig.m_randomSeed = randomSeed;
  394. }
  395. void ScriptManager::AbortScripts(const AZStd::string& reason)
  396. {
  397. m_scriptReporter.SetInvalidationMessage(reason);
  398. m_scriptOperations = {};
  399. m_executingScripts.clear();
  400. m_scriptPaused = false;
  401. m_scriptIdleFrames = 0;
  402. m_scriptIdleSeconds = 0.0f;
  403. m_waitForAssetTracker = false;
  404. while (m_scriptReporter.HasActiveScript())
  405. {
  406. m_scriptReporter.PopScript();
  407. }
  408. m_doFinalScriptCleanup = true;
  409. }
  410. void ScriptManager::ShowScriptRunnerDialog()
  411. {
  412. if (ImGui::Begin("Script Runner", &m_showScriptRunnerDialog))
  413. {
  414. auto drawAbortButton = [this](const char* uniqueId)
  415. {
  416. ImGui::PushID(uniqueId);
  417. if (ImGui::Button("Abort"))
  418. {
  419. AbortScripts("Script(s) manually aborted.");
  420. }
  421. ImGui::PopID();
  422. };
  423. // The main buttons are at the bottom, but show the Abort button at the top too, in case the window size is small.
  424. if (!m_scriptOperations.empty())
  425. {
  426. drawAbortButton("Button1");
  427. }
  428. ImGuiAssetBrowser::WidgetSettings assetBrowserSettings;
  429. assetBrowserSettings.m_labels.m_root = "Lua Scripts";
  430. m_scriptBrowser.Tick(assetBrowserSettings);
  431. AZStd::string selectedFileName = "<none>";
  432. AzFramework::StringFunc::Path::GetFullFileName(m_scriptBrowser.GetSelectedAssetPath().c_str(), selectedFileName);
  433. ImGui::LabelText("##SelectedScript", "Selected: %s", selectedFileName.c_str());
  434. ImGui::Separator();
  435. ImGui::Text("Settings");
  436. ImGui::Indent();
  437. ImGui::InputInt("Random Seed for Test Order Execution", &m_testSuiteRunConfig.m_randomSeed);
  438. m_imageComparisonOptions.DrawImGuiSettings();
  439. if (ImGui::Button("Reset"))
  440. {
  441. m_imageComparisonOptions.ResetImGuiSettings();
  442. }
  443. ImGui::Unindent();
  444. ImGui::Separator();
  445. if (ImGui::Button("Run"))
  446. {
  447. auto scriptAsset = m_scriptBrowser.GetSelectedAsset<AZ::ScriptAsset>();
  448. if (scriptAsset.GetId().IsValid())
  449. {
  450. PrepareAndExecuteScript(m_scriptBrowser.GetSelectedAssetPath());
  451. }
  452. }
  453. if (ImGui::Button("View Latest Results"))
  454. {
  455. m_scriptReporter.OpenReportDialog();
  456. }
  457. if (m_scriptOperations.size() > 0)
  458. {
  459. ImGui::LabelText("##RunningScript", "Running %zu operations...", m_scriptOperations.size());
  460. drawAbortButton("Button2");
  461. }
  462. }
  463. m_messageBox.TickPopup();
  464. ImGui::End();
  465. }
  466. void ScriptManager::ShowPrecommitWizard()
  467. {
  468. if (ImGui::Begin("Pre-commit Wizard", &m_showPrecommitWizard))
  469. {
  470. ShowBackToIntroWarning();
  471. if (ImGui::Button("Start from the Beginning"))
  472. {
  473. ImGui::OpenPopup("Return to Intro Window");
  474. }
  475. switch (m_wizardSettings.m_stage)
  476. {
  477. case PrecommitWizardSettings::Stage::Intro:
  478. ShowPrecommitWizardIntro();
  479. break;
  480. case PrecommitWizardSettings::Stage::RunFullsuiteTest:
  481. ShowPrecommitWizardRunFullsuiteTest();
  482. break;
  483. case PrecommitWizardSettings::Stage::ReportFullsuiteSummary:
  484. ShowPrecommitWizardReportFullsuiteTest();
  485. break;
  486. case PrecommitWizardSettings::Stage::ManualInspection:
  487. // Go through each pass in the full suite test and require users to manually pick from a list
  488. // to describe the difference if it exists.
  489. ShowPrecomitWizardManualInspection();
  490. break;
  491. case PrecommitWizardSettings::Stage::ReportFinalSummary:
  492. // Generate a summary that can be easily copied into the clipboard
  493. ShowPrecommitWizardReportFinalSummary();
  494. break;
  495. }
  496. }
  497. ImGui::End();
  498. }
  499. void ScriptManager::ShowBackToIntroWarning()
  500. {
  501. if (ImGui::BeginPopupModal("Return to Intro Window", nullptr, ImGuiWindowFlags_AlwaysAutoResize))
  502. {
  503. ImGui::Text("Warning: You are returning to the intro window. Current full test suite results will be lost.\n\nAre you sure?");
  504. if (ImGui::Button("Yes"))
  505. {
  506. m_wizardSettings = PrecommitWizardSettings();
  507. ImGui::CloseCurrentPopup();
  508. }
  509. ImGui::SameLine();
  510. if (ImGui::Button("No"))
  511. {
  512. ImGui::CloseCurrentPopup();
  513. }
  514. ImGui::EndPopup();
  515. }
  516. }
  517. void ScriptManager::ShowPrecommitWizardIntro()
  518. {
  519. ImGui::Separator();
  520. ImGui::TextWrapped("Here's what will take place...\n"
  521. "1) The standard '_fulltestsuite_' script will be run.\n"
  522. "2) You'll see a summary of the test results. If any tests failed the automatic checks, "
  523. "you are strongly encouraged to address those issues first.\n"
  524. "3) You will be guided through a series of visual screenshot validations. For each one, "
  525. "you'll need to inspect an image comparison and indicate whether you see visual differences.\n"
  526. "4) The final report will be generated. Copy and paste this into your PR description.");
  527. ImGui::Separator();
  528. if (ImGui::Button("Run Full Test Suite"))
  529. {
  530. PrepareAndExecuteScript(FullSuiteScriptFilepath);
  531. m_wizardSettings.m_stage = PrecommitWizardSettings::Stage::RunFullsuiteTest;
  532. }
  533. }
  534. void ScriptManager::ShowPrecommitWizardRunFullsuiteTest()
  535. {
  536. ImGui::Text("Running Full Test Suite. Please Wait...");
  537. if (m_scriptOperations.empty() && !m_doFinalScriptCleanup)
  538. {
  539. m_scriptReporter.HideReportDialog();
  540. m_wizardSettings.m_stage = PrecommitWizardSettings::Stage::ReportFullsuiteSummary;
  541. }
  542. }
  543. void ScriptManager::ShowPrecommitWizardReportFullsuiteTest()
  544. {
  545. m_scriptReporter.DisplayScriptResultsSummary();
  546. if (ImGui::Button("See Details..."))
  547. {
  548. m_scriptReporter.OpenReportDialog();
  549. }
  550. ImGui::Separator();
  551. if (ImGui::Button("Back"))
  552. {
  553. ImGui::OpenPopup("Return to Intro Window");
  554. }
  555. ImGui::SameLine();
  556. if (ImGui::Button("Continue"))
  557. {
  558. m_wizardSettings.ProcessScriptReports(m_scriptReporter.GetScriptReport());
  559. if (!m_wizardSettings.m_reportsOrderedByThresholdToInspect.empty())
  560. {
  561. m_wizardSettings.m_stage = PrecommitWizardSettings::Stage::ManualInspection;
  562. }
  563. else
  564. {
  565. m_wizardSettings.m_stage = PrecommitWizardSettings::Stage::ReportFinalSummary;
  566. }
  567. }
  568. }
  569. void ScriptManager::ShowPrecomitWizardManualInspection()
  570. {
  571. const AZStd::vector<ScriptReporter::ScriptReport>& scriptReports = m_scriptReporter.GetScriptReport();
  572. // Get the script report and screenshot test corresponding to the current index
  573. const ScriptReporter::ReportIndex currentIndex = m_wizardSettings.m_reportIterator->second;
  574. const ScriptReporter::ScriptReport& scriptReport = scriptReports[currentIndex.first];
  575. const ScriptReporter::ScreenshotTestInfo& screenshotTest = scriptReport.m_screenshotTests[currentIndex.second];
  576. ImGui::Text("Script Name: %s", scriptReport.m_scriptAssetPath.c_str());
  577. ImGui::Text("Screenshot Name: %s", screenshotTest.m_officialBaselineScreenshotFilePath.c_str());
  578. ImGui::Separator();
  579. ImGui::Text("Diff Score: %f", screenshotTest.m_officialComparisonResult.m_diffScore);
  580. // TODO: Render screenshots in ImGui.
  581. ImGui::Separator();
  582. // Check if the current index's screenshot has been manually validated and let the user know
  583. auto it = m_wizardSettings.m_reportIndexDifferenceLevelMap.find(currentIndex);
  584. if (it != m_wizardSettings.m_reportIndexDifferenceLevelMap.end())
  585. {
  586. m_wizardSettings.m_inspectionSelection = it->second;
  587. ImGui::PushStyleColor(ImGuiCol_Text, IM_COL32(0, 255, 0, 255));
  588. ImGui::Text("This inspection has been added to the report summary");
  589. ImGui::PopStyleColor();
  590. }
  591. else
  592. {
  593. ImGui::PushStyleColor(ImGuiCol_Text, IM_COL32(255, 0, 0, 255));
  594. ImGui::Text("This inspection has not been added to the report summary");
  595. ImGui::PopStyleColor();
  596. }
  597. ImGui::TextWrapped(
  598. "Use the 'Export Png' button to inspect the screenshot. Choose from the options below that describe the difference level "
  599. "then click 'Next' to add it in the report summary. Once there are no more noticeable differences as the threshold decreases, "
  600. "click 'Finish' to generate the report summary. Note that the remaining screenshots that were not manually inspected will not "
  601. "appear in the report summary.");
  602. for (int i = 0; i < 4; ++i)
  603. {
  604. ImGui::RadioButton(PrecommitWizardSettings::ManualInspectionOptions[i], &m_wizardSettings.m_inspectionSelection, i);
  605. }
  606. if (ImGui::Button("View Diff"))
  607. {
  608. if (!Utils::RunDiffTool(screenshotTest.m_officialBaselineScreenshotFilePath, screenshotTest.m_screenshotFilePath))
  609. {
  610. ImGui::OpenPopup("Cannot open diff tool");
  611. }
  612. }
  613. if (ImGui::BeginPopupModal("Cannot open diff tool", nullptr, ImGuiWindowFlags_AlwaysAutoResize))
  614. {
  615. ImGui::Text("Image diff is not supported on this platform, or the required diff tool is not installed.");
  616. if (ImGui::Button("Ok"))
  617. {
  618. ImGui::CloseCurrentPopup();
  619. }
  620. ImGui::EndPopup();
  621. }
  622. ImGui::SameLine();
  623. if (ImGui::Button("Export Png"))
  624. {
  625. m_wizardSettings.m_exportedPngPath = m_scriptReporter.ExportImageDiff(scriptReport, screenshotTest);
  626. }
  627. if (!m_wizardSettings.m_exportedPngPath.empty())
  628. {
  629. ImGui::SameLine();
  630. bool copyPath = ImGui::Button("Copy Path");
  631. ImGui::Text("Diff Png was exported to:");
  632. ImGui::SameLine();
  633. if (copyPath)
  634. {
  635. ImGui::LogToClipboard();
  636. }
  637. ImGui::Text("%s", m_wizardSettings.m_exportedPngPath.c_str());
  638. if (copyPath)
  639. {
  640. ImGui::LogFinish();
  641. }
  642. }
  643. ImGui::Separator();
  644. if (ImGui::Button("Back"))
  645. {
  646. if (m_wizardSettings.m_reportIterator == m_wizardSettings.m_reportsOrderedByThresholdToInspect.begin())
  647. {
  648. m_wizardSettings.m_stage = PrecommitWizardSettings::Stage::ReportFullsuiteSummary;
  649. }
  650. else
  651. {
  652. --m_wizardSettings.m_reportIterator;
  653. }
  654. }
  655. ImGui::SameLine();
  656. const bool isNextButtonDisabled =
  657. m_wizardSettings.m_inspectionSelection == PrecommitWizardSettings::DefaultInspectionSelection ? true : false;
  658. if (isNextButtonDisabled)
  659. {
  660. ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true);
  661. ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.5f);
  662. }
  663. if (ImGui::Button("Next"))
  664. {
  665. m_wizardSettings.m_reportIndexDifferenceLevelMap[currentIndex] =
  666. PrecommitWizardSettings::ImageDifferenceLevel::Levels(m_wizardSettings.m_inspectionSelection);
  667. m_wizardSettings.m_inspectionSelection = PrecommitWizardSettings::DefaultInspectionSelection;
  668. m_wizardSettings.m_exportedPngPath.clear();
  669. ++m_wizardSettings.m_reportIterator;
  670. if (m_wizardSettings.m_reportIterator == m_wizardSettings.m_reportsOrderedByThresholdToInspect.end())
  671. {
  672. // Decrement the iterator to make sure it's pointing to the last element in case the user goes
  673. // back to the manual inspection page.
  674. --m_wizardSettings.m_reportIterator;
  675. m_wizardSettings.m_stage = PrecommitWizardSettings::Stage::ReportFinalSummary;
  676. }
  677. }
  678. if (isNextButtonDisabled)
  679. {
  680. ImGui::PopItemFlag();
  681. ImGui::PopStyleVar();
  682. }
  683. ImGui::SameLine();
  684. if (ImGui::Button("Finish Manual Inspection"))
  685. {
  686. m_wizardSettings.m_stage = PrecommitWizardSettings::Stage::ReportFinalSummary;
  687. }
  688. ImGui::SameLine();
  689. ImGui::Text(
  690. "%zu/%zu", aznumeric_cast<size_t>(AZStd::distance(m_wizardSettings.m_reportsOrderedByThresholdToInspect.begin(), m_wizardSettings.m_reportIterator) + 1),
  691. m_wizardSettings.m_reportsOrderedByThresholdToInspect.size());
  692. }
  693. void ScriptManager::ShowPrecommitWizardReportFinalSummary()
  694. {
  695. ImGui::Text("Tests are complete! here is the final report.");
  696. bool copyToClipboard = ImGui::Button("Copy To Clipboard");
  697. const ScriptReporter::ScriptResultsSummary resultsSummary = m_scriptReporter.GetScriptResultSummary();
  698. const AZStd::vector<ScriptReporter::ScriptReport>& scriptReports = m_scriptReporter.GetScriptReport();
  699. AZStd::vector<AZStd::vector<ScriptReporter::ReportIndex>> imageDifferenceSummary(
  700. PrecommitWizardSettings::ImageDifferenceLevel::NumDifferenceLevels);
  701. int totalValidatedScreenshots = 0;
  702. for (const auto& [reportIndex, differenceLevel] : m_wizardSettings.m_reportIndexDifferenceLevelMap)
  703. {
  704. imageDifferenceSummary[differenceLevel].push_back(reportIndex);
  705. }
  706. for (const auto& differenceLevelReports : imageDifferenceSummary)
  707. {
  708. totalValidatedScreenshots += aznumeric_cast<int>(differenceLevelReports.size());
  709. }
  710. ImGui::Separator();
  711. if (copyToClipboard)
  712. {
  713. ImGui::LogToClipboard();
  714. }
  715. ImGui::Text("RHI API: %s", AZ::RHI::Factory::Get().GetName().GetCStr());
  716. ImGui::Text("Test Script Count: %zu", scriptReports.size());
  717. ImGui::Text("Screenshot Count: %d", resultsSummary.m_totalScreenshotsCount);
  718. ImGui::Text(
  719. "Manually Validated Screenshots: %d/%zu", totalValidatedScreenshots,
  720. m_wizardSettings.m_reportsOrderedByThresholdToInspect.size());
  721. ImGui::Text("Screenshot automatic checks failed: %zu", m_wizardSettings.m_failedReports.size());
  722. for (const auto& failedReport : m_wizardSettings.m_failedReports)
  723. {
  724. const ScriptReporter::ReportIndex& reportIndex = failedReport.second;
  725. const ScriptReporter::ScriptReport& scriptReport = scriptReports[reportIndex.first];
  726. const ScriptReporter::ScreenshotTestInfo& screenshotTest = scriptReport.m_screenshotTests[reportIndex.second];
  727. ImGui::Text(
  728. "\t%s %s '%s' %f", scriptReport.m_scriptAssetPath.c_str(), screenshotTest.m_screenshotFilePath.c_str(),
  729. screenshotTest.m_toleranceLevel.m_name.c_str(), screenshotTest.m_officialComparisonResult.m_diffScore);
  730. }
  731. // Present the information by printing highest differences first. See enum class ImageDifferenceLevel
  732. for (int i = aznumeric_cast<int>(imageDifferenceSummary.size() - 1); i >= 0; --i)
  733. {
  734. if (!imageDifferenceSummary[i].empty())
  735. {
  736. ImGui::Text("Screenshot interactive check '%s'", PrecommitWizardSettings::ManualInspectionDifferenceLevels[i]);
  737. for (const auto& reportIndex : imageDifferenceSummary[i])
  738. {
  739. const ScriptReporter::ScriptReport& scriptReport = scriptReports[reportIndex.first];
  740. const ScriptReporter::ScreenshotTestInfo& screenshotTest = scriptReport.m_screenshotTests[reportIndex.second];
  741. ImGui::Text(
  742. "\t%s %s '%s' %f", scriptReport.m_scriptAssetPath.c_str(), screenshotTest.m_screenshotFilePath.c_str(),
  743. screenshotTest.m_toleranceLevel.m_name.c_str(), screenshotTest.m_officialComparisonResult.m_diffScore);
  744. }
  745. }
  746. }
  747. if (copyToClipboard)
  748. {
  749. ImGui::LogFinish();
  750. }
  751. ImGui::Separator();
  752. if (ImGui::Button("Back"))
  753. {
  754. m_wizardSettings.m_stage = PrecommitWizardSettings::Stage::ManualInspection;
  755. auto reportIndexToDifference = m_wizardSettings.m_reportIndexDifferenceLevelMap.find(m_wizardSettings.m_reportIterator->second);
  756. m_wizardSettings.m_inspectionSelection = reportIndexToDifference != m_wizardSettings.m_reportIndexDifferenceLevelMap.end()
  757. ? reportIndexToDifference->second
  758. : PrecommitWizardSettings::DefaultInspectionSelection;
  759. }
  760. }
  761. void ScriptManager::PrepareAndExecuteScript(const AZStd::string& scriptFilePath)
  762. {
  763. ReportScriptableAction(AZStd::string::format("RunScript('%s')", scriptFilePath.c_str()));
  764. // Save the window size so we can restore it after running the script, in case the script calls ResizeViewport
  765. AzFramework::NativeWindowHandle defaultWindowHandle;
  766. AzFramework::WindowSize windowSize;
  767. AzFramework::WindowSystemRequestBus::BroadcastResult(defaultWindowHandle, &AzFramework::WindowSystemRequestBus::Events::GetDefaultWindowHandle);
  768. AzFramework::WindowRequestBus::EventResult(windowSize, defaultWindowHandle, &AzFramework::WindowRequests::GetClientAreaSize);
  769. m_savedViewportWidth = windowSize.m_width;
  770. m_savedViewportHeight = windowSize.m_height;
  771. if (m_savedViewportWidth == 0 || m_savedViewportHeight == 0)
  772. {
  773. AZ_Assert(false, "Could not get current window size");
  774. }
  775. else
  776. {
  777. m_shouldRestoreViewportSize = true;
  778. }
  779. // Setup the ScriptReporter to track and report the results
  780. m_scriptReporter.Reset();
  781. m_scriptReporter.SetAvailableToleranceLevels(m_imageComparisonOptions.GetAvailableToleranceLevels());
  782. if (m_imageComparisonOptions.IsLevelAdjusted())
  783. {
  784. m_scriptReporter.SetInvalidationMessage("Results are invalid because the tolerance level has been adjusted.");
  785. }
  786. else if (!m_imageComparisonOptions.IsScriptControlled())
  787. {
  788. m_scriptReporter.SetInvalidationMessage("Results are invalid because the tolerance level has been overridden.");
  789. }
  790. else
  791. {
  792. m_scriptReporter.SetInvalidationMessage("");
  793. }
  794. AZ_Assert(m_executingScripts.empty(), "There should be no active scripts at this point");
  795. ExecuteScript(scriptFilePath);
  796. }
  797. void ScriptManager::ExecuteScript(const AZStd::string& scriptFilePath)
  798. {
  799. AZ::Data::Asset<AZ::ScriptAsset> scriptAsset = AZ::RPI::AssetUtils::LoadAssetByProductPath<AZ::ScriptAsset>(scriptFilePath.c_str());
  800. if (!scriptAsset)
  801. {
  802. // Push an error operation on the back of the queue instead of reporting it immediately so it doesn't get lost
  803. // in front of a bunch of queued m_scriptOperations.
  804. Script_Error(AZStd::string::format("Could not find or load script asset '%s'.", scriptFilePath.c_str()));
  805. return;
  806. }
  807. if (s_instance->m_executingScripts.find(scriptAsset.GetId()) != s_instance->m_executingScripts.end())
  808. {
  809. Script_Error(AZStd::string::format("Calling script '%s' would likely cause an infinite loop and crash. Skipping.", scriptFilePath.c_str()));
  810. return;
  811. }
  812. if (s_instance->m_imageComparisonOptions.IsScriptControlled())
  813. {
  814. s_instance->m_imageComparisonOptions.SelectToleranceLevel(nullptr); // Clear the preset before each script to make sure the script is selecting it.
  815. }
  816. // Execute(script) will add commands to the m_scriptOperations. These should be considered part of their own test script, for reporting purposes.
  817. s_instance->m_scriptOperations.push([scriptFilePath]()
  818. {
  819. s_instance->m_scriptReporter.PushScript(scriptFilePath);
  820. }
  821. );
  822. s_instance->m_scriptOperations.push([scriptFilePath]()
  823. {
  824. AZ_Printf("Automation", "Running script '%s'...\n", scriptFilePath.c_str());
  825. }
  826. );
  827. s_instance->m_executingScripts.insert(scriptAsset.GetId());
  828. auto& scriptData = scriptAsset->m_data;
  829. if (!s_instance->m_scriptContext->Execute(scriptData.GetScriptBuffer().data(), scriptFilePath.c_str(), scriptData.GetScriptBuffer().size()))
  830. {
  831. // Push an error operation on the back of the queue instead of reporting it immediately so it doesn't get lost
  832. // in front of a bunch of queued m_scriptOperations.
  833. Script_Error(AZStd::string::format("Error running script '%s'.", scriptAsset.ToString<AZStd::string>().c_str()));
  834. }
  835. s_instance->m_executingScripts.erase(scriptAsset.GetId());
  836. // Execute(script) will have added commands to the m_scriptOperations. When they finish, consider this test as completed, for reporting purposes.
  837. s_instance->m_scriptOperations.push([]()
  838. {
  839. // We don't call m_scriptReporter.PopScript() yet because some cleanup needs to happen in TickScript() on the next frame.
  840. AZ_Assert(!s_instance->m_shouldPopScript, "m_shouldPopScript is already true");
  841. s_instance->m_shouldPopScript = true;
  842. }
  843. );
  844. }
  845. void ScriptManager::OnCameraMoveEnded(AZ::TypeId controllerTypeId, uint32_t channels)
  846. {
  847. if (controllerTypeId == azrtti_typeid<AZ::Debug::ArcBallControllerComponent>())
  848. {
  849. if (channels & AZ::Debug::ArcBallControllerChannel_Center)
  850. {
  851. AZ::Vector3 center = AZ::Vector3::CreateZero();
  852. AZ::Debug::ArcBallControllerRequestBus::EventResult(center, m_cameraEntity->GetId(), &AZ::Debug::ArcBallControllerRequests::GetCenter);
  853. ReportScriptableAction(AZStd::string::format("ArcBallCameraController_SetCenter(Vector3(%f, %f, %f))", (float)center.GetX(), (float)center.GetY(), (float)center.GetZ()));
  854. }
  855. if (channels & AZ::Debug::ArcBallControllerChannel_Pan)
  856. {
  857. AZ::Vector3 pan = AZ::Vector3::CreateZero();
  858. AZ::Debug::ArcBallControllerRequestBus::EventResult(pan, m_cameraEntity->GetId(), &AZ::Debug::ArcBallControllerRequests::GetPan);
  859. ReportScriptableAction(AZStd::string::format("ArcBallCameraController_SetPan(Vector3(%f, %f, %f))", (float)pan.GetX(), (float)pan.GetY(), (float)pan.GetZ()));
  860. }
  861. if (channels & AZ::Debug::ArcBallControllerChannel_Heading)
  862. {
  863. float heading = 0.0;
  864. AZ::Debug::ArcBallControllerRequestBus::EventResult(heading, m_cameraEntity->GetId(), &AZ::Debug::ArcBallControllerRequests::GetHeading);
  865. ReportScriptableAction(AZStd::string::format("ArcBallCameraController_SetHeading(DegToRad(%f))", AZ::RadToDeg(heading)));
  866. }
  867. if (channels & AZ::Debug::ArcBallControllerChannel_Pitch)
  868. {
  869. float pitch = 0.0;
  870. AZ::Debug::ArcBallControllerRequestBus::EventResult(pitch, m_cameraEntity->GetId(), &AZ::Debug::ArcBallControllerRequests::GetPitch);
  871. ReportScriptableAction(AZStd::string::format("ArcBallCameraController_SetPitch(DegToRad(%f))", AZ::RadToDeg(pitch)));
  872. }
  873. if (channels & AZ::Debug::ArcBallControllerChannel_Distance)
  874. {
  875. float distance = 0.0;
  876. AZ::Debug::ArcBallControllerRequestBus::EventResult(distance, m_cameraEntity->GetId(), &AZ::Debug::ArcBallControllerRequests::GetDistance);
  877. ReportScriptableAction(AZStd::string::format("ArcBallCameraController_SetDistance(%f)", distance));
  878. }
  879. }
  880. if (controllerTypeId == azrtti_typeid<AZ::Debug::NoClipControllerComponent>())
  881. {
  882. if (channels & AZ::Debug::NoClipControllerChannel_Position)
  883. {
  884. AZ::Vector3 position = AZ::Vector3::CreateZero();
  885. AZ::Debug::NoClipControllerRequestBus::EventResult(position, m_cameraEntity->GetId(), &AZ::Debug::NoClipControllerRequests::GetPosition);
  886. ReportScriptableAction(AZStd::string::format("NoClipCameraController_SetPosition(Vector3(%f, %f, %f))", (float)position.GetX(), (float)position.GetY(), (float)position.GetZ()));
  887. }
  888. if (channels & AZ::Debug::NoClipControllerChannel_Orientation)
  889. {
  890. float heading = 0.0;
  891. AZ::Debug::NoClipControllerRequestBus::EventResult(heading, m_cameraEntity->GetId(), &AZ::Debug::NoClipControllerRequests::GetHeading);
  892. ReportScriptableAction(AZStd::string::format("NoClipCameraController_SetHeading(DegToRad(%f))", AZ::RadToDeg(heading)));
  893. float pitch = 0.0;
  894. AZ::Debug::NoClipControllerRequestBus::EventResult(pitch, m_cameraEntity->GetId(), &AZ::Debug::NoClipControllerRequests::GetPitch);
  895. ReportScriptableAction(AZStd::string::format("NoClipCameraController_SetPitch(DegToRad(%f))", AZ::RadToDeg(pitch)));
  896. }
  897. if (channels & AZ::Debug::NoClipControllerChannel_Fov)
  898. {
  899. float fov = 0.0;
  900. AZ::Debug::NoClipControllerRequestBus::EventResult(fov, m_cameraEntity->GetId(), &AZ::Debug::NoClipControllerRequests::GetFov);
  901. ReportScriptableAction(AZStd::string::format("NoClipCameraController_SetFov(DegToRad(%f))", AZ::RadToDeg(fov)));
  902. }
  903. }
  904. }
  905. void ScriptManager::ReflectScriptContext(AZ::BehaviorContext* behaviorContext)
  906. {
  907. AZ::MathReflect(behaviorContext);
  908. AZ::SettingsRegistryScriptUtils::ReflectSettingsRegistryToBehaviorContext(*behaviorContext);
  909. // Utilities...
  910. behaviorContext->Method("RunScript", &Script_RunScript);
  911. behaviorContext->Method("Error", &Script_Error);
  912. behaviorContext->Method("Warning", &Script_Warning);
  913. behaviorContext->Method("Print", &Script_Print);
  914. behaviorContext->Method("IdleFrames", &Script_IdleFrames);
  915. behaviorContext->Method("IdleSeconds", &Script_IdleSeconds);
  916. behaviorContext->Method("LockFrameTime", &Script_LockFrameTime);
  917. behaviorContext->Method("UnlockFrameTime", &Script_UnlockFrameTime);
  918. behaviorContext->Method("ResizeViewport", &Script_ResizeViewport);
  919. behaviorContext->Method("SetShowImGui", &Script_SetShowImGui);
  920. behaviorContext->Method("ExecuteConsoleCommand", &Script_ExecuteConsoleCommand);
  921. // Utilities returning data (these special functions do return data because they don't read dynamic state)...
  922. behaviorContext->Method("ResolvePath", &Script_ResolvePath);
  923. behaviorContext->Method("NormalizePath", &Script_NormalizePath);
  924. behaviorContext->Method("DegToRad", &Script_DegToRad);
  925. behaviorContext->Method("GetRenderApiName", &Script_GetRenderApiName);
  926. behaviorContext->Method("GetRandomTestSeed", &Script_GetRandomTestSeed);
  927. // Samples...
  928. behaviorContext->Method("OpenSample", &Script_OpenSample);
  929. behaviorContext->Method("SetImguiValue", &Script_SetImguiValue);
  930. // Debug profilers...
  931. behaviorContext->Method("ShowTool", &Script_ShowTool);
  932. // Screenshots...
  933. behaviorContext->Method("SetScreenshotFolder", &Script_SetScreenshotFolder);
  934. behaviorContext->Method("SetTestEnvPath", &Script_SetTestEnvPath);
  935. behaviorContext->Method("SetOfficialBaselineImageFolder", &Script_SetOfficialBaselineImageFolder);
  936. behaviorContext->Method("SetLocalBaselineImageFolder", &Script_SetLocalBaselineImageFolder);
  937. behaviorContext->Method("SelectImageComparisonToleranceLevel", &Script_SelectImageComparisonToleranceLevel);
  938. behaviorContext->Method("CaptureScreenshot", &Script_CaptureScreenshot);
  939. behaviorContext->Method("CaptureScreenshotWithImGui", &Script_CaptureScreenshotWithImGui);
  940. behaviorContext->Method("CaptureScreenshotWithPreview", &Script_CaptureScreenshotWithPreview);
  941. behaviorContext->Method("CapturePassAttachment", &Script_CapturePassAttachment);
  942. // Profiling data...
  943. behaviorContext->Method("CapturePassTimestamp", &Script_CapturePassTimestamp);
  944. behaviorContext->Method("CaptureCpuFrameTime", &Script_CaptureCpuFrameTime);
  945. behaviorContext->Method("CapturePassPipelineStatistics", &Script_CapturePassPipelineStatistics);
  946. behaviorContext->Method("CaptureCpuProfilingStatistics", &Script_CaptureCpuProfilingStatistics);
  947. behaviorContext->Method("CaptureBenchmarkMetadata", &Script_CaptureBenchmarkMetadata);
  948. // Camera...
  949. behaviorContext->Method("ArcBallCameraController_SetCenter", &Script_ArcBallCameraController_SetCenter);
  950. behaviorContext->Method("ArcBallCameraController_SetPan", &Script_ArcBallCameraController_SetPan);
  951. behaviorContext->Method("ArcBallCameraController_SetDistance", &Script_ArcBallCameraController_SetDistance);
  952. behaviorContext->Method("ArcBallCameraController_SetHeading", &Script_ArcBallCameraController_SetHeading);
  953. behaviorContext->Method("ArcBallCameraController_SetPitch", &Script_ArcBallCameraController_SetPitch);
  954. behaviorContext->Method("NoClipCameraController_SetPosition", &Script_NoClipCameraController_SetPosition);
  955. behaviorContext->Method("NoClipCameraController_SetHeading", &Script_NoClipCameraController_SetHeading);
  956. behaviorContext->Method("NoClipCameraController_SetPitch", &Script_NoClipCameraController_SetPitch);
  957. behaviorContext->Method("NoClipCameraController_SetFov", &Script_NoClipCameraController_SetFov);
  958. // Asset System...
  959. AZ::BehaviorParameterOverrides expectedCountDetails = {"expectedCount", "Expected number of asset jobs; default=1", aznew AZ::BehaviorDefaultValue(1u)};
  960. const AZStd::array<AZ::BehaviorParameterOverrides, 2> assetTrackingExpectAssetArgs = {{ AZ::BehaviorParameterOverrides{}, expectedCountDetails }};
  961. behaviorContext->Method("AssetTracking_Start", &Script_AssetTracking_Start);
  962. behaviorContext->Method("AssetTracking_ExpectAsset", &Script_AssetTracking_ExpectAsset, assetTrackingExpectAssetArgs);
  963. behaviorContext->Method("AssetTracking_IdleUntilExpectedAssetsFinish", &Script_AssetTracking_IdleUntilExpectedAssetsFinish);
  964. behaviorContext->Method("AssetTracking_Stop", &Script_AssetTracking_Stop);
  965. }
  966. void ScriptManager::Script_Error(const AZStd::string& message)
  967. {
  968. auto func = [message]()
  969. {
  970. ReportScriptError(message.c_str());
  971. };
  972. s_instance->m_scriptOperations.push(AZStd::move(func));
  973. }
  974. void ScriptManager::Script_Warning(const AZStd::string& message)
  975. {
  976. auto func = [message]()
  977. {
  978. ReportScriptWarning(message.c_str());
  979. };
  980. s_instance->m_scriptOperations.push(AZStd::move(func));
  981. }
  982. void ScriptManager::Script_Print(const AZStd::string& message [[maybe_unused]])
  983. {
  984. #ifndef RELEASE // AZ_TracePrintf is a no-op in release builds
  985. auto func = [message]()
  986. {
  987. AZ_TracePrintf("Automation", "Script: %s\n", message.c_str());
  988. };
  989. s_instance->m_scriptOperations.push(AZStd::move(func));
  990. #endif
  991. }
  992. AZStd::string ScriptManager::Script_ResolvePath(const AZStd::string& path)
  993. {
  994. return Utils::ResolvePath(path);
  995. }
  996. AZStd::string ScriptManager::Script_NormalizePath(const AZStd::string& path)
  997. {
  998. AZStd::string normalizedPath = path;
  999. AzFramework::StringFunc::Path::Normalize(normalizedPath);
  1000. return normalizedPath;
  1001. }
  1002. void ScriptManager::Script_OpenSample(const AZStd::string& sampleName)
  1003. {
  1004. auto operation = [sampleName]()
  1005. {
  1006. AZ_DEBUG_STATIC_MEMEBER(instance, s_instance);
  1007. if (sampleName.empty())
  1008. {
  1009. SampleComponentManagerRequestBus::Broadcast(&SampleComponentManagerRequests::Reset);
  1010. }
  1011. else
  1012. {
  1013. bool foundSample = false;
  1014. SampleComponentManagerRequestBus::BroadcastResult(foundSample, &SampleComponentManagerRequests::OpenSample, sampleName);
  1015. if (foundSample)
  1016. {
  1017. // Samples need a few frames to initialize before consuming actions from ScriptableImGui,
  1018. // so we need to wait before letting the script schedule ScriptableImGui actions.
  1019. // They need 1 frame to activate, 1 frame to start ticking, and 1 frame to guarantee
  1020. // that a sample OnTick occurs before a ScriptManager::OnTick. We schedule
  1021. // a few extra just in case.
  1022. AZ_Assert(s_instance->m_scriptIdleFrames == 0, "m_scriptIdleFrames is being stomped");
  1023. s_instance->m_scriptIdleFrames = 6;
  1024. }
  1025. }
  1026. };
  1027. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1028. }
  1029. void ScriptManager::Script_ShowTool(const AZStd::string& toolName, bool enable)
  1030. {
  1031. auto operation = [toolName, enable]()
  1032. {
  1033. bool foundTool = false;
  1034. SampleComponentManagerRequestBus::BroadcastResult(foundTool, &SampleComponentManagerRequests::ShowTool, toolName, enable);
  1035. AZ_Warning("ScriptManager", foundTool, "Can't find [%s] tool", toolName.c_str());
  1036. };
  1037. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1038. }
  1039. void ScriptManager::Script_RunScript(const AZStd::string& scriptFilePath)
  1040. {
  1041. // Unlike other Script_ callback functions, we process immediately instead of pushing onto the m_scriptOperations queue.
  1042. // This function is special because running the script is what adds more commands onto the m_scriptOperations queue.
  1043. s_instance->ExecuteScript(scriptFilePath);
  1044. }
  1045. void ScriptManager::Script_IdleFrames(int numFrames)
  1046. {
  1047. auto operation = [numFrames]()
  1048. {
  1049. AZ_DEBUG_STATIC_MEMEBER(instance, s_instance);
  1050. AZ_Assert(s_instance->m_scriptIdleFrames == 0, "m_scriptIdleFrames is being stomped");
  1051. s_instance->m_scriptIdleFrames = numFrames;
  1052. };
  1053. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1054. }
  1055. void ScriptManager::Script_IdleSeconds(float numSeconds)
  1056. {
  1057. auto operation = [numSeconds]()
  1058. {
  1059. AZ_DEBUG_STATIC_MEMEBER(instance, s_instance);
  1060. s_instance->m_scriptIdleSeconds = numSeconds;
  1061. };
  1062. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1063. }
  1064. void ScriptManager::Script_LockFrameTime(float seconds)
  1065. {
  1066. auto operation = [seconds]()
  1067. {
  1068. AZ_DEBUG_STATIC_MEMEBER(instance, s_instance);
  1069. AZ::TimeUs us = AZ::SecondsToTimeUs(seconds);
  1070. AZ::CVarFixedString commandString = AZ::CVarFixedString::format("t_simulationTickDeltaOverride %" PRId64, static_cast<int64_t>(us));
  1071. AZ::Interface<AZ::IConsole>::Get()->PerformCommand(commandString.c_str());
  1072. s_instance->m_frameTimeIsLocked = true;
  1073. };
  1074. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1075. }
  1076. void ScriptManager::Script_UnlockFrameTime()
  1077. {
  1078. auto operation = []()
  1079. {
  1080. AZ_DEBUG_STATIC_MEMEBER(instance, s_instance);
  1081. AZ::Interface<AZ::IConsole>::Get()->PerformCommand("t_simulationTickDeltaOverride 0");
  1082. s_instance->m_frameTimeIsLocked = false;
  1083. };
  1084. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1085. }
  1086. void ScriptManager::Script_SetImguiValue(AZ::ScriptDataContext& dc)
  1087. {
  1088. if (dc.GetNumArguments() != 2)
  1089. {
  1090. ReportScriptError("Wrong number of arguments for SetImguiValue");
  1091. return;
  1092. }
  1093. if (!dc.IsString(0))
  1094. {
  1095. ReportScriptError("SetImguiValue first argument must be a string");
  1096. return;
  1097. }
  1098. const char* fieldName = nullptr;
  1099. dc.ReadArg(0, fieldName);
  1100. AZStd::string fieldNameString = fieldName; // Because the lambda will need to capture a copy of something, not a pointer
  1101. if (dc.IsBoolean(1))
  1102. {
  1103. bool value = false;
  1104. dc.ReadArg(1, value);
  1105. auto func = [fieldNameString, value]()
  1106. {
  1107. ScriptableImGui::SetBool(fieldNameString, value);
  1108. };
  1109. s_instance->m_scriptOperations.push(AZStd::move(func));
  1110. }
  1111. else if (dc.IsNumber(1))
  1112. {
  1113. float value = 0.0f;
  1114. dc.ReadArg(1, value);
  1115. auto func = [fieldNameString, value]()
  1116. {
  1117. ScriptableImGui::SetNumber(fieldNameString, value);
  1118. };
  1119. s_instance->m_scriptOperations.push(AZStd::move(func));
  1120. }
  1121. else if (dc.IsString(1))
  1122. {
  1123. const char* value = nullptr;
  1124. dc.ReadArg(1, value);
  1125. AZStd::string valueString = value; // Because the lambda will need to capture a copy of something, not a pointer
  1126. auto func = [fieldNameString, valueString]()
  1127. {
  1128. ScriptableImGui::SetString(fieldNameString, valueString);
  1129. };
  1130. s_instance->m_scriptOperations.push(AZStd::move(func));
  1131. }
  1132. else if (dc.IsClass<AZ::Vector3>(1))
  1133. {
  1134. AZ::Vector3 value = AZ::Vector3::CreateZero();
  1135. dc.ReadArg(1, value);
  1136. auto func = [fieldNameString, value]()
  1137. {
  1138. ScriptableImGui::SetVector(fieldNameString, value);
  1139. };
  1140. s_instance->m_scriptOperations.push(AZStd::move(func));
  1141. }
  1142. else if (dc.IsClass<AZ::Vector2>(1))
  1143. {
  1144. AZ::Vector2 value = AZ::Vector2::CreateZero();
  1145. dc.ReadArg(1, value);
  1146. auto func = [fieldNameString, value]()
  1147. {
  1148. ScriptableImGui::SetVector(fieldNameString, value);
  1149. };
  1150. s_instance->m_scriptOperations.push(AZStd::move(func));
  1151. }
  1152. }
  1153. void ScriptManager::Script_ResizeViewport(int width, int height)
  1154. {
  1155. auto operation = [width,height]()
  1156. {
  1157. if (Utils::SupportsResizeClientArea())
  1158. {
  1159. AzFramework::WindowPosOptions options;
  1160. options.m_ignoreScreenSizeLimit = true;
  1161. Utils::ResizeClientArea(width, height, options);
  1162. }
  1163. else
  1164. {
  1165. s_instance->ReportScriptError("ResizeViewport() is not supported on this platform");
  1166. }
  1167. };
  1168. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1169. }
  1170. void ScriptManager::Script_ExecuteConsoleCommand(const AZStd::string& command)
  1171. {
  1172. auto operation = [command]()
  1173. {
  1174. AZ::Interface<AZ::IConsole>::Get()->PerformCommand(command.c_str());
  1175. };
  1176. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1177. }
  1178. void ScriptManager::SetShowImGui(bool show)
  1179. {
  1180. m_prevShowImGui = m_showImGui;
  1181. if (show)
  1182. {
  1183. AZ::Render::ImGuiSystemRequestBus::Broadcast(&AZ::Render::ImGuiSystemRequestBus::Events::ShowAllImGuiPasses);
  1184. }
  1185. else
  1186. {
  1187. AZ::Render::ImGuiSystemRequestBus::Broadcast(&AZ::Render::ImGuiSystemRequestBus::Events::HideAllImGuiPasses);
  1188. }
  1189. m_showImGui = show;
  1190. }
  1191. void ScriptManager::Script_SetShowImGui(bool show)
  1192. {
  1193. auto operation = [show]()
  1194. {
  1195. s_instance->SetShowImGui(show);
  1196. };
  1197. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1198. }
  1199. bool ScriptManager::PrepareForScreenCapture(const AZStd::string& imageName)
  1200. {
  1201. AZ::Render::FrameCapturePathOutcome pathOutcome;
  1202. AZ::Render::FrameCaptureTestRequestBus::BroadcastResult(
  1203. pathOutcome,
  1204. &AZ::Render::FrameCaptureTestRequestBus::Events::BuildScreenshotFilePath,
  1205. imageName, true);
  1206. if (!pathOutcome.IsSuccess())
  1207. {
  1208. ReportScriptError(pathOutcome.GetError().m_errorMessage);
  1209. return false;
  1210. }
  1211. AZStd::string fullFilePath = pathOutcome.IsSuccess() ? pathOutcome.GetValue() : "";
  1212. // Delete the file if it already exists because if the screen capture fails, we don't want to do a screenshot comparison test using an old screenshot.
  1213. if (AZ::IO::LocalFileIO::GetInstance()->Exists(fullFilePath.c_str()) && !AZ::IO::LocalFileIO::GetInstance()->Remove(fullFilePath.c_str()))
  1214. {
  1215. ReportScriptError(AZStd::string::format("Failed to delete existing screenshot file '%s'.", fullFilePath.c_str()));
  1216. return false;
  1217. }
  1218. s_instance->m_scriptReporter.AddScreenshotTest(imageName);
  1219. s_instance->m_isCapturePending = true;
  1220. s_instance->PauseScript();
  1221. return true;
  1222. }
  1223. void ScriptManager::Script_SetScreenshotFolder(const AZStd::string& screenshotFolder)
  1224. {
  1225. auto operation = [screenshotFolder]()
  1226. {
  1227. AZ::Render::FrameCaptureTestRequestBus::Broadcast(
  1228. &AZ::Render::FrameCaptureTestRequestBus::Events::SetScreenshotFolder, screenshotFolder);
  1229. };
  1230. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1231. }
  1232. void ScriptManager::Script_SetTestEnvPath(const AZStd::string& envPath)
  1233. {
  1234. auto operation = [envPath]()
  1235. {
  1236. AZ::Render::FrameCaptureTestRequestBus::Broadcast(
  1237. &AZ::Render::FrameCaptureTestRequestBus::Events::SetTestEnvPath, envPath);
  1238. };
  1239. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1240. }
  1241. void ScriptManager::Script_SetOfficialBaselineImageFolder(const AZStd::string& baselineFolder)
  1242. {
  1243. auto operation = [baselineFolder]()
  1244. {
  1245. AZ::Render::FrameCaptureTestRequestBus::Broadcast(
  1246. &AZ::Render::FrameCaptureTestRequestBus::Events::SetOfficialBaselineImageFolder, baselineFolder);
  1247. };
  1248. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1249. }
  1250. void ScriptManager::Script_SetLocalBaselineImageFolder(const AZStd::string& baselineFolder)
  1251. {
  1252. auto operation = [baselineFolder]()
  1253. {
  1254. AZ::Render::FrameCaptureTestRequestBus::Broadcast(
  1255. &AZ::Render::FrameCaptureTestRequestBus::Events::SetLocalBaselineImageFolder, baselineFolder);
  1256. };
  1257. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1258. }
  1259. void ScriptManager::Script_SelectImageComparisonToleranceLevel(const AZStd::string& presetName)
  1260. {
  1261. auto operation = [presetName]()
  1262. {
  1263. s_instance->m_imageComparisonOptions.SelectToleranceLevel(presetName);
  1264. };
  1265. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1266. }
  1267. void ScriptManager::Script_CaptureScreenshot(const AZStd::string& imageName)
  1268. {
  1269. Script_SetShowImGui(false);
  1270. auto operation = [imageName]()
  1271. {
  1272. // Note this will pause the script until the capture is complete
  1273. if (PrepareForScreenCapture(imageName))
  1274. {
  1275. AZ::Render::FrameCapturePathOutcome pathOutcome;
  1276. AZ::Render::FrameCaptureTestRequestBus::BroadcastResult(
  1277. pathOutcome,
  1278. &AZ::Render::FrameCaptureTestRequestBus::Events::BuildScreenshotFilePath,
  1279. imageName, true);
  1280. if (!pathOutcome.IsSuccess())
  1281. {
  1282. ReportScriptError(pathOutcome.GetError().m_errorMessage);
  1283. s_instance->m_isCapturePending = false;
  1284. s_instance->m_frameCaptureId = AZ::Render::InvalidFrameCaptureId;
  1285. s_instance->ResumeScript();
  1286. return;
  1287. }
  1288. AZStd::string screenshotFilePath = pathOutcome.GetValue();
  1289. AZ_Assert(s_instance->m_frameCaptureId == AZ::Render::InvalidFrameCaptureId, "Attempting to start a capture while one is in progress");
  1290. AZ::Render::FrameCaptureOutcome capOutcome;
  1291. AZ::Render::FrameCaptureRequestBus::BroadcastResult(capOutcome, &AZ::Render::FrameCaptureRequestBus::Events::CaptureScreenshot, screenshotFilePath);
  1292. if (!capOutcome.IsSuccess())
  1293. {
  1294. ReportScriptError(AZStd::string::format("Failed to initiate screenshot capture for '%s: %s'", screenshotFilePath.c_str(), capOutcome.GetError().m_errorMessage.c_str()));
  1295. s_instance->m_isCapturePending = false;
  1296. s_instance->m_frameCaptureId = AZ::Render::InvalidFrameCaptureId;
  1297. s_instance->ResumeScript();
  1298. return;
  1299. }
  1300. s_instance->m_frameCaptureId = capOutcome.GetValue();
  1301. s_instance->AZ::Render::FrameCaptureNotificationBus::Handler::BusConnect(s_instance->m_frameCaptureId);
  1302. }
  1303. };
  1304. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1305. s_instance->m_scriptOperations.push([]()
  1306. {
  1307. s_instance->m_scriptReporter.CheckLatestScreenshot(s_instance->m_imageComparisonOptions.GetCurrentToleranceLevel());
  1308. });
  1309. // restore imgui show/hide
  1310. s_instance->m_scriptOperations.push([]()
  1311. {
  1312. s_instance->SetShowImGui(s_instance->m_prevShowImGui);
  1313. });
  1314. }
  1315. void ScriptManager::Script_CaptureScreenshotWithImGui(const AZStd::string& imageName)
  1316. {
  1317. Script_SetShowImGui(true);
  1318. auto operation = [imageName]()
  1319. {
  1320. // Note this will pause the script until the capture is complete
  1321. if (PrepareForScreenCapture(imageName))
  1322. {
  1323. AZ::Render::FrameCapturePathOutcome pathOutcome;
  1324. AZ::Render::FrameCaptureTestRequestBus::BroadcastResult(
  1325. pathOutcome,
  1326. &AZ::Render::FrameCaptureTestRequestBus::Events::BuildScreenshotFilePath,
  1327. imageName, true);
  1328. if (!pathOutcome.IsSuccess())
  1329. {
  1330. ReportScriptError(pathOutcome.GetError().m_errorMessage);
  1331. s_instance->m_isCapturePending = false;
  1332. s_instance->m_frameCaptureId = AZ::Render::InvalidFrameCaptureId;
  1333. s_instance->ResumeScript();
  1334. return;
  1335. }
  1336. AZStd::string screenshotFilePath = pathOutcome.GetValue();
  1337. AZ_Assert(s_instance->m_frameCaptureId == AZ::Render::InvalidFrameCaptureId, "Attempting to start a capture while one is in progress");
  1338. AZ::Render::FrameCaptureOutcome capOutcome;
  1339. AZ::Render::FrameCaptureRequestBus::BroadcastResult(capOutcome, &AZ::Render::FrameCaptureRequestBus::Events::CaptureScreenshot, screenshotFilePath);
  1340. if (!capOutcome.IsSuccess())
  1341. {
  1342. ReportScriptError(AZStd::string::format("Failed to initiate screenshot capture for '%s: %s'", screenshotFilePath.c_str(), capOutcome.GetError().m_errorMessage.c_str()));
  1343. s_instance->m_isCapturePending = false;
  1344. s_instance->m_frameCaptureId = AZ::Render::InvalidFrameCaptureId;
  1345. s_instance->ResumeScript();
  1346. return;
  1347. }
  1348. s_instance->m_frameCaptureId = capOutcome.GetValue();
  1349. s_instance->AZ::Render::FrameCaptureNotificationBus::Handler::BusConnect(s_instance->m_frameCaptureId);
  1350. }
  1351. };
  1352. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1353. s_instance->m_scriptOperations.push([]()
  1354. {
  1355. s_instance->m_scriptReporter.CheckLatestScreenshot(s_instance->m_imageComparisonOptions.GetCurrentToleranceLevel());
  1356. });
  1357. // restore imgui show/hide
  1358. s_instance->m_scriptOperations.push([]()
  1359. {
  1360. s_instance->SetShowImGui(s_instance->m_prevShowImGui);
  1361. });
  1362. }
  1363. void ScriptManager::Script_CaptureScreenshotWithPreview(const AZStd::string& imageName)
  1364. {
  1365. auto operation = [imageName]()
  1366. {
  1367. // Note this will pause the script until the capture is complete
  1368. if (PrepareForScreenCapture(imageName))
  1369. {
  1370. AZ::Render::FrameCapturePathOutcome pathOutcome;
  1371. AZ::Render::FrameCaptureTestRequestBus::BroadcastResult(
  1372. pathOutcome,
  1373. &AZ::Render::FrameCaptureTestRequestBus::Events::BuildScreenshotFilePath,
  1374. imageName, true);
  1375. if (!pathOutcome.IsSuccess())
  1376. {
  1377. ReportScriptError(pathOutcome.GetError().m_errorMessage);
  1378. s_instance->m_isCapturePending = false;
  1379. s_instance->m_frameCaptureId = AZ::Render::InvalidFrameCaptureId;
  1380. s_instance->ResumeScript();
  1381. return;
  1382. }
  1383. AZStd::string screenshotFilePath = pathOutcome.GetValue();
  1384. AZ_Assert(s_instance->m_frameCaptureId == AZ::Render::InvalidFrameCaptureId, "Attempting to start a capture while one is in progress");
  1385. AZ::Render::FrameCaptureOutcome capOutcome;
  1386. AZ::Render::FrameCaptureRequestBus::BroadcastResult(capOutcome, &AZ::Render::FrameCaptureRequestBus::Events::CaptureScreenshotWithPreview, screenshotFilePath);
  1387. if (!capOutcome.IsSuccess())
  1388. {
  1389. ReportScriptError(AZStd::string::format("Failed to initiate screenshot capture for '%s: %s'", screenshotFilePath.c_str(), capOutcome.GetError().m_errorMessage.c_str()));
  1390. s_instance->m_isCapturePending = false;
  1391. s_instance->m_frameCaptureId = AZ::Render::InvalidFrameCaptureId;
  1392. s_instance->ResumeScript();
  1393. return;
  1394. }
  1395. s_instance->m_frameCaptureId = capOutcome.GetValue();
  1396. s_instance->AZ::Render::FrameCaptureNotificationBus::Handler::BusConnect(s_instance->m_frameCaptureId);
  1397. }
  1398. };
  1399. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1400. s_instance->m_scriptOperations.push([]()
  1401. {
  1402. s_instance->m_scriptReporter.CheckLatestScreenshot(s_instance->m_imageComparisonOptions.GetCurrentToleranceLevel());
  1403. });
  1404. }
  1405. void ScriptManager::Script_CapturePassAttachment(AZ::ScriptDataContext& dc)
  1406. {
  1407. if (dc.GetNumArguments() != 3 && dc.GetNumArguments() != 4)
  1408. {
  1409. ReportScriptError("CapturePassAttachment needs three or four arguments");
  1410. return;
  1411. }
  1412. if (!dc.IsTable(0))
  1413. {
  1414. ReportScriptError("CapturePassAttachment's first argument must be a table of strings");
  1415. return;
  1416. }
  1417. if (!dc.IsString(1) || !dc.IsString(2))
  1418. {
  1419. ReportScriptError("CapturePassAttachment's second and third argument must be strings");
  1420. return;
  1421. }
  1422. if (dc.GetNumArguments() == 4 && !dc.IsString(3))
  1423. {
  1424. ReportScriptError("CapturePassAttachment's forth argument must be a string 'Input' or 'Output'");
  1425. return;
  1426. }
  1427. const char* stringValue = nullptr;
  1428. AZStd::vector<AZStd::string> passHierarchy;
  1429. AZStd::string slot;
  1430. AZStd::string imageName;
  1431. // read slot name and output file path
  1432. dc.ReadArg(1, stringValue);
  1433. slot = AZStd::string(stringValue);
  1434. dc.ReadArg(2, stringValue);
  1435. imageName = AZStd::string(stringValue);
  1436. AZ::RPI::PassAttachmentReadbackOption readbackOption = AZ::RPI::PassAttachmentReadbackOption::Output;
  1437. if (dc.GetNumArguments() == 4)
  1438. {
  1439. AZStd::string option;
  1440. dc.ReadArg(3, option);
  1441. if (option == "Input")
  1442. {
  1443. readbackOption = AZ::RPI::PassAttachmentReadbackOption::Input;
  1444. }
  1445. }
  1446. // read pass hierarchy
  1447. AZ::ScriptDataContext stringtable;
  1448. dc.InspectTable(0, stringtable);
  1449. const char* fieldName;
  1450. int fieldIndex;
  1451. int elementIndex;
  1452. while (stringtable.InspectNextElement(elementIndex, fieldName, fieldIndex))
  1453. {
  1454. if (fieldIndex != -1)
  1455. {
  1456. if (!stringtable.IsString(elementIndex))
  1457. {
  1458. ReportScriptError("CapturePassAttachment's first argument must contain only strings");
  1459. return;
  1460. }
  1461. const char* stringTableValue = nullptr;
  1462. if (stringtable.ReadValue(elementIndex, stringTableValue))
  1463. {
  1464. passHierarchy.push_back(stringTableValue);
  1465. }
  1466. }
  1467. }
  1468. auto operation = [passHierarchy, slot, imageName, readbackOption]()
  1469. {
  1470. // Note this will pause the script until the capture is complete
  1471. if (PrepareForScreenCapture(imageName))
  1472. {
  1473. AZ::Render::FrameCapturePathOutcome pathOutcome;
  1474. AZ::Render::FrameCaptureTestRequestBus::BroadcastResult(
  1475. pathOutcome,
  1476. &AZ::Render::FrameCaptureTestRequestBus::Events::BuildScreenshotFilePath,
  1477. imageName, true);
  1478. if (!pathOutcome.IsSuccess())
  1479. {
  1480. ReportScriptError(pathOutcome.GetError().m_errorMessage);
  1481. s_instance->m_isCapturePending = false;
  1482. s_instance->m_frameCaptureId = AZ::Render::InvalidFrameCaptureId;
  1483. s_instance->ResumeScript();
  1484. return;
  1485. }
  1486. AZStd::string screenshotFilePath = pathOutcome.GetValue();
  1487. AZ_Assert(s_instance->m_frameCaptureId == AZ::Render::InvalidFrameCaptureId, "Attempting to start a capture while one is in progress");
  1488. AZ::Render::FrameCaptureOutcome capOutcome;
  1489. AZ::Render::FrameCaptureRequestBus::BroadcastResult(capOutcome, &AZ::Render::FrameCaptureRequestBus::Events::CapturePassAttachment, screenshotFilePath, passHierarchy, slot, readbackOption);
  1490. if (!capOutcome.IsSuccess())
  1491. {
  1492. ReportScriptError(AZStd::string::format("Failed to initiate screenshot capture for '%s: %s'", screenshotFilePath.c_str(), capOutcome.GetError().m_errorMessage.c_str()));
  1493. s_instance->m_isCapturePending = false;
  1494. s_instance->m_frameCaptureId = AZ::Render::InvalidFrameCaptureId;
  1495. s_instance->ResumeScript();
  1496. return;
  1497. }
  1498. s_instance->m_frameCaptureId = capOutcome.GetValue();
  1499. s_instance->AZ::Render::FrameCaptureNotificationBus::Handler::BusConnect(s_instance->m_frameCaptureId);
  1500. }
  1501. };
  1502. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1503. s_instance->m_scriptOperations.push([]()
  1504. {
  1505. s_instance->m_scriptReporter.CheckLatestScreenshot(s_instance->m_imageComparisonOptions.GetCurrentToleranceLevel());
  1506. });
  1507. }
  1508. void ScriptManager::OnFrameCaptureFinished(AZ::Render::FrameCaptureResult result, const AZStd::string &info)
  1509. {
  1510. m_isCapturePending = false;
  1511. m_frameCaptureId = AZ::Render::InvalidFrameCaptureId;
  1512. AZ::Render::FrameCaptureNotificationBus::Handler::BusDisconnect();
  1513. ResumeScript();
  1514. // This is checking for the exact scenario that results from an HDR setup. The goal is to add a very specific and prominent message that will
  1515. // alert users to a common issue and what action to take. Any other Format issues will be reported by FrameCaptureSystemComponent with a
  1516. // "Can't save image with format %s to a ppm file" message.
  1517. if (result == AZ::Render::FrameCaptureResult::UnsupportedFormat && info.find(AZ::RHI::ToString(AZ::RHI::Format::R10G10B10A2_UNORM)) != AZStd::string::npos)
  1518. {
  1519. m_messageBox.OpenPopupMessage("HDR Not Supported", "Screen capture testing is not supported in HDR. Please change the system configuration to disable the HDR display feature.");
  1520. AbortScripts("Script(s) aborted due to HDR configuration.");
  1521. }
  1522. }
  1523. void ScriptManager::OnCaptureQueryTimestampFinished([[maybe_unused]] bool result, [[maybe_unused]] const AZStd::string& info)
  1524. {
  1525. m_isCapturePending = false;
  1526. AZ::Render::ProfilingCaptureNotificationBus::Handler::BusDisconnect();
  1527. ResumeScript();
  1528. }
  1529. void ScriptManager::OnCaptureCpuFrameTimeFinished([[maybe_unused]] bool result, [[maybe_unused]] const AZStd::string& info)
  1530. {
  1531. m_isCapturePending = false;
  1532. AZ::Render::ProfilingCaptureNotificationBus::Handler::BusDisconnect();
  1533. ResumeScript();
  1534. }
  1535. void ScriptManager::OnCaptureQueryPipelineStatisticsFinished([[maybe_unused]] bool result, [[maybe_unused]] const AZStd::string& info)
  1536. {
  1537. m_isCapturePending = false;
  1538. AZ::Render::ProfilingCaptureNotificationBus::Handler::BusDisconnect();
  1539. ResumeScript();
  1540. }
  1541. void ScriptManager::OnCaptureFinished([[maybe_unused]] bool result, [[maybe_unused]] const AZStd::string& info)
  1542. {
  1543. m_isCapturePending = false;
  1544. AZ::Debug::ProfilerNotificationBus::Handler::BusDisconnect();
  1545. ResumeScript();
  1546. }
  1547. void ScriptManager::OnCaptureBenchmarkMetadataFinished([[maybe_unused]] bool result, [[maybe_unused]] const AZStd::string& info)
  1548. {
  1549. m_isCapturePending = false;
  1550. AZ::Render::ProfilingCaptureNotificationBus::Handler::BusDisconnect();
  1551. ResumeScript();
  1552. }
  1553. void ScriptManager::Script_CapturePassTimestamp(AZ::ScriptDataContext& dc)
  1554. {
  1555. AZStd::string outputFilePath;
  1556. const bool readScriptDataContext = ValidateProfilingCaptureScripContexts(dc, outputFilePath);
  1557. if (!readScriptDataContext)
  1558. {
  1559. return;
  1560. }
  1561. auto operation = [outputFilePath]()
  1562. {
  1563. s_instance->m_isCapturePending = true;
  1564. s_instance->AZ::Render::ProfilingCaptureNotificationBus::Handler::BusConnect();
  1565. s_instance->PauseScript();
  1566. AZ::Render::ProfilingCaptureRequestBus::Broadcast(&AZ::Render::ProfilingCaptureRequestBus::Events::CapturePassTimestamp, outputFilePath);
  1567. };
  1568. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1569. }
  1570. void ScriptManager::Script_CaptureCpuFrameTime(AZ::ScriptDataContext& dc)
  1571. {
  1572. AZStd::string outputFilePath;
  1573. const bool readScriptDataContext = ValidateProfilingCaptureScripContexts(dc, outputFilePath);
  1574. if (!readScriptDataContext)
  1575. {
  1576. return;
  1577. }
  1578. auto operation = [outputFilePath]()
  1579. {
  1580. s_instance->m_isCapturePending = true;
  1581. s_instance->AZ::Render::ProfilingCaptureNotificationBus::Handler::BusConnect();
  1582. s_instance->PauseScript();
  1583. AZ::Render::ProfilingCaptureRequestBus::Broadcast(&AZ::Render::ProfilingCaptureRequestBus::Events::CaptureCpuFrameTime, outputFilePath);
  1584. };
  1585. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1586. }
  1587. void ScriptManager::Script_CapturePassPipelineStatistics(AZ::ScriptDataContext& dc)
  1588. {
  1589. AZStd::string outputFilePath;
  1590. const bool readScriptDataContext = ValidateProfilingCaptureScripContexts(dc, outputFilePath);
  1591. if (!readScriptDataContext)
  1592. {
  1593. return;
  1594. }
  1595. auto operation = [outputFilePath]()
  1596. {
  1597. s_instance->m_isCapturePending = true;
  1598. s_instance->AZ::Render::ProfilingCaptureNotificationBus::Handler::BusConnect();
  1599. s_instance->PauseScript();
  1600. AZ::Render::ProfilingCaptureRequestBus::Broadcast(&AZ::Render::ProfilingCaptureRequestBus::Events::CapturePassPipelineStatistics, outputFilePath);
  1601. };
  1602. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1603. }
  1604. void ScriptManager::Script_CaptureCpuProfilingStatistics(AZ::ScriptDataContext& dc)
  1605. {
  1606. AZStd::string outputFilePath;
  1607. const bool readScriptDataContext = ValidateProfilingCaptureScripContexts(dc, outputFilePath);
  1608. if (!readScriptDataContext)
  1609. {
  1610. return;
  1611. }
  1612. auto operation = [outputFilePath]()
  1613. {
  1614. s_instance->m_isCapturePending = true;
  1615. s_instance->AZ::Debug::ProfilerNotificationBus::Handler::BusConnect();
  1616. s_instance->PauseScript();
  1617. if (auto profilerSystem = AZ::Debug::ProfilerSystemInterface::Get(); profilerSystem)
  1618. {
  1619. profilerSystem->CaptureFrame(outputFilePath);
  1620. }
  1621. };
  1622. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1623. }
  1624. void ScriptManager::Script_CaptureBenchmarkMetadata(AZ::ScriptDataContext& dc)
  1625. {
  1626. if (dc.GetNumArguments() != 2)
  1627. {
  1628. ReportScriptError("CaptureBenchmarkMetadata needs two arguments, benchmarkName and outputFilePath.");
  1629. return;
  1630. }
  1631. if (!dc.IsString(0) || !dc.IsString(1))
  1632. {
  1633. ReportScriptError("CaptureBenchmarkMetadata's arguments benchmarkName and outputFilePath must both be of type string.");
  1634. return;
  1635. }
  1636. const char* stringValue = nullptr;
  1637. AZStd::string benchmarkName;
  1638. AZStd::string outputFilePath;
  1639. dc.ReadArg(0, stringValue);
  1640. benchmarkName = AZStd::string(stringValue);
  1641. dc.ReadArg(1, stringValue);
  1642. outputFilePath = AZStd::string(stringValue);
  1643. auto operation = [benchmarkName, outputFilePath]()
  1644. {
  1645. s_instance->m_isCapturePending = true;
  1646. s_instance->AZ::Render::ProfilingCaptureNotificationBus::Handler::BusConnect();
  1647. s_instance->PauseScript();
  1648. AZ::Render::ProfilingCaptureRequestBus::Broadcast(&AZ::Render::ProfilingCaptureRequestBus::Events::CaptureBenchmarkMetadata, benchmarkName, outputFilePath);
  1649. };
  1650. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1651. }
  1652. bool ScriptManager::ValidateProfilingCaptureScripContexts(AZ::ScriptDataContext& dc, AZStd::string& outputFilePath)
  1653. {
  1654. if (dc.GetNumArguments() != 1)
  1655. {
  1656. ReportScriptError("ProfilingCaptureScriptDataContext needs one argument");
  1657. return false;
  1658. }
  1659. if (!dc.IsString(0))
  1660. {
  1661. ReportScriptError("ProfilingCaptureScriptDataContext's first (and only) argument must be of type string");
  1662. return false;
  1663. }
  1664. // Read slot name and output file path
  1665. const char* stringValue = nullptr;
  1666. dc.ReadArg(0, stringValue);
  1667. if (stringValue == nullptr)
  1668. {
  1669. ReportScriptError("ProfilingCaptureScriptDataContext failed to read the string value");
  1670. return false;
  1671. }
  1672. outputFilePath = AZStd::string(stringValue);
  1673. return true;
  1674. }
  1675. float ScriptManager::Script_DegToRad(float degrees)
  1676. {
  1677. return AZ::DegToRad(degrees);
  1678. }
  1679. AZStd::string ScriptManager::Script_GetRenderApiName()
  1680. {
  1681. AZ::RPI::RPISystemInterface* rpiSystem = AZ::RPI::RPISystemInterface::Get();
  1682. return rpiSystem->GetRenderApiName().GetCStr();
  1683. }
  1684. int ScriptManager::Script_GetRandomTestSeed()
  1685. {
  1686. return s_instance->m_testSuiteRunConfig.m_randomSeed;
  1687. }
  1688. void ScriptManager::CheckArcBallControllerHandler()
  1689. {
  1690. if (0 == AZ::Debug::ArcBallControllerRequestBus::GetNumOfEventHandlers(s_instance->m_cameraEntity->GetId()))
  1691. {
  1692. ReportScriptError("There is no handler for ArcBallControllerRequestBus for the camera entity.");
  1693. }
  1694. }
  1695. void ScriptManager::CheckNoClipControllerHandler()
  1696. {
  1697. if (0 == AZ::Debug::NoClipControllerRequestBus::GetNumOfEventHandlers(s_instance->m_cameraEntity->GetId()))
  1698. {
  1699. ReportScriptError("There is no handler for NoClipControllerRequestBus for the camera entity.");
  1700. }
  1701. }
  1702. void ScriptManager::Script_ArcBallCameraController_SetCenter(AZ::Vector3 center)
  1703. {
  1704. auto operation = [center]()
  1705. {
  1706. AZ_DEBUG_STATIC_MEMEBER(instance, s_instance);
  1707. CheckArcBallControllerHandler();
  1708. AZ::Debug::ArcBallControllerRequestBus::Event(s_instance->m_cameraEntity->GetId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetCenter, center);
  1709. };
  1710. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1711. }
  1712. void ScriptManager::Script_ArcBallCameraController_SetPan(AZ::Vector3 pan)
  1713. {
  1714. auto operation = [pan]()
  1715. {
  1716. AZ_DEBUG_STATIC_MEMEBER(instance, s_instance);
  1717. CheckArcBallControllerHandler();
  1718. AZ::Debug::ArcBallControllerRequestBus::Event(s_instance->m_cameraEntity->GetId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetPan, pan);
  1719. };
  1720. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1721. }
  1722. void ScriptManager::Script_ArcBallCameraController_SetDistance(float distance)
  1723. {
  1724. auto operation = [distance]()
  1725. {
  1726. AZ_DEBUG_STATIC_MEMEBER(instance, s_instance);
  1727. CheckArcBallControllerHandler();
  1728. AZ::Debug::ArcBallControllerRequestBus::Event(s_instance->m_cameraEntity->GetId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetDistance, distance);
  1729. };
  1730. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1731. }
  1732. void ScriptManager::Script_ArcBallCameraController_SetHeading(float heading)
  1733. {
  1734. auto operation = [heading]()
  1735. {
  1736. AZ_DEBUG_STATIC_MEMEBER(instance, s_instance);
  1737. CheckArcBallControllerHandler();
  1738. AZ::Debug::ArcBallControllerRequestBus::Event(s_instance->m_cameraEntity->GetId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetHeading, heading);
  1739. };
  1740. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1741. }
  1742. void ScriptManager::Script_ArcBallCameraController_SetPitch(float pitch)
  1743. {
  1744. auto operation = [pitch]()
  1745. {
  1746. AZ_DEBUG_STATIC_MEMEBER(instance, s_instance);
  1747. CheckArcBallControllerHandler();
  1748. AZ::Debug::ArcBallControllerRequestBus::Event(s_instance->m_cameraEntity->GetId(), &AZ::Debug::ArcBallControllerRequestBus::Events::SetPitch, pitch);
  1749. };
  1750. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1751. }
  1752. void ScriptManager::Script_NoClipCameraController_SetPosition(AZ::Vector3 position)
  1753. {
  1754. auto operation = [position]()
  1755. {
  1756. AZ_DEBUG_STATIC_MEMEBER(instance, s_instance);
  1757. CheckNoClipControllerHandler();
  1758. AZ::Debug::NoClipControllerRequestBus::Event(s_instance->m_cameraEntity->GetId(), &AZ::Debug::NoClipControllerRequestBus::Events::SetPosition, position);
  1759. };
  1760. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1761. }
  1762. void ScriptManager::Script_NoClipCameraController_SetHeading(float heading)
  1763. {
  1764. auto operation = [heading]()
  1765. {
  1766. AZ_DEBUG_STATIC_MEMEBER(instance, s_instance);
  1767. CheckNoClipControllerHandler();
  1768. AZ::Debug::NoClipControllerRequestBus::Event(s_instance->m_cameraEntity->GetId(), &AZ::Debug::NoClipControllerRequestBus::Events::SetHeading, heading);
  1769. };
  1770. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1771. }
  1772. void ScriptManager::Script_NoClipCameraController_SetPitch(float pitch)
  1773. {
  1774. auto operation = [pitch]()
  1775. {
  1776. AZ_DEBUG_STATIC_MEMEBER(instance, s_instance);
  1777. CheckNoClipControllerHandler();
  1778. AZ::Debug::NoClipControllerRequestBus::Event(s_instance->m_cameraEntity->GetId(), &AZ::Debug::NoClipControllerRequestBus::Events::SetPitch, pitch);
  1779. };
  1780. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1781. }
  1782. void ScriptManager::Script_NoClipCameraController_SetFov(float fov)
  1783. {
  1784. auto operation = [fov]()
  1785. {
  1786. AZ_DEBUG_STATIC_MEMEBER(instance, s_instance);
  1787. CheckNoClipControllerHandler();
  1788. AZ::Debug::NoClipControllerRequestBus::Event(s_instance->m_cameraEntity->GetId(), &AZ::Debug::NoClipControllerRequestBus::Events::SetFov, fov);
  1789. };
  1790. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1791. }
  1792. void ScriptManager::Script_AssetTracking_Start()
  1793. {
  1794. auto operation = []()
  1795. {
  1796. AZ_DEBUG_STATIC_MEMEBER(instance, s_instance);
  1797. s_instance->m_assetStatusTracker.StartTracking();
  1798. };
  1799. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1800. }
  1801. void ScriptManager::Script_AssetTracking_ExpectAsset(const AZStd::string& sourceAssetPath, uint32_t expectedCount)
  1802. {
  1803. auto operation = [sourceAssetPath, expectedCount]()
  1804. {
  1805. AZ_DEBUG_STATIC_MEMEBER(instance, s_instance);
  1806. s_instance->m_assetStatusTracker.ExpectAsset(sourceAssetPath, expectedCount);
  1807. };
  1808. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1809. }
  1810. void ScriptManager::Script_AssetTracking_IdleUntilExpectedAssetsFinish(float timeout)
  1811. {
  1812. auto operation = [timeout]()
  1813. {
  1814. AZ_DEBUG_STATIC_MEMEBER(instance, s_instance);
  1815. AZ_Assert(!s_instance->m_waitForAssetTracker, "It shouldn't be possible to run the next command until m_waitForAssetTracker is false");
  1816. s_instance->m_waitForAssetTracker = true;
  1817. s_instance->m_assetTrackingTimeout = timeout;
  1818. };
  1819. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1820. }
  1821. void ScriptManager::Script_AssetTracking_Stop()
  1822. {
  1823. auto operation = []()
  1824. {
  1825. AZ_DEBUG_STATIC_MEMEBER(instance, s_instance);
  1826. s_instance->m_assetStatusTracker.StopTracking();
  1827. };
  1828. s_instance->m_scriptOperations.push(AZStd::move(operation));
  1829. }
  1830. } // namespace AtomSampleViewer