SimulationManager.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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 "SimulationManager.h"
  9. #include "SimulationInterfaces/SimulationMangerRequestBus.h"
  10. #include <AzCore/Component/ComponentApplicationBus.h>
  11. #include <AzCore/Serialization/SerializeContext.h>
  12. #include <AzCore/Settings/SettingsRegistry.h>
  13. #include <AzFramework/Components/ConsoleBus.h>
  14. #include <AzFramework/Physics/PhysicsSystem.h>
  15. #include <SimulationInterfaces/SimulationFeaturesAggregatorRequestBus.h>
  16. #include <SimulationInterfaces/SimulationInterfacesTypeIds.h>
  17. #include <simulation_interfaces/msg/simulator_features.hpp>
  18. namespace SimulationInterfaces
  19. {
  20. namespace
  21. {
  22. constexpr AZStd::string_view StartInStoppedStateKey = "/SimulationInterfaces/StartInStoppedState";
  23. bool StartInStoppedState()
  24. {
  25. AZ::SettingsRegistryInterface* settingsRegistry = AZ::SettingsRegistry::Get();
  26. AZ_Assert(settingsRegistry, "Settings Registry is not available");
  27. bool output = true;
  28. settingsRegistry->Get(output, StartInStoppedStateKey);
  29. return output;
  30. }
  31. } // namespace
  32. AZ_COMPONENT_IMPL(SimulationManager, "SimulationManager", SimulationManagerTypeId);
  33. void SimulationManager::Reflect(AZ::ReflectContext* context)
  34. {
  35. if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  36. {
  37. serializeContext->Class<SimulationManager, AZ::Component>()->Version(0);
  38. }
  39. }
  40. void SimulationManager::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
  41. {
  42. provided.push_back(AZ_CRC_CE("SimulationManagerService"));
  43. }
  44. void SimulationManager::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
  45. {
  46. incompatible.push_back(AZ_CRC_CE("SimulationManagerService"));
  47. }
  48. void SimulationManager::GetRequiredServices([[maybe_unused]] AZ::ComponentDescriptor::DependencyArrayType& required)
  49. {
  50. required.push_back(AZ_CRC_CE("PhysicsService"));
  51. required.push_back(AZ_CRC_CE("SimulationFeaturesAggregator"));
  52. }
  53. void SimulationManager::GetDependentServices([[maybe_unused]] AZ::ComponentDescriptor::DependencyArrayType& dependent)
  54. {
  55. dependent.push_back(AZ_CRC_CE("SimulationFeaturesAggregator"));
  56. }
  57. SimulationManager::SimulationManager()
  58. {
  59. if (SimulationManagerRequestBusInterface::Get() == nullptr)
  60. {
  61. SimulationManagerRequestBusInterface::Register(this);
  62. }
  63. }
  64. SimulationManager::~SimulationManager()
  65. {
  66. if (SimulationManagerRequestBusInterface::Get() == this)
  67. {
  68. SimulationManagerRequestBusInterface::Unregister(this);
  69. }
  70. }
  71. void SimulationManager::Init()
  72. {
  73. }
  74. void SimulationManager::InitializeSimulationState()
  75. {
  76. // if start in stopped state, pause simulation. Default state for simulation by the standard is STOPPED and
  77. // SetSimulationState has logic to prevent transition to the same state.
  78. if (StartInStoppedState())
  79. {
  80. m_simulationState = simulation_interfaces::msg::SimulationState::STATE_STOPPED;
  81. SetSimulationPaused(true);
  82. }
  83. else
  84. {
  85. SetSimulationState(simulation_interfaces::msg::SimulationState::STATE_PLAYING);
  86. }
  87. }
  88. void SimulationManager::Activate()
  89. {
  90. AzFramework::LevelSystemLifecycleNotificationBus::Handler::BusDisconnect();
  91. SimulationManagerRequestBus::Handler::BusConnect();
  92. SimulationFeaturesAggregatorRequestBus::Broadcast(
  93. &SimulationFeaturesAggregatorRequests::AddSimulationFeatures,
  94. AZStd::unordered_set<SimulationFeatureType>{ simulation_interfaces::msg::SimulatorFeatures::SIMULATION_RESET,
  95. simulation_interfaces::msg::SimulatorFeatures::SIMULATION_RESET_TIME,
  96. simulation_interfaces::msg::SimulatorFeatures::SIMULATION_RESET_STATE,
  97. simulation_interfaces::msg::SimulatorFeatures::SIMULATION_RESET_SPAWNED,
  98. simulation_interfaces::msg::SimulatorFeatures::SIMULATION_STATE_PAUSE,
  99. simulation_interfaces::msg::SimulatorFeatures::STEP_SIMULATION_SINGLE,
  100. simulation_interfaces::msg::SimulatorFeatures::STEP_SIMULATION_MULTIPLE,
  101. simulation_interfaces::msg::SimulatorFeatures::STEP_SIMULATION_ACTION,
  102. simulation_interfaces::msg::SimulatorFeatures::SIMULATION_STATE_SETTING,
  103. simulation_interfaces::msg::SimulatorFeatures::SIMULATION_STATE_GETTING });
  104. AZ::SystemTickBus::QueueFunction(
  105. [this]()
  106. {
  107. InitializeSimulationState();
  108. });
  109. }
  110. void SimulationManager::Deactivate()
  111. {
  112. SimulationManagerRequestBus::Handler::BusDisconnect();
  113. }
  114. bool SimulationManager::IsSimulationPaused() const
  115. {
  116. return m_isSimulationPaused;
  117. }
  118. bool SimulationManager::IsSimulationStepsActive() const
  119. {
  120. return m_simulationFinishEvent.IsConnected();
  121. }
  122. void SimulationManager::CancelStepSimulation()
  123. {
  124. if (m_simulationFinishEvent.IsConnected())
  125. {
  126. m_simulationFinishEvent.Disconnect();
  127. SetSimulationPaused(true);
  128. m_numberOfPhysicsSteps = 0;
  129. }
  130. }
  131. void SimulationManager::SetSimulationPaused(bool paused)
  132. {
  133. // get az physics system
  134. auto* physicsSystem = AZ::Interface<AzPhysics::SystemInterface>::Get();
  135. AZ_Assert(physicsSystem, "Physics system is not available");
  136. const auto& sceneHandlers = physicsSystem->GetAllScenes();
  137. [[maybe_unused]] auto* sceneInterface = AZ::Interface<AzPhysics::SceneInterface>::Get();
  138. AZ_Assert(sceneInterface, "Physics scene interface is not available");
  139. for (auto& scene : sceneHandlers)
  140. {
  141. AZ_Assert(scene, "Physics scene is not available");
  142. scene->SetEnabled(!paused);
  143. m_isSimulationPaused = paused;
  144. }
  145. }
  146. void SimulationManager::StepSimulation(AZ::u64 steps)
  147. {
  148. if (steps == 0)
  149. {
  150. return;
  151. }
  152. m_numberOfPhysicsSteps = steps;
  153. // install handler
  154. m_simulationFinishEvent = AzPhysics::SceneEvents::OnSceneSimulationFinishHandler(
  155. [this](AzPhysics::SceneHandle sceneHandle, float)
  156. {
  157. m_numberOfPhysicsSteps--;
  158. AZ_Printf("SimulationManager", "Physics simulation step finished. Remaining steps: %d", m_numberOfPhysicsSteps);
  159. SimulationManagerNotificationsBus::Broadcast(
  160. &SimulationManagerNotifications::OnSimulationStepFinish, m_numberOfPhysicsSteps);
  161. if (m_numberOfPhysicsSteps <= 0)
  162. {
  163. SetSimulationPaused(true);
  164. // remove handler
  165. m_simulationFinishEvent.Disconnect();
  166. }
  167. });
  168. // get default scene
  169. [[maybe_unused]] auto* physicsSystem = AZ::Interface<AzPhysics::SystemInterface>::Get();
  170. AZ_Assert(physicsSystem, "Physics system is not available");
  171. auto* sceneInterface = AZ::Interface<AzPhysics::SceneInterface>::Get();
  172. AZ_Assert(sceneInterface, "Physics scene interface is not available");
  173. AzPhysics::SceneHandle defaultScene = sceneInterface->GetSceneHandle(AzPhysics::DefaultPhysicsSceneName);
  174. auto scene = sceneInterface->GetScene(defaultScene);
  175. AZ_Assert(scene, "Default physics scene is not available");
  176. // install handler
  177. scene->RegisterSceneSimulationFinishHandler(m_simulationFinishEvent);
  178. SetSimulationPaused(false);
  179. }
  180. void SimulationManager::ReloadLevel(SimulationManagerRequests::ReloadLevelCallback completionCallback)
  181. {
  182. AzFramework::LevelSystemLifecycleNotificationBus::Handler::BusConnect();
  183. m_reloadLevelCallback = completionCallback;
  184. // We need to delete all entities before reloading the level
  185. DeletionCompletedCb deleteAllCompletion = [](const AZ::Outcome<void, FailedResult>& result)
  186. {
  187. AZ_Trace("SimulationManager", "Delete all entities completed: %s, reload level", result.IsSuccess() ? "true" : "false");
  188. const char* levelName = AZ::Interface<AzFramework::ILevelSystemLifecycle>::Get()->GetCurrentLevelName();
  189. AzFramework::ConsoleRequestBus::Broadcast(&AzFramework::ConsoleRequests::ExecuteConsoleCommand, "UnloadLevel");
  190. AZStd::string command = AZStd::string::format("LoadLevel %s", levelName);
  191. AzFramework::ConsoleRequestBus::Broadcast(&AzFramework::ConsoleRequests::ExecuteConsoleCommand, command.c_str());
  192. };
  193. // delete spawned entities
  194. SimulationEntityManagerRequestBus::Broadcast(&SimulationEntityManagerRequests::DeleteAllEntities, deleteAllCompletion);
  195. }
  196. void SimulationManager::OnLoadingComplete(const char* levelName)
  197. {
  198. AZ_Printf("SimulationManager", "Level loading started: %s", levelName);
  199. if (m_reloadLevelCallback)
  200. {
  201. m_reloadLevelCallback();
  202. m_reloadLevelCallback = nullptr;
  203. }
  204. // reset of the simulation, assign the same state as at the beginning
  205. InitializeSimulationState();
  206. AzFramework::LevelSystemLifecycleNotificationBus::Handler::BusDisconnect();
  207. }
  208. SimulationState SimulationManager::GetSimulationState() const
  209. {
  210. return m_simulationState;
  211. }
  212. AZ::Outcome<void, FailedResult> SimulationManager::SetSimulationState(SimulationState stateToSet)
  213. {
  214. // check if simulation is in desire state
  215. if (m_simulationState == stateToSet)
  216. {
  217. return AZ::Failure(FailedResult(
  218. simulation_interfaces::srv::SetSimulationState::Response::ALREADY_IN_TARGET_STATE,
  219. "Simulation is already in requested state, transition unecessary"));
  220. }
  221. if (IsTransitionForbidden(stateToSet))
  222. {
  223. return AZ::Failure(FailedResult(
  224. simulation_interfaces::srv::SetSimulationState::Response::INCORRECT_TRANSITION,
  225. AZStd::string::format("Requested transition (%d -> %d) is forbidden", m_simulationState, stateToSet)));
  226. }
  227. switch (stateToSet)
  228. {
  229. case simulation_interfaces::msg::SimulationState::STATE_STOPPED:
  230. {
  231. SimulationManagerRequests::ReloadLevelCallback cb = []()
  232. {
  233. SimulationInterfaces::SimulationManagerRequestBus::Broadcast(
  234. &SimulationInterfaces::SimulationManagerRequests::SetSimulationPaused, true);
  235. };
  236. ReloadLevel(cb);
  237. break;
  238. }
  239. case simulation_interfaces::msg::SimulationState::STATE_PLAYING:
  240. {
  241. SetSimulationPaused(false);
  242. break;
  243. }
  244. case simulation_interfaces::msg::SimulationState::STATE_PAUSED:
  245. {
  246. SetSimulationPaused(true);
  247. break;
  248. }
  249. case simulation_interfaces::msg::SimulationState::STATE_QUITTING:
  250. {
  251. // stop simulation -> kill the simulator.
  252. SetSimulationPaused(true);
  253. // queue to allow status of this method to be returned, then start quitting
  254. AZ::SystemTickBus::QueueFunction(
  255. []()
  256. {
  257. AzFramework::ConsoleRequestBus::Broadcast(&AzFramework::ConsoleRequests::ExecuteConsoleCommand, "quit");
  258. });
  259. break;
  260. }
  261. default:
  262. {
  263. return AZ::Failure(FailedResult(
  264. simulation_interfaces::srv::SetSimulationState::Response::INCORRECT_TRANSITION, "Requested state doesn't exists"));
  265. break;
  266. }
  267. }
  268. m_simulationState = stateToSet;
  269. return AZ::Success();
  270. }
  271. bool SimulationManager::IsTransitionForbidden(SimulationState requestedState)
  272. {
  273. AZStd::pair<SimulationState, SimulationState> desireTransition{ m_simulationState, requestedState };
  274. auto it = AZStd::find(m_forbiddenStatesTransitions.begin(), m_forbiddenStatesTransitions.end(), desireTransition);
  275. return it != m_forbiddenStatesTransitions.end();
  276. }
  277. } // namespace SimulationInterfaces