Updated to MonoGame 3.6 + Directory refactor

- Barotrauma's projects are in the Barotrauma directory
- All libraries are in the Libraries directory
- MonoGame is now managed by NuGet, rather than referenced from the installed files (TODO: consider using PCL for easier cross-platform development?)
- NuGet libraries are not included in the repo, as getting the latest versions automatically should be preferred
- Removed Content/effects.mgfx as it didn't seem to be used anywhere
- Removed some references to Subsurface directory
- Renamed Launcher2 to Launcher
This commit is contained in:
juanjp600
2017-06-27 09:52:57 -03:00
parent 330b24bcf6
commit 4d225c65f2
1301 changed files with 169 additions and 77952 deletions
@@ -0,0 +1,86 @@
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Barotrauma.Networking
{
partial class BanList
{
private GUIComponent banFrame;
public GUIComponent BanFrame
{
get { return banFrame; }
}
public GUIComponent CreateBanFrame(GUIComponent parent)
{
banFrame = new GUIListBox(new Rectangle(0, 0, 0, 0), "", parent);
foreach (BannedPlayer bannedPlayer in bannedPlayers)
{
GUITextBlock textBlock = new GUITextBlock(
new Rectangle(0, 0, 0, 25),
bannedPlayer.IP + " (" + bannedPlayer.Name + ")",
"",
Alignment.Left, Alignment.Left, banFrame);
textBlock.Padding = new Vector4(10.0f, 10.0f, 0.0f, 0.0f);
textBlock.UserData = banFrame;
var removeButton = new GUIButton(new Rectangle(0, 0, 100, 20), "Remove", Alignment.Right | Alignment.CenterY, "", textBlock);
removeButton.UserData = bannedPlayer;
removeButton.OnClicked = RemoveBan;
if (bannedPlayer.IP.IndexOf(".x") <= -1)
{
var rangeBanButton = new GUIButton(new Rectangle(-100, 0, 100, 20), "Ban range", Alignment.Right | Alignment.CenterY, "", textBlock);
rangeBanButton.UserData = bannedPlayer;
rangeBanButton.OnClicked = RangeBan;
}
}
return banFrame;
}
private bool RemoveBan(GUIButton button, object obj)
{
BannedPlayer banned = obj as BannedPlayer;
if (banned == null) return false;
RemoveBan(banned);
if (banFrame != null)
{
banFrame.Parent.RemoveChild(banFrame);
CreateBanFrame(banFrame.Parent);
}
return true;
}
private bool RangeBan(GUIButton button, object obj)
{
BannedPlayer banned = obj as BannedPlayer;
if (banned == null) return false;
RangeBan(banned);
if (banFrame != null)
{
banFrame.Parent.RemoveChild(banFrame);
CreateBanFrame(banFrame.Parent);
}
return true;
}
private bool CloseFrame(GUIButton button, object obj)
{
banFrame = null;
return true;
}
}
}
@@ -0,0 +1,44 @@
using Barotrauma.Networking;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Barotrauma
{
partial class EntitySpawner : Entity, IServerSerializable
{
public void ClientRead(ServerNetObject type, Lidgren.Network.NetBuffer message, float sendingTime)
{
if (GameMain.Server != null) return;
bool remove = message.ReadBoolean();
if (remove)
{
ushort entityId = message.ReadUInt16();
var entity = FindEntityByID(entityId);
if (entity != null)
{
entity.Remove();
}
}
else
{
switch (message.ReadByte())
{
case (byte)SpawnableType.Item:
Item.ReadSpawnData(message, true);
break;
case (byte)SpawnableType.Character:
Character.ReadSpawnData(message, true);
break;
default:
DebugConsole.ThrowError("Received invalid entity spawn message (unknown spawnable type)");
break;
}
}
}
}
}
@@ -0,0 +1,409 @@
using Lidgren.Network;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;
namespace Barotrauma.Networking
{
class FileReceiver
{
public class FileTransferIn : IDisposable
{
public string FileName
{
get;
private set;
}
public string FilePath
{
get;
private set;
}
public ulong FileSize
{
get;
set;
}
public ulong Received
{
get;
private set;
}
public FileTransferType FileType
{
get;
private set;
}
public FileTransferStatus Status
{
get;
set;
}
public float BytesPerSecond
{
get;
private set;
}
public float Progress
{
get { return Received / (float)FileSize; }
}
public FileStream WriteStream
{
get;
private set;
}
public int TimeStarted
{
get;
private set;
}
public NetConnection Connection
{
get;
private set;
}
public int SequenceChannel;
public FileTransferIn(NetConnection connection, string filePath, FileTransferType fileType)
{
FilePath = filePath;
FileName = Path.GetFileName(FilePath);
FileType = fileType;
Connection = connection;
WriteStream = new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.None);
TimeStarted = Environment.TickCount;
Status = FileTransferStatus.NotStarted;
}
public void ReadBytes(NetIncomingMessage inc)
{
byte[] all = inc.ReadBytes(inc.LengthBytes - inc.PositionInBytes);
Received += (ulong)all.Length;
WriteStream.Write(all, 0, all.Length);
int passed = Environment.TickCount - TimeStarted;
float psec = passed / 1000.0f;
if (GameSettings.VerboseLogging)
{
DebugConsole.Log("Received "+all.Length+" bytes of the file "+FileName+" ("+Received+"/"+FileSize+" received)");
}
BytesPerSecond = Received / psec;
Status = Received >= FileSize ? FileTransferStatus.Finished : FileTransferStatus.Receiving;
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (disposed) return;
if (disposing)
{
if (WriteStream != null)
{
WriteStream.Flush();
WriteStream.Close();
WriteStream.Dispose();
WriteStream = null;
}
}
disposed = true;
}
public void Dispose()
{
Dispose(true);
}
}
const int MaxFileSize = 1000000;
public delegate void OnFinishedDelegate(FileTransferIn fileStreamReceiver);
public OnFinishedDelegate OnFinished;
private List<FileTransferIn> activeTransfers;
private string downloadFolder;
public List<FileTransferIn> ActiveTransfers
{
get { return activeTransfers; }
}
public FileReceiver(string downloadFolder)
{
if (GameMain.Server != null)
{
throw new InvalidOperationException("Creating a file receiver is not allowed when a server is running.");
}
activeTransfers = new List<FileTransferIn>();
this.downloadFolder = downloadFolder;
}
public void ReadMessage(NetIncomingMessage inc)
{
if (GameMain.Server != null)
{
throw new InvalidOperationException("Receiving files when a server is running is not allowed");
}
System.Diagnostics.Debug.Assert(!activeTransfers.Any(t =>
t.Status == FileTransferStatus.Error ||
t.Status == FileTransferStatus.Canceled ||
t.Status == FileTransferStatus.Finished), "List of active file transfers contains entires that should have been removed");
byte transferMessageType = inc.ReadByte();
switch (transferMessageType)
{
case (byte)FileTransferMessageType.Initiate:
var existingTransfer = activeTransfers.Find(t => t.SequenceChannel == inc.SequenceChannel);
if (existingTransfer != null)
{
GameMain.Client.CancelFileTransfer(inc.SequenceChannel);
DebugConsole.ThrowError("File transfer error: file transfer initiated on a sequence channel that's already in use");
return;
}
byte fileType = inc.ReadByte();
ushort chunkLen = inc.ReadUInt16();
ulong fileSize = inc.ReadUInt64();
string fileName = inc.ReadString();
string errorMsg;
if (!ValidateInitialData(fileType, fileName, fileSize, out errorMsg))
{
GameMain.Client.CancelFileTransfer(inc.SequenceChannel);
DebugConsole.ThrowError("File transfer failed (" + errorMsg + ")");
return;
}
if (GameSettings.VerboseLogging)
{
DebugConsole.Log("Received file transfer initiation message: ");
DebugConsole.Log(" File: "+fileName);
DebugConsole.Log(" Size: " + fileSize);
DebugConsole.Log(" Sequence channel: " + inc.SequenceChannel);
}
if (!Directory.Exists(downloadFolder))
{
try
{
Directory.CreateDirectory(downloadFolder);
}
catch (Exception e)
{
DebugConsole.ThrowError("Could not start a file transfer: failed to create the folder \""+downloadFolder+"\".", e);
return;
}
}
var newTransfer = new FileTransferIn(inc.SenderConnection, Path.Combine(downloadFolder, fileName), (FileTransferType)fileType);
newTransfer.SequenceChannel = inc.SequenceChannel;
newTransfer.Status = FileTransferStatus.Receiving;
newTransfer.FileSize = fileSize;
activeTransfers.Add(newTransfer);
break;
case (byte)FileTransferMessageType.Data:
var activeTransfer = activeTransfers.Find(t => t.Connection == inc.SenderConnection && t.SequenceChannel == inc.SequenceChannel);
if (activeTransfer == null)
{
GameMain.Client.CancelFileTransfer(inc.SequenceChannel);
DebugConsole.ThrowError("File transfer error: received data without a transfer initiation message");
return;
}
if (activeTransfer.Received + (ulong)(inc.LengthBytes-inc.PositionInBytes) > activeTransfer.FileSize)
{
GameMain.Client.CancelFileTransfer(inc.SequenceChannel);
DebugConsole.ThrowError("File transfer error: Received more data than expected");
activeTransfer.Status = FileTransferStatus.Error;
StopTransfer(activeTransfer);
return;
}
try
{
activeTransfer.ReadBytes(inc);
}
catch (Exception e)
{
GameMain.Client.CancelFileTransfer(inc.SequenceChannel);
DebugConsole.ThrowError("File transfer error: "+e.Message);
activeTransfer.Status = FileTransferStatus.Error;
StopTransfer(activeTransfer, true);
return;
}
if (activeTransfer.Status == FileTransferStatus.Finished)
{
activeTransfer.Dispose();
string errorMessage = "";
if (ValidateReceivedData(activeTransfer, out errorMessage))
{
OnFinished(activeTransfer);
StopTransfer(activeTransfer);
}
else
{
new GUIMessageBox("File transfer aborted", errorMessage);
activeTransfer.Status = FileTransferStatus.Error;
StopTransfer(activeTransfer, true);
}
}
break;
case (byte)FileTransferMessageType.Cancel:
byte sequenceChannel = inc.ReadByte();
var matchingTransfer = activeTransfers.Find(t => t.Connection == inc.SenderConnection && t.SequenceChannel == sequenceChannel);
if (matchingTransfer != null)
{
new GUIMessageBox("File transfer cancelled", "The server has cancelled the transfer of the file \"" + matchingTransfer.FileName + "\".");
StopTransfer(matchingTransfer);
}
break;
}
}
private bool ValidateInitialData(byte type, string fileName, ulong fileSize, out string errorMessage)
{
errorMessage = "";
if (fileSize > MaxFileSize)
{
errorMessage = "File too large (" + MathUtils.GetBytesReadable((long)fileSize) + ")";
return false;
}
if (!Enum.IsDefined(typeof(FileTransferType), (int)type))
{
errorMessage = "Unknown file type";
return false;
}
if (string.IsNullOrEmpty(fileName) ||
fileName.IndexOfAny(Path.GetInvalidFileNameChars()) > -1)
{
errorMessage = "Illegal characters in file name ''" + fileName + "''";
return false;
}
switch (type)
{
case (byte)FileTransferType.Submarine:
if (Path.GetExtension(fileName) != ".sub")
{
errorMessage = "Wrong file extension ''" + Path.GetExtension(fileName) + "''! (Expected .sub)";
return false;
}
break;
}
return true;
}
private bool ValidateReceivedData(FileTransferIn fileTransfer, out string ErrorMessage)
{
ErrorMessage = "";
switch (fileTransfer.FileType)
{
case FileTransferType.Submarine:
Stream stream = null;
try
{
stream = SaveUtil.DecompressFiletoStream(fileTransfer.FilePath);
}
catch (Exception e)
{
ErrorMessage = "Loading received submarine ''" + fileTransfer.FileName + "'' failed! {" + e.Message + "}";
return false;
}
if (stream == null)
{
ErrorMessage = "Decompressing received submarine file''" + fileTransfer.FilePath + "'' failed!";
return false;
}
try
{
stream.Position = 0;
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Prohibit;
settings.IgnoreProcessingInstructions = true;
using (var reader = XmlReader.Create(stream, settings))
{
while (reader.Read());
}
}
catch
{
stream.Close();
stream.Dispose();
ErrorMessage = "Parsing file ''" + fileTransfer.FilePath + "'' failed! The file may not be a valid submarine file.";
return false;
}
stream.Close();
stream.Dispose();
break;
}
return true;
}
public void StopTransfer(FileTransferIn transfer, bool deleteFile = false)
{
if (transfer.Status != FileTransferStatus.Finished &&
transfer.Status != FileTransferStatus.Error)
{
transfer.Status = FileTransferStatus.Canceled;
}
if (activeTransfers.Contains(transfer)) activeTransfers.Remove(transfer);
transfer.Dispose();
if (deleteFile && File.Exists(transfer.FilePath))
{
try
{
File.Delete(transfer.FilePath);
}
catch (Exception e)
{
DebugConsole.ThrowError("Failed to delete file \""+transfer.FilePath+"\" ("+e.Message+")");
}
}
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,217 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Lidgren.Network;
using Microsoft.Xna.Framework;
using RestSharp;
using Barotrauma.Items.Components;
namespace Barotrauma.Networking
{
partial class GameServer : NetworkMember
{
private NetStats netStats;
private GUIButton showLogButton;
private GUIScrollBar clientListScrollBar;
void InitProjSpecific()
{
//----------------------------------------
var endRoundButton = new GUIButton(new Rectangle(GameMain.GraphicsWidth - 170, 20, 150, 20), "End round", Alignment.TopLeft, "", inGameHUD);
endRoundButton.OnClicked = (btn, userdata) => { EndGame(); return true; };
showLogButton = new GUIButton(new Rectangle(GameMain.GraphicsWidth - 170 - 170, 20, 150, 20), "Server Log", Alignment.TopLeft, "", inGameHUD);
showLogButton.OnClicked = (GUIButton button, object userData) =>
{
if (log.LogFrame == null)
{
log.CreateLogFrame();
}
else
{
log.LogFrame = null;
GUIComponent.KeyboardDispatcher.Subscriber = null;
}
return true;
};
GUIButton settingsButton = new GUIButton(new Rectangle(GameMain.GraphicsWidth - 170 - 170 - 170, 20, 150, 20), "Settings", Alignment.TopLeft, "", inGameHUD);
settingsButton.OnClicked = ToggleSettingsFrame;
settingsButton.UserData = "settingsButton";
//----------------------------------------
}
public override void AddToGUIUpdateList()
{
if (started) base.AddToGUIUpdateList();
if (settingsFrame != null) settingsFrame.AddToGUIUpdateList();
if (log.LogFrame != null) log.LogFrame.AddToGUIUpdateList();
}
public override void Draw(Microsoft.Xna.Framework.Graphics.SpriteBatch spriteBatch)
{
base.Draw(spriteBatch);
if (settingsFrame != null)
{
settingsFrame.Draw(spriteBatch);
}
else if (log.LogFrame != null)
{
log.LogFrame.Draw(spriteBatch);
}
if (!ShowNetStats) return;
GUI.Font.DrawString(spriteBatch, "Unique Events: " + entityEventManager.UniqueEvents.Count, new Vector2(10, 50), Color.White);
int width = 200, height = 300;
int x = GameMain.GraphicsWidth - width, y = (int)(GameMain.GraphicsHeight * 0.3f);
if (clientListScrollBar == null)
{
clientListScrollBar = new GUIScrollBar(new Rectangle(x + width - 10, y, 10, height), "", 1.0f);
}
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);
GUI.SmallFont.DrawString(spriteBatch, "Connections: " + server.ConnectionsCount, new Vector2(x + 10, y + 30), Color.White);
GUI.SmallFont.DrawString(spriteBatch, "Received bytes: " + MathUtils.GetBytesReadable(server.Statistics.ReceivedBytes), new Vector2(x + 10, y + 45), Color.White);
GUI.SmallFont.DrawString(spriteBatch, "Received packets: " + server.Statistics.ReceivedPackets, new Vector2(x + 10, y + 60), Color.White);
GUI.SmallFont.DrawString(spriteBatch, "Sent bytes: " + MathUtils.GetBytesReadable(server.Statistics.SentBytes), new Vector2(x + 10, y + 75), Color.White);
GUI.SmallFont.DrawString(spriteBatch, "Sent packets: " + server.Statistics.SentPackets, new Vector2(x + 10, y + 90), Color.White);
int resentMessages = 0;
int clientListHeight = connectedClients.Count * 40;
float scrollBarHeight = (height - 110) / (float)Math.Max(clientListHeight, 110);
if (clientListScrollBar.BarSize != scrollBarHeight)
{
clientListScrollBar.BarSize = scrollBarHeight;
}
int startY = y + 110;
y = (startY - (int)(clientListScrollBar.BarScroll * (clientListHeight - (height - 110))));
foreach (Client c in connectedClients)
{
Color clientColor = c.Connection.AverageRoundtripTime > 0.3f ? Color.Red : Color.White;
if (y >= startY && y < startY + height - 120)
{
GUI.SmallFont.DrawString(spriteBatch, c.name + " (" + c.Connection.RemoteEndPoint.Address.ToString() + ")", new Vector2(x + 10, y), clientColor);
GUI.SmallFont.DrawString(spriteBatch, "Ping: " + (int)(c.Connection.AverageRoundtripTime * 1000.0f) + " ms", new Vector2(x + 20, y + 10), clientColor);
}
if (y + 25 >= startY && y < startY + height - 130) GUI.SmallFont.DrawString(spriteBatch, "Resent messages: " + c.Connection.Statistics.ResentMessages, new Vector2(x + 20, y + 20), clientColor);
resentMessages += (int)c.Connection.Statistics.ResentMessages;
y += 40;
}
clientListScrollBar.Update(1.0f / 60.0f);
clientListScrollBar.Draw(spriteBatch);
netStats.AddValue(NetStats.NetStatType.ResentMessages, Math.Max(resentMessages, 0));
netStats.AddValue(NetStats.NetStatType.SentBytes, server.Statistics.SentBytes);
netStats.AddValue(NetStats.NetStatType.ReceivedBytes, server.Statistics.ReceivedBytes);
netStats.Draw(spriteBatch, new Rectangle(200, 0, 800, 200), this);
}
private void UpdateFileTransferIndicator(Client client)
{
var transfers = fileSender.ActiveTransfers.FindAll(t => t.Connection == client.Connection);
var clientNameBox = GameMain.NetLobbyScreen.PlayerList.FindChild(client.name);
var clientInfo = clientNameBox.FindChild("filetransfer");
if (clientInfo == null)
{
clientNameBox.ClearChildren();
clientInfo = new GUIFrame(new Rectangle(0, 0, 180, 0), Color.Transparent, Alignment.TopRight, null, clientNameBox);
clientInfo.UserData = "filetransfer";
}
else if (transfers.Count == 0)
{
clientInfo.Parent.RemoveChild(clientInfo);
}
clientInfo.ClearChildren();
var progressBar = new GUIProgressBar(new Rectangle(0, 4, 160, clientInfo.Rect.Height - 8), Color.Green, "", 0.0f, Alignment.Left, clientInfo);
progressBar.IsHorizontal = true;
progressBar.ProgressGetter = () => { return transfers.Sum(t => t.Progress) / transfers.Count; };
var textBlock = new GUITextBlock(new Rectangle(0, 2, 160, 0), "", "", Alignment.TopLeft, Alignment.Left | Alignment.CenterY, clientInfo, true, GUI.SmallFont);
textBlock.TextGetter = () =>
{ return MathUtils.GetBytesReadable(transfers.Sum(t => t.SentOffset)) + " / " + MathUtils.GetBytesReadable(transfers.Sum(t => t.Data.Length)); };
var cancelButton = new GUIButton(new Rectangle(-5, 0, 14, 0), "X", Alignment.Right, "", clientInfo);
cancelButton.OnClicked = (GUIButton button, object userdata) =>
{
transfers.ForEach(t => fileSender.CancelTransfer(t));
return true;
};
}
public override bool SelectCrewCharacter(Character character, GUIComponent crewFrame)
{
if (character == null) return false;
var characterFrame = crewFrame.FindChild("selectedcharacter");
if (character != myCharacter)
{
var banButton = new GUIButton(new Rectangle(0, 0, 100, 20), "Ban", Alignment.BottomRight, "", characterFrame);
banButton.UserData = character.Name;
banButton.OnClicked += GameMain.NetLobbyScreen.BanPlayer;
var rangebanButton = new GUIButton(new Rectangle(0, -25, 100, 20), "Ban range", Alignment.BottomRight, "", characterFrame);
rangebanButton.UserData = character.Name;
rangebanButton.OnClicked += GameMain.NetLobbyScreen.BanPlayerRange;
var kickButton = new GUIButton(new Rectangle(0, 0, 100, 20), "Kick", Alignment.BottomLeft, "", characterFrame);
kickButton.UserData = character.Name;
kickButton.OnClicked += GameMain.NetLobbyScreen.KickPlayer;
}
return true;
}
private GUIMessageBox upnpBox;
void InitUPnP()
{
server.UPnP.ForwardPort(config.Port, "barotrauma");
upnpBox = new GUIMessageBox("Please wait...", "Attempting UPnP port forwarding", new string[] { "Cancel" });
upnpBox.Buttons[0].OnClicked = upnpBox.Close;
}
bool DiscoveringUPnP()
{
return server.UPnP.Status == UPnPStatus.Discovering && GUIMessageBox.VisibleBox == upnpBox;
}
void FinishUPnP()
{
upnpBox.Close(null, null);
}
public bool StartGameClicked(GUIButton button, object obj)
{
return StartGame();
}
}
}
@@ -0,0 +1,534 @@
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace Barotrauma.Networking
{
partial class GameServer : NetworkMember, IPropertyObject
{
private GUIFrame settingsFrame;
private GUIFrame[] settingsTabs;
private int settingsTabIndex;
private void CreateSettingsFrame()
{
settingsFrame = new GUIFrame(new Rectangle(0, 0, GameMain.GraphicsWidth, GameMain.GraphicsHeight), Color.Black * 0.5f, null);
GUIFrame innerFrame = new GUIFrame(new Rectangle(0, 0, 400, 430), null, Alignment.Center, "", settingsFrame);
innerFrame.Padding = new Vector4(20.0f, 20.0f, 20.0f, 20.0f);
new GUITextBlock(new Rectangle(0, -5, 0, 20), "Settings", "", innerFrame, GUI.LargeFont);
string[] tabNames = { "Rounds", "Server", "Banlist", "Whitelist" };
settingsTabs = new GUIFrame[tabNames.Length];
for (int i = 0; i < tabNames.Length; i++)
{
settingsTabs[i] = new GUIFrame(new Rectangle(0, 15, 0, innerFrame.Rect.Height - 120), null, Alignment.Center, "InnerFrame", innerFrame);
settingsTabs[i].Padding = new Vector4(40.0f, 20.0f, 40.0f, 40.0f);
var tabButton = new GUIButton(new Rectangle(85 * i, 35, 80, 20), tabNames[i], "", innerFrame);
tabButton.UserData = i;
tabButton.OnClicked = SelectSettingsTab;
}
settingsTabs[2].Padding = Vector4.Zero;
SelectSettingsTab(null, 0);
var closeButton = new GUIButton(new Rectangle(10, 0, 100, 20), "Close", Alignment.BottomRight, "", innerFrame);
closeButton.OnClicked = ToggleSettingsFrame;
//--------------------------------------------------------------------------------
// game settings
//--------------------------------------------------------------------------------
int y = 0;
settingsTabs[0].Padding = new Vector4(40.0f, 5.0f, 40.0f, 40.0f);
new GUITextBlock(new Rectangle(0, y, 100, 20), "Submarine selection:", "", settingsTabs[0]);
var selectionFrame = new GUIFrame(new Rectangle(0, y + 20, 300, 20), null, settingsTabs[0]);
for (int i = 0; i < 3; i++)
{
var selectionTick = new GUITickBox(new Rectangle(i * 100, 0, 20, 20), ((SelectionMode)i).ToString(), Alignment.Left, selectionFrame);
selectionTick.Selected = i == (int)subSelectionMode;
selectionTick.OnSelected = SwitchSubSelection;
selectionTick.UserData = (SelectionMode)i;
}
y += 45;
new GUITextBlock(new Rectangle(0, y, 100, 20), "Mode selection:", "", settingsTabs[0]);
selectionFrame = new GUIFrame(new Rectangle(0, y + 20, 300, 20), null, settingsTabs[0]);
for (int i = 0; i < 3; i++)
{
var selectionTick = new GUITickBox(new Rectangle(i * 100, 0, 20, 20), ((SelectionMode)i).ToString(), Alignment.Left, selectionFrame);
selectionTick.Selected = i == (int)modeSelectionMode;
selectionTick.OnSelected = SwitchModeSelection;
selectionTick.UserData = (SelectionMode)i;
}
y += 60;
var endBox = new GUITickBox(new Rectangle(0, y, 20, 20), "End round when destination reached", Alignment.Left, settingsTabs[0]);
endBox.Selected = EndRoundAtLevelEnd;
endBox.OnSelected = (GUITickBox) => { EndRoundAtLevelEnd = GUITickBox.Selected; return true; };
y += 25;
var endVoteBox = new GUITickBox(new Rectangle(0, y, 20, 20), "End round by voting", Alignment.Left, settingsTabs[0]);
endVoteBox.Selected = Voting.AllowEndVoting;
endVoteBox.OnSelected = (GUITickBox) =>
{
Voting.AllowEndVoting = !Voting.AllowEndVoting;
GameMain.Server.UpdateVoteStatus();
return true;
};
var votesRequiredText = new GUITextBlock(new Rectangle(20, y + 15, 20, 20), "Votes required: 50 %", "", settingsTabs[0], GUI.SmallFont);
var votesRequiredSlider = new GUIScrollBar(new Rectangle(150, y + 22, 100, 15), "", 0.1f, settingsTabs[0]);
votesRequiredSlider.UserData = votesRequiredText;
votesRequiredSlider.Step = 0.2f;
votesRequiredSlider.BarScroll = (EndVoteRequiredRatio - 0.5f) * 2.0f;
votesRequiredSlider.OnMoved = (GUIScrollBar scrollBar, float barScroll) =>
{
GUITextBlock voteText = scrollBar.UserData as GUITextBlock;
EndVoteRequiredRatio = barScroll / 2.0f + 0.5f;
voteText.Text = "Votes required: " + (int)MathUtils.Round(EndVoteRequiredRatio * 100.0f, 10.0f) + " %";
return true;
};
votesRequiredSlider.OnMoved(votesRequiredSlider, votesRequiredSlider.BarScroll);
y += 35;
var respawnBox = new GUITickBox(new Rectangle(0, y, 20, 20), "Allow respawning", Alignment.Left, settingsTabs[0]);
respawnBox.Selected = AllowRespawn;
respawnBox.OnSelected = (GUITickBox) =>
{
AllowRespawn = !AllowRespawn;
return true;
};
var respawnIntervalText = new GUITextBlock(new Rectangle(20, y + 13, 20, 20), "Respawn interval", "", settingsTabs[0], GUI.SmallFont);
var respawnIntervalSlider = new GUIScrollBar(new Rectangle(150, y + 20, 100, 15), "", 0.1f, settingsTabs[0]);
respawnIntervalSlider.UserData = respawnIntervalText;
respawnIntervalSlider.Step = 0.05f;
respawnIntervalSlider.BarScroll = RespawnInterval / 600.0f;
respawnIntervalSlider.OnMoved = (GUIScrollBar scrollBar, float barScroll) =>
{
GUITextBlock text = scrollBar.UserData as GUITextBlock;
RespawnInterval = Math.Max(barScroll * 600.0f, 10.0f);
text.Text = "Interval: " + ToolBox.SecondsToReadableTime(RespawnInterval);
return true;
};
respawnIntervalSlider.OnMoved(respawnIntervalSlider, respawnIntervalSlider.BarScroll);
y += 35;
var minRespawnText = new GUITextBlock(new Rectangle(0, y, 200, 20), "Minimum players to respawn", "", settingsTabs[0]);
minRespawnText.ToolTip = "What percentage of players has to be dead/spectating until a respawn shuttle is dispatched";
var minRespawnSlider = new GUIScrollBar(new Rectangle(150, y + 20, 100, 15), "", 0.1f, settingsTabs[0]);
minRespawnSlider.ToolTip = minRespawnText.ToolTip;
minRespawnSlider.UserData = minRespawnText;
minRespawnSlider.Step = 0.1f;
minRespawnSlider.BarScroll = MinRespawnRatio;
minRespawnSlider.OnMoved = (GUIScrollBar scrollBar, float barScroll) =>
{
GUITextBlock txt = scrollBar.UserData as GUITextBlock;
MinRespawnRatio = barScroll;
txt.Text = "Minimum players to respawn: " + (int)MathUtils.Round(MinRespawnRatio * 100.0f, 10.0f) + " %";
return true;
};
minRespawnSlider.OnMoved(minRespawnSlider, MinRespawnRatio);
y += 30;
var respawnDurationText = new GUITextBlock(new Rectangle(0, y, 200, 20), "Duration of respawn transport", "", settingsTabs[0]);
respawnDurationText.ToolTip = "The amount of time respawned players have to navigate the respawn shuttle to the main submarine. " +
"After the duration expires, the shuttle will automatically head back out of the level.";
var respawnDurationSlider = new GUIScrollBar(new Rectangle(150, y + 20, 100, 15), "", 0.1f, settingsTabs[0]);
respawnDurationSlider.ToolTip = minRespawnText.ToolTip;
respawnDurationSlider.UserData = respawnDurationText;
respawnDurationSlider.Step = 0.1f;
respawnDurationSlider.BarScroll = MaxTransportTime <= 0.0f ? 1.0f : (MaxTransportTime - 60.0f) / 600.0f;
respawnDurationSlider.OnMoved = (GUIScrollBar scrollBar, float barScroll) =>
{
GUITextBlock txt = scrollBar.UserData as GUITextBlock;
if (barScroll == 1.0f)
{
MaxTransportTime = 0;
txt.Text = "Duration of respawn transport: unlimited";
}
else
{
MaxTransportTime = barScroll * 600.0f + 60.0f;
txt.Text = "Duration of respawn transport: " + ToolBox.SecondsToReadableTime(MaxTransportTime);
}
return true;
};
respawnDurationSlider.OnMoved(respawnDurationSlider, respawnDurationSlider.BarScroll);
y += 35;
var monsterButton = new GUIButton(new Rectangle(0, y, 130, 20), "Monster Spawns", "", settingsTabs[0]);
monsterButton.Enabled = !GameStarted;
var monsterFrame = new GUIListBox(new Rectangle(-290, 60, 280, 250), "", settingsTabs[0]);
monsterFrame.Visible = false;
monsterButton.UserData = monsterFrame;
monsterButton.OnClicked = (button, obj) =>
{
if (gameStarted)
{
((GUIComponent)obj).Visible = false;
button.Enabled = false;
return true;
}
((GUIComponent)obj).Visible = !((GUIComponent)obj).Visible;
return true;
};
List<string> monsterNames = monsterEnabled.Keys.ToList();
foreach (string s in monsterNames)
{
GUITextBlock textBlock = new GUITextBlock(
new Rectangle(0, 0, 260, 25),
s,
"",
Alignment.Left, Alignment.Left, monsterFrame);
textBlock.Padding = new Vector4(35.0f, 3.0f, 0.0f, 0.0f);
textBlock.UserData = monsterFrame;
textBlock.CanBeFocused = false;
var monsterEnabledBox = new GUITickBox(new Rectangle(-25, 0, 20, 20), "", Alignment.Left, textBlock);
monsterEnabledBox.Selected = monsterEnabled[s];
monsterEnabledBox.OnSelected = (GUITickBox) =>
{
if (gameStarted)
{
monsterFrame.Visible = false;
monsterButton.Enabled = false;
return true;
}
monsterEnabled[s] = !monsterEnabled[s];
return true;
};
}
var cargoButton = new GUIButton(new Rectangle(160, y, 130, 20), "Additional Cargo", "", settingsTabs[0]);
cargoButton.Enabled = !GameStarted;
var cargoFrame = new GUIListBox(new Rectangle(300, 60, 280, 250), "", settingsTabs[0]);
cargoFrame.Visible = false;
cargoButton.UserData = cargoFrame;
cargoButton.OnClicked = (button, obj) =>
{
if (gameStarted)
{
((GUIComponent)obj).Visible = false;
button.Enabled = false;
return true;
}
((GUIComponent)obj).Visible = !((GUIComponent)obj).Visible;
return true;
};
foreach (MapEntityPrefab pf in MapEntityPrefab.list)
{
if (!(pf is ItemPrefab) || (pf.Price <= 0.0f && !pf.tags.Contains("smallitem"))) continue;
GUITextBlock textBlock = new GUITextBlock(
new Rectangle(0, 0, 260, 25),
pf.Name, "",
Alignment.Left, Alignment.CenterLeft, cargoFrame, false, GUI.SmallFont);
textBlock.Padding = new Vector4(40.0f, 3.0f, 0.0f, 0.0f);
textBlock.UserData = cargoFrame;
textBlock.CanBeFocused = false;
if (pf.sprite != null)
{
float scale = Math.Min(Math.Min(30.0f / pf.sprite.SourceRect.Width, 30.0f / pf.sprite.SourceRect.Height), 1.0f);
GUIImage img = new GUIImage(new Rectangle(-20 - (int)(pf.sprite.SourceRect.Width * scale * 0.5f), 12 - (int)(pf.sprite.SourceRect.Height * scale * 0.5f), 40, 40), pf.sprite, Alignment.Left, textBlock);
img.Color = pf.SpriteColor;
img.Scale = scale;
}
int cargoVal = 0;
extraCargo.TryGetValue(pf.Name, out cargoVal);
var countText = new GUITextBlock(
new Rectangle(160, 0, 55, 25),
cargoVal.ToString(),
"",
Alignment.Left, Alignment.Center, textBlock);
var incButton = new GUIButton(new Rectangle(200, 5, 15, 15), ">", "", textBlock);
incButton.UserData = countText;
incButton.OnClicked = (button, obj) =>
{
int val;
if (extraCargo.TryGetValue(pf.Name, out val))
{
extraCargo[pf.Name]++; val = extraCargo[pf.Name];
}
else
{
extraCargo.Add(pf.Name, 1); val = 1;
}
((GUITextBlock)obj).Text = val.ToString();
((GUITextBlock)obj).SetTextPos();
return true;
};
var decButton = new GUIButton(new Rectangle(160, 5, 15, 15), "<", "", textBlock);
decButton.UserData = countText;
decButton.OnClicked = (button, obj) =>
{
int val;
if (extraCargo.TryGetValue(pf.Name, out val))
{
extraCargo[pf.Name]--;
val = extraCargo[pf.Name];
if (val <= 0)
{
extraCargo.Remove(pf.Name);
val = 0;
}
((GUITextBlock)obj).Text = val.ToString();
((GUITextBlock)obj).SetTextPos();
}
return true;
};
}
//--------------------------------------------------------------------------------
// server settings
//--------------------------------------------------------------------------------
y = 0;
var startIntervalText = new GUITextBlock(new Rectangle(-10, y, 100, 20), "Autorestart delay", "", settingsTabs[1]);
var startIntervalSlider = new GUIScrollBar(new Rectangle(10, y + 22, 100, 15), "", 0.1f, settingsTabs[1]);
startIntervalSlider.UserData = startIntervalText;
startIntervalSlider.Step = 0.05f;
startIntervalSlider.BarScroll = AutoRestartInterval / 300.0f;
startIntervalSlider.OnMoved = (GUIScrollBar scrollBar, float barScroll) =>
{
GUITextBlock text = scrollBar.UserData as GUITextBlock;
AutoRestartInterval = Math.Max(barScroll * 300.0f, 10.0f);
text.Text = "Autorestart delay: " + ToolBox.SecondsToReadableTime(AutoRestartInterval);
return true;
};
startIntervalSlider.OnMoved(startIntervalSlider, startIntervalSlider.BarScroll);
y += 45;
var allowSpecBox = new GUITickBox(new Rectangle(0, y, 20, 20), "Allow spectating", Alignment.Left, settingsTabs[1]);
allowSpecBox.Selected = AllowSpectating;
allowSpecBox.OnSelected = (GUITickBox) =>
{
AllowSpectating = GUITickBox.Selected;
return true;
};
y += 40;
var voteKickBox = new GUITickBox(new Rectangle(0, y, 20, 20), "Allow vote kicking", Alignment.Left, settingsTabs[1]);
voteKickBox.Selected = Voting.AllowVoteKick;
voteKickBox.OnSelected = (GUITickBox) =>
{
Voting.AllowVoteKick = !Voting.AllowVoteKick;
GameMain.Server.UpdateVoteStatus();
return true;
};
var kickVotesRequiredText = new GUITextBlock(new Rectangle(20, y + 20, 20, 20), "Votes required: 50 %", "", settingsTabs[1], GUI.SmallFont);
var kickVoteSlider = new GUIScrollBar(new Rectangle(150, y + 22, 100, 15), "", 0.1f, settingsTabs[1]);
kickVoteSlider.UserData = kickVotesRequiredText;
kickVoteSlider.Step = 0.2f;
kickVoteSlider.BarScroll = (KickVoteRequiredRatio - 0.5f) * 2.0f;
kickVoteSlider.OnMoved = (GUIScrollBar scrollBar, float barScroll) =>
{
GUITextBlock voteText = scrollBar.UserData as GUITextBlock;
KickVoteRequiredRatio = barScroll / 2.0f + 0.5f;
voteText.Text = "Votes required: " + (int)MathUtils.Round(KickVoteRequiredRatio * 100.0f, 10.0f) + " %";
return true;
};
kickVoteSlider.OnMoved(kickVoteSlider, kickVoteSlider.BarScroll);
y += 45;
var shareSubsBox = new GUITickBox(new Rectangle(0, y, 20, 20), "Share submarine files with players", Alignment.Left, settingsTabs[1]);
shareSubsBox.Selected = AllowFileTransfers;
shareSubsBox.OnSelected = (GUITickBox) =>
{
AllowFileTransfers = GUITickBox.Selected;
return true;
};
y += 40;
var randomizeLevelBox = new GUITickBox(new Rectangle(0, y, 20, 20), "Randomize level seed between rounds", Alignment.Left, settingsTabs[1]);
randomizeLevelBox.Selected = RandomizeSeed;
randomizeLevelBox.OnSelected = (GUITickBox) =>
{
RandomizeSeed = GUITickBox.Selected;
return true;
};
y += 40;
var saveLogsBox = new GUITickBox(new Rectangle(0, y, 20, 20), "Save server logs", Alignment.Left, settingsTabs[1]);
saveLogsBox.Selected = SaveServerLogs;
saveLogsBox.OnSelected = (GUITickBox) =>
{
SaveServerLogs = GUITickBox.Selected;
showLogButton.Visible = SaveServerLogs;
return true;
};
//--------------------------------------------------------------------------------
// banlist
//--------------------------------------------------------------------------------
banList.CreateBanFrame(settingsTabs[2]);
//--------------------------------------------------------------------------------
// whitelist
//--------------------------------------------------------------------------------
whitelist.CreateWhiteListFrame(settingsTabs[3]);
}
private bool SwitchSubSelection(GUITickBox tickBox)
{
subSelectionMode = (SelectionMode)tickBox.UserData;
foreach (GUIComponent otherTickBox in tickBox.Parent.children)
{
if (otherTickBox == tickBox) continue;
((GUITickBox)otherTickBox).Selected = false;
}
Voting.AllowSubVoting = subSelectionMode == SelectionMode.Vote;
if (subSelectionMode == SelectionMode.Random)
{
GameMain.NetLobbyScreen.SubList.Select(Rand.Range(0, GameMain.NetLobbyScreen.SubList.CountChildren));
}
return true;
}
private bool SelectSettingsTab(GUIButton button, object obj)
{
settingsTabIndex = (int)obj;
for (int i = 0; i < settingsTabs.Length; i++)
{
settingsTabs[i].Visible = i == settingsTabIndex;
}
return true;
}
private bool SwitchModeSelection(GUITickBox tickBox)
{
modeSelectionMode = (SelectionMode)tickBox.UserData;
foreach (GUIComponent otherTickBox in tickBox.Parent.children)
{
if (otherTickBox == tickBox) continue;
((GUITickBox)otherTickBox).Selected = false;
}
Voting.AllowModeVoting = modeSelectionMode == SelectionMode.Vote;
if (modeSelectionMode == SelectionMode.Random)
{
GameMain.NetLobbyScreen.ModeList.Select(Rand.Range(0, GameMain.NetLobbyScreen.ModeList.CountChildren));
}
return true;
}
public bool ToggleSettingsFrame(GUIButton button, object obj)
{
if (settingsFrame == null)
{
CreateSettingsFrame();
}
else
{
settingsFrame = null;
SaveSettings();
}
return false;
}
public void ManagePlayersFrame(GUIFrame infoFrame)
{
GUIListBox cList = new GUIListBox(new Rectangle(0, 0, 0, 300), Color.White * 0.7f, "", infoFrame);
cList.Padding = new Vector4(10.0f, 10.0f, 10.0f, 10.0f);
//crewList.OnSelected = SelectCrewCharacter;
foreach (Client c in ConnectedClients)
{
GUIFrame frame = new GUIFrame(new Rectangle(0, 0, 0, 40), Color.Transparent, null, cList);
frame.Padding = new Vector4(5.0f, 5.0f, 5.0f, 5.0f);
frame.Color = (c.inGame && c.Character != null && !c.Character.IsDead) ? Color.Gold * 0.2f : Color.Transparent;
frame.HoverColor = Color.LightGray * 0.5f;
frame.SelectedColor = Color.Gold * 0.5f;
GUITextBlock textBlock = new GUITextBlock(
new Rectangle(40, 0, 0, 25),
c.name + " (" + c.Connection.RemoteEndPoint.Address.ToString() + ")",
Color.Transparent, Color.White,
Alignment.Left, Alignment.Left,
null, frame);
var banButton = new GUIButton(new Rectangle(-110, 0, 100, 20), "Ban", Alignment.Right | Alignment.CenterY, "", frame);
banButton.UserData = c.name;
banButton.OnClicked = GameMain.NetLobbyScreen.BanPlayer;
var rangebanButton = new GUIButton(new Rectangle(-220, 0, 100, 20), "Ban range", Alignment.Right | Alignment.CenterY, "", frame);
rangebanButton.UserData = c.name;
rangebanButton.OnClicked = GameMain.NetLobbyScreen.BanPlayerRange;
var kickButton = new GUIButton(new Rectangle(0, 0, 100, 20), "Kick", Alignment.Right | Alignment.CenterY, "", frame);
kickButton.UserData = c.name;
kickButton.OnClicked = GameMain.NetLobbyScreen.KickPlayer;
textBlock.Padding = new Vector4(5.0f, 0.0f, 5.0f, 0.0f);
}
}
}
}
@@ -0,0 +1,227 @@
using Lidgren.Network;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Barotrauma.Networking
{
class ClientEntityEventManager : NetEntityEventManager
{
private List<ClientEntityEvent> events;
private UInt16 ID;
private GameClient thisClient;
//when was a specific entity event last sent to the client
// key = event id, value = NetTime.Now when sending
public Dictionary<UInt16, float> eventLastSent;
public UInt16 LastReceivedID
{
get { return lastReceivedID; }
}
private UInt16 lastReceivedID;
public ClientEntityEventManager(GameClient client)
{
events = new List<ClientEntityEvent>();
eventLastSent = new Dictionary<UInt16, float>();
thisClient = client;
}
public void CreateEvent(IClientSerializable entity, object[] extraData = null)
{
if (GameMain.Client == null || GameMain.Client.Character == null) return;
if (!(entity is Entity))
{
DebugConsole.ThrowError("Can't create an entity event for " + entity + "!");
return;
}
ID++;
var newEvent = new ClientEntityEvent(entity, ID);
newEvent.CharacterStateID = GameMain.Client.Character.LastNetworkUpdateID;
if (extraData != null) newEvent.SetData(extraData);
events.Add(newEvent);
}
public void Write(NetOutgoingMessage msg, NetConnection serverConnection)
{
if (events.Count == 0 || serverConnection == null) return;
List<NetEntityEvent> eventsToSync = new List<NetEntityEvent>();
//find the index of the first event the server hasn't received
int startIndex = events.Count;
while (startIndex > 0 &&
NetIdUtils.IdMoreRecent(events[startIndex-1].ID,thisClient.LastSentEntityEventID))
{
startIndex--;
}
for (int i = startIndex; i < events.Count; i++)
{
//find the first event that hasn't been sent in 1.5 * roundtriptime or at all
float lastSent = 0;
eventLastSent.TryGetValue(events[i].ID, out lastSent);
if (lastSent > NetTime.Now - serverConnection.AverageRoundtripTime * 1.5f)
{
continue;
}
eventsToSync.AddRange(events.GetRange(i, events.Count - i));
break;
}
if (eventsToSync.Count == 0) return;
//too many events for one packet
if (eventsToSync.Count > MaxEventsPerWrite)
{
eventsToSync.RemoveRange(MaxEventsPerWrite, eventsToSync.Count - MaxEventsPerWrite);
}
if (eventsToSync.Count == 0) return;
foreach (NetEntityEvent entityEvent in eventsToSync)
{
eventLastSent[entityEvent.ID] = (float)NetTime.Now;
}
msg.Write((byte)ClientNetObject.ENTITY_STATE);
Write(msg, eventsToSync);
}
private UInt16? firstNewID;
/// <summary>
/// Read the events from the message, ignoring ones we've already received
/// </summary>
public void Read(ServerNetObject type, NetIncomingMessage msg, float sendingTime)
{
UInt16 unreceivedEntityEventCount = 0;
if (type == ServerNetObject.ENTITY_EVENT_INITIAL)
{
unreceivedEntityEventCount = msg.ReadUInt16();
firstNewID = msg.ReadUInt16();
if (GameSettings.VerboseLogging)
{
DebugConsole.NewMessage(
"received midround syncing msg, unreceived: " + unreceivedEntityEventCount +
", first new ID: " + firstNewID, Microsoft.Xna.Framework.Color.Yellow);
}
}
else if (firstNewID != null)
{
if (GameSettings.VerboseLogging)
{
DebugConsole.NewMessage("midround syncing complete, switching to ID " + (UInt16) (firstNewID - 1),
Microsoft.Xna.Framework.Color.Yellow);
}
lastReceivedID = (UInt16)(firstNewID - 1);
firstNewID = null;
}
UInt16 firstEventID = msg.ReadUInt16();
int eventCount = msg.ReadByte();
for (int i = 0; i < eventCount; i++)
{
UInt16 thisEventID = (UInt16)(firstEventID + (UInt16)i);
UInt16 entityID = msg.ReadUInt16();
if (entityID == 0 && thisEventID == (UInt16)(lastReceivedID + 1))
{
msg.ReadPadBits();
lastReceivedID++;
continue;
}
byte msgLength = msg.ReadByte();
IServerSerializable entity = Entity.FindEntityByID(entityID) as IServerSerializable;
//skip the event if we've already received it or if the entity isn't found
if (thisEventID != (UInt16)(lastReceivedID + 1) || entity == null)
{
if (GameSettings.VerboseLogging)
{
if (thisEventID != (UInt16) (lastReceivedID + 1))
{
DebugConsole.NewMessage(
"received msg " + thisEventID + " (waiting for " + (lastReceivedID + 1) + ")",
thisEventID < lastReceivedID + 1
? Microsoft.Xna.Framework.Color.Yellow
: Microsoft.Xna.Framework.Color.Red);
}
else if (entity == null)
{
DebugConsole.NewMessage(
"received msg " + thisEventID + ", entity " + entityID + " not found",
Microsoft.Xna.Framework.Color.Red);
}
}
msg.Position += msgLength * 8;
}
else
{
long msgPosition = msg.Position;
if (GameSettings.VerboseLogging)
{
DebugConsole.NewMessage("received msg " + thisEventID + " (" + entity.ToString() + ")",
Microsoft.Xna.Framework.Color.Green);
}
lastReceivedID++;
try
{
ReadEvent(msg, entity, sendingTime);
}
catch (Exception e)
{
if (GameSettings.VerboseLogging)
{
DebugConsole.ThrowError("Failed to read event for entity \"" + entity.ToString() + "\"!", e);
}
msg.Position = msgPosition + msgLength * 8;
}
}
msg.ReadPadBits();
}
}
protected override void WriteEvent(NetBuffer buffer, NetEntityEvent entityEvent, Client recipient = null)
{
var clientEvent = entityEvent as ClientEntityEvent;
if (clientEvent == null) return;
clientEvent.Write(buffer);
}
protected void ReadEvent(NetIncomingMessage buffer, IServerSerializable entity, float sendingTime)
{
entity.ClientRead(ServerNetObject.ENTITY_EVENT, buffer, sendingTime);
}
public void Clear()
{
ID = 0;
lastReceivedID = 0;
firstNewID = null;
events.Clear();
eventLastSent.Clear();
}
}
}
@@ -0,0 +1,24 @@
using Lidgren.Network;
using System;
namespace Barotrauma.Networking
{
class ClientEntityEvent : NetEntityEvent
{
private IClientSerializable serializable;
public UInt16 CharacterStateID;
public ClientEntityEvent(IClientSerializable entity, UInt16 id)
: base(entity, id)
{
serializable = entity;
}
public void Write(NetBuffer msg)
{
msg.Write(CharacterStateID);
serializable.ClientWrite(msg, Data);
}
}
}
@@ -0,0 +1,177 @@
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Barotrauma.Networking
{
class NetStats
{
public enum NetStatType
{
SentBytes = 0,
ReceivedBytes = 1,
ResentMessages = 2
}
private Graph[] graphs;
private float[] totalValue;
private float[] lastValue;
const float UpdateInterval = 0.1f;
float updateTimer;
public NetStats()
{
graphs = new Graph[3];
totalValue = new float[3];
lastValue = new float[3];
for (int i = 0; i < 3; i++ )
{
graphs[i] = new Graph();
}
}
public void AddValue(NetStatType statType, float value)
{
float valueChange = value - lastValue[(int)statType];
totalValue[(int)statType] += valueChange;
lastValue[(int)statType] = value;
}
public void Update(float deltaTime)
{
updateTimer -= deltaTime;
if (updateTimer > 0.0f) return;
for (int i = 0; i<3; i++)
{
graphs[i].Update(totalValue[i] / UpdateInterval);
totalValue[i] = 0.0f;
}
updateTimer = UpdateInterval;
}
public void Draw(SpriteBatch spriteBatch, Rectangle rect, GameServer server)
{
GUI.DrawRectangle(spriteBatch, rect, Color.Black*0.4f, true);
graphs[(int)NetStatType.ReceivedBytes].Draw(spriteBatch, rect, null, 0.0f, Color.Cyan);
graphs[(int)NetStatType.SentBytes].Draw(spriteBatch, rect, null, 0.0f, Color.Orange);
graphs[(int)NetStatType.ResentMessages].Draw(spriteBatch, rect, null, 0.0f, Color.Red);
GUI.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.X + 10, rect.Y + 10), Color.Cyan);
GUI.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.X + 10, rect.Y + 30), Color.Orange);
GUI.SmallFont.DrawString(spriteBatch, "Peak resent: " + graphs[(int)NetStatType.ResentMessages].LargestValue() + " messages/s",
new Vector2(rect.X + 10, rect.Y + 50), Color.Red);
#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), Color.Red);
y += 15;
}
#endif
}
}
class Graph
{
public const int ArraySize = 100;
private float[] values;
public Graph()
{
values = new float[ArraySize];
}
public float LargestValue()
{
float maxValue = 0.0f;
for (int i = 0; i < values.Length; i++)
{
if (values[i] > maxValue) maxValue = values[i];
}
return maxValue;
}
public float Average()
{
return values.Length == 0 ? 0.0f : values.Average();
}
public void Update(float newValue)
{
for (int i = values.Length-1; i > 0; i--)
{
values[i] = values[i - 1];
}
values[0] = newValue;
}
public void Draw(SpriteBatch spriteBatch, Rectangle rect, float? maxVal, float xOffset, Color color)
{
float graphMaxVal = 1.0f;
if (maxVal == null)
{
graphMaxVal = LargestValue();
}
else if (maxVal > 0.0f)
{
graphMaxVal = (float)maxVal;
}
GUI.DrawRectangle(spriteBatch, rect, Color.White);
if (values.Length == 0) return;
float lineWidth = (float)rect.Width / (float)(values.Length - 2);
float yScale = (float)rect.Height / graphMaxVal;
Vector2 prevPoint = new Vector2(rect.Right, rect.Bottom - (values[1] + (values[0] - values[1]) * xOffset) * yScale);
float currX = rect.Right - ((xOffset - 1.0f) * lineWidth);
for (int i = 1; i < values.Length - 1; i++)
{
currX -= lineWidth;
Vector2 newPoint = new Vector2(currX, rect.Bottom - values[i] * yScale);
GUI.DrawLine(spriteBatch, prevPoint, newPoint - new Vector2(1.0f, 0), color);
prevPoint = newPoint;
}
Vector2 lastPoint = new Vector2(rect.X,
rect.Bottom - (values[values.Length - 1] + (values[values.Length - 2] - values[values.Length - 1]) * xOffset) * yScale);
GUI.DrawLine(spriteBatch, prevPoint, lastPoint, color);
}
}
}
@@ -0,0 +1,165 @@
using System;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.Collections.Generic;
using Lidgren.Network;
using Barotrauma.Items.Components;
namespace Barotrauma.Networking
{
abstract partial class NetworkMember
{
protected CharacterInfo characterInfo;
protected Character myCharacter;
public CharacterInfo CharacterInfo
{
get { return characterInfo; }
set { characterInfo = value; }
}
public Character Character
{
get { return myCharacter; }
set { myCharacter = value; }
}
protected GUIFrame inGameHUD;
protected GUIListBox chatBox;
protected GUITextBox chatMsgBox;
public GUIFrame InGameHUD
{
get { return inGameHUD; }
}
private void InitProjSpecific()
{
inGameHUD = new GUIFrame(new Rectangle(0, 0, 0, 0), null, null);
inGameHUD.CanBeFocused = false;
int width = (int)MathHelper.Clamp(GameMain.GraphicsWidth * 0.35f, 350, 500);
int height = (int)MathHelper.Clamp(GameMain.GraphicsHeight * 0.15f, 100, 200);
chatBox = new GUIListBox(new Rectangle(
GameMain.GraphicsWidth - 20 - width,
GameMain.GraphicsHeight - 40 - 25 - height,
width, height),
Color.White * 0.5f, "", inGameHUD);
chatBox.Padding = Vector4.Zero;
chatMsgBox = new GUITextBox(
new Rectangle(chatBox.Rect.X, chatBox.Rect.Y + chatBox.Rect.Height + 20, chatBox.Rect.Width, 25),
Color.White * 0.5f, Color.Black, Alignment.TopLeft, Alignment.Left, "", inGameHUD);
chatMsgBox.Font = GUI.SmallFont;
chatMsgBox.MaxTextLength = ChatMessage.MaxLength;
chatMsgBox.Padding = Vector4.Zero;
chatMsgBox.OnEnterPressed = EnterChatMessage;
chatMsgBox.OnTextChanged = TypingChatMessage;
}
public bool TypingChatMessage(GUITextBox textBox, string text)
{
string tempStr;
string command = ChatMessage.GetChatMessageCommand(text, out tempStr);
switch (command)
{
case "r":
case "radio":
textBox.TextColor = ChatMessage.MessageColor[(int)ChatMessageType.Radio];
break;
case "d":
case "dead":
textBox.TextColor = ChatMessage.MessageColor[(int)ChatMessageType.Dead];
break;
default:
textBox.TextColor = ChatMessage.MessageColor[(int)ChatMessageType.Default];
break;
}
return true;
}
public bool EnterChatMessage(GUITextBox textBox, string message)
{
textBox.TextColor = ChatMessage.MessageColor[(int)ChatMessageType.Default];
if (string.IsNullOrWhiteSpace(message)) return false;
if (this == GameMain.Server)
{
GameMain.Server.SendChatMessage(message, null, null);
}
else if (this == GameMain.Client)
{
GameMain.Client.SendChatMessage(message);
}
if (textBox == chatMsgBox) textBox.Deselect();
return true;
}
public virtual void AddToGUIUpdateList()
{
if (gameStarted && Screen.Selected == GameMain.GameScreen)
{
inGameHUD.AddToGUIUpdateList();
}
}
public virtual void Draw(Microsoft.Xna.Framework.Graphics.SpriteBatch spriteBatch)
{
if (!gameStarted || Screen.Selected != GameMain.GameScreen) return;
GameMain.GameSession.CrewManager.Draw(spriteBatch);
inGameHUD.Draw(spriteBatch);
if (EndVoteCount > 0)
{
if (GameMain.NetworkMember.myCharacter == null)
{
GUI.DrawString(spriteBatch, new Vector2(GameMain.GraphicsWidth - 180.0f, 40),
"Votes to end the round (y/n): " + EndVoteCount + "/" + (EndVoteMax - EndVoteCount), Color.White, null, 0, GUI.SmallFont);
}
else
{
GUI.DrawString(spriteBatch, new Vector2(GameMain.GraphicsWidth - 140.0f, 40),
"Votes (y/n): " + EndVoteCount + "/" + (EndVoteMax - EndVoteCount), Color.White, null, 0, GUI.SmallFont);
}
}
if (respawnManager != null)
{
string respawnInfo = "";
if (respawnManager.CurrentState == RespawnManager.State.Waiting &&
respawnManager.CountdownStarted)
{
respawnInfo = respawnManager.RespawnTimer <= 0.0f ? "" : "Respawn Shuttle dispatching in " + ToolBox.SecondsToReadableTime(respawnManager.RespawnTimer);
}
else if (respawnManager.CurrentState == RespawnManager.State.Transporting)
{
respawnInfo = respawnManager.TransportTimer <= 0.0f ? "" : "Shuttle leaving in " + ToolBox.SecondsToReadableTime(respawnManager.TransportTimer);
}
if (!string.IsNullOrEmpty(respawnInfo))
{
GUI.DrawString(spriteBatch,
new Vector2(120.0f, 10),
respawnInfo, Color.White, null, 0, GUI.SmallFont);
}
}
}
public virtual bool SelectCrewCharacter(Character character, GUIComponent crewFrame)
{
return false;
}
}
}
@@ -0,0 +1,128 @@
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Barotrauma.Networking
{
partial class ServerLog
{
public GUIFrame LogFrame;
private GUIListBox listBox;
public void CreateLogFrame()
{
LogFrame = new GUIFrame(new Rectangle(0, 0, GameMain.GraphicsWidth, GameMain.GraphicsHeight), Color.Black * 0.5f);
GUIFrame innerFrame = new GUIFrame(new Rectangle(0, 0, 600, 420), null, Alignment.Center, "", LogFrame);
innerFrame.Padding = new Vector4(10.0f, 20.0f, 10.0f, 20.0f);
new GUITextBlock(new Rectangle(-200, 0, 100, 15), "Filter", "", Alignment.TopRight, Alignment.CenterRight, innerFrame, false, GUI.SmallFont);
GUITextBox searchBox = new GUITextBox(new Rectangle(-20, 0, 180, 15), Alignment.TopRight, "", innerFrame);
searchBox.Font = GUI.SmallFont;
searchBox.OnTextChanged = (textBox, text) =>
{
msgFilter = text;
FilterMessages();
return true;
};
GUIComponent.KeyboardDispatcher.Subscriber = searchBox;
var clearButton = new GUIButton(new Rectangle(0, 0, 15, 15), "x", Alignment.TopRight, "", innerFrame);
clearButton.OnClicked = ClearFilter;
clearButton.UserData = searchBox;
listBox = new GUIListBox(new Rectangle(0, 30, 450, 340), "", Alignment.TopRight, innerFrame);
int y = 30;
foreach (MessageType msgType in Enum.GetValues(typeof(MessageType)))
{
var tickBox = new GUITickBox(new Rectangle(0, y, 20, 20), messageTypeName[(int)msgType], Alignment.TopLeft, GUI.SmallFont, innerFrame);
tickBox.Selected = true;
tickBox.TextColor = messageColor[(int)msgType];
tickBox.OnSelected += (GUITickBox tb) =>
{
msgTypeHidden[(int)msgType] = !tb.Selected;
FilterMessages();
return true;
};
y += 20;
}
var currLines = lines.ToList();
foreach (LogMessage line in currLines)
{
AddLine(line);
}
listBox.UpdateScrollBarSize();
if (listBox.BarScroll == 0.0f || listBox.BarScroll == 1.0f) listBox.BarScroll = 1.0f;
GUIButton closeButton = new GUIButton(new Rectangle(-100, 10, 100, 15), "Close", Alignment.BottomRight, "", innerFrame);
closeButton.OnClicked = (button, userData) =>
{
LogFrame = null;
return true;
};
msgFilter = "";
}
private void AddLine(LogMessage line)
{
float prevSize = listBox.BarSize;
var textBlock = new GUITextBlock(new Rectangle(0, 0, 0, 0), line.Text, "", Alignment.TopLeft, Alignment.TopLeft, listBox, true, GUI.SmallFont);
textBlock.Rect = new Rectangle(textBlock.Rect.X, textBlock.Rect.Y, textBlock.Rect.Width, Math.Max(13, textBlock.Rect.Height));
textBlock.TextColor = messageColor[(int)line.Type];
textBlock.CanBeFocused = false;
textBlock.UserData = line;
if ((prevSize == 1.0f && listBox.BarScroll == 0.0f) || (prevSize < 1.0f && listBox.BarScroll == 1.0f)) listBox.BarScroll = 1.0f;
}
private bool FilterMessages()
{
string filter = msgFilter == null ? "" : msgFilter.ToLower();
foreach (GUIComponent child in listBox.children)
{
var textBlock = child as GUITextBlock;
if (textBlock == null) continue;
child.Visible = true;
if (msgTypeHidden[(int)((LogMessage)child.UserData).Type])
{
child.Visible = false;
continue;
}
textBlock.Visible = string.IsNullOrEmpty(filter) || textBlock.Text.ToLower().Contains(filter);
}
listBox.BarScroll = 0.0f;
return true;
}
public bool ClearFilter(GUIComponent button, object obj)
{
var searchBox = button.UserData as GUITextBox;
if (searchBox != null) searchBox.Text = "";
msgFilter = "";
FilterMessages();
return true;
}
}
}
@@ -0,0 +1,169 @@
using Barotrauma.Networking;
using Lidgren.Network;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Barotrauma
{
partial class Voting
{
public bool AllowSubVoting
{
get { return allowSubVoting; }
set
{
if (value == allowSubVoting) return;
allowSubVoting = value;
GameMain.NetLobbyScreen.SubList.Enabled = value || GameMain.Server != null;
GameMain.NetLobbyScreen.InfoFrame.FindChild("subvotes").Visible = value;
if (GameMain.Server != null)
{
UpdateVoteTexts(GameMain.Server.ConnectedClients, VoteType.Sub);
GameMain.Server.UpdateVoteStatus();
}
else
{
GameMain.NetLobbyScreen.SubList.Deselect();
}
}
}
public bool AllowModeVoting
{
get { return allowModeVoting; }
set
{
if (value == allowModeVoting) return;
allowModeVoting = value;
GameMain.NetLobbyScreen.ModeList.Enabled = value || GameMain.Server != null;
GameMain.NetLobbyScreen.InfoFrame.FindChild("modevotes").Visible = value;
if (GameMain.Server != null)
{
UpdateVoteTexts(GameMain.Server.ConnectedClients, VoteType.Mode);
GameMain.Server.UpdateVoteStatus();
}
else
{
GameMain.NetLobbyScreen.ModeList.Deselect();
}
}
}
public void UpdateVoteTexts(List<Client> clients, VoteType voteType)
{
GUIListBox listBox = (voteType == VoteType.Sub) ?
GameMain.NetLobbyScreen.SubList : GameMain.NetLobbyScreen.ModeList;
foreach (GUIComponent comp in listBox.children)
{
GUITextBlock voteText = comp.FindChild("votes") as GUITextBlock;
if (voteText != null) comp.RemoveChild(voteText);
}
List<Pair<object, int>> voteList = GetVoteList(voteType, clients);
foreach (Pair<object, int> votable in voteList)
{
SetVoteText(listBox, votable.First, votable.Second);
}
}
private void SetVoteText(GUIListBox listBox, object userData, int votes)
{
if (userData == null) return;
foreach (GUIComponent comp in listBox.children)
{
if (comp.UserData != userData) continue;
GUITextBlock voteText = comp.FindChild("votes") as GUITextBlock;
if (voteText == null)
{
voteText = new GUITextBlock(new Rectangle(0, 0, 30, 0), "", "", Alignment.Right, Alignment.Right, comp);
voteText.UserData = "votes";
}
voteText.Text = votes == 0 ? "" : votes.ToString();
}
}
public void ClientWrite(NetBuffer msg, VoteType voteType, object data)
{
if (GameMain.Server != null) return;
msg.Write((byte)voteType);
switch (voteType)
{
case VoteType.Sub:
Submarine sub = data as Submarine;
if (sub == null) return;
msg.Write(sub.Name);
break;
case VoteType.Mode:
GameModePreset gameMode = data as GameModePreset;
if (gameMode == null) return;
msg.Write(gameMode.Name);
break;
case VoteType.EndRound:
if (!(data is bool)) return;
msg.Write((bool)data);
break;
case VoteType.Kick:
Client votedClient = data as Client;
if (votedClient == null) return;
msg.Write(votedClient.ID);
break;
}
msg.WritePadBits();
}
public void ClientRead(NetIncomingMessage inc)
{
if (GameMain.Server != null) return;
AllowSubVoting = inc.ReadBoolean();
if (allowSubVoting)
{
foreach (Submarine sub in Submarine.SavedSubmarines)
{
SetVoteText(GameMain.NetLobbyScreen.SubList, sub, 0);
}
int votableCount = inc.ReadByte();
for (int i = 0; i < votableCount; i++)
{
int votes = inc.ReadByte();
string subName = inc.ReadString();
Submarine sub = Submarine.SavedSubmarines.Find(sm => sm.Name == subName);
SetVoteText(GameMain.NetLobbyScreen.SubList, sub, votes);
}
}
AllowModeVoting = inc.ReadBoolean();
if (allowModeVoting)
{
int votableCount = inc.ReadByte();
for (int i = 0; i < votableCount; i++)
{
int votes = inc.ReadByte();
string modeName = inc.ReadString();
GameModePreset mode = GameModePreset.list.Find(m => m.Name == modeName);
SetVoteText(GameMain.NetLobbyScreen.ModeList, mode, votes);
}
}
AllowEndVoting = inc.ReadBoolean();
if (AllowEndVoting)
{
GameMain.NetworkMember.EndVoteCount = inc.ReadByte();
GameMain.NetworkMember.EndVoteMax = inc.ReadByte();
}
AllowVoteKick = inc.ReadBoolean();
inc.ReadPadBits();
}
}
}
@@ -0,0 +1,112 @@
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Barotrauma.Networking
{
partial class WhiteList
{
private GUIComponent whitelistFrame;
private GUITextBox nameBox;
private GUITextBox ipBox;
public GUIComponent CreateWhiteListFrame(GUIComponent parent)
{
if (whitelistFrame != null)
{
whitelistFrame.Parent.ClearChildren();
whitelistFrame = null;
}
parent.Padding = new Vector4(10.0f, 10.0f, 10.0f, 10.0f);
var enabledTick = new GUITickBox(new Rectangle(0, 0, 20, 20), "Enabled", Alignment.TopLeft, parent);
enabledTick.Selected = Enabled;
enabledTick.OnSelected = (GUITickBox box) =>
{
Enabled = !Enabled;
if (Enabled)
{
foreach (Client c in GameMain.Server.ConnectedClients)
{
if (!IsWhiteListed(c.name, c.Connection.RemoteEndPoint.Address.ToString()))
{
whitelistedPlayers.Add(new WhiteListedPlayer(c.name, c.Connection.RemoteEndPoint.Address.ToString()));
if (whitelistFrame != null) CreateWhiteListFrame(whitelistFrame.Parent);
}
}
}
Save();
return true;
};
new GUITextBlock(new Rectangle(0, -35, 90, 20), "Name:", "", Alignment.BottomLeft, Alignment.CenterLeft, parent, false, GUI.Font);
nameBox = new GUITextBox(new Rectangle(100, -35, 170, 20), Alignment.BottomLeft, "", parent);
nameBox.Font = GUI.Font;
new GUITextBlock(new Rectangle(0, 0, 90, 20), "IP Address:", "", Alignment.BottomLeft, Alignment.CenterLeft, parent, false, GUI.Font);
ipBox = new GUITextBox(new Rectangle(100, 0, 170, 20), Alignment.BottomLeft, "", parent);
ipBox.Font = GUI.Font;
var addnewButton = new GUIButton(new Rectangle(0, 35, 150, 20), "Add to whitelist", Alignment.BottomLeft, "", parent);
addnewButton.OnClicked = AddToWhiteList;
whitelistFrame = new GUIListBox(new Rectangle(0, 30, 0, parent.Rect.Height - 110), "", parent);
foreach (WhiteListedPlayer wlp in whitelistedPlayers)
{
string blockText = wlp.Name;
if (!string.IsNullOrWhiteSpace(wlp.IP)) blockText += " (" + wlp.IP + ")";
GUITextBlock textBlock = new GUITextBlock(
new Rectangle(0, 0, 0, 25),
blockText,
"",
Alignment.Left, Alignment.Left, whitelistFrame);
textBlock.Padding = new Vector4(10.0f, 10.0f, 0.0f, 0.0f);
textBlock.UserData = wlp;
var removeButton = new GUIButton(new Rectangle(0, 0, 100, 20), "Remove", Alignment.Right | Alignment.CenterY, "", textBlock);
removeButton.UserData = wlp;
removeButton.OnClicked = RemoveFromWhiteList;
}
return parent;
}
private bool RemoveFromWhiteList(GUIButton button, object obj)
{
WhiteListedPlayer wlp = obj as WhiteListedPlayer;
if (wlp == null) return false;
RemoveFromWhiteList(wlp);
if (whitelistFrame != null)
{
whitelistFrame.Parent.ClearChildren();
CreateWhiteListFrame(whitelistFrame.Parent);
}
return true;
}
private bool AddToWhiteList(GUIButton button, object obj)
{
if (string.IsNullOrWhiteSpace(nameBox.Text)) return false;
if (whitelistedPlayers.Any(x => x.Name.ToLower() == nameBox.Text.ToLower() && x.IP == ipBox.Text)) return false;
AddToWhiteList(nameBox.Text, ipBox.Text);
if (whitelistFrame != null)
{
CreateWhiteListFrame(whitelistFrame.Parent);
}
return true;
}
}
}