GameMain.LuaCs is no more

This commit is contained in:
Evil Factory
2026-02-28 16:05:20 -03:00
parent c676233dfd
commit 8e8b8eb8aa
35 changed files with 99 additions and 96 deletions
@@ -223,7 +223,7 @@ namespace Barotrauma
private static bool IsCommandPermitted(Identifier command, GameClient client) private static bool IsCommandPermitted(Identifier command, GameClient client)
{ {
if (GameMain.LuaCs.Game.IsCustomCommandPermitted(command)) { return true; } if (LuaCsSetup.Instance.Game.IsCustomCommandPermitted(command)) { return true; }
switch (command.Value.ToLowerInvariant()) switch (command.Value.ToLowerInvariant())
{ {
@@ -4231,14 +4231,14 @@ namespace Barotrauma
return; return;
} }
if (GameMain.LuaCs.CurrentRunState != RunState.Running) if (LuaCsSetup.Instance.CurrentRunState != RunState.Running)
{ {
ThrowError("LuaCs not initialized, use the console command cl_reloadluacs to force initialization."); ThrowError("LuaCs not initialized, use the console command cl_reloadluacs to force initialization.");
return; return;
} }
var result = GameMain.LuaCs.LuaScriptManagementService.DoString(string.Join(" ", args)); var result = LuaCsSetup.Instance.LuaScriptManagementService.DoString(string.Join(" ", args));
GameMain.LuaCs.Logger.LogResults(result.ToResult()); LuaCsSetup.Instance.Logger.LogResults(result.ToResult());
})); }));
} }
@@ -415,7 +415,7 @@ namespace Barotrauma
if (GameMain.IsSingleplayer) if (GameMain.IsSingleplayer)
{ {
bool? should = null; bool? should = null;
GameMain.LuaCs.EventService.PublishEvent<IEventChatMessage>(x => should = x.OnChatMessage(message.Text, message.SenderClient, message.Type, message) ?? should); LuaCsSetup.Instance.EventService.PublishEvent<IEventChatMessage>(x => should = x.OnChatMessage(message.Text, message.SenderClient, message.Type, message) ?? should);
if (should != null && should.Value) { return; } if (should != null && should.Value) { return; }
} }
@@ -24,8 +24,6 @@ namespace Barotrauma
{ {
class GameMain : Game class GameMain : Game
{ {
private static LuaCsSetup _luaCs;
public static LuaCsSetup LuaCs => _luaCs ??= new LuaCsSetup();
public static bool ShowFPS; public static bool ShowFPS;
public static bool ShowPerf; public static bool ShowPerf;
public static bool DebugDraw; public static bool DebugDraw;
@@ -298,7 +296,7 @@ namespace Barotrauma
Window.FileDropped += OnFileDropped; Window.FileDropped += OnFileDropped;
LuaCs.GetType(); LuaCsSetup.Instance.GetType();
} }
public static void ExecuteAfterContentFinishedLoading(Action action) public static void ExecuteAfterContentFinishedLoading(Action action)
@@ -1296,10 +1294,9 @@ namespace Barotrauma
CreatureMetrics.Save(); CreatureMetrics.Save();
try try
{ {
if (_luaCs is not null) if (LuaCsSetup.Instance is not null)
{ {
_luaCs.Dispose(); LuaCsSetup.Instance.Dispose();
_luaCs = null;
} }
} }
catch (Exception e) catch (Exception e)
@@ -19,33 +19,33 @@ namespace Barotrauma
new GUITickBox(new RectTransform(new Vector2(0.8f, 0.1f), list.Content.RectTransform), "Enable CSharp Scripting") new GUITickBox(new RectTransform(new Vector2(0.8f, 0.1f), list.Content.RectTransform), "Enable CSharp Scripting")
{ {
Selected = GameMain.LuaCs.IsCsEnabled, Selected = LuaCsSetup.Instance.IsCsEnabled,
ToolTip = "This enables CSharp Scripting for mods to use, WARNING: CSharp is NOT sandboxed, be careful with what mods you download.", ToolTip = "This enables CSharp Scripting for mods to use, WARNING: CSharp is NOT sandboxed, be careful with what mods you download.",
OnSelected = (GUITickBox tick) => OnSelected = (GUITickBox tick) =>
{ {
GameMain.LuaCs.IsCsEnabled = tick.Selected; LuaCsSetup.Instance.IsCsEnabled = tick.Selected;
return true; return true;
} }
}; };
new GUITickBox(new RectTransform(new Vector2(0.8f, 0.1f), list.Content.RectTransform), "Disable Error GUI Overlay") new GUITickBox(new RectTransform(new Vector2(0.8f, 0.1f), list.Content.RectTransform), "Disable Error GUI Overlay")
{ {
Selected = GameMain.LuaCs.DisableErrorGUIOverlay, Selected = LuaCsSetup.Instance.DisableErrorGUIOverlay,
ToolTip = "", ToolTip = "",
OnSelected = (GUITickBox tick) => OnSelected = (GUITickBox tick) =>
{ {
GameMain.LuaCs.DisableErrorGUIOverlay = tick.Selected; LuaCsSetup.Instance.DisableErrorGUIOverlay = tick.Selected;
return true; return true;
} }
}; };
new GUITickBox(new RectTransform(new Vector2(0.8f, 0.1f), list.Content.RectTransform), "Hide usernames In Error Logs") new GUITickBox(new RectTransform(new Vector2(0.8f, 0.1f), list.Content.RectTransform), "Hide usernames In Error Logs")
{ {
Selected = GameMain.LuaCs.HideUserNamesInLogs, Selected = LuaCsSetup.Instance.HideUserNamesInLogs,
ToolTip = "Hides the operating system username when displaying error logs (eg your username on windows).", ToolTip = "Hides the operating system username when displaying error logs (eg your username on windows).",
OnSelected = (GUITickBox tick) => OnSelected = (GUITickBox tick) =>
{ {
GameMain.LuaCs.HideUserNamesInLogs = tick.Selected; LuaCsSetup.Instance.HideUserNamesInLogs = tick.Selected;
return true; return true;
} }
}; };
@@ -3004,7 +3004,7 @@ namespace Barotrauma.Networking
public override void AddChatMessage(ChatMessage message) public override void AddChatMessage(ChatMessage message)
{ {
bool? should = null; bool? should = null;
GameMain.LuaCs.EventService.PublishEvent<IEventChatMessage>(x => should = x.OnChatMessage(message.Text, message.SenderClient, message.Type, message) ?? should); LuaCsSetup.Instance.EventService.PublishEvent<IEventChatMessage>(x => should = x.OnChatMessage(message.Text, message.SenderClient, message.Type, message) ?? should);
if (should != null && should.Value) { return; } if (should != null && should.Value) { return; }
if (string.IsNullOrEmpty(message.Text)) { return; } if (string.IsNullOrEmpty(message.Text)) { return; }
@@ -65,7 +65,7 @@ namespace Barotrauma
var owner = GameMain.Server.ConnectedClients.Find(c => c.Character == this); var owner = GameMain.Server.ConnectedClients.Find(c => c.Character == this);
if (owner != null) if (owner != null)
{ {
if (!GameMain.LuaCs.Game.overrideTraitors) if (!LuaCsSetup.Instance.Game.overrideTraitors)
{ {
GameMain.Server.SendDirectChatMessage(TextManager.FormatServerMessage("KilledByTraitorNotification"), owner, ChatMessageType.ServerMessageBoxInGame); GameMain.Server.SendDirectChatMessage(TextManager.FormatServerMessage("KilledByTraitorNotification"), owner, ChatMessageType.ServerMessageBoxInGame);
} }
@@ -811,7 +811,7 @@ namespace Barotrauma
var tempBuffer = new ReadWriteMessage(); var tempBuffer = new ReadWriteMessage();
WriteStatus(tempBuffer, forceAfflictionData: true); WriteStatus(tempBuffer, forceAfflictionData: true);
if (msgLengthBeforeStatus + tempBuffer.LengthBytes >= 255 && restrictMessageSize && (GameMain.LuaCs.RestrictMessageSize)) if (msgLengthBeforeStatus + tempBuffer.LengthBytes >= 255 && restrictMessageSize && (LuaCsSetup.Instance.RestrictMessageSize))
{ {
msg.WriteBoolean(false); msg.WriteBoolean(false);
if (msgLengthBeforeStatus < 255) if (msgLengthBeforeStatus < 255)
@@ -1291,14 +1291,14 @@ namespace Barotrauma
commands.Add(new Command("lua", "lua: Runs a string.", (string[] args) => commands.Add(new Command("lua", "lua: Runs a string.", (string[] args) =>
{ {
var result = GameMain.LuaCs.LuaScriptManagementService.DoString(string.Join(" ", args)); var result = LuaCsSetup.Instance.LuaScriptManagementService.DoString(string.Join(" ", args));
GameMain.LuaCs.Logger.LogResults(result.ToResult()); LuaCsSetup.Instance.Logger.LogResults(result.ToResult());
})); }));
commands.Add(new Command("reloadlua|reloadcs|reloadluacs", "Re-initializes the LuaCs environment.", (string[] args) => commands.Add(new Command("reloadlua|reloadcs|reloadluacs", "Re-initializes the LuaCs environment.", (string[] args) =>
{ {
//GameMain.LuaCs.Initialize(); //GameMain.LuaCs.Initialize();
GameMain.LuaCs.EventService.PublishEvent<IEventReloadAllPackages>(sub => sub.OnReloadAllPackages()); LuaCsSetup.Instance.EventService.PublishEvent<IEventReloadAllPackages>(sub => sub.OnReloadAllPackages());
})); }));
commands.Add(new Command("toggleluadebug", "Toggles the MoonSharp Debug Server.", (string[] args) => commands.Add(new Command("toggleluadebug", "Toggles the MoonSharp Debug Server.", (string[] args) =>
@@ -35,9 +35,6 @@ namespace Barotrauma
set { world = value; } set { world = value; }
} }
private static LuaCsSetup _luaCs;
public static LuaCsSetup LuaCs => _luaCs ??= new LuaCsSetup();
public static GameServer Server; public static GameServer Server;
public static NetworkMember NetworkMember public static NetworkMember NetworkMember
{ {
@@ -115,7 +112,7 @@ namespace Barotrauma
MainThread = Thread.CurrentThread; MainThread = Thread.CurrentThread;
LuaCs.GetType(); LuaCsSetup.Instance.GetType();
} }
public void Init() public void Init()
@@ -367,9 +364,9 @@ namespace Barotrauma
CoroutineManager.Update(paused: false, (float)Timing.Step); CoroutineManager.Update(paused: false, (float)Timing.Step);
performanceCounterTimer.Stop(); performanceCounterTimer.Stop();
if (GameMain.LuaCs.PerformanceCounter.EnablePerformanceCounter) if (LuaCsSetup.Instance.PerformanceCounter.EnablePerformanceCounter)
{ {
GameMain.LuaCs.PerformanceCounter.AddElapsedTicks(new SimplePerformanceData("Update", performanceCounterTimer.ElapsedTicks)); LuaCsSetup.Instance.PerformanceCounter.AddElapsedTicks(new SimplePerformanceData("Update", performanceCounterTimer.ElapsedTicks));
} }
performanceCounterTimer.Reset(); performanceCounterTimer.Reset();
@@ -455,10 +452,9 @@ namespace Barotrauma
ShouldRun = false; ShouldRun = false;
try try
{ {
if (_luaCs is not null) if (LuaCsSetup.Instance is not null)
{ {
_luaCs.Dispose(); LuaCsSetup.Instance.Dispose();
_luaCs = null;
} }
} }
catch (Exception e) catch (Exception e)
@@ -89,7 +89,7 @@ namespace Barotrauma.Networking
if (flaggedAsSpam) { return; } if (flaggedAsSpam) { return; }
bool? should = null; bool? should = null;
GameMain.LuaCs.EventService.PublishEvent<IEventChatMessage>(x => should = x.OnChatMessage(txt, c, type, ChatMessage.Create(c.Name, txt, type, null, c)) ?? should); LuaCsSetup.Instance.EventService.PublishEvent<IEventChatMessage>(x => should = x.OnChatMessage(txt, c, type, ChatMessage.Create(c.Name, txt, type, null, c)) ?? should);
if (should != null && should.Value) { return; } if (should != null && should.Value) { return; }
if (type == ChatMessageType.Order) if (type == ChatMessageType.Order)
@@ -440,7 +440,7 @@ namespace Barotrauma.Networking
(permadeathMode && (!character.IsDead || character.CauseOfDeath?.Type == CauseOfDeathType.Disconnected))); (permadeathMode && (!character.IsDead || character.CauseOfDeath?.Type == CauseOfDeathType.Disconnected)));
if (!character.IsDead) if (!character.IsDead)
{ {
if (!GameMain.LuaCs.Game.disableDisconnectCharacter) if (!LuaCsSetup.Instance.Game.disableDisconnectCharacter)
{ {
character.KillDisconnectedTimer += deltaTime; character.KillDisconnectedTimer += deltaTime;
character.SetStun(1.0f); character.SetStun(1.0f);
@@ -3178,7 +3178,7 @@ namespace Barotrauma.Networking
} }
TraitorManager.Initialize(GameMain.GameSession.EventManager, Level.Loaded); TraitorManager.Initialize(GameMain.GameSession.EventManager, Level.Loaded);
if (GameMain.LuaCs.Game.overrideTraitors) if (LuaCsSetup.Instance.Game.overrideTraitors)
{ {
TraitorManager.Enabled = false; TraitorManager.Enabled = false;
} }
@@ -3512,7 +3512,7 @@ namespace Barotrauma.Networking
} }
bool? result = null; bool? result = null;
GameMain.LuaCs.EventService.PublishEvent<IEventTryClientChangeName>(x => result = x.OnTryClienChangeName(c, newName, newJob, newTeam) ?? result); LuaCsSetup.Instance.EventService.PublishEvent<IEventTryClientChangeName>(x => result = x.OnTryClienChangeName(c, newName, newJob, newTeam) ?? result);
if (result != null) if (result != null)
{ {
@@ -3964,7 +3964,7 @@ namespace Barotrauma.Networking
senderName = null; senderName = null;
senderCharacter = null; senderCharacter = null;
} }
else if (type == ChatMessageType.Radio && !GameMain.LuaCs.Game.overrideSignalRadio) else if (type == ChatMessageType.Radio && !LuaCsSetup.Instance.Game.overrideSignalRadio)
{ {
//send to chat-linked wifi components //send to chat-linked wifi components
Signal s = new Signal(message, sender: senderCharacter, source: senderRadio.Item); Signal s = new Signal(message, sender: senderCharacter, source: senderRadio.Item);
@@ -4771,7 +4771,7 @@ namespace Barotrauma.Networking
{ {
if (GameMain.Server == null || !GameMain.Server.ServerSettings.SaveServerLogs) { return; } if (GameMain.Server == null || !GameMain.Server.ServerSettings.SaveServerLogs) { return; }
GameMain.LuaCs?.EventService.PublishEvent<IEventServerLog>(x => x.OnServerLog(line, messageType)); LuaCsSetup.Instance?.EventService.PublishEvent<IEventServerLog>(x => x.OnServerLog(line, messageType));
GameMain.Server.ServerSettings.ServerLog.WriteLine(line, messageType); GameMain.Server.ServerSettings.ServerLog.WriteLine(line, messageType);
@@ -18,7 +18,7 @@ namespace Barotrauma.Networking
MultiPlayerCampaign campaign = GameMain.GameSession.GameMode as MultiPlayerCampaign; MultiPlayerCampaign campaign = GameMain.GameSession.GameMode as MultiPlayerCampaign;
foreach (Client c in networkMember.ConnectedClients) foreach (Client c in networkMember.ConnectedClients)
{ {
if (GameMain.LuaCs.Game.overrideRespawnSub) if (LuaCsSetup.Instance.Game.overrideRespawnSub)
continue; continue;
if (!c.InGame) { continue; } if (!c.InGame) { continue; }
@@ -169,7 +169,7 @@ namespace Barotrauma.Networking
private bool ShouldStartRespawnCountdown(int characterToRespawnCount) private bool ShouldStartRespawnCountdown(int characterToRespawnCount)
{ {
if (GameMain.LuaCs.Game.overrideRespawnSub) if (LuaCsSetup.Instance.Game.overrideRespawnSub)
{ {
characterToRespawnCount = 0; characterToRespawnCount = 0;
} }
@@ -187,7 +187,7 @@ namespace Barotrauma.Networking
var teamId = teamSpecificState.TeamID; var teamId = teamSpecificState.TeamID;
var respawnShuttle = GetShuttle(teamId); var respawnShuttle = GetShuttle(teamId);
if (respawnShuttle != null && !GameMain.LuaCs.Game.overrideRespawnSub) if (respawnShuttle != null && !LuaCsSetup.Instance.Game.overrideRespawnSub)
{ {
respawnShuttle.Velocity = Vector2.Zero; respawnShuttle.Velocity = Vector2.Zero;
} }
@@ -240,7 +240,7 @@ namespace Barotrauma.Networking
if (RespawnShuttles.Any()) if (RespawnShuttles.Any())
{ {
ResetShuttle(teamSpecificState); ResetShuttle(teamSpecificState);
if (GameMain.LuaCs.Game.overrideRespawnSub) if (LuaCsSetup.Instance.Game.overrideRespawnSub)
{ {
teamSpecificState.CurrentState = State.Waiting; teamSpecificState.CurrentState = State.Waiting;
} }
@@ -100,7 +100,7 @@ namespace Barotrauma.Networking
(recipientSpectating || ChatMessage.CanUseRadio(recipient.Character, out recipientRadio))) (recipientSpectating || ChatMessage.CanUseRadio(recipient.Character, out recipientRadio)))
{ {
bool? canUse = null; bool? canUse = null;
GameMain.LuaCs.EventService.PublishEvent<IEventCanUseVoiceRadio>(x => canUse = x.OnCanUseVoiceRadio(sender, recipient) ?? canUse); LuaCsSetup.Instance.EventService.PublishEvent<IEventCanUseVoiceRadio>(x => canUse = x.OnCanUseVoiceRadio(sender, recipient) ?? canUse);
if (canUse != null) if (canUse != null)
{ {
@@ -121,7 +121,7 @@ namespace Barotrauma.Networking
} }
float range = 1.0f; float range = 1.0f;
GameMain.LuaCs.EventService.PublishEvent<IEventChangeLocalVoiceRange>(x => range = x.OnChangeLocalVoiceRange(sender, recipient) ?? range); LuaCsSetup.Instance.EventService.PublishEvent<IEventChangeLocalVoiceRange>(x => range = x.OnChangeLocalVoiceRange(sender, recipient) ?? range);
if (recipientSpectating) if (recipientSpectating)
{ {
@@ -1306,11 +1306,11 @@ namespace Barotrauma
//increase oxygen and clamp it above zero //increase oxygen and clamp it above zero
// -> the character should be revived if there are no major afflictions in addition to lack of oxygen // -> the character should be revived if there are no major afflictions in addition to lack of oxygen
target.Oxygen = Math.Max(target.Oxygen + 10.0f, 10.0f); target.Oxygen = Math.Max(target.Oxygen + 10.0f, 10.0f);
GameMain.LuaCs.EventService.PublishEvent<IEventHumanCPRSuccess>(x => x.OnCharacterCPRSuccess(this)); LuaCsSetup.Instance.EventService.PublishEvent<IEventHumanCPRSuccess>(x => x.OnCharacterCPRSuccess(this));
} }
else else
{ {
GameMain.LuaCs.EventService.PublishEvent<IEventHumanCPRFailed>(x => x.OnCharacterCPRFailed(this)); LuaCsSetup.Instance.EventService.PublishEvent<IEventHumanCPRFailed>(x => x.OnCharacterCPRFailed(this));
} }
} }
} }
@@ -859,7 +859,7 @@ namespace Barotrauma
float impactDamage = GetImpactDamage(impact, impactTolerance); float impactDamage = GetImpactDamage(impact, impactTolerance);
float? should = null; float? should = null;
GameMain.LuaCs.EventService.PublishEvent<IEventChangeFallDamage>(x => should = x.OnChangeFallDamage(impactDamage, character, impactPos, velocity) ?? should); LuaCsSetup.Instance.EventService.PublishEvent<IEventChangeFallDamage>(x => should = x.OnChangeFallDamage(impactDamage, character, impactPos, velocity) ?? should);
if (should != null) if (should != null)
{ {
@@ -3388,13 +3388,13 @@ namespace Barotrauma
{ {
for (int i = 0; i < CharacterList.Count; i++) for (int i = 0; i < CharacterList.Count; i++)
{ {
if (GameMain.LuaCs.Game.UpdatePriorityCharacters.Contains(CharacterList[i])) continue; if (LuaCsSetup.Instance.Game.UpdatePriorityCharacters.Contains(CharacterList[i])) continue;
CharacterList[i].Update(deltaTime * CharacterUpdateInterval, cam); CharacterList[i].Update(deltaTime * CharacterUpdateInterval, cam);
} }
} }
foreach (Character character in GameMain.LuaCs.Game.UpdatePriorityCharacters) foreach (Character character in LuaCsSetup.Instance.Game.UpdatePriorityCharacters)
{ {
if (character.Removed) { continue; } if (character.Removed) { continue; }
Debug.Assert(character is { Removed: false }); Debug.Assert(character is { Removed: false });
@@ -338,13 +338,13 @@ namespace Barotrauma
if (Prefab is AfflictionPrefabHusk huskPrefab) if (Prefab is AfflictionPrefabHusk huskPrefab)
{ {
if (huskPrefab.ControlHusk || GameMain.LuaCs.Game.enableControlHusk) if (huskPrefab.ControlHusk || LuaCsSetup.Instance.Game.enableControlHusk)
{ {
#if SERVER #if SERVER
if (client != null) if (client != null)
{ {
GameMain.Server.SetClientCharacter(client, husk); GameMain.Server.SetClientCharacter(client, husk);
GameMain.LuaCs.EventService.PublishEvent<IEventClientControlHusk>(x => x.OnClientControlHusk(client, husk)); LuaCsSetup.Instance.EventService.PublishEvent<IEventClientControlHusk>(x => x.OnClientControlHusk(client, husk));
} }
#else #else
if (!character.IsRemotelyControlled && character == Character.Controlled) if (!character.IsRemotelyControlled && character == Character.Controlled)
@@ -658,7 +658,7 @@ namespace Barotrauma
} }
bool? should = null; bool? should = null;
GameMain.LuaCs.EventService.PublishEvent<IEventCharacterApplyDamage>(x => should = x.OnCharacterApplyDamage(this, attackResult, hitLimb, allowStacking) ?? should); LuaCsSetup.Instance.EventService.PublishEvent<IEventCharacterApplyDamage>(x => should = x.OnCharacterApplyDamage(this, attackResult, hitLimb, allowStacking) ?? should);
if (should != null && should.Value) { return; } if (should != null && should.Value) { return; }
foreach (Affliction newAffliction in attackResult.Afflictions) foreach (Affliction newAffliction in attackResult.Afflictions)
@@ -830,7 +830,7 @@ namespace Barotrauma
if (Character.Params.Health.ImmunityIdentifiers.Contains(newAffliction.Identifier)) { return; } if (Character.Params.Health.ImmunityIdentifiers.Contains(newAffliction.Identifier)) { return; }
bool? should = null; bool? should = null;
GameMain.LuaCs.EventService.PublishEvent<IEventCharacterApplyAffliction>(x => should = x.OnCharacterApplyAffliction(this, limbHealth, newAffliction, allowStacking) ?? should); LuaCsSetup.Instance.EventService.PublishEvent<IEventCharacterApplyAffliction>(x => should = x.OnCharacterApplyAffliction(this, limbHealth, newAffliction, allowStacking) ?? should);
if (should != null && should.Value) { return; } if (should != null && should.Value) { return; }
Affliction existingAffliction = null; Affliction existingAffliction = null;
@@ -436,7 +436,7 @@ namespace Barotrauma.Items.Components
Structure targetStructure = target.UserData as Structure ?? targetFixture.UserData as Structure; Structure targetStructure = target.UserData as Structure ?? targetFixture.UserData as Structure;
Item targetItem = target.UserData is Holdable h ? h.Item : target.UserData as Item ?? targetFixture.UserData as Item; Item targetItem = target.UserData is Holdable h ? h.Item : target.UserData as Item ?? targetFixture.UserData as Item;
Entity targetEntity = targetCharacter ?? targetStructure ?? targetItem ?? target.UserData as Entity; Entity targetEntity = targetCharacter ?? targetStructure ?? targetItem ?? target.UserData as Entity;
GameMain.LuaCs.EventService.PublishEvent<IEventMeleeWeaponHandleImpact>(x => x.OnMeleeWeaponHandleImpact(this, target)); LuaCsSetup.Instance.EventService.PublishEvent<IEventMeleeWeaponHandleImpact>(x => x.OnMeleeWeaponHandleImpact(this, target));
if (Attack != null) if (Attack != null)
{ {
@@ -335,7 +335,7 @@ namespace Barotrauma.Items.Components
} }
bool? should = null; bool? should = null;
GameMain.LuaCs.EventService.PublishEvent<IEventItemDeconstructed>(x => should = x.OnItemDeconstructed(targetItem, this, user, allowRemove) ?? should); LuaCsSetup.Instance.EventService.PublishEvent<IEventItemDeconstructed>(x => should = x.OnItemDeconstructed(targetItem, this, user, allowRemove) ?? should);
if (should == true) { return; } if (should == true) { return; }
if (targetItem.AllowDeconstruct && allowRemove) if (targetItem.AllowDeconstruct && allowRemove)
@@ -232,7 +232,7 @@ namespace Barotrauma.Items.Components
public void TransmitSignal(Signal signal, bool sentFromChat) public void TransmitSignal(Signal signal, bool sentFromChat)
{ {
bool? should = null; bool? should = null;
GameMain.LuaCs.EventService.PublishEvent<IEventWifiSignalTransmitted>(x => should = x.OnWifiSignalTransmitted(this, signal, sentFromChat) ?? should); LuaCsSetup.Instance.EventService.PublishEvent<IEventWifiSignalTransmitted>(x => should = x.OnWifiSignalTransmitted(this, signal, sentFromChat) ?? should);
if (should != null && should.Value) { return; } if (should != null && should.Value) { return; }
bool chatMsgSent = false; bool chatMsgSent = false;
@@ -3895,7 +3895,7 @@ namespace Barotrauma
} }
bool? should = null; bool? should = null;
GameMain.LuaCs.EventService.PublishEvent<IEventItemReadPropertyChange>(x => should = x.OnItemReadPropertyChange(this, property, parentObject, allowEditing, sender) ?? should); LuaCsSetup.Instance.EventService.PublishEvent<IEventItemReadPropertyChange>(x => should = x.OnItemReadPropertyChange(this, property, parentObject, allowEditing, sender) ?? should);
if (should != null && should.Value) { return; } if (should != null && should.Value) { return; }
Type type = property.PropertyType; Type type = property.PropertyType;
@@ -22,8 +22,16 @@ namespace Barotrauma
partial class LuaCsSetup : IDisposable, IEventScreenSelected, IEventEnabledPackageListChanged, partial class LuaCsSetup : IDisposable, IEventScreenSelected, IEventEnabledPackageListChanged,
IEventReloadAllPackages IEventReloadAllPackages
{ {
public LuaCsSetup() private static LuaCsSetup _luaCsSetup;
public static LuaCsSetup Instance => _luaCsSetup ??= new LuaCsSetup();
private LuaCsSetup()
{ {
if (_luaCsSetup != null)
{
throw new Exception("Tried to create another LuaCsSetup instance");
}
// == startup // == startup
_servicesProvider = SetupServicesProvider(); _servicesProvider = SetupServicesProvider();
_runStateMachine = SetupStateMachine(); _runStateMachine = SetupStateMachine();
@@ -432,6 +440,8 @@ namespace Barotrauma
Console.WriteLine(e); Console.WriteLine(e);
throw; throw;
} }
_luaCsSetup = null;
GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
@@ -74,27 +74,27 @@ namespace Barotrauma.LuaCs
public static void PrintMessage(string s) public static void PrintMessage(string s)
{ {
#if SERVER #if SERVER
GameMain.LuaCs.Logger.LogMessage($"{s}"); LuaCsSetup.Instance.Logger.LogMessage($"{s}");
#else #else
GameMain.LuaCs.Logger.LogMessage($"{s}"); LuaCsSetup.Instance.Logger.LogMessage($"{s}");
#endif #endif
} }
public static void PrintWarning(string s) public static void PrintWarning(string s)
{ {
#if SERVER #if SERVER
GameMain.LuaCs.Logger.Log($"{s}", Color.Yellow); LuaCsSetup.Instance.Logger.Log($"{s}", Color.Yellow);
#else #else
GameMain.LuaCs.Logger.Log($"{s}", Color.Yellow); LuaCsSetup.Instance.Logger.Log($"{s}", Color.Yellow);
#endif #endif
} }
public static void PrintError(string s) public static void PrintError(string s)
{ {
#if SERVER #if SERVER
GameMain.LuaCs.Logger.LogError($"{s}"); LuaCsSetup.Instance.Logger.LogError($"{s}");
#else #else
GameMain.LuaCs.Logger.LogError($"{s}"); LuaCsSetup.Instance.Logger.LogError($"{s}");
#endif #endif
} }
} }
@@ -48,7 +48,7 @@ namespace Barotrauma
} }
catch (Exception e) catch (Exception e)
{ {
GameMain.LuaCs.Logger.HandleException(e); LuaCsSetup.Instance.Logger.HandleException(e);
} }
IsDisposed = true; IsDisposed = true;
} }
@@ -60,7 +60,7 @@ public partial class LoggerService : ILoggerService
if (!_isInsideLogCall) if (!_isInsideLogCall)
{ {
_isInsideLogCall = true; _isInsideLogCall = true;
GameMain.LuaCs?.EventService.PublishEvent<IEventServerLog>(x => x.OnServerLog(logMessage, log.MessageType)); LuaCsSetup.Instance?.EventService.PublishEvent<IEventServerLog>(x => x.OnServerLog(logMessage, log.MessageType));
_isInsideLogCall = false; _isInsideLogCall = false;
} }
} }
@@ -12,13 +12,13 @@ public sealed class LuaCsInfoProvider : ILuaCsInfoProvider
} }
public bool IsDisposed => false; public bool IsDisposed => false;
public bool IsCsEnabled => GameMain.LuaCs.IsCsEnabled; public bool IsCsEnabled => LuaCsSetup.Instance.IsCsEnabled;
public bool DisableErrorGUIOverlay => GameMain.LuaCs.DisableErrorGUIOverlay; public bool DisableErrorGUIOverlay => LuaCsSetup.Instance.DisableErrorGUIOverlay;
public bool HideUserNamesInLogs => GameMain.LuaCs.HideUserNamesInLogs; public bool HideUserNamesInLogs => LuaCsSetup.Instance.HideUserNamesInLogs;
public ulong LuaForBarotraumaSteamId => GameMain.LuaCs.LuaForBarotraumaSteamId; public ulong LuaForBarotraumaSteamId => LuaCsSetup.Instance.LuaForBarotraumaSteamId;
public bool RestrictMessageSize => GameMain.LuaCs.RestrictMessageSize; public bool RestrictMessageSize => LuaCsSetup.Instance.RestrictMessageSize;
public string LocalDataSavePath => GameMain.LuaCs.LocalDataSavePath; public string LocalDataSavePath => LuaCsSetup.Instance.LocalDataSavePath;
public RunState CurrentRunState => GameMain.LuaCs.CurrentRunState; public RunState CurrentRunState => LuaCsSetup.Instance.CurrentRunState;
public ContentPackage LuaCsForBarotraumaPackage public ContentPackage LuaCsForBarotraumaPackage
{ {
get get
@@ -90,7 +90,7 @@ class LuaScriptManagementService : ILuaScriptManagementService, ILuaDataService
{ {
commands.RegisterCommand("cl_reloadlua|cl_reloadcs|cl_reloadluacs", "Re-initializes the LuaCs environment.", (string[] args) => commands.RegisterCommand("cl_reloadlua|cl_reloadcs|cl_reloadluacs", "Re-initializes the LuaCs environment.", (string[] args) =>
{ {
GameMain.LuaCs.EventService.PublishEvent<IEventReloadAllPackages>(sub => sub.OnReloadAllPackages()); LuaCsSetup.Instance.EventService.PublishEvent<IEventReloadAllPackages>(sub => sub.OnReloadAllPackages());
}); });
commands.RegisterCommand("cl_toggleluadebug", "Toggles the MoonSharp Debug Server.", (string[] args) => commands.RegisterCommand("cl_toggleluadebug", "Toggles the MoonSharp Debug Server.", (string[] args) =>
@@ -59,7 +59,7 @@ namespace Barotrauma
{ {
public object GetComponentString(string component) public object GetComponentString(string component)
{ {
Type type = GameMain.LuaCs.PluginManagementService.GetType("Barotrauma.Items.Components." + component); Type type = LuaCsSetup.Instance.PluginManagementService.GetType("Barotrauma.Items.Components." + component);
if (type == null) if (type == null)
{ {
@@ -17,41 +17,41 @@ namespace Barotrauma
{ {
public static void HandleException(Exception ex, LuaCsMessageOrigin origin) public static void HandleException(Exception ex, LuaCsMessageOrigin origin)
{ {
GameMain.LuaCs.Logger.HandleException(ex); LuaCsSetup.Instance.Logger.HandleException(ex);
} }
public static void LogError(string message, LuaCsMessageOrigin origin) public static void LogError(string message, LuaCsMessageOrigin origin)
{ {
GameMain.LuaCs.Logger.LogError(message); LuaCsSetup.Instance.Logger.LogError(message);
} }
public static void LogError(string message) public static void LogError(string message)
{ {
GameMain.LuaCs.Logger.LogError(message); LuaCsSetup.Instance.Logger.LogError(message);
} }
public static void LogMessage(string message, Color? serverColor = null, Color? clientColor = null) public static void LogMessage(string message, Color? serverColor = null, Color? clientColor = null)
{ {
GameMain.LuaCs.Logger.LogMessage(message, serverColor, clientColor); LuaCsSetup.Instance.Logger.LogMessage(message, serverColor, clientColor);
} }
public static void Log(string message, Color? color = null, ServerLog.MessageType messageType = ServerLog.MessageType.ServerMessage) public static void Log(string message, Color? color = null, ServerLog.MessageType messageType = ServerLog.MessageType.ServerMessage)
{ {
GameMain.LuaCs.Logger.Log(message, color, messageType); LuaCsSetup.Instance.Logger.Log(message, color, messageType);
} }
} }
partial class LuaCsSetup partial class LuaCsSetup
{ {
// Compatibility with cs mods that use this method. // Compatibility with cs mods that use this method.
public static void PrintLuaError(object message) => GameMain.LuaCs.Logger.LogError($"{message}"); public static void PrintLuaError(object message) => LuaCsSetup.Instance.Logger.LogError($"{message}");
public static void PrintCsError(object message) => GameMain.LuaCs.Logger.LogError($"{message}"); public static void PrintCsError(object message) => LuaCsSetup.Instance.Logger.LogError($"{message}");
public static void PrintGenericError(object message) => GameMain.LuaCs.Logger.LogError($"{message}"); public static void PrintGenericError(object message) => LuaCsSetup.Instance.Logger.LogError($"{message}");
internal void PrintMessage(object message) => GameMain.LuaCs.Logger.LogMessage($"{message}"); internal void PrintMessage(object message) => LuaCsSetup.Instance.Logger.LogMessage($"{message}");
public static void PrintCsMessage(object message) => GameMain.LuaCs.Logger.LogMessage($"{message}"); public static void PrintCsMessage(object message) => LuaCsSetup.Instance.Logger.LogMessage($"{message}");
internal void HandleException(Exception ex, LuaCsMessageOrigin origin) => GameMain.LuaCs.Logger.HandleException(ex); internal void HandleException(Exception ex, LuaCsMessageOrigin origin) => LuaCsSetup.Instance.Logger.HandleException(ex);
} }
} }
@@ -60,7 +60,7 @@ namespace Barotrauma
foreach (var package in ContentPackageManager.AllPackages) foreach (var package in ContentPackageManager.AllPackages)
{ {
if (package.UgcId.ValueEquals(new SteamWorkshopId(GameMain.LuaCs.LuaForBarotraumaSteamId)) if (package.UgcId.ValueEquals(new SteamWorkshopId(LuaCsSetup.Instance.LuaForBarotraumaSteamId))
&& pathStartsWith(getFullPath(package.Path))) && pathStartsWith(getFullPath(package.Path)))
{ {
return false; return false;
@@ -294,7 +294,7 @@ namespace Barotrauma.LuaCs
private static MethodBase ResolveMethod(string className, string methodName, string[] parameters) private static MethodBase ResolveMethod(string className, string methodName, string[] parameters)
{ {
var classType = GameMain.LuaCs.PluginManagementService.GetType(className); var classType = LuaCsSetup.Instance.PluginManagementService.GetType(className);
if (classType == null) throw new ScriptRuntimeException($"invalid class name '{className}'"); if (classType == null) throw new ScriptRuntimeException($"invalid class name '{className}'");
const BindingFlags BINDING_FLAGS = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; const BindingFlags BINDING_FLAGS = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
@@ -309,7 +309,7 @@ namespace Barotrauma.LuaCs
for (int i = 0; i < parameters.Length; i++) for (int i = 0; i < parameters.Length; i++)
{ {
Type type = GameMain.LuaCs.PluginManagementService.GetType(parameters[i]); Type type = LuaCsSetup.Instance.PluginManagementService.GetType(parameters[i]);
if (type == null) if (type == null)
{ {
throw new ScriptRuntimeException($"invalid parameter type '{parameters[i]}'"); throw new ScriptRuntimeException($"invalid parameter type '{parameters[i]}'");
@@ -670,7 +670,7 @@ namespace Barotrauma.LuaCs
} }
var type = typeBuilder.CreateType(); var type = typeBuilder.CreateType();
type.GetField(FIELD_LUACS, BindingFlags.Public | BindingFlags.Static).SetValue(null, GameMain.LuaCs); type.GetField(FIELD_LUACS, BindingFlags.Public | BindingFlags.Static).SetValue(null, LuaCsSetup.Instance);
return type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static); return type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static);
} }
@@ -886,7 +886,7 @@ namespace Barotrauma
} }
bool? should = null; bool? should = null;
GameMain.LuaCs.EventService.PublishEvent<IEventGapOxygenUpdate>(x => should = x.OnGapOxygenUpdate(this, hull1, hull2) ?? should); LuaCsSetup.Instance.EventService.PublishEvent<IEventGapOxygenUpdate>(x => should = x.OnGapOxygenUpdate(this, hull1, hull2) ?? should);
if (should != null && should.Value) return; if (should != null && should.Value) return;
float totalOxygen = hull1.Oxygen + hull2.Oxygen; float totalOxygen = hull1.Oxygen + hull2.Oxygen;
@@ -697,7 +697,7 @@ namespace Barotrauma
{ {
foreach (Item item in Item.ItemList) foreach (Item item in Item.ItemList)
{ {
if (GameMain.LuaCs.Game.UpdatePriorityItems.Contains(item)) { continue; } if (LuaCsSetup.Instance.Game.UpdatePriorityItems.Contains(item)) { continue; }
lastUpdatedItem = item; lastUpdatedItem = item;
item.Update(deltaTime * MapEntityUpdateInterval, cam); item.Update(deltaTime * MapEntityUpdateInterval, cam);
} }
@@ -712,7 +712,7 @@ namespace Barotrauma
} }
} }
foreach (var item in GameMain.LuaCs.Game.UpdatePriorityItems) foreach (var item in LuaCsSetup.Instance.Game.UpdatePriorityItems)
{ {
if (item.Removed) continue; if (item.Removed) continue;
@@ -1787,14 +1787,14 @@ namespace Barotrauma
{ {
if (entity is Item item) if (entity is Item item)
{ {
var result = GameMain.LuaCs.Hook.Call<bool?>("statusEffect.apply." + item.Prefab.Identifier, this, deltaTime, entity, targets, worldPosition); var result = LuaCsSetup.Instance.Hook.Call<bool?>("statusEffect.apply." + item.Prefab.Identifier, this, deltaTime, entity, targets, worldPosition);
if (result != null && result.Value) { return; } if (result != null && result.Value) { return; }
} }
if (entity is Character character) if (entity is Character character)
{ {
var result = GameMain.LuaCs.Hook.Call<bool?>("statusEffect.apply." + character.SpeciesName, this, deltaTime, entity, targets, worldPosition); var result = LuaCsSetup.Instance.Hook.Call<bool?>("statusEffect.apply." + character.SpeciesName, this, deltaTime, entity, targets, worldPosition);
if (result != null && result.Value) { return; } if (result != null && result.Value) { return; }
} }
@@ -1804,7 +1804,7 @@ namespace Barotrauma
{ {
foreach ((string hookName, ContentXElement element) in luaHook) foreach ((string hookName, ContentXElement element) in luaHook)
{ {
var result = GameMain.LuaCs.Hook.Call<bool?>(hookName, this, deltaTime, entity, targets, worldPosition, element); var result = LuaCsSetup.Instance.Hook.Call<bool?>(hookName, this, deltaTime, entity, targets, worldPosition, element);
if (result != null && result.Value) { return; } if (result != null && result.Value) { return; }
} }