diff --git a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Configuration/IDisplayableConfig.cs b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Configuration/IDisplayableConfig.cs
new file mode 100644
index 000000000..789c00ac0
--- /dev/null
+++ b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Configuration/IDisplayableConfig.cs
@@ -0,0 +1,142 @@
+using System;
+using System.Collections.Generic;
+using Barotrauma.LuaCs.Data;
+
+namespace Barotrauma.LuaCs.Configuration;
+
+
+///
+/// Base type of all menu displayable types.
+///
+public interface IDisplayableConfigBase : IDataInfo, IConfigDisplayInfo
+{
+ ///
+ /// Whether the current config is editable.
+ ///
+ bool IsEditable { get; }
+ ///
+ /// Used to indicate the implemented interface and targeted display logic.
+ ///
+ static virtual DisplayType DisplayOption => DisplayType.Undefined;
+}
+
+public interface IDisplayableConfigBase : IDisplayableConfigBase
+{
+ void SetValue(TValue value);
+ TDisplay GetDisplayValue();
+}
+
+public interface IDisplayableConfigBool : IDisplayableConfigBase
+{
+ static DisplayType IDisplayableConfigBase.DisplayOption => DisplayType.Boolean;
+}
+
+public interface IDisplayableConfigText : IDisplayableConfigBase
+{
+ static DisplayType IDisplayableConfigBase.DisplayOption => DisplayType.Text;
+}
+
+public interface IDisplayableConfigInt : IDisplayableConfigBase
+{
+ static DisplayType IDisplayableConfigBase.DisplayOption => DisplayType.Integer;
+}
+
+public interface IDisplayableConfigFloat : IDisplayableConfigBase
+{
+ static DisplayType IDisplayableConfigBase.DisplayOption => DisplayType.Float;
+}
+
+public interface IDisplayableConfigSliderInt : IDisplayableConfigBase<(int Min, int Max, int Value, int Steps), int>
+{
+ static DisplayType IDisplayableConfigBase.DisplayOption => DisplayType.SliderInt;
+}
+
+public interface IDisplayableConfigSliderFloat : IDisplayableConfigBase<(float Min, float Max, float Value, int Steps), float>
+{
+ static DisplayType IDisplayableConfigBase.DisplayOption => DisplayType.SliderFloat;
+}
+
+public interface IDisplayableConfigDropdown : IDisplayableConfigBase, string>
+{
+ static DisplayType IDisplayableConfigBase.DisplayOption => DisplayType.Dropdown;
+}
+
+///
+/// Allows completely custom-designed UI for this configuration component.
+///
+public interface IDisplayableConfigCustom : IDisplayableConfigBase
+{
+ static DisplayType IDisplayableConfigBase.DisplayOption => DisplayType.Custom;
+ ///
+ /// Draw your menu settings option.
+ ///
+ /// Parent layout component.
+ void DrawComponent(GUILayoutGroup layoutGroup);
+ ///
+ /// Called when the config element is set to be disposed to allow for cleanup.
+ ///
+ void DisposeGUI();
+ ///
+ /// Called when the UI indicates to save the current value as permanent.
+ ///
+ void OnValueSaved();
+ ///
+ /// Called when the UI indicates to discard the currently displayed value and revert to the last saved value.
+ ///
+ void OnValueDiscarded();
+}
+
+
+
+///
+/// Indicates the intended display and feedback logic to be used by the .
+///
[Important]
+///
The type must implement the indicated interface for the selected option, or it will not be displayed.
+///
+public enum DisplayType
+{
+ ///
+ /// Will not be displayed in menus.
+ ///
+ Undefined,
+ ///
+ /// Will be shown as a checkbox.
+ ///
[Requires()]
+ ///
+ Boolean,
+ ///
+ /// Shown as an editable text input.
+ ///
[Requires()]
+ ///
+ Text,
+ ///
+ /// Shown as number input (no decimal input).
+ ///
[Requires()]
+ ///
+ Integer,
+ ///
+ /// Shown as a number input.
+ ///
[Requires()]
+ ///
+ Float,
+ ///
+ /// Shown as a slider, values parsed as integers.
+ ///
[Requires()]
+ ///
+ SliderInt,
+ ///
+ /// Shown as a slider, values parsed as single-precision decimal numbers.
+ ///
[Requires()]
+ ///
+ SliderFloat,
+ ///
+ /// Shown as a menu, values parsed as strings.
+ ///
[Requires()]
+ ///
+ Dropdown,
+ ///
+ /// UI Display is implemented by inheritor and actioned by a call to .
+ ///
[Requires()]
+ ///
+ Custom
+}
diff --git a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Data/DataInterfaceDefinitions.cs b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Data/DataInterfaceDefinitions.cs
deleted file mode 100644
index 570f48f9b..000000000
--- a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Data/DataInterfaceDefinitions.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-using System.Collections.Immutable;
-using System.Globalization;
-
-namespace Barotrauma.LuaCs.Data;
-
-public partial record ModConfigInfo : IModConfigInfo
-{
- public ImmutableArray Styles { get; init; }
-}
-
-public record StylesResourceInfo : IStylesResourceInfo
-{
- public Platform SupportedPlatforms { get; init; }
- public Target SupportedTargets { get; init; }
- public int LoadPriority { get; init; }
- public ImmutableArray FilePaths { get; init; }
- public bool Optional { get; init; }
- public ImmutableArray SupportedCultures { get; init; }
- public string InternalName { get; init; }
- public ContentPackage OwnerPackage { get; init; }
- public string FallbackPackageName { get; init; }
- public ImmutableArray Dependencies { get; init; }
-}
diff --git a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Data/IConfigInfo.cs b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Data/IConfigInfo.cs
index 576d18118..801bc5ac4 100644
--- a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Data/IConfigInfo.cs
+++ b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Data/IConfigInfo.cs
@@ -2,8 +2,22 @@ using Barotrauma.LuaCs.Configuration;
namespace Barotrauma.LuaCs.Data;
-public partial interface IConfigInfo
+public partial interface IConfigInfo : IConfigDisplayInfo { }
+
+public interface IConfigDisplayInfo
{
+ ///
+ /// User-friendly name or Localization Token.
+ ///
+ string DisplayName { get; }
+ ///
+ /// User-friendly description or Localization Token.
+ ///
+ string Description { get; }
+ ///
+ /// The menu category to display under. Used for filtering.
+ ///
+ string DisplayCategory { get; }
///
/// Should this config be displayed in end-user menus.
///
diff --git a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Data/IResourceInfoDeclarations.cs b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Data/IResourceInfoDeclarations.cs
deleted file mode 100644
index de47ef225..000000000
--- a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Data/IResourceInfoDeclarations.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-using System.Collections.Immutable;
-
-namespace Barotrauma.LuaCs.Data;
-
-public partial interface IModConfigInfo : IStylesResourcesInfo { }
-
-public interface IStylesResourceInfo : IResourceInfo, IResourceCultureInfo, IDataInfo, IPackageDependenciesInfo { }
-
-public interface IStylesResourcesInfo
-{
- ///
- /// Collection of loadable styles data.
- ///
- ImmutableArray Styles { get; }
-}
diff --git a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Data/IStylesInfo.cs b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Data/IStylesInfo.cs
deleted file mode 100644
index b3e2a456b..000000000
--- a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Data/IStylesInfo.cs
+++ /dev/null
@@ -1,6 +0,0 @@
-namespace Barotrauma.LuaCs.Data;
-
-public interface IStylesInfo
-{
-
-}
diff --git a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/LuaCsSetup.cs b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/LuaCsSetup.cs
index 19649aea8..894641c17 100644
--- a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/LuaCsSetup.cs
+++ b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/LuaCsSetup.cs
@@ -22,9 +22,6 @@ namespace Barotrauma
}
private partial bool ShouldRunCs() => IsCsEnabled.Value;
-
- public IStylesManagementService StylesManagementService => _servicesProvider.TryGetService(out var svc)
- ? svc : throw new NullReferenceException("Networking Manager service not found!");
public void CheckCsEnabled()
{
diff --git a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/ConfigService.cs b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/ConfigService.cs
new file mode 100644
index 000000000..a628969b2
--- /dev/null
+++ b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/ConfigService.cs
@@ -0,0 +1,26 @@
+using System;
+using System.Collections.Immutable;
+using Barotrauma.LuaCs.Configuration;
+using Barotrauma.LuaCs.Data;
+using Barotrauma.Networking;
+using FluentResults;
+
+namespace Barotrauma.LuaCs.Services;
+
+public partial class ConfigService
+{
+ public ImmutableArray GetDisplayableConfigs()
+ {
+ throw new NotImplementedException();
+ }
+
+ public ImmutableArray GetDisplayableConfigsForPackage(ContentPackage package)
+ {
+ throw new NotImplementedException();
+ }
+
+ public Result AddConfigControl(IConfigInfo configInfo)
+ {
+ throw new NotImplementedException();
+ }
+}
diff --git a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/IConfigService.cs b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/IConfigService.cs
index 89b2316a3..cbe7bf94d 100644
--- a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/IConfigService.cs
+++ b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/IConfigService.cs
@@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
+using System.Collections.Immutable;
using Barotrauma.LuaCs.Configuration;
+using Barotrauma.LuaCs.Data;
using Barotrauma.LuaCs.Services;
using Barotrauma.Networking;
@@ -8,28 +10,8 @@ namespace Barotrauma.LuaCs.Services;
public partial interface IConfigService
{
- /*
- * Immediate mode
- */
- FluentResults.Result> AddConfigEntry(IDisplayableData data,
- T defaultValue,
- NetSync syncMode = NetSync.None,
- ClientPermissions permissions = ClientPermissions.None,
- Func valueChangePredicate = null,
- Action> onValueChanged = null) where T : IConvertible, IEquatable;
-
- FluentResults.Result AddConfigList(IDisplayableData data,
- int defaultIndex, IReadOnlyList values,
- NetSync syncMode = NetSync.None,
- ClientPermissions permissions = ClientPermissions.None,
- Func valueChangePredicate = null,
- Action onValueChanged = null);
+ ImmutableArray GetDisplayableConfigs();
+ ImmutableArray GetDisplayableConfigsForPackage(ContentPackage package);
- FluentResults.Result> AddConfigRangeEntry(IDisplayableData data,
- T defaultValue, T minValue, T maxValue,
- Func, int> getStepCount,
- NetSync syncMode = NetSync.None,
- ClientPermissions permissions = ClientPermissions.None,
- Func valueChangePredicate = null,
- Action> onValueChanged = null) where T : IConvertible, IEquatable;
+ FluentResults.Result AddConfigControl(IConfigInfo configInfo);
}
diff --git a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/IStylesManagementService.cs b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/IStylesManagementService.cs
deleted file mode 100644
index dc5dfc69a..000000000
--- a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/IStylesManagementService.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-using System.Collections.Immutable;
-using System.Threading.Tasks;
-using Barotrauma.LuaCs.Data;
-
-namespace Barotrauma.LuaCs.Services;
-
-public interface IStylesManagementService : IReusableService
-{
- Task LoadStylesAsync(ImmutableArray styles);
- FluentResults.Result GetStylesService(ContentPackage package);
- Task DisposeAllStyles();
- Task DisposeStylesForPackage(ContentPackage package);
-}
diff --git a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/IStylesService.cs b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/IStylesService.cs
deleted file mode 100644
index 26c8b2404..000000000
--- a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/IStylesService.cs
+++ /dev/null
@@ -1,58 +0,0 @@
-using System.Threading.Tasks;
-
-namespace Barotrauma.LuaCs.Services;
-
-// TODO: Rework interface to support resource infos.
-///
-/// Loads XML Style assets from the given content package.
-///
-public interface IStylesService : IService
-{
- ///
- /// Tries to load the styles file for the given and path into a new instance.
- ///
- ///
- ///
- ///
- Task LoadStylesFileAsync(ContentPackage package, ContentPath path);
-
- ///
- /// Unloads all styles assets and instances.
- ///
- FluentResults.Result UnloadAllStyles();
-
- ///
- /// Tries to the get the asset by xml asset name, returns null on failure.
- ///
- /// XML Name of the asset.
- /// The asset or null if none are found.
- GUIFont GetFont(string fontName);
-
- ///
- /// Tries to the get the asset by xml asset name, returns null on failure.
- ///
- /// XML Name of the asset.
- /// The asset or null if none are found.
- GUISprite GetSprite(string spriteName);
-
- ///
- /// Tries to the get the asset by xml asset name, returns null on failure.
- ///
- /// XML Name of the asset.
- /// The asset or null if none are found.
- GUISpriteSheet GetSpriteSheet(string spriteSheetName);
-
- ///
- /// Tries to the get the asset by xml asset name, returns null on failure.
- ///
- /// XML Name of the asset.
- /// The asset or null if none are found.
- GUICursor GetCursor(string cursorName);
-
- ///
- /// Tries to the get the asset by xml asset name, returns null on failure.
- ///
- /// XML Name of the asset.
- /// The asset or null if none are found.
- GUIColor GetColor(string colorName);
-}
diff --git a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/NetworkingService.cs b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/NetworkingService.cs
index 597709cc5..654e2c817 100644
--- a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/NetworkingService.cs
+++ b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/NetworkingService.cs
@@ -1,13 +1,14 @@
using Barotrauma.LuaCs.Services;
using Barotrauma.Networking;
using System;
+using System.Collections.Concurrent;
using System.Collections.Generic;
namespace Barotrauma.LuaCs.Services;
partial class NetworkingService : INetworkingService
{
- private Dictionary> receiveQueue = new Dictionary>();
+ private ConcurrentDictionary> receiveQueue = new();
public void SendSyncMessage()
{
@@ -99,7 +100,7 @@ partial class NetworkingService : INetworkingService
}
else
{
- if (!receiveQueue.ContainsKey(id)) { receiveQueue[id] = new Queue(); }
+ if (!receiveQueue.ContainsKey(id)) { receiveQueue[id] = new ConcurrentQueue(); }
receiveQueue[id].Enqueue(netMessage);
if (GameSettings.CurrentConfig.VerboseLogging)
diff --git a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/PackageManagementService.cs b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/PackageManagementService.cs
deleted file mode 100644
index 7b722751a..000000000
--- a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/PackageManagementService.cs
+++ /dev/null
@@ -1,81 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Linq;
-using System.Threading.Tasks;
-using Barotrauma.LuaCs.Data;
-using Barotrauma.LuaCs.Services.Processing;
-using FluentResults;
-// ReSharper disable UseCollectionExpression
-
-namespace Barotrauma.LuaCs.Services;
-
-public partial class PackageManagementService : IPackageManagementService
-{
- public PackageManagementService(
- IConverterServiceAsync modConfigParserService,
- IProcessorService, IAssembliesResourcesInfo> assemblyInfoConverter,
- IProcessorService, IConfigsResourcesInfo> configsInfoConverter,
- IProcessorService, IConfigProfilesResourcesInfo> configProfilesConverter,
- IProcessorService, ILocalizationsResourcesInfo> localizationsConverter,
- IProcessorService, ILuaScriptsResourcesInfo> luaScriptsConverter,
- IPackageInfoLookupService packageInfoLookupService, Func, IStylesResourcesInfo> stylesInfoConverter)
- {
- _stylesInfoConverter = stylesInfoConverter;
- _modConfigParserService = modConfigParserService;
- _assemblyInfoConverter = assemblyInfoConverter;
- _configsInfoConverter = configsInfoConverter;
- _configProfilesConverter = configProfilesConverter;
- _localizationsConverter = localizationsConverter;
- _luaScriptsConverter = luaScriptsConverter;
- _packageInfoLookupService = packageInfoLookupService;
- }
-
- private readonly Func, IStylesResourcesInfo> _stylesInfoConverter;
-
- public ImmutableArray Styles => _modInfos.IsEmpty ? ImmutableArray.Empty
- : _modInfos.SelectMany(kvp => kvp.Value.Styles).ToImmutableArray();
-
- public Result GetStylesInfos(ContentPackage package, bool onlySupportedResources = true)
- {
- ((IService)this).CheckDisposed();
- if (package is null)
- return FluentResults.Result.Fail($"{nameof(GetStylesInfos)}: ContentPackage is null.");
- if (_modInfos.TryGetValue(package, out var result))
- return FluentResults.Result.Ok(_stylesInfoConverter(onlySupportedResources?
- result.Styles.Where(r =>
- (r.SupportedPlatforms & ModUtils.Environment.CurrentPlatform) > 0
- && (r.SupportedTargets & ModUtils.Environment.CurrentTarget) > 0).ToImmutableArray()
- : result.Styles
- ));
- return FluentResults.Result.Fail(
- $"{nameof(GetStylesInfos)}: ContentPackage {package.Name} is not registered.");
- }
-
- public Result GetStylesInfos(IReadOnlyList packages, bool onlySupportedResources = true)
- {
- ((IService)this).CheckDisposed();
- if (packages is null || packages.Count == 0)
- return FluentResults.Result.Fail($"{nameof(GetStylesInfos)}: ContentPackage list is null or empty.");
- var builder = ImmutableArray.CreateBuilder();
- foreach (var package in packages)
- {
- if (_modInfos.TryGetValue(package, out var result) && result.Styles is { IsEmpty: false })
- {
- builder.AddRange(onlySupportedResources?
- result.Styles.Where(r =>
- (r.SupportedPlatforms & ModUtils.Environment.CurrentPlatform) > 0
- && (r.SupportedTargets & ModUtils.Environment.CurrentTarget) > 0).ToImmutableArray()
- : result.Styles);
- }
- }
-
- return FluentResults.Result.Ok(_stylesInfoConverter(builder.MoveToImmutable()));
- }
-
- public async Task> GetStylesInfosAsync(IReadOnlyList packages, bool onlySupportedResources = true)
- {
- return await Task.Run(() => GetStylesInfos(packages, onlySupportedResources));
-
- }
-}
diff --git a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/Processing/ModConfigService.cs b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/Processing/ModConfigService.cs
index 386a66940..0e46339e7 100644
--- a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/Processing/ModConfigService.cs
+++ b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/Processing/ModConfigService.cs
@@ -14,26 +14,17 @@ public partial class ModConfigService
private partial async Task> GetModConfigInfoAsync(ContentPackage package, XElement root)
{
var asm = root.GetChildElements("Assembly").ToImmutableArray();
- var loc = root.GetChildElements("Localization").ToImmutableArray();
var cfg = root.GetChildElements("Config").ToImmutableArray();
var lua = root.GetChildElements("Lua").ToImmutableArray();
- var stl = root.GetChildElements("Style").ToImmutableArray();
return FluentResults.Result.Ok(new ModConfigInfo()
{
Package = package,
PackageName = package.Name,
Assemblies = asm.Any() ? GetAssemblies(package, asm) : ImmutableArray.Empty,
- Localizations = loc.Any() ? GetLocalizations(package, loc) : ImmutableArray.Empty,
Configs = cfg.Any() ? GetConfigs(package, cfg) : ImmutableArray.Empty,
ConfigProfiles = cfg.Any() ? GetConfigProfiles(package, cfg) : ImmutableArray.Empty,
- LuaScripts = lua.Any() ? GetLuaScripts(package, lua) : ImmutableArray.Empty,
- Styles = stl.Any() ? GetStyles(package, stl) : ImmutableArray.Empty
+ LuaScripts = lua.Any() ? GetLuaScripts(package, lua) : ImmutableArray.Empty
});
}
-
- private ImmutableArray GetStyles(ContentPackage src, IEnumerable elements)
- {
- throw new NotImplementedException();
- }
}
diff --git a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/Processing/StylesManagementService.cs b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/Processing/StylesManagementService.cs
deleted file mode 100644
index 49bd12eb2..000000000
--- a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/Processing/StylesManagementService.cs
+++ /dev/null
@@ -1,6 +0,0 @@
-namespace Barotrauma.LuaCs.Services.Processing;
-
-public class StylesManagementService : IStylesManagementService
-{
-
-}
diff --git a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/StylesService.cs b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/StylesService.cs
deleted file mode 100644
index 6e608a5fc..000000000
--- a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/StylesService.cs
+++ /dev/null
@@ -1,120 +0,0 @@
-using System;
-using System.Collections.Concurrent;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Threading.Tasks;
-using System.Xml.Linq;
-using FluentResults;
-using FluentResults.LuaCs;
-
-namespace Barotrauma.LuaCs.Services;
-
-// TODO: Complete rewrite
-public class StylesService : IStylesService
-{
- private readonly ConcurrentDictionary _loadedProcessors = new();
- private readonly IStorageService _storageService;
- private readonly ILoggerService _loggerService;
-
- public StylesService(IStorageService storageService, ILoggerService loggerService)
- {
- _storageService = storageService;
- _loggerService = loggerService;
- }
-
-
- public async Task LoadStylesFileAsync(ContentPackage package, ContentPath path)
- {
- throw new NotImplementedException();
- }
-
- public FluentResults.Result UnloadAllStyles()
- {
- if (NoProcessorsLoaded)
- return FluentResults.Result.Fail(new Error($"{nameof(StylesService)}.{nameof(UnloadAllStyles)}: No processors have been loaded.")
- .WithMetadata(MetadataType.ExceptionObject, this));
-
- foreach (var processor in _loadedProcessors)
- {
- processor.Value.UnloadFile();
- }
- _loadedProcessors.Clear();
- return FluentResults.Result.Ok();
- }
-
- public GUIFont GetFont(string fontName)
- {
- if (NoProcessorsLoaded)
- return null;
- foreach (var processor in _loadedProcessors.Values)
- {
- if (processor.Fonts.TryGetValue(fontName, out var asset))
- return asset;
- }
-
- return null;
- }
-
- public GUISprite GetSprite(string spriteName)
- {
- if (NoProcessorsLoaded)
- return null;
- foreach (var processor in _loadedProcessors.Values)
- {
- if (processor.Sprites.TryGetValue(spriteName, out var asset))
- return asset;
- }
-
- return null;
- }
-
- public GUISpriteSheet GetSpriteSheet(string spriteSheetName)
- {
- if (NoProcessorsLoaded)
- return null;
- foreach (var processor in _loadedProcessors.Values)
- {
- if (processor.SpriteSheets.TryGetValue(spriteSheetName, out var asset))
- return asset;
- }
-
- return null;
- }
-
- public GUICursor GetCursor(string cursorName)
- {
- if (NoProcessorsLoaded)
- return null;
- foreach (var processor in _loadedProcessors.Values)
- {
- if (processor.Cursors.TryGetValue(cursorName, out var asset))
- return asset;
- }
-
- return null;
- }
-
- public GUIColor GetColor(string colorName)
- {
- if (NoProcessorsLoaded)
- return null;
- foreach (var processor in _loadedProcessors.Values)
- {
- if (processor.Colors.TryGetValue(colorName, out var asset))
- return asset;
- }
-
- return null;
- }
-
- private bool NoProcessorsLoaded => _loadedProcessors.IsEmpty;
-
- public void Dispose()
- {
- UnloadAllStyles();
- GC.SuppressFinalize(this);
- }
-
- public bool IsDisposed { get; private set; }
-}
diff --git a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/UIStyleProcessor.cs b/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/UIStyleProcessor.cs
deleted file mode 100644
index b90276e7a..000000000
--- a/Barotrauma/BarotraumaClient/ClientSource/LuaCs/Services/UIStyleProcessor.cs
+++ /dev/null
@@ -1,93 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Xml.Linq;
-using Barotrauma.Extensions;
-
-namespace Barotrauma.LuaCs.Services;
-
-public class UIStyleProcessor : HashlessFile
-{
- private readonly UIStyleFile _fake;
- public readonly Dictionary Fonts = new();
- public readonly Dictionary Sprites = new();
- public readonly Dictionary SpriteSheets = new();
- public readonly Dictionary Cursors = new();
- public readonly Dictionary Colors = new();
-
- public UIStyleProcessor(ContentPackage contentPackage, ContentPath path) : base(contentPackage, path)
- {
- _fake = new UIStyleFile(contentPackage, path);
- }
-
- public override void LoadFile()
- {
- var element = XMLExtensions.TryLoadXml(path: Path)?.Root?.FromPackage(ContentPackage);
- if (element is null)
- throw new InvalidDataException($"UIStyleProcessor: Failed to load UI style file: {Path}");
-
- var styleElement = element.Name.LocalName.ToLowerInvariant() == "style" ? element : element.GetChildElement("style");
- if (styleElement is null)
- throw new InvalidDataException($"UIStyleProcessor: no 'style' XmlElement found in file: {Path}");
-
- var childElements = styleElement.GetChildElements("Font");
- if (childElements is not null)
- AddToList(Fonts, childElements, _fake);
-
- childElements = styleElement.GetChildElements("Sprite");
- if (childElements is not null)
- AddToList(Sprites, childElements, _fake);
-
- childElements = styleElement.GetChildElements("Spritesheet");
- if (childElements is not null)
- AddToList(SpriteSheets, childElements, _fake);
-
- childElements = styleElement.GetChildElements("Cursor");
- if (childElements is not null)
- AddToList(Cursors, childElements, _fake);
-
- childElements = styleElement.GetChildElements("Color");
- if (childElements is not null)
- AddToList(Colors, childElements, _fake);
-
-
- void AddToList(Dictionary dict, IEnumerable ele, UIStyleFile file) where T1 : GUISelector where T2 : GUIPrefab
- {
- foreach (ContentXElement prefabElement in ele)
- {
- 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()
- {
- Fonts.Values.ForEach(p => p.Prefabs.RemoveByFile(_fake));
- Sprites.Values.ForEach(p => p.Prefabs.RemoveByFile(_fake));
- SpriteSheets.Values.ForEach(p => p.Prefabs.RemoveByFile(_fake));
- Cursors.Values.ForEach(p => p.Prefabs.RemoveByFile(_fake));
- Colors.Values.ForEach(p => p.Prefabs.RemoveByFile(_fake));
-
- Fonts.Clear();
- Sprites.Clear();
- SpriteSheets.Clear();
- Cursors.Clear();
- Colors.Clear();
- }
-
- public override void Sort()
- {
- 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());
- }
-}
diff --git a/Barotrauma/BarotraumaClient/ClientSource/Screens/SubEditorScreen.cs b/Barotrauma/BarotraumaClient/ClientSource/Screens/SubEditorScreen.cs
index 37b5d6e5c..d7b368980 100644
--- a/Barotrauma/BarotraumaClient/ClientSource/Screens/SubEditorScreen.cs
+++ b/Barotrauma/BarotraumaClient/ClientSource/Screens/SubEditorScreen.cs
@@ -12,6 +12,7 @@ using System.Globalization;
using System.Linq;
using System.Threading;
using System.Xml.Linq;
+using Barotrauma.LuaCs.Events;
using Barotrauma.Sounds;
namespace Barotrauma
@@ -1532,7 +1533,7 @@ namespace Barotrauma
{
Select(enableAutoSave: true);
- GameMain.LuaCs.CheckInitialize();
+ GameMain.LuaCs.EventService.PublishEvent(sub => sub.OnScreenSelected(this));
}
public void Select(bool enableAutoSave = true)
diff --git a/Barotrauma/BarotraumaServer/ServerSource/LuaCs/Services/PackageManagementService.cs b/Barotrauma/BarotraumaServer/ServerSource/LuaCs/Services/PackageManagementService.cs
index 435facc4d..99e66743e 100644
--- a/Barotrauma/BarotraumaServer/ServerSource/LuaCs/Services/PackageManagementService.cs
+++ b/Barotrauma/BarotraumaServer/ServerSource/LuaCs/Services/PackageManagementService.cs
@@ -11,7 +11,6 @@ public partial class PackageManagementService
IProcessorService, IAssembliesResourcesInfo> assemblyInfoConverter,
IProcessorService, IConfigsResourcesInfo> configsInfoConverter,
IProcessorService, IConfigProfilesResourcesInfo> configProfilesConverter,
- IProcessorService, ILocalizationsResourcesInfo> localizationsConverter,
IProcessorService, ILuaScriptsResourcesInfo> luaScriptsConverter,
IPackageInfoLookupService packageInfoLookupService)
{
@@ -19,7 +18,6 @@ public partial class PackageManagementService
_assemblyInfoConverter = assemblyInfoConverter;
_configsInfoConverter = configsInfoConverter;
_configProfilesConverter = configProfilesConverter;
- _localizationsConverter = localizationsConverter;
_luaScriptsConverter = luaScriptsConverter;
_packageInfoLookupService = packageInfoLookupService;
}
diff --git a/Barotrauma/BarotraumaServer/ServerSource/LuaCs/Services/Processing/ModConfigService.cs b/Barotrauma/BarotraumaServer/ServerSource/LuaCs/Services/Processing/ModConfigService.cs
index ee93eccf5..3c59ac10e 100644
--- a/Barotrauma/BarotraumaServer/ServerSource/LuaCs/Services/Processing/ModConfigService.cs
+++ b/Barotrauma/BarotraumaServer/ServerSource/LuaCs/Services/Processing/ModConfigService.cs
@@ -15,7 +15,6 @@ public partial class ModConfigService
private partial async Task> GetModConfigInfoAsync(ContentPackage package, XElement root)
{
var asm = root.GetChildElements("Assembly").ToImmutableArray();
- var loc = root.GetChildElements("Localization").ToImmutableArray();
var cfg = root.GetChildElements("Config").ToImmutableArray();
var lua = root.GetChildElements("Lua").ToImmutableArray();
@@ -24,7 +23,6 @@ public partial class ModConfigService
Package = package,
PackageName = package.Name,
Assemblies = asm.Any() ? GetAssemblies(package, asm) : ImmutableArray.Empty,
- Localizations = loc.Any() ? GetLocalizations(package, loc) : ImmutableArray.Empty,
Configs = cfg.Any() ? GetConfigs(package, cfg) : ImmutableArray.Empty,
ConfigProfiles = cfg.Any() ? GetConfigProfiles(package, cfg) : ImmutableArray.Empty,
LuaScripts = lua.Any() ? GetLuaScripts(package, lua) : ImmutableArray.Empty
diff --git a/Barotrauma/BarotraumaShared/Lua/Content/ModConfig.xml b/Barotrauma/BarotraumaShared/Lua/Content/ModConfig.xml
new file mode 100644
index 000000000..e69de29bb
diff --git a/Barotrauma/BarotraumaShared/Lua/Content/Schemas/IModConfig.xsd b/Barotrauma/BarotraumaShared/Lua/Content/Schemas/IModConfig.xsd
new file mode 100644
index 000000000..1908c9960
--- /dev/null
+++ b/Barotrauma/BarotraumaShared/Lua/Content/Schemas/IModConfig.xsd
@@ -0,0 +1,50 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Configuration/ConfigEntry.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Configuration/ConfigEntry.cs
new file mode 100644
index 000000000..4fd22a1cb
--- /dev/null
+++ b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Configuration/ConfigEntry.cs
@@ -0,0 +1,103 @@
+using System;
+using System.Xml.Linq;
+using Barotrauma.LuaCs.Data;
+using Barotrauma.LuaCs.Services;
+using Barotrauma.Networking;
+using OneOf;
+
+namespace Barotrauma.LuaCs.Configuration;
+
+public class ConfigEntry : IConfigEntry where T : IEquatable
+{
+
+ private readonly Action, INetReadMessage> _readMessageHandler;
+ private readonly Action, INetWriteMessage> _writeMessageHandler;
+
+ public ConfigEntry(IConfigInfo configInfo, Action, INetReadMessage> readMessageHandler,
+ Action, INetWriteMessage> writeMessageHandler)
+ {
+ _readMessageHandler = readMessageHandler;
+ _writeMessageHandler = writeMessageHandler;
+ }
+
+ public string InternalName { get; init; }
+ public ContentPackage OwnerPackage { get; init; }
+
+ public bool Equals(IConfigBase other)
+ {
+ if (ReferenceEquals(this, other))
+ return true;
+ throw new NotImplementedException();
+ }
+
+ public void Dispose()
+ {
+ throw new NotImplementedException();
+ }
+
+ public Type GetValueType()
+ {
+ throw new NotImplementedException();
+ }
+
+ public string GetValue()
+ {
+ throw new NotImplementedException();
+ }
+
+ public bool TrySetValue(OneOf value)
+ {
+ throw new NotImplementedException();
+ }
+
+ public bool IsAssignable(OneOf value)
+ {
+ throw new NotImplementedException();
+ }
+
+ private event Action> _onValueChanged;
+ public event Action> OnValueChanged
+ {
+ add => _onValueChanged += value;
+ remove => _onValueChanged -= value;
+ }
+
+ event Action IConfigBase.OnValueChanged
+ {
+ add => _onValueChanged += value;
+ remove => _onValueChanged -= value;
+ }
+
+ public OneOf GetSerializableValue()
+ {
+ throw new NotImplementedException();
+ }
+
+ public Guid InstanceId => throw new NotImplementedException();
+
+ public NetSync SyncType => throw new NotImplementedException();
+
+ public ClientPermissions WritePermissions => throw new NotImplementedException();
+
+ public void ReadNetMessage(INetReadMessage message)
+ {
+ throw new NotImplementedException();
+ }
+
+ public void WriteNetMessage(INetWriteMessage message)
+ {
+ throw new NotImplementedException();
+ }
+
+ public T Value => throw new NotImplementedException();
+
+ public bool TrySetValue(T value)
+ {
+ throw new NotImplementedException();
+ }
+
+ public bool IsAssignable(T value)
+ {
+ throw new NotImplementedException();
+ }
+}
diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Configuration/ConfigList.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Configuration/ConfigList.cs
new file mode 100644
index 000000000..d67d09e7d
--- /dev/null
+++ b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Configuration/ConfigList.cs
@@ -0,0 +1,111 @@
+using System;
+using System.Collections.Generic;
+using System.Xml.Linq;
+using Barotrauma.LuaCs.Data;
+using Barotrauma.LuaCs.Services;
+using Barotrauma.Networking;
+using OneOf;
+
+namespace Barotrauma.LuaCs.Configuration;
+
+public class ConfigList : IConfigList where T : IEquatable
+{
+ private readonly Action, INetReadMessage> _readMessageHandler;
+ private readonly Action, INetWriteMessage> _writeMessageHandler;
+
+ public ConfigList(IConfigInfo configInfo, Action, INetReadMessage> readMessageHandler,
+ Action, INetWriteMessage> writeMessageHandler)
+ {
+ _readMessageHandler = readMessageHandler;
+ _writeMessageHandler = writeMessageHandler;
+ }
+
+ public string InternalName => throw new NotImplementedException();
+
+ public ContentPackage OwnerPackage => throw new NotImplementedException();
+
+ public bool Equals(IConfigBase other)
+ {
+ throw new NotImplementedException();
+ }
+
+ public void Dispose()
+ {
+ throw new NotImplementedException();
+ }
+
+ public Type GetValueType()
+ {
+ throw new NotImplementedException();
+ }
+
+ public string GetValue()
+ {
+ throw new NotImplementedException();
+ }
+
+ public bool TrySetValue(OneOf value)
+ {
+ throw new NotImplementedException();
+ }
+
+ public bool IsAssignable(OneOf value)
+ {
+ throw new NotImplementedException();
+ }
+
+ private event Action> _onValueChanged;
+
+ public event Action> OnValueChanged
+ {
+ add => _onValueChanged += value;
+ remove => _onValueChanged -= value;
+ }
+
+ event Action> IConfigEntry.OnValueChanged
+ {
+ add => _onValueChanged += value;
+ remove => _onValueChanged -= value;
+ }
+
+ event Action IConfigBase.OnValueChanged
+ {
+ add => _onValueChanged += value;
+ remove => _onValueChanged -= value;
+ }
+
+ public T Value => throw new NotImplementedException();
+
+ public bool TrySetValue(T value)
+ {
+ throw new NotImplementedException();
+ }
+
+ public bool IsAssignable(T value)
+ {
+ throw new NotImplementedException();
+ }
+
+ public OneOf GetSerializableValue()
+ {
+ throw new NotImplementedException();
+ }
+
+ public Guid InstanceId => throw new NotImplementedException();
+
+ public NetSync SyncType => throw new NotImplementedException();
+
+ public ClientPermissions WritePermissions => throw new NotImplementedException();
+
+ public void ReadNetMessage(INetReadMessage message)
+ {
+ throw new NotImplementedException();
+ }
+
+ public void WriteNetMessage(INetWriteMessage message)
+ {
+ throw new NotImplementedException();
+ }
+
+ public IReadOnlyList Options => throw new NotImplementedException();
+}
diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Configuration/IConfigBase.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Configuration/IConfigBase.cs
index 87334e592..8e65f68b5 100644
--- a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Configuration/IConfigBase.cs
+++ b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Configuration/IConfigBase.cs
@@ -1,20 +1,17 @@
using System;
+using System.Xml.Linq;
using Barotrauma.LuaCs.Data;
+using Barotrauma.LuaCs.Services;
using Barotrauma.Networking;
namespace Barotrauma.LuaCs.Configuration;
-public partial interface IConfigBase : IVarId
+public partial interface IConfigBase : IDataInfo, IEquatable, IDisposable
{
- bool IsInitialized { get; }
- string GetValue();
- bool TrySetValue(string value);
- bool IsAssignable(string value);
Type GetValueType();
- void Initialize(IVarId id, string defaultValue);
-}
-
-public interface IVarId : IDataInfo
-{
- Guid InstanceId { get; }
+ string GetValue();
+ bool TrySetValue(OneOf.OneOf value);
+ bool IsAssignable(OneOf.OneOf value);
+ event Action OnValueChanged;
+ OneOf.OneOf GetSerializableValue();
}
diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Configuration/IConfigEntry.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Configuration/IConfigEntry.cs
index a39032258..9b173233a 100644
--- a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Configuration/IConfigEntry.cs
+++ b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Configuration/IConfigEntry.cs
@@ -3,10 +3,10 @@ using Barotrauma.LuaCs.Services;
namespace Barotrauma.LuaCs.Configuration;
-public interface IConfigEntry : IConfigBase, INetVar where T : IConvertible, IEquatable
+public interface IConfigEntry : IConfigBase, INetworkSyncEntity where T : IEquatable
{
T Value { get; }
bool TrySetValue(T value);
bool IsAssignable(T value);
- void Initialize(IVarId id, T defaultValue);
+ new event Action> OnValueChanged;
}
diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Configuration/IConfigEnum.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Configuration/IConfigEnum.cs
new file mode 100644
index 000000000..742f80a46
--- /dev/null
+++ b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Configuration/IConfigEnum.cs
@@ -0,0 +1,9 @@
+using System;
+using Barotrauma.LuaCs.Services;
+
+namespace Barotrauma.LuaCs.Configuration;
+
+public interface IConfigEnum : IConfigBase, INetworkSyncEntity
+{
+
+}
diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Configuration/IConfigList.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Configuration/IConfigList.cs
index 0d291f215..d78b5779d 100644
--- a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Configuration/IConfigList.cs
+++ b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Configuration/IConfigList.cs
@@ -1,8 +1,11 @@
+using System;
+using System.Collections.Generic;
using Barotrauma.LuaCs.Services;
namespace Barotrauma.LuaCs.Configuration;
-public interface IConfigList : IConfigBase, INetVar
+public interface IConfigList : IConfigEntry, INetworkSyncEntity where T : IEquatable
{
-
+ IReadOnlyList Options { get; }
+ new event Action> OnValueChanged;
}
diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/DataInterfaceDefinitions.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/DataInterfaceImplementations.cs
similarity index 86%
rename from Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/DataInterfaceDefinitions.cs
rename to Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/DataInterfaceImplementations.cs
index 6dd98c625..790c7c9cd 100644
--- a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/DataInterfaceDefinitions.cs
+++ b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/DataInterfaceImplementations.cs
@@ -5,7 +5,10 @@ using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
+using System.Xml.Linq;
+using Barotrauma.LuaCs.Services;
using Barotrauma.Steam;
+using OneOf;
namespace Barotrauma.LuaCs.Data;
@@ -16,7 +19,6 @@ public partial record ModConfigInfo : IModConfigInfo
public ContentPackage Package { get; init; }
public string PackageName { get; init; }
public ImmutableArray Assemblies { get; init; }
- public ImmutableArray Localizations { get; init; }
public ImmutableArray LuaScripts { get; init; }
public ImmutableArray Configs { get; init; }
public ImmutableArray ConfigProfiles { get; init; }
@@ -24,10 +26,9 @@ public partial record ModConfigInfo : IModConfigInfo
#endregion
-#region DataContracts
+#region DataContracts_Resources
public record AssemblyResourcesInfo(ImmutableArray Assemblies) : IAssembliesResourcesInfo;
-public record LocalizationResourcesInfo(ImmutableArray Localizations) : ILocalizationsResourcesInfo;
public record LuaScriptsResourcesInfo(ImmutableArray LuaScripts) : ILuaScriptsResourcesInfo;
public record ConfigResourcesInfo(ImmutableArray Configs) : IConfigsResourcesInfo;
public record ConfigProfilesResourcesInfo(ImmutableArray ConfigProfiles) : IConfigProfilesResourcesInfo;
@@ -161,20 +162,7 @@ public record ConfigProfileResourceInfo : IConfigProfileResourceInfo
public ContentPackage OwnerPackage { get; init; }
}
-public record LocalizationResourceInfo : ILocalizationResourceInfo
-{
- public string InternalName { get; init; }
- public ContentPackage OwnerPackage { get; init; }
- public Platform SupportedPlatforms { get; init; }
- public Target SupportedTargets { get; init; }
- public int LoadPriority { get; init; }
- public ImmutableArray FilePaths { get; init; }
- public ImmutableArray SupportedCultures { get; init; }
- public ImmutableArray Dependencies { get; init; }
- public bool Optional { get; init; }
-}
-
-public readonly struct LuaScriptScriptResourceInfo : ILuaScriptResourceInfo
+public readonly struct LuaScriptsResourceInfo : ILuaScriptResourceInfo
{
public ContentPackage OwnerPackage { get; init; }
public Platform SupportedPlatforms { get; init; }
@@ -189,3 +177,34 @@ public readonly struct LuaScriptScriptResourceInfo : ILuaScriptResourceInfo
}
#endregion
+
+#region DataContracts_ParsedInfo
+
+public record ConfigInfo : IConfigInfo
+{
+ public string InternalName { get; init; }
+ public ContentPackage OwnerPackage { get; init; }
+ public Type DataType { get; init; }
+ public OneOf DefaultValue { get; init; }
+ public OneOf Value { get; init; }
+ public RunState EditableStates { get; init; }
+ public NetSync NetSync { get; init; }
+
+#if CLIENT // IConfigDisplayInfo
+ public string DisplayName { get; init; }
+ public string Description { get; init; }
+ public string DisplayCategory { get; init; }
+ public bool ShowInMenus { get; init; }
+ public string Tooltip { get; init; }
+ public string ImageIconPath { get; init; }
+#endif
+}
+
+public record ConfigProfileInfo : IConfigProfileInfo
+{
+ public string InternalName { get; init; }
+ public ContentPackage OwnerPackage { get; init; }
+ public IReadOnlyList<(string ConfigName, OneOf Value)> ProfileValues { get; init; }
+}
+
+#endregion
diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/IConfigInfo.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/IConfigInfo.cs
index cfa46a629..4d8a5e5ea 100644
--- a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/IConfigInfo.cs
+++ b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/IConfigInfo.cs
@@ -1,51 +1,43 @@
using System;
+using System.Xml.Linq;
using Barotrauma.LuaCs.Services;
using Barotrauma.Networking;
namespace Barotrauma.LuaCs.Data;
-// TODO: Finish
+///
+/// Parsed data from a configuration xml.
+///
public partial interface IConfigInfo : IDataInfo
{
///
- /// Specifies the data type this should be initialized to (ie. string, int, vector, etc.)
- /// Custom types can be registered by mods.
+ /// Specifies the type initializer that will be used to instantiate the config var.
///
Type DataType { get; }
///
- /// String version of the default value.
+ /// The default value.
///
- string DefaultValue { get; }
+ OneOf.OneOf DefaultValue { get; }
///
- /// The value the last time this config was saved, if found in /data/.
+ /// The value the last time this config was saved. If not found, returns the default value.
+ ///
[If(Type='')]
+ /// The value is from the 'Value' Attribute. Typically used for types with single/simple values, such as primitives.
+ ///
[If(Type='')]
+ /// The value is from the first 'Value' child element. Typically used with complex config types, such as range and list.
///
- string StoredValue { get; }
+ OneOf.OneOf Value { get; }
///
- /// Custom data storage for other type-specific information needed. IE. Used to store the min,
- /// max and step values for the IConfigRangeEntry(T).
+ /// In what (s) is this config editable. Will be editable in the selected state, and lower value states.
+ ///
+ /// [Important]
Setting this to value lower than 'Configuration` will render this config read-only.
+ ///
Expected Behaviour:
+ ///
[|]: Read-Only.
+ ///
[]: Can only be changed at the Main Menu (not in a lobby).
+ ///
[]: Can be changed at the Main Menu and while a lobby is active.
///
- string CustomParameters { get; }
- ///
- /// [Multiplayer]
- /// What permissions do clients require to change this setting.
- ///
- ClientPermissions RequiredPermissions { get; }
- ///
- /// In what s is this config editable.
- ///
- /// Note: Setting this to value lower than 'Configuration` will render this config read-only.
- ///
- RunState CanEditStates { get; }
+ RunState EditableStates { get; }
///
/// Network synchronization rules for this config.
///
NetSync NetSync { get; }
- ///
- /// User friendly name or Localization Token.
- ///
- string DisplayName { get; }
- ///
- /// User friendly description or Localization Token.
- ///
- string Description { get; }
}
diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/IConfigProfileInfo.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/IConfigProfileInfo.cs
index 7be1db56c..d60fb2772 100644
--- a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/IConfigProfileInfo.cs
+++ b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/IConfigProfileInfo.cs
@@ -1,6 +1,9 @@
-namespace Barotrauma.LuaCs.Data;
+using System.Collections.Generic;
+using System.Xml.Linq;
-public interface IConfigProfileInfo
+namespace Barotrauma.LuaCs.Data;
+
+public interface IConfigProfileInfo : IDataInfo
{
-
+ IReadOnlyList<(string ConfigName, OneOf.OneOf Value)> ProfileValues { get; }
}
diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/ILocalizationInfo.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/ILocalizationInfo.cs
deleted file mode 100644
index b74b1f275..000000000
--- a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/ILocalizationInfo.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-using System.Collections.Generic;
-using System.Globalization;
-
-namespace Barotrauma.LuaCs.Data;
-
-public interface ILocalizationInfo : IDataInfo
-{
- string Symbol { get; }
- IReadOnlyDictionary LocalizedValues { get; }
- RawLString GetLocalizedString(CultureInfo locale);
- RawLString GetLocalizedString(string cultureCode);
-}
diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/IModConfigInfo.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/IModConfigInfo.cs
index 7d60bf562..cdecd9037 100644
--- a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/IModConfigInfo.cs
+++ b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/IModConfigInfo.cs
@@ -3,7 +3,7 @@
namespace Barotrauma.LuaCs.Data;
public partial interface IModConfigInfo : IAssembliesResourcesInfo,
- ILocalizationsResourcesInfo, ILuaScriptsResourcesInfo, IConfigsResourcesInfo,
+ ILuaScriptsResourcesInfo, IConfigsResourcesInfo,
IConfigProfilesResourcesInfo
{
// package info
diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/IResourceInfoDeclarations.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/IResourceInfoDeclarations.cs
index ad6bb45d3..777bd24d1 100644
--- a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/IResourceInfoDeclarations.cs
+++ b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/IResourceInfoDeclarations.cs
@@ -6,7 +6,6 @@ namespace Barotrauma.LuaCs.Data;
public interface IConfigResourceInfo : IResourceInfo, IResourceCultureInfo, IPackageDependenciesInfo, IDataInfo { }
public interface IConfigProfileResourceInfo : IResourceInfo, IResourceCultureInfo, IPackageDependenciesInfo, IDataInfo { }
-public interface ILocalizationResourceInfo : IResourceInfo, IResourceCultureInfo, IPackageDependenciesInfo, IDataInfo { }
///
/// Represents loadable Lua files.
@@ -40,11 +39,6 @@ public interface IAssembliesResourcesInfo
ImmutableArray Assemblies { get; }
}
-public interface ILocalizationsResourcesInfo
-{
- ImmutableArray Localizations { get; }
-}
-
public interface ILuaScriptsResourcesInfo
{
ImmutableArray LuaScripts { get; }
diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/ServicesConfigData.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/ServicesConfigData.cs
new file mode 100644
index 000000000..f3e3bab2d
--- /dev/null
+++ b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Data/ServicesConfigData.cs
@@ -0,0 +1,206 @@
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using System.Collections.ObjectModel;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using System.Security.AccessControl;
+using Barotrauma.Networking;
+using FluentResults;
+
+namespace Barotrauma.LuaCs.Data;
+
+
+// --- Storage Service
+public interface IStorageServiceConfig
+{
+ string LocalModsDirectory { get; }
+ string WorkshopModsDirectory { get; }
+ string GameSettingsConfigPath { get; }
+#if CLIENT
+ string TempDownloadsDirectory { get; }
+#endif
+
+ //ReadOnlyCollection SafeIOReadDirectories { get; }
+ //ReadOnlyCollection SafeIOWriteDirectories { get; }
+ IEnumerable GlobalIOReadWhitelist();
+ IEnumerable GlobalIOWriteWhitelist();
+
+ bool IOReadWhiteListContains(string filePath);
+ bool IOWriteWhiteListContains(string filePath);
+
+ string LocalDataSavePath { get; }
+ string LocalDataPathRegex { get; }
+ string LocalPackageDataPath { get; }
+ public string RunLocation { get; }
+ bool GlobalSafeIOEnabled { get; }
+}
+
+internal interface IStorageServiceConfigUpdate
+{
+ public FluentResults.Result SetSafeReadFilePaths(string[] filePaths);
+ public FluentResults.Result SetSafeWriteFilePaths(string[] filePaths);
+}
+
+public record StorageServiceConfig : IStorageServiceConfig, IStorageServiceConfigUpdate
+{
+ private static readonly string ExecutionLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location.CleanUpPath());
+
+ public string LocalModsDirectory { get; init; } = System.IO.Path.GetFullPath(ContentPackage.LocalModsDir).CleanUpPath();
+ public string WorkshopModsDirectory { get; init; } = System.IO.Path.GetFullPath(ContentPackage.WorkshopModsDir).CleanUpPath();
+ public string GameSettingsConfigPath { get; init; } = System.IO.Path.GetFullPath(
+ string.IsNullOrEmpty(GameSettings.CurrentConfig.SavePath)
+ ? SaveUtil.DefaultSaveFolder
+ : GameSettings.CurrentConfig.SavePath).CleanUpPath();
+#if CLIENT
+ public string TempDownloadsDirectory { get; init; } = System.IO.Path.GetFullPath(ModReceiver.DownloadFolder).CleanUpPath();
+#endif
+
+ private readonly AsyncReaderWriterLock _safeIOReadLock = new();
+ private readonly AsyncReaderWriterLock _safeIOWriteLock = new();
+ private readonly ConcurrentDictionary _safeIOReadFilePaths = new();
+
+ private readonly ConcurrentDictionary _safeIOWriteFilePaths = new();
+
+ public IEnumerable GlobalIOReadWhitelist()
+ {
+ using var lck = _safeIOReadLock.AcquireReaderLock().GetAwaiter().GetResult();
+
+ if (_safeIOReadFilePaths.Count == 0)
+ {
+ yield break;
+ }
+
+ foreach (var path in _safeIOReadFilePaths)
+ {
+ yield return path.Key;
+ }
+ }
+
+ public IEnumerable GlobalIOWriteWhitelist()
+ {
+ using var lck = _safeIOWriteLock.AcquireReaderLock().GetAwaiter().GetResult();
+
+ if (_safeIOWriteFilePaths.Count == 0)
+ {
+ yield break;
+ }
+
+ foreach (var path in _safeIOWriteFilePaths)
+ {
+ yield return path.Key;
+ }
+ }
+
+ public bool IOReadWhiteListContains(string filePath)
+ {
+ if (filePath.IsNullOrWhiteSpace())
+ return false;
+ return _safeIOReadFilePaths.ContainsKey(filePath);
+ }
+
+ public bool IOWriteWhiteListContains(string filePath)
+ {
+ if (filePath.IsNullOrWhiteSpace())
+ return false;
+ return _safeIOWriteFilePaths.ContainsKey(filePath);
+ }
+
+ public string LocalDataSavePath => Path.Combine(ExecutionLocation, "/Data/Mods/");
+
+ public string LocalDataPathRegex => "";
+
+ public string RunLocation => ExecutionLocation;
+ public bool GlobalSafeIOEnabled => false;
+
+ public string LocalPackageDataPath
+ {
+ get
+ {
+ return ContainsIllegalPaths(LocalDataSavePath) ? $"/Data/Mods/{LocalDataPathRegex}"
+ : Path.Combine(LocalDataSavePath, LocalDataPathRegex);
+
+ bool ContainsIllegalPaths(string path)
+ {
+ throw new NotImplementedException();
+ }
+ }
+ }
+
+
+ public FluentResults.Result SetSafeReadFilePaths(string[] filePaths)
+ {
+ using var lck = _safeIOReadLock.AcquireWriterLock().GetAwaiter().GetResult();
+ return SetSafeDirectory(_safeIOReadFilePaths, filePaths);
+ }
+
+ public FluentResults.Result SetSafeWriteFilePaths(string[] filePaths)
+ {
+ using var lck = _safeIOWriteLock.AcquireWriterLock().GetAwaiter().GetResult();
+ return SetSafeDirectory(_safeIOWriteFilePaths, filePaths);
+ }
+
+ private FluentResults.Result SetSafeDirectory(ConcurrentDictionary target, string[] filePaths)
+ {
+ if (filePaths is null || filePaths.Length < 1)
+ {
+ target.Clear();
+ return FluentResults.Result.Ok();
+ }
+
+ FluentResults.Result result = new();
+
+ target.Clear();
+ foreach (string path in filePaths)
+ {
+ if (path.IsNullOrWhiteSpace())
+ {
+ result = result.WithError($"ServicesConfigData: A supplied whitelist path was null.");
+ continue;
+ }
+
+ try
+ {
+ var path2 = Path.GetFullPath(path);
+ target.TryAdd(path2, 0);
+ }
+ catch (Exception e)
+ {
+ result = result.WithError(
+ new ExceptionalError(e).WithMetadata(FluentResults.LuaCs.MetadataType.ExceptionObject, this));
+ continue;
+ }
+ }
+
+ return result.WithSuccess($"Whitelist updated.");
+ }
+}
+
+// --- Config Service
+public interface IConfigServiceConfig
+{
+ string LocalConfigPathPartial { get; }
+ string FileNamePattern { get; }
+}
+
+public record ConfigServiceConfig : IConfigServiceConfig
+{
+ public string LocalConfigPathPartial => $"/Config/{FileNamePattern}.xml";
+ public string FileNamePattern => "";
+}
+
+
+// --- Lua Scripts Service
+public interface ILuaScriptServicesConfig
+{
+ bool SafeLuaIOEnabled { get; }
+ bool UseCaching { get; }
+}
+
+public record LuaScriptServicesConfig : ILuaScriptServicesConfig
+{
+ public bool SafeLuaIOEnabled => true;
+ public bool UseCaching => true;
+}
diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/IEvents.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/IEvents.cs
index 36d8d9b82..ffefc003c 100644
--- a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/IEvents.cs
+++ b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/IEvents.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Reflection;
+using Barotrauma.LuaCs.Configuration;
using Barotrauma.LuaCs.Services;
using Barotrauma.Networking;
using Dynamitey;
@@ -60,6 +61,11 @@ internal interface IEventReloadAllPackages : IEvent
void OnReloadAllPackages();
}
+internal interface IEventConfigVarInstanced : IEvent
+{
+ void OnConfigCreated(IConfigBase config);
+}
+
#endregion
#region GameEvents
diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Lua/LuaScriptLoader.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Lua/LuaScriptLoader.cs
deleted file mode 100644
index 212c70ae5..000000000
--- a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Lua/LuaScriptLoader.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.IO;
-using MoonSharp.Interpreter;
-using MoonSharp.Interpreter.Loaders;
-using System.Linq;
-
-namespace Barotrauma
-{
- class LuaScriptLoader : ScriptLoaderBase
- {
-
- public override object LoadFile(string file, Table globalContext)
- {
- if (!LuaCsFile.IsPathAllowedLuaException(file, false)) return null;
-
- return File.ReadAllText(file);
- }
-
- public override bool ScriptFileExists(string file)
- {
- if (!LuaCsFile.IsPathAllowedLuaException(file, false)) return false;
-
- return File.Exists(file);
- }
- }
-}
diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/LuaCsSetup.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/LuaCsSetup.cs
index c409ac4d3..ae24a2efc 100644
--- a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/LuaCsSetup.cs
+++ b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/LuaCsSetup.cs
@@ -44,15 +44,11 @@ namespace Barotrauma
_servicesProvider.RegisterServiceType(ServiceLifetime.Singleton);
_servicesProvider.RegisterServiceType(ServiceLifetime.Transient);
_servicesProvider.RegisterServiceType(ServiceLifetime.Singleton);
-#if CLIENT
- _servicesProvider.RegisterServiceType(ServiceLifetime.Transient);
- _servicesProvider.RegisterServiceType(ServiceLifetime.Singleton);
-#endif
_servicesProvider.RegisterServiceType(ServiceLifetime.Singleton);
_servicesProvider.RegisterServiceType(ServiceLifetime.Singleton);
_servicesProvider.RegisterServiceType(ServiceLifetime.Singleton);
_servicesProvider.RegisterServiceType(ServiceLifetime.Singleton);
- // TODO: ILocalizationService
+
// TODO: IConfigService
// TODO: INetworkingService
// TODO: [Resource Converter/Parser Services]
@@ -61,13 +57,12 @@ namespace Barotrauma
_servicesProvider.RegisterServiceType, IAssembliesResourcesInfo>, ResourceInfoArrayPacker>(ServiceLifetime.Transient);
_servicesProvider.RegisterServiceType, IConfigsResourcesInfo>, ResourceInfoArrayPacker>(ServiceLifetime.Transient);
_servicesProvider.RegisterServiceType, IConfigProfilesResourcesInfo>, ResourceInfoArrayPacker>(ServiceLifetime.Transient);
- _servicesProvider.RegisterServiceType, ILocalizationsResourcesInfo>, ResourceInfoArrayPacker>(ServiceLifetime.Transient);
_servicesProvider.RegisterServiceType, ILuaScriptsResourcesInfo>, ResourceInfoArrayPacker>(ServiceLifetime.Transient);
+ // Loaders and Processors (yes the naming is reversed, oops).
_servicesProvider.RegisterServiceType, ModConfigService>(ServiceLifetime.Transient);
_servicesProvider.RegisterServiceType, ModConfigService>(ServiceLifetime.Transient);
-
-
+ _servicesProvider.RegisterServiceType(ServiceLifetime.Transient);
_servicesProvider.Compile();
}
@@ -121,8 +116,6 @@ namespace Barotrauma
? svc : throw new NullReferenceException("Plugin Manager service not found!");
public ILuaScriptManagementService LuaScriptManagementService => _servicesProvider.TryGetService(out var svc)
? svc : throw new NullReferenceException("Lua Script Manager service not found!");
- public ILocalizationService LocalizationService => _servicesProvider.TryGetService(out var svc)
- ? svc : throw new NullReferenceException("Localization Manager service not found!");
public INetworkingService NetworkingService => _servicesProvider.TryGetService(out var svc)
? svc : throw new NullReferenceException("Networking Manager service not found!");
public IEventService EventService => _servicesProvider.TryGetService(out var svc)
@@ -179,6 +172,11 @@ namespace Barotrauma
/// TODO: @evilfactory@users.noreply.github.com
///
public IConfigEntry RestrictMessageSize { get; private set; }
+
+ ///
+ /// The local save path for all local data storage for mods.
+ ///
+ public IConfigEntry LocalDataSavePath { get; private set; }
/**
* == Ops Vars
@@ -287,11 +285,7 @@ namespace Barotrauma
PluginManagementService.Dispose();
LuaScriptManagementService.Dispose();
-#if CLIENT
- StylesManagementService.Dispose();
-#endif
ConfigService.Dispose();
- LocalizationService.Dispose();
PackageManagementService.Dispose();
// TODO: Add all missing services.
//NetworkingService.Dispose();
@@ -372,12 +366,7 @@ namespace Barotrauma
while (_toUnload.TryDequeue(out var cp))
{
LuaScriptManagementService.DisposePackageResources(cp);
- ConfigService.DisposeConfigsProfiles(cp);
- ConfigService.DisposeConfigs(cp);
-#if CLIENT
- StylesManagementService.DisposeStylesForPackage(cp);
-#endif
- LocalizationService.DisposePackage(cp);
+ ConfigService.DisposePackageData(cp);
PackageManagementService.DisposePackageInfos(cp);
}
@@ -515,23 +504,22 @@ namespace Barotrauma
void LoadLuaCsConfig()
{
- IsCsEnabled = ConfigService.GetConfig>(ContentPackageManager.VanillaCorePackage, "IsCsEnabled")
- ?? throw new NullReferenceException($"{nameof(IsCsEnabled)} cannot be loaded.");
- TreatForcedModsAsNormal = ConfigService.GetConfig>(ContentPackageManager.VanillaCorePackage, "TreatForcedModsAsNormal")
- ?? throw new NullReferenceException($"{nameof(TreatForcedModsAsNormal)} cannot be loaded.");
- DisableErrorGUIOverlay = ConfigService.GetConfig>(ContentPackageManager.VanillaCorePackage, "DisableErrorGUIOverlay")
- ?? throw new NullReferenceException($"{nameof(DisableErrorGUIOverlay)} cannot be loaded.");
- HideUserNamesInLogs = ConfigService.GetConfig>(ContentPackageManager.VanillaCorePackage, "HideUserNamesInLogs")
- ?? throw new NullReferenceException($"{nameof(HideUserNamesInLogs)} cannot be loaded.");
- LuaForBarotraumaSteamId = ConfigService.GetConfig>(ContentPackageManager.VanillaCorePackage, "LuaForBarotraumaSteamId")
- ?? throw new NullReferenceException($"{nameof(LuaForBarotraumaSteamId)} cannot be loaded.");
- CsForBarotraumaSteamId = ConfigService.GetConfig>(ContentPackageManager.VanillaCorePackage, "CsForBarotraumaSteamId")
- ?? throw new NullReferenceException($"{nameof(CsForBarotraumaSteamId)} cannot be loaded.");
- RestrictMessageSize = ConfigService.GetConfig>(ContentPackageManager.VanillaCorePackage, "RestrictMessageSize")
- ?? throw new NullReferenceException($"{nameof(RestrictMessageSize)} cannot be loaded.");
- ReloadPackagesOnLobbyStart = ConfigService.GetConfig>(ContentPackageManager.VanillaCorePackage, "ReloadPackagesOnLobbyStart")
- ?? throw new NullReferenceException($"{nameof(ReloadPackagesOnLobbyStart)} cannot be loaded.");
-
+ IsCsEnabled = ConfigService.TryGetConfig>(ContentPackageManager.VanillaCorePackage, "IsCsEnabled", out var val1) ? val1
+ : throw new NullReferenceException($"{nameof(IsCsEnabled)} cannot be loaded.");
+ TreatForcedModsAsNormal = ConfigService.TryGetConfig>(ContentPackageManager.VanillaCorePackage, "TreatForcedModsAsNormal", out var val2) ? val2
+ : throw new NullReferenceException($"{nameof(TreatForcedModsAsNormal)} cannot be loaded.");
+ DisableErrorGUIOverlay = ConfigService.TryGetConfig>(ContentPackageManager.VanillaCorePackage, "DisableErrorGUIOverlay", out var val3) ? val3
+ : throw new NullReferenceException($"{nameof(DisableErrorGUIOverlay)} cannot be loaded.");
+ HideUserNamesInLogs = ConfigService.TryGetConfig>(ContentPackageManager.VanillaCorePackage, "HideUserNamesInLogs", out var val4) ? val4
+ : throw new NullReferenceException($"{nameof(HideUserNamesInLogs)} cannot be loaded.");
+ LuaForBarotraumaSteamId = ConfigService.TryGetConfig>(ContentPackageManager.VanillaCorePackage, "LuaForBarotraumaSteamId", out var val5) ? val5
+ : throw new NullReferenceException($"{nameof(LuaForBarotraumaSteamId)} cannot be loaded.");
+ CsForBarotraumaSteamId = ConfigService.TryGetConfig>(ContentPackageManager.VanillaCorePackage, "CsForBarotraumaSteamId", out var val6) ? val6
+ : throw new NullReferenceException($"{nameof(CsForBarotraumaSteamId)} cannot be loaded.");
+ RestrictMessageSize = ConfigService.TryGetConfig>(ContentPackageManager.VanillaCorePackage, "RestrictMessageSize", out var val7) ? val7
+ : throw new NullReferenceException($"{nameof(RestrictMessageSize)} cannot be loaded.");
+ ReloadPackagesOnLobbyStart = ConfigService.TryGetConfig>(ContentPackageManager.VanillaCorePackage, "ReloadPackagesOnLobbyStart", out var val8) ? val8
+ : throw new NullReferenceException($"{nameof(ReloadPackagesOnLobbyStart)} cannot be loaded.");
}
void DisposeLuaCsConfig()
@@ -548,27 +536,14 @@ namespace Barotrauma
async Task LoadStaticAssetsAsync(IReadOnlyList packages)
{
- var locRes = ImmutableArray.Empty;
var cfgRes = ImmutableArray.Empty;
var cfpRes = ImmutableArray.Empty;
var luaRes = ImmutableArray.Empty;
-
-#if CLIENT
- var styleRes = ImmutableArray.Empty;
-#endif
var tasksBuilder = ImmutableArray.CreateBuilder();
//---- get resource infos
- tasksBuilder.AddRange(new Func(async () =>
- {
- var res = await PackageManagementService.GetLocalizationsInfosAsync(packages);
- if (res.IsSuccess)
- locRes = res.Value.Localizations;
- if (res.Errors.Any())
- ThreadPool.QueueUserWorkItem(state => Logger.LogResults((FluentResults.Result)state),
- res.ToResult());
- })(),
+ tasksBuilder.AddRange(
new Func(async () =>
{
var res = await PackageManagementService.GetConfigsInfosAsync(packages);
@@ -596,18 +571,7 @@ namespace Barotrauma
ThreadPool.QueueUserWorkItem(state => Logger.LogResults((FluentResults.Result)state),
res.ToResult());
})());
-
-#if CLIENT
- tasksBuilder.Add(new Func(async () =>
- {
- var res = await PackageManagementService.GetStylesInfosAsync(packages);
- if (res.IsSuccess)
- styleRes = res.Value.Styles;
- if (res.Errors.Any())
- ThreadPool.QueueUserWorkItem(state => Logger.LogResults((FluentResults.Result)state),
- res.ToResult());
- })());
-#endif
+
await Task.WhenAll(tasksBuilder.MoveToImmutable());
tasksBuilder.Clear();
@@ -628,23 +592,6 @@ namespace Barotrauma
Logger.LogResults(res);
})());
-#if CLIENT
- tasksBuilder.Add(new Func(async () =>
- {
- var res = await StylesManagementService.LoadStylesAsync(styleRes);
- if (res.Errors.Any())
- Logger.LogResults(res);
- })());
-#endif
-
- // load localizations first
- if (!locRes.IsDefaultOrEmpty)
- {
- var res = await LocalizationService.LoadLocalizations(locRes);
- if (res.Errors.Any())
- Logger.LogResults(res);
- }
-
await Task.WhenAll(tasksBuilder.MoveToImmutable());
}
@@ -706,22 +653,18 @@ namespace Barotrauma
}
//lua
- var luaRes = PackageManagementService.GetLuaScriptsInfos(PackageManagementService
- .GetAllLoadedPackages()
+ var luaRes = PackageManagementService.LuaScripts
+ .Select(ls => ls.OwnerPackage)
+ .Where(p => p is not null)
.Where(ContentPackageManager.EnabledPackages.All.Contains)
- .ToList());
- if (luaRes.IsFailed)
+ .ToImmutableArray();
+ if (luaRes.IsDefaultOrEmpty)
{
Logger.LogError($"{nameof(RunScripts)}: Failed to get enabled lua script resources!");
- Logger.LogResults(luaRes.ToResult());
return;
}
- if (luaRes.Errors.Any())
- Logger.LogResults(luaRes.ToResult());
-
-
- LuaScriptManagementService.ExecuteLoadedScripts(luaRes.Value.LuaScripts);
+ LuaScriptManagementService.ExecuteLoadedScriptsForPackages(luaRes);
if (CurrentRunState < RunState.Running)
_runState = RunState.Running;
@@ -748,10 +691,6 @@ namespace Barotrauma
PluginManagementService.Reset();
LuaScriptManagementService.Reset();
ConfigService.Reset();
-#if CLIENT
- StylesManagementService.Reset();
-#endif
- LocalizationService.Reset();
if (CurrentRunState >= RunState.Configuration)
{
diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/ModUtils.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/ModUtils.cs
index ad34c723d..fc30ce5db 100644
--- a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/ModUtils.cs
+++ b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/ModUtils.cs
@@ -567,8 +567,17 @@ namespace FluentResults.LuaCs
public static class MetadataType
{
public static string ExceptionDetails = nameof(ExceptionDetails);
+ ///
+ /// The object that threw the exception.
+ ///
public static string ExceptionObject = nameof(ExceptionObject);
+ ///
+ /// The parameter-object responsible for the exception thrown (not the exception thrower).
+ ///
public static string RootObject = nameof(RootObject);
+ ///
+ /// Additional exception sources.
+ ///
public static string Sources = nameof(Sources);
public static string StackTrace = nameof(StackTrace);
}
diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Networking/INetVar.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Networking/INetVar.cs
deleted file mode 100644
index a907b18fa..000000000
--- a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Networking/INetVar.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-using System;
-using Barotrauma.LuaCs.Configuration;
-using Barotrauma.LuaCs.Data;
-using Barotrauma.LuaCs.Services;
-using Barotrauma.Networking;
-
-namespace Barotrauma.LuaCs.Services;
-
-public interface INetVar : IVarId
-{
- ///
- /// Synchronization type
- ///
- NetSync SyncType { get; }
- ///
- /// Permissions needed by clients to send net-events or receive net messages.
- ///
- ClientPermissions WritePermissions { get; }
-
- void ReadNetMessage(INetReadMessage message);
- void WriteNetMessage(INetWriteMessage message);
-}
-
-public enum NetSync
-{
- None, TwoWay, ServerAuthority, ClientOneWay
-}
diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Networking/INetworkSyncEntity.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Networking/INetworkSyncEntity.cs
new file mode 100644
index 000000000..e0cb5713d
--- /dev/null
+++ b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Networking/INetworkSyncEntity.cs
@@ -0,0 +1,66 @@
+using System;
+using Barotrauma.LuaCs.Configuration;
+using Barotrauma.LuaCs.Data;
+using Barotrauma.LuaCs.Services;
+using Barotrauma.Networking;
+
+namespace Barotrauma.LuaCs.Services;
+
+public interface INetworkSyncEntity
+{
+ ///
+ /// Network-synchronized object ID. Used for networking send/receive message events.
+ ///
+ Guid InstanceId { get; }
+
+ ///
+ /// Synchronization type. See for more information.
+ ///
+ NetSync SyncType { get; }
+
+ ///
+ /// Permissions needed by clients to send net-events and/or receive net messages.
+ ///
+ ClientPermissions WritePermissions { get; }
+
+ ///
+ /// Called when an incoming net message has data for this network object, typically from the same entity on another
+ /// machine.
+ ///
+ /// Wrapper for the internal type:
+ void ReadNetMessage(INetReadMessage message);
+
+ ///
+ /// Called when a network send-event involving this entity is triggered. Any data expected to be read by the recipient
+ /// network object on the other instance(s) should be written to the packet.
+ ///
+ /// Wrapper for the internal type:
+ void WriteNetMessage(INetWriteMessage message);
+}
+
+///
+/// Specifies the networking send/receive relationship for network object. Objects implementing this interface are
+/// expected to adhere to the contract or de-sync may occur.
+///
+public enum NetSync
+{
+ ///
+ /// No network synchronization.
+ ///
+ None,
+ ///
+ /// Both the client and the server have 'send' and 'receive' permissions (limited by ). Can also be used to allow two-way communication
+ /// with the server.
+ ///
+ TwoWay,
+ ///
+ /// Only the host/server has the authority to change this value.
+ ///
+ ServerAuthority,
+ ///
+ /// Only clients (with the required by ) may change the value and all value changes are communicated to the server/host.
+ ///
[Important] The host/server will not send the value to other connected clients.
+ /// Intended to allow clients to send one-way messages to the server.
+ ///
+ ClientOneWay
+}
diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Services/Compatibility/ILuaCsUtility.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Services/Compatibility/ILuaCsUtility.cs
index b5db0066c..4e1bde042 100644
--- a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Services/Compatibility/ILuaCsUtility.cs
+++ b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Services/Compatibility/ILuaCsUtility.cs
@@ -2,5 +2,9 @@
public interface ILuaCsUtility : ILuaCsShim
{
+ public bool CanReadFromPath(string file);
+ public bool CanWriteToPath(string file);
+ internal bool IsPathAllowedException(string path, bool write = true,
+ LuaCsMessageOrigin origin = LuaCsMessageOrigin.Unknown);
}
diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Services/ConfigInitializers.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Services/ConfigInitializers.cs
new file mode 100644
index 000000000..d3bad9e9d
--- /dev/null
+++ b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/Services/ConfigInitializers.cs
@@ -0,0 +1,340 @@
+using System;
+using System.Numerics;
+using Barotrauma.LuaCs.Configuration;
+using Barotrauma.LuaCs.Data;
+using FluentResults;
+using Microsoft.Xna.Framework;
+using Vector2 = Microsoft.Xna.Framework.Vector2;
+using Vector3 = Microsoft.Xna.Framework.Vector3;
+using Vector4 = Microsoft.Xna.Framework.Vector4;
+
+namespace Barotrauma.LuaCs.Services;
+
+public class ConfigInitializers : IService
+{
+ // parameterless .ctor
+ public ConfigInitializers()
+ {
+ }
+
+ public void Dispose()
+ {
+ // stateless service
+ return;
+ }
+
+ // stateless service
+ public bool IsDisposed => false;
+
+ private Result> CreateConfigEntry(IConfigInfo configInfo,
+ Action, INetReadMessage> readHandler,
+ Action, INetWriteMessage> writeHandler)
+ where T : IEquatable
+ {
+ try
+ {
+ var ice = new ConfigEntry(configInfo, readHandler, writeHandler);
+ return FluentResults.Result.Ok>(ice);
+ }
+ catch (Exception e)
+ {
+ return FluentResults.Result.Fail($"Error while initializing config var: {configInfo?.OwnerPackage} - {configInfo?.InternalName}")
+ .WithError(new ExceptionalError(e));
+ }
+ }
+
+ private Result> CreateConfigList(IConfigInfo configInfo,
+ Action, INetReadMessage> readHandler, Action, INetWriteMessage> writeHandler)
+ where T : IEquatable
+ {
+ try
+ {
+ var icl = new ConfigList(configInfo, readHandler, writeHandler);
+ return FluentResults.Result.Ok>(icl);
+ }
+ catch (Exception e)
+ {
+ return FluentResults.Result.Fail($"Error while initializing config var: {configInfo?.OwnerPackage} - {configInfo?.InternalName}")
+ .WithError(new ExceptionalError(e));
+ }
+ }
+
+ public void RegisterTypeInitializers(IConfigService configService)
+ {
+ if (configService == null)
+ throw new ArgumentNullException($"{nameof(RegisterTypeInitializers)}: {nameof(IConfigService)} is null.");
+
+ configService.RegisterTypeInitializer>(this.CreateConfigBool);
+ configService.RegisterTypeInitializer>(this.CreateConfigSbyte);
+ configService.RegisterTypeInitializer>(this.CreateConfigByte);
+ configService.RegisterTypeInitializer>(this.CreateConfigShort);
+ configService.RegisterTypeInitializer>(this.CreateConfigUShort);
+ configService.RegisterTypeInitializer>(this.CreateConfigInt32);
+ configService.RegisterTypeInitializer>(this.CreateConfigUInt32);
+ configService.RegisterTypeInitializer>(this.CreateConfigInt64);
+ configService.RegisterTypeInitializer>(this.CreateConfigUInt64);
+ configService.RegisterTypeInitializer>(this.CreateConfigFloat32);
+ configService.RegisterTypeInitializer>(this.CreateConfigFloat64);
+ configService.RegisterTypeInitializer>(this.CreateConfigFloat128);
+ configService.RegisterTypeInitializer>(this.CreateConfigChar);
+ configService.RegisterTypeInitializer>(this.CreateConfigString);
+ configService.RegisterTypeInitializer>(this.CreateConfigColor);
+ configService.RegisterTypeInitializer>(this.CreateConfigVector2);
+ configService.RegisterTypeInitializer>(this.CreateConfigVector3);
+ configService.RegisterTypeInitializer>(this.CreateConfigVector4);
+ }
+
+
+ #region InitializerWrappers_NetworkInjected
+
+ private void AssignValueConditional(T val, IConfigEntry inst) where T : IEquatable
+ {
+#if SERVER
+ if (inst.SyncType is NetSync.None or NetSync.ServerAuthority)
+ throw new InvalidOperationException($"[Server] Tried to assign a net value to a type that does not support sync: {inst.SyncType}. Name: {inst.InternalName}, Package: {inst.OwnerPackage.Name}");
+ inst.TrySetValue(val);
+#else
+ if (inst.SyncType is NetSync.None or NetSync.ClientOneWay)
+ throw new InvalidOperationException($"[Client] Tried to assign a net value to a type that does not support sync: {inst.SyncType}. Name: {inst.InternalName}, Package: {inst.OwnerPackage.Name}");
+ inst.TrySetValue(val);
+#endif
+ }
+
+ private Result> CreateConfigBool(IConfigInfo configInfo)
+ {
+ return CreateConfigEntry(configInfo, (inst, readMsg) =>
+ {
+ AssignValueConditional(readMsg.ReadBoolean(), inst);
+
+ }, (inst, writeMsg) =>
+ {
+ writeMsg.WriteBoolean(inst.Value);
+ });
+ }
+
+ private Result> CreateConfigSbyte(IConfigInfo configInfo)
+ {
+ return CreateConfigEntry(configInfo, (inst, readMsg) =>
+ {
+ AssignValueConditional((sbyte)readMsg.ReadInt16(), inst);
+
+ }, (inst, writeMsg) =>
+ {
+ writeMsg.WriteInt16((short)inst.Value);
+ });
+ }
+
+ private Result> CreateConfigByte(IConfigInfo configInfo)
+ {
+ return CreateConfigEntry(configInfo, (inst, readMsg) =>
+ {
+ AssignValueConditional((byte)readMsg.ReadUInt16(), inst);
+
+ }, (inst, writeMsg) =>
+ {
+ writeMsg.WriteUInt16((byte)inst.Value);
+ });
+ }
+
+ private Result> CreateConfigShort(IConfigInfo configInfo)
+ {
+ return CreateConfigEntry(configInfo, (inst, readMsg) =>
+ {
+ AssignValueConditional(readMsg.ReadInt16(), inst);
+
+ }, (inst, writeMsg) =>
+ {
+ writeMsg.WriteInt16(inst.Value);
+ });
+ }
+
+ private Result> CreateConfigUShort(IConfigInfo configInfo)
+ {
+ return CreateConfigEntry(configInfo, (inst, readMsg) =>
+ {
+ AssignValueConditional(readMsg.ReadUInt16(), inst);
+
+ }, (inst, writeMsg) =>
+ {
+ writeMsg.WriteUInt16(inst.Value);
+ });
+ }
+
+ private Result> CreateConfigInt32(IConfigInfo configInfo)
+ {
+ return CreateConfigEntry(configInfo, (inst, readMsg) =>
+ {
+ AssignValueConditional(readMsg.ReadInt32(), inst);
+
+ }, (inst, writeMsg) =>
+ {
+ writeMsg.WriteInt32(inst.Value);
+ });
+ }
+
+ private Result> CreateConfigUInt32(IConfigInfo configInfo)
+ {
+ return CreateConfigEntry(configInfo, (inst, readMsg) =>
+ {
+ AssignValueConditional(readMsg.ReadUInt32(), inst);
+
+ }, (inst, writeMsg) =>
+ {
+ writeMsg.WriteUInt32(inst.Value);
+ });
+ }
+
+ private Result> CreateConfigInt64(IConfigInfo configInfo)
+ {
+ return CreateConfigEntry(configInfo, (inst, readMsg) =>
+ {
+ AssignValueConditional(readMsg.ReadInt64(), inst);
+
+ }, (inst, writeMsg) =>
+ {
+ writeMsg.WriteInt64(inst.Value);
+ });
+ }
+
+ private Result> CreateConfigUInt64(IConfigInfo configInfo)
+ {
+ return CreateConfigEntry(configInfo, (inst, readMsg) =>
+ {
+ AssignValueConditional(readMsg.ReadUInt64(), inst);
+
+ }, (inst, writeMsg) =>
+ {
+ writeMsg.WriteUInt64(inst.Value);
+ });
+ }
+
+ private Result> CreateConfigFloat32(IConfigInfo configInfo)
+ {
+ return CreateConfigEntry(configInfo, (inst, readMsg) =>
+ {
+ AssignValueConditional(readMsg.ReadSingle(), inst);
+
+ }, (inst, writeMsg) =>
+ {
+ writeMsg.WriteSingle(inst.Value);
+ });
+ }
+
+ private Result> CreateConfigFloat64(IConfigInfo configInfo)
+ {
+ return CreateConfigEntry(configInfo, (inst, readMsg) =>
+ {
+ AssignValueConditional(readMsg.ReadDouble(), inst);
+
+ }, (inst, writeMsg) =>
+ {
+ writeMsg.WriteDouble(inst.Value);
+ });
+ }
+
+ private Result> CreateConfigFloat128(IConfigInfo configInfo)
+ {
+ return CreateConfigEntry(configInfo, (inst, readMsg) =>
+ {
+ var decimalArr = new int[4];
+ decimalArr[0] = readMsg.ReadInt32();
+ decimalArr[1] = readMsg.ReadInt32();
+ decimalArr[2] = readMsg.ReadInt32();
+ decimalArr[3] = readMsg.ReadInt32();
+ AssignValueConditional(new decimal(decimalArr), inst);
+
+ }, (inst, writeMsg) =>
+ {
+ var decimalArr = Decimal.GetBits(inst.Value);
+ writeMsg.WriteInt32(decimalArr[0]);
+ writeMsg.WriteInt32(decimalArr[1]);
+ writeMsg.WriteInt32(decimalArr[2]);
+ writeMsg.WriteInt32(decimalArr[3]);
+ });
+ }
+
+ private Result> CreateConfigChar(IConfigInfo configInfo)
+ {
+ return CreateConfigEntry(configInfo, (inst, readMsg) =>
+ {
+ AssignValueConditional((char)readMsg.ReadUInt16(), inst);
+
+ }, (inst, writeMsg) =>
+ {
+ writeMsg.WriteUInt16(inst.Value);
+ });
+ }
+
+ private Result