-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlugin.cs
More file actions
3003 lines (2752 loc) · 148 KB
/
Copy pathPlugin.cs
File metadata and controls
3003 lines (2752 loc) · 148 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.InputSystem;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem.UI;
using UnityEngine.TextCore;
using TMPro;
using HarmonyLib;
namespace ControllerMod
{
[BepInPlugin(PluginGuid, "Paralives Controller Mod", PluginVersion)]
public class Plugin : BaseUnityPlugin
{
public const string PluginGuid = "com.zorrph.paralives.controllermod";
public const string PluginVersion = "1.1.1";
// The pre-release development GUID - existing config files carry this name and are
// migrated to the new one on first launch (the GUID names the .cfg file).
// Older GUIDs whose config files migrate forward automatically, newest first.
private static readonly string[] LegacyGuids =
{
"net.kmarlin.paralives.controllermod", // v1.0.0-v1.1.0
"com.yourname.controllerfix", // pre-release builds
};
internal static ManualLogSource Log;
// Set once by KeyBindingPatch.LoadPostfix; used by Update() to gate the D-pad-bound
// build-tool actions below.
internal static InputActionAsset Actions;
private static readonly string[] DPadBuildActions =
{
// FloorUp/FloorDown are native game actions we never rebound - they're gamepad-bound
// to dpad up/down by default and fire regardless of any open UI, stealing D-pad input
// from popups like the interaction menu (confirmed: dpad-up both failed to navigate
// the interaction popup AND changed floors in the background at the same time).
"BuildWall", "PipetteMode", "SledgehammerMode", "ToggleGrid", "FloorUp", "FloorDown",
// The LB/RB+D-pad combo actions (this mod's bindings) share the same physical D-pad
// the menu navigation reads, so they get the same window-open gating.
"Undo", "Redo", "QuickSave", "CenterCameraOnCharacter",
"PauseTime", "TimeSpeed0", "TimeSpeed1", "TimeSpeed2",
"DuplicateItem", "LotMode"
};
private bool _dpadBuildActionsEnabled = true;
internal static UnityEngine.GameObject OwnGameObject;
// BG3-style world cursor: toggled with left-stick click (leftStickPress) by default,
// configurable below. While active, the right stick moves the reticle instead of the
// camera (View disabled).
internal static bool VirtualCursorEnabled;
internal static Vector2 VirtualCursorPosition;
private GameObject _cursorVisualGO;
private RectTransform _cursorVisualRect;
private static Sprite _cachedReticleSprite;
// User-rebindable gamepad bindings, persisted to BepInEx/config/com.yourname.controllerfix.cfg.
// Values are Unity Input System binding paths (e.g. "<Gamepad>/buttonNorth"); two paths
// joined with '+' become a modifier combo (e.g. "<Gamepad>/leftShoulder+<Gamepad>/select").
internal static ConfigEntry<string> CfgMenu;
internal static ConfigEntry<string> CfgCatalog;
internal static ConfigEntry<string> CfgBuildWall;
internal static ConfigEntry<string> CfgPipetteMode;
internal static ConfigEntry<string> CfgSledgehammerMode;
internal static ConfigEntry<string> CfgToggleGrid;
internal static ConfigEntry<string> CfgDelete;
internal static ConfigEntry<string> CfgLargeRotateItem;
internal static ConfigEntry<string> CfgToggleParaBuild;
internal static ConfigEntry<string> CfgTownMap;
internal static ConfigEntry<string> CfgPhotoMode;
internal static ConfigEntry<string> CfgUndo;
internal static ConfigEntry<string> CfgRedo;
internal static ConfigEntry<string> CfgQuickSave;
internal static ConfigEntry<string> CfgCenterCameraOnCharacter;
internal static ConfigEntry<string> CfgPauseTime;
internal static ConfigEntry<string> CfgTimeSpeed0;
internal static ConfigEntry<string> CfgTimeSpeed1;
internal static ConfigEntry<string> CfgTimeSpeed2;
internal static ConfigEntry<string> CfgFamilyTree;
internal static ConfigEntry<string> CfgCalendar;
internal static ConfigEntry<string> CfgLotMode;
internal static ConfigEntry<string> CfgDuplicateItem;
internal static ConfigEntry<string> CfgNoSnapHold;
internal static ConfigEntry<string> CfgMoveVerticallyHold;
internal static ConfigEntry<string> CfgCursorToggleButton;
internal static ConfigEntry<float> CfgCursorSpeed;
// Verbose diagnostics (heartbeat, lifecycle watches, nav/combo traces). Off for normal
// play; flip on when reporting a bug so the log tells the whole story.
internal static bool DebugLogging;
private void BindConfig()
{
const string bindingsSection = "Gamepad Bindings";
const string pathHelp = " (Input System binding path; combine two with '+' for a modifier combo)";
CfgMenu = Config.Bind(bindingsSection, "Menu", "<Gamepad>/start", "Toggle the pause menu" + pathHelp);
CfgCatalog = Config.Bind(bindingsSection, "Catalog", "<Gamepad>/buttonNorth", "Open/close the build catalog" + pathHelp);
// Build tools live on RB+D-pad combos, NOT bare D-pad: the game natively binds
// FloorUp/FloorDown to bare dpad up/down, so bare-dpad tool bindings double-fired
// (dpad-down switched floors AND opened the sledgehammer). Bare dpad up/down stays
// the native floor switch; bare dpad left/right is time-speed stepping, handled in
// code by UpdateTimeStepping() rather than a binding.
CfgBuildWall = Config.Bind(bindingsSection, "BuildWall", "<Gamepad>/rightShoulder+<Gamepad>/dpad/left", "Wall tool (build mode)" + pathHelp);
CfgPipetteMode = Config.Bind(bindingsSection, "PipetteMode", "<Gamepad>/rightShoulder+<Gamepad>/dpad/right", "Pipette/eyedropper tool (build mode)" + pathHelp);
CfgSledgehammerMode = Config.Bind(bindingsSection, "SledgehammerMode", "<Gamepad>/rightShoulder+<Gamepad>/dpad/down", "Sledgehammer/bulldozer tool (build mode)" + pathHelp);
CfgToggleGrid = Config.Bind(bindingsSection, "ToggleGrid", "<Gamepad>/rightShoulder+<Gamepad>/dpad/up", "Toggle the build grid" + pathHelp);
CfgDelete = Config.Bind(bindingsSection, "Delete", "<Gamepad>/buttonWest", "Delete/sell the selected object" + pathHelp);
CfgLargeRotateItem = Config.Bind(bindingsSection, "LargeRotateItem", "<Gamepad>/leftShoulder+<Gamepad>/buttonWest", "90-degree rotate of the selected object" + pathHelp);
CfgToggleParaBuild = Config.Bind(bindingsSection, "ToggleParaBuild", "<Gamepad>/leftShoulder+<Gamepad>/select", "Toggle between live and build mode" + pathHelp);
CfgTownMap = Config.Bind(bindingsSection, "TownMap", "<Gamepad>/select", "Open the town map" + pathHelp);
CfgPhotoMode = Config.Bind(bindingsSection, "PhotoMode", "<Gamepad>/rightStickPress", "Toggle photo mode" + pathHelp);
// Keyboard-only actions given gamepad combos by this mod (found via the binding
// audit). LB+D-pad = editing helpers, RB+D-pad = time controls.
CfgUndo = Config.Bind(bindingsSection, "Undo", "<Gamepad>/leftShoulder+<Gamepad>/dpad/left", "Undo (Ctrl+Z equivalent)" + pathHelp);
CfgRedo = Config.Bind(bindingsSection, "Redo", "<Gamepad>/leftShoulder+<Gamepad>/dpad/right", "Redo (Ctrl+Y equivalent)" + pathHelp);
CfgQuickSave = Config.Bind(bindingsSection, "QuickSave", "<Gamepad>/leftShoulder+<Gamepad>/dpad/up", "Quick save (F5 equivalent)" + pathHelp);
CfgCenterCameraOnCharacter = Config.Bind(bindingsSection, "CenterCameraOnCharacter", "<Gamepad>/leftShoulder+<Gamepad>/dpad/down", "Center camera on the selected character (F equivalent)" + pathHelp);
// PauseTime/TimeSpeed0-2 have no gamepad bindings by default: D-pad left/right step
// the time speed down/up (left eventually pauses; right resumes), see
// UpdateTimeStepping(). Leave these empty unless you want dedicated buttons too.
CfgPauseTime = Config.Bind(bindingsSection, "PauseTime", "", "Pause/unpause game time (Space equivalent); empty = use D-pad left time stepping" + pathHelp);
CfgTimeSpeed0 = Config.Bind(bindingsSection, "TimeSpeed0", "", "Time speed 1 (normal); empty = use D-pad left/right time stepping" + pathHelp);
CfgTimeSpeed1 = Config.Bind(bindingsSection, "TimeSpeed1", "", "Time speed 2 (fast); empty = use D-pad left/right time stepping" + pathHelp);
CfgTimeSpeed2 = Config.Bind(bindingsSection, "TimeSpeed2", "", "Time speed 3 (fastest); empty = use D-pad left/right time stepping" + pathHelp);
CfgFamilyTree = Config.Bind(bindingsSection, "FamilyTree", "<Gamepad>/rightShoulder+<Gamepad>/select", "Open the family tree (T equivalent)" + pathHelp);
CfgCalendar = Config.Bind(bindingsSection, "Calendar", "<Gamepad>/rightShoulder+<Gamepad>/start", "Open the calendar (C equivalent)" + pathHelp);
CfgLotMode = Config.Bind(bindingsSection, "LotMode", "<Gamepad>/leftShoulder+<Gamepad>/buttonNorth", "Lot mode (L equivalent)" + pathHelp);
CfgDuplicateItem = Config.Bind(bindingsSection, "DuplicateItem", "<Gamepad>/rightShoulder+<Gamepad>/buttonWest", "Duplicate the selected item (Ctrl+V equivalent)" + pathHelp);
// Contextual hold-modifiers: these are gamepad control NAMES (not binding paths)
// because they don't bind to actions - ContextualTriggerModifiers ORs them into the
// game's InputManager.Alt/.Shift checks, but only while an item is being
// placed/moved/resized or a wall is being drawn. Trigger zoom is suspended during
// exactly that window, so LT/RT don't conflict with their normal camera-zoom role.
CfgNoSnapHold = Config.Bind(bindingsSection, "NoSnapHold", "leftTrigger",
"Gamepad control held for No Snap (Alt equivalent) while placing/moving an item or drawing a wall (a control name on the gamepad, e.g. leftTrigger); empty = disabled");
CfgMoveVerticallyHold = Config.Bind(bindingsSection, "MoveVerticallyHold", "rightTrigger",
"Gamepad control held to Move Vertically / grid-divide (Shift equivalent) while placing/moving an item or drawing a wall (a control name on the gamepad, e.g. rightTrigger); empty = disabled");
const string cursorSection = "Virtual Cursor";
CfgCursorToggleButton = Config.Bind(cursorSection, "ToggleButton", "leftStickPress",
"Gamepad control that toggles the virtual cursor (a control name on the gamepad, e.g. leftStickPress, rightStickPress, select)");
CfgCursorSpeed = Config.Bind(cursorSection, "SpeedPixelsPerSecond", 1000f,
"How fast the virtual cursor moves at full stick deflection, in screen pixels per second");
DebugLogging = Config.Bind("Advanced", "DebugLogging", false,
"Verbose diagnostic logging (lifecycle watches, navigation/combo traces, heartbeat). Enable when reporting a bug.").Value;
// Config values persist in the .cfg file across mod updates, so changing a default
// above does nothing for existing installs. If an entry still holds the exact old
// default (i.e. the user never customized it), move it to the new default.
MigrateOldDefault(CfgBuildWall, "<Gamepad>/dpad/left");
MigrateOldDefault(CfgPipetteMode, "<Gamepad>/dpad/right");
MigrateOldDefault(CfgSledgehammerMode, "<Gamepad>/dpad/down");
MigrateOldDefault(CfgToggleGrid, "<Gamepad>/dpad/up");
MigrateOldDefault(CfgPauseTime, "<Gamepad>/rightShoulder+<Gamepad>/dpad/up");
MigrateOldDefault(CfgTimeSpeed0, "<Gamepad>/rightShoulder+<Gamepad>/dpad/left");
MigrateOldDefault(CfgTimeSpeed1, "<Gamepad>/rightShoulder+<Gamepad>/dpad/down");
MigrateOldDefault(CfgTimeSpeed2, "<Gamepad>/rightShoulder+<Gamepad>/dpad/right");
// Stick clicks swapped 2026-07: cursor on LS-press feels more natural (per user
// feedback), photo mode moves to RS-press.
MigrateOldDefault(CfgPhotoMode, "<Gamepad>/leftStickPress");
MigrateOldDefault(CfgCursorToggleButton, "rightStickPress");
}
// BepInEx names the config file after the plugin GUID and loads it in the
// BaseUnityPlugin constructor - before Awake. So: copy the legacy file over, then
// Config.Reload() so the already-constructed ConfigFile picks the values up before
// BindConfig() reads them.
private void MigrateLegacyConfigFile()
{
try
{
string newPath = System.IO.Path.Combine(Paths.ConfigPath, PluginGuid + ".cfg");
if (System.IO.File.Exists(newPath))
{
return;
}
foreach (var legacyGuid in LegacyGuids)
{
string oldPath = System.IO.Path.Combine(Paths.ConfigPath, legacyGuid + ".cfg");
if (System.IO.File.Exists(oldPath))
{
System.IO.File.Copy(oldPath, newPath);
Config.Reload();
Log.LogInfo($"Controller Fix: Migrated config from '{legacyGuid}.cfg' to '{PluginGuid}.cfg'.");
return;
}
}
}
catch (Exception e)
{
Log.LogWarning($"Controller Fix: Legacy config migration failed (defaults will be used): {e.Message}");
}
}
private static void MigrateOldDefault(ConfigEntry<string> entry, string oldDefault)
{
if (entry.Value == oldDefault)
{
entry.Value = (string)entry.DefaultValue;
Log.LogInfo($"Controller Fix: Migrated config '{entry.Definition.Key}' from old default '{oldDefault}' to '{entry.Value}'.");
}
}
void Awake()
{
Log = Logger;
OwnGameObject = gameObject;
MigrateLegacyConfigFile();
BindConfig();
// DontDestroyOnLoad alone did NOT stop the destroy (confirmed by testing), which rules
// out a normal scene-unload wipe - DontDestroyOnLoad should be bulletproof against
// that. Something is explicitly calling Destroy() on this object/a component on it.
// Patch Object.Destroy itself (below) to log a stack trace when it targets us.
try
{
DontDestroyOnLoad(gameObject);
// DontDestroyOnLoad alone did NOT survive (confirmed: object's scene name went
// from 'DontDestroyOnLoad' to '' by OnDisable, with zero managed Destroy/
// DestroyImmediate call intercepted - a native-only teardown). BepInEx's own
// manager GameObject additionally sets HideAndDontSave, which is the stronger
// flag that actually blocks native scene-unload sweeps. Match that.
gameObject.hideFlags = HideFlags.HideAndDontSave;
if (DebugLogging)
Log.LogInfo("Controller Fix: [Lifecycle] DontDestroyOnLoad call completed without throwing. " +
$"scene='{gameObject.scene.name}' buildIndex={gameObject.scene.buildIndex} " +
$"parent='{(gameObject.transform.parent == null ? "<none>" : gameObject.transform.parent.name)}' " +
$"hideFlags={gameObject.hideFlags}");
}
catch (Exception e)
{
Log.LogError($"Controller Fix: DontDestroyOnLoad threw: {e.Message}\n{e.StackTrace}");
}
var harmony = new Harmony(PluginGuid);
// Lifecycle watch patches (Destroy/SetActive/SetParent on our own GameObject) exist
// purely to diagnose the historical "plugin GameObject torn down" issue - patching
// Object.Destroy globally is not free, so only install them in debug mode.
if (DebugLogging)
try
{
var destroy1 = AccessTools.Method(typeof(UnityEngine.Object), "Destroy", new[] { typeof(UnityEngine.Object) });
var destroy2 = AccessTools.Method(typeof(UnityEngine.Object), "Destroy", new[] { typeof(UnityEngine.Object), typeof(float) });
var destroyPrefix = AccessTools.Method(typeof(DestroyWatchPatch), nameof(DestroyWatchPatch.Prefix));
harmony.Patch(destroy1, prefix: new HarmonyMethod(destroyPrefix));
harmony.Patch(destroy2, prefix: new HarmonyMethod(destroyPrefix));
Log.LogInfo("Controller Fix: Watching Object.Destroy for calls targeting our own GameObject.");
// Destroy() never fired our watch on the previous test, so also cover
// DestroyImmediate - Unity's editor/immediate-mode destroy path, which some
// engine-internal and "scene sanitizing" code paths use instead of Destroy().
var destroyImmediate1 = AccessTools.Method(typeof(UnityEngine.Object), "DestroyImmediate", new[] { typeof(UnityEngine.Object) });
var destroyImmediate2 = AccessTools.Method(typeof(UnityEngine.Object), "DestroyImmediate", new[] { typeof(UnityEngine.Object), typeof(bool) });
harmony.Patch(destroyImmediate1, prefix: new HarmonyMethod(destroyPrefix));
harmony.Patch(destroyImmediate2, prefix: new HarmonyMethod(destroyPrefix));
Log.LogInfo("Controller Fix: Watching Object.DestroyImmediate for calls targeting our own GameObject.");
// Also watch SetActive(false) on our own GameObject - this alone explains
// OnDisable but not OnDestroy, so if we see this WITHOUT a matching Destroy/
// DestroyImmediate log, the destroy is happening through a native engine path
// (e.g. scene unload) that never calls a managed Object method at all.
var setActiveMethod = AccessTools.Method(typeof(UnityEngine.GameObject), nameof(UnityEngine.GameObject.SetActive));
var setActivePrefix = AccessTools.Method(typeof(SetActiveWatchPatch), nameof(SetActiveWatchPatch.Prefix));
harmony.Patch(setActiveMethod, prefix: new HarmonyMethod(setActivePrefix));
Log.LogInfo("Controller Fix: Watching GameObject.SetActive for calls targeting our own GameObject.");
// If nothing reparents us, DontDestroyOnLoad should be bulletproof against scene
// unload. If something calls SetParent on our transform (or a parent of it) after
// Awake, Unity silently pulls us back into a regular scene - no exception, no log -
// undoing DontDestroyOnLoad's protection. Watch for that specifically.
var setParentMethod = AccessTools.Method(typeof(UnityEngine.Transform), nameof(UnityEngine.Transform.SetParent), new[] { typeof(UnityEngine.Transform) });
var setParentPrefix = AccessTools.Method(typeof(SetParentWatchPatch), nameof(SetParentWatchPatch.Prefix));
harmony.Patch(setParentMethod, prefix: new HarmonyMethod(setParentPrefix));
Log.LogInfo("Controller Fix: Watching Transform.SetParent for calls targeting our own GameObject.");
}
catch (Exception e)
{
Log.LogError($"Controller Fix: Failed to patch Object.Destroy/DestroyImmediate/SetActive/SetParent: {e.Message}\n{e.StackTrace}");
}
if (DebugLogging)
{
try
{
foreach (var device in InputSystem.devices)
{
Log.LogInfo($"Controller Fix: Input device detected: '{device.displayName}' (layout={device.layout}, type={device.GetType().Name})");
}
}
catch (Exception e)
{
Log.LogError($"Controller Fix: Device enumeration failed: {e.Message}");
}
}
try
{
var type = AccessTools.TypeByName("Setting.KeyBindings");
if (type != null)
{
var targetMethod = AccessTools.Method(type, "LoadAndApplyKeyRebindings");
if (targetMethod != null)
{
var postfix = AccessTools.Method(typeof(KeyBindingPatch), nameof(KeyBindingPatch.LoadPostfix));
harmony.Patch(targetMethod, postfix: new HarmonyMethod(postfix));
Log.LogInfo("Controller Fix: Surgical strike hook deployed on LoadAndApplyKeyRebindings.");
}
else
{
Log.LogError("Controller Fix: Target method 'LoadAndApplyKeyRebindings' missing!");
}
}
else
{
Log.LogError("Controller Fix: Target class 'Setting.KeyBindings' not found.");
}
// Decompiled Back.cs: pressing Cancel (Escape/B) with nothing else to back out
// of falls through to UI.Get<UIEscapeMenu>(playerIndex).Show(). Escape and B
// share the single "Cancel" action, so this is what makes B open the pause menu.
// Patch the shared UIContainer.Show() (UIEscapeMenu has no override of its own)
// and block it specifically when the trigger this frame was a gamepad B press.
var showMethod = AccessTools.Method(typeof(UIContainer), nameof(UIContainer.Show));
var showPrefix = AccessTools.Method(typeof(EscapeMenuGuardPatch), nameof(EscapeMenuGuardPatch.Prefix));
harmony.Patch(showMethod, prefix: new HarmonyMethod(showPrefix));
Log.LogInfo("Controller Fix: Guarded UIEscapeMenu.Show() against gamepad B triggers.");
// Diagnostic only: log what NavigateMenu sees each time D-pad is pressed, so a
// bug report log can show whether nav is never called, called with no
// CurrentWindow, or called with a window that has no registered Focusables.
if (DebugLogging)
{
var navigateMethod = AccessTools.Method(typeof(UIManager), nameof(UIManager.NavigateMenu));
var navigatePrefix = AccessTools.Method(typeof(MenuNavDiagnosticPatch), nameof(MenuNavDiagnosticPatch.Prefix));
harmony.Patch(navigateMethod, prefix: new HarmonyMethod(navigatePrefix));
Log.LogInfo("Controller Fix: Attached menu-navigation diagnostics to UIManager.NavigateMenu.");
}
// Navigation itself works (confirmed via NavDiag logs), but ParaButton.OnFocusGained
// only plays a sound and fires a UnityEvent that isn't wired to any visual change in
// this menu's prefab - so focus moves with no visible indicator. Add a generic Outline
// highlight on focus gain/loss so any focused ParaButton is visibly marked, regardless
// of what its own (possibly empty) ButtonFocused event does.
var gainedMethod = AccessTools.Method(typeof(ParaButton), "OnFocusGained");
var gainedPostfix = AccessTools.Method(typeof(ButtonFocusHighlightPatch), nameof(ButtonFocusHighlightPatch.GainedPostfix));
harmony.Patch(gainedMethod, postfix: new HarmonyMethod(gainedPostfix));
var lostMethod = AccessTools.Method(typeof(ParaButton), "OnFocusLost");
var lostPostfix = AccessTools.Method(typeof(ButtonFocusHighlightPatch), nameof(ButtonFocusHighlightPatch.LostPostfix));
harmony.Patch(lostMethod, postfix: new HarmonyMethod(lostPostfix));
Log.LogInfo("Controller Fix: Added visible focus-highlight outline to ParaButton.");
// Make gamepad focus reuse whatever IsMouseHovered visual (e.g. the main menu's
// blue underline) is already configured on a button, for exact visual parity
// instead of a second, different-looking highlight style.
var isStateActiveMethod = AccessTools.PropertyGetter(typeof(ParaButtonAnimationBase), nameof(ParaButtonAnimationBase.IsStateActive));
var isStateActivePostfix = AccessTools.Method(typeof(GamepadFocusVisualParityPatch), nameof(GamepadFocusVisualParityPatch.Postfix));
harmony.Patch(isStateActiveMethod, postfix: new HarmonyMethod(isStateActivePostfix));
Log.LogInfo("Controller Fix: Gamepad focus now reuses existing hover visuals.");
// Same visual-feedback gap as ParaButton, but for stock Selectable controls
// (sliders/toggles/input fields): selection works, but nothing renders it.
var selOnSelect = AccessTools.Method(typeof(Selectable), "OnSelect", new[] { typeof(BaseEventData) });
var selSelectPostfix = AccessTools.Method(typeof(SelectableFocusHighlightPatch), nameof(SelectableFocusHighlightPatch.SelectPostfix));
harmony.Patch(selOnSelect, postfix: new HarmonyMethod(selSelectPostfix));
var selOnDeselect = AccessTools.Method(typeof(Selectable), "OnDeselect", new[] { typeof(BaseEventData) });
var selDeselectPostfix = AccessTools.Method(typeof(SelectableFocusHighlightPatch), nameof(SelectableFocusHighlightPatch.DeselectPostfix));
harmony.Patch(selOnDeselect, postfix: new HarmonyMethod(selDeselectPostfix));
Log.LogInfo("Controller Fix: Added visible focus-highlight outline to Selectable controls.");
// UIInteractionsList (the whole interaction-menu panel/box) is itself a Focusable
// (UIListItemBase : ParaToggle : ParaButton : Focusable) purely because it reuses
// UIListItemBase for UIList's pooling API - it never overrides OnClick/focus
// behavior. But it still registers to the same FocusableGroup as each individual
// UIInteractionsListItem row inside it, so D-pad navigation randomly lands on the
// whole box instead of a row (confirmed: user reported focus flipping between one
// list item and the entire container). Unregister it right after it registers so
// only the actual rows are ever navigable.
var focusableOnEnable = AccessTools.Method(typeof(Focusable), "OnEnable");
var skipContainerPostfix = AccessTools.Method(typeof(SkipListContainerFocusRegistrationPatch), nameof(SkipListContainerFocusRegistrationPatch.Postfix));
harmony.Patch(focusableOnEnable, postfix: new HarmonyMethod(skipContainerPostfix));
Log.LogInfo("Controller Fix: Excluded UIInteractionsList container from gamepad focus navigation.");
// Gamepad A-presses on a focused element can be swallowed by Focusable.ClickUp's
// hover check after the (virtual or real) mouse has ever hovered that element -
// see GamepadFocusClickPatch for the _justEnabled mechanics.
var clickUpMethod = AccessTools.Method(typeof(Focusable), nameof(Focusable.ClickUp));
var clickUpPrefix = AccessTools.Method(typeof(GamepadFocusClickPatch), nameof(GamepadFocusClickPatch.Prefix));
harmony.Patch(clickUpMethod, prefix: new HarmonyMethod(clickUpPrefix));
Log.LogInfo("Controller Fix: Gamepad A-clicks on focused elements no longer blocked by stale hover state.");
// InputManager.GetCursorPosition is the single choke point nearly every world
// interaction system reads through (hover detection, item placement/rotation,
// build-mode widgets, terrain tools, etc.) - it's hardcoded to ScreenCenterPosition
// for gamepad, which is why players had to pan the camera to "aim". Override it
// with our own right-stick-driven virtual cursor position instead.
var getCursorPositionMethod = AccessTools.Method(typeof(InputManager), nameof(InputManager.GetCursorPosition));
var getCursorPositionPostfix = AccessTools.Method(typeof(VirtualCursorPositionPatch), nameof(VirtualCursorPositionPatch.Postfix));
harmony.Patch(getCursorPositionMethod, postfix: new HarmonyMethod(getCursorPositionPostfix));
// With the virtual cursor off and a menu open, A-presses on focused menu items
// also fired invisible world clicks at screen center - see
// SuppressWorldClickInMenusPatch for the mechanics.
var isPointerOverUIMethod = AccessTools.Method(typeof(InputManager), nameof(InputManager.IsPointerOverUI));
var suppressWorldClickPostfix = AccessTools.Method(typeof(SuppressWorldClickInMenusPatch), nameof(SuppressWorldClickInMenusPatch.Postfix));
harmony.Patch(isPointerOverUIMethod, postfix: new HarmonyMethod(suppressWorldClickPostfix));
Log.LogInfo("Controller Fix: World clicks suppressed while a menu is open and the virtual cursor is off.");
// CursorManager.LateUpdate unconditionally forces Cursor.visible = true every
// frame, which would show the real OS pointer stuck wherever the physical mouse
// last was, on top of our reticle. Force it off while our cursor is active.
var cursorManagerLateUpdate = AccessTools.Method(typeof(CursorManager), "LateUpdate");
var cursorManagerPrefix = AccessTools.Method(typeof(HideOSCursorPatch), nameof(HideOSCursorPatch.Prefix));
harmony.Patch(cursorManagerLateUpdate, prefix: new HarmonyMethod(cursorManagerPrefix));
Log.LogInfo("Controller Fix: Installed BG3-style virtual world cursor (toggle: left stick click).");
// TranslationManager embeds keybinding hints into tooltip text via /{ActionName}
// placeholders, resolved through KeyRebindingManager.GetBindingIndex(action,
// isGamepad, ...). Many actions referenced this way were apparently only ever
// authored/tested for keyboard and have no gamepad binding at all, so the gamepad
// lookup returns -1 and the raw fallback text "*CANNOT FIND INPUT ACTION X*"
// leaks straight into tooltips - something mouse+keyboard players would never see
// (their lookup already succeeds) and gamepad players could never see either,
// before this mod, since they couldn't freely hover items to trigger these
// tooltips in the first place. Patch the single choke point: if the gamepad
// lookup for an action fails, fall back to its keyboard binding instead of
// leaving the placeholder text on screen.
var getBindingIndexMethod = AccessTools.Method(typeof(KeyRebindingManager), nameof(KeyRebindingManager.GetBindingIndex));
var getBindingIndexPostfix = AccessTools.Method(typeof(GamepadBindingFallbackPatch), nameof(GamepadBindingFallbackPatch.Postfix));
harmony.Patch(getBindingIndexMethod, postfix: new HarmonyMethod(getBindingIndexPostfix));
Log.LogInfo("Controller Fix: Added keyboard-binding fallback for tooltips with no gamepad binding.");
// Y (the Catalog action) opens the build catalog but nothing dedicated closes it -
// SetPlayerCatalogueModeEvent only ever shows it. Make Y a toggle on gamepad: if
// the catalog is already open (player is in a build-ish state), route to
// MessageTogglePlayerMainMode, which is the game's own live<->build switch, so
// closing behaves exactly like clicking the Live Mode button. Keyboard behavior
// is untouched (the prefix only diverts when the player is on gamepad).
var catalogueModeMethod = AccessTools.Method(typeof(SetPlayerCatalogueModeEvent), "UpdateMessage");
var catalogueTogglePrefix = AccessTools.Method(typeof(CatalogToggleParityPatch), nameof(CatalogToggleParityPatch.Prefix));
harmony.Patch(catalogueModeMethod, prefix: new HarmonyMethod(catalogueTogglePrefix));
Log.LogInfo("Controller Fix: Y now toggles the build catalog open/closed on gamepad.");
// The bottom keybinding-tips bar (UIKeyBindingTipsItem.Init) hardcodes
// isGamepad: false in its GetBindingIndex call, so it always renders keyboard
// keys even mid-gamepad-session. Take over rendering when the player is on
// gamepad and show the gamepad binding as a text label. (Text for now - the game
// ships only a KeyboardAndMouseSprites TMP atlas, no controller glyph art, so
// proper Xbox glyphs need an embedded CC0 sprite sheet as a follow-up step.)
var tipsInitMethod = AccessTools.Method(typeof(UIKeyBindingTipsItem), nameof(UIKeyBindingTipsItem.Init));
var tipsInitPrefix = AccessTools.Method(typeof(GamepadKeyBindingTipsPatch), nameof(GamepadKeyBindingTipsPatch.Prefix));
harmony.Patch(tipsInitMethod, prefix: new HarmonyMethod(tipsInitPrefix));
Log.LogInfo("Controller Fix: Keybinding tips bar now shows gamepad bindings when on controller.");
// Tooltip /{ActionName} placeholders render Xbox glyph sprites on gamepad
// instead of plain binding text (embedded Kenney CC0 atlas, see XboxGlyphs).
var injectionMethod = AccessTools.Method(typeof(TranslationManager), "ActionInputKeyInjection");
var injectionPrefix = AccessTools.Method(typeof(GamepadTooltipGlyphPatch), nameof(GamepadTooltipGlyphPatch.Prefix));
harmony.Patch(injectionMethod, prefix: new HarmonyMethod(injectionPrefix));
Log.LogInfo("Controller Fix: Tooltips now show Xbox button glyphs on controller.");
// "No Snap" (Alt) / "Move Vertically" (Shift) on the triggers, contextually -
// see ContextualTriggerModifiers for why the zoom suppression is scoped the way
// it is.
var altGetter = AccessTools.PropertyGetter(typeof(InputManager), "Alt");
var shiftGetter = AccessTools.PropertyGetter(typeof(InputManager), "Shift");
var onZoomMethod = AccessTools.Method(typeof(HybridPlayer), "OnZoom");
harmony.Patch(altGetter, postfix: new HarmonyMethod(AccessTools.Method(typeof(ContextualTriggerModifiers), nameof(ContextualTriggerModifiers.AltPostfix))));
harmony.Patch(shiftGetter, postfix: new HarmonyMethod(AccessTools.Method(typeof(ContextualTriggerModifiers), nameof(ContextualTriggerModifiers.ShiftPostfix))));
harmony.Patch(onZoomMethod, prefix: new HarmonyMethod(AccessTools.Method(typeof(ContextualTriggerModifiers), nameof(ContextualTriggerModifiers.OnZoomPrefix))));
Log.LogInfo("Controller Fix: LT = No Snap, RT = Move Vertically while placing items or drawing walls (trigger zoom suspended only then).");
// Options menu: left/right on a focused settings slider adjusts its value
// instead of navigating (works with UpdateOptionsFieldNavigation, which makes
// the slider rows focusable in the first place).
var groupNavigateMethod = AccessTools.Method(typeof(FocusableGroup), "Navigate");
var sliderAdjustPrefix = AccessTools.Method(typeof(SliderAdjustNavigatePatch), nameof(SliderAdjustNavigatePatch.Prefix));
harmony.Patch(groupNavigateMethod, prefix: new HarmonyMethod(sliderAdjustPrefix));
Log.LogInfo("Controller Fix: Settings sliders are D-pad navigable and adjustable (left/right changes the value).");
// While an item/wall is being carried the catalog window is still "open" but the
// player is working in the world - stop menu nav from eating the D-pad and A.
var uiNavigateMenuMethod = AccessTools.Method(typeof(UIManager), nameof(UIManager.NavigateMenu));
var placingNavPrefix = AccessTools.Method(typeof(MenuNavSuppressedWhilePlacingPatch), nameof(MenuNavSuppressedWhilePlacingPatch.Prefix));
harmony.Patch(uiNavigateMenuMethod, prefix: new HarmonyMethod(placingNavPrefix));
Log.LogInfo("Controller Fix: Menu navigation suspended while carrying an item (D-pad rotates/switches floors, A places).");
}
catch (Exception e)
{
Log.LogError($"Controller Fix: Hook deployment failure: {e.Message}");
}
}
void OnEnable()
{
if (!DebugLogging) return;
Log?.LogInfo("Controller Fix: [Lifecycle] OnEnable called. " +
$"scene='{gameObject.scene.name}' buildIndex={gameObject.scene.buildIndex} " +
$"parent='{(gameObject.transform.parent == null ? "<none>" : gameObject.transform.parent.name)}' " +
$"hideFlags={gameObject.hideFlags} activeInHierarchy={gameObject.activeInHierarchy}");
}
void OnDisable()
{
if (!DebugLogging) return;
// gameObject is still valid here (this fires just before OnDestroy), so this is our
// last chance to see what scene/parent it was in at the moment it got torn down.
string sceneInfo;
try
{
sceneInfo = $"scene='{gameObject.scene.name}' buildIndex={gameObject.scene.buildIndex} " +
$"parent='{(gameObject.transform.parent == null ? "<none>" : gameObject.transform.parent.name)}' " +
$"hideFlags={gameObject.hideFlags}";
}
catch (Exception e)
{
sceneInfo = $"<failed to read gameObject state: {e.Message}>";
}
Log?.LogInfo("Controller Fix: [Lifecycle] OnDisable called. " + sceneInfo + "\nStack:\n" + Environment.StackTrace);
}
void OnDestroy()
{
if (!DebugLogging) return;
Log?.LogInfo("Controller Fix: [Lifecycle] OnDestroy called.\nStack:\n" + Environment.StackTrace);
}
void Start()
{
if (!DebugLogging) return;
Log?.LogInfo("Controller Fix: [Lifecycle] Start called.");
}
// UIManager.NavigateMenu is only ever called from Back.cs's Update(), which loops over
// PlayerManager.Instance.Players (household members) - at the main menu, before any save
// is loaded, that list is empty, so NavigateMenu (and any Harmony patch on it) never runs
// at all. Drive the main menu's own navigation independently every frame instead.
private static string _lastMainMenuDiagState;
private int _heartbeatFrameCount;
void Update()
{
_heartbeatFrameCount++;
if (DebugLogging && (_heartbeatFrameCount <= 5 || _heartbeatFrameCount % 180 == 0))
{
Log.LogInfo($"Controller Fix: [Heartbeat] Update() is running, frame {_heartbeatFrameCount}.");
}
// Each of these is independent and must run every frame regardless of what the
// others do - they used to live in one try block where an early `return` (e.g. "not
// in the main menu") skipped DPad gating/cursor updates entirely for the rest of the
// frame, including during real gameplay. Keep them as separate top-level calls.
UpdateMainMenuNavigation();
UpdateDPadBuildActionGating();
UpdateTimeStepping();
UpdateCatalogScrollIntoView();
UpdateOptionsFieldNavigation();
UpdateVirtualCursor();
ContextualTriggerModifiers.SuppressStaleZoom();
}
// D-pad left/right = step the game speed down/up, BG3/console-sim style:
// pause <- normal <- fast <- fastest (left) and the reverse (right). Driven from code
// rather than bindings because "one step slower/faster" needs the current speed, which
// a static InputAction binding can't express. Uses the game's own message events
// (MessageTogglePause / MessageSetTimeSpeed*) so audio cues and the UITime widget
// behave exactly as if the keyboard shortcuts were pressed.
private void UpdateTimeStepping()
{
try
{
var gamepad = Gamepad.current;
if (gamepad == null || PlayerManager.Instance == null || SystemManager.Instance == null)
{
return;
}
if (SavedGameManager.Instance == null || !SavedGameManager.Instance.HasLoadedSavedGame)
{
return;
}
var hybridPlayer = PlayerManager.Instance.HybridPlayer1;
if (hybridPlayer == null || !hybridPlayer.IsUsingGamePad)
{
return;
}
// While a shoulder is held the D-pad press belongs to a combo binding
// (LB+dpad = Undo/Redo/etc., RB+dpad = build tools), never to rotate/time.
if (gamepad.leftShoulder.isPressed || gamepad.rightShoulder.isPressed)
{
return;
}
bool stepSlower = gamepad.dpad.left.wasPressedThisFrame;
bool stepFaster = gamepad.dpad.right.wasPressedThisFrame;
if (!stepSlower && !stepFaster)
{
return;
}
// D-pad left/right rotates instead of stepping time while an item is carried
// (menu nav is suspended then, so the D-pad is free even with the catalog open)
// or selected with no menu open. The game never wired ANY gamepad control to
// SmallRotateItem - the shoulders only ever meant "switch menu tab" - and bare
// LB/RB bindings would mis-fire a 45 whenever an LB+X 90 rotate starts.
bool windowOpen = IsAnyBlockingWindowOpen(hybridPlayer);
try
{
var player = hybridPlayer.Player;
bool holdingItem = player?.ItemInPlacement != null;
bool selectedItem = player?.ItemSelected != null && !windowOpen;
if (holdingItem || selectedItem)
{
SystemManager.Instance.RegisterMessage(new MessageRotateItem
{
RotateLeft = stepSlower,
DoBigRotation = false,
PlayerIndex = player.PlayerIndex
});
return;
}
}
catch
{
return; // Player not ready - don't fall through into time stepping blind
}
// While a menu is open the D-pad navigates it, not the clock.
if (windowOpen)
{
return;
}
// Mirror the game's own guard in UpdateKeyboardShortcuts: no time control while
// something holds a pause override (cutscenes/storyboards).
try
{
if (hybridPlayer.Player != null && hybridPlayer.Player.HasPauseOverride())
{
return;
}
}
catch
{
// Player not ready - skip this frame rather than risk fighting an override.
return;
}
if (stepSlower)
{
if (ParaTime.IsPausedByPlayer)
{
return; // already at the bottom of the ladder
}
switch (ParaTime.TimeSpeedIndex)
{
case 0:
SystemManager.Instance.RegisterMessage(new MessageTogglePause());
break;
case 1:
SystemManager.Instance.RegisterMessage(new MessageSetTimeSpeedNormal());
break;
default:
SystemManager.Instance.RegisterMessage(new MessageSetTimeSpeedFast());
break;
}
}
else
{
if (ParaTime.IsPausedByPlayer)
{
// SetTimeSpeed(0) also clears IsPausedByPlayer, so this both unpauses
// and lands on normal speed - the first rung above pause.
SystemManager.Instance.RegisterMessage(new MessageSetTimeSpeedNormal());
return;
}
switch (ParaTime.TimeSpeedIndex)
{
case 0:
SystemManager.Instance.RegisterMessage(new MessageSetTimeSpeedFast());
break;
case 1:
SystemManager.Instance.RegisterMessage(new MessageSetTimeSpeedFastest());
break;
// already at fastest - nothing above
}
}
}
catch (Exception e)
{
Log.LogError($"Controller Fix: Time stepping failed: {e.Message}\n{e.StackTrace}");
}
}
// When D-pad focus lands on a catalog item that's scrolled out of the grid's viewport,
// nothing scrolls it into sight (the game's FocusableGroup nav has no ScrollRect
// awareness). Nudge the ScrollRect content the minimum distance to reveal the item.
private Focusable _lastScrolledCatalogFocus;
private void UpdateCatalogScrollIntoView()
{
try
{
var commonWindow = HybridReferences.Instance?.UIManagerCommon?.CurrentWindow;
var perPlayerWindow = PlayerManager.Instance?.HybridPlayer1?.UIManager?.CurrentWindow;
var catalog = (commonWindow as UIBuildModeCatalog) ?? (perPlayerWindow as UIBuildModeCatalog);
if (catalog == null)
{
_lastScrolledCatalogFocus = null;
return;
}
var focused = catalog.GetFocused(false);
if (focused == null || ReferenceEquals(focused, _lastScrolledCatalogFocus))
{
return;
}
_lastScrolledCatalogFocus = focused;
if (!(focused is UIBuildModeItem))
{
return;
}
var scroll = focused.GetComponentInParent<ScrollRect>();
if (scroll == null || scroll.content == null)
{
return;
}
var viewport = scroll.viewport != null ? scroll.viewport : scroll.GetComponent<RectTransform>();
var vpCorners = new Vector3[4];
viewport.GetWorldCorners(vpCorners);
var itemCorners = new Vector3[4];
((RectTransform)focused.transform).GetWorldCorners(itemCorners);
float aboveBy = itemCorners[1].y - vpCorners[1].y; // item pokes out the top
float belowBy = vpCorners[0].y - itemCorners[0].y; // item pokes out the bottom
if (aboveBy > 0f)
{
scroll.content.position -= new Vector3(0f, aboveBy, 0f);
}
else if (belowBy > 0f)
{
scroll.content.position += new Vector3(0f, belowBy, 0f);
}
}
catch (Exception e)
{
Log.LogError($"Controller Fix: Catalog scroll-into-view failed: {e.Message}");
}
}
// The options screen's right panel is inspector-generated: each row is a pooled
// UIFieldGameObject whose widgets are stock Unity UI (Slider, Toggle, TMP_InputField),
// not the game's Focusable system, so gamepad focus could never reach a slider. Fix, per
// frame while the options window is open:
// 1. Give every visible slider row a bare Focusable (all its virtuals are no-ops, so
// it's inert except for participating in focus/nav).
// 2. Re-home every Focusable under the inspector (slider rows + the ParaButton/
// ParaToggle rows the prefabs already carry) to the window's own FocusableGroup -
// same nested-group trap as the build catalog.
// 3. Drive the row's ImageHighlighted as the focus visual for slider rows (bare
// Focusables have no visuals; the game only uses ImageHighlighted in the mod-editor
// split view, never in the options menu).
// 4. Scroll the focused row into the inspector's ScrollRect viewport.
// Left/right value adjustment lives in SliderAdjustNavigatePatch.
private Focusable _lastScrolledOptionsFocus;
private void UpdateOptionsFieldNavigation()
{
try
{
var commonWindow = HybridReferences.Instance?.UIManagerCommon?.CurrentWindow;
var perPlayerWindow = PlayerManager.Instance?.HybridPlayer1?.UIManager?.CurrentWindow;
var options = (commonWindow as UIOptions) ?? (perPlayerWindow as UIOptions);
if (options == null || options.UIInspector == null)
{
_lastScrolledOptionsFocus = null;
return;
}
FocusableGroup windowGroup = options;
var fieldGOs = options.UIInspector.GetComponentsInChildren<UIFieldGameObject>(includeInactive: false);
var focused = windowGroup.GetFocused(isShoulderButton: false);
foreach (var ufg in fieldGOs)
{
bool isSliderRow = ufg.Slider != null && ufg.Slider.gameObject.activeInHierarchy
&& ufg.UIField is UIFieldSlider;
var focusable = ufg.GetComponent<Focusable>();
if (isSliderRow)
{
if (focusable == null)
{
focusable = ufg.gameObject.AddComponent<Focusable>();
}
else if (!focusable.enabled)
{
focusable.enabled = true;
}
}
else if (focusable != null && focusable.enabled && focusable.GetType() == typeof(Focusable))
{
// Pooled row got reused for a non-slider field: retire our Focusable so
// focus can't land on an invisible row (disable unregisters it).
focusable.enabled = false;
}
// Row-level focus visual for EVERY row type: bare Focusables (sliders) have
// no visuals at all, and the toggle prefabs have no gamepad-focus animation
// either, so without this a focused toggle row looked like the D-pad press
// did nothing.
if (ufg.ImageHighlighted != null)
{
bool highlight = focused != null && focused.transform.IsChildOf(ufg.transform);
if (ufg.ImageHighlighted.activeSelf != highlight)
{
ufg.ImageHighlighted.SetActive(highlight);
}
}
}
// Re-home: Focusable.OnEnable registers to the NEAREST group ancestor, which for
// inspector rows may be a nested group nothing ever drives. Move strays into the
// window's group so the game's own nav includes them. (Rows re-register to the
// nearest group every time pooling re-enables them, hence per-frame.)
foreach (var f in options.UIInspector.GetComponentsInChildren<Focusable>(includeInactive: false))
{
var groupField = Traverse.Create(f).Field("_focusableGroup");
var group = groupField.GetValue<FocusableGroup>();
if (!ReferenceEquals(group, windowGroup))
{
group?.UnregisterFocusable(f);
windowGroup.RegistrerFocusable(f); // sic - the game misspells it
groupField.SetValue(windowGroup);
}
}
// Scroll the focused row into view, once per focus change.
if (focused == null || ReferenceEquals(focused, _lastScrolledOptionsFocus))
{
return;
}
_lastScrolledOptionsFocus = focused;
if (!focused.transform.IsChildOf(options.UIInspector.transform))
{
return;
}
var scroll = focused.GetComponentInParent<ScrollRect>();
if (scroll == null || scroll.content == null)
{
return;
}
var viewport = scroll.viewport != null ? scroll.viewport : scroll.GetComponent<RectTransform>();
var vpCorners = new Vector3[4];
viewport.GetWorldCorners(vpCorners);
var itemCorners = new Vector3[4];
((RectTransform)focused.transform).GetWorldCorners(itemCorners);
float aboveBy = itemCorners[1].y - vpCorners[1].y;
float belowBy = vpCorners[0].y - itemCorners[0].y;
if (aboveBy > 0f)
{
scroll.content.position -= new Vector3(0f, aboveBy, 0f);
}
else if (belowBy > 0f)
{
scroll.content.position += new Vector3(0f, belowBy, 0f);
}
}
catch (Exception e)
{
Log.LogError($"Controller Fix: Options field navigation failed: {e.Message}");
}
}
private void UpdateMainMenuNavigation()
{
try
{
if (PlayerManager.Instance == null || UI.Instance == null)
{
LogMainMenuDiagOnce("PlayerManager.Instance or UI.Instance is null");
return;
}
var hybridPlayer = PlayerManager.Instance.HybridPlayer1;
if (hybridPlayer == null)
{
LogMainMenuDiagOnce("HybridPlayer1 is null");
return;
}
if (!hybridPlayer.IsUsingGamePad)
{
LogMainMenuDiagOnce($"IsUsingGamePad=false (currentControlScheme='{hybridPlayer.PlayerInput?.currentControlScheme}')");
return;
}
// UIMainMenu isn't tied to a specific player - it's shown before any household
// exists - so it's likely registered under the shared/common UI (-1), not player 0.
var mainMenuNeg1 = UI.GetOrNull<UIMainMenu>(-1);
var mainMenu = mainMenuNeg1 ?? UI.GetOrNull<UIMainMenu>(0);
if (mainMenu == null)
{
LogMainMenuDiagOnce("UIMainMenu instance not found at playerIndex -1 or 0");
return;
}
if (!mainMenu.IsVisible)
{
LogMainMenuDiagOnce($"UIMainMenu found (via index {(mainMenuNeg1 != null ? -1 : 0)}) but IsVisible=false");
return;
}
var perPlayerWindow = hybridPlayer.UIManager != null ? hybridPlayer.UIManager.CurrentWindow : null;
var commonWindow = (HybridReferences.Instance != null && HybridReferences.Instance.UIManagerCommon != null)
? HybridReferences.Instance.UIManagerCommon.CurrentWindow : null;
// Don't steal navigation from a sub-window (e.g. New Game/Settings) that's
// currently on top of the main menu - it should be driven by the normal
// NavigateMenu path once household/back-button registration exists for it.
if (perPlayerWindow != null || commonWindow != null)
{
LogMainMenuDiagOnce($"Blocked by CurrentWindow (perPlayer='{perPlayerWindow?.GetType().Name}', common='{commonWindow?.GetType().Name}')");
return;
}
// Focusable.OnEnable() registers each button to the NEAREST FocusableGroup
// ancestor via GetComponentInParent<FocusableGroup>(). UIContainer (which
// MainPanel is) is itself a FocusableGroup, so the main menu buttons register to
// MainPanel, not to the outer UIMainMenu window - confirmed by HasAnyFocusable
// being false when driving navigation directly on mainMenu. Navigate MainPanel.
var panel = mainMenu.MainPanel;
if (panel == null)
{
LogMainMenuDiagOnce("mainMenu.MainPanel is null");
return;
}
LogMainMenuDiagOnce($"Driving navigation on MainPanel (HasFocused={panel.HasFocused(false)}, HasAnyFocusable={panel.GetLeftMostFocusable(false) != null})");
// Navigate()'s first directional press only primes default focus and returns
// early (see FocusableGroup.Navigate) - nothing gets visibly focused until a
// second press. Prime it ourselves every frame (no-op once something's focused)
// so a default selection is visible as soon as the menu is driven by gamepad.
panel.FocusDefaultFocusable(false);
panel.NavigateMenuArrows(hybridPlayer);
panel.NavigateMenuShoulders(hybridPlayer);
panel.NavigateMenuDoClick(hybridPlayer);
}
catch (Exception e)
{
Log.LogError($"Controller Fix: Main menu navigation failed: {e.Message}\n{e.StackTrace}");
}
}
private void LogMainMenuDiagOnce(string state)
{
if (!DebugLogging || state == _lastMainMenuDiagState)
{
return;
}
_lastMainMenuDiagState = state;
Log.LogInfo($"Controller Fix: [MainMenuDiag] {state}");
}
private static string _lastDPadGateDiagState;
// BuildWall/PipetteMode/SledgehammerMode/ToggleGrid are bound to the same physical D-pad
// directions the FocusableGroup navigation system reads (ButtonDPadLeft/Right/Up/Down) for
// moving focus in any open menu/interaction window. Both fire simultaneously, so opening
// an in-game interaction menu while these are live can trigger a build tool by accident.
// Disable them whenever a real modal-ish window is open; re-enable once nothing is.
//
// Originally used the private _visibleWindows list instead of CurrentWindow, on the
// theory that non-back-button-registered windows would be invisible to a CurrentWindow
// check. In practice this backfired badly: _visibleWindows during ordinary live-mode
// play includes a pile of always-on HUD elements (UIGameBar, UIThoughtBubbles, UITime,
// UICharacters, UIInteractionQueue, UINotifications, UISkillsInProgressAndUpcomingEvents,
// UICharacterSubMenuBar, UIThoughts, ...) that are essentially ALWAYS present, so "any
// window visible" was true almost permanently and permanently disabled build actions and
// the virtual cursor. CurrentWindow (_visibleWindowsRegisteredForBackButton), confirmed
// via [NavDiag] logs, correctly turns non-null only for real modal windows (UIInteractions,
// UIEscapeMenu, loading/transition screens) and stays null for all of the above HUD noise.
// Shared by DPad build-action gating and the virtual cursor (both need to know "is a
// real menu/popup open").