1#include "touch_controls.h"
2
3#include <base/color.h>
4#include <base/dbg.h>
5#include <base/io.h>
6#include <base/log.h>
7#include <base/str.h>
8#include <base/time.h>
9
10#include <engine/client.h>
11#include <engine/console.h>
12#include <engine/external/json-parser/json.h>
13#include <engine/shared/config.h>
14#include <engine/shared/json.h>
15#include <engine/shared/jsonwriter.h>
16#include <engine/shared/localization.h>
17
18#include <game/client/components/camera.h>
19#include <game/client/components/chat.h>
20#include <game/client/components/console.h>
21#include <game/client/components/controls.h>
22#include <game/client/components/emoticon.h>
23#include <game/client/components/menus.h>
24#include <game/client/components/spectator.h>
25#include <game/client/components/voting.h>
26#include <game/client/gameclient.h>
27#include <game/localization.h>
28
29#include <algorithm>
30#include <cstdlib>
31#include <functional>
32#include <iterator>
33#include <queue>
34
35using namespace std::chrono_literals;
36
37// TODO: Add combined weapon picker button that shows all currently available weapons
38// TODO: Add "joystick-aim-relative", a virtual joystick that moves the mouse pointer relatively. And add "aim-relative" ingame direct touch input.
39// TODO: Add "choice" predefined behavior which shows a selection popup for 2 or more other behaviors?
40// TODO: Support changing labels of menu buttons (or support overriding label for all predefined button behaviors)?
41
42static constexpr const char *const ACTION_NAMES[] = {Localizable(pStr: "Aim"), Localizable(pStr: "Fire"), Localizable(pStr: "Hook")};
43static constexpr const char *const ACTION_SWAP_NAMES[] = {/* unused */ "", Localizable(pStr: "Active: Fire"), Localizable(pStr: "Active: Hook")};
44static constexpr const char *const ACTION_COMMANDS[] = {/* unused */ "", "+fire", "+hook"};
45
46static constexpr std::chrono::milliseconds LONG_TOUCH_DURATION = 500ms;
47static constexpr std::chrono::milliseconds BIND_REPEAT_INITIAL_DELAY = 250ms;
48static constexpr std::chrono::nanoseconds BIND_REPEAT_RATE = std::chrono::nanoseconds(1s) / 15;
49
50static constexpr const char *const CONFIGURATION_FILENAME = "touch_controls.json";
51
52/* This is required for the localization script to find the labels of the default bind buttons specified in the configuration file:
53Localizable("Move left") Localizable("Move right") Localizable("Jump") Localizable("Prev. weapon") Localizable("Next weapon")
54Localizable("Zoom out") Localizable("Default zoom") Localizable("Zoom in") Localizable("Scoreboard") Localizable("Chat") Localizable("Team chat")
55Localizable("Vote yes") Localizable("Vote no") Localizable("Toggle dummy")
56*/
57
58CTouchControls::CTouchButton::CTouchButton(CTouchControls *pTouchControls) :
59 m_pTouchControls(pTouchControls),
60 m_UnitRect({.m_X: 0, .m_Y: 0, .m_W: BUTTON_SIZE_MINIMUM, .m_H: BUTTON_SIZE_MINIMUM}),
61 m_Shape(EButtonShape::RECT),
62 m_pBehavior(nullptr),
63 m_VisibilityCached(false)
64{
65}
66
67CTouchControls::CTouchButton::CTouchButton(CTouchButton &&Other) noexcept :
68 m_pTouchControls(Other.m_pTouchControls),
69 m_UnitRect(Other.m_UnitRect),
70 m_Shape(Other.m_Shape),
71 m_vVisibilities(Other.m_vVisibilities),
72 m_pBehavior(std::move(Other.m_pBehavior)),
73 m_VisibilityCached(false)
74{
75 Other.m_pTouchControls = nullptr;
76 UpdatePointers();
77 UpdateScreenFromUnitRect();
78}
79
80CTouchControls::CTouchButton &CTouchControls::CTouchButton::operator=(CTouchButton &&Other) noexcept
81{
82 if(this == &Other)
83 {
84 return *this;
85 }
86 m_pTouchControls = Other.m_pTouchControls;
87 Other.m_pTouchControls = nullptr;
88 m_UnitRect = Other.m_UnitRect;
89 m_Shape = Other.m_Shape;
90 m_vVisibilities = Other.m_vVisibilities;
91 m_pBehavior = std::move(Other.m_pBehavior);
92 m_VisibilityCached = false;
93 UpdatePointers();
94 UpdateScreenFromUnitRect();
95 return *this;
96}
97
98void CTouchControls::CTouchButton::UpdatePointers()
99{
100 m_pBehavior->Init(pTouchButton: this);
101}
102
103void CTouchControls::CTouchButton::UpdateScreenFromUnitRect()
104{
105 m_ScreenRect = m_pTouchControls->CalculateScreenFromUnitRect(Unit: m_UnitRect, Shape: m_Shape);
106}
107
108CUIRect CTouchControls::CalculateScreenFromUnitRect(CUnitRect Unit, EButtonShape Shape) const
109{
110 Unit = CalculateHitbox(Rect: Unit, Shape);
111 const vec2 ScreenSize = CalculateScreenSize();
112 CUIRect ScreenRect;
113 ScreenRect.x = Unit.m_X * ScreenSize.x / BUTTON_SIZE_SCALE;
114 ScreenRect.y = Unit.m_Y * ScreenSize.y / BUTTON_SIZE_SCALE;
115 ScreenRect.w = Unit.m_W * ScreenSize.x / BUTTON_SIZE_SCALE;
116 ScreenRect.h = Unit.m_H * ScreenSize.y / BUTTON_SIZE_SCALE;
117 return ScreenRect;
118}
119
120CTouchControls::CUnitRect CTouchControls::CalculateHitbox(const CUnitRect &Rect, EButtonShape Shape) const
121{
122 switch(Shape)
123 {
124 case EButtonShape::RECT: return Rect;
125 case EButtonShape::CIRCLE:
126 {
127 const vec2 ScreenSize = CalculateScreenSize();
128 CUnitRect Hitbox = Rect;
129 if(ScreenSize.x * Rect.m_W < ScreenSize.y * Rect.m_H)
130 {
131 Hitbox.m_Y += (ScreenSize.y * Rect.m_H - ScreenSize.x * Rect.m_W) / 2 / ScreenSize.y;
132 Hitbox.m_H = ScreenSize.x * Rect.m_W / ScreenSize.y;
133 }
134 else if(ScreenSize.x * Rect.m_W > ScreenSize.y * Rect.m_H)
135 {
136 Hitbox.m_X += (ScreenSize.x * Rect.m_W - ScreenSize.y * Rect.m_H) / 2 / ScreenSize.x;
137 Hitbox.m_W = ScreenSize.y * Rect.m_H / ScreenSize.x;
138 }
139 return Hitbox;
140 }
141 default: dbg_assert_failed("Unhandled shape");
142 }
143}
144
145void CTouchControls::CTouchButton::UpdateBackgroundCorners()
146{
147 if(m_Shape != EButtonShape::RECT)
148 {
149 m_BackgroundCorners = IGraphics::CORNER_NONE;
150 return;
151 }
152
153 // Determine rounded corners based on button layout
154 m_BackgroundCorners = IGraphics::CORNER_ALL;
155
156 if(m_UnitRect.m_X == 0)
157 {
158 m_BackgroundCorners &= ~IGraphics::CORNER_L;
159 }
160 if(m_UnitRect.m_X + m_UnitRect.m_W == BUTTON_SIZE_SCALE)
161 {
162 m_BackgroundCorners &= ~IGraphics::CORNER_R;
163 }
164 if(m_UnitRect.m_Y == 0)
165 {
166 m_BackgroundCorners &= ~IGraphics::CORNER_T;
167 }
168 if(m_UnitRect.m_Y + m_UnitRect.m_H == BUTTON_SIZE_SCALE)
169 {
170 m_BackgroundCorners &= ~IGraphics::CORNER_B;
171 }
172
173 const auto &&PointInOrOnRect = [](ivec2 Point, CUnitRect Rect) {
174 return Point.x >= Rect.m_X && Point.x <= Rect.m_X + Rect.m_W && Point.y >= Rect.m_Y && Point.y <= Rect.m_Y + Rect.m_H;
175 };
176 for(const CTouchButton &OtherButton : m_pTouchControls->m_vTouchButtons)
177 {
178 if(&OtherButton == this || OtherButton.m_Shape != EButtonShape::RECT || !OtherButton.IsVisible())
179 continue;
180
181 if((m_BackgroundCorners & IGraphics::CORNER_TL) && PointInOrOnRect(ivec2(m_UnitRect.m_X, m_UnitRect.m_Y), OtherButton.m_UnitRect))
182 {
183 m_BackgroundCorners &= ~IGraphics::CORNER_TL;
184 }
185 if((m_BackgroundCorners & IGraphics::CORNER_TR) && PointInOrOnRect(ivec2(m_UnitRect.m_X + m_UnitRect.m_W, m_UnitRect.m_Y), OtherButton.m_UnitRect))
186 {
187 m_BackgroundCorners &= ~IGraphics::CORNER_TR;
188 }
189 if((m_BackgroundCorners & IGraphics::CORNER_BL) && PointInOrOnRect(ivec2(m_UnitRect.m_X, m_UnitRect.m_Y + m_UnitRect.m_H), OtherButton.m_UnitRect))
190 {
191 m_BackgroundCorners &= ~IGraphics::CORNER_BL;
192 }
193 if((m_BackgroundCorners & IGraphics::CORNER_BR) && PointInOrOnRect(ivec2(m_UnitRect.m_X + m_UnitRect.m_W, m_UnitRect.m_Y + m_UnitRect.m_H), OtherButton.m_UnitRect))
194 {
195 m_BackgroundCorners &= ~IGraphics::CORNER_BR;
196 }
197 if(m_BackgroundCorners == IGraphics::CORNER_NONE)
198 {
199 break;
200 }
201 }
202}
203
204vec2 CTouchControls::CTouchButton::ClampTouchPosition(vec2 TouchPosition) const
205{
206 switch(m_Shape)
207 {
208 case EButtonShape::RECT:
209 {
210 TouchPosition.x = std::clamp(val: TouchPosition.x, lo: m_ScreenRect.x, hi: m_ScreenRect.x + m_ScreenRect.w);
211 TouchPosition.y = std::clamp(val: TouchPosition.y, lo: m_ScreenRect.y, hi: m_ScreenRect.y + m_ScreenRect.h);
212 break;
213 }
214 case EButtonShape::CIRCLE:
215 {
216 const vec2 Center = m_ScreenRect.Center();
217 const float MaxLength = std::min(a: m_ScreenRect.w, b: m_ScreenRect.h) / 2.0f;
218 const vec2 TouchDirection = TouchPosition - Center;
219 const float Length = length(a: TouchDirection);
220 if(Length > MaxLength)
221 {
222 TouchPosition = normalize_pre_length(v: TouchDirection, len: Length) * MaxLength + Center;
223 }
224 break;
225 }
226 default:
227 dbg_assert_failed("Unhandled shape");
228 }
229 return TouchPosition;
230}
231
232bool CTouchControls::CTouchButton::IsInside(vec2 TouchPosition) const
233{
234 switch(m_Shape)
235 {
236 case EButtonShape::RECT:
237 return m_ScreenRect.Inside(Point: TouchPosition);
238 case EButtonShape::CIRCLE:
239 return distance(a: TouchPosition, b: m_ScreenRect.Center()) <= std::min(a: m_ScreenRect.w, b: m_ScreenRect.h) / 2.0f;
240 default:
241 dbg_assert_failed("Unhandled shape");
242 return false;
243 }
244}
245
246void CTouchControls::CTouchButton::UpdateVisibilityGame()
247{
248 const bool PrevVisibility = m_VisibilityCached;
249 m_VisibilityCached = std::all_of(first: m_vVisibilities.begin(), last: m_vVisibilities.end(), pred: [&](CButtonVisibility Visibility) {
250 return m_pTouchControls->m_aVisibilityFunctions[(int)Visibility.m_Type].m_Function() == Visibility.m_Parity;
251 });
252 if(m_VisibilityCached && !PrevVisibility)
253 {
254 m_VisibilityStartTime = time_get_nanoseconds();
255 }
256}
257
258void CTouchControls::CTouchButton::UpdateVisibilityEditor()
259{
260 const bool PrevVisibility = m_VisibilityCached;
261 m_VisibilityCached = std::all_of(first: m_vVisibilities.begin(), last: m_vVisibilities.end(), pred: [&](CButtonVisibility Visibility) {
262 return m_pTouchControls->m_aVirtualVisibilities[(int)Visibility.m_Type] == Visibility.m_Parity;
263 });
264 if(m_VisibilityCached && !PrevVisibility)
265 {
266 m_VisibilityStartTime = time_get_nanoseconds();
267 }
268}
269
270bool CTouchControls::CTouchButton::IsVisible() const
271{
272 return m_VisibilityCached;
273}
274
275// TODO: Optimization: Use text and quad containers for rendering
276void CTouchControls::CTouchButton::Render(std::optional<bool> Selected, std::optional<CUnitRect> Rect) const
277{
278 dbg_assert(m_pBehavior != nullptr, "Touch button behavior is nullptr");
279 CUIRect ScreenRect;
280 if(Rect.has_value())
281 ScreenRect = m_pTouchControls->CalculateScreenFromUnitRect(Unit: *Rect, Shape: m_Shape);
282 else
283 ScreenRect = m_ScreenRect;
284
285 ColorRGBA ButtonColor;
286 // "Selected" can decide which color to use, while not disturbing the original color check.
287 ButtonColor = m_pBehavior->IsActive() || Selected.value_or(u: false) ? m_pTouchControls->m_BackgroundColorActive : m_pTouchControls->m_BackgroundColorInactive;
288 if(!Selected.value_or(u: true))
289 ButtonColor = m_pTouchControls->m_BackgroundColorInactive;
290 switch(m_Shape)
291 {
292 case EButtonShape::RECT:
293 {
294 ScreenRect.Draw(Color: ButtonColor, Corners: m_pTouchControls->m_EditingActive ? IGraphics::CORNER_NONE : m_BackgroundCorners, Rounding: 10.0f);
295 break;
296 }
297 case EButtonShape::CIRCLE:
298 {
299 const vec2 Center = ScreenRect.Center();
300 const float Radius = std::min(a: ScreenRect.w, b: ScreenRect.h) / 2.0f;
301 m_pTouchControls->Graphics()->TextureClear();
302 m_pTouchControls->Graphics()->QuadsBegin();
303 m_pTouchControls->Graphics()->SetColor(ButtonColor);
304 m_pTouchControls->Graphics()->DrawCircle(CenterX: Center.x, CenterY: Center.y, Radius, Segments: std::max(a: round_truncate(f: Radius / 4.0f) & ~1, b: 32));
305 m_pTouchControls->Graphics()->QuadsEnd();
306 break;
307 }
308 default:
309 dbg_assert_failed("Unhandled shape");
310 }
311
312 const float FontSize = 22.0f;
313 CButtonLabel LabelData = m_pBehavior->GetLabel();
314 CUIRect LabelRect;
315 ScreenRect.Margin(Cut: 10.0f, pOtherRect: &LabelRect);
316 SLabelProperties LabelProps;
317 LabelProps.m_MaxWidth = LabelRect.w;
318 if(LabelData.m_Type == CButtonLabel::EType::ICON)
319 {
320 m_pTouchControls->TextRender()->SetFontPreset(EFontPreset::ICON_FONT);
321 m_pTouchControls->TextRender()->SetRenderFlags(ETextRenderFlags::TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH | ETextRenderFlags::TEXT_RENDER_FLAG_NO_X_BEARING | ETextRenderFlags::TEXT_RENDER_FLAG_NO_Y_BEARING);
322 m_pTouchControls->Ui()->DoLabel(pRect: &LabelRect, pText: LabelData.m_pLabel, Size: FontSize, Align: TEXTALIGN_MC, LabelProps);
323 m_pTouchControls->TextRender()->SetRenderFlags(0);
324 m_pTouchControls->TextRender()->SetFontPreset(EFontPreset::DEFAULT_FONT);
325 }
326 else
327 {
328 const char *pLabel = LabelData.m_Type == CButtonLabel::EType::LOCALIZED ? Localize(pStr: LabelData.m_pLabel) : LabelData.m_pLabel;
329 m_pTouchControls->Ui()->DoLabel(pRect: &LabelRect, pText: pLabel, Size: FontSize, Align: TEXTALIGN_MC, LabelProps);
330 }
331}
332
333void CTouchControls::CTouchButton::WriteToConfiguration(CJsonWriter *pWriter)
334{
335 char aBuf[256];
336
337 pWriter->BeginObject();
338
339 pWriter->WriteAttribute(pName: "x");
340 pWriter->WriteIntValue(Value: m_UnitRect.m_X);
341 pWriter->WriteAttribute(pName: "y");
342 pWriter->WriteIntValue(Value: m_UnitRect.m_Y);
343 pWriter->WriteAttribute(pName: "w");
344 pWriter->WriteIntValue(Value: m_UnitRect.m_W);
345 pWriter->WriteAttribute(pName: "h");
346 pWriter->WriteIntValue(Value: m_UnitRect.m_H);
347
348 pWriter->WriteAttribute(pName: "shape");
349 pWriter->WriteStrValue(pValue: SHAPE_NAMES[(int)m_Shape]);
350
351 pWriter->WriteAttribute(pName: "visibilities");
352 pWriter->BeginArray();
353 for(CButtonVisibility Visibility : m_vVisibilities)
354 {
355 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%s%s", Visibility.m_Parity ? "" : "-", m_pTouchControls->m_aVisibilityFunctions[(int)Visibility.m_Type].m_pId);
356 pWriter->WriteStrValue(pValue: aBuf);
357 }
358 pWriter->EndArray();
359
360 pWriter->WriteAttribute(pName: "behavior");
361 pWriter->BeginObject();
362 m_pBehavior->WriteToConfiguration(pWriter);
363 pWriter->EndObject();
364
365 pWriter->EndObject();
366}
367
368void CTouchControls::CTouchButtonBehavior::Init(CTouchButton *pTouchButton)
369{
370 m_pTouchButton = pTouchButton;
371 m_pTouchControls = pTouchButton->m_pTouchControls;
372}
373
374void CTouchControls::CTouchButtonBehavior::Reset()
375{
376 m_Active = false;
377}
378
379void CTouchControls::CTouchButtonBehavior::SetActive(const IInput::CTouchFingerState &FingerState)
380{
381 const vec2 ScreenSize = m_pTouchControls->CalculateScreenSize();
382 const CUIRect ButtonScreenRect = m_pTouchButton->m_ScreenRect;
383 const vec2 Position = (m_pTouchButton->ClampTouchPosition(TouchPosition: FingerState.m_Position * ScreenSize) - ButtonScreenRect.TopLeft()) / ButtonScreenRect.Size();
384 const vec2 Delta = FingerState.m_Delta * ScreenSize / ButtonScreenRect.Size();
385 if(!m_Active)
386 {
387 m_Active = true;
388 m_ActivePosition = Position;
389 m_AccumulatedDelta = Delta;
390 m_ActivationStartTime = time_get_nanoseconds();
391 m_Finger = FingerState.m_Finger;
392 OnActivate();
393 }
394 else if(m_Finger == FingerState.m_Finger)
395 {
396 m_ActivePosition = Position;
397 m_AccumulatedDelta += Delta;
398 OnUpdate();
399 }
400 else
401 {
402 dbg_assert_failed("Touch button must be inactive or use same finger");
403 }
404}
405
406void CTouchControls::CTouchButtonBehavior::SetInactive(bool ByFinger)
407{
408 if(m_Active)
409 {
410 m_Active = false;
411 OnDeactivate(ByFinger);
412 }
413}
414
415bool CTouchControls::CTouchButtonBehavior::IsActive() const
416{
417 return m_Active;
418}
419
420bool CTouchControls::CTouchButtonBehavior::IsActive(const IInput::CTouchFinger &Finger) const
421{
422 return m_Active && m_Finger == Finger;
423}
424
425void CTouchControls::CPredefinedTouchButtonBehavior::WriteToConfiguration(CJsonWriter *pWriter)
426{
427 pWriter->WriteAttribute(pName: "type");
428 pWriter->WriteStrValue(pValue: BEHAVIOR_TYPE);
429
430 pWriter->WriteAttribute(pName: "id");
431 pWriter->WriteStrValue(pValue: m_pId);
432}
433
434// Ingame menu button: always opens ingame menu.
435CTouchControls::CButtonLabel CTouchControls::CIngameMenuTouchButtonBehavior::GetLabel() const
436{
437 return {.m_Type: CButtonLabel::EType::ICON, .m_pLabel: "\xEF\x85\x8E"};
438}
439
440void CTouchControls::CIngameMenuTouchButtonBehavior::OnDeactivate(bool ByFinger)
441{
442 if(!ByFinger)
443 return;
444 m_pTouchControls->GameClient()->m_Menus.SetActive(true);
445}
446
447// Extra menu button:
448// - Short press: show/hide additional buttons (toggle extra-menu visibilities)
449// - Long press: open ingame menu
450CTouchControls::CExtraMenuTouchButtonBehavior::CExtraMenuTouchButtonBehavior(int Number) :
451 CPredefinedTouchButtonBehavior(BEHAVIOR_ID),
452 m_Number(Number)
453{
454 if(m_Number == 0)
455 {
456 str_copy(dst&: m_aLabel, src: "\xEF\x83\x89");
457 }
458 else
459 {
460 str_format(buffer: m_aLabel, buffer_size: sizeof(m_aLabel), format: "\xEF\x83\x89%d", m_Number + 1);
461 }
462}
463
464CTouchControls::CButtonLabel CTouchControls::CExtraMenuTouchButtonBehavior::GetLabel() const
465{
466 if(m_Active && time_get_nanoseconds() - m_ActivationStartTime >= LONG_TOUCH_DURATION)
467 {
468 return {.m_Type: CButtonLabel::EType::ICON, .m_pLabel: "\xEF\x95\x90"};
469 }
470 else
471 {
472 return {.m_Type: CButtonLabel::EType::ICON, .m_pLabel: m_aLabel};
473 }
474}
475
476void CTouchControls::CExtraMenuTouchButtonBehavior::OnDeactivate(bool ByFinger)
477{
478 if(!ByFinger)
479 return;
480 if(time_get_nanoseconds() - m_ActivationStartTime >= LONG_TOUCH_DURATION)
481 {
482 m_pTouchControls->GameClient()->m_Menus.SetActive(true);
483 }
484 else
485 {
486 m_pTouchControls->m_aExtraMenuActive[m_Number] = !m_pTouchControls->m_aExtraMenuActive[m_Number];
487 }
488}
489
490void CTouchControls::CExtraMenuTouchButtonBehavior::WriteToConfiguration(CJsonWriter *pWriter)
491{
492 CPredefinedTouchButtonBehavior::WriteToConfiguration(pWriter);
493
494 pWriter->WriteAttribute(pName: "number");
495 pWriter->WriteIntValue(Value: m_Number + 1);
496}
497
498// Emoticon button: keeps the emoticon HUD open, next touch in emoticon HUD will close it again.
499CTouchControls::CButtonLabel CTouchControls::CEmoticonTouchButtonBehavior::GetLabel() const
500{
501 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: Localizable(pStr: "Emoticon")};
502}
503
504void CTouchControls::CEmoticonTouchButtonBehavior::OnDeactivate(bool ByFinger)
505{
506 if(!ByFinger)
507 return;
508 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 1, pStr: "+emote", ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
509}
510
511// Spectate button: keeps the spectate menu open, next touch in spectate menu will close it again.
512CTouchControls::CButtonLabel CTouchControls::CSpectateTouchButtonBehavior::GetLabel() const
513{
514 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: Localizable(pStr: "Spectator mode")};
515}
516
517void CTouchControls::CSpectateTouchButtonBehavior::OnDeactivate(bool ByFinger)
518{
519 if(!ByFinger)
520 return;
521 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 1, pStr: "+spectate", ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
522}
523
524// Swap action button:
525// - If joystick is currently active with one action: activate the other action.
526// - Else: swap active action.
527CTouchControls::CButtonLabel CTouchControls::CSwapActionTouchButtonBehavior::GetLabel() const
528{
529 if(m_ActiveAction != NUM_ACTIONS)
530 {
531 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: ACTION_NAMES[m_ActiveAction]};
532 }
533 else if(m_pTouchControls->m_JoystickPressCount != 0)
534 {
535 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: ACTION_NAMES[m_pTouchControls->NextActiveAction(Action: m_pTouchControls->m_ActionSelected)]};
536 }
537 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: ACTION_SWAP_NAMES[m_pTouchControls->m_ActionSelected]};
538}
539
540void CTouchControls::CSwapActionTouchButtonBehavior::OnActivate()
541{
542 if(m_pTouchControls->m_JoystickPressCount != 0)
543 {
544 m_ActiveAction = m_pTouchControls->NextActiveAction(Action: m_pTouchControls->m_ActionSelected);
545 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 1, pStr: ACTION_COMMANDS[m_ActiveAction], ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
546 }
547 else
548 {
549 m_pTouchControls->m_ActionSelected = m_pTouchControls->NextActiveAction(Action: m_pTouchControls->m_ActionSelected);
550 }
551}
552
553void CTouchControls::CSwapActionTouchButtonBehavior::OnDeactivate(bool ByFinger)
554{
555 if(m_ActiveAction != NUM_ACTIONS)
556 {
557 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 0, pStr: ACTION_COMMANDS[m_ActiveAction], ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
558 m_ActiveAction = NUM_ACTIONS;
559 }
560}
561
562// Use action button: always uses the active action.
563CTouchControls::CButtonLabel CTouchControls::CUseActionTouchButtonBehavior::GetLabel() const
564{
565 if(m_ActiveAction != NUM_ACTIONS)
566 {
567 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: ACTION_NAMES[m_ActiveAction]};
568 }
569 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: ACTION_NAMES[m_pTouchControls->m_ActionSelected]};
570}
571
572void CTouchControls::CUseActionTouchButtonBehavior::OnActivate()
573{
574 m_ActiveAction = m_pTouchControls->m_ActionSelected;
575 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 1, pStr: ACTION_COMMANDS[m_ActiveAction], ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
576}
577
578void CTouchControls::CUseActionTouchButtonBehavior::OnDeactivate(bool ByFinger)
579{
580 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 0, pStr: ACTION_COMMANDS[m_ActiveAction], ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
581 m_ActiveAction = NUM_ACTIONS;
582}
583
584// Generic joystick button behavior: aim with virtual joystick and use action (defined by subclass).
585CTouchControls::CButtonLabel CTouchControls::CJoystickTouchButtonBehavior::GetLabel() const
586{
587 if(m_ActiveAction != NUM_ACTIONS)
588 {
589 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: ACTION_NAMES[m_ActiveAction]};
590 }
591 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: ACTION_NAMES[SelectedAction()]};
592}
593
594void CTouchControls::CJoystickTouchButtonBehavior::OnActivate()
595{
596 m_ActiveAction = SelectedAction();
597 OnUpdate();
598 if(m_ActiveAction != ACTION_AIM)
599 {
600 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 1, pStr: ACTION_COMMANDS[m_ActiveAction], ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
601 }
602 m_pTouchControls->m_JoystickPressCount++;
603}
604
605void CTouchControls::CJoystickTouchButtonBehavior::OnDeactivate(bool ByFinger)
606{
607 if(m_ActiveAction != ACTION_AIM)
608 {
609 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 0, pStr: ACTION_COMMANDS[m_ActiveAction], ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
610 }
611 m_ActiveAction = NUM_ACTIONS;
612 m_pTouchControls->m_JoystickPressCount--;
613}
614
615void CTouchControls::CJoystickTouchButtonBehavior::OnUpdate()
616{
617 CControls &Controls = m_pTouchControls->GameClient()->m_Controls;
618 if(m_pTouchControls->GameClient()->m_Snap.m_SpecInfo.m_Active)
619 {
620 vec2 WorldScreenSize;
621 m_pTouchControls->Graphics()->CalcScreenParams(Aspect: m_pTouchControls->Graphics()->ScreenAspect(), Zoom: m_pTouchControls->GameClient()->m_Camera.m_Zoom, pWidth: &WorldScreenSize.x, pHeight: &WorldScreenSize.y);
622 Controls.m_aMousePos[g_Config.m_ClDummy] += -m_AccumulatedDelta * WorldScreenSize;
623 Controls.m_aMouseInputType[g_Config.m_ClDummy] = CControls::EMouseInputType::RELATIVE;
624 Controls.m_aMousePos[g_Config.m_ClDummy].x = std::clamp(val: Controls.m_aMousePos[g_Config.m_ClDummy].x, lo: -201.0f * 32, hi: (m_pTouchControls->Collision()->GetWidth() + 201.0f) * 32.0f);
625 Controls.m_aMousePos[g_Config.m_ClDummy].y = std::clamp(val: Controls.m_aMousePos[g_Config.m_ClDummy].y, lo: -201.0f * 32, hi: (m_pTouchControls->Collision()->GetHeight() + 201.0f) * 32.0f);
626 m_AccumulatedDelta = vec2(0.0f, 0.0f);
627 }
628 else
629 {
630 const vec2 AbsolutePosition = (m_ActivePosition - vec2(0.5f, 0.5f)) * 2.0f;
631 Controls.m_aMousePos[g_Config.m_ClDummy] = AbsolutePosition * (Controls.GetMaxMouseDistance() - Controls.GetMinMouseDistance()) + normalize(v: AbsolutePosition) * Controls.GetMinMouseDistance();
632 Controls.m_aMouseInputType[g_Config.m_ClDummy] = CControls::EMouseInputType::ABSOLUTE;
633 if(length(a: Controls.m_aMousePos[g_Config.m_ClDummy]) < 0.001f)
634 {
635 Controls.m_aMousePos[g_Config.m_ClDummy].x = 0.001f;
636 Controls.m_aMousePos[g_Config.m_ClDummy].y = 0.0f;
637 }
638 }
639}
640
641// Joystick that uses the active action.
642int CTouchControls::CJoystickActionTouchButtonBehavior::SelectedAction() const
643{
644 return m_pTouchControls->m_ActionSelected;
645}
646
647// Joystick that only aims.
648int CTouchControls::CJoystickAimTouchButtonBehavior::SelectedAction() const
649{
650 return ACTION_AIM;
651}
652
653// Joystick that always uses fire.
654int CTouchControls::CJoystickFireTouchButtonBehavior::SelectedAction() const
655{
656 return ACTION_FIRE;
657}
658
659// Joystick that always uses hook.
660int CTouchControls::CJoystickHookTouchButtonBehavior::SelectedAction() const
661{
662 return ACTION_HOOK;
663}
664
665// Bind button behavior that executes a command like a bind.
666CTouchControls::CButtonLabel CTouchControls::CBindTouchButtonBehavior::GetLabel() const
667{
668 return {.m_Type: m_LabelType, .m_pLabel: m_Label.c_str()};
669}
670
671void CTouchControls::CBindTouchButtonBehavior::OnActivate()
672{
673 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 1, pStr: m_Command.c_str(), ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
674 m_Repeating = false;
675}
676
677void CTouchControls::CBindTouchButtonBehavior::OnDeactivate(bool ByFinger)
678{
679 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 0, pStr: m_Command.c_str(), ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
680}
681
682void CTouchControls::CBindTouchButtonBehavior::OnUpdate()
683{
684 const auto Now = time_get_nanoseconds();
685 if(m_Repeating)
686 {
687 m_AccumulatedRepeatingTime += Now - m_LastUpdateTime;
688 m_LastUpdateTime = Now;
689 if(m_AccumulatedRepeatingTime >= BIND_REPEAT_RATE)
690 {
691 m_AccumulatedRepeatingTime -= BIND_REPEAT_RATE;
692 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 1, pStr: m_Command.c_str(), ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
693 }
694 }
695 else if(Now - m_ActivationStartTime >= BIND_REPEAT_INITIAL_DELAY)
696 {
697 m_Repeating = true;
698 m_LastUpdateTime = Now;
699 m_AccumulatedRepeatingTime = 0ns;
700 }
701}
702
703void CTouchControls::CBindTouchButtonBehavior::WriteToConfiguration(CJsonWriter *pWriter)
704{
705 pWriter->WriteAttribute(pName: "type");
706 pWriter->WriteStrValue(pValue: BEHAVIOR_TYPE);
707
708 pWriter->WriteAttribute(pName: "label");
709 pWriter->WriteStrValue(pValue: m_Label.c_str());
710
711 pWriter->WriteAttribute(pName: "label-type");
712 pWriter->WriteStrValue(pValue: LABEL_TYPE_NAMES[(int)m_LabelType]);
713
714 pWriter->WriteAttribute(pName: "command");
715 pWriter->WriteStrValue(pValue: m_Command.c_str());
716}
717
718// Bind button behavior that switches between executing one of two or more console commands.
719CTouchControls::CButtonLabel CTouchControls::CBindToggleTouchButtonBehavior::GetLabel() const
720{
721 const auto &ActiveCommand = m_vCommands[m_ActiveCommandIndex];
722 return {.m_Type: ActiveCommand.m_LabelType, .m_pLabel: ActiveCommand.m_Label.c_str()};
723}
724
725void CTouchControls::CBindToggleTouchButtonBehavior::OnActivate()
726{
727 m_pTouchControls->Console()->ExecuteLine(pStr: m_vCommands[m_ActiveCommandIndex].m_Command.c_str(), ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
728 m_ActiveCommandIndex = (m_ActiveCommandIndex + 1) % m_vCommands.size();
729}
730
731void CTouchControls::CBindToggleTouchButtonBehavior::WriteToConfiguration(CJsonWriter *pWriter)
732{
733 pWriter->WriteAttribute(pName: "type");
734 pWriter->WriteStrValue(pValue: BEHAVIOR_TYPE);
735
736 pWriter->WriteAttribute(pName: "commands");
737 pWriter->BeginArray();
738
739 for(const auto &Command : m_vCommands)
740 {
741 pWriter->BeginObject();
742
743 pWriter->WriteAttribute(pName: "label");
744 pWriter->WriteStrValue(pValue: Command.m_Label.c_str());
745
746 pWriter->WriteAttribute(pName: "label-type");
747 pWriter->WriteStrValue(pValue: LABEL_TYPE_NAMES[(int)Command.m_LabelType]);
748
749 pWriter->WriteAttribute(pName: "command");
750 pWriter->WriteStrValue(pValue: Command.m_Command.c_str());
751
752 pWriter->EndObject();
753 }
754
755 pWriter->EndArray();
756}
757
758void CTouchControls::OnInit()
759{
760 InitVisibilityFunctions();
761 if(!LoadConfigurationFromFile(StorageType: IStorage::TYPE_ALL))
762 {
763 Client()->AddWarning(Warning: SWarning(Localize(pStr: "Error loading touch controls"), Localize(pStr: "Could not load touch controls from file. See local console for details.")));
764 }
765}
766
767void CTouchControls::OnReset()
768{
769 ResetButtons();
770 m_EditingActive = false;
771}
772
773void CTouchControls::OnWindowResize()
774{
775 ResetButtons();
776 for(CTouchButton &TouchButton : m_vTouchButtons)
777 {
778 TouchButton.UpdateScreenFromUnitRect();
779 }
780}
781
782bool CTouchControls::OnTouchState(const std::vector<IInput::CTouchFingerState> &vTouchFingerStates)
783{
784 if(!g_Config.m_ClTouchControls)
785 return false;
786 if(Client()->State() != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK)
787 return false;
788 if(GameClient()->m_Chat.IsActive() ||
789 GameClient()->m_GameConsole.IsActive() ||
790 GameClient()->m_Menus.IsActive() ||
791 GameClient()->m_Emoticon.IsActive() ||
792 GameClient()->m_Spectator.IsActive() ||
793 m_PreviewAllButtons)
794 {
795 ResetButtons();
796 return false;
797 }
798
799 if(m_EditingActive)
800 UpdateButtonsEditor(vTouchFingerStates);
801 else
802 UpdateButtonsGame(vTouchFingerStates);
803 return true;
804}
805
806void CTouchControls::OnRender()
807{
808 if(!g_Config.m_ClTouchControls)
809 return;
810 if(Client()->State() != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK)
811 return;
812 if(GameClient()->m_Chat.IsActive() ||
813 GameClient()->m_Emoticon.IsActive() ||
814 GameClient()->m_Spectator.IsActive())
815 {
816 return;
817 }
818
819 const vec2 ScreenSize = CalculateScreenSize();
820 Graphics()->MapScreen(TopLeftX: 0.0f, TopLeftY: 0.0f, BottomRightX: ScreenSize.x, BottomRightY: ScreenSize.y);
821
822 if(m_EditingActive)
823 {
824 RenderButtonsEditor();
825 return;
826 }
827 // If not editing, deselect it.
828 m_pSelectedButton = nullptr;
829 m_pSampleButton = nullptr;
830 m_UnsavedChanges = false;
831 RenderButtonsGame();
832}
833
834bool CTouchControls::LoadConfigurationFromFile(int StorageType)
835{
836 void *pFileData;
837 unsigned FileLength;
838 if(!Storage()->ReadFile(pFilename: CONFIGURATION_FILENAME, Type: StorageType, ppResult: &pFileData, pResultLen: &FileLength))
839 {
840 log_error("touch_controls", "Failed to read configuration from '%s'", CONFIGURATION_FILENAME);
841 return false;
842 }
843
844 const bool Result = ParseConfiguration(pFileData, FileLength);
845 free(ptr: pFileData);
846 return Result;
847}
848
849bool CTouchControls::LoadConfigurationFromClipboard()
850{
851 std::string Clipboard = Input()->GetClipboardText();
852 return ParseConfiguration(pFileData: Clipboard.c_str(), FileLength: Clipboard.size());
853}
854
855bool CTouchControls::SaveConfigurationToFile()
856{
857 IOHANDLE File = Storage()->OpenFile(pFilename: CONFIGURATION_FILENAME, Flags: IOFLAG_WRITE, Type: IStorage::TYPE_SAVE);
858 if(!File)
859 {
860 log_error("touch_controls", "Failed to open '%s' for writing configuration", CONFIGURATION_FILENAME);
861 return false;
862 }
863
864 CJsonFileWriter Writer(File);
865 WriteConfiguration(pWriter: &Writer);
866 return true;
867}
868
869void CTouchControls::SaveConfigurationToClipboard()
870{
871 CJsonStringWriter Writer;
872 WriteConfiguration(pWriter: &Writer);
873 std::string ConfigurationString = Writer.GetOutputString();
874 Input()->SetClipboardText(ConfigurationString.c_str());
875}
876
877void CTouchControls::InitVisibilityFunctions()
878{
879 m_aVisibilityFunctions[(int)EButtonVisibility::INGAME].m_pId = "ingame";
880 m_aVisibilityFunctions[(int)EButtonVisibility::INGAME].m_Function = [&]() {
881 return !GameClient()->m_Snap.m_SpecInfo.m_Active;
882 };
883 m_aVisibilityFunctions[(int)EButtonVisibility::ZOOM_ALLOWED].m_pId = "zoom-allowed";
884 m_aVisibilityFunctions[(int)EButtonVisibility::ZOOM_ALLOWED].m_Function = [&]() {
885 return GameClient()->m_Camera.ZoomAllowed();
886 };
887 m_aVisibilityFunctions[(int)EButtonVisibility::VOTE_ACTIVE].m_pId = "vote-active";
888 m_aVisibilityFunctions[(int)EButtonVisibility::VOTE_ACTIVE].m_Function = [&]() {
889 return GameClient()->m_Voting.IsVoting();
890 };
891 m_aVisibilityFunctions[(int)EButtonVisibility::DUMMY_ALLOWED].m_pId = "dummy-allowed";
892 m_aVisibilityFunctions[(int)EButtonVisibility::DUMMY_ALLOWED].m_Function = [&]() {
893 return Client()->DummyAllowed();
894 };
895 m_aVisibilityFunctions[(int)EButtonVisibility::DUMMY_CONNECTED].m_pId = "dummy-connected";
896 m_aVisibilityFunctions[(int)EButtonVisibility::DUMMY_CONNECTED].m_Function = [&]() {
897 return Client()->DummyConnected();
898 };
899 m_aVisibilityFunctions[(int)EButtonVisibility::RCON_AUTHED].m_pId = "rcon-authed";
900 m_aVisibilityFunctions[(int)EButtonVisibility::RCON_AUTHED].m_Function = [&]() {
901 return Client()->RconAuthed();
902 };
903 m_aVisibilityFunctions[(int)EButtonVisibility::DEMO_PLAYER].m_pId = "demo-player";
904 m_aVisibilityFunctions[(int)EButtonVisibility::DEMO_PLAYER].m_Function = [&]() {
905 return Client()->State() == IClient::STATE_DEMOPLAYBACK;
906 };
907 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_1].m_pId = "extra-menu";
908 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_1].m_Function = [&]() {
909 return m_aExtraMenuActive[0];
910 };
911 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_2].m_pId = "extra-menu-2";
912 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_2].m_Function = [&]() {
913 return m_aExtraMenuActive[1];
914 };
915 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_3].m_pId = "extra-menu-3";
916 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_3].m_Function = [&]() {
917 return m_aExtraMenuActive[2];
918 };
919 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_4].m_pId = "extra-menu-4";
920 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_4].m_Function = [&]() {
921 return m_aExtraMenuActive[3];
922 };
923 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_5].m_pId = "extra-menu-5";
924 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_5].m_Function = [&]() {
925 return m_aExtraMenuActive[4];
926 };
927}
928
929int CTouchControls::NextActiveAction(int Action) const
930{
931 switch(Action)
932 {
933 case ACTION_FIRE:
934 return ACTION_HOOK;
935 case ACTION_HOOK:
936 return ACTION_FIRE;
937 default:
938 dbg_assert_failed("Action invalid for NextActiveAction");
939 }
940}
941
942int CTouchControls::NextDirectTouchAction() const
943{
944 if(GameClient()->m_Snap.m_SpecInfo.m_Active)
945 {
946 switch(m_DirectTouchSpectate)
947 {
948 case EDirectTouchSpectateMode::DISABLED:
949 return NUM_ACTIONS;
950 case EDirectTouchSpectateMode::AIM:
951 return ACTION_AIM;
952 default:
953 dbg_assert_failed("m_DirectTouchSpectate invalid");
954 }
955 }
956 else
957 {
958 switch(m_DirectTouchIngame)
959 {
960 case EDirectTouchIngameMode::DISABLED:
961 return NUM_ACTIONS;
962 case EDirectTouchIngameMode::ACTION:
963 return m_ActionSelected;
964 case EDirectTouchIngameMode::AIM:
965 return ACTION_AIM;
966 case EDirectTouchIngameMode::FIRE:
967 return ACTION_FIRE;
968 case EDirectTouchIngameMode::HOOK:
969 return ACTION_HOOK;
970 default:
971 dbg_assert_failed("m_DirectTouchIngame invalid");
972 }
973 }
974}
975
976static auto MatchFingerStateFinger(const IInput::CTouchFinger &Finger)
977{
978 return [Finger](const IInput::CTouchFingerState &TouchFingerState) {
979 return TouchFingerState.m_Finger == Finger;
980 };
981}
982
983void CTouchControls::UpdateButtonsGame(const std::vector<IInput::CTouchFingerState> &vTouchFingerStates)
984{
985 // Update cached button visibilities and store time that buttons become visible.
986 for(CTouchButton &TouchButton : m_vTouchButtons)
987 {
988 TouchButton.UpdateVisibilityGame();
989 }
990
991 const int DirectTouchAction = NextDirectTouchAction();
992 const vec2 ScreenSize = CalculateScreenSize();
993
994 std::vector<IInput::CTouchFingerState> vRemainingTouchFingerStates = vTouchFingerStates;
995
996 if(!m_vStaleFingers.empty())
997 {
998 // Remove stale fingers that are not pressed anymore.
999 m_vStaleFingers.erase(
1000 first: std::remove_if(first: m_vStaleFingers.begin(), last: m_vStaleFingers.end(), pred: [&](const IInput::CTouchFinger &Finger) {
1001 return std::find_if(first: vRemainingTouchFingerStates.begin(), last: vRemainingTouchFingerStates.end(), pred: MatchFingerStateFinger(Finger)) == vRemainingTouchFingerStates.end();
1002 }),
1003 last: m_vStaleFingers.end());
1004 // Prevent stale fingers from activating touch buttons and direct touch.
1005 vRemainingTouchFingerStates.erase(
1006 first: std::remove_if(first: vRemainingTouchFingerStates.begin(), last: vRemainingTouchFingerStates.end(), pred: [&](const IInput::CTouchFingerState &TouchFingerState) {
1007 return std::find_if(first: m_vStaleFingers.begin(), last: m_vStaleFingers.end(), pred: [&](const IInput::CTouchFinger &Finger) {
1008 return TouchFingerState.m_Finger == Finger;
1009 }) != m_vStaleFingers.end();
1010 }),
1011 last: vRemainingTouchFingerStates.end());
1012 }
1013
1014 // Remove remaining finger states for fingers which are responsible for active actions
1015 // and release action when the finger responsible for it is not pressed down anymore.
1016 bool GotDirectFingerState = false; // Whether DirectFingerState is valid
1017 IInput::CTouchFingerState DirectFingerState{}; // The finger that will be used to update the mouse position
1018 for(int Action = ACTION_AIM; Action < NUM_ACTIONS; ++Action)
1019 {
1020 if(!m_aDirectTouchActionStates[Action].m_Active)
1021 {
1022 continue;
1023 }
1024
1025 const auto ActiveFinger = std::find_if(first: vRemainingTouchFingerStates.begin(), last: vRemainingTouchFingerStates.end(), pred: MatchFingerStateFinger(Finger: m_aDirectTouchActionStates[Action].m_Finger));
1026 if(ActiveFinger == vRemainingTouchFingerStates.end() || DirectTouchAction == NUM_ACTIONS)
1027 {
1028 m_aDirectTouchActionStates[Action].m_Active = false;
1029 if(Action != ACTION_AIM)
1030 {
1031 Console()->ExecuteLineStroked(Stroke: 0, pStr: ACTION_COMMANDS[Action], ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
1032 }
1033 }
1034 else
1035 {
1036 if(Action == m_DirectTouchLastAction)
1037 {
1038 GotDirectFingerState = true;
1039 DirectFingerState = *ActiveFinger;
1040 }
1041 vRemainingTouchFingerStates.erase(position: ActiveFinger);
1042 }
1043 }
1044
1045 // Update touch button states after the active action fingers were removed from the vector
1046 // so that current cursor movement can cross over touch buttons without activating them.
1047
1048 // Activate visible, inactive buttons with hovered finger. Deactivate previous button being
1049 // activated by the same finger. Touch buttons are only activated if they became visible
1050 // before the respective touch finger was pressed down, to prevent repeatedly activating
1051 // overlapping buttons of excluding visibilities.
1052 for(CTouchButton &TouchButton : m_vTouchButtons)
1053 {
1054 if(!TouchButton.IsVisible() || TouchButton.m_pBehavior->IsActive())
1055 {
1056 continue;
1057 }
1058 const auto FingerInsideButton = std::find_if(first: vRemainingTouchFingerStates.begin(), last: vRemainingTouchFingerStates.end(), pred: [&](const IInput::CTouchFingerState &TouchFingerState) {
1059 return TouchButton.m_VisibilityStartTime < TouchFingerState.m_PressTime &&
1060 TouchButton.IsInside(TouchPosition: TouchFingerState.m_Position * ScreenSize);
1061 });
1062 if(FingerInsideButton == vRemainingTouchFingerStates.end())
1063 {
1064 continue;
1065 }
1066 const auto OtherHoveredTouchButton = std::find_if(first: m_vTouchButtons.begin(), last: m_vTouchButtons.end(), pred: [&](const CTouchButton &Button) {
1067 return &Button != &TouchButton && Button.IsVisible() && Button.IsInside(TouchPosition: FingerInsideButton->m_Position * ScreenSize);
1068 });
1069 if(OtherHoveredTouchButton != m_vTouchButtons.end())
1070 {
1071 // Do not activate any button if multiple overlapping buttons are hovered.
1072 // TODO: Prevent overlapping buttons entirely when parsing the button configuration?
1073 vRemainingTouchFingerStates.erase(position: FingerInsideButton);
1074 continue;
1075 }
1076 auto PrevActiveTouchButton = std::find_if(first: m_vTouchButtons.begin(), last: m_vTouchButtons.end(), pred: [&](const CTouchButton &Button) {
1077 return Button.m_pBehavior->IsActive(Finger: FingerInsideButton->m_Finger);
1078 });
1079 if(PrevActiveTouchButton != m_vTouchButtons.end())
1080 {
1081 PrevActiveTouchButton->m_pBehavior->SetInactive(true);
1082 }
1083 TouchButton.m_pBehavior->SetActive(*FingerInsideButton);
1084 }
1085
1086 // Deactivate touch buttons only when the respective finger is released, so touch buttons
1087 // are kept active also if the finger is moved outside the button.
1088 for(CTouchButton &TouchButton : m_vTouchButtons)
1089 {
1090 if(!TouchButton.IsVisible())
1091 {
1092 if(TouchButton.m_pBehavior->IsActive())
1093 {
1094 // Remember fingers responsible for buttons that were deactivated due to becoming invisible,
1095 // to ensure that these fingers will not activate direct touch input or touch buttons.
1096 m_vStaleFingers.push_back(x: TouchButton.m_pBehavior->m_Finger);
1097 const auto ActiveFinger = std::find_if(first: vRemainingTouchFingerStates.begin(), last: vRemainingTouchFingerStates.end(), pred: MatchFingerStateFinger(Finger: TouchButton.m_pBehavior->m_Finger));
1098 // ActiveFinger could be released during this progress.
1099 if(ActiveFinger != vRemainingTouchFingerStates.end())
1100 vRemainingTouchFingerStates.erase(position: ActiveFinger);
1101 }
1102 TouchButton.m_pBehavior->SetInactive(false);
1103 continue;
1104 }
1105 if(!TouchButton.m_pBehavior->IsActive())
1106 {
1107 continue;
1108 }
1109 const auto ActiveFinger = std::find_if(first: vRemainingTouchFingerStates.begin(), last: vRemainingTouchFingerStates.end(), pred: MatchFingerStateFinger(Finger: TouchButton.m_pBehavior->m_Finger));
1110 if(ActiveFinger == vRemainingTouchFingerStates.end())
1111 {
1112 TouchButton.m_pBehavior->SetInactive(true);
1113 }
1114 else
1115 {
1116 // Update the already active touch button with the current finger state
1117 TouchButton.m_pBehavior->SetActive(*ActiveFinger);
1118 }
1119 }
1120
1121 // Remove remaining fingers for active buttons after updating the buttons.
1122 for(CTouchButton &TouchButton : m_vTouchButtons)
1123 {
1124 if(!TouchButton.m_pBehavior->IsActive())
1125 {
1126 continue;
1127 }
1128 const auto ActiveFinger = std::find_if(first: vRemainingTouchFingerStates.begin(), last: vRemainingTouchFingerStates.end(), pred: MatchFingerStateFinger(Finger: TouchButton.m_pBehavior->m_Finger));
1129 dbg_assert(ActiveFinger != vRemainingTouchFingerStates.end(), "Active button finger not found");
1130 vRemainingTouchFingerStates.erase(position: ActiveFinger);
1131 }
1132
1133 // TODO: Support standard gesture to zoom (enabled separately for ingame and spectator)
1134
1135 // Activate action if there is an unhandled pressed down finger.
1136 int ActivateAction = NUM_ACTIONS;
1137 if(DirectTouchAction != NUM_ACTIONS && !vRemainingTouchFingerStates.empty() && !m_aDirectTouchActionStates[DirectTouchAction].m_Active)
1138 {
1139 GotDirectFingerState = true;
1140 DirectFingerState = vRemainingTouchFingerStates[0];
1141 vRemainingTouchFingerStates.erase(position: vRemainingTouchFingerStates.begin());
1142 m_aDirectTouchActionStates[DirectTouchAction].m_Active = true;
1143 m_aDirectTouchActionStates[DirectTouchAction].m_Finger = DirectFingerState.m_Finger;
1144 m_DirectTouchLastAction = DirectTouchAction;
1145 ActivateAction = DirectTouchAction;
1146 }
1147
1148 // Update mouse position based on the finger responsible for the last active action.
1149 if(GotDirectFingerState)
1150 {
1151 const float Zoom = GameClient()->m_Snap.m_SpecInfo.m_Active ? GameClient()->m_Camera.m_Zoom : 1.0f;
1152 vec2 WorldScreenSize;
1153 Graphics()->CalcScreenParams(Aspect: Graphics()->ScreenAspect(), Zoom, pWidth: &WorldScreenSize.x, pHeight: &WorldScreenSize.y);
1154 CControls &Controls = GameClient()->m_Controls;
1155 if(GameClient()->m_Snap.m_SpecInfo.m_Active)
1156 {
1157 Controls.m_aMousePos[g_Config.m_ClDummy] += -DirectFingerState.m_Delta * WorldScreenSize;
1158 Controls.m_aMouseInputType[g_Config.m_ClDummy] = CControls::EMouseInputType::RELATIVE;
1159 Controls.m_aMousePos[g_Config.m_ClDummy].x = std::clamp(val: Controls.m_aMousePos[g_Config.m_ClDummy].x, lo: -201.0f * 32, hi: (Collision()->GetWidth() + 201.0f) * 32.0f);
1160 Controls.m_aMousePos[g_Config.m_ClDummy].y = std::clamp(val: Controls.m_aMousePos[g_Config.m_ClDummy].y, lo: -201.0f * 32, hi: (Collision()->GetHeight() + 201.0f) * 32.0f);
1161 }
1162 else
1163 {
1164 Controls.m_aMousePos[g_Config.m_ClDummy] = (DirectFingerState.m_Position - vec2(0.5f, 0.5f)) * WorldScreenSize;
1165 Controls.m_aMouseInputType[g_Config.m_ClDummy] = CControls::EMouseInputType::ABSOLUTE;
1166 }
1167 }
1168
1169 // Activate action after the mouse position is set.
1170 if(ActivateAction != ACTION_AIM && ActivateAction != NUM_ACTIONS)
1171 {
1172 Console()->ExecuteLineStroked(Stroke: 1, pStr: ACTION_COMMANDS[ActivateAction], ClientId: IConsole::CLIENT_ID_UNSPECIFIED);
1173 }
1174}
1175
1176void CTouchControls::ResetButtons()
1177{
1178 for(CTouchButton &TouchButton : m_vTouchButtons)
1179 {
1180 TouchButton.m_pBehavior->Reset();
1181 }
1182 for(CActionState &ActionState : m_aDirectTouchActionStates)
1183 {
1184 ActionState.m_Active = false;
1185 }
1186}
1187
1188void CTouchControls::RenderButtonsGame()
1189{
1190 for(CTouchButton &TouchButton : m_vTouchButtons)
1191 {
1192 TouchButton.UpdateVisibilityGame();
1193 }
1194 for(CTouchButton &TouchButton : m_vTouchButtons)
1195 {
1196 if(!TouchButton.IsVisible())
1197 {
1198 continue;
1199 }
1200 TouchButton.UpdateBackgroundCorners();
1201 TouchButton.UpdateScreenFromUnitRect();
1202 TouchButton.Render();
1203 }
1204}
1205
1206vec2 CTouchControls::CalculateScreenSize() const
1207{
1208 const float ScreenHeight = 400.0f * 3.0f;
1209 const float ScreenWidth = ScreenHeight * Graphics()->ScreenAspect();
1210 return vec2(ScreenWidth, ScreenHeight);
1211}
1212
1213bool CTouchControls::ParseConfiguration(const void *pFileData, unsigned FileLength)
1214{
1215 json_settings JsonSettings{};
1216 char aError[256];
1217 json_value *pConfiguration = JsonParseEx(pSettings: &JsonSettings, pJson: static_cast<const json_char *>(pFileData), Length: FileLength, pError: aError);
1218
1219 if(pConfiguration == nullptr)
1220 {
1221 log_error("touch_controls", "Failed to parse configuration (invalid json): '%s'", aError);
1222 return false;
1223 }
1224 if(pConfiguration->type != json_object)
1225 {
1226 log_error("touch_controls", "Failed to parse configuration: root must be an object");
1227 json_value_free(pConfiguration);
1228 return false;
1229 }
1230
1231 std::optional<EDirectTouchIngameMode> ParsedDirectTouchIngame = ParseDirectTouchIngameMode(pModeValue: &(*pConfiguration)["direct-touch-ingame"]);
1232 if(!ParsedDirectTouchIngame.has_value())
1233 {
1234 json_value_free(pConfiguration);
1235 return false;
1236 }
1237
1238 std::optional<EDirectTouchSpectateMode> ParsedDirectTouchSpectate = ParseDirectTouchSpectateMode(pModeValue: &(*pConfiguration)["direct-touch-spectate"]);
1239 if(!ParsedDirectTouchSpectate.has_value())
1240 {
1241 json_value_free(pConfiguration);
1242 return false;
1243 }
1244
1245 std::optional<ColorRGBA> ParsedBackgroundColorInactive =
1246 ParseColor(pColorValue: &(*pConfiguration)["background-color-inactive"], pAttributeName: "background-color-inactive", DefaultColor: ColorRGBA(0.0f, 0.0f, 0.0f, 0.25f));
1247 if(!ParsedBackgroundColorInactive.has_value())
1248 {
1249 json_value_free(pConfiguration);
1250 return false;
1251 }
1252
1253 std::optional<ColorRGBA> ParsedBackgroundColorActive =
1254 ParseColor(pColorValue: &(*pConfiguration)["background-color-active"], pAttributeName: "background-color-active", DefaultColor: ColorRGBA(0.2f, 0.2f, 0.2f, 0.25f));
1255 if(!ParsedBackgroundColorActive.has_value())
1256 {
1257 json_value_free(pConfiguration);
1258 return false;
1259 }
1260
1261 const json_value &TouchButtons = (*pConfiguration)["touch-buttons"];
1262 if(TouchButtons.type != json_array)
1263 {
1264 log_error("touch_controls", "Failed to parse configuration: attribute 'touch-buttons' must specify an array");
1265 json_value_free(pConfiguration);
1266 return false;
1267 }
1268
1269 std::vector<CTouchButton> vParsedTouchButtons;
1270 vParsedTouchButtons.reserve(n: TouchButtons.u.array.length);
1271 for(unsigned ButtonIndex = 0; ButtonIndex < TouchButtons.u.array.length; ++ButtonIndex)
1272 {
1273 std::optional<CTouchButton> ParsedButton = ParseButton(pButtonObject: &TouchButtons[ButtonIndex]);
1274 if(!ParsedButton.has_value())
1275 {
1276 log_error("touch_controls", "Failed to parse configuration: could not parse button at index '%d'", ButtonIndex);
1277 json_value_free(pConfiguration);
1278 return false;
1279 }
1280
1281 vParsedTouchButtons.push_back(x: std::move(ParsedButton.value()));
1282 }
1283
1284 // Parsing successful. Apply parsed configuration.
1285 m_DirectTouchIngame = ParsedDirectTouchIngame.value();
1286 m_DirectTouchSpectate = ParsedDirectTouchSpectate.value();
1287 m_BackgroundColorInactive = ParsedBackgroundColorInactive.value();
1288 m_BackgroundColorActive = ParsedBackgroundColorActive.value();
1289
1290 m_vTouchButtons = std::move(vParsedTouchButtons);
1291 for(CTouchButton &TouchButton : m_vTouchButtons)
1292 {
1293 TouchButton.UpdatePointers();
1294 TouchButton.UpdateScreenFromUnitRect();
1295 }
1296
1297 json_value_free(pConfiguration);
1298
1299 // If successfully parsing buttons, deselect it.
1300 m_pSelectedButton = nullptr;
1301 m_pSampleButton = nullptr;
1302 m_UnsavedChanges = false;
1303
1304 return true;
1305}
1306
1307std::optional<CTouchControls::EDirectTouchIngameMode> CTouchControls::ParseDirectTouchIngameMode(const json_value *pModeValue)
1308{
1309 // TODO: Remove json_boolean backwards compatibility
1310 const json_value &DirectTouchIngame = *pModeValue;
1311 if(DirectTouchIngame.type != json_boolean && DirectTouchIngame.type != json_string)
1312 {
1313 log_error("touch_controls", "Failed to parse configuration: attribute 'direct-touch-ingame' must specify a string");
1314 return {};
1315 }
1316 if(DirectTouchIngame.type == json_boolean)
1317 {
1318 return DirectTouchIngame.u.boolean ? EDirectTouchIngameMode::ACTION : EDirectTouchIngameMode::DISABLED;
1319 }
1320 EDirectTouchIngameMode ParsedDirectTouchIngame = EDirectTouchIngameMode::NUM_STATES;
1321 for(int CurrentMode = (int)EDirectTouchIngameMode::DISABLED; CurrentMode < (int)EDirectTouchIngameMode::NUM_STATES; ++CurrentMode)
1322 {
1323 if(str_comp(a: DirectTouchIngame.u.string.ptr, b: DIRECT_TOUCH_INGAME_MODE_NAMES[CurrentMode]) == 0)
1324 {
1325 ParsedDirectTouchIngame = (EDirectTouchIngameMode)CurrentMode;
1326 break;
1327 }
1328 }
1329 if(ParsedDirectTouchIngame == EDirectTouchIngameMode::NUM_STATES)
1330 {
1331 log_error("touch_controls", "Failed to parse configuration: attribute 'direct-touch-ingame' specifies unknown value '%s'", DirectTouchIngame.u.string.ptr);
1332 return {};
1333 }
1334 return ParsedDirectTouchIngame;
1335}
1336
1337std::optional<CTouchControls::EDirectTouchSpectateMode> CTouchControls::ParseDirectTouchSpectateMode(const json_value *pModeValue)
1338{
1339 // TODO: Remove json_boolean backwards compatibility
1340 const json_value &DirectTouchSpectate = *pModeValue;
1341 if(DirectTouchSpectate.type != json_boolean && DirectTouchSpectate.type != json_string)
1342 {
1343 log_error("touch_controls", "Failed to parse configuration: attribute 'direct-touch-spectate' must specify a string");
1344 return {};
1345 }
1346 if(DirectTouchSpectate.type == json_boolean)
1347 {
1348 return DirectTouchSpectate.u.boolean ? EDirectTouchSpectateMode::AIM : EDirectTouchSpectateMode::DISABLED;
1349 }
1350 EDirectTouchSpectateMode ParsedDirectTouchSpectate = EDirectTouchSpectateMode::NUM_STATES;
1351 for(int CurrentMode = (int)EDirectTouchSpectateMode::DISABLED; CurrentMode < (int)EDirectTouchSpectateMode::NUM_STATES; ++CurrentMode)
1352 {
1353 if(str_comp(a: DirectTouchSpectate.u.string.ptr, b: DIRECT_TOUCH_SPECTATE_MODE_NAMES[CurrentMode]) == 0)
1354 {
1355 ParsedDirectTouchSpectate = (EDirectTouchSpectateMode)CurrentMode;
1356 break;
1357 }
1358 }
1359 if(ParsedDirectTouchSpectate == EDirectTouchSpectateMode::NUM_STATES)
1360 {
1361 log_error("touch_controls", "Failed to parse configuration: attribute 'direct-touch-spectate' specifies unknown value '%s'", DirectTouchSpectate.u.string.ptr);
1362 return {};
1363 }
1364 return ParsedDirectTouchSpectate;
1365}
1366
1367std::optional<ColorRGBA> CTouchControls::ParseColor(const json_value *pColorValue, const char *pAttributeName, std::optional<ColorRGBA> DefaultColor) const
1368{
1369 const json_value &Color = *pColorValue;
1370 if(Color.type == json_none && DefaultColor.has_value())
1371 {
1372 return DefaultColor;
1373 }
1374 if(Color.type != json_string)
1375 {
1376 log_error("touch_controls", "Failed to parse configuration: attribute '%s' must specify a string", pAttributeName);
1377 return {};
1378 }
1379 std::optional<ColorRGBA> ParsedColor = color_parse<ColorRGBA>(pStr: Color.u.string.ptr);
1380 if(!ParsedColor.has_value())
1381 {
1382 log_error("touch_controls", "Failed to parse configuration: attribute '%s' specifies invalid color value '%s'", pAttributeName, Color.u.string.ptr);
1383 return {};
1384 }
1385 return ParsedColor;
1386}
1387
1388std::optional<CTouchControls::CTouchButton> CTouchControls::ParseButton(const json_value *pButtonObject)
1389{
1390 const json_value &ButtonObject = *pButtonObject;
1391 if(ButtonObject.type != json_object)
1392 {
1393 log_error("touch_controls", "Failed to parse touch button: must be an object");
1394 return {};
1395 }
1396
1397 const auto &&ParsePositionSize = [&](const char *pAttribute, int &ParsedValue, int Min, int Max) {
1398 const json_value &AttributeValue = ButtonObject[pAttribute];
1399 if(AttributeValue.type != json_integer || !in_range<json_int_t>(a: AttributeValue.u.integer, lower: Min, upper: Max))
1400 {
1401 log_error("touch_controls", "Failed to parse touch button: attribute '%s' must specify an integer between '%d' and '%d'", pAttribute, Min, Max);
1402 return false;
1403 }
1404 ParsedValue = AttributeValue.u.integer;
1405 return true;
1406 };
1407 CUnitRect ParsedUnitRect;
1408 if(!ParsePositionSize("w", ParsedUnitRect.m_W, BUTTON_SIZE_MINIMUM, BUTTON_SIZE_MAXIMUM) ||
1409 !ParsePositionSize("h", ParsedUnitRect.m_H, BUTTON_SIZE_MINIMUM, BUTTON_SIZE_MAXIMUM))
1410 {
1411 return {};
1412 }
1413 if(!ParsePositionSize("x", ParsedUnitRect.m_X, 0, BUTTON_SIZE_SCALE - ParsedUnitRect.m_W) ||
1414 !ParsePositionSize("y", ParsedUnitRect.m_Y, 0, BUTTON_SIZE_SCALE - ParsedUnitRect.m_H))
1415 {
1416 return {};
1417 }
1418
1419 const json_value &Shape = ButtonObject["shape"];
1420 if(Shape.type != json_string)
1421 {
1422 log_error("touch_controls", "Failed to parse touch button: attribute 'shape' must specify a string");
1423 return {};
1424 }
1425 EButtonShape ParsedShape = EButtonShape::NUM_SHAPES;
1426 for(int CurrentShape = (int)EButtonShape::RECT; CurrentShape < (int)EButtonShape::NUM_SHAPES; ++CurrentShape)
1427 {
1428 if(str_comp(a: Shape.u.string.ptr, b: SHAPE_NAMES[CurrentShape]) == 0)
1429 {
1430 ParsedShape = (EButtonShape)CurrentShape;
1431 break;
1432 }
1433 }
1434 if(ParsedShape == EButtonShape::NUM_SHAPES)
1435 {
1436 log_error("touch_controls", "Failed to parse touch button: attribute 'shape' specifies unknown value '%s'", Shape.u.string.ptr);
1437 return {};
1438 }
1439
1440 const json_value &Visibilities = ButtonObject["visibilities"];
1441 if(Visibilities.type != json_array)
1442 {
1443 log_error("touch_controls", "Failed to parse touch button: attribute 'visibilities' must specify an array");
1444 return {};
1445 }
1446 std::vector<CButtonVisibility> vParsedVisibilities;
1447 vParsedVisibilities.reserve(n: Visibilities.u.array.length);
1448 for(unsigned VisibilityIndex = 0; VisibilityIndex < Visibilities.u.array.length; ++VisibilityIndex)
1449 {
1450 const json_value &Visibility = Visibilities[VisibilityIndex];
1451 if(Visibility.type != json_string)
1452 {
1453 log_error("touch_controls", "Failed to parse touch button: attribute 'visibilities' does not specify string at index '%d'", VisibilityIndex);
1454 return {};
1455 }
1456 EButtonVisibility ParsedVisibility = EButtonVisibility::NUM_VISIBILITIES;
1457 const bool ParsedParity = Visibility.u.string.ptr[0] != '-';
1458 const char *pVisibilityString = ParsedParity ? Visibility.u.string.ptr : &Visibility.u.string.ptr[1];
1459 for(int CurrentVisibility = (int)EButtonVisibility::INGAME; CurrentVisibility < (int)EButtonVisibility::NUM_VISIBILITIES; ++CurrentVisibility)
1460 {
1461 if(str_comp(a: pVisibilityString, b: m_aVisibilityFunctions[CurrentVisibility].m_pId) == 0)
1462 {
1463 ParsedVisibility = (EButtonVisibility)CurrentVisibility;
1464 break;
1465 }
1466 }
1467 if(ParsedVisibility == EButtonVisibility::NUM_VISIBILITIES)
1468 {
1469 log_error("touch_controls", "Failed to parse touch button: attribute 'visibilities' specifies unknown value '%s' at index '%d'", pVisibilityString, VisibilityIndex);
1470 return {};
1471 }
1472 const bool VisibilityAlreadyUsed = std::any_of(first: vParsedVisibilities.begin(), last: vParsedVisibilities.end(), pred: [&](CButtonVisibility OtherParsedVisibility) {
1473 return OtherParsedVisibility.m_Type == ParsedVisibility;
1474 });
1475 if(VisibilityAlreadyUsed)
1476 {
1477 log_error("touch_controls", "Failed to parse touch button: attribute 'visibilities' specifies duplicate value '%s' at '%d'", pVisibilityString, VisibilityIndex);
1478 return {};
1479 }
1480 vParsedVisibilities.emplace_back(args&: ParsedVisibility, args: ParsedParity);
1481 }
1482
1483 std::unique_ptr<CTouchButtonBehavior> pParsedBehavior = ParseBehavior(pBehaviorObject: &ButtonObject["behavior"]);
1484 if(pParsedBehavior == nullptr)
1485 {
1486 log_error("touch_controls", "Failed to parse touch button: failed to parse attribute 'behavior' (see details above)");
1487 return {};
1488 }
1489
1490 CTouchButton Button(this);
1491 Button.m_UnitRect = ParsedUnitRect;
1492 Button.m_Shape = ParsedShape;
1493 Button.m_vVisibilities = std::move(vParsedVisibilities);
1494 Button.m_pBehavior = std::move(pParsedBehavior);
1495 return Button;
1496}
1497
1498std::unique_ptr<CTouchControls::CTouchButtonBehavior> CTouchControls::ParseBehavior(const json_value *pBehaviorObject)
1499{
1500 const json_value &BehaviorObject = *pBehaviorObject;
1501 if(BehaviorObject.type != json_object)
1502 {
1503 log_error("touch_controls", "Failed to parse touch button behavior: must be an object");
1504 return nullptr;
1505 }
1506
1507 const json_value &BehaviorType = BehaviorObject["type"];
1508 if(BehaviorType.type != json_string)
1509 {
1510 log_error("touch_controls", "Failed to parse touch button behavior: attribute 'type' must specify a string");
1511 return nullptr;
1512 }
1513
1514 if(str_comp(a: BehaviorType.u.string.ptr, b: CPredefinedTouchButtonBehavior::BEHAVIOR_TYPE) == 0)
1515 {
1516 return ParsePredefinedBehavior(pBehaviorObject: &BehaviorObject);
1517 }
1518 else if(str_comp(a: BehaviorType.u.string.ptr, b: CBindTouchButtonBehavior::BEHAVIOR_TYPE) == 0)
1519 {
1520 return ParseBindBehavior(pBehaviorObject: &BehaviorObject);
1521 }
1522 else if(str_comp(a: BehaviorType.u.string.ptr, b: CBindToggleTouchButtonBehavior::BEHAVIOR_TYPE) == 0)
1523 {
1524 return ParseBindToggleBehavior(pBehaviorObject: &BehaviorObject);
1525 }
1526 else
1527 {
1528 log_error("touch_controls", "Failed to parse touch button behavior: attribute 'type' specifies unknown value '%s'", BehaviorType.u.string.ptr);
1529 return nullptr;
1530 }
1531}
1532
1533std::unique_ptr<CTouchControls::CPredefinedTouchButtonBehavior> CTouchControls::ParsePredefinedBehavior(const json_value *pBehaviorObject)
1534{
1535 const json_value &BehaviorObject = *pBehaviorObject;
1536 const json_value &PredefinedId = BehaviorObject["id"];
1537 if(PredefinedId.type != json_string)
1538 {
1539 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': attribute 'id' must specify a string", CPredefinedTouchButtonBehavior::BEHAVIOR_TYPE);
1540 return nullptr;
1541 }
1542
1543 class CBehaviorFactory
1544 {
1545 public:
1546 const char *m_pId;
1547 std::function<std::unique_ptr<CPredefinedTouchButtonBehavior>(const json_value *pBehaviorObject)> m_Factory;
1548 };
1549 static const CBehaviorFactory BEHAVIOR_FACTORIES[] = {
1550 {.m_pId: CIngameMenuTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CIngameMenuTouchButtonBehavior>(); }},
1551 {.m_pId: CExtraMenuTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [&](const json_value *pBehavior) { return ParseExtraMenuBehavior(pBehaviorObject: pBehavior); }},
1552 {.m_pId: CEmoticonTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CEmoticonTouchButtonBehavior>(); }},
1553 {.m_pId: CSpectateTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CSpectateTouchButtonBehavior>(); }},
1554 {.m_pId: CSwapActionTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CSwapActionTouchButtonBehavior>(); }},
1555 {.m_pId: CUseActionTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CUseActionTouchButtonBehavior>(); }},
1556 {.m_pId: CJoystickActionTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CJoystickActionTouchButtonBehavior>(); }},
1557 {.m_pId: CJoystickAimTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CJoystickAimTouchButtonBehavior>(); }},
1558 {.m_pId: CJoystickFireTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CJoystickFireTouchButtonBehavior>(); }},
1559 {.m_pId: CJoystickHookTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CJoystickHookTouchButtonBehavior>(); }}};
1560 for(const CBehaviorFactory &BehaviorFactory : BEHAVIOR_FACTORIES)
1561 {
1562 if(str_comp(a: PredefinedId.u.string.ptr, b: BehaviorFactory.m_pId) == 0)
1563 {
1564 return BehaviorFactory.m_Factory(&BehaviorObject);
1565 }
1566 }
1567
1568 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': attribute 'id' specifies unknown value '%s'", CPredefinedTouchButtonBehavior::BEHAVIOR_TYPE, PredefinedId.u.string.ptr);
1569 return nullptr;
1570}
1571
1572std::unique_ptr<CTouchControls::CExtraMenuTouchButtonBehavior> CTouchControls::ParseExtraMenuBehavior(const json_value *pBehaviorObject)
1573{
1574 const json_value &BehaviorObject = *pBehaviorObject;
1575 const json_value &MenuNumber = BehaviorObject["number"];
1576 // TODO: Remove json_none backwards compatibility
1577 if(MenuNumber.type != json_none && (MenuNumber.type != json_integer || !in_range<json_int_t>(a: MenuNumber.u.integer, lower: 1, upper: MAX_EXTRA_MENU_NUMBER)))
1578 {
1579 log_error("touch_controls", "Failed to parse touch button behavior of type '%s' and ID '%s': attribute 'number' must specify an integer between '%d' and '%d'",
1580 CPredefinedTouchButtonBehavior::BEHAVIOR_TYPE, CExtraMenuTouchButtonBehavior::BEHAVIOR_ID, 1, MAX_EXTRA_MENU_NUMBER);
1581 return nullptr;
1582 }
1583 int ParsedMenuNumber = MenuNumber.type == json_none ? 0 : (MenuNumber.u.integer - 1);
1584
1585 return std::make_unique<CExtraMenuTouchButtonBehavior>(args&: ParsedMenuNumber);
1586}
1587
1588std::unique_ptr<CTouchControls::CBindTouchButtonBehavior> CTouchControls::ParseBindBehavior(const json_value *pBehaviorObject)
1589{
1590 const json_value &BehaviorObject = *pBehaviorObject;
1591 const json_value &Label = BehaviorObject["label"];
1592 if(Label.type != json_string)
1593 {
1594 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': attribute 'label' must specify a string", CBindTouchButtonBehavior::BEHAVIOR_TYPE);
1595 return nullptr;
1596 }
1597
1598 const json_value &LabelType = BehaviorObject["label-type"];
1599 if(LabelType.type != json_string && LabelType.type != json_none)
1600 {
1601 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': attribute 'label-type' must specify a string", CBindTouchButtonBehavior::BEHAVIOR_TYPE);
1602 return {};
1603 }
1604 CButtonLabel::EType ParsedLabelType = CButtonLabel::EType::NUM_TYPES;
1605 if(LabelType.type == json_none)
1606 {
1607 ParsedLabelType = CButtonLabel::EType::PLAIN;
1608 }
1609 else
1610 {
1611 for(int CurrentType = (int)CButtonLabel::EType::PLAIN; CurrentType < (int)CButtonLabel::EType::NUM_TYPES; ++CurrentType)
1612 {
1613 if(str_comp(a: LabelType.u.string.ptr, b: LABEL_TYPE_NAMES[CurrentType]) == 0)
1614 {
1615 ParsedLabelType = (CButtonLabel::EType)CurrentType;
1616 break;
1617 }
1618 }
1619 }
1620 if(ParsedLabelType == CButtonLabel::EType::NUM_TYPES)
1621 {
1622 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': attribute 'label-type' specifies unknown value '%s'", CBindTouchButtonBehavior::BEHAVIOR_TYPE, LabelType.u.string.ptr);
1623 return {};
1624 }
1625
1626 const json_value &Command = BehaviorObject["command"];
1627 if(Command.type != json_string)
1628 {
1629 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': attribute 'command' must specify a string", CBindTouchButtonBehavior::BEHAVIOR_TYPE);
1630 return nullptr;
1631 }
1632
1633 return std::make_unique<CBindTouchButtonBehavior>(args: Label.u.string.ptr, args&: ParsedLabelType, args: Command.u.string.ptr);
1634}
1635
1636std::unique_ptr<CTouchControls::CBindToggleTouchButtonBehavior> CTouchControls::ParseBindToggleBehavior(const json_value *pBehaviorObject)
1637{
1638 const json_value &CommandsObject = (*pBehaviorObject)["commands"];
1639 if(CommandsObject.type != json_array || CommandsObject.u.array.length < 2)
1640 {
1641 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': attribute 'commands' must specify an array with at least 2 entries", CBindToggleTouchButtonBehavior::BEHAVIOR_TYPE);
1642 return {};
1643 }
1644
1645 std::vector<CTouchControls::CBindToggleTouchButtonBehavior::CCommand> vCommands;
1646 vCommands.reserve(n: CommandsObject.u.array.length);
1647 for(unsigned CommandIndex = 0; CommandIndex < CommandsObject.u.array.length; ++CommandIndex)
1648 {
1649 const json_value &CommandObject = CommandsObject[CommandIndex];
1650 if(CommandObject.type != json_object)
1651 {
1652 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': failed to parse command at index '%d': attribute 'commands' must specify an array of objects", CBindToggleTouchButtonBehavior::BEHAVIOR_TYPE, CommandIndex);
1653 return nullptr;
1654 }
1655
1656 const json_value &Label = CommandObject["label"];
1657 if(Label.type != json_string)
1658 {
1659 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': failed to parse command at index '%d': attribute 'label' must specify a string", CBindToggleTouchButtonBehavior::BEHAVIOR_TYPE, CommandIndex);
1660 return nullptr;
1661 }
1662
1663 const json_value &LabelType = CommandObject["label-type"];
1664 if(LabelType.type != json_string && LabelType.type != json_none)
1665 {
1666 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': failed to parse command at index '%d': attribute 'label-type' must specify a string", CBindToggleTouchButtonBehavior::BEHAVIOR_TYPE, CommandIndex);
1667 return {};
1668 }
1669 CButtonLabel::EType ParsedLabelType = CButtonLabel::EType::NUM_TYPES;
1670 if(LabelType.type == json_none)
1671 {
1672 ParsedLabelType = CButtonLabel::EType::PLAIN;
1673 }
1674 else
1675 {
1676 for(int CurrentType = (int)CButtonLabel::EType::PLAIN; CurrentType < (int)CButtonLabel::EType::NUM_TYPES; ++CurrentType)
1677 {
1678 if(str_comp(a: LabelType.u.string.ptr, b: LABEL_TYPE_NAMES[CurrentType]) == 0)
1679 {
1680 ParsedLabelType = (CButtonLabel::EType)CurrentType;
1681 break;
1682 }
1683 }
1684 }
1685 if(ParsedLabelType == CButtonLabel::EType::NUM_TYPES)
1686 {
1687 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': failed to parse command at index '%d': attribute 'label-type' specifies unknown value '%s'", CBindToggleTouchButtonBehavior::BEHAVIOR_TYPE, CommandIndex, LabelType.u.string.ptr);
1688 return {};
1689 }
1690
1691 const json_value &Command = CommandObject["command"];
1692 if(Command.type != json_string)
1693 {
1694 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': failed to parse command at index '%d': attribute 'command' must specify a string", CBindToggleTouchButtonBehavior::BEHAVIOR_TYPE, CommandIndex);
1695 return nullptr;
1696 }
1697 vCommands.emplace_back(args: Label.u.string.ptr, args&: ParsedLabelType, args: Command.u.string.ptr);
1698 }
1699 return std::make_unique<CBindToggleTouchButtonBehavior>(args: std::move(vCommands));
1700}
1701
1702void CTouchControls::WriteConfiguration(CJsonWriter *pWriter)
1703{
1704 pWriter->BeginObject();
1705
1706 pWriter->WriteAttribute(pName: "direct-touch-ingame");
1707 pWriter->WriteStrValue(pValue: DIRECT_TOUCH_INGAME_MODE_NAMES[(int)m_DirectTouchIngame]);
1708
1709 pWriter->WriteAttribute(pName: "direct-touch-spectate");
1710 pWriter->WriteStrValue(pValue: DIRECT_TOUCH_SPECTATE_MODE_NAMES[(int)m_DirectTouchSpectate]);
1711
1712 char aColor[9];
1713 str_format(buffer: aColor, buffer_size: sizeof(aColor), format: "%08X", m_BackgroundColorInactive.PackAlphaLast());
1714 pWriter->WriteAttribute(pName: "background-color-inactive");
1715 pWriter->WriteStrValue(pValue: aColor);
1716
1717 str_format(buffer: aColor, buffer_size: sizeof(aColor), format: "%08X", m_BackgroundColorActive.PackAlphaLast());
1718 pWriter->WriteAttribute(pName: "background-color-active");
1719 pWriter->WriteStrValue(pValue: aColor);
1720
1721 pWriter->WriteAttribute(pName: "touch-buttons");
1722 pWriter->BeginArray();
1723 for(CTouchButton &TouchButton : m_vTouchButtons)
1724 {
1725 TouchButton.WriteToConfiguration(pWriter);
1726 }
1727 pWriter->EndArray();
1728
1729 pWriter->EndObject();
1730}
1731
1732// This is called when the checkbox "Edit touch controls" is selected, so virtual visibility could be set as the real visibility on entering.
1733void CTouchControls::ResetVirtualVisibilities()
1734{
1735 // Update virtual visibilities.
1736 for(int Visibility = (int)EButtonVisibility::INGAME; Visibility < (int)EButtonVisibility::NUM_VISIBILITIES; ++Visibility)
1737 m_aVirtualVisibilities[Visibility] = m_aVisibilityFunctions[Visibility].m_Function();
1738}
1739
1740void CTouchControls::UpdateButtonsEditor(const std::vector<IInput::CTouchFingerState> &vTouchFingerStates)
1741{
1742 std::vector<CUnitRect> vVisibleButtonRects;
1743 const vec2 ScreenSize = CalculateScreenSize();
1744 bool LongPress = false;
1745 for(CTouchButton &TouchButton : m_vTouchButtons)
1746 {
1747 TouchButton.UpdateVisibilityEditor();
1748 }
1749
1750 if(vTouchFingerStates.empty())
1751 m_PreventSaving = false;
1752
1753 // Remove if the finger deleted has released.
1754 if(!m_vDeletedFingerState.empty())
1755 {
1756 const auto &Remove = std::remove_if(first: m_vDeletedFingerState.begin(), last: m_vDeletedFingerState.end(), pred: [&vTouchFingerStates](const auto &TargetState) {
1757 return std::none_of(vTouchFingerStates.begin(), vTouchFingerStates.end(), [&](const auto &State) {
1758 return State.m_Finger == TargetState.m_Finger;
1759 });
1760 });
1761 m_vDeletedFingerState.erase(first: Remove, last: m_vDeletedFingerState.end());
1762 }
1763 // Delete fingers if they are press later. So they cant be the longpress finger.
1764 if(vTouchFingerStates.size() > 1)
1765 {
1766 std::for_each(first: vTouchFingerStates.begin() + 1, last: vTouchFingerStates.end(), f: [&](const auto &State) {
1767 m_vDeletedFingerState.push_back(State);
1768 });
1769 }
1770
1771 // If released, and there is finger on screen, and the "first finger" is not deleted(new finger), then it can be a LongPress candidate.
1772 if(!vTouchFingerStates.empty() && !std::any_of(first: m_vDeletedFingerState.begin(), last: m_vDeletedFingerState.end(), pred: [&vTouchFingerStates](const auto &State) {
1773 return vTouchFingerStates[0].m_Finger == State.m_Finger;
1774 }))
1775 {
1776 // If has different finger, reset the accumulated delta.
1777 if(m_LongPressFingerState.has_value() && (*m_LongPressFingerState).m_Finger != vTouchFingerStates[0].m_Finger)
1778 m_AccumulatedDelta = vec2(0.0f, 0.0f);
1779 // Update the LongPress candidate state.
1780 m_LongPressFingerState = vTouchFingerStates[0];
1781 }
1782 // If no suitable finger for long press, then clear it.
1783 else
1784 {
1785 m_LongPressFingerState = std::nullopt;
1786 }
1787
1788 // Find long press button. LongPress == true means the first fingerstate long pressed.
1789 if(m_LongPressFingerState.has_value())
1790 {
1791 m_AccumulatedDelta += (*m_LongPressFingerState).m_Delta;
1792 // If slided, then delete.
1793 if(length(a: m_AccumulatedDelta) > 0.005f)
1794 {
1795 m_AccumulatedDelta = vec2(0.0f, 0.0f);
1796 m_vDeletedFingerState.push_back(x: *m_LongPressFingerState);
1797 m_LongPressFingerState = std::nullopt;
1798 m_PreventSaving = true;
1799 }
1800 // Till now, this else contains: if the finger hasn't slided, have no fingers that remain pressed down when it pressed, hasn't been a longpress already, the candidate is always the first finger.
1801 else
1802 {
1803 const auto Now = time_get_nanoseconds();
1804 if(!m_PreventSaving && Now - (*m_LongPressFingerState).m_PressTime > LONG_TOUCH_DURATION)
1805 {
1806 LongPress = true;
1807 m_vDeletedFingerState.push_back(x: *m_LongPressFingerState);
1808 // LongPress will be used this frame for sure, so reset delta.
1809 m_AccumulatedDelta = vec2(0.0f, 0.0f);
1810 }
1811 }
1812 }
1813
1814 // Update active and zoom fingerstate. The first finger will be used for moving button.
1815 if(!vTouchFingerStates.empty())
1816 m_ActiveFingerState = vTouchFingerStates[0];
1817 else
1818 {
1819 m_ActiveFingerState = std::nullopt;
1820 if(m_pSampleButton != nullptr && m_ShownRect.has_value())
1821 m_pSampleButton->m_UnitRect = (*m_ShownRect);
1822 }
1823 // Only the second finger will be used for zooming button.
1824 if(vTouchFingerStates.size() > 1)
1825 {
1826 // If zoom finger is pressed now, reset the zoom startpos
1827 if(!m_ZoomFingerState.has_value())
1828 m_ZoomStartPos = m_ActiveFingerState.value().m_Position - vTouchFingerStates[1].m_Position;
1829 m_ZoomFingerState = vTouchFingerStates[1];
1830 m_PreventSaving = true;
1831
1832 // If Zooming started, update it's x,y value so it's width and height could be calculated correctly.
1833 if(m_pSampleButton != nullptr && m_ShownRect.has_value())
1834 {
1835 m_pSampleButton->m_UnitRect.m_X = m_ShownRect->m_X;
1836 m_pSampleButton->m_UnitRect.m_Y = m_ShownRect->m_Y;
1837 }
1838 }
1839 else
1840 {
1841 m_ZoomFingerState = std::nullopt;
1842 m_ZoomStartPos = vec2(0.0f, 0.0f);
1843 if(m_pSampleButton != nullptr && m_ShownRect.has_value())
1844 {
1845 m_pSampleButton->m_UnitRect.m_W = m_ShownRect->m_W;
1846 m_pSampleButton->m_UnitRect.m_H = m_ShownRect->m_H;
1847 }
1848 }
1849 for(auto &TouchButton : m_vTouchButtons)
1850 {
1851 if(TouchButton.m_VisibilityCached)
1852 {
1853 if(m_pSelectedButton == &TouchButton)
1854 continue;
1855 // Only Long Pressed finger "in visible button" is used for selecting a button.
1856 if(LongPress && !vTouchFingerStates.empty() && TouchButton.IsInside(TouchPosition: (*m_LongPressFingerState).m_Position * ScreenSize))
1857 {
1858 // If m_pSelectedButton changes, Confirm if saving changes, then change.
1859 // LongPress used.
1860 LongPress = false;
1861 // Note: Even after the popup is opened by ChangeSelectedButtonWhile..., the fingerstate still exists. So we have to add it to m_vDeletedFingerState.
1862 m_vDeletedFingerState.push_back(x: *m_LongPressFingerState);
1863 m_LongPressFingerState = std::nullopt;
1864 if(m_UnsavedChanges)
1865 {
1866 // Update sample button before saving, or sample button's position value might be not updated.
1867 if(m_pSampleButton != nullptr && m_ShownRect.has_value())
1868 m_pSampleButton->m_UnitRect = *m_ShownRect;
1869 m_PopupParam.m_KeepMenuOpen = false;
1870 m_PopupParam.m_pOldSelectedButton = m_pSelectedButton;
1871 m_PopupParam.m_pNewSelectedButton = &TouchButton;
1872 m_PopupParam.m_PopupType = EPopupType::BUTTON_CHANGED;
1873 GameClient()->m_Menus.SetActive(true);
1874 // End the function.
1875 return;
1876 }
1877 m_pSelectedButton = &TouchButton;
1878 // Update illegal position when Long press the button. Or later it will keep saying unsavedchanges.
1879 if(IsRectOverlapping(MyRect: TouchButton.m_UnitRect, Shape: TouchButton.m_Shape))
1880 {
1881 std::optional<CUnitRect> FreeRect = UpdatePosition(MyRect: TouchButton.m_UnitRect, Shape: TouchButton.m_Shape);
1882 m_UnsavedChanges = true;
1883 if(!FreeRect.has_value())
1884 {
1885 m_PopupParam.m_PopupType = EPopupType::NO_SPACE;
1886 m_PopupParam.m_KeepMenuOpen = true;
1887 GameClient()->m_Menus.SetActive(true);
1888 return;
1889 }
1890 TouchButton.m_UnitRect = FreeRect.value();
1891 TouchButton.UpdateScreenFromUnitRect();
1892 }
1893 m_aIssueParam[(int)EIssueType::CACHE_SETTINGS].m_pTargetButton = m_pSelectedButton;
1894 m_aIssueParam[(int)EIssueType::CACHE_SETTINGS].m_Resolved = false;
1895 RemakeSampleButton();
1896 UpdateSampleButton(SrcButton: *m_pSelectedButton);
1897 // Don't insert the long pressed button. It is selected button now.
1898 continue;
1899 }
1900 // Insert visible but not selected buttons.
1901 vVisibleButtonRects.emplace_back(args: CalculateHitbox(Rect: TouchButton.m_UnitRect, Shape: TouchButton.m_Shape));
1902 }
1903 // If selected button not visible, unselect it.
1904 else if(m_pSelectedButton == &TouchButton && !GameClient()->m_Menus.IsActive())
1905 {
1906 m_PopupParam.m_PopupType = EPopupType::BUTTON_INVISIBLE;
1907 GameClient()->m_Menus.SetActive(true);
1908 return;
1909 }
1910 }
1911
1912 // Nothing left to do if no button selected.
1913 if(m_pSampleButton == nullptr)
1914 return;
1915
1916 // If LongPress == true, LongPress finger has to be outside of all visible buttons.(Except m_pSampleButton. This button hasn't been checked)
1917 if(LongPress)
1918 {
1919 // LongPress should be set to false, but to pass clang-tidy check, this shouldn't be set now
1920 // LongPress = false;
1921 bool IsInside = CalculateScreenFromUnitRect(Unit: *m_ShownRect).Inside(Point: m_LongPressFingerState->m_Position * ScreenSize);
1922 m_vDeletedFingerState.push_back(x: *m_LongPressFingerState);
1923 m_LongPressFingerState = std::nullopt;
1924 if(m_UnsavedChanges && !IsInside)
1925 {
1926 m_pSampleButton->m_UnitRect = *m_ShownRect;
1927 m_PopupParam.m_pNewSelectedButton = nullptr;
1928 m_PopupParam.m_pOldSelectedButton = m_pSelectedButton;
1929 m_PopupParam.m_KeepMenuOpen = false;
1930 m_PopupParam.m_PopupType = EPopupType::BUTTON_CHANGED;
1931 GameClient()->m_Menus.SetActive(true);
1932 }
1933 else if(!IsInside)
1934 {
1935 m_UnsavedChanges = false;
1936 ResetButtonPointers();
1937 // No need for caching settings issue. So the issue is set to finished.
1938 m_aIssueParam[(int)EIssueType::CACHE_SETTINGS].m_Resolved = true;
1939 m_aIssueParam[(int)EIssueType::SAVE_SETTINGS].m_Resolved = true;
1940 m_aIssueParam[(int)EIssueType::CACHE_POSITION].m_Resolved = true;
1941 }
1942 }
1943
1944 if(m_pSampleButton != nullptr)
1945 {
1946 if(m_ActiveFingerState.has_value() && m_ZoomFingerState == std::nullopt)
1947 {
1948 vec2 UnitXYDelta = m_ActiveFingerState->m_Delta * BUTTON_SIZE_SCALE;
1949 m_pSampleButton->m_UnitRect.m_X += UnitXYDelta.x;
1950 m_pSampleButton->m_UnitRect.m_Y += UnitXYDelta.y;
1951 auto Hitbox = CalculateHitbox(Rect: m_pSampleButton->m_UnitRect, Shape: m_pSampleButton->m_Shape);
1952 m_ShownRect = FindPositionXY(vVisibleButtonRects, MyRect: Hitbox);
1953 dbg_assert(m_ShownRect.has_value(), "Unexpected nullopt in m_ShownRect. Original rect: %d %d %d %d", Hitbox.m_X, Hitbox.m_Y, Hitbox.m_W, Hitbox.m_H);
1954 if(m_pSelectedButton != nullptr)
1955 {
1956 unsigned Movement = std::abs(x: m_pSelectedButton->m_UnitRect.m_X - m_ShownRect->m_X) + std::abs(x: m_pSelectedButton->m_UnitRect.m_Y - m_ShownRect->m_Y);
1957 if(Movement > 10000)
1958 {
1959 // Moved a lot, meaning changes made.
1960 m_UnsavedChanges = true;
1961 }
1962 }
1963 }
1964 else if(m_ActiveFingerState.has_value() && m_ZoomFingerState.has_value())
1965 {
1966 m_ShownRect = m_pSampleButton->m_UnitRect;
1967 vec2 UnitWHDelta;
1968 UnitWHDelta.x = (std::abs(x: m_ActiveFingerState.value().m_Position.x - m_ZoomFingerState.value().m_Position.x) - std::abs(x: m_ZoomStartPos.x)) * BUTTON_SIZE_SCALE;
1969 UnitWHDelta.y = (std::abs(x: m_ActiveFingerState.value().m_Position.y - m_ZoomFingerState.value().m_Position.y) - std::abs(x: m_ZoomStartPos.y)) * BUTTON_SIZE_SCALE;
1970 m_ShownRect->m_W = m_pSampleButton->m_UnitRect.m_W + UnitWHDelta.x;
1971 m_ShownRect->m_H = m_pSampleButton->m_UnitRect.m_H + UnitWHDelta.y;
1972
1973 m_ShownRect = FindSizeWH(vVisibleButtonRects, MyRect: m_ShownRect.value());
1974 m_UnsavedChanges = true;
1975 }
1976 // No finger on screen, then show it as is.
1977 else
1978 {
1979 m_ShownRect = m_pSampleButton->m_UnitRect;
1980 }
1981 // Finished moving, no finger on screen.
1982 if(vTouchFingerStates.empty())
1983 {
1984 m_AccumulatedDelta = vec2(0.0f, 0.0f);
1985 std::optional<CUnitRect> OldRect = m_ShownRect;
1986 auto Hitbox = CalculateHitbox(Rect: m_pSampleButton->m_UnitRect, Shape: m_pSampleButton->m_Shape);
1987 m_ShownRect = FindPositionXY(vVisibleButtonRects, MyRect: Hitbox);
1988 dbg_assert(m_ShownRect.has_value(), "Unexpected nullopt in m_ShownRect. Original rect: %d %d %d %d", Hitbox.m_X, Hitbox.m_Y, Hitbox.m_W, Hitbox.m_H);
1989 m_UnsavedChanges |= OldRect != m_ShownRect;
1990 m_pSampleButton->m_UnitRect = (*m_ShownRect);
1991 m_aIssueParam[(int)EIssueType::CACHE_POSITION].m_pTargetButton = m_pSampleButton.get();
1992 m_aIssueParam[(int)EIssueType::CACHE_POSITION].m_Resolved = false;
1993 m_pSampleButton->UpdateScreenFromUnitRect();
1994 }
1995 if(m_ShownRect->m_X == -1)
1996 {
1997 m_UnsavedChanges = true;
1998 m_PopupParam.m_PopupType = EPopupType::NO_SPACE;
1999 m_PopupParam.m_KeepMenuOpen = true;
2000 GameClient()->m_Menus.SetActive(true);
2001 return;
2002 }
2003 m_pSampleButton->UpdateScreenFromUnitRect();
2004 }
2005}
2006
2007void CTouchControls::RenderButtonsEditor()
2008{
2009 for(auto &TouchButton : m_vTouchButtons)
2010 {
2011 if(&TouchButton == m_pSelectedButton)
2012 continue;
2013 TouchButton.UpdateVisibilityEditor();
2014 if(TouchButton.m_VisibilityCached || m_PreviewAllButtons)
2015 {
2016 TouchButton.UpdateScreenFromUnitRect();
2017 TouchButton.Render(Selected: false);
2018 }
2019 }
2020
2021 if(m_pSampleButton != nullptr && m_ShownRect.has_value())
2022 {
2023 m_pSampleButton->Render(Selected: true, Rect: m_ShownRect);
2024 }
2025}
2026
2027std::optional<CTouchControls::CUnitRect> CTouchControls::FindPositionXY(std::vector<CUnitRect> &vVisibleButtonRects, CUnitRect MyRect)
2028{
2029 // Border clamp
2030 MyRect.m_X = std::clamp(val: MyRect.m_X, lo: 0, hi: BUTTON_SIZE_SCALE - MyRect.m_W);
2031 MyRect.m_Y = std::clamp(val: MyRect.m_Y, lo: 0, hi: BUTTON_SIZE_SCALE - MyRect.m_H);
2032 // Not overlapping with any rects
2033 {
2034 bool IfOverlap = std::any_of(first: vVisibleButtonRects.begin(), last: vVisibleButtonRects.end(), pred: [&MyRect](const auto &Rect) {
2035 return MyRect.IsOverlap(Other: Rect);
2036 });
2037 if(!IfOverlap)
2038 return MyRect;
2039 }
2040 if(vVisibleButtonRects != m_vLastUpdateRects || MyRect.m_W != m_LastWidth || MyRect.m_H != m_LastHeight)
2041 {
2042 m_LastWidth = MyRect.m_W;
2043 m_LastHeight = MyRect.m_H;
2044 m_vLastUpdateRects = vVisibleButtonRects;
2045 BuildPositionXY(vVisibleButtonRects: m_vLastUpdateRects, MyRect);
2046 }
2047 std::optional<CUnitRect> Result;
2048 CUnitRect SampleRect;
2049 for(const ivec2 &Target : m_vTargets)
2050 {
2051 SampleRect = {.m_X: Target.x, .m_Y: Target.y, .m_W: MyRect.m_W, .m_H: MyRect.m_H};
2052 if(!Result.has_value() || MyRect.Distance(Other: Result.value()) > MyRect.Distance(Other: SampleRect))
2053 Result = SampleRect;
2054 }
2055 int BestXPosition = -BUTTON_SIZE_SCALE, BestYPosition = -BUTTON_SIZE_SCALE, Cur = 0;
2056 std::vector<CUnitRect> vTargetRects;
2057 vTargetRects.reserve(n: m_vLastUpdateRects.size());
2058 std::copy_if(first: m_vXSortedRects.begin(), last: m_vXSortedRects.end(), result: std::back_inserter(x&: vTargetRects), pred: [&](const CUnitRect &Rect) {
2059 return !(Rect.m_Y + Rect.m_H <= MyRect.m_Y || MyRect.m_Y + MyRect.m_H <= Rect.m_Y);
2060 });
2061 for(const CUnitRect &Rect : vTargetRects)
2062 {
2063 if(Cur >= Rect.m_X + Rect.m_W)
2064 continue;
2065 SampleRect = {.m_X: Cur, .m_Y: MyRect.m_Y, .m_W: MyRect.m_W, .m_H: MyRect.m_H};
2066 if(Cur + MyRect.m_W <= BUTTON_SIZE_SCALE && !SampleRect.IsOverlap(Other: Rect))
2067 {
2068 BestXPosition = std::abs(x: Cur - MyRect.m_X) < std::abs(x: BestXPosition - MyRect.m_X) ? Cur : BestXPosition;
2069 BestXPosition = std::abs(x: Rect.m_X - MyRect.m_W - MyRect.m_X) < std::abs(x: BestXPosition - MyRect.m_X) ? Rect.m_X - MyRect.m_W : BestXPosition;
2070 }
2071 Cur = Rect.m_X + Rect.m_W;
2072 }
2073 if(Cur + MyRect.m_W <= BUTTON_SIZE_SCALE)
2074 {
2075 BestXPosition = std::abs(x: Cur - MyRect.m_X) < std::abs(x: BestXPosition - MyRect.m_X) ? Cur : BestXPosition;
2076 }
2077
2078 vTargetRects.clear();
2079 std::copy_if(first: m_vYSortedRects.begin(), last: m_vYSortedRects.end(), result: std::back_inserter(x&: vTargetRects), pred: [&](const CUnitRect &Rect) {
2080 return !(Rect.m_X + Rect.m_W <= MyRect.m_X || MyRect.m_X + MyRect.m_W <= Rect.m_X);
2081 });
2082 Cur = 0;
2083 for(const CUnitRect &Rect : vTargetRects)
2084 {
2085 if(Cur >= Rect.m_Y + Rect.m_H)
2086 continue;
2087 SampleRect = {.m_X: MyRect.m_X, .m_Y: Cur, .m_W: MyRect.m_W, .m_H: MyRect.m_H};
2088 if(Cur + MyRect.m_H <= BUTTON_SIZE_SCALE && !SampleRect.IsOverlap(Other: Rect))
2089 {
2090 BestYPosition = std::abs(x: Cur - MyRect.m_Y) < std::abs(x: BestYPosition - MyRect.m_Y) ? Cur : BestYPosition;
2091 BestYPosition = std::abs(x: Rect.m_Y - MyRect.m_H - MyRect.m_Y) < std::abs(x: BestYPosition - MyRect.m_Y) ? Rect.m_Y - MyRect.m_H : BestYPosition;
2092 }
2093 Cur = Rect.m_Y + Rect.m_H;
2094 }
2095 if(Cur + MyRect.m_H <= BUTTON_SIZE_SCALE)
2096 {
2097 BestYPosition = std::abs(x: Cur - MyRect.m_Y) < std::abs(x: BestYPosition - MyRect.m_Y) ? Cur : BestYPosition;
2098 }
2099
2100 if(BestXPosition != -BUTTON_SIZE_SCALE)
2101 {
2102 SampleRect = {.m_X: BestXPosition, .m_Y: MyRect.m_Y, .m_W: MyRect.m_W, .m_H: MyRect.m_H};
2103 if(!Result.has_value() || MyRect.Distance(Other: Result.value()) > MyRect.Distance(Other: SampleRect))
2104 Result = SampleRect;
2105 }
2106 if(BestYPosition != -BUTTON_SIZE_SCALE)
2107 {
2108 SampleRect = {.m_X: MyRect.m_X, .m_Y: BestYPosition, .m_W: MyRect.m_W, .m_H: MyRect.m_H};
2109 if(!Result.has_value() || MyRect.Distance(Other: Result.value()) > MyRect.Distance(Other: SampleRect))
2110 Result = SampleRect;
2111 }
2112 return Result;
2113}
2114
2115void CTouchControls::BuildPositionXY(std::vector<CUnitRect> vVisibleButtonRects, CUnitRect MyRect)
2116{
2117 m_vTargets.clear();
2118 m_vTargets.reserve(n: vVisibleButtonRects.size() * 4);
2119 m_vXSortedRects = m_vYSortedRects = vVisibleButtonRects;
2120 std::sort(first: m_vXSortedRects.begin(), last: m_vXSortedRects.end(), comp: [](const CUnitRect &Lhs, const CUnitRect &Rhs) {
2121 return Lhs.m_X < Rhs.m_X;
2122 });
2123 std::sort(first: m_vYSortedRects.begin(), last: m_vYSortedRects.end(), comp: [](const CUnitRect &Lhs, const CUnitRect &Rhs) {
2124 return Lhs.m_Y < Rhs.m_Y;
2125 });
2126 std::sort(first: vVisibleButtonRects.begin(), last: vVisibleButtonRects.end(), comp: [](const CUnitRect &Lhs, const CUnitRect &Rhs) {
2127 return Lhs.m_X < Rhs.m_X;
2128 });
2129 class CTree
2130 {
2131 public:
2132 void Init(const std::vector<CUnitRect> &vRects)
2133 {
2134 m_vOrder.reserve(n: vRects.size() * 2);
2135 for(const CUnitRect &Rect : vRects)
2136 {
2137 m_vOrder.emplace_back(args: Rect.m_Y);
2138 m_vOrder.emplace_back(args: Rect.m_Y + Rect.m_H);
2139 }
2140 m_vOrder.emplace_back(args: 0);
2141 m_vOrder.emplace_back(args: BUTTON_SIZE_SCALE);
2142 std::sort(first: m_vOrder.begin(), last: m_vOrder.end());
2143 m_vOrder.erase(first: std::unique(first: m_vOrder.begin(), last: m_vOrder.end()), last: m_vOrder.end());
2144 m_vTree.resize(sz: m_vOrder.size() * 4, c: {-1, -1, 0, 0});
2145 New(Start: 0, End: m_vOrder.size() - 2, Cur: 0);
2146 m_vZone.reserve(n: m_vTree.size());
2147 }
2148 void New(int Start, int End, unsigned Cur)
2149 {
2150 if(m_vTree[Cur].x != -1)
2151 return;
2152 m_vTree[Cur].x = Start;
2153 m_vTree[Cur].y = End;
2154 m_vTree[Cur].z = 0;
2155 m_vTree[Cur].w = 0;
2156 }
2157 void Add(int Start, int End, unsigned Cur)
2158 {
2159 m_vTree[Cur].z++;
2160 if(m_vTree[Cur].x == Start && m_vTree[Cur].y == End)
2161 {
2162 m_vTree[Cur].w++;
2163 return;
2164 }
2165 int Mid = (m_vTree[Cur].x + m_vTree[Cur].y) / 2;
2166 New(Start: Mid + 1, End: m_vTree[Cur].y, Cur: Cur * 2 + 2);
2167 New(Start: m_vTree[Cur].x, End: Mid, Cur: Cur * 2 + 1);
2168 if(Start <= Mid)
2169 {
2170 Add(Start, End: std::min(a: Mid, b: End), Cur: Cur * 2 + 1);
2171 }
2172 if(End >= Mid + 1)
2173 {
2174 Add(Start: std::max(a: Mid + 1, b: Start), End, Cur: Cur * 2 + 2);
2175 }
2176 }
2177 void Delete(int Start, int End, unsigned Cur)
2178 {
2179 m_vTree[Cur].z--;
2180 if(m_vTree[Cur].x == Start && m_vTree[Cur].y == End)
2181 {
2182 m_vTree[Cur].w--;
2183 return;
2184 }
2185 int Mid = (m_vTree[Cur].x + m_vTree[Cur].y) / 2;
2186 if(Start <= Mid)
2187 {
2188 Delete(Start, End: std::min(a: Mid, b: End), Cur: Cur * 2 + 1);
2189 }
2190 if(End >= Mid + 1)
2191 {
2192 Delete(Start: std::max(a: Mid + 1, b: Start), End, Cur: Cur * 2 + 2);
2193 }
2194 }
2195 void InnerQuery(unsigned Start)
2196 {
2197 std::vector<unsigned> vStack;
2198 vStack.reserve(n: BUTTON_SIZE_SCALE / BUTTON_SIZE_MINIMUM);
2199 vStack.push_back(x: Start);
2200 while(!vStack.empty())
2201 {
2202 unsigned Cur = vStack.back();
2203 vStack.pop_back();
2204 if(m_vTree[Cur].w > 0)
2205 {
2206 m_vZone.emplace_back(args&: m_vTree[Cur].x, args&: m_vTree[Cur].y);
2207 continue;
2208 }
2209 if(m_vTree[Cur].x == m_vTree[Cur].y || m_vTree[Cur].z == 0)
2210 continue;
2211 if(m_vTree[Cur * 2 + 2].x != -1 && m_vTree[Cur * 2 + 2].z > 0)
2212 {
2213 vStack.push_back(x: (Cur << 1) + 2);
2214 }
2215 if(m_vTree[Cur * 2 + 1].x != -1 && m_vTree[Cur * 2 + 1].z > 0)
2216 {
2217 vStack.push_back(x: (Cur << 1) + 1);
2218 }
2219 }
2220 }
2221 std::vector<ivec2> Query(int Length)
2222 {
2223 m_vZone.clear();
2224 InnerQuery(Start: 0);
2225 if(m_vZone.empty())
2226 {
2227 return {{0, BUTTON_SIZE_SCALE}};
2228 }
2229
2230 // Inverse discretization
2231 for(ivec2 &Zone : m_vZone)
2232 {
2233 Zone.x = m_vOrder[Zone.x];
2234 Zone.y = m_vOrder[Zone.y + 1];
2235 }
2236 if(m_vZone[0].x < Length)
2237 m_vZone[0].x = 0;
2238 // Merge segments.
2239 for(unsigned Index = 1; Index < m_vZone.size(); Index++)
2240 {
2241 if(m_vZone[Index - 1].y + Length <= m_vZone[Index].x)
2242 continue;
2243 m_vZone[Index].x = m_vZone[Index - 1].x;
2244 m_vZone[Index - 1].x = -1;
2245 }
2246 if(m_vZone.back().y + Length > BUTTON_SIZE_SCALE)
2247 m_vZone.back().y = BUTTON_SIZE_SCALE;
2248 m_vZone.erase(first: std::remove_if(first: m_vZone.begin(), last: m_vZone.end(), pred: [](const ivec2 &Zone) { return Zone.x == -1; }),
2249 last: m_vZone.end());
2250 // Result stores obstacles, now turn it into free spaces.
2251 std::vector<ivec2> vFree;
2252 vFree.reserve(n: m_vZone.size());
2253 if(m_vZone[0].x != 0)
2254 vFree.emplace_back(args: 0, args&: m_vZone[0].x);
2255 for(unsigned Index = 1; Index < m_vZone.size(); Index++)
2256 {
2257 vFree.emplace_back(args&: m_vZone[Index - 1].y, args&: m_vZone[Index].x);
2258 }
2259 if(m_vZone.back().y != BUTTON_SIZE_SCALE)
2260 vFree.emplace_back(args&: m_vZone.back().y, args: BUTTON_SIZE_SCALE);
2261 return vFree;
2262 }
2263 ivec2 Discretization(int Start, int End)
2264 {
2265 ivec2 Result;
2266 auto It = std::lower_bound(first: m_vOrder.begin(), last: m_vOrder.end(), val: Start);
2267 Result.x = std::distance(first: m_vOrder.begin(), last: It);
2268 It = std::lower_bound(first: m_vOrder.begin(), last: m_vOrder.end(), val: End);
2269 Result.y = std::distance(first: m_vOrder.begin(), last: It) - 1;
2270 return Result;
2271 }
2272
2273 private:
2274 std::vector<int> m_vOrder;
2275 std::vector<ivec4> m_vTree;
2276 std::vector<ivec2> m_vZone;
2277 } Tree;
2278
2279 std::set<int> CandidateX;
2280 for(const CUnitRect &Rect : vVisibleButtonRects)
2281 {
2282 // Rect right border.
2283 int Pos = Rect.m_X + Rect.m_W;
2284 if(Pos + MyRect.m_W <= BUTTON_SIZE_SCALE)
2285 CandidateX.insert(x: Pos);
2286 // Rect left border.
2287 Pos = Rect.m_X - MyRect.m_W;
2288 if(Pos >= 0)
2289 CandidateX.insert(x: Pos);
2290 }
2291 CandidateX.insert(position: CandidateX.begin(), x: 0);
2292 CandidateX.insert(x: BUTTON_SIZE_SCALE - MyRect.m_W);
2293 Tree.Init(vRects: vVisibleButtonRects);
2294
2295 auto Cmp = [&vVisibleButtonRects](int Lhs, int Rhs) -> bool {
2296 return vVisibleButtonRects[Lhs].m_X + vVisibleButtonRects[Lhs].m_W > vVisibleButtonRects[Rhs].m_X + vVisibleButtonRects[Rhs].m_W;
2297 };
2298 std::priority_queue<int, std::vector<int>, decltype(Cmp)> Out(Cmp);
2299
2300 unsigned Index = 0;
2301
2302 for(int CurrentX : CandidateX)
2303 {
2304 while(Index < vVisibleButtonRects.size() && vVisibleButtonRects[Index].m_X < CurrentX + MyRect.m_W)
2305 {
2306 auto Segment = Tree.Discretization(Start: vVisibleButtonRects[Index].m_Y, End: vVisibleButtonRects[Index].m_Y + vVisibleButtonRects[Index].m_H);
2307 Tree.Add(Start: Segment.x, End: Segment.y, Cur: 0);
2308 Out.emplace(args: Index++);
2309 }
2310 while(!Out.empty() && vVisibleButtonRects[Out.top()].m_X + vVisibleButtonRects[Out.top()].m_W <= CurrentX)
2311 {
2312 auto Segment = Tree.Discretization(Start: vVisibleButtonRects[Out.top()].m_Y, End: vVisibleButtonRects[Out.top()].m_Y + vVisibleButtonRects[Out.top()].m_H);
2313 Tree.Delete(Start: Segment.x, End: Segment.y, Cur: 0);
2314 Out.pop();
2315 }
2316 auto Spaces = Tree.Query(Length: MyRect.m_H);
2317 for(ivec2 &Space : Spaces)
2318 {
2319 m_vTargets.emplace_back(args&: CurrentX, args&: Space.x);
2320 m_vTargets.emplace_back(args&: CurrentX, args: Space.y - MyRect.m_H);
2321 }
2322 }
2323}
2324
2325// Retrieve the size data from `m_pSampleButton` and shrink it appropriately,
2326// ensuring that `m_ShownRect` (which will receive the data subsequently)
2327// does not overlap with any other buttons.
2328CTouchControls::CUnitRect CTouchControls::FindSizeWH(std::vector<CUnitRect> vVisibleButtonRects, CUnitRect MyRect)
2329{
2330 MyRect.m_W = std::clamp(val: MyRect.m_W, lo: BUTTON_SIZE_MINIMUM, hi: BUTTON_SIZE_MAXIMUM);
2331 MyRect.m_H = std::clamp(val: MyRect.m_H, lo: BUTTON_SIZE_MINIMUM, hi: BUTTON_SIZE_MAXIMUM);
2332 MyRect.m_W = std::min(a: MyRect.m_W, b: BUTTON_SIZE_SCALE - MyRect.m_X);
2333 MyRect.m_H = std::min(a: MyRect.m_H, b: BUTTON_SIZE_SCALE - MyRect.m_Y);
2334 // So every rectangle in the vector overlaps with MyRect.
2335 vVisibleButtonRects.erase(first: std::remove_if(first: vVisibleButtonRects.begin(), last: vVisibleButtonRects.end(), pred: [&](const CUnitRect &TargetRect) {
2336 return !MyRect.IsOverlap(Other: TargetRect);
2337 }),
2338 last: vVisibleButtonRects.end());
2339 if(vVisibleButtonRects.empty())
2340 return MyRect;
2341
2342 // We only consider the top left corner.
2343 std::sort(first: vVisibleButtonRects.begin(), last: vVisibleButtonRects.end(), comp: [](const CUnitRect &Lhs, const CUnitRect &Rhs) {
2344 return Lhs.m_X != Rhs.m_X ? Lhs.m_X < Rhs.m_X : Lhs.m_Y > Rhs.m_Y;
2345 });
2346
2347 // Delete elements which have no effect on the answer.
2348 size_t Read = 1, Write = 1, Comp = 0;
2349 while(Read < vVisibleButtonRects.size())
2350 {
2351 if(vVisibleButtonRects[Read].m_Y >= vVisibleButtonRects[Comp].m_Y)
2352 {
2353 Read++;
2354 continue;
2355 }
2356 vVisibleButtonRects[Write] = vVisibleButtonRects[Read];
2357 Comp = Write;
2358 Write++;
2359 Read++;
2360 }
2361 vVisibleButtonRects.resize(sz: Write);
2362
2363 int64_t Delta = std::numeric_limits<int64_t>::max();
2364 CUnitRect Result = MyRect;
2365 auto CalculateDelta = [&](int64_t NewHeight, int64_t NewWidth) -> int64_t {
2366 return (MyRect.m_H - NewHeight) * (MyRect.m_H - NewHeight) + (MyRect.m_W - NewWidth) * (MyRect.m_W - NewWidth);
2367 };
2368 for(size_t Index = 0; Index < vVisibleButtonRects.size() - 1; Index++)
2369 {
2370 int LimitH = vVisibleButtonRects[Index].m_Y - MyRect.m_Y;
2371 int LimitW = vVisibleButtonRects[Index + 1].m_X - MyRect.m_X;
2372 if(std::min(a: LimitH, b: LimitW) >= BUTTON_SIZE_MINIMUM && Delta > CalculateDelta(LimitH, LimitW))
2373 {
2374 Delta = CalculateDelta(LimitH, LimitW);
2375 Result.m_H = LimitH;
2376 Result.m_W = LimitW;
2377 }
2378 }
2379 int LimitH = vVisibleButtonRects.back().m_Y - MyRect.m_Y, LimitW = vVisibleButtonRects.front().m_X - MyRect.m_X;
2380 if(LimitH >= BUTTON_SIZE_MINIMUM && Delta > CalculateDelta(LimitH, MyRect.m_W))
2381 {
2382 Delta = CalculateDelta(LimitH, MyRect.m_W);
2383 Result.m_H = LimitH;
2384 Result.m_W = MyRect.m_W;
2385 }
2386 if(LimitW >= BUTTON_SIZE_MINIMUM && Delta > CalculateDelta(MyRect.m_H, LimitW))
2387 {
2388 Result.m_H = MyRect.m_H;
2389 Result.m_W = LimitW;
2390 }
2391
2392 // As FindPositionXY called earlier, this function can never fail. But if it fails, MyRect will not change.
2393 return Result;
2394}
2395
2396// Create a new button and push_back to m_vTouchButton, then return a pointer.
2397CTouchControls::CTouchButton *CTouchControls::NewButton()
2398{
2399 // Ensure m_pSelectedButton doesn't go wild.
2400 int Target = -1;
2401 if(m_pSelectedButton != nullptr)
2402 Target = std::distance(first: m_vTouchButtons.data(), last: m_pSelectedButton);
2403 CTouchButton NewButton(this);
2404 NewButton.m_pBehavior = std::make_unique<CBindTouchButtonBehavior>(args: "", args: CButtonLabel::EType::PLAIN, args: "");
2405 // So the vector's elements might be moved. If moved all button's m_VisibilityCached will be set to false. This should be prevented.
2406 std::vector<bool> vCachedVisibilities;
2407 vCachedVisibilities.reserve(n: m_vTouchButtons.size());
2408 for(const auto &Button : m_vTouchButtons)
2409 {
2410 vCachedVisibilities.emplace_back(args: Button.m_VisibilityCached);
2411 }
2412 for(unsigned Iterator = 0; Iterator < vCachedVisibilities.size(); Iterator++)
2413 {
2414 m_vTouchButtons[Iterator].m_VisibilityCached = vCachedVisibilities[Iterator];
2415 }
2416 m_vTouchButtons.push_back(x: std::move(NewButton));
2417 if(Target != -1)
2418 m_pSelectedButton = &m_vTouchButtons[Target];
2419 return &m_vTouchButtons.back();
2420}
2421
2422void CTouchControls::DeleteSelectedButton()
2423{
2424 if(m_pSelectedButton != nullptr)
2425 {
2426 auto DeleteIt = m_vTouchButtons.begin() + (m_pSelectedButton - m_vTouchButtons.data());
2427 m_vTouchButtons.erase(position: DeleteIt);
2428 }
2429 ResetButtonPointers();
2430 m_UnsavedChanges = false;
2431}
2432
2433bool CTouchControls::IsRectOverlapping(CUnitRect MyRect, EButtonShape Shape) const
2434{
2435 MyRect = CalculateHitbox(Rect: MyRect, Shape);
2436 for(const auto &TouchButton : m_vTouchButtons)
2437 {
2438 if(m_pSelectedButton == &TouchButton)
2439 continue;
2440 bool IsVisible = std::all_of(first: TouchButton.m_vVisibilities.begin(), last: TouchButton.m_vVisibilities.end(), pred: [&](const auto &Visibility) {
2441 return Visibility.m_Parity == m_aVirtualVisibilities[(int)Visibility.m_Type];
2442 });
2443 if(IsVisible && MyRect.IsOverlap(Other: CalculateHitbox(Rect: TouchButton.m_UnitRect, Shape: TouchButton.m_Shape)))
2444 return true;
2445 }
2446 return false;
2447}
2448
2449std::optional<CTouchControls::CUnitRect> CTouchControls::UpdatePosition(CUnitRect MyRect, EButtonShape Shape, bool Ignore)
2450{
2451 MyRect = CalculateHitbox(Rect: MyRect, Shape);
2452 std::vector<CUnitRect> vVisibleButtonRects;
2453 for(const auto &TouchButton : m_vTouchButtons)
2454 {
2455 if(m_pSelectedButton == &TouchButton && !Ignore)
2456 continue;
2457 bool IsVisible = std::all_of(first: TouchButton.m_vVisibilities.begin(), last: TouchButton.m_vVisibilities.end(), pred: [&](const auto &Visibility) {
2458 return Visibility.m_Parity == m_aVirtualVisibilities[(int)Visibility.m_Type];
2459 });
2460 if(!IsVisible)
2461 continue;
2462 vVisibleButtonRects.emplace_back(args: CalculateHitbox(Rect: TouchButton.m_UnitRect, Shape: TouchButton.m_Shape));
2463 }
2464 return FindPositionXY(vVisibleButtonRects, MyRect);
2465}
2466
2467void CTouchControls::ResetButtonPointers()
2468{
2469 m_pSelectedButton = nullptr;
2470 m_pSampleButton = nullptr;
2471 m_ShownRect = std::nullopt;
2472}
2473
2474// After sending the type, the popup should be reset immediately.
2475CTouchControls::CPopupParam CTouchControls::RequiredPopup()
2476{
2477 CPopupParam ReturnPopup = m_PopupParam;
2478 // Reset type so it won't be called for multiple times.
2479 m_PopupParam.m_PopupType = EPopupType::NUM_POPUPS;
2480 return ReturnPopup;
2481}
2482
2483// Return true if any issue is not finished.
2484bool CTouchControls::AnyIssueNotResolved() const
2485{
2486 return std::any_of(first: m_aIssueParam.begin(), last: m_aIssueParam.end(), pred: [](const auto &Issue) {
2487 return !Issue.m_Resolved;
2488 });
2489}
2490
2491std::array<CTouchControls::CIssueParam, (unsigned)CTouchControls::EIssueType::NUM_ISSUES> CTouchControls::Issues()
2492{
2493 std::array<CIssueParam, (unsigned)EIssueType::NUM_ISSUES> aUnresolvedIssues;
2494 for(int Issue = 0; Issue < (int)EIssueType::NUM_ISSUES; Issue++)
2495 {
2496 aUnresolvedIssues[Issue] = m_aIssueParam[Issue];
2497 m_aIssueParam[Issue].m_Resolved = true;
2498 }
2499 return aUnresolvedIssues;
2500}
2501
2502// Make it look like the button, only have bind behavior. This is only used on m_pSampleButton.
2503void CTouchControls::UpdateSampleButton(const CTouchButton &SrcButton)
2504{
2505 dbg_assert(m_pSampleButton != nullptr, "Sample button not created");
2506 m_pSampleButton->m_UnitRect = SrcButton.m_UnitRect;
2507 m_pSampleButton->m_Shape = SrcButton.m_Shape;
2508 m_pSampleButton->m_vVisibilities = SrcButton.m_vVisibilities;
2509 CButtonLabel Label = SrcButton.m_pBehavior->GetLabel();
2510 m_pSampleButton->m_pBehavior = std::make_unique<CBindTouchButtonBehavior>(args&: Label.m_pLabel, args&: Label.m_Type, args: "");
2511 m_pSampleButton->UpdatePointers();
2512 m_pSampleButton->m_UnitRect = CalculateHitbox(Rect: m_pSampleButton->m_UnitRect, Shape: m_pSampleButton->m_Shape);
2513 m_pSampleButton->UpdateScreenFromUnitRect();
2514}
2515
2516std::vector<CTouchControls::CTouchButton *> CTouchControls::GetButtonsEditor()
2517{
2518 std::vector<CTouchButton *> vpButtons;
2519 vpButtons.reserve(n: m_vTouchButtons.size());
2520 for(auto &TouchButton : m_vTouchButtons)
2521 {
2522 TouchButton.UpdateVisibilityEditor();
2523 vpButtons.emplace_back(args: &TouchButton);
2524 }
2525 return vpButtons;
2526}
2527
2528float CTouchControls::CUnitRect::Distance(const CUnitRect &Other) const
2529{
2530 vec2 Delta;
2531 Delta.x = Other.m_X + Other.m_W / 2.0f - m_X - m_W / 2.0f;
2532 Delta.y = Other.m_Y + Other.m_H / 2.0f - m_Y - m_H / 2.0f;
2533 return length(a: Delta / BUTTON_SIZE_SCALE);
2534}
2535