(f0d812055) v0.9.9.0

This commit is contained in:
Joonas Rikkonen
2020-04-23 19:19:37 +03:00
parent b647059b93
commit ac37a3b0e4
391 changed files with 15054 additions and 5420 deletions
@@ -17,10 +17,12 @@ namespace Barotrauma.Networking
{
UInt16 ID = msg.ReadUInt16();
ChatMessageType type = (ChatMessageType)msg.ReadByte();
PlayerConnectionChangeType changeType = PlayerConnectionChangeType.None;
string txt = "";
if (type != ChatMessageType.Order)
{
changeType = (PlayerConnectionChangeType)msg.ReadByte();
txt = msg.ReadString();
}
@@ -114,7 +116,7 @@ namespace Barotrauma.Networking
GameMain.Client.ServerSettings.ServerLog?.WriteLine(txt, messageType);
break;
default:
GameMain.Client.AddChatMessage(txt, type, senderName, senderCharacter);
GameMain.Client.AddChatMessage(txt, type, senderName, senderCharacter, changeType);
break;
}
LastID = ID;
@@ -14,8 +14,10 @@ namespace Barotrauma.Networking
public UInt64 SteamID;
public byte ID;
public UInt16 CharacterID;
public float Karma;
public bool Muted;
public bool InGame;
public bool HasPermissions;
public bool AllowKicking;
}
@@ -44,6 +46,8 @@ namespace Barotrauma.Networking
public bool AllowKicking;
public float Karma;
public void UpdateSoundPosition()
{
if (VoipSound == null) { return; }
@@ -72,7 +76,8 @@ namespace Barotrauma.Networking
else
{
VoipSound.SetPosition(null);
}
VoipSound.Gain = 1.0f;
}
}
partial void InitProjSpecific()
@@ -28,6 +28,8 @@ namespace Barotrauma.Networking
get { return name; }
}
public string PendingName = string.Empty;
public void SetName(string value)
{
value = value.Replace(":", "").Replace(";", "");
@@ -78,7 +80,7 @@ namespace Barotrauma.Networking
private List<Client> otherClients;
private readonly List<Submarine> serverSubmarines = new List<Submarine>();
private readonly List<SubmarineInfo> serverSubmarines = new List<SubmarineInfo>();
private string serverIP, serverName;
@@ -112,6 +114,7 @@ namespace Barotrauma.Networking
public bool SpawnAsTraitor;
public string TraitorFirstObjective;
public TraitorMissionPrefab TraitorMission = null;
public byte ID
{
@@ -482,19 +485,24 @@ namespace Barotrauma.Networking
if (requiresPw && !canStart && !connectCancelled)
{
GUI.ClearCursorWait();
reconnectBox?.Close(); reconnectBox = null;
string pwMsg = TextManager.Get("PasswordRequired");
var msgBox = new GUIMessageBox(pwMsg, "", new string[] { TextManager.Get("OK"), TextManager.Get("Cancel") },
relativeSize: new Vector2(0.25f, 0.1f), minSize: new Point(400, 170));
var passwordHolder = new GUILayoutGroup(new RectTransform(Vector2.One, msgBox.Content.RectTransform), childAnchor: Anchor.TopCenter);
var passwordBox = new GUITextBox(new RectTransform(new Vector2(0.8f, 1f) , passwordHolder.RectTransform) { MinSize = new Point(0, 20) })
relativeSize: new Vector2(0.25f, 0.1f), minSize: new Point(400, (int)(170 * Math.Max(1.0f, GUI.Scale))));
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) })
{
UserData = "password",
Censor = true
};
msgBox.Content.Recalculate();
msgBox.Content.RectTransform.MinSize = new Point(0, msgBox.Content.RectTransform.Children.Sum(c => c.Rect.Height));
msgBox.Content.Parent.RectTransform.MinSize = new Point(0, (int)(msgBox.Content.RectTransform.MinSize.Y / msgBox.Content.RectTransform.RelativeSize.Y));
var okButton = msgBox.Buttons[0];
var cancelButton = msgBox.Buttons[1];
@@ -509,6 +517,7 @@ namespace Barotrauma.Networking
{
requiresPw = false;
connectCancelled = true;
GameMain.ServerListScreen.Select();
return true;
};
@@ -540,6 +549,7 @@ namespace Barotrauma.Networking
foreach (Client c in ConnectedClients)
{
if (c.Character != null && c.Character.Removed) { c.Character = null; }
c.UpdateSoundPosition();
}
@@ -664,6 +674,7 @@ namespace Barotrauma.Networking
if (header != ServerPacketHeader.STARTGAMEFINALIZE &&
header != ServerPacketHeader.ENDGAME &&
header != ServerPacketHeader.PING_REQUEST &&
roundInitStatus == RoundInitStatus.WaitingForStartGameFinalize)
{
//rewind the header byte we just read
@@ -674,6 +685,31 @@ namespace Barotrauma.Networking
switch (header)
{
case ServerPacketHeader.PING_REQUEST:
IWriteMessage response = new WriteOnlyMessage();
response.Write((byte)ClientPacketHeader.PING_RESPONSE);
byte requestLen = inc.ReadByte();
response.Write(requestLen);
for (int i=0;i<requestLen;i++)
{
byte b = inc.ReadByte();
response.Write(b);
}
clientPeer.Send(response, DeliveryMethod.Unreliable);
break;
case ServerPacketHeader.CLIENT_PINGS:
byte clientCount = inc.ReadByte();
for (int i=0;i<clientCount;i++)
{
byte clientId = inc.ReadByte();
UInt16 clientPing = inc.ReadUInt16();
Client client = ConnectedClients.Find(c => c.ID == clientId);
if (client != null)
{
client.Ping = clientPing;
}
}
break;
case ServerPacketHeader.UPDATE_LOBBY:
ReadLobbyUpdate(inc);
break;
@@ -837,7 +873,7 @@ namespace Barotrauma.Networking
if (Level.Loaded.EqualityCheckVal != levelEqualityCheckVal)
{
string errorMsg = "Level equality check failed. The level generated at your end doesn't match the level generated by the server (seed: " + Level.Loaded.Seed +
", sub: " + Submarine.MainSub.Name + " (" + Submarine.MainSub.MD5Hash.ShortHash + ")" +
", sub: " + Submarine.MainSub.Info.Name + " (" + Submarine.MainSub.Info.MD5Hash.ShortHash + ")" +
", mirrored: " + Level.Loaded.Mirrored + ").";
GameAnalyticsManager.AddErrorEventOnce("GameClient.StartGame:LevelsDontMatch" + Level.Loaded.Seed, GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
throw new Exception(errorMsg);
@@ -1051,11 +1087,13 @@ namespace Barotrauma.Networking
var missionPrefab = TraitorMissionPrefab.List.Find(t => t.Identifier == missionIdentifier);
Sprite icon = missionPrefab?.Icon;
switch(messageType) {
switch(messageType)
{
case TraitorMessageType.Objective:
var isTraitor = !string.IsNullOrEmpty(message);
SpawnAsTraitor = isTraitor;
TraitorFirstObjective = message;
TraitorMission = missionPrefab;
if (Character != null)
{
Character.IsTraitor = isTraitor;
@@ -1326,7 +1364,6 @@ namespace Barotrauma.Networking
mirrorLevel: campaign.Map.CurrentLocation != campaign.Map.SelectedConnection.Locations[0]);
});*/
GameMain.GameSession.StartRound(campaign.Map.SelectedConnection.Level,
reloadSub: true,
mirrorLevel: campaign.Map.CurrentLocation != campaign.Map.SelectedConnection.Locations[0]);
}
@@ -1406,9 +1443,9 @@ namespace Barotrauma.Networking
}
}
if (GameMain.GameSession.Submarine.IsFileCorrupted)
if (GameMain.GameSession.Submarine.Info.IsFileCorrupted)
{
DebugConsole.ThrowError($"Failed to start a round. Could not load the submarine \"{GameMain.GameSession.Submarine.Name}\".");
DebugConsole.ThrowError($"Failed to start a round. Could not load the submarine \"{GameMain.GameSession.Submarine.Info.Name}\".");
yield return CoroutineStatus.Failure;
}
@@ -1498,8 +1535,8 @@ namespace Barotrauma.Networking
bool requiredContentPackagesInstalled = inc.ReadBoolean();
var matchingSub =
Submarine.SavedSubmarines.FirstOrDefault(s => s.Name == subName && s.MD5Hash.Hash == subHash) ??
new Submarine(Path.Combine(Submarine.SavePath, subName) + ".sub", subHash, false);
SubmarineInfo.SavedSubmarines.FirstOrDefault(s => s.Name == subName && s.MD5Hash.Hash == subHash) ??
new SubmarineInfo(Path.Combine(SubmarineInfo.SavePath, subName) + ".sub", subHash, tryLoad: false);
matchingSub.RequiredContentPackagesInstalled = requiredContentPackagesInstalled;
serverSubmarines.Add(matchingSub);
@@ -1533,9 +1570,11 @@ namespace Barotrauma.Networking
string name = inc.ReadString();
string preferredJob = inc.ReadString();
UInt16 characterID = inc.ReadUInt16();
float karma = inc.ReadSingle();
bool muted = inc.ReadBoolean();
bool inGame = inc.ReadBoolean();
bool allowKicking = inc.ReadBoolean();
bool hasPermissions = inc.ReadBoolean();
bool allowKicking = inc.ReadBoolean() || IsServerOwner;
inc.ReadPadBits();
tempClients.Add(new TempClient
@@ -1546,8 +1585,10 @@ namespace Barotrauma.Networking
Name = name,
PreferredJob = preferredJob,
CharacterID = characterID,
Karma = karma,
Muted = muted,
InGame = inGame,
HasPermissions = hasPermissions,
AllowKicking = allowKicking
});
}
@@ -1575,7 +1616,9 @@ namespace Barotrauma.Networking
existingClient.NameID = tc.NameID;
existingClient.PreferredJob = tc.PreferredJob;
existingClient.Character = null;
existingClient.Karma = tc.Karma;
existingClient.Muted = tc.Muted;
existingClient.HasPermissions = tc.HasPermissions;
existingClient.InGame = tc.InGame;
existingClient.AllowKicking = tc.AllowKicking;
GameMain.NetLobbyScreen.SetPlayerNameAndJobPreference(existingClient);
@@ -2028,15 +2071,15 @@ namespace Barotrauma.Networking
{
case FileTransferType.Submarine:
new GUIMessageBox(TextManager.Get("ServerDownloadFinished"), TextManager.GetWithVariable("FileDownloadedNotification", "[filename]", transfer.FileName));
var newSub = new Submarine(transfer.FilePath);
var newSub = new SubmarineInfo(transfer.FilePath);
if (newSub.IsFileCorrupted) { return; }
var existingSubs = Submarine.SavedSubmarines.Where(s => s.Name == newSub.Name && s.MD5Hash.Hash == newSub.MD5Hash.Hash).ToList();
foreach (Submarine existingSub in existingSubs)
var existingSubs = SubmarineInfo.SavedSubmarines.Where(s => s.Name == newSub.Name && s.MD5Hash.Hash == newSub.MD5Hash.Hash).ToList();
foreach (SubmarineInfo existingSub in existingSubs)
{
existingSub.Dispose();
}
Submarine.AddToSavedSubs(newSub);
SubmarineInfo.AddToSavedSubs(newSub);
for (int i = 0; i < 2; i++)
{
@@ -2045,8 +2088,8 @@ namespace Barotrauma.Networking
GameMain.NetLobbyScreen.SubList.Content.Children;
var subElement = subListChildren.FirstOrDefault(c =>
((Submarine)c.UserData).Name == newSub.Name &&
((Submarine)c.UserData).MD5Hash.Hash == newSub.MD5Hash.Hash);
((SubmarineInfo)c.UserData).Name == newSub.Name &&
((SubmarineInfo)c.UserData).MD5Hash.Hash == newSub.MD5Hash.Hash);
if (subElement == null) continue;
subElement.GetChild<GUITextBlock>().TextColor = new Color(subElement.GetChild<GUITextBlock>().TextColor, 1.0f);
@@ -2074,17 +2117,17 @@ namespace Barotrauma.Networking
if (campaign == null) { return; }
GameMain.GameSession.SavePath = transfer.FilePath;
if (GameMain.GameSession.Submarine == null)
if (GameMain.GameSession.SubmarineInfo == null)
{
var gameSessionDoc = SaveUtil.LoadGameSessionDoc(GameMain.GameSession.SavePath);
string subPath = Path.Combine(SaveUtil.TempPath, gameSessionDoc.Root.GetAttributeString("submarine", "")) + ".sub";
GameMain.GameSession.Submarine = new Submarine(subPath, "");
GameMain.GameSession.SubmarineInfo = new SubmarineInfo(subPath, "");
}
SaveUtil.LoadGame(GameMain.GameSession.SavePath, GameMain.GameSession);
GameMain.GameSession?.Submarine?.CheckSubsLeftBehind();
if (GameMain.GameSession?.Submarine?.Name != null)
GameMain.GameSession?.SubmarineInfo?.CheckSubsLeftBehind();
if (GameMain.GameSession?.SubmarineInfo?.Name != null)
{
GameMain.NetLobbyScreen.TryDisplayCampaignSubmarine(GameMain.GameSession.Submarine);
GameMain.NetLobbyScreen.TryDisplayCampaignSubmarine(GameMain.GameSession.SubmarineInfo);
}
campaign.LastSaveID = campaign.PendingSaveID;
@@ -2119,8 +2162,7 @@ namespace Barotrauma.Networking
{
if (!permissions.HasFlag(ClientPermissions.ConsoleCommands)) { return false; }
commandName = commandName.ToLowerInvariant();
if (permittedConsoleCommands.Any(c => c.ToLowerInvariant() == commandName)) { return true; }
if (permittedConsoleCommands.Any(c => c.Equals(commandName, StringComparison.OrdinalIgnoreCase))) { return true; }
//check aliases
foreach (DebugConsole.Command command in DebugConsole.Commands)
@@ -2371,7 +2413,7 @@ namespace Barotrauma.Networking
clientPeer.Send(msg, DeliveryMethod.Reliable);
}
public void SetupNewCampaign(Submarine sub, string saveName, string mapSeed)
public void SetupNewCampaign(SubmarineInfo sub, string saveName, string mapSeed)
{
GameMain.NetLobbyScreen.CampaignSetupFrame.Visible = false;
@@ -2537,6 +2579,11 @@ namespace Barotrauma.Networking
inGameHUD.AddToGUIUpdateList();
GameMain.NetLobbyScreen.FileTransferFrame?.AddToGUIUpdateList();
}
serverSettings.AddToGUIUpdateList();
if (serverSettings.ServerLog.LogFrame != null) serverSettings.ServerLog.LogFrame.AddToGUIUpdateList();
GameMain.NetLobbyScreen?.PlayerFrame?.AddToGUIUpdateList();
}
public void UpdateHUD(float deltaTime)
@@ -2580,7 +2627,7 @@ namespace Barotrauma.Networking
if (GUI.KeyboardDispatcher.Subscriber == null)
{
bool chatKeyHit = PlayerInput.KeyHit(InputType.Chat);
bool radioKeyHit = PlayerInput.KeyHit(InputType.RadioChat) && (Character.Controlled == null || Character.Controlled.SpeechImpediment < 0);
bool radioKeyHit = PlayerInput.KeyHit(InputType.RadioChat) && (Character.Controlled == null || Character.Controlled.SpeechImpediment < 100);
if (chatKeyHit || radioKeyHit)
{
@@ -2626,8 +2673,6 @@ namespace Barotrauma.Networking
}
}
}
serverSettings.AddToGUIUpdateList();
if (serverSettings.ServerLog.LogFrame != null) serverSettings.ServerLog.LogFrame.AddToGUIUpdateList();
}
public virtual void Draw(Microsoft.Xna.Framework.Graphics.SpriteBatch spriteBatch)
@@ -2740,73 +2785,106 @@ namespace Barotrauma.Networking
}*/
}
public virtual bool SelectCrewCharacter(Character character, GUIComponent characterFrame)
public virtual bool SelectCrewCharacter(Character character, GUIComponent frame)
{
if (character == null) { return false; }
if (character == null) return false;
if (character != myCharacter)
{
var client = GameMain.NetworkMember.ConnectedClients.Find(c => c.Character == character);
if (client == null) { return false; }
if (client == null) return false;
var content = new GUIFrame(new RectTransform(new Vector2(0.9f, 1.0f - characterFrame.RectTransform.RelativeSize.Y), characterFrame.RectTransform, Anchor.BottomCenter, Pivot.TopCenter),
style: null);
var mute = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.5f), content.RectTransform, Anchor.TopCenter),
TextManager.Get("Mute"))
{
Selected = client.MutedLocally,
OnSelected = (tickBox) => { client.MutedLocally = tickBox.Selected; return true; }
};
var buttonContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.5f), content.RectTransform, Anchor.BottomCenter), isHorizontal: true)
{
RelativeSpacing = 0.05f,
ChildAnchor = Anchor.CenterLeft,
Stretch = true
};
if (HasPermission(ClientPermissions.Ban))
{
var banButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.9f), buttonContainer.RectTransform),
TextManager.Get("Ban"), style: "GUIButtonSmall")
{
UserData = client,
OnClicked = (btn, userdata) => { GameMain.NetLobbyScreen.BanPlayer(client); return false; }
};
}
if (HasPermission(ClientPermissions.Kick))
{
var kickButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.9f), buttonContainer.RectTransform),
TextManager.Get("Kick"), style: "GUIButtonSmall")
{
UserData = client,
OnClicked = (btn, userdata) => { GameMain.NetLobbyScreen.KickPlayer(client); return false; }
};
}
else if (serverSettings.Voting.AllowVoteKick)
{
var kickVoteButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.9f), buttonContainer.RectTransform),
TextManager.Get("VoteToKick"), style: "GUIButtonSmall")
{
UserData = client,
OnClicked = (btn, userdata) => { VoteForKick(client); btn.Enabled = false; return true; }
};
if (GameMain.NetworkMember.ConnectedClients != null)
{
kickVoteButton.Enabled = !client.HasKickVoteFromID(myID);
}
}
CreateSelectionRelatedButtons(client, frame);
}
return true;
}
public virtual bool SelectCrewClient(Client client, GUIComponent frame)
{
if (client == null || client.ID == ID) return false;
CreateSelectionRelatedButtons(client, frame);
return true;
}
private void CreateSelectionRelatedButtons(Client client, GUIComponent frame)
{
var content = new GUIFrame(new RectTransform(new Vector2(1f, 1.0f - frame.RectTransform.RelativeSize.Y), frame.RectTransform, Anchor.BottomCenter, Pivot.TopCenter),
style: null);
var mute = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.5f), content.RectTransform, Anchor.TopCenter),
TextManager.Get("Mute"))
{
Selected = client.MutedLocally,
OnSelected = (tickBox) => { client.MutedLocally = tickBox.Selected; return true; }
};
var buttonContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.35f), content.RectTransform, Anchor.BottomCenter), isHorizontal: true, childAnchor: Anchor.BottomLeft)
{
RelativeSpacing = 0.05f,
Stretch = true
};
if (!GameMain.Client.GameStarted || (GameMain.Client.Character == null || GameMain.Client.Character.IsDead) && (client.Character == null || client.Character.IsDead))
{
var messageButton = new GUIButton(new RectTransform(new Vector2(1f, 0.2f), content.RectTransform, Anchor.BottomCenter) { RelativeOffset = new Vector2(0f, buttonContainer.RectTransform.RelativeSize.Y) },
TextManager.Get("message"), style: "GUIButtonSmall")
{
UserData = client,
OnClicked = (btn, userdata) =>
{
chatBox.InputBox.Text = $"{client.Name}; ";
CoroutineManager.StartCoroutine(selectCoroutine());
return false;
}
};
}
// Need a delayed selection due to the inputbox being deselected when a left click occurs outside of it
IEnumerable<object> selectCoroutine()
{
yield return new WaitForSeconds(0.01f, true);
chatBox.InputBox.Select(chatBox.InputBox.Text.Length);
}
if (HasPermission(ClientPermissions.Ban) && client.AllowKicking)
{
var banButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.9f), buttonContainer.RectTransform),
TextManager.Get("Ban"), style: "GUIButtonSmall")
{
UserData = client,
OnClicked = (btn, userdata) => { GameMain.NetLobbyScreen.BanPlayer(client); return false; }
};
}
if (HasPermission(ClientPermissions.Kick) && client.AllowKicking)
{
var kickButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.9f), buttonContainer.RectTransform),
TextManager.Get("Kick"), style: "GUIButtonSmall")
{
UserData = client,
OnClicked = (btn, userdata) => { GameMain.NetLobbyScreen.KickPlayer(client); return false; }
};
}
else if (serverSettings.Voting.AllowVoteKick && client.AllowKicking)
{
var kickVoteButton = new GUIButton(new RectTransform(new Vector2(0.45f, 0.9f), buttonContainer.RectTransform),
TextManager.Get("VoteToKick"), style: "GUIButtonSmall")
{
UserData = client,
OnClicked = (btn, userdata) => { VoteForKick(client); btn.Enabled = false; return true; }
};
if (GameMain.NetworkMember.ConnectedClients != null)
{
kickVoteButton.Enabled = !client.HasKickVoteFromID(myID);
}
}
}
public void CreateKickReasonPrompt(string clientName, bool ban, bool rangeBan = false)
{
var banReasonPrompt = new GUIMessageBox(
TextManager.Get(ban ? "BanReasonPrompt" : "KickReasonPrompt"),
"", new string[] { TextManager.Get("OK"), TextManager.Get("Cancel") }, new Vector2(0.25f, 0.2f), new Point(400, 200));
"", new string[] { TextManager.Get("OK"), TextManager.Get("Cancel") }, new Vector2(0.25f, 0.22f), new Point(400, 220));
var content = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.6f), banReasonPrompt.InnerFrame.RectTransform, Anchor.Center));
var banReasonBox = new GUITextBox(new RectTransform(new Vector2(1.0f, 0.3f), content.RectTransform))
@@ -2820,14 +2898,16 @@ namespace Barotrauma.Networking
if (ban)
{
new GUITextBlock(new RectTransform(new Vector2(0.8f, 0.15f), content.RectTransform), TextManager.Get("BanDuration"));
permaBanTickBox = new GUITickBox(new RectTransform(new Vector2(0.8f, 0.15f), content.RectTransform) { RelativeOffset = new Vector2(0.05f, 0.0f) },
TextManager.Get("BanPermanent"))
var labelContainer = new GUILayoutGroup(new RectTransform(new Vector2(1f, 0.25f), content.RectTransform), isHorizontal: false);
new GUITextBlock(new RectTransform(new Vector2(1f, 0.5f), labelContainer.RectTransform), TextManager.Get("BanDuration")) { 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"))
{
Selected = true
};
var durationContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.8f, 0.15f), content.RectTransform), isHorizontal: true)
var durationContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.8f, 1f), buttonContent.RectTransform), isHorizontal: true)
{
Visible = false
};
@@ -2930,7 +3010,7 @@ namespace Barotrauma.Networking
}
if (GameMain.GameSession?.Submarine != null)
{
errorLines.Add("Submarine: " + GameMain.GameSession.Submarine.Name);
errorLines.Add("Submarine: " + GameMain.GameSession.Submarine.Info.Name);
}
if (Level.Loaded != null)
{
@@ -2952,8 +3032,8 @@ namespace Barotrauma.Networking
errorLines.Add(" " + DebugConsole.Messages[i].Time + " - " + DebugConsole.Messages[i].Text);
}
string filePath = "event_error_log_client_" + Name + "_" + ToolBox.RemoveInvalidFileNameChars(DateTime.UtcNow.ToShortTimeString() + ".log");
filePath = Path.Combine(ServerLog.SavePath, filePath);
string filePath = "event_error_log_client_" + Name + "_" + DateTime.UtcNow.ToShortTimeString() + ".log";
filePath = Path.Combine(ServerLog.SavePath, ToolBox.RemoveInvalidFileNameChars(filePath));
if (!Directory.Exists(ServerLog.SavePath))
{
@@ -47,11 +47,30 @@ namespace Barotrauma
CreateLabeledSlider(parent, 0.0f, 1.0f, 0.01f, nameof(StructureDamageKarmaDecrease));
CreateLabeledSlider(parent, 0.0f, 1.0f, 0.01f, nameof(DamageFriendlyKarmaDecrease));
//hide these for now if a localized text is not available
if (TextManager.ContainsTag("Karma." + nameof(StunFriendlyKarmaDecrease)))
{
CreateLabeledSlider(parent, 0.0f, 1.0f, 0.01f, nameof(StunFriendlyKarmaDecrease));
}
if (TextManager.ContainsTag("Karma." + nameof(StunFriendlyKarmaDecreaseThreshold)))
{
CreateLabeledSlider(parent, 0.0f, 10.0f, 1.0f, nameof(StunFriendlyKarmaDecreaseThreshold));
}
CreateLabeledSlider(parent, 0.0f, 100.0f, 1.0f, nameof(ReactorMeltdownKarmaDecrease));
CreateLabeledSlider(parent, 0.0f, 10.0f, 0.05f, nameof(ReactorOverheatKarmaDecrease));
CreateLabeledNumberInput(parent, 0, 20, nameof(AllowedWireDisconnectionsPerMinute));
CreateLabeledSlider(parent, 0.0f, 20.0f, 0.5f, nameof(WireDisconnectionKarmaDecrease));
CreateLabeledSlider(parent, 0.0f, 30.0f, 1.0f, nameof(SpamFilterKarmaDecrease));
//hide these for now if a localized text is not available
if (TextManager.ContainsTag("Karma." + nameof(DangerousItemStealKarmaDecrease)))
{
CreateLabeledSlider(parent, 0.0f, 30.0f, 1.0f, nameof(DangerousItemStealKarmaDecrease));
}
if (TextManager.ContainsTag("Karma." + nameof(DangerousItemStealBots)))
{
CreateLabeledTickBox(parent, nameof(DangerousItemStealBots));
}
}
private void CreateLabeledSlider(GUIComponent parent, float min, float max, float step, string propertyName)
@@ -39,7 +39,10 @@ namespace Barotrauma.Networking
contentPackageOrderReceived = false;
netPeerConfiguration = new NetPeerConfiguration("barotrauma");
netPeerConfiguration = new NetPeerConfiguration("barotrauma")
{
UseDualModeSockets = GameMain.Config.UseDualModeSockets
};
netPeerConfiguration.DisableMessageType(NetIncomingMessageType.DebugMessage | NetIncomingMessageType.WarningMessage | NetIncomingMessageType.Receipt
| NetIncomingMessageType.ErrorMessage | NetIncomingMessageType.Error);
@@ -137,8 +137,9 @@ namespace Barotrauma.Networking
timeout -= deltaTime;
heartbeatTimer -= deltaTime;
while (Steamworks.SteamNetworking.IsP2PPacketAvailable())
for (int i=0;i<100;i++)
{
if (!Steamworks.SteamNetworking.IsP2PPacketAvailable()) { break; }
var packet = Steamworks.SteamNetworking.ReadP2PPacket();
if (packet.HasValue)
{
@@ -204,8 +204,9 @@ namespace Barotrauma.Networking
}
}
while (Steamworks.SteamNetworking.IsP2PPacketAvailable())
for (int i=0;i<100;i++)
{
if (!Steamworks.SteamNetworking.IsP2PPacketAvailable()) { break; }
var packet = Steamworks.SteamNetworking.ReadP2PPacket();
if (packet.HasValue)
{
@@ -2,6 +2,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework.Graphics;
using Barotrauma.Extensions;
namespace Barotrauma.Networking
{
@@ -9,9 +11,19 @@ namespace Barotrauma.Networking
{
public GUIButton LogFrame;
private GUIListBox listBox;
private GUIButton reverseButton;
private string msgFilter;
private bool reverseOrder = false;
private bool OnReverseClicked(GUIButton btn, object obj)
{
SetMessageReversal(!reverseOrder);
return false;
}
public void CreateLogFrame()
{
LogFrame = new GUIButton(new RectTransform(Vector2.One, GUI.Canvas), style: "GUIBackgroundBlocker")
@@ -80,7 +92,17 @@ namespace Barotrauma.Networking
GUI.KeyboardDispatcher.Subscriber = searchBox;
filterArea.RectTransform.MinSize = new Point(0, filterArea.RectTransform.Children.Max(c => c.MinSize.Y));
listBox = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.95f), rightColumn.RectTransform));
GUILayoutGroup listBoxLayout = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.95f), rightColumn.RectTransform))
{
Stretch = true,
RelativeSpacing = 0.0f
};
reverseButton = new GUIButton(new RectTransform(new Vector2(1.0f, 0.05f), listBoxLayout.RectTransform), style: "UIToggleButtonVertical");
reverseButton.Children.ForEach(c => c.SpriteEffects = reverseOrder ? SpriteEffects.FlipVertically : SpriteEffects.None);
reverseButton.OnClicked = OnReverseClicked;
listBox = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.95f), listBoxLayout.RectTransform));
GUIButton closeButton = new GUIButton(new RectTransform(new Vector2(0.25f, 0.05f), rightColumn.RectTransform), TextManager.Get("Close"))
{
@@ -107,7 +129,7 @@ namespace Barotrauma.Networking
msgFilter = "";
}
public void AssignLogFrame(GUIListBox inListBox, GUIComponent tickBoxContainer, GUITextBox searchBox)
public void AssignLogFrame(GUIButton inReverseButton, GUIListBox inListBox, GUIComponent tickBoxContainer, GUITextBox searchBox)
{
searchBox.OnTextChanged += (textBox, text) =>
{
@@ -144,6 +166,10 @@ namespace Barotrauma.Networking
inListBox.ClearChildren();
listBox = inListBox;
reverseButton = inReverseButton;
reverseButton.Children.ForEach(c => c.SpriteEffects = reverseOrder ? SpriteEffects.FlipVertically : SpriteEffects.None);
reverseButton.OnClicked = OnReverseClicked;
var currLines = lines.ToList();
foreach (LogMessage line in currLines)
{
@@ -158,8 +184,34 @@ namespace Barotrauma.Networking
{
float prevSize = listBox.BarSize;
var textBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), listBox.Content.RectTransform),
line.Text, wrap: true, font: GUI.SmallFont)
GUIFrame textContainer = null;
Anchor anchor = Anchor.TopLeft;
Pivot pivot = Pivot.TopLeft;
if (line.RichData != null)
{
foreach (var data in line.RichData)
{
UInt64 id = 0;
if (!UInt64.TryParse(data.Metadata, out id)) { return; }
Client client = GameMain.Client.ConnectedClients.Find(c => c.SteamID == id);
client ??= GameMain.Client.ConnectedClients.Find(c => c.ID == id);
if (client != null && client.Karma < 40.0f)
{
textContainer = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.0f), listBox.Content.RectTransform),
style: null, color: new Color(0xff111155))
{
CanBeFocused = false
};
anchor = Anchor.CenterLeft;
pivot = Pivot.CenterLeft;
break;
}
}
}
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)
{
TextColor = messageColor[line.Type],
Visible = !msgTypeHidden[(int)line.Type],
@@ -167,6 +219,38 @@ namespace Barotrauma.Networking
UserData = line
};
if (textContainer != null)
{
textContainer.RectTransform.NonScaledSize = new Point(textContainer.RectTransform.NonScaledSize.X, textBlock.RectTransform.NonScaledSize.Y + 5);
textBlock.SetTextPos();
textBlock.RectTransform.Resize(textContainer.RectTransform.NonScaledSize);
}
if (reverseOrder)
{
textBlock.RectTransform.SetAsFirstChild();
}
if (line.RichData != null)
{
foreach (var data in line.RichData)
{
textBlock.ClickableAreas.Add(new GUITextBlock.ClickableArea()
{
Data = data,
OnClick = (component, area) =>
{
UInt64 id = 0;
if (!UInt64.TryParse(area.Data.Metadata, out id)) { return; }
Client client = GameMain.Client.ConnectedClients.Find(c => c.SteamID == id);
client ??= GameMain.Client.ConnectedClients.Find(c => c.ID == id);
if (client == null) { return; }
GameMain.NetLobbyScreen.SelectPlayer(client);
}
});
}
}
if ((prevSize == 1.0f && listBox.BarScroll == 0.0f) || (prevSize < 1.0f && listBox.BarScroll == 1.0f)) listBox.BarScroll = 1.0f;
}
@@ -195,6 +279,16 @@ namespace Barotrauma.Networking
return true;
}
private void SetMessageReversal(bool reverse)
{
if (reverseOrder == reverse) { return; }
reverseOrder = reverse;
reverseButton.Children.ForEach(c => c.SpriteEffects = reverseOrder ? SpriteEffects.FlipVertically : SpriteEffects.None);
listBox.Content.RectTransform.ReverseChildren();
}
public bool ClearFilter(GUIComponent button, object obj)
{
var searchBox = button.UserData as GUITextBox;
@@ -571,6 +571,9 @@ namespace Barotrauma.Networking
var ragdollButtonBox = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.05f), roundsTab.RectTransform), TextManager.Get("ServerSettingsAllowRagdollButton"));
GetPropertyData("AllowRagdollButton").AssignGUIComponent(ragdollButtonBox);
var disableBotConversationsBox = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.05f), roundsTab.RectTransform), TextManager.Get("ServerSettingsDisableBotConversations"));
GetPropertyData("DisableBotConversations").AssignGUIComponent(disableBotConversationsBox);
/*var traitorRatioBox = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.05f), roundsTab.RectTransform), TextManager.Get("ServerSettingsUseTraitorRatio"));
CreateLabeledSlider(roundsTab, "", out slider, out sliderLabel);
@@ -10,11 +10,14 @@ using RestSharp.Contrib;
using System.Xml.Linq;
using System.Xml;
using Color = Microsoft.Xna.Framework.Color;
using System.Runtime.InteropServices;
namespace Barotrauma.Steam
{
static partial class SteamManager
{
private static Dictionary<Steamworks.Data.PublishedFileId, Task> modCopiesInProgress = new Dictionary<Steamworks.Data.PublishedFileId, Task>();
private static void InitializeProjectSpecific()
{
if (isInitialized) { return; }
@@ -35,6 +38,11 @@ namespace Barotrauma.Steam
popularTags.Insert(i, commonness.Key);
i++;
}
LogSteamworksNetworkingDelegate = LogSteamworksNetworking;
IntPtr logSteamworksNetworkingPtr = Marshal.GetFunctionPointerForDelegate(LogSteamworksNetworkingDelegate);
Steamworks.SteamNetworkingUtils.SetDebugOutputFunction(Steamworks.Data.DebugOutputType.Everything, logSteamworksNetworkingPtr);
}
}
catch (DllNotFoundException)
@@ -61,22 +69,17 @@ namespace Barotrauma.Steam
}
}
public static bool NetworkingDebugLog = false;
private static Steamworks.Data.FSteamNetworkingSocketsDebugOutput LogSteamworksNetworkingDelegate;
private static void LogSteamworksNetworking(Steamworks.Data.DebugOutputType nType, string pszMsg)
{
if (NetworkingDebugLog) { DebugConsole.NewMessage($"({nType}) {pszMsg}", Color.Orange); }
}
private static void UpdateProjectSpecific(float deltaTime)
{
for (int i=0;i<(ugcResultPageTasks?.Count ?? 0);i++)
{
var task = ugcResultPageTasks[i];
if (task.IsCompleted)
{
if (!task.IsCompletedSuccessfully)
{
DebugConsole.ThrowError("Failed to retrieve Steam Workshop page info: TaskStatus = "+task.Status.ToString());
}
ugcResultPageTasks.RemoveAt(i);
i--;
}
}
if (ugcSubscriptionTasks != null)
{
var ugcSubscriptionKeys = ugcSubscriptionTasks.Keys.ToList();
@@ -525,7 +528,37 @@ namespace Barotrauma.Steam
}
}
private static List<Task> ugcResultPageTasks;
private static async Task<List<Steamworks.Ugc.Item>> GetWorkshopItemsAsync(Steamworks.Ugc.Query query, int clampResults = 0, Predicate<Steamworks.Ugc.Item> itemPredicate=null)
{
await Task.Yield();
int pageIndex = 1;
Steamworks.Ugc.ResultPage? resultPage = await query.GetPageAsync(pageIndex);
List<Steamworks.Ugc.Item> retVal = new List<Steamworks.Ugc.Item>();
while (resultPage.HasValue && resultPage?.ResultCount > 0)
{
if (itemPredicate != null)
{
retVal.AddRange(resultPage.Value.Entries.Where(it => itemPredicate(it)));
}
else
{
retVal.AddRange(resultPage.Value.Entries);
}
if (clampResults > 0 && retVal.Count >= clampResults)
{
retVal = retVal.Take(clampResults).ToList();
break;
}
pageIndex++;
resultPage = await query.GetPageAsync(pageIndex);
}
return retVal;
}
public static void GetSubscribedWorkshopItems(Action<IList<Steamworks.Ugc.Item>> onItemsFound, List<string> requireTags = null)
{
@@ -535,30 +568,9 @@ namespace Barotrauma.Steam
.RankedByTotalUniqueSubscriptions()
.WhereUserSubscribed()
.WithLongDescription();
if (requireTags != null) query.WithTags(requireTags);
if (requireTags != null) { query = query.WithTags(requireTags); }
ugcResultPageTasks ??= new List<Task>();
ugcResultPageTasks.Add(Task.Run(async () =>
{
int processedResults = 0; int pageIndex = 1;
Steamworks.Ugc.ResultPage? resultPage = await query.GetPageAsync(pageIndex);
while (resultPage.HasValue && resultPage?.ResultCount > 0)
{
onItemsFound?.Invoke(resultPage.Value.Entries.ToList());
processedResults += resultPage.Value.ResultCount;
pageIndex++;
if (processedResults < resultPage?.TotalCount)
{
resultPage = await query.GetPageAsync(pageIndex);
}
else
{
resultPage = null;
}
}
}));
TaskPool.Add(GetWorkshopItemsAsync(query), (task) => { onItemsFound?.Invoke(task.Result); });
}
public static void GetPopularWorkshopItems(Action<IList<Steamworks.Ugc.Item>> onItemsFound, int amount, List<string> requireTags = null)
@@ -570,65 +582,40 @@ namespace Barotrauma.Steam
.WithLongDescription();
if (requireTags != null) query.WithTags(requireTags);
ugcResultPageTasks ??= new List<Task>();
ugcResultPageTasks.Add(Task.Run(async () =>
{
int processedResults = 0; int pageIndex = 1;
Steamworks.Ugc.ResultPage? resultPage = await query.GetPageAsync(pageIndex);
TaskPool.Add(GetWorkshopItemsAsync(query, amount, (item) => !item.IsSubscribed), (task) => {
var entries = task.Result;
while (resultPage.HasValue && resultPage?.ResultCount > 0)
//count the number of each unique tag
foreach (var item in entries)
{
var entries = resultPage.Value.Entries.ToList();
//count the number of each unique tag
foreach (var item in entries)
foreach (string tag in item.Tags)
{
foreach (string tag in item.Tags)
if (string.IsNullOrEmpty(tag)) { continue; }
string caseInvariantTag = tag.ToLowerInvariant();
if (!tagCommonness.ContainsKey(caseInvariantTag))
{
if (string.IsNullOrEmpty(tag)) { continue; }
string caseInvariantTag = tag.ToLowerInvariant();
if (!tagCommonness.ContainsKey(caseInvariantTag))
{
tagCommonness[caseInvariantTag] = 1;
}
else
{
tagCommonness[caseInvariantTag]++;
}
tagCommonness[caseInvariantTag] = 1;
}
}
//populate the popularTags list with tags sorted by commonness
popularTags.Clear();
foreach (KeyValuePair<string, int> tagCommonnessKVP in tagCommonness)
{
int i = 0;
while (i < popularTags.Count &&
tagCommonness[popularTags[i]] > tagCommonnessKVP.Value)
else
{
i++;
tagCommonness[caseInvariantTag]++;
}
popularTags.Insert(i, tagCommonnessKVP.Key);
}
var nonSubscribedItems = entries.Where(it => !it.IsSubscribed);
if (nonSubscribedItems.Count() > (amount-processedResults))
{
nonSubscribedItems = nonSubscribedItems.Take(amount - processedResults);
}
onItemsFound?.Invoke(nonSubscribedItems.ToList());
processedResults += resultPage.Value.ResultCount;
pageIndex++;
if (processedResults < resultPage?.TotalCount && processedResults < amount)
{
resultPage = await query.GetPageAsync(pageIndex);
}
else
{
resultPage = null;
}
}
}));
//populate the popularTags list with tags sorted by commonness
popularTags.Clear();
foreach (KeyValuePair<string, int> tagCommonnessKVP in tagCommonness)
{
int i = 0;
while (i < popularTags.Count &&
tagCommonness[popularTags[i]] > tagCommonnessKVP.Value)
{
i++;
}
popularTags.Insert(i, tagCommonnessKVP.Key);
}
onItemsFound?.Invoke(task.Result);
});
}
public static void GetPublishedWorkshopItems(Action<IList<Steamworks.Ugc.Item>> onItemsFound, List<string> requireTags = null)
@@ -641,28 +628,7 @@ namespace Barotrauma.Steam
.WithLongDescription();
if (requireTags != null) query.WithTags(requireTags);
ugcResultPageTasks ??= new List<Task>();
ugcResultPageTasks.Add(Task.Run(async () =>
{
int processedResults = 0; int pageIndex = 1;
Steamworks.Ugc.ResultPage? resultPage = await query.GetPageAsync(pageIndex);
while (resultPage.HasValue && resultPage?.ResultCount > 0)
{
onItemsFound?.Invoke(resultPage.Value.Entries.ToList());
processedResults += resultPage.Value.ResultCount;
pageIndex++;
if (processedResults < resultPage?.TotalCount)
{
resultPage = await query.GetPageAsync(pageIndex);
}
else
{
resultPage = null;
}
}
}));
TaskPool.Add(GetWorkshopItemsAsync(query), (task) => { onItemsFound?.Invoke(task.Result); });
}
private static Dictionary<ulong, Task> ugcSubscriptionTasks;
@@ -926,7 +892,7 @@ namespace Barotrauma.Steam
/// <summary>
/// Enables a workshop item by moving it to the game folder.
/// </summary>
public static bool EnableWorkShopItem(Steamworks.Ugc.Item? item, bool allowFileOverwrite, out string errorMsg)
public static bool EnableWorkShopItem(Steamworks.Ugc.Item? item, bool allowFileOverwrite, out string errorMsg, bool selectContentPackage = false, bool suppressInstallNotif = false)
{
if (!(item?.IsInstalled ?? false))
{
@@ -952,10 +918,18 @@ namespace Barotrauma.Steam
if (ContentPackage.List.Any(cp => cp.Path.CleanUpPath() == newContentPackagePath.CleanUpPath()))
{
errorMsg = TextManager.GetWithVariables("WorkshopErrorSamePathInstalled",
new string[] { "[itemname]", "[itempath]" },
new string[] { item?.Title, Path.GetDirectoryName(newContentPackagePath) });
return false;
if (item?.Owner.Id != Steamworks.SteamClient.SteamId)
{
errorMsg = TextManager.GetWithVariables("WorkshopErrorSamePathInstalled",
new string[] { "[itemname]", "[itempath]" },
new string[] { item?.Title, Path.GetDirectoryName(newContentPackagePath) });
return false;
}
else
{
RemoveMods(cp => !string.IsNullOrWhiteSpace(cp.SteamWorkshopUrl) && cp.SteamWorkshopUrl == contentPackage.SteamWorkshopUrl,
false);
}
}
if (!contentPackage.IsCompatible())
@@ -972,57 +946,116 @@ namespace Barotrauma.Steam
return false;
}
GameMain.Config.SuppressModFolderWatcher = true;
Task<string> newTask = null;
CopyWorkShopItem(item, contentPackage, newContentPackagePath, metaDataFilePath, allowFileOverwrite, out errorMsg);
var newPackage = new ContentPackage(contentPackage.Path, newContentPackagePath)
lock (modCopiesInProgress)
{
SteamWorkshopUrl = item?.Url,
InstallTime = item?.Updated > item?.Created ? item?.Updated : item?.Created
};
foreach (ContentFile contentFile in newPackage.Files)
{
contentFile.Path = CorrectContentFilePath(contentFile.Path, contentPackage, true);
if (modCopiesInProgress.ContainsKey(item.Value.Id))
{
if (!modCopiesInProgress[item.Value.Id].IsCompleted &&
!modCopiesInProgress[item.Value.Id].IsFaulted &&
!modCopiesInProgress[item.Value.Id].IsCanceled)
{
errorMsg = ""; return true;
}
modCopiesInProgress.Remove(item.Value.Id);
}
newTask = CopyWorkShopItemAsync(item, contentPackage, newContentPackagePath, metaDataFilePath, allowFileOverwrite);
modCopiesInProgress.Add(item.Value.Id, newTask);
}
TaskPool.Add(newTask,
contentPackage,
(task, cp) =>
{
if (task.IsFaulted || task.IsCanceled)
{
DebugConsole.ThrowError($"Failed to copy \"{item?.Title}\"", task.Exception);
GameMain.SteamWorkshopScreen?.SetReinstallButtonStatus(item, true, GUI.Style.Red);
return;
}
if (!string.IsNullOrWhiteSpace(task.Result))
{
DebugConsole.ThrowError($"Failed to copy \"{item?.Title}\": {task.Result}");
GameMain.SteamWorkshopScreen?.SetReinstallButtonStatus(item, true, GUI.Style.Red);
return;
}
if (!Directory.Exists(Path.GetDirectoryName(newContentPackagePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(newContentPackagePath));
}
newPackage.Save(newContentPackagePath);
ContentPackage.List.Add(newPackage);
if (newPackage.CorePackage)
{
GameMain.Config.SelectCorePackage(newPackage);
}
else
{
GameMain.Config.SelectContentPackage(newPackage);
}
GameMain.Config.SaveNewPlayerConfig();
GameMain.Config.SuppressModFolderWatcher = true;
GameMain.Config.WarnIfContentPackageSelectionDirty();
var newPackage = new ContentPackage(cp.Path, newContentPackagePath)
{
SteamWorkshopUrl = item?.Url,
InstallTime = item?.Updated > item?.Created ? item?.Updated : item?.Created
};
GameMain.Config.SuppressModFolderWatcher = false;
foreach (ContentFile contentFile in newPackage.Files)
{
contentFile.Path = CorrectContentFilePath(contentFile.Path, cp, true);
}
if (newPackage.Files.Any(f => f.Type == ContentType.Submarine))
{
Submarine.RefreshSavedSubs();
}
if (!Directory.Exists(Path.GetDirectoryName(newContentPackagePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(newContentPackagePath));
}
newPackage.Save(newContentPackagePath);
ContentPackage.List.Add(newPackage);
if (selectContentPackage)
{
if (newPackage.CorePackage)
{
GameMain.Config.SelectCorePackage(newPackage);
}
else
{
GameMain.Config.SelectContentPackage(newPackage);
}
GameMain.Config.SaveNewPlayerConfig();
GameMain.Config.WarnIfContentPackageSelectionDirty();
if (newPackage.Files.Any(f => f.Type == ContentType.Submarine))
{
SubmarineInfo.RefreshSavedSubs();
}
}
else if (!suppressInstallNotif)
{
GameMain.MainMenuScreen?.SetEnableModsNotification(true);
}
GameMain.Config.SuppressModFolderWatcher = false;
GameMain.SteamWorkshopScreen?.SetReinstallButtonStatus(item, true, GUI.Style.Green);
});
errorMsg = "";
return true;
}
private static bool CopyWorkShopItem(Steamworks.Ugc.Item? item, ContentPackage contentPackage, string newContentPackagePath, string metaDataFilePath, bool allowFileOverwrite, out string errorMsg)
/// <summary>
/// Asynchronously copies a Workshop item into the Mods folder.
/// </summary>
/// <returns>Returns an empty string on success, otherwise returns an error message.</returns>
private async static Task<string> CopyWorkShopItemAsync(Steamworks.Ugc.Item? item, ContentPackage contentPackage, string newContentPackagePath, string metaDataFilePath, bool allowFileOverwrite)
{
errorMsg = "";
await Task.Yield();
string targetPath = Path.GetDirectoryName(GetWorkshopItemContentPackagePath(contentPackage));
string copyingPath = Path.Combine(targetPath, CopyIndicatorFileName);
string errorMsg = "";
if (contentPackage.GameVersion > new Version(0, 9, 1, 0))
{
SaveUtil.CopyFolder(item?.Directory, Path.GetDirectoryName(GetWorkshopItemContentPackagePath(contentPackage)), copySubDirs: true, overwriteExisting: true);
return true;
Directory.CreateDirectory(targetPath);
File.WriteAllText(copyingPath, "TEMPORARY FILE");
SaveUtil.CopyFolder(item?.Directory, targetPath, copySubDirs: true, overwriteExisting: true);
File.Delete(copyingPath);
return "";
}
var allPackageFiles = Directory.GetFiles(item?.Directory, "*", SearchOption.AllDirectories);
@@ -1042,7 +1075,7 @@ namespace Barotrauma.Steam
{
errorMsg = TextManager.GetWithVariables("WorkshopErrorOverwriteOnEnable", new string[2] { "[itemname]", "[filename]" }, new string[2] { item?.Title, newContentPackagePath });
DebugConsole.NewMessage(errorMsg, Color.Red);
return false;
return errorMsg;
}
foreach (ContentFile contentFile in contentPackage.Files)
@@ -1053,84 +1086,79 @@ namespace Barotrauma.Steam
{
errorMsg = TextManager.GetWithVariables("WorkshopErrorOverwriteOnEnable", new string[2] { "[itemname]", "[filename]" }, new string[2] { item?.Title, contentFile.Path });
DebugConsole.NewMessage(errorMsg, Color.Red);
return false;
return errorMsg;
}
}
}
try
Directory.CreateDirectory(targetPath);
File.WriteAllText(copyingPath, "TEMPORARY FILE");
foreach (ContentFile contentFile in contentPackage.Files)
{
foreach (ContentFile contentFile in contentPackage.Files)
contentFile.Path = contentFile.Path.CleanUpPath();
string sourceFile = Path.Combine(item?.Directory, contentFile.Path);
if (!File.Exists(sourceFile))
{
contentFile.Path = contentFile.Path.CleanUpPath();
string sourceFile = Path.Combine(item?.Directory, contentFile.Path);
if (!File.Exists(sourceFile))
string[] splitPath = contentFile.Path.Split('/');
if (splitPath.Length >= 2 && splitPath[0] == "Mods")
{
string[] splitPath = contentFile.Path.Split('/');
if (splitPath.Length >= 2 && splitPath[0] == "Mods")
{
sourceFile = Path.Combine(item?.Directory, string.Join("/", splitPath.Skip(2)));
}
sourceFile = Path.Combine(item?.Directory, string.Join("/", splitPath.Skip(2)));
}
}
contentFile.Path = CorrectContentFilePath(contentFile.Path, contentPackage, false);
contentFile.Path = CorrectContentFilePath(contentFile.Path, contentPackage,
contentFile.Type != ContentType.Submarine);
//path not allowed -> the content file must be a reference to an external file (such as some vanilla file outside the Mods folder)
if (!ContentPackage.IsModFilePathAllowed(contentFile))
//path not allowed -> the content file must be a reference to an external file (such as some vanilla file outside the Mods folder)
if (!ContentPackage.IsModFilePathAllowed(contentFile))
{
//the content package is trying to copy a file to a prohibited path, which is not allowed
if (File.Exists(sourceFile))
{
//the content package is trying to copy a file to a prohibited path, which is not allowed
if (File.Exists(sourceFile))
{
errorMsg = TextManager.GetWithVariable("WorkshopErrorIllegalPathOnEnable", "[filename]", contentFile.Path);
return false;
}
//not trying to copy anything, so this is a reference to an external file
//if the external file doesn't exist, we cannot enable the package
else if (!File.Exists(contentFile.Path))
{
errorMsg = TextManager.GetWithVariable("WorkshopErrorEnableFailed", "[itemname]", item?.Title) + " " + TextManager.GetWithVariable("WorkshopFileNotFound", "[path]", "\"" + contentFile.Path + "\"");
return false;
}
errorMsg = TextManager.GetWithVariable("WorkshopErrorIllegalPathOnEnable", "[filename]", contentFile.Path);
return errorMsg;
}
//not trying to copy anything, so this is a reference to an external file
//if the external file doesn't exist, we cannot enable the package
else if (!File.Exists(contentFile.Path))
{
errorMsg = TextManager.GetWithVariable("WorkshopErrorEnableFailed", "[itemname]", item?.Title) + " " + TextManager.GetWithVariable("WorkshopFileNotFound", "[path]", "\"" + contentFile.Path + "\"");
return errorMsg;
}
continue;
}
else if (!File.Exists(sourceFile))
{
if (File.Exists(contentFile.Path))
{
//the file is already present in the game folder, all good
continue;
}
else if (!File.Exists(sourceFile))
else
{
if (File.Exists(contentFile.Path))
{
//the file is already present in the game folder, all good
continue;
}
else
{
//file not present in either the mod or the game folder -> cannot enable the package
errorMsg = TextManager.GetWithVariable("WorkshopErrorEnableFailed", "[itemname]", item?.Title) + " " + TextManager.GetWithVariable("WorkshopFileNotFound", "[path]", "\"" + contentFile.Path + "\"");
return false;
}
//file not present in either the mod or the game folder -> cannot enable the package
errorMsg = TextManager.GetWithVariable("WorkshopErrorEnableFailed", "[itemname]", item?.Title) + " " + TextManager.GetWithVariable("WorkshopFileNotFound", "[path]", "\"" + contentFile.Path + "\"");
return errorMsg;
}
//make sure the destination directory exists
Directory.CreateDirectory(Path.GetDirectoryName(contentFile.Path));
CorrectContentFileCopy(contentPackage, sourceFile, contentFile.Path, overwrite: true);
}
foreach (string nonContentFile in nonContentFiles)
{
string sourceFile = Path.Combine(item?.Directory, nonContentFile);
if (!File.Exists(sourceFile)) { continue; }
string destinationPath = CorrectContentFilePath(nonContentFile, contentPackage, false);
Directory.CreateDirectory(Path.GetDirectoryName(destinationPath));
CorrectContentFileCopy(contentPackage, sourceFile, destinationPath, overwrite: true);
}
//make sure the destination directory exists
Directory.CreateDirectory(Path.GetDirectoryName(contentFile.Path));
CorrectContentFileCopy(contentPackage, sourceFile, contentFile.Path, overwrite: true);
}
catch (Exception e)
foreach (string nonContentFile in nonContentFiles)
{
errorMsg = TextManager.GetWithVariable("WorkshopErrorEnableFailed", "[itemname]", item?.Title) + " {" + e.Message + "}";
DebugConsole.NewMessage(errorMsg, Color.Red);
return false;
string sourceFile = Path.Combine(item?.Directory, nonContentFile);
if (!File.Exists(sourceFile)) { continue; }
string destinationPath = CorrectContentFilePath(nonContentFile, contentPackage, false);
Directory.CreateDirectory(Path.GetDirectoryName(destinationPath));
CorrectContentFileCopy(contentPackage, sourceFile, destinationPath, overwrite: true);
}
return true;
File.Delete(copyingPath);
return "";
}
private static bool CheckFileEquality(string filePath1, string filePath2)
@@ -1149,6 +1177,47 @@ namespace Barotrauma.Steam
}
}
private static void RemoveMods(Func<ContentPackage, bool> predicate, bool delete = true)
{
var toRemove = ContentPackage.List.Where(predicate).ToList();
var packagesToDeselect = GameMain.Config.SelectedContentPackages.Where(p => toRemove.Contains(p)).ToList();
foreach (var cp in packagesToDeselect)
{
if (cp.CorePackage)
{
GameMain.Config.SelectCorePackage(ContentPackage.List.Find(cpp => cpp.CorePackage && !toRemove.Contains(cpp)));
}
else
{
GameMain.Config.DeselectContentPackage(cp);
}
}
if (delete)
{
foreach (var cp in toRemove)
{
try
{
string path = Path.GetDirectoryName(cp.Path);
if (Directory.Exists(path)) { Directory.Delete(path, true); }
}
catch (Exception e)
{
DebugConsole.ThrowError($"An error occurred while attempting to delete {Path.GetDirectoryName(cp.Path)}", e);
}
}
}
ContentPackage.List.RemoveAll(cp => toRemove.Contains(cp));
GameMain.Config.SelectedContentPackages.RemoveAll(cp => !ContentPackage.List.Contains(cp));
ContentPackage.SortContentPackages();
GameMain.Config.SaveNewPlayerConfig();
GameMain.Config.WarnIfContentPackageSelectionDirty();
}
/// <summary>
/// Disables a workshop item by removing the files from the game folder.
/// </summary>
@@ -1173,44 +1242,11 @@ namespace Barotrauma.Steam
GameMain.Config.SuppressModFolderWatcher = true;
try
{
var toRemove = ContentPackage.List.Where(cp => !string.IsNullOrWhiteSpace(cp.SteamWorkshopUrl) && cp.SteamWorkshopUrl == contentPackage.SteamWorkshopUrl).ToList();
var packagesToDeselect = GameMain.Config.SelectedContentPackages.Where(p => toRemove.Contains(p)).ToList();
foreach (var cp in packagesToDeselect)
{
if (cp.CorePackage)
{
GameMain.Config.SelectCorePackage(ContentPackage.List.Find(cpp => cpp.CorePackage && !toRemove.Contains(cpp)));
}
else
{
GameMain.Config.DeselectContentPackage(cp);
}
}
foreach (var cp in toRemove)
{
try
{
Directory.Delete(Path.GetDirectoryName(cp.Path), true);
}
catch (Exception e)
{
DebugConsole.ThrowError($"An error occurred while attempting to delete {Path.GetDirectoryName(cp.Path)}", e);
}
}
ContentPackage.List.RemoveAll(cp => toRemove.Contains(cp));
GameMain.Config.SelectedContentPackages.RemoveAll(cp => !ContentPackage.List.Contains(cp));
ContentPackage.SortContentPackages();
GameMain.Config.SaveNewPlayerConfig();
GameMain.Config.WarnIfContentPackageSelectionDirty();
RemoveMods(cp => !string.IsNullOrWhiteSpace(cp.SteamWorkshopUrl) && cp.SteamWorkshopUrl == contentPackage.SteamWorkshopUrl);
}
catch (Exception e)
{
errorMsg = "Disabling the workshop item \"" + item?.Title + "\" failed. " + e.Message;
errorMsg = "Disabling the workshop item \"" + item?.Title + "\" failed. " + e.Message + "\n" + e.StackTrace;
if (!noLog)
{
DebugConsole.NewMessage(errorMsg, Microsoft.Xna.Framework.Color.Red);
@@ -1219,6 +1255,8 @@ namespace Barotrauma.Steam
}
GameMain.Config.SuppressModFolderWatcher = false;
GameMain.SteamWorkshopScreen?.SetReinstallButtonStatus(item, false, null);
errorMsg = "";
return true;
}
@@ -1314,7 +1352,7 @@ namespace Barotrauma.Steam
return upToDate;
}
public static async Task<bool> AutoUpdateWorkshopItems()
public static async Task<bool> AutoUpdateWorkshopItemsAsync()
{
if (!isInitialized) { return false; }
@@ -1322,60 +1360,104 @@ namespace Barotrauma.Steam
.WhereUserSubscribed()
.WithLongDescription();
DateTime startTime = DateTime.Now;
DateTime endTime = startTime + new TimeSpan(0, 0, 30);
List<Steamworks.Ugc.Item> items = await GetWorkshopItemsAsync(query);
int processedResults = 0; int pageIndex = 1;
Steamworks.Ugc.ResultPage? resultPage = await query.GetPageAsync(pageIndex);
GameMain.Config.SuppressModFolderWatcher = true;
while (resultPage.HasValue && resultPage?.ResultCount > 0)
//remove mods that the player is no longer subscribed to
RemoveMods(cp => !string.IsNullOrWhiteSpace(cp.SteamWorkshopUrl) && !items.Any(it => it.Id == GetWorkshopItemIDFromUrl(cp.SteamWorkshopUrl)));
GameMain.Config.SuppressModFolderWatcher = false;
List<string> updateNotifications = new List<string>();
foreach (var item in items)
{
if (DateTime.Now > endTime)
try
{
return false;
}
foreach (var item in resultPage.Value.Entries)
{
try
if (!item.IsInstalled) { continue; }
bool installedSuccessfully = false;
string errorMsg;
if (!CheckWorkshopItemEnabled(item))
{
if (!item.IsInstalled || !CheckWorkshopItemEnabled(item) || CheckWorkshopItemUpToDate(item)) { continue; }
if (!UpdateWorkshopItem(item, out string errorMsg))
installedSuccessfully = EnableWorkShopItem(item, true, out errorMsg);
}
else if (!CheckWorkshopItemUpToDate(item))
{
installedSuccessfully = UpdateWorkshopItem(item, out errorMsg);
}
else
{
continue;
}
if (!installedSuccessfully)
{
CrossThread.RequestExecutionOnMainThread(() =>
{
DebugConsole.NewMessage(errorMsg, Color.Red);
string errorId = errorMsg;
if (!GUIMessageBox.MessageBoxes.Any(m => m.UserData as string == errorId))
{
new GUIMessageBox(
TextManager.Get("Error"),
TextManager.GetWithVariables("WorkshopItemUpdateFailed", new string[2] { "[itemname]", "[errormessage]" }, new string[2] { item.Title, errorMsg }))
{
UserData = errorId
};
}
});
}
else
{
updateNotifications.Add(TextManager.GetWithVariable("WorkshopItemUpdated", "[itemname]", item.Title));
}
}
catch (Exception e)
{
CrossThread.RequestExecutionOnMainThread(() =>
{
string errorId = e.Message;
if (!GUIMessageBox.MessageBoxes.Any(m => m.UserData as string == errorId))
{
DebugConsole.ThrowError(errorMsg);
new GUIMessageBox(
TextManager.Get("Error"),
TextManager.GetWithVariables("WorkshopItemUpdateFailed", new string[2] { "[itemname]", "[errormessage]" }, new string[2] { item.Title, errorMsg }));
TextManager.GetWithVariables("WorkshopItemUpdateFailed", new string[2] { "[itemname]", "[errormessage]" }, new string[2] { item.Title, e.Message + ", " + e.TargetSite }))
{
UserData = errorId
};
}
else
{
//TODO: potential race condition
new GUIMessageBox("", TextManager.GetWithVariable("WorkshopItemUpdated", "[itemname]", item.Title));
}
}
catch (Exception e)
{
new GUIMessageBox(
TextManager.Get("Error"),
TextManager.GetWithVariables("WorkshopItemUpdateFailed", new string[2] { "[itemname]", "[errormessage]" }, new string[2] { item.Title, e.Message + ", " + e.TargetSite }));
GameAnalyticsManager.AddErrorEventOnce(
"SteamManager.AutoUpdateWorkshopItems:" + e.Message,
GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
"Failed to autoupdate workshop item \"" + item.Title + "\". " + e.Message + "\n" + e.StackTrace);
}
}
processedResults += resultPage.Value.ResultCount;
pageIndex++;
if (processedResults < resultPage?.TotalCount)
{
resultPage = await query.GetPageAsync(pageIndex);
}
else
{
resultPage = null;
});
}
}
if (updateNotifications.Count > 0)
{
CrossThread.RequestExecutionOnMainThread(() =>
{
while (updateNotifications.Count > 0)
{
int notificationsPerMsgBox = 20;
new GUIMessageBox("", string.Join('\n', updateNotifications.Take(notificationsPerMsgBox)),
relativeSize: new Microsoft.Xna.Framework.Vector2(0.5f, 0.0f),
minSize: new Microsoft.Xna.Framework.Point(600, 0));
updateNotifications.RemoveRange(0, Math.Min(notificationsPerMsgBox, updateNotifications.Count));
}
});
}
List<Task> tasks;
lock (modCopiesInProgress)
{
tasks = modCopiesInProgress.Values.ToList();
}
await Task.WhenAll(tasks);
return true;
}
@@ -1383,7 +1465,10 @@ namespace Barotrauma.Steam
{
errorMsg = "";
if (!(item?.IsInstalled ?? false)) { return false; }
if (!DisableWorkShopItem(item, false, out errorMsg)) { return false; }
if (item?.Owner.Id != Steamworks.SteamClient.SteamId)
{
if (!DisableWorkShopItem(item, false, out errorMsg)) { return false; }
}
if (!EnableWorkShopItem(item, allowFileOverwrite: false, errorMsg: out errorMsg)) { return false; }
return true;
@@ -1391,8 +1476,9 @@ namespace Barotrauma.Steam
private static string GetWorkshopItemContentPackagePath(ContentPackage contentPackage)
{
string packageName = contentPackage.Name;
string packageName = contentPackage.Name.Trim();
packageName = ToolBox.RemoveInvalidFileNameChars(packageName);
while (packageName.Last() == '.') { packageName = packageName.Substring(0, packageName.Length-1); }
//packageName = packageName + "_" + GetWorkshopItemIDFromUrl(contentPackage.SteamWorkshopUrl);
return Path.Combine("Mods", packageName, MetadataFileName);
@@ -1421,7 +1507,7 @@ namespace Barotrauma.Steam
private static void CorrectContentFileCopy(ContentPackage package, string src, string dest, bool overwrite)
{
if (Path.GetExtension(src).ToLowerInvariant() == ".xml")
if (Path.GetExtension(src).Equals(".xml", StringComparison.OrdinalIgnoreCase))
{
XDocument doc = XMLExtensions.TryLoadXml(src);
if (doc != null)
@@ -1471,7 +1557,7 @@ namespace Barotrauma.Steam
{
if (checkIfFileExists)
{
ContentPackage otherContentPackage = ContentPackage.List.Find(cp => cp.Name.ToLowerInvariant() == splitPath[1].ToLowerInvariant());
ContentPackage otherContentPackage = ContentPackage.List.Find(cp => cp.Name.Equals(splitPath[1], StringComparison.OrdinalIgnoreCase));
if (otherContentPackage != null)
{
string otherPackageName = Path.GetDirectoryName(otherContentPackage.Path);
@@ -1483,7 +1569,8 @@ namespace Barotrauma.Steam
}
}
}
newPath = Path.Combine(packageName, string.Join("/", splitPath.Skip(2)));
splitPath = splitPath.Skip(Math.Clamp(splitPath.Length-1, 0, 2)).ToArray();
newPath = Path.Combine(packageName, string.Join("/", splitPath));
}
else
{
@@ -149,9 +149,15 @@ namespace Barotrauma.Networking
}
}
short[] uncompressedBuffer = new short[VoipConfig.BUFFER_SIZE];
short[] prevUncompressedBuffer = new short[VoipConfig.BUFFER_SIZE];
bool prevCaptured = true;
int captureTimer;
void UpdateCapture()
{
short[] uncompressedBuffer = new short[VoipConfig.BUFFER_SIZE];
Array.Copy(uncompressedBuffer, 0, prevUncompressedBuffer, 0, VoipConfig.BUFFER_SIZE);
Array.Clear(uncompressedBuffer, 0, VoipConfig.BUFFER_SIZE);
while (capturing)
{
int alcError;
@@ -202,6 +208,21 @@ namespace Barotrauma.Networking
bool allowEnqueue = false;
if (GameMain.WindowActive)
{
ForceLocal = captureTimer > 0 ? ForceLocal : false;
bool pttDown = false;
if ((PlayerInput.KeyDown(InputType.Voice) || PlayerInput.KeyDown(InputType.LocalVoice)) &&
GUI.KeyboardDispatcher.Subscriber == null)
{
pttDown = true;
if (PlayerInput.KeyDown(InputType.LocalVoice))
{
ForceLocal = true;
}
else
{
ForceLocal = false;
}
}
if (GameMain.Config.VoiceSetting == GameSettings.VoiceMode.Activity)
{
if (dB > GameMain.Config.NoiseGateThreshold)
@@ -211,25 +232,38 @@ namespace Barotrauma.Networking
}
else if (GameMain.Config.VoiceSetting == GameSettings.VoiceMode.PushToTalk)
{
if (PlayerInput.KeyDown(InputType.Voice) && GUI.KeyboardDispatcher.Subscriber == null)
if (pttDown)
{
allowEnqueue = true;
}
}
}
if (allowEnqueue)
if (allowEnqueue || captureTimer > 0)
{
LastEnqueueAudio = DateTime.Now;
//encode audio and enqueue it
lock (buffers)
{
if (!prevCaptured) //enqueue the previous buffer if not sent to avoid cutoff
{
int compressedCountPrev = VoipConfig.Encoder.Encode(prevUncompressedBuffer, 0, VoipConfig.BUFFER_SIZE, BufferToQueue, 0, VoipConfig.MAX_COMPRESSED_SIZE);
EnqueueBuffer(compressedCountPrev);
}
int compressedCount = VoipConfig.Encoder.Encode(uncompressedBuffer, 0, VoipConfig.BUFFER_SIZE, BufferToQueue, 0, VoipConfig.MAX_COMPRESSED_SIZE);
EnqueueBuffer(compressedCount);
}
captureTimer -= (VoipConfig.BUFFER_SIZE * 1000) / VoipConfig.FREQUENCY;
if (allowEnqueue)
{
captureTimer = GameMain.Config.VoiceChatCutoffPrevention;
}
prevCaptured = true;
}
else
{
captureTimer = 0;
prevCaptured = false;
//enqueue silence
lock (buffers)
{
@@ -85,20 +85,20 @@ namespace Barotrauma.Networking
return;
}
if (queue.Read(msg))
Client client = gameClient.ConnectedClients.Find(c => c.VoipQueue == queue);
if (queue.Read(msg, discardData: client.Muted || client.MutedLocally))
{
Client client = gameClient.ConnectedClients.Find(c => c.VoipQueue == queue);
if (client.Muted || client.MutedLocally) { return; }
if (client.VoipSound == null)
{
DebugConsole.Log("Recreating voipsound " + queueId);
client.VoipSound = new VoipSound(GameMain.SoundManager, client.VoipQueue);
client.VoipSound = new VoipSound(client.Name, GameMain.SoundManager, client.VoipQueue);
}
if (client.Character != null && !client.Character.IsDead && !client.Character.Removed && client.Character.SpeechImpediment <= 100.0f)
{
var messageType = ChatMessage.CanUseRadio(client.Character, out WifiComponent radio) ? ChatMessageType.Radio : ChatMessageType.Default;
WifiComponent radio = null;
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;
@@ -61,10 +61,10 @@ namespace Barotrauma
foreach (GUIComponent comp in listBox.Content.Children)
{
if (comp.FindChild("votes") is GUITextBlock voteText) comp.RemoveChild(voteText);
if (comp.FindChild("votes") is GUITextBlock voteText) { comp.RemoveChild(voteText); }
}
if (clients == null) return;
if (clients == null) { return; }
List<Pair<object, int>> voteList = GetVoteList(voteType, clients);
foreach (Pair<object, int> votable in voteList)
@@ -73,7 +73,7 @@ namespace Barotrauma
}
break;
case VoteType.StartRound:
if (clients == null) return;
if (clients == null) { return; }
foreach (Client client in clients)
{
var clientReady = GameMain.NetLobbyScreen.PlayerList.Content.FindChild(client)?.FindChild("clientready");
@@ -113,18 +113,18 @@ namespace Barotrauma
switch (voteType)
{
case VoteType.Sub:
Submarine sub = data as Submarine;
if (sub == null) return;
SubmarineInfo sub = data as SubmarineInfo;
if (sub == null) { return; }
msg.Write(sub.Name);
break;
case VoteType.Mode:
GameModePreset gameMode = data as GameModePreset;
if (gameMode == null) return;
if (gameMode == null) { return; }
msg.Write(gameMode.Identifier);
break;
case VoteType.EndRound:
if (!(data is bool)) return;
if (!(data is bool)) { return; }
msg.Write((bool)data);
break;
case VoteType.Kick:
@@ -153,12 +153,12 @@ namespace Barotrauma
{
int votes = inc.ReadByte();
string subName = inc.ReadString();
List<Submarine> serversubs = new List<Submarine>();
List<SubmarineInfo> serversubs = new List<SubmarineInfo>();
foreach (GUIComponent item in GameMain.NetLobbyScreen?.SubList?.Content?.Children)
{
if (item.UserData != null && item.UserData is Submarine) serversubs.Add(item.UserData as Submarine);
if (item.UserData != null && item.UserData is SubmarineInfo) { serversubs.Add(item.UserData as SubmarineInfo); }
}
Submarine sub = serversubs.FirstOrDefault(sm => sm.Name == subName);
SubmarineInfo sub = serversubs.FirstOrDefault(s => s.Name == subName);
SetVoteText(GameMain.NetLobbyScreen.SubList, sub, votes);
}
}