forked from CnCNet/xna-cncnet-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameLobbyBase.cs
More file actions
2632 lines (2118 loc) · 107 KB
/
GameLobbyBase.cs
File metadata and controls
2632 lines (2118 loc) · 107 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 ClientCore;
using ClientCore.Statistics;
using ClientGUI;
using DTAClient.Domain;
using DTAClient.Domain.Multiplayer;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Rampastring.Tools;
using Rampastring.XNAUI;
using Rampastring.XNAUI.XNAControls;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ClientCore.Enums;
using DTAClient.DXGUI.Multiplayer.CnCNet;
using DTAClient.Online.EventArguments;
using ClientCore.Extensions;
using TextCopy;
using System.Diagnostics;
namespace DTAClient.DXGUI.Multiplayer.GameLobby
{
/// <summary>
/// A generic base for all game lobbies (Skirmish, LAN and CnCNet).
/// Contains the common logic for parsing game options and handling player info.
/// </summary>
public abstract class GameLobbyBase : INItializableWindow
{
protected const int MAX_PLAYER_COUNT = 8;
protected const int PLAYER_OPTION_VERTICAL_MARGIN = 12;
protected const int PLAYER_OPTION_HORIZONTAL_MARGIN = 3;
protected const int PLAYER_OPTION_CAPTION_Y = 6;
private const int DROP_DOWN_HEIGHT = 21;
protected readonly string BTN_LAUNCH_GAME = "Launch Game".L10N("Client:Main:ButtonLaunchGame");
protected readonly string BTN_LAUNCH_READY = "I'm Ready".L10N("Client:Main:ButtonIAmReady");
protected readonly string BTN_LAUNCH_NOT_READY = "Not Ready".L10N("Client:Main:ButtonNotReady");
private readonly string FavoriteMapsLabel = "Favorite Maps".L10N("Client:Main:FavoriteMaps");
private const int RANK_NONE = 0;
private const int RANK_EASY = 1;
private const int RANK_MEDIUM = 2;
private const int RANK_HARD = 3;
/// <summary>
/// Creates a new instance of the game lobby base.
/// </summary>
/// <param name="windowManager"></param>
/// <param name="iniName">The name of the lobby in GameOptions.ini.</param>
/// <param name="mapLoader"></param>
/// <param name="isMultiplayer"></param>
/// <param name="discordHandler"></param>
public GameLobbyBase(
WindowManager windowManager,
string iniName,
MapLoader mapLoader,
bool isMultiplayer,
DiscordHandler discordHandler
) : base(windowManager)
{
_iniSectionName = iniName;
MapLoader = mapLoader;
this.isMultiplayer = isMultiplayer;
this.discordHandler = discordHandler;
}
private string _iniSectionName;
protected XNAPanel PlayerOptionsPanel;
protected List<MultiplayerColor> MPColors;
public List<GameLobbyCheckBox> CheckBoxes = new List<GameLobbyCheckBox>();
public List<GameLobbyDropDown> DropDowns = new List<GameLobbyDropDown>();
protected DiscordHandler discordHandler;
protected MapLoader MapLoader;
/// <summary>
/// The list of multiplayer game mode maps.
/// Each is an instance of a map for a specific game mode.
/// </summary>
protected GameModeMapCollection GameModeMaps => MapLoader.GameModeMaps;
protected GameModeMapFilter gameModeMapFilter;
private GameModeMap _gameModeMap;
/// <summary>
/// The currently selected game mode.
/// </summary>
protected GameModeMap GameModeMap
{
get => _gameModeMap;
set
{
var oldGameModeMap = _gameModeMap;
_gameModeMap = value;
if (value != null && oldGameModeMap != value)
UpdateDiscordPresence();
}
}
protected Map Map => GameModeMap?.Map;
protected GameMode GameMode => GameModeMap?.GameMode;
protected XNAClientDropDown[] ddPlayerNames;
protected XNAClientDropDown[] ddPlayerSides;
protected XNAClientDropDown[] ddPlayerColors;
protected XNAClientDropDown[] ddPlayerStarts;
protected XNAClientDropDown[] ddPlayerTeams;
protected XNAClientButton btnPlayerExtraOptionsOpen;
protected PlayerExtraOptionsPanel PlayerExtraOptionsPanel;
protected XNAClientButton btnLeaveGame;
protected GameLaunchButton btnLaunchGame;
protected XNAClientButton btnPickRandomMap;
protected XNALabel lblMapName;
protected XNALabel lblMapAuthor;
protected XNALabel lblGameMode;
protected XNALabel lblMapSize;
protected MapPreviewBox MapPreviewBox;
protected XNAMultiColumnListBox lbGameModeMapList;
protected ToolTip mapListTooltip;
protected XNAClientDropDown ddGameModeMapFilter;
protected XNALabel lblGameModeSelect;
protected XNAContextMenu mapContextMenu;
private XNAContextMenuItem toggleFavoriteItem;
protected XNAClientStateButton<SortDirection> btnMapSortAlphabetically;
protected XNASuggestionTextBox tbMapSearch;
protected List<PlayerInfo> Players = new List<PlayerInfo>();
protected List<PlayerInfo> AIPlayers = new List<PlayerInfo>();
protected virtual PlayerInfo FindLocalPlayer() => Players.Find(p => p.Name == ProgramConstants.PLAYERNAME);
protected bool PlayerUpdatingInProgress { get; set; }
protected Texture2D[] RankTextures;
/// <summary>
/// The seed used for randomizing player options.
/// </summary>
protected int RandomSeed { get; set; }
/// <summary>
/// An unique identifier for this game.
/// </summary>
protected int UniqueGameID { get; set; }
protected int SideCount { get; private set; }
protected int RandomSelectorCount { get; private set; } = 1;
protected List<int[]> RandomSelectors = new List<int[]>();
private readonly bool isMultiplayer = false;
private MatchStatistics matchStatistics;
private bool disableGameOptionUpdateBroadcast = false;
protected EventHandler<MultiplayerNameRightClickedEventArgs> MultiplayerNameRightClicked;
/// <summary>
/// If set, the client will remove all starting waypoints from the map
/// before launching it.
/// </summary>
protected bool RemoveStartingLocations { get; set; } = false;
protected IniFile GameOptionsIni { get; private set; }
protected XNAClientButton btnSaveLoadGameOptions { get; set; }
private XNAContextMenu loadSaveGameOptionsMenu { get; set; }
private LoadOrSaveGameOptionPresetWindow loadOrSaveGameOptionPresetWindow;
public override void Initialize()
{
Name = _iniSectionName;
//if (WindowManager.RenderResolutionY < 800)
// ClientRectangle = new Rectangle(0, 0, WindowManager.RenderResolutionX, WindowManager.RenderResolutionY);
//else
ClientRectangle = new Rectangle(0, 0, WindowManager.RenderResolutionX - 60, WindowManager.RenderResolutionY - 32);
WindowManager.CenterControlOnScreen(this);
BackgroundTexture = AssetLoader.LoadTexture("gamelobbybg.png");
RankTextures = new Texture2D[4]
{
AssetLoader.LoadTexture("rankNone.png"),
AssetLoader.LoadTexture("rankEasy.png"),
AssetLoader.LoadTexture("rankNormal.png"),
AssetLoader.LoadTexture("rankHard.png")
};
MPColors = MultiplayerColor.LoadColors();
GameOptionsIni = new IniFile(SafePath.CombineFilePath(ProgramConstants.GetBaseResourcePath(), "GameOptions.ini"));
base.Initialize();
try
{
PlayerOptionsPanel = FindChild<XNAPanel>(nameof(PlayerOptionsPanel));
}
catch (Exception ex)
{
throw new Exception(string.Format("It seems the client configuration was not migrated to accommodate for the 'Tiberian Sun Client v6 Changes'.\n\nPlease refer to {0} for more details.\n\nError message: {1}".L10N("Client:Main:NotMigratedClientException"),
"https://github.com/CnCNet/xna-cncnet-client/blob/122b2de962afc404e203290d0618363d83c4264a/Docs/Migration-INI.md",
ex.Message));
}
btnLeaveGame = FindChild<XNAClientButton>(nameof(btnLeaveGame));
btnLeaveGame.LeftClick += BtnLeaveGame_LeftClick;
btnLaunchGame = FindChild<GameLaunchButton>(nameof(btnLaunchGame));
btnLaunchGame.LeftClick += BtnLaunchGame_LeftClick;
btnLaunchGame.InitStarDisplay(RankTextures);
MapPreviewBox = FindChild<MapPreviewBox>("MapPreviewBox");
MapPreviewBox.SetFields(Players, AIPlayers, MPColors, GameOptionsIni.GetStringValue("General", "Sides", String.Empty).Split(','), GameOptionsIni);
MapPreviewBox.ToggleFavorite += MapPreviewBox_ToggleFavorite;
lblMapName = FindChild<XNALabel>(nameof(lblMapName));
lblMapAuthor = FindChild<XNALabel>(nameof(lblMapAuthor));
lblGameMode = FindChild<XNALabel>(nameof(lblGameMode));
lblMapSize = FindChild<XNALabel>(nameof(lblMapSize));
lbGameModeMapList = FindChild<XNAMultiColumnListBox>("lbMapList"); // lbMapList for backwards compatibility
lbGameModeMapList.SelectedIndexChanged += LbGameModeMapList_SelectedIndexChanged;
lbGameModeMapList.RightClick += LbGameModeMapList_RightClick;
lbGameModeMapList.AllowKeyboardInput = true; //!isMultiplayer
mapListTooltip = new(WindowManager, masterControl: lbGameModeMapList);
mapListTooltip.FollowCursor = true;
lbGameModeMapList.HoveredIndexChanged += LbGameModeMapList_HoveredIndexChanged;
mapContextMenu = new XNAContextMenu(WindowManager);
mapContextMenu.Name = nameof(mapContextMenu);
mapContextMenu.Width = 192; // TODO autosizing
mapContextMenu.AddItem("Favorite".L10N("Client:Main:Favorite"),
selectAction: ToggleFavoriteMap);
toggleFavoriteItem = mapContextMenu.Items.First();
mapContextMenu.AddItem("Copy Map Name".L10N("Client:Main:CopyMapName"),
selectAction: () => ClipboardService.SetText(Map?.Name));
mapContextMenu.AddItem("Copy Original Name".L10N("Client:Main:CopyOriginalMapName"),
selectAction: () => ClipboardService.SetText(Map?.UntranslatedName),
visibilityChecker: () => Map?.UntranslatedName != Map?.Name);
mapContextMenu.AddItem("Delete Map".L10N("Client:Main:DeleteMap"),
selectAction: DeleteMapConfirmation,
visibilityChecker: CanDeleteMap);
AddChild(mapContextMenu);
XNAPanel rankHeader = new XNAPanel(WindowManager);
rankHeader.BackgroundTexture = AssetLoader.LoadTexture("rank.png");
rankHeader.ClientRectangle = new Rectangle(0, 0, rankHeader.BackgroundTexture.Width,
19);
XNAListBox rankListBox = new XNAListBox(WindowManager);
rankListBox.TextBorderDistance = 2;
lbGameModeMapList.AddColumn(rankHeader, rankListBox);
lbGameModeMapList.AddColumn("MAP NAME".L10N("Client:Main:MapNameHeader"), lbGameModeMapList.Width - RankTextures[1].Width - 3);
ddGameModeMapFilter = FindChild<XNAClientDropDown>("ddGameMode"); // ddGameMode for backwards compatibility
ddGameModeMapFilter.SelectedIndexChanged += DdGameModeMapFilter_SelectedIndexChanged;
ddGameModeMapFilter.AddItem(CreateGameFilterItem(FavoriteMapsLabel, new GameModeMapFilter(GetFavoriteGameModeMaps)));
foreach (GameMode gm in GameModeMaps.GameModes)
ddGameModeMapFilter.AddItem(CreateGameFilterItem(gm.UIName, new GameModeMapFilter(GetGameModeMaps(gm))));
lblGameModeSelect = FindChild<XNALabel>(nameof(lblGameModeSelect));
InitBtnMapSort();
tbMapSearch = FindChild<XNASuggestionTextBox>(nameof(tbMapSearch));
tbMapSearch.InputReceived += TbMapSearch_InputReceived;
btnPickRandomMap = FindChild<XNAClientButton>(nameof(btnPickRandomMap));
btnPickRandomMap.LeftClick += BtnPickRandomMap_LeftClick;
CheckBoxes.ForEach(chk => chk.CheckedChanged += ChkBox_CheckedChanged);
DropDowns.ForEach(dd => dd.SelectedIndexChanged += Dropdown_SelectedIndexChanged);
InitializeGameOptionPresetUI();
}
/// <summary>
/// Until the GUICreator can handle typed classes, this must remain manually done.
/// </summary>
private void InitBtnMapSort()
{
btnMapSortAlphabetically = new XNAClientStateButton<SortDirection>(WindowManager, new Dictionary<SortDirection, Texture2D>()
{
{ SortDirection.None, AssetLoader.LoadTexture("sortAlphaNone.png") },
{ SortDirection.Asc, AssetLoader.LoadTexture("sortAlphaAsc.png") },
{ SortDirection.Desc, AssetLoader.LoadTexture("sortAlphaDesc.png") },
});
btnMapSortAlphabetically.Name = nameof(btnMapSortAlphabetically);
btnMapSortAlphabetically.ClientRectangle = new Rectangle(
ddGameModeMapFilter.X + -ddGameModeMapFilter.Height - 4, ddGameModeMapFilter.Y,
ddGameModeMapFilter.Height, ddGameModeMapFilter.Height
);
btnMapSortAlphabetically.LeftClick += BtnMapSortAlphabetically_LeftClick;
btnMapSortAlphabetically.SetToolTipText("Sort Maps Alphabetically".L10N("Client:Main:MapSortAlphabeticallyToolTip"));
RefreshMapSortAlphabeticallyBtn();
AddChild(btnMapSortAlphabetically);
// Allow repositioning / disabling in INI.
ReadINIForControl(btnMapSortAlphabetically);
}
private void InitializeGameOptionPresetUI()
{
btnSaveLoadGameOptions = FindChild<XNAClientButton>(nameof(btnSaveLoadGameOptions), true);
if (btnSaveLoadGameOptions != null)
{
loadOrSaveGameOptionPresetWindow = new LoadOrSaveGameOptionPresetWindow(WindowManager);
loadOrSaveGameOptionPresetWindow.Name = nameof(loadOrSaveGameOptionPresetWindow);
loadOrSaveGameOptionPresetWindow.PresetLoaded += (sender, s) => HandleGameOptionPresetLoadCommand(s);
loadOrSaveGameOptionPresetWindow.PresetSaved += (sender, s) => HandleGameOptionPresetSaveCommand(s);
loadOrSaveGameOptionPresetWindow.Disable();
var loadConfigMenuItem = new XNAContextMenuItem()
{
Text = "Load".L10N("Client:Main:ButtonLoad"),
SelectAction = () => loadOrSaveGameOptionPresetWindow.Show(true)
};
var saveConfigMenuItem = new XNAContextMenuItem()
{
Text = "Save".L10N("Client:Main:ButtonSave"),
SelectAction = () => loadOrSaveGameOptionPresetWindow.Show(false)
};
loadSaveGameOptionsMenu = new XNAContextMenu(WindowManager);
loadSaveGameOptionsMenu.Name = nameof(loadSaveGameOptionsMenu);
loadSaveGameOptionsMenu.ClientRectangle = new Rectangle(0, 0, 75, 0);
loadSaveGameOptionsMenu.Items.Add(loadConfigMenuItem);
loadSaveGameOptionsMenu.Items.Add(saveConfigMenuItem);
btnSaveLoadGameOptions.LeftClick += (sender, args) =>
loadSaveGameOptionsMenu.Open(GetCursorPoint());
AddChild(loadSaveGameOptionsMenu);
AddChild(loadOrSaveGameOptionPresetWindow);
}
}
private void BtnMapSortAlphabetically_LeftClick(object sender, EventArgs e)
{
UserINISettings.Instance.MapSortState.Value = (int)btnMapSortAlphabetically.GetState();
RefreshMapSortAlphabeticallyBtn();
UserINISettings.Instance.SaveSettings();
ListMaps();
}
private void RefreshMapSortAlphabeticallyBtn()
{
if (Enum.IsDefined(typeof(SortDirection), UserINISettings.Instance.MapSortState.Value))
btnMapSortAlphabetically.SetState((SortDirection)UserINISettings.Instance.MapSortState.Value);
}
private static XNADropDownItem CreateGameFilterItem(string text, GameModeMapFilter filter)
{
return new XNADropDownItem
{
Text = text,
Tag = filter
};
}
protected bool IsFavoriteMapsSelected() => ddGameModeMapFilter.SelectedItem?.Text == FavoriteMapsLabel;
private List<GameModeMap> GetFavoriteGameModeMaps() =>
GameModeMaps.Where(gmm => gmm.IsFavorite).ToList();
private Func<List<GameModeMap>> GetGameModeMaps(GameMode gm) => () =>
GameModeMaps.Where(gmm => gmm.GameMode == gm).ToList();
private void RefreshBtnPlayerExtraOptionsOpenTexture()
{
if (btnPlayerExtraOptionsOpen != null)
{
var textureName = GetPlayerExtraOptions().IsDefault() ? "optionsButton.png" : "optionsButtonActive.png";
var hoverTextureName = GetPlayerExtraOptions().IsDefault() ? "optionsButton_c.png" : "optionsButtonActive_c.png";
var hoverTexture = AssetLoader.AssetExists(hoverTextureName) ? AssetLoader.LoadTexture(hoverTextureName) : null;
btnPlayerExtraOptionsOpen.IdleTexture = AssetLoader.LoadTexture(textureName);
btnPlayerExtraOptionsOpen.HoverTexture = hoverTexture;
}
}
protected void HandleGameOptionPresetSaveCommand(GameOptionPresetEventArgs e) => HandleGameOptionPresetSaveCommand(e.PresetName);
protected void HandleGameOptionPresetSaveCommand(string presetName)
{
string error = AddGameOptionPreset(presetName);
if (!string.IsNullOrEmpty(error))
AddNotice(error);
}
protected void HandleGameOptionPresetLoadCommand(GameOptionPresetEventArgs e) => HandleGameOptionPresetLoadCommand(e.PresetName);
protected void HandleGameOptionPresetLoadCommand(string presetName)
{
if (LoadGameOptionPreset(presetName))
AddNotice("Game option preset loaded succesfully.".L10N("Client:Main:PresetLoaded"));
else
AddNotice(string.Format("Preset {0} not found!".L10N("Client:Main:PresetNotFound"), presetName));
}
protected void AddNotice(string message) => AddNotice(message, Color.White);
protected abstract void AddNotice(string message, Color color);
private void BtnPickRandomMap_LeftClick(object sender, EventArgs e) => PickRandomMap();
private void TbMapSearch_InputReceived(object sender, EventArgs e) => ListMaps();
private void Dropdown_SelectedIndexChanged(object sender, EventArgs e)
{
if (disableGameOptionUpdateBroadcast)
return;
var dd = (GameLobbyDropDown)sender;
dd.HostSelectedIndex = dd.SelectedIndex;
OnGameOptionChanged();
}
private void ChkBox_CheckedChanged(object sender, EventArgs e)
{
if (disableGameOptionUpdateBroadcast)
return;
var checkBox = (GameLobbyCheckBox)sender;
checkBox.HostChecked = checkBox.Checked;
OnGameOptionChanged();
}
protected virtual void OnGameOptionChanged()
{
CheckDisallowedSides();
btnLaunchGame.SetRank(GetRank());
}
protected void DdGameModeMapFilter_SelectedIndexChanged(object sender, EventArgs e)
{
gameModeMapFilter = ddGameModeMapFilter.SelectedItem.Tag as GameModeMapFilter;
tbMapSearch.Text = string.Empty;
tbMapSearch.OnSelectedChanged();
ListMaps();
if (lbGameModeMapList.SelectedIndex == -1)
lbGameModeMapList.SelectedIndex = 0; // Select default GameModeMap
else
ChangeMap(GameModeMap);
}
protected void BtnPlayerExtraOptions_LeftClick(object sender, EventArgs e)
{
if (PlayerExtraOptionsPanel.Enabled)
PlayerExtraOptionsPanel.Disable();
else
PlayerExtraOptionsPanel.Enable();
}
protected void ApplyPlayerExtraOptions(string sender, string message)
{
var playerExtraOptions = PlayerExtraOptions.FromMessage(message);
if (PlayerExtraOptionsPanel != null)
{
if (playerExtraOptions.IsForceRandomSides != PlayerExtraOptionsPanel.IsForcedRandomSides)
AddPlayerExtraOptionForcedNotice(playerExtraOptions.IsForceRandomSides, "side selection".L10N("Client:Main:SideAsANoun"));
if (playerExtraOptions.IsForceRandomColors != PlayerExtraOptionsPanel.IsForcedRandomColors)
AddPlayerExtraOptionForcedNotice(playerExtraOptions.IsForceRandomColors, "color selection".L10N("Client:Main:ColorAsANoun"));
if (playerExtraOptions.IsForceRandomStarts != PlayerExtraOptionsPanel.IsForcedRandomStarts)
AddPlayerExtraOptionForcedNotice(playerExtraOptions.IsForceRandomStarts, "start selection".L10N("Client:Main:StartPositionAsANoun"));
if (playerExtraOptions.IsForceNoTeams != PlayerExtraOptionsPanel.IsForcedNoTeams)
AddPlayerExtraOptionForcedNotice(playerExtraOptions.IsForceNoTeams, "team selection".L10N("Client:Main:TeamAsANoun"));
if (playerExtraOptions.IsUseTeamStartMappings != PlayerExtraOptionsPanel.IsUseTeamStartMappings)
AddPlayerExtraOptionForcedNotice(!playerExtraOptions.IsUseTeamStartMappings, "auto ally".L10N("Client:Main:AutoAllyAsANoun"));
}
SetPlayerExtraOptions(playerExtraOptions);
UpdateMapPreviewBoxEnabledStatus();
}
private void AddPlayerExtraOptionForcedNotice(bool disabled, string type)
=> AddNotice(disabled ?
string.Format("The game host has disabled {0}".L10N("Client:Main:HostDisableSection"), type) :
string.Format("The game host has enabled {0}".L10N("Client:Main:HostEnableSection"), type));
protected List<GameModeMap> GetSortedGameModeMaps()
{
var gameModeMaps = gameModeMapFilter.GetGameModeMaps();
// Only apply sort if the map list sort button is available.
if (btnMapSortAlphabetically.Enabled && btnMapSortAlphabetically.Visible)
{
switch ((SortDirection)UserINISettings.Instance.MapSortState.Value)
{
case SortDirection.Asc:
gameModeMaps = gameModeMaps.OrderBy(gmm => gmm.Map.Name).ToList();
break;
case SortDirection.Desc:
gameModeMaps = gameModeMaps.OrderByDescending(gmm => gmm.Map.Name).ToList();
break;
}
}
return gameModeMaps;
}
protected void ListMaps()
{
lbGameModeMapList.SelectedIndexChanged -= LbGameModeMapList_SelectedIndexChanged;
lbGameModeMapList.ClearItems();
lbGameModeMapList.SetTopIndex(0);
lbGameModeMapList.SelectedIndex = -1;
int mapIndex = -1;
int skippedMapsCount = 0;
var isFavoriteMapsSelected = IsFavoriteMapsSelected();
var maps = GetSortedGameModeMaps();
bool gameModeMapChanged = false;
for (int i = 0; i < maps.Count; i++)
{
var gameModeMap = maps[i];
if (tbMapSearch.Text != tbMapSearch.Suggestion)
{
string promptUpper = tbMapSearch.Text.ToUpperInvariant();
bool mapMatches = gameModeMap.Map.Name.ToUpperInvariant().Contains(promptUpper)
|| gameModeMap.Map.UntranslatedName.ToUpperInvariant().Contains(promptUpper);
if (!mapMatches)
{
skippedMapsCount++;
continue;
}
}
XNAListBoxItem rankItem = new XNAListBoxItem();
if (gameModeMap.IsCoop)
{
if (StatisticsManager.Instance.HasBeatCoOpMap(gameModeMap.Map.UntranslatedName, gameModeMap.GameMode.UntranslatedUIName))
rankItem.Texture = RankTextures[Math.Abs(2 - gameModeMap.CoopDifficultyLevel) + 1];
else
rankItem.Texture = RankTextures[0];
}
else
rankItem.Texture = RankTextures[GetDefaultMapRankIndex(gameModeMap) + 1];
XNAListBoxItem mapNameItem = new XNAListBoxItem();
var mapNameText = gameModeMap.Map.Name;
if (isFavoriteMapsSelected)
mapNameText += $" - {gameModeMap.GameMode.UIName}";
mapNameItem.Text = Renderer.GetSafeString(mapNameText, lbGameModeMapList.FontIndex);
if (gameModeMap.MultiplayerOnly && !isMultiplayer)
mapNameItem.TextColor = UISettings.ActiveSettings.DisabledItemColor;
mapNameItem.Tag = gameModeMap;
XNAListBoxItem[] mapInfoArray = {
rankItem,
mapNameItem,
};
lbGameModeMapList.AddItem(mapInfoArray);
// Preserve the selected map
if (gameModeMap == GameModeMap)
{
mapIndex = i - skippedMapsCount;
gameModeMapChanged = false;
}
// Preserve the selected map, even if the game mode has changed
if (mapIndex == -1 && (gameModeMap?.Map?.Equals(GameModeMap?.Map) ?? false))
{
mapIndex = i - skippedMapsCount;
gameModeMapChanged = true;
}
}
if (mapIndex > -1)
{
lbGameModeMapList.SelectedIndex = mapIndex;
while (mapIndex > lbGameModeMapList.LastIndex)
lbGameModeMapList.TopIndex++;
}
lbGameModeMapList.SelectedIndexChanged += LbGameModeMapList_SelectedIndexChanged;
// Trigger the event manually to update GameModeMap
if (gameModeMapChanged)
LbGameModeMapList_SelectedIndexChanged();
}
protected abstract int GetDefaultMapRankIndex(GameModeMap gameModeMap);
private void LbGameModeMapList_RightClick(object sender, EventArgs e)
{
if (lbGameModeMapList.HoveredIndex < 0 || lbGameModeMapList.HoveredIndex >= lbGameModeMapList.ItemCount)
return;
lbGameModeMapList.SelectedIndex = lbGameModeMapList.HoveredIndex;
if (!mapContextMenu.Items.Any(i => i.VisibilityChecker == null || i.VisibilityChecker()))
return;
toggleFavoriteItem.Text = GameModeMap.IsFavorite ? "Remove Favorite".L10N("Client:Main:RemoveFavorite") : "Add Favorite".L10N("Client:Main:AddFavorite");
mapContextMenu.Open(GetCursorPoint());
}
private bool CanDeleteMap()
{
return Map != null && !Map.Official && !isMultiplayer;
}
private void DeleteMapConfirmation()
{
if (Map == null)
return;
var messageBox = XNAMessageBox.ShowYesNoDialog(WindowManager, "Delete Confirmation".L10N("Client:Main:DeleteMapConfirmTitle"),
string.Format("Are you sure you wish to delete the custom map {0}?".L10N("Client:Main:DeleteMapConfirmText"), Map.Name));
messageBox.YesClickedAction = DeleteSelectedMap;
}
private void MapPreviewBox_ToggleFavorite(object sender, EventArgs e) =>
ToggleFavoriteMap();
protected virtual void ToggleFavoriteMap()
{
if (GameModeMap != null)
{
GameModeMap.IsFavorite = UserINISettings.Instance.ToggleFavoriteMap(Map.UntranslatedName, GameMode.Name, GameModeMap.IsFavorite);
MapPreviewBox.RefreshFavoriteBtn();
}
}
protected void RefreshForFavoriteMapRemoved()
{
if (!gameModeMapFilter.GetGameModeMaps().Any())
{
LoadDefaultGameModeMap();
return;
}
ListMaps();
if (IsFavoriteMapsSelected())
lbGameModeMapList.SelectedIndex = 0; // the map was removed while viewing favorites
}
private void DeleteSelectedMap(XNAMessageBox messageBox)
{
try
{
MapLoader.DeleteCustomMap(GameModeMap);
tbMapSearch.Text = string.Empty;
if (GameMode.Maps.Count == 0)
{
// this will trigger another GameMode to be selected
GameModeMap = GameModeMaps.Find(gm => gm.GameMode.Maps.Count > 0);
}
else
{
// this will trigger another Map to be selected
lbGameModeMapList.SelectedIndex = lbGameModeMapList.SelectedIndex == 0 ? 1 : lbGameModeMapList.SelectedIndex - 1;
}
ListMaps();
ChangeMap(GameModeMap);
}
catch (IOException ex)
{
Logger.Log($"Deleting map {Map.BaseFilePath} failed! Message: {ex.ToString()}");
XNAMessageBox.Show(WindowManager, "Deleting Map Failed".L10N("Client:Main:DeleteMapFailedTitle"),
"Deleting map failed! Reason:".L10N("Client:Main:DeleteMapFailedText") + " " + ex.Message);
}
}
private void LbGameModeMapList_SelectedIndexChanged()
{
if (lbGameModeMapList.SelectedIndex < 0 || lbGameModeMapList.SelectedIndex >= lbGameModeMapList.ItemCount)
{
ChangeMap(null);
return;
}
XNAListBoxItem item = lbGameModeMapList.GetItem(1, lbGameModeMapList.SelectedIndex);
GameModeMap gameModeMap = (GameModeMap)item.Tag;
ChangeMap(gameModeMap);
}
private void LbGameModeMapList_SelectedIndexChanged(object sender, EventArgs e)
=> LbGameModeMapList_SelectedIndexChanged();
private void LbGameModeMapList_HoveredIndexChanged(object sender, EventArgs e)
{
if (lbGameModeMapList.HoveredIndex < 0 || lbGameModeMapList.HoveredIndex >= lbGameModeMapList.ItemCount)
{
mapListTooltip.Text = string.Empty;
return;
}
var gmm = (GameModeMap)lbGameModeMapList.GetItem(1, lbGameModeMapList.HoveredIndex).Tag;
if (gmm.Map.UntranslatedName != gmm.Map.Name)
mapListTooltip.Text = "Original name:".L10N("Client:Main:OriginalMapName") + " " + gmm.Map.UntranslatedName;
else
mapListTooltip.Text = string.Empty;
}
private void PickRandomMap()
{
int totalPlayerCount = Players.Count(p => p.SideId < ddPlayerSides[0].Items.Count - 1)
+ AIPlayers.Count;
List<Map> maps = GetMapList(totalPlayerCount);
if (maps.Count < 1)
return;
int random = new Random().Next(0, maps.Count);
bool isFavoriteMapsSelected = IsFavoriteMapsSelected();
GameModeMap = GameModeMaps.Find(gmm => (gmm.GameMode == GameMode || gmm.IsFavorite && isFavoriteMapsSelected) && gmm.Map == maps[random]);
Logger.Log("PickRandomMap: Rolled " + random + " out of " + maps.Count + ". Picked map: " + Map.Name);
ChangeMap(GameModeMap);
tbMapSearch.Text = string.Empty;
tbMapSearch.OnSelectedChanged();
ListMaps();
}
private List<Map> GetMapList(int playerCount)
{
List<Map> maps = IsFavoriteMapsSelected()
? GetFavoriteGameModeMaps().Select(gameModeMap => gameModeMap.Map).ToList()
: GameMode?.Maps.ToList() ?? new List<Map>();
if (playerCount != 1)
{
if (GameMode?.MaxPlayersOverride != null)
{
// MaxPlayers have been overridden in GameMode. This means all maps in the game mode has the same MaxPlayers value
if (playerCount != GameMode.MaxPlayersOverride)
maps = [];
}
else
{
// Maps could have different MaxPlayers values.
maps = maps.Where(x => x.MaxPlayers == playerCount).ToList();
}
if (maps.Count < 1 && playerCount <= MAX_PLAYER_COUNT)
return GetMapList(playerCount + 1);
}
return maps;
}
/// <summary>
/// Refreshes the map selection UI to match the currently selected map
/// and game mode.
/// </summary>
protected void RefreshMapSelectionUI()
{
if (GameMode == null)
return;
int gameModeMapFilterIndex = ddGameModeMapFilter.Items.FindIndex(i => i.Text == GameMode.UIName);
if (gameModeMapFilterIndex == -1)
return;
if (ddGameModeMapFilter.SelectedIndex == gameModeMapFilterIndex)
DdGameModeMapFilter_SelectedIndexChanged(this, EventArgs.Empty);
ddGameModeMapFilter.SelectedIndex = gameModeMapFilterIndex;
}
protected void AddSideToDropDown(XNADropDown dd, string name, string? uiName = null, Texture2D? texture = null)
{
XNADropDownItem item = new()
{
Text = uiName ?? name.L10N($"INI:Sides:{name}"),
Tag = name,
Texture = texture ?? LoadTextureOrNull(name + "icon.png"),
};
dd.AddItem(item);
}
/// <summary>
/// Initializes the player option drop-down controls.
/// </summary>
protected void InitPlayerOptionDropdowns()
{
ddPlayerNames = new XNAClientDropDown[MAX_PLAYER_COUNT];
ddPlayerSides = new XNAClientDropDown[MAX_PLAYER_COUNT];
ddPlayerColors = new XNAClientDropDown[MAX_PLAYER_COUNT];
ddPlayerStarts = new XNAClientDropDown[MAX_PLAYER_COUNT];
ddPlayerTeams = new XNAClientDropDown[MAX_PLAYER_COUNT];
int playerOptionVecticalMargin = ConfigIni.GetIntValue(Name, "PlayerOptionVerticalMargin", PLAYER_OPTION_VERTICAL_MARGIN);
int playerOptionHorizontalMargin = ConfigIni.GetIntValue(Name, "PlayerOptionHorizontalMargin", PLAYER_OPTION_HORIZONTAL_MARGIN);
int playerOptionCaptionLocationY = ConfigIni.GetIntValue(Name, "PlayerOptionCaptionLocationY", PLAYER_OPTION_CAPTION_Y);
int playerNameWidth = ConfigIni.GetIntValue(Name, "PlayerNameWidth", 136);
int sideWidth = ConfigIni.GetIntValue(Name, "SideWidth", 91);
int colorWidth = ConfigIni.GetIntValue(Name, "ColorWidth", 79);
int startWidth = ConfigIni.GetIntValue(Name, "StartWidth", 49);
int teamWidth = ConfigIni.GetIntValue(Name, "TeamWidth", 46);
int locationX = ConfigIni.GetIntValue(Name, "PlayerOptionLocationX", 25);
int locationY = ConfigIni.GetIntValue(Name, "PlayerOptionLocationY", 24);
// InitPlayerOptionDropdowns(136, 91, 79, 49, 46, new Point(25, 24));
string[] sides = ClientConfiguration.Instance.Sides.Split(',').ToArray();
SideCount = sides.Length;
List<string> selectorNames = new();
GetRandomSelectors(selectorNames, RandomSelectors);
RandomSelectorCount = RandomSelectors.Count + 1;
MapPreviewBox.RandomSelectorCount = RandomSelectorCount;
string randomColor = GameOptionsIni.GetStringValue("General", "RandomColor", "255,255,255");
for (int i = MAX_PLAYER_COUNT - 1; i > -1; i--)
{
var ddPlayerName = new XNAClientDropDown(WindowManager);
ddPlayerName.Name = "ddPlayerName" + i;
ddPlayerName.ClientRectangle = new Rectangle(locationX,
locationY + (DROP_DOWN_HEIGHT + playerOptionVecticalMargin) * i,
playerNameWidth, DROP_DOWN_HEIGHT);
ddPlayerName.AddItem(String.Empty);
ProgramConstants.AI_PLAYER_NAMES.ForEach(ddPlayerName.AddItem);
ddPlayerName.AllowDropDown = true;
ddPlayerName.SelectedIndexChanged += CopyPlayerDataFromUI;
ddPlayerName.RightClick += MultiplayerName_RightClick;
ddPlayerName.Tag = true;
var ddPlayerSide = new XNAClientDropDown(WindowManager);
ddPlayerSide.Name = "ddPlayerSide" + i;
ddPlayerSide.ClientRectangle = new Rectangle(
ddPlayerName.Right + playerOptionHorizontalMargin,
ddPlayerName.Y, sideWidth, DROP_DOWN_HEIGHT);
const string randomName = "Random";
AddSideToDropDown(ddPlayerSide, randomName, randomName.L10N("Client:Sides:RandomSide"), LoadTextureOrNull("randomicon.png"));
foreach (string randomSelector in selectorNames)
AddSideToDropDown(ddPlayerSide, randomSelector);
foreach (string sideName in sides)
AddSideToDropDown(ddPlayerSide, sideName);
ddPlayerSide.AllowDropDown = false;
ddPlayerSide.SelectedIndexChanged += CopyPlayerDataFromUI;
ddPlayerSide.Tag = true;
var ddPlayerColor = new XNAClientDropDown(WindowManager);
ddPlayerColor.Name = "ddPlayerColor" + i;
ddPlayerColor.ClientRectangle = new Rectangle(
ddPlayerSide.Right + playerOptionHorizontalMargin,
ddPlayerName.Y, colorWidth, DROP_DOWN_HEIGHT);
ddPlayerColor.AddItem("Random".L10N("Client:Main:RandomColor"), AssetLoader.GetColorFromString(randomColor));
foreach (MultiplayerColor mpColor in MPColors)
ddPlayerColor.AddItem(mpColor.Name, mpColor.XnaColor);
ddPlayerColor.AllowDropDown = false;
ddPlayerColor.SelectedIndexChanged += CopyPlayerDataFromUI;
ddPlayerColor.Tag = false;
var ddPlayerTeam = new XNAClientDropDown(WindowManager);
ddPlayerTeam.Name = "ddPlayerTeam" + i;
ddPlayerTeam.ClientRectangle = new Rectangle(
ddPlayerColor.Right + playerOptionHorizontalMargin,
ddPlayerName.Y, teamWidth, DROP_DOWN_HEIGHT);
ddPlayerTeam.AddItem("-");
ProgramConstants.TEAMS.ForEach(ddPlayerTeam.AddItem);
ddPlayerTeam.AllowDropDown = false;
ddPlayerTeam.SelectedIndexChanged += CopyPlayerDataFromUI;
ddPlayerTeam.Tag = true;
var ddPlayerStart = new XNAClientDropDown(WindowManager);
ddPlayerStart.Name = "ddPlayerStart" + i;
ddPlayerStart.ClientRectangle = new Rectangle(
ddPlayerTeam.Right + playerOptionHorizontalMargin,
ddPlayerName.Y, startWidth, DROP_DOWN_HEIGHT);
for (int j = 1; j < 9; j++)
ddPlayerStart.AddItem(j.ToString());
ddPlayerStart.AllowDropDown = false;
ddPlayerStart.SelectedIndexChanged += CopyPlayerDataFromUI;
ddPlayerStart.Visible = false;
ddPlayerStart.Enabled = false;
ddPlayerStart.Tag = true;
ddPlayerNames[i] = ddPlayerName;
ddPlayerSides[i] = ddPlayerSide;
ddPlayerColors[i] = ddPlayerColor;
ddPlayerStarts[i] = ddPlayerStart;
ddPlayerTeams[i] = ddPlayerTeam;
PlayerOptionsPanel.AddChild(ddPlayerName);
PlayerOptionsPanel.AddChild(ddPlayerSide);
PlayerOptionsPanel.AddChild(ddPlayerColor);
PlayerOptionsPanel.AddChild(ddPlayerStart);
PlayerOptionsPanel.AddChild(ddPlayerTeam);
ReadINIForControl(ddPlayerName);
ReadINIForControl(ddPlayerSide);
ReadINIForControl(ddPlayerColor);
ReadINIForControl(ddPlayerStart);
ReadINIForControl(ddPlayerTeam);
}
var lblName = GeneratePlayerOptionCaption("lblName", "PLAYER".L10N("Client:Main:PlayerOptionPlayer"), ddPlayerNames[0].X, playerOptionCaptionLocationY);
var lblSide = GeneratePlayerOptionCaption("lblSide", "SIDE".L10N("Client:Main:PlayerOptionSide"), ddPlayerSides[0].X, playerOptionCaptionLocationY);
var lblColor = GeneratePlayerOptionCaption("lblColor", "COLOR".L10N("Client:Main:PlayerOptionColor"), ddPlayerColors[0].X, playerOptionCaptionLocationY);
var lblStart = GeneratePlayerOptionCaption("lblStart", "START".L10N("Client:Main:PlayerOptionStart"), ddPlayerStarts[0].X, playerOptionCaptionLocationY);
lblStart.Visible = false;
var lblTeam = GeneratePlayerOptionCaption("lblTeam", "TEAM".L10N("Client:Main:PlayerOptionTeam"), ddPlayerTeams[0].X, playerOptionCaptionLocationY);
ReadINIForControl(lblName);
ReadINIForControl(lblSide);
ReadINIForControl(lblColor);
ReadINIForControl(lblStart);
ReadINIForControl(lblTeam);
btnPlayerExtraOptionsOpen = FindChild<XNAClientButton>(nameof(btnPlayerExtraOptionsOpen), true);
if (btnPlayerExtraOptionsOpen != null)
{
PlayerExtraOptionsPanel = FindChild<PlayerExtraOptionsPanel>(nameof(PlayerExtraOptionsPanel));
PlayerExtraOptionsPanel.Disable();
PlayerExtraOptionsPanel.OptionsChanged += PlayerExtraOptions_OptionsChanged;
btnPlayerExtraOptionsOpen.LeftClick += BtnPlayerExtraOptions_LeftClick;
}
CheckDisallowedSides();
}
private XNALabel GeneratePlayerOptionCaption(string name, string text, int x, int y)
{
var label = new XNALabel(WindowManager);
label.Name = name;
label.Text = text;
label.FontIndex = 1;
label.ClientRectangle = new Rectangle(x, y, 0, 0);
PlayerOptionsPanel.AddChild(label);
return label;
}
protected virtual void PlayerExtraOptions_OptionsChanged(object sender, EventArgs e)
{
var playerExtraOptions = GetPlayerExtraOptions();
for (int i = 0; i < MAX_PLAYER_COUNT; i++)
{
var pInfo = GetPlayerInfoForIndex(i);
// IsForceRandomSides
if (pInfo != null && playerExtraOptions.IsForceRandomSides)
pInfo.SideId = 0;
EnablePlayerOptionDropDown(ddPlayerSides[i], i, !playerExtraOptions.IsForceRandomSides);
// IsForceNoTeams
Debug.Assert(!playerExtraOptions.IsForceNoTeams || !GameModeMap.IsCoop, "Co-ops should not have force no teams enabled.");
if (pInfo != null && playerExtraOptions.IsForceNoTeams)
pInfo.TeamId = 0;
EnablePlayerOptionDropDown(ddPlayerTeams[i], i, !playerExtraOptions.IsForceNoTeams);
// IsForceRandomColors
if (pInfo != null && playerExtraOptions.IsForceRandomColors)