initial cs-lua merge work

This commit is contained in:
Oiltanker
2022-04-11 22:44:53 +03:00
parent ae2b84cceb
commit 1e6ac68e86
44 changed files with 786 additions and 1046 deletions
@@ -80,7 +80,7 @@ namespace Barotrauma
public void AddObjective<T>(T objective) where T : AIObjective
{
var result = new LuaResult(GameMain.Lua.hook.Call("AI.AddObjective", this, objective));
var result = new LuaResult(GameMain.LuaCs.hook.Call("AI.AddObjective", this, objective));
if (result.Bool()) return;
@@ -1440,11 +1440,11 @@ namespace Barotrauma
// -> 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);
GameMain.Lua.hook.Call("human.CPRSuccess", this);
}
GameMain.LuaCs.hook.Call("human.CPRSuccess", this);
}
else
{
GameMain.Lua.hook.Call("human.CPRFailed", this);
GameMain.LuaCs.hook.Call("human.CPRFailed", this);
}
}
}
@@ -745,9 +745,9 @@ namespace Barotrauma
float impactDamage = Math.Min((impact - ImpactTolerance) * ImpactDamageMultiplayer, character.MaxVitality * MaxImpactDamage);
var should = new LuaResult(GameMain.Lua.hook.Call("changeFallDamage", new object[] { impactDamage, character, impactPos, velocity }));
var should = new LuaResult(GameMain.LuaCs.hook.Call("changeFallDamage", new object[] { impactDamage, character, impactPos, velocity }));
if (!should.IsNull())
if (!should.IsNull())
{
impactDamage = should.Float();
}
@@ -1043,7 +1043,7 @@ namespace Barotrauma
}
#endif
GameMain.Lua.hook.Call("characterCreated", new object[] { newCharacter });
GameMain.LuaCs.hook.Call("characterCreated", new object[] { newCharacter });
return newCharacter;
}
@@ -2723,13 +2723,13 @@ namespace Barotrauma
{
for (int i = 0; i < CharacterList.Count; i++)
{
if (GameMain.Lua.game.updatePriorityCharacters.Contains(CharacterList[i])) continue;
if (GameMain.LuaCs.game.updatePriorityCharacters.Contains(CharacterList[i])) continue;
CharacterList[i].Update(deltaTime * CharacterUpdateInterval, cam);
}
}
foreach (Character character in GameMain.Lua.game.updatePriorityCharacters)
foreach (Character character in GameMain.LuaCs.game.updatePriorityCharacters)
{
if (character.Removed) continue;
@@ -388,7 +388,7 @@ namespace Barotrauma
AdditionStrength -= amount;
}
#if SERVER
GameMain.Lua.hook.Call("afflictionUpdate", new object[] { this, characterHealth, targetLimb, deltaTime });
GameMain.LuaCs.hook.Call("afflictionUpdate", new object[] { this, characterHealth, targetLimb, deltaTime });
#endif
}
@@ -302,13 +302,13 @@ namespace Barotrauma
if (Prefab is AfflictionPrefabHusk huskPrefab)
{
if (huskPrefab.ControlHusk || GameMain.Lua.game.enableControlHusk)
if (huskPrefab.ControlHusk || GameMain.LuaCs.game.enableControlHusk)
{
#if SERVER
if (client != null)
{
GameMain.Server.SetClientCharacter(client, husk);
GameMain.Lua.hook.Call("husk.clientControlHusk", new object[] { client, husk });
GameMain.LuaCs.hook.Call("husk.clientControlHusk", new object[] { client, husk });
}
#else
if (!character.IsRemotelyControlled && character == Character.Controlled)
@@ -541,7 +541,7 @@ namespace Barotrauma
return;
}
var should = new LuaResult(GameMain.Lua.hook.Call("character.applyDamage", new object[] { this, attackResult, hitLimb, allowStacking }));
var should = new LuaResult(GameMain.LuaCs.hook.Call("character.applyDamage", new object[] { this, attackResult, hitLimb, allowStacking }));
if (should.Bool())
return;
@@ -674,7 +674,7 @@ namespace Barotrauma
}
}
var should = new LuaResult(GameMain.Lua.hook.Call("character.applyAffliction", new object[] { this, limbHealth, newAffliction, allowStacking }));
var should = new LuaResult(GameMain.LuaCs.hook.Call("character.applyAffliction", new object[] { this, limbHealth, newAffliction, allowStacking }));
if (should.Bool())
return;
@@ -526,7 +526,7 @@ namespace Barotrauma
HintManager.OnRoundStarted();
GameMain.Lua.hook.Call("roundStart");
GameMain.LuaCs.hook.Call("roundStart");
#endif
}
@@ -781,7 +781,7 @@ namespace Barotrauma
RoundEnding = true;
#if CLIENT
GameMain.Lua.hook.Call("roundEnd");
GameMain.LuaCs.hook.Call("roundEnd");
#endif
//Clear the grids to allow for garbage collection
Powered.Grids.Clear();
@@ -387,7 +387,7 @@ namespace Barotrauma.Items.Components
Limb targetLimb = target.UserData as Limb;
Character targetCharacter = targetLimb?.character ?? target.UserData as Character;
GameMain.Lua.hook.Call("meleeWeapon.handleImpact", this, target);
GameMain.LuaCs.hook.Call("meleeWeapon.handleImpact", this, target);
if (Attack != null)
{
Attack.SetUser(User);
@@ -325,8 +325,8 @@ namespace Barotrauma.Items.Components
Connection connection = recipient;
object[] obj = new object[] { signal, connection };
GameMain.Lua.hook.Call("signalReceived", obj);
GameMain.Lua.hook.Call("signalReceived." + recipient.item.Prefab.Identifier, obj);
GameMain.LuaCs.hook.Call("signalReceived", obj);
GameMain.LuaCs.hook.Call("signalReceived." + recipient.item.Prefab.Identifier, obj);
foreach (ItemComponent ic in recipient.item.Components)
{
@@ -74,7 +74,7 @@ namespace Barotrauma.Items.Components
#if SERVER
get
{
if(GameMain.Lua.game.allowWifiChat) return true;
if(GameMain.LuaCs.game.allowWifiChat) return true;
return linkToChat;
}
@@ -205,7 +205,7 @@ namespace Barotrauma.Items.Components
public void TransmitSignal(Signal signal, bool sentFromChat)
{
var should = new LuaResult(GameMain.Lua.hook.Call("wifiSignalTransmitted", new object[] { this, signal, sentFromChat }));
var should = new LuaResult(GameMain.LuaCs.hook.Call("wifiSignalTransmitted", new object[] { this, signal, sentFromChat }));
if (should.Bool())
return;
@@ -540,7 +540,7 @@ namespace Barotrauma
return;
}
var should = new LuaResult(GameMain.Lua.hook.Call("inventoryPutItem", new object[] { this, item, user, i, removeItem }));
var should = new LuaResult(GameMain.LuaCs.hook.Call("inventoryPutItem", new object[] { this, item, user, i, removeItem }));
if (should.Bool())
return;
@@ -648,7 +648,7 @@ namespace Barotrauma
if (slots[index].Items.Any(it => !it.IsInteractable(user))) { return false; }
if (!AllowSwappingContainedItems) { return false; }
var should = new LuaResult(GameMain.Lua.hook.Call("inventoryItemSwap", new object[] { this, item, user, index, swapWholeStack }));
var should = new LuaResult(GameMain.LuaCs.hook.Call("inventoryItemSwap", new object[] { this, item, user, index, swapWholeStack }));
if (!should.IsNull())
return should.Bool();
@@ -999,7 +999,7 @@ namespace Barotrauma
if (Components.Any(ic => ic is Wire) && Components.All(ic => ic is Wire || ic is Holdable)) { isWire = true; }
if (HasTag("logic")) { isLogic = true; }
GameMain.Lua.hook.Call("item.created", this);
GameMain.LuaCs.hook.Call("item.created", this);
ApplyStatusEffects(ActionType.OnSpawn, 1.0f);
Components.ForEach(c => c.ApplyStatusEffects(ActionType.OnSpawn, 1.0f));
@@ -2469,7 +2469,7 @@ namespace Barotrauma
if (condition == 0.0f) { return; }
var should = new LuaResult(GameMain.Lua.hook.Call("item.use", new object[] { this, character, targetLimb }));
var should = new LuaResult(GameMain.LuaCs.hook.Call("item.use", new object[] { this, character, targetLimb }));
if (should.Bool())
return;
@@ -2507,7 +2507,7 @@ namespace Barotrauma
{
if (condition == 0.0f) { return; }
var should = new LuaResult(GameMain.Lua.hook.Call("item.secondaryUse", new object[] { this, character}));
var should = new LuaResult(GameMain.LuaCs.hook.Call("item.secondaryUse", new object[] { this, character}));
if (should.Bool())
return;
@@ -2851,7 +2851,7 @@ namespace Barotrauma
}
}
var result = new LuaResult(GameMain.Lua.hook.Call("item.readPropertyChange", this, property, parentObject, allowEditing));
var result = new LuaResult(GameMain.LuaCs.hook.Call("item.readPropertyChange", this, property, parentObject, allowEditing));
if (result.Bool())
return;
@@ -3343,7 +3343,7 @@ namespace Barotrauma
body = null;
}
GameMain.Lua.hook.Call("item.removed", this);
GameMain.LuaCs.hook.Call("item.removed", this);
}
public override void Remove()
@@ -3427,7 +3427,7 @@ namespace Barotrauma
RemoveProjSpecific();
GameMain.Lua.hook.Call("item.removed", this);
GameMain.LuaCs.hook.Call("item.removed", this);
}
partial void RemoveProjSpecific();
@@ -31,7 +31,7 @@ namespace Barotrauma
public void Wait(object function, int millisecondDelay)
{
GameMain.Lua.hook.EnqueueTimedFunction((float)Timing.TotalTime + (millisecondDelay / 1000f), function);
GameMain.LuaCs.hook.EnqueueTimedFunction((float)Timing.TotalTime + (millisecondDelay / 1000f), function);
}
public static double GetTime()
@@ -122,14 +122,14 @@ namespace Barotrauma
if (CanWriteToPath(path))
return true;
else
GameMain.Lua.HandleLuaException(new Exception("File access to \"" + path + "\" not allowed."));
GameMain.LuaCs.HandleLuaException(new Exception("File access to \"" + path + "\" not allowed."));
}
else
{
if (CanReadFromPath(path))
return true;
else
GameMain.Lua.HandleLuaException(new Exception("File access to \"" + path + "\" not allowed."));
GameMain.LuaCs.HandleLuaException(new Exception("File access to \"" + path + "\" not allowed."));
}
return false;
@@ -239,29 +239,29 @@ namespace Barotrauma
{
string netMessageName = netMessage.ReadString();
if (LuaNetReceives[netMessageName] is Closure)
GameMain.Lua.CallFunction(LuaNetReceives[netMessageName], new object[] { netMessage, client });
GameMain.LuaCs.CallFunction(LuaNetReceives[netMessageName], new object[] { netMessage, client });
}
else
{
GameMain.Lua.hook.Call("netMessageReceived", netMessage, header, client);
GameMain.LuaCs.hook.Call("netMessageReceived", netMessage, header, client);
}
}
#else
[MoonSharpHidden]
public void NetMessageReceived(IReadMessage netMessage, ServerPacketHeader header, Client client = null)
[MoonSharpHidden]
public void NetMessageReceived(IReadMessage netMessage, ServerPacketHeader header, Client client = null)
{
if (header == ServerPacketHeader.LUA_NET_MESSAGE)
{
if (header == ServerPacketHeader.LUA_NET_MESSAGE)
{
string netMessageName = netMessage.ReadString();
if (LuaNetReceives[netMessageName] is Closure)
GameMain.Lua.lua.Call(LuaNetReceives[netMessageName], new object[] { netMessage, client });
}
else
{
GameMain.Lua.hook.Call("netMessageReceived", netMessage, header, client);
}
string netMessageName = netMessage.ReadString();
if (LuaNetReceives[netMessageName] is Closure)
GameMain.LuaCs.lua.Call(LuaNetReceives[netMessageName], new object[] { netMessage, client });
}
else
{
GameMain.LuaCs.hook.Call("netMessageReceived", netMessage, header, client);
}
}
#endif
public void Receive(string netMessageName, object callback)
@@ -327,18 +327,18 @@ namespace Barotrauma
{
var httpResponse = httpWebRequest.EndGetResponse(result);
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
GameMain.Lua.hook.EnqueueFunction(callback, streamReader.ReadToEnd());
GameMain.LuaCs.hook.EnqueueFunction(callback, streamReader.ReadToEnd());
}
catch (Exception e)
{
GameMain.Lua.hook.EnqueueFunction(callback, e.ToString());
GameMain.LuaCs.hook.EnqueueFunction(callback, e.ToString());
}
}), null);
}
catch (Exception e)
{
GameMain.Lua.hook.EnqueueFunction(callback, e.ToString());
GameMain.LuaCs.hook.EnqueueFunction(callback, e.ToString());
}
}
@@ -354,17 +354,17 @@ namespace Barotrauma
{
var httpResponse = httpWebRequest.EndGetResponse(result);
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
GameMain.Lua.hook.EnqueueFunction(callback, streamReader.ReadToEnd());
GameMain.LuaCs.hook.EnqueueFunction(callback, streamReader.ReadToEnd());
}
catch (Exception e)
{
GameMain.Lua.hook.EnqueueFunction(callback, e.ToString());
GameMain.LuaCs.hook.EnqueueFunction(callback, e.ToString());
}
}), null);
}
catch (Exception e)
{
GameMain.Lua.hook.EnqueueFunction(callback, e.ToString());
GameMain.LuaCs.hook.EnqueueFunction(callback, e.ToString());
}
}
@@ -326,11 +326,11 @@ namespace Barotrauma
public void AddCommand(string name, string help, object onExecute, object getValidArgs = null, bool isCheat = false)
{
var cmd = new DebugConsole.Command(name, help, (string[] arg1) => { GameMain.Lua.CallFunction(onExecute, new object[] { arg1 }); },
var cmd = new DebugConsole.Command(name, help, (string[] arg1) => { GameMain.LuaCs.CallFunction(onExecute, new object[] { arg1 }); },
() =>
{
if (getValidArgs == null) return null;
var result = new LuaResult(GameMain.Lua.CallFunction(getValidArgs, new object[] { }));
var result = new LuaResult(GameMain.LuaCs.CallFunction(getValidArgs, new object[] { }));
var obj = result.Object();
if (obj is string[][]) return (string[][])obj;
return null;
@@ -357,7 +357,7 @@ namespace Barotrauma
public List<DebugConsole.Command> Commands => DebugConsole.Commands;
public void AssignOnExecute(string names, object onExecute) => DebugConsole.AssignOnExecute(names, (string[] a) => { GameMain.Lua.CallFunction(onExecute, new object[] { a }); });
public void AssignOnExecute(string names, object onExecute) => DebugConsole.AssignOnExecute(names, (string[] a) => { GameMain.LuaCs.CallFunction(onExecute, new object[] { a }); });
#if SERVER
@@ -412,7 +412,7 @@ namespace Barotrauma
GameMain.Server.EndGame();
}
public void AssignOnClientRequestExecute(string names, object onExecute) => DebugConsole.AssignOnClientRequestExecute(names, (Client a, Vector2 b, string[] c) => { GameMain.Lua.CallFunction(onExecute, new object[] { a, b, c }); });
public void AssignOnClientRequestExecute(string names, object onExecute) => DebugConsole.AssignOnClientRequestExecute(names, (Client a, Vector2 b, string[] c) => { GameMain.LuaCs.CallFunction(onExecute, new object[] { a, b, c }); });
#endif
@@ -1,364 +0,0 @@
using System;
using System.Linq;
using System.Reflection;
using MoonSharp.Interpreter;
using HarmonyLib;
using System.Collections.Generic;
using System.Text;
namespace Barotrauma
{
partial class LuaHook
{
public LuaHook()
{
_hookPrefixMethods = new Dictionary<long, HashSet<Tuple<string, object>>>();
_hookPostfixMethods = new Dictionary<long, HashSet<Tuple<string, object>>>();
}
public class HookFunction
{
public string name;
public string hookName;
public object function;
public HookFunction(string n, string hn, object func)
{
name = n;
hookName = hn;
function = func;
}
}
private Dictionary<string, Dictionary<string, HookFunction>> hookFunctions = new Dictionary<string, Dictionary<string, HookFunction>>();
private static Dictionary<long, HashSet<Tuple<string, object>>> _hookPrefixMethods;
private static Dictionary<long, HashSet<Tuple<string, object>>> _hookPostfixMethods;
private Queue<Tuple<float, object, object[]>> queuedFunctionCalls = new Queue<Tuple<float, object, object[]>>();
public enum HookMethodType
{
Before, After
}
static void _hookLuaPatch(MethodBase __originalMethod, object[] __args, object __instance, out LuaResult result, HookMethodType hookMethodType)
{
result = new LuaResult(null);
#if CLIENT
if (GameMain.GameSession?.IsRunning == false && GameMain.IsSingleplayer)
return;
#endif
try
{
var funcAddr = ((long)__originalMethod.MethodHandle.GetFunctionPointer());
HashSet<Tuple<string, object>> methodSet = null;
switch (hookMethodType)
{
case HookMethodType.Before:
_hookPrefixMethods.TryGetValue(funcAddr, out methodSet);
break;
case HookMethodType.After:
_hookPostfixMethods.TryGetValue(funcAddr, out methodSet);
break;
default:
break;
}
if (methodSet != null)
{
var @params = __originalMethod.GetParameters();
var ptable = new Dictionary<string, object>();
for (int i = 0; i < @params.Length; i++)
{
ptable.Add(@params[i].Name, __args[i]);
}
foreach (var tuple in methodSet)
{
result = new LuaResult(GameMain.Lua.lua.Call(tuple.Item2, __instance, ptable));
}
}
}
catch (Exception ex)
{
GameMain.Lua.HandleLuaException(ex);
}
}
static bool HookLuaPatchPrefix(MethodBase __originalMethod, object[] __args, object __instance)
{
_hookLuaPatch(__originalMethod, __args, __instance, out LuaResult result, HookMethodType.Before);
return result.IsNull();
}
static bool HookLuaPatchRetPrefix(MethodBase __originalMethod, object[] __args, ref object __result, object __instance)
{
_hookLuaPatch(__originalMethod, __args, __instance, out LuaResult result, HookMethodType.Before);
if (!result.IsNull())
{
if (__originalMethod is MethodInfo mi)
{
__result = result.DynValue().ToObject(mi.ReturnType);
}
else
{
__result = result.Object();
}
return false;
}
return true;
}
static void HookLuaPatchPostfix(MethodBase __originalMethod, object[] __args, object __instance)
{
_hookLuaPatch(__originalMethod, __args, __instance, out LuaResult result, HookMethodType.After);
}
static void HookLuaPatchRetPostfix(MethodBase __originalMethod, object[] __args, ref object __result, object __instance)
{
_hookLuaPatch(__originalMethod, __args, __instance, out LuaResult result, HookMethodType.After);
if (!result.IsNull())
{
if (__originalMethod is MethodInfo mi)
{
__result = result.DynValue().ToObject(mi.ReturnType);
}
else
{
__result = result.Object();
}
}
}
private const BindingFlags DefaultBindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
private static MethodInfo _miHookLuaPatchPrefix = typeof(LuaHook).GetMethod("HookLuaPatchPrefix", BindingFlags.NonPublic | BindingFlags.Static);
private static MethodInfo _miHookLuaPatchRetPrefix = typeof(LuaHook).GetMethod("HookLuaPatchRetPrefix", BindingFlags.NonPublic | BindingFlags.Static);
private static MethodInfo _miHookLuaPatchPostfix = typeof(LuaHook).GetMethod("HookLuaPatchPostfix", BindingFlags.NonPublic | BindingFlags.Static);
private static MethodInfo _miHookLuaPatchRetPostfix = typeof(LuaHook).GetMethod("HookLuaPatchRetPostfix", BindingFlags.NonPublic | BindingFlags.Static);
public void HookMethod(string identifier, string className, string methodName, string[] parameterNames, object hookMethod, HookMethodType hookMethodType = HookMethodType.Before)
{
var classType = LuaUserData.GetType(className);
if (classType == null)
{
GameMain.Lua.HandleLuaException(new Exception($"Tried to use HookMethod with an invalid class name '{className}'."));
return;
}
MethodInfo methodInfo = null;
if (parameterNames != null)
{
Type[] parameterTypes = parameterNames.Select(x => LuaUserData.GetType(x)).ToArray();
methodInfo = classType.GetMethod(methodName, DefaultBindingFlags, null, parameterTypes, null);
}
else
{
methodInfo = classType.GetMethod(methodName, DefaultBindingFlags);
}
if (methodInfo == null)
{
string parameterNamesStr = parameterNames == null ? "" : string.Join(", ", parameterNames == null);
GameMain.Lua.HandleLuaException(new Exception($"Method '{methodName}' with parameters '{parameterNamesStr}' not found in class '{className}'"));
return;
}
identifier = identifier.ToLower();
var funcAddr = ((long)methodInfo.MethodHandle.GetFunctionPointer());
var patches = Harmony.GetPatchInfo(methodInfo);
if (hookMethodType == HookMethodType.Before)
{
if (methodInfo.ReturnType == typeof(void))
{
if (patches == null || patches.Prefixes == null || patches.Prefixes.Find(patch => patch.PatchMethod == _miHookLuaPatchPrefix) == null)
{
GameMain.Lua.harmony.Patch(methodInfo, prefix: new HarmonyMethod(_miHookLuaPatchPrefix));
}
}
else
{
if (patches == null || patches.Prefixes == null || patches.Prefixes.Find(patch => patch.PatchMethod == _miHookLuaPatchRetPrefix) == null)
{
GameMain.Lua.harmony.Patch(methodInfo, prefix: new HarmonyMethod(_miHookLuaPatchRetPrefix));
}
}
if (_hookPrefixMethods.TryGetValue(funcAddr, out HashSet<Tuple<string, object>> methodSet))
{
if (identifier != "")
{
methodSet.RemoveWhere(tuple => tuple.Item1 == identifier);
}
if (hookMethod != null)
{
methodSet.Add(Tuple.Create(identifier, hookMethod));
}
}
else if (hookMethod != null)
{
_hookPrefixMethods.Add(funcAddr, new HashSet<Tuple<string, object>>() { Tuple.Create(identifier, hookMethod) });
}
}
else if (hookMethodType == HookMethodType.After)
{
if (methodInfo.ReturnType == typeof(void))
{
if (patches == null || patches.Postfixes == null || patches.Postfixes.Find(patch => patch.PatchMethod == _miHookLuaPatchPostfix) == null)
{
GameMain.Lua.harmony.Patch(methodInfo, postfix: new HarmonyMethod(_miHookLuaPatchPostfix));
}
}
else
{
if (patches == null || patches.Postfixes == null || patches.Postfixes.Find(patch => patch.PatchMethod == _miHookLuaPatchRetPostfix) == null)
{
GameMain.Lua.harmony.Patch(methodInfo, postfix: new HarmonyMethod(_miHookLuaPatchRetPostfix));
}
}
if (_hookPostfixMethods.TryGetValue(funcAddr, out HashSet<Tuple<string, object>> methodSet))
{
if (identifier != "")
{
methodSet.RemoveWhere(tuple => tuple.Item1 == identifier);
}
if (hookMethod != null)
{
methodSet.Add(Tuple.Create(identifier, hookMethod));
}
}
else if (hookMethod != null)
{
_hookPostfixMethods.Add(funcAddr, new HashSet<Tuple<string, object>>() { Tuple.Create(identifier, hookMethod) });
}
}
}
public void HookMethod(string className, string methodName, object hookMethod, HookMethodType hookMethodType = HookMethodType.Before)
{
HookMethod("", className, methodName, null, hookMethod, hookMethodType);
}
public void HookMethod(string className, string methodName, string[] parameterNames, object hookMethod, HookMethodType hookMethodType = HookMethodType.Before)
{
HookMethod("", className, methodName, parameterNames, hookMethod, hookMethodType);
}
public void HookMethod(string identifier, string className, string methodName, object hookMethod, HookMethodType hookMethodType = HookMethodType.Before)
{
HookMethod(identifier, className, methodName, null, hookMethod, hookMethodType);
}
public void EnqueueFunction(object function, params object[] args)
{
queuedFunctionCalls.Enqueue(new Tuple<float, object, object[]>(0, function, args));
}
public void EnqueueTimedFunction(float time, object function, params object[] args)
{
queuedFunctionCalls.Enqueue(new Tuple<float, object, object[]>(time, function, args));
}
public void Add(string name, string hookName, object function)
{
if (name == null && hookName == null && function == null) return;
name = name.ToLower();
if (!hookFunctions.ContainsKey(name))
hookFunctions.Add(name, new Dictionary<string, HookFunction>());
hookFunctions[name][hookName] = new HookFunction(name, hookName, function);
}
public void Remove(string name, string hookName)
{
if (name == null && hookName == null) return;
name = name.ToLower();
if (!hookFunctions.ContainsKey(name))
return;
if (hookFunctions[name].ContainsKey(hookName))
hookFunctions[name].Remove(hookName);
}
public void Update()
{
try
{
if (queuedFunctionCalls.TryPeek(out Tuple<float, object, object[]> result))
{
if (Timing.TotalTime >= result.Item1)
{
GameMain.Lua.CallFunction(result.Item2, result.Item3);
queuedFunctionCalls.Dequeue();
}
}
}
catch (Exception ex)
{
GameMain.Lua.HandleLuaException(ex, $"queuedFunctionCalls was {queuedFunctionCalls}");
}
}
public object Call(string name, params object[] args)
{
#if CLIENT
if (GameMain.GameSession?.IsRunning == false && GameMain.IsSingleplayer)
return null;
#endif
if (GameMain.Lua == null) return null;
if (name == null) return null;
if (args == null) { args = new object[] { }; }
name = name.ToLower();
if (!hookFunctions.ContainsKey(name))
return null;
object lastResult = null;
foreach (HookFunction hf in hookFunctions[name].Values)
{
try
{
if (hf.function is Closure)
{
var result = GameMain.Lua.lua.Call(hf.function, args);
if (!result.IsNil())
lastResult = result;
}
}
catch (Exception e)
{
StringBuilder argsSb = new StringBuilder();
foreach (var arg in args)
{
argsSb.Append(arg + " ");
}
GameMain.Lua.HandleLuaException(e, $"Error in Hook '{name}'->'{hf.hookName}', with args '{argsSb}'");
}
}
return lastResult;
}
}
}
@@ -28,7 +28,7 @@ namespace Barotrauma
if (type == null)
{
GameMain.Lua.HandleLuaException(new Exception($"Tried to register a type that doesn't exist: {typeName}."));
GameMain.LuaCs.HandleLuaException(new Exception($"Tried to register a type that doesn't exist: {typeName}."));
return null;
}
@@ -41,7 +41,7 @@ namespace Barotrauma
if (type == null)
{
GameMain.Lua.HandleLuaException(new Exception($"Tried to unregister a type that doesn't exist: {typeName}."));
GameMain.LuaCs.HandleLuaException(new Exception($"Tried to unregister a type that doesn't exist: {typeName}."));
return;
}
@@ -79,7 +79,7 @@ namespace Barotrauma
if (type == null)
{
GameMain.Lua.HandleLuaException(new Exception($"Tried to create a static userdata of a type that doesn't exist: {typeName}."));
GameMain.LuaCs.HandleLuaException(new Exception($"Tried to create a static userdata of a type that doesn't exist: {typeName}."));
return null;
}
@@ -94,7 +94,7 @@ namespace Barotrauma
if (type == null)
{
GameMain.Lua.HandleLuaException(new Exception($"Tried to create an enum table with a type that doesn't exist:: {typeName}."));
GameMain.LuaCs.HandleLuaException(new Exception($"Tried to create an enum table with a type that doesn't exist:: {typeName}."));
return null;
}
@@ -126,7 +126,7 @@ namespace Barotrauma
{
if (IUUD == null)
{
GameMain.Lua.HandleLuaException(new Exception($"Tried to use a UserDataDescriptor that is null to make {fieldName} accessible."));
GameMain.LuaCs.HandleLuaException(new Exception($"Tried to use a UserDataDescriptor that is null to make {fieldName} accessible."));
return;
}
@@ -140,7 +140,7 @@ namespace Barotrauma
if (field == null)
{
GameMain.Lua.HandleLuaException(new Exception($"Tried to make field '{fieldName}' accessible, but the field doesn't exist."));
GameMain.LuaCs.HandleLuaException(new Exception($"Tried to make field '{fieldName}' accessible, but the field doesn't exist."));
return;
}
@@ -164,7 +164,7 @@ namespace Barotrauma
{
if (IUUD == null)
{
GameMain.Lua.HandleLuaException(new Exception($"Tried to use a UserDataDescriptor that is null to make {methodName} accessible."));
GameMain.LuaCs.HandleLuaException(new Exception($"Tried to use a UserDataDescriptor that is null to make {methodName} accessible."));
return;
}
@@ -178,7 +178,7 @@ namespace Barotrauma
if (method == null)
{
GameMain.Lua.HandleLuaException(new Exception($"Tried to make method '{methodName}' accessible, but the method doesn't exist."));
GameMain.LuaCs.HandleLuaException(new Exception($"Tried to make method '{methodName}' accessible, but the method doesn't exist."));
return;
}
@@ -190,7 +190,7 @@ namespace Barotrauma
{
if (IUUD == null)
{
GameMain.Lua.HandleLuaException(new Exception($"Tried to use a UserDataDescriptor that is null to add method {methodName}."));
GameMain.LuaCs.HandleLuaException(new Exception($"Tried to use a UserDataDescriptor that is null to add method {methodName}."));
return;
}
@@ -198,8 +198,8 @@ namespace Barotrauma
descriptor.RemoveMember(methodName);
descriptor.AddMember(methodName, new ObjectCallbackMemberDescriptor(methodName, (object arg1, ScriptExecutionContext arg2, CallbackArguments arg3) =>
{
if (GameMain.Lua != null)
return GameMain.Lua.CallFunction(function, arg3.GetArray());
if (GameMain.LuaCs != null)
return GameMain.LuaCs.CallFunction(function, arg3.GetArray());
return null;
}));
}
@@ -208,7 +208,7 @@ namespace Barotrauma
{
if (IUUD == null)
{
GameMain.Lua.HandleLuaException(new Exception($"Tried to use a UserDataDescriptor that is null to remove the member {memberName}."));
GameMain.LuaCs.HandleLuaException(new Exception($"Tried to use a UserDataDescriptor that is null to remove the member {memberName}."));
return;
}
@@ -29,7 +29,7 @@ namespace Barotrauma
RegisterAction<Microsoft.Xna.Framework.Graphics.SpriteBatch, float>();
{
object Call(object function, params object[] arguments) => GameMain.Lua.CallFunction(function, arguments);
object Call(object function, params object[] arguments) => GameMain.LuaCs.CallFunction(function, arguments);
void RegisterHandler<T>(Func<Closure, object> converter)
{
Script.GlobalOptions.CustomConverters.SetScriptToClrCustomConversion(DataType.Function, typeof(T), v => converter(v.Function));
@@ -122,7 +122,7 @@ namespace Barotrauma
Script.GlobalOptions.CustomConverters.SetScriptToClrCustomConversion(DataType.Function, typeof(Action<T>), v =>
{
var function = v.Function;
return (Action<T>)(p => GameMain.Lua.CallFunction(function, p));
return (Action<T>)(p => GameMain.LuaCs.CallFunction(function, p));
});
}
@@ -131,7 +131,7 @@ namespace Barotrauma
Script.GlobalOptions.CustomConverters.SetScriptToClrCustomConversion(DataType.Function, typeof(Action<T1, T2>), v =>
{
var function = v.Function;
return (Action<T1, T2>)((a1, a2) => GameMain.Lua.CallFunction(function, a1, a2));
return (Action<T1, T2>)((a1, a2) => GameMain.LuaCs.CallFunction(function, a1, a2));
});
}
@@ -140,7 +140,7 @@ namespace Barotrauma
Script.GlobalOptions.CustomConverters.SetScriptToClrCustomConversion(DataType.Function, typeof(Action), v =>
{
var function = v.Function;
return (Action)(() => GameMain.Lua.CallFunction(function));
return (Action)(() => GameMain.LuaCs.CallFunction(function));
});
}
@@ -8,7 +8,7 @@ using System.Linq;
namespace Barotrauma
{
partial class LuaSetup {
partial class LuaCsSetup {
public class LuaScriptLoader : ScriptLoaderBase
{
@@ -0,0 +1,448 @@
using System;
using System.Linq;
using System.Reflection;
using MoonSharp.Interpreter;
using HarmonyLib;
using System.Collections.Generic;
using System.Text;
namespace Barotrauma
{
delegate object CsHookDelegate(params object[] args);
delegate object CsPatchDelegate(object self, params object[] args);
partial class LuaCsHook
{
public LuaCsHook()
{
luaHookPrefixMethods = new Dictionary<long, HashSet<(string, object)>>();
luaHookPostfixMethods = new Dictionary<long, HashSet<(string, object)>>();
csHookPrefixMethods = new Dictionary<long, HashSet<(IDisposable, CsPatchDelegate)>>();
csHookPostfixMethods = new Dictionary<long, HashSet<(IDisposable, CsPatchDelegate)>>();
}
public class LuaHookFunction
{
public string name;
public string hookName;
public object function;
public LuaHookFunction(string n, string hn, object func)
{
name = n;
hookName = hn;
function = func;
}
}
private Dictionary<string, Dictionary<string, LuaHookFunction>> luaHookFunctions = new Dictionary<string, Dictionary<string, LuaHookFunction>>();
private Dictionary<string, Dictionary<CsHookDelegate, IDisposable>> csHookFunctions = new Dictionary<string, Dictionary<CsHookDelegate, IDisposable>>();
private static Dictionary<long, HashSet<(string, object)>> luaHookPrefixMethods;
private static Dictionary<long, HashSet<(string, object)>> luaHookPostfixMethods;
private static Dictionary<long, HashSet<(IDisposable, CsPatchDelegate)>> csHookPrefixMethods;
private static Dictionary<long, HashSet<(IDisposable, CsPatchDelegate)>> csHookPostfixMethods;
private Queue<Tuple<float, object, object[]>> queuedFunctionCalls = new Queue<Tuple<float, object, object[]>>();
public enum HookMethodType
{
Before, After
}
static void _hookLuaPatch(MethodBase __originalMethod, object[] __args, object __instance, out LuaResult result, HookMethodType hookMethodType)
{
result = new LuaResult(null);
#if CLIENT
if (GameMain.GameSession?.IsRunning == false && GameMain.IsSingleplayer)
return;
#endif
try
{
var funcAddr = ((long)__originalMethod.MethodHandle.GetFunctionPointer());
HashSet<(string, object)> methodSet = null;
switch (hookMethodType)
{
case HookMethodType.Before:
luaHookPrefixMethods.TryGetValue(funcAddr, out methodSet);
break;
case HookMethodType.After:
luaHookPostfixMethods.TryGetValue(funcAddr, out methodSet);
break;
default:
break;
}
if (methodSet != null)
{
var @params = __originalMethod.GetParameters();
var ptable = new Dictionary<string, object>();
for (int i = 0; i < @params.Length; i++)
{
ptable.Add(@params[i].Name, __args[i]);
}
foreach (var tuple in methodSet)
{
result = new LuaResult(GameMain.LuaCs.lua.Call(tuple.Item2, __instance, ptable));
}
}
}
catch (Exception ex)
{
GameMain.LuaCs.HandleLuaException(ex);
}
}
private static bool HookLuaPatchPrefix(MethodBase __originalMethod, object[] __args, object __instance)
{
_hookLuaPatch(__originalMethod, __args, __instance, out LuaResult result, HookMethodType.Before);
return result.IsNull();
}
private static bool HookLuaPatchRetPrefix(MethodBase __originalMethod, object[] __args, ref object __result, object __instance)
{
_hookLuaPatch(__originalMethod, __args, __instance, out LuaResult result, HookMethodType.Before);
if (!result.IsNull())
{
if (__originalMethod is MethodInfo mi)
{
__result = result.DynValue().ToObject(mi.ReturnType);
}
else
{
__result = result.Object();
}
return false;
}
return true;
}
private static void HookLuaPatchPostfix(MethodBase __originalMethod, object[] __args, object __instance)
{
_hookLuaPatch(__originalMethod, __args, __instance, out LuaResult result, HookMethodType.After);
}
private static void HookLuaPatchRetPostfix(MethodBase __originalMethod, object[] __args, ref object __result, object __instance)
{
_hookLuaPatch(__originalMethod, __args, __instance, out LuaResult result, HookMethodType.After);
if (!result.IsNull())
{
if (__originalMethod is MethodInfo mi)
{
__result = result.DynValue().ToObject(mi.ReturnType);
}
else
{
__result = result.Object();
}
}
}
private const BindingFlags DefaultBindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
private static MethodInfo _miHookLuaPatchPrefix = typeof(LuaCsHook).GetMethod("HookLuaPatchPrefix", BindingFlags.NonPublic | BindingFlags.Static);
private static MethodInfo _miHookLuaPatchRetPrefix = typeof(LuaCsHook).GetMethod("HookLuaPatchRetPrefix", BindingFlags.NonPublic | BindingFlags.Static);
private static MethodInfo _miHookLuaPatchPostfix = typeof(LuaCsHook).GetMethod("HookLuaPatchPostfix", BindingFlags.NonPublic | BindingFlags.Static);
private static MethodInfo _miHookLuaPatchRetPostfix = typeof(LuaCsHook).GetMethod("HookLuaPatchRetPostfix", BindingFlags.NonPublic | BindingFlags.Static);
private void HookMethod(string identifier, string className, string methodName, string[] parameterNames, object hookMethod, HookMethodType hookMethodType = HookMethodType.Before)
{
var classType = LuaUserData.GetType(className);
if (classType == null)
{
GameMain.LuaCs.HandleLuaException(new Exception($"Tried to use HookMethod with an invalid class name '{className}'."));
return;
}
MethodInfo methodInfo = null;
if (parameterNames != null)
{
Type[] parameterTypes = parameterNames.Select(x => LuaUserData.GetType(x)).ToArray();
methodInfo = classType.GetMethod(methodName, DefaultBindingFlags, null, parameterTypes, null);
}
else
{
methodInfo = classType.GetMethod(methodName, DefaultBindingFlags);
}
if (methodInfo == null)
{
string parameterNamesStr = parameterNames == null ? "" : string.Join(", ", parameterNames == null);
GameMain.LuaCs.HandleLuaException(new Exception($"Method '{methodName}' with parameters '{parameterNamesStr}' not found in class '{className}'"));
return;
}
identifier = identifier.ToLower();
var funcAddr = ((long)methodInfo.MethodHandle.GetFunctionPointer());
var patches = Harmony.GetPatchInfo(methodInfo);
if (hookMethodType == HookMethodType.Before)
{
if (methodInfo.ReturnType == typeof(void))
{
if (patches == null || patches.Prefixes == null || patches.Prefixes.Find(patch => patch.PatchMethod == _miHookLuaPatchPrefix) == null)
{
GameMain.LuaCs.harmony.Patch(methodInfo, prefix: new HarmonyMethod(_miHookLuaPatchPrefix));
}
}
else
{
if (patches == null || patches.Prefixes == null || patches.Prefixes.Find(patch => patch.PatchMethod == _miHookLuaPatchRetPrefix) == null)
{
GameMain.LuaCs.harmony.Patch(methodInfo, prefix: new HarmonyMethod(_miHookLuaPatchRetPrefix));
}
}
if (luaHookPrefixMethods.TryGetValue(funcAddr, out HashSet<(string, object)> methodSet))
{
if (identifier != "")
{
methodSet.RemoveWhere(tuple => tuple.Item1 == identifier);
}
if (hookMethod != null)
{
methodSet.Add((identifier, hookMethod));
}
}
else if (hookMethod != null)
{
luaHookPrefixMethods.Add(funcAddr, new HashSet<(string, object)>() { (identifier, hookMethod) });
}
}
else if (hookMethodType == HookMethodType.After)
{
if (methodInfo.ReturnType == typeof(void))
{
if (patches == null || patches.Postfixes == null || patches.Postfixes.Find(patch => patch.PatchMethod == _miHookLuaPatchPostfix) == null)
{
GameMain.LuaCs.harmony.Patch(methodInfo, postfix: new HarmonyMethod(_miHookLuaPatchPostfix));
}
}
else
{
if (patches == null || patches.Postfixes == null || patches.Postfixes.Find(patch => patch.PatchMethod == _miHookLuaPatchRetPostfix) == null)
{
GameMain.LuaCs.harmony.Patch(methodInfo, postfix: new HarmonyMethod(_miHookLuaPatchRetPostfix));
}
}
if (luaHookPostfixMethods.TryGetValue(funcAddr, out HashSet<(string, object)> methodSet))
{
if (identifier != "")
{
methodSet.RemoveWhere(tuple => tuple.Item1 == identifier);
}
if (hookMethod != null)
{
methodSet.Add((identifier, hookMethod));
}
}
else if (hookMethod != null)
{
luaHookPostfixMethods.Add(funcAddr, new HashSet<(string, object)>() { (identifier, hookMethod) });
}
}
}
private void HookMethod(string className, string methodName, object hookMethod, HookMethodType hookMethodType = HookMethodType.Before)
{
HookMethod("", className, methodName, null, hookMethod, hookMethodType);
}
private void HookMethod(string className, string methodName, string[] parameterNames, object hookMethod, HookMethodType hookMethodType = HookMethodType.Before)
{
HookMethod("", className, methodName, parameterNames, hookMethod, hookMethodType);
}
private void HookMethod(string identifier, string className, string methodName, object hookMethod, HookMethodType hookMethodType = HookMethodType.Before)
{
HookMethod(identifier, className, methodName, null, hookMethod, hookMethodType);
}
public void HookMethod(IDisposable owner, MethodInfo methodInfo, CsPatchDelegate hookMethod, HookMethodType hookMethodType = HookMethodType.Before)
{
if (owner == null || methodInfo == null || hookMethod == null) throw new ArgumentNullException("All 'HookMethod' arguments must not be null.");
var funcAddr = ((long)methodInfo.MethodHandle.GetFunctionPointer());
var patches = Harmony.GetPatchInfo(methodInfo);
if (hookMethodType == HookMethodType.Before)
{
if (patches == null || patches.Prefixes == null || patches.Prefixes.Find(patch => patch.PatchMethod == hookMethod.Method) == null)
{
GameMain.LuaCs.harmony.Patch(methodInfo, prefix: new HarmonyMethod(hookMethod.Method));
}
if (csHookPrefixMethods.TryGetValue(funcAddr, out HashSet<(IDisposable, CsPatchDelegate)> methodSet))
{
methodSet.RemoveWhere(tuple => tuple.Item1 == owner);
if (hookMethod != null)
{
methodSet.Add((owner, hookMethod));
}
}
else if (hookMethod != null)
{
csHookPrefixMethods.Add(funcAddr, new HashSet<(IDisposable, CsPatchDelegate)>() { (owner, hookMethod) });
}
}
else if (hookMethodType == HookMethodType.After)
{
if (patches == null || patches.Postfixes == null || patches.Postfixes.Find(patch => patch.PatchMethod == hookMethod.Method) == null)
{
GameMain.LuaCs.harmony.Patch(methodInfo, postfix: new HarmonyMethod(hookMethod.Method));
}
if (csHookPostfixMethods.TryGetValue(funcAddr, out HashSet<(IDisposable, CsPatchDelegate)> methodSet))
{
methodSet.RemoveWhere(tuple => tuple.Item1 == owner);
if (hookMethod != null)
{
methodSet.Add((owner, hookMethod));
}
}
else if (hookMethod != null)
{
csHookPostfixMethods.Add(funcAddr, new HashSet<(IDisposable, CsPatchDelegate)>() { (owner, hookMethod) });
}
}
}
public void EnqueueFunction(object function, params object[] args)
{
queuedFunctionCalls.Enqueue(new Tuple<float, object, object[]>(0, function, args));
}
public void EnqueueTimedFunction(float time, object function, params object[] args)
{
queuedFunctionCalls.Enqueue(new Tuple<float, object, object[]>(time, function, args));
}
public void Add(string name, string hookName, object function)
{
if (name == null || hookName == null || function == null) return;
name = name.ToLower();
if (!luaHookFunctions.ContainsKey(name))
luaHookFunctions.Add(name, new Dictionary<string, LuaHookFunction>());
luaHookFunctions[name][hookName] = new LuaHookFunction(name, hookName, function);
}
public void Remove(string name, string hookName)
{
if (name == null || hookName == null) return;
name = name.ToLower();
if (!luaHookFunctions.ContainsKey(name))
return;
if (luaHookFunctions[name].ContainsKey(hookName))
luaHookFunctions[name].Remove(hookName);
}
public void Add(string name, CsHookDelegate hook, IDisposable owner = null)
{
if (name == null || hook == null) throw new ArgumentNullException("Name and Hook must not be null");
if (!csHookFunctions.ContainsKey(name))
csHookFunctions.Add(name, new Dictionary<CsHookDelegate, IDisposable>());
csHookFunctions[name][hook] = owner;
}
public void Remove(string name, CsHookDelegate hook)
{
if (name == null || hook == null) throw new ArgumentNullException("All arguments must not be null");
if (!csHookFunctions.ContainsKey(name))
return;
if (csHookFunctions[name].ContainsKey(hook))
csHookFunctions[name].Remove(hook);
}
public void Update()
{
try
{
if (queuedFunctionCalls.TryPeek(out Tuple<float, object, object[]> result))
{
if (Timing.TotalTime >= result.Item1)
{
GameMain.LuaCs.CallFunction(result.Item2, result.Item3);
queuedFunctionCalls.Dequeue();
}
}
}
catch (Exception ex)
{
GameMain.LuaCs.HandleLuaException(ex, $"queuedFunctionCalls was {queuedFunctionCalls}");
}
}
public object Call(string name, params object[] args)
{
#if CLIENT
if (GameMain.GameSession?.IsRunning == false && GameMain.IsSingleplayer)
return null;
#endif
if (GameMain.LuaCs == null) return null;
if (name == null) return null;
if (args == null) { args = new object[] { }; }
name = name.ToLower();
if (!luaHookFunctions.ContainsKey(name))
return null;
object lastResult = null;
foreach (LuaHookFunction hf in luaHookFunctions[name].Values)
{
try
{
if (hf.function is Closure)
{
var result = GameMain.LuaCs.lua.Call(hf.function, args);
if (!result.IsNil())
lastResult = result;
}
}
catch (Exception e)
{
StringBuilder argsSb = new StringBuilder();
foreach (var arg in args)
{
argsSb.Append(arg + " ");
}
GameMain.LuaCs.HandleLuaException(e, $"Error in Hook '{name}'->'{hf.hookName}', with args '{argsSb}'");
}
}
return lastResult;
}
}
}
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
@@ -8,22 +8,26 @@ using Microsoft.Xna.Framework;
using MoonSharp.Interpreter.Interop;
using System.IO.Compression;
using HarmonyLib;
using static Barotrauma.LuaCsSetup;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("NetScriptAssembly", AllInternalsVisible = true)]
namespace Barotrauma
{
partial class LuaSetup
partial class LuaCsSetup
{
public const string LUASETUP_FILE = "Lua/LuaSetup.lua";
public const string VERSION_FILE = "luacsversion.txt";
public Script lua;
public LuaHook hook;
public LuaCsHook hook;
public LuaGame game;
public LuaNetworking networking;
public Harmony harmony;
public LuaScriptLoader luaScriptLoader;
public NetScriptLoader netScriptLoader;
public static ContentPackage GetPackage()
{
@@ -64,9 +68,9 @@ namespace Barotrauma
}
}
public void PrintError(object message)
{
if (message == null) { message = "nil"; }
private static void PrintErrorBase(string prefix, object message, string empty)
{
if (message == null) { message = empty; }
string str = message.ToString();
for (int i = 0; i < str.Length; i += 1024)
@@ -74,12 +78,7 @@ namespace Barotrauma
string subStr = str.Substring(i, Math.Min(1024, str.Length - i));
string errorMsg = subStr;
if (i == 0)
#if SERVER
errorMsg = "[SV LUA ERROR] " + errorMsg;
#else
errorMsg = "[CL LUA ERROR] " + errorMsg;
#endif
if (i == 0) errorMsg = prefix + errorMsg;
DebugConsole.ThrowError(errorMsg);
@@ -97,9 +96,17 @@ namespace Barotrauma
}
}
public void PrintMessage(object message)
{
if (message == null) { message = "nil"; }
#if SERVER
private void PrintError(object message) => PrintErrorBase("[SV LUA ERROR] ", message, "nil");
public static void PrintCsError(object message) => PrintErrorBase("[SV CS ERROR] ", message, "Null");
#else
private void PrintError(object message) => PrintErrorBase("[CL LUA ERROR] ", message, "nil");
public static void PrintCsError(object message) => PrintErrorBase("[CL CS ERROR] ", message, "Null");
#endif
private static void PrintMessageBase(string prefix, object message, string empty)
{
if (message == null) { message = empty; }
string str = message.ToString();
for (int i = 0; i < str.Length; i += 1024)
@@ -115,7 +122,7 @@ namespace Barotrauma
GameMain.Server.SendDirectChatMessage(ChatMessage.Create("", subStr, ChatMessageType.Console, null, textColor: Color.MediumPurple), c);
}
GameServer.Log("[LUA] " + subStr, ServerLog.MessageType.ServerMessage);
GameServer.Log(prefix + subStr, ServerLog.MessageType.ServerMessage);
}
#endif
}
@@ -126,6 +133,8 @@ namespace Barotrauma
DebugConsole.NewMessage(message.ToString(), Color.Purple);
#endif
}
private void PrintMessage(object message) => PrintMessageBase("[LUA] ", message, "nil");
public static void PrintCsMessage(object message) => PrintMessageBase("[CS] ", message, "Null");
public DynValue DoString(string code, Table globalContext = null, string codeStringFriendly = null)
{
@@ -242,25 +251,44 @@ namespace Barotrauma
public void Stop()
{
harmony?.UnpatchAll();
ANetMod.LoadedMods.ForEach(m => m.Dispose());
ANetMod.LoadedMods.Clear();
hook?.Call("stop");
game?.Stop();
hook?.Call("stop", new object[] { });
harmony?.UnpatchAll();
hook = new LuaHook();
hook = new LuaCsHook();
game = new LuaGame();
networking = new LuaNetworking();
luaScriptLoader = null;
}
private void InitCs()
{
netScriptLoader = new NetScriptLoader(this);
netScriptLoader.SearchFolders();
if (netScriptLoader == null) throw new Exception("LuaCsSetup was not properly initialized.");
try
{
var modTypes = netScriptLoader.Compile();
modTypes.ForEach(t => t.GetConstructor(new Type[] { }).Invoke(null));
}
catch (Exception ex)
{
PrintMessage(ex);
}
}
public void Initialize()
{
Stop();
PrintMessage("Lua! Version " + AssemblyInfo.GitRevision);
PrintMessage("LuaCs! Version " + AssemblyInfo.GitRevision);
luaScriptLoader = new LuaScriptLoader();
luaScriptLoader.ModulePaths = new string[] { };
InitCs();
LuaCustomConverters.RegisterAll();
@@ -271,11 +299,11 @@ namespace Barotrauma
harmony = new Harmony("com.LuaForBarotrauma");
harmony.UnpatchAll();
hook = new LuaHook();
hook = new LuaCsHook();
game = new LuaGame();
networking = new LuaNetworking();
UserData.RegisterType<LuaHook>();
UserData.RegisterType<LuaCsHook>();
UserData.RegisterType<LuaGame>();
UserData.RegisterType<LuaTimer>();
UserData.RegisterType<LuaFile>();
@@ -333,7 +361,7 @@ namespace Barotrauma
try
{
string luaPath = Path.Combine(path, "Binary/Lua/LuaSetup.lua");
string luaPath = Path.Combine(path, "Binary/LuaCs/LuaCsSetup.lua");
lua.Call(lua.LoadFile(luaPath), Path.GetDirectoryName(luaPath));
}
catch (Exception e)
@@ -343,13 +371,13 @@ namespace Barotrauma
}
else
{
PrintError("Lua loader not found! Lua/LuaSetup.lua, no Lua scripts will be executed or work.");
PrintError("LuaCs loader not found! LuaCs/LuaCsSetup.lua, no LuaCs scripts will be executed or work.");
}
}
public LuaSetup()
public LuaCsSetup()
{
hook = new LuaHook();
hook = new LuaCsHook();
game = new LuaGame();
networking = new LuaNetworking();
}
@@ -660,7 +660,7 @@ namespace Barotrauma
if (Math.Max(hull1.WorldSurface + hull1.WaveY[hull1.WaveY.Length - 1], hull2.WorldSurface + hull2.WaveY[0]) > WorldRect.Y) { return; }
}
var should = new LuaResult(GameMain.Lua.hook.Call("gapOxygenUpdate", new object[] { this, hull1, hull2 }));
var should = new LuaResult(GameMain.LuaCs.hook.Call("gapOxygenUpdate", this, hull1, hull2));
if (should.Bool())
return;
@@ -596,12 +596,12 @@ namespace Barotrauma
Powered.UpdatePower(deltaTime * MapEntityUpdateInterval);
foreach (Item item in Item.ItemList)
{
if (GameMain.Lua.game.updatePriorityItems.Contains(item)) continue;
if (GameMain.LuaCs.game.updatePriorityItems.Contains(item)) continue;
item.Update(deltaTime * MapEntityUpdateInterval, cam);
}
}
foreach (var item in GameMain.Lua.game.updatePriorityItems)
foreach (var item in GameMain.LuaCs.game.updatePriorityItems)
{
if (item.Removed) continue;
@@ -1,255 +0,0 @@
using System;
using System.Linq;
using System.Reflection;
using MoonSharp.Interpreter;
using HarmonyLib;
using System.Collections.Generic;
using System.Text;
namespace Barotrauma
{
using NetHookMethod = Func<object[], object>;
using HookMethod = Func<object, Dictionary<string, object>, object>;
partial class NetHook
{
public NetHook()
{
_hookPrefixMethods = new Dictionary<long, HashSet<Tuple<string, HookMethod>>>();
_hookPostfixMethods = new Dictionary<long, HashSet<Tuple<string, HookMethod>>>();
}
private Dictionary<string, List<NetHookMethod>> hookFunctions = new Dictionary<string, List<NetHookMethod>>();
private static Dictionary<long, HashSet<Tuple<string, HookMethod>>> _hookPrefixMethods;
private static Dictionary<long, HashSet<Tuple<string, HookMethod>>> _hookPostfixMethods;
private Queue<Tuple<float, NetHookMethod, object[]>> queuedFunctionCalls = new Queue<Tuple<float, NetHookMethod, object[]>>();
public enum HookMethodType
{
Before, After
}
static void _hookNetPatch(MethodBase __originalMethod, object[] __args, object __instance, out object result, HookMethodType hookMethodType)
{
result = null;
#if CLIENT
if (GameMain.GameSession?.IsRunning == false && GameMain.IsSingleplayer)
return;
#endif
try
{
var funcAddr = ((long)__originalMethod.MethodHandle.GetFunctionPointer());
HashSet<Tuple<string, HookMethod>> methodSet = null;
switch (hookMethodType)
{
case HookMethodType.Before:
_hookPrefixMethods.TryGetValue(funcAddr, out methodSet);
break;
case HookMethodType.After:
_hookPostfixMethods.TryGetValue(funcAddr, out methodSet);
break;
default:
break;
}
if (methodSet != null)
{
var @params = __originalMethod.GetParameters();
var ptable = new Dictionary<string, object>();
for (int i = 0; i < @params.Length; i++)
{
ptable.Add(@params[i].Name, __args[i]);
}
foreach (var tuple in methodSet)
{
result = tuple.Item2(__instance, ptable);
}
}
}
catch (Exception ex)
{
GameMain.Net.HandleException(ex, null);
}
}
private const BindingFlags DefaultBindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
public void HookMethod(string identifier, MethodInfo methodInfo, HookMethod hookMethod, HookMethodType hookMethodType = HookMethodType.Before)
{
if (identifier == null || methodInfo == null || methodInfo == null) throw new ArgumentNullException("All 'HookMethod' arguments must not be null.");
identifier = identifier.ToLower();
var funcAddr = ((long)methodInfo.MethodHandle.GetFunctionPointer());
var patches = Harmony.GetPatchInfo(methodInfo);
if (hookMethodType == HookMethodType.Before)
{
if (methodInfo.ReturnType == typeof(void))
{
if (patches == null || patches.Prefixes == null || patches.Prefixes.Find(patch => patch.PatchMethod == hookMethod.Method) == null)
{
GameMain.Net.harmony.Patch(methodInfo, prefix: new HarmonyMethod(hookMethod.Method));
}
}
else
{
if (patches == null || patches.Prefixes == null || patches.Prefixes.Find(patch => patch.PatchMethod == hookMethod.Method) == null)
{
GameMain.Net.harmony.Patch(methodInfo, prefix: new HarmonyMethod(hookMethod.Method));
}
}
if (_hookPrefixMethods.TryGetValue(funcAddr, out HashSet<Tuple<string, HookMethod>> methodSet))
{
if (identifier != "")
{
methodSet.RemoveWhere(tuple => tuple.Item1 == identifier);
}
if (hookMethod != null)
{
methodSet.Add(Tuple.Create(identifier, hookMethod));
}
}
else if (hookMethod != null)
{
_hookPrefixMethods.Add(funcAddr, new HashSet<Tuple<string, HookMethod>>() { Tuple.Create(identifier, hookMethod) });
}
}
else if (hookMethodType == HookMethodType.After)
{
if (methodInfo.ReturnType == typeof(void))
{
if (patches == null || patches.Postfixes == null || patches.Postfixes.Find(patch => patch.PatchMethod == hookMethod.Method) == null)
{
GameMain.Net.harmony.Patch(methodInfo, postfix: new HarmonyMethod(hookMethod.Method));
}
}
else
{
if (patches == null || patches.Postfixes == null || patches.Postfixes.Find(patch => patch.PatchMethod == hookMethod.Method) == null)
{
GameMain.Net.harmony.Patch(methodInfo, postfix: new HarmonyMethod(hookMethod.Method));
}
}
if (_hookPostfixMethods.TryGetValue(funcAddr, out HashSet<Tuple<string, HookMethod>> methodSet))
{
if (identifier != "")
{
methodSet.RemoveWhere(tuple => tuple.Item1 == identifier);
}
if (hookMethod != null)
{
methodSet.Add(Tuple.Create(identifier, hookMethod));
}
}
else if (hookMethod != null)
{
_hookPostfixMethods.Add(funcAddr, new HashSet<Tuple<string, HookMethod>>() { Tuple.Create(identifier, hookMethod) });
}
}
}
public void EnqueueFunction(NetHookMethod function, params object[] args)
{
queuedFunctionCalls.Enqueue(new Tuple<float, NetHookMethod, object[]>(0, function, args));
}
public void EnqueueTimedFunction(float time, NetHookMethod function, params object[] args)
{
queuedFunctionCalls.Enqueue(new Tuple<float, NetHookMethod, object[]>(time, function, args));
}
public void Add(string name, NetHookMethod hook)
{
if (name == null || hook == null) throw new ArgumentNullException("Name and Action cannot be null");
name = name.ToLower();
if (!hookFunctions.ContainsKey(name))
hookFunctions.Add(name, new List<NetHookMethod>());
hookFunctions[name].Add(hook);
}
public void Remove(string name, NetHookMethod hook)
{
if (name == null || hook == null) throw new ArgumentNullException("Name and Action cannot be null");
name = name.ToLower();
if (!hookFunctions.ContainsKey(name))
return;
if (hookFunctions[name].Contains(hook))
hookFunctions[name].Remove(hook);
}
public void Update()
{
try
{
if (queuedFunctionCalls.TryPeek(out Tuple<float, NetHookMethod, object[]> result))
{
if (Timing.TotalTime >= result.Item1)
{
result.Item2(result.Item3);
queuedFunctionCalls.Dequeue();
}
}
}
catch (Exception ex)
{
GameMain.Net.HandleException(ex, $"queuedFunctionCalls was {queuedFunctionCalls}");
}
}
public object Call(string name, params object[] args)
{
#if CLIENT
if (GameMain.GameSession?.IsRunning == false && GameMain.IsSingleplayer)
return null;
#endif
if (GameMain.Net == null) return null;
if (name == null) return null;
if (args == null) { args = new object[] { }; }
name = name.ToLower();
if (!hookFunctions.ContainsKey(name))
return null;
object lastResult = null;
foreach (var hook in hookFunctions[name])
{
try
{
var result = hook(args);
if (!(result == null))
lastResult = result;
}
catch (Exception e)
{
StringBuilder argsSb = new StringBuilder();
foreach (var arg in args)
{
argsSb.Append(arg + " ");
}
GameMain.Net.HandleException(e, $"Error in Hook '{name}'->'{hook}', with args '{argsSb}'\n{Environment.StackTrace}");
}
}
return lastResult;
}
}
}
@@ -13,150 +13,147 @@ using static NetScript;
namespace Barotrauma
{
partial class NetSetup
class NetScriptLoader : AssemblyLoadContext
{
public LuaCsSetup setup;
private List<MetadataReference> defaultReferences;
private List<SyntaxTree> syntaxTrees;
public Assembly Assembly { get; private set; }
public class NetScriptLoader : AssemblyLoadContext
public NetScriptLoader(LuaCsSetup setup)
{
public NetSetup net;
private List<MetadataReference> defaultReferences;
private List<SyntaxTree> syntaxTrees;
public Assembly Assembly { get; private set; }
this.setup = setup;
public NetScriptLoader(NetSetup net)
{
this.net = net;
defaultReferences = AppDomain.CurrentDomain.GetAssemblies()
.Where(a => !(a.IsDynamic || string.IsNullOrEmpty(a.Location) || a.Location.Contains("xunit")))
.Select(a => MetadataReference.CreateFromFile(a.Location) as MetadataReference)
.ToList();
syntaxTrees = new List<SyntaxTree>();
Assembly = null;
}
public void SearchFolders()
{
foreach(ContentPackage cp in GameMain.Config.AllEnabledPackages)
{
var path = Path.GetDirectoryName(cp.Path);
RunFolder(path);
}
}
public void RunFolder(string folder)
{
var scriptFiles = new List<string>();
foreach (var str in DirSearch(folder))
{
var s = str.Replace("\\", "/");
if (s.EndsWith(".cs"))
{
NetSetup.PrintMessage(s);
scriptFiles.Add(s);
}
}
try
{
if (scriptFiles.Count <= 0) return;
var mainFile = scriptFiles.Find(s => s.EndsWith("Main.cs"));
if (mainFile == null) throw new Exception("Mod folder has no Main.cs file");
scriptFiles.Remove(mainFile);
scriptFiles.Add(mainFile);
// Check file content for prohibited stuff
foreach (var file in scriptFiles)
{
var tree = SyntaxFactory.ParseSyntaxTree(File.ReadAllText(file), CSharpParseOptions.Default, file);
var error = NetScriptFilter.FilterSyntaxTree(tree as CSharpSyntaxTree);
if (error != null) throw new Exception(error);
syntaxTrees.Add(tree);
}
}
catch (CompilationErrorException ex)
{
string errStr = "Cmopilation Error in '" + folder + "':";
foreach (var diag in ex.Diagnostics)
{
errStr += "\n" + diag.ToString();
}
NetSetup.PrintMessage(errStr);
}
catch (Exception ex)
{
NetSetup.PrintMessage("Error loading '" + folder + "':\n" + ex.Message + "\n" + ex.StackTrace);
}
}
public List<Type> Compile()
{
var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
.WithMetadataImportOptions(MetadataImportOptions.All)
.WithOptimizationLevel(OptimizationLevel.Release)
.WithAllowUnsafe(false);
var compilation = CSharpCompilation.Create("NetScriptAssembly",syntaxTrees, defaultReferences, options);
using (var mem = new MemoryStream())
{
var result = compilation.Emit(mem);
if (!result.Success)
{
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(d => d.IsWarningAsError || d.Severity == DiagnosticSeverity.Error);
string errStr = "NET MODS NOT LOADED | Mod cmopilation errors:";
foreach (Diagnostic diagnostic in failures)
errStr = $"\n{diagnostic}";
NetSetup.PrintMessage(errStr);
}
else
{
mem.Seek(0, SeekOrigin.Begin);
var errStr = NetScriptFilter.FilterMetadata(new PEReader(mem).GetMetadataReader());
if (errStr == null)
{
mem.Seek(0, SeekOrigin.Begin);
Assembly = LoadFromStream(mem);
}
else NetSetup.PrintMessage(errStr);
}
}
syntaxTrees.Clear();
if (Assembly != null)
return Assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(ANetMod))).ToList();
else
throw new Exception("Unable to create net mods assembly.");
}
static string[] DirSearch(string sDir)
{
List<string> files = new List<string>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(DirSearch(d));
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
return files.ToArray();
}
defaultReferences = AppDomain.CurrentDomain.GetAssemblies()
.Where(a => !(a.IsDynamic || string.IsNullOrEmpty(a.Location) || a.Location.Contains("xunit")))
.Select(a => MetadataReference.CreateFromFile(a.Location) as MetadataReference)
.ToList();
syntaxTrees = new List<SyntaxTree>();
Assembly = null;
}
public void SearchFolders()
{
foreach(ContentPackage cp in ContentPackageManager.EnabledPackages.All)
{
var path = Path.GetDirectoryName(cp.Path);
RunFolder(path);
}
}
private void RunFolder(string folder)
{
var scriptFiles = new List<string>();
foreach (var str in DirSearch(folder))
{
var s = str.Replace("\\", "/");
if (s.EndsWith(".cs"))
{
LuaCsSetup.PrintCsMessage(s);
scriptFiles.Add(s);
}
}
try
{
if (scriptFiles.Count <= 0) return;
var mainFile = scriptFiles.Find(s => s.EndsWith("Main.cs"));
if (mainFile == null) throw new Exception("Mod folder has no Main.cs file");
scriptFiles.Remove(mainFile);
scriptFiles.Add(mainFile);
// Check file content for prohibited stuff
foreach (var file in scriptFiles)
{
var tree = SyntaxFactory.ParseSyntaxTree(File.ReadAllText(file), CSharpParseOptions.Default, file);
var error = NetScriptFilter.FilterSyntaxTree(tree as CSharpSyntaxTree);
if (error != null) throw new Exception(error);
syntaxTrees.Add(tree);
}
}
catch (CompilationErrorException ex)
{
string errStr = "Cmopilation Error in '" + folder + "':";
foreach (var diag in ex.Diagnostics)
{
errStr += "\n" + diag.ToString();
}
LuaCsSetup.PrintCsMessage(errStr);
}
catch (Exception ex)
{
LuaCsSetup.PrintCsMessage("Error loading '" + folder + "':\n" + ex.Message + "\n" + ex.StackTrace);
}
}
public List<Type> Compile()
{
var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
.WithMetadataImportOptions(MetadataImportOptions.All)
.WithOptimizationLevel(OptimizationLevel.Release)
.WithAllowUnsafe(false);
var compilation = CSharpCompilation.Create("NetScriptAssembly",syntaxTrees, defaultReferences, options);
using (var mem = new MemoryStream())
{
var result = compilation.Emit(mem);
if (!result.Success)
{
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(d => d.IsWarningAsError || d.Severity == DiagnosticSeverity.Error);
string errStr = "NET MODS NOT LOADED | Mod cmopilation errors:";
foreach (Diagnostic diagnostic in failures)
errStr = $"\n{diagnostic}";
LuaCsSetup.PrintCsMessage(errStr);
}
else
{
mem.Seek(0, SeekOrigin.Begin);
var errStr = NetScriptFilter.FilterMetadata(new PEReader(mem).GetMetadataReader());
if (errStr == null)
{
mem.Seek(0, SeekOrigin.Begin);
Assembly = LoadFromStream(mem);
}
else LuaCsSetup.PrintCsMessage(errStr);
}
}
syntaxTrees.Clear();
if (Assembly != null)
return Assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(ANetMod))).ToList();
else
throw new Exception("Unable to create net mods assembly.");
}
private static string[] DirSearch(string sDir)
{
List<string> files = new List<string>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(DirSearch(d));
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
return files.ToArray();
}
}
}
@@ -1,102 +0,0 @@
using System;
using Barotrauma.Networking;
using Microsoft.Xna.Framework;
using HarmonyLib;
using System.Runtime.CompilerServices;
//using System.Linq;
//using System.Collections.Generic;
//using Microsoft.CodeAnalysis;
//using Microsoft.CodeAnalysis.CSharp;
[assembly: InternalsVisibleTo("NetScriptAssembly", AllInternalsVisible = true)]
namespace Barotrauma
{
partial class NetSetup : IDisposable
{
public NetScriptLoader Loader { get; private set; }
public Harmony harmony;
public LuaHook hook;
public NetSetup() => Initialize();
public void Dispose() => Stop();
public void Reload()
{
Stop();
Initialize();
Execute();
}
public void Initialize()
{
hook = new LuaHook();
Loader = new NetScriptLoader(this);
Loader.SearchFolders();
}
public void Execute()
{
if (Loader == null) throw new Exception("NetSetup was not properly initialized.");
try
{
var modTypes = Loader.Compile();
modTypes.ForEach(t => t.GetConstructor(new Type[] { }).Invoke(null));
}
catch (Exception ex)
{
PrintMessage(ex);
}
}
public void Stop()
{
ANetMod.LoadedMods.ForEach(m => m.Dispose());
ANetMod.LoadedMods.Clear();
Loader.Unload();
harmony?.UnpatchAll();
hook?.Call("stop", new object[] { });
hook = null;
Loader = null;
}
public void Update()
{
hook?.Update();
ANetMod.LoadedMods.ForEach(m => m.Update());
}
public static void PrintMessage(object message)
{
if (message == null) { message = "null"; }
string str = message.ToString();
#if SERVER
if (GameMain.Server != null)
{
for (int i = 0; i < str.Length; i += 1024)
{
string subStr = str.Substring(i, Math.Min(1024, str.Length - i));
foreach (var c in GameMain.Server.ConnectedClients)
{
GameMain.Server.SendDirectChatMessage(ChatMessage.Create("", subStr, ChatMessageType.Console, null, textColor: Color.MediumPurple), c);
}
GameServer.Log("[NET] " + subStr, ServerLog.MessageType.ServerMessage);
}
}
else
{
DebugConsole.NewMessage("[NET]" + message.ToString(), Color.MediumPurple);
}
#else
DebugConsole.NewMessage(message.ToString(), Color.Purple);
#endif
}
public void HandleException(Exception ex, string? info)
{
throw new NotImplementedException();
}
}
}
@@ -117,7 +117,7 @@ namespace Barotrauma.Networking
foreach (Wire wire in connection.Wires)
{
#if SERVER
if (GameMain.Lua.game.overrideRespawnSub == false)
if (GameMain.LuaCs.game.overrideRespawnSub == false)
{
if (wire != null) wire.Locked = true;
}
@@ -205,7 +205,7 @@ namespace Barotrauma.Networking
{
#if SERVER
if (GameMain.Lua.game.overrideRespawnSub)
if (GameMain.LuaCs.game.overrideRespawnSub)
{
yield return CoroutineStatus.Success;
}
@@ -1201,7 +1201,7 @@ namespace Barotrauma
{
if (entity is Item item)
{
var result = new LuaResult(GameMain.Lua.hook.Call("statusEffect.apply." + item.Prefab.Identifier, this, deltaTime, entity, targets, worldPosition));
var result = new LuaResult(GameMain.LuaCs.hook.Call("statusEffect.apply." + item.Prefab.Identifier, this, deltaTime, entity, targets, worldPosition));
if (result.Bool())
return;
@@ -1209,7 +1209,7 @@ namespace Barotrauma
if (entity is Character character)
{
var result = new LuaResult(GameMain.Lua.hook.Call("statusEffect.apply." + character.SpeciesName, this, deltaTime, entity, targets, worldPosition));
var result = new LuaResult(GameMain.LuaCs.hook.Call("statusEffect.apply." + character.SpeciesName, this, deltaTime, entity, targets, worldPosition));
if (result.Bool())
return;
@@ -1218,7 +1218,7 @@ namespace Barotrauma
foreach (string luaHooks in luaHook)
{
var result = new LuaResult(GameMain.Lua.hook.Call(luaHooks, this, deltaTime, entity, targets, worldPosition));
var result = new LuaResult(GameMain.LuaCs.hook.Call(luaHooks, this, deltaTime, entity, targets, worldPosition));
if (result.Bool())
return;