CameraComponentController.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  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 "CameraComponentController.h"
  9. #include "AzCore/Component/TransformBus.h"
  10. #include "CameraViewRegistrationBus.h"
  11. #include <Atom/RPI.Public/Pass/PassFilter.h>
  12. #include <Atom/RPI.Public/View.h>
  13. #include <Atom/RPI.Public/ViewportContextManager.h>
  14. #include <Atom/RPI.Public/ViewportContext.h>
  15. #include <AzCore/Asset/AssetSerializer.h>
  16. #include <AzCore/Component/EntityBus.h>
  17. #include <AzCore/Math/MatrixUtils.h>
  18. #include <AzCore/Math/Vector2.h>
  19. #include <AzFramework/Viewport/ViewportScreen.h>
  20. #include <AzCore/Settings/SettingsRegistry.h>
  21. namespace Camera
  22. {
  23. void CameraComponentConfig::Reflect(AZ::ReflectContext* context)
  24. {
  25. if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  26. {
  27. serializeContext->Class<CameraComponentConfig, AZ::ComponentConfig>()
  28. ->Version(6)
  29. ->Field("Orthographic", &CameraComponentConfig::m_orthographic)
  30. ->Field("Orthographic Half Width", &CameraComponentConfig::m_orthographicHalfWidth)
  31. ->Field("Field of View", &CameraComponentConfig::m_fov)
  32. ->Field("Near Clip Plane Distance", &CameraComponentConfig::m_nearClipDistance)
  33. ->Field("Far Clip Plane Distance", &CameraComponentConfig::m_farClipDistance)
  34. ->Field("SpecifyDimensions", &CameraComponentConfig::m_specifyFrustumDimensions)
  35. ->Field("FrustumWidth", &CameraComponentConfig::m_frustumWidth)
  36. ->Field("FrustumHeight", &CameraComponentConfig::m_frustumHeight)
  37. ->Field("MakeActiveViewOnActivation", &CameraComponentConfig::m_makeActiveViewOnActivation)
  38. ->Field("RenderToTexture", &CameraComponentConfig::m_renderTextureAsset)
  39. ->Field("PipelineTemplate", &CameraComponentConfig::m_pipelineTemplate)
  40. ->Field("AllowPipelineChange", &CameraComponentConfig::m_allowPipelineChanges)
  41. ;
  42. if (auto editContext = serializeContext->GetEditContext())
  43. {
  44. editContext->Class<CameraComponentConfig>("CameraComponentConfig", "Configuration for a CameraComponent or EditorCameraComponent")
  45. ->ClassElement(AZ::Edit::ClassElements::EditorData, "")
  46. ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
  47. ->DataElement(AZ::Edit::UIHandlers::Default, &CameraComponentConfig::m_makeActiveViewOnActivation,
  48. "Make active camera on activation?", "If true, this camera will become the active render camera when it activates")
  49. ->DataElement(AZ::Edit::UIHandlers::Default, &CameraComponentConfig::m_orthographic, "Orthographic",
  50. "If set, this camera will use an orthographic projection instead of a perspective one. Objects will appear as the same size, regardless of distance from the camera.")
  51. ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::EntireTree)
  52. ->DataElement(AZ::Edit::UIHandlers::Default, &CameraComponentConfig::m_orthographicHalfWidth, "Orthographic Half-width", "The half-width used to calculate the orthographic projection. The height will be determined by the aspect ratio.")
  53. ->Attribute(AZ::Edit::Attributes::Visibility, &CameraComponentConfig::GetOrthographicParameterVisibility)
  54. ->Attribute(AZ::Edit::Attributes::Min, 0.001f)
  55. ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::ValuesOnly)
  56. ->DataElement(AZ::Edit::UIHandlers::Default, &CameraComponentConfig::m_fov, "Field of view", "Vertical field of view in degrees. Note: Max FoV is less than 180.")
  57. ->Attribute(AZ::Edit::Attributes::Min, MinFoV)
  58. ->Attribute(AZ::Edit::Attributes::Suffix, " degrees")
  59. ->Attribute(AZ::Edit::Attributes::Step, 1.f)
  60. ->Attribute(AZ::Edit::Attributes::Max, AZ::RadToDeg(AZ::Constants::Pi) - 0.001f) //We assert at fovs >= Pi so set the max for this field to be just under that
  61. ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::ValuesOnly)
  62. ->Attribute(AZ::Edit::Attributes::Visibility, &CameraComponentConfig::GetPerspectiveParameterVisibility)
  63. ->DataElement(AZ::Edit::UIHandlers::Default, &CameraComponentConfig::m_nearClipDistance, "Near clip distance",
  64. "Distance to the near clip plane of the view Frustum")
  65. ->Attribute(AZ::Edit::Attributes::Min, MinimumNearPlaneDistance)
  66. ->Attribute(AZ::Edit::Attributes::Suffix, " m")
  67. ->Attribute(AZ::Edit::Attributes::Step, 0.1f)
  68. ->Attribute(AZ::Edit::Attributes::Max, &CameraComponentConfig::GetFarClipDistance)
  69. ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::AttributesAndValues)
  70. ->DataElement(AZ::Edit::UIHandlers::Default, &CameraComponentConfig::m_farClipDistance, "Far clip distance",
  71. "Distance to the far clip plane of the view Frustum")
  72. ->Attribute(AZ::Edit::Attributes::Min, &CameraComponentConfig::GetNearClipDistance)
  73. ->Attribute(AZ::Edit::Attributes::Suffix, " m")
  74. ->Attribute(AZ::Edit::Attributes::Step, 10.f)
  75. ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::AttributesAndValues)
  76. ->ClassElement(AZ::Edit::ClassElements::Group, "Render To Texture")
  77. ->DataElement(AZ::Edit::UIHandlers::Default, &CameraComponentConfig::m_renderTextureAsset, "Target texture", "The render target texture which the camera renders to.")
  78. ->DataElement(AZ::Edit::UIHandlers::Default, &CameraComponentConfig::m_pipelineTemplate, "Pipeline template", "The root pass template for the camera's render pipeline")
  79. ->DataElement(AZ::Edit::UIHandlers::Default, &CameraComponentConfig::m_allowPipelineChanges, "Allow pipeline changes", "If true, the camera's render pipeline can be changed at runtime.")
  80. ->Attribute(AZ::Edit::Attributes::Visibility, &CameraComponentConfig::GetAllowPipelineChangesVisibility)
  81. ;
  82. }
  83. }
  84. }
  85. AZ::u32 CameraComponentConfig::GetAllowPipelineChangesVisibility() const
  86. {
  87. bool experimentalFeaturesEnabled = false;
  88. const auto* registry = AZ::SettingsRegistry::Get();
  89. if (registry)
  90. {
  91. registry->Get(experimentalFeaturesEnabled, "/O3DE/Atom/ExperimentalFeaturesEnabled");
  92. }
  93. return experimentalFeaturesEnabled ? AZ::Edit::PropertyVisibility::Show : AZ::Edit::PropertyVisibility::Hide;
  94. }
  95. float CameraComponentConfig::GetFarClipDistance() const
  96. {
  97. return m_farClipDistance;
  98. }
  99. float CameraComponentConfig::GetNearClipDistance() const
  100. {
  101. return m_nearClipDistance;
  102. }
  103. AZ::EntityId CameraComponentConfig::GetEditorEntityId() const
  104. {
  105. return AZ::EntityId(m_editorEntityId);
  106. }
  107. AZ::u32 CameraComponentConfig::GetPerspectiveParameterVisibility() const
  108. {
  109. return m_orthographic ? AZ::Edit::PropertyVisibility::Hide : AZ::Edit::PropertyVisibility::Show;
  110. }
  111. AZ::u32 CameraComponentConfig::GetOrthographicParameterVisibility() const
  112. {
  113. return m_orthographic ? AZ::Edit::PropertyVisibility::Show : AZ::Edit::PropertyVisibility::Hide;
  114. }
  115. CameraComponentController::CameraComponentController(const CameraComponentConfig& config)
  116. {
  117. SetConfiguration(config);
  118. }
  119. void CameraComponentController::ActivateAtomView()
  120. {
  121. auto atomViewportRequests = AZ::Interface<AZ::RPI::ViewportContextRequestsInterface>::Get();
  122. if (atomViewportRequests)
  123. {
  124. AZ_Assert(GetView(), "Attempted to activate Atom camera before component activation");
  125. const AZ::Name contextName = atomViewportRequests->GetDefaultViewportContextName();
  126. AZ::RPI::ViewportContextNotificationBus::Handler::BusConnect(contextName);
  127. // Ensure the Atom camera is updated with our current transform state
  128. AZ::Transform localTransform;
  129. AZ::TransformBus::EventResult(localTransform, m_entityId, &AZ::TransformBus::Events::GetLocalTM);
  130. AZ::Transform worldTransform;
  131. AZ::TransformBus::EventResult(worldTransform, m_entityId, &AZ::TransformBus::Events::GetWorldTM);
  132. OnTransformChanged(localTransform, worldTransform);
  133. // Push the Atom camera after we make sure we're up-to-date with our component's transform to ensure the viewport reads the correct state
  134. UpdateCamera();
  135. atomViewportRequests->PushViewGroup(contextName, m_atomCameraViewGroup);
  136. }
  137. }
  138. void CameraComponentController::DeactivateAtomView()
  139. {
  140. if (auto atomViewportRequests = AZ::Interface<AZ::RPI::ViewportContextRequestsInterface>::Get())
  141. {
  142. const AZ::Name contextName = atomViewportRequests->GetDefaultViewportContextName();
  143. atomViewportRequests->PopViewGroup(contextName, m_atomCameraViewGroup);
  144. AZ::RPI::ViewportContextNotificationBus::Handler::BusDisconnect(contextName);
  145. }
  146. }
  147. void CameraComponentController::SetShouldActivateFunction(AZStd::function<bool()> shouldActivateFunction)
  148. {
  149. m_shouldActivateFn = AZStd::move(shouldActivateFunction);
  150. }
  151. void CameraComponentController::SetIsLockedFunction(AZStd::function<bool()> isLockedFunction)
  152. {
  153. m_isLockedFn = AZStd::move(isLockedFunction);
  154. }
  155. void CameraComponentController::Reflect(AZ::ReflectContext* context)
  156. {
  157. CameraComponentConfig::Reflect(context);
  158. if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  159. {
  160. serializeContext->Class<CameraComponentController>()
  161. ->Version(1)
  162. ->Field("Configuration", &CameraComponentController::m_config)
  163. ;
  164. if (auto editContext = serializeContext->GetEditContext())
  165. {
  166. editContext->Class<CameraComponentController>("CameraComponentController", "Controller for a CameraComponent or EditorCameraComponent")
  167. ->ClassElement(AZ::Edit::ClassElements::EditorData, "")
  168. ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
  169. ->DataElement(AZ::Edit::UIHandlers::Default, &CameraComponentController::m_config, "Configuration", "Camera Controller Configuration")
  170. ;
  171. }
  172. }
  173. }
  174. void CameraComponentController::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
  175. {
  176. required.push_back(AZ_CRC_CE("TransformService"));
  177. }
  178. void CameraComponentController::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
  179. {
  180. provided.push_back(AZ_CRC_CE("CameraService"));
  181. }
  182. void CameraComponentController::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
  183. {
  184. incompatible.push_back(AZ_CRC_CE("CameraService"));
  185. }
  186. void CameraComponentController::Init()
  187. {
  188. AZStd::function<void(AZ::RPI::ViewPtr view)> onChange = [this](AZ::RPI::ViewPtr view)
  189. {
  190. if (!m_updatingTransformFromEntity && !m_isLockedFn())
  191. {
  192. AZ::TransformBus::Event(m_entityId, &AZ::TransformInterface::SetWorldTM, view->GetCameraTransform());
  193. }
  194. };
  195. m_atomCameraViewGroup = AZStd::make_shared<AZ::RPI::ViewGroup>();
  196. m_atomCameraViewGroup->Init(AZ::RPI::ViewGroup::Descriptor{ onChange, nullptr });
  197. if (auto rpiSystemInterface = AZ::RPI::RPISystemInterface::Get())
  198. {
  199. m_xrSystem = rpiSystemInterface->GetXRSystem();
  200. if (m_xrSystem)
  201. {
  202. m_numSterescopicViews = m_xrSystem->GetNumViews();
  203. AZ_Assert(m_numSterescopicViews <= AZ::RPI::XRMaxNumViews, "Atom only supports two XR views");
  204. }
  205. }
  206. }
  207. void CameraComponentController::Activate(AZ::EntityId entityId)
  208. {
  209. m_entityId = entityId;
  210. // Let's set the camera default transforms:
  211. AZ::TransformBus::EventResult(m_xrCameraToBaseSpaceTm, m_entityId, &AZ::TransformBus::Handler::GetWorldTM);
  212. m_xrBaseSpaceToHeadTm = AZ::Transform::CreateIdentity();
  213. m_xrHeadToLeftEyeTm = AZ::Transform::CreateIdentity();
  214. m_xrHeadToRightEyeTm = AZ::Transform::CreateIdentity();
  215. AZ::RPI::XRSpaceNotificationBus::Handler::BusConnect();
  216. auto atomViewportRequests = AZ::Interface<AZ::RPI::ViewportContextRequestsInterface>::Get();
  217. if (atomViewportRequests)
  218. {
  219. const AZ::EntityId editorEntityId = m_config.GetEditorEntityId();
  220. // Lazily create our camera as part of Activate
  221. // This will be persisted as part of our config so that it may be shared between the Editor & Game components.
  222. // Also, when using the Editor and opening the level for the first time, GetViewForEntity() will return a null ViewPtr.
  223. if (GetView() == nullptr && editorEntityId.IsValid())
  224. {
  225. AZ::RPI::ViewPtr atomEditorView = nullptr;
  226. CameraViewRegistrationRequestsBus::BroadcastResult(atomEditorView, &CameraViewRegistrationRequests::GetViewForEntity, editorEntityId);
  227. m_atomCameraViewGroup->SetView(atomEditorView, AZ::RPI::ViewType::Default);
  228. }
  229. AZStd::string entityName;
  230. AZ::ComponentApplicationBus::BroadcastResult(entityName, &AZ::ComponentApplicationBus::Events::GetEntityName, m_entityId);
  231. AZ::Name cameraName = AZ::Name(AZStd::string::format("%s View", entityName.c_str()));
  232. // If there wasn't already a view registered (or the registration system isn't available), create a View
  233. if (GetView() == nullptr)
  234. {
  235. m_atomCameraViewGroup->CreateMainView(cameraName);
  236. if (editorEntityId.IsValid())
  237. {
  238. CameraViewRegistrationRequestsBus::Broadcast(
  239. &CameraViewRegistrationRequests::SetViewForEntity,
  240. editorEntityId,
  241. GetView());
  242. }
  243. }
  244. m_atomCameraViewGroup->CreateStereoscopicViews(cameraName);
  245. AZ::RPI::ViewProviderBus::Handler::BusConnect(m_entityId);
  246. m_atomCameraViewGroup->Activate();
  247. }
  248. // OnTransformChanged() is only called if the camera is actually moved, so make sure we call it at least once,
  249. // so the camera-transform is also correct for static cameras even before they are made the active view
  250. AZ::Transform local, world;
  251. AZ::TransformBus::Event(entityId, &AZ::TransformBus::Events::GetLocalAndWorld, local, world);
  252. OnTransformChanged(local, world);
  253. CameraRequestBus::Handler::BusConnect(m_entityId);
  254. AZ::TransformNotificationBus::Handler::BusConnect(m_entityId);
  255. CameraBus::Handler::BusConnect();
  256. CameraNotificationBus::Broadcast(&CameraNotificationBus::Events::OnCameraAdded, m_entityId);
  257. if (m_config.m_renderTextureAsset.GetId().IsValid())
  258. {
  259. CreateRenderPipelineForTexture();
  260. }
  261. // Only activate if we're configured to do so, and our activation call back indicates that we should
  262. if (m_config.m_makeActiveViewOnActivation && (!m_shouldActivateFn || m_shouldActivateFn()))
  263. {
  264. MakeActiveView();
  265. }
  266. }
  267. void CameraComponentController::Deactivate()
  268. {
  269. AZ::RPI::XRSpaceNotificationBus::Handler::BusDisconnect();
  270. if (m_renderToTexturePipeline)
  271. {
  272. auto scene = AZ::RPI::RPISystemInterface::Get()->GetSceneByName(AZ::Name("Main"));
  273. scene->RemoveRenderPipeline(m_renderToTexturePipeline->GetId());
  274. m_renderToTexturePipeline = nullptr;
  275. }
  276. CameraNotificationBus::Broadcast(&CameraNotificationBus::Events::OnCameraRemoved, m_entityId);
  277. CameraBus::Handler::BusDisconnect();
  278. AZ::TransformNotificationBus::Handler::BusDisconnect(m_entityId);
  279. CameraRequestBus::Handler::BusDisconnect(m_entityId);
  280. AZ::RPI::ViewProviderBus::Handler::BusDisconnect(m_entityId);
  281. m_atomCameraViewGroup->Deactivate();
  282. DeactivateAtomView();
  283. }
  284. void CameraComponentController::CreateRenderPipelineForTexture()
  285. {
  286. auto scene = AZ::RPI::RPISystemInterface::Get()->GetSceneByName(AZ::Name("Main"));
  287. const AZStd::string pipelineName = "Camera_" + m_entityId.ToString() + "_Pipeline";
  288. AZ::RPI::RenderPipelineDescriptor pipelineDesc;
  289. pipelineDesc.m_mainViewTagName = "MainCamera";
  290. pipelineDesc.m_name = pipelineName;
  291. pipelineDesc.m_rootPassTemplate = m_config.m_pipelineTemplate;
  292. pipelineDesc.m_renderSettings.m_multisampleState = AZ::RPI::RPISystemInterface::Get()->GetApplicationMultisampleState();
  293. pipelineDesc.m_allowModification = m_config.m_allowPipelineChanges;
  294. m_renderToTexturePipeline = AZ::RPI::RenderPipeline::CreateRenderPipelineForImage(pipelineDesc, m_config.m_renderTextureAsset);
  295. if (!m_renderToTexturePipeline)
  296. {
  297. AZStd::string entityName;
  298. AZ::ComponentApplicationBus::BroadcastResult(entityName, &AZ::ComponentApplicationRequests::GetEntityName, m_entityId);
  299. AZ_Error("Camera", false, "Failed to create render to texture pipeline for camera component in entity %s", entityName.c_str());
  300. return;
  301. }
  302. scene->AddRenderPipeline(m_renderToTexturePipeline);
  303. m_renderToTexturePipeline->SetDefaultView(GetView());
  304. }
  305. void CameraComponentController::SetConfiguration(const CameraComponentConfig& config)
  306. {
  307. m_config = config;
  308. UpdateCamera();
  309. }
  310. const CameraComponentConfig& CameraComponentController::GetConfiguration() const
  311. {
  312. return m_config;
  313. }
  314. AZ::RPI::ViewportContextPtr CameraComponentController::GetViewportContext()
  315. {
  316. if (auto atomViewportRequests = AZ::Interface<AZ::RPI::ViewportContextRequestsInterface>::Get();
  317. m_atomCameraViewGroup && atomViewportRequests)
  318. {
  319. return atomViewportRequests->GetDefaultViewportContext();
  320. }
  321. return nullptr;
  322. }
  323. AZ::EntityId CameraComponentController::GetCameras()
  324. {
  325. return m_entityId;
  326. }
  327. float CameraComponentController::GetFovDegrees()
  328. {
  329. return m_config.m_fov;
  330. }
  331. float CameraComponentController::GetFovRadians()
  332. {
  333. return AZ::DegToRad(m_config.m_fov);
  334. }
  335. float CameraComponentController::GetNearClipDistance()
  336. {
  337. return m_config.m_nearClipDistance;
  338. }
  339. float CameraComponentController::GetFarClipDistance()
  340. {
  341. return m_config.m_farClipDistance;
  342. }
  343. float CameraComponentController::GetFrustumWidth()
  344. {
  345. return m_config.m_frustumWidth;
  346. }
  347. float CameraComponentController::GetFrustumHeight()
  348. {
  349. return m_config.m_frustumHeight;
  350. }
  351. bool CameraComponentController::IsOrthographic()
  352. {
  353. return m_config.m_orthographic;
  354. }
  355. float CameraComponentController::GetOrthographicHalfWidth()
  356. {
  357. return m_config.m_orthographicHalfWidth;
  358. }
  359. void CameraComponentController::SetFovDegrees(float fov)
  360. {
  361. m_config.m_fov = AZ::GetClamp(fov, MinFoV, MaxFoV);
  362. UpdateCamera();
  363. }
  364. void CameraComponentController::SetFovRadians(float fov)
  365. {
  366. SetFovDegrees(AZ::RadToDeg(fov));
  367. }
  368. void CameraComponentController::SetNearClipDistance(float nearClipDistance)
  369. {
  370. m_config.m_nearClipDistance = AZ::GetMin(nearClipDistance, m_config.m_farClipDistance);
  371. UpdateCamera();
  372. }
  373. void CameraComponentController::SetFarClipDistance(float farClipDistance)
  374. {
  375. m_config.m_farClipDistance = AZ::GetMax(farClipDistance, m_config.m_nearClipDistance);
  376. UpdateCamera();
  377. }
  378. void CameraComponentController::SetFrustumWidth(float width)
  379. {
  380. m_config.m_frustumWidth = width;
  381. UpdateCamera();
  382. }
  383. void CameraComponentController::SetFrustumHeight(float height)
  384. {
  385. m_config.m_frustumHeight = height;
  386. UpdateCamera();
  387. }
  388. void CameraComponentController::SetOrthographic(bool orthographic)
  389. {
  390. m_config.m_orthographic = orthographic;
  391. UpdateCamera();
  392. }
  393. void CameraComponentController::SetOrthographicHalfWidth(float halfWidth)
  394. {
  395. m_config.m_orthographicHalfWidth = halfWidth;
  396. UpdateCamera();
  397. }
  398. void CameraComponentController::SetXRViewQuaternion([[maybe_unused]] const AZ::Quaternion& viewQuat, [[maybe_unused]] uint32_t xrViewIndex)
  399. {
  400. //No implementation needed as we are calling into CR system directly to get view data within OnTransformChanged
  401. }
  402. void CameraComponentController::MakeActiveView()
  403. {
  404. if (IsActiveView())
  405. {
  406. return;
  407. }
  408. // Set Atom camera, if it exists
  409. if (m_atomCameraViewGroup->IsAnyViewEnabled())
  410. {
  411. ActivateAtomView();
  412. }
  413. // Update camera parameters
  414. UpdateCamera();
  415. // Notify of active view changed
  416. CameraNotificationBus::Broadcast(&CameraNotificationBus::Events::OnActiveViewChanged, m_entityId);
  417. }
  418. bool CameraComponentController::IsActiveView()
  419. {
  420. return m_isActiveView;
  421. }
  422. namespace Util
  423. {
  424. AZ::Vector3 GetWorldPosition(const AZ::Vector3& origin, float depth, const AzFramework::CameraState& cameraState)
  425. {
  426. if (depth == 0.f)
  427. {
  428. return origin;
  429. }
  430. else
  431. {
  432. const AZ::Vector3 rayDirection = cameraState.m_orthographic ? cameraState.m_forward : (origin - cameraState.m_position);
  433. return origin + (rayDirection.GetNormalized() * depth);
  434. }
  435. }
  436. }
  437. AZ::Vector3 CameraComponentController::ScreenToWorld(const AZ::Vector2& screenPosition, float depth)
  438. {
  439. const AzFramework::ScreenPoint point{ static_cast<int>(screenPosition.GetX()), static_cast<int>(screenPosition.GetY()) };
  440. const AzFramework::CameraState& cameraState = GetCameraState();
  441. const AZ::Vector3 origin = AzFramework::ScreenToWorld(point, cameraState);
  442. return Util::GetWorldPosition(origin, depth, cameraState);
  443. }
  444. AZ::Vector3 CameraComponentController::ScreenNdcToWorld(const AZ::Vector2& screenNdcPosition, float depth)
  445. {
  446. const AzFramework::CameraState& cameraState = GetCameraState();
  447. const AZ::Vector3 origin = AzFramework::ScreenNdcToWorld(screenNdcPosition, AzFramework::InverseCameraView(cameraState), AzFramework::InverseCameraProjection(cameraState));
  448. return Util::GetWorldPosition(origin, depth, cameraState);
  449. }
  450. AZ::Vector2 CameraComponentController::WorldToScreenNdc(const AZ::Vector3& worldPosition)
  451. {
  452. const AzFramework::CameraState& cameraState = GetCameraState();
  453. const AZ::Vector3 screenPosition = AzFramework::WorldToScreenNdc(worldPosition, AzFramework::CameraView(cameraState), AzFramework::CameraProjection(cameraState));
  454. return AZ::Vector2(screenPosition);
  455. }
  456. AZ::Vector2 CameraComponentController::WorldToScreen(const AZ::Vector3& worldPosition)
  457. {
  458. const AzFramework::ScreenPoint& point = AzFramework::WorldToScreen(worldPosition, GetCameraState());
  459. return AZ::Vector2(static_cast<float>(point.m_x), static_cast<float>(point.m_y));
  460. }
  461. AzFramework::CameraState CameraComponentController::GetCameraState()
  462. {
  463. auto viewportContext = GetViewportContext();
  464. if (!m_atomCameraViewGroup->IsAnyViewEnabled() || !viewportContext)
  465. {
  466. return AzFramework::CameraState();
  467. }
  468. const auto windowSize = viewportContext->GetViewportSize();
  469. const auto viewportSize = AzFramework::ScreenSize(windowSize.m_width, windowSize.m_height);
  470. AzFramework::CameraState cameraState =
  471. AzFramework::CreateDefaultCamera(GetView()->GetCameraTransform(), viewportSize);
  472. AzFramework::SetCameraClippingVolumeFromPerspectiveFovMatrixRH(
  473. cameraState, GetView()->GetViewToClipMatrix());
  474. return cameraState;
  475. }
  476. void CameraComponentController::OnTransformChanged([[maybe_unused]] const AZ::Transform& local, const AZ::Transform& world)
  477. {
  478. if (m_updatingTransformFromEntity)
  479. {
  480. return;
  481. }
  482. m_updatingTransformFromEntity = true;
  483. if (m_xrSystem && m_xrSystem->ShouldRender())
  484. {
  485. // When the XR System is active, The camera world transform will always be:
  486. // camWorldTm = m_xrCameraToBaseSpaceTm * m_xrBaseSpaceToHeadTm.
  487. // But when OnTransformChanged is called, may be because a Lua Script is changing
  488. // the camera location, we need to apply the inverse operation to preserve the value
  489. // of m_xrCameraToBaseSpaceTm.
  490. // This is the quick math:
  491. // m_xrCameraToBaseSpaceTm~ * camWorldTm = m_xrCameraToBaseSpaceTm~ * m_xrCameraToBaseSpaceTm * m_xrBaseSpaceToHeadTm
  492. // m_xrCameraToBaseSpaceTm~ * camWorldTm = m_xrBaseSpaceToHeadTm
  493. // m_xrCameraToBaseSpaceTm~ * camWorldTm * camWorldTm~ = m_xrBaseSpaceToHeadTm * camWorldTm~
  494. // m_xrCameraToBaseSpaceTm~ = m_xrBaseSpaceToHeadTm * camWorldTm~
  495. // m_xrCameraToBaseSpaceTm~~ = (m_xrBaseSpaceToHeadTm * camWorldTm~)~
  496. // m_xrCameraToBaseSpaceTm = camWorldTm~~ * m_xrBaseSpaceToHeadTm~
  497. // m_xrCameraToBaseSpaceTm = camWorldTm * m_xrBaseSpaceToHeadTm~
  498. m_xrCameraToBaseSpaceTm = world * m_xrBaseSpaceToHeadTm.GetInverse();
  499. m_updatingTransformFromEntity = false;
  500. // We are not going to call m_atomCameraViewGroup->SetCameraTransform() yet.
  501. // We need to wait for the OnXRSpaceLocationsChanged() notification, which will give us
  502. // the XR Headset orientation.
  503. return;
  504. }
  505. else
  506. {
  507. m_atomCameraViewGroup->SetCameraTransform(AZ::Matrix3x4::CreateFromTransform(world.GetOrthogonalized()));
  508. }
  509. m_updatingTransformFromEntity = false;
  510. UpdateCamera();
  511. }
  512. void CameraComponentController::OnViewportSizeChanged([[maybe_unused]] AzFramework::WindowSize size)
  513. {
  514. if (IsActiveView())
  515. {
  516. UpdateCamera();
  517. }
  518. }
  519. void CameraComponentController::OnViewportDefaultViewChanged(AZ::RPI::ViewPtr view)
  520. {
  521. m_isActiveView = GetView() == view;
  522. }
  523. AZ::RPI::ViewPtr CameraComponentController::GetView() const
  524. {
  525. return m_atomCameraViewGroup->GetView(AZ::RPI::ViewType::Default);
  526. }
  527. AZ::RPI::ViewPtr CameraComponentController::GetStereoscopicView(AZ::RPI::ViewType viewType) const
  528. {
  529. return m_atomCameraViewGroup->GetView(viewType);
  530. }
  531. void CameraComponentController::UpdateCamera()
  532. {
  533. // O3de assumes a setup for reversed depth
  534. const bool reverseDepth = true;
  535. if (auto viewportContext = GetViewportContext())
  536. {
  537. AZ::Matrix4x4 viewToClipMatrix;
  538. if (!m_atomAuxGeom)
  539. {
  540. SetupAtomAuxGeom(viewportContext);
  541. }
  542. auto windowSize = viewportContext->GetViewportSize();
  543. const float aspectRatio = aznumeric_cast<float>(windowSize.m_width) / aznumeric_cast<float>(windowSize.m_height);
  544. // This assumes a reversed depth buffer, in line with other LY Atom integration
  545. if (m_config.m_orthographic)
  546. {
  547. AZ::MakeOrthographicMatrixRH(viewToClipMatrix,
  548. -m_config.m_orthographicHalfWidth,
  549. m_config.m_orthographicHalfWidth,
  550. -m_config.m_orthographicHalfWidth / aspectRatio,
  551. m_config.m_orthographicHalfWidth / aspectRatio,
  552. m_config.m_nearClipDistance,
  553. m_config.m_farClipDistance,
  554. reverseDepth);
  555. }
  556. else
  557. {
  558. AZ::MakePerspectiveFovMatrixRH(viewToClipMatrix,
  559. AZ::DegToRad(m_config.m_fov),
  560. aspectRatio,
  561. m_config.m_nearClipDistance,
  562. m_config.m_farClipDistance,
  563. reverseDepth);
  564. }
  565. m_updatingTransformFromEntity = true;
  566. m_atomCameraViewGroup->SetViewToClipMatrix(viewToClipMatrix);
  567. // Update stereoscopic projection matrix
  568. if (m_xrSystem && m_xrSystem->ShouldRender())
  569. {
  570. AZ::Matrix4x4 projection = AZ::Matrix4x4::CreateIdentity();
  571. for (AZ::u32 i = 0; i < m_numSterescopicViews; i++)
  572. {
  573. AZ::RPI::ViewType viewType = i == 0 ? AZ::RPI::ViewType::XrLeft : AZ::RPI::ViewType::XrRight;
  574. AZ::RPI::FovData fovData;
  575. m_xrSystem->GetViewFov(i, fovData);
  576. if ( (fovData.m_angleLeft != 0 || fovData.m_angleRight != 0) && (fovData.m_angleUp != 0 || fovData.m_angleDown != 0))
  577. {
  578. projection = m_xrSystem->CreateStereoscopicProjection(
  579. fovData.m_angleLeft,
  580. fovData.m_angleRight,
  581. fovData.m_angleDown,
  582. fovData.m_angleUp,
  583. m_config.m_nearClipDistance,
  584. m_config.m_farClipDistance,
  585. reverseDepth);
  586. m_atomCameraViewGroup->SetStereoscopicViewToClipMatrix(projection, reverseDepth, viewType);
  587. }
  588. }
  589. }
  590. m_updatingTransformFromEntity = false;
  591. }
  592. }
  593. void CameraComponentController::SetupAtomAuxGeom(AZ::RPI::ViewportContextPtr viewportContext)
  594. {
  595. if (auto scene = viewportContext->GetRenderScene())
  596. {
  597. if (auto auxGeomFP = scene->GetFeatureProcessor<AZ::RPI::AuxGeomFeatureProcessorInterface>())
  598. {
  599. m_atomAuxGeom = auxGeomFP->GetOrCreateDrawQueueForView(GetView().get());
  600. }
  601. }
  602. }
  603. ////////////////////////////////////////////////////////////////////
  604. // AZ::RPI::XRSpaceNotificationBus::Handler Overrides
  605. void CameraComponentController::OnXRSpaceLocationsChanged(
  606. const AZ::Transform& baseSpaceToHeadTm,
  607. const AZ::Transform& headToleftEyeTm,
  608. const AZ::Transform& headToRightEyeTm)
  609. {
  610. if (!m_xrSystem || !m_xrSystem->ShouldRender())
  611. {
  612. return;
  613. }
  614. m_updatingTransformFromEntity = true;
  615. m_xrBaseSpaceToHeadTm = baseSpaceToHeadTm;
  616. const auto mainCameraWorldTm = m_xrCameraToBaseSpaceTm * baseSpaceToHeadTm;
  617. AZ::TransformBus::Event(m_entityId, &AZ::TransformBus::Handler::SetWorldTM, mainCameraWorldTm);
  618. // Update camera world matrix for the main pipeline.
  619. m_atomCameraViewGroup->SetCameraTransform(AZ::Matrix3x4::CreateFromTransform(mainCameraWorldTm));
  620. // Update camera world matrix for the left eye pipeline.
  621. m_xrHeadToLeftEyeTm = headToleftEyeTm;
  622. const auto leftEyeWorldTm = mainCameraWorldTm * headToleftEyeTm;
  623. m_atomCameraViewGroup->SetCameraTransform(AZ::Matrix3x4::CreateFromTransform(leftEyeWorldTm), AZ::RPI::ViewType::XrLeft);
  624. // Update camera world matrix for the right eye pipeline.
  625. m_xrHeadToRightEyeTm = headToRightEyeTm;
  626. const auto rightEyeWorldTm = mainCameraWorldTm * headToRightEyeTm;
  627. m_atomCameraViewGroup->SetCameraTransform(AZ::Matrix3x4::CreateFromTransform(rightEyeWorldTm), AZ::RPI::ViewType::XrRight);
  628. UpdateCamera();
  629. m_updatingTransformFromEntity = false;
  630. }
  631. ////////////////////////////////////////////////////////////////////
  632. } //namespace Camera