Skip to content
Merged

Lua #186

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"preLaunchTask": "build Source.Launcher",
"program": "${workspaceFolder}/Build/Debug/Source.Launcher.dll",
"cwd": "${workspaceFolder}/Build/Debug",
// "args": ["-noworkshop", "-noaddons"],
"stopAtEntry": false
},
{
Expand Down
7 changes: 7 additions & 0 deletions Game.Client/C_BaseAnimating.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1522,6 +1522,13 @@ private void UpdateBoneAttachments() {

}

public virtual void RemoveFromPreviousBoneSetups() => PreviousBoneSetups.Remove(this);

public int LookupBone(ReadOnlySpan<char> name) {
Assert(GetModelPtr());
return BoneSetup.Studio_BoneIndexByName(GetModelPtr(), name);
}

public int LookupAttachment(ReadOnlySpan<char> attachmentName) {
StudioHdr? hdr = GetModelPtr();
if (hdr == null)
Expand Down
8 changes: 8 additions & 0 deletions Game.Client/C_BaseEntity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -713,6 +713,14 @@ private static void RecvProxy_MoveType(ref readonly RecvProxyData data, object i
DEFINE.FIELD(nameof(ProxyRandomValue), FieldType.Float ),
]); public virtual DataMap? GetPredDescMap() => PredMap;

public static readonly DataMap DataDesc = new(typeof(C_BaseEntity), [
DEFINE.FIELD(nameof(ModelName), FieldType.String),
DEFINE.FIELD(nameof(AbsOrigin), FieldType.PositionVector),
DEFINE.FIELD(nameof(AbsRotation), FieldType.Vector),
// DEFINE.ARRAY(nameof(CoordinateFrame), FieldType.Float, 12),
DEFINE.FIELD(nameof(flags), FieldType.Integer),
]); public virtual DataMap? GetDataDescMap() => DataDesc;


static readonly DynamicAccessor DA_Origin = FIELD.OF(nameof(Origin));
static readonly DynamicAccessor DA_Rotation = FIELD.OF(nameof(Rotation));
Expand Down
15 changes: 15 additions & 0 deletions Game.Client/GarrysMod/C_GMOD_Player.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,21 @@ public virtual void SetWeaponColor(in Vector3 color) {
public override bool RestrictPlayerPitch() => (GModPlayerFlags & 16) == 0;
public override bool CanAttack() => PressedWidget.Get() == null;

public C_BaseEntity? FindUseEntity() {
C_BaseEntity? ent = null; // todo: base.FindUseEntity()
if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.FindUseEntity)) {
LuaEntity.Push_Entity(this);
LuaEntity.Push_Entity(ent);
if (gGM.CallReturns(2, 1)) {
ILuaObject ret = g_Lua!.GetReturn(0);
if (ret.GetType() == LuaType.Entity)
return (C_BaseEntity?)ret.GetEntity();
return null;
}
}
return ent;
}

public override void UpdateClientSideAnimation() {
if (Driving.Get() != null) {
if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PlayerDriveAnimate)) {
Expand Down
111 changes: 111 additions & 0 deletions Game.Client/GarrysMod/LuaPresets.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Source;
using Source.Common.Formats.Keyvalues;
using Source.Common.GarrysMod.Lua;

Expand Down Expand Up @@ -46,4 +47,114 @@ static int LoadPresets(ILuaInterface lua) {
presets.UnReference();
return 1;
}

static void SavePreset(string group, string name, LuaObject preset, int index) {
Span<char> fileName = stackalloc char[260];
sprintf(fileName, "%d-%s").I(index).S(name);
strlower(fileName);
for (int i = 0; i < fileName.Length && fileName[i] != '\0'; i++) {
switch (fileName[i]) {
case '\t':
case '\n':
case '!':
case '"':
case '#':
case '%':
case '&':
case '\'':
case '*':
case '.':
case '/':
case ':':
case '<':
case '>':
case '?':
case '@':
case '\\':
case '`':
case '{':
case '}':
fileName[i] = '_';
break;
}
}

string path = $"settings/presets/{group}/{((ReadOnlySpan<char>)fileName).SliceNullTerminatedString()}.txt";
KeyValues kv = new(name);

preset.Push();
g_Lua!.PushNil();
while (g_Lua.Next(-2)) {
if (g_Lua.GetType(-2) != LuaType.String)
g_Lua.ErrorNoHalt($"SavePresets: Preset keyvalue key is a {g_Lua.GetTypeName(g_Lua.GetType(-2))}, string expected");
else if (g_Lua.GetType(-1) != LuaType.String)
g_Lua.ErrorNoHalt($"SavePresets: Preset keyvalue value is a {g_Lua.GetTypeName(g_Lua.GetType(-1))}, string expected");
else
kv.SetString(g_Lua.GetString(-2), g_Lua.GetString(-1));
g_Lua.Pop(1);
}
g_Lua.Pop(1);

kv.WriteToFile(filesystem, path, null);
}

static void SavePresetGroup(string group, LuaObject presets) {
if (group.Contains('\\') || group.Contains('/') || group.Contains('.') || group.Contains("..") || group.Contains("./") || group.IndexOfAny([':', '*', '?']) != -1)
return;

ReadOnlySpan<char> file = filesystem.FindFirstEx($"settings/presets/{group}/*.txt", null, out ulong handle);
while (!file.IsEmpty) {
filesystem.RemoveFile($"settings/presets/{group}/{file}", null);
file = filesystem.FindNext(handle);
}
filesystem.FindClose(handle);
filesystem.CreateDirHierarchy($"settings/presets/{group}/", null);

int index = 1;
presets.Push();
g_Lua!.PushNil();
while (g_Lua.Next(-2)) {
LuaObject key = new(-2, LuaType.None);
LuaObject value = new(-1, LuaType.None);
if (!key.isString())
g_Lua.ErrorNoHalt($"SavePresets: Preset Key is a {g_Lua.GetTypeName(key.GetType())}, string expected");
else if (!value.isTable())
g_Lua.ErrorNoHalt($"SavePresets: Preset value is a {g_Lua.GetTypeName(value.GetType())}, table expected");
else
SavePreset(group, key.GetString()!, value, index++);
value.UnReference();
key.UnReference();
g_Lua.Pop(1);
}
g_Lua.Pop(1);
}

[LuaGlobal]
static int SavePresets(ILuaInterface lua) {
LuaObject presets = new(1, LuaType.None);
if (!presets.isTable()) {
lua.TypeError("table", 1);
presets.UnReference();
return 0;
}

presets.Push();
lua.PushNil();
while (lua.Next(-2)) {
LuaObject key = new(-2, LuaType.None);
LuaObject value = new(-1, LuaType.None);
if (!key.isString())
lua.ErrorNoHalt($"SavePresets: Group Key is a {lua.GetTypeName(key.GetType())}, string expected");
else if (!value.isTable())
lua.ErrorNoHalt($"SavePresets: Group Value is a {lua.GetTypeName(value.GetType())}, table expected");
else
SavePresetGroup(key.GetString()!, value);
value.UnReference();
key.UnReference();
lua.Pop(1);
}
lua.Pop(1);
presets.UnReference();
return 0;
}
}
12 changes: 11 additions & 1 deletion Game.Client/GarrysMod/LuaRender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,17 @@ static int GetCurrentRenderTarget(ILuaInterface lua) {
return 1;
}

[LuaFunction]
static int CopyRenderTargetToTexture(ILuaInterface lua) {
ITexture? texture = (ITexture?)LuaTexture.LC_ITexture.Get(1);
using MatRenderContextPtr renderContext = new(materials);
ITexture? renderTarget = renderContext.GetRenderTarget();
if (enginevgui.IsConsoleVisible() && !(renderTarget == null ? ViewRender.RenderingView : renderTarget.IsRenderTarget()))
return 0;
renderContext.CopyRenderTargetToTexture(texture);
return 0;
}

[LuaFunction]
static int SetRenderTarget(ILuaInterface lua) {
ITexture? texture = null;
Expand Down Expand Up @@ -551,7 +562,6 @@ static int SetViewPort(ILuaInterface lua) {
// todo: RenderView
// todo: GetViewSetup
// todo: RenderHUD
// todo: CopyRenderTargetToTexture
static int CustomClipPlaneCount;

[LuaFunction]
Expand Down
22 changes: 21 additions & 1 deletion Game.Client/HLClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,24 @@ public bool CanShowSpeakerLabels() {

public static bool g_bLevelInitialized;
public static INetworkStringTable? g_pStringTableClientSideChoreoScenes;
public static INetworkStringTable? g_pStringTableMaterials;

public static int GetMaterialIndex(ReadOnlySpan<char> materialName) {
if (!materialName.IsEmpty) {
int index = g_pStringTableMaterials!.FindStringIndex(materialName);
Assert(index >= 0);
if (index >= 0)
return index;
}
return 0;
}

public static ReadOnlySpan<char> GetMaterialNameFromIndex(int index) {
if (index != (g_pStringTableMaterials!.GetMaxStrings() - 1))
return g_pStringTableMaterials.GetString(index);
else
return null;
}

public void EncodeUserCmdToBuffer(bf_write buf, int slot) {
input.EncodeUserCmdToBuffer(buf, slot);
Expand Down Expand Up @@ -272,7 +290,9 @@ public void View_Render(ViewRects rects) {
public void InstallStringTableCallback(ReadOnlySpan<char> tableName) {
switch (tableName) {
case "VguiScreen": Warning("FIXME: VguiScreen string table not being processed yet\n"); break;
case "Materials": Warning("FIXME: Materials string table not being processed yet\n"); break;
case "Materials":
g_pStringTableMaterials = networkstringtable.FindTable(tableName);
break;
case "EffectDispatch": Warning("FIXME: EffectDispatch string table not being processed yet\n"); break;
// I don't think InfoPanel is a thing?
case "Scenes":
Expand Down
2 changes: 2 additions & 0 deletions Game.Client/View.cs
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,8 @@ public void RenderView(in ViewSetup viewRender, ClearFlags clearFlags, RenderVie
renderContext.Flush();
}
}

RenderingView = false;
}

private void ViewDrawScene(bool drew3dSkybox, SkyboxVisibility skyboxVisible, in ViewSetup viewRender, ClearFlags clearFlags, ViewID viewID, bool drawViewModel = false, DrawFlags baseDrawFlags = 0) {
Expand Down
8 changes: 8 additions & 0 deletions Game.Server/BaseAnimating.cs
Original file line number Diff line number Diff line change
Expand Up @@ -622,6 +622,14 @@ public virtual void SetupBones(Span<Matrix3x4> boneToWorld, int boneMask) {
RemoveEFlags(EFL.SettingUpBones);
}

public int LookupBone(ReadOnlySpan<char> name) {
StudioHdr? studioHdr = GetModelPtr();
Assert(studioHdr);
if (studioHdr == null)
return -1;
return BoneSetup.Studio_BoneIndexByName(studioHdr, name);
}

public int LookupAttachment(ReadOnlySpan<char> name) {
StudioHdr? studioHdr = GetModelPtr();
if (studioHdr == null) {
Expand Down
4 changes: 3 additions & 1 deletion Game.Server/BaseCombatWeapon.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ public override void Use(BaseEntity? activator, BaseEntity? caller, UseType useT
public override bool IsWeapon() => true;
public override GarrysMod.LuaClass Lua_GetLuaClass() => GarrysMod.LuaEntity.LC_Weapon;

public static void W_Precache(){
public static void W_Precache() {

}

Expand Down Expand Up @@ -268,4 +268,6 @@ public void CheckRespawn() {
return;
}
}

public override bool IsBaseCombatWeapon() => true;
}
22 changes: 19 additions & 3 deletions Game.Server/GameInterface.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@

namespace Game.Server;

public static class GameInterfaceGlobals {
public static readonly ConVar sv_unlockedchapters = new( "sv_unlockedchapters", "1", FCvar.Archive | FCvar.ArchiveXbox);
public static class GameInterfaceGlobals
{
public static readonly ConVar sv_unlockedchapters = new("sv_unlockedchapters", "1", FCvar.Archive | FCvar.ArchiveXbox);
}

[EngineComponent]
Expand All @@ -40,10 +41,25 @@ public static class GameInterface
public static INetworkStringTable? g_pStringTableClientSideChoreoScenes;
public static INetworkStringTable? g_pStringTableMaterials;

public static void PrecacheMaterial(ReadOnlySpan<char> materialName){
public static void PrecacheMaterial(ReadOnlySpan<char> materialName) {
g_pStringTableMaterials!.AddString(true, materialName);
}

public static int GetMaterialIndex(ReadOnlySpan<char> materialName) {
if (!materialName.IsEmpty) {
int index = g_pStringTableMaterials!.FindStringIndex(materialName);
if (index != INetworkStringTable.INVALID_STRING_INDEX)
return index;
else {
DevMsg($"Warning! GetMaterialIndex: couldn't find material {materialName}\n ");
return 0;
}
}
return 0;
}

public static ReadOnlySpan<char> GetMaterialNameFromIndex(int materialIndex) => g_pStringTableMaterials!.GetString(materialIndex);

public static bf_write? g_pMsgBuffer;
public static void UserMessageBegin(in IRecipientFilter filter, ReadOnlySpan<char> messagename) {
Assert(g_pMsgBuffer == null);
Expand Down
15 changes: 15 additions & 0 deletions Game.Server/GarrysMod/GMOD_Player.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,21 @@ public override void Spawn() {
public override bool RestrictPlayerPitch() => (GModPlayerFlags & 16) == 0;
public override bool CanAttack() => PressedWidget.Get() == null;

public override BaseEntity? FindUseEntity() {
BaseEntity? ent = base.FindUseEntity();
if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.FindUseEntity)) {
LuaEntity.Push_Entity(this);
LuaEntity.Push_Entity(ent);
if (gGM.CallReturns(2, 1)) {
ILuaObject ret = g_Lua!.GetReturn(0);
if (ret.GetType() == LuaType.Entity)
return (BaseEntity?)ret.GetEntity();
return null;
}
}
return ent;
}

public override BaseEntity EntSelectSpawnPoint() {
BaseEntity? spot = null;
while ((spot = gEntList.FindEntityByClassname(spot, "info_player_start")) != null) {
Expand Down
24 changes: 24 additions & 0 deletions Game.Shared/GarrysMod/BaseEntityLua.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,30 @@ public partial class
BaseEntity
#endif
{
public class LuaCallback
{
public int ID;
public readonly LuaObject Function = new();
public bool Removed;
}

public class LuaCallbackList
{
public readonly LinkedList<LuaCallback> Callbacks = [];
public int NextID;
public int Changes;
}

public static readonly string[] LuaCallbackNames = ["OnAngleChange", "BuildBonePositions", "PhysicsCollide", "BuildFlexWeights"];
public readonly LuaCallbackList[] LuaCallbacks = [new(), new(), new(), new()];

public static int LuaCallbackIndex(ReadOnlySpan<char> name) {
for (int i = 0; i < LuaCallbackNames.Length; i++)
if (strcmp(name, LuaCallbackNames[i]) == 0)
return i;
return -1;
}

public LuaObject LuaCalcAbsolutePosition = new();
public LuaObject? LuaTableObject = new();
public LuaObject? LuaEntityObject = new();
Expand Down
5 changes: 2 additions & 3 deletions Game.Shared/GarrysMod/LuaConVar.cs
Original file line number Diff line number Diff line change
Expand Up @@ -209,9 +209,8 @@ static int CreateConVar(ILuaInterface lua) {
ConVar convar = g_Lua.CreateConVar(name, defaultValue, helpString, flags);
convar.SetMin(hasMin, min);
convar.SetMax(hasMax, max);
if ((flags & (int)FCvar.UserInfo) != 0) {
// todo: cvar.CallGlobalChangeCallbacks(convar, "", 0.0f);
}
if ((flags & (int)FCvar.UserInfo) != 0)
cvar.CallGlobalChangeCallbacks(convar, new ConVarChangeContext { Old = "" });

Push_ConVar(convar);
return 1;
Expand Down
6 changes: 6 additions & 0 deletions Game.Shared/GarrysMod/LuaEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ public static partial class LuaEngine
[LuaLibrary]
static readonly LuaLibrary LL_Factory_engine = new("engine");

[LuaFunction]
static int TickInterval(ILuaInterface lua) {
g_Lua!.PushNumber(gpGlobals.IntervalPerTick);
return 1;
}

[LuaFunction]
static int ActiveGamemode(ILuaInterface lua) {
g_Lua!.PushString(filesystem.Gamemodes().Active().Name);
Expand Down
Loading
Loading