Merge branch 'master' of https://github.com/Regalis11/Barotrauma into develop

This commit is contained in:
EvilFactory
2024-03-28 14:26:18 -03:00
271 changed files with 13174 additions and 3021 deletions
@@ -49,7 +49,7 @@ namespace Barotrauma
static void UnlockAchievement(string id)
{
SteamAchievementManager.UnlockAchievement(id.ToIdentifier(), unlockClients: true);
AchievementManager.UnlockAchievement(id.ToIdentifier(), unlockClients: true);
}
}
@@ -9,7 +9,7 @@ using System.Xml.Linq;
namespace Barotrauma
{
class SinglePlayerCampaignSetupUI : CampaignSetupUI
sealed class SinglePlayerCampaignSetupUI : CampaignSetupUI
{
private GUIListBox subList;
@@ -550,7 +550,10 @@ namespace Barotrauma
width -= 16;
}
valueText = ToolBox.WrapText(valueText, width, GUIStyle.SubHeadingFont.Value);
if (GUIStyle.SubHeadingFont.Value != null)
{
valueText = ToolBox.WrapText(valueText, width, GUIStyle.SubHeadingFont.Value);
}
wrappedText = valueText;
}
}
@@ -974,7 +974,7 @@ namespace Barotrauma
spriteBatch.Begin(SpriteSortMode.Deferred, samplerState: GUI.SamplerState);
GUI.Draw(Cam, spriteBatch);
if (!string.IsNullOrWhiteSpace(DrawnTooltip))
if (!string.IsNullOrWhiteSpace(DrawnTooltip) && GUIStyle.SmallFont.Value != null)
{
string tooltip = ToolBox.WrapText(DrawnTooltip, 256.0f, GUIStyle.SmallFont.Value);
GUI.DrawString(spriteBatch, PlayerInput.MousePosition + new Vector2(32, 32), tooltip, Color.White, Color.Black * 0.8f, 4, GUIStyle.SmallFont);
@@ -9,7 +9,7 @@ using Microsoft.Xna.Framework.Graphics;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Collections.Immutable;
using System.Diagnostics;
using Barotrauma.IO;
using System.Linq;
@@ -21,7 +21,7 @@ using Barotrauma.Steam;
namespace Barotrauma
{
class MainMenuScreen : Screen
sealed class MainMenuScreen : Screen
{
private enum Tab
{
@@ -33,7 +33,7 @@ namespace Barotrauma
JoinServer = 5,
CharacterEditor = 6,
SubmarineEditor = 7,
SteamWorkshop = 8,
Mods = 8,
Credits = 9,
Empty = 10
}
@@ -59,6 +59,8 @@ namespace Barotrauma
private GUIImage playstyleBanner;
private GUITextBlock playstyleDescription;
private static string RemoteContentUrl => GameSettings.CurrentConfig.RemoteMainMenuContentUrl;
private readonly GUIComponent remoteContentContainer;
private XDocument remoteContentDoc;
@@ -76,11 +78,76 @@ namespace Barotrauma
private GUITextBlock tutorialHeader, tutorialDescription;
private GUIListBox tutorialList;
private readonly GUITextBlock gameAnalyticsStatusText;
private readonly GUILayoutGroup leftTextFooterLayout;
private readonly GUILayoutGroup rightTextFooterLayout;
private GUIComponent versionMismatchWarning;
#region Creation
public MainMenuScreen(GameMain game)
public MainMenuScreen(GameMain game) : base()
{
leftTextFooterLayout = createTextFooter();
rightTextFooterLayout = createTextFooter();
gameAnalyticsStatusText = createLeftText(TextManager.Get($"GameAnalyticsStatus.{GameAnalyticsManager.Consent.Unknown}"));
createLeftText("Barotrauma v" + GameMain.Version + " (" + AssemblyInfo.BuildString + ", branch " + AssemblyInfo.GitBranch + ", revision " + AssemblyInfo.GitRevision + ")");
var privacyPolicyText = createRightText(TextManager.Get("privacypolicy").Fallback("Privacy policy"));
(Rectangle Rect, bool MouseOn) getPrivacyPolicyHoverRect()
{
var textSize = privacyPolicyText.Font.MeasureString(privacyPolicyText.Text);
var bottomRight = privacyPolicyText.Rect.Location.ToVector2()
+ privacyPolicyText.TextPos
+ privacyPolicyText.TextOffset;
var rect = new Rectangle((bottomRight - textSize).ToPoint(), textSize.ToPoint());
bool mouseOn = rect.Contains(PlayerInput.LatestMousePosition) && GUI.IsMouseOn(privacyPolicyText);
return (rect, mouseOn);
}
new GUICustomComponent(new RectTransform(Vector2.One, privacyPolicyText.RectTransform),
onUpdate: (dt, component) =>
{
var (_, mouseOn) = getPrivacyPolicyHoverRect();
if (mouseOn && PlayerInput.PrimaryMouseButtonClicked())
{
GameMain.ShowOpenUriPrompt("https://privacypolicy.daedalic.com");
}
},
onDraw: (sb, component) =>
{
var (rect, mouseOn) = getPrivacyPolicyHoverRect();
Color color = mouseOn ? Color.White : Color.White * 0.7f;
privacyPolicyText.TextColor = color;
GUI.DrawLine(sb, new Vector2(rect.Left, rect.Bottom), new Vector2(rect.Right, rect.Bottom), color);
});
createRightText("© " + DateTime.Now.Year + " Undertow Games & FakeFish. All rights reserved.");
createRightText("© " + DateTime.Now.Year + " Daedalic Entertainment GmbH. The Daedalic logo is a trademark of Daedalic Entertainment GmbH, Germany. All rights reserved.");
GUILayoutGroup createTextFooter()
=> new GUILayoutGroup(new RectTransform((1.0f, 0.06f), Frame.RectTransform, Anchor.BottomCenter))
{
ChildAnchor = Anchor.BottomLeft
};
GUITextBlock createTextInFooter(GUILayoutGroup footer, LocalizedString str, Alignment textAlignment)
{
var textBlock = new GUITextBlock(
rectT: new RectTransform((1.0f, 0.3f), footer.RectTransform),
text: str,
textAlignment: textAlignment,
font: GUIStyle.SmallFont,
textColor: Color.White * 0.7f);
textBlock.RectTransform.SetAsFirstChild();
return textBlock;
}
GUITextBlock createLeftText(LocalizedString str)
=> createTextInFooter(leftTextFooterLayout, str, Alignment.BottomLeft);
GUITextBlock createRightText(LocalizedString str)
=> createTextInFooter(rightTextFooterLayout, str, Alignment.BottomRight);
GameMain.Instance.ResolutionChanged += () =>
{
SetMenuTabPositioning();
@@ -306,7 +373,7 @@ namespace Barotrauma
{
ForceUpperCase = ForceUpperCase.Yes,
Enabled = true,
UserData = Tab.SteamWorkshop,
UserData = Tab.Mods,
OnClicked = SelectTab
};
@@ -321,7 +388,7 @@ namespace Barotrauma
},
Visible = false
};
new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), customizeList.RectTransform), TextManager.Get("SubEditorButton"), textAlignment: Alignment.Left, style: "MainMenuGUIButton")
{
ForceUpperCase = ForceUpperCase.Yes,
@@ -378,7 +445,7 @@ namespace Barotrauma
OnClicked = (button, userData) =>
{
string url = TextManager.Get("EditorDisclaimerWikiUrl").Fallback("https://barotraumagame.com/wiki").Value;
GameMain.ShowOpenUrlInWebBrowserPrompt(url, promptExtensionTag: "wikinotice");
GameMain.ShowOpenUriPrompt(url, promptExtensionTag: "wikinotice");
return true;
}
};
@@ -474,39 +541,40 @@ namespace Barotrauma
menuTabs = new Dictionary<Tab, GUIFrame>
{
[Tab.Settings] = new GUIFrame(new RectTransform(new Vector2(relativeSize.X, 0.8f), GUI.Canvas, anchor, pivot, minSize, maxSize) { RelativeOffset = relativeOffset },
[Tab.Settings] = new GUIFrame(new RectTransform(new Vector2(relativeSize.X, 0.8f), Frame.RectTransform, anchor, pivot, minSize, maxSize) { RelativeOffset = relativeOffset },
style: null)
{
CanBeFocused = false
},
[Tab.NewGame] = new GUIFrame(new RectTransform(relativeSize * new Vector2(1.0f, 1.15f), GUI.Canvas, anchor, pivot, minSize, maxSize) { RelativeOffset = relativeOffset }),
[Tab.LoadGame] = new GUIFrame(new RectTransform(relativeSize, GUI.Canvas, anchor, pivot, minSize, maxSize) { RelativeOffset = relativeOffset })
[Tab.NewGame] = new GUIFrame(new RectTransform(relativeSize * new Vector2(1.0f, 1.15f), Frame.RectTransform, anchor, pivot, minSize, maxSize) { RelativeOffset = relativeOffset }),
[Tab.LoadGame] = new GUIFrame(new RectTransform(relativeSize, Frame.RectTransform, anchor, pivot, minSize, maxSize) { RelativeOffset = relativeOffset })
};
CreateCampaignSetupUI();
var hostServerScale = new Vector2(0.7f, 1.2f);
menuTabs[Tab.HostServer] = new GUIFrame(new RectTransform(
Vector2.Multiply(relativeSize, hostServerScale), GUI.Canvas, anchor, pivot, minSize.Multiply(hostServerScale), maxSize.Multiply(hostServerScale))
Vector2.Multiply(relativeSize, hostServerScale), Frame.RectTransform, anchor, pivot, minSize.Multiply(hostServerScale), maxSize.Multiply(hostServerScale))
{ RelativeOffset = relativeOffset });
CreateHostServerFields();
//----------------------------------------------------------------------
menuTabs[Tab.Tutorials] = new GUIFrame(new RectTransform(relativeSize, GUI.Canvas, anchor, pivot, minSize, maxSize) { RelativeOffset = relativeOffset });
menuTabs[Tab.Tutorials] = new GUIFrame(new RectTransform(relativeSize, Frame.RectTransform, anchor, pivot, minSize, maxSize) { RelativeOffset = relativeOffset });
CreateTutorialTab();
this.game = game;
menuTabs[Tab.Credits] = new GUIFrame(new RectTransform(Vector2.One, GUI.Canvas, Anchor.Center), style: null)
menuTabs[Tab.Credits] = new GUIFrame(new RectTransform(Vector2.One, Frame.RectTransform, Anchor.Center), style: null)
{
CanBeFocused = false
};
new GUIFrame(new RectTransform(GUI.Canvas.RelativeSize, menuTabs[Tab.Credits].RectTransform, Anchor.Center), style: "GUIBackgroundBlocker")
var blockerFrame = new GUIFrame(new RectTransform(GUI.Canvas.RelativeSize, menuTabs[Tab.Credits].RectTransform, Anchor.Center), style: "GUIBackgroundBlocker")
{
CanBeFocused = false
};
blockerFrame.RectTransform.RelativeOffset = GUI.IsUltrawide ? Vector2.Zero : new Vector2(0.05f, 0.0f);
var creditsContainer = new GUIFrame(new RectTransform(new Vector2(0.75f, 1.5f), menuTabs[Tab.Credits].RectTransform, Anchor.CenterRight), style: "OuterGlow", color: Color.Black * 0.8f);
creditsPlayer = new CreditsPlayer(new RectTransform(Vector2.One, creditsContainer.RectTransform), "Content/Texts/Credits.xml");
@@ -517,6 +585,7 @@ namespace Barotrauma
};
SetMenuTabPositioning();
SelectTab(Tab.Empty);
}
private void SetMenuTabPositioning()
@@ -611,7 +680,7 @@ namespace Barotrauma
GameMain.LuaCs.Stop();
ResetModUpdateButton();
if (WorkshopItemsToUpdate.Any())
{
while (WorkshopItemsToUpdate.TryDequeue(out ulong workshopId))
@@ -636,6 +705,8 @@ namespace Barotrauma
versionMismatchWarning.Visible = GameMain.Version < ContentPackageManager.VanillaCorePackage.GameVersion;
ResetButtonStates(null);
Eos.EosAccount.ExecuteAfterLogin(AchievementManager.SyncBetweenPlatforms);
}
public override void Deselect()
@@ -751,7 +822,7 @@ namespace Barotrauma
case Tab.SubmarineEditor:
CoroutineManager.StartCoroutine(SelectScreenWithWaitCursor(GameMain.SubEditorScreen));
break;
case Tab.SteamWorkshop:
case Tab.Mods:
var settings = SettingsMenu.Create(menuTabs[Tab.Settings].RectTransform);
settings.SelectTab(SettingsMenu.Tab.Mods);
tab = Tab.Settings;
@@ -767,6 +838,14 @@ namespace Barotrauma
}
selectedTab = tab;
leftTextFooterLayout.Visible = tab != Tab.Credits;
rightTextFooterLayout.Visible = tab != Tab.Credits;
foreach (var tabFrame in menuTabs.Values)
{
tabFrame.Visible = false;
}
if (menuTabs.TryGetValue(selectedTab, out var visibleTab)) { visibleTab.Visible = true; }
return true;
}
@@ -891,6 +970,17 @@ namespace Barotrauma
tutorialSkipWarning.Buttons[1].OnClicked += proceedToTab(Tab.Tutorials);
}
public override void AddToGUIUpdateList()
{
base.AddToGUIUpdateList();
switch (selectedTab)
{
case Tab.NewGame:
campaignSetupUI.CharacterMenus?.ForEach(static m => m.AddToGUIUpdateList());
break;
}
}
private void UpdateTutorialList()
{
foreach (GUITextBlock tutorialText in tutorialList.Content.Children)
@@ -971,35 +1061,55 @@ namespace Barotrauma
#endif
}
string arguments =
"-name \"" + ToolBox.EscapeCharacters(name) + "\"" +
" -public " + isPublicBox.Selected.ToString() +
" -playstyle " + ((PlayStyle)playstyleBanner.UserData).ToString() +
" -banafterwrongpassword " + wrongPasswordBanBox.Selected.ToString() +
" -karmaenabled " + (!karmaBox.Selected).ToString() +
" -maxplayers " + maxPlayersBox.Text +
$" -language \"{(LanguageIdentifier)languageDropdown.SelectedData}\"";
var arguments = new List<string>
{
"-name", name,
"-public", isPublicBox.Selected.ToString(),
"-playstyle", ((PlayStyle)playstyleBanner.UserData).ToString(),
"-banafterwrongpassword", wrongPasswordBanBox.Selected.ToString(),
"-karmaenabled", (!karmaBox.Selected).ToString(),
"-maxplayers", maxPlayersBox.Text,
"-language", languageDropdown.SelectedData.ToString()
};
if (!string.IsNullOrWhiteSpace(passwordBox.Text))
{
arguments += " -password \"" + ToolBox.EscapeCharacters(passwordBox.Text) + "\"";
arguments.Add("-password");
arguments.Add(passwordBox.Text);
}
else
{
arguments += " -nopassword";
arguments.Add("-nopassword");
}
if (SteamManager.GetSteamId().TryUnwrap(out var steamId1))
var puids = EosInterface.IdQueries.GetLoggedInPuids();
var endpoints = new List<Endpoint>();
if (SteamManager.GetSteamId().TryUnwrap(out var steamId))
{
arguments += " -steamid " + steamId1.Value;
endpoints.Add(new SteamP2PEndpoint(steamId));
}
if (puids.Length > 0)
{
endpoints.Add(new EosP2PEndpoint(puids[0]));
}
if (endpoints.Count == 0)
{
endpoints.Add(new LidgrenEndpoint(IPAddress.Loopback, NetConfig.DefaultPort));
}
if (endpoints.First() is P2PEndpoint firstEndpoint)
{
arguments.Add("-endpoint");
arguments.Add(firstEndpoint.StringRepresentation);
}
int ownerKey = Math.Max(CryptoRandom.Instance.Next(), 1);
arguments += " -ownerkey " + ownerKey;
arguments.Add("-ownerkey");
arguments.Add(ownerKey.ToString());
var processInfo = new ProcessStartInfo
{
FileName = fileName,
Arguments = arguments,
WorkingDirectory = Directory.GetCurrentDirectory(),
#if !DEBUG
CreateNoWindow = true,
@@ -1007,16 +1117,15 @@ namespace Barotrauma
WindowStyle = ProcessWindowStyle.Hidden
#endif
};
arguments.ForEach(processInfo.ArgumentList.Add);
ChildServerRelay.Start(processInfo);
Thread.Sleep(1000); //wait until the server is ready before connecting
GameMain.Client = new GameClient(MultiplayerPreferences.Instance.PlayerName.FallbackNullOrEmpty(
SteamManager.GetUsername().FallbackNullOrEmpty(name)),
SteamManager.GetSteamId().TryUnwrap(out var steamId)
? new SteamP2PEndpoint(steamId)
: (Endpoint)new LidgrenEndpoint(IPAddress.Loopback, NetConfig.DefaultPort),
endpoints.ToImmutableArray(),
name,
Option<int>.Some(ownerKey));
Option.Some(ownerKey));
}
catch (Exception e)
{
@@ -1030,21 +1139,6 @@ namespace Barotrauma
return true;
}
public override void AddToGUIUpdateList()
{
Frame.AddToGUIUpdateList();
if (selectedTab < Tab.Empty && menuTabs.TryGetValue(selectedTab, out GUIFrame tab) && tab != null)
{
tab.AddToGUIUpdateList();
switch (selectedTab)
{
case Tab.NewGame:
campaignSetupUI.CharacterMenus?.ForEach(m => m.AddToGUIUpdateList());
break;
}
}
}
private void UpdateOutOfDateWorkshopItemCount()
{
if (DateTime.Now < modUpdateStatus.WhenToRefresh) { return; }
@@ -1079,16 +1173,16 @@ namespace Barotrauma
modUpdateStatus = (DateTime.Now + ModUpdateInterval, count);
}
private static bool CanHostServer()
=> EosInterface.IdQueries.IsLoggedIntoEosConnect
|| SteamManager.IsInitialized
|| AssemblyInfo.CurrentConfiguration == AssemblyInfo.Configuration.Debug;
public override void Update(double deltaTime)
{
#if DEBUG
hostServerButton.Enabled = true;
#else
if (GameSettings.CurrentConfig.UseSteamMatchmaking)
{
hostServerButton.Enabled = SteamManager.IsInitialized;
}
#endif
hostServerButton.Enabled = CanHostServer();
gameAnalyticsStatusText.Text = TextManager.Get($"GameAnalyticsStatus.{GameAnalyticsManager.UserConsented}");
UpdateOutOfDateWorkshopItemCount();
modUpdatesButton.Visible = modUpdateStatus.Count > 0;
@@ -1145,13 +1239,6 @@ namespace Barotrauma
}
}
readonly LocalizedString[] legalCrap = new LocalizedString[]
{
TextManager.Get("privacypolicy").Fallback("Privacy policy"),
"© " + DateTime.Now.Year + " Undertow Games & FakeFish. All rights reserved.",
"© " + DateTime.Now.Year + " Daedalic Entertainment GmbH. The Daedalic logo is a trademark of Daedalic Entertainment GmbH, Germany. All rights reserved."
};
public override void Draw(double deltaTime, GraphicsDevice graphics, SpriteBatch spriteBatch)
{
spriteBatch.Begin(SpriteSortMode.Deferred, null, GUI.SamplerState, null, GameMain.ScissorTestEnable);
@@ -1160,42 +1247,6 @@ namespace Barotrauma
GUI.Draw(Cam, spriteBatch);
if (selectedTab != Tab.Credits)
{
#if !UNSTABLE
string versionString = "Barotrauma v" + GameMain.Version + " (" + AssemblyInfo.BuildString + ", branch " + AssemblyInfo.GitBranch + ", revision " + AssemblyInfo.GitRevision + ")";
GUIStyle.SmallFont.DrawString(spriteBatch, versionString, new Vector2(HUDLayoutSettings.Padding, GameMain.GraphicsHeight - GUIStyle.SmallFont.MeasureString(versionString).Y - HUDLayoutSettings.Padding * 0.75f), Color.White * 0.7f);
#endif
LocalizedString gameAnalyticsStatus = TextManager.Get($"GameAnalyticsStatus.{GameAnalyticsManager.UserConsented}");
Vector2 textSize = GUIStyle.SmallFont.MeasureString(gameAnalyticsStatus).ToPoint().ToVector2();
GUIStyle.SmallFont.DrawString(spriteBatch, gameAnalyticsStatus, new Vector2(HUDLayoutSettings.Padding, GameMain.GraphicsHeight - GUIStyle.SmallFont.LineHeight * 2 - HUDLayoutSettings.Padding * 0.75f), Color.White * 0.7f);
Vector2 textPos = new Vector2(GameMain.GraphicsWidth - HUDLayoutSettings.Padding, GameMain.GraphicsHeight - HUDLayoutSettings.Padding * 0.75f);
for (int i = legalCrap.Length - 1; i >= 0; i--)
{
textSize = GUIStyle.SmallFont.MeasureString(legalCrap[i])
.ToPoint().ToVector2();
bool mouseOn = i == 0 &&
PlayerInput.MousePosition.X > textPos.X - textSize.X && PlayerInput.MousePosition.X < textPos.X &&
PlayerInput.MousePosition.Y > textPos.Y - textSize.Y && PlayerInput.MousePosition.Y < textPos.Y;
GUIStyle.SmallFont.DrawString(spriteBatch,
legalCrap[i], textPos - textSize,
mouseOn ? Color.White : Color.White * 0.7f);
if (i == 0)
{
GUI.DrawLine(spriteBatch, textPos, textPos - Vector2.UnitX * textSize.X, mouseOn ? Color.White : Color.White * 0.7f);
if (mouseOn && PlayerInput.PrimaryMouseButtonClicked() && GUI.MouseOn == null)
{
GameMain.ShowOpenUrlInWebBrowserPrompt("http://privacypolicy.daedalic.com");
}
}
textPos.Y -= textSize.Y;
}
}
spriteBatch.End();
}
@@ -2320,12 +2320,12 @@ namespace Barotrauma
List<ContextMenuOption> options = new List<ContextMenuOption>();
if (client.AccountId.TryUnwrap(out var accountId) && accountId is SteamId steamId)
if (client.AccountId.TryUnwrap(out var accountId))
{
options.Add(new ContextMenuOption("ViewSteamProfile", isEnabled: hasAccountId, onSelected: () =>
{
SteamManager.OverlayProfile(steamId);
}));
options.Add(new ContextMenuOption(accountId.ViewProfileLabel(), isEnabled: hasAccountId, onSelected: () =>
{
accountId.OpenProfile();
}));
}
options.Add(new ContextMenuOption("ModerationMenu.ManagePlayer", isEnabled: true, onSelected: () =>
@@ -2702,17 +2702,17 @@ namespace Barotrauma
}
}
if (selectedClient.AccountId.TryUnwrap(out var accountId) && accountId is SteamId steamId && Steam.SteamManager.IsInitialized)
if (selectedClient.AccountId.TryUnwrap(out var accountId))
{
var viewSteamProfileButton = new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), headerContainer.RectTransform, Anchor.TopCenter) { MaxSize = new Point(int.MaxValue, (int)(40 * GUI.Scale)) },
TextManager.Get("ViewSteamProfile"))
accountId.ViewProfileLabel())
{
UserData = selectedClient
};
viewSteamProfileButton.TextBlock.AutoScaleHorizontal = true;
viewSteamProfileButton.OnClicked = (bt, userdata) =>
{
SteamManager.OverlayProfile(steamId);
accountId.OpenProfile();
return true;
};
}
@@ -7,25 +7,20 @@ namespace Barotrauma
{
abstract partial class Screen
{
private GUIFrame frame;
public GUIFrame Frame
{
get
{
if (frame == null)
{
frame = new GUIFrame(new RectTransform(GUI.Canvas.RelativeSize, GUI.Canvas), style: null)
{
CanBeFocused = false
};
public readonly GUIFrame Frame;
}
return frame;
}
protected Screen()
{
Frame = new GUIFrame(new RectTransform(Vector2.One, GUI.Canvas), style: null)
{
CanBeFocused = false
};
}
/// <summary>
/// By default, creates a new frame for the screen and adds all elements to the gui update list.
/// By default, submits the screen's main GUIFrame and,
/// if requested upon construction, the social drawer,
/// to the GUI update list.
/// </summary>
public virtual void AddToGUIUpdateList()
{
@@ -68,9 +63,7 @@ namespace Barotrauma
public virtual void Release()
{
if (frame is null) { return; }
frame.RectTransform.Parent = null;
frame = null;
Frame.RectTransform.Parent = null;
}
}
}
@@ -7,7 +7,9 @@ using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using Barotrauma.Steam;
namespace Barotrauma
{
@@ -44,70 +46,6 @@ namespace Barotrauma
Disabled
}
//friends list
public sealed class FriendInfo
{
public string Name;
public readonly AccountId Id;
public enum Status
{
Offline,
NotPlaying,
PlayingAnotherGame,
PlayingBarotrauma
}
public readonly Status CurrentStatus;
public string ServerName;
public Option<ConnectCommand> ConnectCommand;
public Option<Sprite> Avatar;
public bool IsInServer
=> CurrentStatus == Status.PlayingBarotrauma && ConnectCommand.IsSome();
public bool IsPlayingBarotrauma
=> CurrentStatus == Status.PlayingBarotrauma;
public bool PlayingAnotherGame
=> CurrentStatus == Status.PlayingAnotherGame;
public bool IsOnline
=> CurrentStatus != Status.Offline;
public LocalizedString StatusText
=> CurrentStatus switch
{
Status.Offline => "",
_ when ConnectCommand.IsSome()
=> TextManager.GetWithVariable("FriendPlayingOnServer", "[servername]", ServerName),
_ => TextManager.Get($"Friend{CurrentStatus}")
};
public FriendInfo(string name, AccountId id, Status status)
{
Name = name;
Id = id;
CurrentStatus = status;
ConnectCommand = Option<ConnectCommand>.None();
Avatar = Option<Sprite>.None();
}
}
private GUILayoutGroup friendsButtonHolder;
private GUIButton friendsDropdownButton;
private GUIListBox friendsDropdown;
private readonly FriendProvider friendProvider = new SteamFriendProvider();
private List<FriendInfo> friendsList;
private GUIFrame friendPopup;
private double friendsListUpdateTime;
public enum TabEnum
{
All,
@@ -115,7 +53,7 @@ namespace Barotrauma
Recent
}
public struct Tab
public readonly struct Tab
{
public readonly string Storage;
public readonly GUIButton Button;
@@ -127,7 +65,7 @@ namespace Barotrauma
{
Storage = storage;
servers = new List<ServerInfo>();
Button = new GUIButton(new RectTransform(new Vector2(0.2f, 1.0f), tabber.RectTransform),
Button = new GUIButton(new RectTransform(new Vector2(0.33f, 1.0f), tabber.RectTransform),
TextManager.Get($"ServerListTab.{tabEnum}"), style: "GUITabButton")
{
OnClicked = (_,__) =>
@@ -187,8 +125,7 @@ namespace Barotrauma
}
}
private readonly ServerProvider serverProvider
= new CompositeServerProvider(new SteamDedicatedServerProvider(), new SteamP2PServerProvider());
private ServerProvider serverProvider = null;
public GUITextBox ClientNameBox { get; private set; }
@@ -257,16 +194,16 @@ namespace Barotrauma
private bool sortedAscending = true;
private const float sidebarWidth = 0.2f;
public ServerListScreen()
public ServerListScreen() : base()
{
selectedServer = Option<ServerInfo>.None();
GameMain.Instance.ResolutionChanged += CreateUI;
CreateUI();
}
private string GetDefaultUserName()
private static Task<string> GetDefaultUserName()
{
return friendProvider.GetUserName();
return new CompositeFriendProvider(new SteamFriendProvider(), new EpicFriendProvider()).GetSelfUserName();
}
private void AddTernaryFilter(RectTransform parent, float elementHeight, Identifier tag, Action<TernaryOption> valueSetter)
@@ -331,13 +268,32 @@ namespace Barotrauma
var topRow = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.15f), paddedFrame.RectTransform)) { Stretch = true };
var title = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.33f), topRow.RectTransform), TextManager.Get("JoinServer"), font: GUIStyle.LargeFont)
var titleContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.995f, 0.33f), topRow.RectTransform), isHorizontal: true) { Stretch = true };
var title = new GUITextBlock(new RectTransform(new Vector2(1.0f, 1.0f), titleContainer.RectTransform), TextManager.Get("JoinServer"), font: GUIStyle.LargeFont)
{
Padding = Vector4.Zero,
ForceUpperCase = ForceUpperCase.Yes,
AutoScaleHorizontal = true
};
var friendsButton = new GUIButton(
new RectTransform(Vector2.One * 0.9f, titleContainer.RectTransform, scaleBasis: ScaleBasis.BothHeight),
style: "FriendsButton")
{
OnClicked = (_, _) =>
{
if (SocialOverlay.Instance is { } socialOverlay) { socialOverlay.IsOpen = true; }
return false;
},
ToolTip = TextManager.GetWithVariable("SocialOverlayShortcutHint", "[shortcut]", SocialOverlay.ShortcutBindText)
};
new GUIFrame(new RectTransform(Vector2.One, friendsButton.RectTransform, Anchor.Center),
style: "FriendsButtonIcon")
{
CanBeFocused = false
};
var infoHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.33f), topRow.RectTransform), isHorizontal: true, Anchor.BottomLeft) { RelativeSpacing = 0.01f, Stretch = false };
var clientNameHolder = new GUILayoutGroup(new RectTransform(new Vector2(sidebarWidth, 1.0f), infoHolder.RectTransform)) { RelativeSpacing = 0.05f };
@@ -352,7 +308,13 @@ namespace Barotrauma
if (string.IsNullOrEmpty(ClientNameBox.Text))
{
ClientNameBox.Text = GetDefaultUserName();
TaskPool.Add("GetDefaultUserName",
GetDefaultUserName(),
t =>
{
if (!t.TryGetResult(out string name)) { return; }
if (ClientNameBox.Text.IsNullOrEmpty()) { ClientNameBox.Text = name; }
});
}
ClientNameBox.OnTextChanged += (textbox, text) =>
{
@@ -366,14 +328,6 @@ namespace Barotrauma
tabs[TabEnum.Favorites] = new Tab(TabEnum.Favorites, this, tabButtonHolder, "Data/favoriteservers.xml");
tabs[TabEnum.Recent] = new Tab(TabEnum.Recent, this, tabButtonHolder, "Data/recentservers.xml");
var friendsButtonFrame = new GUIFrame(new RectTransform(new Vector2(0.31f, 2.0f), tabButtonHolder.RectTransform, Anchor.BottomRight), style: "InnerFrame")
{
IgnoreLayoutGroups = true
};
friendsButtonHolder = new GUILayoutGroup(new RectTransform(new Vector2(0.98f, 0.9f), friendsButtonFrame.RectTransform, Anchor.Center), childAnchor: Anchor.TopLeft) { RelativeSpacing = 0.01f, IsHorizontal = true };
friendsList = new List<FriendInfo>();
//-------------------------------------------------------------------------------------
// Bottom row
//-------------------------------------------------------------------------------------
@@ -740,7 +694,7 @@ namespace Barotrauma
{
if (selectedServer.TryUnwrap(out var serverInfo))
{
JoinServer(serverInfo.Endpoint, serverInfo.ServerName);
JoinServer(serverInfo.Endpoints, serverInfo.ServerName);
}
return true;
},
@@ -778,7 +732,7 @@ namespace Barotrauma
{
GUIComponent existingElement = serverList.Content.FindChild(d =>
d.UserData is ServerInfo existingServerInfo &&
existingServerInfo.Endpoint == serverInfo.Endpoint);
existingServerInfo.Endpoints.Any(serverInfo.Endpoints.Contains));
if (existingElement == null)
{
AddToServerList(serverInfo);
@@ -791,7 +745,7 @@ namespace Barotrauma
public void AddToRecentServers(ServerInfo info)
{
if (info.Endpoint.Address.IsLocalHost) { return; }
if (info.Endpoints.First().Address.IsLocalHost) { return; }
tabs[TabEnum.Recent].AddOrUpdate(info);
tabs[TabEnum.Recent].Save();
}
@@ -924,7 +878,32 @@ namespace Barotrauma
public override void Select()
{
base.Select();
if (EosInterface.IdQueries.IsLoggedIntoEosConnect)
{
if (SteamManager.IsInitialized)
{
serverProvider = new CompositeServerProvider(
new EosServerProvider(),
new SteamDedicatedServerProvider(),
new SteamP2PServerProvider());
}
else
{
serverProvider = new EosServerProvider();
}
}
else if (SteamManager.IsInitialized)
{
serverProvider = new CompositeServerProvider(
new SteamDedicatedServerProvider(),
new SteamP2PServerProvider());
}
else
{
serverProvider = null;
}
Steamworks.SteamMatchmaking.ResetActions();
selectedTab = TabEnum.All;
@@ -957,6 +936,7 @@ namespace Barotrauma
public override void Deselect()
{
base.Deselect();
serverProvider?.Cancel();
GameSettings.SaveCurrentConfig();
}
@@ -964,21 +944,9 @@ namespace Barotrauma
{
base.Update(deltaTime);
UpdateFriendsList();
panelAnimator?.Update();
scanServersButton.Enabled = (DateTime.Now - lastRefreshTime) >= AllowedRefreshInterval;
if (PlayerInput.PrimaryMouseButtonClicked())
{
friendPopup = null;
if (friendsDropdown != null && friendsDropdownButton != null &&
!friendsDropdown.Rect.Contains(PlayerInput.MousePosition) &&
!friendsDropdownButton.Rect.Contains(PlayerInput.MousePosition))
{
friendsDropdown.Visible = false;
}
}
}
public void FilterServers()
@@ -1113,7 +1081,8 @@ namespace Barotrauma
RelativeSpacing = 0.05f
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), content.RectTransform), TextManager.Get("ServerEndpoint"), textAlignment: Alignment.Center);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), content.RectTransform),
SteamManager.IsInitialized ? TextManager.Get("ServerEndpoint") : TextManager.Get("ServerIP"), textAlignment: Alignment.Center);
var endpointBox = new GUITextBox(new RectTransform(new Vector2(1.0f, 0.5f), content.RectTransform));
content.RectTransform.NonScaledSize = new Point(content.Rect.Width, (int)(content.RectTransform.Children.Sum(c => c.Rect.Height)));
@@ -1126,11 +1095,18 @@ namespace Barotrauma
{
if (Endpoint.Parse(endpointBox.Text).TryUnwrap(out var endpoint))
{
JoinServer(endpoint, "");
if (endpoint is SteamP2PEndpoint && !SteamManager.IsInitialized)
{
new GUIMessageBox(TextManager.Get("error"), TextManager.Get("CannotJoinSteamServer.SteamNotInitialized"));
}
else
{
JoinServer(endpoint.ToEnumerable().ToImmutableArray(), "");
}
}
else if (LidgrenEndpoint.ParseFromWithHostNameCheck(endpointBox.Text, tryParseHostName: true).TryUnwrap(out var lidgrenEndpoint))
{
JoinServer(lidgrenEndpoint, "");
JoinServer(((Endpoint)lidgrenEndpoint).ToEnumerable().ToImmutableArray(), "");
}
else
{
@@ -1171,8 +1147,6 @@ namespace Barotrauma
selectedTab = TabEnum.Favorites;
FilterServers();
#warning Interface with server providers to get up-to-date info on the given server
msgBox.Close();
return false;
};
@@ -1187,222 +1161,6 @@ namespace Barotrauma
};
}
private bool JoinFriend(GUIButton button, object userdata)
{
if (!(userdata is FriendInfo { IsInServer: true } info)) { return false; }
GameMain.Instance.ConnectCommand = info.ConnectCommand;
return false;
}
private bool OpenFriendPopup(GUIButton button, object userdata)
{
if (!(userdata is FriendInfo { IsInServer: true } info)) { return false; }
if (info.IsInServer
&& info.ConnectCommand.TryUnwrap(out var command)
&& command.EndpointOrLobby.TryGet(out ConnectCommand.NameAndEndpoint nameAndEndpoint))
{
const int framePadding = 5;
friendPopup = new GUIFrame(new RectTransform(Vector2.One, GUI.Canvas));
var serverNameText = new GUITextBlock(new RectTransform(new Vector2(0.7f, 1.0f), friendPopup.RectTransform, Anchor.CenterLeft), nameAndEndpoint.ServerName ?? "[Unnamed]");
serverNameText.RectTransform.AbsoluteOffset = new Point(framePadding, 0);
var joinButton = new GUIButton(new RectTransform(new Vector2(0.3f, 1.0f), friendPopup.RectTransform, Anchor.CenterRight), TextManager.Get("ServerListJoin"))
{
UserData = info
};
joinButton.OnClicked = JoinFriend;
joinButton.RectTransform.AbsoluteOffset = new Point(framePadding, 0);
Point joinButtonTextSize = joinButton.Font.MeasureString(joinButton.Text).ToPoint();
int joinButtonHeight = joinButton.RectTransform.NonScaledSize.Y;
int totalAdditionalTextPadding = (joinButtonHeight - joinButtonTextSize.Y);
// Make the final button sized so that the space between the text and the edges in the X direction is the same as the Y direction.
Point finalButtonSize = new Point(joinButtonTextSize.X + totalAdditionalTextPadding, joinButtonHeight);
// Add padding to the server name to match the padding on the button text.
serverNameText.Padding = new Vector4(totalAdditionalTextPadding / 2);
// Get the dimensions of the text we want to show, plus the extra padding we added.
Point serverNameSize = serverNameText.Font.MeasureString(serverNameText.Text).ToPoint() + new Point(totalAdditionalTextPadding, totalAdditionalTextPadding);
// Now determine how large the parent frame has to be to exactly fit our two controls.
Point frameDims = new Point(serverNameSize.X + finalButtonSize.X + framePadding*2, Math.Max(serverNameSize.Y, finalButtonSize.Y) + framePadding * 2);
var popupPos = PlayerInput.MousePosition.ToPoint();
if(popupPos.X+frameDims.X > GUI.Canvas.NonScaledSize.X)
{
// Prevent the Join button from going off the end of the screen if the server name is long or we click a user towards the edge.
popupPos.X = GUI.Canvas.NonScaledSize.X - frameDims.X;
}
// Apply the size and position changes.
friendPopup.RectTransform.NonScaledSize = frameDims;
friendPopup.RectTransform.RelativeOffset = Vector2.Zero;
friendPopup.RectTransform.AbsoluteOffset = popupPos;
joinButton.RectTransform.NonScaledSize = finalButtonSize;
friendPopup.RectTransform.RecalculateChildren(true);
friendPopup.RectTransform.SetPosition(Anchor.TopLeft);
}
return false;
}
public enum AvatarSize
{
Small,
Medium,
Large
}
private void UpdateFriendsList()
{
if (friendsListUpdateTime > Timing.TotalTime) { return; }
friendsListUpdateTime = Timing.TotalTime + 5.0;
float prevDropdownScroll = friendsDropdown?.ScrollBar.BarScrollValue ?? 0.0f;
friendsDropdown ??= new GUIListBox(new RectTransform(Vector2.One, GUI.Canvas))
{
OutlineColor = Color.Black,
Visible = false
};
friendsDropdown.ClearChildren();
var avatarSize = friendsButtonHolder.RectTransform.Rect.Height switch
{
var h when h <= 24 => AvatarSize.Small,
var h when h <= 48 => AvatarSize.Medium,
_ => AvatarSize.Large
};
FriendInfo[] friends = friendProvider.RetrieveFriends();
foreach (var friend in friends)
{
int existingIndex = friendsList.FindIndex(f => f.Id == friend.Id);
if (existingIndex >= 0)
{
friend.Avatar = friend.Avatar.Fallback(friendsList[existingIndex].Avatar);
}
if (friend.Avatar.IsNone())
{
friendProvider.RetrieveAvatar(friend, avatarSize);
}
}
friendsList.Clear(); friendsList.AddRange(friends.OrderByDescending(f => f.CurrentStatus));
friendsButtonHolder.ClearChildren();
if (friendsList.Count > 0)
{
friendsDropdownButton = new GUIButton(new RectTransform(Vector2.One, friendsButtonHolder.RectTransform, Anchor.BottomRight, Pivot.BottomRight, scaleBasis: ScaleBasis.BothHeight), "\u2022 \u2022 \u2022", style: "GUIButtonFriendsDropdown")
{
OnClicked = (button, udt) =>
{
friendsDropdown.RectTransform.NonScaledSize = new Point(friendsButtonHolder.Rect.Height * 5 * 166 / 100, friendsButtonHolder.Rect.Height * 4 * 166 / 100);
friendsDropdown.RectTransform.AbsoluteOffset = new Point(friendsButtonHolder.Rect.X, friendsButtonHolder.Rect.Bottom);
friendsDropdown.RectTransform.RecalculateChildren(true);
friendsDropdown.Visible = !friendsDropdown.Visible;
return false;
}
};
}
else
{
friendsDropdownButton = null;
friendsDropdown.Visible = false;
}
for (int i = 0; i < friendsList.Count; i++)
{
var friend = friendsList[i];
if (i < 5)
{
string style = friend.IsPlayingBarotrauma
? "GUIButtonFriendPlaying"
: "GUIButtonFriendNotPlaying";
var guiButton = new GUIButton(new RectTransform(Vector2.One, friendsButtonHolder.RectTransform, scaleBasis: ScaleBasis.BothHeight), style: style)
{
UserData = friend,
OnClicked = OpenFriendPopup
};
guiButton.ToolTip = friend.Name + "\n" + friend.StatusText;
if (friend.Avatar.TryUnwrap(out Sprite sprite))
{
new GUICustomComponent(new RectTransform(Vector2.One, guiButton.RectTransform, Anchor.Center),
onDraw: (sb, component) =>
{
var destinationRect = component.Rect;
destinationRect.Inflate(-GUI.IntScale(4), -GUI.IntScale(4));
sb.Draw(sprite.Texture, destinationRect, Color.White);
if (!GUI.IsMouseOn(guiButton))
{
return;
}
sb.End();
sb.Begin(
SpriteSortMode.Deferred,
blendState: BlendState.Additive,
samplerState: GUI.SamplerState,
rasterizerState: GameMain.ScissorTestEnable);
sb.Draw(sprite.Texture, destinationRect, Color.White * 0.5f);
sb.End();
sb.Begin(
SpriteSortMode.Deferred,
samplerState: GUI.SamplerState,
rasterizerState: GameMain.ScissorTestEnable);
}) { CanBeFocused = false };
}
}
var friendFrame = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.167f), friendsDropdown.Content.RectTransform), style: "GUIFrameFriendsDropdown");
if (friend.Avatar.TryUnwrap(out var avatar))
{
GUIImage guiImage =
new GUIImage(
new RectTransform(Vector2.One * 0.9f, friendFrame.RectTransform, Anchor.CenterLeft,
scaleBasis: ScaleBasis.BothHeight) { RelativeOffset = new Vector2(0.02f, 0.02f) },
avatar, null, true);
}
var textBlock = new GUITextBlock(new RectTransform(Vector2.One * 0.8f, friendFrame.RectTransform, Anchor.CenterLeft, scaleBasis: ScaleBasis.BothHeight) { RelativeOffset = new Vector2(1.0f / 7.7f, 0.0f) }, friend.Name + "\n" + friend.StatusText)
{
Font = GUIStyle.SmallFont
};
if (friend.IsPlayingBarotrauma) { textBlock.TextColor = GUIStyle.Green; }
if (friend.PlayingAnotherGame) { textBlock.TextColor = GUIStyle.Blue; }
if (friend.IsInServer)
{
var joinButton = new GUIButton(new RectTransform(new Vector2(0.25f, 0.6f), friendFrame.RectTransform, Anchor.CenterRight) { RelativeOffset = new Vector2(0.05f, 0.0f) }, TextManager.Get("ServerListJoin"), style: "GUIButtonJoinFriend")
{
UserData = friend,
OnClicked = JoinFriend
};
}
}
friendsDropdown.RectTransform.NonScaledSize = new Point(friendsButtonHolder.Rect.Height * 5 * 166 / 100, friendsButtonHolder.Rect.Height * 4 * 166 / 100);
friendsDropdown.RectTransform.AbsoluteOffset = new Point(friendsButtonHolder.Rect.X, friendsButtonHolder.Rect.Bottom);
friendsDropdown.RectTransform.RecalculateChildren(true);
friendsDropdown.ScrollBar.BarScrollValue = prevDropdownScroll;
}
private void RemoveMsgFromServerList()
{
serverList.Content.Children
@@ -1429,7 +1187,7 @@ namespace Barotrauma
private void RefreshServers()
{
lastRefreshTime = DateTime.Now;
serverProvider.Cancel();
serverProvider?.Cancel();
currentServerDataRecvCallbackObj = null;
PingUtils.QueryPingData();
@@ -1462,7 +1220,7 @@ namespace Barotrauma
}
var (onServerDataReceived, onQueryCompleted) = MakeServerQueryCallbacks();
serverProvider.RetrieveServers(onServerDataReceived, onQueryCompleted);
serverProvider?.RetrieveServers(onServerDataReceived, onQueryCompleted);
}
private GUIComponent FindFrameMatchingServerInfo(ServerInfo serverInfo)
@@ -1474,7 +1232,7 @@ namespace Barotrauma
#if DEBUG
if (serverList.Content.Children.Count(matches) > 1)
{
DebugConsole.ThrowError($"There are several entries in the server list for endpoint {serverInfo.Endpoint}");
DebugConsole.ThrowError($"There are several entries in the server list for endpoints {string.Join(", ", serverInfo.Endpoints)}");
}
#endif
@@ -1482,7 +1240,7 @@ namespace Barotrauma
}
private object currentServerDataRecvCallbackObj = null;
private (Action<ServerInfo> OnServerDataReceived, Action OnQueryCompleted) MakeServerQueryCallbacks()
private (Action<ServerInfo, ServerProvider> OnServerDataReceived, Action OnQueryCompleted) MakeServerQueryCallbacks()
{
var uniqueObject = new object();
currentServerDataRecvCallbackObj = uniqueObject;
@@ -1497,10 +1255,21 @@ namespace Barotrauma
}
return (
serverInfo =>
(serverInfo, serverProvider) =>
{
if (!shouldRunCallback()) { return; }
if (serverProvider is not EosServerProvider
&& EosInterface.IdQueries.IsLoggedIntoEosConnect)
{
if (serverInfo.EosCrossplay)
{
// EosServerProvider should get us this server,
// don't add it again
return;
}
}
if (selectedTab == TabEnum.All)
{
AddToServerList(serverInfo);
@@ -1724,7 +1493,7 @@ namespace Barotrauma
private static void ReportServer(ServerInfo info, IEnumerable<ReportReason> reasons)
{
if (!reasons.Any()) { return; }
GameAnalyticsManager.AddErrorEvent(GameAnalyticsManager.ErrorSeverity.Info, $"[Spam] Reported server: Name: \"{info.ServerName}\", Message: \"{info.ServerMessage}\", Endpoint: \"{info.Endpoint.StringRepresentation}\". Reason: \"{string.Join(", ", reasons)}\".");
GameAnalyticsManager.AddErrorEvent(GameAnalyticsManager.ErrorSeverity.Info, $"[Spam] Reported server: Name: \"{info.ServerName}\", Message: \"{info.ServerMessage}\", Endpoint: \"{info.Endpoints.First().StringRepresentation}\". Reason: \"{string.Join(", ", reasons)}\".");
}
private void UpdateServerInfoUI(ServerInfo serverInfo)
@@ -1784,7 +1553,7 @@ namespace Barotrauma
var serverName = new GUITextBlock(columnRT(ColumnLabel.ServerListName),
#if DEBUG
$"[{serverInfo.Endpoint.GetType().Name}] " +
$"[{serverInfo.Endpoints.First().GetType().Name}] " +
#endif
serverInfo.ServerName,
style: "GUIServerListTextBox") { CanBeFocused = false };
@@ -1819,6 +1588,13 @@ namespace Barotrauma
serverPingText.Text = ping.ToString();
serverPingText.TextColor = GetPingTextColor(ping);
}
else if ((serverInfo.Endpoints.Length == 1 && serverInfo.Endpoints.First() is EosP2PEndpoint)
|| (!SteamManager.IsInitialized && serverInfo.Endpoints.Any(e => e is P2PEndpoint)))
{
serverPingText.Text = "-";
serverPingText.ToolTip = TextManager.Get("EosPingUnavailable");
serverPingText.TextAlignment = Alignment.Center;
}
else
{
serverPingText.Text = "?";
@@ -1954,7 +1730,7 @@ namespace Barotrauma
}
}
public void JoinServer(Endpoint endpoint, string serverName)
public void JoinServer(ImmutableArray<Endpoint> endpoints, string serverName)
{
if (string.IsNullOrWhiteSpace(ClientNameBox.Text))
{
@@ -1967,20 +1743,38 @@ namespace Barotrauma
MultiplayerPreferences.Instance.PlayerName = ClientNameBox.Text;
GameSettings.SaveCurrentConfig();
#if !DEBUG
try
if (MultiplayerPreferences.Instance.PlayerName.IsNullOrEmpty())
{
#endif
GameMain.Client = new GameClient(MultiplayerPreferences.Instance.PlayerName.FallbackNullOrEmpty(GetDefaultUserName()), endpoint, serverName, Option<int>.None());
#if !DEBUG
TaskPool.Add("GetDefaultUserName",
GetDefaultUserName(),
t =>
{
if (!t.TryGetResult(out string name)) { return; }
startClient(name);
});
}
catch (Exception e)
else
{
DebugConsole.ThrowError("Failed to start the client", e);
startClient(MultiplayerPreferences.Instance.PlayerName);
}
void startClient(string name)
{
#if !DEBUG
try
{
#endif
GameMain.Client = new GameClient(name, endpoints, serverName, Option.None);
#if !DEBUG
}
catch (Exception e)
{
DebugConsole.ThrowError("Failed to start the client", e);
}
#endif
}
}
private static Color GetPingTextColor(int ping)
{
if (ping < 0) { return Color.DarkRed; }
@@ -2000,8 +1794,6 @@ namespace Barotrauma
public override void AddToGUIUpdateList()
{
menu.AddToGUIUpdateList();
friendPopup?.AddToGUIUpdateList();
friendsDropdown?.AddToGUIUpdateList();
}
public void StoreServerFilters()
@@ -1557,7 +1557,6 @@ namespace Barotrauma
autoSaveLabel?.Parent?.RemoveChild(autoSaveLabel);
autoSaveLabel = null;
#if USE_STEAM
if (editorSelectedTime.TryUnwrap(out DateTime selectedTime))
{
TimeSpan timeInEditor = DateTime.Now - selectedTime;
@@ -1571,11 +1570,10 @@ namespace Barotrauma
}
else
{
SteamAchievementManager.IncrementStat("hoursineditor".ToIdentifier(), (float)timeInEditor.TotalHours);
AchievementManager.IncrementStat(AchievementStat.HoursInEditor, (float)timeInEditor.TotalHours);
editorSelectedTime = Option<DateTime>.None();
}
}
#endif
GUI.ForceMouseOn(null);
@@ -4176,7 +4174,7 @@ namespace Barotrauma
Rectangle newColorRect = new Rectangle(rect.Location, areaSize);
Rectangle oldColorRect = new Rectangle(new Point(newColorRect.Left, newColorRect.Bottom), areaSize);
GUI.DrawRectangle(batch, newColorRect, ToolBox.HSVToRGB(colorPicker.SelectedHue, colorPicker.SelectedSaturation, colorPicker.SelectedValue), isFilled: true);
GUI.DrawRectangle(batch, newColorRect, ToolBoxCore.HSVToRGB(colorPicker.SelectedHue, colorPicker.SelectedSaturation, colorPicker.SelectedValue), isFilled: true);
GUI.DrawRectangle(batch, oldColorRect, originalColor, isFilled: true);
GUI.DrawRectangle(batch, rect, Color.Black, isFilled: false);
});
@@ -4296,7 +4294,7 @@ namespace Barotrauma
setValues = true;
}
Color color = ToolBox.HSVToRGB(colorPicker.SelectedHue, colorPicker.SelectedSaturation, colorPicker.SelectedValue);
Color color = ToolBoxCore.HSVToRGB(colorPicker.SelectedHue, colorPicker.SelectedSaturation, colorPicker.SelectedValue);
foreach (var (e, origColor, prop) in entities)
{
if (e is MapEntity { Removed: true }) { continue; }
@@ -4330,7 +4328,7 @@ namespace Barotrauma
void SetHex(Vector3 hsv)
{
Color hexColor = ToolBox.HSVToRGB(hsv.X, hsv.Y, hsv.Z);
Color hexColor = ToolBoxCore.HSVToRGB(hsv.X, hsv.Y, hsv.Z);
hexValueBox!.Text = ColorToHex(hexColor);
}
}