UiDynamicLayoutComponent.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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 "UiDynamicLayoutComponent.h"
  9. #include "UiElementComponent.h"
  10. #include <AzCore/Serialization/SerializeContext.h>
  11. #include <AzCore/Serialization/EditContext.h>
  12. #include <AzCore/RTTI/BehaviorContext.h>
  13. #include <AzCore/Component/ComponentApplicationBus.h>
  14. #include <LyShine/Bus/UiCanvasBus.h>
  15. #include <LyShine/Bus/UiLayoutBus.h>
  16. #include <LyShine/Bus/UiTransform2dBus.h>
  17. ////////////////////////////////////////////////////////////////////////////////////////////////////
  18. // PUBLIC MEMBER FUNCTIONS
  19. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21. UiDynamicLayoutComponent::UiDynamicLayoutComponent()
  22. : m_numChildElementsToClone(0)
  23. {
  24. }
  25. ////////////////////////////////////////////////////////////////////////////////////////////////////
  26. UiDynamicLayoutComponent::~UiDynamicLayoutComponent()
  27. {
  28. }
  29. ////////////////////////////////////////////////////////////////////////////////////////////////////
  30. void UiDynamicLayoutComponent::SetNumChildElements(int numChildren)
  31. {
  32. AZ::Entity* prototypeEntity = nullptr;
  33. AZ::ComponentApplicationBus::BroadcastResult(prototypeEntity, &AZ::ComponentApplicationBus::Events::FindEntity, m_prototypeElement);
  34. if (prototypeEntity)
  35. {
  36. int curNumChildren = 0;
  37. UiElementBus::EventResult(curNumChildren, GetEntityId(), &UiElementBus::Events::GetNumChildElements);
  38. if (curNumChildren != numChildren)
  39. {
  40. if (curNumChildren < numChildren)
  41. {
  42. SetPrototypeElementActive(true);
  43. AZ::EntityId canvasEntityId;
  44. UiElementBus::EventResult(canvasEntityId, GetEntityId(), &UiElementBus::Events::GetCanvasEntityId);
  45. for (int i = 0; i < numChildren - curNumChildren; i++)
  46. {
  47. // Clone the prototype element and add it as a child
  48. AZ::Entity* clonedElement = nullptr;
  49. UiCanvasBus::EventResult(
  50. clonedElement, canvasEntityId, &UiCanvasBus::Events::CloneElement, prototypeEntity, GetEntity());
  51. }
  52. SetPrototypeElementActive(false);
  53. }
  54. else // curNumChildren > numChildren
  55. {
  56. UiElementComponent* elementComponent = GetEntity()->FindComponent<UiElementComponent>();
  57. AZ_Assert(elementComponent, "entity has no UiElementComponent");
  58. for (int i = curNumChildren - 1; i >= numChildren; i--)
  59. {
  60. // Remove the cloned child element
  61. AZ::Entity* element = nullptr;
  62. UiElementBus::EventResult(element, GetEntityId(), &UiElementBus::Events::GetChildElement, i);
  63. if (element)
  64. {
  65. elementComponent->RemoveChild(element);
  66. UiElementBus::Event(element->GetId(), &UiElementBus::Events::DestroyElement);
  67. }
  68. }
  69. }
  70. // Resize the element
  71. ResizeToFitChildElements();
  72. }
  73. }
  74. }
  75. ////////////////////////////////////////////////////////////////////////////////////////////////////
  76. void UiDynamicLayoutComponent::InGamePostActivate()
  77. {
  78. // Find the prototype element
  79. int numChildren = 0;
  80. UiElementBus::EventResult(numChildren, GetEntityId(), &UiElementBus::Events::GetNumChildElements);
  81. if (numChildren > 0)
  82. {
  83. AZ::Entity* prototypeEntity = nullptr;
  84. UiElementBus::EventResult(prototypeEntity, GetEntityId(), &UiElementBus::Events::GetChildElement, 0);
  85. if (prototypeEntity)
  86. {
  87. // Store the prototype element for future cloning
  88. m_prototypeElement = prototypeEntity->GetId();
  89. // Store the size of the prototype element for future layout element size calculations
  90. UiTransformBus::EventResult(
  91. m_prototypeElementSize, m_prototypeElement, &UiTransformBus::Events::GetCanvasSpaceSizeNoScaleRotate);
  92. UiElementComponent* elementComponent = GetEntity()->FindComponent<UiElementComponent>();
  93. AZ_Assert(elementComponent, "entity has no UiElementComponent");
  94. // Remove any extra elements
  95. if (numChildren > 1)
  96. {
  97. for (int i = numChildren - 1; i > 0; i--)
  98. {
  99. // Remove the child element
  100. AZ::Entity* element = nullptr;
  101. UiElementBus::EventResult(element, GetEntityId(), &UiElementBus::Events::GetChildElement, i);
  102. if (element)
  103. {
  104. elementComponent->RemoveChild(element);
  105. UiElementBus::Event(element->GetId(), &UiElementBus::Events::DestroyElement);
  106. }
  107. }
  108. }
  109. // Remove the prototype element
  110. elementComponent->RemoveChild(prototypeEntity);
  111. SetPrototypeElementActive(false);
  112. // Listen for canvas space rect changes
  113. UiTransformChangeNotificationBus::Handler::BusConnect(GetEntityId());
  114. }
  115. }
  116. // Initialize the number of child elements
  117. SetNumChildElements(m_numChildElementsToClone);
  118. if (m_numChildElementsToClone == 0)
  119. {
  120. // Resize the element
  121. ResizeToFitChildElements();
  122. }
  123. }
  124. ////////////////////////////////////////////////////////////////////////////////////////////////////
  125. void UiDynamicLayoutComponent::OnCanvasSpaceRectChanged([[maybe_unused]] AZ::EntityId entityId, const UiTransformInterface::Rect& oldRect, const UiTransformInterface::Rect& newRect)
  126. {
  127. // If old rect equals new rect, size changed due to initialization
  128. bool sizeChanged = (oldRect == newRect) || (!oldRect.GetSize().IsClose(newRect.GetSize(), 0.05f));
  129. if (sizeChanged)
  130. {
  131. // Resize the element
  132. ResizeToFitChildElements();
  133. }
  134. }
  135. ////////////////////////////////////////////////////////////////////////////////////////////////////
  136. void UiDynamicLayoutComponent::OnUiElementBeingDestroyed()
  137. {
  138. if (m_prototypeElement.IsValid())
  139. {
  140. UiElementBus::Event(m_prototypeElement, &UiElementBus::Events::DestroyElement);
  141. m_prototypeElement.SetInvalid();
  142. }
  143. }
  144. ////////////////////////////////////////////////////////////////////////////////////////////////////
  145. // PUBLIC STATIC MEMBER FUNCTIONS
  146. ////////////////////////////////////////////////////////////////////////////////////////////////////
  147. void UiDynamicLayoutComponent::Reflect(AZ::ReflectContext* context)
  148. {
  149. AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
  150. if (serializeContext)
  151. {
  152. serializeContext->Class<UiDynamicLayoutComponent, AZ::Component>()
  153. ->Version(1)
  154. ->Field("NumChildElements", &UiDynamicLayoutComponent::m_numChildElementsToClone);
  155. AZ::EditContext* ec = serializeContext->GetEditContext();
  156. if (ec)
  157. {
  158. auto editInfo = ec->Class<UiDynamicLayoutComponent>("DynamicLayout",
  159. "A component that clones the prototype element and resizes the layout. The first child element acts as the prototype element.");
  160. editInfo->ClassElement(AZ::Edit::ClassElements::EditorData, "")
  161. ->Attribute(AZ::Edit::Attributes::Category, "UI")
  162. ->Attribute(AZ::Edit::Attributes::Icon, "Editor/Icons/Components/UiDynamicLayout.png")
  163. ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Editor/Icons/Components/Viewport/UiDynamicLayout.png")
  164. ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("UI", 0x27ff46b0))
  165. ->Attribute(AZ::Edit::Attributes::AutoExpand, true);
  166. editInfo->DataElement(AZ::Edit::UIHandlers::SpinBox, &UiDynamicLayoutComponent::m_numChildElementsToClone, "Num Cloned Elements",
  167. "The number of child elements to initialize the layout with.")
  168. ->Attribute(AZ::Edit::Attributes::Min, 0);
  169. }
  170. }
  171. AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context);
  172. if (behaviorContext)
  173. {
  174. behaviorContext->EBus<UiDynamicLayoutBus>("UiDynamicLayoutBus")
  175. ->Event("SetNumChildElements", &UiDynamicLayoutBus::Events::SetNumChildElements);
  176. }
  177. }
  178. ////////////////////////////////////////////////////////////////////////////////////////////////////
  179. // PROTECTED MEMBER FUNCTIONS
  180. ////////////////////////////////////////////////////////////////////////////////////////////////////
  181. ////////////////////////////////////////////////////////////////////////////////////////////////////
  182. void UiDynamicLayoutComponent::Activate()
  183. {
  184. UiDynamicLayoutBus::Handler::BusConnect(GetEntityId());
  185. UiInitializationBus::Handler::BusConnect(GetEntityId());
  186. UiElementNotificationBus::Handler::BusConnect(GetEntityId());
  187. }
  188. ////////////////////////////////////////////////////////////////////////////////////////////////////
  189. void UiDynamicLayoutComponent::Deactivate()
  190. {
  191. UiDynamicLayoutBus::Handler::BusDisconnect();
  192. UiInitializationBus::Handler::BusDisconnect();
  193. if (UiTransformChangeNotificationBus::Handler::BusIsConnected())
  194. {
  195. UiTransformChangeNotificationBus::Handler::BusDisconnect();
  196. }
  197. UiElementNotificationBus::Handler::BusDisconnect();
  198. }
  199. ////////////////////////////////////////////////////////////////////////////////////////////////////
  200. void UiDynamicLayoutComponent::SetPrototypeElementActive(bool active)
  201. {
  202. AZ::Entity* prototypeEntity = nullptr;
  203. AZ::ComponentApplicationBus::BroadcastResult(prototypeEntity, &AZ::ComponentApplicationBus::Events::FindEntity, m_prototypeElement);
  204. if (prototypeEntity)
  205. {
  206. LyShine::EntityArray descendantElements;
  207. if (active)
  208. {
  209. prototypeEntity->Activate();
  210. // Have to get children after it is Activated since it will not be connected to bus before that
  211. UiElementBus::Event(
  212. prototypeEntity->GetId(),
  213. &UiElementBus::Events::FindDescendantElements,
  214. [](const AZ::Entity*)
  215. {
  216. return true;
  217. },
  218. descendantElements);
  219. }
  220. else
  221. {
  222. // Have to get children before it is Deactivated since it will not be connected to bus after that
  223. UiElementBus::Event(
  224. prototypeEntity->GetId(),
  225. &UiElementBus::Events::FindDescendantElements,
  226. [](const AZ::Entity*)
  227. {
  228. return true;
  229. },
  230. descendantElements);
  231. prototypeEntity->Deactivate();
  232. }
  233. for (AZ::Entity* child : descendantElements)
  234. {
  235. if (active)
  236. {
  237. if (child->GetState() != AZ::Entity::State::Active)
  238. {
  239. child->Activate();
  240. }
  241. else
  242. {
  243. AZ_Warning("UiDynamicLayoutComponent", false, "Entity %s [%s] is already activated, which is not expected. Make sure you are not calling SetNumChildElements from a Script Activate function.",
  244. child->GetName().c_str(), child->GetId().ToString().c_str());
  245. }
  246. }
  247. else
  248. {
  249. if (child->GetState() == AZ::Entity::State::Active)
  250. {
  251. child->Deactivate();
  252. }
  253. else
  254. {
  255. AZ_Warning("UiDynamicLayoutComponent", false, "Entity %s [%s] is already deactivated, which is not expected.",
  256. child->GetName().c_str(), child->GetId().ToString().c_str());
  257. }
  258. }
  259. }
  260. }
  261. }
  262. ////////////////////////////////////////////////////////////////////////////////////////////////////
  263. void UiDynamicLayoutComponent::ResizeToFitChildElements()
  264. {
  265. if (!m_prototypeElement.IsValid())
  266. {
  267. return;
  268. }
  269. // Only change the layout's size if it's not being controlled by its parent
  270. AZ::Entity* parentElement = nullptr;
  271. UiElementBus::EventResult(parentElement, GetEntityId(), &UiElementBus::Events::GetParent);
  272. if (parentElement)
  273. {
  274. bool isControlledByParent = false;
  275. UiLayoutBus::EventResult(isControlledByParent, parentElement->GetId(), &UiLayoutBus::Events::IsControllingChild, GetEntityId());
  276. if (isControlledByParent)
  277. {
  278. return;
  279. }
  280. }
  281. int numChildren = 0;
  282. UiElementBus::EventResult(numChildren, GetEntityId(), &UiElementBus::Events::GetNumChildElements);
  283. AZ::Vector2 curSize(0.0f, 0.0f);
  284. UiTransformBus::EventResult(curSize, GetEntityId(), &UiTransformBus::Events::GetCanvasSpaceSizeNoScaleRotate);
  285. AZ::Vector2 newSize(0.0f, 0.0f);
  286. UiLayoutBus::EventResult(newSize, GetEntityId(), &UiLayoutBus::Events::GetSizeToFitChildElements, m_prototypeElementSize, numChildren);
  287. if (!curSize.IsClose(newSize, 0.05f))
  288. {
  289. UiTransform2dInterface::Offsets offsets;
  290. UiTransform2dBus::EventResult(offsets, GetEntityId(), &UiTransform2dBus::Events::GetOffsets);
  291. AZ::Vector2 pivot;
  292. UiTransformBus::EventResult(pivot, GetEntityId(), &UiTransformBus::Events::GetPivot);
  293. AZ::Vector2 sizeDiff = newSize - curSize;
  294. bool offsetsChanged = false;
  295. if (sizeDiff.GetX() != 0.0f)
  296. {
  297. offsets.m_left -= sizeDiff.GetX() * pivot.GetX();
  298. offsets.m_right += sizeDiff.GetX() * (1.0f - pivot.GetX());
  299. offsetsChanged = true;
  300. }
  301. if (sizeDiff.GetY() != 0.0f)
  302. {
  303. offsets.m_top -= sizeDiff.GetY() * pivot.GetY();
  304. offsets.m_bottom += sizeDiff.GetY() * (1.0f - pivot.GetY());
  305. offsetsChanged = true;
  306. }
  307. if (offsetsChanged)
  308. {
  309. UiTransform2dBus::Event(GetEntityId(), &UiTransform2dBus::Events::SetOffsets, offsets);
  310. }
  311. }
  312. }