TransformComponent.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330
  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 "TransformComponent.h"
  9. #include <AzCore/Component/ComponentApplicationBus.h>
  10. #include <AzCore/Component/Entity.h>
  11. #include <AzCore/Math/Aabb.h>
  12. #include <AzCore/Math/IntersectSegment.h>
  13. #include <AzCore/Math/MathUtils.h>
  14. #include <AzCore/Math/Quaternion.h>
  15. #include <AzCore/Math/Transform.h>
  16. #include <AzCore/RTTI/BehaviorContext.h>
  17. #include <AzCore/Serialization/EditContext.h>
  18. #include <AzCore/Serialization/Json/RegistrationContext.h>
  19. #include <AzCore/Serialization/SerializeContext.h>
  20. #include <AzFramework/API/ApplicationAPI.h>
  21. #include <AzFramework/Components/TransformComponent.h>
  22. #include <AzFramework/Visibility/EntityBoundsUnionBus.h>
  23. #include <AzToolsFramework/API/EntityCompositionRequestBus.h>
  24. #include <AzToolsFramework/Entity/EditorEntityTransformBus.h>
  25. #include <AzToolsFramework/API/EntityPropertyEditorRequestsBus.h>
  26. #include <AzToolsFramework/API/ToolsApplicationAPI.h>
  27. #include <AzToolsFramework/ContainerEntity/ContainerEntityInterface.h>
  28. #include <AzToolsFramework/Entity/EditorEntityContextBus.h>
  29. #include <AzToolsFramework/Entity/EditorEntityHelpers.h>
  30. #include <AzToolsFramework/Entity/EditorEntityInfoBus.h>
  31. #include <AzToolsFramework/Entity/ReadOnly/ReadOnlyEntityInterface.h>
  32. #include <AzToolsFramework/Prefab/PrefabFocusPublicInterface.h>
  33. #include <AzToolsFramework/ToolsComponents/TransformComponentBus.h>
  34. #include <AzToolsFramework/ToolsComponents/TransformComponentSerializer.h>
  35. #include <AzToolsFramework/ToolsComponents/EditorInspectorComponentBus.h>
  36. #include <AzToolsFramework/ToolsComponents/EditorPendingCompositionBus.h>
  37. #include <AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI.h>
  38. #include <AzToolsFramework/ViewportSelection/EditorSelectionUtil.h>
  39. #include <AzToolsFramework/Viewport/ViewportMessages.h>
  40. #include <QMenu>
  41. #include <QMessageBox>
  42. namespace AzToolsFramework
  43. {
  44. namespace Components
  45. {
  46. namespace Internal
  47. {
  48. const AZ::u32 ParentEntityCRC = AZ_CRC_CE("Parent Entity");
  49. // Decompose a transform into euler angles in degrees, uniform scale, and translation.
  50. void DecomposeTransform(const AZ::Transform& transform, AZ::Vector3& translation, AZ::Vector3& rotation, float& scale)
  51. {
  52. scale = transform.GetUniformScale();
  53. translation = transform.GetTranslation();
  54. rotation = transform.GetRotation().GetEulerDegrees();
  55. }
  56. bool TransformComponentDataConverter(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement)
  57. {
  58. if (classElement.GetVersion() < 6)
  59. {
  60. // In v6, "Slice Transform" became slice-relative.
  61. const int sliceRelTransformIdx = classElement.FindElement(AZ_CRC_CE("Slice Transform"));
  62. if (sliceRelTransformIdx >= 0)
  63. {
  64. // Convert slice-relative transform/root to standard parent-child relationship.
  65. const int sliceRootIdx = classElement.FindElement(AZ_CRC_CE("Slice Root"));
  66. const int parentIdx = classElement.FindElement(ParentEntityCRC);
  67. const int editorTransformIdx = classElement.FindElement(AZ_CRC_CE("Transform Data"));
  68. const int cachedTransformIdx = classElement.FindElement(AZ_CRC_CE("Cached World Transform"));
  69. if (editorTransformIdx >= 0 && sliceRootIdx >= 0 && parentIdx >= 0)
  70. {
  71. auto& sliceTransformElement = classElement.GetSubElement(sliceRelTransformIdx);
  72. auto& sliceRootElement = classElement.GetSubElement(sliceRootIdx);
  73. auto& parentElement = classElement.GetSubElement(parentIdx);
  74. auto& editorTransformElement = classElement.GetSubElement(editorTransformIdx);
  75. AZ::Transform sliceRelTransform;
  76. if (sliceTransformElement.GetData(sliceRelTransform))
  77. {
  78. // If the entity already has a parent assigned, we don't need to fix anything up.
  79. // We only need to convert slice root to parent for non-child entities.
  80. const int parentIdValueIdx = parentElement.FindElement(AZ_CRC_CE("id"));
  81. AZ::u64 parentId = 0;
  82. if (parentIdValueIdx >= 0)
  83. {
  84. parentElement.GetSubElement(parentIdValueIdx).GetData(parentId);
  85. }
  86. AZ::EntityId sliceRootId;
  87. const int entityIdValueIdx = sliceRootElement.FindElement(AZ_CRC_CE("id"));
  88. if (entityIdValueIdx < 0)
  89. {
  90. return false;
  91. }
  92. if (parentId == static_cast<AZ::u64>(AZ::EntityId()) && sliceRootElement.GetSubElement(entityIdValueIdx).GetData(sliceRootId))
  93. {
  94. // Upgrading the data itself is only relevant when a slice root was actually defined.
  95. if (sliceRootId.IsValid())
  96. {
  97. // Cached transforms weren't nullified in really old slices.
  98. if (cachedTransformIdx >= 0)
  99. {
  100. auto& cachedTransformElement = classElement.GetSubElement(cachedTransformIdx);
  101. cachedTransformElement.Convert<AZ::Transform>(context);
  102. cachedTransformElement.SetData(context, AZ::Transform::Identity());
  103. }
  104. // Our old slice root Id is now our parent Id.
  105. // Note - this could be ourself, but we can't know yet, so it gets fixed up by EditorEntityFixupComponent.
  106. parentElement.Convert<AZ::EntityId>(context);
  107. parentElement.SetData(context, sliceRootId);
  108. // Decompose the old slice-relative transform and set it as a our editor transform,
  109. // since the entity is now our parent.
  110. EditorTransform editorTransform;
  111. DecomposeTransform(sliceRelTransform, editorTransform.m_translate, editorTransform.m_rotate, editorTransform.m_uniformScale);
  112. editorTransformElement.Convert<EditorTransform>(context);
  113. editorTransformElement.SetData(context, editorTransform);
  114. }
  115. }
  116. // Finally, remove old fields.
  117. classElement.RemoveElementByName(AZ_CRC_CE("Slice Transform"));
  118. classElement.RemoveElementByName(AZ_CRC_CE("Slice Root"));
  119. }
  120. }
  121. }
  122. }
  123. if (classElement.GetVersion() < 7)
  124. {
  125. // "IsStatic" added at v7.
  126. // Old versions of TransformComponent are assumed to be non-static.
  127. classElement.AddElementWithData(context, "IsStatic", false);
  128. }
  129. if (classElement.GetVersion() < 8)
  130. {
  131. // "InterpolatePosition" added at v8.
  132. // "InterpolateRotation" added at v8.
  133. // Old versions of TransformComponent are assumed to be using linear interpolation.
  134. classElement.AddElementWithData(context, "InterpolatePosition", AZ::InterpolationMode::NoInterpolation);
  135. classElement.AddElementWithData(context, "InterpolateRotation", AZ::InterpolationMode::NoInterpolation);
  136. }
  137. // note the == on the following line. Do not add to this block. If you add an "InterpolateScale" back in, then
  138. // consider erasing this block. The version was bumped from 8 to 9 to ensure this code runs.
  139. // if you add the field back in, then increment the version number again.
  140. if (classElement.GetVersion() == 8)
  141. {
  142. // a field was temporarily added to this specific version, then was removed.
  143. // However, some data may have been exported with this field present, so
  144. // remove it if its found, but only in this version which the change was present in, so that
  145. // future re-additions of it won't remove it (as long as they bump the version number.)
  146. classElement.RemoveElementByName(AZ_CRC_CE("InterpolateScale"));
  147. }
  148. if (classElement.GetVersion() < 10)
  149. {
  150. // The "Sync Enabled" flag is no longer needed.
  151. classElement.RemoveElementByName(AZ_CRC_CE("Sync Enabled"));
  152. }
  153. return true;
  154. }
  155. bool EditorTransformDataConverter(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement)
  156. {
  157. if (classElement.GetVersion() < 3)
  158. {
  159. // version 3 replaces vector scale with uniform scale but does not yet delete the legacy scale data
  160. // in order to allow for migration
  161. AZ::Vector3 vectorScale;
  162. if (classElement.FindSubElementAndGetData<AZ::Vector3>(AZ_CRC_CE("Scale"), vectorScale))
  163. {
  164. const float uniformScale = vectorScale.GetMaxElement();
  165. classElement.AddElementWithData(context, "UniformScale", uniformScale);
  166. }
  167. }
  168. return true;
  169. }
  170. } // namespace Internal
  171. TransformComponent::TransformComponent()
  172. : m_isStatic(false)
  173. , m_parentActivationTransformMode(AZ::TransformConfig::ParentActivationTransformMode::MaintainOriginalRelativeTransform)
  174. , m_cachedWorldTransform(AZ::Transform::Identity())
  175. , m_suppressTransformChangedEvent(false)
  176. , m_interpolatePosition(AZ::InterpolationMode::NoInterpolation)
  177. , m_interpolateRotation(AZ::InterpolationMode::NoInterpolation)
  178. , m_focusModeInterface(AZ::Interface<AzToolsFramework::FocusModeInterface>::Get())
  179. {
  180. }
  181. TransformComponent::~TransformComponent()
  182. {
  183. }
  184. void TransformComponent::Init()
  185. {
  186. //Ensure that when we init that our previous/parent match
  187. m_previousParentEntityId = m_parentEntityId;
  188. }
  189. void TransformComponent::Activate()
  190. {
  191. EditorComponentBase::Activate();
  192. TransformComponentMessages::Bus::Handler::BusConnect(GetEntityId());
  193. AZ::TransformBus::Handler::BusConnect(GetEntityId());
  194. AZ::SliceEntityHierarchyRequestBus::Handler::BusConnect(GetEntityId());
  195. // for drag + drop child entity from one parent to another, undo/redo
  196. if (m_parentEntityId.IsValid())
  197. {
  198. AZ::EntityBus::Handler::BusConnect(m_parentEntityId);
  199. if (m_parentEntityId != m_previousParentEntityId)
  200. {
  201. ToolsApplicationNotificationBus::Broadcast(
  202. &ToolsApplicationEvents::EntityParentChanged, GetEntityId(),
  203. m_parentEntityId, m_previousParentEntityId);
  204. }
  205. m_previousParentEntityId = m_parentEntityId;
  206. }
  207. // it includes the process of create/delete entity
  208. else
  209. {
  210. CheckApplyCachedWorldTransform(AZ::Transform::Identity());
  211. UpdateCachedWorldTransform();
  212. }
  213. }
  214. void TransformComponent::Deactivate()
  215. {
  216. AZ::EntityBus::Handler::BusDisconnect();
  217. AZ::SliceEntityHierarchyRequestBus::Handler::BusDisconnect();
  218. AZ::TransformBus::Handler::BusDisconnect();
  219. TransformComponentMessages::Bus::Handler::BusDisconnect();
  220. AZ::TransformHierarchyInformationBus::Handler::BusDisconnect();
  221. AZ::TransformNotificationBus::MultiHandler::BusDisconnect();
  222. EditorComponentBase::Deactivate();
  223. }
  224. void TransformComponent::BindTransformChangedEventHandler(AZ::TransformChangedEvent::Handler& handler)
  225. {
  226. handler.Connect(m_transformChangedEvent);
  227. }
  228. void TransformComponent::BindParentChangedEventHandler(AZ::ParentChangedEvent::Handler& handler)
  229. {
  230. handler.Connect(m_parentChangedEvent);
  231. }
  232. void TransformComponent::BindChildChangedEventHandler(AZ::ChildChangedEvent::Handler& handler)
  233. {
  234. handler.Connect(m_childChangedEvent);
  235. }
  236. void TransformComponent::NotifyChildChangedEvent(AZ::ChildChangeType changeType, AZ::EntityId entityId)
  237. {
  238. m_childChangedEvent.Signal(changeType, entityId);
  239. }
  240. // This is called when our transform changes directly, or our parent's has changed.
  241. void TransformComponent::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& world)
  242. {
  243. m_localTransformDirty = true;
  244. m_worldTransformDirty = true;
  245. if (const AZ::Entity* entity = GetEntity())
  246. {
  247. SetDirty();
  248. // Update parent-relative transform.
  249. const auto& localTM = GetLocalTM();
  250. const auto worldTM = world * localTM;
  251. if (m_parentEntityId.IsValid())
  252. {
  253. // If the parent entity is invalid, the world position of the entity shouldn't be cached as this can be later used in
  254. // calculating the local translation of the entity when activated under a different parent.
  255. UpdateCachedWorldTransform();
  256. }
  257. AZ::TransformNotificationBus::Event(
  258. GetEntityId(), &TransformNotification::OnTransformChanged, localTM, worldTM);
  259. m_transformChangedEvent.Signal(localTM, worldTM);
  260. AzFramework::IEntityBoundsUnion* boundsUnion = AZ::Interface<AzFramework::IEntityBoundsUnion>::Get();
  261. if (boundsUnion != nullptr)
  262. {
  263. boundsUnion->OnTransformUpdated(GetEntity());
  264. }
  265. // Fire a property changed notification for this component. This will cascade to updating the UI. It is not
  266. // necessary to notify the UI directly.
  267. if (const AZ::Component* component = entity->FindComponent<Components::TransformComponent>())
  268. {
  269. PropertyEditorEntityChangeNotificationBus::Event(
  270. GetEntityId(), &PropertyEditorEntityChangeNotifications::OnEntityComponentPropertyChanged, component->GetId());
  271. }
  272. }
  273. }
  274. void TransformComponent::OnTransformChanged()
  275. {
  276. if (!m_suppressTransformChangedEvent)
  277. {
  278. auto parent = GetParentTransformComponent();
  279. if (parent)
  280. {
  281. OnTransformChanged(parent->GetLocalTM(), parent->GetWorldTM());
  282. }
  283. else
  284. {
  285. OnTransformChanged(AZ::Transform::Identity(), AZ::Transform::Identity());
  286. }
  287. }
  288. }
  289. void TransformComponent::UpdateCachedWorldTransform()
  290. {
  291. const AZ::Transform& worldTransform = GetWorldTM();
  292. if (m_cachedWorldTransformParent != m_parentEntityId || !worldTransform.IsClose(m_cachedWorldTransform))
  293. {
  294. m_cachedWorldTransformParent = GetParentId();
  295. m_cachedWorldTransform = GetWorldTM();
  296. if (GetEntity())
  297. {
  298. SetDirty();
  299. }
  300. }
  301. }
  302. void TransformComponent::ClearCachedWorldTransform()
  303. {
  304. m_cachedWorldTransform = AZ::Transform::Identity();
  305. m_cachedWorldTransformParent = AZ::EntityId();
  306. }
  307. void TransformComponent::CheckApplyCachedWorldTransform(const AZ::Transform& parentWorld)
  308. {
  309. if (m_parentEntityId != m_cachedWorldTransformParent)
  310. {
  311. if (!m_cachedWorldTransform.IsClose(AZ::Transform::Identity()))
  312. {
  313. SetLocalTM(parentWorld.GetInverse() * m_cachedWorldTransform);
  314. }
  315. }
  316. }
  317. AZ::Transform TransformComponent::GetLocalTranslationTM() const
  318. {
  319. return AZ::Transform::CreateTranslation(m_editorTransform.m_translate);
  320. }
  321. AZ::Transform TransformComponent::GetLocalRotationTM() const
  322. {
  323. return AZ::ConvertEulerDegreesToTransform(m_editorTransform.m_rotate);
  324. }
  325. AZ::Transform TransformComponent::GetLocalScaleTM() const
  326. {
  327. return AZ::Transform::CreateUniformScale(m_editorTransform.m_uniformScale);
  328. }
  329. const AZ::Transform& TransformComponent::GetLocalTM()
  330. {
  331. if (m_localTransformDirty)
  332. {
  333. m_localTransformCache = GetLocalTranslationTM() * GetLocalRotationTM() * GetLocalScaleTM();
  334. m_localTransformDirty = false;
  335. }
  336. return m_localTransformCache;
  337. }
  338. // given a local transform, update local transform.
  339. void TransformComponent::SetLocalTM(const AZ::Transform& finalTx)
  340. {
  341. AZ::Vector3 tx, rot;
  342. float uniformScale;
  343. Internal::DecomposeTransform(finalTx, tx, rot, uniformScale);
  344. m_editorTransform.m_translate = tx;
  345. m_editorTransform.m_rotate = rot;
  346. m_editorTransform.m_uniformScale = uniformScale;
  347. TransformChanged();
  348. }
  349. const EditorTransform& TransformComponent::GetLocalEditorTransform()
  350. {
  351. return m_editorTransform;
  352. }
  353. void TransformComponent::SetLocalEditorTransform(const EditorTransform& dest)
  354. {
  355. m_editorTransform = dest;
  356. TransformChanged();
  357. }
  358. bool TransformComponent::IsTransformLocked()
  359. {
  360. return m_editorTransform.m_locked;
  361. }
  362. const AZ::Transform& TransformComponent::GetWorldTM()
  363. {
  364. if (m_worldTransformDirty)
  365. {
  366. m_worldTransformCache = GetParentWorldTM() * GetLocalTM();
  367. m_worldTransformDirty = false;
  368. }
  369. return m_worldTransformCache;
  370. }
  371. void TransformComponent::SetWorldTM(const AZ::Transform& finalTx)
  372. {
  373. AZ::Transform parentGlobalToWorldInverse = GetParentWorldTM().GetInverse();
  374. SetLocalTM(parentGlobalToWorldInverse * finalTx);
  375. }
  376. void TransformComponent::GetLocalAndWorld(AZ::Transform& localTM, AZ::Transform& worldTM)
  377. {
  378. localTM = GetLocalTM();
  379. worldTM = GetWorldTM();
  380. }
  381. void TransformComponent::SetWorldTranslation(const AZ::Vector3& newPosition)
  382. {
  383. AZ::Transform newWorldTransform = GetWorldTM();
  384. newWorldTransform.SetTranslation(newPosition);
  385. SetWorldTM(newWorldTransform);
  386. }
  387. void TransformComponent::SetLocalTranslation(const AZ::Vector3& newPosition)
  388. {
  389. AZ::Transform newLocalTransform = GetLocalTM();
  390. newLocalTransform.SetTranslation(newPosition);
  391. SetLocalTM(newLocalTransform);
  392. }
  393. AZ::Vector3 TransformComponent::GetWorldTranslation()
  394. {
  395. return GetWorldTM().GetTranslation();
  396. }
  397. AZ::Vector3 TransformComponent::GetLocalTranslation()
  398. {
  399. return GetLocalTM().GetTranslation();
  400. }
  401. void TransformComponent::MoveEntity(const AZ::Vector3& offset)
  402. {
  403. const AZ::Vector3& worldPosition = GetWorldTM().GetTranslation();
  404. SetWorldTranslation(worldPosition + offset);
  405. }
  406. void TransformComponent::SetWorldX(float newX)
  407. {
  408. const AZ::Vector3& worldPosition = GetWorldTM().GetTranslation();
  409. SetWorldTranslation(AZ::Vector3(newX, worldPosition.GetY(), worldPosition.GetZ()));
  410. }
  411. void TransformComponent::SetWorldY(float newY)
  412. {
  413. const AZ::Vector3& worldPosition = GetWorldTM().GetTranslation();
  414. SetWorldTranslation(AZ::Vector3(worldPosition.GetX(), newY, worldPosition.GetZ()));
  415. }
  416. void TransformComponent::SetWorldZ(float newZ)
  417. {
  418. const AZ::Vector3& worldPosition = GetWorldTM().GetTranslation();
  419. SetWorldTranslation(AZ::Vector3(worldPosition.GetX(), worldPosition.GetY(), newZ));
  420. }
  421. float TransformComponent::GetWorldX()
  422. {
  423. return GetWorldTranslation().GetX();
  424. }
  425. float TransformComponent::GetWorldY()
  426. {
  427. return GetWorldTranslation().GetY();
  428. }
  429. float TransformComponent::GetWorldZ()
  430. {
  431. return GetWorldTranslation().GetZ();
  432. }
  433. void TransformComponent::SetLocalX(float x)
  434. {
  435. m_editorTransform.m_translate.SetX(x);
  436. TransformChanged();
  437. }
  438. void TransformComponent::SetLocalY(float y)
  439. {
  440. m_editorTransform.m_translate.SetY(y);
  441. TransformChanged();
  442. }
  443. void TransformComponent::SetLocalZ(float z)
  444. {
  445. m_editorTransform.m_translate.SetZ(z);
  446. TransformChanged();
  447. }
  448. float TransformComponent::GetLocalX()
  449. {
  450. return m_editorTransform.m_translate.GetX();
  451. }
  452. float TransformComponent::GetLocalY()
  453. {
  454. return m_editorTransform.m_translate.GetY();
  455. }
  456. float TransformComponent::GetLocalZ()
  457. {
  458. return m_editorTransform.m_translate.GetZ();
  459. }
  460. void TransformComponent::SetWorldRotationQuaternion(const AZ::Quaternion& quaternion)
  461. {
  462. AZ::Transform newWorldTransform = GetWorldTM();
  463. newWorldTransform.SetRotation(quaternion);
  464. SetWorldTM(newWorldTransform);
  465. }
  466. AZ::Vector3 TransformComponent::GetWorldRotation()
  467. {
  468. return GetWorldTM().GetRotation().GetEulerRadians();
  469. }
  470. AZ::Quaternion TransformComponent::GetWorldRotationQuaternion()
  471. {
  472. return GetWorldTM().GetRotation();
  473. }
  474. void TransformComponent::SetLocalRotation(const AZ::Vector3& eulerAnglesRadian)
  475. {
  476. m_editorTransform.m_rotate = AZ::Vector3RadToDeg(eulerAnglesRadian);
  477. TransformChanged();
  478. }
  479. void TransformComponent::SetLocalRotationQuaternion(const AZ::Quaternion& quaternion)
  480. {
  481. m_editorTransform.m_rotate = quaternion.GetEulerDegrees();
  482. TransformChanged();
  483. }
  484. void TransformComponent::RotateAroundLocalX(float eulerAngleRadian)
  485. {
  486. AZ::Transform localRotate = AZ::ConvertEulerDegreesToTransform(m_editorTransform.m_rotate);
  487. AZ::Vector3 xAxis = localRotate.GetBasisX();
  488. AZ::Quaternion xRotate = AZ::Quaternion::CreateFromAxisAngle(xAxis, eulerAngleRadian);
  489. AZ::Quaternion currentRotate = AZ::ConvertEulerDegreesToQuaternion(m_editorTransform.m_rotate);
  490. AZ::Quaternion newRotate = xRotate * currentRotate;
  491. newRotate.Normalize();
  492. m_editorTransform.m_rotate = newRotate.GetEulerDegrees();
  493. TransformChanged();
  494. }
  495. void TransformComponent::RotateAroundLocalY(float eulerAngleRadian)
  496. {
  497. AZ::Transform localRotate = AZ::ConvertEulerDegreesToTransform(m_editorTransform.m_rotate);
  498. AZ::Vector3 yAxis = localRotate.GetBasisY();
  499. AZ::Quaternion yRotate = AZ::Quaternion::CreateFromAxisAngle(yAxis, eulerAngleRadian);
  500. AZ::Quaternion currentRotate = AZ::ConvertEulerDegreesToQuaternion(m_editorTransform.m_rotate);
  501. AZ::Quaternion newRotate = yRotate * currentRotate;
  502. newRotate.Normalize();
  503. m_editorTransform.m_rotate = newRotate.GetEulerDegrees();
  504. TransformChanged();
  505. }
  506. void TransformComponent::RotateAroundLocalZ(float eulerAngleRadian)
  507. {
  508. AZ::Transform localRotate = AZ::ConvertEulerDegreesToTransform(m_editorTransform.m_rotate);
  509. AZ::Vector3 zAxis = localRotate.GetBasisZ();
  510. AZ::Quaternion zRotate = AZ::Quaternion::CreateFromAxisAngle(zAxis, eulerAngleRadian);
  511. AZ::Quaternion currentRotate = AZ::ConvertEulerDegreesToQuaternion(m_editorTransform.m_rotate);
  512. AZ::Quaternion newRotate = zRotate * currentRotate;
  513. newRotate.Normalize();
  514. m_editorTransform.m_rotate = newRotate.GetEulerDegrees();
  515. TransformChanged();
  516. }
  517. AZ::Vector3 TransformComponent::GetLocalRotation()
  518. {
  519. AZ::Vector3 result = AZ::Vector3DegToRad(m_editorTransform.m_rotate);
  520. return result;
  521. }
  522. AZ::Quaternion TransformComponent::GetLocalRotationQuaternion()
  523. {
  524. AZ::Quaternion result = AZ::ConvertEulerDegreesToQuaternion(m_editorTransform.m_rotate);
  525. return result;
  526. }
  527. AZ::Vector3 TransformComponent::GetLocalScale()
  528. {
  529. AZ_WarningOnce("TransformComponent", false, "GetLocalScale is deprecated, please use GetLocalUniformScale instead");
  530. return m_editorTransform.m_legacyScale;
  531. }
  532. void TransformComponent::SetLocalUniformScale(float scale)
  533. {
  534. m_editorTransform.m_uniformScale = scale;
  535. TransformChanged();
  536. }
  537. float TransformComponent::GetLocalUniformScale()
  538. {
  539. return m_editorTransform.m_uniformScale;
  540. }
  541. float TransformComponent::GetWorldUniformScale()
  542. {
  543. return GetWorldTM().GetUniformScale();
  544. }
  545. const AZ::Transform& TransformComponent::GetParentWorldTM() const
  546. {
  547. auto parent = GetParentTransformComponent();
  548. if (parent)
  549. {
  550. return parent->GetWorldTM();
  551. }
  552. return AZ::Transform::Identity();
  553. }
  554. void TransformComponent::SetParentImpl(AZ::EntityId parentId, bool relative)
  555. {
  556. // If the parent id to be set is the same as the current parent id
  557. // Or if the component belongs to an entity and the entity's id is the same as the id being set as parent
  558. if (parentId == m_parentEntityId || (GetEntity() && (GetEntityId() == parentId)))
  559. {
  560. return;
  561. }
  562. // Entity is not associated if we're just doing data preparation (slice construction).
  563. if (!GetEntity() || GetEntity()->GetState() == AZ::Entity::State::Constructed)
  564. {
  565. m_previousParentEntityId = m_parentEntityId = parentId;
  566. return;
  567. }
  568. // Prevent this from parenting to its own child. Check if this entity is in the new parent's hierarchy.
  569. auto potentialParentTransformComponent = GetTransformComponent(parentId);
  570. if (potentialParentTransformComponent && potentialParentTransformComponent->IsEntityInHierarchy(GetEntityId()))
  571. {
  572. return;
  573. }
  574. auto oldParentId = m_parentEntityId;
  575. bool canChangeParent = true;
  576. AZ::TransformNotificationBus::Event(
  577. GetEntityId(),
  578. &AZ::TransformNotificationBus::Events::CanParentChange,
  579. canChangeParent,
  580. oldParentId,
  581. parentId);
  582. if (!canChangeParent)
  583. {
  584. return;
  585. }
  586. // SetLocalTM calls below can confuse listeners, because transforms are mathematically
  587. // detached before the ParentChanged events are dispatched. Suppress TransformChanged()
  588. // until the transaction is complete.
  589. m_suppressTransformChangedEvent = true;
  590. if (m_parentEntityId.IsValid())
  591. {
  592. AZ::TransformHierarchyInformationBus::Handler::BusDisconnect();
  593. AZ::TransformNotificationBus::MultiHandler::BusDisconnect(m_parentEntityId);
  594. AZ::EntityBus::Handler::BusDisconnect(m_parentEntityId);
  595. if (!relative)
  596. {
  597. SetLocalTM(GetParentWorldTM() * GetLocalTM());
  598. }
  599. TransformComponent* parentTransform = GetParentTransformComponent();
  600. if (parentTransform)
  601. {
  602. auto& parentChildIds = GetParentTransformComponent()->m_childrenEntityIds;
  603. parentChildIds.erase(AZStd::remove(parentChildIds.begin(), parentChildIds.end(), GetEntityId()), parentChildIds.end());
  604. }
  605. m_parentEntityId.SetInvalid();
  606. m_previousParentEntityId = m_parentEntityId;
  607. }
  608. if (parentId.IsValid())
  609. {
  610. AZ::TransformNotificationBus::MultiHandler::BusConnect(parentId);
  611. AZ::TransformHierarchyInformationBus::Handler::BusConnect(parentId);
  612. m_parentEntityId = parentId;
  613. m_previousParentEntityId = m_parentEntityId;
  614. if (!relative)
  615. {
  616. AZ::Transform parentXform = GetParentWorldTM();
  617. AZ::Transform inverseXform = parentXform.GetInverse();
  618. SetLocalTM(inverseXform * GetLocalTM());
  619. }
  620. // OnEntityActivated will trigger immediately if the parent is active
  621. AZ::EntityBus::Handler::BusConnect(m_parentEntityId);
  622. }
  623. m_suppressTransformChangedEvent = false;
  624. // This is for Create Entity as child / Drag+drop parent update / add component
  625. AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast(
  626. &AzToolsFramework::ToolsApplicationEvents::Bus::Events::EntityParentChanged, GetEntityId(), parentId, oldParentId);
  627. AZ::TransformNotificationBus::Event(
  628. GetEntityId(), &AZ::TransformNotificationBus::Events::OnParentChanged, oldParentId, parentId);
  629. m_parentChangedEvent.Signal(oldParentId, parentId);
  630. TransformChanged();
  631. }
  632. void TransformComponent::SetParent(AZ::EntityId parentId)
  633. {
  634. SetParentImpl(parentId, false);
  635. }
  636. void TransformComponent::SetParentRelative(AZ::EntityId parentId)
  637. {
  638. SetParentImpl(parentId, true);
  639. }
  640. AZ::EntityId TransformComponent::GetParentId()
  641. {
  642. return m_parentEntityId;
  643. }
  644. EntityIdList TransformComponent::GetChildren()
  645. {
  646. EntityIdList children;
  647. AZ::TransformHierarchyInformationBus::Event(GetEntityId(), &AZ::TransformHierarchyInformation::GatherChildren, children);
  648. return children;
  649. }
  650. EntityIdList TransformComponent::GetAllDescendants()
  651. {
  652. EntityIdList descendants = GetChildren();
  653. for (size_t i = 0; i < descendants.size(); ++i)
  654. {
  655. AZ::TransformHierarchyInformationBus::Event(descendants[i], &AZ::TransformHierarchyInformation::GatherChildren, descendants);
  656. }
  657. return descendants;
  658. }
  659. AZStd::vector<AZ::EntityId> TransformComponent::GetEntityAndAllDescendants()
  660. {
  661. AZStd::vector<AZ::EntityId> descendants = { GetEntityId() };
  662. for (size_t i = 0; i < descendants.size(); ++i)
  663. {
  664. AZ::TransformHierarchyInformationBus::Event(descendants[i], &AZ::TransformHierarchyInformation::GatherChildren, descendants);
  665. }
  666. return descendants;
  667. }
  668. void TransformComponent::GatherChildren(EntityIdList& children)
  669. {
  670. children.push_back(GetEntityId());
  671. }
  672. bool TransformComponent::IsStaticTransform()
  673. {
  674. return m_isStatic;
  675. }
  676. void TransformComponent::SetIsStaticTransform(bool isStatic)
  677. {
  678. m_isStatic = isStatic;
  679. }
  680. TransformComponent* TransformComponent::GetParentTransformComponent() const
  681. {
  682. TransformComponent* component = GetTransformComponent(m_parentEntityId);
  683. // if our parent was cleared but we haven't gotten our change notify yet, we need to walk the previous parent if possible
  684. // to get the proper component for any necessary cleanup
  685. if (!component && !m_parentEntityId.IsValid() && m_previousParentEntityId.IsValid())
  686. {
  687. component = GetTransformComponent(m_previousParentEntityId);
  688. }
  689. return component;
  690. }
  691. TransformComponent* TransformComponent::GetTransformComponent(AZ::EntityId otherEntityId) const
  692. {
  693. if (!otherEntityId.IsValid())
  694. {
  695. return nullptr;
  696. }
  697. AZ::Entity* entity = AZ::Interface<AZ::ComponentApplicationRequests>::Get()->FindEntity(otherEntityId);
  698. if (!entity)
  699. {
  700. return nullptr;
  701. }
  702. return entity->FindComponent<TransformComponent>();
  703. }
  704. AZ::TransformInterface* TransformComponent::GetParent()
  705. {
  706. return GetParentTransformComponent();
  707. }
  708. void TransformComponent::OnEntityActivated(const AZ::EntityId& parentEntityId)
  709. {
  710. AZ::TransformNotificationBus::MultiHandler::BusConnect(parentEntityId);
  711. AZ::TransformHierarchyInformationBus::Handler::BusConnect(parentEntityId);
  712. // Our parent entity has just been activated.
  713. AZ_Assert(parentEntityId == m_parentEntityId,
  714. "Received Activation message for an entity other than our parent.");
  715. TransformComponent* parentTransform = GetParentTransformComponent();
  716. if (parentTransform)
  717. {
  718. // Prevent circular parent/child relationships potentially generated through slice data hierarchies.
  719. // This doesn't only occur through direct user assignment of parent (which is handled separately),
  720. // but can also occur through cascading of slicces, so we need to validate on activation as well.
  721. if (GetEntity() && parentTransform->IsEntityInHierarchy(GetEntityId()))
  722. {
  723. AZ_Error("Transform Component", false,
  724. "Slice data propagation for Entity %s [%llu] has resulted in circular parent/child relationships. "
  725. "Parent assignment for this entity has been reset.",
  726. GetEntity()->GetName().c_str(),
  727. GetEntityId());
  728. SetParent(AZ::EntityId());
  729. return;
  730. }
  731. bool suppressTransformChangedEvent = m_suppressTransformChangedEvent;
  732. // temporarily disable calling OnTransformChanged, because CheckApplyCachedWorldTransform is not guaranteed
  733. // to call it when m_cachedWorldTransform is identity. We send it manually later.
  734. m_suppressTransformChangedEvent = false;
  735. // When parent comes online, compute local TM from world TM.
  736. CheckApplyCachedWorldTransform(parentTransform->GetWorldTM());
  737. if (!m_initialized)
  738. {
  739. m_initialized = true;
  740. // If this is the first time this entity is being activated, manually compute OnTransformChanged
  741. // this can occur when either the entity first created or undo/redo command is performed
  742. OnTransformChanged(AZ::Transform::Identity(), parentTransform->GetWorldTM());
  743. }
  744. m_suppressTransformChangedEvent = suppressTransformChangedEvent;
  745. auto& parentChildIds = GetParentTransformComponent()->m_childrenEntityIds;
  746. if (parentChildIds.end() == AZStd::find(parentChildIds.begin(), parentChildIds.end(), GetEntityId()))
  747. {
  748. parentChildIds.push_back(GetEntityId());
  749. }
  750. }
  751. UpdateCachedWorldTransform();
  752. }
  753. void TransformComponent::OnEntityDeactivated(const AZ::EntityId& parentEntityId)
  754. {
  755. AZ_Assert(parentEntityId == m_parentEntityId,
  756. "Received Deactivation message for an entity other than our parent.");
  757. AZ::TransformNotificationBus::MultiHandler::BusDisconnect(parentEntityId);
  758. }
  759. bool TransformComponent::IsEntityInHierarchy(AZ::EntityId entityId)
  760. {
  761. /// Begin 1.7 Release hack - #TODO - LMBR-37330
  762. if (GetParentId() == GetEntityId())
  763. {
  764. m_parentEntityId = m_previousParentEntityId;
  765. }
  766. /// End 1.7 Release hack
  767. auto parentTComp = this;
  768. while (parentTComp)
  769. {
  770. if (parentTComp->GetEntityId() == entityId)
  771. {
  772. return true;
  773. }
  774. parentTComp = parentTComp->GetParentTransformComponent();
  775. }
  776. return false;
  777. }
  778. AZ::Outcome<void, AZStd::string> TransformComponent::ValidatePotentialParent(void* newValue, const AZ::Uuid& valueType)
  779. {
  780. if (azrtti_typeid<AZ::EntityId>() != valueType)
  781. {
  782. AZ_Assert(false, "Unexpected value type");
  783. return AZ::Failure(AZStd::string("Trying to set an entity ID to something that isn't an entity ID."));
  784. }
  785. AZ::EntityId newParentId = static_cast<AZ::EntityId>(*((AZ::EntityId*)newValue));
  786. if (!newParentId.IsValid())
  787. {
  788. // Handled by the calling code.
  789. return AZ::Success();
  790. }
  791. AZ::EntityId selectedEntityId = GetEntityId();
  792. // Prevent setting the parent to the entity itself.
  793. if (newParentId == selectedEntityId)
  794. {
  795. return AZ::Failure(AZStd::string("You cannot set an entity's parent to itself."));
  796. }
  797. if (!EntitiesBelongToSamePrefab(EntityIdList{ selectedEntityId }, newParentId))
  798. {
  799. return AZ::Failure(AZStd::string("You cannot set an entity to be a child of an entity owned by a different prefab."));
  800. }
  801. // Don't allow the change if it will result in a cycle hierarchy
  802. auto potentialParentTransformComponent = GetTransformComponent(newParentId);
  803. if (potentialParentTransformComponent && potentialParentTransformComponent->IsEntityInHierarchy(selectedEntityId))
  804. {
  805. return AZ::Failure(AZStd::string("You cannot set an entity to be a child of one of its own children."));
  806. }
  807. // Don't allow read-only entities to be re-parented at all.
  808. // Also don't allow entities to be parented under read-only entities.
  809. if (auto readOnlyEntityPublicInterface = AZ::Interface<ReadOnlyEntityPublicInterface>::Get();
  810. readOnlyEntityPublicInterface->IsReadOnly(selectedEntityId) || readOnlyEntityPublicInterface->IsReadOnly(newParentId))
  811. {
  812. return AZ::Failure(AZStd::string("You cannot set an entity to be a child of a read-only entity."));
  813. }
  814. // Don't allow entities to be parented under closed containers.
  815. if (auto containerEntityInterface = AZ::Interface<ContainerEntityInterface>::Get();
  816. !containerEntityInterface->IsContainerOpen(newParentId))
  817. {
  818. return AZ::Failure(AZStd::string("You cannot set an entity to be a child of a closed container."));
  819. }
  820. // Don't allow entities to be parented outside their container.
  821. if (m_focusModeInterface && !m_focusModeInterface->IsInFocusSubTree(newParentId))
  822. {
  823. return AZ::Failure(AZStd::string("You can only set a parent as one of the entities belonging to the focused prefab."));
  824. }
  825. return AZ::Success();
  826. }
  827. AZ::u32 TransformComponent::ParentChangedInspector()
  828. {
  829. AZ::u32 refreshLevel = AZ::Edit::PropertyRefreshLevels::None;
  830. if (!m_parentEntityId.IsValid())
  831. {
  832. // Reroute the invalid id to the focused prefab container entity id
  833. auto prefabFocusPublicInterface = AZ::Interface<Prefab::PrefabFocusPublicInterface>::Get();
  834. if (prefabFocusPublicInterface)
  835. {
  836. auto editorEntityContextId = AzFramework::EntityContextId::CreateNull();
  837. EditorEntityContextRequestBus::BroadcastResult(
  838. editorEntityContextId, &EditorEntityContextRequests::GetEditorEntityContextId);
  839. m_parentEntityId = prefabFocusPublicInterface->GetFocusedPrefabContainerEntityId(editorEntityContextId);
  840. refreshLevel = AZ::Edit::PropertyRefreshLevels::ValuesOnly;
  841. }
  842. }
  843. auto parentId = m_parentEntityId;
  844. m_parentEntityId = m_previousParentEntityId;
  845. SetParent(parentId);
  846. return refreshLevel;
  847. }
  848. AZ::u32 TransformComponent::TransformChangedInspector()
  849. {
  850. if (TransformChanged())
  851. {
  852. AzToolsFramework::EditorTransformChangeNotificationBus::Broadcast(
  853. &AzToolsFramework::EditorTransformChangeNotificationBus::Events::OnEntityTransformChanged,
  854. EntityIdList{ GetEntityId() });
  855. }
  856. return AZ::Edit::PropertyRefreshLevels::None;
  857. }
  858. bool TransformComponent::TransformChanged()
  859. {
  860. if (!m_suppressTransformChangedEvent)
  861. {
  862. if (auto parent = GetParentTransformComponent())
  863. {
  864. OnTransformChanged(parent->GetLocalTM(), parent->GetWorldTM());
  865. }
  866. else
  867. {
  868. OnTransformChanged(AZ::Transform::Identity(), AZ::Transform::Identity());
  869. }
  870. return true;
  871. }
  872. return false;
  873. }
  874. // This is called when our transform changes static state.
  875. AZ::u32 TransformComponent::StaticChangedInspector()
  876. {
  877. InvalidatePropertyDisplay(AzToolsFramework::PropertyModificationRefreshLevel::Refresh_EntireTree);
  878. if (GetEntity())
  879. {
  880. SetDirty();
  881. AZ::TransformNotificationBus::Event(GetEntityId(), &AZ::TransformNotificationBus::Events::OnStaticChanged, m_isStatic);
  882. }
  883. return AZ::Edit::PropertyRefreshLevels::EntireTree;
  884. }
  885. void TransformComponent::ModifyEditorTransform(AZ::Vector3& vec, const AZ::Vector3& data, const AZ::Transform& parentInverse)
  886. {
  887. if (data.IsZero())
  888. {
  889. return;
  890. }
  891. auto delta = parentInverse.TransformPoint(data);
  892. vec += delta;
  893. TransformChanged();
  894. }
  895. void TransformComponent::TranslateBy(const AZ::Vector3& data)
  896. {
  897. auto parent = GetParentWorldTM();
  898. parent.SetTranslation(AZ::Vector3::CreateZero());
  899. parent.Invert();
  900. ModifyEditorTransform(m_editorTransform.m_translate, data, parent);
  901. }
  902. void TransformComponent::RotateBy(const AZ::Vector3& data)
  903. {
  904. auto parent = GetParentWorldTM();
  905. parent.SetTranslation(AZ::Vector3::CreateZero());
  906. parent.Invert();
  907. ModifyEditorTransform(m_editorTransform.m_rotate, data, parent);
  908. }
  909. AZ::EntityId TransformComponent::GetSliceEntityParentId()
  910. {
  911. return GetParentId();
  912. }
  913. EntityIdList TransformComponent::GetSliceEntityChildren()
  914. {
  915. return GetChildren();
  916. }
  917. void TransformComponent::BuildGameEntity(AZ::Entity* gameEntity)
  918. {
  919. AZ::TransformConfig configuration;
  920. configuration.m_parentId = m_parentEntityId;
  921. configuration.m_worldTransform = GetWorldTM();
  922. configuration.m_localTransform = GetLocalTM();
  923. configuration.m_parentActivationTransformMode = m_parentActivationTransformMode;
  924. configuration.m_isStatic = m_isStatic;
  925. configuration.m_interpolatePosition = m_interpolatePosition;
  926. configuration.m_interpolateRotation = m_interpolateRotation;
  927. gameEntity->CreateComponent<AzFramework::TransformComponent>()->SetConfiguration(configuration);
  928. }
  929. void TransformComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
  930. {
  931. provided.push_back(AZ_CRC_CE("TransformService"));
  932. }
  933. void TransformComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
  934. {
  935. incompatible.push_back(AZ_CRC_CE("TransformService"));
  936. }
  937. void TransformComponent::PasteOverComponent(const TransformComponent* sourceComponent, TransformComponent* destinationComponent)
  938. {
  939. // When pasting from another transform component, just grab the world transform as that's the part the user is intuitively expecting to bring over
  940. destinationComponent->SetWorldTM(const_cast<TransformComponent*>(sourceComponent)->GetWorldTM());
  941. }
  942. AZ::Component* TransformComponent::FindPresentOrPendingComponent(AZ::Uuid componentUuid)
  943. {
  944. // first check if the component is present and valid
  945. if (AZ::Component* foundComponent = GetEntity()->FindComponent(componentUuid))
  946. {
  947. return foundComponent;
  948. }
  949. // then check to see if there's a component pending because it's in an invalid state
  950. AZ::Entity::ComponentArrayType pendingComponents;
  951. AzToolsFramework::EditorPendingCompositionRequestBus::Event(GetEntityId(),
  952. &AzToolsFramework::EditorPendingCompositionRequests::GetPendingComponents, pendingComponents);
  953. for (const auto pendingComponent : pendingComponents)
  954. {
  955. if (pendingComponent->RTTI_IsTypeOf(componentUuid))
  956. {
  957. return pendingComponent;
  958. }
  959. }
  960. return nullptr;
  961. }
  962. bool TransformComponent::IsAddNonUniformScaleButtonReadOnly()
  963. {
  964. return FindPresentOrPendingComponent(EditorNonUniformScaleComponent::TYPEINFO_Uuid()) != nullptr;
  965. }
  966. AZ::Crc32 TransformComponent::OnAddNonUniformScaleButtonPressed()
  967. {
  968. // if there is already a non-uniform scale component, do nothing
  969. if (FindPresentOrPendingComponent(EditorNonUniformScaleComponent::TYPEINFO_Uuid()))
  970. {
  971. return AZ::Edit::PropertyRefreshLevels::None;
  972. }
  973. const AZStd::vector<AZ::EntityId> entityList = { GetEntityId() };
  974. const AZ::ComponentTypeList componentsToAdd = { EditorNonUniformScaleComponent::TYPEINFO_Uuid() };
  975. AzToolsFramework::EntityCompositionRequests::AddComponentsOutcome addComponentsOutcome;
  976. AzToolsFramework::EntityCompositionRequestBus::BroadcastResult(addComponentsOutcome,
  977. &AzToolsFramework::EntityCompositionRequests::AddComponentsToEntities, entityList, componentsToAdd);
  978. const auto nonUniformScaleComponent = FindPresentOrPendingComponent(EditorNonUniformScaleComponent::RTTI_Type());
  979. AZ::ComponentId nonUniformScaleComponentId =
  980. nonUniformScaleComponent ? nonUniformScaleComponent->GetId() : AZ::InvalidComponentId;
  981. if (!addComponentsOutcome.IsSuccess() || !nonUniformScaleComponent)
  982. {
  983. AZ_Warning("Transform component", false, "Failed to add non-uniform scale component.");
  984. return AZ::Edit::PropertyRefreshLevels::None;
  985. }
  986. AzToolsFramework::EntityPropertyEditorRequestBus::Broadcast(
  987. &AzToolsFramework::EntityPropertyEditorRequests::SetNewComponentId, nonUniformScaleComponentId);
  988. return AZ::Edit::PropertyRefreshLevels::EntireTree;
  989. }
  990. bool TransformComponent::ShowClearButtonHandler()
  991. {
  992. // Hide the clear button if the current entity is the focus root, which is the default value.
  993. return(!m_focusModeInterface->IsFocusRoot(GetParentId()));
  994. }
  995. void TransformComponent::Reflect(AZ::ReflectContext* context)
  996. {
  997. // reflect data for script, serialization, editing..
  998. if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  999. {
  1000. serializeContext->Class<EditorTransform>()->
  1001. Field("Translate", &EditorTransform::m_translate)->
  1002. Field("Rotate", &EditorTransform::m_rotate)->
  1003. Field("Scale", &EditorTransform::m_legacyScale)->
  1004. Field("Locked", &EditorTransform::m_locked)->
  1005. Field("UniformScale", &EditorTransform::m_uniformScale)->
  1006. Version(3, &Internal::EditorTransformDataConverter);
  1007. serializeContext->Class<Components::TransformComponent, EditorComponentBase>()->
  1008. Field("Parent Entity", &TransformComponent::m_parentEntityId)->
  1009. Field("Transform Data", &TransformComponent::m_editorTransform)->
  1010. Field("Cached World Transform", &TransformComponent::m_cachedWorldTransform)->
  1011. Field("Cached World Transform Parent", &TransformComponent::m_cachedWorldTransformParent)->
  1012. Field("Parent Activation Transform Mode", &TransformComponent::m_parentActivationTransformMode)->
  1013. Field("IsStatic", &TransformComponent::m_isStatic)->
  1014. Field("InterpolatePosition", &TransformComponent::m_interpolatePosition)->
  1015. Field("InterpolateRotation", &TransformComponent::m_interpolateRotation)->
  1016. Version(10, &Internal::TransformComponentDataConverter);
  1017. if (AZ::EditContext* ptrEdit = serializeContext->GetEditContext())
  1018. {
  1019. ptrEdit->Class<TransformComponent>("Transform", "Controls the placement of the entity in the world in 3d")->
  1020. ClassElement(AZ::Edit::ClassElements::EditorData, "")->
  1021. Attribute(AZ::Edit::Attributes::FixedComponentListIndex, 0)->
  1022. Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/Transform.svg")->
  1023. Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/Transform.svg")->
  1024. Attribute(AZ::Edit::Attributes::HelpPageURL, "https://o3de.org/docs/user-guide/components/reference/transform/")->
  1025. Attribute(AZ::Edit::Attributes::AutoExpand, true)->
  1026. DataElement(AZ::Edit::UIHandlers::Default, &TransformComponent::m_parentEntityId, "Parent entity", "")->
  1027. Attribute(AZ::Edit::Attributes::ChangeValidate, &TransformComponent::ValidatePotentialParent)->
  1028. Attribute(AZ::Edit::Attributes::ChangeNotify, &TransformComponent::ParentChangedInspector)->
  1029. Attribute(AZ::Edit::Attributes::SliceFlags, AZ::Edit::SliceFlags::DontGatherReference | AZ::Edit::SliceFlags::NotPushableOnSliceRoot)->
  1030. Attribute(AZ::Edit::Attributes::ShowClearButtonHandler, &TransformComponent::ShowClearButtonHandler)->
  1031. DataElement(AZ::Edit::UIHandlers::Default, &TransformComponent::m_editorTransform, "Values", "")->
  1032. Attribute(AZ::Edit::Attributes::ChangeNotify, &TransformComponent::TransformChangedInspector)->
  1033. Attribute(AZ::Edit::Attributes::AutoExpand, true)->
  1034. UIElement(AZ::Edit::UIHandlers::Button, "", "")->
  1035. Attribute(AZ::Edit::Attributes::ButtonText, "Add non-uniform scale")->
  1036. Attribute(AZ::Edit::Attributes::ReadOnly, &TransformComponent::IsAddNonUniformScaleButtonReadOnly)->
  1037. Attribute(AZ::Edit::Attributes::ChangeNotify, &TransformComponent::OnAddNonUniformScaleButtonPressed)->
  1038. DataElement(AZ::Edit::UIHandlers::ComboBox, &TransformComponent::m_parentActivationTransformMode,
  1039. "Parent activation", "Configures relative transform behavior when parent activates.")->
  1040. EnumAttribute(AZ::TransformConfig::ParentActivationTransformMode::MaintainOriginalRelativeTransform, "Original relative transform")->
  1041. EnumAttribute(AZ::TransformConfig::ParentActivationTransformMode::MaintainCurrentWorldTransform, "Current world transform")->
  1042. DataElement(AZ::Edit::UIHandlers::Default, &TransformComponent::m_isStatic ,"Static", "Static entities are highly optimized and cannot be moved during runtime.")->
  1043. Attribute(AZ::Edit::Attributes::ChangeNotify, &TransformComponent::StaticChangedInspector)->
  1044. DataElement(AZ::Edit::UIHandlers::Default, &TransformComponent::m_cachedWorldTransformParent, "Cached Parent Entity", "")->
  1045. Attribute(AZ::Edit::Attributes::SliceFlags, AZ::Edit::SliceFlags::DontGatherReference | AZ::Edit::SliceFlags::NotPushable)->
  1046. Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::Hide)->
  1047. DataElement(AZ::Edit::UIHandlers::Default, &TransformComponent::m_cachedWorldTransform, "Cached World Transform", "")->
  1048. Attribute(AZ::Edit::Attributes::SliceFlags, AZ::Edit::SliceFlags::NotPushable)->
  1049. Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::Hide);
  1050. ptrEdit->Class<EditorTransform>("Values", "XYZ PYR")->
  1051. DataElement(AZ::Edit::UIHandlers::Default, &EditorTransform::m_translate, "Translate", "Local Position (Relative to parent) in meters.")->
  1052. Attribute(AZ::Edit::Attributes::Step, 0.1f)->
  1053. Attribute(AZ::Edit::Attributes::Suffix, " m")->
  1054. Attribute(AZ::Edit::Attributes::Min, -AZ::Constants::MaxFloatBeforePrecisionLoss)->
  1055. Attribute(AZ::Edit::Attributes::Max, AZ::Constants::MaxFloatBeforePrecisionLoss)->
  1056. Attribute(AZ::Edit::Attributes::SliceFlags, AZ::Edit::SliceFlags::NotPushableOnSliceRoot)->
  1057. Attribute(AZ::Edit::Attributes::ReadOnly, &EditorTransform::m_locked)->
  1058. DataElement(AZ::Edit::UIHandlers::Default, &EditorTransform::m_rotate, "Rotate", "Local Rotation (Relative to parent) in degrees.")->
  1059. Attribute(AZ::Edit::Attributes::Step, 1.0f)->
  1060. Attribute(AZ::Edit::Attributes::Suffix, " deg")->
  1061. Attribute(AZ::Edit::Attributes::ReadOnly, &EditorTransform::m_locked)->
  1062. Attribute(AZ::Edit::Attributes::SliceFlags, AZ::Edit::SliceFlags::NotPushableOnSliceRoot)->
  1063. DataElement(AZ::Edit::UIHandlers::Default, &EditorTransform::m_uniformScale, "Uniform Scale", "Local Uniform Scale")->
  1064. Attribute(AZ::Edit::Attributes::Step, 0.1f)->
  1065. Attribute(AZ::Edit::Attributes::ReadOnly, &EditorTransform::m_locked)
  1066. ;
  1067. }
  1068. }
  1069. if (AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
  1070. {
  1071. // string-name differs from class-name to avoid collisions with the other "TransformComponent" (AzFramework::TransformComponent).
  1072. behaviorContext->Class<TransformComponent>("EditorTransformBus")->RequestBus("TransformBus");
  1073. }
  1074. AZ::JsonRegistrationContext* jsonRegistration = azrtti_cast<AZ::JsonRegistrationContext*>(context);
  1075. if (jsonRegistration)
  1076. {
  1077. jsonRegistration->Serializer<JsonTransformComponentSerializer>()->HandlesType<TransformComponent>();
  1078. }
  1079. }
  1080. void TransformComponent::AddContextMenuActions(QMenu* menu)
  1081. {
  1082. bool parentEntityIsReadOnly = false;
  1083. // If the parent entity is marked as read-only, don't allow actions on this transform.
  1084. if (auto readOnlyEntityPublicInterface = AZ::Interface<ReadOnlyEntityPublicInterface>::Get();
  1085. readOnlyEntityPublicInterface->IsReadOnly(GetEntityId()))
  1086. {
  1087. parentEntityIsReadOnly = true;
  1088. }
  1089. if (menu)
  1090. {
  1091. if (!menu->actions().empty())
  1092. {
  1093. menu->addSeparator();
  1094. }
  1095. QAction* resetAction = menu->addAction(QObject::tr("Reset transform values"), [this]()
  1096. {
  1097. {
  1098. AzToolsFramework::ScopedUndoBatch undo("Reset transform values");
  1099. m_editorTransform.m_translate = AZ::Vector3::CreateZero();
  1100. m_editorTransform.m_legacyScale = AZ::Vector3::CreateOne();
  1101. m_editorTransform.m_uniformScale = 1.0f;
  1102. m_editorTransform.m_rotate = AZ::Vector3::CreateZero();
  1103. OnTransformChanged();
  1104. SetDirty();
  1105. }
  1106. InvalidatePropertyDisplay(AzToolsFramework::Refresh_Values);
  1107. });
  1108. resetAction->setEnabled(!m_editorTransform.m_locked && !parentEntityIsReadOnly);
  1109. QString lockString = m_editorTransform.m_locked ? "Unlock transform values" : "Lock transform values";
  1110. QAction* lockAction = menu->addAction(lockString, [this, lockString]()
  1111. {
  1112. {
  1113. AzToolsFramework::ScopedUndoBatch undo(lockString.toUtf8().data());
  1114. m_editorTransform.m_locked = !m_editorTransform.m_locked;
  1115. SetDirty();
  1116. }
  1117. InvalidatePropertyDisplay(AzToolsFramework::Refresh_AttributesAndValues);
  1118. });
  1119. lockAction->setEnabled(!parentEntityIsReadOnly);
  1120. }
  1121. }
  1122. }
  1123. } // namespace AzToolsFramework