OBT/1.2.0(Spring Update)

Sync with Upstream
This commit is contained in:
NotAlwaysTrue
2026-04-25 13:25:41 +08:00
committed by GitHub
parent 5207b381b7
commit 59bc21973a
421 changed files with 24090 additions and 11391 deletions
@@ -0,0 +1,33 @@
using Barotrauma.LuaCs.Data;
namespace Barotrauma.LuaCs.Data;
public partial interface IConfigInfo : IConfigDisplayInfo { }
public interface IConfigDisplayInfo
{
/// <summary>
/// Localization Token for display name.
/// </summary>
string DisplayName { get; }
/// <summary>
/// Localization Token for description.
/// </summary>
string Description { get; }
/// <summary>
/// The menu category to display under. Used for filtering.
/// </summary>
string DisplayCategory { get; }
/// <summary>
/// Should this config be displayed in end-user menus.
/// </summary>
bool ShowInMenus { get; }
/// <summary>
/// User-friendly on-hover tooltip text or Localization Token.
/// </summary>
string Tooltip { get; }
/// <summary>
/// Icon for display in menus, if available.
/// </summary>
ContentPath ImageIconPath { get; }
}
@@ -0,0 +1,9 @@
using System;
using Microsoft.Xna.Framework;
namespace Barotrauma.LuaCs.Data;
public interface IDisplayable
{
public void AddDisplayComponent(GUILayoutGroup layoutGroup, Vector2 relativeSize, Action<string> onSerializedValue);
}
@@ -0,0 +1,6 @@
namespace Barotrauma.LuaCs.Data;
public partial interface ISettingBase : IDisplayable
{
}
@@ -0,0 +1,11 @@
using System;
namespace Barotrauma.LuaCs.Data;
public interface ISettingControl : ISettingBase
{
KeyOrMouse Value { get; }
bool TrySetValue(KeyOrMouse value);
bool IsDown();
bool IsHit();
}
@@ -0,0 +1,252 @@
using System;
using System.Globalization;
using System.Linq;
using System.Xml.Linq;
using Barotrauma.LuaCs.Data;
using Microsoft.Toolkit.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using OneOf;
namespace Barotrauma.LuaCs.Data;
public sealed class SettingControl : SettingBase, ISettingControl
{
public class Factory : ISettingBase.IFactory<ISettingBase>
{
public ISettingBase CreateInstance(IConfigInfo configInfo, Func<OneOf<string, XElement, object>, bool> valueChangePredicate)
{
Guard.IsNotNull(configInfo, nameof(configInfo));
return new SettingControl(configInfo, valueChangePredicate);
}
}
public SettingControl(IConfigInfo configInfo, Func<OneOf<string, XElement, object>, bool> valueChangePredicate) : base(configInfo)
{
_valueChangePredicate = valueChangePredicate;
TrySetSerializedValue(configInfo.Element);
}
protected override void OnDispose()
{
OnValueChanged = null;
}
private Func<OneOf<string, XElement, object>, bool> _valueChangePredicate;
public override Type GetValueType() => typeof(KeyOrMouse);
public override string GetStringValue() => Value.ToString();
public override string GetDefaultStringValue() => new KeyOrMouse(Keys.NumLock).ToString();
public override bool TrySetSerializedValue(OneOf<string, XElement> value)
{
var newVal = value.Match<KeyOrMouse>(
(string v) => GetKeyOrMouse(v),
(XElement e) => e.GetAttributeKeyOrMouse("Value", null));
if (newVal is null)
{
return false;
}
if (_valueChangePredicate is not null && !_valueChangePredicate.Invoke(newVal))
{
return false;
}
Value = newVal;
OnValueChanged?.Invoke(this);
return true;
KeyOrMouse GetKeyOrMouse(string strValue)
{
strValue ??= string.Empty;
if (Enum.TryParse(strValue, true, out Microsoft.Xna.Framework.Input.Keys key))
{
return key;
}
else if (Enum.TryParse(strValue, out MouseButton mouseButton))
{
return mouseButton;
}
else if (int.TryParse(strValue, NumberStyles.Any, CultureInfo.InvariantCulture, out int mouseButtonInt) &&
Enum.GetValues<MouseButton>().Contains((MouseButton)mouseButtonInt))
{
return (MouseButton)mouseButtonInt;
}
else if (string.Equals(strValue, "LeftMouse", StringComparison.OrdinalIgnoreCase))
{
return !PlayerInput.MouseButtonsSwapped() ? MouseButton.PrimaryMouse : MouseButton.SecondaryMouse;
}
else if (string.Equals(strValue, "RightMouse", StringComparison.OrdinalIgnoreCase))
{
return !PlayerInput.MouseButtonsSwapped() ? MouseButton.SecondaryMouse : MouseButton.PrimaryMouse;
}
return null;
}
}
public override event Action<ISettingBase> OnValueChanged;
public override OneOf<string, XElement> GetSerializableValue() => Value.ToString();
public KeyOrMouse Value { get; private set; } = new KeyOrMouse(Keys.NumLock);
public bool TrySetValue(KeyOrMouse value)
{
Value = value;
OnValueChanged?.Invoke(this);
return true;
}
public bool IsDown()
{
if (this.Value is null)
return false;
switch (this.Value.MouseButton)
{
case MouseButton.None:
return Barotrauma.PlayerInput.KeyDown(this.Value.Key);
case MouseButton.PrimaryMouse:
return Barotrauma.PlayerInput.PrimaryMouseButtonHeld();
case MouseButton.SecondaryMouse:
return Barotrauma.PlayerInput.SecondaryMouseButtonHeld();
case MouseButton.MiddleMouse:
return Barotrauma.PlayerInput.MidButtonHeld();
case MouseButton.MouseButton4:
return Barotrauma.PlayerInput.Mouse4ButtonHeld();
case MouseButton.MouseButton5:
return Barotrauma.PlayerInput.Mouse5ButtonHeld();
case MouseButton.MouseWheelUp:
return Barotrauma.PlayerInput.MouseWheelUpClicked();
case MouseButton.MouseWheelDown:
return Barotrauma.PlayerInput.MouseWheelDownClicked();
}
return false;
}
public bool IsHit()
{
if (this.Value is null)
return false;
switch (this.Value.MouseButton)
{
case MouseButton.None:
return Barotrauma.PlayerInput.KeyHit(this.Value.Key);
case MouseButton.PrimaryMouse:
return Barotrauma.PlayerInput.PrimaryMouseButtonClicked();
case MouseButton.SecondaryMouse:
return Barotrauma.PlayerInput.SecondaryMouseButtonClicked();
case MouseButton.MiddleMouse:
return Barotrauma.PlayerInput.MidButtonClicked();
case MouseButton.MouseButton4:
return Barotrauma.PlayerInput.Mouse4ButtonClicked();
case MouseButton.MouseButton5:
return Barotrauma.PlayerInput.Mouse5ButtonClicked();
case MouseButton.MouseWheelUp:
return Barotrauma.PlayerInput.MouseWheelUpClicked();
case MouseButton.MouseWheelDown:
return Barotrauma.PlayerInput.MouseWheelDownClicked();
}
return false;
}
#if CLIENT
private static GUICustomComponent InputListener;
public override void AddDisplayComponent(GUILayoutGroup layoutGroup, Vector2 relativeSize, Action<string> onSerializedValue)
{
var inputButton = new GUIButton(new RectTransform(relativeSize, layoutGroup.RectTransform), Alignment.Center,
style: "GUITextBoxNoIcon")
{
Text = this.Value.ToString(),
OnClicked = (btn, obj) =>
{
if (InputListener is not null)
{
// Another button is active
return true;
}
CoroutineManager.Invoke(() =>
{
CreateListener(btn);
}, 0f); // delay one frame for button inputs
return true;
}
};
inputButton.OutlineColor = Color.PeachPuff;
inputButton.TextColor = Color.White;
void ClearListener()
{
InputListener?.Parent.RemoveChild(InputListener);
InputListener = null;
}
void CreateListener(GUIButton button)
{
ClearListener();
InputListener = new GUICustomComponent(new RectTransform(Vector2.Zero, layoutGroup.RectTransform),
onUpdate: (deltaTime, component) =>
{
var pressedKeys = PlayerInput.GetKeyboardState.GetPressedKeys();
if (pressedKeys?.Any() ?? false)
{
if (pressedKeys.Contains(Keys.Escape))
{
ClearListener();
return;
}
ApplyValue(pressedKeys.First(), button);
return;
}
if (PlayerInput.PrimaryMouseButtonClicked() &&
(GUI.MouseOn == null || !(GUI.MouseOn is GUIButton) || GUI.MouseOn.IsChildOf(layoutGroup)))
{
ApplyValue(MouseButton.PrimaryMouse, button);
return;
}
else if (PlayerInput.SecondaryMouseButtonClicked())
{
ApplyValue(MouseButton.SecondaryMouse, button);
return;
}
else if (PlayerInput.MidButtonClicked())
{
ApplyValue(MouseButton.MiddleMouse, button);
return;
}
else if (PlayerInput.Mouse4ButtonClicked())
{
ApplyValue(MouseButton.MouseButton4, button);
return;
}
else if (PlayerInput.Mouse5ButtonClicked())
{
ApplyValue(MouseButton.MouseButton5, button);
return;
}
else if (PlayerInput.MouseWheelUpClicked())
{
ApplyValue(MouseButton.MouseWheelUp, button);
return;
}
else if (PlayerInput.MouseWheelDownClicked())
{
ApplyValue(MouseButton.MouseWheelDown, button);
return;
}
});
}
void ApplyValue(KeyOrMouse input, GUIButton button)
{
button.Text = input.ToString();
onSerializedValue?.Invoke(input.ToString());
ClearListener();
}
}
#endif
}
@@ -0,0 +1,17 @@
using System.Collections.Immutable;
namespace Barotrauma.LuaCs.Data;
public interface IStylesResourceInfo : IBaseResourceInfo { }
public record StylesResourceInfo : BaseResourceInfo, IStylesResourceInfo { }
public partial interface IModConfigInfo
{
public ImmutableArray<IStylesResourceInfo> Styles { get; }
}
public partial record ModConfigInfo
{
public ImmutableArray<IStylesResourceInfo> Styles { get; init; }
}
@@ -0,0 +1,143 @@
using System;
using System.Collections.Generic;
using Barotrauma.Extensions;
using Microsoft.Xna.Framework;
#nullable enable
namespace Barotrauma.LuaCs;
/// <summary>
/// A collection of helper GUI functions. Mostly ripped from "Barotrauma/ClientSource/Settings/SettingsMenu.cs"
/// </summary>
public static class GUIUtil
{
public static (GUILayoutGroup Left, GUILayoutGroup Right) CreateSidebars(GUIFrame parent, bool split = false)
{
GUILayoutGroup layout = new GUILayoutGroup(new RectTransform(Vector2.One, parent.RectTransform), isHorizontal: true);
GUILayoutGroup left = new GUILayoutGroup(new RectTransform((0.4875f, 1.0f), layout.RectTransform), isHorizontal: false);
var centerFrame = new GUIFrame(new RectTransform((0.025f, 1.0f), layout.RectTransform), style: null);
if (split)
{
new GUICustomComponent(new RectTransform(Vector2.One, centerFrame.RectTransform),
onDraw: (sb, c) =>
{
sb.DrawLine((c.Rect.Center.X, c.Rect.Top),
(c.Rect.Center.X, c.Rect.Bottom),
GUIStyle.TextColorDim,
2f);
});
}
GUILayoutGroup right = new GUILayoutGroup(new RectTransform((0.4875f, 1.0f), layout.RectTransform), isHorizontal: false);
return (left, right);
}
public static (GUILayoutGroup Left, GUILayoutGroup Right) CreateSidebars(GUILayoutGroup parent, bool split = false)
{
GUILayoutGroup layout = new GUILayoutGroup(new RectTransform(Vector2.One, parent.RectTransform), isHorizontal: true);
GUILayoutGroup left = new GUILayoutGroup(new RectTransform((0.4875f, 1.0f), layout.RectTransform), isHorizontal: false);
var centerFrame = new GUIFrame(new RectTransform((0.025f, 1.0f), layout.RectTransform), style: null);
if (split)
{
new GUICustomComponent(new RectTransform(Vector2.One, centerFrame.RectTransform),
onDraw: (sb, c) =>
{
sb.DrawLine((c.Rect.Center.X, c.Rect.Top),
(c.Rect.Center.X, c.Rect.Bottom),
GUIStyle.TextColorDim,
2f);
});
}
GUILayoutGroup right = new GUILayoutGroup(new RectTransform((0.4875f, 1.0f), layout.RectTransform), isHorizontal: false);
return (left, right);
}
public static GUILayoutGroup CreateCenterLayout(GUIFrame parent)
=> new GUILayoutGroup(new RectTransform((0.5f, 1.0f), parent.RectTransform, Anchor.TopCenter, Pivot.TopCenter)) { ChildAnchor = Anchor.TopCenter };
public static RectTransform NewItemRectT(GUILayoutGroup parent, Vector2 adjustRatio)
=> new RectTransform((1.0f * adjustRatio.X, 0.06f * adjustRatio.Y), parent.RectTransform, Anchor.CenterLeft);
public static void Spacer(GUILayoutGroup parent, Vector2 adjustRatio)
=> new GUIFrame(new RectTransform((1.0f * adjustRatio.X, 0.03f * adjustRatio.Y), parent.RectTransform, Anchor.CenterLeft), style: null);
public static void ClearChildElements(GUIComponent component, bool clearSelfFromParent = false)
{
component.GetAllChildren().ForEachMod(c =>
{
c.Visible = false;
component.RemoveChild(c);
});
if (clearSelfFromParent && component.Parent is not null)
component.Parent.RemoveChild(component);
}
public static GUITextBlock Label(GUILayoutGroup parent, LocalizedString str, GUIFont font, Vector2 adjustRatio)
=> new GUITextBlock(NewItemRectT(parent, adjustRatio), str, font: font);
public static GUIDropDown DropdownEnum<T>(GUILayoutGroup parent, Func<T, LocalizedString> textFunc, Func<T, LocalizedString>? tooltipFunc, T currentValue,
Action<T> setter, Vector2 adjustRatio) where T : Enum
=> Dropdown(parent, textFunc, tooltipFunc, (T[])Enum.GetValues(typeof(T)), currentValue, setter, adjustRatio);
public static GUIDropDown Dropdown<T>(GUILayoutGroup parent, Func<T, LocalizedString> textFunc, Func<T,
LocalizedString>? tooltipFunc, IReadOnlyList<T> values, T currentValue, Action<T> setter, Vector2 adjustRatio, float listBoxScale = 1)
{
var dropdown = new GUIDropDown(NewItemRectT(parent, adjustRatio), listBoxScale: listBoxScale);
values.ForEach(v => dropdown.AddItem(text: textFunc(v), userData: v, toolTip: tooltipFunc?.Invoke(v) ?? null));
int childIndex = values.IndexOf(currentValue);
dropdown.Select(childIndex);
dropdown.ListBox.ForceLayoutRecalculation();
dropdown.ListBox.ScrollToElement(dropdown.ListBox.Content.GetChild(childIndex));
dropdown.OnSelected = (dd, obj) =>
{
setter((T)obj);
return true;
};
return dropdown;
}
public static (GUIScrollBar, GUITextBlock) Slider(GUILayoutGroup parent, Vector2 range, int steps, Func<float,
string> labelFunc, float currentValue, Action<float> setter, LocalizedString? tooltip, Vector2 adjustRatio)
{
var layout = new GUILayoutGroup(new RectTransform(adjustRatio, parent.RectTransform), isHorizontal: true);
var slider = new GUIScrollBar(new RectTransform((0.72f, 1.0f), layout.RectTransform), style: "GUISlider")
{
Range = range,
BarScrollValue = currentValue,
Step = 1.0f / (float)(steps - 1),
BarSize = 1.0f / steps
};
if (tooltip != null)
{
slider.ToolTip = tooltip;
}
var label = new GUITextBlock(new RectTransform((0.28f, 1.0f), layout.RectTransform),
labelFunc(currentValue), wrap: false, textAlignment: Alignment.Center);
slider.OnMoved = (sb, val) =>
{
label.Text = labelFunc(sb.BarScrollValue);
setter(sb.BarScrollValue);
return true;
};
return (slider, label);
}
public static GUITickBox Tickbox(GUILayoutGroup parent, LocalizedString label, LocalizedString tooltip,
bool currentValue, Action<bool> setter, Vector2 adjustRatio)
{
var tickbox = new GUITickBox(NewItemRectT(parent, adjustRatio), label)
{
Selected = currentValue,
ToolTip = tooltip,
OnSelected = (tb) =>
{
setter(tb.Selected);
return true;
}
};
return tickbox;
}
public static string Percentage(float v) => ToolBox.GetFormattedPercentage(v);
public static int Round(float v) => (int)MathF.Round(v);
}
@@ -8,115 +8,7 @@ namespace Barotrauma
{
public static void Uninstall()
{
if (!File.Exists("Temp/Original/Barotrauma.dll"))
{
new GUIMessageBox("Error", "Error: Temp/Original/Barotrauma.dll not found, Github version? Use Steam validate files instead.");
return;
}
var msg = new GUIMessageBox("Confirm", "Are you sure you want to remove Client-Side ProjectEP?", new LocalizedString[2] { TextManager.Get("Yes"), TextManager.Get("Cancel") });
msg.Buttons[0].OnClicked = (GUIButton button, object obj) =>
{
msg.Close();
string[] filesToRemove = new string[]
{
"Barotrauma.dll", "Barotrauma.deps.json", "Barotrauma.pdb", "BarotraumaCore.dll", "BarotraumaCore.pdb",
"System.Reflection.Metadata.dll", "System.Collections.Immutable.dll",
"System.Runtime.CompilerServices.Unsafe.dll"
};
try
{
CreateMissingDirectory();
foreach (string file in filesToRemove)
{
File.Move(file, "Temp/ToDelete/" + file, true);
File.Move("Temp/Original/" + file, file, true);
}
}
catch (Exception e)
{
new GUIMessageBox("Error", $"{e} {e.InnerException} \nTry verifying files instead.");
return false;
}
new GUIMessageBox("Restart", "Restart your game to apply the changes. If the mod continues to stay active after the restart, try verifying games instead.");
return true;
};
msg.Buttons[1].OnClicked = (GUIButton button, object obj) =>
{
msg.Close();
return true;
};
}
public static void CheckUpdate()
{
if (!File.Exists(LuaCsSetup.VersionFile)) { return; }
ContentPackage luaPackage = LuaCsSetup.GetPackage(LuaCsSetup.LuaForBarotraumaId);
if (luaPackage == null) { return; }
string luaCsPath = Path.GetDirectoryName(luaPackage.Path);
string clientVersion = File.ReadAllText(LuaCsSetup.VersionFile);
string workshopVersion = luaPackage.ModVersion;
if (clientVersion == workshopVersion || File.Exists("debugsomething")) { return; }
var msg = new GUIMessageBox($"LuaCs Update", $"Your LuaCs client version is different from the version found in the LuaCsForBarotrauma workshop files. Do you want to update?\n\n Client Version: {clientVersion}\n Workshop Version: {workshopVersion}",
new LocalizedString[2] { TextManager.Get("Yes"), TextManager.Get("Cancel") });
msg.Buttons[0].OnClicked = (GUIButton button, object obj) =>
{
string[] filesToUpdate = trackingFiles.Concat(Directory.EnumerateFiles(luaCsPath, "*.dll", SearchOption.AllDirectories)
.Where(s => s.Contains("mscordaccore_amd64_amd64")).Select(s => Path.GetFileName(s))).ToArray();
try
{
CreateMissingDirectory();
foreach (string file in filesToUpdate)
{
try
{
File.Move(file, "Temp/Old/" + file, true);
File.Copy(Path.Combine(luaCsPath, "Binary", file), file, true);
}
catch (Exception e)
{
DebugConsole.ThrowError($"Failed to update file {e}");
}
}
File.WriteAllText(LuaCsSetup.VersionFile, workshopVersion);
}
catch (Exception e)
{
new GUIMessageBox("Failed", $"Failed to update, error: {e}");
msg.Close();
return true;
}
new GUIMessageBox("Restart", $"LuaCs updated! Restart your game to apply the changes.");
msg.Close();
return true;
};
msg.Buttons[1].OnClicked = (GUIButton button, object obj) =>
{
msg.Close();
return true;
};
}
}
}
@@ -1,143 +0,0 @@
using Barotrauma.Networking;
using System.Collections.Generic;
namespace Barotrauma
{
partial class LuaCsNetworking
{
private Dictionary<ushort, Queue<IReadMessage>> receiveQueue = new Dictionary<ushort, Queue<IReadMessage>>();
public void SendSyncMessage()
{
if (GameMain.Client == null) { return; }
WriteOnlyMessage message = new WriteOnlyMessage();
message.WriteByte((byte)ClientPacketHeader.LUA_NET_MESSAGE);
message.WriteByte((byte)LuaCsClientToServer.RequestAllIds);
GameMain.Client.ClientPeer.Send(message, DeliveryMethod.Reliable);
}
public void NetMessageReceived(IReadMessage netMessage, ServerPacketHeader header, Client client = null)
{
if (header != ServerPacketHeader.LUA_NET_MESSAGE)
{
GameMain.LuaCs.Hook.Call("netMessageReceived", netMessage, header, client);
return;
}
LuaCsServerToClient luaCsHeader = (LuaCsServerToClient)netMessage.ReadByte();
switch (luaCsHeader)
{
case LuaCsServerToClient.NetMessageString:
HandleNetMessageString(netMessage);
break;
case LuaCsServerToClient.NetMessageId:
HandleNetMessageId(netMessage);
break;
case LuaCsServerToClient.ReceiveIds:
ReadIds(netMessage);
break;
}
}
public IWriteMessage Start(string netMessageName)
{
var message = new WriteOnlyMessage();
message.WriteByte((byte)ClientPacketHeader.LUA_NET_MESSAGE);
if (stringToId.ContainsKey(netMessageName))
{
message.WriteByte((byte)LuaCsClientToServer.NetMessageId);
message.WriteUInt16(stringToId[netMessageName]);
}
else
{
message.WriteByte((byte)LuaCsClientToServer.NetMessageString);
message.WriteString(netMessageName);
}
return message;
}
public void Receive(string netMessageName, LuaCsAction callback)
{
RequestId(netMessageName);
netReceives[netMessageName] = callback;
}
public void RequestId(string netMessageName)
{
if (stringToId.ContainsKey(netMessageName)) { return; }
if (GameMain.Client == null) { return; }
WriteOnlyMessage message = new WriteOnlyMessage();
message.WriteByte((byte)ClientPacketHeader.LUA_NET_MESSAGE);
message.WriteByte((byte)LuaCsClientToServer.RequestSingleId);
message.WriteString(netMessageName);
Send(message, DeliveryMethod.Reliable);
}
public void Send(IWriteMessage netMessage, DeliveryMethod deliveryMethod = DeliveryMethod.Reliable)
{
GameMain.Client.ClientPeer.Send(netMessage, deliveryMethod);
}
private void HandleNetMessageId(IReadMessage netMessage, Client client = null)
{
ushort id = netMessage.ReadUInt16();
if (idToString.ContainsKey(id))
{
string name = idToString[id];
HandleNetMessage(netMessage, name, client);
}
else
{
if (!receiveQueue.ContainsKey(id)) { receiveQueue[id] = new Queue<IReadMessage>(); }
receiveQueue[id].Enqueue(netMessage);
if (GameSettings.CurrentConfig.VerboseLogging)
{
LuaCsLogger.LogMessage($"Received NetMessage with unknown id {id} from server, storing in queue in case we receive the id later.");
}
}
}
private void ReadIds(IReadMessage netMessage)
{
ushort size = netMessage.ReadUInt16();
for (int i = 0; i < size; i++)
{
ushort id = netMessage.ReadUInt16();
string name = netMessage.ReadString();
idToString[id] = name;
stringToId[name] = id;
if (!receiveQueue.ContainsKey(id))
{
continue;
}
while (receiveQueue[id].TryDequeue(out var queueMessage))
{
if (netReceives.ContainsKey(name))
{
netReceives[name](queueMessage, null);
}
}
}
}
}
}
@@ -1,115 +0,0 @@
using Microsoft.Xna.Framework;
namespace Barotrauma
{
static class LuaCsSettingsMenu
{
private static GUIFrame frame;
public static void Open(RectTransform rectTransform)
{
Close();
frame = new GUIFrame(new RectTransform(new Vector2(0.4f, 0.6f), rectTransform, Anchor.Center));
GUIListBox list = new GUIListBox(new RectTransform(new Vector2(0.95f, 0.95f), frame.RectTransform, Anchor.Center), false);
new GUITextBlock(new RectTransform(new Vector2(1f, 0.1f), list.Content.RectTransform), "LuaCs Settings", textAlignment: Alignment.Center);
new GUITickBox(new RectTransform(new Vector2(0.8f, 0.1f), list.Content.RectTransform), "Enable CSharp Scripting")
{
Selected = GameMain.LuaCs.Config.EnableCsScripting,
ToolTip = "This enables CSharp Scripting for mods to use, WARNING: CSharp is NOT sandboxed, be careful with what mods you download.",
OnSelected = (GUITickBox tick) =>
{
GameMain.LuaCs.Config.EnableCsScripting = tick.Selected;
GameMain.LuaCs.WriteSettings();
return true;
}
};
new GUITickBox(new RectTransform(new Vector2(0.8f, 0.1f), list.Content.RectTransform), "Treat Forced Mods As Normal")
{
Selected = GameMain.LuaCs.Config.TreatForcedModsAsNormal,
ToolTip = "This makes mods that were setup to run even when disabled to only run when enabled.",
OnSelected = (GUITickBox tick) =>
{
GameMain.LuaCs.Config.TreatForcedModsAsNormal = tick.Selected;
GameMain.LuaCs.WriteSettings();
return true;
}
};
new GUITickBox(new RectTransform(new Vector2(0.8f, 0.1f), list.Content.RectTransform), "Prefer To Use Workshop Lua Setup")
{
Selected = GameMain.LuaCs.Config.PreferToUseWorkshopLuaSetup,
ToolTip = "This makes Lua look first for the Lua/LuaSetup.lua located in the Workshop package instead of the one located locally.",
OnSelected = (GUITickBox tick) =>
{
GameMain.LuaCs.Config.PreferToUseWorkshopLuaSetup = tick.Selected;
GameMain.LuaCs.WriteSettings();
return true;
}
};
new GUITickBox(new RectTransform(new Vector2(0.8f, 0.1f), list.Content.RectTransform), "Disable Error GUI Overlay")
{
Selected = GameMain.LuaCs.Config.DisableErrorGUIOverlay,
ToolTip = "",
OnSelected = (GUITickBox tick) =>
{
GameMain.LuaCs.Config.DisableErrorGUIOverlay = tick.Selected;
GameMain.LuaCs.WriteSettings();
return true;
}
};
new GUITickBox(new RectTransform(new Vector2(0.8f, 0.1f), list.Content.RectTransform), "Hide usernames In Error Logs")
{
Selected = GameMain.LuaCs.Config.HideUserNames,
ToolTip = "Hides the operating system username when displaying error logs (eg your username on windows).",
OnSelected = (GUITickBox tick) =>
{
GameMain.LuaCs.Config.HideUserNames = tick.Selected;
GameMain.LuaCs.WriteSettings();
return true;
}
};
new GUIButton(new RectTransform(new Vector2(1f, 0.1f), list.Content.RectTransform), $"Remove Client-Side ProjectEP", style: "GUIButtonSmall")
{
ToolTip = "Remove Client-Side ProjectEP.",
OnClicked = (tb, userdata) =>
{
LuaCsInstaller.Uninstall();
return true;
}
};
new GUIButton(new RectTransform(new Vector2(0.8f, 0.01f), frame.RectTransform, Anchor.BottomCenter)
{
RelativeOffset = new Vector2(0f, 0.05f)
}, "Close")
{
OnClicked = (GUIButton button, object obj) =>
{
Close();
return true;
}
};
}
public static void Close()
{
frame?.Parent.RemoveChild(frame);
frame = null;
}
}
}
@@ -1,75 +1,184 @@
using System.Collections.Generic;
using Barotrauma.CharacterEditor;
using Barotrauma.Extensions;
using Barotrauma.LuaCs;
using Barotrauma.LuaCs.Data;
using Barotrauma.Networking;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text;
using static System.Collections.Specialized.BitVector32;
// ReSharper disable ObjectCreationAsStatement
namespace Barotrauma
{
partial class LuaCsSetup
{
public void AddToGUIUpdateList()
{
public void PromptCSharpMods(Action<bool> onSelection, bool joiningServer)
{
if (!GameMain.LuaCs.Config.DisableErrorGUIOverlay)
ImmutableArray<ContentPackage> contentPackages = PackageManagementService.GetLoadedUnrestrictedPackages()
.Where(p => p.Name != PackageName)
.ToImmutableArray();
if (_csRunPolicy?.Value is "Enabled")
{
LuaCsLogger.AddToGUIUpdateList();
IsCsEnabledForSession = true;
onSelection(true);
return;
}
else if (_csRunPolicy?.Value is "Disabled")
{
IsCsEnabledForSession = false;
onSelection(false);
return;
}
if (contentPackages.None())
{
onSelection(true);
return;
}
GUIMessageBox messageBox = new GUIMessageBox(
TextManager.Get("warning"),
relativeSize: new Vector2(0.3f, 0.55f),
minSize: new Point(400, 500),
text: string.Empty,
buttons: []);
GUILayoutGroup msgBoxLayout = new GUILayoutGroup(new RectTransform(new Vector2(1f, 0.75f), messageBox.Content.RectTransform), isHorizontal: false, childAnchor: Anchor.TopCenter)
{
RelativeSpacing = 0.01f,
Stretch = true
};
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), msgBoxLayout.RectTransform), "The following mods contain CSharp code OR Unsandboxed Lua Code",
font: GUIStyle.SubHeadingFont, wrap: true, textAlignment: Alignment.Center);
GUIListBox packageListBox = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.4f), msgBoxLayout.RectTransform))
{
CurrentSelectMode = GUIListBox.SelectMode.None
};
foreach (ContentPackage package in contentPackages)
{
GUIFrame packageFrame = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.15f), packageListBox.Content.RectTransform), style: "ListBoxElement");
GUILayoutGroup packageLayout = new GUILayoutGroup(new RectTransform(Vector2.One, packageFrame.RectTransform), true, Anchor.CenterLeft);
new GUITextBlock(new RectTransform(new Vector2(0.7f, 1f), packageLayout.RectTransform), package.Name);
new GUIButton(new RectTransform(new Vector2(0.3f, 1f), packageLayout.RectTransform, Anchor.CenterRight), "Open Folder", style: "GUIButtonSmall")
{
OnClicked = (GUIButton button, object obj) =>
{
string directory = package.Dir;
if (string.IsNullOrEmpty(directory)) { return false; }
ToolBox.OpenFileWithShell(directory);
return true;
}
};
}
string bodyText =
joiningServer ?
"You are joining a server that includes mods with C# code OR unrestricted Lua code. These mods are not sandboxed and may access your computer without restrictions. If you trust these mods, select 'Enable C# for this session'. Otherwise, select 'Cancel' to run only Lua mods."
: "You have enabled mods that include C# code. These mods are not sandboxed and may access your computer without restrictions. If you trust these mods, select 'Enable C# for this session'. Otherwise, select 'Cancel' to run only Sandboxed Lua mods.";
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0f), msgBoxLayout.RectTransform), bodyText, wrap: true)
{
Wrap = true
};
GUILayoutGroup buttonLayout = new GUILayoutGroup(new RectTransform(new Vector2(1f, 0.25f), messageBox.Content.RectTransform, Anchor.BottomCenter), isHorizontal: false, childAnchor: Anchor.TopCenter);
new GUIButton(new RectTransform(new Vector2(0.8f, 0.0f), buttonLayout.RectTransform), "Enable C# for this session")
{
TextBlock = { AutoScaleHorizontal = true },
OnClicked = (btn, userdata) =>
{
IsCsEnabledForSession = true;
onSelection(true);
messageBox.Close();
return true;
}
};
new GUIButton(new RectTransform(new Vector2(0.8f, 0.0f), buttonLayout.RectTransform), "Cancel")
{
OnClicked = (btn, userdata) =>
{
IsCsEnabledForSession = false;
onSelection(false);
messageBox.Close();
return true;
}
};
}
public void CheckInitialize()
private void SetupServicesProviderClient(IServicesProvider serviceProvider)
{
List<ContentPackage> csharpMods = new List<ContentPackage>();
foreach (ContentPackage cp in ContentPackageManager.EnabledPackages.All)
serviceProvider.RegisterServiceType<IUIStylesService, UIStylesService>(ServiceLifetime.Singleton);
// supplied via factory
//serviceProvider.RegisterServiceType<IUIStylesCollection, UIStylesCollection>(ServiceLifetime.Transient);
serviceProvider.RegisterServiceType<IParserServiceAsync<ResourceParserInfo, IStylesResourceInfo>, ModConfigFileParserService>(ServiceLifetime.Transient);
serviceProvider.RegisterServiceType<IUIStylesCollection.IFactory, UIStylesCollection.Factory>(ServiceLifetime.Transient);
serviceProvider.RegisterServiceType<ISettingsMenuSystem, SettingsMenuSystem>(ServiceLifetime.Singleton);
}
/// <summary>
/// Handles changes in game states tracked by screen changes.
/// </summary>
/// <param name="screen">The new game screen.</param>
public partial void OnScreenSelected(Screen screen)
{
/*Note: This logic needs to be run after the triggering event so that recursion scenarios (ie. resetting the EventService)
do not occur, so we delay it by one game tick.*/
CoroutineManager.Invoke(() =>
{
if (Directory.Exists(cp.Dir + "/CSharp") || Directory.Exists(cp.Dir + "/bin"))
switch (screen)
{
csharpMods.Add(cp);
// menus and navigation states
case MainMenuScreen:
case ModDownloadScreen:
case ServerListScreen:
SetRunState(RunState.Unloaded);
SetRunState(RunState.LoadedNoExec);
break;
// running lobby or editor states
case CampaignEndScreen:
case CharacterEditorScreen:
case EventEditorScreen:
case GameScreen:
case LevelEditorScreen:
case NetLobbyScreen:
case ParticleEditorScreen:
case RoundSummaryScreen:
case SpriteEditorScreen:
case SubEditorScreen:
case TestScreen: // notes: TestScreen is a Linux edge case editor screen and is deprecated.
if (screen is NetLobbyScreen && CurrentRunState != RunState.Running && GameMain.Client?.ClientPeer is not P2POwnerPeer)
{
PromptCSharpMods(selection =>
{
SetRunState(RunState.Running);
}, joiningServer: true);
}
else
{
SetRunState(RunState.Running);
}
break;
default:
Logger.LogError(
$"{nameof(LuaCsSetup)}: Received an unknown screen {screen?.GetType().Name ?? "'null screen'"}. Retarding load state to 'unloaded'.");
SetRunState(RunState.Unloaded);
break;
}
}
if (csharpMods.Count == 0 || ShouldRunCs)
{
Initialize();
return;
}
StringBuilder sb = new StringBuilder();
foreach (ContentPackage cp in csharpMods)
{
if (cp.UgcId.TryUnwrap(out ContentPackageId id))
{
sb.AppendLine($"- {cp.Name} ({id})");
}
else
{
sb.AppendLine($"- {cp.Name} (Not On Workshop)");
}
}
if (GameMain.Client == null || GameMain.Client.IsServerOwner)
{
new GUIMessageBox("", $"You have CSharp mods enabled but don't have the CSharp Scripting enabled, those mods might not work, go to the Main Menu, click on LuaCs Settings and check Enable CSharp Scripting.\n\n{sb}");
Initialize();
return;
}
GUIMessageBox msg = new GUIMessageBox(
"Confirm",
$"This server has the following CSharp mods installed: \n{sb}\nDo you wish to run them? Cs mods are not sandboxed so make sure you trust these mods.",
new LocalizedString[2] { "Run", "Don't Run" });
msg.Buttons[0].OnClicked = (GUIButton button, object obj) =>
{
Initialize(true);
msg.Close();
return true;
};
msg.Buttons[1].OnClicked = (GUIButton button, object obj) =>
{
Initialize();
msg.Close();
return true;
};
}, delay: 0f); // min is one tick delay.
}
}
}
@@ -0,0 +1,22 @@
using System;
using System.Collections.Immutable;
using System.Linq;
using Barotrauma.LuaCs.Data;
namespace Barotrauma.LuaCs;
public sealed partial class ConfigService
{
public ImmutableArray<ISettingBase> GetDisplayableConfigs()
{
using var _ = _operationLock.AcquireReaderLock().ConfigureAwait(false).GetAwaiter().GetResult();
IService.CheckDisposed(this);
return _settingsInstances.Values
.Where(s => !s.IsDisposed)
.Where(s => s.GetDisplayInfo().ShowInMenus)
.Where(s => !GameMain.IsMultiplayer || s.GetConfigInfo().NetSync != NetSync.ServerAuthority)
.Where(s => s.GetConfigInfo().EditableStates >= _infoProvider.CurrentRunState)
.ToImmutableArray();
}
}
@@ -0,0 +1,50 @@
using Microsoft.Xna.Framework;
namespace Barotrauma.LuaCs;
public partial class LoggerService : ILoggerService, IClientLoggerService
{
private GUIFrame _overlayFrame;
private GUITextBlock _textBlock;
private double _showTimer = 0;
private void CreateOverlay(string message)
{
_overlayFrame = new GUIFrame(new RectTransform(new Vector2(0.4f, 0.03f), null), null, new Color(50, 50, 50, 100))
{
CanBeFocused = false
};
GUILayoutGroup layout =
new GUILayoutGroup(
new RectTransform(new Vector2(0.8f, 0.8f), _overlayFrame.RectTransform, Anchor.CenterLeft), false,
Anchor.Center);
_textBlock = new GUITextBlock(new RectTransform(new Vector2(1f, 0f), layout.RectTransform), message);
_overlayFrame.RectTransform.MinSize = new Point((int)(_textBlock.TextSize.X * 1.2), 0);
layout.Recalculate();
}
public void AddToGUIUpdateList()
{
if (_overlayFrame != null && Timing.TotalTime <= _showTimer)
{
_overlayFrame.AddToGUIUpdateList();
}
}
public void ShowErrorOverlay(string message, float time = 5f, float duration = 1.5f)
{
if (Timing.TotalTime <= _showTimer)
{
return;
}
CreateOverlay(message);
_overlayFrame.Flash(Color.Red, duration, true);
_showTimer = Timing.TotalTime + time;
}
}
@@ -0,0 +1,44 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Barotrauma.LuaCs.Data;
using FluentResults;
namespace Barotrauma.LuaCs;
public sealed partial class ModConfigFileParserService :
IParserServiceAsync<ResourceParserInfo, IStylesResourceInfo>
{
async Task<Result<IStylesResourceInfo>> IParserServiceAsync<ResourceParserInfo, IStylesResourceInfo>.TryParseResourceAsync(ResourceParserInfo src)
{
using var lck = await _operationsLock.AcquireReaderLock();
IService.CheckDisposed(this);
if (CheckThrowNullRefs(src, "Style") is { IsFailed: true } fail)
return fail;
var runtimeEnv = GetRuntimeEnvironment(src.Element);
var fileResults = await UnsafeGetCheckedFiles(src.Element, src.Owner, ".xml");
if (fileResults.IsFailed)
return FluentResults.Result.Fail(fileResults.Errors);
return new StylesResourceInfo()
{
SupportedPlatforms = runtimeEnv.Platform,
SupportedTargets = Target.Client, // clientside only
LoadPriority = src.Element.GetAttributeInt("LoadPriority", 0),
FilePaths = fileResults.Value,
Optional = src.Element.GetAttributeBool("Optional", false),
InternalName = src.Element.GetAttributeString("Name", string.Empty),
OwnerPackage = src.Owner,
RequiredPackages = src.Required,
IncompatiblePackages = src.Incompatible
};
}
public async Task<ImmutableArray<Result<IStylesResourceInfo>>> TryParseResourcesAsync(IEnumerable<ResourceParserInfo> sources)
{
return await this.TryParseGenericResourcesAsync<IStylesResourceInfo>(sources);
}
}
@@ -0,0 +1,163 @@
using Barotrauma.LuaCs;
using Barotrauma.LuaCs.Events;
using Barotrauma.Networking;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
namespace Barotrauma.LuaCs;
partial class NetworkingService : INetworkingService, IEventServerConnected, IEventServerRawNetMessageReceived
{
private ConcurrentDictionary<ushort, ConcurrentQueue<IReadMessage>> receiveQueue = new();
public void OnServerConnected()
{
ActivateNetVars();
SendSyncMessage();
}
private void ActivateNetVars()
{
if (GameMain.Client == null)
{
return;
}
// re-activate net vars
// todo: unregister net vars on client disconnect, currently handled by unloading the state machine.
foreach (var networkSyncVar in netVars.Keys)
{
networkSyncVar.SetNetworkOwner(this);
}
}
public bool? OnReceivedServerNetMessage(IReadMessage netMessage, ServerPacketHeader serverPacketHeader)
{
if (serverPacketHeader != ServerHeader)
{
return null;
}
ServerToClient luaCsHeader = (ServerToClient)netMessage.ReadByte();
switch (luaCsHeader)
{
case ServerToClient.NetMessageNetId:
HandleNetMessageString(netMessage);
break;
case ServerToClient.NetMessageInternalId:
HandleNetMessageId(netMessage);
break;
case ServerToClient.ReceiveNetIds:
ReadIds(netMessage);
break;
}
return true;
}
private void SendSyncMessage()
{
if (GameMain.Client == null) { return; }
WriteOnlyMessage message = new WriteOnlyMessage();
message.WriteByte((byte)ClientHeader);
message.WriteByte((byte)ClientToServer.RequestSync);
GameMain.Client.ClientPeer.Send(message, DeliveryMethod.Reliable);
}
public IWriteMessage Start(NetId netId)
{
var message = new WriteOnlyMessage();
message.WriteByte((byte)ClientHeader);
if (idToPacket.ContainsKey(netId))
{
message.WriteByte((byte)ClientToServer.NetMessageInternalId);
message.WriteUInt16(idToPacket[netId]);
}
else
{
message.WriteByte((byte)ClientToServer.NetMessageNetId);
NetId.Write(message, netId);
}
return message;
}
public void SendToServer(IWriteMessage netMessage, DeliveryMethod deliveryMethod = DeliveryMethod.Reliable)
{
GameMain.Client.ClientPeer.Send(netMessage, deliveryMethod);
}
public void Send(IWriteMessage netMessage, DeliveryMethod deliveryMethod = DeliveryMethod.Reliable)
=> SendToServer(netMessage, deliveryMethod);
private void RequestId(NetId netId)
{
if (idToPacket.ContainsKey(netId)) { return; }
if (GameMain.Client == null) { return; }
WriteOnlyMessage message = new WriteOnlyMessage();
message.WriteByte((byte)ClientHeader);
message.WriteByte((byte)ClientToServer.RequestSingleNetId);
NetId.Write(message, netId);
SendToServer(message, DeliveryMethod.Reliable);
}
private void HandleNetMessageId(IReadMessage netMessage, Client client = null)
{
ushort id = netMessage.ReadUInt16();
if (packetToId.ContainsKey(id))
{
HandleNetMessage(netMessage, packetToId[id], client);
}
else
{
if (!receiveQueue.ContainsKey(id)) { receiveQueue[id] = new ConcurrentQueue<IReadMessage>(); }
receiveQueue[id].Enqueue(netMessage);
if (GameSettings.CurrentConfig.VerboseLogging)
{
_loggerService.LogMessage($"Received NetMessage with unknown id {id} from server, storing in queue in case we receive the id later.");
}
}
}
private void ReadIds(IReadMessage netMessage)
{
ushort size = netMessage.ReadUInt16();
for (int i = 0; i < size; i++)
{
ushort packetId = netMessage.ReadUInt16();
NetId netId = NetId.Read(netMessage);
packetToId[packetId] = netId;
idToPacket[netId] = packetId;
if (!receiveQueue.ContainsKey(packetId))
{
continue;
}
// We could have received messages before receiving the sync message, so we need to process them now
while (receiveQueue[packetId].TryDequeue(out var queueMessage))
{
if (netReceives.ContainsKey(netId))
{
netReceives[netId](queueMessage);
}
}
}
}
}
@@ -0,0 +1,239 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using Barotrauma.Extensions;
using Barotrauma.LuaCs.Data;
using FluentResults;
using Microsoft.Toolkit.Diagnostics;
namespace Barotrauma.LuaCs;
public class UIStylesCollection : HashlessFile, IUIStylesCollection
{
public class Factory : IUIStylesCollection.IFactory
{
public IEnumerable<IUIStylesCollection> CreateInstance(IStylesResourceInfo info, IStorageService storageService)
{
Guard.IsNotNull(info, nameof(info));
Guard.IsNotNull(info.OwnerPackage, nameof(info.OwnerPackage));
if (info.FilePaths.IsDefaultOrEmpty)
{
return ImmutableArray<IUIStylesCollection>.Empty;
}
var builder = ImmutableArray.CreateBuilder<IUIStylesCollection>();
foreach (var contentPath in info.FilePaths)
{
builder.Add(new UIStylesCollection(contentPath, storageService));
}
return builder.ToImmutable();
}
public void Dispose()
{
//ignore, stateless service
}
public bool IsDisposed => false;
}
private readonly ConcurrentDictionary<string, GUIFont> _fonts = new();
private readonly ConcurrentDictionary<string, GUISprite> _sprites = new();
private readonly ConcurrentDictionary<string, GUISpriteSheet> _spriteSheets = new();
private readonly ConcurrentDictionary<string, GUICursor> _cursors = new();
private readonly ConcurrentDictionary<string, GUIColor> _colors = new();
/// <summary>
/// Only for internal reference.
/// </summary>
private UIStyleFile _fakeFile;
private IStorageService _storageService;
public UIStylesCollection(ContentPath path, IStorageService storageService) : base(path.ContentPackage, path)
{
Guard.IsNotNull(path, nameof(path));
Guard.IsNotNull(path.ContentPackage, nameof(path.ContentPackage));
_storageService = storageService;
_fakeFile = new UIStyleFile(path.ContentPackage, path);
}
public new ContentPath Path => base.Path;
public Result<GUIFont> GetFont(string name)
{
using var lck = _lock.AcquireReaderLock().ConfigureAwait(false).GetAwaiter().GetResult();
IService.CheckDisposed(this);
if (_fonts.TryGetValue(name, out var asset))
{
return asset;
}
return FluentResults.Result.Fail($"{nameof(GetFont)}: Failed to find the font with the name '{name}'");
}
public Result<GUISprite> GetSprite(string name)
{
using var lck = _lock.AcquireReaderLock().ConfigureAwait(false).GetAwaiter().GetResult();
IService.CheckDisposed(this);
if (_sprites.TryGetValue(name, out var asset))
{
return asset;
}
return FluentResults.Result.Fail($"{nameof(GetSprite)}: Failed to find the sprite with the name '{name}'");
}
public Result<GUISpriteSheet> GetSpriteSheet(string name)
{
using var lck = _lock.AcquireReaderLock().ConfigureAwait(false).GetAwaiter().GetResult();
IService.CheckDisposed(this);
if (_spriteSheets.TryGetValue(name, out var asset))
{
return asset;
}
return FluentResults.Result.Fail($"{nameof(GetSpriteSheet)}: Failed to find the spritesheet with the name '{name}'");
}
public Result<GUICursor> GetCursor(string name)
{
using var lck = _lock.AcquireReaderLock().ConfigureAwait(false).GetAwaiter().GetResult();
IService.CheckDisposed(this);
if (_cursors.TryGetValue(name, out var asset))
{
return asset;
}
return FluentResults.Result.Fail($"{nameof(GetCursor)}: Failed to find the cursor with the name '{name}'");
}
public Result<GUIColor> GetColor(string name)
{
using var lck = _lock.AcquireReaderLock().ConfigureAwait(false).GetAwaiter().GetResult();
IService.CheckDisposed(this);
if (_colors.TryGetValue(name, out var asset))
{
return asset;
}
return FluentResults.Result.Fail($"{nameof(GetColor)}: Failed to find the color with the name '{name}'");
}
public override void LoadFile()
{
using var lck = _lock.AcquireWriterLock().ConfigureAwait(false).GetAwaiter().GetResult();
IService.CheckDisposed(this);
if (_storageService.LoadPackageXml(Path) is not { IsSuccess: true } result)
{
DebugConsole.LogError($"Failed to load xml from {Path.FullPath}.");
ThrowHelper.ThrowArgumentException($"Failed to load xml from {Path.FullPath}.");
return;
}
var root = result.Value.Root?.FromPackage(Path.ContentPackage);
if (root is null)
{
return;
}
var styleElement = root.Name.LocalName.ToLowerInvariant() == "style" ? root : root.GetChildElement("style");
if (styleElement is null)
return;
var childElements = styleElement.GetChildElements("Font");
if (childElements is not null)
AddToList<GUIFont, GUIFontPrefab>(_fonts, childElements, _fakeFile);
childElements = styleElement.GetChildElements("Sprite");
if (childElements is not null)
AddToList<GUISprite, GUISpritePrefab>(_sprites, childElements, _fakeFile);
childElements = styleElement.GetChildElements("Spritesheet");
if (childElements is not null)
AddToList<GUISpriteSheet, GUISpriteSheetPrefab>(_spriteSheets, childElements, _fakeFile);
childElements = styleElement.GetChildElements("Cursor");
if (childElements is not null)
AddToList<GUICursor, GUICursorPrefab>(_cursors, childElements, _fakeFile);
childElements = styleElement.GetChildElements("Color");
if (childElements is not null)
AddToList<GUIColor, GUIColorPrefab>(_colors, childElements, _fakeFile);
void AddToList<T1, T2>(ConcurrentDictionary<string, T1> dict, IEnumerable<ContentXElement> elem, UIStyleFile file) where T1 : GUISelector<T2> where T2 : GUIPrefab
{
foreach (ContentXElement prefabElement in elem)
{
string name = prefabElement.GetAttributeString("name", string.Empty);
if (name != string.Empty)
{
var prefab = (T2)Activator.CreateInstance(typeof(T2), new object[]{ prefabElement, file })!;
if (!dict.ContainsKey(name))
dict[name] = (T1)Activator.CreateInstance(typeof(T1), new object[] { name })!;
dict[name].Prefabs.Add(prefab, false);
}
}
}
}
public override void UnloadFile()
{
using var lck = _lock.AcquireWriterLock().ConfigureAwait(false).GetAwaiter().GetResult();
IService.CheckDisposed(this);
_fonts.Values.ForEach(p => p.Prefabs.RemoveByFile(_fakeFile));
_sprites.Values.ForEach(p => p.Prefabs.RemoveByFile(_fakeFile));
_spriteSheets.Values.ForEach(p => p.Prefabs.RemoveByFile(_fakeFile));
_cursors.Values.ForEach(p => p.Prefabs.RemoveByFile(_fakeFile));
_colors.Values.ForEach(p => p.Prefabs.RemoveByFile(_fakeFile));
}
public override void Sort()
{
using var lck = _lock.AcquireWriterLock().ConfigureAwait(false).GetAwaiter().GetResult();
IService.CheckDisposed(this);
_fonts.Values.ForEach(p => p.Prefabs.Sort());
_sprites.Values.ForEach(p => p.Prefabs.Sort());
_spriteSheets.Values.ForEach(p => p.Prefabs.Sort());
_cursors.Values.ForEach(p => p.Prefabs.Sort());
_colors.Values.ForEach(p => p.Prefabs.Sort());
}
#region INTERNAL_DISPOSE
private readonly AsyncReaderWriterLock _lock = new();
public void Dispose()
{
using var lck = _lock.AcquireWriterLock().ConfigureAwait(false).GetAwaiter().GetResult();
if (!ModUtils.Threading.CheckIfClearAndSetBool(ref _isDisposed))
{
return;
}
_fonts.Values.ForEach(p => p.Prefabs.RemoveByFile(_fakeFile));
_sprites.Values.ForEach(p => p.Prefabs.RemoveByFile(_fakeFile));
_spriteSheets.Values.ForEach(p => p.Prefabs.RemoveByFile(_fakeFile));
_cursors.Values.ForEach(p => p.Prefabs.RemoveByFile(_fakeFile));
_colors.Values.ForEach(p => p.Prefabs.RemoveByFile(_fakeFile));
_fonts.Clear();
_sprites.Clear();
_spriteSheets.Clear();
_cursors.Clear();
_colors.Clear();
}
private int _isDisposed;
public bool IsDisposed
{
get => ModUtils.Threading.GetBool(ref _isDisposed);
private set => ModUtils.Threading.SetBool(ref _isDisposed, value);
}
#endregion
}
@@ -0,0 +1,350 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Linq;
using Barotrauma.LuaCs.Data;
using FluentResults;
using Microsoft.Toolkit.Diagnostics;
namespace Barotrauma.LuaCs;
public class UIStylesService : IUIStylesService
{
#region DISPOSAL
public void Dispose()
{
using var lck = _lock.AcquireWriterLock().ConfigureAwait(false).GetAwaiter().GetResult();
if (!ModUtils.Threading.CheckIfClearAndSetBool(ref _isDisposed))
{
return;
}
foreach (var collection in _stylesCollections.Values.SelectMany(c => c))
{
try
{
collection.Dispose();
}
catch
{
//ignored
}
}
_stylesCollections.Clear();
_storageService.Dispose();
_stylesCollectionFactory.Dispose();
_storageService = null;
_stylesCollectionFactory = null;
}
private int _isDisposed = 0;
public bool IsDisposed
{
get => ModUtils.Threading.GetBool(ref _isDisposed);
private set => ModUtils.Threading.SetBool(ref _isDisposed, value);
}
public FluentResults.Result Reset()
{
using var lck = _lock.AcquireWriterLock().ConfigureAwait(false).GetAwaiter().GetResult();
IService.CheckDisposed(this);
var result = FluentResults.Result.Ok();
foreach (var collection in _stylesCollections.Values.SelectMany(c => c))
{
try
{
collection.Dispose();
}
catch (Exception e)
{
result.WithError(new ExceptionalError(e));
}
}
_stylesCollections.Clear();
return result;
}
private readonly AsyncReaderWriterLock _lock = new();
#endregion
private IStorageService _storageService;
private IUIStylesCollection.IFactory _stylesCollectionFactory;
private ConcurrentDictionary<(ContentPackage Package, string InternalName), ImmutableArray<IUIStylesCollection>>
_stylesCollections = new();
public UIStylesService(IUIStylesCollection.IFactory stylesCollectionFactory, IStorageService storageService)
{
_stylesCollectionFactory = stylesCollectionFactory;
_storageService = storageService;
}
public Result<GUIColor> GetColor(ContentPackage package, string internalName, string assetName)
{
using var lck = _lock.AcquireReaderLock().ConfigureAwait(false).GetAwaiter().GetResult();
IService.CheckDisposed(this);
Guard.IsNotNull(package, nameof(package));
Guard.IsNotNullOrWhiteSpace(internalName, nameof(internalName));
Guard.IsNotNullOrWhiteSpace(assetName, nameof(assetName));
if (!_stylesCollections.TryGetValue((package, internalName), out var collection)
|| collection.IsDefaultOrEmpty)
{
return FluentResults.Result.Fail(
$"{nameof(UIStylesService)}: No styles loaded for [ContentPackage].[InternalName] of: [{package.Name}].[{internalName}]");
}
var failedResult = new FluentResults.Result();
foreach (var stylesCollection in collection)
{
var res = stylesCollection.GetColor(assetName);
if (res.IsSuccess)
{
return res;
}
failedResult.WithErrors(res.Errors);
}
return failedResult;
}
public Result<GUICursor> GetCursor(ContentPackage package, string internalName, string assetName)
{
using var lck = _lock.AcquireReaderLock().ConfigureAwait(false).GetAwaiter().GetResult();
IService.CheckDisposed(this);
Guard.IsNotNull(package, nameof(package));
Guard.IsNotNullOrWhiteSpace(internalName, nameof(internalName));
Guard.IsNotNullOrWhiteSpace(assetName, nameof(assetName));
if (!_stylesCollections.TryGetValue((package, internalName), out var collection)
|| collection.IsDefaultOrEmpty)
{
return FluentResults.Result.Fail(
$"{nameof(UIStylesService)}: No styles loaded for [ContentPackage].[InternalName] of: [{package.Name}].[{internalName}]");
}
var failedResult = new FluentResults.Result();
foreach (var stylesCollection in collection)
{
var res = stylesCollection.GetCursor(assetName);
if (res.IsSuccess)
{
return res;
}
failedResult.WithErrors(res.Errors);
}
return failedResult;
}
public Result<GUIFont> GetFont(ContentPackage package, string internalName, string assetName)
{
using var lck = _lock.AcquireReaderLock().ConfigureAwait(false).GetAwaiter().GetResult();
IService.CheckDisposed(this);
Guard.IsNotNull(package, nameof(package));
Guard.IsNotNullOrWhiteSpace(internalName, nameof(internalName));
Guard.IsNotNullOrWhiteSpace(assetName, nameof(assetName));
if (!_stylesCollections.TryGetValue((package, internalName), out var collection)
|| collection.IsDefaultOrEmpty)
{
return FluentResults.Result.Fail(
$"{nameof(UIStylesService)}: No styles loaded for [ContentPackage].[InternalName] of: [{package.Name}].[{internalName}]");
}
var failedResult = new FluentResults.Result();
foreach (var stylesCollection in collection)
{
var res = stylesCollection.GetFont(assetName);
if (res.IsSuccess)
{
return res;
}
failedResult.WithErrors(res.Errors);
}
return failedResult;
}
public Result<GUISprite> GetSprite(ContentPackage package, string internalName, string assetName)
{
using var lck = _lock.AcquireReaderLock().ConfigureAwait(false).GetAwaiter().GetResult();
IService.CheckDisposed(this);
Guard.IsNotNull(package, nameof(package));
Guard.IsNotNullOrWhiteSpace(internalName, nameof(internalName));
Guard.IsNotNullOrWhiteSpace(assetName, nameof(assetName));
if (!_stylesCollections.TryGetValue((package, internalName), out var collection)
|| collection.IsDefaultOrEmpty)
{
return FluentResults.Result.Fail(
$"{nameof(UIStylesService)}: No styles loaded for [ContentPackage].[InternalName] of: [{package.Name}].[{internalName}]");
}
var failedResult = new FluentResults.Result();
foreach (var stylesCollection in collection)
{
var res = stylesCollection.GetSprite(assetName);
if (res.IsSuccess)
{
return res;
}
failedResult.WithErrors(res.Errors);
}
return failedResult;
}
public Result<GUISpriteSheet> GetSpriteSheet(ContentPackage package, string internalName, string assetName)
{
using var lck = _lock.AcquireReaderLock().ConfigureAwait(false).GetAwaiter().GetResult();
IService.CheckDisposed(this);
Guard.IsNotNull(package, nameof(package));
Guard.IsNotNullOrWhiteSpace(internalName, nameof(internalName));
Guard.IsNotNullOrWhiteSpace(assetName, nameof(assetName));
if (!_stylesCollections.TryGetValue((package, internalName), out var collection)
|| collection.IsDefaultOrEmpty)
{
return FluentResults.Result.Fail(
$"{nameof(UIStylesService)}: No styles loaded for [ContentPackage].[InternalName] of: [{package.Name}].[{internalName}]");
}
var failedResult = new FluentResults.Result();
foreach (var stylesCollection in collection)
{
var res = stylesCollection.GetSpriteSheet(assetName);
if (res.IsSuccess)
{
return res;
}
failedResult.WithErrors(res.Errors);
}
return failedResult;
}
public FluentResults.Result LoadAssets(ImmutableArray<IStylesResourceInfo> resources)
{
using var lck = _lock.AcquireReaderLock().ConfigureAwait(false).GetAwaiter().GetResult();
IService.CheckDisposed(this);
if (resources.IsDefaultOrEmpty)
{
ThrowHelper.ThrowArgumentNullException(nameof(resources));
}
var operationSuccess = FluentResults.Result.Ok();
foreach (var resource in resources)
{
var builder = ImmutableArray.CreateBuilder<IUIStylesCollection>();
if (_stylesCollections.TryGetValue((resource.OwnerPackage, resource.InternalName), out var collection))
{
builder.AddRange(collection);
}
try
{
var newCollections = _stylesCollectionFactory.CreateInstance(resource, _storageService).ToImmutableArray();
foreach (var stylesCollection in newCollections)
{
stylesCollection.LoadFile();
}
builder.AddRange(newCollections);
}
catch (Exception e)
{
operationSuccess.WithError(new ExceptionalError(e));
continue;
}
_stylesCollections[(resource.OwnerPackage, resource.InternalName)] = builder.ToImmutable();
}
return operationSuccess;
}
public FluentResults.Result UnloadPackages(ImmutableArray<ContentPackage> packages)
{
using var lck = _lock.AcquireWriterLock().ConfigureAwait(false).GetAwaiter().GetResult();
IService.CheckDisposed(this);
var toRemove = _stylesCollections
.Select(c => c.Key)
.Where(c => packages.Contains(c.Package))
.ToImmutableArray();
var result = FluentResults.Result.Ok();
foreach (var key in toRemove)
{
if (_stylesCollections.TryRemove(key, out var collection) && !collection.IsDefaultOrEmpty)
{
foreach (var stylesCollection in collection)
{
try
{
stylesCollection.UnloadFile();
}
catch (Exception e)
{
result.WithError(new ExceptionalError(e));
}
}
}
}
return result;
}
public FluentResults.Result UnloadPackage(ContentPackage package)
{
// Yes, this is very cursed/inefficient. We don't care.
return UnloadPackages(new [] { package }.ToImmutableArray());
}
public FluentResults.Result UnloadAllPackages()
{
using var lck = _lock.AcquireWriterLock().ConfigureAwait(false).GetAwaiter().GetResult();
IService.CheckDisposed(this);
var result = FluentResults.Result.Ok();
foreach (var key in _stylesCollections.Keys.ToImmutableArray())
{
if (_stylesCollections.TryRemove(key, out var collection) && !collection.IsDefaultOrEmpty)
{
foreach (var stylesCollection in collection)
{
try
{
stylesCollection.UnloadFile();
}
catch (Exception e)
{
result.WithError(new ExceptionalError(e));
}
}
}
}
return result;
}
}
@@ -0,0 +1,7 @@
namespace Barotrauma.LuaCs;
public interface IClientLoggerService : IReusableService
{
void AddToGUIUpdateList();
void ShowErrorOverlay(string message, float time = 5f, float duration = 1.5f);
}
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using Barotrauma.LuaCs.Data;
using Barotrauma.LuaCs;
using Barotrauma.Networking;
namespace Barotrauma.LuaCs;
public partial interface IConfigService
{
ImmutableArray<ISettingBase> GetDisplayableConfigs();
}
@@ -0,0 +1,6 @@
namespace Barotrauma.LuaCs;
public interface ISettingsMenuSystem : ISystem
{
}
@@ -0,0 +1,75 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using Barotrauma.LuaCs.Data;
using FluentResults;
namespace Barotrauma.LuaCs;
public interface IUIStylesCollection : IService
{
public interface IFactory : IService
{
/// <summary>
/// Returns a new <see cref="IUIStylesCollection"/> for-each <see cref="ContentPath"/> in the given
/// <see cref="IStylesResourceInfo.FilePaths"/> or empty is none.
/// </summary>
/// <param name="info"></param>
/// <param name="storageService"></param>
/// <returns></returns>
IEnumerable<IUIStylesCollection> CreateInstance(IStylesResourceInfo info, IStorageService storageService);
}
/// <summary>
/// The assigned/target <see cref="ContentPath"/> for this collection.
/// </summary>
public ContentPath Path { get; }
/// <summary>
/// Gets the <see cref="GUIFont"/> with the given name.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public Result<GUIFont> GetFont(string name);
/// <summary>
/// Gets the <see cref="GUISprite"/> with the given name.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public Result<GUISprite> GetSprite(string name);
/// <summary>
/// Gets the <see cref="GUISpriteSheet"/> with the given name.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public Result<GUISpriteSheet> GetSpriteSheet(string name);
/// <summary>
/// Gets the <see cref="GUICursor"/> with the given name.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public Result<GUICursor> GetCursor(string name);
/// <summary>
/// Gets the <see cref="GUIColor"/> with the given name.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public Result<GUIColor> GetColor(string name);
#region BAROTRAUMA.UISTYLEFILE
/// <summary>
/// Definition of <see cref="HashlessFile.LoadFile"/>
/// </summary>
internal void LoadFile();
/// <summary>
/// Definition of <see cref="HashlessFile.UnloadFile"/>
/// </summary>
internal void UnloadFile();
/// <summary>
/// Definition of <see cref="HashlessFile.Sort"/>
/// </summary>
internal void Sort();
#endregion
}
@@ -0,0 +1,57 @@
using System.Collections.Immutable;
using Barotrauma.LuaCs.Data;
using FluentResults;
namespace Barotrauma.LuaCs;
public interface IUIStylesService : IReusableService
{
/// <summary>
/// Gets the first loaded <see cref="GUIColor"/>.
/// </summary>
/// <param name="package">The target <see cref="ContentPackage"/></param>
/// <param name="internalName">The targets <see cref="IDataInfo.InternalName"/> as specified in the ModConfig.xml.</param>
/// <param name="assetName">The asset's name as specified in the styles XML file.</param>
/// <returns>A <see cref="FluentResults.Result"/> indicating success, and the target if succeeded.</returns>
public Result<GUIColor> GetColor(ContentPackage package, string internalName, string assetName);
/// <summary>
/// Gets the loaded <see cref="GUICursor"/>.
/// </summary>
/// <param name="package">The target <see cref="ContentPackage"/></param>
/// <param name="internalName">The targets <see cref="IDataInfo.InternalName"/> as specified in the ModConfig.xml.</param>
/// <param name="assetName">The asset's name as specified in the styles XML file.</param>
/// <returns>A <see cref="FluentResults.Result"/> indicating success, and the target if succeeded.</returns>
public Result<GUICursor> GetCursor(ContentPackage package, string internalName, string assetName);
/// <summary>
/// Gets the loaded <see cref="GUIFont"/>.
/// </summary>
/// <param name="package">The target <see cref="ContentPackage"/></param>
/// <param name="internalName">The targets <see cref="IDataInfo.InternalName"/> as specified in the ModConfig.xml.</param>
/// <param name="assetName">The asset's name as specified in the styles XML file.</param>
/// <returns>A <see cref="FluentResults.Result"/> indicating success, and the target if succeeded.</returns>
public Result<GUIFont> GetFont(ContentPackage package, string internalName, string assetName);
/// <summary>
/// Gets the loaded <see cref="GUISprite"/>.
/// </summary>
/// <param name="package">The target <see cref="ContentPackage"/></param>
/// <param name="internalName">The targets <see cref="IDataInfo.InternalName"/> as specified in the ModConfig.xml.</param>
/// <param name="assetName">The asset's name as specified in the styles XML file.</param>
/// <returns>A <see cref="FluentResults.Result"/> indicating success, and the target if succeeded.</returns>
public Result<GUISprite> GetSprite(ContentPackage package, string internalName, string assetName);
/// <summary>
/// Gets the loaded <see cref="GUISpriteSheet"/>.
/// </summary>
/// <param name="package">The target <see cref="ContentPackage"/></param>
/// <param name="internalName">The targets <see cref="IDataInfo.InternalName"/> as specified in the ModConfig.xml.</param>
/// <param name="assetName">The asset's name as specified in the styles XML file.</param>
/// <returns>A <see cref="FluentResults.Result"/> indicating success, and the target if succeeded.</returns>
public Result<GUISpriteSheet> GetSpriteSheet(ContentPackage package, string internalName, string assetName);
public FluentResults.Result LoadAssets(ImmutableArray<IStylesResourceInfo> resources);
public FluentResults.Result UnloadPackages(ImmutableArray<ContentPackage> packages);
public FluentResults.Result UnloadPackage(ContentPackage package);
public FluentResults.Result UnloadAllPackages();
}
@@ -0,0 +1,22 @@
namespace Barotrauma.LuaCs;
internal sealed class ModsControlsSettingsMenu : ModsSettingsMenuBase
{
public ModsControlsSettingsMenu(GUIFrame contentFrame,
IPackageManagementService packageManagementService,
IConfigService configService,
SettingsMenu settingsMenuInstance) : base(contentFrame, packageManagementService, configService, settingsMenuInstance)
{
}
protected override void DisposeInternal()
{
// TODO: Finish this later.
}
public override void ApplyInstalledModChanges()
{
// TODO: Finish this later.
}
}
@@ -0,0 +1,458 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.Xna.Framework;
using System.Linq;
using System.Numerics;
using Barotrauma.LuaCs.Data;
using Vector2 = Microsoft.Xna.Framework.Vector2;
using Vector4 = Microsoft.Xna.Framework.Vector4;
// ReSharper disable ObjectCreationAsStatement
namespace Barotrauma.LuaCs;
internal sealed class ModsGameplaySettingsMenu : ModsSettingsMenuBase
{
private ImmutableArray<ISettingBase> _settingsInstancesGameplay;
// menu vars
private GUILayoutGroup _modCategoryDisplayGroup, _settingsDisplayGroup;
private string _selectedSearchQuery = string.Empty;
private ContentPackage _selectedContentPackage;
private string _selectedCategory = string.Empty;
private ImmutableArray<ISettingBase> _currentlyDisplayedSettings;
private ILoggerService _loggerService;
private bool _promptOpen = false;
// Note: "static" instead of "const" for Hot Reload and to allow changing at runtime.
// ReSharper disable FieldCanBeMadeReadOnly.Local
// --- UI controls ---
private static float MenuTitleHeight = 0.06f; // (ContentDisplayAreaHeightContainer + MenuTitleHeight) < 1f
private static float ContentDisplayAreaHeightContainer = 0.93f;
private static float ContentDisplayAreaHeightInnerCategories = 0.99f;
private static float ContentDisplayAreaHeightInnerSettings = 0.97f;
private static float ContentLeftRightSplitPosition = 0.3f;
// Search Bar
private static float SearchBarLayoutHeight = 0.06f;
private static float SearchBarLabelWidth = 0.1f;
private static float SearchBarLabelBoxSpacing = 0.05f;
private static float SearchBarTextBoxWidth = 1f - SearchBarLabelWidth - SearchBarLabelBoxSpacing;
// Categories, Packages Display Area
private static float CategoriesDisplayListHeight = 0.945f;
private static float CategoryButtonHeightRelative = 0.122f;
private static float PackageSelectionButtonHeight = 0.07f;
private static Color CategoryButtonHoverSelectColor = new Color(50, 50, 50, 255);
private static Color CategoryButtonTextColor = Color.PeachPuff;
private static Color CategoryButtonTextColorSelected = Color.White;
private static Color CategoryButtonColorPressed = Color.TransparentBlack;
// Settings Display Area
private static float SettingLabelWidth = 0.6f;
private static float SettingControlWidth = 0.4f;
private static float SettingHeight = 0.05625f/ContentDisplayAreaHeightContainer/ContentDisplayAreaHeightInnerSettings;
private static Color SettingEntryLabelTextColor = Color.PeachPuff;
private static string SettingGUIFrameStyle = "";
private static Color? SettingGUIFrameColor = null;
// settings reset
private static Vector2 SettingsResetButtonTopSpacer = new Vector2(0f, 0.02f);
private static Vector2 SettingsResetButtonDimensions = new Vector2(0.3f, 0.05f);
private static string SettingsResetButtonStyle = "GUIButtonSmall";
private static Color SettingsResetButtonColor = Color.DarkOliveGreen;
private static Color SettingsResetButtonHoverColor = Color.Olive;
private static Color SettingsResetButtonTextColor = Color.PeachPuff;
private static Color SettingsResetButtonTextColorSelected = Color.White;
private static Vector2 ResetConfirmationPromptDimensions = new Vector2(0.15f, 0.2f);
// ReSharper restore FieldCanBeMadeReadOnly.Local
private const string SettingsResetButtonText = "LuaCsForBarotrauma.SettingsMenu.ResetVisibleSettings";
private const string SettingsResetPromptTitle = "LuaCsForBarotrauma.SettingsMenu.ResetPrompt.Title";
private const string SettingsResetPromptContents = "LuaCsForBarotrauma.SettingsMenu.ResetPrompt.Message";
private const string SettingsResetPromptYesText = "LuaCsForBarotrauma.SettingsMenu.ResetPrompt.Yes";
private const string SettingsResetPromptNoText = "LuaCsForBarotrauma.SettingsMenu.ResetPrompt.No";
private event Action OnApplyInstalledModsChanges;
public ModsGameplaySettingsMenu(GUIFrame contentFrame,
IPackageManagementService packageManagementService,
IConfigService configService,
ILoggerService loggerService,
SettingsMenu settingsMenuInstance) : base(contentFrame, packageManagementService, configService, settingsMenuInstance)
{
_settingsInstancesGameplay = configService.GetDisplayableConfigs()
.ToImmutableArray();
_loggerService = loggerService;
var mainLayoutGroup = new GUILayoutGroup(new RectTransform(new Vector2(1f, 1f), contentFrame.RectTransform, Anchor.Center), false, Anchor.TopLeft);
// page title
var menuTitleLayoutGroup = new GUILayoutGroup(
new RectTransform(new Vector2(1f, MenuTitleHeight), mainLayoutGroup.RectTransform, Anchor.TopLeft), true, Anchor.TopLeft);
GUIUtil.Label(menuTitleLayoutGroup,
GetLocalizedString("LuaCsForBarotrauma.SettingsMenu.ModGameplayButton", "Mod Gameplay Settings"),
GUIStyle.LargeFont, new Vector2(1f, 1f));
// page contents
var contentAreaLayoutGroup = new GUILayoutGroup(
new RectTransform(new Vector2(1f, 0.94f), mainLayoutGroup.RectTransform, Anchor.BottomLeft), false,
Anchor.TopLeft);
var searchBarLayoutGroup = new GUILayoutGroup(
new RectTransform(new Vector2(1f, SearchBarLayoutHeight), contentAreaLayoutGroup.RectTransform, Anchor.TopCenter), true, Anchor.CenterLeft);
GUIUtil.Label(searchBarLayoutGroup, "Search: ", GUIStyle.SubHeadingFont, new Vector2(SearchBarLabelWidth, 1f));
var searchBar = new GUITextBox(
new RectTransform(new Vector2(SearchBarTextBoxWidth, 0.1f), searchBarLayoutGroup.RectTransform, Anchor.TopLeft),
createClearButton: true)
{
OnTextChangedDelegate = (btn, txt) =>
{
GenerateDisplayFromFilter(txt);
return true;
}
};
// main display area
var settingsContentAreaGroup = new GUILayoutGroup(new RectTransform(new Vector2(1f, ContentDisplayAreaHeightContainer), contentAreaLayoutGroup.RectTransform, Anchor.BottomCenter));
GUIUtil.Spacer(settingsContentAreaGroup, Vector2.One);
(_modCategoryDisplayGroup, _settingsDisplayGroup) = GUIUtil.CreateSidebars(settingsContentAreaGroup, true);
_modCategoryDisplayGroup.RectTransform.RelativeSize = new Vector2(ContentLeftRightSplitPosition, ContentDisplayAreaHeightInnerCategories);
_settingsDisplayGroup.RectTransform.RelativeSize = new Vector2(1f-ContentLeftRightSplitPosition, ContentDisplayAreaHeightInnerSettings);
// default category
_selectedCategory = "All";
OnApplyInstalledModsChanges = () =>
{
_settingsInstancesGameplay = configService.GetDisplayableConfigs()
.ToImmutableArray();
if (_selectedContentPackage is not null && !GetTargetPackagesList().Contains(_selectedContentPackage))
{
_selectedContentPackage = null;
_selectedCategory = string.Empty;
}
GenerateCategoryListDisplay(_modCategoryDisplayGroup, GetTargetPackagesList(), GetDisplayCategoriesList());
GenerateSettingsListDisplay(_settingsDisplayGroup, GetDisplaySettingsList());
};
GenerateCategoryListDisplay(_modCategoryDisplayGroup, GetTargetPackagesList(), GetDisplayCategoriesList());
GenerateSettingsListDisplay(_settingsDisplayGroup, GetDisplaySettingsList());
void GenerateDisplayFromFilter(string text)
{
_selectedSearchQuery = text;
GenerateCategoryListDisplay(_modCategoryDisplayGroup, GetTargetPackagesList(), GetDisplayCategoriesList());
GenerateSettingsListDisplay(_settingsDisplayGroup, GetDisplaySettingsList());
}
string GetLocalizedString(string identifier, string defaultValue)
{
var lstr = TextManager.Get(identifier);
return lstr.IsNullOrWhiteSpace() ? defaultValue : lstr.Value;
}
// Filters by selected package and query text
ImmutableArray<string> GetDisplayCategoriesList()
{
return GetFilteredSettingsList()
.Select(s => GetLocalizedString(s.GetDisplayInfo().DisplayCategory, "General"))
.Concat(new []{ "All" })
.Distinct()
.OrderBy(s => s)
.ToImmutableArray();
}
// Filters by query text
ImmutableArray<ContentPackage> GetTargetPackagesList()
{
return _settingsInstancesGameplay
.Where(s => SettingMatchesQuery(s, _selectedSearchQuery))
.Select(s => s.OwnerPackage)
.Concat(new[] { ContentPackageManager.VanillaCorePackage })
.Distinct()
.OrderByDescending(p => p == ContentPackageManager.VanillaCorePackage ? 0 : 1)
.ThenBy(p => p.Name)
.ToImmutableArray();
}
// Filters by selected package, query text, and selected category.
ImmutableArray<ISettingBase> GetDisplaySettingsList()
{
return GetFilteredSettingsList()
.Where(s => _selectedCategory.IsNullOrWhiteSpace()
|| _selectedCategory == "All"
|| GetLocalizedString(s.GetDisplayInfo().DisplayCategory, "General") == _selectedCategory)
.OrderBy(s => GetLocalizedString(s.GetDisplayInfo().DisplayName, s.InternalName))
.ToImmutableArray();
}
// Filters by selected package and by query text.
ImmutableArray<ISettingBase> GetFilteredSettingsList()
{
return _settingsInstancesGameplay
.Where(s => SettingMatchesQuery(s, _selectedSearchQuery))
.Where(s => _selectedContentPackage is null
|| _selectedContentPackage == ContentPackageManager.VanillaCorePackage // vanilla is treated as all packages
|| s.OwnerPackage == _selectedContentPackage)
.OrderBy(s => GetLocalizedString(s.GetDisplayInfo().DisplayName, s.InternalName))
.ToImmutableArray();
}
bool SettingMatchesQuery(ISettingBase setting, string queryText)
{
if (queryText.IsNullOrWhiteSpace())
{
return true;
}
queryText = queryText.ToLowerInvariant().Trim();
if (setting.InternalName.ToLowerInvariant().Trim().Contains(queryText) || setting.OwnerPackage.Name.ToLowerInvariant().Trim().Contains(queryText))
{
return true;
}
var displayInfo = setting.GetDisplayInfo();
return TextManager.Get(displayInfo.DisplayName).Value.ToLowerInvariant().Trim().Contains(queryText)
|| TextManager.Get(displayInfo.DisplayCategory).Value.ToLowerInvariant().Trim().Contains(queryText)
|| TextManager.Get(displayInfo.Description).Value.ToLowerInvariant().Trim().Contains(queryText)
|| TextManager.Get(displayInfo.Tooltip).Value.ToLowerInvariant().Trim().Contains(queryText);
}
string GetPackageName(ContentPackage package)
{
return package is null || package == ContentPackageManager.VanillaCorePackage ? "All" : package.Name;
}
ContentPackage GetCurrentSelectedPackage(ImmutableArray<ContentPackage> packages)
{
if (_selectedContentPackage is null)
{
return ContentPackageManager.VanillaCorePackage;
}
if (packages.Contains(_selectedContentPackage))
{
return _selectedContentPackage;
}
if (packages.Length > 0)
{
_selectedContentPackage = packages[0];
return packages[0];
}
return null;
}
void GenerateCategoryListDisplay(GUILayoutGroup layoutGroup, ImmutableArray<ContentPackage> packagesList,
ImmutableArray<string> categories)
{
layoutGroup.ClearChildren();
var packageSelectionList = GUIUtil.Dropdown<ContentPackage>(layoutGroup, cp => GetPackageName(cp), null,
packagesList, GetCurrentSelectedPackage(packagesList), cp =>
{
_selectedContentPackage = cp;
_selectedCategory = string.Empty;
GenerateCategoryListDisplay(_modCategoryDisplayGroup, GetTargetPackagesList(), GetDisplayCategoriesList());
GenerateSettingsListDisplay(_settingsDisplayGroup, GetDisplaySettingsList());
}, new Vector2(1f, PackageSelectionButtonHeight));
var containerBox = new GUIListBox(new RectTransform(new Vector2(1f, CategoriesDisplayListHeight), layoutGroup.RectTransform));
float sizeY = MathF.Max(categories.Length * CategoryButtonHeightRelative, 1f);
var displayedCategoriesFrame = new GUIFrame(new RectTransform(new Vector2(1f, sizeY), containerBox.Content.RectTransform), style: null, color: Color.Black)
{
CanBeFocused = false
};
var displayCategoriesLayout = new GUILayoutGroup(new RectTransform(Vector2.One, displayedCategoriesFrame.RectTransform));
foreach (var category in categories)
{
var btn = new GUIButton(new RectTransform(new Vector2(1f, CategoryButtonHeightRelative), displayCategoriesLayout.RectTransform),
text: category, color: Color.TransparentBlack)
{
CanBeFocused = true,
CanBeSelected = true,
TextColor = CategoryButtonTextColor,
HoverColor = CategoryButtonHoverSelectColor,
HoverTextColor = CategoryButtonTextColorSelected,
PressedColor = CategoryButtonColorPressed,
SelectedColor = CategoryButtonHoverSelectColor,
SelectedTextColor = CategoryButtonHoverSelectColor,
OnClicked = (btn, obj) =>
{
_selectedCategory = category;
GenerateSettingsListDisplay(_settingsDisplayGroup, GetDisplaySettingsList());
return true;
}
};
}
}
void GenerateSettingsListDisplay(GUILayoutGroup layoutGroup, ImmutableArray<ISettingBase> settings)
{
layoutGroup.ClearChildren();
_currentlyDisplayedSettings = settings;
var containerBox = new GUIListBox(new RectTransform(new Vector2(1f, 1f-SettingsResetButtonDimensions.Y), layoutGroup.RectTransform));
foreach (var setting in settings)
{
var entry = AddSettingToDisplay(
setting,
containerBox.Content.RectTransform,
settingHeight: SettingHeight,
labelSize: new Vector2(SettingLabelWidth, 1f),
controlSize: new Vector2(SettingControlWidth, 1f));
}
var spacer = new GUIFrame(new RectTransform(SettingsResetButtonTopSpacer, layoutGroup.RectTransform),
style: null, color: Color.TransparentBlack);
var resetSettingsButton = new GUIButton(
new RectTransform(SettingsResetButtonDimensions, layoutGroup.RectTransform),
GetLocalizedString(SettingsResetButtonText, "Reset Visible Settings"),
style: SettingsResetButtonStyle)
{
CanBeSelected = true,
CanBeFocused = true,
Color = SettingsResetButtonColor,
HoverColor = SettingsResetButtonHoverColor,
SelectedColor = SettingsResetButtonHoverColor,
SelectedTextColor = SettingsResetButtonTextColorSelected,
TextColor = SettingsResetButtonTextColor,
OnClicked = (btn, obj) =>
{
DisplayResetConfirmationPrompt(settings);
return true;
}
};
}
(GUIFrame entryFrame, GUILayoutGroup entryLayoutGroup)
AddSettingToDisplay(ISettingBase setting, RectTransform parent, float settingHeight, Vector2 labelSize, Vector2 controlSize)
{
GUIFrame entryFrame = new GUIFrame(new RectTransform(new Vector2(1f, settingHeight), parent),
style: SettingGUIFrameStyle, color: SettingGUIFrameColor)
{
Color = Color.DarkGray
};
GUILayoutGroup entryLayoutGroup = new GUILayoutGroup(new RectTransform(Vector2.One, entryFrame.RectTransform), isHorizontal: true);
// padding
new GUIFrame(new RectTransform(new Vector2(0.02f, 1f), entryLayoutGroup.RectTransform),
color: Color.TransparentBlack);
// setting label
new GUITextBlock(new RectTransform(labelSize - new Vector2(0.05f, 0f), entryLayoutGroup.RectTransform),
GetLocalizedString(setting.GetDisplayInfo().DisplayName, setting.GetDisplayInfo().DisplayName),
textColor: SettingEntryLabelTextColor,
font: GUIStyle.SmallFont,
textAlignment: Alignment.Left)
{
ToolTip = GetLocalizedString(setting.GetDisplayInfo().Tooltip, string.Empty)
};
setting.AddDisplayComponent(entryLayoutGroup, controlSize, newValue =>
{
NewValuesCache[setting] = newValue;
});
return (entryFrame, entryLayoutGroup);
}
void DisplayResetConfirmationPrompt(ImmutableArray<ISettingBase> settings)
{
if (_promptOpen)
{
return;
}
_promptOpen = true;
var msgBox = new GUIMessageBox(GetLocalizedString(SettingsResetPromptTitle, "Reset Visible Settings"),
GetLocalizedString(SettingsResetPromptContents,
"Are you sure you want to reset the values for currently displayed settings?"),
new LocalizedString[]
{
GetLocalizedString(SettingsResetPromptYesText, "Yes"),
GetLocalizedString(SettingsResetPromptNoText, "No")
}, ResetConfirmationPromptDimensions);
msgBox.Buttons[0].OnClicked = (btn, obj) =>
{
ResetValuesForDisplayedSettings(settings);
btn.Visible = false;
_promptOpen = false;
msgBox.Close();
return true;
};
msgBox.Buttons[1].OnClicked = (btn, obj) =>
{
btn.Visible = false;
_promptOpen = false;
msgBox.Close();
return true;
};
}
void ResetValuesForDisplayedSettings(ImmutableArray<ISettingBase> settings)
{
if (settings.IsDefaultOrEmpty)
{
return;
}
NewValuesCache.Clear();
foreach (var setting in settings)
{
var str = setting.GetDefaultStringValue();
NewValuesCache[setting] = str;
loggerService.LogDebug($"Resetting value for {setting.InternalName} to '{str}'");
}
ApplyInstalledModChanges();
}
}
protected override void DisposeInternal()
{
NewValuesCache.Clear();
_modCategoryDisplayGroup?.Parent.RemoveChild(_modCategoryDisplayGroup);
_settingsDisplayGroup?.Parent.RemoveChild(_settingsDisplayGroup);
_modCategoryDisplayGroup = null;
_settingsDisplayGroup = null;
}
public override void ApplyInstalledModChanges()
{
foreach (var kvp in NewValuesCache)
{
if (kvp.Key.IsDisposed)
{
continue;
}
var success = kvp.Key.TrySetSerializedValue(kvp.Value);
if (success)
{
ConfigService.SaveConfigValue(kvp.Key);
_loggerService.LogDebug($"Applied save value for {kvp.Key.InternalName} of {kvp.Value.ToString()}");
}
}
NewValuesCache.Clear();
OnApplyInstalledModsChanges?.Invoke();
}
}
@@ -0,0 +1,42 @@
using System;
using System.Collections.Concurrent;
using System.Xml.Linq;
using Barotrauma.Extensions;
using Barotrauma.LuaCs.Data;
using Microsoft.Xna.Framework;
using OneOf;
namespace Barotrauma.LuaCs;
internal abstract class ModsSettingsMenuBase : IDisposable
{
public GUIFrame ContentFrame { get; private set; }
protected IPackageManagementService PackageManagementService { get; private set; }
protected IConfigService ConfigService { get; private set; }
protected SettingsMenu SettingsMenuInstance { get; private set; }
protected readonly ConcurrentDictionary<ISettingBase, OneOf<string, XElement>> NewValuesCache = new();
protected ModsSettingsMenuBase(GUIFrame contentFrame,
IPackageManagementService packageManagementService,
IConfigService configService, SettingsMenu settingsMenuInstance)
{
ContentFrame = contentFrame;
PackageManagementService = packageManagementService;
ConfigService = configService;
SettingsMenuInstance = settingsMenuInstance;
}
protected abstract void DisposeInternal();
public abstract void ApplyInstalledModChanges();
public void Dispose()
{
DisposeInternal();
ContentFrame?.Parent.RemoveChild(ContentFrame);
SettingsMenuInstance = null;
ContentFrame = null;
PackageManagementService = null;
ConfigService = null;
NewValuesCache.Clear();
}
}
@@ -0,0 +1,125 @@
using System;
using System.Linq;
using Barotrauma.Extensions;
using HarmonyLib;
using Microsoft.Xna.Framework;
namespace Barotrauma.LuaCs;
public class SettingsMenuSystem : ISettingsMenuSystem
{
private ModsControlsSettingsMenu _controlsMenuInstance;
private ModsGameplaySettingsMenu _gameplayMenuInstance;
private GUIFrame _gameplayContentFrame;
private GUIFrame _controlsContentFrame;
private SettingsMenu _settingsMenuInstance;
private readonly Harmony _harmony;
private readonly IPackageManagementService _packageManagementService;
private readonly IConfigService _configService;
private readonly ILoggerService _loggerService;
private static SettingsMenuSystem SystemInstance;
public SettingsMenuSystem(IPackageManagementService packageManagementService, IConfigService configService, ILoggerService loggerService)
{
_packageManagementService = packageManagementService;
_configService = configService;
_loggerService = loggerService;
SystemInstance = this;
_harmony = Harmony.CreateAndPatchAll(typeof(SettingsMenuSystem));
}
[HarmonyPatch(typeof(SettingsMenu), "CreateModsTab"), HarmonyPostfix]
private static void SettingsMenu_CreateModsTab_Post(SettingsMenu __instance)
{
SystemInstance._settingsMenuInstance = __instance;
SystemInstance.CreateSettingsMenu(__instance);
}
private void CreateSettingsMenu(SettingsMenu __instance)
{
DisposeMenuFrames();
var tabCount = Enum.GetValues<SettingsMenu.Tab>().Length;
var tabGameplayIndex = (SettingsMenu.Tab)tabCount;
var tabControlsIndex = (SettingsMenu.Tab)tabCount+1;
_gameplayContentFrame = CreateNewContentTab(tabGameplayIndex, __instance,
GUIStyle.ComponentStyles.ContainsKey("SettingsMenuTab.LuaCsSettings") ? "SettingsMenuTab.LuaCsSettings" : "SettingsMenuTab.Mods",
"LuaCsForBarotrauma.SettingsMenu.ModGameplayButton");
/*_controlsContentFrame = CreateNewContentTab(tabControlsIndex, __instance,
"SettingsMenuTab.Controls", "LuaCsForBarotrauma.SettingsMenu.ModControlsButton");
*/
_gameplayMenuInstance = new ModsGameplaySettingsMenu(_gameplayContentFrame, _packageManagementService, _configService, _loggerService, __instance);
//_controlsMenuInstance = new ModsControlsSettingsMenu(_controlsContentFrame, _packageManagementService, _configService, __instance);
}
private GUIFrame CreateNewContentTab(SettingsMenu.Tab tab, SettingsMenu settingsMenuInstance, string settingsMenuTabName, string settingMenuHoverTextIdent)
{
if (settingsMenuInstance.tabContents.TryGetValue(tab, out (GUIButton Button, GUIFrame Content) tabContent))
{
return tabContent.Content;
}
var contentFr = new GUIFrame(new RectTransform(Vector2.One * 0.95f, settingsMenuInstance.contentFrame.RectTransform, Anchor.Center, Pivot.Center), style: null);
var button = new GUIButton(new RectTransform(Vector2.One, settingsMenuInstance.tabber.RectTransform,
Anchor.TopLeft, Pivot.TopLeft, scaleBasis: ScaleBasis.Smallest), "", style: settingsMenuTabName)
{
ToolTip = TextManager.Get(settingMenuHoverTextIdent),
OnClicked = (b, _) =>
{
settingsMenuInstance.SelectTab(tab);
return false;
}
};
button.RectTransform.MaxSize = RectTransform.MaxPoint;
button.Children.ForEach(c => c.RectTransform.MaxSize = RectTransform.MaxPoint);
settingsMenuInstance.tabContents.Add(tab, (button, contentFr));
return contentFr;
}
[HarmonyPatch(typeof(SettingsMenu), nameof(SettingsMenu.ApplyInstalledModChanges)), HarmonyPostfix]
private static void SettingsMenu_ApplyInstalledModChanges_Post()
{
SystemInstance._gameplayMenuInstance?.ApplyInstalledModChanges();
SystemInstance._controlsMenuInstance?.ApplyInstalledModChanges();
}
private void DisposeMenuFrames()
{
_controlsMenuInstance?.Dispose();
_gameplayMenuInstance?.Dispose();
_controlsMenuInstance = null;
_gameplayMenuInstance = null;
}
#region DISPOSAL
public void Dispose()
{
if (!ModUtils.Threading.CheckIfClearAndSetBool(ref _isDisposed))
{
return;
}
DisposeMenuFrames();
GC.SuppressFinalize(this);
}
private int _isDisposed = 0;
public bool IsDisposed
{
get => ModUtils.Threading.GetBool(ref _isDisposed);
private set => ModUtils.Threading.SetBool(ref _isDisposed, value);
}
public FluentResults.Result Reset()
{
throw new NotImplementedException();
}
#endregion
}