3
0

UiScrollBoxComponent.cpp 106 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682
  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 "UiScrollBoxComponent.h"
  9. #include "Sprite.h"
  10. #include <AzCore/Component/TickBus.h>
  11. #include <AzCore/Serialization/SerializeContext.h>
  12. #include <AzCore/Serialization/EditContext.h>
  13. #include <AzCore/RTTI/BehaviorContext.h>
  14. #include <AzCore/std/sort.h>
  15. #include <LyShine/Bus/UiCanvasBus.h>
  16. #include <LyShine/Bus/UiElementBus.h>
  17. #include <LyShine/Bus/UiTransform2dBus.h>
  18. #include <LyShine/Bus/UiTransformBus.h>
  19. #include <LyShine/Bus/UiVisualBus.h>
  20. #include <LyShine/ISprite.h>
  21. #include <LyShine/UiSerializeHelpers.h>
  22. #include "UiSerialize.h"
  23. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24. //! UiScrollBoxNotificationBus Behavior context handler class
  25. class BehaviorUiScrollBoxNotificationBusHandler
  26. : public UiScrollBoxNotificationBus::Handler
  27. , public AZ::BehaviorEBusHandler
  28. {
  29. public:
  30. AZ_EBUS_BEHAVIOR_BINDER(BehaviorUiScrollBoxNotificationBusHandler, "{15CA0E45-F673-4E18-922F-D9DB1272CFEA}", AZ::SystemAllocator,
  31. OnScrollOffsetChanging, OnScrollOffsetChanged);
  32. void OnScrollOffsetChanging(AZ::Vector2 value) override
  33. {
  34. Call(FN_OnScrollOffsetChanging, value);
  35. }
  36. void OnScrollOffsetChanged(AZ::Vector2 value) override
  37. {
  38. Call(FN_OnScrollOffsetChanged, value);
  39. }
  40. };
  41. ////////////////////////////////////////////////////////////////////////////////////////////////////
  42. //! UiScrollableNotificationBus Behavior context handler class
  43. class BehaviorUiScrollableNotificationBusHandler
  44. : public UiScrollableNotificationBus::Handler
  45. , public AZ::BehaviorEBusHandler
  46. {
  47. public:
  48. AZ_EBUS_BEHAVIOR_BINDER(BehaviorUiScrollableNotificationBusHandler, "{7F130E59-778C-4951-BB62-B2E57E530BC0}", AZ::SystemAllocator,
  49. OnScrollableValueChanging, OnScrollableValueChanged);
  50. void OnScrollableValueChanging(AZ::Vector2 value) override
  51. {
  52. Call(FN_OnScrollableValueChanging, value);
  53. }
  54. void OnScrollableValueChanged(AZ::Vector2 value) override
  55. {
  56. Call(FN_OnScrollableValueChanged, value);
  57. }
  58. };
  59. ////////////////////////////////////////////////////////////////////////////////////////////////////
  60. // PUBLIC MEMBER FUNCTIONS
  61. ////////////////////////////////////////////////////////////////////////////////////////////////////
  62. ////////////////////////////////////////////////////////////////////////////////////////////////////
  63. UiScrollBoxComponent::UiScrollBoxComponent()
  64. : m_scrollOffset(0.0f, 0.0f)
  65. , m_isHorizontalScrollingEnabled(true)
  66. , m_isVerticalScrollingEnabled(false)
  67. , m_isScrollingConstrained(true)
  68. , m_snapMode(SnapMode::None)
  69. , m_snapGrid(10.0f, 10.0f)
  70. , m_hScrollBarVisibility(ScrollBarVisibility::AlwaysShow)
  71. , m_vScrollBarVisibility(ScrollBarVisibility::AlwaysShow)
  72. , m_contentEntity()
  73. , m_hScrollBarEntity()
  74. , m_vScrollBarEntity()
  75. , m_onScrollOffsetChanged()
  76. , m_onScrollOffsetChanging()
  77. , m_scrollOffsetChangedActionName()
  78. , m_scrollOffsetChangingActionName()
  79. , m_isDragging(false)
  80. , m_isActive(false)
  81. , m_pressedScrollOffset(0.0f, 0.0f)
  82. , m_lastDragPoint(0.0f, 0.0f)
  83. , m_scrollSensitivity(1.0f, 1.0f)
  84. , m_lastOffsetChange(0.0f, 0.0f)
  85. , m_offsetChangeAccumulator(0.0f, 0.0f)
  86. , m_stoppingTimeAccumulator(0.0f)
  87. , m_draggingTimeAccumulator(0.0f)
  88. , m_momentumIsActive(false)
  89. , m_momentumDuration(0.0f)
  90. , m_momentumTimeAccumulator(0.0f)
  91. {
  92. }
  93. ////////////////////////////////////////////////////////////////////////////////////////////////////
  94. UiScrollBoxComponent::~UiScrollBoxComponent()
  95. {
  96. }
  97. ////////////////////////////////////////////////////////////////////////////////////////////////////
  98. AZ::Vector2 UiScrollBoxComponent::GetScrollOffset()
  99. {
  100. return m_scrollOffset;
  101. }
  102. ////////////////////////////////////////////////////////////////////////////////////////////////////
  103. void UiScrollBoxComponent::SetScrollOffset(AZ::Vector2 scrollOffset)
  104. {
  105. if (m_isScrollingConstrained)
  106. {
  107. AZ::Entity* contentParentEntity = nullptr;
  108. UiElementBus::EventResult(contentParentEntity, m_contentEntity, &UiElementBus::Events::GetParent);
  109. if (contentParentEntity)
  110. {
  111. scrollOffset = ConstrainOffset(scrollOffset, contentParentEntity);
  112. }
  113. }
  114. if (scrollOffset != m_scrollOffset)
  115. {
  116. DoSetScrollOffset(scrollOffset);
  117. // Reset drag info
  118. if (m_isDragging)
  119. {
  120. m_pressedScrollOffset = m_scrollOffset;
  121. m_pressedPoint = m_lastDragPoint;
  122. }
  123. NotifyScrollersOnValueChanged();
  124. DoChangedActions();
  125. }
  126. }
  127. ////////////////////////////////////////////////////////////////////////////////////////////////////
  128. AZ::Vector2 UiScrollBoxComponent::GetNormalizedScrollValue()
  129. {
  130. AZ::Vector2 normalizedScrollValueOut(0.0f, 0.0f);
  131. ScrollOffsetToNormalizedScrollValue(m_scrollOffset, normalizedScrollValueOut);
  132. return normalizedScrollValueOut;
  133. }
  134. ////////////////////////////////////////////////////////////////////////////////////////////////////
  135. void UiScrollBoxComponent::ChangeContentSizeAndScrollOffset(AZ::Vector2 contentSize, AZ::Vector2 scrollOffset)
  136. {
  137. if (m_contentEntity.IsValid())
  138. {
  139. AZ::Vector2 prevScrollOffset = m_scrollOffset;
  140. // Get current content size
  141. AZ::Vector2 prevContentSize(0.0f, 0.0f);
  142. UiTransformBus::EventResult(prevContentSize, m_contentEntity, &UiTransformBus::Events::GetCanvasSpaceSizeNoScaleRotate);
  143. // Resize content element
  144. if (prevContentSize != contentSize)
  145. {
  146. UiTransform2dInterface::Offsets offsets;
  147. UiTransform2dBus::EventResult(offsets, m_contentEntity, &UiTransform2dBus::Events::GetOffsets);
  148. AZ::Vector2 pivot;
  149. UiTransformBus::EventResult(pivot, m_contentEntity, &UiTransformBus::Events::GetPivot);
  150. AZ::Vector2 sizeDiff = contentSize - prevContentSize;
  151. if (sizeDiff.GetX() != 0.0f)
  152. {
  153. offsets.m_left -= sizeDiff.GetX() * pivot.GetX();
  154. offsets.m_right += sizeDiff.GetX() * (1.0f - pivot.GetX());
  155. }
  156. if (sizeDiff.GetY() != 0.0f)
  157. {
  158. offsets.m_top -= sizeDiff.GetY() * pivot.GetY();
  159. offsets.m_bottom += sizeDiff.GetY() * (1.0f - pivot.GetY());
  160. }
  161. UiTransform2dBus::Event(m_contentEntity, &UiTransform2dBus::Events::SetOffsets, offsets);
  162. }
  163. // Adjust scroll offset
  164. if (m_scrollOffset != scrollOffset)
  165. {
  166. DoSetScrollOffset(scrollOffset);
  167. }
  168. // Reset drag info
  169. if (m_isDragging)
  170. {
  171. m_pressedScrollOffset = m_scrollOffset;
  172. m_pressedPoint = m_lastDragPoint;
  173. }
  174. // Handle content size change which also handles snapping/constraining
  175. if (prevContentSize != contentSize)
  176. {
  177. ContentOrParentSizeChanged();
  178. }
  179. else
  180. {
  181. if (prevScrollOffset != m_scrollOffset)
  182. {
  183. NotifyScrollersOnValueChanged();
  184. }
  185. if (DoSnap())
  186. {
  187. // Reset drag info
  188. if (m_isDragging)
  189. {
  190. m_pressedScrollOffset = m_scrollOffset;
  191. m_pressedPoint = m_lastDragPoint;
  192. }
  193. NotifyScrollersOnValueChanged();
  194. DoChangedActions();
  195. }
  196. }
  197. }
  198. }
  199. ////////////////////////////////////////////////////////////////////////////////////////////////////
  200. bool UiScrollBoxComponent::HasHorizontalContentToScroll()
  201. {
  202. bool hasContentToScroll = false;
  203. if (!m_isHorizontalScrollingEnabled)
  204. {
  205. hasContentToScroll = false;
  206. }
  207. else if (!m_isScrollingConstrained)
  208. {
  209. hasContentToScroll = true;
  210. }
  211. else
  212. {
  213. if (m_hScrollBarEntity.IsValid() && (m_hScrollBarVisibility != ScrollBarVisibility::AlwaysShow))
  214. {
  215. bool isEnabled = false;
  216. UiElementBus::EventResult(isEnabled, m_hScrollBarEntity, &UiElementBus::Events::IsEnabled);
  217. hasContentToScroll = isEnabled;
  218. }
  219. else
  220. {
  221. AZ::Entity* contentParentEntity = nullptr;
  222. UiElementBus::EventResult(contentParentEntity, m_contentEntity, &UiElementBus::Events::GetParent);
  223. if (contentParentEntity)
  224. {
  225. // Get content parent's size
  226. AZ::Vector2 parentSize;
  227. UiTransformBus::EventResult(
  228. parentSize, contentParentEntity->GetId(), &UiTransformBus::Events::GetCanvasSpaceSizeNoScaleRotate);
  229. // Get content size
  230. UiTransformInterface::Rect contentRect = GetAxisAlignedContentRect();
  231. AZ::Vector2 contentSize = contentRect.GetSize();
  232. hasContentToScroll = contentSize.GetX() > parentSize.GetX();
  233. }
  234. }
  235. }
  236. return hasContentToScroll;
  237. }
  238. ////////////////////////////////////////////////////////////////////////////////////////////////////
  239. bool UiScrollBoxComponent::HasVerticalContentToScroll()
  240. {
  241. bool hasContentToScroll = false;
  242. if (!m_isVerticalScrollingEnabled)
  243. {
  244. hasContentToScroll = false;
  245. }
  246. else if (!m_isScrollingConstrained)
  247. {
  248. hasContentToScroll = true;
  249. }
  250. else
  251. {
  252. if (m_vScrollBarEntity.IsValid() && (m_vScrollBarVisibility != ScrollBarVisibility::AlwaysShow))
  253. {
  254. bool isEnabled = false;
  255. UiElementBus::EventResult(isEnabled, m_vScrollBarEntity, &UiElementBus::Events::IsEnabled);
  256. hasContentToScroll = isEnabled;
  257. }
  258. else
  259. {
  260. AZ::Entity* contentParentEntity = nullptr;
  261. UiElementBus::EventResult(contentParentEntity, m_contentEntity, &UiElementBus::Events::GetParent);
  262. if (contentParentEntity)
  263. {
  264. // Get content parent's size
  265. AZ::Vector2 parentSize;
  266. UiTransformBus::EventResult(
  267. parentSize, contentParentEntity->GetId(), &UiTransformBus::Events::GetCanvasSpaceSizeNoScaleRotate);
  268. // Get content size
  269. UiTransformInterface::Rect contentRect = GetAxisAlignedContentRect();
  270. AZ::Vector2 contentSize = contentRect.GetSize();
  271. hasContentToScroll = contentSize.GetY() > parentSize.GetY();
  272. }
  273. }
  274. }
  275. return hasContentToScroll;
  276. }
  277. ////////////////////////////////////////////////////////////////////////////////////////////////////
  278. bool UiScrollBoxComponent::GetIsHorizontalScrollingEnabled()
  279. {
  280. return m_isHorizontalScrollingEnabled;
  281. }
  282. ////////////////////////////////////////////////////////////////////////////////////////////////////
  283. void UiScrollBoxComponent::SetIsHorizontalScrollingEnabled(bool isEnabled)
  284. {
  285. m_isHorizontalScrollingEnabled = isEnabled;
  286. }
  287. ////////////////////////////////////////////////////////////////////////////////////////////////////
  288. bool UiScrollBoxComponent::GetIsVerticalScrollingEnabled()
  289. {
  290. return m_isVerticalScrollingEnabled;
  291. }
  292. ////////////////////////////////////////////////////////////////////////////////////////////////////
  293. void UiScrollBoxComponent::SetIsVerticalScrollingEnabled(bool isEnabled)
  294. {
  295. m_isVerticalScrollingEnabled = isEnabled;
  296. }
  297. ////////////////////////////////////////////////////////////////////////////////////////////////////
  298. bool UiScrollBoxComponent::GetIsScrollingConstrained()
  299. {
  300. return m_isScrollingConstrained;
  301. }
  302. ////////////////////////////////////////////////////////////////////////////////////////////////////
  303. void UiScrollBoxComponent::SetIsScrollingConstrained(bool isConstrained)
  304. {
  305. m_isScrollingConstrained = isConstrained;
  306. }
  307. ////////////////////////////////////////////////////////////////////////////////////////////////////
  308. UiScrollBoxInterface::SnapMode UiScrollBoxComponent::GetSnapMode()
  309. {
  310. return m_snapMode;
  311. }
  312. ////////////////////////////////////////////////////////////////////////////////////////////////////
  313. void UiScrollBoxComponent::SetSnapMode(SnapMode snapMode)
  314. {
  315. m_snapMode = snapMode;
  316. }
  317. ////////////////////////////////////////////////////////////////////////////////////////////////////
  318. AZ::Vector2 UiScrollBoxComponent::GetSnapGrid()
  319. {
  320. return m_snapGrid;
  321. }
  322. ////////////////////////////////////////////////////////////////////////////////////////////////////
  323. void UiScrollBoxComponent::SetSnapGrid(AZ::Vector2 snapGrid)
  324. {
  325. m_snapGrid = snapGrid;
  326. }
  327. ////////////////////////////////////////////////////////////////////////////////////////////////////
  328. UiScrollBoxInterface::ScrollBarVisibility UiScrollBoxComponent::GetHorizontalScrollBarVisibility()
  329. {
  330. return m_hScrollBarVisibility;
  331. }
  332. ////////////////////////////////////////////////////////////////////////////////////////////////////
  333. void UiScrollBoxComponent::SetHorizontalScrollBarVisibility(ScrollBarVisibility visibility)
  334. {
  335. m_hScrollBarVisibility = visibility;
  336. }
  337. ////////////////////////////////////////////////////////////////////////////////////////////////////
  338. UiScrollBoxInterface::ScrollBarVisibility UiScrollBoxComponent::GetVerticalScrollBarVisibility()
  339. {
  340. return m_vScrollBarVisibility;
  341. }
  342. ////////////////////////////////////////////////////////////////////////////////////////////////////
  343. void UiScrollBoxComponent::SetVerticalScrollBarVisibility(ScrollBarVisibility visibility)
  344. {
  345. m_vScrollBarVisibility = visibility;
  346. }
  347. ////////////////////////////////////////////////////////////////////////////////////////////////////
  348. AZ::Vector2 UiScrollBoxComponent::GetScrollSensitivity()
  349. {
  350. return m_scrollSensitivity;
  351. }
  352. ////////////////////////////////////////////////////////////////////////////////////////////////////
  353. void UiScrollBoxComponent::SetScrollSensitivity(AZ::Vector2 scrollSensitivity)
  354. {
  355. m_scrollSensitivity = scrollSensitivity;
  356. }
  357. ////////////////////////////////////////////////////////////////////////////////////////////////////
  358. float UiScrollBoxComponent::GetMomentumDuration()
  359. {
  360. return m_momentumDuration;
  361. }
  362. ////////////////////////////////////////////////////////////////////////////////////////////////////
  363. void UiScrollBoxComponent::SetMomentumDuration(float scrollMomentumDuration)
  364. {
  365. m_momentumDuration = scrollMomentumDuration;
  366. }
  367. void UiScrollBoxComponent::SetMomentumActive(bool activate)
  368. {
  369. m_momentumIsActive = activate;
  370. if (m_momentumIsActive)
  371. {
  372. m_momentumTimeAccumulator = 0.0f;
  373. }
  374. else
  375. {
  376. m_offsetChangeAccumulator.Set(0.0f, 0.0f);
  377. m_draggingTimeAccumulator = 0.0f;
  378. m_stoppingTimeAccumulator = 0.0f;
  379. }
  380. }
  381. void UiScrollBoxComponent::StopMomentum()
  382. {
  383. m_offsetChangeAccumulator.Set(0.0f, 0.0f);
  384. m_draggingTimeAccumulator = 0.0f;
  385. m_stoppingTimeAccumulator = 0.0f;
  386. m_momentumTimeAccumulator = 0.0f;
  387. }
  388. ////////////////////////////////////////////////////////////////////////////////////////////////////
  389. UiScrollBoxComponent::ScrollOffsetChangeCallback UiScrollBoxComponent::GetScrollOffsetChangingCallback()
  390. {
  391. return m_onScrollOffsetChanging;
  392. }
  393. ////////////////////////////////////////////////////////////////////////////////////////////////////
  394. void UiScrollBoxComponent::SetScrollOffsetChangingCallback(ScrollOffsetChangeCallback onChange)
  395. {
  396. m_onScrollOffsetChanging = onChange;
  397. }
  398. ////////////////////////////////////////////////////////////////////////////////////////////////////
  399. const LyShine::ActionName& UiScrollBoxComponent::GetScrollOffsetChangingActionName()
  400. {
  401. return m_scrollOffsetChangingActionName;
  402. }
  403. ////////////////////////////////////////////////////////////////////////////////////////////////////
  404. void UiScrollBoxComponent::SetScrollOffsetChangingActionName(const LyShine::ActionName& actionName)
  405. {
  406. m_scrollOffsetChangingActionName = actionName;
  407. }
  408. ////////////////////////////////////////////////////////////////////////////////////////////////////
  409. UiScrollBoxComponent::ScrollOffsetChangeCallback UiScrollBoxComponent::GetScrollOffsetChangedCallback()
  410. {
  411. return m_onScrollOffsetChanged;
  412. }
  413. ////////////////////////////////////////////////////////////////////////////////////////////////////
  414. void UiScrollBoxComponent::SetScrollOffsetChangedCallback(ScrollOffsetChangeCallback onChange)
  415. {
  416. m_onScrollOffsetChanged = onChange;
  417. }
  418. ////////////////////////////////////////////////////////////////////////////////////////////////////
  419. const LyShine::ActionName& UiScrollBoxComponent::GetScrollOffsetChangedActionName()
  420. {
  421. return m_scrollOffsetChangedActionName;
  422. }
  423. ////////////////////////////////////////////////////////////////////////////////////////////////////
  424. void UiScrollBoxComponent::SetScrollOffsetChangedActionName(const LyShine::ActionName& actionName)
  425. {
  426. m_scrollOffsetChangedActionName = actionName;
  427. }
  428. ////////////////////////////////////////////////////////////////////////////////////////////////////
  429. void UiScrollBoxComponent::SetContentEntity(AZ::EntityId entityId)
  430. {
  431. m_contentEntity = entityId;
  432. }
  433. ////////////////////////////////////////////////////////////////////////////////////////////////////
  434. AZ::EntityId UiScrollBoxComponent::GetContentEntity()
  435. {
  436. return m_contentEntity;
  437. }
  438. ////////////////////////////////////////////////////////////////////////////////////////////////////
  439. void UiScrollBoxComponent::SetHorizontalScrollBarEntity(AZ::EntityId entityId)
  440. {
  441. m_hScrollBarEntity = entityId;
  442. }
  443. ////////////////////////////////////////////////////////////////////////////////////////////////////
  444. AZ::EntityId UiScrollBoxComponent::GetHorizontalScrollBarEntity()
  445. {
  446. return m_hScrollBarEntity;
  447. }
  448. ////////////////////////////////////////////////////////////////////////////////////////////////////
  449. void UiScrollBoxComponent::SetVerticalScrollBarEntity(AZ::EntityId entityId)
  450. {
  451. m_vScrollBarEntity = entityId;
  452. }
  453. ////////////////////////////////////////////////////////////////////////////////////////////////////
  454. AZ::EntityId UiScrollBoxComponent::GetVerticalScrollBarEntity()
  455. {
  456. return m_vScrollBarEntity;
  457. }
  458. ////////////////////////////////////////////////////////////////////////////////////////////////////
  459. AZ::EntityId UiScrollBoxComponent::FindClosestContentChildElement()
  460. {
  461. // if no content entity return an invalid entity id
  462. if (!m_contentEntity.IsValid())
  463. {
  464. return AZ::EntityId();
  465. }
  466. // Iterate over the children of the content element and find the one that has the smallest
  467. // offset from the content elements anchors to the child's pivot.
  468. // E.g. if the anchors are the center of the content (the default) and the chilren's pivots
  469. // are in their centers (the default) then we will find the child whose center is closest
  470. // to the center of the content element's parent (usually the mask element)
  471. LyShine::EntityArray children;
  472. UiElementBus::EventResult(children, m_contentEntity, &UiElementBus::Events::GetChildElements);
  473. float closestDistSq = FLT_MAX;
  474. AZ::EntityId closestChild;
  475. for (auto child : children)
  476. {
  477. AZ::Vector2 scrollOffsetToChild = ComputeCurrentOffsetToChild(child->GetId());
  478. float distSq = scrollOffsetToChild.GetLengthSq();
  479. if (distSq < closestDistSq)
  480. {
  481. closestChild = child->GetId();
  482. closestDistSq = distSq;
  483. }
  484. }
  485. return closestChild;
  486. }
  487. ////////////////////////////////////////////////////////////////////////////////////////////////////
  488. AZ::EntityId UiScrollBoxComponent::FindNextContentChildElement(UiNavigationHelpers::Command command)
  489. {
  490. // if no content entity return an invalid entity id
  491. if (!m_contentEntity.IsValid())
  492. {
  493. return AZ::EntityId();
  494. }
  495. // Iterate over the children of the content element and find the one who's pivot is closest to
  496. // the content element's anchors in the specified direction.
  497. LyShine::EntityArray children;
  498. UiElementBus::EventResult(children, m_contentEntity, &UiElementBus::Events::GetChildElements);
  499. float shortestDist = FLT_MAX;
  500. float shortestPerpendicularDist = FLT_MAX;
  501. AZ::EntityId closestChild;
  502. for (auto child : children)
  503. {
  504. AZ::Vector2 scrollOffsetToChild = ComputeCurrentOffsetToChild(child->GetId());
  505. float dist = 0.0f;
  506. const float epsilon = 0.01f;
  507. if (command == UiNavigationHelpers::Command::Up)
  508. {
  509. dist = scrollOffsetToChild.GetY() < -epsilon ? -scrollOffsetToChild.GetY() : 0.0f;
  510. }
  511. else if (command == UiNavigationHelpers::Command::Down)
  512. {
  513. dist = scrollOffsetToChild.GetY() > epsilon ? scrollOffsetToChild.GetY() : 0.0f;
  514. }
  515. else if (command == UiNavigationHelpers::Command::Left)
  516. {
  517. dist = scrollOffsetToChild.GetX() < -epsilon ? -scrollOffsetToChild.GetX() : 0.0f;
  518. }
  519. else if (command == UiNavigationHelpers::Command::Right)
  520. {
  521. dist = scrollOffsetToChild.GetX() > epsilon ? scrollOffsetToChild.GetX() : 0.0f;
  522. }
  523. if (dist > 0.0f)
  524. {
  525. if (dist < shortestDist)
  526. {
  527. shortestDist = dist;
  528. shortestPerpendicularDist = fabs((command == UiNavigationHelpers::Command::Up || command == UiNavigationHelpers::Command::Down) ? scrollOffsetToChild.GetX() : scrollOffsetToChild.GetY());
  529. closestChild = child->GetId();
  530. }
  531. else if (dist == shortestDist)
  532. {
  533. float perpDist = fabs((command == UiNavigationHelpers::Command::Up || command == UiNavigationHelpers::Command::Down) ? scrollOffsetToChild.GetX() : scrollOffsetToChild.GetY());
  534. if (perpDist < shortestPerpendicularDist)
  535. {
  536. shortestPerpendicularDist = perpDist;
  537. closestChild = child->GetId();
  538. }
  539. }
  540. }
  541. }
  542. return closestChild;
  543. }
  544. ////////////////////////////////////////////////////////////////////////////////////////////////////
  545. bool UiScrollBoxComponent::GetScrollableParentToContentRatio(AZ::Vector2& ratioOut)
  546. {
  547. AZ::Entity* contentParentEntity = nullptr;
  548. UiElementBus::EventResult(contentParentEntity, m_contentEntity, &UiElementBus::Events::GetParent);
  549. if (contentParentEntity)
  550. {
  551. AZ::Vector2 parentSize;
  552. UiTransformBus::EventResult(parentSize, contentParentEntity->GetId(), &UiTransformBus::Events::GetCanvasSpaceSizeNoScaleRotate);
  553. UiTransformInterface::Rect contentRect = GetAxisAlignedContentRect();
  554. AZ::Vector2 contentSize = contentRect.GetSize();
  555. ratioOut.SetX(contentSize.GetX() != 0.0f ? parentSize.GetX() / contentSize.GetX() : 1.0f);
  556. ratioOut.SetY(contentSize.GetY() != 0.0f ? parentSize.GetY() / contentSize.GetY() : 1.0f);
  557. return true;
  558. }
  559. return false;
  560. }
  561. ////////////////////////////////////////////////////////////////////////////////////////////////////
  562. void UiScrollBoxComponent::OnValueChangingByScroller(float value)
  563. {
  564. AZ::EntityId scroller = *UiScrollerToScrollableNotificationBus::GetCurrentBusId();
  565. AZ::Vector2 newScrollOffsetOut;
  566. bool result = ScrollerValueToScrollOffsets(scroller, value, newScrollOffsetOut);
  567. if (result && m_scrollOffset != newScrollOffsetOut)
  568. {
  569. DoSetScrollOffset(newScrollOffsetOut);
  570. DoChangingActions();
  571. }
  572. }
  573. ////////////////////////////////////////////////////////////////////////////////////////////////////
  574. void UiScrollBoxComponent::OnValueChangedByScroller(float value)
  575. {
  576. AZ::EntityId scroller = *UiScrollerToScrollableNotificationBus::GetCurrentBusId();
  577. AZ::Vector2 newScrollOffsetOut;
  578. bool result = ScrollerValueToScrollOffsets(scroller, value, newScrollOffsetOut);
  579. if (result)
  580. {
  581. AZ::Vector2 prevScrollOffset = m_scrollOffset;
  582. if (m_scrollOffset != newScrollOffsetOut)
  583. {
  584. DoSetScrollOffset(newScrollOffsetOut);
  585. }
  586. if (DoSnap())
  587. {
  588. // Snapping/constraining caused the scroll offsets to change, so notify scrollers
  589. NotifyScrollersOnValueChanged();
  590. }
  591. if (m_scrollOffset != prevScrollOffset)
  592. {
  593. DoChangedActions();
  594. }
  595. }
  596. }
  597. ////////////////////////////////////////////////////////////////////////////////////////////////////
  598. void UiScrollBoxComponent::InGamePostActivate()
  599. {
  600. if (m_hScrollBarEntity.IsValid() && m_isHorizontalScrollingEnabled)
  601. {
  602. // Set this entity as the scrollable entity of the scroller
  603. UiScrollerBus::Event(m_hScrollBarEntity, &UiScrollerBus::Events::SetScrollableEntity, GetEntityId());
  604. UiScrollerToScrollableNotificationBus::MultiHandler::BusConnect(m_hScrollBarEntity);
  605. }
  606. if (m_vScrollBarEntity.IsValid() && m_isVerticalScrollingEnabled)
  607. {
  608. // Set this entity as the scrollable entity of the scroller
  609. UiScrollerBus::Event(m_vScrollBarEntity, &UiScrollerBus::Events::SetScrollableEntity, GetEntityId());
  610. UiScrollerToScrollableNotificationBus::MultiHandler::BusConnect(m_vScrollBarEntity);
  611. }
  612. DoSetScrollOffset(m_scrollOffset);
  613. // Setup based on the size of the content and its parent
  614. ContentOrParentSizeChanged();
  615. // Listen for canvas space rect changes from the content entity
  616. if (m_contentEntity.IsValid())
  617. {
  618. UiTransformChangeNotificationBus::MultiHandler::BusConnect(m_contentEntity);
  619. // Listen for canvas space rect changes from the content entity's parent
  620. AZ::Entity* contentParentEntity = nullptr;
  621. UiElementBus::EventResult(contentParentEntity, m_contentEntity, &UiElementBus::Events::GetParent);
  622. if (contentParentEntity)
  623. {
  624. UiTransformChangeNotificationBus::MultiHandler::BusConnect(contentParentEntity->GetId());
  625. }
  626. }
  627. }
  628. ////////////////////////////////////////////////////////////////////////////////////////////////////
  629. bool UiScrollBoxComponent::HandlePressed(AZ::Vector2 point, bool& shouldStayActive)
  630. {
  631. bool handled = UiInteractableComponent::HandlePressed(point, shouldStayActive);
  632. if (handled)
  633. {
  634. // clear the dragging flag, we are not dragging until we detect a drag
  635. m_isDragging = false;
  636. // record the scroll offset at the time of the press
  637. m_pressedScrollOffset = m_scrollOffset;
  638. }
  639. // Stop momentum if the user pressed the screen, when handled directly
  640. SetMomentumActive(false);
  641. return handled;
  642. }
  643. ////////////////////////////////////////////////////////////////////////////////////////////////////
  644. bool UiScrollBoxComponent::HandleReleased([[maybe_unused]] AZ::Vector2 point)
  645. {
  646. if (m_isHandlingEvents)
  647. {
  648. // handle snapping
  649. DoSnap();
  650. UiInteractableComponent::TriggerReleasedAction();
  651. NotifyScrollersOnValueChanged();
  652. // NOTE: when we have inertia/rubber-banding these actions should occur when snap is finished
  653. DoChangedActions();
  654. }
  655. m_isPressed = false;
  656. m_isDragging = false;
  657. //Start momentum if released the screen
  658. SetMomentumActive(true);
  659. return m_isHandlingEvents;
  660. }
  661. /////////////////////////////////////////////////////////////////
  662. bool UiScrollBoxComponent::HandleEnterPressed(bool& shouldStayActive)
  663. {
  664. bool handled = UiInteractableComponent::HandleEnterPressed(shouldStayActive);
  665. if (handled)
  666. {
  667. // the scrollbox will stay active after released
  668. shouldStayActive = true;
  669. m_isActive = true;
  670. }
  671. return handled;
  672. }
  673. /////////////////////////////////////////////////////////////////
  674. bool UiScrollBoxComponent::HandleAutoActivation()
  675. {
  676. if (!m_isHandlingEvents)
  677. {
  678. return false;
  679. }
  680. m_isActive = true;
  681. return true;
  682. }
  683. /////////////////////////////////////////////////////////////////
  684. bool UiScrollBoxComponent::HandleKeyInputBegan(const AzFramework::InputChannel::Snapshot& inputSnapshot, AzFramework::ModifierKeyMask activeModifierKeys)
  685. {
  686. if (!m_isHandlingEvents)
  687. {
  688. return false;
  689. }
  690. // don't accept key input while in pressed state
  691. if (m_isPressed)
  692. {
  693. return false;
  694. }
  695. bool result = false;
  696. const UiNavigationHelpers::Command command = UiNavigationHelpers::MapInputChannelIdToUiNavigationCommand(inputSnapshot.m_channelId, activeModifierKeys);
  697. if (m_isHorizontalScrollingEnabled && ((command == UiNavigationHelpers::Command::Left || command == UiNavigationHelpers::Command::Right))
  698. || (m_isVerticalScrollingEnabled && (command == UiNavigationHelpers::Command::Up || command == UiNavigationHelpers::Command::Down)))
  699. {
  700. AZ::Vector2 newScrollOffset = m_scrollOffset;
  701. if (m_snapMode == UiScrollBoxInterface::SnapMode::Children)
  702. {
  703. AZ::EntityId closestChild = FindNextContentChildElement(command);
  704. if (closestChild.IsValid())
  705. {
  706. // want elastic animation eventually
  707. AZ::Vector2 deltaToSubtract = ComputeCurrentOffsetToChild(closestChild);
  708. // snapping should only move the content in the directions it is allowed to scroll
  709. if (!m_isHorizontalScrollingEnabled)
  710. {
  711. deltaToSubtract.SetX(0.0f);
  712. }
  713. else if (!m_isVerticalScrollingEnabled)
  714. {
  715. deltaToSubtract.SetY(0.0f);
  716. }
  717. newScrollOffset -= deltaToSubtract;
  718. // do constraining
  719. if (m_isScrollingConstrained)
  720. {
  721. AZ::Entity* contentParentEntity = nullptr;
  722. UiElementBus::EventResult(contentParentEntity, m_contentEntity, &UiElementBus::Events::GetParent);
  723. newScrollOffset = ConstrainOffset(newScrollOffset, contentParentEntity);
  724. }
  725. }
  726. }
  727. else if (m_snapMode == UiScrollBoxInterface::SnapMode::Grid)
  728. {
  729. if (command == UiNavigationHelpers::Command::Up)
  730. {
  731. newScrollOffset.SetY(newScrollOffset.GetY() + m_snapGrid.GetY());
  732. }
  733. else if (command == UiNavigationHelpers::Command::Down)
  734. {
  735. newScrollOffset.SetY(newScrollOffset.GetY() - m_snapGrid.GetY());
  736. }
  737. else if (command == UiNavigationHelpers::Command::Left)
  738. {
  739. newScrollOffset.SetX(newScrollOffset.GetX() + m_snapGrid.GetX());
  740. }
  741. else if (command == UiNavigationHelpers::Command::Right)
  742. {
  743. newScrollOffset.SetX(newScrollOffset.GetX() - m_snapGrid.GetX());
  744. }
  745. if (m_isScrollingConstrained)
  746. {
  747. AZ::Entity* contentParentEntity = nullptr;
  748. UiElementBus::EventResult(contentParentEntity, m_contentEntity, &UiElementBus::Events::GetParent);
  749. // Only scroll if constraining doesn't change the offset
  750. AZ::Vector2 constrainedScrollOffset = ConstrainOffset(newScrollOffset, contentParentEntity);
  751. if (constrainedScrollOffset != newScrollOffset)
  752. {
  753. newScrollOffset = m_scrollOffset;
  754. }
  755. }
  756. }
  757. else
  758. {
  759. // get content parent's rect in canvas space
  760. AZ::Entity* contentParentEntity = nullptr;
  761. UiElementBus::EventResult(contentParentEntity, m_contentEntity, &UiElementBus::Events::GetParent);
  762. if (contentParentEntity)
  763. {
  764. UiTransformInterface::Rect parentRect;
  765. UiTransformBus::Event(contentParentEntity->GetId(), &UiTransformBus::Events::GetCanvasSpaceRectNoScaleRotate, parentRect);
  766. const float keySteps = 10.0f;
  767. if (command == UiNavigationHelpers::Command::Left || command == UiNavigationHelpers::Command::Right)
  768. {
  769. float xStep = parentRect.GetSize().GetX() / keySteps;
  770. newScrollOffset.SetX(newScrollOffset.GetX() + (command == UiNavigationHelpers::Command::Left ? xStep : -xStep));
  771. }
  772. else
  773. {
  774. float yStep = parentRect.GetSize().GetY() / keySteps;
  775. newScrollOffset.SetY(newScrollOffset.GetY() + (command == UiNavigationHelpers::Command::Up ? yStep : -yStep));
  776. }
  777. // do constraining
  778. if (m_isScrollingConstrained)
  779. {
  780. newScrollOffset = ConstrainOffset(newScrollOffset, contentParentEntity);
  781. }
  782. }
  783. }
  784. if (newScrollOffset != m_scrollOffset)
  785. {
  786. DoSetScrollOffset(newScrollOffset);
  787. NotifyScrollersOnValueChanged();
  788. DoChangingActions();
  789. DoChangedActions();
  790. }
  791. result = true;
  792. }
  793. return result;
  794. }
  795. /////////////////////////////////////////////////////////////////
  796. void UiScrollBoxComponent::InputPositionUpdate(AZ::Vector2 point)
  797. {
  798. if (m_isPressed && m_contentEntity.IsValid())
  799. {
  800. m_lastOffsetChange = AZ::Vector2(0.0f, 0.0f);
  801. if (!m_isDragging)
  802. {
  803. CheckForDragOrHandOffToParent(point);
  804. }
  805. if (m_isDragging)
  806. {
  807. AZ::Vector2 dragVector = point - m_pressedPoint;
  808. dragVector *= m_scrollSensitivity;
  809. AZ::Entity* contentParentEntity = nullptr;
  810. UiElementBus::EventResult(contentParentEntity, m_contentEntity, &UiElementBus::Events::GetParent);
  811. AZ::Matrix4x4 transform;
  812. if (contentParentEntity)
  813. {
  814. UiTransformBus::Event(contentParentEntity->GetId(), &UiTransformBus::Events::GetTransformFromViewport, transform);
  815. }
  816. else
  817. {
  818. transform = AZ::Matrix4x4::CreateIdentity();
  819. }
  820. // Transform the draw vector from viewport space to the local space of the parent of the content element
  821. // This means we can do all calculations in unrotated/unscaled space.
  822. AZ::Vector3 dragVector3(dragVector.GetX(), dragVector.GetY(), 0.0f);
  823. dragVector3 = transform.Multiply3x3(dragVector3);
  824. AZ::Vector2 dragVectorInParentSpace(dragVector3.GetX(), dragVector3.GetY());
  825. if (!m_isHorizontalScrollingEnabled)
  826. {
  827. dragVectorInParentSpace.SetX(0.0f);
  828. }
  829. if (!m_isVerticalScrollingEnabled)
  830. {
  831. dragVectorInParentSpace.SetY(0.0f);
  832. }
  833. AZ::Vector2 newScrollOffset = m_pressedScrollOffset + dragVectorInParentSpace;
  834. // do constraining
  835. if (m_isScrollingConstrained)
  836. {
  837. newScrollOffset = ConstrainOffset(newScrollOffset, contentParentEntity);
  838. }
  839. m_lastDragPoint = point;
  840. if (newScrollOffset != m_scrollOffset)
  841. {
  842. m_lastOffsetChange = newScrollOffset - m_scrollOffset;
  843. m_offsetChangeAccumulator += m_lastOffsetChange;
  844. DoSetScrollOffset(newScrollOffset);
  845. NotifyScrollersOnValueChanging();
  846. DoChangingActions();
  847. }
  848. //Reset offset and time accumulators if change scrolling direction
  849. if (m_lastOffsetChange.Dot(m_offsetChangeAccumulator) < 0.0f)
  850. {
  851. SetMomentumActive(false);
  852. }
  853. }
  854. }
  855. }
  856. /////////////////////////////////////////////////////////////////
  857. bool UiScrollBoxComponent::DoesSupportDragHandOff(AZ::Vector2 startPoint)
  858. {
  859. // this component does support hand-off, so long as the start point is in its bounds
  860. bool isPointInRect = false;
  861. UiTransformBus::EventResult(isPointInRect, GetEntityId(), &UiTransformBus::Events::IsPointInRect, startPoint);
  862. return isPointInRect;
  863. }
  864. /////////////////////////////////////////////////////////////////
  865. bool UiScrollBoxComponent::OfferDragHandOff(AZ::EntityId currentActiveInteractable, AZ::Vector2 startPoint, AZ::Vector2 currentPoint, float dragThreshold)
  866. {
  867. bool result = false;
  868. // This only gets called if this is not already the active interactable, check preconditions
  869. AZ_Assert(!m_isPressed && !m_isDragging, "ScrollBox is already active");
  870. // get transform of content entity
  871. AZ::Entity* contentParentEntity = nullptr;
  872. UiElementBus::EventResult(contentParentEntity, m_contentEntity, &UiElementBus::Events::GetParent);
  873. AZ::Matrix4x4 transform;
  874. if (contentParentEntity)
  875. {
  876. UiTransformBus::Event(contentParentEntity->GetId(), &UiTransformBus::Events::GetTransformFromViewport, transform);
  877. }
  878. else
  879. {
  880. transform = AZ::Matrix4x4::CreateIdentity();
  881. }
  882. float validDragDistance = GetValidDragDistanceInPixels(startPoint, currentPoint);
  883. if (validDragDistance > dragThreshold)
  884. {
  885. // share this common code?
  886. m_isDragging = true;
  887. m_isPressed = true;
  888. m_pressedPoint = startPoint;
  889. m_pressedScrollOffset = m_scrollOffset;
  890. m_lastDragPoint = m_pressedPoint;
  891. // Stop momentum if the user pressed the screen, when handled indirectly
  892. SetMomentumActive(false);
  893. // tell the canvas that this is now the active interacatable
  894. UiInteractableActiveNotificationBus::Event(
  895. currentActiveInteractable, &UiInteractableActiveNotificationBus::Events::ActiveChanged, GetEntityId(), false);
  896. result = true;
  897. }
  898. else
  899. {
  900. // The current drag movement is not over the threshhold to be dragging this interactable
  901. // look for a parent interactable that the start point of the drag is inside
  902. AZ::EntityId interactableContainer;
  903. UiElementBus::EventResult(
  904. interactableContainer, GetEntityId(), &UiElementBus::Events::FindParentInteractableSupportingDrag, startPoint);
  905. // if there was a parent interactable offer them the opportunity to become the active interactable
  906. UiInteractableBus::EventResult(
  907. result,
  908. interactableContainer,
  909. &UiInteractableBus::Events::OfferDragHandOff,
  910. currentActiveInteractable,
  911. startPoint,
  912. currentPoint,
  913. dragThreshold);
  914. }
  915. return result;
  916. }
  917. ////////////////////////////////////////////////////////////////////////////////////////////////////
  918. void UiScrollBoxComponent::LostActiveStatus()
  919. {
  920. UiInteractableComponent::LostActiveStatus();
  921. if (m_isDragging)
  922. {
  923. if (m_isHandlingEvents)
  924. {
  925. // handle snapping
  926. DoSnap();
  927. NotifyScrollersOnValueChanged();
  928. // NOTE: when we have inertia/rubber-banding these actions should occur when snap is finished
  929. DoChangedActions();
  930. }
  931. m_isDragging = false;
  932. }
  933. m_isActive = false;
  934. }
  935. ////////////////////////////////////////////////////////////////////////////////////////////////////
  936. void UiScrollBoxComponent::HandleDescendantReceivedHoverByNavigation(AZ::EntityId descendantEntityId)
  937. {
  938. // Check if the content element is an ancestor of the descendant element
  939. bool isAncestor = false;
  940. if (m_contentEntity.IsValid())
  941. {
  942. UiElementBus::EventResult(isAncestor, descendantEntityId, &UiElementBus::Events::IsAncestor, m_contentEntity);
  943. }
  944. if (isAncestor)
  945. {
  946. AZ::Vector2 newScrollOffset = m_scrollOffset;
  947. if (m_snapMode == UiScrollBoxInterface::SnapMode::Children)
  948. {
  949. // Find the descendant's ancestor that's a direct child of the content entity
  950. AZ::EntityId parent;
  951. UiElementBus::EventResult(parent, descendantEntityId, &UiElementBus::Events::GetParentEntityId);
  952. while (parent.IsValid())
  953. {
  954. if (parent == m_contentEntity)
  955. {
  956. break;
  957. }
  958. descendantEntityId = parent;
  959. parent.SetInvalid();
  960. UiElementBus::EventResult(parent, descendantEntityId, &UiElementBus::Events::GetParentEntityId);
  961. }
  962. if (descendantEntityId.IsValid())
  963. {
  964. AZ::Vector2 offset = ComputeCurrentOffsetToChild(descendantEntityId);
  965. if (!m_isHorizontalScrollingEnabled)
  966. {
  967. offset.SetX(0.0f);
  968. }
  969. if (!m_isVerticalScrollingEnabled)
  970. {
  971. offset.SetY(0.0f);
  972. }
  973. newScrollOffset = m_scrollOffset - offset;
  974. }
  975. }
  976. else
  977. {
  978. // Check if the descendant element is visible in the viewport area
  979. AZ::EntityId contentParent;
  980. UiElementBus::EventResult(contentParent, m_contentEntity, &UiElementBus::Events::GetParentEntityId);
  981. if (contentParent.IsValid())
  982. {
  983. UiTransformInterface::Rect contentParentRect;
  984. AZ::Matrix4x4 transformFromViewport;
  985. UiTransformBus::Event(contentParent, &UiTransformBus::Events::GetCanvasSpaceRectNoScaleRotate, contentParentRect);
  986. UiTransformBus::Event(contentParent, &UiTransformBus::Events::GetTransformFromViewport, transformFromViewport);
  987. UiTransformInterface::RectPoints descendantPoints;
  988. UiTransformBus::Event(descendantEntityId, &UiTransformBus::Events::GetViewportSpacePoints, descendantPoints);
  989. descendantPoints = descendantPoints.Transform(transformFromViewport);
  990. UiTransformInterface::Rect descendantRect;
  991. descendantRect.left = descendantPoints.GetAxisAlignedTopLeft().GetX();
  992. descendantRect.right = descendantPoints.GetAxisAlignedBottomRight().GetX();
  993. descendantRect.top = descendantPoints.GetAxisAlignedTopLeft().GetY();
  994. descendantRect.bottom = descendantPoints.GetAxisAlignedBottomRight().GetY();
  995. bool descendantInsideH = (descendantRect.left >= contentParentRect.left &&
  996. descendantRect.right <= contentParentRect.right);
  997. bool descendantInsideV = (descendantRect.top >= contentParentRect.top &&
  998. descendantRect.bottom <= contentParentRect.bottom);
  999. if (!descendantInsideH || !descendantInsideV)
  1000. {
  1001. AZ::Vector2 offset(0.0f, 0.0f);
  1002. // Scroll to make the descendant visible in the viewport area
  1003. if (!descendantInsideH && m_isHorizontalScrollingEnabled)
  1004. {
  1005. float leftOffset = descendantRect.left - contentParentRect.left;
  1006. float rightOffset = descendantRect.right - contentParentRect.right;
  1007. bool shouldOffsetFromLeft = fabs(leftOffset) < fabs(rightOffset);
  1008. offset.SetX(shouldOffsetFromLeft ? leftOffset : rightOffset);
  1009. }
  1010. if (!descendantInsideV && m_isVerticalScrollingEnabled)
  1011. {
  1012. float topOffset = descendantRect.top - contentParentRect.top;
  1013. float bottomOffset = descendantRect.bottom - contentParentRect.bottom;
  1014. bool shouldOffsetFromTop = fabs(topOffset) < fabs(bottomOffset);
  1015. offset.SetY(shouldOffsetFromTop ? topOffset : bottomOffset);
  1016. }
  1017. newScrollOffset = m_scrollOffset - offset;
  1018. if (m_snapMode == UiScrollBoxInterface::SnapMode::Grid)
  1019. {
  1020. // Make sure new offset is on the grid
  1021. const float gridEpsilon = 0.00001f;
  1022. if (m_snapGrid.GetX() >= gridEpsilon && m_isHorizontalScrollingEnabled)
  1023. {
  1024. float gridSteps = newScrollOffset.GetX() / m_snapGrid.GetX();
  1025. float roundedGridSteps = (offset.GetX() < 0.0f) ? ceil(gridSteps) : floor(gridSteps);
  1026. newScrollOffset.SetX(roundedGridSteps * m_snapGrid.GetX());
  1027. }
  1028. if (m_snapGrid.GetY() >= gridEpsilon && m_isVerticalScrollingEnabled)
  1029. {
  1030. float gridSteps = newScrollOffset.GetY() / m_snapGrid.GetY();
  1031. float roundedGridSteps = (offset.GetY() < 0.0f) ? ceil(gridSteps) : floor(gridSteps);
  1032. newScrollOffset.SetY(roundedGridSteps * m_snapGrid.GetY());
  1033. }
  1034. }
  1035. }
  1036. }
  1037. }
  1038. if (newScrollOffset != m_scrollOffset)
  1039. {
  1040. SetScrollOffset(newScrollOffset);
  1041. }
  1042. }
  1043. }
  1044. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1045. void UiScrollBoxComponent::OnCanvasSpaceRectChanged([[maybe_unused]] AZ::EntityId entityId, const UiTransformInterface::Rect& oldRect, const UiTransformInterface::Rect& newRect)
  1046. {
  1047. // If old rect equals new rect, size changed due to initialization
  1048. bool sizeChanged = (oldRect == newRect) || (!oldRect.GetSize().IsClose(newRect.GetSize(), 0.05f));
  1049. if (sizeChanged)
  1050. {
  1051. ContentOrParentSizeChanged();
  1052. }
  1053. }
  1054. void UiScrollBoxComponent::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time)
  1055. {
  1056. if (!m_momentumIsActive && m_isDragging)
  1057. {
  1058. m_draggingTimeAccumulator += deltaTime;
  1059. // Detect if stopped by checking if immediate offset change falls below threshold
  1060. if ((m_lastOffsetChange / m_scrollSensitivity).GetLength() < MIN_OFFSET_THRESHOLD)
  1061. {
  1062. m_stoppingTimeAccumulator += deltaTime;
  1063. }
  1064. else
  1065. {
  1066. m_stoppingTimeAccumulator = 0.0f;
  1067. }
  1068. }
  1069. // Stop momentum if off or already ran the full momentum duration
  1070. if (!m_momentumIsActive ||
  1071. m_momentumDuration < m_momentumTimeAccumulator)
  1072. {
  1073. return;
  1074. }
  1075. // Stop momentum if no dragging accumulator, or not enough drag, or if stopped for long enough
  1076. if (m_draggingTimeAccumulator == 0.0f ||
  1077. (m_offsetChangeAccumulator / m_scrollSensitivity).GetLength() < MIN_OFFSET_THRESHOLD ||
  1078. m_stoppingTimeAccumulator > MAX_STOPPING_DELAY)
  1079. {
  1080. return;
  1081. }
  1082. m_momentumTimeAccumulator += deltaTime;
  1083. float momentumRatio = AZ::GetClamp(m_momentumTimeAccumulator / m_momentumDuration, 0.0f, 1.0f);
  1084. float momentumEasing = 1.0f + (momentumRatio - 1.0f) * (momentumRatio - 1.0f) * (momentumRatio - 1.0f); // Ease Out Cubic decrease
  1085. // m_offsetChangeAccumulator is the aggregated unidirectional scrolling, inverse easing for deceleration
  1086. AZ::Vector2 momentumOffsetChange = m_offsetChangeAccumulator * ( deltaTime / m_draggingTimeAccumulator) * (1.0f - momentumEasing);
  1087. AZ::Vector2 newScrollOffset = m_scrollOffset + momentumOffsetChange;
  1088. // do constraining
  1089. if (m_isScrollingConstrained)
  1090. {
  1091. AZ::Entity* contentParentEntity = nullptr;
  1092. EBUS_EVENT_ID_RESULT(contentParentEntity, m_contentEntity, UiElementBus, GetParent);
  1093. newScrollOffset = ConstrainOffset(newScrollOffset, contentParentEntity);
  1094. }
  1095. if (newScrollOffset != m_scrollOffset)
  1096. {
  1097. DoSetScrollOffset(newScrollOffset);
  1098. NotifyScrollersOnValueChanging();
  1099. DoChangingActions();
  1100. }
  1101. }
  1102. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1103. // PROTECTED MEMBER FUNCTIONS
  1104. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1105. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1106. void UiScrollBoxComponent::Activate()
  1107. {
  1108. UiInteractableComponent::Activate();
  1109. UiScrollBoxBus::Handler::BusConnect(GetEntityId());
  1110. UiScrollableBus::Handler::BusConnect(GetEntityId());
  1111. UiInitializationBus::Handler::BusConnect(GetEntityId());
  1112. }
  1113. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1114. void UiScrollBoxComponent::Deactivate()
  1115. {
  1116. UiInteractableComponent::Deactivate();
  1117. UiScrollBoxBus::Handler::BusDisconnect(GetEntityId());
  1118. UiScrollableBus::Handler::BusDisconnect(GetEntityId());
  1119. UiInitializationBus::Handler::BusDisconnect(GetEntityId());
  1120. UiTransformChangeNotificationBus::MultiHandler::BusDisconnect();
  1121. if (m_hScrollBarEntity.IsValid() && m_isHorizontalScrollingEnabled)
  1122. {
  1123. UiScrollerToScrollableNotificationBus::MultiHandler::BusDisconnect(m_hScrollBarEntity);
  1124. }
  1125. if (m_vScrollBarEntity.IsValid() && m_isVerticalScrollingEnabled)
  1126. {
  1127. UiScrollerToScrollableNotificationBus::MultiHandler::BusDisconnect(m_vScrollBarEntity);
  1128. }
  1129. }
  1130. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1131. bool UiScrollBoxComponent::IsAutoActivationSupported()
  1132. {
  1133. return true;
  1134. }
  1135. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1136. UiInteractableStatesInterface::State UiScrollBoxComponent::ComputeInteractableState()
  1137. {
  1138. UiInteractableStatesInterface::State state = UiInteractableStatesInterface::StateNormal;
  1139. if (!m_isHandlingEvents)
  1140. {
  1141. state = UiInteractableStatesInterface::StateDisabled;
  1142. }
  1143. else if (m_isPressed || m_isActive)
  1144. {
  1145. // Use pressed state regardless of mouse position
  1146. state = UiInteractableStatesInterface::StatePressed;
  1147. }
  1148. else if (m_isHover)
  1149. {
  1150. state = UiInteractableStatesInterface::StateHover;
  1151. }
  1152. return state;
  1153. }
  1154. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1155. // PROTECTED STATIC MEMBER FUNCTIONS
  1156. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1157. void UiScrollBoxComponent::Reflect(AZ::ReflectContext* context)
  1158. {
  1159. AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
  1160. if (serializeContext)
  1161. {
  1162. serializeContext->Class<UiScrollBoxComponent, UiInteractableComponent>()
  1163. ->Version(4, &VersionConverter)
  1164. // Content group
  1165. ->Field("ContentEntity", &UiScrollBoxComponent::m_contentEntity)
  1166. ->Field("ScrollOffset", &UiScrollBoxComponent::m_scrollOffset)
  1167. ->Field("ConstrainScrolling", &UiScrollBoxComponent::m_isScrollingConstrained)
  1168. ->Field("SnapMode", &UiScrollBoxComponent::m_snapMode)
  1169. ->Field("SnapGrid", &UiScrollBoxComponent::m_snapGrid)
  1170. // Horizontal scrolling group
  1171. ->Field("AllowHorizSrolling", &UiScrollBoxComponent::m_isHorizontalScrollingEnabled)
  1172. ->Field("HScrollBarEntity", &UiScrollBoxComponent::m_hScrollBarEntity)
  1173. ->Field("HScrollBarVisibility", &UiScrollBoxComponent::m_hScrollBarVisibility)
  1174. // Vertical scrolling group
  1175. ->Field("AllowVertScrolling", &UiScrollBoxComponent::m_isVerticalScrollingEnabled)
  1176. ->Field("VScrollBarEntity", &UiScrollBoxComponent::m_vScrollBarEntity)
  1177. ->Field("VScrollBarVisibility", &UiScrollBoxComponent::m_vScrollBarVisibility)
  1178. // Actions group
  1179. ->Field("ScrollOffsetChangingActionName", &UiScrollBoxComponent::m_scrollOffsetChangingActionName)
  1180. ->Field("ScrollOffsetChangedActionName", &UiScrollBoxComponent::m_scrollOffsetChangedActionName);
  1181. AZ::EditContext* ec = serializeContext->GetEditContext();
  1182. if (ec)
  1183. {
  1184. auto editInfo = ec->Class<UiScrollBoxComponent>("ScrollBox", "An interactable component for scrolling a child element.");
  1185. editInfo->ClassElement(AZ::Edit::ClassElements::EditorData, "")
  1186. ->Attribute(AZ::Edit::Attributes::Category, "UI")
  1187. ->Attribute(AZ::Edit::Attributes::Icon, "Editor/Icons/Components/UiScrollBox.png")
  1188. ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Editor/Icons/Components/Viewport/UiScrollBox.png")
  1189. ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("UI", 0x27ff46b0))
  1190. ->Attribute(AZ::Edit::Attributes::AutoExpand, true);
  1191. // Content group
  1192. {
  1193. editInfo->ClassElement(AZ::Edit::ClassElements::Group, "Content")
  1194. ->Attribute(AZ::Edit::Attributes::AutoExpand, true);
  1195. editInfo->DataElement(AZ::Edit::UIHandlers::ComboBox, &UiScrollBoxComponent::m_contentEntity, "Content element", "The child element that is the scrollable content.")
  1196. ->Attribute(AZ::Edit::Attributes::EnumValues, &UiScrollBoxComponent::PopulateChildEntityList);
  1197. editInfo->DataElement(0, &UiScrollBoxComponent::m_scrollOffset, "Initial scroll offset", "The initial offset of the scroll box content.")
  1198. ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::Show); // needed because sub-elements are hidden
  1199. editInfo->DataElement(AZ::Edit::UIHandlers::CheckBox, &UiScrollBoxComponent::m_isScrollingConstrained, "Constrain scrolling",
  1200. "Check this box to prevent the content from being scrolled beyond its edges.");
  1201. editInfo->DataElement(AZ::Edit::UIHandlers::ComboBox, &UiScrollBoxComponent::m_snapMode, "Snap",
  1202. "Sets the snapping behavior when the control is released.")
  1203. ->EnumAttribute(UiScrollBoxInterface::SnapMode::None, "None")
  1204. ->EnumAttribute(UiScrollBoxInterface::SnapMode::Children, "To children")
  1205. ->EnumAttribute(UiScrollBoxInterface::SnapMode::Grid, "To grid")
  1206. ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ_CRC("RefreshEntireTree", 0xefbc823c));
  1207. editInfo->DataElement(0, &UiScrollBoxComponent::m_snapGrid, "Grid spacing",
  1208. "The scroll offset will be snapped to multiples of these values.")
  1209. ->Attribute(AZ::Edit::Attributes::Visibility, &UiScrollBoxComponent::IsSnapToGrid);
  1210. }
  1211. // Horizontal scrolling group
  1212. {
  1213. editInfo->ClassElement(AZ::Edit::ClassElements::Group, "Horizontal scrolling")
  1214. ->Attribute(AZ::Edit::Attributes::AutoExpand, true);
  1215. editInfo->DataElement(AZ::Edit::UIHandlers::CheckBox, &UiScrollBoxComponent::m_isHorizontalScrollingEnabled, "Enabled",
  1216. "Check this box to allow the scroll box to be scrolled horizontally.")
  1217. ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ_CRC("RefreshEntireTree", 0xefbc823c));
  1218. editInfo->DataElement(AZ::Edit::UIHandlers::ComboBox, &UiScrollBoxComponent::m_hScrollBarEntity, "Scrollbar element",
  1219. "The element that is the horizontal scrollbar.")
  1220. ->Attribute(AZ::Edit::Attributes::Visibility, &UiScrollBoxComponent::m_isHorizontalScrollingEnabled)
  1221. ->Attribute(AZ::Edit::Attributes::EnumValues, &UiScrollBoxComponent::PopulateHScrollBarEntityList);
  1222. editInfo->DataElement(AZ::Edit::UIHandlers::ComboBox, &UiScrollBoxComponent::m_hScrollBarVisibility, "Scrollbar visibility",
  1223. "Sets visibility behavior of the horizontal scrollbar.")
  1224. ->Attribute(AZ::Edit::Attributes::Visibility, &UiScrollBoxComponent::m_isHorizontalScrollingEnabled)
  1225. ->EnumAttribute(UiScrollBoxInterface::ScrollBarVisibility::AlwaysShow, "Always visible")
  1226. ->EnumAttribute(UiScrollBoxInterface::ScrollBarVisibility::AutoHide, "Auto hide")
  1227. ->EnumAttribute(UiScrollBoxInterface::ScrollBarVisibility::AutoHideAndResizeViewport, "Auto hide and resize view area");
  1228. }
  1229. // Vertical scrolling group
  1230. {
  1231. editInfo->ClassElement(AZ::Edit::ClassElements::Group, "Vertical scrolling")
  1232. ->Attribute(AZ::Edit::Attributes::AutoExpand, true);
  1233. editInfo->DataElement(AZ::Edit::UIHandlers::CheckBox, &UiScrollBoxComponent::m_isVerticalScrollingEnabled, "Enabled",
  1234. "Check this box to allow the scroll box to be scrolled vertically.")
  1235. ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ_CRC("RefreshEntireTree", 0xefbc823c));
  1236. editInfo->DataElement(AZ::Edit::UIHandlers::ComboBox, &UiScrollBoxComponent::m_vScrollBarEntity, "Scrollbar element",
  1237. "The element that is the vertical scrollbar.")
  1238. ->Attribute(AZ::Edit::Attributes::Visibility, &UiScrollBoxComponent::m_isVerticalScrollingEnabled)
  1239. ->Attribute(AZ::Edit::Attributes::EnumValues, &UiScrollBoxComponent::PopulateVScrollBarEntityList);
  1240. editInfo->DataElement(AZ::Edit::UIHandlers::ComboBox, &UiScrollBoxComponent::m_vScrollBarVisibility, "Scrollbar visibility",
  1241. "Sets visibility behavior of the vertical scrollbar.")
  1242. ->Attribute(AZ::Edit::Attributes::Visibility, &UiScrollBoxComponent::m_isVerticalScrollingEnabled)
  1243. ->EnumAttribute(UiScrollBoxInterface::ScrollBarVisibility::AlwaysShow, "Always visible")
  1244. ->EnumAttribute(UiScrollBoxInterface::ScrollBarVisibility::AutoHide, "Auto hide")
  1245. ->EnumAttribute(UiScrollBoxInterface::ScrollBarVisibility::AutoHideAndResizeViewport, "Auto hide and resize view area");
  1246. }
  1247. // Actions group
  1248. {
  1249. editInfo->ClassElement(AZ::Edit::ClassElements::Group, "Actions")
  1250. ->Attribute(AZ::Edit::Attributes::AutoExpand, true);
  1251. editInfo->DataElement(0, &UiScrollBoxComponent::m_scrollOffsetChangingActionName, "Change", "The action triggered while the offset is changing.");
  1252. editInfo->DataElement(0, &UiScrollBoxComponent::m_scrollOffsetChangedActionName, "End change", "The action triggered when the offset is done changing.");
  1253. }
  1254. }
  1255. }
  1256. AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context);
  1257. if (behaviorContext)
  1258. {
  1259. behaviorContext->EBus<UiScrollBoxBus>("UiScrollBoxBus")
  1260. ->Event("GetScrollOffset", &UiScrollBoxBus::Events::GetScrollOffset)
  1261. ->Event("SetScrollOffset", &UiScrollBoxBus::Events::SetScrollOffset)
  1262. ->Event("GetNormalizedScrollValue", &UiScrollBoxBus::Events::GetNormalizedScrollValue)
  1263. ->Event("HasHorizontalContentToScroll", &UiScrollBoxBus::Events::HasHorizontalContentToScroll)
  1264. ->Event("HasVerticalContentToScroll", &UiScrollBoxBus::Events::HasVerticalContentToScroll)
  1265. ->Event("GetIsHorizontalScrollingEnabled", &UiScrollBoxBus::Events::GetIsHorizontalScrollingEnabled)
  1266. ->Event("SetIsHorizontalScrollingEnabled", &UiScrollBoxBus::Events::SetIsHorizontalScrollingEnabled)
  1267. ->Event("GetIsVerticalScrollingEnabled", &UiScrollBoxBus::Events::GetIsVerticalScrollingEnabled)
  1268. ->Event("SetIsVerticalScrollingEnabled", &UiScrollBoxBus::Events::SetIsVerticalScrollingEnabled)
  1269. ->Event("GetIsScrollingConstrained", &UiScrollBoxBus::Events::GetIsScrollingConstrained)
  1270. ->Event("SetIsScrollingConstrained", &UiScrollBoxBus::Events::SetIsScrollingConstrained)
  1271. ->Event("GetSnapMode", &UiScrollBoxBus::Events::GetSnapMode)
  1272. ->Event("SetSnapMode", &UiScrollBoxBus::Events::SetSnapMode)
  1273. ->Event("GetSnapGrid", &UiScrollBoxBus::Events::GetSnapGrid)
  1274. ->Event("SetSnapGrid", &UiScrollBoxBus::Events::SetSnapGrid)
  1275. ->Event("GetHorizontalScrollBarVisibility", &UiScrollBoxBus::Events::GetHorizontalScrollBarVisibility)
  1276. ->Event("SetHorizontalScrollBarVisibility", &UiScrollBoxBus::Events::SetHorizontalScrollBarVisibility)
  1277. ->Event("GetVerticalScrollBarVisibility", &UiScrollBoxBus::Events::GetVerticalScrollBarVisibility)
  1278. ->Event("SetVerticalScrollBarVisibility", &UiScrollBoxBus::Events::SetVerticalScrollBarVisibility)
  1279. ->Event("GetScrollSensitivity", &UiScrollBoxBus::Events::GetScrollSensitivity)
  1280. ->Event("SetScrollSensitivity", &UiScrollBoxBus::Events::SetScrollSensitivity)
  1281. ->Event("GetMomentumDuration", &UiScrollBoxBus::Events::GetMomentumDuration)
  1282. ->Event("SetMomentumDuration", &UiScrollBoxBus::Events::SetMomentumDuration)
  1283. ->Event("SetMomentumActive", &UiScrollBoxBus::Events::SetMomentumActive)
  1284. ->Event("StopMomentum", &UiScrollBoxBus::Events::StopMomentum)
  1285. ->Event("GetScrollOffsetChangingActionName", &UiScrollBoxBus::Events::GetScrollOffsetChangingActionName)
  1286. ->Event("SetScrollOffsetChangingActionName", &UiScrollBoxBus::Events::SetScrollOffsetChangingActionName)
  1287. ->Event("GetScrollOffsetChangedActionName", &UiScrollBoxBus::Events::GetScrollOffsetChangedActionName)
  1288. ->Event("SetScrollOffsetChangedActionName", &UiScrollBoxBus::Events::SetScrollOffsetChangedActionName)
  1289. ->Event("GetContentEntity", &UiScrollBoxBus::Events::GetContentEntity)
  1290. ->Event("SetContentEntity", &UiScrollBoxBus::Events::SetContentEntity)
  1291. ->Event("GetHorizontalScrollBarEntity", &UiScrollBoxBus::Events::GetHorizontalScrollBarEntity)
  1292. ->Event("SetHorizontalScrollBarEntity", &UiScrollBoxBus::Events::SetHorizontalScrollBarEntity)
  1293. ->Event("GetVerticalScrollBarEntity", &UiScrollBoxBus::Events::GetVerticalScrollBarEntity)
  1294. ->Event("SetVerticalScrollBarEntity", &UiScrollBoxBus::Events::SetVerticalScrollBarEntity)
  1295. ->Event("FindClosestContentChildElement", &UiScrollBoxBus::Events::FindClosestContentChildElement);
  1296. behaviorContext->Enum<(int)UiScrollBoxInterface::SnapMode::None>("eUiScrollBoxSnapMode_None")
  1297. ->Enum<(int)UiScrollBoxInterface::SnapMode::Children>("eUiScrollBoxSnapMode_Children")
  1298. ->Enum<(int)UiScrollBoxInterface::SnapMode::Grid>("eUiScrollBoxSnapMode_Grid")
  1299. ->Enum<(int)UiScrollBoxInterface::ScrollBarVisibility::AlwaysShow>("eUiScrollBoxScrollBarVisibility_AlwaysShow")
  1300. ->Enum<(int)UiScrollBoxInterface::ScrollBarVisibility::AutoHide>("eUiScrollBoxScrollBarVisibility_AutoHide")
  1301. ->Enum<(int)UiScrollBoxInterface::ScrollBarVisibility::AutoHideAndResizeViewport>("eUiScrollBoxScrollBarVisibility_AutoHideAndResizeViewport");
  1302. behaviorContext->EBus<UiScrollBoxNotificationBus>("UiScrollBoxNotificationBus")
  1303. ->Handler<BehaviorUiScrollBoxNotificationBusHandler>();
  1304. behaviorContext->EBus<UiScrollableNotificationBus>("UiScrollableNotificationBus")
  1305. ->Handler<BehaviorUiScrollableNotificationBusHandler>();
  1306. }
  1307. }
  1308. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1309. UiScrollBoxComponent::EntityComboBoxVec UiScrollBoxComponent::PopulateChildEntityList()
  1310. {
  1311. EntityComboBoxVec result;
  1312. // add a first entry for "None"
  1313. result.push_back(AZStd::make_pair(AZ::EntityId(AZ::EntityId()), "<None>"));
  1314. // Get a list of all child elements
  1315. LyShine::EntityArray matchingElements;
  1316. UiElementBus::Event(
  1317. GetEntityId(),
  1318. &UiElementBus::Events::FindDescendantElements,
  1319. []([[maybe_unused]] const AZ::Entity* entity)
  1320. {
  1321. return true;
  1322. },
  1323. matchingElements);
  1324. // add their names to the StringList and their IDs to the id list
  1325. for (auto childEntity : matchingElements)
  1326. {
  1327. result.push_back(AZStd::make_pair(AZ::EntityId(childEntity->GetId()), childEntity->GetName()));
  1328. }
  1329. return result;
  1330. }
  1331. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1332. UiScrollBoxComponent::EntityComboBoxVec UiScrollBoxComponent::PopulateHScrollBarEntityList()
  1333. {
  1334. return PopulateScrollBarEntityList(UiScrollerInterface::Orientation::Horizontal);
  1335. }
  1336. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1337. UiScrollBoxComponent::EntityComboBoxVec UiScrollBoxComponent::PopulateVScrollBarEntityList()
  1338. {
  1339. return PopulateScrollBarEntityList(UiScrollerInterface::Orientation::Vertical);
  1340. }
  1341. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1342. UiScrollBoxComponent::EntityComboBoxVec UiScrollBoxComponent::PopulateScrollBarEntityList(UiScrollerInterface::Orientation orientation)
  1343. {
  1344. EntityComboBoxVec result;
  1345. // Add a first entry for "None"
  1346. result.push_back(AZStd::make_pair(AZ::EntityId(), "<None>"));
  1347. // Get a list of all scrollbar elements
  1348. AZ::EntityId canvasEntityId;
  1349. UiElementBus::EventResult(canvasEntityId, GetEntityId(), &UiElementBus::Events::GetCanvasEntityId);
  1350. LyShine::EntityArray scrollBarElements;
  1351. UiCanvasBus::Event(
  1352. canvasEntityId,
  1353. &UiCanvasBus::Events::FindElements,
  1354. [this, orientation](const AZ::Entity* entity)
  1355. {
  1356. bool isScroller = false;
  1357. if (entity->GetId() != GetEntityId())
  1358. {
  1359. if (UiScrollerBus::FindFirstHandler(entity->GetId()))
  1360. {
  1361. // Check scrollbar's orientation
  1362. UiScrollerInterface::Orientation entityOrientation;
  1363. UiScrollerBus::EventResult(entityOrientation, entity->GetId(), &UiScrollerBus::Events::GetOrientation);
  1364. isScroller = (entityOrientation == orientation);
  1365. }
  1366. }
  1367. return isScroller;
  1368. },
  1369. scrollBarElements);
  1370. // Sort the elements by name
  1371. AZStd::sort(scrollBarElements.begin(), scrollBarElements.end(),
  1372. [](const AZ::Entity* e1, const AZ::Entity* e2) { return e1->GetName() < e2->GetName(); });
  1373. // Add their names to the StringList and their IDs to the id list
  1374. for (auto scrollBarEntity : scrollBarElements)
  1375. {
  1376. result.push_back(AZStd::make_pair(scrollBarEntity->GetId(), scrollBarEntity->GetName()));
  1377. }
  1378. return result;
  1379. }
  1380. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1381. bool UiScrollBoxComponent::IsSnapToGrid() const
  1382. {
  1383. return m_snapMode == SnapMode::Grid;
  1384. }
  1385. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1386. AZ::Vector2 UiScrollBoxComponent::ConstrainOffset(AZ::Vector2 proposedOffset, AZ::Entity* contentParentEntity)
  1387. {
  1388. AZ::Vector2 newScrollOffset = proposedOffset;
  1389. if (contentParentEntity)
  1390. {
  1391. // get content parent's rect in canvas space
  1392. UiTransformInterface::Rect parentRect;
  1393. UiTransformBus::Event(contentParentEntity->GetId(), &UiTransformBus::Events::GetCanvasSpaceRectNoScaleRotate, parentRect);
  1394. // get content's rect in canvas space
  1395. UiTransformInterface::Rect contentRect = GetAxisAlignedContentRect();
  1396. AZ::Vector2 latestOffsetDelta = newScrollOffset - m_scrollOffset;
  1397. // add the requested scroll offset to the content rect to get the proposed position
  1398. // The content has already need moved by the requested offset all but latestOffsetDelta
  1399. contentRect.MoveBy(latestOffsetDelta);
  1400. if (contentRect.GetWidth() <= parentRect.GetWidth())
  1401. {
  1402. newScrollOffset.SetX(0.0f);
  1403. }
  1404. else if (contentRect.left > parentRect.left)
  1405. {
  1406. newScrollOffset.SetX(newScrollOffset.GetX() - (contentRect.left - parentRect.left));
  1407. }
  1408. else if (contentRect.right < parentRect.right)
  1409. {
  1410. newScrollOffset.SetX(newScrollOffset.GetX() + (parentRect.right - contentRect.right));
  1411. }
  1412. if (contentRect.GetHeight() <= parentRect.GetHeight())
  1413. {
  1414. newScrollOffset.SetY(0.0f);
  1415. }
  1416. else if (contentRect.top > parentRect.top)
  1417. {
  1418. newScrollOffset.SetY(newScrollOffset.GetY() - (contentRect.top - parentRect.top));
  1419. }
  1420. else if (contentRect.bottom < parentRect.bottom)
  1421. {
  1422. newScrollOffset.SetY(newScrollOffset.GetY() + (parentRect.bottom - contentRect.bottom));
  1423. }
  1424. }
  1425. return newScrollOffset;
  1426. }
  1427. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1428. bool UiScrollBoxComponent::DoSnap()
  1429. {
  1430. AZ::Vector2 newScrollOffset = m_scrollOffset;
  1431. AZ::Vector2 deltaToSubtract(0.0f, 0.0f);
  1432. if (m_snapMode == UiScrollBoxInterface::SnapMode::Children)
  1433. {
  1434. AZ::EntityId closestChild = FindClosestContentChildElement();
  1435. if (closestChild.IsValid())
  1436. {
  1437. // want elastic animation eventually
  1438. deltaToSubtract = ComputeCurrentOffsetToChild(closestChild);
  1439. }
  1440. }
  1441. else if (m_snapMode == UiScrollBoxInterface::SnapMode::Grid)
  1442. {
  1443. deltaToSubtract = ComputeCurrentOffsetFromGrid();
  1444. }
  1445. // snapping should only move the content in the directions it is allowed to scroll
  1446. if (!m_isHorizontalScrollingEnabled)
  1447. {
  1448. deltaToSubtract.SetX(0.0f);
  1449. }
  1450. if (!m_isVerticalScrollingEnabled)
  1451. {
  1452. deltaToSubtract.SetY(0.0f);
  1453. }
  1454. newScrollOffset = m_scrollOffset - deltaToSubtract;
  1455. if (m_isScrollingConstrained)
  1456. {
  1457. AZ::Entity* contentParentEntity = nullptr;
  1458. UiElementBus::EventResult(contentParentEntity, m_contentEntity, &UiElementBus::Events::GetParent);
  1459. newScrollOffset = ConstrainOffset(newScrollOffset, contentParentEntity);
  1460. }
  1461. if (newScrollOffset != m_scrollOffset)
  1462. {
  1463. DoSetScrollOffset(newScrollOffset);
  1464. return true;
  1465. }
  1466. return false;
  1467. }
  1468. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1469. AZ::Vector2 UiScrollBoxComponent::ComputeCurrentOffsetToChild(AZ::EntityId child)
  1470. {
  1471. // Get the position of the child element's pivot in canvas space
  1472. AZ::Vector2 childPivotPosition;
  1473. UiTransformBus::EventResult(childPivotPosition, child, &UiTransformBus::Events::GetCanvasSpacePivot);
  1474. AZ::Vector2 anchorCenter = ComputeContentAnchorCenterInCanvasSpace();
  1475. // offset is the distance from the content anchors to the current child pivot position
  1476. // (given the current scroll offset)
  1477. AZ::Vector2 offsetToChild = childPivotPosition - anchorCenter;
  1478. AZ::Entity* contentParentEntity = nullptr;
  1479. UiElementBus::EventResult(contentParentEntity, m_contentEntity, &UiElementBus::Events::GetParent);
  1480. AZ::Matrix4x4 transform;
  1481. if (contentParentEntity)
  1482. {
  1483. UiTransformBus::Event(contentParentEntity->GetId(), &UiTransformBus::Events::GetTransformFromCanvasSpace, transform);
  1484. }
  1485. else
  1486. {
  1487. transform = AZ::Matrix4x4::CreateIdentity();
  1488. }
  1489. // Transform the offset from canvas space to the local space of the parent of the content element
  1490. AZ::Vector3 offsetToChild3(offsetToChild.GetX(), offsetToChild.GetY(), 0.0f);
  1491. offsetToChild3 = transform.Multiply3x3(offsetToChild3);
  1492. offsetToChild = AZ::Vector2(offsetToChild3.GetX(), offsetToChild3.GetY());
  1493. return offsetToChild;
  1494. }
  1495. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1496. AZ::Vector2 UiScrollBoxComponent::ComputeCurrentOffsetFromGrid()
  1497. {
  1498. // offset is the delta to add to subtract from m_scrollOffset to put it on the grid
  1499. AZ::Vector2 offsetToGrid;
  1500. offsetToGrid.SetX(ComputeOffsetOfValueFromGrid(m_scrollOffset.GetX(), m_snapGrid.GetX()));
  1501. offsetToGrid.SetY(ComputeOffsetOfValueFromGrid(m_scrollOffset.GetY(), m_snapGrid.GetY()));
  1502. return offsetToGrid;
  1503. }
  1504. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1505. AZ::Vector2 UiScrollBoxComponent::ComputeContentAnchorCenterInCanvasSpace() const
  1506. {
  1507. // Get the position of the content elements anchors in canvas space
  1508. AZ::Entity* contentParentEntity = nullptr;
  1509. UiElementBus::EventResult(contentParentEntity, m_contentEntity, &UiElementBus::Events::GetParent);
  1510. if (!contentParentEntity)
  1511. {
  1512. return AZ::Vector2(0.0f, 0.0f);
  1513. }
  1514. // get content parent's rect in canvas space
  1515. UiTransformInterface::Rect parentRect;
  1516. UiTransformBus::Event(contentParentEntity->GetId(), &UiTransformBus::Events::GetCanvasSpaceRectNoScaleRotate, parentRect);
  1517. // Get the content anchor center in canvas space
  1518. UiTransform2dInterface::Anchors anchors;
  1519. UiTransform2dBus::EventResult(anchors, m_contentEntity, &UiTransform2dBus::Events::GetAnchors);
  1520. UiTransformInterface::Rect anchorRect;
  1521. anchorRect.left = parentRect.left + anchors.m_left * parentRect.GetWidth();
  1522. anchorRect.right = parentRect.left + anchors.m_right * parentRect.GetWidth();
  1523. anchorRect.top = parentRect.top + anchors.m_top * parentRect.GetHeight();
  1524. anchorRect.bottom = parentRect.top + anchors.m_bottom * parentRect.GetHeight();
  1525. AZ::Vector2 anchorCenter = anchorRect.GetCenter();
  1526. AZ::Matrix4x4 transformToCanvasSpace;
  1527. UiTransformBus::Event(contentParentEntity->GetId(), &UiTransformBus::Events::GetTransformToCanvasSpace, transformToCanvasSpace);
  1528. AZ::Vector3 anchorCenter3(anchorCenter.GetX(), anchorCenter.GetY(), 0.0f);
  1529. anchorCenter3 = transformToCanvasSpace * anchorCenter3;
  1530. anchorCenter = AZ::Vector2(anchorCenter3.GetX(), anchorCenter3.GetY());
  1531. return anchorCenter;
  1532. }
  1533. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1534. float UiScrollBoxComponent::ComputeOffsetOfValueFromGrid(float value, float gridStep)
  1535. {
  1536. const float gridEpsilon = 0.00001f;
  1537. // compute offset to round to nearest point on grid
  1538. float offsetFromGrid = 0.0f;
  1539. if (gridStep >= gridEpsilon)
  1540. {
  1541. float roundedGridStep = roundf(value / gridStep);
  1542. float targetValue = roundedGridStep * gridStep;
  1543. offsetFromGrid = value - targetValue;
  1544. }
  1545. return offsetFromGrid;
  1546. }
  1547. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1548. // calculate how much we have dragged along the dragable axes of the ScrollBox
  1549. float UiScrollBoxComponent::GetValidDragDistanceInPixels(AZ::Vector2 startPoint, AZ::Vector2 endPoint)
  1550. {
  1551. const float validDragRatio = 0.5f;
  1552. AZ::Entity* contentParentEntity = nullptr;
  1553. UiElementBus::EventResult(contentParentEntity, m_contentEntity, &UiElementBus::Events::GetParent);
  1554. if (!contentParentEntity)
  1555. {
  1556. return 0.0f;
  1557. }
  1558. // convert the drag vector to local space
  1559. AZ::Matrix4x4 transformFromViewport;
  1560. UiTransformBus::Event(contentParentEntity->GetId(), &UiTransformBus::Events::GetTransformFromViewport, transformFromViewport);
  1561. AZ::Vector2 dragVec = endPoint - startPoint;
  1562. AZ::Vector3 dragVec3(dragVec.GetX(), dragVec.GetY(), 0.0f);
  1563. AZ::Vector3 localDragVec = transformFromViewport.Multiply3x3(dragVec3);
  1564. // constrain to the allowed movement directions
  1565. if (!m_isHorizontalScrollingEnabled)
  1566. {
  1567. localDragVec.SetX(0.0f);
  1568. }
  1569. if (!m_isVerticalScrollingEnabled)
  1570. {
  1571. localDragVec.SetY(0.0f);
  1572. }
  1573. // convert back to viewport space
  1574. AZ::Matrix4x4 transformToViewport;
  1575. UiTransformBus::Event(contentParentEntity->GetId(), &UiTransformBus::Events::GetTransformToViewport, transformToViewport);
  1576. AZ::Vector3 validDragVec = transformToViewport.Multiply3x3(localDragVec);
  1577. float validDistance = validDragVec.GetLengthSq();
  1578. float totalDistance = dragVec.GetLengthSq();
  1579. // if they are not dragging mostly in a valid direction then ignore the drag
  1580. if (validDistance / totalDistance < validDragRatio)
  1581. {
  1582. validDistance = 0.0f;
  1583. }
  1584. // return the valid drag distance
  1585. return validDistance;
  1586. }
  1587. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1588. void UiScrollBoxComponent::CheckForDragOrHandOffToParent(AZ::Vector2 point)
  1589. {
  1590. AZ::EntityId parentDraggable;
  1591. UiElementBus::EventResult(parentDraggable, GetEntityId(), &UiElementBus::Events::FindParentInteractableSupportingDrag, point);
  1592. // if this interactable is inside another interactable that supports drag then we use
  1593. // a threshold value before starting a drag on this interactable
  1594. const float normalDragThreshold = 0.0f;
  1595. const float containedDragThreshold = 5.0f;
  1596. float dragThreshold = normalDragThreshold;
  1597. if (parentDraggable.IsValid())
  1598. {
  1599. dragThreshold = containedDragThreshold;
  1600. }
  1601. // calculate how much we have dragged in a valid direction
  1602. float validDragDistance = GetValidDragDistanceInPixels(m_pressedPoint, point);
  1603. if (validDragDistance > dragThreshold)
  1604. {
  1605. // we dragged above the threshold value along axis of slider
  1606. m_isDragging = true;
  1607. }
  1608. else if (parentDraggable.IsValid())
  1609. {
  1610. // offer the parent draggable the chance to become the active interactable
  1611. bool handOff = false;
  1612. UiInteractableBus::EventResult(
  1613. handOff,
  1614. parentDraggable,
  1615. &UiInteractableBus::Events::OfferDragHandOff,
  1616. GetEntityId(),
  1617. m_pressedPoint,
  1618. point,
  1619. containedDragThreshold);
  1620. if (handOff)
  1621. {
  1622. // interaction has been handed off to a container entity
  1623. m_isPressed = false;
  1624. }
  1625. }
  1626. }
  1627. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1628. void UiScrollBoxComponent::DoSetScrollOffset(AZ::Vector2 scrollOffset)
  1629. {
  1630. m_scrollOffset = scrollOffset;
  1631. if (m_contentEntity.IsValid())
  1632. {
  1633. // The scrollOffset is the distance from the content element's anchors to its pivot
  1634. // Given the scrollOffset we adjust the offsets to make this so.
  1635. UiTransform2dInterface::Offsets offsets;
  1636. UiTransform2dBus::EventResult(offsets, m_contentEntity, &UiTransform2dBus::Events::GetOffsets);
  1637. AZ::Vector2 pivot;
  1638. UiTransformBus::EventResult(pivot, m_contentEntity, &UiTransformBus::Events::GetPivot);
  1639. float width = offsets.m_right - offsets.m_left;
  1640. float height = offsets.m_bottom - offsets.m_top;
  1641. offsets.m_left = scrollOffset.GetX() - width * pivot.GetX();
  1642. offsets.m_right = offsets.m_left + width;
  1643. offsets.m_top = scrollOffset.GetY() - height * pivot.GetY();
  1644. offsets.m_bottom = offsets.m_top + height;
  1645. UiTransform2dBus::Event(m_contentEntity, &UiTransform2dBus::Events::SetOffsets, offsets);
  1646. }
  1647. }
  1648. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1649. void UiScrollBoxComponent::DoChangedActions()
  1650. {
  1651. if (m_onScrollOffsetChanged)
  1652. {
  1653. m_onScrollOffsetChanged(GetEntityId(), m_scrollOffset);
  1654. }
  1655. // Tell any action listeners about the event
  1656. if (!m_scrollOffsetChangedActionName.empty())
  1657. {
  1658. AZ::EntityId canvasEntityId;
  1659. UiElementBus::EventResult(canvasEntityId, GetEntityId(), &UiElementBus::Events::GetCanvasEntityId);
  1660. UiCanvasNotificationBus::Event(
  1661. canvasEntityId, &UiCanvasNotificationBus::Events::OnAction, GetEntityId(), m_scrollOffsetChangedActionName);
  1662. }
  1663. NotifyListenersOnScrollOffsetChanged();
  1664. NotifyListenersOnScrollValueChanged();
  1665. }
  1666. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1667. void UiScrollBoxComponent::DoChangingActions()
  1668. {
  1669. if (m_onScrollOffsetChanging)
  1670. {
  1671. m_onScrollOffsetChanging(GetEntityId(), m_scrollOffset);
  1672. }
  1673. // Tell any action listeners about the event
  1674. if (!m_scrollOffsetChangingActionName.empty())
  1675. {
  1676. AZ::EntityId canvasEntityId;
  1677. UiElementBus::EventResult(canvasEntityId, GetEntityId(), &UiElementBus::Events::GetCanvasEntityId);
  1678. UiCanvasNotificationBus::Event(
  1679. canvasEntityId, &UiCanvasNotificationBus::Events::OnAction, GetEntityId(), m_scrollOffsetChangingActionName);
  1680. }
  1681. NotifyListenersOnScrollOffsetChanging();
  1682. NotifyListenersOnScrollValueChanging();
  1683. }
  1684. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1685. void UiScrollBoxComponent::NotifyScrollersOnValueChanged()
  1686. {
  1687. AZ::Vector2 normalizedScrollValueOut;
  1688. bool result = ScrollOffsetToNormalizedScrollValue(m_scrollOffset, normalizedScrollValueOut);
  1689. if (result)
  1690. {
  1691. UiScrollableToScrollerNotificationBus::Event(
  1692. GetEntityId(), &UiScrollableToScrollerNotificationBus::Events::OnValueChangedByScrollable, normalizedScrollValueOut);
  1693. }
  1694. }
  1695. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1696. void UiScrollBoxComponent::NotifyScrollersOnValueChanging()
  1697. {
  1698. AZ::Vector2 normalizedScrollValueOut;
  1699. bool result = ScrollOffsetToNormalizedScrollValue(m_scrollOffset, normalizedScrollValueOut);
  1700. if (result)
  1701. {
  1702. UiScrollableToScrollerNotificationBus::Event(
  1703. GetEntityId(), &UiScrollableToScrollerNotificationBus::Events::OnValueChangingByScrollable, normalizedScrollValueOut);
  1704. }
  1705. }
  1706. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1707. void UiScrollBoxComponent::NotifyListenersOnScrollValueChanged()
  1708. {
  1709. AZ::Vector2 normalizedScrollValueOut;
  1710. bool result = ScrollOffsetToNormalizedScrollValue(m_scrollOffset, normalizedScrollValueOut);
  1711. if (result)
  1712. {
  1713. UiScrollableNotificationBus::Event(
  1714. GetEntityId(), &UiScrollableNotificationBus::Events::OnScrollableValueChanged, normalizedScrollValueOut);
  1715. }
  1716. }
  1717. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1718. void UiScrollBoxComponent::NotifyListenersOnScrollValueChanging()
  1719. {
  1720. AZ::Vector2 normalizedScrollValueOut;
  1721. bool result = ScrollOffsetToNormalizedScrollValue(m_scrollOffset, normalizedScrollValueOut);
  1722. if (result)
  1723. {
  1724. UiScrollableNotificationBus::Event(
  1725. GetEntityId(), &UiScrollableNotificationBus::Events::OnScrollableValueChanging, normalizedScrollValueOut);
  1726. }
  1727. }
  1728. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1729. void UiScrollBoxComponent::NotifyListenersOnScrollOffsetChanged()
  1730. {
  1731. UiScrollBoxNotificationBus::Event(GetEntityId(), &UiScrollBoxNotificationBus::Events::OnScrollOffsetChanged, m_scrollOffset);
  1732. }
  1733. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1734. void UiScrollBoxComponent::NotifyListenersOnScrollOffsetChanging()
  1735. {
  1736. UiScrollBoxNotificationBus::Event(GetEntityId(), &UiScrollBoxNotificationBus::Events::OnScrollOffsetChanging, m_scrollOffset);
  1737. }
  1738. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1739. UiTransformInterface::Rect UiScrollBoxComponent::GetAxisAlignedContentRect()
  1740. {
  1741. UiTransformInterface::RectPoints points;
  1742. UiTransformBus::Event(m_contentEntity, &UiTransformBus::Events::GetCanvasSpacePointsNoScaleRotate, points);
  1743. AZ::Matrix4x4 transform;
  1744. UiTransformBus::Event(m_contentEntity, &UiTransformBus::Events::GetLocalTransform, transform);
  1745. points = points.Transform(transform);
  1746. UiTransformInterface::Rect rect;
  1747. rect.left = points.GetAxisAlignedTopLeft().GetX();
  1748. rect.right = points.GetAxisAlignedBottomRight().GetX();
  1749. rect.top = points.GetAxisAlignedTopLeft().GetY();
  1750. rect.bottom = points.GetAxisAlignedBottomRight().GetY();
  1751. return rect;
  1752. }
  1753. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1754. bool UiScrollBoxComponent::ScrollOffsetToNormalizedScrollValue(AZ::Vector2 scrollOffset, AZ::Vector2& normalizedScrollValueOut)
  1755. {
  1756. AZ::Entity* contentParentEntity = nullptr;
  1757. UiElementBus::EventResult(contentParentEntity, m_contentEntity, &UiElementBus::Events::GetParent);
  1758. if (contentParentEntity)
  1759. {
  1760. UiTransformInterface::Rect parentRect;
  1761. UiTransformBus::Event(contentParentEntity->GetId(), &UiTransformBus::Events::GetCanvasSpaceRectNoScaleRotate, parentRect);
  1762. UiTransformInterface::Rect contentRect = GetAxisAlignedContentRect();
  1763. if (contentRect.GetWidth() <= parentRect.GetWidth())
  1764. {
  1765. normalizedScrollValueOut.SetX(0.0f);
  1766. }
  1767. else
  1768. {
  1769. float minScrollOffset = scrollOffset.GetX() - (contentRect.left - parentRect.left);
  1770. float maxScrollOffset = scrollOffset.GetX() - (contentRect.right - parentRect.right);
  1771. normalizedScrollValueOut.SetX((scrollOffset.GetX() - minScrollOffset) / (maxScrollOffset - minScrollOffset));
  1772. }
  1773. if (contentRect.GetHeight() <= parentRect.GetHeight())
  1774. {
  1775. normalizedScrollValueOut.SetY(0.0f);
  1776. }
  1777. else
  1778. {
  1779. float minScrollOffset = scrollOffset.GetY() - (contentRect.top - parentRect.top);
  1780. float maxScrollOffset = scrollOffset.GetY() - (contentRect.bottom - parentRect.bottom);
  1781. normalizedScrollValueOut.SetY((scrollOffset.GetY() - minScrollOffset) / (maxScrollOffset - minScrollOffset));
  1782. }
  1783. return true;
  1784. }
  1785. return false;
  1786. }
  1787. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1788. bool UiScrollBoxComponent::NormalizedScrollValueToScrollOffset(UiScrollerInterface::Orientation orientation, float normalizedScrollValue, float& scrollOffsetOut)
  1789. {
  1790. if (orientation == UiScrollerInterface::Orientation::Horizontal || orientation == UiScrollerInterface::Orientation::Vertical)
  1791. {
  1792. AZ::Entity* contentParentEntity = nullptr;
  1793. UiElementBus::EventResult(contentParentEntity, m_contentEntity, &UiElementBus::Events::GetParent);
  1794. if (contentParentEntity)
  1795. {
  1796. UiTransformInterface::Rect parentRect;
  1797. UiTransformBus::Event(contentParentEntity->GetId(), &UiTransformBus::Events::GetCanvasSpaceRectNoScaleRotate, parentRect);
  1798. UiTransformInterface::Rect contentRect = GetAxisAlignedContentRect();
  1799. if (orientation == UiScrollerInterface::Orientation::Horizontal)
  1800. {
  1801. if (contentRect.GetWidth() <= parentRect.GetWidth())
  1802. {
  1803. if (m_isScrollingConstrained)
  1804. {
  1805. scrollOffsetOut = 0.0f;
  1806. }
  1807. else
  1808. {
  1809. scrollOffsetOut = m_scrollOffset.GetX();
  1810. }
  1811. }
  1812. else
  1813. {
  1814. float minScrollOffset = m_scrollOffset.GetX() - (contentRect.left - parentRect.left);
  1815. float maxScrollOffset = m_scrollOffset.GetX() - (contentRect.right - parentRect.right);
  1816. scrollOffsetOut = minScrollOffset + (maxScrollOffset - minScrollOffset) * normalizedScrollValue;
  1817. }
  1818. }
  1819. else // orientation == UiScrollerInterface::Orientation::Vertical
  1820. {
  1821. if (contentRect.GetHeight() <= parentRect.GetHeight())
  1822. {
  1823. if (m_isScrollingConstrained)
  1824. {
  1825. scrollOffsetOut = 0.0f;
  1826. }
  1827. else
  1828. {
  1829. scrollOffsetOut = m_scrollOffset.GetY();
  1830. }
  1831. }
  1832. else
  1833. {
  1834. float minScrollOffset = m_scrollOffset.GetY() - (contentRect.top - parentRect.top);
  1835. float maxScrollOffset = m_scrollOffset.GetY() - (contentRect.bottom - parentRect.bottom);
  1836. scrollOffsetOut = minScrollOffset + (maxScrollOffset - minScrollOffset) * normalizedScrollValue;
  1837. }
  1838. }
  1839. return true;
  1840. }
  1841. }
  1842. return false;
  1843. }
  1844. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1845. bool UiScrollBoxComponent::ScrollerValueToScrollOffsets(AZ::EntityId scroller, float scrollerValue, AZ::Vector2& scrollOffsetsOut)
  1846. {
  1847. if (((scroller == m_hScrollBarEntity) && m_isHorizontalScrollingEnabled)
  1848. || ((scroller == m_vScrollBarEntity) && m_isVerticalScrollingEnabled))
  1849. {
  1850. float scrollOffsetOut;
  1851. UiScrollerInterface::Orientation orientation = (scroller == m_hScrollBarEntity) ? UiScrollerInterface::Orientation::Horizontal : UiScrollerInterface::Orientation::Vertical;
  1852. bool result = NormalizedScrollValueToScrollOffset(orientation, scrollerValue, scrollOffsetOut);
  1853. if (result)
  1854. {
  1855. scrollOffsetsOut = m_scrollOffset;
  1856. if (orientation == UiScrollerInterface::Orientation::Horizontal)
  1857. {
  1858. scrollOffsetsOut.SetX(scrollOffsetOut);
  1859. }
  1860. else // orientation == UiScrollerInterface::Orientation::Vertical
  1861. {
  1862. scrollOffsetsOut.SetY(scrollOffsetOut);
  1863. }
  1864. return true;
  1865. }
  1866. }
  1867. return false;
  1868. }
  1869. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1870. bool UiScrollBoxComponent::IsVerticalScrollBarOnRight()
  1871. {
  1872. // Check if vertical scrollbar is on the right of the content's parent
  1873. AZ::Entity* contentParentEntity = nullptr;
  1874. UiElementBus::EventResult(contentParentEntity, m_contentEntity, &UiElementBus::Events::GetParent);
  1875. if (contentParentEntity)
  1876. {
  1877. // Get content parent rect in canvas space
  1878. UiTransformInterface::Rect parentRect;
  1879. UiTransformBus::Event(contentParentEntity->GetId(), &UiTransformBus::Events::GetCanvasSpaceRectNoScaleRotate, parentRect);
  1880. // Get vertical scrollbar rect in canvas space
  1881. UiTransformInterface::Rect vScrollBarRect;
  1882. UiTransformBus::Event(m_vScrollBarEntity, &UiTransformBus::Events::GetCanvasSpaceRectNoScaleRotate, vScrollBarRect);
  1883. return (vScrollBarRect.GetCenter().GetX() > parentRect.GetCenter().GetX());
  1884. }
  1885. return true;
  1886. }
  1887. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1888. bool UiScrollBoxComponent::IsHorizontalScrollBarOnBottom()
  1889. {
  1890. // Check if horizontal scrollbar is on the bottom of the content's parent
  1891. AZ::Entity* contentParentEntity = nullptr;
  1892. UiElementBus::EventResult(contentParentEntity, m_contentEntity, &UiElementBus::Events::GetParent);
  1893. if (contentParentEntity)
  1894. {
  1895. // Get content parent rect in canvas space
  1896. UiTransformInterface::Rect parentRect;
  1897. UiTransformBus::Event(contentParentEntity->GetId(), &UiTransformBus::Events::GetCanvasSpaceRectNoScaleRotate, parentRect);
  1898. // Get horizontal scrollbar rect in canvas space
  1899. UiTransformInterface::Rect hScrollBarRect;
  1900. UiTransformBus::Event(m_hScrollBarEntity, &UiTransformBus::Events::GetCanvasSpaceRectNoScaleRotate, hScrollBarRect);
  1901. return (hScrollBarRect.GetCenter().GetY() > parentRect.GetCenter().GetY());
  1902. }
  1903. return true;
  1904. }
  1905. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1906. void UiScrollBoxComponent::UpdateScrollBarVisiblity()
  1907. {
  1908. bool updateHorizontalScrollBar = m_hScrollBarEntity.IsValid() && m_isHorizontalScrollingEnabled && (m_hScrollBarVisibility != ScrollBarVisibility::AlwaysShow);
  1909. bool updateVerticalScrollBar = m_vScrollBarEntity.IsValid() && m_isVerticalScrollingEnabled && (m_vScrollBarVisibility != ScrollBarVisibility::AlwaysShow);
  1910. if (updateHorizontalScrollBar || updateVerticalScrollBar)
  1911. {
  1912. // Set scrollbar visibility based on whether there is scrollable content
  1913. AZ::Entity* contentParentEntity = nullptr;
  1914. UiElementBus::EventResult(contentParentEntity, m_contentEntity, &UiElementBus::Events::GetParent);
  1915. if (contentParentEntity)
  1916. {
  1917. bool showHScrollBar = true;
  1918. bool showVScrollBar = true;
  1919. // Get content parent's size
  1920. AZ::Vector2 parentSize;
  1921. UiTransformBus::EventResult(parentSize, contentParentEntity->GetId(), &UiTransformBus::Events::GetCanvasSpaceSizeNoScaleRotate);
  1922. // Get content size
  1923. UiTransformInterface::Rect contentRect = GetAxisAlignedContentRect();
  1924. AZ::Vector2 contentSize = contentRect.GetSize();
  1925. // First check if none of the hideable scrollbars are needed
  1926. bool needHScrollBar = false;
  1927. bool needVScrollBar = false;
  1928. if (updateHorizontalScrollBar)
  1929. {
  1930. needHScrollBar = (contentSize.GetX() > parentSize.GetX());
  1931. }
  1932. if (updateVerticalScrollBar)
  1933. {
  1934. needVScrollBar = (contentSize.GetY() > parentSize.GetY());
  1935. }
  1936. if (!needHScrollBar && !needVScrollBar)
  1937. {
  1938. showHScrollBar = false;
  1939. showVScrollBar = false;
  1940. }
  1941. else
  1942. {
  1943. // Next, check if only a horizontal scrollbar is needed
  1944. AZ::Vector2 supposedParentSize = parentSize;
  1945. if (updateHorizontalScrollBar && (m_hScrollBarVisibility == ScrollBarVisibility::AutoHideAndResizeViewport))
  1946. {
  1947. // Get height of horizontal scrollbar
  1948. AZ::Vector2 hScrollBarSize;
  1949. UiTransformBus::EventResult(
  1950. hScrollBarSize, m_hScrollBarEntity, &UiTransformBus::Events::GetCanvasSpaceSizeNoScaleRotate);
  1951. float hScrollBarHeight = hScrollBarSize.GetY();
  1952. supposedParentSize.SetY(supposedParentSize.GetY() - hScrollBarHeight);
  1953. }
  1954. if (contentSize.GetY() <= supposedParentSize.GetY() && contentSize.GetX() > supposedParentSize.GetX())
  1955. {
  1956. showHScrollBar = true;
  1957. showVScrollBar = false;
  1958. }
  1959. else
  1960. {
  1961. // Next, check if only a vertical scrollbar is needed
  1962. supposedParentSize = parentSize;
  1963. if (updateVerticalScrollBar && (m_vScrollBarVisibility == ScrollBarVisibility::AutoHideAndResizeViewport))
  1964. {
  1965. // Get width of vertical scrollbar
  1966. AZ::Vector2 vScrollBarSize;
  1967. UiTransformBus::EventResult(
  1968. vScrollBarSize, m_vScrollBarEntity, &UiTransformBus::Events::GetCanvasSpaceSizeNoScaleRotate);
  1969. float vScrollBarWidth = vScrollBarSize.GetX();
  1970. supposedParentSize.SetX(supposedParentSize.GetX() - vScrollBarWidth);
  1971. }
  1972. if (contentSize.GetX() <= supposedParentSize.GetX() && contentSize.GetY() > supposedParentSize.GetY())
  1973. {
  1974. showHScrollBar = false;
  1975. showVScrollBar = true;
  1976. }
  1977. else
  1978. {
  1979. // Both scrollbars are needed
  1980. showHScrollBar = true;
  1981. showVScrollBar = true;
  1982. }
  1983. }
  1984. }
  1985. // Set enabled property on the scrollbars
  1986. if (updateHorizontalScrollBar)
  1987. {
  1988. UiElementBus::Event(m_hScrollBarEntity, &UiElementBus::Events::SetIsEnabled, showHScrollBar);
  1989. }
  1990. if (updateVerticalScrollBar)
  1991. {
  1992. UiElementBus::Event(m_vScrollBarEntity, &UiElementBus::Events::SetIsEnabled, showVScrollBar);
  1993. }
  1994. }
  1995. }
  1996. }
  1997. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1998. void UiScrollBoxComponent::UpdateScrollBarAnchorsAndOffsets()
  1999. {
  2000. // Set scrollbar anchors and offsets based on the other scrollbar's visibility
  2001. if (m_hScrollBarEntity.IsValid() && m_isHorizontalScrollingEnabled && (m_hScrollBarVisibility != ScrollBarVisibility::AlwaysShow))
  2002. {
  2003. // Set anchors
  2004. UiTransform2dInterface::Anchors anchors;
  2005. UiTransform2dBus::EventResult(anchors, m_hScrollBarEntity, &UiTransform2dBus::Events::GetAnchors);
  2006. anchors.m_left = 0.0f;
  2007. anchors.m_right = 1.0f;
  2008. UiTransform2dBus::Event(m_hScrollBarEntity, &UiTransform2dBus::Events::SetAnchors, anchors, false, false);
  2009. // Set offsets
  2010. UiTransform2dInterface::Offsets offsets;
  2011. UiTransform2dBus::EventResult(offsets, m_hScrollBarEntity, &UiTransform2dBus::Events::GetOffsets);
  2012. bool isVScrollBarEnabled = false;
  2013. if (m_vScrollBarEntity.IsValid() && m_isVerticalScrollingEnabled)
  2014. {
  2015. UiElementBus::EventResult(isVScrollBarEnabled, m_vScrollBarEntity, &UiElementBus::Events::IsEnabled);
  2016. }
  2017. if (isVScrollBarEnabled)
  2018. {
  2019. // Get width of vertical scrollbar
  2020. AZ::Vector2 vScrollBarSize;
  2021. UiTransformBus::EventResult(vScrollBarSize, m_vScrollBarEntity, &UiTransformBus::Events::GetCanvasSpaceSizeNoScaleRotate);
  2022. if (IsVerticalScrollBarOnRight())
  2023. {
  2024. offsets.m_left = 0.0f;
  2025. offsets.m_right = -vScrollBarSize.GetX();
  2026. }
  2027. else
  2028. {
  2029. offsets.m_left = vScrollBarSize.GetX();
  2030. offsets.m_right = 0.0f;
  2031. }
  2032. }
  2033. else
  2034. {
  2035. offsets.m_left = 0.0f;
  2036. offsets.m_right = 0.0f;
  2037. }
  2038. UiTransform2dBus::Event(m_hScrollBarEntity, &UiTransform2dBus::Events::SetOffsets, offsets);
  2039. }
  2040. if (m_vScrollBarEntity.IsValid() && m_isVerticalScrollingEnabled && (m_vScrollBarVisibility != ScrollBarVisibility::AlwaysShow))
  2041. {
  2042. // Set anchors
  2043. UiTransform2dInterface::Anchors anchors;
  2044. UiTransform2dBus::EventResult(anchors, m_vScrollBarEntity, &UiTransform2dBus::Events::GetAnchors);
  2045. anchors.m_top = 0.0f;
  2046. anchors.m_bottom = 1.0f;
  2047. UiTransform2dBus::Event(m_vScrollBarEntity, &UiTransform2dBus::Events::SetAnchors, anchors, false, false);
  2048. // Set offsets
  2049. UiTransform2dInterface::Offsets offsets;
  2050. UiTransform2dBus::EventResult(offsets, m_vScrollBarEntity, &UiTransform2dBus::Events::GetOffsets);
  2051. bool isHScrollBarEnabled = false;
  2052. if (m_hScrollBarEntity.IsValid() && m_isHorizontalScrollingEnabled)
  2053. {
  2054. UiElementBus::EventResult(isHScrollBarEnabled, m_hScrollBarEntity, &UiElementBus::Events::IsEnabled);
  2055. }
  2056. if (isHScrollBarEnabled)
  2057. {
  2058. // Get height of horizontal scrollbar
  2059. AZ::Vector2 hScrollBarSize;
  2060. UiTransformBus::EventResult(hScrollBarSize, m_hScrollBarEntity, &UiTransformBus::Events::GetCanvasSpaceSizeNoScaleRotate);
  2061. if (IsHorizontalScrollBarOnBottom())
  2062. {
  2063. offsets.m_top = 0.0f;
  2064. offsets.m_bottom = -hScrollBarSize.GetY();
  2065. }
  2066. else
  2067. {
  2068. offsets.m_top = hScrollBarSize.GetY();
  2069. offsets.m_bottom = 0.0f;
  2070. }
  2071. }
  2072. else
  2073. {
  2074. offsets.m_top = 0.0f;
  2075. offsets.m_bottom = 0.0f;
  2076. }
  2077. UiTransform2dBus::Event(m_vScrollBarEntity, &UiTransform2dBus::Events::SetOffsets, offsets);
  2078. }
  2079. }
  2080. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2081. void UiScrollBoxComponent::UpdateContentParentOffsets(bool checkScrollBarVisibility)
  2082. {
  2083. if ((m_hScrollBarEntity.IsValid() && m_isHorizontalScrollingEnabled && (m_hScrollBarVisibility == ScrollBarVisibility::AutoHideAndResizeViewport))
  2084. || (m_vScrollBarEntity.IsValid() && m_isVerticalScrollingEnabled && (m_vScrollBarVisibility == ScrollBarVisibility::AutoHideAndResizeViewport)))
  2085. {
  2086. // Set content parent offsets based on scrollbar visibility
  2087. AZ::Entity* contentParentEntity = nullptr;
  2088. UiElementBus::EventResult(contentParentEntity, m_contentEntity, &UiElementBus::Events::GetParent);
  2089. if (contentParentEntity)
  2090. {
  2091. UiTransform2dInterface::Offsets offsets;
  2092. UiTransform2dBus::EventResult(offsets, contentParentEntity->GetId(), &UiTransform2dBus::Events::GetOffsets);
  2093. if (m_hScrollBarEntity.IsValid() && m_isHorizontalScrollingEnabled && (m_hScrollBarVisibility == ScrollBarVisibility::AutoHideAndResizeViewport))
  2094. {
  2095. bool isHScrollBarEnabled = false;
  2096. if (checkScrollBarVisibility)
  2097. {
  2098. UiElementBus::EventResult(isHScrollBarEnabled, m_hScrollBarEntity, &UiElementBus::Events::IsEnabled);
  2099. }
  2100. if (isHScrollBarEnabled)
  2101. {
  2102. // Get height of horizontal scrollbar
  2103. AZ::Vector2 hScrollBarSize;
  2104. UiTransformBus::EventResult(
  2105. hScrollBarSize, m_hScrollBarEntity, &UiTransformBus::Events::GetCanvasSpaceSizeNoScaleRotate);
  2106. if (IsHorizontalScrollBarOnBottom())
  2107. {
  2108. offsets.m_top = 0.0f;
  2109. offsets.m_bottom = -hScrollBarSize.GetY();
  2110. }
  2111. else
  2112. {
  2113. offsets.m_top = hScrollBarSize.GetY();
  2114. offsets.m_bottom = 0.0f;
  2115. }
  2116. }
  2117. else
  2118. {
  2119. offsets.m_top = 0.0f;
  2120. offsets.m_bottom = 0.0f;
  2121. }
  2122. }
  2123. if (m_vScrollBarEntity.IsValid() && m_isVerticalScrollingEnabled && (m_vScrollBarVisibility == ScrollBarVisibility::AutoHideAndResizeViewport))
  2124. {
  2125. bool isVScrollBarEnabled = false;
  2126. if (checkScrollBarVisibility)
  2127. {
  2128. UiElementBus::EventResult(isVScrollBarEnabled, m_vScrollBarEntity, &UiElementBus::Events::IsEnabled);
  2129. }
  2130. if (isVScrollBarEnabled)
  2131. {
  2132. // Get width of vertical scrollbar
  2133. AZ::Vector2 vScrollBarSize;
  2134. UiTransformBus::EventResult(
  2135. vScrollBarSize, m_vScrollBarEntity, &UiTransformBus::Events::GetCanvasSpaceSizeNoScaleRotate);
  2136. if (IsVerticalScrollBarOnRight())
  2137. {
  2138. offsets.m_left = 0.0f;
  2139. offsets.m_right = -vScrollBarSize.GetX();
  2140. }
  2141. else
  2142. {
  2143. offsets.m_left = vScrollBarSize.GetX();
  2144. offsets.m_right = 0.0f;
  2145. }
  2146. }
  2147. else
  2148. {
  2149. offsets.m_left = 0.0f;
  2150. offsets.m_right = 0.0f;
  2151. }
  2152. }
  2153. UiTransform2dBus::Event(contentParentEntity->GetId(), &UiTransform2dBus::Events::SetOffsets, offsets);
  2154. }
  2155. }
  2156. }
  2157. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2158. void UiScrollBoxComponent::ContentOrParentSizeChanged()
  2159. {
  2160. // Initialize content parent offsets if they are being controlled by scrollbar visibility behavior.
  2161. // Offsets are initialized as if scrollbars are not visible
  2162. UpdateContentParentOffsets(false);
  2163. // Set whether scrollbars are visible based on scrollbar visibility behavior, content size and the size of its parent
  2164. UpdateScrollBarVisiblity();
  2165. // Set scrollbar anchors and offsets based on scrollbar visibility behavior and whether the other scrollbar is visible
  2166. UpdateScrollBarAnchorsAndOffsets();
  2167. // Set content parent offsets based on scrollbar visibility behavior and whether scrollbars are visible
  2168. UpdateContentParentOffsets(true);
  2169. // Notify listeners of ratio change between content size and the size of its parent
  2170. AZ::Vector2 parentToContentRatio;
  2171. bool result = GetScrollableParentToContentRatio(parentToContentRatio);
  2172. if (result)
  2173. {
  2174. UiScrollableToScrollerNotificationBus::Event(
  2175. GetEntityId(), &UiScrollableToScrollerNotificationBus::Events::OnScrollableParentToContentRatioChanged, parentToContentRatio);
  2176. }
  2177. if (DoSnap())
  2178. {
  2179. // Reset drag info
  2180. if (m_isDragging)
  2181. {
  2182. m_pressedScrollOffset = m_scrollOffset;
  2183. m_pressedPoint = m_lastDragPoint;
  2184. }
  2185. NotifyScrollersOnValueChanged();
  2186. DoChangedActions();
  2187. }
  2188. else
  2189. {
  2190. NotifyScrollersOnValueChanged();
  2191. }
  2192. }
  2193. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2194. // PRIVATE STATIC MEMBER FUNCTIONS
  2195. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2196. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2197. bool UiScrollBoxComponent::VersionConverter(AZ::SerializeContext& context,
  2198. AZ::SerializeContext::DataElementNode& classElement)
  2199. {
  2200. // conversion from version 1 to 2:
  2201. // - Need to convert AZStd::string sprites to AzFramework::SimpleAssetReference<LmbrCentral::TextureAsset>
  2202. if (classElement.GetVersion() < 2)
  2203. {
  2204. if (!LyShine::ConvertSubElementFromAzStringToAssetRef<LmbrCentral::TextureAsset>(context, classElement, "SelectedSprite"))
  2205. {
  2206. return false;
  2207. }
  2208. if (!LyShine::ConvertSubElementFromAzStringToAssetRef<LmbrCentral::TextureAsset>(context, classElement, "DisabledSprite"))
  2209. {
  2210. return false;
  2211. }
  2212. }
  2213. // Conversion from version 2 to 3:
  2214. if (classElement.GetVersion() < 3)
  2215. {
  2216. // find the base class (AZ::Component)
  2217. // NOTE: in very old versions there may not be a base class because the base class was not serialized
  2218. int componentBaseClassIndex = classElement.FindElement(AZ_CRC("BaseClass1", 0xd4925735));
  2219. // If there was a base class, make a copy and remove it
  2220. AZ::SerializeContext::DataElementNode componentBaseClassNode;
  2221. if (componentBaseClassIndex != -1)
  2222. {
  2223. // make a local copy of the component base class node
  2224. componentBaseClassNode = classElement.GetSubElement(componentBaseClassIndex);
  2225. // remove the component base class from the button
  2226. classElement.RemoveElement(componentBaseClassIndex);
  2227. }
  2228. // Add a new base class (UiInteractableComponent)
  2229. int interactableBaseClassIndex = classElement.AddElement<UiInteractableComponent>(context, "BaseClass1");
  2230. AZ::SerializeContext::DataElementNode& interactableBaseClassNode = classElement.GetSubElement(interactableBaseClassIndex);
  2231. // if there was previously a base class...
  2232. if (componentBaseClassIndex != -1)
  2233. {
  2234. // copy the component base class into the new interactable base class
  2235. // Since AZ::Component is now the base class of UiInteractableComponent
  2236. interactableBaseClassNode.AddElement(componentBaseClassNode);
  2237. }
  2238. // Move the selected/hover state to the base class
  2239. if (!UiSerialize::MoveToInteractableStateActions(context, classElement, "HoverStateActions",
  2240. "SelectedColor", "SelectedAlpha", "SelectedSprite"))
  2241. {
  2242. return false;
  2243. }
  2244. // Move the disabled state to the base class
  2245. if (!UiSerialize::MoveToInteractableStateActions(context, classElement, "DisabledStateActions",
  2246. "DisabledColor", "DisabledAlpha", "DisabledSprite"))
  2247. {
  2248. return false;
  2249. }
  2250. }
  2251. // Conversion from version 3 to 4:
  2252. // - Need to convert Vec2 to AZ::Vector2
  2253. if (classElement.GetVersion() < 4)
  2254. {
  2255. if (!LyShine::ConvertSubElementFromVec2ToVector2(context, classElement, "ScrollOffset"))
  2256. {
  2257. return false;
  2258. }
  2259. if (!LyShine::ConvertSubElementFromVec2ToVector2(context, classElement, "SnapGrid"))
  2260. {
  2261. return false;
  2262. }
  2263. }
  2264. return true;
  2265. }