Unstable 0.17.0.0

This commit is contained in:
Markus Isberg
2022-02-26 02:43:01 +09:00
parent a83f375681
commit 3974067915
913 changed files with 32472 additions and 32364 deletions
@@ -97,12 +97,12 @@ namespace Barotrauma.Networking
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedPlayerFrame.RectTransform),
bannedPlayer.ExpirationTime == null ?
TextManager.Get("BanPermanent") : TextManager.GetWithVariable("BanExpires", "[time]", bannedPlayer.ExpirationTime.Value.ToString()),
font: GUI.SmallFont);
font: GUIStyle.SmallFont);
var reasonText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedPlayerFrame.RectTransform),
TextManager.Get("BanReason") + " " +
(string.IsNullOrEmpty(bannedPlayer.Reason) ? TextManager.Get("None") : bannedPlayer.Reason),
font: GUI.SmallFont, wrap: true)
font: GUIStyle.SmallFont, wrap: true)
{
ToolTip = bannedPlayer.Reason
};
@@ -61,25 +61,27 @@ namespace Barotrauma.Networking
break;
case ChatMessageType.Order:
var orderMessageInfo = OrderChatMessage.ReadOrder(msg);
if (orderMessageInfo.OrderIndex < 0 || orderMessageInfo.OrderIndex >= Order.PrefabList.Count)
if (orderMessageInfo.OrderIdentifier == Identifier.Empty)
{
DebugConsole.ThrowError("Invalid order message - order index out of bounds.");
if (NetIdUtils.IdMoreRecent(id, LastID)) { LastID = id; }
return;
}
var orderPrefab = orderMessageInfo.OrderPrefab ?? Order.PrefabList[orderMessageInfo.OrderIndex];
string orderOption = orderMessageInfo.OrderOption;
orderOption ??= orderMessageInfo.OrderOptionIndex.HasValue && orderMessageInfo.OrderOptionIndex >= 0 && orderMessageInfo.OrderOptionIndex < orderPrefab.Options.Length ?
orderPrefab.Options[orderMessageInfo.OrderOptionIndex.Value] : "";
var orderPrefab = orderMessageInfo.OrderPrefab ?? OrderPrefab.Prefabs[orderMessageInfo.OrderIdentifier];
Identifier orderOption = orderMessageInfo.OrderOption;
orderOption = orderOption.IfEmpty(
orderMessageInfo.OrderOptionIndex.HasValue && orderMessageInfo.OrderOptionIndex >= 0 && orderMessageInfo.OrderOptionIndex < orderPrefab.Options.Length
? orderPrefab.Options[orderMessageInfo.OrderOptionIndex.Value]
: Identifier.Empty);
string targetRoom;
if (orderMessageInfo.TargetEntity is Hull targetHull)
{
targetRoom = targetHull.DisplayName;
targetRoom = targetHull.DisplayName.Value;
}
else
{
targetRoom = senderCharacter?.CurrentHull?.DisplayName;
targetRoom = senderCharacter?.CurrentHull?.DisplayName?.Value;
}
txt = orderPrefab.GetChatMessage(orderMessageInfo.TargetCharacter?.Name, targetRoom,
@@ -93,18 +95,19 @@ namespace Barotrauma.Networking
switch (orderMessageInfo.TargetType)
{
case Order.OrderTargetType.Entity:
order = new Order(orderPrefab, orderMessageInfo.TargetEntity, orderPrefab.GetTargetItemComponent(orderMessageInfo.TargetEntity as Item), orderGiver: senderCharacter);
order = new Order(orderPrefab, orderOption, orderMessageInfo.TargetEntity, orderPrefab.GetTargetItemComponent(orderMessageInfo.TargetEntity as Item), orderGiver: senderCharacter);
break;
case Order.OrderTargetType.Position:
order = new Order(orderPrefab, orderMessageInfo.TargetPosition, orderGiver: senderCharacter);
order = new Order(orderPrefab, orderOption, orderMessageInfo.TargetPosition, orderGiver: senderCharacter);
break;
case Order.OrderTargetType.WallSection:
order = new Order(orderPrefab, orderMessageInfo.TargetEntity as Structure, orderMessageInfo.WallSectionIndex, orderGiver: senderCharacter);
order = new Order(orderPrefab, orderOption, orderMessageInfo.TargetEntity as Structure, orderMessageInfo.WallSectionIndex, orderGiver: senderCharacter);
break;
}
if (order != null)
{
order = order.WithManualPriority(orderMessageInfo.Priority);
if (order.TargetAllCharacters)
{
var fadeOutTime = !orderPrefab.IsIgnoreOrder ? (float?)orderPrefab.FadeOutTime : null;
@@ -112,24 +115,39 @@ namespace Barotrauma.Networking
}
else
{
orderMessageInfo.TargetCharacter?.SetOrder(order, orderOption, orderMessageInfo.Priority, senderCharacter);
orderMessageInfo.TargetCharacter?.SetOrder(order);
}
}
}
if (NetIdUtils.IdMoreRecent(id, LastID))
{
Order order = null;
if (orderMessageInfo.TargetPosition != null)
{
order = new Order(orderPrefab, orderOption, orderMessageInfo.Priority, Order.OrderType.Current, null, orderMessageInfo.TargetPosition, orderGiver: senderCharacter);
}
else if (orderMessageInfo.WallSectionIndex != null)
{
order = new Order(orderPrefab, orderOption, orderMessageInfo.TargetEntity as Structure, orderMessageInfo.WallSectionIndex, orderGiver: senderCharacter)
.WithManualPriority(orderMessageInfo.Priority);
}
else
{
order = new Order(orderPrefab, orderOption, orderMessageInfo.TargetEntity, orderPrefab.GetTargetItemComponent(orderMessageInfo.TargetEntity as Item), orderGiver: senderCharacter)
.WithManualPriority(orderMessageInfo.Priority);
}
GameMain.Client.AddChatMessage(
new OrderChatMessage(orderPrefab, orderOption, orderMessageInfo.Priority, txt, orderMessageInfo.TargetPosition ?? orderMessageInfo.TargetEntity as ISpatialEntity, orderMessageInfo.TargetCharacter, senderCharacter));
new OrderChatMessage(order, txt, orderMessageInfo.TargetCharacter, senderCharacter));
LastID = id;
}
return;
case ChatMessageType.ServerMessageBox:
txt = TextManager.GetServerMessage(txt);
txt = TextManager.GetServerMessage(txt).Value;
break;
case ChatMessageType.ServerMessageBoxInGame:
styleSetting = msg.ReadString();
txt = TextManager.GetServerMessage(txt);
txt = TextManager.GetServerMessage(txt).Value;
break;
}
@@ -148,7 +166,7 @@ namespace Barotrauma.Networking
break;
case ChatMessageType.ServerMessageBoxInGame:
{
GUIMessageBox messageBox = new GUIMessageBox("", txt, new string[0], type: GUIMessageBox.Type.InGame, iconStyle: styleSetting);
GUIMessageBox messageBox = new GUIMessageBox("", txt, Array.Empty<LocalizedString>(), type: GUIMessageBox.Type.InGame, iconStyle: styleSetting);
if (textColor != null) { messageBox.Text.TextColor = textColor.Value; }
}
break;
@@ -9,7 +9,7 @@ namespace Barotrauma.Networking
struct TempClient
{
public string Name;
public string PreferredJob;
public Identifier PreferredJob;
public CharacterTeamType PreferredTeam;
public UInt16 NameID;
public UInt64 SteamID;
@@ -66,7 +66,7 @@ namespace Barotrauma.Networking
if (character != null)
{
if (GameMain.Config.UseDirectionalVoiceChat)
if (GameSettings.CurrentConfig.Audio.UseDirectionalVoiceChat)
{
VoipSound.SetPosition(new Vector3(character.WorldPosition.X, character.WorldPosition.Y, 0.0f));
}
@@ -19,7 +19,7 @@ namespace Barotrauma
DebugConsole.Log($"Received entity removal message for \"{entity}\".");
if (entity is Item item && item.Container?.GetComponent<Deconstructor>() != null)
{
GameAnalyticsManager.AddDesignEvent("ItemDeconstructed:" + (GameMain.GameSession?.GameMode?.Preset.Identifier ?? "none") + ":" + item.prefab.Identifier);
GameAnalyticsManager.AddDesignEvent("ItemDeconstructed:" + (GameMain.GameSession?.GameMode?.Preset.Identifier ?? "none".ToIdentifier()) + ":" + item.Prefab.Identifier);
}
entity.Remove();
}
@@ -36,7 +36,7 @@ namespace Barotrauma
var newItem = Item.ReadSpawnData(message, true);
if (newItem is Item item && item.Container?.GetComponent<Fabricator>() != null)
{
GameAnalyticsManager.AddDesignEvent("ItemFabricated:" + (GameMain.GameSession?.GameMode?.Preset.Identifier ?? "none") + ":" + item.prefab.Identifier);
GameAnalyticsManager.AddDesignEvent("ItemFabricated:" + (GameMain.GameSession?.GameMode?.Preset.Identifier ?? "none".ToIdentifier()) + ":" + item.Prefab.Identifier);
}
break;
case (byte)SpawnableType.Character:
@@ -1,6 +1,7 @@
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using Barotrauma.IO;
using System.Linq;
using System.Threading;
@@ -35,6 +36,8 @@ namespace Barotrauma.Networking
get;
private set;
}
public int LastSeen { get; set; }
public FileTransferType FileType
{
@@ -119,7 +122,7 @@ namespace Barotrauma.Networking
int passed = Environment.TickCount - TimeStarted;
float psec = passed / 1000.0f;
if (GameSettings.VerboseLogging)
if (GameSettings.CurrentConfig.VerboseLogging)
{
DebugConsole.Log($"Received {all.Length} bytes of the file {FileName} ({Received / 1000}/{FileSize / 1000} kB received)");
}
@@ -162,16 +165,15 @@ namespace Barotrauma.Networking
private readonly List<FileTransferIn> activeTransfers;
private readonly List<(int transferId, double finishedTime)> finishedTransfers;
private readonly Dictionary<FileTransferType, string> downloadFolders = new Dictionary<FileTransferType, string>()
private readonly ImmutableDictionary<FileTransferType, string> downloadFolders = new Dictionary<FileTransferType, string>()
{
{ FileTransferType.Submarine, SaveUtil.SubmarineDownloadFolder },
{ FileTransferType.CampaignSave, SaveUtil.CampaignDownloadFolder }
};
{ FileTransferType.CampaignSave, SaveUtil.CampaignDownloadFolder },
{ FileTransferType.Mod, ModReceiver.DownloadFolder }
}.ToImmutableDictionary();
public List<FileTransferIn> ActiveTransfers
{
get { return activeTransfers; }
}
public IReadOnlyList<FileTransferIn> ActiveTransfers => activeTransfers;
public bool HasActiveTransfers => ActiveTransfers.Any();
public FileReceiver()
{
@@ -211,7 +213,7 @@ namespace Barotrauma.Networking
}
else //resend acknowledgement packet
{
GameMain.Client.UpdateFileTransfer(transferId, existingTransfer.Received);
GameMain.Client.UpdateFileTransfer(transferId, existingTransfer.Received, existingTransfer.LastSeen);
}
return;
}
@@ -223,7 +225,7 @@ namespace Barotrauma.Networking
return;
}
if (GameSettings.VerboseLogging)
if (GameSettings.CurrentConfig.VerboseLogging)
{
DebugConsole.Log("Received file transfer initiation message: ");
DebugConsole.Log(" File: " + fileName);
@@ -278,7 +280,7 @@ namespace Barotrauma.Networking
}
activeTransfers.Add(newTransfer);
GameMain.Client.UpdateFileTransfer(transferId, 0); //send acknowledgement packet
GameMain.Client.UpdateFileTransfer(transferId, 0, 0); //send acknowledgement packet
}
break;
case (byte)FileTransferMessageType.TransferOnSameMachine:
@@ -287,7 +289,7 @@ namespace Barotrauma.Networking
byte fileType = inc.ReadByte();
string filePath = inc.ReadString();
if (GameSettings.VerboseLogging)
if (GameSettings.CurrentConfig.VerboseLogging)
{
DebugConsole.Log("Received file transfer message on the same machine: ");
DebugConsole.Log(" File: " + filePath);
@@ -308,7 +310,7 @@ namespace Barotrauma.Networking
FileSize = 0
};
Md5Hash.RemoveFromCache(directTransfer.FilePath);
Md5Hash.Cache.Remove(directTransfer.FilePath);
OnFinished(directTransfer);
}
break;
@@ -335,10 +337,12 @@ namespace Barotrauma.Networking
int bytesToRead = inc.ReadUInt16();
if (offset != activeTransfer.Received)
{
activeTransfer.LastSeen = Math.Max(offset, activeTransfer.LastSeen);
DebugConsole.Log($"Received {bytesToRead} bytes of the file {activeTransfer.FileName} (ignoring: offset {offset}, waiting for {activeTransfer.Received})");
GameMain.Client.UpdateFileTransfer(activeTransfer.ID, activeTransfer.Received);
GameMain.Client.UpdateFileTransfer(activeTransfer.ID, activeTransfer.Received, activeTransfer.LastSeen);
return;
}
activeTransfer.LastSeen = offset;
if (activeTransfer.Received + bytesToRead > activeTransfer.FileSize)
{
@@ -366,7 +370,7 @@ namespace Barotrauma.Networking
return;
}
GameMain.Client.UpdateFileTransfer(activeTransfer.ID, activeTransfer.Received, reliable: activeTransfer.Status == FileTransferStatus.Finished);
GameMain.Client.UpdateFileTransfer(activeTransfer.ID, activeTransfer.Received, activeTransfer.LastSeen, reliable: activeTransfer.Status == FileTransferStatus.Finished);
if (activeTransfer.Status == FileTransferStatus.Finished)
{
activeTransfer.Dispose();
@@ -375,7 +379,7 @@ namespace Barotrauma.Networking
{
finishedTransfers.Add((transferId, Timing.TotalTime));
StopTransfer(activeTransfer);
Md5Hash.RemoveFromCache(activeTransfer.FilePath);
Md5Hash.Cache.Remove(activeTransfer.FilePath);
OnFinished(activeTransfer);
}
else
@@ -0,0 +1,8 @@
namespace Barotrauma.Networking
{
static class ModReceiver
{
public const string DownloadFolder = "TempMods_Download";
public const string Extension = ".barodir.gz";
}
}
@@ -10,6 +10,7 @@ using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Barotrauma.Extensions;
namespace Barotrauma.Networking
{
@@ -50,8 +51,9 @@ namespace Barotrauma.Networking
private GUIMessageBox reconnectBox, waitInServerQueueBox;
//TODO: move these to NetLobbyScreen
public LocalizedString endRoundVoteText;
public GUITickBox EndVoteTickBox;
private GUIComponent buttonContainer;
private readonly GUIComponent buttonContainer;
public readonly NetStats NetStats;
@@ -121,7 +123,7 @@ namespace Barotrauma.Networking
public bool HasSpawned;
public bool SpawnAsTraitor;
public string TraitorFirstObjective;
public LocalizedString TraitorFirstObjective;
public TraitorMissionPrefab TraitorMission = null;
public byte ID
@@ -221,13 +223,14 @@ namespace Barotrauma.Networking
CanBeFocused = false
};
endRoundVoteText = TextManager.Get("EndRound");
EndVoteTickBox = new GUITickBox(new RectTransform(new Vector2(0.1f, 0.4f), buttonContainer.RectTransform) { MinSize = new Point(150, 0) },
TextManager.Get("EndRound"))
endRoundVoteText)
{
UserData = TextManager.Get("EndRound"),
OnSelected = ToggleEndRoundVote,
Visible = false
};
EndVoteTickBox.TextBlock.Wrap = true;
ShowLogButton = new GUIButton(new RectTransform(new Vector2(0.1f, 0.6f), buttonContainer.RectTransform) { MinSize = new Point(150, 0) },
TextManager.Get("ServerLog"))
@@ -282,8 +285,7 @@ namespace Barotrauma.Networking
//ServerLog = new ServerLog("");
ChatMessage.LastID = 0;
GameMain.NetLobbyScreen?.Release();
GameMain.NetLobbyScreen = new NetLobbyScreen();
GameMain.ResetNetLobbyScreen();
}
private void ConnectToServer(object endpoint, string hostName)
@@ -340,7 +342,7 @@ namespace Barotrauma.Networking
catch
{
new GUIMessageBox(TextManager.Get("CouldNotConnectToServer"),
TextManager.GetWithVariables("InvalidIPAddress", new string[2] { "[serverip]", "[port]" }, new string[2] { serverIP, port.ToString() }));
TextManager.GetWithVariables("InvalidIPAddress", ("[serverip]", serverIP), ("[port]", port.ToString())));
return;
}
@@ -361,39 +363,7 @@ namespace Barotrauma.Networking
}
clientPeer.OnDisconnect = OnDisconnect;
clientPeer.OnDisconnectMessageReceived = HandleDisconnectMessage;
clientPeer.OnInitializationComplete = () =>
{
if (SteamManager.IsInitialized)
{
Steamworks.SteamFriends.ClearRichPresence();
Steamworks.SteamFriends.SetRichPresence("status", "Playing on " + serverName);
Steamworks.SteamFriends.SetRichPresence("connect", "-connect \"" + serverName.Replace("\"", "\\\"") + "\" " + serverEndpoint);
}
canStart = true;
connected = true;
VoipClient = new VoipClient(this, clientPeer);
if (Screen.Selected != GameMain.GameScreen)
{
GameMain.NetLobbyScreen.Select();
}
else
{
entityEventManager.ClearSelf();
foreach (Character c in Character.CharacterList)
{
c.ResetNetState();
}
}
chatBox.InputBox.Enabled = true;
if (GameMain.NetLobbyScreen?.ChatInput != null)
{
GameMain.NetLobbyScreen.ChatInput.Enabled = true;
}
};
clientPeer.OnInitializationComplete = OnConnectionInitializationComplete;
clientPeer.OnRequestPassword = (int salt, int retries) =>
{
if (pwRetries != retries)
@@ -471,10 +441,10 @@ namespace Barotrauma.Networking
canStart = false;
DateTime timeOut = DateTime.Now + new TimeSpan(0, 0, 40);
DateTime reqAuthTime = DateTime.Now + new TimeSpan(0, 0, 0, 0, 200);
DateTime reqAuthTime = DateTime.Now + new TimeSpan(0, 0, 0, 0, 200);
// Loop until we are approved
string connectingText = TextManager.Get("Connecting");
LocalizedString connectingText = TextManager.Get("Connecting");
while (!canStart && !connectCancelled)
{
if (reconnectBox == null && waitInServerQueueBox == null)
@@ -493,12 +463,12 @@ namespace Barotrauma.Networking
}
}
}
if (string.IsNullOrEmpty(serverDisplayName)) { serverDisplayName = TextManager.Get("Unknown"); }
if (string.IsNullOrEmpty(serverDisplayName)) { serverDisplayName = TextManager.Get("Unknown").Value; }
reconnectBox = new GUIMessageBox(
connectingText,
TextManager.GetWithVariable("ConnectingTo", "[serverip]", serverDisplayName),
new string[] { TextManager.Get("Cancel") });
new LocalizedString[] { TextManager.Get("Cancel") });
reconnectBox.Buttons[0].OnClicked += (btn, userdata) => { CancelConnect(); return true; };
reconnectBox.Buttons[0].OnClicked += reconnectBox.Close;
}
@@ -524,9 +494,9 @@ namespace Barotrauma.Networking
GUI.ClearCursorWait();
reconnectBox?.Close(); reconnectBox = null;
string pwMsg = TextManager.Get("PasswordRequired");
LocalizedString pwMsg = TextManager.Get("PasswordRequired");
var msgBox = new GUIMessageBox(pwMsg, "", new string[] { TextManager.Get("OK"), TextManager.Get("Cancel") },
var msgBox = new GUIMessageBox(pwMsg, "", new LocalizedString[] { TextManager.Get("OK"), TextManager.Get("Cancel") },
relativeSize: new Vector2(0.25f, 0.1f), minSize: new Point(400, GUI.IntScale(170)));
var passwordHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.5f), msgBox.Content.RectTransform), childAnchor: Anchor.TopCenter);
var passwordBox = new GUITextBox(new RectTransform(new Vector2(0.8f, 1f), passwordHolder.RectTransform) { MinSize = new Point(0, 20) })
@@ -537,7 +507,7 @@ namespace Barotrauma.Networking
if (wrongPassword)
{
var incorrectPasswordText = new GUITextBlock(new RectTransform(new Vector2(1f, 0.0f), passwordHolder.RectTransform), TextManager.Get("incorrectpassword"), GUI.Style.Red, GUI.Font, textAlignment: Alignment.Center);
var incorrectPasswordText = new GUITextBlock(new RectTransform(new Vector2(1f, 0.0f), passwordHolder.RectTransform), TextManager.Get("incorrectpassword"), GUIStyle.Red, GUIStyle.Font, textAlignment: Alignment.Center);
incorrectPasswordText.RectTransform.MinSize = new Point(0, (int)incorrectPasswordText.TextSize.Y);
passwordHolder.Recalculate();
}
@@ -651,7 +621,7 @@ namespace Barotrauma.Networking
}
GameAnalyticsManager.AddErrorEventOnce("GameClient.Update:CheckServerMessagesException" + e.TargetSite.ToString(), GameAnalyticsManager.ErrorSeverity.Error, errorMsg);
DebugConsole.ThrowError("Error while reading a message from server.", e);
new GUIMessageBox(TextManager.Get("Error"), TextManager.GetWithVariables("MessageReadError", new string[2] { "[message]", "[targetsite]" }, new string[2] { e.Message, e.TargetSite.ToString() }));
new GUIMessageBox(TextManager.Get("Error"), TextManager.GetWithVariables("MessageReadError", ("[message]", e.Message), ("[targetsite]", e.TargetSite.ToString())));
Disconnect();
GameMain.ServerListScreen.Select();
return;
@@ -734,6 +704,22 @@ namespace Barotrauma.Networking
MultiPlayerCampaign campaign = GameMain.NetLobbyScreen.SelectedMode == GameMain.GameSession?.GameMode.Preset ?
GameMain.GameSession?.GameMode as MultiPlayerCampaign : null;
if (Screen.Selected is ModDownloadScreen)
{
switch (header)
{
case ServerPacketHeader.UPDATE_LOBBY:
case ServerPacketHeader.PING_REQUEST:
case ServerPacketHeader.FILE_TRANSFER:
case ServerPacketHeader.PERMISSIONS:
case ServerPacketHeader.CHEATS_ENABLED:
//allow interpreting this packet
break;
default:
return; //ignore any other packets
}
}
switch (header)
{
case ServerPacketHeader.PING_REQUEST:
@@ -980,9 +966,12 @@ namespace Barotrauma.Networking
List<ContentFile> contentToPreload = new List<ContentFile>();
for (int i = 0; i < contentToPreloadCount; i++)
{
ContentType contentType = (ContentType)inc.ReadByte();
string filePath = inc.ReadString();
contentToPreload.Add(new ContentFile(filePath, contentType));
ContentFile file = ContentPackageManager.EnabledPackages.All
.Select(p =>
p.Files.FirstOrDefault(f => f.Path == filePath))
.FirstOrDefault(f => !(f is null));
contentToPreload.AddIfNotNull(file);
}
GameMain.GameSession.EventManager.PreloadContent(contentToPreload);
@@ -1002,10 +991,10 @@ namespace Barotrauma.Networking
string errorMsg = $"Mission equality check failed. Mission count doesn't match the server (server: {missionCount}, client: {GameMain.GameSession.Missions.Count()})";
throw new Exception(errorMsg);
}
List<string> serverMissionIdentifiers = new List<string>();
List<Identifier> serverMissionIdentifiers = new List<Identifier>();
for (int i = 0; i < missionCount; i++)
{
serverMissionIdentifiers.Add(inc.ReadString() ?? "");
serverMissionIdentifiers.Add(inc.ReadIdentifier());
}
if (missionCount > 0)
@@ -1032,7 +1021,7 @@ namespace Barotrauma.Networking
" (client value count: " + Level.Loaded.EqualityCheckValues.Count +
", level value count: " + levelEqualityCheckValues.Count +
", seed: " + Level.Loaded.Seed +
", sub: " + Submarine.MainSub.Info.Name + " (" + Submarine.MainSub.Info.MD5Hash.ShortHash + ")" +
", sub: " + Submarine.MainSub.Info.Name + " (" + Submarine.MainSub.Info.MD5Hash.ShortRepresentation + ")" +
", mirrored: " + Level.Loaded.Mirrored + ").";
GameAnalyticsManager.AddErrorEventOnce("GameClient.StartGame:LevelsDontMatch" + Level.Loaded.Seed, GameAnalyticsManager.ErrorSeverity.Error, errorMsg);
throw new Exception(errorMsg);
@@ -1048,7 +1037,7 @@ namespace Barotrauma.Networking
", server value #" + i + ": " + levelEqualityCheckValues[i].ToString("X") +
", level value count: " + levelEqualityCheckValues.Count +
", seed: " + Level.Loaded.Seed +
", sub: " + Submarine.MainSub.Info.Name + " (" + Submarine.MainSub.Info.MD5Hash.ShortHash + ")" +
", sub: " + Submarine.MainSub.Info.Name + " (" + Submarine.MainSub.Info.MD5Hash.ShortRepresentation + ")" +
", mirrored: " + Level.Loaded.Mirrored + ").";
GameAnalyticsManager.AddErrorEventOnce("GameClient.StartGame:LevelsDontMatch" + Level.Loaded.Seed, GameAnalyticsManager.ErrorSeverity.Error, errorMsg);
throw new Exception(errorMsg);
@@ -1076,7 +1065,7 @@ namespace Barotrauma.Networking
reconnectBox?.Close();
reconnectBox = null;
GameMain.Config.RestoreBackupPackages();
ContentPackageManager.EnabledPackages.Restore();
GUI.ClearCursorWait();
@@ -1138,7 +1127,7 @@ namespace Barotrauma.Networking
var queueBox = new GUIMessageBox(
TextManager.Get("DisconnectReason.ServerFull"),
TextManager.Get("ServerFullQuestionPrompt"), new string[] { TextManager.Get("Cancel"), TextManager.Get("ServerQueue") });
TextManager.Get("ServerFullQuestionPrompt"), new LocalizedString[] { TextManager.Get("Cancel"), TextManager.Get("ServerQueue") });
queueBox.Buttons[0].OnClicked += queueBox.Close;
queueBox.Buttons[1].OnClicked += queueBox.Close;
@@ -1178,15 +1167,15 @@ namespace Barotrauma.Networking
DebugConsole.NewMessage("Attempting to reconnect...");
//if the first part of the message is the disconnect reason Enum, don't include it in the popup message
string msg = TextManager.GetServerMessage(disconnectReasonIncluded ? string.Join('/', splitMsg.Skip(1)) : disconnectMsg);
msg = string.IsNullOrWhiteSpace(msg) ?
LocalizedString msg = TextManager.GetServerMessage(disconnectReasonIncluded ? string.Join('/', splitMsg.Skip(1)) : disconnectMsg);
msg = msg.IsNullOrWhiteSpace() ?
TextManager.Get("ConnectionLostReconnecting") :
msg + '\n' + TextManager.Get("ConnectionLostReconnecting");
reconnectBox?.Close();
reconnectBox = new GUIMessageBox(
TextManager.Get("ConnectionLost"), msg,
new string[] { TextManager.Get("Cancel") });
new LocalizedString[] { TextManager.Get("Cancel") });
reconnectBox.Buttons[0].OnClicked += (btn, userdata) => { CancelConnect(); return true; };
connected = false;
ConnectToServer(serverEndpoint, serverName);
@@ -1196,7 +1185,7 @@ namespace Barotrauma.Networking
connected = false;
connectCancelled = true;
string msg = "";
LocalizedString msg = "";
if (disconnectReason == DisconnectReason.Unknown)
{
DebugConsole.NewMessage("Not attempting to reconnect (unknown disconnect reason).");
@@ -1241,11 +1230,45 @@ namespace Barotrauma.Networking
}
}
private void OnConnectionInitializationComplete()
{
if (SteamManager.IsInitialized)
{
Steamworks.SteamFriends.ClearRichPresence();
Steamworks.SteamFriends.SetRichPresence("status", "Playing on " + serverName);
Steamworks.SteamFriends.SetRichPresence("connect", "-connect \"" + serverName.Replace("\"", "\\\"") + "\" " + serverEndpoint);
}
canStart = true;
connected = true;
VoipClient = new VoipClient(this, clientPeer);
if (Screen.Selected != GameMain.GameScreen)
{
GameMain.ModDownloadScreen.Select();
}
else
{
entityEventManager.ClearSelf();
foreach (Character c in Character.CharacterList)
{
c.ResetNetState();
}
}
chatBox.InputBox.Enabled = true;
if (GameMain.NetLobbyScreen?.ChatInput != null)
{
GameMain.NetLobbyScreen.ChatInput.Enabled = true;
}
}
private IEnumerable<CoroutineStatus> WaitInServerQueue()
{
waitInServerQueueBox = new GUIMessageBox(
TextManager.Get("ServerQueuePleaseWait"),
TextManager.Get("WaitingInServerQueue"), new string[] { TextManager.Get("Cancel") });
TextManager.Get("WaitingInServerQueue"), new LocalizedString[] { TextManager.Get("Cancel") });
waitInServerQueueBox.Buttons[0].OnClicked += (btn, userdata) =>
{
CoroutineManager.StopCoroutines("WaitInServerQueue");
@@ -1273,7 +1296,7 @@ namespace Barotrauma.Networking
private void ReadAchievement(IReadMessage inc)
{
string achievementIdentifier = inc.ReadString();
Identifier achievementIdentifier = inc.ReadIdentifier();
int amount = inc.ReadInt32();
if (amount == 0)
{
@@ -1289,16 +1312,16 @@ namespace Barotrauma.Networking
{
TraitorMessageType messageType = (TraitorMessageType)inc.ReadByte();
string missionIdentifier = inc.ReadString();
string message = inc.ReadString();
message = TextManager.GetServerMessage(message);
string messageFmt = inc.ReadString();
LocalizedString message = TextManager.GetServerMessage(messageFmt);
var missionPrefab = TraitorMissionPrefab.List.Find(t => t.Identifier == missionIdentifier);
var missionPrefab = TraitorMissionPrefab.Prefabs.Find(t => t.Identifier == missionIdentifier);
Sprite icon = missionPrefab?.Icon;
switch (messageType)
{
case TraitorMessageType.Objective:
var isTraitor = !string.IsNullOrEmpty(message);
var isTraitor = !message.IsNullOrEmpty();
SpawnAsTraitor = isTraitor;
TraitorFirstObjective = message;
TraitorMission = missionPrefab;
@@ -1309,11 +1332,11 @@ namespace Barotrauma.Networking
}
break;
case TraitorMessageType.Console:
GameMain.Client.AddChatMessage(ChatMessage.Create("", message, ChatMessageType.Console, null));
GameMain.Client.AddChatMessage(ChatMessage.Create("", message.Value, ChatMessageType.Console, null));
DebugConsole.NewMessage(message);
break;
case TraitorMessageType.ServerMessageBox:
var msgBox = new GUIMessageBox("", message, new string[0], type: GUIMessageBox.Type.InGame, icon: icon);
var msgBox = new GUIMessageBox("", message, Array.Empty<LocalizedString>(), type: GUIMessageBox.Type.InGame, icon: icon);
if (msgBox.Icon != null)
{
msgBox.IconColor = missionPrefab.IconColor;
@@ -1321,7 +1344,7 @@ namespace Barotrauma.Networking
break;
case TraitorMessageType.Server:
default:
GameMain.Client.AddChatMessage(message, ChatMessageType.Server);
GameMain.Client.AddChatMessage(message.Value, ChatMessageType.Server);
break;
}
}
@@ -1369,7 +1392,7 @@ namespace Barotrauma.Networking
msgBox.Content.ClearChildren();
msgBox.Content.RectTransform.RelativeSize = new Vector2(0.95f, 0.9f);
var header = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), msgBox.Content.RectTransform), TextManager.Get("PermissionsChanged"), textAlignment: Alignment.Center, font: GUI.LargeFont);
var header = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), msgBox.Content.RectTransform), TextManager.Get("PermissionsChanged"), textAlignment: Alignment.Center, font: GUIStyle.LargeFont);
header.RectTransform.IsFixedSize = true;
var permissionArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 1.0f), msgBox.Content.RectTransform), isHorizontal: true) { Stretch = true, RelativeSpacing = 0.05f };
@@ -1378,12 +1401,12 @@ namespace Barotrauma.Networking
var permissionsLabel = new GUITextBlock(new RectTransform(new Vector2(newPermissions == ClientPermissions.None ? 2.0f : 1.0f, 0.0f), leftColumn.RectTransform),
TextManager.Get(newPermissions == ClientPermissions.None ? "PermissionsRemoved" : "CurrentPermissions"),
wrap: true, font: (newPermissions == ClientPermissions.None ? GUI.Font : GUI.SubHeadingFont));
wrap: true, font: (newPermissions == ClientPermissions.None ? GUIStyle.Font : GUIStyle.SubHeadingFont));
permissionsLabel.RectTransform.NonScaledSize = new Point(permissionsLabel.Rect.Width, permissionsLabel.Rect.Height);
permissionsLabel.RectTransform.IsFixedSize = true;
if (newPermissions != ClientPermissions.None)
{
string permissionList = "";
LocalizedString permissionList = "";
foreach (ClientPermissions permission in Enum.GetValues(typeof(ClientPermissions)))
{
if (!newPermissions.HasFlag(permission) || permission == ClientPermissions.None) { continue; }
@@ -1396,12 +1419,12 @@ namespace Barotrauma.Networking
if (newPermissions.HasFlag(ClientPermissions.ConsoleCommands))
{
var commandsLabel = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), rightColumn.RectTransform),
TextManager.Get("PermittedConsoleCommands"), wrap: true, font: GUI.SubHeadingFont);
TextManager.Get("PermittedConsoleCommands"), wrap: true, font: GUIStyle.SubHeadingFont);
var commandList = new GUIListBox(new RectTransform(new Vector2(1.0f, 1.0f), rightColumn.RectTransform));
foreach (string permittedCommand in permittedConsoleCommands)
{
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), commandList.Content.RectTransform, minSize: new Point(0, 15)),
permittedCommand, font: GUI.SmallFont)
permittedCommand, font: GUIStyle.SmallFont)
{
CanBeFocused = false
};
@@ -1504,11 +1527,11 @@ namespace Barotrauma.Networking
string subHash = inc.ReadString();
string shuttleName = inc.ReadString();
string shuttleHash = inc.ReadString();
List<int> missionIndices = new List<int>();
List<UInt32> missionHashes = new List<UInt32>();
int missionCount = inc.ReadByte();
for (int i = 0; i < missionCount; i++)
{
missionIndices.Add(inc.ReadInt16());
missionHashes.Add(inc.ReadUInt32());
}
if (!GameMain.NetLobbyScreen.TrySelectSub(subName, subHash, GameMain.NetLobbyScreen.SubList))
{
@@ -1525,7 +1548,7 @@ namespace Barotrauma.Networking
//this shouldn't happen, TrySelectSub should stop the coroutine if the correct sub/shuttle cannot be found
if (GameMain.NetLobbyScreen.SelectedSub == null ||
GameMain.NetLobbyScreen.SelectedSub.Name != subName ||
GameMain.NetLobbyScreen.SelectedSub.MD5Hash?.Hash != subHash)
GameMain.NetLobbyScreen.SelectedSub.MD5Hash?.StringRepresentation != subHash)
{
string errorMsg = "Failed to select submarine \"" + subName + "\" (hash: " + subHash + ").";
if (GameMain.NetLobbyScreen.SelectedSub == null)
@@ -1538,9 +1561,9 @@ namespace Barotrauma.Networking
{
errorMsg += "\n" + "Name mismatch: " + GameMain.NetLobbyScreen.SelectedSub.Name + " != " + subName;
}
if (GameMain.NetLobbyScreen.SelectedSub.MD5Hash?.Hash != subHash)
if (GameMain.NetLobbyScreen.SelectedSub.MD5Hash?.StringRepresentation != subHash)
{
errorMsg += "\n" + "Hash mismatch: " + GameMain.NetLobbyScreen.SelectedSub.MD5Hash?.Hash + " != " + subHash;
errorMsg += "\n" + "Hash mismatch: " + GameMain.NetLobbyScreen.SelectedSub.MD5Hash?.StringRepresentation + " != " + subHash;
}
}
gameStarted = true;
@@ -1552,7 +1575,7 @@ namespace Barotrauma.Networking
}
if (GameMain.NetLobbyScreen.SelectedShuttle == null ||
GameMain.NetLobbyScreen.SelectedShuttle.Name != shuttleName ||
GameMain.NetLobbyScreen.SelectedShuttle.MD5Hash?.Hash != shuttleHash)
GameMain.NetLobbyScreen.SelectedShuttle.MD5Hash?.StringRepresentation != shuttleHash)
{
gameStarted = true;
GameMain.NetLobbyScreen.Select();
@@ -1563,7 +1586,7 @@ namespace Barotrauma.Networking
yield return CoroutineStatus.Failure;
}
var selectedMissions = missionIndices.Select(i => MissionPrefab.List[i]);
var selectedMissions = missionHashes.Select(i => MissionPrefab.Prefabs.Find(p => p.UintIdentifier == i));
GameMain.GameSession = new GameSession(GameMain.NetLobbyScreen.SelectedSub, gameMode, missionPrefabs: selectedMissions);
GameMain.GameSession.StartRound(levelSeed, levelDifficulty);
@@ -1767,7 +1790,7 @@ namespace Barotrauma.Networking
GameMain.GameScreen.Select();
AddChatMessage($"ServerMessage.HowToCommunicate~[chatbutton]={GameMain.Config.KeyBindText(InputType.Chat)}~[radiobutton]={GameMain.Config.KeyBindText(InputType.RadioChat)}", ChatMessageType.Server);
AddChatMessage($"ServerMessage.HowToCommunicate~[chatbutton]={GameSettings.CurrentConfig.KeyMap.KeyBindText(InputType.Chat)}~[radiobutton]={GameSettings.CurrentConfig.KeyMap.KeyBindText(InputType.RadioChat)}", ChatMessageType.Server);
yield return CoroutineStatus.Success;
}
@@ -1850,7 +1873,7 @@ namespace Barotrauma.Networking
byte subClass = inc.ReadByte();
bool requiredContentPackagesInstalled = inc.ReadBoolean();
var matchingSub = SubmarineInfo.SavedSubmarines.FirstOrDefault(s => s.Name == subName && s.MD5Hash.Hash == subHash);
var matchingSub = SubmarineInfo.SavedSubmarines.FirstOrDefault(s => s.Name == subName && s.MD5Hash.StringRepresentation == subHash);
if (matchingSub == null)
{
matchingSub = new SubmarineInfo(Path.Combine(SubmarineInfo.SavePath, subName) + ".sub", subHash, tryLoad: false)
@@ -1913,7 +1936,7 @@ namespace Barotrauma.Networking
if (Screen.Selected != GameMain.GameScreen)
{
new GUIMessageBox(TextManager.Get("PleaseWait"), TextManager.Get(allowSpectating ? "RoundRunningSpectateEnabled" : "RoundRunningSpectateDisabled"));
GameMain.NetLobbyScreen.Select();
if (!(Screen.Selected is ModDownloadScreen)) { GameMain.NetLobbyScreen.Select(); }
}
}
}
@@ -1930,7 +1953,7 @@ namespace Barotrauma.Networking
UInt64 steamId = inc.ReadUInt64();
UInt16 nameId = inc.ReadUInt16();
string name = inc.ReadString();
string preferredJob = inc.ReadString();
Identifier preferredJob = inc.ReadIdentifier();
byte preferredTeam = inc.ReadByte();
UInt16 characterID = inc.ReadUInt16();
float karma = inc.ReadSingle();
@@ -2088,7 +2111,7 @@ namespace Barotrauma.Networking
bool isInitialUpdate = inc.ReadBoolean();
if (isInitialUpdate)
{
if (GameSettings.VerboseLogging)
if (GameSettings.CurrentConfig.VerboseLogging)
{
DebugConsole.NewMessage("Received initial lobby update, ID: " + updateID + ", last ID: " + GameMain.NetLobbyScreen.LastUpdateID, Color.Gray);
}
@@ -2253,7 +2276,10 @@ namespace Barotrauma.Networking
}
break;
case ServerNetObject.ENTITY_POSITION:
bool isItem = inc.ReadBoolean();
inc.ReadPadBits(); //padding is required here to make sure any padding bits within tempBuffer are read correctly
bool isItem = inc.ReadBoolean(); inc.ReadPadBits();
UInt32 incomingUintIdentifier = inc.ReadUInt32();
UInt16 id = inc.ReadUInt16();
uint msgLength = inc.ReadVariableUInt32();
int msgEndPos = (int)(inc.BitPosition + msgLength * 8);
@@ -2272,11 +2298,18 @@ namespace Barotrauma.Networking
{
DebugConsole.AddWarning($"Received a potentially invalid ENTITY_POSITION message. Entity type does not match (server entity is {(isItem ? "an item" : "not an item")}, client entity is {(entity?.GetType().ToString() ?? "null")}). Ignoring the message...");
}
else if (entity is MapEntity { Prefab: { UintIdentifier: { } uintIdentifier } } me &&
uintIdentifier != incomingUintIdentifier)
{
DebugConsole.AddWarning($"Received a potentially invalid ENTITY_POSITION message."
+$"Entity identifier does not match (server entity is {MapEntityPrefab.List.FirstOrDefault(p => p.UintIdentifier == incomingUintIdentifier)?.Identifier.Value ?? "[not found]"}, "
+$"client entity is {me.Prefab.Identifier}). Ignoring the message...");
}
else
{
entity.ClientRead(objHeader.Value, inc, sendingTime);
}
}
}
//force to the correct position in case the entity doesn't exist
//or the message wasn't read correctly for whatever reason
@@ -2382,13 +2415,13 @@ namespace Barotrauma.Networking
var jobPreferences = GameMain.NetLobbyScreen.JobPreferences;
if (jobPreferences.Count > 0)
{
outmsg.Write(jobPreferences[0].First.Identifier);
outmsg.Write(jobPreferences[0].Prefab.Identifier);
}
else
{
outmsg.Write("");
}
outmsg.Write((byte)GameMain.Config.TeamPreference);
outmsg.Write((byte)MultiplayerPreferences.Instance.TeamPreference);
if (!(GameMain.GameSession?.GameMode is MultiPlayerCampaign campaign) || campaign.LastSaveID == 0)
{
@@ -2512,8 +2545,8 @@ namespace Barotrauma.Networking
msg.Write((byte)ClientPacketHeader.FILE_REQUEST);
msg.Write((byte)FileTransferMessageType.Initiate);
msg.Write((byte)fileType);
if (file != null) msg.Write(file);
if (fileHash != null) msg.Write(fileHash);
msg.Write(file ?? throw new ArgumentNullException(nameof(file)));
msg.Write(fileHash ?? throw new ArgumentNullException(nameof(fileHash)));
clientPeer.Send(msg, DeliveryMethod.Reliable);
}
@@ -2522,13 +2555,14 @@ namespace Barotrauma.Networking
CancelFileTransfer(transfer.ID);
}
public void UpdateFileTransfer(int id, int offset, bool reliable = false)
public void UpdateFileTransfer(int id, int expecting, int lastSeen, bool reliable = false)
{
IWriteMessage msg = new WriteOnlyMessage();
msg.Write((byte)ClientPacketHeader.FILE_REQUEST);
msg.Write((byte)FileTransferMessageType.Data);
msg.Write((byte)id);
msg.Write(offset);
msg.Write(expecting);
msg.Write(lastSeen);
clientPeer.Send(msg, reliable ? DeliveryMethod.Reliable : DeliveryMethod.Unreliable);
}
@@ -2550,7 +2584,7 @@ namespace Barotrauma.Networking
var newSub = new SubmarineInfo(transfer.FilePath);
if (newSub.IsFileCorrupted) { return; }
var existingSubs = SubmarineInfo.SavedSubmarines.Where(s => s.Name == newSub.Name && s.MD5Hash.Hash == newSub.MD5Hash.Hash).ToList();
var existingSubs = SubmarineInfo.SavedSubmarines.Where(s => s.Name == newSub.Name && s.MD5Hash.StringRepresentation == newSub.MD5Hash.StringRepresentation).ToList();
foreach (SubmarineInfo existingSub in existingSubs)
{
existingSub.Dispose();
@@ -2565,7 +2599,7 @@ namespace Barotrauma.Networking
var subElement = subListChildren.FirstOrDefault(c =>
((SubmarineInfo)c.UserData).Name == newSub.Name &&
((SubmarineInfo)c.UserData).MD5Hash.Hash == newSub.MD5Hash.Hash);
((SubmarineInfo)c.UserData).MD5Hash.StringRepresentation == newSub.MD5Hash.StringRepresentation);
if (subElement == null) continue;
Color newSubTextColor = new Color(subElement.GetChild<GUITextBlock>().TextColor, 1.0f);
@@ -2585,25 +2619,25 @@ namespace Barotrauma.Networking
if (GameMain.NetLobbyScreen.FailedSelectedSub.HasValue &&
GameMain.NetLobbyScreen.FailedSelectedSub.Value.Name == newSub.Name &&
GameMain.NetLobbyScreen.FailedSelectedSub.Value.Hash == newSub.MD5Hash.Hash)
GameMain.NetLobbyScreen.FailedSelectedSub.Value.Hash == newSub.MD5Hash.StringRepresentation)
{
GameMain.NetLobbyScreen.TrySelectSub(newSub.Name, newSub.MD5Hash.Hash, GameMain.NetLobbyScreen.SubList);
GameMain.NetLobbyScreen.TrySelectSub(newSub.Name, newSub.MD5Hash.StringRepresentation, GameMain.NetLobbyScreen.SubList);
}
if (GameMain.NetLobbyScreen.FailedSelectedShuttle.HasValue &&
GameMain.NetLobbyScreen.FailedSelectedShuttle.Value.Name == newSub.Name &&
GameMain.NetLobbyScreen.FailedSelectedShuttle.Value.Hash == newSub.MD5Hash.Hash)
GameMain.NetLobbyScreen.FailedSelectedShuttle.Value.Name == newSub.MD5Hash.StringRepresentation)
{
GameMain.NetLobbyScreen.TrySelectSub(newSub.Name, newSub.MD5Hash.Hash, GameMain.NetLobbyScreen.ShuttleList.ListBox);
GameMain.NetLobbyScreen.TrySelectSub(newSub.Name, newSub.MD5Hash.StringRepresentation, GameMain.NetLobbyScreen.ShuttleList.ListBox);
}
NetLobbyScreen.FailedSubInfo failedCampaignSub = GameMain.NetLobbyScreen.FailedCampaignSubs.Find(s => s.Name == newSub.Name && s.Hash == newSub.MD5Hash.Hash);
NetLobbyScreen.FailedSubInfo failedCampaignSub = GameMain.NetLobbyScreen.FailedCampaignSubs.Find(s => s.Name == newSub.Name && s.Hash == newSub.MD5Hash.StringRepresentation);
if (failedCampaignSub != default)
{
GameMain.NetLobbyScreen.FailedCampaignSubs.Remove(failedCampaignSub);
}
NetLobbyScreen.FailedSubInfo failedOwnedSub = GameMain.NetLobbyScreen.FailedOwnedSubs.Find(s => s.Name == newSub.Name && s.Hash == newSub.MD5Hash.Hash);
NetLobbyScreen.FailedSubInfo failedOwnedSub = GameMain.NetLobbyScreen.FailedOwnedSubs.Find(s => s.Name == newSub.Name && s.Hash == newSub.MD5Hash.StringRepresentation);
if (failedOwnedSub != default)
{
GameMain.NetLobbyScreen.ServerOwnedSubmarines.Add(newSub);
@@ -2611,7 +2645,7 @@ namespace Barotrauma.Networking
}
// Replace a submarine dud with the downloaded version
SubmarineInfo existingServerSub = ServerSubmarines.Find(s => s.Name == newSub.Name && s.MD5Hash?.Hash == newSub.MD5Hash?.Hash);
SubmarineInfo existingServerSub = ServerSubmarines.Find(s => s.Name == newSub.Name && s.MD5Hash?.StringRepresentation == newSub.MD5Hash?.StringRepresentation);
if (existingServerSub != null)
{
int existingIndex = ServerSubmarines.IndexOf(existingServerSub);
@@ -2661,6 +2695,11 @@ namespace Barotrauma.Networking
//(as there may have been campaign updates after the save file was created)
campaign.LastUpdateID--;
break;
case FileTransferType.Mod:
if (!(Screen.Selected is ModDownloadScreen)) { return; }
GameMain.ModDownloadScreen.CurrentDownloadFinished(transfer);
break;
}
}
@@ -2756,24 +2795,26 @@ namespace Barotrauma.Networking
msg.Write(characterInfo == null);
if (characterInfo == null) return;
msg.Write((byte)characterInfo.Gender);
msg.Write((byte)characterInfo.Race);
msg.Write((byte)characterInfo.HeadSpriteId);
msg.Write((byte)characterInfo.HairIndex);
msg.Write((byte)characterInfo.BeardIndex);
msg.Write((byte)characterInfo.MoustacheIndex);
msg.Write((byte)characterInfo.FaceAttachmentIndex);
msg.WriteColorR8G8B8(characterInfo.SkinColor);
msg.WriteColorR8G8B8(characterInfo.HairColor);
msg.WriteColorR8G8B8(characterInfo.FacialHairColor);
msg.Write((byte)characterInfo.Head.Preset.TagSet.Count);
foreach (Identifier tag in characterInfo.Head.Preset.TagSet)
{
msg.Write(tag);
}
msg.Write((byte)characterInfo.Head.HairIndex);
msg.Write((byte)characterInfo.Head.BeardIndex);
msg.Write((byte)characterInfo.Head.MoustacheIndex);
msg.Write((byte)characterInfo.Head.FaceAttachmentIndex);
msg.WriteColorR8G8B8(characterInfo.Head.SkinColor);
msg.WriteColorR8G8B8(characterInfo.Head.HairColor);
msg.WriteColorR8G8B8(characterInfo.Head.FacialHairColor);
var jobPreferences = GameMain.NetLobbyScreen.JobPreferences;
int count = Math.Min(jobPreferences.Count, 3);
msg.Write((byte)count);
for (int i = 0; i < count; i++)
{
msg.Write(jobPreferences[i].First.Identifier);
msg.Write((byte)jobPreferences[i].Second);
msg.Write(jobPreferences[i].Prefab.Identifier);
msg.Write((byte)jobPreferences[i].Variant);
}
}
@@ -2976,7 +3017,7 @@ namespace Barotrauma.Networking
msg.Write(saveName);
msg.Write(mapSeed);
msg.Write(sub.Name);
msg.Write(sub.MD5Hash.Hash);
msg.Write(sub.MD5Hash.StringRepresentation);
settings.Serialize(msg);
clientPeer.Send(msg, DeliveryMethod.Reliable);
@@ -3259,7 +3300,7 @@ namespace Barotrauma.Networking
GameMain.NetLobbyScreen.FileTransferFrame.UserData = transfer;
GameMain.NetLobbyScreen.FileTransferTitle.Text =
ToolBox.LimitString(
TextManager.GetWithVariable("DownloadingFile", "[filename]", transfer.FileName),
TextManager.GetWithVariable("DownloadingFile", "[filename]", transfer.FileName).Value,
GameMain.NetLobbyScreen.FileTransferTitle.Font,
GameMain.NetLobbyScreen.FileTransferTitle.Rect.Width);
GameMain.NetLobbyScreen.FileTransferProgressBar.BarSize = transfer.Progress;
@@ -3279,26 +3320,25 @@ namespace Barotrauma.Networking
{
if (EndVoteTickBox.Visible)
{
EndVoteTickBox.Text =
(EndVoteTickBox.UserData as string) + " " + EndVoteCount + "/" + EndVoteMax;
EndVoteTickBox.Text = $"{endRoundVoteText} {EndVoteCount}/{EndVoteMax}";
}
else
{
string endVoteText = TextManager.GetWithVariables("EndRoundVotes", new string[2] { "[votes]", "[max]" }, new string[2] { EndVoteCount.ToString(), EndVoteMax.ToString() });
GUI.DrawString(spriteBatch, EndVoteTickBox.Rect.Center.ToVector2() - GUI.SmallFont.MeasureString(endVoteText) / 2,
endVoteText,
LocalizedString endVoteText = TextManager.GetWithVariables("EndRoundVotes", ("[votes]", EndVoteCount.ToString()), ("[max]", EndVoteMax.ToString()));
GUI.DrawString(spriteBatch, EndVoteTickBox.Rect.Center.ToVector2() - GUIStyle.SmallFont.MeasureString(endVoteText) / 2,
endVoteText.Value,
Color.White,
font: GUI.SmallFont);
font: GUIStyle.SmallFont);
}
}
else
{
EndVoteTickBox.Text = EndVoteTickBox.UserData as string;
EndVoteTickBox.Text = endRoundVoteText;
}
if (respawnManager != null)
{
string respawnText = string.Empty;
LocalizedString respawnText = string.Empty;
Color textColor = Color.White;
bool canChooseRespawn =
GameMain.GameSession.GameMode is CampaignMode &&
@@ -3316,9 +3356,9 @@ namespace Barotrauma.Networking
}
else if (respawnManager.PendingRespawnCount > 0)
{
respawnText = TextManager.GetWithVariables("RespawnWaitingForMoreDeadPlayers",
new string[] { "[deadplayers]", "[requireddeadplayers]" },
new string[] { respawnManager.PendingRespawnCount.ToString(), respawnManager.RequiredRespawnCount.ToString() });
respawnText = TextManager.GetWithVariables("RespawnWaitingForMoreDeadPlayers",
("[deadplayers]", respawnManager.PendingRespawnCount.ToString()),
("[requireddeadplayers]", respawnManager.RequiredRespawnCount.ToString()));
}
}
else if (respawnManager.CurrentState == RespawnManager.State.Transporting &&
@@ -3333,13 +3373,13 @@ namespace Barotrauma.Networking
//oscillate between 0-1
float phase = (float)(Math.Sin(timeLeft * MathHelper.Pi) + 1.0f) * 0.5f;
//textScale = 1.0f + phase * 0.5f;
textColor = Color.Lerp(GUI.Style.Red, Color.White, 1.0f - phase);
textColor = Color.Lerp(GUIStyle.Red, Color.White, 1.0f - phase);
}
canChooseRespawn = false;
}
GameMain.GameSession?.SetRespawnInfo(
visible: !string.IsNullOrEmpty(respawnText) || canChooseRespawn, text: respawnText, textColor: textColor,
visible: !respawnText.IsNullOrEmpty() || canChooseRespawn, text: respawnText.Value, textColor: textColor,
buttonsVisible: canChooseRespawn, waitForNextRoundRespawn: (WaitForNextRoundRespawn ?? true));
}
@@ -3352,23 +3392,23 @@ namespace Barotrauma.Networking
int x = GameMain.GraphicsWidth - width, y = (int)(GameMain.GraphicsHeight * 0.3f);
GUI.DrawRectangle(spriteBatch, new Rectangle(x, y, width, height), Color.Black * 0.7f, true);
GUI.Font.DrawString(spriteBatch, "Network statistics:", new Vector2(x + 10, y + 10), Color.White);
GUIStyle.Font.DrawString(spriteBatch, "Network statistics:", new Vector2(x + 10, y + 10), Color.White);
if (client.ServerConnection != null)
{
GUI.Font.DrawString(spriteBatch, "Ping: " + (int)(client.ServerConnection.AverageRoundtripTime * 1000.0f) + " ms", new Vector2(x + 10, y + 25), Color.White);
GUIStyle.Font.DrawString(spriteBatch, "Ping: " + (int)(client.ServerConnection.AverageRoundtripTime * 1000.0f) + " ms", new Vector2(x + 10, y + 25), Color.White);
y += 15;
GUI.SmallFont.DrawString(spriteBatch, "Received bytes: " + client.Statistics.ReceivedBytes, new Vector2(x + 10, y + 45), Color.White);
GUI.SmallFont.DrawString(spriteBatch, "Received packets: " + client.Statistics.ReceivedPackets, new Vector2(x + 10, y + 60), Color.White);
GUIStyle.SmallFont.DrawString(spriteBatch, "Received bytes: " + client.Statistics.ReceivedBytes, new Vector2(x + 10, y + 45), Color.White);
GUIStyle.SmallFont.DrawString(spriteBatch, "Received packets: " + client.Statistics.ReceivedPackets, new Vector2(x + 10, y + 60), Color.White);
GUI.SmallFont.DrawString(spriteBatch, "Sent bytes: " + client.Statistics.SentBytes, new Vector2(x + 10, y + 75), Color.White);
GUI.SmallFont.DrawString(spriteBatch, "Sent packets: " + client.Statistics.SentPackets, new Vector2(x + 10, y + 90), Color.White);
GUIStyle.SmallFont.DrawString(spriteBatch, "Sent bytes: " + client.Statistics.SentBytes, new Vector2(x + 10, y + 75), Color.White);
GUIStyle.SmallFont.DrawString(spriteBatch, "Sent packets: " + client.Statistics.SentPackets, new Vector2(x + 10, y + 90), Color.White);
}
else
{
GUI.Font.DrawString(spriteBatch, "Disconnected", new Vector2(x + 10, y + 25), Color.White);
GUIStyle.Font.DrawString(spriteBatch, "Disconnected", new Vector2(x + 10, y + 25), Color.White);
}*/
}
@@ -3471,7 +3511,7 @@ namespace Barotrauma.Networking
{
var banReasonPrompt = new GUIMessageBox(
TextManager.Get(ban ? "BanReasonPrompt" : "KickReasonPrompt"),
"", new string[] { TextManager.Get("OK"), TextManager.Get("Cancel") }, new Vector2(0.25f, 0.25f), new Point(400, 260));
"", new LocalizedString[] { TextManager.Get("OK"), TextManager.Get("Cancel") }, new Vector2(0.25f, 0.25f), new Point(400, 260));
var content = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.6f), banReasonPrompt.InnerFrame.RectTransform, Anchor.Center))
{
@@ -3489,7 +3529,7 @@ namespace Barotrauma.Networking
if (ban)
{
var labelContainer = new GUILayoutGroup(new RectTransform(new Vector2(1f, 0.25f), content.RectTransform), isHorizontal: false);
new GUITextBlock(new RectTransform(new Vector2(1f, 0.0f), labelContainer.RectTransform), TextManager.Get("BanDuration"), font: GUI.SubHeadingFont) { Padding = Vector4.Zero };
new GUITextBlock(new RectTransform(new Vector2(1f, 0.0f), labelContainer.RectTransform), TextManager.Get("BanDuration"), font: GUIStyle.SubHeadingFont) { Padding = Vector4.Zero };
var buttonContent = new GUILayoutGroup(new RectTransform(new Vector2(1f, 0.5f), labelContainer.RectTransform), isHorizontal: true);
permaBanTickBox = new GUITickBox(new RectTransform(new Vector2(0.4f, 0.15f), buttonContent.RectTransform), TextManager.Get("BanPermanent"))
{
@@ -3599,7 +3639,7 @@ namespace Barotrauma.Networking
if (GameMain.GameSession?.GameMode != null)
{
errorLines.Add("Game mode: " + GameMain.GameSession.GameMode.Name);
errorLines.Add("Game mode: " + GameMain.GameSession.GameMode.Name.Value);
if (GameMain.GameSession?.GameMode is MultiPlayerCampaign campaign)
{
errorLines.Add("Campaign ID: " + campaign.CampaignID);
@@ -3623,19 +3663,18 @@ namespace Barotrauma.Networking
errorLines.Add("Level: " + Level.Loaded.Seed + ", " + string.Join(", ", Level.Loaded.EqualityCheckValues.Select(cv => cv.ToString("X"))));
errorLines.Add("Entity count before generating level: " + Level.Loaded.EntityCountBeforeGenerate);
errorLines.Add("Entities:");
foreach (Entity e in Level.Loaded.EntitiesBeforeGenerate)
foreach (Entity e in Level.Loaded.EntitiesBeforeGenerate.OrderBy(e => e.CreationIndex))
{
errorLines.Add(" " + e.ID + ": " + e.ToString());
errorLines.Add(e.ErrorLine);
}
errorLines.Add("Entity count after generating level: " + Level.Loaded.EntityCountAfterGenerate);
}
errorLines.Add("Entity IDs:");
List<Entity> sortedEntities = Entity.GetEntities().ToList();
sortedEntities.Sort((e1, e2) => e1.ID.CompareTo(e2.ID));
Entity[] sortedEntities = Entity.GetEntities().OrderBy(e => e.CreationIndex).ToArray();
foreach (Entity e in sortedEntities)
{
errorLines.Add(e.ID + ": " + e.ToString());
errorLines.Add(e.ErrorLine);
}
errorLines.Add("");
@@ -3645,7 +3684,7 @@ namespace Barotrauma.Networking
errorLines.Add(" " + DebugConsole.Messages[i].Time + " - " + DebugConsole.Messages[i].Text);
}
string filePath = "event_error_log_client_" + Name + "_" + DateTime.UtcNow.ToShortTimeString() + ".log";
string filePath = $"event_error_log_client_{Name}_{DateTime.UtcNow.ToShortTimeString()}.log";
filePath = Path.Combine(ServerLog.SavePath, ToolBox.RemoveInvalidFileNameChars(filePath));
if (!Directory.Exists(ServerLog.SavePath))
@@ -28,7 +28,7 @@ namespace Barotrauma
CreateLabeledSlider(parent, 0.0f, 50.0f, 1.0f, nameof(KarmaIncreaseThreshold));
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.12f), parent.RectTransform), TextManager.Get("Karma.PositiveActions"),
textAlignment: Alignment.Center, font: GUI.SubHeadingFont)
textAlignment: Alignment.Center, font: GUIStyle.SubHeadingFont)
{
CanBeFocused = false
};
@@ -41,7 +41,7 @@ namespace Barotrauma
CreateLabeledSlider(parent, 0.0f, 1.0f, 0.01f, nameof(BallastFloraKarmaIncrease));
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.12f), parent.RectTransform), TextManager.Get("Karma.NegativeActions"),
textAlignment: Alignment.Center, font: GUI.SubHeadingFont)
textAlignment: Alignment.Center, font: GUIStyle.SubHeadingFont)
{
CanBeFocused = false
};
@@ -86,9 +86,9 @@ namespace Barotrauma
ToolTip = TextManager.Get("Karma." + propertyName + "ToolTip")
};
string labelText = TextManager.Get("Karma." + propertyName);
LocalizedString labelText = TextManager.Get("Karma." + propertyName);
var label = new GUITextBlock(new RectTransform(new Vector2(0.7f, 1.0f), container.RectTransform),
labelText, textAlignment: Alignment.CenterLeft, font: GUI.SmallFont)
labelText, textAlignment: Alignment.CenterLeft, font: GUIStyle.SmallFont)
{
ToolTip = TextManager.Get("Karma." + propertyName + "ToolTip")
};
@@ -120,8 +120,8 @@ namespace Barotrauma
ToolTip = TextManager.Get("Karma." + propertyName + "ToolTip")
};
string labelText = TextManager.Get("Karma." + propertyName);
new GUITextBlock(new RectTransform(new Vector2(0.7f, 1.0f), container.RectTransform), labelText, textAlignment: Alignment.CenterLeft, font: GUI.SmallFont)
LocalizedString labelText = TextManager.Get("Karma." + propertyName);
new GUITextBlock(new RectTransform(new Vector2(0.7f, 1.0f), container.RectTransform), labelText, textAlignment: Alignment.CenterLeft, font: GUIStyle.SmallFont)
{
ToolTip = TextManager.Get("Karma." + propertyName + "ToolTip")
};
@@ -140,7 +140,7 @@ namespace Barotrauma
{
var tickBox = new GUITickBox(new RectTransform(new Vector2(0.3f, 0.1f), parent.RectTransform), TextManager.Get("Karma." + propertyName))
{
ToolTip = TextManager.Get("Karma." + propertyName + "ToolTip", returnNull: true) ?? ""
ToolTip = TextManager.Get("Karma." + propertyName + "ToolTip").Fallback("")
};
GameMain.NetworkMember.ServerSettings.AssignGUIComponent(propertyName, tickBox);
}
@@ -120,7 +120,7 @@ namespace Barotrauma.Networking
unreceivedEntityEventCount = msg.ReadUInt16();
firstNewID = msg.ReadUInt16();
if (GameSettings.VerboseLogging)
if (GameSettings.CurrentConfig.VerboseLogging)
{
DebugConsole.NewMessage(
"received midround syncing msg, unreceived: " + unreceivedEntityEventCount +
@@ -132,7 +132,7 @@ namespace Barotrauma.Networking
MidRoundSyncingDone = true;
if (firstNewID != null)
{
if (GameSettings.VerboseLogging)
if (GameSettings.CurrentConfig.VerboseLogging)
{
DebugConsole.NewMessage("midround syncing complete, switching to ID " + (UInt16) (firstNewID - 1),
Microsoft.Xna.Framework.Color.Yellow);
@@ -167,7 +167,7 @@ namespace Barotrauma.Networking
if (entityID == Entity.NullEntityID)
{
if (GameSettings.VerboseLogging)
if (GameSettings.CurrentConfig.VerboseLogging)
{
DebugConsole.NewMessage("received msg " + thisEventID + " (null entity)",
Microsoft.Xna.Framework.Color.Orange);
@@ -188,12 +188,12 @@ namespace Barotrauma.Networking
{
if (thisEventID != (UInt16) (lastReceivedID + 1))
{
if (GameSettings.VerboseLogging)
if (GameSettings.CurrentConfig.VerboseLogging)
{
DebugConsole.NewMessage(
"Received msg " + thisEventID + " (waiting for " + (lastReceivedID + 1) + ")",
NetIdUtils.IdMoreRecent(thisEventID, (UInt16)(lastReceivedID + 1))
? GUI.Style.Red
? GUIStyle.Red
: Microsoft.Xna.Framework.Color.Yellow);
}
}
@@ -201,7 +201,7 @@ namespace Barotrauma.Networking
{
DebugConsole.NewMessage(
"Received msg " + thisEventID + ", entity " + entityID + " not found",
GUI.Style.Red);
GUIStyle.Red);
GameMain.Client.ReportError(ClientNetError.MISSING_ENTITY, eventID: thisEventID, entityID: entityID);
return false;
}
@@ -212,7 +212,7 @@ namespace Barotrauma.Networking
else
{
int msgPosition = msg.BitPosition;
if (GameSettings.VerboseLogging)
if (GameSettings.CurrentConfig.VerboseLogging)
{
DebugConsole.NewMessage("received msg " + thisEventID + " (" + entity.ToString() + ")",
Microsoft.Xna.Framework.Color.Green);
@@ -61,29 +61,29 @@ namespace Barotrauma.Networking
GUI.DrawRectangle(spriteBatch, rect, Color.Black * 0.4f, true);
graphs[(int)NetStatType.ReceivedBytes].Draw(spriteBatch, rect, color: Color.Cyan);
graphs[(int)NetStatType.SentBytes].Draw(spriteBatch, rect, null, color: GUI.Style.Orange);
graphs[(int)NetStatType.SentBytes].Draw(spriteBatch, rect, null, color: GUIStyle.Orange);
if (graphs[(int)NetStatType.ResentMessages].Average() > 0)
{
graphs[(int)NetStatType.ResentMessages].Draw(spriteBatch, rect, color: GUI.Style.Red);
GUI.SmallFont.DrawString(spriteBatch, "Peak resent: " + graphs[(int)NetStatType.ResentMessages].LargestValue() + " messages/s",
new Vector2(rect.Right + 10, rect.Y + 50), GUI.Style.Red);
graphs[(int)NetStatType.ResentMessages].Draw(spriteBatch, rect, color: GUIStyle.Red);
GUIStyle.SmallFont.DrawString(spriteBatch, "Peak resent: " + graphs[(int)NetStatType.ResentMessages].LargestValue() + " messages/s",
new Vector2(rect.Right + 10, rect.Y + 50), GUIStyle.Red);
}
GUI.SmallFont.DrawString(spriteBatch,
GUIStyle.SmallFont.DrawString(spriteBatch,
"Peak received: " + MathUtils.GetBytesReadable((int)graphs[(int)NetStatType.ReceivedBytes].LargestValue()) + "/s " +
"Avg received: " + MathUtils.GetBytesReadable((int)graphs[(int)NetStatType.ReceivedBytes].Average()) + "/s",
new Vector2(rect.Right + 10, rect.Y + 10), Color.Cyan);
GUI.SmallFont.DrawString(spriteBatch, "Peak sent: " + MathUtils.GetBytesReadable((int)graphs[(int)NetStatType.SentBytes].LargestValue()) + "/s " +
GUIStyle.SmallFont.DrawString(spriteBatch, "Peak sent: " + MathUtils.GetBytesReadable((int)graphs[(int)NetStatType.SentBytes].LargestValue()) + "/s " +
"Avg sent: " + MathUtils.GetBytesReadable((int)graphs[(int)NetStatType.SentBytes].Average()) + "/s",
new Vector2(rect.Right + 10, rect.Y + 30), GUI.Style.Orange);
new Vector2(rect.Right + 10, rect.Y + 30), GUIStyle.Orange);
#if DEBUG
/*int y = 10;
foreach (KeyValuePair<string, long> msgBytesSent in server.messageCount.OrderBy(key => -key.Value))
{
GUI.SmallFont.DrawString(spriteBatch, msgBytesSent.Key + ": " + MathUtils.GetBytesReadable(msgBytesSent.Value),
new Vector2(rect.Right - 200, rect.Y + y), GUI.Style.Red);
GUIStyle.SmallFont.DrawString(spriteBatch, msgBytesSent.Key + ": " + MathUtils.GetBytesReadable(msgBytesSent.Value),
new Vector2(rect.Right - 200, rect.Y + y), GUIStyle.Red);
y += 15;
}
@@ -2,6 +2,7 @@
using Barotrauma.Steam;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using System.Text;
@@ -10,30 +11,37 @@ namespace Barotrauma.Networking
{
abstract class ClientPeer
{
protected class ServerContentPackage
public class ServerContentPackage
{
public readonly string Name;
public readonly string Hash;
public readonly Md5Hash Hash;
public readonly UInt64 WorkshopId;
public readonly DateTime InstallTime;
public ContentPackage RegularPackage
public RegularPackage RegularPackage
{
get
{
return ContentPackage.RegularPackages.Find(p => p.MD5hash.Hash.Equals(Hash));
return ContentPackageManager.RegularPackages.FirstOrDefault(p => p.Hash.Equals(Hash));
}
}
public ContentPackage CorePackage
public CorePackage CorePackage
{
get
{
return ContentPackage.CorePackages.Find(p => p.MD5hash.Hash.Equals(Hash));
return ContentPackageManager.CorePackages.FirstOrDefault(p => p.Hash.Equals(Hash));
}
}
public ServerContentPackage(string name, string hash, UInt64 workshopId, DateTime installTime)
public ContentPackage ContentPackage
=> (ContentPackage)RegularPackage ?? CorePackage;
public string GetPackageStr()
=> $"\"{Name}\" (hash {Hash.ShortRepresentation})";
public ServerContentPackage(string name, Md5Hash hash, UInt64 workshopId, DateTime installTime)
{
Name = name;
Hash = hash;
@@ -42,14 +50,8 @@ namespace Barotrauma.Networking
}
}
protected string GetPackageStr(ContentPackage contentPackage)
{
return $"\"{contentPackage.Name}\" (hash {contentPackage.MD5hash.ShortHash})";
}
protected string GetPackageStr(ServerContentPackage contentPackage)
{
return $"\"{contentPackage.Name}\" (hash {Md5Hash.GetShortHash(contentPackage.Hash)})";
}
public ImmutableArray<ServerContentPackage> ServerContentPackages { get; private set; } =
ImmutableArray<ServerContentPackage>.Empty;
public delegate void MessageCallback(IReadMessage message);
public delegate void DisconnectCallback(bool disableReconnect);
@@ -72,7 +74,7 @@ namespace Barotrauma.Networking
public abstract void Start(object endPoint, int ownerKey);
public abstract void Close(string msg = null, bool disableReconnect = false);
public abstract void Update(float deltaTime);
public abstract void Send(IWriteMessage msg, DeliveryMethod deliveryMethod);
public abstract void Send(IWriteMessage msg, DeliveryMethod deliveryMethod, bool compressPastThreshold = true);
public abstract void SendPassword(string password);
protected abstract void SendMsgInternal(DeliveryMethod deliveryMethod, IWriteMessage msg);
@@ -108,7 +110,7 @@ namespace Barotrauma.Networking
outMsg.Write(steamAuthTicket.Data, 0, steamAuthTicket.Data.Length);
}
outMsg.Write(GameMain.Version.ToString());
outMsg.Write(GameMain.Config.Language);
outMsg.Write(GameSettings.CurrentConfig.Language.Value);
SendMsgInternal(DeliveryMethod.Reliable, outMsg);
break;
@@ -122,121 +124,26 @@ namespace Barotrauma.Networking
string serverName = inc.ReadString();
UInt32 cpCount = inc.ReadVariableUInt32();
ServerContentPackage corePackage = null;
List<ServerContentPackage> regularPackages = new List<ServerContentPackage>();
List<ServerContentPackage> missingPackages = new List<ServerContentPackage>();
for (int i = 0; i < cpCount; i++)
UInt32 packageCount = inc.ReadVariableUInt32();
List<ServerContentPackage> serverPackages = new List<ServerContentPackage>();
for (int i = 0; i < packageCount; i++)
{
string name = inc.ReadString();
string hash = inc.ReadString();
UInt32 hashByteCount = inc.ReadVariableUInt32();
byte[] hashBytes = inc.ReadBytes((int)hashByteCount);
UInt64 workshopId = inc.ReadUInt64();
UInt32 installTimeDiffSeconds = inc.ReadUInt32();
DateTime installTime = DateTime.UtcNow + TimeSpan.FromSeconds(installTimeDiffSeconds);
var pkg = new ServerContentPackage(name, hash, workshopId, installTime);
if (pkg.CorePackage != null)
{
corePackage = pkg;
}
else if (pkg.RegularPackage != null)
{
regularPackages.Add(pkg);
}
else
{
missingPackages.Add(pkg);
}
}
if (missingPackages.Count > 0)
{
var nonDownloadable = missingPackages.Where(p => p.WorkshopId == 0);
var mismatchedButDownloaded = missingPackages.Where(remote =>
{
return ContentPackage.AllPackages.Any(local =>
local.SteamWorkshopId != 0 && /* is a Workshop item */
remote.WorkshopId == local.SteamWorkshopId && /* ids match */
remote.InstallTime < local.InstallTime/* remote is older than local */);
});
if (mismatchedButDownloaded.Any())
{
string disconnectMsg;
if (mismatchedButDownloaded.Count() == 1)
{
disconnectMsg = $"DisconnectMessage.MismatchedWorkshopMod~[incompatiblecontentpackage]={GetPackageStr(mismatchedButDownloaded.First())}";
}
else
{
List<string> packageStrs = new List<string>();
mismatchedButDownloaded.ForEach(cp => packageStrs.Add(GetPackageStr(cp)));
disconnectMsg = $"DisconnectMessage.MismatchedWorkshopMods~[incompatiblecontentpackages]={string.Join(", ", packageStrs)}";
}
Close(disconnectMsg, disableReconnect: true);
OnDisconnectMessageReceived?.Invoke(DisconnectReason.MissingContentPackage + "/" + disconnectMsg);
}
else if (nonDownloadable.Any())
{
string disconnectMsg;
if (nonDownloadable.Count() == 1)
{
disconnectMsg = $"DisconnectMessage.MissingContentPackage~[missingcontentpackage]={GetPackageStr(nonDownloadable.First())}";
}
else
{
List<string> packageStrs = new List<string>();
nonDownloadable.ForEach(cp => packageStrs.Add(GetPackageStr(cp)));
disconnectMsg = $"DisconnectMessage.MissingContentPackages~[missingcontentpackages]={string.Join(", ", packageStrs)}";
}
Close(disconnectMsg, disableReconnect: true);
OnDisconnectMessageReceived?.Invoke(DisconnectReason.MissingContentPackage + "/" + disconnectMsg);
}
else
{
Close(disableReconnect: true);
string missingModNames = "\n";
int displayedModCount = 0;
foreach (ServerContentPackage missingPackage in missingPackages)
{
missingModNames += "\n- " + GetPackageStr(missingPackage);
displayedModCount++;
if (GUI.Font.MeasureString(missingModNames).Y > GameMain.GraphicsHeight * 0.5f)
{
missingModNames += "\n\n" + TextManager.GetWithVariable("workshopitemdownloadprompttruncated", "[number]", (missingPackages.Count - displayedModCount).ToString());
break;
}
}
missingModNames += "\n\n";
var msgBox = new GUIMessageBox(
TextManager.Get("WorkshopItemDownloadTitle"),
TextManager.GetWithVariable("WorkshopItemDownloadPrompt", "[items]", missingModNames),
new string[] { TextManager.Get("Yes"), TextManager.Get("No") });
msgBox.Buttons[0].OnClicked = (yesBtn, userdata) =>
{
GameMain.ServerListScreen.Select();
IEnumerable<ServerListScreen.PendingWorkshopDownload> downloads =
missingPackages.Select(p => new ServerListScreen.PendingWorkshopDownload(p.Hash, p.WorkshopId));
GameMain.ServerListScreen.DownloadWorkshopItems(downloads, serverName, ServerConnection.EndPointString);
return true;
};
msgBox.Buttons[0].OnClicked += msgBox.Close;
msgBox.Buttons[1].OnClicked = msgBox.Close;
}
return;
var pkg = new ServerContentPackage(name, Md5Hash.BytesAsHash(hashBytes), workshopId, installTime);
serverPackages.Add(pkg);
}
if (!contentPackageOrderReceived)
{
GameMain.Config.BackUpModOrder();
GameMain.Config.SwapPackages(corePackage.CorePackage, regularPackages.Select(p => p.RegularPackage).ToList());
contentPackageOrderReceived = true;
ServerContentPackages = serverPackages.ToImmutableArray();
SendMsgInternal(DeliveryMethod.Reliable, outMsg);
}
SendMsgInternal(DeliveryMethod.Reliable, outMsg);
break;
case ConnectionInitialization.Password:
if (initializationStep == ConnectionInitialization.SteamTicketAndVersion) { initializationStep = ConnectionInitialization.Password; }
@@ -36,7 +36,7 @@ namespace Barotrauma.Networking
netPeerConfiguration = new NetPeerConfiguration("barotrauma")
{
UseDualModeSockets = GameMain.Config.UseDualModeSockets
UseDualModeSockets = GameSettings.CurrentConfig.UseDualModeSockets
};
netPeerConfiguration.DisableMessageType(NetIncomingMessageType.DebugMessage | NetIncomingMessageType.WarningMessage | NetIncomingMessageType.Receipt
@@ -175,13 +175,13 @@ namespace Barotrauma.Networking
isActive = false;
netClient.Shutdown(msg ?? TextManager.Get("Disconnecting"));
netClient.Shutdown(msg ?? TextManager.Get("Disconnecting").Value);
netClient = null;
steamAuthTicket?.Cancel(); steamAuthTicket = null;
OnDisconnect?.Invoke(disableReconnect);
}
public override void Send(IWriteMessage msg, DeliveryMethod deliveryMethod)
public override void Send(IWriteMessage msg, DeliveryMethod deliveryMethod, bool compressPastThreshold = true)
{
if (!isActive) { return; }
@@ -208,7 +208,7 @@ namespace Barotrauma.Networking
NetOutgoingMessage lidgrenMsg = netClient.CreateMessage();
byte[] msgData = new byte[msg.LengthBytes];
msg.PrepareForSending(ref msgData, out bool isCompressed, out int length);
msg.PrepareForSending(ref msgData, compressPastThreshold, out bool isCompressed, out int length);
lidgrenMsg.Write((byte)(isCompressed ? PacketHeader.IsCompressed : PacketHeader.None));
lidgrenMsg.Write((UInt16)length);
lidgrenMsg.Write(msgData, 0, length);
@@ -242,7 +242,7 @@ namespace Barotrauma.Networking
incomingDataMessages.Clear();
}
public override void Send(IWriteMessage msg, DeliveryMethod deliveryMethod)
public override void Send(IWriteMessage msg, DeliveryMethod deliveryMethod, bool compressPastThreshold = true)
{
if (!isActive) { return; }
@@ -250,7 +250,7 @@ namespace Barotrauma.Networking
buf[0] = (byte)deliveryMethod;
byte[] bufAux = new byte[msg.LengthBytes];
msg.PrepareForSending(ref bufAux, out bool isCompressed, out int length);
msg.PrepareForSending(ref bufAux, compressPastThreshold, out bool isCompressed, out int length);
buf[1] = (byte)(isCompressed ? PacketHeader.IsCompressed : PacketHeader.None);
@@ -429,13 +429,13 @@ namespace Barotrauma.Networking
Steamworks.SteamUser.OnValidateAuthTicketResponse -= OnAuthChange;
}
public override void Send(IWriteMessage msg, DeliveryMethod deliveryMethod)
public override void Send(IWriteMessage msg, DeliveryMethod deliveryMethod, bool compressPastThreshold = true)
{
if (!isActive) { return; }
IWriteMessage msgToSend = new WriteOnlyMessage();
byte[] msgData = new byte[msg.LengthBytes];
msg.PrepareForSending(ref msgData, out bool isCompressed, out int length);
msg.PrepareForSending(ref msgData, compressPastThreshold, out bool isCompressed, out int length);
msgToSend.Write(selfSteamID);
msgToSend.Write(selfSteamID);
msgToSend.Write((byte)(isCompressed ? PacketHeader.IsCompressed : PacketHeader.None));
@@ -52,7 +52,7 @@ namespace Barotrauma.Networking
if (Character.Controlled != null || (!(GameMain.GameSession?.IsRunning ?? false))) { return; }
var respawnPrompt = new GUIMessageBox(
TextManager.Get("tutorial.tryagainheader"), TextManager.Get("respawnquestionprompt"),
new string[] { TextManager.Get("respawnquestionpromptrespawn"), TextManager.Get("respawnquestionpromptwait") })
new LocalizedString[] { TextManager.Get("respawnquestionpromptrespawn"), TextManager.Get("respawnquestionpromptwait") })
{
UserData = "respawnquestionprompt"
};
@@ -51,7 +51,7 @@ namespace Barotrauma.Networking
public bool? FriendlyFireEnabled;
public bool? AllowRespawn;
public YesNoMaybe? TraitorsEnabled;
public string GameMode;
public Identifier GameMode;
public PlayStyle? PlayStyle;
public bool Recent;
@@ -103,7 +103,7 @@ namespace Barotrauma.Networking
frame.ClearChildren();
var title = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), frame.RectTransform), ServerName, font: GUI.LargeFont)
var title = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), frame.RectTransform), ServerName, font: GUIStyle.LargeFont)
{
ToolTip = ServerName
};
@@ -143,7 +143,7 @@ namespace Barotrauma.Networking
var playStyleName = new GUITextBlock(new RectTransform(new Vector2(0.15f, 0.0f), playStyleBanner.RectTransform) { RelativeOffset = new Vector2(0.0f, 0.06f) },
TextManager.AddPunctuation(':', TextManager.Get("serverplaystyle"), TextManager.Get("servertag."+ playStyle)), textColor: Color.White,
font: GUI.SmallFont, textAlignment: Alignment.Center,
font: GUIStyle.SmallFont, textAlignment: Alignment.Center,
color: ServerListScreen.PlayStyleColors[(int)playStyle], style: "GUISlopedHeader");
playStyleName.RectTransform.NonScaledSize = (playStyleName.Font.MeasureString(playStyleName.Text) + new Vector2(20, 5) * GUI.Scale).ToPoint();
playStyleName.RectTransform.IsFixedSize = true;
@@ -188,7 +188,7 @@ namespace Barotrauma.Networking
new GUIFrame(new RectTransform(new Vector2(1.0f, 0.025f), content.RectTransform), style: null);
var serverMsg = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.3f), content.RectTransform)) { ScrollBarVisible = true };
var msgText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), serverMsg.Content.RectTransform), ServerMessage, font: GUI.SmallFont, wrap: true)
var msgText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), serverMsg.Content.RectTransform), ServerMessage, font: GUIStyle.SmallFont, wrap: true)
{
CanBeFocused = false
};
@@ -197,7 +197,7 @@ namespace Barotrauma.Networking
var gameMode = new GUITextBlock(new RectTransform(new Vector2(1.0f, elementHeight), content.RectTransform), TextManager.Get("GameMode"));
new GUITextBlock(new RectTransform(Vector2.One, gameMode.RectTransform),
TextManager.Get(string.IsNullOrEmpty(GameMode) ? "Unknown" : "GameMode." + GameMode, returnNull: true) ?? GameMode,
TextManager.Get(GameMode.IsEmpty ? "Unknown" : "GameMode." + GameMode).Fallback(GameMode.Value),
textAlignment: Alignment.Right);
GUITextBlock playStyleText = null;
@@ -218,11 +218,11 @@ namespace Barotrauma.Networking
subSelection.TextSize.X + subSelection.GetChild<GUITextBlock>().TextSize.X > subSelection.Rect.Width ||
modeSelection.TextSize.X + modeSelection.GetChild<GUITextBlock>().TextSize.X > modeSelection.Rect.Width)
{
gameMode.Font = subSelection.Font = modeSelection.Font = GUI.SmallFont;
gameMode.GetChild<GUITextBlock>().Font = subSelection.GetChild<GUITextBlock>().Font = modeSelection.GetChild<GUITextBlock>().Font = GUI.SmallFont;
gameMode.Font = subSelection.Font = modeSelection.Font = GUIStyle.SmallFont;
gameMode.GetChild<GUITextBlock>().Font = subSelection.GetChild<GUITextBlock>().Font = modeSelection.GetChild<GUITextBlock>().Font = GUIStyle.SmallFont;
if (playStyleText != null)
{
playStyleText.Font = playStyleText.GetChild<GUITextBlock>().Font = GUI.SmallFont;
playStyleText.Font = playStyleText.GetChild<GUITextBlock>().Font = GUIStyle.SmallFont;
}
}
@@ -268,7 +268,7 @@ namespace Barotrauma.Networking
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), content.RectTransform),
TextManager.Get("ServerListContentPackages"), textAlignment: Alignment.Center, font: GUI.SubHeadingFont);
TextManager.Get("ServerListContentPackages"), textAlignment: Alignment.Center, font: GUIStyle.SubHeadingFont);
var contentPackageList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.3f), frame.RectTransform)) { ScrollBarVisible = true };
if (ContentPackageNames.Count == 0)
@@ -289,7 +289,7 @@ namespace Barotrauma.Networking
};
if (i < ContentPackageHashes.Count)
{
if (ContentPackage.AllPackages.Any(cp => cp.MD5hash.Hash == ContentPackageHashes[i]))
if (ContentPackageManager.AllPackages.Any(contentPackage => contentPackage.Hash.StringRepresentation == ContentPackageHashes[i]))
{
packageText.Selected = true;
continue;
@@ -298,14 +298,14 @@ namespace Barotrauma.Networking
//workshop download link found
if (i < ContentPackageWorkshopIds.Count && ContentPackageWorkshopIds[i] != 0)
{
packageText.TextColor = GUI.Style.Yellow;
packageText.TextColor = GUIStyle.Yellow;
packageText.ToolTip = TextManager.GetWithVariable("ServerListIncompatibleContentPackageWorkshopAvailable", "[contentpackage]", ContentPackageNames[i]);
}
else //no package or workshop download link found, tough luck
{
packageText.TextColor = GUI.Style.Red;
packageText.TextColor = GUIStyle.Red;
packageText.ToolTip = TextManager.GetWithVariables("ServerListIncompatibleContentPackage",
new string[2] { "[contentpackage]", "[hash]" }, new string[2] { ContentPackageNames[i], ContentPackageHashes[i] });
("[contentpackage]", ContentPackageNames[i]), ("[hash]", ContentPackageHashes[i]));
}
}
}
@@ -361,7 +361,7 @@ namespace Barotrauma.Networking
info.RespondedToSteamQuery = null;
info.GameMode = element.GetAttributeString("GameMode", "");
info.GameMode = element.GetAttributeIdentifier("GameMode", Identifier.Empty);
info.GameVersion = element.GetAttributeString("GameVersion", "");
int maxPlayersElement = element.GetAttributeInt("MaxPlayers", 0);
@@ -515,7 +515,7 @@ namespace Barotrauma.Networking
element.SetAttributeValue("OwnerID", SteamManager.SteamIDUInt64ToString(OwnerID));
}
element.SetAttributeValue("GameMode", GameMode ?? "");
element.SetAttributeValue("GameMode", GameMode);
element.SetAttributeValue("GameVersion", GameVersion ?? "");
element.SetAttributeValue("MaxPlayers", MaxPlayers);
if (PlayStyle.HasValue) { element.SetAttributeValue("PlayStyle", PlayStyle.Value.ToString()); }
@@ -49,7 +49,7 @@ namespace Barotrauma.Networking
List<GUITickBox> tickBoxes = new List<GUITickBox>();
foreach (MessageType msgType in Enum.GetValues(typeof(MessageType)))
{
var tickBox = new GUITickBox(new RectTransform(new Point(tickBoxContainer.Rect.Width, 30), tickBoxContainer.RectTransform), TextManager.Get("ServerLog." + messageTypeName[msgType]), font: GUI.SmallFont)
var tickBox = new GUITickBox(new RectTransform(new Point(tickBoxContainer.Rect.Width, 30), tickBoxContainer.RectTransform), TextManager.Get("ServerLog." + messageTypeName[msgType]), font: GUIStyle.SmallFont)
{
Selected = true,
TextColor = messageColor[msgType],
@@ -84,8 +84,8 @@ namespace Barotrauma.Networking
isHorizontal: true, childAnchor: Anchor.CenterLeft);
new GUITextBlock(new RectTransform(new Vector2(0.2f, 1.0f), filterArea.RectTransform), TextManager.Get("ServerLog.Filter"),
font: GUI.SubHeadingFont);
GUITextBox searchBox = new GUITextBox(new RectTransform(new Vector2(0.8f, 1.0f), filterArea.RectTransform), font: GUI.SmallFont, createClearButton: true);
font: GUIStyle.SubHeadingFont);
GUITextBox searchBox = new GUITextBox(new RectTransform(new Vector2(0.8f, 1.0f), filterArea.RectTransform), font: GUIStyle.SmallFont, createClearButton: true);
searchBox.OnTextChanged += (textBox, text) =>
{
msgFilter = text;
@@ -146,7 +146,7 @@ namespace Barotrauma.Networking
List<GUITickBox> tickBoxes = new List<GUITickBox>();
foreach (MessageType msgType in Enum.GetValues(typeof(MessageType)))
{
var tickBox = new GUITickBox(new RectTransform(new Point(tickBoxContainer.Rect.Width, (int)(25 * GUI.Scale)), tickBoxContainer.RectTransform), TextManager.Get("ServerLog." + messageTypeName[msgType]), font: GUI.SmallFont)
var tickBox = new GUITickBox(new RectTransform(new Point(tickBoxContainer.Rect.Width, (int)(25 * GUI.Scale)), tickBoxContainer.RectTransform), TextManager.Get("ServerLog." + messageTypeName[msgType]), font: GUIStyle.SmallFont)
{
Selected = true,
TextColor = messageColor[msgType],
@@ -191,9 +191,10 @@ namespace Barotrauma.Networking
Anchor anchor = Anchor.TopLeft;
Pivot pivot = Pivot.TopLeft;
if (line.RichData != null)
RichString richString = line.Text as RichString;
if (richString != null && richString.RichTextData.HasValue)
{
foreach (var data in line.RichData)
foreach (var data in richString.RichTextData.Value)
{
if (!UInt64.TryParse(data.Metadata, out ulong id)) { return; }
Client client = GameMain.Client.ConnectedClients.Find(c => c.SteamID == id)
@@ -215,7 +216,7 @@ namespace Barotrauma.Networking
}
var textBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), (textContainer ?? listBox.Content).RectTransform, anchor, pivot),
line.RichData, line.SanitizedText, wrap: true, font: GUI.SmallFont)
line.Text, wrap: true, font: GUIStyle.SmallFont)
{
TextColor = messageColor[line.Type],
Visible = !msgTypeHidden[(int)line.Type],
@@ -235,9 +236,9 @@ namespace Barotrauma.Networking
textBlock.RectTransform.SetAsFirstChild();
}
if (line.RichData != null)
if (richString != null && richString.RichTextData.HasValue)
{
foreach (var data in line.RichData)
foreach (var data in richString.RichTextData.Value)
{
textBlock.ClickableAreas.Add(new GUITextBlock.ClickableArea()
{
@@ -77,18 +77,18 @@ namespace Barotrauma.Networking
}
}
}
private Dictionary<string, bool> tempMonsterEnabled;
private Dictionary<Identifier, bool> tempMonsterEnabled;
partial void InitProjSpecific()
{
var properties = TypeDescriptor.GetProperties(GetType()).Cast<PropertyDescriptor>();
SerializableProperties = new Dictionary<string, SerializableProperty>();
SerializableProperties = new Dictionary<Identifier, SerializableProperty>();
foreach (var property in properties)
{
SerializableProperty objProperty = new SerializableProperty(property);
SerializableProperties.Add(property.Name.ToLowerInvariant(), objProperty);
SerializableProperties.Add(property.Name.ToIdentifier(), objProperty);
}
}
@@ -168,7 +168,16 @@ namespace Barotrauma.Networking
}
}
public void ClientAdminWrite(NetFlags dataToSend, int? missionTypeOr = null, int? missionTypeAnd = null, float? levelDifficulty = null, bool? autoRestart = null, int traitorSetting = 0, int botCount = 0, int botSpawnMode = 0, bool? useRespawnShuttle = null)
public void ClientAdminWrite(
NetFlags dataToSend,
int? missionTypeOr = null,
int? missionTypeAnd = null,
float? levelDifficulty = null,
bool? autoRestart = null,
int traitorSetting = 0,
int botCount = 0,
int botSpawnMode = 0,
bool? useRespawnShuttle = null)
{
if (!GameMain.Client.HasPermission(Networking.ClientPermissions.ManageSettings)) return;
@@ -208,7 +217,7 @@ namespace Barotrauma.Networking
outMsg.Write(count);
foreach (KeyValuePair<UInt32, NetPropertyData> prop in changedProperties)
{
DebugConsole.NewMessage(prop.Value.Name, Color.Lime);
DebugConsole.NewMessage(prop.Value.Name.Value, Color.Lime);
outMsg.Write(prop.Key);
prop.Value.Write(outMsg, prop.Value.GUIComponentValue);
}
@@ -315,7 +324,7 @@ namespace Barotrauma.Networking
RelativeSpacing = 0.02f
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform), TextManager.Get("Settings"), font: GUI.LargeFont);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform), TextManager.Get("Settings"), font: GUIStyle.LargeFont);
var buttonArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.04f), paddedFrame.RectTransform), isHorizontal: true)
{
@@ -326,12 +335,9 @@ namespace Barotrauma.Networking
var tabContent = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.85f), paddedFrame.RectTransform), style: "InnerFrame");
//tabs
var tabValues = Enum.GetValues(typeof(SettingsTab)).Cast<SettingsTab>().ToArray();
string[] tabNames = new string[tabValues.Count()];
for (int i = 0; i < tabNames.Length; i++)
{
tabNames[i] = TextManager.Get("ServerSettings" + tabValues[i] + "Tab");
}
LocalizedString[] tabNames =
Enum.GetValues(typeof(SettingsTab)).Cast<SettingsTab>()
.Select(tv => TextManager.Get("ServerSettings" + tv + "Tab")).ToArray();
settingsTabs = new GUIFrame[tabNames.Length];
tabButtons = new GUIButton[tabNames.Length];
for (int i = 0; i < tabNames.Length; i++)
@@ -367,7 +373,7 @@ namespace Barotrauma.Networking
//***********************************************
// Sub Selection
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), serverTab.RectTransform), TextManager.Get("ServerSettingsSubSelection"), font: GUI.SubHeadingFont);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), serverTab.RectTransform), TextManager.Get("ServerSettingsSubSelection"), font: GUIStyle.SubHeadingFont);
var selectionFrame = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.02f), serverTab.RectTransform), isHorizontal: true)
{
Stretch = true,
@@ -377,7 +383,7 @@ namespace Barotrauma.Networking
GUIRadioButtonGroup selectionMode = new GUIRadioButtonGroup();
for (int i = 0; i < 3; i++)
{
var selectionTick = new GUITickBox(new RectTransform(new Vector2(0.3f, 1.0f), selectionFrame.RectTransform), TextManager.Get(((SelectionMode)i).ToString()), font: GUI.SmallFont, style: "GUIRadioButton");
var selectionTick = new GUITickBox(new RectTransform(new Vector2(0.3f, 1.0f), selectionFrame.RectTransform), TextManager.Get(((SelectionMode)i).ToString()), font: GUIStyle.SmallFont, style: "GUIRadioButton");
selectionMode.AddRadioButton(i, selectionTick);
}
selectionFrame.RectTransform.NonScaledSize = new Point(selectionFrame.Rect.Width, selectionFrame.Children.First().Rect.Height);
@@ -386,7 +392,7 @@ namespace Barotrauma.Networking
GetPropertyData(nameof(SubSelectionMode)).AssignGUIComponent(selectionMode);
// Mode Selection
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), serverTab.RectTransform), TextManager.Get("ServerSettingsModeSelection"), font: GUI.SubHeadingFont);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), serverTab.RectTransform), TextManager.Get("ServerSettingsModeSelection"), font: GUIStyle.SubHeadingFont);
selectionFrame = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.02f), serverTab.RectTransform), isHorizontal: true)
{
Stretch = true,
@@ -396,7 +402,7 @@ namespace Barotrauma.Networking
selectionMode = new GUIRadioButtonGroup();
for (int i = 0; i < 3; i++)
{
var selectionTick = new GUITickBox(new RectTransform(new Vector2(0.3f, 1.0f), selectionFrame.RectTransform), TextManager.Get(((SelectionMode)i).ToString()), font: GUI.SmallFont, style: "GUIRadioButton");
var selectionTick = new GUITickBox(new RectTransform(new Vector2(0.3f, 1.0f), selectionFrame.RectTransform), TextManager.Get(((SelectionMode)i).ToString()), font: GUIStyle.SmallFont, style: "GUIRadioButton");
selectionMode.AddRadioButton(i, selectionTick);
}
selectionFrame.RectTransform.NonScaledSize = new Point(selectionFrame.Rect.Width, selectionFrame.Children.First().Rect.Height);
@@ -413,7 +419,7 @@ namespace Barotrauma.Networking
//***********************************************
string autoRestartDelayLabel = TextManager.Get("ServerSettingsAutoRestartDelay") + " ";
LocalizedString autoRestartDelayLabel = TextManager.Get("ServerSettingsAutoRestartDelay") + " ";
var startIntervalText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), serverTab.RectTransform), autoRestartDelayLabel);
var startIntervalSlider = new GUIScrollBar(new RectTransform(new Vector2(1.0f, 0.05f), serverTab.RectTransform), barSize: 0.1f, style: "GUISlider")
{
@@ -437,7 +443,7 @@ namespace Barotrauma.Networking
GetPropertyData(nameof(StartWhenClientsReady)).AssignGUIComponent(startWhenClientsReady);
CreateLabeledSlider(serverTab, "ServerSettingsStartWhenClientsReadyRatio", out GUIScrollBar slider, out GUITextBlock sliderLabel);
string clientsReadyRequiredLabel = sliderLabel.Text;
LocalizedString clientsReadyRequiredLabel = sliderLabel.Text;
slider.Step = 0.2f;
slider.Range = new Vector2(0.5f, 1.0f);
slider.OnMoved = (GUIScrollBar scrollBar, float barScroll) =>
@@ -481,7 +487,7 @@ namespace Barotrauma.Networking
};
// Play Style Selection
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), roundsTab.RectTransform), TextManager.Get("ServerSettingsPlayStyle"), font: GUI.SubHeadingFont);
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), roundsTab.RectTransform), TextManager.Get("ServerSettingsPlayStyle"), font: GUIStyle.SubHeadingFont);
var playstyleList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.16f), roundsTab.RectTransform))
{
AutoHideScrollBar = true,
@@ -493,7 +499,7 @@ namespace Barotrauma.Networking
GUIRadioButtonGroup selectionPlayStyle = new GUIRadioButtonGroup();
foreach (PlayStyle playStyle in Enum.GetValues(typeof(PlayStyle)))
{
var selectionTick = new GUITickBox(new RectTransform(new Vector2(0.32f, 0.49f), playstyleList.Content.RectTransform), TextManager.Get("servertag." + playStyle), font: GUI.SmallFont, style: "GUIRadioButton")
var selectionTick = new GUITickBox(new RectTransform(new Vector2(0.32f, 0.49f), playstyleList.Content.RectTransform), TextManager.Get("servertag." + playStyle), font: GUIStyle.SmallFont, style: "GUIRadioButton")
{
ToolTip = TextManager.Get("servertagdescription." + playStyle)
};
@@ -510,7 +516,7 @@ namespace Barotrauma.Networking
CreateLabeledSlider(roundsTab, "ServerSettingsEndRoundVotesRequired", out slider, out sliderLabel);
string endRoundLabel = sliderLabel.Text;
LocalizedString endRoundLabel = sliderLabel.Text;
slider.Step = 0.2f;
slider.Range = new Vector2(0.5f, 1.0f);
GetPropertyData(nameof(EndVoteRequiredRatio)).AssignGUIComponent(slider);
@@ -526,7 +532,7 @@ namespace Barotrauma.Networking
GetPropertyData(nameof(AllowRespawn)).AssignGUIComponent(respawnBox);
CreateLabeledSlider(roundsTab, "ServerSettingsRespawnInterval", out slider, out sliderLabel);
string intervalLabel = sliderLabel.Text;
LocalizedString intervalLabel = sliderLabel.Text;
slider.Range = new Vector2(10.0f, 600.0f);
slider.StepValue = 10.0f;
GetPropertyData(nameof(RespawnInterval)).AssignGUIComponent(slider);
@@ -549,11 +555,11 @@ namespace Barotrauma.Networking
ToolTip = TextManager.Get("ServerSettingsMinRespawnToolTip")
};
string minRespawnLabel = TextManager.Get("ServerSettingsMinRespawn") + " ";
LocalizedString minRespawnLabel = TextManager.Get("ServerSettingsMinRespawn") + " ";
CreateLabeledSlider(minRespawnLayout, "", out slider, out sliderLabel);
sliderLabel.RectTransform.RelativeSize = Vector2.Zero;
slider.RectTransform.RelativeSize = new Vector2(1.0f, 0.5f);
slider.ToolTip = minRespawnText.RawToolTip;
slider.ToolTip = minRespawnText.ToolTip;
slider.UserData = minRespawnText;
slider.Step = 0.1f;
slider.Range = new Vector2(0.0f, 1.0f);
@@ -573,11 +579,11 @@ namespace Barotrauma.Networking
ToolTip = TextManager.Get("ServerSettingsRespawnDurationToolTip")
};
string respawnDurationLabel = TextManager.Get("ServerSettingsRespawnDuration") + " ";
LocalizedString respawnDurationLabel = TextManager.Get("ServerSettingsRespawnDuration") + " ";
CreateLabeledSlider(respawnDurationLayout, "", out slider, out sliderLabel);
sliderLabel.RectTransform.RelativeSize = Vector2.Zero;
slider.RectTransform.RelativeSize = new Vector2(1.0f, 0.5f);
slider.ToolTip = respawnDurationText.RawToolTip;
slider.ToolTip = respawnDurationText.ToolTip;
slider.UserData = respawnDurationText;
slider.Step = 0.1f;
slider.Range = new Vector2(60.0f, 660.0f);
@@ -620,7 +626,7 @@ namespace Barotrauma.Networking
LosMode[] losModes = (LosMode[])Enum.GetValues(typeof(LosMode));
for (int i = 0; i < losModes.Length; i++)
{
var losTick = new GUITickBox(new RectTransform(new Vector2(0.3f, 1.0f), losModeRadioButtonLayout.RectTransform), TextManager.Get($"LosMode{losModes[i]}"), font: GUI.SmallFont, style: "GUIRadioButton");
var losTick = new GUITickBox(new RectTransform(new Vector2(0.3f, 1.0f), losModeRadioButtonLayout.RectTransform), TextManager.Get($"LosMode{losModes[i]}"), font: GUIStyle.SmallFont, style: "GUIRadioButton");
losModeRadioButtonGroup.AddRadioButton(i, losTick);
}
GetPropertyData(nameof(LosMode)).AssignGUIComponent(losModeRadioButtonGroup);
@@ -663,13 +669,13 @@ namespace Barotrauma.Networking
};
InitMonstersEnabled();
List<string> monsterNames = MonsterEnabled.Keys.ToList();
tempMonsterEnabled = new Dictionary<string, bool>(MonsterEnabled);
foreach (string s in monsterNames)
List<Identifier> monsterNames = MonsterEnabled.Keys.ToList();
tempMonsterEnabled = new Dictionary<Identifier, bool>(MonsterEnabled);
foreach (Identifier s in monsterNames)
{
string translatedLabel = TextManager.Get($"Character.{s}", true);
LocalizedString translatedLabel = TextManager.Get($"Character.{s}").Fallback(s.Value);
var monsterEnabledBox = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.1f), monsterFrame.Content.RectTransform) { MinSize = new Point(0, 25) },
label: translatedLabel ?? s)
label: translatedLabel)
{
Selected = tempMonsterEnabled[s],
OnSelected = (GUITickBox tb) =>
@@ -722,10 +728,10 @@ namespace Barotrauma.Networking
RelativeSpacing = 0.05f
};
if (ip.InventoryIcon != null || ip.sprite != null)
if (ip.InventoryIcon != null || ip.Sprite != null)
{
GUIImage img = new GUIImage(new RectTransform(new Point(itemFrame.Rect.Height), itemFrame.RectTransform),
ip.InventoryIcon ?? ip.sprite, scaleToFit: true)
ip.InventoryIcon ?? ip.Sprite, scaleToFit: true)
{
CanBeFocused = false
};
@@ -733,7 +739,7 @@ namespace Barotrauma.Networking
}
new GUITextBlock(new RectTransform(new Vector2(0.75f, 1.0f), itemFrame.RectTransform),
ip.Name, font: GUI.SmallFont)
ip.Name, font: GUIStyle.SmallFont)
{
Wrap = true,
CanBeFocused = false
@@ -826,7 +832,7 @@ namespace Barotrauma.Networking
tickBoxContainer.RectTransform.MinSize = new Point(0, (int)(tickBoxContainer.Content.Children.First().Rect.Height * 2.0f + tickBoxContainer.Padding.Y + tickBoxContainer.Padding.W));
CreateLabeledSlider(antigriefingTab, "ServerSettingsKickVotesRequired", out slider, out sliderLabel);
string votesRequiredLabel = sliderLabel.Text + " ";
LocalizedString votesRequiredLabel = sliderLabel.Text + " ";
slider.Step = 0.2f;
slider.Range = new Vector2(0.5f, 1.0f);
slider.OnMoved = (GUIScrollBar scrollBar, float barScroll) =>
@@ -838,7 +844,7 @@ namespace Barotrauma.Networking
slider.OnMoved(slider, slider.BarScroll);
CreateLabeledSlider(antigriefingTab, "ServerSettingsAutobanTime", out slider, out sliderLabel);
string autobanLabel = sliderLabel.Text + " ";
LocalizedString autobanLabel = sliderLabel.Text + " ";
slider.Step = 0.01f;
slider.Range = new Vector2(0.0f, MaxAutoBanTime);
slider.OnMoved = (GUIScrollBar scrollBar, float barScroll) =>
@@ -946,7 +952,7 @@ namespace Barotrauma.Networking
slider = new GUIScrollBar(new RectTransform(new Vector2(0.5f, 1.0f), container.RectTransform), barSize: 0.1f, style: "GUISlider");
label = new GUITextBlock(new RectTransform(new Vector2(0.5f, 1.0f), container.RectTransform),
string.IsNullOrEmpty(labelTag) ? "" : TextManager.Get(labelTag), textAlignment: Alignment.CenterLeft, font: GUI.SmallFont);
string.IsNullOrEmpty(labelTag) ? "" : TextManager.Get(labelTag), textAlignment: Alignment.CenterLeft, font: GUIStyle.SmallFont);
container.RectTransform.MinSize = new Point(0, slider.RectTransform.MinSize.Y);
container.RectTransform.MaxSize = new Point(int.MaxValue, slider.RectTransform.MaxSize.Y);
@@ -965,7 +971,7 @@ namespace Barotrauma.Networking
};
var label = new GUITextBlock(new RectTransform(new Vector2(0.7f, 1.0f), container.RectTransform),
TextManager.Get(labelTag), textAlignment: Alignment.CenterLeft, font: GUI.SmallFont)
TextManager.Get(labelTag), textAlignment: Alignment.CenterLeft, font: GUIStyle.SmallFont)
{
AutoScaleHorizontal = true
};
File diff suppressed because it is too large Load Diff
@@ -3,6 +3,7 @@ using Concentus.Structs;
using Microsoft.Xna.Framework;
using OpenAL;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
@@ -18,6 +19,9 @@ namespace Barotrauma.Networking
private set;
}
public static IReadOnlyList<string> CaptureDeviceNames =>
Alc.GetStringList(IntPtr.Zero, OpenAL.Alc.CaptureDeviceSpecifier);
private IntPtr captureDevice;
private Thread captureThread;
@@ -40,7 +44,7 @@ namespace Barotrauma.Networking
public float Gain
{
get { return GameMain.Config?.MicrophoneVolume ?? 1.0f; }
get { return GameSettings.CurrentConfig.Audio.MicrophoneVolume; }
}
public DateTime LastEnqueueAudio;
@@ -106,16 +110,18 @@ namespace Barotrauma.Networking
string errorCode = Alc.GetError(IntPtr.Zero).ToString();
if (!GUIMessageBox.MessageBoxes.Any(mb => mb.UserData as string == "capturedevicenotfound"))
{
GUI.SettingsMenuOpen = false;
//GUI.SettingsMenuOpen = false;
new GUIMessageBox(TextManager.Get("Error"),
(TextManager.Get("VoipCaptureDeviceNotFound", returnNull: true) ?? "Could not start voice capture, suitable capture device not found.") + " (" + errorCode + ")")
(TextManager.Get("VoipCaptureDeviceNotFound").Fallback("Could not start voice capture, suitable capture device not found.")) + " (" + errorCode + ")")
{
UserData = "capturedevicenotfound"
};
}
GameAnalyticsManager.AddErrorEventOnce("Alc.CaptureDeviceOpenFailed", GameAnalyticsManager.ErrorSeverity.Error,
"Alc.CaptureDeviceOpen(" + deviceName + ") failed. Error code: " + errorCode);
GameMain.Config.VoiceSetting = GameSettings.VoiceMode.Disabled;
var config = GameSettings.CurrentConfig;
config.Audio.VoiceSetting = VoiceMode.Disabled;
GameSettings.SetCurrentConfig(config);
Instance?.Dispose();
Instance = null;
return;
@@ -157,13 +163,15 @@ namespace Barotrauma.Networking
public static void ChangeCaptureDevice(string deviceName)
{
GameMain.Config.VoiceCaptureDevice = deviceName;
var config = GameSettings.CurrentConfig;
config.Audio.VoiceCaptureDevice = deviceName;
GameSettings.SetCurrentConfig(config);
if (Instance != null)
{
UInt16 storedBufferID = Instance.LatestBufferID;
Instance.Dispose();
Create(GameMain.Config.VoiceCaptureDevice, storedBufferID);
Create(GameSettings.CurrentConfig.Audio.VoiceCaptureDevice, storedBufferID);
}
}
@@ -222,9 +230,9 @@ namespace Barotrauma.Networking
LastAmplitude = maxAmplitude;
bool allowEnqueue = overrideSound != null;
if (GameMain.WindowActive)
if (GameMain.WindowActive && SettingsMenu.Instance is null)
{
ForceLocal = captureTimer > 0 ? ForceLocal : GameMain.Config.UseLocalVoiceByDefault;
ForceLocal = captureTimer > 0 ? ForceLocal : GameSettings.CurrentConfig.Audio.UseLocalVoiceByDefault;
bool pttDown = false;
if ((PlayerInput.KeyDown(InputType.Voice) || PlayerInput.KeyDown(InputType.LocalVoice)) &&
GUI.KeyboardDispatcher.Subscriber == null)
@@ -239,14 +247,14 @@ namespace Barotrauma.Networking
ForceLocal = false;
}
}
if (GameMain.Config.VoiceSetting == GameSettings.VoiceMode.Activity)
if (GameSettings.CurrentConfig.Audio.VoiceSetting == VoiceMode.Activity)
{
if (dB > GameMain.Config.NoiseGateThreshold)
if (dB > GameSettings.CurrentConfig.Audio.NoiseGateThreshold)
{
allowEnqueue = true;
}
}
else if (GameMain.Config.VoiceSetting == GameSettings.VoiceMode.PushToTalk)
else if (GameSettings.CurrentConfig.Audio.VoiceSetting == VoiceMode.PushToTalk)
{
if (pttDown)
{
@@ -277,7 +285,7 @@ namespace Barotrauma.Networking
captureTimer -= (VoipConfig.BUFFER_SIZE * 1000) / VoipConfig.FREQUENCY;
if (allowEnqueue)
{
captureTimer = GameMain.Config.VoiceChatCutoffPrevention;
captureTimer = GameSettings.CurrentConfig.Audio.VoiceChatCutoffPrevention;
}
prevCaptured = true;
}
@@ -378,6 +386,7 @@ namespace Barotrauma.Networking
capturing = false;
captureThread?.Join();
captureThread = null;
if (captureDevice != IntPtr.Zero) { Alc.CaptureCloseDevice(captureDevice); }
}
}
}
@@ -43,7 +43,7 @@ namespace Barotrauma.Networking
public void SendToServer()
{
if (GameMain.Config.VoiceSetting == GameSettings.VoiceMode.Disabled)
if (GameSettings.CurrentConfig.Audio.VoiceSetting == VoiceMode.Disabled)
{
if (VoipCapture.Instance != null)
{
@@ -54,8 +54,8 @@ namespace Barotrauma.Networking
}
else
{
if (VoipCapture.Instance == null) VoipCapture.Create(GameMain.Config.VoiceCaptureDevice, storedBufferID);
if (VoipCapture.Instance == null || VoipCapture.Instance.EnqueuedTotalLength <= 0) return;
if (VoipCapture.Instance == null) { VoipCapture.Create(GameSettings.CurrentConfig.Audio.VoiceCaptureDevice, storedBufferID); }
if (VoipCapture.Instance == null || VoipCapture.Instance.EnqueuedTotalLength <= 0) { return; }
}
if (DateTime.Now >= lastSendTime + VoipConfig.SEND_INTERVAL)
@@ -80,7 +80,7 @@ namespace Barotrauma.Networking
if (queue == null)
{
#if DEBUG
DebugConsole.NewMessage("Couldn't find VoipQueue with id " + queueId.ToString() + "!", GUI.Style.Red);
DebugConsole.NewMessage("Couldn't find VoipQueue with id " + queueId.ToString() + "!", GUIStyle.Red);
#endif
return;
}
@@ -102,7 +102,7 @@ namespace Barotrauma.Networking
var messageType = !client.VoipQueue.ForceLocal && ChatMessage.CanUseRadio(client.Character, out radio) ? ChatMessageType.Radio : ChatMessageType.Default;
client.Character.ShowSpeechBubble(1.25f, ChatMessage.MessageColor[(int)messageType]);
client.VoipSound.UseRadioFilter = messageType == ChatMessageType.Radio && !GameMain.Config.DisableVoiceChatFilters;
client.VoipSound.UseRadioFilter = messageType == ChatMessageType.Radio && !GameSettings.CurrentConfig.Audio.DisableVoiceChatFilters;
if (messageType == ChatMessageType.Radio)
{
client.VoipSound.SetRange(radio.Range * 0.8f, radio.Range);
@@ -111,7 +111,7 @@ namespace Barotrauma.Networking
{
client.VoipSound.SetRange(ChatMessage.SpeakRange * 0.4f, ChatMessage.SpeakRange);
}
if (messageType != ChatMessageType.Radio && Character.Controlled != null && !GameMain.Config.DisableVoiceChatFilters)
if (messageType != ChatMessageType.Radio && Character.Controlled != null && !GameSettings.CurrentConfig.Audio.DisableVoiceChatFilters)
{
client.VoipSound.UseMuffleFilter = SoundPlayer.ShouldMuffleSound(Character.Controlled, client.Character.WorldPosition, ChatMessage.SpeakRange, client.Character.CurrentHull);
}
@@ -144,7 +144,7 @@ namespace Barotrauma.Networking
{
if (voiceIconSheetRects == null)
{
var soundIconStyle = GUI.Style.GetComponentStyle("GUISoundIcon");
var soundIconStyle = GUIStyle.GetComponentStyle("GUISoundIcon");
Rectangle sourceRect = soundIconStyle.Sprites.First().Value.First().Sprite.SourceRect;
var indexPieces = soundIconStyle.Element.Attribute("sheetindices").Value.Split(';');
voiceIconSheetRects = new Rectangle[indexPieces.Length];
@@ -122,7 +122,7 @@ namespace Barotrauma
if (sub.EqualityCheckVal == 0)
{
//sub doesn't exist client-side, use hash to let the server know which one we voted for
msg.Write(sub.MD5Hash.Hash);
msg.Write(sub.MD5Hash.StringRepresentation);
}
break;
case VoteType.Mode:
@@ -302,7 +302,7 @@ namespace Barotrauma
}
else if (GameMain.Client.ConnectedClients.Count > 1)
{
GameMain.NetworkMember.AddChatMessage(VotingInterface.GetSubmarineVoteResultMessage(subInfo, voteType, yesClientCount.ToString(), noClientCount.ToString(), passed), ChatMessageType.Server);
GameMain.NetworkMember.AddChatMessage(VotingInterface.GetSubmarineVoteResultMessage(subInfo, voteType, yesClientCount.ToString(), noClientCount.ToString(), passed).Value, ChatMessageType.Server);
}
if (passed)