CameraComponentController.cpp 29 KB

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