-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
10482 lines (9679 loc) · 394 KB
/
Copy pathmain.cpp
File metadata and controls
10482 lines (9679 loc) · 394 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <iphlpapi.h>
#include <Xinput.h>
#include <shellapi.h>
#include <mmsystem.h>
#include <gdiplus.h>
#include <SDL.h>
#include <algorithm>
#include <array>
#include <atomic>
#include <cctype>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cwchar>
#include <cwctype>
#include <filesystem>
#include <fstream>
#include <map>
#include <memory>
#include <mutex>
#include <sstream>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
#include "GeneratedAssetTable.h"
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "shell32.lib")
#pragma comment(lib, "gdiplus.lib")
#pragma comment(lib, "iphlpapi.lib")
namespace
{
constexpr size_t kTagSize = 180;
constexpr uint8_t kLoadCommand = 0x01;
constexpr uint8_t kRemoveCommand = 0x02;
constexpr uint8_t kMoveCommand = 0x03;
// The controller poll used to run on a WM_TIMER. Windows only synthesises
// WM_TIMER when the message queue is otherwise empty, and it shares that
// lowest priority tier with WM_PAINT - so every millisecond spent painting
// was a millisecond the next controller poll was delayed by, and a slow
// frame turned directly into a dropped or late button press. A posted
// message is an ordinary queued message and is delivered ahead of both, so
// input now always wins over drawing. A small thread does the pacing; the
// handler still runs on the UI thread, so nothing about the app's
// single-threaded state model changes.
constexpr UINT kTickMessage = WM_APP + 4;
// 8ms while the picker is up, so a quick tap of a button is never missed.
// Twice that while it is hidden, where the only thing the poll is looking
// for is the toggle shortcut - which nobody presses for less than 16ms -
// and where this app otherwise sits in the tray all day burning CPU for
// nothing.
constexpr DWORD kTickIntervalVisibleMs = 8;
constexpr DWORD kTickIntervalHiddenMs = 16;
// NOTE: this string is a cross-repo contract with the Cemu fork's
// Controller.cpp, which opens this same named event and waits on it to
// know when to neutralize real controller input. It must match the
// kToypadPickerInputEvent constant in Cemu's src/input/api/Controller.cpp
// exactly (currently "Local\CemuToypadPickerInputActive") or the handoff
// will silently stop working.
constexpr wchar_t kLegoToypadInputEvent[] = L"Local\\CemuToypadPickerInputActive";
// Overlay window sizing. All assets (portraits, logos, background,
// wordmark, tag .bins) are compiled into the exe as resources at build
// time by generate_assets.py - nothing is read from disk at runtime.
constexpr int kOverlayWidth = 900;
constexpr int kOverlayHeight = 610;
// Uniform translucency for the whole panel, as a percentage of opaque.
// 92% is the old fixed 235/255. The Settings row steps this (and sound
// volume) by kSettingsPercentStep in either direction.
constexpr int kDefaultOpacityPercent = 92;
// Toypad sneak peek: a click-through, never-activated HUD drawn straight
// over the running game while a button is held. It is a second view of
// the same seven pads - it reads g_app.padState / g_app.ledRegions and
// nothing else, so it is always in lockstep with the overlay's own pads.
//
// The point of it is that the game keeps running. The picker overlay
// takes the foreground and asserts input ownership (see
// UpdateInputOwnership), which is exactly what stops the emulator dead
// while it is up; the peek window does neither - WS_EX_TRANSPARENT plus
// WS_EX_NOACTIVATE means every button, including the one being held to
// summon it, goes to the game untouched.
constexpr int kPeekSizeChoiceCount = 4; // Off / Small / Medium / Large
constexpr size_t kDefaultPeekSizeChoice = 2; // Medium
// Pad height as a fraction of the monitor's height at Medium, so the HUD
// is the same physical size at 1080p and at 4K. The other sizes scale
// this by kPeekSizeScales.
constexpr float kPeekPadHeightFraction = 0.145f;
constexpr std::array<float, kPeekSizeChoiceCount> kPeekSizeScales = {0.0f, 0.78f, 1.0f, 1.26f};
// Screen-edge insets, as fractions of the monitor.
constexpr float kPeekMarginXFraction = 0.022f;
constexpr float kPeekMarginYFraction = 0.030f;
constexpr DWORD kPeekFadeInMs = 90;
constexpr DWORD kPeekFadeOutMs = 130;
constexpr int kOpacityFloorPercent = 20; // below this the window becomes hard to see
constexpr int kSettingsPercentStep = 15;
constexpr int kWindowCornerRadius = 20;
// kAppVersion itself now comes from GeneratedAssetTable (generated from
// generate_assets.py's APP_VERSION) so the web UI's version string can
// never drift from the exe's own FILEVERSION/ProductVersion again.
// Tray icon / menu.
constexpr UINT kTrayCallbackMessage = WM_APP + 1;
constexpr UINT kTrayIconId = 1;
constexpr UINT kMenuIdToggle = 1001;
constexpr UINT kMenuIdSettings = 1002;
constexpr UINT kMenuIdExit = 1003;
constexpr UINT kMenuIdWebAddress = 1004;
// Global toggle hotkey id (used only when the shortcut type is Keyboard).
constexpr UINT kToggleHotkeyId = 1;
struct ToypadSlot
{
uint8_t pad;
uint8_t index;
const wchar_t* label;
};
// pad = 1 is the CENTER pad, pad = 2 is the LEFT pad, pad = 3 is the RIGHT
// pad (this is the real toypad convention, confirmed by the USB protocol and
// by Cemu's own built-in toypad window, which renders pad 2 on the left and
// pad 1 in the middle). The toypad geometry is 3/1/3: the left section owns
// slots 0/3/4, the center section is the single slot 1, the right section
// owns slots 2/5/6.
constexpr std::array<ToypadSlot, 7> kSlots = {{
{2, 0, L"Left - upper"},
{1, 1, L"Center"},
{3, 2, L"Right - upper"},
{2, 3, L"Left - lower left"},
{2, 4, L"Left - lower right"},
{3, 5, L"Right - lower left"},
{3, 6, L"Right - lower right"},
}};
// The real Toypad only writes tags through its centre portal - the two
// side portals are read-only in hardware. That is a fixed fact about the
// physical device, not something this app or the picker's own pad
// selection has any say in: when a game prompts for a blank tag to
// create a custom one, it always means the centre pad, regardless of
// which of the 7 slots the user had focused when they opened the "+"
// tile.
constexpr size_t kCenterPadSlotIndex = 1;
// Controller inputs as a bitmask. XInput's own WORD is full (0x0001 to
// 0x8000), so the analog triggers - which XInput reports as axes, not
// buttons - get bits above it and this stays 32-bit wide. Everything
// that stores or compares a button set uses this type, including the
// values persisted in LegoToypad.ini.
using ButtonMask = uint32_t;
// LT / RT as pressable buttons. A trigger counts as pressed past this
// much of its travel; XInput's own recommended threshold is 30/255,
// but a higher one keeps a resting finger from arming a binding.
constexpr ButtonMask kTriggerLeftButton = 0x00010000u;
constexpr ButtonMask kTriggerRightButton = 0x00020000u;
constexpr int16_t kTriggerPressThreshold = 8000; // of SDL's 0..32767
// Which pad's labels the UI speaks. SDL reads Xbox, PlayStation and
// Nintendo pads through the same GameController API, so this only
// changes what the buttons are *called*, never what they do.
// Order matches the style order of kControllerIconResourceIds, so a
// style doubles as the row index into the bundled icon table.
enum class ButtonStyle
{
Xbox,
DualShock4,
Nintendo,
};
constexpr size_t kButtonStyleCount = 3;
// Settings row values: Auto follows whatever is plugged in, the rest
// pin one style. Auto is index 0, so the explicit styles are offset
// by one (see ButtonStyleFromChoice).
constexpr size_t kButtonStyleChoiceCount = kButtonStyleCount + 1;
struct ButtonName
{
ButtonMask mask;
const wchar_t* xbox;
const wchar_t* dualShock4;
// Nintendo face buttons keep their letters: SDL is asked to report
// them by label (SDL_GAMECONTROLLER_USE_BUTTON_LABELS), so the
// button printed "A" on the pad is the one the app calls A, even
// though it sits where an Xbox pad has B.
const wchar_t* nintendo;
};
// Order matches the button order of kControllerIconResourceIds, so an
// entry's index here is also its column in the bundled icon table.
constexpr std::array<ButtonName, 16> kButtonNames = {{
{XINPUT_GAMEPAD_DPAD_UP, L"D-Pad Up", L"D-Pad Up", L"D-Pad Up"},
{XINPUT_GAMEPAD_DPAD_DOWN, L"D-Pad Down", L"D-Pad Down", L"D-Pad Down"},
{XINPUT_GAMEPAD_DPAD_LEFT, L"D-Pad Left", L"D-Pad Left", L"D-Pad Left"},
{XINPUT_GAMEPAD_DPAD_RIGHT, L"D-Pad Right", L"D-Pad Right", L"D-Pad Right"},
{XINPUT_GAMEPAD_START, L"Start", L"Options", L"+"},
{XINPUT_GAMEPAD_BACK, L"Back", L"Share", L"-"},
{XINPUT_GAMEPAD_LEFT_THUMB, L"Left Stick Click", L"L3", L"Left Stick Click"},
{XINPUT_GAMEPAD_RIGHT_THUMB, L"Right Stick Click", L"R3", L"Right Stick Click"},
{XINPUT_GAMEPAD_LEFT_SHOULDER, L"LB", L"L1", L"L"},
{XINPUT_GAMEPAD_RIGHT_SHOULDER, L"RB", L"R1", L"R"},
{kTriggerLeftButton, L"LT", L"L2", L"ZL"},
{kTriggerRightButton, L"RT", L"R2", L"ZR"},
{XINPUT_GAMEPAD_A, L"A", L"Cross", L"A"},
{XINPUT_GAMEPAD_B, L"B", L"Circle", L"B"},
{XINPUT_GAMEPAD_X, L"X", L"Square", L"X"},
{XINPUT_GAMEPAD_Y, L"Y", L"Triangle", L"Y"},
}};
const wchar_t* ButtonNameFor(const ButtonName& entry, ButtonStyle style)
{
switch (style)
{
case ButtonStyle::DualShock4: return entry.dualShock4;
case ButtonStyle::Nintendo: return entry.nintendo;
case ButtonStyle::Xbox: break;
}
return entry.xbox;
}
// The bundled icon for one button in one style, or 0 when that style's
// set doesn't include it (the caller then falls back to the name).
int ButtonIconResourceId(size_t buttonIndex, ButtonStyle style)
{
const size_t styleIndex = static_cast<size_t>(style);
if (styleIndex >= kControllerIconStyleCount || buttonIndex >= kControllerIconButtonCount)
return 0;
return kControllerIconResourceIds[styleIndex][buttonIndex];
}
// The D-pad is reserved for menu navigation and can never be rebound;
// the rest of the picker's own buttons live in kBindableActions and are
// checked dynamically (see ReservedNavigationMask below), since every
// one of them is remappable from the Settings screen.
constexpr ButtonMask kDpadButtons = XINPUT_GAMEPAD_DPAD_UP | XINPUT_GAMEPAD_DPAD_DOWN |
XINPUT_GAMEPAD_DPAD_LEFT | XINPUT_GAMEPAD_DPAD_RIGHT;
// Reserved chord that always cancels shortcut capture on a controller,
// regardless of what is being assigned. Keyboard capture is cancelled
// with Esc instead. This guarantees there is always a way to back out
// without a mouse or keyboard.
constexpr ButtonMask kShortcutCancelChord = XINPUT_GAMEPAD_BACK | XINPUT_GAMEPAD_START;
enum class Screen
{
PadViewer, // 7 gloss pads; initial screen. Choose a pad.
PadAction, // bottom action bar inside the selected pad: Load / Move / Clear
FranchiseList, // grid of the 30 world (franchise) tiles
RosterList, // that world's characters + vehicles as circular portraits
PlusPicker, // capsule listing a multi-build vehicle's builds by number
Settings,
};
// The 3 actions in the selected pad's bottom action bar.
enum class PadActionKind
{
Load,
Move,
Clear,
};
constexpr size_t kPadActionCount = 3;
enum class ShortcutType
{
Controller,
Keyboard,
};
// LegoToypad's own record of what it has sent to each of the 7 pad
// slots. This is bookkeeping only, not verified truth - the wire
// protocol is fire-and-forget (no acknowledgement from Cemu), so this
// can drift out of sync if Cemu's native dialog is also used, if Cemu
// restarts without LegoToypad restarting, or if a send silently fails
// to actually land. See "Clear all pad" in Settings.
struct PadSlot
{
bool occupied = false;
std::wstring figureName;
int binResourceId = 0;
int portraitResourceId = 0;
unsigned int ringColor = 0;
};
// How a physical pad region's LED is behaving, as commanded by the game's
// HID LED commands (0xC0..0xC8). The app mirrors this so the overlay glows
// like the real toypad during keystone puzzles. ApplyLedCommand is the seam
// the wire poll (and the mock demo) drives.
//
// Durations arrive as toypad *ticks*, not milliseconds - the wire fields are
// single bytes, so a millisecond reading would cap every effect at 255ms and
// make finite ones expire before the first repaint. See kLedTickMs.
enum class LedMode : uint8_t { Off, Solid, Flash, Fade };
struct LedRegion
{
LedMode mode = LedMode::Off;
uint8_t r = 0, g = 0, b = 0; // Fade: the target colour being faded to
uint8_t fromR = 0, fromG = 0, fromB = 0; // Fade: the colour being faded from
int onTicks = 0; // Flash: lit duration, in toypad ticks
int offTicks = 0; // Flash: dark duration, in toypad ticks
int count = 0; // Flash/Fade: cycle count, 0 = repeat until next command
int speedTicks = 0; // Fade: ticks per fade step
DWORD cycleStart = 0;
float intensity = 0.0f; // 0..1 overall alpha, computed by the animation tick
// The colour actually drawn this frame. Equals r/g/b for every mode
// except Fade, where the real toypad alternates between fromR/G/B and
// r/g/b rather than ramping one colour's brightness - see
// ComputeLedFrame.
uint8_t curR = 0, curG = 0, curB = 0;
};
// One flat slot in the roster grid: a character portrait, a vehicle's
// build-1 portrait, or the "+" tile of a multi-build vehicle.
//
// Character makes up the grid's first (character) section; Vehicle / Plus
// make up the second one, below the separator.
struct RosterSlot
{
enum class Kind { Character, Vehicle, Plus } kind = Kind::Character;
const RosterEntry* entry = nullptr; // Character / Vehicle (build 1)
const VehicleGroup* group = nullptr; // Plus tile
};
// A favorited character or vehicle, identified by (franchise, name)
// rather than a resource id: ids are reassigned whenever the asset
// generator's symbol table changes, but names are stable and are what
// gets persisted to the ini. "name" is the character name for a
// character, or the vehicle group's baseName (family) for a vehicle -
// favoriting a multi-build vehicle favorites the whole group, same as
// what the roster tile itself represents.
struct FavoriteEntry
{
std::wstring franchise;
std::wstring name;
bool isVehicle = false;
// Which build of a multi-build vehicle this favorite pins - 0 means
// "unspecified": either a character (irrelevant), or a favorite
// saved before per-variant favoriting existed, which resolves to
// build 1 for backward compatibility. A specific vehicle favorited
// today always stores its real RosterEntry::buildNumber, so two
// builds of the same family can be favorited independently.
int buildNumber = 0;
};
struct AppState
{
Screen screen = Screen::PadViewer;
size_t slotIndex = 0;
size_t padActionIndex = 0;
int hoveredPadActionIndex = -1;
int pressedPadActionIndex = -1;
size_t settingsIndex = 0;
int settingsTopRow = 0; // first visible Settings row (scrolled list)
uint16_t port = 9191;
std::wstring status;
bool overlayVisible = false;
HWND previousForegroundWindow = nullptr;
ShortcutType shortcutType = ShortcutType::Controller;
ButtonMask shortcutControllerMask = XINPUT_GAMEPAD_BACK;
UINT shortcutKeyModifiers = 0;
UINT shortcutKeyCode = 0;
bool swapConfirmBackButtons = false;
size_t backgroundIndex = 0;
bool capturingShortcut = false;
// Controller bindings for the picker's own actions. Single-button
// masks, remappable from the Settings screen, persisted in [Input].
ButtonMask buttonConfirm = XINPUT_GAMEPAD_A;
ButtonMask buttonBack = XINPUT_GAMEPAD_B;
ButtonMask buttonSettings = XINPUT_GAMEPAD_Y;
ButtonMask buttonMoveActive = XINPUT_GAMEPAD_X;
ButtonMask buttonQuickLoad = XINPUT_GAMEPAD_RIGHT_SHOULDER;
ButtonMask buttonQuickClear = XINPUT_GAMEPAD_LEFT_SHOULDER;
// Same physical default as buttonSettings (Y / Triangle / Y) - no
// conflict, since this only fires on the RosterList/PlusPicker
// screens and buttonSettings only fires on PadViewer.
ButtonMask buttonFavorite = XINPUT_GAMEPAD_Y;
// Reorganize: picks a favorite/franchise tile up so the next
// navigation + confirm drops it in a new spot. Same physical default
// as buttonMoveActive (X / Square / X) - no conflict, disjoint
// screens from everything else already on X.
ButtonMask buttonReorganizeRoster = XINPUT_GAMEPAD_X;
ButtonMask buttonReorganizeFranchise = XINPUT_GAMEPAD_X;
// Held (not tapped) to summon the sneak-peek HUD over the game. The
// left trigger by default: nothing else in the picker is bound to it,
// and LEGO Dimensions itself only uses it for the shoulder-swap, so
// holding it is cheap in-game.
ButtonMask buttonSneakPeek = kTriggerLeftButton;
// Sneak peek size, 0 = off. Index into kPeekSizeScales.
size_t peekSizeChoice = kDefaultPeekSizeChoice;
// Index into kBindableActions while capturing a new button for one
// of them from Settings; -1 when no binding capture is running.
int capturingBindingIndex = -1;
// Which pad's button labels the UI uses. 0 = Auto (follow whatever
// is connected), 1..4 = pinned to one style.
size_t buttonStyleChoice = 0;
// Mirrors the running game's toypad LEDs onto the overlay's pads.
// OFF by default: the mirror repaints the pads as bare outlines and
// polls the listener 30x a second, which is not what a first run
// should look like or cost. Turning it on in Settings starts the poll
// thread; turning it off stops it entirely, so nothing talks to the
// listener and the pads stay their printed glass art.
bool ledMirrorEnabled = false;
// UI sound effects (Assets/SFX): a blip when the selection moves and
// a different one when something is confirmed.
bool soundEffects = true;
// Playback level, 0-100. PlaySound has no volume control of its own,
// so this is applied by scaling the WAV's samples (see GetSoundBytes).
int soundVolume = 70;
// Whole-window translucency, as a percentage of opaque. Applied as
// UpdateLayeredWindow's constant alpha on top of the frame's own
// per-pixel alpha, so it dims glows and art alike.
int opacityPercent = kDefaultOpacityPercent;
// Which folder under Assets/Pads supplies the seven pad images.
// Stored by name in the ini so adding or removing a skin folder never
// silently repoints this at a different one.
size_t padSkinIndex = 0;
// Window placement. Fixed re-centres the overlay on the active
// monitor every time it is shown; draggable lets the mouse pick it
// up anywhere that isn't a clickable control and remembers where it
// was dropped, across hide/show and across restarts.
bool windowDraggable = false;
bool hasSavedWindowPos = false;
int savedWindowX = 0;
int savedWindowY = 0;
// Live drag state; only meaningful while the left button is held
// down on a draggable overlay. Both points are screen coordinates,
// so the delta stays right even as the window moves under the mouse.
bool draggingWindow = false;
POINT dragStartCursor{};
POINT dragStartWindow{};
// Live controller facts, refreshed by every controller poll: what
// Auto resolves to, and whether anything is plugged in at all.
ButtonStyle detectedButtonStyle = ButtonStyle::Xbox;
bool controllerConnected = false;
// Web remote: the built-in HTTP server that lets the same tag library
// be driven from a phone browser on the local network. Runs on its own
// thread; requests that touch app state are marshaled back to the
// window's UI thread, so this is fully off by default.
bool webEnabled = true;
uint16_t webPort = 8765;
std::wstring webUrl;
// Stays false until every controller button has been seen released
// at least once after entering capture mode, so whatever button was
// still held down from opening the Settings screen can't be
// mistaken for the start of the new shortcut.
bool shortcutCaptureArmed = false;
std::array<PadSlot, 7> padState{};
std::array<LedRegion, 3> ledRegions{};
// True while PadViewer is being shown specifically to pick a Move's
// destination pad, rather than the normal "pick a pad to act on"
// mode. Reuses the same screen/grid per the original design intent.
bool selectingMoveDestination = false;
size_t moveSourceSlotIndex = 0;
// True while the RosterList screen is showing the story-mode starter
// roster instead of a franchise's roster, so Back returns straight
// to the pad viewer and no franchise logo is drawn as the header.
bool storyRosterActive = false;
// Franchise / roster browsing state.
size_t franchiseIndex = 0;
int franchiseTopRow = 0; // first visible franchise row (scrolled grid)
std::vector<RosterSlot> rosterSlots;
size_t rosterIndex = 0;
int rosterTopRow = 0; // first visible roster row (scrolled grids)
const VehicleGroup* plusGroup = nullptr;
size_t plusBuildIndex = 0;
// The roster slot that was focused when the build picker was opened,
// so backing out of it re-selects that vehicle instead of resetting
// to the top of the roster.
size_t rosterIndexBeforePlus = 0;
// Favorites: characters/vehicles marked from the roster screen,
// persisted in the ini under [Favorites] and browsed through the
// Favorites tile prepended to the franchise grid.
std::vector<FavoriteEntry> favorites;
// True when the franchise grid's logical index 0 (the Favorites
// tile) is the focused/open tile, instead of kFranchises[franchiseIndex].
bool favoritesTileSelected = false;
// Reordering the Favorites roster: pick a tile up (source index into
// rosterSlots), navigate to a new spot, drop it there. Only ever
// active while browsing the Favorites roster itself.
bool reorganizingRoster = false;
size_t reorganizeRosterSourceIndex = 0;
// Custom franchise/world display order, indices into kFranchises.
// Defaults to [0, 1, ..., kFranchiseCount-1] (the catalog's own
// order); persisted by name under [FranchiseOrder], resolved back to
// indices on load - see LoadFranchiseOrderFromIni.
std::vector<size_t> franchiseDisplayOrder;
// Reordering the franchise grid: same pick-up/move/drop shape as
// reorganizingRoster above, but reorganizeFranchiseSourceIndex is a
// display slot (0-based over real franchises, the synthetic
// Favorites tile excluded).
bool reorganizingFranchise = false;
size_t reorganizeFranchiseSourceIndex = 0;
// How the franchise grid is sorted/filtered on the franchise page.
// Cycled with the shoulder buttons (RB/LB, R1/L1, R/L) so the user can
// browse all-series / custom / story in real time without touching
// Settings. Favorites is reserved for a future mode.
enum class FranchiseSort { Default, User, Story, Favorites };
FranchiseSort franchiseSort = FranchiseSort::Default;
// Effective grid content for the current sort: franchise indices in
// display order, excluding the optional Favorites tile. Rebuilt by
// RebuildFranchiseDisplay(); franchiseDisplayOrder stays the user's
// persisted custom order (used only when sort == User).
std::vector<size_t> franchiseDisplayList;
bool showFavoritesTile = true;
};
AppState g_app;
HANDLE g_inputOwnershipEvent = nullptr;
// ---------------------------------------------------------------------
// Transitions
// ---------------------------------------------------------------------
// Two independent fades:
//
// - the whole window fades in when the overlay is summoned and back out
// when it is dismissed, so it arrives and leaves instead of snapping.
// This one rides UpdateLayeredWindow's constant alpha, which costs
// nothing extra: the frame is already presented that way, only the
// blend value changes.
// - the screen content cross-fades (and settles up a few pixels) every
// time the picker moves between screens. That one renders the content
// into a scratch layer for the ~150ms it lasts and composites the
// layer at a scaled alpha; outside a transition it is drawn straight
// into the frame with no layer at all, so the steady state is exactly
// as cheap as before.
//
// Both are driven off the existing 8ms controller timer, which already
// owned the "does anything still need repainting" decision for the LEDs.
constexpr DWORD kWindowFadeInMs = 140;
constexpr DWORD kWindowFadeOutMs = 110;
constexpr DWORD kScreenFadeMs = 150;
constexpr int kScreenFadeRisePx = 10;
DWORD g_windowFadeStart = 0;
bool g_windowFadingOut = false;
// True from the moment a hide is asked for until the fade-out finishes
// and the window is really hidden. The overlay still counts as visible
// (and still paints) throughout, but stops accepting navigation.
bool g_overlayHiding = false;
DWORD g_screenFadeStart = 0;
Screen g_lastTransitionScreen = Screen::PadViewer;
// A small banner that flashes g_app.status whenever it changes, then
// fades - e.g. "Added to favorites: X". g_app.status has dozens of call
// sites and no dedicated setter, so rather than touching every one of
// them, this just diffs the string once a tick (SyncStatusToast) and
// times the fade from whenever it last changed.
constexpr DWORD kStatusToastHoldMs = 1400;
constexpr DWORD kStatusToastFadeMs = 450;
constexpr DWORD kStatusToastTotalMs = kStatusToastHoldMs + kStatusToastFadeMs;
std::wstring g_lastSeenStatus;
DWORD g_statusToastStart = 0;
void SyncStatusToast()
{
if (g_app.status == g_lastSeenStatus)
return;
g_lastSeenStatus = g_app.status;
if (g_app.status.empty())
{
g_statusToastStart = 0;
return;
}
g_statusToastStart = GetTickCount();
if (g_statusToastStart == 0)
g_statusToastStart = 1; // never let 0 mean "armed" collide with "off"
}
bool StatusToastActive()
{
return g_statusToastStart != 0 && GetTickCount() - g_statusToastStart < kStatusToastTotalMs;
}
// 1 through the hold phase, easing down to 0 over the fade phase.
float StatusToastAlpha()
{
if (!StatusToastActive())
return 0.0f;
const DWORD elapsed = GetTickCount() - g_statusToastStart;
if (elapsed < kStatusToastHoldMs)
return 1.0f;
const float t = static_cast<float>(elapsed - kStatusToastHoldMs) / static_cast<float>(kStatusToastFadeMs);
return 1.0f - std::clamp(t, 0.0f, 1.0f);
}
// The focused tile's landing animation. The selection glow itself is
// steady; what moves is a single small spring the moment the selection
// arrives somewhere new - the tile swells ~5% and settles back over
// ~220ms, and then nothing animates at all.
//
// This replaced a glow that breathed continuously. That version had two
// problems: every frame of it was a full-window repaint forever, and
// because the whole 900x610 layered surface was being re-presented at a
// slightly different alpha several times a second, the entire panel
// appeared to shimmer rather than the selected tile appearing to glow.
// A one-shot animation is both calmer to look at and free when idle.
constexpr DWORD kSelectionTapMs = 220;
constexpr float kSelectionTapScale = 0.05f; // 5% at the peak
constexpr float kSelectionGlowRest = 0.80f; // steady glow alpha between taps
DWORD g_selectionTapStart = 0;
uint64_t g_lastSelectionSignature = 0;
bool g_hasSelectionSignature = false;
bool SelectionTapActive()
{
return g_selectionTapStart != 0 && GetTickCount() - g_selectionTapStart < kSelectionTapMs;
}
// 0 -> 1 -> 0 over the tap, rising quickly and settling slowly, with zero
// velocity at both ends so it neither jerks on nor stops dead. The time
// warp (t^0.6) is what puts the peak at ~31% of the duration instead of
// halfway, which is the difference between a tap and a throb.
float SelectionTapAmount()
{
if (!SelectionTapActive())
return 0.0f;
const float t = std::clamp(
static_cast<float>(GetTickCount() - g_selectionTapStart) / static_cast<float>(kSelectionTapMs),
0.0f, 1.0f);
return std::pow(std::sin(3.14159265f * std::pow(t, 0.6f)), 1.5f);
}
// How much the focused tile is scaled up right now, about its own centre.
float SelectionTapScale()
{
return 1.0f + kSelectionTapScale * SelectionTapAmount();
}
// The focused tile's halo: steady, with a small lift while the tap runs.
float SelectionGlowAlpha()
{
return kSelectionGlowRest + (1.0f - kSelectionGlowRest) * SelectionTapAmount();
}
// Poll pacing. kTickPending keeps at most one tick in flight, so a slow
// frame can never let the queue fill with a backlog of stale polls that
// would then all run at once (which is what "it registers something I
// didn't press, then starts accepting input again" looks like).
std::atomic<bool> g_tickRunning{false};
std::atomic<bool> g_tickPending{false};
// Read by the pacing thread, written by the UI thread when the overlay is
// shown or hidden - hence the atomic rather than reading overlayVisible
// across threads.
std::atomic<DWORD> g_tickIntervalMs{kTickIntervalHiddenMs};
std::thread g_tickThread;
// Cubic ease-out: fast at the start, gentle at the end. Applied to both
// fades so they feel like they are settling rather than stopping dead.
float EaseOutCubic(float t)
{
t = std::clamp(t, 0.0f, 1.0f);
const float inv = 1.0f - t;
return 1.0f - inv * inv * inv;
}
float ElapsedFraction(DWORD start, DWORD durationMs)
{
if (start == 0 || durationMs == 0)
return 1.0f;
const DWORD elapsed = GetTickCount() - start;
return elapsed >= durationMs ? 1.0f : static_cast<float>(elapsed) / static_cast<float>(durationMs);
}
BYTE TargetOverlayAlpha()
{
const int percent = std::clamp(g_app.opacityPercent, 20, 100);
return static_cast<BYTE>(std::clamp(percent * 255 / 100, 1, 255));
}
bool WindowFadeActive()
{
return g_windowFadeStart != 0 &&
ElapsedFraction(g_windowFadeStart, g_windowFadingOut ? kWindowFadeOutMs : kWindowFadeInMs) < 1.0f;
}
// The constant alpha handed to UpdateLayeredWindow this frame.
BYTE CurrentOverlayAlpha()
{
const BYTE target = TargetOverlayAlpha();
if (g_windowFadeStart == 0)
return target;
const float t = EaseOutCubic(
ElapsedFraction(g_windowFadeStart, g_windowFadingOut ? kWindowFadeOutMs : kWindowFadeInMs));
const float scale = g_windowFadingOut ? 1.0f - t : t;
return static_cast<BYTE>(std::clamp(static_cast<int>(target * scale + 0.5f), 0, 255));
}
// Starts a window fade that is already `fromShownFraction` of the way to
// being visible (0 = invisible, 1 = fully shown). Reversing mid-fade
// passes the fraction it had reached, so a quick double-tap of the
// shortcut looks like the window changed its mind rather than teleporting
// to one end and starting over. The start time is back-dated through the
// inverse of the ease so the motion stays continuous across the reversal.
void BeginWindowFade(bool fadingOut, float fromShownFraction)
{
g_windowFadingOut = fadingOut;
const float eased = std::clamp(fadingOut ? 1.0f - fromShownFraction : fromShownFraction, 0.0f, 1.0f);
const float linear = 1.0f - std::cbrt(1.0f - eased); // inverse of EaseOutCubic
const DWORD duration = fadingOut ? kWindowFadeOutMs : kWindowFadeInMs;
g_windowFadeStart = GetTickCount() - static_cast<DWORD>(linear * duration);
if (g_windowFadeStart == 0)
g_windowFadeStart = 1; // 0 is the "no fade running" sentinel
}
// How far along the current fade the window is, as a shown-ness fraction.
float CurrentShownFraction()
{
const BYTE target = TargetOverlayAlpha();
if (target == 0)
return 0.0f;
return std::clamp(static_cast<float>(CurrentOverlayAlpha()) / static_cast<float>(target), 0.0f, 1.0f);
}
bool ScreenTransitionActive()
{
return g_screenFadeStart != 0 && ElapsedFraction(g_screenFadeStart, kScreenFadeMs) < 1.0f;
}
float ScreenFadeAlpha()
{
if (g_screenFadeStart == 0)
return 1.0f;
return EaseOutCubic(ElapsedFraction(g_screenFadeStart, kScreenFadeMs));
}
// Detects a screen change and starts the content fade. Called from the
// timer (so it is noticed within a tick of the change) and from Paint (so
// a repaint that beats the timer still fades rather than popping).
// PadViewer and PadAction are the same picture - the seven pads - with an
// action bar added under the focused one. Cross-fading between them made
// the whole pad grid blink every time a pad was opened or backed out of,
// which reads as a glitch rather than a transition. They are treated as
// one screen here, so only real screen changes fade.
bool IsSamePadScene(Screen a, Screen b)
{
const auto padScene = [](Screen screen) {
return screen == Screen::PadViewer || screen == Screen::PadAction;
};
return padScene(a) && padScene(b);
}
void SyncScreenTransition()
{
if (g_app.screen == g_lastTransitionScreen)
return;
const Screen previous = g_lastTransitionScreen;
g_lastTransitionScreen = g_app.screen;
if (IsSamePadScene(previous, g_app.screen))
return;
g_screenFadeStart = GetTickCount();
if (g_screenFadeStart == 0)
g_screenFadeStart = 1;
}
// The picker's rebindable actions, in the order they appear as Settings
// rows. Confirm/Back stay subject to the swap-confirm-back setting on
// top of whatever buttons they are bound to.
struct BindableAction
{
const wchar_t* label; // Settings row / status text
const wchar_t* iniKey; // [Input] key it persists under
ButtonMask AppState::*button; // the binding itself
// True for Confirm/Back, which are read on every screen and so can
// never share a button with anything else. False for the rest,
// which each only fire on one specific screen (scope) - two of
// those are free to share the same default/bound button as long as
// their screens are never both "live" at once (e.g. Favorite only
// fires on RosterList, Move-active-pad only fires on PadViewer).
bool global;
Screen scope; // ignored when global is true
// True for actions that only fire while the picker is HIDDEN (the
// sneak-peek hold). Those can never collide with a picker action,
// whatever screen it belongs to, because the two are live at
// mutually exclusive times.
bool whileHidden = false;
};
// Two actions need distinct buttons only if either fires on every screen,
// or they fire on the very same screen.
bool ActionsCanConflict(const BindableAction& a, const BindableAction& b)
{
if (a.whileHidden != b.whileHidden)
return false;
if (a.global || b.global)
return true;
return a.scope == b.scope;
}
constexpr std::array<BindableAction, 10> kBindableActions = {{
{L"Confirm", L"ButtonConfirm", &AppState::buttonConfirm, true, Screen::PadViewer},
{L"Back", L"ButtonBack", &AppState::buttonBack, true, Screen::PadViewer},
{L"Settings", L"ButtonSettings", &AppState::buttonSettings, false, Screen::PadViewer},
{L"Move active pad", L"ButtonMoveActive", &AppState::buttonMoveActive, false, Screen::PadViewer},
{L"Quick load", L"ButtonQuickLoad", &AppState::buttonQuickLoad, false, Screen::PadViewer},
{L"Quick clear", L"ButtonQuickClear", &AppState::buttonQuickClear, false, Screen::PadViewer},
{L"Add to favorites", L"ButtonFavorite", &AppState::buttonFavorite, false, Screen::RosterList},
{L"Reorganize favorites", L"ButtonReorganizeRoster", &AppState::buttonReorganizeRoster, false,
Screen::RosterList},
{L"Reorganize worlds", L"ButtonReorganizeFranchise", &AppState::buttonReorganizeFranchise, false,
Screen::FranchiseList},
{L"Sneak peek (hold)", L"ButtonSneakPeek", &AppState::buttonSneakPeek, false,
Screen::PadViewer, true},
}};
// ---------------------------------------------------------------------
// Settings model
// ---------------------------------------------------------------------
// The Settings screen is a scrolled list grouped into categories, laid
// out like the franchise grid: a translucent panel, a right-edge scroll
// bar and a viewport that follows the focus. A row is either a category
// heading (not focusable, not activatable) or one setting.
//
// The same table drives painting and activation, so a row can never end
// up wired to the wrong action - which is exactly what the old
// "settingsIndex == 6" chain made easy to get wrong every time a row was
// inserted.
enum class SettingAction
{
Heading,
Shortcut,
ConfirmStyle,
ButtonStyle,
Binding, // uses bindingIndex
Background,
PadSkin,
Opacity,
WindowPlacement,
SneakPeek,
LedMirror,
SoundEffects,
SoundVolume,
ClearAllPads,
WebRemote,
ResetDefaults,
};
// Whether a row's value is an on/off state, and which way. On is drawn
// green and Off red, so the state of every switch in the list is readable
// without reading a single word. Settings whose value is a choice rather
// than a switch (a wallpaper, a window mode) stay Neutral - colouring
// "All series" green would be asserting something meaningless.
enum class SettingValueTone { Neutral, On, Off };
struct SettingsEntry
{
SettingAction action = SettingAction::Heading;
std::wstring label; // "Toypad LEDs", or the category name on a heading
std::wstring value; // "Off" - drawn separately so it can be coloured
SettingValueTone tone = SettingValueTone::Neutral;
ButtonMask icons = 0; // trailing pad-button icons, 0 for none
size_t bindingIndex = 0;
};
bool IsSettingsHeading(const SettingsEntry& entry)
{
return entry.action == SettingAction::Heading;
}
// Auto resolves to the connected pad's own style; a pinned choice wins
// over detection entirely.
ButtonStyle EffectiveButtonStyle()
{
if (g_app.buttonStyleChoice == 0)
return g_app.detectedButtonStyle;
return static_cast<ButtonStyle>(std::min(g_app.buttonStyleChoice, kButtonStyleCount) - 1);
}
std::wstring ButtonStyleName(ButtonStyle style)
{
switch (style)
{
case ButtonStyle::DualShock4: return L"DualShock 4";
case ButtonStyle::Nintendo: return L"Switch";
case ButtonStyle::Xbox: break;
}
return L"Xbox";
}
// Every button the picker itself currently reacts to while the overlay
// is open. A toggle shortcut made up of only these would fight normal
// use of the picker, so shortcut capture requires at least one button
// outside this set. Computed at call time because the bindings are
// remappable.
ButtonMask ReservedNavigationMask()
{
ButtonMask mask = kDpadButtons;
for (const auto& action : kBindableActions)
mask |= g_app.*(action.button);
return mask;
}
// ---------------------------------------------------------------------
// Web remote (phone browser control)
// ---------------------------------------------------------------------
// A tiny HTTP server embedded in the exe. The sockets library is already
// linked for the toypad listener, and every image/tag is already compiled
// in as resources, so the server needs nothing on disk. Requests that read
// or mutate app state are posted to the window message loop on the UI
// thread (kWebMessage) so they can never race the controller polling.
constexpr UINT kWebMessage = WM_APP + 2;
constexpr UINT kWebDefaultPort = 8765;
struct WebJob
{
enum class Op { State, Leds, Catalog, Load, Move, Clear, ClearAll, FavoritesGet, FavoriteToggle } op = Op::State;
int a = 0; // slot index for Load/Clear; source slot for Move
int b = 0; // bin resource id for Load and FavoriteToggle; destination slot for Move
std::string result; // JSON response body, written on the UI thread
bool ok = false;
HANDLE done = nullptr;
};
std::atomic<bool> g_webRunning{false};
SOCKET g_webListenSocket = INVALID_SOCKET;
HWND g_webWindow = nullptr;
std::thread g_webThread;
HWND g_mainWindow = nullptr;
// Serialises all loopback connections to the emulator's Toypad listener:
// the LED poll thread and the LOAD/REMOVE/MOVE sends run concurrently, and
// the listener serves one connection at a time, so only one is ever open.
std::mutex g_socketMutex;
// The library catalog is static once the app is running, so it is built a
// single time on the UI thread (it reads live background settings) and
// then served from cache to every browser tab.
bool g_catalogBuilt = false;
std::string g_catalogCache;
// Forward-declared here; defined later in the file. Confirm()/Back() run
// before those definitions appear.
void UpdateInputOwnership(HWND window);
void Paint(HWND window);
void HideOverlay(HWND window);
void OpenBrowseScreen();
void OpenStoryRoster();
void OpenFavoritesRoster();
void BeginShortcutCapture();
void CancelShortcutCapture();
void BeginBindingCapture(size_t actionIndex);
void CancelBindingCapture();
void ResetSettingsToDefaults();
void ApplyOverlayTransparency(HWND window);
int CurrentBackgroundResourceId();
bool StartWebServer(HWND window);
void StopWebServer();
void ToggleWebRemote();
void ToggleLedMirror();
void SetLedMirrorEnabled(bool enabled);
void PositionOverlayWindow(HWND window);
std::wstring DescribeLedMirror();
std::wstring DescribeWebRemote();
std::wstring GetLanAddress();
void HandleWebJob(WebJob& job);
void MoveSlotToSlot(size_t sourceIndex, size_t destIndex, bool updateUi);
void SyncSelectionTap();
void StartTickThread(HWND window);
void StopTickThread();
// Settings list (built from the categorised table further down).
std::vector<SettingsEntry> BuildSettingsEntries();
void MoveSettingsSelection(int direction);
void ActivateSettingsEntry();
void AdjustSettingsValue(int direction);
void ClampSettingsSelection();
void BuildPadSkinList();
void CyclePadSkin(int direction);
void CycleOpacity(int direction);
void CycleSoundVolume(int direction);
void CycleSneakPeek(int direction);
std::wstring DescribeSneakPeek();
void HidePeekWindow(bool immediate);
void ToggleSoundEffects();
std::wstring DescribePadSkin();
std::wstring DescribeOpacity();
std::wstring DescribeSoundEffects();
std::wstring DescribeSoundVolume();
// ---------------------------------------------------------------------
// GDI+ plumbing
// ---------------------------------------------------------------------
ULONG_PTR g_gdiplusToken = 0;