Files
LuaCsForBarotraumaEP/Barotrauma/BarotraumaShared/SharedSource/LuaCs/_Services/ModConfigFileParserService.cs
NotAlwaysTrue 9b35f6b23f Sync with upstream
* Update bug-reports.yml

* Fix modifyChatMessage hook

* Add LuaCsSetup.Lua back for compatibility

* Fix Game.AssignOnExecute having command arguments be passed as varargs instead of a table

* Actually use the PackageId const everywhere we need to refer to our content package

* Load languages files even if the package is disabled

* Fix Hook.Remove not being implemented properly

* - Changed event aliases to be case insensitive.

* - Fixed assembly logging style.
- Fixed double logging during execution.

* Fix garbage network data being read by the game when reading LuaCs network messages

* PackageId -> PackageName

* Added caching toggle to PluginManagementService

* Fix LuaCs initializing too late for singleplayer campaigns and rework the C# prompt to only show when enabling mods/joining server

* Oops, fix NRE crash

* Fix hide username in logs config not doing anything

* Fix Cs prompt showing up more than one between rounds

* Fix server host being prompted twice with the C# popup

* Ignore our workshop packages from the game's dependency thing since it doesn't really make sense

* Load console commands after executing and possible fix for the not console command permitted

* Added fallback friendly name resolution for ModConfig assembly contents.

* Register Voronoi2 stuff

* Added configinfo null check to SettingBase.cs

* Add safety check so this stops crashing when we look at it the wrong way

* Fixed "Folder" attribute files not being found.

* Keep the LuaCsConfig class laying around for compatibility, not sure anywhere in our code base (and shouldn't be)

* Added fallback compilation for UseInternalsAwareAssembly if the publicized script compilation fails.

* Added legacy overload of AddCommand for mod compat.

* Added LoggerService to Lua env. Made ILoggerService compliant with LuaCsLogger API.

* Changed csharp script compilation algorithm to be best effort.

* Added "RunUnrestricted" mode for lua scripts that need to run outside of sandbox.

* - Fixed networking sync vars failing to sync initially.
- Fixed lua failing to differentiate overloads ISettingBase.

* Add alias for human.CPRSuccess and human.CPRFailed

* - Fixed up the settings menu.
- Made SettingEntry throw an error if "Value" attribute is not found in XML.
- Fixed saved values for settings sometimes not reloading after disabling and re-enabling a package.

* Fix LuaCs net messages received during connection initialization to be read incorrectly, happened because we would reset the BitPosition in our harmony patch which would cause the message to be read incorrectly later

* Allow reloadlua to force the state to running

* New icon for settings and make the top left text more user friendly

* Fix client.packages hook sending normal packages

* Fixed OnUpdate() not passing in deltaTime instead of totalTime.

* Missing diffs from bb21a09244

* Added networking tests for configs.

* Added missing diffs for f61f852a25.

* Some tweaks to the text

* Remove missing Value error, it should just use the default value if it's not specified

* Fix UseInternalAccessName

* Always purge cashes for plugin content on unloading.

* Fix texture not multiple of 4

* v1.12.7.0 (Spring Update 2026 Hotfix 1)

---------

Co-authored-by: Joonas Rikkonen <poe.regalis@gmail.com>
Co-authored-by: Evil Factory <36804725+evilfactory@users.noreply.github.com>
Co-authored-by: MapleWheels <njainanan@hotmail.com>
2026-04-25 12:10:24 +08:00

282 lines
11 KiB
C#

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Linq;
using Barotrauma.LuaCs.Data;
using FarseerPhysics.Common;
using FluentResults;
using Microsoft.Toolkit.Diagnostics;
namespace Barotrauma.LuaCs;
public sealed partial class ModConfigFileParserService :
IParserServiceAsync<ResourceParserInfo, IAssemblyResourceInfo>,
IParserServiceAsync<ResourceParserInfo, ILuaScriptResourceInfo>,
IParserServiceAsync<ResourceParserInfo, IConfigResourceInfo>
{
private IStorageService _storageService;
private readonly AsyncReaderWriterLock _operationsLock = new();
public ModConfigFileParserService(IStorageService storageService)
{
_storageService = storageService;
}
#region Dispose
public void Dispose()
{
using var lck = _operationsLock.AcquireWriterLock().ConfigureAwait(false).GetAwaiter().GetResult();
if (!ModUtils.Threading.CheckIfClearAndSetBool(ref _isDisposed))
return;
try
{
_storageService.Dispose();
this._storageService = null;
}
catch
{
// ignored
}
}
private int _isDisposed = 0;
public bool IsDisposed
{
get => ModUtils.Threading.GetBool(ref _isDisposed);
private set => ModUtils.Threading.SetBool(ref _isDisposed, value);
}
#endregion
// --- Assemblies
async Task<Result<IAssemblyResourceInfo>> IParserServiceAsync<ResourceParserInfo, IAssemblyResourceInfo>.TryParseResourceAsync(ResourceParserInfo src)
{
using var lck = await _operationsLock.AcquireReaderLock();
IService.CheckDisposed(this);
if (CheckThrowNullRefs(src, "Assembly") is { IsFailed: true } fail)
return fail;
var isScript = src.Element.GetAttributeBool("IsScript", false);
var runtimeEnv = GetRuntimeEnvironment(src.Element);
var fileResults = await UnsafeGetCheckedFiles(src.Element, src.Owner, isScript ? ".cs" : ".dll");
if (fileResults.IsFailed)
return FluentResults.Result.Fail(fileResults.Errors);
return new AssemblyResourceInfo()
{
SupportedPlatforms = runtimeEnv.Platform,
SupportedTargets = runtimeEnv.Target,
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,
// Type Specific
FriendlyName = src.Element.GetAttributeString("FriendlyName", GetFallbackCompliantAssemblyName(src.Owner)),
IsScript = isScript,
UseInternalAccessName = src.Element.GetAttributeBool("UseInternalAccessName", false),
IsReferenceModeOnly = src.Element.GetAttributeBool("IsReferenceModeOnly", false)
};
// helper methods
string GetFallbackCompliantAssemblyName(ContentPackage package)
{
if (package.Name.IsNullOrWhiteSpace())
{
return "FallbackAssemblyName";
}
// replace non az chars with '_'
var sanitizedPackageName = Regex.Replace(package.Name, @"[^a-zA-Z0-9_]", "_");
if (char.IsDigit(sanitizedPackageName[0]))
{
sanitizedPackageName = "ASM" + sanitizedPackageName;
}
// replace consecutive '_'
return Regex.Replace(sanitizedPackageName, @"[_.]{2,}", "_");
}
}
async Task<ImmutableArray<Result<IAssemblyResourceInfo>>> IParserServiceAsync<ResourceParserInfo, IAssemblyResourceInfo>.TryParseResourcesAsync(IEnumerable<ResourceParserInfo> sources)
{
return await this.TryParseGenericResourcesAsync<IAssemblyResourceInfo>(sources);
}
// --- Config
async Task<Result<IConfigResourceInfo>> IParserServiceAsync<ResourceParserInfo, IConfigResourceInfo>.TryParseResourceAsync(ResourceParserInfo src)
{
using var lck = await _operationsLock.AcquireReaderLock();
IService.CheckDisposed(this);
if (CheckThrowNullRefs(src, "Config") 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 ConfigResourceInfo()
{
SupportedPlatforms = runtimeEnv.Platform,
SupportedTargets = runtimeEnv.Target,
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
};
}
async Task<ImmutableArray<Result<IConfigResourceInfo>>> IParserServiceAsync<ResourceParserInfo, IConfigResourceInfo>.TryParseResourcesAsync(IEnumerable<ResourceParserInfo> sources)
{
return await this.TryParseGenericResourcesAsync<IConfigResourceInfo>(sources);
}
// --- Lua Scripts
async Task<Result<ILuaScriptResourceInfo>> IParserServiceAsync<ResourceParserInfo, ILuaScriptResourceInfo>.TryParseResourceAsync(ResourceParserInfo src)
{
using var lck = await _operationsLock.AcquireReaderLock();
IService.CheckDisposed(this);
if (CheckThrowNullRefs(src, "Lua") is { IsFailed: true } fail)
return fail;
var runtimeEnv = GetRuntimeEnvironment(src.Element);
var fileResults = await UnsafeGetCheckedFiles(src.Element, src.Owner, ".lua");
if (fileResults.IsFailed)
return FluentResults.Result.Fail(fileResults.Errors);
return new LuaScriptsResourceInfo()
{
SupportedPlatforms = runtimeEnv.Platform,
SupportedTargets = runtimeEnv.Target,
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,
// Type Specific
IsAutorun = src.Element.GetAttributeBool("IsAutorun", false),
RunUnrestricted = src.Element.GetAttributeBool("RunUnrestricted", false)
};
}
private FluentResults.Result CheckThrowNullRefs(ResourceParserInfo src, string elementName)
{
Guard.IsNotNull(src, nameof(src));
Guard.IsNotNull(src.Owner, nameof(src.Owner));
Guard.IsNotNull(src.Element, nameof(src.Element));
if (src.Element.Name != elementName)
{
return FluentResults.Result.Fail($"Element name '{elementName}' is incorrect");
}
return FluentResults.Result.Ok();
}
async Task<ImmutableArray<Result<ILuaScriptResourceInfo>>> IParserServiceAsync<ResourceParserInfo, ILuaScriptResourceInfo>.TryParseResourcesAsync(IEnumerable<ResourceParserInfo> sources)
{
return await this.TryParseGenericResourcesAsync<ILuaScriptResourceInfo>(sources);
}
// --- Helpers
private async Task<Result<ImmutableArray<ContentPath>>> UnsafeGetCheckedFiles(XElement srcElement, ContentPackage srcOwner, string fileExtension)
{
var builder = ImmutableArray.CreateBuilder<ContentPath>();
var filePath = srcElement.GetAttributeContentPath("File", srcOwner);
var folderPath = srcElement.GetAttributeContentPath("Folder", srcOwner);
var res = new FluentResults.Result<ImmutableArray<ContentPath>>();
if ((!filePath?.Value.IsNullOrWhiteSpace()) ?? false)
{
if (_storageService.FileExists(filePath.FullPath) is { IsSuccess: true, Value: true })
{
builder.Add(filePath);
}
else
{
if (srcElement.GetAttributeBool("IsFileRequired", true))
{
res.WithError($"{srcOwner.Name}: The file '{filePath}' is missing!");
}
else
{
res.WithSuccess($"Skipped missing not-required file: '{filePath}'");
}
}
}
if ((!folderPath?.Value.IsNullOrWhiteSpace()) ?? false)
{
if (_storageService.DirectoryExists(folderPath.FullPath) is { IsSuccess: true, Value: true })
{
var searchLocation = System.IO.Path.GetRelativePath(srcOwner.Dir, folderPath.Value);
var files = _storageService.FindFilesInPackage(srcOwner, searchLocation, "*"+fileExtension, true);
if (files.IsFailed)
{
res.WithError($"{srcOwner.Name}: Failed to load files from {folderPath}!");
}
else
{
foreach (var file in files.Value)
{
builder.Add(ContentPath.FromRaw(srcOwner, $"%ModDir%/{System.IO.Path.GetRelativePath(System.IO.Path.GetFullPath(srcOwner.Dir), file)}"));
}
}
}
else
{
if (srcElement.GetAttributeBool("IsFileRequired", true))
{
res.WithError($"{srcOwner.Name}: The file '{folderPath}' is missing!");
}
else
{
res.WithSuccess($"Skipped missing not-required folder: '{folderPath}'");
}
}
}
return res.WithValue(builder.ToImmutable());
}
private (Platform Platform, Target Target) GetRuntimeEnvironment(XElement element)
{
return (
Platform: element.GetAttributeEnum("Platform", Platform.Any),
Target: element.GetAttributeEnum("Target", Target.Any));
}
private async Task<ImmutableArray<Result<T>>> TryParseGenericResourcesAsync<T>(IEnumerable<ResourceParserInfo> sources)
{
// ReSharper disable once PossibleMultipleEnumeration
Guard.IsNotNull(sources, nameof(IParserServiceAsync<ResourceParserInfo, T>.TryParseResourcesAsync));
var builder = ImmutableArray.CreateBuilder<Result<T>>();
foreach (var info in sources)
{
builder.Add(await Unsafe.As<IParserServiceAsync<ResourceParserInfo, T>>(this).TryParseResourceAsync(info));
}
return builder.ToImmutable();
}
}